civetweb.c 343 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  92. * type size check"); */
  93. /* DTL -- including winsock2.h works better if lean and mean */
  94. #ifndef WIN32_LEAN_AND_MEAN
  95. #define WIN32_LEAN_AND_MEAN
  96. #endif
  97. #if defined(__SYMBIAN32__)
  98. #define NO_SSL /* SSL is not supported */
  99. #define NO_CGI /* CGI is not supported */
  100. #define PATH_MAX FILENAME_MAX
  101. #endif /* __SYMBIAN32__ */
  102. /* Include the header file here, so the CivetWeb interface is defined for the
  103. * entire implementation, including the following forward definitions. */
  104. #include "civetweb.h"
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __MACH__
  116. #define CLOCK_MONOTONIC (1)
  117. #define CLOCK_REALTIME (2)
  118. #include <sys/time.h>
  119. #include <mach/clock.h>
  120. #include <mach/mach.h>
  121. #include <mach/mach_time.h>
  122. #include <assert.h>
  123. /* clock_gettime is not implemented on OSX */
  124. int clock_gettime(int clk_id, struct timespec *t);
  125. int
  126. clock_gettime(int clk_id, struct timespec *t)
  127. {
  128. memset(t, 0, sizeof(*t));
  129. if (clk_id == CLOCK_REALTIME) {
  130. struct timeval now;
  131. int rv = gettimeofday(&now, NULL);
  132. if (rv) {
  133. return rv;
  134. }
  135. t->tv_sec = now.tv_sec;
  136. t->tv_nsec = now.tv_usec * 1000;
  137. return 0;
  138. } else if (clk_id == CLOCK_MONOTONIC) {
  139. static uint64_t clock_start_time = 0;
  140. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  141. uint64_t now = mach_absolute_time();
  142. if (clock_start_time == 0) {
  143. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  144. #if defined(DEBUG)
  145. assert(mach_status == KERN_SUCCESS);
  146. #else
  147. /* appease "unused variable" warning for release builds */
  148. (void)mach_status;
  149. #endif
  150. clock_start_time = now;
  151. }
  152. now = (uint64_t)((double)(now - clock_start_time)
  153. * (double)timebase_ifo.numer
  154. / (double)timebase_ifo.denom);
  155. t->tv_sec = now / 1000000000;
  156. t->tv_nsec = now % 1000000000;
  157. return 0;
  158. }
  159. return -1; /* EINVAL - Clock ID is unknown */
  160. }
  161. #endif
  162. #include <time.h>
  163. #include <stdlib.h>
  164. #include <stdarg.h>
  165. #include <assert.h>
  166. #include <string.h>
  167. #include <ctype.h>
  168. #include <limits.h>
  169. #include <stddef.h>
  170. #include <stdio.h>
  171. #ifndef MAX_WORKER_THREADS
  172. #define MAX_WORKER_THREADS (1024 * 64)
  173. #endif
  174. #ifndef SOCKET_TIMEOUT_QUANTUM
  175. #define SOCKET_TIMEOUT_QUANTUM (10000)
  176. #endif
  177. mg_static_assert(MAX_WORKER_THREADS >= 1,
  178. "worker threads must be a positive number");
  179. #if defined(_WIN32) \
  180. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  181. #include <windows.h>
  182. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  183. #include <ws2tcpip.h>
  184. typedef const char *SOCK_OPT_TYPE;
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (MAX_PATH)
  187. #endif
  188. #if !defined(PATH_MAX)
  189. #define PATH_MAX (4096)
  190. #endif
  191. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  192. #ifndef _IN_PORT_T
  193. #ifndef in_port_t
  194. #define in_port_t u_short
  195. #endif
  196. #endif
  197. #ifndef _WIN32_WCE
  198. #include <process.h>
  199. #include <direct.h>
  200. #include <io.h>
  201. #else /* _WIN32_WCE */
  202. #define NO_CGI /* WinCE has no pipes */
  203. #define NO_POPEN /* WinCE has no popen */
  204. typedef long off_t;
  205. #define errno ((int)(GetLastError()))
  206. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  207. #endif /* _WIN32_WCE */
  208. #define MAKEUQUAD(lo, hi) \
  209. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  210. #define RATE_DIFF (10000000) /* 100 nsecs */
  211. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  212. #define SYS2UNIX_TIME(lo, hi) \
  213. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  214. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  215. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  216. * Also use _strtoui64 on modern M$ compilers */
  217. #if defined(_MSC_VER)
  218. #if (_MSC_VER < 1300)
  219. #define STRX(x) #x
  220. #define STR(x) STRX(x)
  221. #define __func__ __FILE__ ":" STR(__LINE__)
  222. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  223. #define strtoll(x, y, z) (_atoi64(x))
  224. #else
  225. #define __func__ __FUNCTION__
  226. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  227. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  228. #endif
  229. #endif /* _MSC_VER */
  230. #define ERRNO ((int)(GetLastError()))
  231. #define NO_SOCKLEN_T
  232. #if defined(_WIN64) || defined(__MINGW64__)
  233. #define SSL_LIB "ssleay64.dll"
  234. #define CRYPTO_LIB "libeay64.dll"
  235. #else
  236. #define SSL_LIB "ssleay32.dll"
  237. #define CRYPTO_LIB "libeay32.dll"
  238. #endif
  239. #define O_NONBLOCK (0)
  240. #ifndef W_OK
  241. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  242. #endif
  243. #if !defined(EWOULDBLOCK)
  244. #define EWOULDBLOCK WSAEWOULDBLOCK
  245. #endif /* !EWOULDBLOCK */
  246. #define _POSIX_
  247. #define INT64_FMT "I64d"
  248. #define UINT64_FMT "I64u"
  249. #define WINCDECL __cdecl
  250. #define SHUT_RD (0)
  251. #define SHUT_WR (1)
  252. #define SHUT_BOTH (2)
  253. #define vsnprintf_impl _vsnprintf
  254. #define access _access
  255. #define mg_sleep(x) (Sleep(x))
  256. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  257. #ifndef popen
  258. #define popen(x, y) (_popen(x, y))
  259. #endif
  260. #ifndef pclose
  261. #define pclose(x) (_pclose(x))
  262. #endif
  263. #define close(x) (_close(x))
  264. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  265. #define RTLD_LAZY (0)
  266. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  267. #define fdopen(x, y) (_fdopen((x), (y)))
  268. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  269. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  270. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  271. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  272. #define sleep(x) (Sleep((x)*1000))
  273. #define rmdir(x) (_rmdir(x))
  274. #define timegm(x) (_mkgmtime(x))
  275. #if !defined(fileno)
  276. #define fileno(x) (_fileno(x))
  277. #endif /* !fileno MINGW #defines fileno */
  278. typedef HANDLE pthread_mutex_t;
  279. typedef DWORD pthread_key_t;
  280. typedef HANDLE pthread_t;
  281. typedef struct {
  282. CRITICAL_SECTION threadIdSec;
  283. int waitingthreadcount; /* The number of threads queued. */
  284. pthread_t *waitingthreadhdls; /* The thread handles. */
  285. } pthread_cond_t;
  286. #ifndef __clockid_t_defined
  287. typedef DWORD clockid_t;
  288. #endif
  289. #ifndef CLOCK_MONOTONIC
  290. #define CLOCK_MONOTONIC (1)
  291. #endif
  292. #ifndef CLOCK_REALTIME
  293. #define CLOCK_REALTIME (2)
  294. #endif
  295. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  296. #define _TIMESPEC_DEFINED
  297. #endif
  298. #ifndef _TIMESPEC_DEFINED
  299. struct timespec {
  300. time_t tv_sec; /* seconds */
  301. long tv_nsec; /* nanoseconds */
  302. };
  303. #endif
  304. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  305. static int pthread_mutex_lock(pthread_mutex_t *);
  306. static int pthread_mutex_unlock(pthread_mutex_t *);
  307. static void path_to_unicode(const struct mg_connection *conn,
  308. const char *path,
  309. wchar_t *wbuf,
  310. size_t wbuf_len);
  311. struct file;
  312. static const char *
  313. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  314. #if defined(HAVE_STDINT)
  315. #include <stdint.h>
  316. #else
  317. typedef unsigned char uint8_t;
  318. typedef unsigned short uint16_t;
  319. typedef unsigned int uint32_t;
  320. typedef unsigned __int64 uint64_t;
  321. typedef __int64 int64_t;
  322. #ifndef INT64_MAX
  323. #define INT64_MAX (9223372036854775807)
  324. #endif
  325. #endif /* HAVE_STDINT */
  326. /* POSIX dirent interface */
  327. struct dirent {
  328. char d_name[PATH_MAX];
  329. };
  330. typedef struct DIR {
  331. HANDLE handle;
  332. WIN32_FIND_DATAW info;
  333. struct dirent result;
  334. } DIR;
  335. #if defined(_WIN32) && !defined(POLLIN)
  336. #ifndef HAVE_POLL
  337. struct pollfd {
  338. SOCKET fd;
  339. short events;
  340. short revents;
  341. };
  342. #define POLLIN (0x0300)
  343. #endif
  344. #endif
  345. /* Mark required libraries */
  346. #if defined(_MSC_VER)
  347. #pragma comment(lib, "Ws2_32.lib")
  348. #endif
  349. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  350. block */
  351. #include <sys/wait.h>
  352. #include <sys/socket.h>
  353. #include <sys/poll.h>
  354. #include <netinet/in.h>
  355. #include <arpa/inet.h>
  356. #include <sys/time.h>
  357. #include <sys/utsname.h>
  358. #include <stdint.h>
  359. #include <inttypes.h>
  360. #include <netdb.h>
  361. #include <netinet/tcp.h>
  362. typedef const void *SOCK_OPT_TYPE;
  363. #if defined(ANDROID)
  364. typedef unsigned short int in_port_t;
  365. #endif
  366. #include <pwd.h>
  367. #include <unistd.h>
  368. #include <grp.h>
  369. #include <dirent.h>
  370. #define vsnprintf_impl vsnprintf
  371. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  372. #include <dlfcn.h>
  373. #endif
  374. #include <pthread.h>
  375. #if defined(__MACH__)
  376. #define SSL_LIB "libssl.dylib"
  377. #define CRYPTO_LIB "libcrypto.dylib"
  378. #else
  379. #if !defined(SSL_LIB)
  380. #define SSL_LIB "libssl.so"
  381. #endif
  382. #if !defined(CRYPTO_LIB)
  383. #define CRYPTO_LIB "libcrypto.so"
  384. #endif
  385. #endif
  386. #ifndef O_BINARY
  387. #define O_BINARY (0)
  388. #endif /* O_BINARY */
  389. #define closesocket(a) (close(a))
  390. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  391. #define mg_remove(conn, x) (remove(x))
  392. #define mg_sleep(x) (usleep((x)*1000))
  393. #define mg_opendir(conn, x) (opendir(x))
  394. #define mg_closedir(x) (closedir(x))
  395. #define mg_readdir(x) (readdir(x))
  396. #define ERRNO (errno)
  397. #define INVALID_SOCKET (-1)
  398. #define INT64_FMT PRId64
  399. #define UINT64_FMT PRIu64
  400. typedef int SOCKET;
  401. #define WINCDECL
  402. #if defined(__hpux)
  403. /* HPUX 11 does not have monotonic, fall back to realtime */
  404. #ifndef CLOCK_MONOTONIC
  405. #define CLOCK_MONOTONIC CLOCK_REALTIME
  406. #endif
  407. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  408. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  409. * the prototypes use int* rather than socklen_t* which matches the
  410. * actual library expectation. When called with the wrong size arg
  411. * accept() returns a zero client inet addr and check_acl() always
  412. * fails. Since socklen_t is widely used below, just force replace
  413. * their typedef with int. - DTL
  414. */
  415. #define socklen_t int
  416. #endif /* hpux */
  417. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  418. block */
  419. /* va_copy should always be a macro, C99 and C++11 - DTL */
  420. #ifndef va_copy
  421. #define va_copy(x, y) ((x) = (y))
  422. #endif
  423. #ifdef _WIN32
  424. /* Create substitutes for POSIX functions in Win32. */
  425. #if defined(__MINGW32__)
  426. /* Show no warning in case system functions are not used. */
  427. #pragma GCC diagnostic push
  428. #pragma GCC diagnostic ignored "-Wunused-function"
  429. #endif
  430. static CRITICAL_SECTION global_log_file_lock;
  431. static DWORD
  432. pthread_self(void)
  433. {
  434. return GetCurrentThreadId();
  435. }
  436. static int
  437. pthread_key_create(
  438. pthread_key_t *key,
  439. void (*_ignored)(void *) /* destructor not supported for Windows */
  440. )
  441. {
  442. (void)_ignored;
  443. if ((key != 0)) {
  444. *key = TlsAlloc();
  445. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  446. }
  447. return -2;
  448. }
  449. static int
  450. pthread_key_delete(pthread_key_t key)
  451. {
  452. return TlsFree(key) ? 0 : 1;
  453. }
  454. static int
  455. pthread_setspecific(pthread_key_t key, void *value)
  456. {
  457. return TlsSetValue(key, value) ? 0 : 1;
  458. }
  459. static void *
  460. pthread_getspecific(pthread_key_t key)
  461. {
  462. return TlsGetValue(key);
  463. }
  464. #if defined(__MINGW32__)
  465. /* Enable unused function warning again */
  466. #pragma GCC diagnostic pop
  467. #endif
  468. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  469. #else
  470. static pthread_mutexattr_t pthread_mutex_attr;
  471. #endif /* _WIN32 */
  472. #define PASSWORDS_FILE_NAME ".htpasswd"
  473. #define CGI_ENVIRONMENT_SIZE (4096)
  474. #define MAX_CGI_ENVIR_VARS (256)
  475. #define MG_BUF_LEN (8192)
  476. #ifndef MAX_REQUEST_SIZE
  477. #define MAX_REQUEST_SIZE (16384)
  478. #endif
  479. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  480. "request size length must be a positive number");
  481. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  482. #if !defined(DEBUG_TRACE)
  483. #if defined(DEBUG)
  484. #if defined(_WIN32_WCE)
  485. /* Create substitutes for POSIX functions in Win32. */
  486. #if defined(__MINGW32__)
  487. /* Show no warning in case system functions are not used. */
  488. #pragma GCC diagnostic push
  489. #pragma GCC diagnostic ignored "-Wunused-function"
  490. #endif
  491. static time_t
  492. time(time_t *ptime)
  493. {
  494. time_t t;
  495. SYSTEMTIME st;
  496. FILETIME ft;
  497. GetSystemTime(&st);
  498. SystemTimeToFileTime(&st, &ft);
  499. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  500. if (ptime != NULL) {
  501. *ptime = t;
  502. }
  503. return t;
  504. }
  505. static struct tm *
  506. localtime_s(const time_t *ptime, struct tm *ptm)
  507. {
  508. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  509. FILETIME ft, lft;
  510. SYSTEMTIME st;
  511. TIME_ZONE_INFORMATION tzinfo;
  512. if (ptm == NULL) {
  513. return NULL;
  514. }
  515. *(int64_t *)&ft = t;
  516. FileTimeToLocalFileTime(&ft, &lft);
  517. FileTimeToSystemTime(&lft, &st);
  518. ptm->tm_year = st.wYear - 1900;
  519. ptm->tm_mon = st.wMonth - 1;
  520. ptm->tm_wday = st.wDayOfWeek;
  521. ptm->tm_mday = st.wDay;
  522. ptm->tm_hour = st.wHour;
  523. ptm->tm_min = st.wMinute;
  524. ptm->tm_sec = st.wSecond;
  525. ptm->tm_yday = 0; /* hope nobody uses this */
  526. ptm->tm_isdst =
  527. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  528. return ptm;
  529. }
  530. static struct tm *
  531. gmtime_s(const time_t *ptime, struct tm *ptm)
  532. {
  533. /* FIXME(lsm): fix this. */
  534. return localtime_s(ptime, ptm);
  535. }
  536. static struct tm tm_array[MAX_WORKER_THREADS];
  537. static int tm_index = 0;
  538. static struct tm *
  539. localtime(const time_t *ptime)
  540. {
  541. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  542. return localtime_s(ptime, tls_tm + i);
  543. }
  544. static struct tm *
  545. gmtime(const time_t *ptime)
  546. {
  547. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  548. return gmtime_s(ptime, tls_tm + i);
  549. }
  550. static size_t
  551. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  552. {
  553. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  554. // for WinCE");
  555. return 0;
  556. }
  557. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  558. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  559. #define remove(f) mg_remove(NULL, f)
  560. static int
  561. rename(const char *a, const char *b)
  562. {
  563. wchar_t wa[PATH_MAX];
  564. wchar_t wb[PATH_MAX];
  565. path_to_unicode(conn, path, wa, ARRAY_SIZE(wa));
  566. path_to_unicode(conn, path, wb, ARRAY_SIZE(wb));
  567. return MoveFileW(wa, wb) ? 0 : -1;
  568. }
  569. struct stat {
  570. int64_t st_size;
  571. };
  572. static int
  573. stat(const char *name, struct stat *st)
  574. {
  575. wchar_t wbuf[PATH_MAX];
  576. WIN32_FILE_ATTRIBUTE_DATA attr;
  577. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  578. memset(&attr, 0, sizeof(attr));
  579. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  580. st->st_size = ((int64_t)attr.nFileSizeHigh)
  581. << 32 + (int64_t)attr.nFileSizeLow;
  582. /* TODO ... */
  583. }
  584. #define access(x, a) 1 /* not required anyway */
  585. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  586. #define EEXIST 1 /* TODO: See Windows error codes */
  587. #define EACCES 2 /* TODO: See Windows error codes */
  588. #define ENOENT 3 /* TODO: See Windows Error codes */
  589. #if defined(__MINGW32__)
  590. /* Enable unused function warning again */
  591. #pragma GCC diagnostic pop
  592. #endif
  593. #endif /* defined(_WIN32_WCE) */
  594. static void DEBUG_TRACE_FUNC(const char *func,
  595. unsigned line,
  596. PRINTF_FORMAT_STRING(const char *fmt),
  597. ...) PRINTF_ARGS(3, 4);
  598. static void
  599. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  600. {
  601. va_list args;
  602. flockfile(stdout);
  603. printf("*** %lu.%p.%s.%u: ",
  604. (unsigned long)time(NULL),
  605. (void *)pthread_self(),
  606. func,
  607. line);
  608. va_start(args, fmt);
  609. vprintf(fmt, args);
  610. va_end(args);
  611. putchar('\n');
  612. fflush(stdout);
  613. funlockfile(stdout);
  614. }
  615. #define DEBUG_TRACE(fmt, ...) \
  616. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  617. #else
  618. #define DEBUG_TRACE(fmt, ...) \
  619. do { \
  620. } while (0)
  621. #endif /* DEBUG */
  622. #endif /* DEBUG_TRACE */
  623. #if defined(MEMORY_DEBUGGING)
  624. unsigned long mg_memory_debug_blockCount = 0;
  625. unsigned long mg_memory_debug_totalMemUsed = 0;
  626. static void *
  627. mg_malloc_ex(size_t size, const char *file, unsigned line)
  628. {
  629. void *data = malloc(size + sizeof(size_t));
  630. void *memory = 0;
  631. char mallocStr[256];
  632. if (data) {
  633. *(size_t *)data = size;
  634. mg_memory_debug_totalMemUsed += size;
  635. mg_memory_debug_blockCount++;
  636. memory = (void *)(((char *)data) + sizeof(size_t));
  637. }
  638. sprintf(mallocStr,
  639. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  640. memory,
  641. (unsigned long)size,
  642. mg_memory_debug_totalMemUsed,
  643. mg_memory_debug_blockCount,
  644. file,
  645. line);
  646. #if defined(_WIN32)
  647. OutputDebugStringA(mallocStr);
  648. #else
  649. DEBUG_TRACE("%s", mallocStr);
  650. #endif
  651. return memory;
  652. }
  653. static void *
  654. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  655. {
  656. void *data = mg_malloc_ex(size * count, file, line);
  657. if (data) {
  658. memset(data, 0, size);
  659. }
  660. return data;
  661. }
  662. static void
  663. mg_free_ex(void *memory, const char *file, unsigned line)
  664. {
  665. char mallocStr[256];
  666. void *data = (void *)(((char *)memory) - sizeof(size_t));
  667. size_t size;
  668. if (memory) {
  669. size = *(size_t *)data;
  670. mg_memory_debug_totalMemUsed -= size;
  671. mg_memory_debug_blockCount--;
  672. sprintf(mallocStr,
  673. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  674. memory,
  675. (unsigned long)size,
  676. mg_memory_debug_totalMemUsed,
  677. mg_memory_debug_blockCount,
  678. file,
  679. line);
  680. #if defined(_WIN32)
  681. OutputDebugStringA(mallocStr);
  682. #else
  683. DEBUG_TRACE("%s", mallocStr);
  684. #endif
  685. free(data);
  686. }
  687. }
  688. static void *
  689. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  690. {
  691. char mallocStr[256];
  692. void *data;
  693. void *_realloc;
  694. size_t oldsize;
  695. if (newsize) {
  696. if (memory) {
  697. data = (void *)(((char *)memory) - sizeof(size_t));
  698. oldsize = *(size_t *)data;
  699. _realloc = realloc(data, newsize + sizeof(size_t));
  700. if (_realloc) {
  701. data = _realloc;
  702. mg_memory_debug_totalMemUsed -= oldsize;
  703. sprintf(mallocStr,
  704. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  705. memory,
  706. (unsigned long)oldsize,
  707. mg_memory_debug_totalMemUsed,
  708. mg_memory_debug_blockCount,
  709. file,
  710. line);
  711. #if defined(_WIN32)
  712. OutputDebugStringA(mallocStr);
  713. #else
  714. DEBUG_TRACE("%s", mallocStr);
  715. #endif
  716. mg_memory_debug_totalMemUsed += newsize;
  717. sprintf(mallocStr,
  718. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  719. memory,
  720. (unsigned long)newsize,
  721. mg_memory_debug_totalMemUsed,
  722. mg_memory_debug_blockCount,
  723. file,
  724. line);
  725. #if defined(_WIN32)
  726. OutputDebugStringA(mallocStr);
  727. #else
  728. DEBUG_TRACE("%s", mallocStr);
  729. #endif
  730. *(size_t *)data = newsize;
  731. data = (void *)(((char *)data) + sizeof(size_t));
  732. } else {
  733. #if defined(_WIN32)
  734. OutputDebugStringA("MEM: realloc failed\n");
  735. #else
  736. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  737. #endif
  738. return _realloc;
  739. }
  740. } else {
  741. data = mg_malloc_ex(newsize, file, line);
  742. }
  743. } else {
  744. data = 0;
  745. mg_free_ex(memory, file, line);
  746. }
  747. return data;
  748. }
  749. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  750. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  751. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  752. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  753. #else
  754. static __inline void *
  755. mg_malloc(size_t a)
  756. {
  757. return malloc(a);
  758. }
  759. static __inline void *
  760. mg_calloc(size_t a, size_t b)
  761. {
  762. return calloc(a, b);
  763. }
  764. static __inline void *
  765. mg_realloc(void *a, size_t b)
  766. {
  767. return realloc(a, b);
  768. }
  769. static __inline void
  770. mg_free(void *a)
  771. {
  772. free(a);
  773. }
  774. #endif
  775. static void mg_vsnprintf(const struct mg_connection *conn,
  776. int *truncated,
  777. char *buf,
  778. size_t buflen,
  779. const char *fmt,
  780. va_list ap);
  781. static void mg_snprintf(const struct mg_connection *conn,
  782. int *truncated,
  783. char *buf,
  784. size_t buflen,
  785. PRINTF_FORMAT_STRING(const char *fmt),
  786. ...) PRINTF_ARGS(5, 6);
  787. /* This following lines are just meant as a reminder to use the mg-functions
  788. * for memory management */
  789. #ifdef malloc
  790. #undef malloc
  791. #endif
  792. #ifdef calloc
  793. #undef calloc
  794. #endif
  795. #ifdef realloc
  796. #undef realloc
  797. #endif
  798. #ifdef free
  799. #undef free
  800. #endif
  801. #ifdef snprintf
  802. #undef snprintf
  803. #endif
  804. #ifdef vsnprintf
  805. #undef vsnprintf
  806. #endif
  807. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  808. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  809. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  810. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  811. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  812. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  813. * but this define only works well for Windows. */
  814. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  815. #endif
  816. #define MD5_STATIC static
  817. #include "md5.inl"
  818. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  819. #ifdef NO_SOCKLEN_T
  820. typedef int socklen_t;
  821. #endif /* NO_SOCKLEN_T */
  822. #define _DARWIN_UNLIMITED_SELECT
  823. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  824. #if !defined(MSG_NOSIGNAL)
  825. #define MSG_NOSIGNAL (0)
  826. #endif
  827. #if !defined(SOMAXCONN)
  828. #define SOMAXCONN (100)
  829. #endif
  830. /* Size of the accepted socket queue */
  831. #if !defined(MGSQLEN)
  832. #define MGSQLEN (20)
  833. #endif
  834. #if defined(NO_SSL)
  835. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  836. typedef struct SSL_CTX SSL_CTX;
  837. #else
  838. #if defined(NO_SSL_DL)
  839. #include <openssl/ssl.h>
  840. #include <openssl/err.h>
  841. #include <openssl/crypto.h>
  842. #include <openssl/x509.h>
  843. #include <openssl/pem.h>
  844. #include <openssl/engine.h>
  845. #include <openssl/conf.h>
  846. #else
  847. /* SSL loaded dynamically from DLL.
  848. * I put the prototypes here to be independent from OpenSSL source
  849. * installation. */
  850. typedef struct ssl_st SSL;
  851. typedef struct ssl_method_st SSL_METHOD;
  852. typedef struct ssl_ctx_st SSL_CTX;
  853. typedef struct x509_store_ctx_st X509_STORE_CTX;
  854. #define SSL_CTRL_OPTIONS (32)
  855. #define SSL_CTRL_CLEAR_OPTIONS (77)
  856. #define SSL_CTRL_SET_ECDH_AUTO (94)
  857. #define SSL_VERIFY_NONE (0)
  858. #define SSL_VERIFY_PEER (1)
  859. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  860. #define SSL_VERIFY_CLIENT_ONCE (4)
  861. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  862. #define SSL_OP_NO_SSLv2 (0x01000000L)
  863. #define SSL_OP_NO_SSLv3 (0x02000000L)
  864. #define SSL_OP_NO_TLSv1 (0x04000000L)
  865. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  866. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  867. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  868. struct ssl_func {
  869. const char *name; /* SSL function name */
  870. void (*ptr)(void); /* Function pointer */
  871. };
  872. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  873. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  874. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  875. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  876. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  877. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  878. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  879. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  880. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  881. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  882. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  883. #define SSL_CTX_use_PrivateKey_file \
  884. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  885. #define SSL_CTX_use_certificate_file \
  886. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  887. #define SSL_CTX_set_default_passwd_cb \
  888. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  889. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  890. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  891. #define SSL_CTX_use_certificate_chain_file \
  892. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  893. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  894. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  895. #define SSL_CTX_set_verify \
  896. (*(void (*)(SSL_CTX *, \
  897. int, \
  898. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  899. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  900. #define SSL_CTX_load_verify_locations \
  901. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  902. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  903. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  904. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  905. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  906. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  907. #define SSL_CIPHER_get_name \
  908. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  909. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  910. #define SSL_CTX_set_session_id_context \
  911. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  912. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  913. #define SSL_CTX_set_cipher_list \
  914. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  915. #define SSL_CTX_set_options(ctx, op) \
  916. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  917. #define SSL_CTX_clear_options(ctx, op) \
  918. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  919. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  920. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  921. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  922. #define CRYPTO_set_locking_callback \
  923. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  924. #define CRYPTO_set_id_callback \
  925. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  926. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  927. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  928. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  929. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  930. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  931. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  932. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  933. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  934. /* set_ssl_option() function updates this array.
  935. * It loads SSL library dynamically and changes NULLs to the actual addresses
  936. * of respective functions. The macros above (like SSL_connect()) are really
  937. * just calling these functions indirectly via the pointer. */
  938. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  939. {"SSL_accept", NULL},
  940. {"SSL_connect", NULL},
  941. {"SSL_read", NULL},
  942. {"SSL_write", NULL},
  943. {"SSL_get_error", NULL},
  944. {"SSL_set_fd", NULL},
  945. {"SSL_new", NULL},
  946. {"SSL_CTX_new", NULL},
  947. {"SSLv23_server_method", NULL},
  948. {"SSL_library_init", NULL},
  949. {"SSL_CTX_use_PrivateKey_file", NULL},
  950. {"SSL_CTX_use_certificate_file", NULL},
  951. {"SSL_CTX_set_default_passwd_cb", NULL},
  952. {"SSL_CTX_free", NULL},
  953. {"SSL_load_error_strings", NULL},
  954. {"SSL_CTX_use_certificate_chain_file", NULL},
  955. {"SSLv23_client_method", NULL},
  956. {"SSL_pending", NULL},
  957. {"SSL_CTX_set_verify", NULL},
  958. {"SSL_shutdown", NULL},
  959. {"SSL_CTX_load_verify_locations", NULL},
  960. {"SSL_CTX_set_default_verify_paths", NULL},
  961. {"SSL_CTX_set_verify_depth", NULL},
  962. {"SSL_get_peer_certificate", NULL},
  963. {"SSL_get_version", NULL},
  964. {"SSL_get_current_cipher", NULL},
  965. {"SSL_CIPHER_get_name", NULL},
  966. {"SSL_CTX_check_private_key", NULL},
  967. {"SSL_CTX_set_session_id_context", NULL},
  968. {"SSL_CTX_ctrl", NULL},
  969. {"SSL_CTX_set_cipher_list", NULL},
  970. {NULL, NULL}};
  971. /* Similar array as ssl_sw. These functions could be located in different
  972. * lib. */
  973. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  974. {"CRYPTO_set_locking_callback", NULL},
  975. {"CRYPTO_set_id_callback", NULL},
  976. {"ERR_get_error", NULL},
  977. {"ERR_error_string", NULL},
  978. {"ERR_remove_state", NULL},
  979. {"ERR_free_strings", NULL},
  980. {"ENGINE_cleanup", NULL},
  981. {"CONF_modules_unload", NULL},
  982. {"CRYPTO_cleanup_all_ex_data", NULL},
  983. {"EVP_cleanup", NULL},
  984. {NULL, NULL}};
  985. #endif /* NO_SSL_DL */
  986. #endif /* NO_SSL */
  987. #if !defined(NO_CACHING)
  988. static const char *month_names[] = {"Jan",
  989. "Feb",
  990. "Mar",
  991. "Apr",
  992. "May",
  993. "Jun",
  994. "Jul",
  995. "Aug",
  996. "Sep",
  997. "Oct",
  998. "Nov",
  999. "Dec"};
  1000. #endif /* !NO_CACHING */
  1001. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1002. * union u. */
  1003. union usa {
  1004. struct sockaddr sa;
  1005. struct sockaddr_in sin;
  1006. #if defined(USE_IPV6)
  1007. struct sockaddr_in6 sin6;
  1008. #endif
  1009. };
  1010. /* Describes a string (chunk of memory). */
  1011. struct vec {
  1012. const char *ptr;
  1013. size_t len;
  1014. };
  1015. struct file {
  1016. uint64_t size;
  1017. time_t last_modified;
  1018. FILE *fp;
  1019. const char *membuf; /* Non-NULL if file data is in memory */
  1020. int is_directory;
  1021. int gzipped; /* set to 1 if the content is gzipped
  1022. * in which case we need a content-encoding: gzip header */
  1023. };
  1024. #define STRUCT_FILE_INITIALIZER \
  1025. { \
  1026. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1027. }
  1028. /* Describes listening socket, or socket which was accept()-ed by the master
  1029. * thread and queued for future handling by the worker thread. */
  1030. struct socket {
  1031. SOCKET sock; /* Listening socket */
  1032. union usa lsa; /* Local socket address */
  1033. union usa rsa; /* Remote socket address */
  1034. unsigned char is_ssl; /* Is port SSL-ed */
  1035. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1036. * port */
  1037. };
  1038. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1039. enum {
  1040. CGI_EXTENSIONS,
  1041. CGI_ENVIRONMENT,
  1042. PUT_DELETE_PASSWORDS_FILE,
  1043. CGI_INTERPRETER,
  1044. PROTECT_URI,
  1045. AUTHENTICATION_DOMAIN,
  1046. SSI_EXTENSIONS,
  1047. THROTTLE,
  1048. ACCESS_LOG_FILE,
  1049. ENABLE_DIRECTORY_LISTING,
  1050. ERROR_LOG_FILE,
  1051. GLOBAL_PASSWORDS_FILE,
  1052. INDEX_FILES,
  1053. ENABLE_KEEP_ALIVE,
  1054. ACCESS_CONTROL_LIST,
  1055. EXTRA_MIME_TYPES,
  1056. LISTENING_PORTS,
  1057. DOCUMENT_ROOT,
  1058. SSL_CERTIFICATE,
  1059. NUM_THREADS,
  1060. RUN_AS_USER,
  1061. REWRITE,
  1062. HIDE_FILES,
  1063. REQUEST_TIMEOUT,
  1064. SSL_DO_VERIFY_PEER,
  1065. SSL_CA_PATH,
  1066. SSL_CA_FILE,
  1067. SSL_VERIFY_DEPTH,
  1068. SSL_DEFAULT_VERIFY_PATHS,
  1069. SSL_CIPHER_LIST,
  1070. SSL_PROTOCOL_VERSION,
  1071. SSL_SHORT_TRUST,
  1072. #if defined(USE_WEBSOCKET)
  1073. WEBSOCKET_TIMEOUT,
  1074. #endif
  1075. DECODE_URL,
  1076. #if defined(USE_LUA)
  1077. LUA_PRELOAD_FILE,
  1078. LUA_SCRIPT_EXTENSIONS,
  1079. LUA_SERVER_PAGE_EXTENSIONS,
  1080. #endif
  1081. #if defined(USE_DUKTAPE)
  1082. DUKTAPE_SCRIPT_EXTENSIONS,
  1083. #endif
  1084. #if defined(USE_WEBSOCKET)
  1085. WEBSOCKET_ROOT,
  1086. #endif
  1087. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1088. LUA_WEBSOCKET_EXTENSIONS,
  1089. #endif
  1090. ACCESS_CONTROL_ALLOW_ORIGIN,
  1091. ERROR_PAGES,
  1092. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1093. * socket option typedef TCP_NODELAY. */
  1094. #if !defined(NO_CACHING)
  1095. STATIC_FILE_MAX_AGE,
  1096. #endif
  1097. NUM_OPTIONS
  1098. };
  1099. /* Config option name, config types, default value */
  1100. static struct mg_option config_options[] = {
  1101. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1102. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1103. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1104. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1105. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1106. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1107. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1108. {"throttle", CONFIG_TYPE_STRING, NULL},
  1109. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1110. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1111. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1112. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1113. {"index_files",
  1114. CONFIG_TYPE_STRING,
  1115. #ifdef USE_LUA
  1116. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1117. "index.shtml,index.php"},
  1118. #else
  1119. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1120. #endif
  1121. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1122. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1123. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1124. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1125. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1126. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1127. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1128. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1129. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1130. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1131. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1132. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1133. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1134. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1135. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1136. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1137. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1138. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1139. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1140. #if defined(USE_WEBSOCKET)
  1141. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1142. #endif
  1143. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1144. #if defined(USE_LUA)
  1145. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1146. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1147. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1148. #endif
  1149. #if defined(USE_DUKTAPE)
  1150. /* The support for duktape is still in alpha version state.
  1151. * The name of this config option might change. */
  1152. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1153. #endif
  1154. #if defined(USE_WEBSOCKET)
  1155. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1156. #endif
  1157. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1158. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1159. #endif
  1160. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1161. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1162. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1163. #if !defined(NO_CACHING)
  1164. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1165. #endif
  1166. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1167. /* Check if the config_options and the corresponding enum have compatible
  1168. * sizes. */
  1169. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1170. == (NUM_OPTIONS + 1),
  1171. "config_options and enum not sync");
  1172. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1173. struct mg_handler_info {
  1174. /* Name/Pattern of the URI. */
  1175. char *uri;
  1176. size_t uri_len;
  1177. /* handler type */
  1178. int handler_type;
  1179. /* Handler for http/https or authorization requests. */
  1180. mg_request_handler handler;
  1181. /* Handler for ws/wss (websocket) requests. */
  1182. mg_websocket_connect_handler connect_handler;
  1183. mg_websocket_ready_handler ready_handler;
  1184. mg_websocket_data_handler data_handler;
  1185. mg_websocket_close_handler close_handler;
  1186. /* Handler for authorization requests */
  1187. mg_authorization_handler auth_handler;
  1188. /* User supplied argument for the handler function. */
  1189. void *cbdata;
  1190. /* next handler in a linked list */
  1191. struct mg_handler_info *next;
  1192. };
  1193. struct mg_context {
  1194. volatile int stop_flag; /* Should we stop event loop */
  1195. SSL_CTX *ssl_ctx; /* SSL context */
  1196. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1197. struct mg_callbacks callbacks; /* User-defined callback function */
  1198. void *user_data; /* User-defined data */
  1199. int context_type; /* 1 = server context, 2 = client context */
  1200. struct socket *listening_sockets;
  1201. in_port_t *listening_ports;
  1202. unsigned int num_listening_sockets;
  1203. volatile int
  1204. running_worker_threads; /* Number of currently running worker threads */
  1205. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1206. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1207. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1208. volatile int sq_head; /* Head of the socket queue */
  1209. volatile int sq_tail; /* Tail of the socket queue */
  1210. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1211. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1212. pthread_t masterthreadid; /* The master thread ID */
  1213. unsigned int
  1214. cfg_worker_threads; /* The number of configured worker threads. */
  1215. pthread_t *workerthreadids; /* The worker thread IDs */
  1216. time_t start_time; /* Server start time, used for authentication */
  1217. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1218. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1219. unsigned long nonce_count; /* Used nonces, used for authentication */
  1220. char *systemName; /* What operating system is running */
  1221. /* linked list of uri handlers */
  1222. struct mg_handler_info *handlers;
  1223. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1224. /* linked list of shared lua websockets */
  1225. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1226. #endif
  1227. #ifdef USE_TIMERS
  1228. struct ttimers *timers;
  1229. #endif
  1230. };
  1231. struct mg_connection {
  1232. struct mg_request_info request_info;
  1233. struct mg_context *ctx;
  1234. SSL *ssl; /* SSL descriptor */
  1235. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1236. struct socket client; /* Connected client */
  1237. time_t conn_birth_time; /* Time (wall clock) when connection was
  1238. * established */
  1239. struct timespec req_time; /* Time (since system start) when the request
  1240. * was received */
  1241. int64_t num_bytes_sent; /* Total bytes sent to client */
  1242. int64_t content_len; /* Content-Length header value */
  1243. int64_t consumed_content; /* How many bytes of content have been read */
  1244. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1245. * data available, 2: all data read */
  1246. size_t chunk_remainder; /* Unread data from the last chunk */
  1247. char *buf; /* Buffer for received data */
  1248. char *path_info; /* PATH_INFO part of the URL */
  1249. int must_close; /* 1 if connection must be closed */
  1250. int in_error_handler; /* 1 if in handler for user defined error
  1251. * pages */
  1252. int internal_error; /* 1 if an error occured while processing the
  1253. * request */
  1254. int buf_size; /* Buffer size */
  1255. int request_len; /* Size of the request + headers in a buffer */
  1256. int data_len; /* Total size of data in a buffer */
  1257. int status_code; /* HTTP reply status code, e.g. 200 */
  1258. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1259. * throttle */
  1260. time_t last_throttle_time; /* Last time throttled data was sent */
  1261. int64_t last_throttle_bytes; /* Bytes sent this second */
  1262. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1263. * atomic transmissions for websockets */
  1264. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1265. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1266. #endif
  1267. };
  1268. static pthread_key_t sTlsKey; /* Thread local storage index */
  1269. static int sTlsInit = 0;
  1270. static int thread_idx_max = 0;
  1271. struct mg_workerTLS {
  1272. int is_master;
  1273. unsigned long thread_idx;
  1274. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1275. HANDLE pthread_cond_helper_mutex;
  1276. #endif
  1277. };
  1278. /* Directory entry */
  1279. struct de {
  1280. struct mg_connection *conn;
  1281. char *file_name;
  1282. struct file file;
  1283. };
  1284. #if defined(USE_WEBSOCKET)
  1285. static int is_websocket_protocol(const struct mg_connection *conn);
  1286. #else
  1287. #define is_websocket_protocol(conn) (0)
  1288. #endif
  1289. static int
  1290. mg_atomic_inc(volatile int *addr)
  1291. {
  1292. int ret;
  1293. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1294. /* Depending on the SDK, this function uses either
  1295. * (volatile unsigned int *) or (volatile LONG *),
  1296. * so whatever you use, the other SDK is likely to raise a warning. */
  1297. ret = InterlockedIncrement((volatile long *)addr);
  1298. #elif defined(__GNUC__) \
  1299. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1300. ret = __sync_add_and_fetch(addr, 1);
  1301. #else
  1302. ret = (++(*addr));
  1303. #endif
  1304. return ret;
  1305. }
  1306. static int
  1307. mg_atomic_dec(volatile int *addr)
  1308. {
  1309. int ret;
  1310. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1311. /* Depending on the SDK, this function uses either
  1312. * (volatile unsigned int *) or (volatile LONG *),
  1313. * so whatever you use, the other SDK is likely to raise a warning. */
  1314. ret = InterlockedDecrement((volatile long *)addr);
  1315. #elif defined(__GNUC__) \
  1316. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1317. ret = __sync_sub_and_fetch(addr, 1);
  1318. #else
  1319. ret = (--(*addr));
  1320. #endif
  1321. return ret;
  1322. }
  1323. #if !defined(NO_THREAD_NAME)
  1324. #if defined(_WIN32) && defined(_MSC_VER)
  1325. /* Set the thread name for debugging purposes in Visual Studio
  1326. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1327. */
  1328. #pragma pack(push, 8)
  1329. typedef struct tagTHREADNAME_INFO {
  1330. DWORD dwType; /* Must be 0x1000. */
  1331. LPCSTR szName; /* Pointer to name (in user addr space). */
  1332. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1333. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1334. } THREADNAME_INFO;
  1335. #pragma pack(pop)
  1336. #elif defined(__linux__)
  1337. #include <sys/prctl.h>
  1338. #include <sys/sendfile.h>
  1339. #endif
  1340. static void
  1341. mg_set_thread_name(const char *name)
  1342. {
  1343. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1344. mg_snprintf(
  1345. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1346. #if defined(_WIN32)
  1347. #if defined(_MSC_VER)
  1348. /* Windows and Visual Studio Compiler */
  1349. __try
  1350. {
  1351. THREADNAME_INFO info;
  1352. info.dwType = 0x1000;
  1353. info.szName = threadName;
  1354. info.dwThreadID = ~0U;
  1355. info.dwFlags = 0;
  1356. RaiseException(0x406D1388,
  1357. 0,
  1358. sizeof(info) / sizeof(ULONG_PTR),
  1359. (ULONG_PTR *)&info);
  1360. }
  1361. __except(EXCEPTION_EXECUTE_HANDLER)
  1362. {
  1363. }
  1364. #elif defined(__MINGW32__)
  1365. /* No option known to set thread name for MinGW */
  1366. #endif
  1367. #elif defined(__GLIBC__) \
  1368. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1369. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1370. (void)pthread_setname_np(pthread_self(), threadName);
  1371. #elif defined(__linux__)
  1372. /* on linux we can use the old prctl function */
  1373. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1374. #endif
  1375. }
  1376. #else /* !defined(NO_THREAD_NAME) */
  1377. void
  1378. mg_set_thread_name(const char *threadName)
  1379. {
  1380. }
  1381. #endif
  1382. #if defined(MG_LEGACY_INTERFACE)
  1383. const char **
  1384. mg_get_valid_option_names(void)
  1385. {
  1386. /* This function is deprecated. Use mg_get_valid_options instead. */
  1387. static const char *
  1388. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1389. int i;
  1390. for (i = 0; config_options[i].name != NULL; i++) {
  1391. data[i * 2] = config_options[i].name;
  1392. data[i * 2 + 1] = config_options[i].default_value;
  1393. }
  1394. return data;
  1395. }
  1396. #endif
  1397. const struct mg_option *
  1398. mg_get_valid_options(void)
  1399. {
  1400. return config_options;
  1401. }
  1402. static int
  1403. is_file_in_memory(const struct mg_connection *conn,
  1404. const char *path,
  1405. struct file *filep)
  1406. {
  1407. size_t size = 0;
  1408. if (!conn || !filep) {
  1409. return 0;
  1410. }
  1411. if (conn->ctx->callbacks.open_file) {
  1412. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1413. if (filep->membuf != NULL) {
  1414. /* NOTE: override filep->size only on success. Otherwise, it might
  1415. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1416. filep->size = size;
  1417. }
  1418. }
  1419. return filep->membuf != NULL;
  1420. }
  1421. static int
  1422. is_file_opened(const struct file *filep)
  1423. {
  1424. if (!filep) {
  1425. return 0;
  1426. }
  1427. return filep->membuf != NULL || filep->fp != NULL;
  1428. }
  1429. /* mg_fopen will open a file either in memory or on the disk.
  1430. * The input parameter path is a string in UTF-8 encoding.
  1431. * The input parameter mode is the same as for fopen.
  1432. * Either fp or membuf will be set in the output struct filep.
  1433. * The function returns 1 on success, 0 on error. */
  1434. static int
  1435. mg_fopen(const struct mg_connection *conn,
  1436. const char *path,
  1437. const char *mode,
  1438. struct file *filep)
  1439. {
  1440. struct stat st;
  1441. if (!filep) {
  1442. return 0;
  1443. }
  1444. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1445. * only get the file status. They should not work on different members of
  1446. * the same structure (bad cohesion). */
  1447. memset(filep, 0, sizeof(*filep));
  1448. if (stat(path, &st) == 0) {
  1449. filep->size = (uint64_t)(st.st_size);
  1450. }
  1451. if (!is_file_in_memory(conn, path, filep)) {
  1452. #ifdef _WIN32
  1453. wchar_t wbuf[PATH_MAX], wmode[20];
  1454. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1455. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1456. filep->fp = _wfopen(wbuf, wmode);
  1457. #else
  1458. /* Linux et al already use unicode. No need to convert. */
  1459. filep->fp = fopen(path, mode);
  1460. #endif
  1461. }
  1462. return is_file_opened(filep);
  1463. }
  1464. static void
  1465. mg_fclose(struct file *filep)
  1466. {
  1467. if (filep != NULL && filep->fp != NULL) {
  1468. fclose(filep->fp);
  1469. }
  1470. }
  1471. static void
  1472. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1473. {
  1474. for (; *src != '\0' && n > 1; n--) {
  1475. *dst++ = *src++;
  1476. }
  1477. *dst = '\0';
  1478. }
  1479. static int
  1480. lowercase(const char *s)
  1481. {
  1482. return tolower(*(const unsigned char *)s);
  1483. }
  1484. int
  1485. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1486. {
  1487. int diff = 0;
  1488. if (len > 0) {
  1489. do {
  1490. diff = lowercase(s1++) - lowercase(s2++);
  1491. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1492. }
  1493. return diff;
  1494. }
  1495. int
  1496. mg_strcasecmp(const char *s1, const char *s2)
  1497. {
  1498. int diff;
  1499. do {
  1500. diff = lowercase(s1++) - lowercase(s2++);
  1501. } while (diff == 0 && s1[-1] != '\0');
  1502. return diff;
  1503. }
  1504. static char *
  1505. mg_strndup(const char *ptr, size_t len)
  1506. {
  1507. char *p;
  1508. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1509. mg_strlcpy(p, ptr, len + 1);
  1510. }
  1511. return p;
  1512. }
  1513. static char *
  1514. mg_strdup(const char *str)
  1515. {
  1516. return mg_strndup(str, strlen(str));
  1517. }
  1518. static const char *
  1519. mg_strcasestr(const char *big_str, const char *small_str)
  1520. {
  1521. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1522. if (big_len >= small_len) {
  1523. for (i = 0; i <= (big_len - small_len); i++) {
  1524. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1525. return big_str + i;
  1526. }
  1527. }
  1528. }
  1529. return NULL;
  1530. }
  1531. /* Return null terminated string of given maximum length.
  1532. * Report errors if length is exceeded. */
  1533. static void
  1534. mg_vsnprintf(const struct mg_connection *conn,
  1535. int *truncated,
  1536. char *buf,
  1537. size_t buflen,
  1538. const char *fmt,
  1539. va_list ap)
  1540. {
  1541. int n, ok;
  1542. if (buflen == 0) {
  1543. return;
  1544. }
  1545. #ifdef __clang__
  1546. #pragma clang diagnostic push
  1547. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1548. /* Using fmt as a non-literal is intended here, since it is mostly called
  1549. * indirectly by mg_snprintf */
  1550. #endif
  1551. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1552. ok = (n >= 0) && ((size_t)n < buflen);
  1553. #ifdef __clang__
  1554. #pragma clang diagnostic pop
  1555. #endif
  1556. if (ok) {
  1557. if (truncated) {
  1558. *truncated = 0;
  1559. }
  1560. } else {
  1561. if (truncated) {
  1562. *truncated = 1;
  1563. }
  1564. mg_cry(conn,
  1565. "truncating vsnprintf buffer: [%.*s]",
  1566. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1567. buf);
  1568. n = (int)buflen - 1;
  1569. }
  1570. buf[n] = '\0';
  1571. }
  1572. static void
  1573. mg_snprintf(const struct mg_connection *conn,
  1574. int *truncated,
  1575. char *buf,
  1576. size_t buflen,
  1577. const char *fmt,
  1578. ...)
  1579. {
  1580. va_list ap;
  1581. va_start(ap, fmt);
  1582. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1583. va_end(ap);
  1584. }
  1585. static int
  1586. get_option_index(const char *name)
  1587. {
  1588. int i;
  1589. for (i = 0; config_options[i].name != NULL; i++) {
  1590. if (strcmp(config_options[i].name, name) == 0) {
  1591. return i;
  1592. }
  1593. }
  1594. return -1;
  1595. }
  1596. const char *
  1597. mg_get_option(const struct mg_context *ctx, const char *name)
  1598. {
  1599. int i;
  1600. if ((i = get_option_index(name)) == -1) {
  1601. return NULL;
  1602. } else if (!ctx || ctx->config[i] == NULL) {
  1603. return "";
  1604. } else {
  1605. return ctx->config[i];
  1606. }
  1607. }
  1608. struct mg_context *
  1609. mg_get_context(const struct mg_connection *conn)
  1610. {
  1611. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1612. }
  1613. void *
  1614. mg_get_user_data(const struct mg_context *ctx)
  1615. {
  1616. return (ctx == NULL) ? NULL : ctx->user_data;
  1617. }
  1618. void
  1619. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1620. {
  1621. if (conn != NULL) {
  1622. conn->request_info.conn_data = data;
  1623. }
  1624. }
  1625. void *
  1626. mg_get_user_connection_data(const struct mg_connection *conn)
  1627. {
  1628. if (conn != NULL) {
  1629. return conn->request_info.conn_data;
  1630. }
  1631. return NULL;
  1632. }
  1633. size_t
  1634. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1635. {
  1636. size_t i;
  1637. if (!ctx) {
  1638. return 0;
  1639. }
  1640. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1641. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1642. ports[i] = ctx->listening_ports[i];
  1643. }
  1644. return i;
  1645. }
  1646. int
  1647. mg_get_server_ports(const struct mg_context *ctx,
  1648. int size,
  1649. struct mg_server_ports *ports)
  1650. {
  1651. int i, cnt = 0;
  1652. if (size <= 0) {
  1653. return -1;
  1654. }
  1655. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1656. if (!ctx) {
  1657. return -1;
  1658. }
  1659. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1660. return -1;
  1661. }
  1662. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1663. ports[cnt].port = ctx->listening_ports[i];
  1664. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1665. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1666. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1667. /* IPv4 */
  1668. ports[cnt].protocol = 1;
  1669. cnt++;
  1670. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1671. /* IPv6 */
  1672. ports[cnt].protocol = 3;
  1673. cnt++;
  1674. }
  1675. }
  1676. return cnt;
  1677. }
  1678. static void
  1679. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1680. {
  1681. buf[0] = '\0';
  1682. if (!usa) {
  1683. return;
  1684. }
  1685. if (usa->sa.sa_family == AF_INET) {
  1686. getnameinfo(&usa->sa,
  1687. sizeof(usa->sin),
  1688. buf,
  1689. (unsigned)len,
  1690. NULL,
  1691. 0,
  1692. NI_NUMERICHOST);
  1693. }
  1694. #if defined(USE_IPV6)
  1695. else if (usa->sa.sa_family == AF_INET6) {
  1696. getnameinfo(&usa->sa,
  1697. sizeof(usa->sin6),
  1698. buf,
  1699. (unsigned)len,
  1700. NULL,
  1701. 0,
  1702. NI_NUMERICHOST);
  1703. }
  1704. #endif
  1705. }
  1706. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1707. * included in all responses other than 100, 101, 5xx. */
  1708. static void
  1709. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1710. {
  1711. struct tm *tm;
  1712. tm = ((t != NULL) ? gmtime(t) : NULL);
  1713. if (tm != NULL) {
  1714. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1715. } else {
  1716. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1717. buf[buf_len - 1] = '\0';
  1718. }
  1719. }
  1720. /* difftime for struct timespec. Return value is in seconds. */
  1721. static double
  1722. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1723. {
  1724. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1725. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1726. }
  1727. /* Print error message to the opened error log stream. */
  1728. void
  1729. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1730. {
  1731. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1732. va_list ap;
  1733. struct file fi;
  1734. time_t timestamp;
  1735. va_start(ap, fmt);
  1736. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1737. va_end(ap);
  1738. buf[sizeof(buf) - 1] = 0;
  1739. if (!conn) {
  1740. puts(buf);
  1741. return;
  1742. }
  1743. /* Do not lock when getting the callback value, here and below.
  1744. * I suppose this is fine, since function cannot disappear in the
  1745. * same way string option can. */
  1746. if ((conn->ctx->callbacks.log_message == NULL)
  1747. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1748. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1749. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1750. == 0) {
  1751. fi.fp = NULL;
  1752. }
  1753. } else {
  1754. fi.fp = NULL;
  1755. }
  1756. if (fi.fp != NULL) {
  1757. flockfile(fi.fp);
  1758. timestamp = time(NULL);
  1759. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1760. fprintf(fi.fp,
  1761. "[%010lu] [error] [client %s] ",
  1762. (unsigned long)timestamp,
  1763. src_addr);
  1764. if (conn->request_info.request_method != NULL) {
  1765. fprintf(fi.fp,
  1766. "%s %s: ",
  1767. conn->request_info.request_method,
  1768. conn->request_info.request_uri);
  1769. }
  1770. fprintf(fi.fp, "%s", buf);
  1771. fputc('\n', fi.fp);
  1772. fflush(fi.fp);
  1773. funlockfile(fi.fp);
  1774. mg_fclose(&fi);
  1775. }
  1776. }
  1777. }
  1778. /* Return fake connection structure. Used for logging, if connection
  1779. * is not applicable at the moment of logging. */
  1780. static struct mg_connection *
  1781. fc(struct mg_context *ctx)
  1782. {
  1783. static struct mg_connection fake_connection;
  1784. fake_connection.ctx = ctx;
  1785. return &fake_connection;
  1786. }
  1787. const char *
  1788. mg_version(void)
  1789. {
  1790. return CIVETWEB_VERSION;
  1791. }
  1792. const struct mg_request_info *
  1793. mg_get_request_info(const struct mg_connection *conn)
  1794. {
  1795. if (!conn) {
  1796. return NULL;
  1797. }
  1798. return &conn->request_info;
  1799. }
  1800. /* Skip the characters until one of the delimiters characters found.
  1801. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1802. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1803. * Delimiters can be quoted with quotechar. */
  1804. static char *
  1805. skip_quoted(char **buf,
  1806. const char *delimiters,
  1807. const char *whitespace,
  1808. char quotechar)
  1809. {
  1810. char *p, *begin_word, *end_word, *end_whitespace;
  1811. begin_word = *buf;
  1812. end_word = begin_word + strcspn(begin_word, delimiters);
  1813. /* Check for quotechar */
  1814. if (end_word > begin_word) {
  1815. p = end_word - 1;
  1816. while (*p == quotechar) {
  1817. /* While the delimiter is quoted, look for the next delimiter. */
  1818. /* This happens, e.g., in calls from parse_auth_header,
  1819. * if the user name contains a " character. */
  1820. /* If there is anything beyond end_word, copy it. */
  1821. if (*end_word != '\0') {
  1822. size_t end_off = strcspn(end_word + 1, delimiters);
  1823. memmove(p, end_word, end_off + 1);
  1824. p += end_off; /* p must correspond to end_word - 1 */
  1825. end_word += end_off + 1;
  1826. } else {
  1827. *p = '\0';
  1828. break;
  1829. }
  1830. }
  1831. for (p++; p < end_word; p++) {
  1832. *p = '\0';
  1833. }
  1834. }
  1835. if (*end_word == '\0') {
  1836. *buf = end_word;
  1837. } else {
  1838. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1839. for (p = end_word; p < end_whitespace; p++) {
  1840. *p = '\0';
  1841. }
  1842. *buf = end_whitespace;
  1843. }
  1844. return begin_word;
  1845. }
  1846. /* Simplified version of skip_quoted without quote char
  1847. * and whitespace == delimiters */
  1848. static char *
  1849. skip(char **buf, const char *delimiters)
  1850. {
  1851. return skip_quoted(buf, delimiters, delimiters, 0);
  1852. }
  1853. /* Return HTTP header value, or NULL if not found. */
  1854. static const char *
  1855. get_header(const struct mg_request_info *ri, const char *name)
  1856. {
  1857. int i;
  1858. if (ri) {
  1859. for (i = 0; i < ri->num_headers; i++) {
  1860. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1861. return ri->http_headers[i].value;
  1862. }
  1863. }
  1864. }
  1865. return NULL;
  1866. }
  1867. const char *
  1868. mg_get_header(const struct mg_connection *conn, const char *name)
  1869. {
  1870. if (!conn) {
  1871. return NULL;
  1872. }
  1873. return get_header(&conn->request_info, name);
  1874. }
  1875. /* A helper function for traversing a comma separated list of values.
  1876. * It returns a list pointer shifted to the next value, or NULL if the end
  1877. * of the list found.
  1878. * Value is stored in val vector. If value has form "x=y", then eq_val
  1879. * vector is initialized to point to the "y" part, and val vector length
  1880. * is adjusted to point only to "x". */
  1881. static const char *
  1882. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1883. {
  1884. int end;
  1885. reparse:
  1886. if (val == NULL || list == NULL || *list == '\0') {
  1887. /* End of the list */
  1888. list = NULL;
  1889. } else {
  1890. /* Skip over leading LWS */
  1891. while (*list == ' ' || *list == '\t')
  1892. list++;
  1893. val->ptr = list;
  1894. if ((list = strchr(val->ptr, ',')) != NULL) {
  1895. /* Comma found. Store length and shift the list ptr */
  1896. val->len = ((size_t)(list - val->ptr));
  1897. list++;
  1898. } else {
  1899. /* This value is the last one */
  1900. list = val->ptr + strlen(val->ptr);
  1901. val->len = ((size_t)(list - val->ptr));
  1902. }
  1903. /* Adjust length for trailing LWS */
  1904. end = (int)val->len - 1;
  1905. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  1906. end--;
  1907. val->len = (size_t)(end + 1);
  1908. if (val->len == 0) {
  1909. /* Ignore any empty entries. */
  1910. goto reparse;
  1911. }
  1912. if (eq_val != NULL) {
  1913. /* Value has form "x=y", adjust pointers and lengths
  1914. * so that val points to "x", and eq_val points to "y". */
  1915. eq_val->len = 0;
  1916. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1917. if (eq_val->ptr != NULL) {
  1918. eq_val->ptr++; /* Skip over '=' character */
  1919. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1920. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1921. }
  1922. }
  1923. }
  1924. return list;
  1925. }
  1926. /* A helper function for checking if a comma separated list of values contains
  1927. * the given option (case insensitvely).
  1928. * 'header' can be NULL, in which case false is returned. */
  1929. static int
  1930. header_has_option(const char *header, const char *option)
  1931. {
  1932. struct vec opt_vec;
  1933. struct vec eq_vec;
  1934. assert(option != NULL);
  1935. assert(option[0] != '\0');
  1936. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  1937. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  1938. return 1;
  1939. }
  1940. return 0;
  1941. }
  1942. /* Perform case-insensitive match of string against pattern */
  1943. static int
  1944. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1945. {
  1946. const char *or_str;
  1947. size_t i;
  1948. int j, len, res;
  1949. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1950. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1951. return res > 0 ? res : match_prefix(or_str + 1,
  1952. (size_t)((pattern + pattern_len)
  1953. - (or_str + 1)),
  1954. str);
  1955. }
  1956. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1957. if (pattern[i] == '?' && str[j] != '\0') {
  1958. continue;
  1959. } else if (pattern[i] == '$') {
  1960. return str[j] == '\0' ? j : -1;
  1961. } else if (pattern[i] == '*') {
  1962. i++;
  1963. if (pattern[i] == '*') {
  1964. i++;
  1965. len = (int)strlen(str + j);
  1966. } else {
  1967. len = (int)strcspn(str + j, "/");
  1968. }
  1969. if (i == pattern_len) {
  1970. return j + len;
  1971. }
  1972. do {
  1973. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1974. } while (res == -1 && len-- > 0);
  1975. return res == -1 ? -1 : j + res + len;
  1976. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1977. return -1;
  1978. }
  1979. }
  1980. return j;
  1981. }
  1982. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1983. * This function must tolerate situations when connection info is not
  1984. * set up, for example if request parsing failed. */
  1985. static int
  1986. should_keep_alive(const struct mg_connection *conn)
  1987. {
  1988. if (conn != NULL) {
  1989. const char *http_version = conn->request_info.http_version;
  1990. const char *header = mg_get_header(conn, "Connection");
  1991. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1992. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1993. || (header != NULL && !header_has_option(header, "keep-alive"))
  1994. || (header == NULL && http_version
  1995. && 0 != strcmp(http_version, "1.1"))) {
  1996. return 0;
  1997. }
  1998. return 1;
  1999. }
  2000. return 0;
  2001. }
  2002. static int
  2003. should_decode_url(const struct mg_connection *conn)
  2004. {
  2005. if (!conn || !conn->ctx) {
  2006. return 0;
  2007. }
  2008. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2009. }
  2010. static const char *
  2011. suggest_connection_header(const struct mg_connection *conn)
  2012. {
  2013. return should_keep_alive(conn) ? "keep-alive" : "close";
  2014. }
  2015. static int
  2016. send_no_cache_header(struct mg_connection *conn)
  2017. {
  2018. /* Send all current and obsolete cache opt-out directives. */
  2019. return mg_printf(conn,
  2020. "Cache-Control: no-cache, no-store, "
  2021. "must-revalidate, private, max-age=0\r\n"
  2022. "Pragma: no-cache\r\n"
  2023. "Expires: 0\r\n");
  2024. }
  2025. static int
  2026. send_static_cache_header(struct mg_connection *conn)
  2027. {
  2028. #if !defined(NO_CACHING)
  2029. /* Read the server config to check how long a file may be cached.
  2030. * The configuration is in seconds. */
  2031. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2032. if (max_age <= 0) {
  2033. /* 0 means "do not cache". All values <0 are reserved
  2034. * and may be used differently in the future. */
  2035. /* If a file should not be cached, do not only send
  2036. * max-age=0, but also pragmas and Expires headers. */
  2037. return send_no_cache_header(conn);
  2038. }
  2039. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2040. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2041. /* See also https://www.mnot.net/cache_docs/ */
  2042. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2043. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2044. * year to 31622400 seconds. For the moment, we just send whatever has
  2045. * been configured, still the behavior for >1 year should be considered
  2046. * as undefined. */
  2047. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2048. #else /* NO_CACHING */
  2049. return send_no_cache_header(conn);
  2050. #endif /* !NO_CACHING */
  2051. }
  2052. static void handle_file_based_request(struct mg_connection *conn,
  2053. const char *path,
  2054. struct file *filep);
  2055. static int
  2056. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2057. const char *
  2058. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2059. {
  2060. /* See IANA HTTP status code assignment:
  2061. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2062. */
  2063. switch (response_code) {
  2064. /* RFC2616 Section 10.1 - Informational 1xx */
  2065. case 100:
  2066. return "Continue"; /* RFC2616 Section 10.1.1 */
  2067. case 101:
  2068. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2069. case 102:
  2070. return "Processing"; /* RFC2518 Section 10.1 */
  2071. /* RFC2616 Section 10.2 - Successful 2xx */
  2072. case 200:
  2073. return "OK"; /* RFC2616 Section 10.2.1 */
  2074. case 201:
  2075. return "Created"; /* RFC2616 Section 10.2.2 */
  2076. case 202:
  2077. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2078. case 203:
  2079. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2080. case 204:
  2081. return "No Content"; /* RFC2616 Section 10.2.5 */
  2082. case 205:
  2083. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2084. case 206:
  2085. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2086. case 207:
  2087. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2088. case 208:
  2089. return "Already Reported"; /* RFC5842 Section 7.1 */
  2090. case 226:
  2091. return "IM used"; /* RFC3229 Section 10.4.1 */
  2092. /* RFC2616 Section 10.3 - Redirection 3xx */
  2093. case 300:
  2094. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2095. case 301:
  2096. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2097. case 302:
  2098. return "Found"; /* RFC2616 Section 10.3.3 */
  2099. case 303:
  2100. return "See Other"; /* RFC2616 Section 10.3.4 */
  2101. case 304:
  2102. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2103. case 305:
  2104. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2105. case 307:
  2106. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2107. case 308:
  2108. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2109. /* RFC2616 Section 10.4 - Client Error 4xx */
  2110. case 400:
  2111. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2112. case 401:
  2113. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2114. case 402:
  2115. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2116. case 403:
  2117. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2118. case 404:
  2119. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2120. case 405:
  2121. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2122. case 406:
  2123. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2124. case 407:
  2125. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2126. case 408:
  2127. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2128. case 409:
  2129. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2130. case 410:
  2131. return "Gone"; /* RFC2616 Section 10.4.11 */
  2132. case 411:
  2133. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2134. case 412:
  2135. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2136. case 413:
  2137. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2138. case 414:
  2139. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2140. case 415:
  2141. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2142. case 416:
  2143. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2144. case 417:
  2145. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2146. case 421:
  2147. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2148. case 422:
  2149. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2150. * Section 11.2 */
  2151. case 423:
  2152. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2153. case 424:
  2154. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2155. * Section 11.4 */
  2156. case 426:
  2157. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2158. case 428:
  2159. return "Precondition Required"; /* RFC 6585, Section 3 */
  2160. case 429:
  2161. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2162. case 431:
  2163. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2164. case 451:
  2165. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2166. * Section 3 */
  2167. /* RFC2616 Section 10.5 - Server Error 5xx */
  2168. case 500:
  2169. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2170. case 501:
  2171. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2172. case 502:
  2173. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2174. case 503:
  2175. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2176. case 504:
  2177. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2178. case 505:
  2179. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2180. case 506:
  2181. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2182. case 507:
  2183. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2184. * Section 11.5 */
  2185. case 508:
  2186. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2187. case 510:
  2188. return "Not Extended"; /* RFC 2774, Section 7 */
  2189. case 511:
  2190. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2191. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2192. * E.g., "de facto" standards due to common use, ... */
  2193. case 418:
  2194. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2195. case 419:
  2196. return "Authentication Timeout"; /* common use */
  2197. case 420:
  2198. return "Enhance Your Calm"; /* common use */
  2199. case 440:
  2200. return "Login Timeout"; /* common use */
  2201. case 509:
  2202. return "Bandwidth Limit Exceeded"; /* common use */
  2203. default:
  2204. /* This error code is unknown. This should not happen. */
  2205. if (conn) {
  2206. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2207. }
  2208. /* Return at least a category according to RFC 2616 Section 10. */
  2209. if (response_code >= 100 && response_code < 200) {
  2210. /* Unknown informational status code */
  2211. return "Information";
  2212. }
  2213. if (response_code >= 200 && response_code < 300) {
  2214. /* Unknown success code */
  2215. return "Success";
  2216. }
  2217. if (response_code >= 300 && response_code < 400) {
  2218. /* Unknown redirection code */
  2219. return "Redirection";
  2220. }
  2221. if (response_code >= 400 && response_code < 500) {
  2222. /* Unknown request error code */
  2223. return "Client Error";
  2224. }
  2225. if (response_code >= 500 && response_code < 600) {
  2226. /* Unknown server error code */
  2227. return "Server Error";
  2228. }
  2229. /* Response code not even within reasonable range */
  2230. return "";
  2231. }
  2232. }
  2233. static void send_http_error(struct mg_connection *,
  2234. int,
  2235. PRINTF_FORMAT_STRING(const char *fmt),
  2236. ...) PRINTF_ARGS(3, 4);
  2237. static void
  2238. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2239. {
  2240. char buf[MG_BUF_LEN];
  2241. va_list ap;
  2242. int len, i, page_handler_found, scope, truncated;
  2243. char date[64];
  2244. time_t curtime = time(NULL);
  2245. const char *error_handler = NULL;
  2246. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2247. const char *error_page_file_ext, *tstr;
  2248. const char *status_text = mg_get_response_code_text(conn, status);
  2249. if (conn == NULL) {
  2250. return;
  2251. }
  2252. conn->status_code = status;
  2253. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2254. || conn->ctx->callbacks.http_error(conn, status)) {
  2255. if (!conn->in_error_handler) {
  2256. /* Send user defined error pages, if defined */
  2257. error_handler = conn->ctx->config[ERROR_PAGES];
  2258. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2259. page_handler_found = 0;
  2260. if (error_handler != NULL) {
  2261. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2262. switch (scope) {
  2263. case 1: /* Handler for specific error, e.g. 404 error */
  2264. mg_snprintf(conn,
  2265. &truncated,
  2266. buf,
  2267. sizeof(buf) - 32,
  2268. "%serror%03u.",
  2269. error_handler,
  2270. status);
  2271. break;
  2272. case 2: /* Handler for error group, e.g., 5xx error handler
  2273. * for all server errors (500-599) */
  2274. mg_snprintf(conn,
  2275. &truncated,
  2276. buf,
  2277. sizeof(buf) - 32,
  2278. "%serror%01uxx.",
  2279. error_handler,
  2280. status / 100);
  2281. break;
  2282. default: /* Handler for all errors */
  2283. mg_snprintf(conn,
  2284. &truncated,
  2285. buf,
  2286. sizeof(buf) - 32,
  2287. "%serror.",
  2288. error_handler);
  2289. break;
  2290. }
  2291. /* String truncation in buf may only occur if error_handler
  2292. * is too long. This string is from the config, not from a
  2293. * client. */
  2294. (void)truncated;
  2295. len = (int)strlen(buf);
  2296. tstr = strchr(error_page_file_ext, '.');
  2297. while (tstr) {
  2298. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2299. i++)
  2300. buf[len + i - 1] = tstr[i];
  2301. buf[len + i - 1] = 0;
  2302. if (mg_stat(conn, buf, &error_page_file)) {
  2303. page_handler_found = 1;
  2304. break;
  2305. }
  2306. tstr = strchr(tstr + i, '.');
  2307. }
  2308. }
  2309. }
  2310. if (page_handler_found) {
  2311. conn->in_error_handler = 1;
  2312. handle_file_based_request(conn, buf, &error_page_file);
  2313. conn->in_error_handler = 0;
  2314. return;
  2315. }
  2316. }
  2317. /* No custom error page. Send default error page. */
  2318. gmt_time_string(date, sizeof(date), &curtime);
  2319. conn->must_close = 1;
  2320. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2321. send_no_cache_header(conn);
  2322. mg_printf(conn,
  2323. "Date: %s\r\n"
  2324. "Connection: close\r\n\r\n",
  2325. date);
  2326. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2327. if (status > 199 && status != 204 && status != 304) {
  2328. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2329. if (fmt != NULL) {
  2330. va_start(ap, fmt);
  2331. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2332. va_end(ap);
  2333. mg_write(conn, buf, strlen(buf));
  2334. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2335. }
  2336. } else {
  2337. /* No body allowed. Close the connection. */
  2338. DEBUG_TRACE("Error %i", status);
  2339. }
  2340. }
  2341. }
  2342. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2343. /* Create substitutes for POSIX functions in Win32. */
  2344. #if defined(__MINGW32__)
  2345. /* Show no warning in case system functions are not used. */
  2346. #pragma GCC diagnostic push
  2347. #pragma GCC diagnostic ignored "-Wunused-function"
  2348. #endif
  2349. static int
  2350. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2351. {
  2352. (void)unused;
  2353. *mutex = CreateMutex(NULL, FALSE, NULL);
  2354. return *mutex == NULL ? -1 : 0;
  2355. }
  2356. static int
  2357. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2358. {
  2359. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2360. }
  2361. static int
  2362. pthread_mutex_lock(pthread_mutex_t *mutex)
  2363. {
  2364. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2365. }
  2366. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2367. static int
  2368. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2369. {
  2370. switch (WaitForSingleObject(*mutex, 0)) {
  2371. case WAIT_OBJECT_0:
  2372. return 0;
  2373. case WAIT_TIMEOUT:
  2374. return -2; /* EBUSY */
  2375. }
  2376. return -1;
  2377. }
  2378. #endif
  2379. static int
  2380. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2381. {
  2382. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2383. }
  2384. #ifndef WIN_PTHREADS_TIME_H
  2385. static int
  2386. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2387. {
  2388. FILETIME ft;
  2389. ULARGE_INTEGER li;
  2390. BOOL ok = FALSE;
  2391. double d;
  2392. static double perfcnt_per_sec = 0.0;
  2393. if (tp) {
  2394. memset(tp, 0, sizeof(*tp));
  2395. if (clk_id == CLOCK_REALTIME) {
  2396. GetSystemTimeAsFileTime(&ft);
  2397. li.LowPart = ft.dwLowDateTime;
  2398. li.HighPart = ft.dwHighDateTime;
  2399. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2400. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2401. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2402. ok = TRUE;
  2403. } else if (clk_id == CLOCK_MONOTONIC) {
  2404. if (perfcnt_per_sec == 0.0) {
  2405. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2406. perfcnt_per_sec = 1.0 / li.QuadPart;
  2407. }
  2408. if (perfcnt_per_sec != 0.0) {
  2409. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2410. d = li.QuadPart * perfcnt_per_sec;
  2411. tp->tv_sec = (time_t)d;
  2412. d -= tp->tv_sec;
  2413. tp->tv_nsec = (long)(d * 1.0E9);
  2414. ok = TRUE;
  2415. }
  2416. }
  2417. }
  2418. return ok ? 0 : -1;
  2419. }
  2420. #endif
  2421. static int
  2422. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2423. {
  2424. (void)unused;
  2425. InitializeCriticalSection(&cv->threadIdSec);
  2426. cv->waitingthreadcount = 0;
  2427. cv->waitingthreadhdls =
  2428. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2429. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2430. }
  2431. static int
  2432. pthread_cond_timedwait(pthread_cond_t *cv,
  2433. pthread_mutex_t *mutex,
  2434. const struct timespec *abstime)
  2435. {
  2436. struct mg_workerTLS *tls =
  2437. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2438. int ok;
  2439. struct timespec tsnow;
  2440. int64_t nsnow, nswaitabs, nswaitrel;
  2441. DWORD mswaitrel;
  2442. EnterCriticalSection(&cv->threadIdSec);
  2443. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2444. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2445. tls->pthread_cond_helper_mutex;
  2446. cv->waitingthreadcount++;
  2447. LeaveCriticalSection(&cv->threadIdSec);
  2448. if (abstime) {
  2449. clock_gettime(CLOCK_REALTIME, &tsnow);
  2450. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2451. nswaitabs =
  2452. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2453. nswaitrel = nswaitabs - nsnow;
  2454. if (nswaitrel < 0) {
  2455. nswaitrel = 0;
  2456. }
  2457. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2458. } else {
  2459. mswaitrel = INFINITE;
  2460. }
  2461. pthread_mutex_unlock(mutex);
  2462. ok = (WAIT_OBJECT_0
  2463. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2464. pthread_mutex_lock(mutex);
  2465. return ok ? 0 : -1;
  2466. }
  2467. static int
  2468. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2469. {
  2470. return pthread_cond_timedwait(cv, mutex, NULL);
  2471. }
  2472. static int
  2473. pthread_cond_signal(pthread_cond_t *cv)
  2474. {
  2475. int i;
  2476. HANDLE wkup = NULL;
  2477. BOOL ok = FALSE;
  2478. EnterCriticalSection(&cv->threadIdSec);
  2479. if (cv->waitingthreadcount) {
  2480. wkup = cv->waitingthreadhdls[0];
  2481. ok = SetEvent(wkup);
  2482. for (i = 1; i < cv->waitingthreadcount; i++) {
  2483. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2484. }
  2485. cv->waitingthreadcount--;
  2486. assert(ok);
  2487. }
  2488. LeaveCriticalSection(&cv->threadIdSec);
  2489. return ok ? 0 : 1;
  2490. }
  2491. static int
  2492. pthread_cond_broadcast(pthread_cond_t *cv)
  2493. {
  2494. EnterCriticalSection(&cv->threadIdSec);
  2495. while (cv->waitingthreadcount) {
  2496. pthread_cond_signal(cv);
  2497. }
  2498. LeaveCriticalSection(&cv->threadIdSec);
  2499. return 0;
  2500. }
  2501. static int
  2502. pthread_cond_destroy(pthread_cond_t *cv)
  2503. {
  2504. EnterCriticalSection(&cv->threadIdSec);
  2505. assert(cv->waitingthreadcount == 0);
  2506. mg_free(cv->waitingthreadhdls);
  2507. cv->waitingthreadhdls = 0;
  2508. LeaveCriticalSection(&cv->threadIdSec);
  2509. DeleteCriticalSection(&cv->threadIdSec);
  2510. return 0;
  2511. }
  2512. #if defined(__MINGW32__)
  2513. /* Enable unused function warning again */
  2514. #pragma GCC diagnostic pop
  2515. #endif
  2516. /* For Windows, change all slashes to backslashes in path names. */
  2517. static void
  2518. change_slashes_to_backslashes(char *path)
  2519. {
  2520. int i;
  2521. for (i = 0; path[i] != '\0'; i++) {
  2522. if (path[i] == '/') {
  2523. path[i] = '\\';
  2524. }
  2525. /* remove double backslash (check i > 0 to preserve UNC paths,
  2526. * like \\server\file.txt) */
  2527. if ((path[i] == '\\') && (i > 0)) {
  2528. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2529. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2530. }
  2531. }
  2532. }
  2533. }
  2534. static int
  2535. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2536. {
  2537. int diff;
  2538. do {
  2539. diff = tolower(*s1) - tolower(*s2);
  2540. s1++;
  2541. s2++;
  2542. } while (diff == 0 && s1[-1] != '\0');
  2543. return diff;
  2544. }
  2545. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2546. * wbuf and wbuf_len is a target buffer and its length. */
  2547. static void
  2548. path_to_unicode(const struct mg_connection *conn,
  2549. const char *path,
  2550. wchar_t *wbuf,
  2551. size_t wbuf_len)
  2552. {
  2553. char buf[PATH_MAX], buf2[PATH_MAX];
  2554. wchar_t wbuf2[MAX_PATH + 1];
  2555. DWORD long_len, err;
  2556. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2557. mg_strlcpy(buf, path, sizeof(buf));
  2558. change_slashes_to_backslashes(buf);
  2559. /* Convert to Unicode and back. If doubly-converted string does not
  2560. * match the original, something is fishy, reject. */
  2561. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2562. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2563. WideCharToMultiByte(
  2564. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2565. if (strcmp(buf, buf2) != 0) {
  2566. wbuf[0] = L'\0';
  2567. }
  2568. /* TODO: Add a configuration to switch between case sensitive and
  2569. * case insensitive URIs for Windows server. */
  2570. /*
  2571. if (conn) {
  2572. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2573. fcompare = wcscmp;
  2574. }
  2575. }
  2576. */
  2577. (void)conn; /* conn is currently unused */
  2578. #if !defined(_WIN32_WCE)
  2579. /* Only accept a full file path, not a Windows short (8.3) path. */
  2580. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2581. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2582. if (long_len == 0) {
  2583. err = GetLastError();
  2584. if (err == ERROR_FILE_NOT_FOUND) {
  2585. /* File does not exist. This is not always a problem here. */
  2586. return;
  2587. }
  2588. }
  2589. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2590. /* Short name is used. */
  2591. wbuf[0] = L'\0';
  2592. }
  2593. #else
  2594. (void)long_len;
  2595. (void)wbuf2;
  2596. (void)err;
  2597. if (strchr(path, '~')) {
  2598. wbuf[0] = L'\0';
  2599. }
  2600. #endif
  2601. }
  2602. /* Windows happily opens files with some garbage at the end of file name.
  2603. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2604. * "a.cgi", despite one would expect an error back.
  2605. * This function returns non-0 if path ends with some garbage. */
  2606. static int
  2607. path_cannot_disclose_cgi(const char *path)
  2608. {
  2609. static const char *allowed_last_characters = "_-";
  2610. int last = path[strlen(path) - 1];
  2611. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2612. }
  2613. static int
  2614. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2615. {
  2616. wchar_t wbuf[PATH_MAX];
  2617. WIN32_FILE_ATTRIBUTE_DATA info;
  2618. time_t creation_time;
  2619. if (!filep) {
  2620. return 0;
  2621. }
  2622. memset(filep, 0, sizeof(*filep));
  2623. if (conn && is_file_in_memory(conn, path, filep)) {
  2624. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2625. * memset */
  2626. filep->last_modified = time(NULL);
  2627. /* last_modified = now ... assumes the file may change during runtime,
  2628. * so every mg_fopen call may return different data */
  2629. /* last_modified = conn->ctx.start_time;
  2630. * May be used it the data does not change during runtime. This allows
  2631. * browser caching. Since we do not know, we have to assume the file
  2632. * in memory may change. */
  2633. return 1;
  2634. }
  2635. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2636. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2637. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2638. filep->last_modified =
  2639. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2640. info.ftLastWriteTime.dwHighDateTime);
  2641. /* On Windows, the file creation time can be higher than the
  2642. * modification time, e.g. when a file is copied.
  2643. * Since the Last-Modified timestamp is used for caching
  2644. * it should be based on the most recent timestamp. */
  2645. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2646. info.ftCreationTime.dwHighDateTime);
  2647. if (creation_time > filep->last_modified) {
  2648. filep->last_modified = creation_time;
  2649. }
  2650. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2651. /* If file name is fishy, reset the file structure and return
  2652. * error.
  2653. * Note it is important to reset, not just return the error, cause
  2654. * functions like is_file_opened() check the struct. */
  2655. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2656. memset(filep, 0, sizeof(*filep));
  2657. return 0;
  2658. }
  2659. return 1;
  2660. }
  2661. return 0;
  2662. }
  2663. static int
  2664. mg_remove(const struct mg_connection *conn, const char *path)
  2665. {
  2666. wchar_t wbuf[PATH_MAX];
  2667. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2668. return DeleteFileW(wbuf) ? 0 : -1;
  2669. }
  2670. static int
  2671. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2672. {
  2673. wchar_t wbuf[PATH_MAX];
  2674. (void)mode;
  2675. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2676. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2677. }
  2678. /* Create substitutes for POSIX functions in Win32. */
  2679. #if defined(__MINGW32__)
  2680. /* Show no warning in case system functions are not used. */
  2681. #pragma GCC diagnostic push
  2682. #pragma GCC diagnostic ignored "-Wunused-function"
  2683. #endif
  2684. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2685. static DIR *
  2686. mg_opendir(const struct mg_connection *conn, const char *name)
  2687. {
  2688. DIR *dir = NULL;
  2689. wchar_t wpath[PATH_MAX];
  2690. DWORD attrs;
  2691. if (name == NULL) {
  2692. SetLastError(ERROR_BAD_ARGUMENTS);
  2693. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2694. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2695. } else {
  2696. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2697. attrs = GetFileAttributesW(wpath);
  2698. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2699. == FILE_ATTRIBUTE_DIRECTORY)) {
  2700. (void)wcscat(wpath, L"\\*");
  2701. dir->handle = FindFirstFileW(wpath, &dir->info);
  2702. dir->result.d_name[0] = '\0';
  2703. } else {
  2704. mg_free(dir);
  2705. dir = NULL;
  2706. }
  2707. }
  2708. return dir;
  2709. }
  2710. static int
  2711. mg_closedir(DIR *dir)
  2712. {
  2713. int result = 0;
  2714. if (dir != NULL) {
  2715. if (dir->handle != INVALID_HANDLE_VALUE)
  2716. result = FindClose(dir->handle) ? 0 : -1;
  2717. mg_free(dir);
  2718. } else {
  2719. result = -1;
  2720. SetLastError(ERROR_BAD_ARGUMENTS);
  2721. }
  2722. return result;
  2723. }
  2724. static struct dirent *
  2725. mg_readdir(DIR *dir)
  2726. {
  2727. struct dirent *result = 0;
  2728. if (dir) {
  2729. if (dir->handle != INVALID_HANDLE_VALUE) {
  2730. result = &dir->result;
  2731. (void)WideCharToMultiByte(CP_UTF8,
  2732. 0,
  2733. dir->info.cFileName,
  2734. -1,
  2735. result->d_name,
  2736. sizeof(result->d_name),
  2737. NULL,
  2738. NULL);
  2739. if (!FindNextFileW(dir->handle, &dir->info)) {
  2740. (void)FindClose(dir->handle);
  2741. dir->handle = INVALID_HANDLE_VALUE;
  2742. }
  2743. } else {
  2744. SetLastError(ERROR_FILE_NOT_FOUND);
  2745. }
  2746. } else {
  2747. SetLastError(ERROR_BAD_ARGUMENTS);
  2748. }
  2749. return result;
  2750. }
  2751. #ifndef HAVE_POLL
  2752. static int
  2753. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2754. {
  2755. struct timeval tv;
  2756. fd_set set;
  2757. unsigned int i;
  2758. int result;
  2759. SOCKET maxfd = 0;
  2760. memset(&tv, 0, sizeof(tv));
  2761. tv.tv_sec = milliseconds / 1000;
  2762. tv.tv_usec = (milliseconds % 1000) * 1000;
  2763. FD_ZERO(&set);
  2764. for (i = 0; i < n; i++) {
  2765. FD_SET((SOCKET)pfd[i].fd, &set);
  2766. pfd[i].revents = 0;
  2767. if (pfd[i].fd > maxfd) {
  2768. maxfd = pfd[i].fd;
  2769. }
  2770. }
  2771. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2772. for (i = 0; i < n; i++) {
  2773. if (FD_ISSET(pfd[i].fd, &set)) {
  2774. pfd[i].revents = POLLIN;
  2775. }
  2776. }
  2777. }
  2778. return result;
  2779. }
  2780. #endif /* HAVE_POLL */
  2781. #if defined(__MINGW32__)
  2782. /* Enable unused function warning again */
  2783. #pragma GCC diagnostic pop
  2784. #endif
  2785. static void
  2786. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2787. {
  2788. (void)conn; /* Unused. */
  2789. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2790. }
  2791. int
  2792. mg_start_thread(mg_thread_func_t f, void *p)
  2793. {
  2794. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2795. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2796. */
  2797. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2798. == ((uintptr_t)(-1L)))
  2799. ? -1
  2800. : 0);
  2801. #else
  2802. return (
  2803. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2804. ? -1
  2805. : 0);
  2806. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2807. }
  2808. /* Start a thread storing the thread context. */
  2809. static int
  2810. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2811. void *p,
  2812. pthread_t *threadidptr)
  2813. {
  2814. uintptr_t uip;
  2815. HANDLE threadhandle;
  2816. int result = -1;
  2817. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2818. threadhandle = (HANDLE)uip;
  2819. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2820. *threadidptr = threadhandle;
  2821. result = 0;
  2822. }
  2823. return result;
  2824. }
  2825. /* Wait for a thread to finish. */
  2826. static int
  2827. mg_join_thread(pthread_t threadid)
  2828. {
  2829. int result;
  2830. DWORD dwevent;
  2831. result = -1;
  2832. dwevent = WaitForSingleObject(threadid, INFINITE);
  2833. if (dwevent == WAIT_FAILED) {
  2834. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2835. } else {
  2836. if (dwevent == WAIT_OBJECT_0) {
  2837. CloseHandle(threadid);
  2838. result = 0;
  2839. }
  2840. }
  2841. return result;
  2842. }
  2843. #if !defined(NO_SSL_DL)
  2844. /* Create substitutes for POSIX functions in Win32. */
  2845. #if defined(__MINGW32__)
  2846. /* Show no warning in case system functions are not used. */
  2847. #pragma GCC diagnostic push
  2848. #pragma GCC diagnostic ignored "-Wunused-function"
  2849. #endif
  2850. static HANDLE
  2851. dlopen(const char *dll_name, int flags)
  2852. {
  2853. wchar_t wbuf[PATH_MAX];
  2854. (void)flags;
  2855. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  2856. return LoadLibraryW(wbuf);
  2857. }
  2858. static int
  2859. dlclose(void *handle)
  2860. {
  2861. int result;
  2862. if (FreeLibrary((HMODULE)handle) != 0) {
  2863. result = 0;
  2864. } else {
  2865. result = -1;
  2866. }
  2867. return result;
  2868. }
  2869. #if defined(__MINGW32__)
  2870. /* Enable unused function warning again */
  2871. #pragma GCC diagnostic pop
  2872. #endif
  2873. #endif
  2874. #if !defined(NO_CGI)
  2875. #define SIGKILL (0)
  2876. static int
  2877. kill(pid_t pid, int sig_num)
  2878. {
  2879. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2880. (void)CloseHandle((HANDLE)pid);
  2881. return 0;
  2882. }
  2883. static void
  2884. trim_trailing_whitespaces(char *s)
  2885. {
  2886. char *e = s + strlen(s) - 1;
  2887. while (e > s && isspace(*(unsigned char *)e)) {
  2888. *e-- = '\0';
  2889. }
  2890. }
  2891. static pid_t
  2892. spawn_process(struct mg_connection *conn,
  2893. const char *prog,
  2894. char *envblk,
  2895. char *envp[],
  2896. int fdin[2],
  2897. int fdout[2],
  2898. int fderr[2],
  2899. const char *dir)
  2900. {
  2901. HANDLE me;
  2902. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2903. cmdline[PATH_MAX], buf[PATH_MAX];
  2904. int truncated;
  2905. struct file file = STRUCT_FILE_INITIALIZER;
  2906. STARTUPINFOA si;
  2907. PROCESS_INFORMATION pi = {0};
  2908. (void)envp;
  2909. memset(&si, 0, sizeof(si));
  2910. si.cb = sizeof(si);
  2911. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2912. si.wShowWindow = SW_HIDE;
  2913. me = GetCurrentProcess();
  2914. DuplicateHandle(me,
  2915. (HANDLE)_get_osfhandle(fdin[0]),
  2916. me,
  2917. &si.hStdInput,
  2918. 0,
  2919. TRUE,
  2920. DUPLICATE_SAME_ACCESS);
  2921. DuplicateHandle(me,
  2922. (HANDLE)_get_osfhandle(fdout[1]),
  2923. me,
  2924. &si.hStdOutput,
  2925. 0,
  2926. TRUE,
  2927. DUPLICATE_SAME_ACCESS);
  2928. DuplicateHandle(me,
  2929. (HANDLE)_get_osfhandle(fderr[1]),
  2930. me,
  2931. &si.hStdError,
  2932. 0,
  2933. TRUE,
  2934. DUPLICATE_SAME_ACCESS);
  2935. /* Mark handles that should not be inherited. See
  2936. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  2937. */
  2938. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  2939. HANDLE_FLAG_INHERIT,
  2940. 0);
  2941. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  2942. HANDLE_FLAG_INHERIT,
  2943. 0);
  2944. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  2945. HANDLE_FLAG_INHERIT,
  2946. 0);
  2947. /* If CGI file is a script, try to read the interpreter line */
  2948. interp = conn->ctx->config[CGI_INTERPRETER];
  2949. if (interp == NULL) {
  2950. buf[0] = buf[1] = '\0';
  2951. /* Read the first line of the script into the buffer */
  2952. mg_snprintf(
  2953. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2954. if (truncated) {
  2955. pi.hProcess = (pid_t)-1;
  2956. goto spawn_cleanup;
  2957. }
  2958. if (mg_fopen(conn, cmdline, "r", &file)) {
  2959. p = (char *)file.membuf;
  2960. mg_fgets(buf, sizeof(buf), &file, &p);
  2961. mg_fclose(&file);
  2962. buf[sizeof(buf) - 1] = '\0';
  2963. }
  2964. if (buf[0] == '#' && buf[1] == '!') {
  2965. trim_trailing_whitespaces(buf + 2);
  2966. } else {
  2967. buf[2] = '\0';
  2968. }
  2969. interp = buf + 2;
  2970. }
  2971. if (interp[0] != '\0') {
  2972. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2973. interp = full_interp;
  2974. }
  2975. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2976. if (interp[0] != '\0') {
  2977. mg_snprintf(conn,
  2978. &truncated,
  2979. cmdline,
  2980. sizeof(cmdline),
  2981. "\"%s\" \"%s\\%s\"",
  2982. interp,
  2983. full_dir,
  2984. prog);
  2985. } else {
  2986. mg_snprintf(conn,
  2987. &truncated,
  2988. cmdline,
  2989. sizeof(cmdline),
  2990. "\"%s\\%s\"",
  2991. full_dir,
  2992. prog);
  2993. }
  2994. if (truncated) {
  2995. pi.hProcess = (pid_t)-1;
  2996. goto spawn_cleanup;
  2997. }
  2998. DEBUG_TRACE("Running [%s]", cmdline);
  2999. if (CreateProcessA(NULL,
  3000. cmdline,
  3001. NULL,
  3002. NULL,
  3003. TRUE,
  3004. CREATE_NEW_PROCESS_GROUP,
  3005. envblk,
  3006. NULL,
  3007. &si,
  3008. &pi) == 0) {
  3009. mg_cry(
  3010. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3011. pi.hProcess = (pid_t)-1;
  3012. /* goto spawn_cleanup; */
  3013. }
  3014. spawn_cleanup:
  3015. (void)CloseHandle(si.hStdOutput);
  3016. (void)CloseHandle(si.hStdError);
  3017. (void)CloseHandle(si.hStdInput);
  3018. if (pi.hThread != NULL) {
  3019. (void)CloseHandle(pi.hThread);
  3020. }
  3021. return (pid_t)pi.hProcess;
  3022. }
  3023. #endif /* !NO_CGI */
  3024. static int
  3025. set_non_blocking_mode(SOCKET sock)
  3026. {
  3027. unsigned long on = 1;
  3028. return ioctlsocket(sock, (long)FIONBIO, &on);
  3029. }
  3030. #else
  3031. static int
  3032. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3033. {
  3034. struct stat st;
  3035. if (!filep) {
  3036. return 0;
  3037. }
  3038. memset(filep, 0, sizeof(*filep));
  3039. if (conn && is_file_in_memory(conn, path, filep)) {
  3040. return 1;
  3041. }
  3042. if (0 == stat(path, &st)) {
  3043. filep->size = (uint64_t)(st.st_size);
  3044. filep->last_modified = st.st_mtime;
  3045. filep->is_directory = S_ISDIR(st.st_mode);
  3046. return 1;
  3047. }
  3048. return 0;
  3049. }
  3050. static void
  3051. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3052. {
  3053. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3054. if (conn) {
  3055. mg_cry(conn,
  3056. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3057. __func__,
  3058. strerror(ERRNO));
  3059. }
  3060. }
  3061. }
  3062. int
  3063. mg_start_thread(mg_thread_func_t func, void *param)
  3064. {
  3065. pthread_t thread_id;
  3066. pthread_attr_t attr;
  3067. int result;
  3068. (void)pthread_attr_init(&attr);
  3069. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3070. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3071. /* Compile-time option to control stack size,
  3072. * e.g. -DUSE_STACK_SIZE=16384 */
  3073. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3074. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3075. result = pthread_create(&thread_id, &attr, func, param);
  3076. pthread_attr_destroy(&attr);
  3077. return result;
  3078. }
  3079. /* Start a thread storing the thread context. */
  3080. static int
  3081. mg_start_thread_with_id(mg_thread_func_t func,
  3082. void *param,
  3083. pthread_t *threadidptr)
  3084. {
  3085. pthread_t thread_id;
  3086. pthread_attr_t attr;
  3087. int result;
  3088. (void)pthread_attr_init(&attr);
  3089. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3090. /* Compile-time option to control stack size,
  3091. * e.g. -DUSE_STACK_SIZE=16384 */
  3092. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3093. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3094. result = pthread_create(&thread_id, &attr, func, param);
  3095. pthread_attr_destroy(&attr);
  3096. if ((result == 0) && (threadidptr != NULL)) {
  3097. *threadidptr = thread_id;
  3098. }
  3099. return result;
  3100. }
  3101. /* Wait for a thread to finish. */
  3102. static int
  3103. mg_join_thread(pthread_t threadid)
  3104. {
  3105. int result;
  3106. result = pthread_join(threadid, NULL);
  3107. return result;
  3108. }
  3109. #ifndef NO_CGI
  3110. static pid_t
  3111. spawn_process(struct mg_connection *conn,
  3112. const char *prog,
  3113. char *envblk,
  3114. char *envp[],
  3115. int fdin[2],
  3116. int fdout[2],
  3117. int fderr[2],
  3118. const char *dir)
  3119. {
  3120. pid_t pid;
  3121. const char *interp;
  3122. (void)envblk;
  3123. if (conn == NULL) {
  3124. return 0;
  3125. }
  3126. if ((pid = fork()) == -1) {
  3127. /* Parent */
  3128. send_http_error(conn,
  3129. 500,
  3130. "Error: Creating CGI process\nfork(): %s",
  3131. strerror(ERRNO));
  3132. } else if (pid == 0) {
  3133. /* Child */
  3134. if (chdir(dir) != 0) {
  3135. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3136. } else if (dup2(fdin[0], 0) == -1) {
  3137. mg_cry(conn,
  3138. "%s: dup2(%d, 0): %s",
  3139. __func__,
  3140. fdin[0],
  3141. strerror(ERRNO));
  3142. } else if (dup2(fdout[1], 1) == -1) {
  3143. mg_cry(conn,
  3144. "%s: dup2(%d, 1): %s",
  3145. __func__,
  3146. fdout[1],
  3147. strerror(ERRNO));
  3148. } else if (dup2(fderr[1], 2) == -1) {
  3149. mg_cry(conn,
  3150. "%s: dup2(%d, 2): %s",
  3151. __func__,
  3152. fderr[1],
  3153. strerror(ERRNO));
  3154. } else {
  3155. /* Keep stderr and stdout in two different pipes.
  3156. * Stdout will be sent back to the client,
  3157. * stderr should go into a server error log. */
  3158. (void)close(fdin[0]);
  3159. (void)close(fdout[1]);
  3160. (void)close(fderr[1]);
  3161. /* Close write end fdin and read end fdout and fderr */
  3162. (void)close(fdin[1]);
  3163. (void)close(fdout[0]);
  3164. (void)close(fderr[0]);
  3165. /* After exec, all signal handlers are restored to their default
  3166. * values, with one exception of SIGCHLD. According to
  3167. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3168. * leave unchanged after exec if it was set to be ignored. Restore
  3169. * it to default action. */
  3170. signal(SIGCHLD, SIG_DFL);
  3171. interp = conn->ctx->config[CGI_INTERPRETER];
  3172. if (interp == NULL) {
  3173. (void)execle(prog, prog, NULL, envp);
  3174. mg_cry(conn,
  3175. "%s: execle(%s): %s",
  3176. __func__,
  3177. prog,
  3178. strerror(ERRNO));
  3179. } else {
  3180. (void)execle(interp, interp, prog, NULL, envp);
  3181. mg_cry(conn,
  3182. "%s: execle(%s %s): %s",
  3183. __func__,
  3184. interp,
  3185. prog,
  3186. strerror(ERRNO));
  3187. }
  3188. }
  3189. exit(EXIT_FAILURE);
  3190. }
  3191. return pid;
  3192. }
  3193. #endif /* !NO_CGI */
  3194. static int
  3195. set_non_blocking_mode(SOCKET sock)
  3196. {
  3197. int flags;
  3198. flags = fcntl(sock, F_GETFL, 0);
  3199. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3200. return 0;
  3201. }
  3202. #endif /* _WIN32 */
  3203. /* End of initial operating system specific define block. */
  3204. /* Get a random number (independent of C rand function) */
  3205. static uint64_t
  3206. get_random(void)
  3207. {
  3208. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3209. static uint64_t lcg = 0; /* Linear congruential generator */
  3210. struct timespec now;
  3211. memset(&now, 0, sizeof(now));
  3212. clock_gettime(CLOCK_MONOTONIC, &now);
  3213. if (lfsr == 0) {
  3214. /* lfsr will be only 0 if has not been initialized,
  3215. * so this code is called only once. */
  3216. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3217. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3218. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3219. + (uint64_t)(ptrdiff_t)&now;
  3220. } else {
  3221. /* Get the next step of both random number generators. */
  3222. lfsr = (lfsr >> 1)
  3223. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3224. << 63);
  3225. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3226. }
  3227. /* Combining two pseudo-random number generators and a high resolution part
  3228. * of the current server time will make it hard (impossible?) to guess the
  3229. * next number. */
  3230. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3231. }
  3232. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3233. * descriptor. Return number of bytes written. */
  3234. static int
  3235. push(struct mg_context *ctx,
  3236. FILE *fp,
  3237. SOCKET sock,
  3238. SSL *ssl,
  3239. const char *buf,
  3240. int len,
  3241. double timeout)
  3242. {
  3243. struct timespec start, now;
  3244. int n, err;
  3245. #ifdef _WIN32
  3246. typedef int len_t;
  3247. #else
  3248. typedef size_t len_t;
  3249. #endif
  3250. if (timeout > 0) {
  3251. memset(&start, 0, sizeof(start));
  3252. memset(&now, 0, sizeof(now));
  3253. clock_gettime(CLOCK_MONOTONIC, &start);
  3254. }
  3255. if (ctx == NULL) {
  3256. return -1;
  3257. }
  3258. #ifdef NO_SSL
  3259. if (ssl) {
  3260. return -1;
  3261. }
  3262. #endif
  3263. do {
  3264. #ifndef NO_SSL
  3265. if (ssl != NULL) {
  3266. n = SSL_write(ssl, buf, len);
  3267. if (n <= 0) {
  3268. err = SSL_get_error(ssl, n);
  3269. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  3270. err = ERRNO;
  3271. } else {
  3272. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3273. return -1;
  3274. }
  3275. } else {
  3276. err = 0;
  3277. }
  3278. } else
  3279. #endif
  3280. if (fp != NULL) {
  3281. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3282. if (ferror(fp)) {
  3283. n = -1;
  3284. err = ERRNO;
  3285. } else {
  3286. err = 0;
  3287. }
  3288. } else {
  3289. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3290. err = (n < 0) ? ERRNO : 0;
  3291. }
  3292. if (ctx->stop_flag) {
  3293. return -1;
  3294. }
  3295. if ((n > 0) || (n == 0 && len == 0)) {
  3296. /* some data has been read, or no data was requested */
  3297. return n;
  3298. }
  3299. if (n == 0) {
  3300. /* shutdown of the socket at client side */
  3301. return -1;
  3302. }
  3303. if (n < 0) {
  3304. /* socket error - check errno */
  3305. DEBUG_TRACE("send() failed, error %d", err);
  3306. /* TODO: error handling depending on the error code.
  3307. * These codes are different between Windows and Linux.
  3308. */
  3309. return -1;
  3310. }
  3311. /* This code is not reached in the moment.
  3312. * ==> Fix the TODOs above first. */
  3313. if (timeout > 0) {
  3314. clock_gettime(CLOCK_MONOTONIC, &now);
  3315. }
  3316. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3317. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3318. used */
  3319. return -1;
  3320. }
  3321. static int64_t
  3322. push_all(struct mg_context *ctx,
  3323. FILE *fp,
  3324. SOCKET sock,
  3325. SSL *ssl,
  3326. const char *buf,
  3327. int64_t len)
  3328. {
  3329. double timeout = -1.0;
  3330. int64_t n, nwritten = 0;
  3331. if (ctx == NULL) {
  3332. return -1;
  3333. }
  3334. if (ctx->config[REQUEST_TIMEOUT]) {
  3335. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3336. }
  3337. while (len > 0 && ctx->stop_flag == 0) {
  3338. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3339. if (n < 0) {
  3340. if (nwritten == 0) {
  3341. nwritten = n; /* Propagate the error */
  3342. }
  3343. break;
  3344. } else if (n == 0) {
  3345. break; /* No more data to write */
  3346. } else {
  3347. nwritten += n;
  3348. len -= n;
  3349. }
  3350. }
  3351. return nwritten;
  3352. }
  3353. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3354. * Return negative value on error, or number of bytes read on success. */
  3355. static int
  3356. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3357. {
  3358. int nread, err;
  3359. struct timespec start, now;
  3360. #ifdef _WIN32
  3361. typedef int len_t;
  3362. #else
  3363. typedef size_t len_t;
  3364. #endif
  3365. if (timeout > 0) {
  3366. memset(&start, 0, sizeof(start));
  3367. memset(&now, 0, sizeof(now));
  3368. clock_gettime(CLOCK_MONOTONIC, &start);
  3369. }
  3370. do {
  3371. if (fp != NULL) {
  3372. #if !defined(_WIN32_WCE)
  3373. /* Use read() instead of fread(), because if we're reading from the
  3374. * CGI pipe, fread() may block until IO buffer is filled up. We
  3375. * cannot afford to block and must pass all read bytes immediately
  3376. * to the client. */
  3377. nread = (int)read(fileno(fp), buf, (size_t)len);
  3378. #else
  3379. /* WinCE does not support CGI pipes */
  3380. nread = (int)fread(buf, 1, (size_t)len, fp);
  3381. #endif
  3382. err = (nread < 0) ? ERRNO : 0;
  3383. #ifndef NO_SSL
  3384. } else if (conn->ssl != NULL) {
  3385. nread = SSL_read(conn->ssl, buf, len);
  3386. if (nread <= 0) {
  3387. err = SSL_get_error(conn->ssl, nread);
  3388. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3389. err = ERRNO;
  3390. } else {
  3391. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3392. return -1;
  3393. }
  3394. } else {
  3395. err = 0;
  3396. }
  3397. #endif
  3398. } else {
  3399. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3400. err = (nread < 0) ? ERRNO : 0;
  3401. }
  3402. if (conn->ctx->stop_flag) {
  3403. return -1;
  3404. }
  3405. if ((nread > 0) || (nread == 0 && len == 0)) {
  3406. /* some data has been read, or no data was requested */
  3407. return nread;
  3408. }
  3409. if (nread == 0) {
  3410. /* shutdown of the socket at client side */
  3411. return -1;
  3412. }
  3413. if (nread < 0) {
  3414. /* socket error - check errno */
  3415. #ifdef _WIN32
  3416. if (err == WSAEWOULDBLOCK) {
  3417. /* standard case if called from close_socket_gracefully */
  3418. return -1;
  3419. } else if (err == WSAETIMEDOUT) {
  3420. /* timeout is handled by the while loop */
  3421. } else {
  3422. DEBUG_TRACE("recv() failed, error %d", err);
  3423. return -1;
  3424. }
  3425. #else
  3426. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3427. * if the timeout is reached and if the socket was set to non-
  3428. * blocking in close_socket_gracefully, so we can not distinguish
  3429. * here. We have to wait for the timeout in both cases for now.
  3430. */
  3431. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3432. /* EAGAIN/EWOULDBLOCK:
  3433. * standard case if called from close_socket_gracefully
  3434. * => should return -1 */
  3435. /* or timeout occured
  3436. * => the code must stay in the while loop */
  3437. /* EINTR can be generated on a socket with a timeout set even
  3438. * when SA_RESTART is effective for all relevant signals
  3439. * (see signal(7)).
  3440. * => stay in the while loop */
  3441. } else {
  3442. DEBUG_TRACE("recv() failed, error %d", err);
  3443. return -1;
  3444. }
  3445. #endif
  3446. }
  3447. if (timeout > 0) {
  3448. clock_gettime(CLOCK_MONOTONIC, &now);
  3449. }
  3450. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3451. /* Timeout occured, but no data available. */
  3452. return -1;
  3453. }
  3454. static int
  3455. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3456. {
  3457. int n, nread = 0;
  3458. double timeout = -1.0;
  3459. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3460. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3461. }
  3462. while (len > 0 && conn->ctx->stop_flag == 0) {
  3463. n = pull(fp, conn, buf + nread, len, timeout);
  3464. if (n < 0) {
  3465. if (nread == 0) {
  3466. nread = n; /* Propagate the error */
  3467. }
  3468. break;
  3469. } else if (n == 0) {
  3470. break; /* No more data to read */
  3471. } else {
  3472. conn->consumed_content += n;
  3473. nread += n;
  3474. len -= n;
  3475. }
  3476. }
  3477. return nread;
  3478. }
  3479. static void
  3480. discard_unread_request_data(struct mg_connection *conn)
  3481. {
  3482. char buf[MG_BUF_LEN];
  3483. size_t to_read;
  3484. int nread;
  3485. if (conn == NULL) {
  3486. return;
  3487. }
  3488. to_read = sizeof(buf);
  3489. if (conn->is_chunked) {
  3490. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3491. * completely */
  3492. while (conn->is_chunked == 1) {
  3493. nread = mg_read(conn, buf, to_read);
  3494. if (nread <= 0) {
  3495. break;
  3496. }
  3497. }
  3498. } else {
  3499. /* Not chunked: content length is known */
  3500. while (conn->consumed_content < conn->content_len) {
  3501. if (to_read
  3502. > (size_t)(conn->content_len - conn->consumed_content)) {
  3503. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3504. }
  3505. nread = mg_read(conn, buf, to_read);
  3506. if (nread <= 0) {
  3507. break;
  3508. }
  3509. }
  3510. }
  3511. }
  3512. static int
  3513. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3514. {
  3515. int64_t n, buffered_len, nread;
  3516. int64_t len64 =
  3517. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3518. * int, we may not read more
  3519. * bytes */
  3520. const char *body;
  3521. if (conn == NULL) {
  3522. return 0;
  3523. }
  3524. /* If Content-Length is not set for a PUT or POST request, read until
  3525. * socket is closed */
  3526. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3527. conn->content_len = INT64_MAX;
  3528. conn->must_close = 1;
  3529. }
  3530. nread = 0;
  3531. if (conn->consumed_content < conn->content_len) {
  3532. /* Adjust number of bytes to read. */
  3533. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3534. if (left_to_read < len64) {
  3535. /* Do not read more than the total content length of the request.
  3536. */
  3537. len64 = left_to_read;
  3538. }
  3539. /* Return buffered data */
  3540. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3541. - conn->consumed_content;
  3542. if (buffered_len > 0) {
  3543. if (len64 < buffered_len) {
  3544. buffered_len = len64;
  3545. }
  3546. body = conn->buf + conn->request_len + conn->consumed_content;
  3547. memcpy(buf, body, (size_t)buffered_len);
  3548. len64 -= buffered_len;
  3549. conn->consumed_content += buffered_len;
  3550. nread += buffered_len;
  3551. buf = (char *)buf + buffered_len;
  3552. }
  3553. /* We have returned all buffered data. Read new data from the remote
  3554. * socket.
  3555. */
  3556. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3557. nread += n;
  3558. } else {
  3559. nread = (nread > 0 ? nread : n);
  3560. }
  3561. }
  3562. return (int)nread;
  3563. }
  3564. static char
  3565. mg_getc(struct mg_connection *conn)
  3566. {
  3567. char c;
  3568. if (conn == NULL) {
  3569. return 0;
  3570. }
  3571. conn->content_len++;
  3572. if (mg_read_inner(conn, &c, 1) <= 0) {
  3573. return (char)0;
  3574. }
  3575. return c;
  3576. }
  3577. int
  3578. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3579. {
  3580. if (len > INT_MAX) {
  3581. len = INT_MAX;
  3582. }
  3583. if (conn == NULL) {
  3584. return 0;
  3585. }
  3586. if (conn->is_chunked) {
  3587. size_t all_read = 0;
  3588. while (len > 0) {
  3589. if (conn->is_chunked == 2) {
  3590. /* No more data left to read */
  3591. return 0;
  3592. }
  3593. if (conn->chunk_remainder) {
  3594. /* copy from the remainder of the last received chunk */
  3595. long read_ret;
  3596. size_t read_now =
  3597. ((conn->chunk_remainder > len) ? (len)
  3598. : (conn->chunk_remainder));
  3599. conn->content_len += (int)read_now;
  3600. read_ret =
  3601. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3602. all_read += (size_t)read_ret;
  3603. conn->chunk_remainder -= read_now;
  3604. len -= read_now;
  3605. if (conn->chunk_remainder == 0) {
  3606. /* the rest of the data in the current chunk has been read
  3607. */
  3608. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3609. /* Protocol violation */
  3610. return -1;
  3611. }
  3612. }
  3613. } else {
  3614. /* fetch a new chunk */
  3615. int i = 0;
  3616. char lenbuf[64];
  3617. char *end = 0;
  3618. unsigned long chunkSize = 0;
  3619. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3620. lenbuf[i] = mg_getc(conn);
  3621. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3622. continue;
  3623. }
  3624. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3625. lenbuf[i + 1] = 0;
  3626. chunkSize = strtoul(lenbuf, &end, 16);
  3627. if (chunkSize == 0) {
  3628. /* regular end of content */
  3629. conn->is_chunked = 2;
  3630. }
  3631. break;
  3632. }
  3633. if (!isalnum(lenbuf[i])) {
  3634. /* illegal character for chunk length */
  3635. return -1;
  3636. }
  3637. }
  3638. if ((end == NULL) || (*end != '\r')) {
  3639. /* chunksize not set correctly */
  3640. return -1;
  3641. }
  3642. if (chunkSize == 0) {
  3643. break;
  3644. }
  3645. conn->chunk_remainder = chunkSize;
  3646. }
  3647. }
  3648. return (int)all_read;
  3649. }
  3650. return mg_read_inner(conn, buf, len);
  3651. }
  3652. int
  3653. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3654. {
  3655. time_t now;
  3656. int64_t n, total, allowed;
  3657. if (conn == NULL) {
  3658. return 0;
  3659. }
  3660. if (conn->throttle > 0) {
  3661. if ((now = time(NULL)) != conn->last_throttle_time) {
  3662. conn->last_throttle_time = now;
  3663. conn->last_throttle_bytes = 0;
  3664. }
  3665. allowed = conn->throttle - conn->last_throttle_bytes;
  3666. if (allowed > (int64_t)len) {
  3667. allowed = (int64_t)len;
  3668. }
  3669. if ((total = push_all(conn->ctx,
  3670. NULL,
  3671. conn->client.sock,
  3672. conn->ssl,
  3673. (const char *)buf,
  3674. (int64_t)allowed)) == allowed) {
  3675. buf = (const char *)buf + total;
  3676. conn->last_throttle_bytes += total;
  3677. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3678. allowed = conn->throttle > (int64_t)len - total
  3679. ? (int64_t)len - total
  3680. : conn->throttle;
  3681. if ((n = push_all(conn->ctx,
  3682. NULL,
  3683. conn->client.sock,
  3684. conn->ssl,
  3685. (const char *)buf,
  3686. (int64_t)allowed)) != allowed) {
  3687. break;
  3688. }
  3689. sleep(1);
  3690. conn->last_throttle_bytes = allowed;
  3691. conn->last_throttle_time = time(NULL);
  3692. buf = (const char *)buf + n;
  3693. total += n;
  3694. }
  3695. }
  3696. } else {
  3697. total = push_all(conn->ctx,
  3698. NULL,
  3699. conn->client.sock,
  3700. conn->ssl,
  3701. (const char *)buf,
  3702. (int64_t)len);
  3703. }
  3704. return (int)total;
  3705. }
  3706. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3707. static int
  3708. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3709. {
  3710. va_list ap_copy;
  3711. size_t size = MG_BUF_LEN / 4;
  3712. int len = -1;
  3713. *buf = NULL;
  3714. while (len < 0) {
  3715. if (*buf) {
  3716. mg_free(*buf);
  3717. }
  3718. size *= 4;
  3719. *buf = (char *)mg_malloc(size);
  3720. if (!*buf) {
  3721. break;
  3722. }
  3723. va_copy(ap_copy, ap);
  3724. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3725. va_end(ap_copy);
  3726. (*buf)[size - 1] = 0;
  3727. }
  3728. return len;
  3729. }
  3730. /* Print message to buffer. If buffer is large enough to hold the message,
  3731. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3732. * and return allocated buffer. */
  3733. static int
  3734. alloc_vprintf(char **out_buf,
  3735. char *prealloc_buf,
  3736. size_t prealloc_size,
  3737. const char *fmt,
  3738. va_list ap)
  3739. {
  3740. va_list ap_copy;
  3741. int len;
  3742. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3743. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3744. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3745. * Therefore, we make two passes: on first pass, get required message
  3746. * length.
  3747. * On second pass, actually print the message. */
  3748. va_copy(ap_copy, ap);
  3749. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3750. va_end(ap_copy);
  3751. if (len < 0) {
  3752. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3753. * Switch to alternative code path that uses incremental allocations.
  3754. */
  3755. va_copy(ap_copy, ap);
  3756. len = alloc_vprintf2(out_buf, fmt, ap);
  3757. va_end(ap_copy);
  3758. } else if ((size_t)(len) >= prealloc_size) {
  3759. /* The pre-allocated buffer not large enough. */
  3760. /* Allocate a new buffer. */
  3761. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3762. if (!*out_buf) {
  3763. /* Allocation failed. Return -1 as "out of memory" error. */
  3764. return -1;
  3765. }
  3766. /* Buffer allocation successful. Store the string there. */
  3767. va_copy(ap_copy, ap);
  3768. IGNORE_UNUSED_RESULT(
  3769. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3770. va_end(ap_copy);
  3771. } else {
  3772. /* The pre-allocated buffer is large enough.
  3773. * Use it to store the string and return the address. */
  3774. va_copy(ap_copy, ap);
  3775. IGNORE_UNUSED_RESULT(
  3776. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3777. va_end(ap_copy);
  3778. *out_buf = prealloc_buf;
  3779. }
  3780. return len;
  3781. }
  3782. static int
  3783. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3784. {
  3785. char mem[MG_BUF_LEN];
  3786. char *buf = NULL;
  3787. int len;
  3788. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3789. len = mg_write(conn, buf, (size_t)len);
  3790. }
  3791. if (buf != mem && buf != NULL) {
  3792. mg_free(buf);
  3793. }
  3794. return len;
  3795. }
  3796. int
  3797. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3798. {
  3799. va_list ap;
  3800. int result;
  3801. va_start(ap, fmt);
  3802. result = mg_vprintf(conn, fmt, ap);
  3803. va_end(ap);
  3804. return result;
  3805. }
  3806. int
  3807. mg_url_decode(const char *src,
  3808. int src_len,
  3809. char *dst,
  3810. int dst_len,
  3811. int is_form_url_encoded)
  3812. {
  3813. int i, j, a, b;
  3814. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3815. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3816. if (i < src_len - 2 && src[i] == '%'
  3817. && isxdigit(*(const unsigned char *)(src + i + 1))
  3818. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3819. a = tolower(*(const unsigned char *)(src + i + 1));
  3820. b = tolower(*(const unsigned char *)(src + i + 2));
  3821. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3822. i += 2;
  3823. } else if (is_form_url_encoded && src[i] == '+') {
  3824. dst[j] = ' ';
  3825. } else {
  3826. dst[j] = src[i];
  3827. }
  3828. }
  3829. dst[j] = '\0'; /* Null-terminate the destination */
  3830. return i >= src_len ? j : -1;
  3831. }
  3832. int
  3833. mg_get_var(const char *data,
  3834. size_t data_len,
  3835. const char *name,
  3836. char *dst,
  3837. size_t dst_len)
  3838. {
  3839. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3840. }
  3841. int
  3842. mg_get_var2(const char *data,
  3843. size_t data_len,
  3844. const char *name,
  3845. char *dst,
  3846. size_t dst_len,
  3847. size_t occurrence)
  3848. {
  3849. const char *p, *e, *s;
  3850. size_t name_len;
  3851. int len;
  3852. if (dst == NULL || dst_len == 0) {
  3853. len = -2;
  3854. } else if (data == NULL || name == NULL || data_len == 0) {
  3855. len = -1;
  3856. dst[0] = '\0';
  3857. } else {
  3858. name_len = strlen(name);
  3859. e = data + data_len;
  3860. len = -1;
  3861. dst[0] = '\0';
  3862. /* data is "var1=val1&var2=val2...". Find variable first */
  3863. for (p = data; p + name_len < e; p++) {
  3864. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3865. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3866. /* Point p to variable value */
  3867. p += name_len + 1;
  3868. /* Point s to the end of the value */
  3869. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3870. if (s == NULL) {
  3871. s = e;
  3872. }
  3873. /* assert(s >= p); */
  3874. if (s < p) {
  3875. return -3;
  3876. }
  3877. /* Decode variable into destination buffer */
  3878. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3879. /* Redirect error code from -1 to -2 (destination buffer too
  3880. * small). */
  3881. if (len == -1) {
  3882. len = -2;
  3883. }
  3884. break;
  3885. }
  3886. }
  3887. }
  3888. return len;
  3889. }
  3890. int
  3891. mg_get_cookie(const char *cookie_header,
  3892. const char *var_name,
  3893. char *dst,
  3894. size_t dst_size)
  3895. {
  3896. const char *s, *p, *end;
  3897. int name_len, len = -1;
  3898. if (dst == NULL || dst_size == 0) {
  3899. len = -2;
  3900. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3901. len = -1;
  3902. dst[0] = '\0';
  3903. } else {
  3904. name_len = (int)strlen(var_name);
  3905. end = s + strlen(s);
  3906. dst[0] = '\0';
  3907. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3908. if (s[name_len] == '=') {
  3909. s += name_len + 1;
  3910. if ((p = strchr(s, ' ')) == NULL) {
  3911. p = end;
  3912. }
  3913. if (p[-1] == ';') {
  3914. p--;
  3915. }
  3916. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3917. s++;
  3918. p--;
  3919. }
  3920. if ((size_t)(p - s) < dst_size) {
  3921. len = (int)(p - s);
  3922. mg_strlcpy(dst, s, (size_t)len + 1);
  3923. } else {
  3924. len = -3;
  3925. }
  3926. break;
  3927. }
  3928. }
  3929. }
  3930. return len;
  3931. }
  3932. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3933. static void
  3934. base64_encode(const unsigned char *src, int src_len, char *dst)
  3935. {
  3936. static const char *b64 =
  3937. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3938. int i, j, a, b, c;
  3939. for (i = j = 0; i < src_len; i += 3) {
  3940. a = src[i];
  3941. b = i + 1 >= src_len ? 0 : src[i + 1];
  3942. c = i + 2 >= src_len ? 0 : src[i + 2];
  3943. dst[j++] = b64[a >> 2];
  3944. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3945. if (i + 1 < src_len) {
  3946. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3947. }
  3948. if (i + 2 < src_len) {
  3949. dst[j++] = b64[c & 63];
  3950. }
  3951. }
  3952. while (j % 4 != 0) {
  3953. dst[j++] = '=';
  3954. }
  3955. dst[j++] = '\0';
  3956. }
  3957. #endif
  3958. #if defined(USE_LUA)
  3959. static unsigned char
  3960. b64reverse(char letter)
  3961. {
  3962. if (letter >= 'A' && letter <= 'Z') {
  3963. return letter - 'A';
  3964. }
  3965. if (letter >= 'a' && letter <= 'z') {
  3966. return letter - 'a' + 26;
  3967. }
  3968. if (letter >= '0' && letter <= '9') {
  3969. return letter - '0' + 52;
  3970. }
  3971. if (letter == '+') {
  3972. return 62;
  3973. }
  3974. if (letter == '/') {
  3975. return 63;
  3976. }
  3977. if (letter == '=') {
  3978. return 255; /* normal end */
  3979. }
  3980. return 254; /* error */
  3981. }
  3982. static int
  3983. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3984. {
  3985. int i;
  3986. unsigned char a, b, c, d;
  3987. *dst_len = 0;
  3988. for (i = 0; i < src_len; i += 4) {
  3989. a = b64reverse(src[i]);
  3990. if (a >= 254) {
  3991. return i;
  3992. }
  3993. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3994. if (b >= 254) {
  3995. return i + 1;
  3996. }
  3997. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3998. if (c == 254) {
  3999. return i + 2;
  4000. }
  4001. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  4002. if (d == 254) {
  4003. return i + 3;
  4004. }
  4005. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4006. if (c != 255) {
  4007. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4008. if (d != 255) {
  4009. dst[(*dst_len)++] = (c << 6) + d;
  4010. }
  4011. }
  4012. }
  4013. return -1;
  4014. }
  4015. #endif
  4016. static int
  4017. is_put_or_delete_method(const struct mg_connection *conn)
  4018. {
  4019. if (conn) {
  4020. const char *s = conn->request_info.request_method;
  4021. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4022. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4023. }
  4024. return 0;
  4025. }
  4026. static void
  4027. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4028. char *filename, /* out: filename */
  4029. size_t filename_buf_len, /* in: size of filename buffer */
  4030. struct file *filep, /* out: file structure */
  4031. int *is_found, /* out: file is found (directly) */
  4032. int *is_script_resource, /* out: handled by a script? */
  4033. int *is_websocket_request, /* out: websocket connetion? */
  4034. int *is_put_or_delete_request /* out: put/delete a file? */
  4035. )
  4036. {
  4037. /* TODO (high): Restructure this function */
  4038. #if !defined(NO_FILES)
  4039. const char *uri = conn->request_info.local_uri;
  4040. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4041. const char *rewrite;
  4042. struct vec a, b;
  4043. int match_len;
  4044. char gz_path[PATH_MAX];
  4045. char const *accept_encoding;
  4046. int truncated;
  4047. #if !defined(NO_CGI) || defined(USE_LUA)
  4048. char *p;
  4049. #endif
  4050. #else
  4051. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4052. #endif
  4053. memset(filep, 0, sizeof(*filep));
  4054. *filename = 0;
  4055. *is_found = 0;
  4056. *is_script_resource = 0;
  4057. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4058. #if defined(USE_WEBSOCKET)
  4059. *is_websocket_request = is_websocket_protocol(conn);
  4060. #if !defined(NO_FILES)
  4061. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4062. root = conn->ctx->config[WEBSOCKET_ROOT];
  4063. }
  4064. #endif /* !NO_FILES */
  4065. #else /* USE_WEBSOCKET */
  4066. *is_websocket_request = 0;
  4067. #endif /* USE_WEBSOCKET */
  4068. #if !defined(NO_FILES)
  4069. /* Note that root == NULL is a regular use case here. This occurs,
  4070. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4071. * config is not required. */
  4072. if (root == NULL) {
  4073. /* all file related outputs have already been set to 0, just return
  4074. */
  4075. return;
  4076. }
  4077. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4078. * of the path one byte on the right.
  4079. * If document_root is NULL, leave the file empty. */
  4080. mg_snprintf(
  4081. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4082. if (truncated) {
  4083. goto interpret_cleanup;
  4084. }
  4085. rewrite = conn->ctx->config[REWRITE];
  4086. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4087. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4088. mg_snprintf(conn,
  4089. &truncated,
  4090. filename,
  4091. filename_buf_len - 1,
  4092. "%.*s%s",
  4093. (int)b.len,
  4094. b.ptr,
  4095. uri + match_len);
  4096. break;
  4097. }
  4098. }
  4099. if (truncated) {
  4100. goto interpret_cleanup;
  4101. }
  4102. /* Local file path and name, corresponding to requested URI
  4103. * is now stored in "filename" variable. */
  4104. if (mg_stat(conn, filename, filep)) {
  4105. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4106. /* File exists. Check if it is a script type. */
  4107. if (0
  4108. #if !defined(NO_CGI)
  4109. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4110. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4111. filename) > 0
  4112. #endif
  4113. #if defined(USE_LUA)
  4114. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4115. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4116. filename) > 0
  4117. #endif
  4118. #if defined(USE_DUKTAPE)
  4119. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4120. strlen(
  4121. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4122. filename) > 0
  4123. #endif
  4124. ) {
  4125. /* The request addresses a CGI script or a Lua script. The URI
  4126. * corresponds to the script itself (like /path/script.cgi),
  4127. * and there is no additional resource path
  4128. * (like /path/script.cgi/something).
  4129. * Requests that modify (replace or delete) a resource, like
  4130. * PUT and DELETE requests, should replace/delete the script
  4131. * file.
  4132. * Requests that read or write from/to a resource, like GET and
  4133. * POST requests, should call the script and return the
  4134. * generated response. */
  4135. *is_script_resource = !*is_put_or_delete_request;
  4136. }
  4137. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4138. *is_found = 1;
  4139. return;
  4140. }
  4141. /* If we can't find the actual file, look for the file
  4142. * with the same name but a .gz extension. If we find it,
  4143. * use that and set the gzipped flag in the file struct
  4144. * to indicate that the response need to have the content-
  4145. * encoding: gzip header.
  4146. * We can only do this if the browser declares support. */
  4147. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4148. if (strstr(accept_encoding, "gzip") != NULL) {
  4149. mg_snprintf(
  4150. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4151. if (truncated) {
  4152. goto interpret_cleanup;
  4153. }
  4154. if (mg_stat(conn, gz_path, filep)) {
  4155. if (filep) {
  4156. filep->gzipped = 1;
  4157. *is_found = 1;
  4158. }
  4159. /* Currently gz files can not be scripts. */
  4160. return;
  4161. }
  4162. }
  4163. }
  4164. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4165. /* Support PATH_INFO for CGI scripts. */
  4166. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4167. if (*p == '/') {
  4168. *p = '\0';
  4169. if ((0
  4170. #if !defined(NO_CGI)
  4171. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4172. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4173. filename) > 0
  4174. #endif
  4175. #if defined(USE_LUA)
  4176. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4177. strlen(
  4178. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4179. filename) > 0
  4180. #endif
  4181. #if defined(USE_DUKTAPE)
  4182. || match_prefix(
  4183. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4184. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4185. filename) > 0
  4186. #endif
  4187. ) && mg_stat(conn, filename, filep)) {
  4188. /* Shift PATH_INFO block one character right, e.g.
  4189. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4190. * conn->path_info is pointing to the local variable "path"
  4191. * declared in handle_request(), so PATH_INFO is not valid
  4192. * after handle_request returns. */
  4193. conn->path_info = p + 1;
  4194. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4195. * trailing \0 */
  4196. p[1] = '/';
  4197. *is_script_resource = 1;
  4198. break;
  4199. } else {
  4200. *p = '/';
  4201. }
  4202. }
  4203. }
  4204. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4205. #endif /* !defined(NO_FILES) */
  4206. return;
  4207. #if !defined(NO_FILES)
  4208. /* Reset all outputs */
  4209. interpret_cleanup:
  4210. memset(filep, 0, sizeof(*filep));
  4211. *filename = 0;
  4212. *is_found = 0;
  4213. *is_script_resource = 0;
  4214. *is_websocket_request = 0;
  4215. *is_put_or_delete_request = 0;
  4216. #endif /* !defined(NO_FILES) */
  4217. }
  4218. /* Check whether full request is buffered. Return:
  4219. * -1 if request is malformed
  4220. * 0 if request is not yet fully buffered
  4221. * >0 actual request length, including last \r\n\r\n */
  4222. static int
  4223. get_request_len(const char *buf, int buflen)
  4224. {
  4225. const char *s, *e;
  4226. int len = 0;
  4227. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4228. /* Control characters are not allowed but >=128 is. */
  4229. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4230. && *(const unsigned char *)s < 128) {
  4231. len = -1;
  4232. break; /* [i_a] abort scan as soon as one malformed character is
  4233. * found; */
  4234. /* don't let subsequent \r\n\r\n win us over anyhow */
  4235. } else if (s[0] == '\n' && s[1] == '\n') {
  4236. len = (int)(s - buf) + 2;
  4237. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4238. len = (int)(s - buf) + 3;
  4239. }
  4240. return len;
  4241. }
  4242. #if !defined(NO_CACHING)
  4243. /* Convert month to the month number. Return -1 on error, or month number */
  4244. static int
  4245. get_month_index(const char *s)
  4246. {
  4247. size_t i;
  4248. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4249. if (!strcmp(s, month_names[i])) {
  4250. return (int)i;
  4251. }
  4252. }
  4253. return -1;
  4254. }
  4255. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4256. static time_t
  4257. parse_date_string(const char *datetime)
  4258. {
  4259. char month_str[32] = {0};
  4260. int second, minute, hour, day, month, year;
  4261. time_t result = (time_t)0;
  4262. struct tm tm;
  4263. if ((sscanf(datetime,
  4264. "%d/%3s/%d %d:%d:%d",
  4265. &day,
  4266. month_str,
  4267. &year,
  4268. &hour,
  4269. &minute,
  4270. &second) == 6) || (sscanf(datetime,
  4271. "%d %3s %d %d:%d:%d",
  4272. &day,
  4273. month_str,
  4274. &year,
  4275. &hour,
  4276. &minute,
  4277. &second) == 6)
  4278. || (sscanf(datetime,
  4279. "%*3s, %d %3s %d %d:%d:%d",
  4280. &day,
  4281. month_str,
  4282. &year,
  4283. &hour,
  4284. &minute,
  4285. &second) == 6) || (sscanf(datetime,
  4286. "%d-%3s-%d %d:%d:%d",
  4287. &day,
  4288. month_str,
  4289. &year,
  4290. &hour,
  4291. &minute,
  4292. &second) == 6)) {
  4293. month = get_month_index(month_str);
  4294. if ((month >= 0) && (year >= 1970)) {
  4295. memset(&tm, 0, sizeof(tm));
  4296. tm.tm_year = year - 1900;
  4297. tm.tm_mon = month;
  4298. tm.tm_mday = day;
  4299. tm.tm_hour = hour;
  4300. tm.tm_min = minute;
  4301. tm.tm_sec = second;
  4302. result = timegm(&tm);
  4303. }
  4304. }
  4305. return result;
  4306. }
  4307. #endif /* !NO_CACHING */
  4308. /* Protect against directory disclosure attack by removing '..',
  4309. * excessive '/' and '\' characters */
  4310. static void
  4311. remove_double_dots_and_double_slashes(char *s)
  4312. {
  4313. char *p = s;
  4314. while (*s != '\0') {
  4315. *p++ = *s++;
  4316. if (s[-1] == '/' || s[-1] == '\\') {
  4317. /* Skip all following slashes, backslashes and double-dots */
  4318. while (s[0] != '\0') {
  4319. if (s[0] == '/' || s[0] == '\\') {
  4320. s++;
  4321. } else if (s[0] == '.' && s[1] == '.') {
  4322. s += 2;
  4323. } else {
  4324. break;
  4325. }
  4326. }
  4327. }
  4328. }
  4329. *p = '\0';
  4330. }
  4331. static const struct {
  4332. const char *extension;
  4333. size_t ext_len;
  4334. const char *mime_type;
  4335. } builtin_mime_types[] = {
  4336. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4337. * application types */
  4338. {".doc", 4, "application/msword"},
  4339. {".eps", 4, "application/postscript"},
  4340. {".exe", 4, "application/octet-stream"},
  4341. {".js", 3, "application/javascript"},
  4342. {".json", 5, "application/json"},
  4343. {".pdf", 4, "application/pdf"},
  4344. {".ps", 3, "application/postscript"},
  4345. {".rtf", 4, "application/rtf"},
  4346. {".xhtml", 6, "application/xhtml+xml"},
  4347. {".xsl", 4, "application/xml"},
  4348. {".xslt", 5, "application/xml"},
  4349. /* fonts */
  4350. {".ttf", 4, "application/font-sfnt"},
  4351. {".cff", 4, "application/font-sfnt"},
  4352. {".otf", 4, "application/font-sfnt"},
  4353. {".aat", 4, "application/font-sfnt"},
  4354. {".sil", 4, "application/font-sfnt"},
  4355. {".pfr", 4, "application/font-tdpfr"},
  4356. {".woff", 5, "application/font-woff"},
  4357. /* audio */
  4358. {".mp3", 4, "audio/mpeg"},
  4359. {".oga", 4, "audio/ogg"},
  4360. {".ogg", 4, "audio/ogg"},
  4361. /* image */
  4362. {".gif", 4, "image/gif"},
  4363. {".ief", 4, "image/ief"},
  4364. {".jpeg", 5, "image/jpeg"},
  4365. {".jpg", 4, "image/jpeg"},
  4366. {".jpm", 4, "image/jpm"},
  4367. {".jpx", 4, "image/jpx"},
  4368. {".png", 4, "image/png"},
  4369. {".svg", 4, "image/svg+xml"},
  4370. {".tif", 4, "image/tiff"},
  4371. {".tiff", 5, "image/tiff"},
  4372. /* model */
  4373. {".wrl", 4, "model/vrml"},
  4374. /* text */
  4375. {".css", 4, "text/css"},
  4376. {".csv", 4, "text/csv"},
  4377. {".htm", 4, "text/html"},
  4378. {".html", 5, "text/html"},
  4379. {".sgm", 4, "text/sgml"},
  4380. {".shtm", 5, "text/html"},
  4381. {".shtml", 6, "text/html"},
  4382. {".txt", 4, "text/plain"},
  4383. {".xml", 4, "text/xml"},
  4384. /* video */
  4385. {".mov", 4, "video/quicktime"},
  4386. {".mp4", 4, "video/mp4"},
  4387. {".mpeg", 5, "video/mpeg"},
  4388. {".mpg", 4, "video/mpeg"},
  4389. {".ogv", 4, "video/ogg"},
  4390. {".qt", 3, "video/quicktime"},
  4391. /* not registered types
  4392. * (http://reference.sitepoint.com/html/mime-types-full,
  4393. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4394. {".arj", 4, "application/x-arj-compressed"},
  4395. {".gz", 3, "application/x-gunzip"},
  4396. {".rar", 4, "application/x-arj-compressed"},
  4397. {".swf", 4, "application/x-shockwave-flash"},
  4398. {".tar", 4, "application/x-tar"},
  4399. {".tgz", 4, "application/x-tar-gz"},
  4400. {".torrent", 8, "application/x-bittorrent"},
  4401. {".ppt", 4, "application/x-mspowerpoint"},
  4402. {".xls", 4, "application/x-msexcel"},
  4403. {".zip", 4, "application/x-zip-compressed"},
  4404. {".aac",
  4405. 4,
  4406. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4407. {".aif", 4, "audio/x-aif"},
  4408. {".m3u", 4, "audio/x-mpegurl"},
  4409. {".mid", 4, "audio/x-midi"},
  4410. {".ra", 3, "audio/x-pn-realaudio"},
  4411. {".ram", 4, "audio/x-pn-realaudio"},
  4412. {".wav", 4, "audio/x-wav"},
  4413. {".bmp", 4, "image/bmp"},
  4414. {".ico", 4, "image/x-icon"},
  4415. {".pct", 4, "image/x-pct"},
  4416. {".pict", 5, "image/pict"},
  4417. {".rgb", 4, "image/x-rgb"},
  4418. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4419. {".asf", 4, "video/x-ms-asf"},
  4420. {".avi", 4, "video/x-msvideo"},
  4421. {".m4v", 4, "video/x-m4v"},
  4422. {NULL, 0, NULL}};
  4423. const char *
  4424. mg_get_builtin_mime_type(const char *path)
  4425. {
  4426. const char *ext;
  4427. size_t i, path_len;
  4428. path_len = strlen(path);
  4429. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4430. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4431. if (path_len > builtin_mime_types[i].ext_len
  4432. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4433. return builtin_mime_types[i].mime_type;
  4434. }
  4435. }
  4436. return "text/plain";
  4437. }
  4438. /* Look at the "path" extension and figure what mime type it has.
  4439. * Store mime type in the vector. */
  4440. static void
  4441. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4442. {
  4443. struct vec ext_vec, mime_vec;
  4444. const char *list, *ext;
  4445. size_t path_len;
  4446. path_len = strlen(path);
  4447. if (ctx == NULL || vec == NULL) {
  4448. return;
  4449. }
  4450. /* Scan user-defined mime types first, in case user wants to
  4451. * override default mime types. */
  4452. list = ctx->config[EXTRA_MIME_TYPES];
  4453. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4454. /* ext now points to the path suffix */
  4455. ext = path + path_len - ext_vec.len;
  4456. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4457. *vec = mime_vec;
  4458. return;
  4459. }
  4460. }
  4461. vec->ptr = mg_get_builtin_mime_type(path);
  4462. vec->len = strlen(vec->ptr);
  4463. }
  4464. /* Stringify binary data. Output buffer must be twice as big as input,
  4465. * because each byte takes 2 bytes in string representation */
  4466. static void
  4467. bin2str(char *to, const unsigned char *p, size_t len)
  4468. {
  4469. static const char *hex = "0123456789abcdef";
  4470. for (; len--; p++) {
  4471. *to++ = hex[p[0] >> 4];
  4472. *to++ = hex[p[0] & 0x0f];
  4473. }
  4474. *to = '\0';
  4475. }
  4476. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4477. char *
  4478. mg_md5(char buf[33], ...)
  4479. {
  4480. md5_byte_t hash[16];
  4481. const char *p;
  4482. va_list ap;
  4483. md5_state_t ctx;
  4484. md5_init(&ctx);
  4485. va_start(ap, buf);
  4486. while ((p = va_arg(ap, const char *)) != NULL) {
  4487. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4488. }
  4489. va_end(ap);
  4490. md5_finish(&ctx, hash);
  4491. bin2str(buf, hash, sizeof(hash));
  4492. return buf;
  4493. }
  4494. /* Check the user's password, return 1 if OK */
  4495. static int
  4496. check_password(const char *method,
  4497. const char *ha1,
  4498. const char *uri,
  4499. const char *nonce,
  4500. const char *nc,
  4501. const char *cnonce,
  4502. const char *qop,
  4503. const char *response)
  4504. {
  4505. char ha2[32 + 1], expected_response[32 + 1];
  4506. /* Some of the parameters may be NULL */
  4507. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4508. || qop == NULL
  4509. || response == NULL) {
  4510. return 0;
  4511. }
  4512. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4513. if (strlen(response) != 32) {
  4514. return 0;
  4515. }
  4516. mg_md5(ha2, method, ":", uri, NULL);
  4517. mg_md5(expected_response,
  4518. ha1,
  4519. ":",
  4520. nonce,
  4521. ":",
  4522. nc,
  4523. ":",
  4524. cnonce,
  4525. ":",
  4526. qop,
  4527. ":",
  4528. ha2,
  4529. NULL);
  4530. return mg_strcasecmp(response, expected_response) == 0;
  4531. }
  4532. /* Use the global passwords file, if specified by auth_gpass option,
  4533. * or search for .htpasswd in the requested directory. */
  4534. static void
  4535. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4536. {
  4537. if (conn != NULL && conn->ctx != NULL) {
  4538. char name[PATH_MAX];
  4539. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4540. struct file file = STRUCT_FILE_INITIALIZER;
  4541. int truncated;
  4542. if (gpass != NULL) {
  4543. /* Use global passwords file */
  4544. if (!mg_fopen(conn, gpass, "r", filep)) {
  4545. #ifdef DEBUG
  4546. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4547. #endif
  4548. }
  4549. /* Important: using local struct file to test path for is_directory
  4550. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4551. * was opened. */
  4552. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4553. mg_snprintf(conn,
  4554. &truncated,
  4555. name,
  4556. sizeof(name),
  4557. "%s/%s",
  4558. path,
  4559. PASSWORDS_FILE_NAME);
  4560. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4561. #ifdef DEBUG
  4562. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4563. #endif
  4564. }
  4565. } else {
  4566. /* Try to find .htpasswd in requested directory. */
  4567. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4568. if (e[0] == '/') {
  4569. break;
  4570. }
  4571. }
  4572. mg_snprintf(conn,
  4573. &truncated,
  4574. name,
  4575. sizeof(name),
  4576. "%.*s/%s",
  4577. (int)(e - p),
  4578. p,
  4579. PASSWORDS_FILE_NAME);
  4580. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4581. #ifdef DEBUG
  4582. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4583. #endif
  4584. }
  4585. }
  4586. }
  4587. }
  4588. /* Parsed Authorization header */
  4589. struct ah {
  4590. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4591. };
  4592. /* Return 1 on success. Always initializes the ah structure. */
  4593. static int
  4594. parse_auth_header(struct mg_connection *conn,
  4595. char *buf,
  4596. size_t buf_size,
  4597. struct ah *ah)
  4598. {
  4599. char *name, *value, *s;
  4600. const char *auth_header;
  4601. uint64_t nonce;
  4602. if (!ah || !conn) {
  4603. return 0;
  4604. }
  4605. (void)memset(ah, 0, sizeof(*ah));
  4606. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4607. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4608. return 0;
  4609. }
  4610. /* Make modifiable copy of the auth header */
  4611. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4612. s = buf;
  4613. /* Parse authorization header */
  4614. for (;;) {
  4615. /* Gobble initial spaces */
  4616. while (isspace(*(unsigned char *)s)) {
  4617. s++;
  4618. }
  4619. name = skip_quoted(&s, "=", " ", 0);
  4620. /* Value is either quote-delimited, or ends at first comma or space. */
  4621. if (s[0] == '\"') {
  4622. s++;
  4623. value = skip_quoted(&s, "\"", " ", '\\');
  4624. if (s[0] == ',') {
  4625. s++;
  4626. }
  4627. } else {
  4628. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4629. * spaces */
  4630. }
  4631. if (*name == '\0') {
  4632. break;
  4633. }
  4634. if (!strcmp(name, "username")) {
  4635. ah->user = value;
  4636. } else if (!strcmp(name, "cnonce")) {
  4637. ah->cnonce = value;
  4638. } else if (!strcmp(name, "response")) {
  4639. ah->response = value;
  4640. } else if (!strcmp(name, "uri")) {
  4641. ah->uri = value;
  4642. } else if (!strcmp(name, "qop")) {
  4643. ah->qop = value;
  4644. } else if (!strcmp(name, "nc")) {
  4645. ah->nc = value;
  4646. } else if (!strcmp(name, "nonce")) {
  4647. ah->nonce = value;
  4648. }
  4649. }
  4650. #ifndef NO_NONCE_CHECK
  4651. /* Read the nonce from the response. */
  4652. if (ah->nonce == NULL) {
  4653. return 0;
  4654. }
  4655. s = NULL;
  4656. nonce = strtoull(ah->nonce, &s, 10);
  4657. if ((s == NULL) || (*s != 0)) {
  4658. return 0;
  4659. }
  4660. /* Convert the nonce from the client to a number. */
  4661. nonce ^= conn->ctx->auth_nonce_mask;
  4662. /* The converted number corresponds to the time the nounce has been
  4663. * created. This should not be earlier than the server start. */
  4664. /* Server side nonce check is valuable in all situations but one:
  4665. * if the server restarts frequently, but the client should not see
  4666. * that, so the server should accept nonces from previous starts. */
  4667. /* However, the reasonable default is to not accept a nonce from a
  4668. * previous start, so if anyone changed the access rights between
  4669. * two restarts, a new login is required. */
  4670. if (nonce < (uint64_t)conn->ctx->start_time) {
  4671. /* nonce is from a previous start of the server and no longer valid
  4672. * (replay attack?) */
  4673. return 0;
  4674. }
  4675. /* Check if the nonce is too high, so it has not (yet) been used by the
  4676. * server. */
  4677. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4678. return 0;
  4679. }
  4680. #else
  4681. (void)nonce;
  4682. #endif
  4683. /* CGI needs it as REMOTE_USER */
  4684. if (ah->user != NULL) {
  4685. conn->request_info.remote_user = mg_strdup(ah->user);
  4686. } else {
  4687. return 0;
  4688. }
  4689. return 1;
  4690. }
  4691. static const char *
  4692. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4693. {
  4694. const char *eof;
  4695. size_t len;
  4696. const char *memend;
  4697. if (!filep) {
  4698. return NULL;
  4699. }
  4700. if (filep->membuf != NULL && *p != NULL) {
  4701. memend = (const char *)&filep->membuf[filep->size];
  4702. /* Search for \n from p till the end of stream */
  4703. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4704. if (eof != NULL) {
  4705. eof += 1; /* Include \n */
  4706. } else {
  4707. eof = memend; /* Copy remaining data */
  4708. }
  4709. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4710. memcpy(buf, *p, len);
  4711. buf[len] = '\0';
  4712. *p += len;
  4713. return len ? eof : NULL;
  4714. } else if (filep->fp != NULL) {
  4715. return fgets(buf, (int)size, filep->fp);
  4716. } else {
  4717. return NULL;
  4718. }
  4719. }
  4720. struct read_auth_file_struct {
  4721. struct mg_connection *conn;
  4722. struct ah ah;
  4723. char *domain;
  4724. char buf[256 + 256 + 40];
  4725. char *f_user;
  4726. char *f_domain;
  4727. char *f_ha1;
  4728. };
  4729. static int
  4730. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4731. {
  4732. char *p;
  4733. int is_authorized = 0;
  4734. struct file fp;
  4735. size_t l;
  4736. if (!filep || !workdata) {
  4737. return 0;
  4738. }
  4739. /* Loop over passwords file */
  4740. p = (char *)filep->membuf;
  4741. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4742. l = strlen(workdata->buf);
  4743. while (l > 0) {
  4744. if (isspace(workdata->buf[l - 1])
  4745. || iscntrl(workdata->buf[l - 1])) {
  4746. l--;
  4747. workdata->buf[l] = 0;
  4748. } else
  4749. break;
  4750. }
  4751. if (l < 1) {
  4752. continue;
  4753. }
  4754. workdata->f_user = workdata->buf;
  4755. if (workdata->f_user[0] == ':') {
  4756. /* user names may not contain a ':' and may not be empty,
  4757. * so lines starting with ':' may be used for a special purpose */
  4758. if (workdata->f_user[1] == '#') {
  4759. /* :# is a comment */
  4760. continue;
  4761. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4762. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4763. is_authorized = read_auth_file(&fp, workdata);
  4764. mg_fclose(&fp);
  4765. } else {
  4766. mg_cry(workdata->conn,
  4767. "%s: cannot open authorization file: %s",
  4768. __func__,
  4769. workdata->buf);
  4770. }
  4771. continue;
  4772. }
  4773. /* everything is invalid for the moment (might change in the
  4774. * future) */
  4775. mg_cry(workdata->conn,
  4776. "%s: syntax error in authorization file: %s",
  4777. __func__,
  4778. workdata->buf);
  4779. continue;
  4780. }
  4781. workdata->f_domain = strchr(workdata->f_user, ':');
  4782. if (workdata->f_domain == NULL) {
  4783. mg_cry(workdata->conn,
  4784. "%s: syntax error in authorization file: %s",
  4785. __func__,
  4786. workdata->buf);
  4787. continue;
  4788. }
  4789. *(workdata->f_domain) = 0;
  4790. (workdata->f_domain)++;
  4791. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4792. if (workdata->f_ha1 == NULL) {
  4793. mg_cry(workdata->conn,
  4794. "%s: syntax error in authorization file: %s",
  4795. __func__,
  4796. workdata->buf);
  4797. continue;
  4798. }
  4799. *(workdata->f_ha1) = 0;
  4800. (workdata->f_ha1)++;
  4801. if (!strcmp(workdata->ah.user, workdata->f_user)
  4802. && !strcmp(workdata->domain, workdata->f_domain)) {
  4803. return check_password(workdata->conn->request_info.request_method,
  4804. workdata->f_ha1,
  4805. workdata->ah.uri,
  4806. workdata->ah.nonce,
  4807. workdata->ah.nc,
  4808. workdata->ah.cnonce,
  4809. workdata->ah.qop,
  4810. workdata->ah.response);
  4811. }
  4812. }
  4813. return is_authorized;
  4814. }
  4815. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4816. static int
  4817. authorize(struct mg_connection *conn, struct file *filep)
  4818. {
  4819. struct read_auth_file_struct workdata;
  4820. char buf[MG_BUF_LEN];
  4821. if (!conn || !conn->ctx) {
  4822. return 0;
  4823. }
  4824. memset(&workdata, 0, sizeof(workdata));
  4825. workdata.conn = conn;
  4826. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4827. return 0;
  4828. }
  4829. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4830. return read_auth_file(filep, &workdata);
  4831. }
  4832. /* Return 1 if request is authorised, 0 otherwise. */
  4833. static int
  4834. check_authorization(struct mg_connection *conn, const char *path)
  4835. {
  4836. char fname[PATH_MAX];
  4837. struct vec uri_vec, filename_vec;
  4838. const char *list;
  4839. struct file file = STRUCT_FILE_INITIALIZER;
  4840. int authorized = 1, truncated;
  4841. if (!conn || !conn->ctx) {
  4842. return 0;
  4843. }
  4844. list = conn->ctx->config[PROTECT_URI];
  4845. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4846. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4847. mg_snprintf(conn,
  4848. &truncated,
  4849. fname,
  4850. sizeof(fname),
  4851. "%.*s",
  4852. (int)filename_vec.len,
  4853. filename_vec.ptr);
  4854. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4855. mg_cry(conn,
  4856. "%s: cannot open %s: %s",
  4857. __func__,
  4858. fname,
  4859. strerror(errno));
  4860. }
  4861. break;
  4862. }
  4863. }
  4864. if (!is_file_opened(&file)) {
  4865. open_auth_file(conn, path, &file);
  4866. }
  4867. if (is_file_opened(&file)) {
  4868. authorized = authorize(conn, &file);
  4869. mg_fclose(&file);
  4870. }
  4871. return authorized;
  4872. }
  4873. static void
  4874. send_authorization_request(struct mg_connection *conn)
  4875. {
  4876. char date[64];
  4877. time_t curtime = time(NULL);
  4878. if (conn && conn->ctx) {
  4879. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4880. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4881. nonce += conn->ctx->nonce_count;
  4882. ++conn->ctx->nonce_count;
  4883. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4884. nonce ^= conn->ctx->auth_nonce_mask;
  4885. conn->status_code = 401;
  4886. conn->must_close = 1;
  4887. gmt_time_string(date, sizeof(date), &curtime);
  4888. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  4889. send_no_cache_header(conn);
  4890. mg_printf(conn,
  4891. "Date: %s\r\n"
  4892. "Connection: %s\r\n"
  4893. "Content-Length: 0\r\n"
  4894. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4895. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4896. date,
  4897. suggest_connection_header(conn),
  4898. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4899. nonce);
  4900. }
  4901. }
  4902. #if !defined(NO_FILES)
  4903. static int
  4904. is_authorized_for_put(struct mg_connection *conn)
  4905. {
  4906. if (conn) {
  4907. struct file file = STRUCT_FILE_INITIALIZER;
  4908. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4909. int ret = 0;
  4910. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4911. ret = authorize(conn, &file);
  4912. mg_fclose(&file);
  4913. }
  4914. return ret;
  4915. }
  4916. return 0;
  4917. }
  4918. #endif
  4919. int
  4920. mg_modify_passwords_file(const char *fname,
  4921. const char *domain,
  4922. const char *user,
  4923. const char *pass)
  4924. {
  4925. int found, i;
  4926. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4927. FILE *fp, *fp2;
  4928. found = 0;
  4929. fp = fp2 = NULL;
  4930. /* Regard empty password as no password - remove user record. */
  4931. if (pass != NULL && pass[0] == '\0') {
  4932. pass = NULL;
  4933. }
  4934. /* Other arguments must not be empty */
  4935. if (fname == NULL || domain == NULL || user == NULL) {
  4936. return 0;
  4937. }
  4938. /* Using the given file format, user name and domain must not contain ':'
  4939. */
  4940. if (strchr(user, ':') != NULL) {
  4941. return 0;
  4942. }
  4943. if (strchr(domain, ':') != NULL) {
  4944. return 0;
  4945. }
  4946. /* Do not allow control characters like newline in user name and domain.
  4947. * Do not allow excessively long names either. */
  4948. for (i = 0; i < 255 && user[i] != 0; i++) {
  4949. if (iscntrl(user[i])) {
  4950. return 0;
  4951. }
  4952. }
  4953. if (user[i]) {
  4954. return 0;
  4955. }
  4956. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4957. if (iscntrl(domain[i])) {
  4958. return 0;
  4959. }
  4960. }
  4961. if (domain[i]) {
  4962. return 0;
  4963. }
  4964. /* The maximum length of the path to the password file is limited */
  4965. if ((strlen(fname) + 4) >= PATH_MAX) {
  4966. return 0;
  4967. }
  4968. /* Create a temporary file name. Length has been checked before. */
  4969. strcpy(tmp, fname);
  4970. strcat(tmp, ".tmp");
  4971. /* Create the file if does not exist */
  4972. /* Use of fopen here is OK, since fname is only ASCII */
  4973. if ((fp = fopen(fname, "a+")) != NULL) {
  4974. (void)fclose(fp);
  4975. }
  4976. /* Open the given file and temporary file */
  4977. if ((fp = fopen(fname, "r")) == NULL) {
  4978. return 0;
  4979. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4980. fclose(fp);
  4981. return 0;
  4982. }
  4983. /* Copy the stuff to temporary file */
  4984. while (fgets(line, sizeof(line), fp) != NULL) {
  4985. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4986. continue;
  4987. }
  4988. u[255] = 0;
  4989. d[255] = 0;
  4990. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4991. found++;
  4992. if (pass != NULL) {
  4993. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4994. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4995. }
  4996. } else {
  4997. fprintf(fp2, "%s", line);
  4998. }
  4999. }
  5000. /* If new user, just add it */
  5001. if (!found && pass != NULL) {
  5002. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5003. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5004. }
  5005. /* Close files */
  5006. fclose(fp);
  5007. fclose(fp2);
  5008. /* Put the temp file in place of real file */
  5009. IGNORE_UNUSED_RESULT(remove(fname));
  5010. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5011. return 1;
  5012. }
  5013. static int
  5014. is_valid_port(unsigned long port)
  5015. {
  5016. return port < 0xffff;
  5017. }
  5018. static int
  5019. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5020. {
  5021. struct addrinfo hints, *res, *ressave;
  5022. int func_ret = 0;
  5023. int gai_ret;
  5024. memset(&hints, 0, sizeof(struct addrinfo));
  5025. hints.ai_family = af;
  5026. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5027. if (gai_ret != 0) {
  5028. /* gai_strerror could be used to convert gai_ret to a string */
  5029. /* POSIX return values: see
  5030. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5031. */
  5032. /* Windows return values: see
  5033. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5034. */
  5035. return 0;
  5036. }
  5037. ressave = res;
  5038. while (res) {
  5039. if (dstlen >= res->ai_addrlen) {
  5040. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5041. func_ret = 1;
  5042. }
  5043. res = res->ai_next;
  5044. }
  5045. freeaddrinfo(ressave);
  5046. return func_ret;
  5047. }
  5048. static int
  5049. connect_socket(struct mg_context *ctx /* may be NULL */,
  5050. const char *host,
  5051. int port,
  5052. int use_ssl,
  5053. char *ebuf,
  5054. size_t ebuf_len,
  5055. SOCKET *sock /* output: socket, must not be NULL */,
  5056. union usa *sa /* output: socket address, must not be NULL */
  5057. )
  5058. {
  5059. int ip_ver = 0;
  5060. *sock = INVALID_SOCKET;
  5061. memset(sa, 0, sizeof(*sa));
  5062. if (ebuf_len > 0) {
  5063. *ebuf = 0;
  5064. }
  5065. if (host == NULL) {
  5066. mg_snprintf(NULL,
  5067. NULL, /* No truncation check for ebuf */
  5068. ebuf,
  5069. ebuf_len,
  5070. "%s",
  5071. "NULL host");
  5072. return 0;
  5073. }
  5074. if (port < 0 || !is_valid_port((unsigned)port)) {
  5075. mg_snprintf(NULL,
  5076. NULL, /* No truncation check for ebuf */
  5077. ebuf,
  5078. ebuf_len,
  5079. "%s",
  5080. "invalid port");
  5081. return 0;
  5082. }
  5083. #if !defined(NO_SSL)
  5084. if (use_ssl && (SSLv23_client_method == NULL)) {
  5085. mg_snprintf(NULL,
  5086. NULL, /* No truncation check for ebuf */
  5087. ebuf,
  5088. ebuf_len,
  5089. "%s",
  5090. "SSL is not initialized");
  5091. return 0;
  5092. }
  5093. #else
  5094. (void)use_ssl;
  5095. #endif
  5096. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5097. sa->sin.sin_port = htons((uint16_t)port);
  5098. ip_ver = 4;
  5099. #ifdef USE_IPV6
  5100. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5101. sa->sin6.sin6_port = htons((uint16_t)port);
  5102. ip_ver = 6;
  5103. } else if (host[0] == '[') {
  5104. /* While getaddrinfo on Windows will work with [::1],
  5105. * getaddrinfo on Linux only works with ::1 (without []). */
  5106. size_t l = strlen(host + 1);
  5107. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  5108. if (h) {
  5109. h[l - 1] = 0;
  5110. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5111. sa->sin6.sin6_port = htons((uint16_t)port);
  5112. ip_ver = 6;
  5113. }
  5114. mg_free(h);
  5115. }
  5116. #endif
  5117. }
  5118. if (ip_ver == 0) {
  5119. mg_snprintf(NULL,
  5120. NULL, /* No truncation check for ebuf */
  5121. ebuf,
  5122. ebuf_len,
  5123. "%s",
  5124. "host not found");
  5125. return 0;
  5126. }
  5127. if (ip_ver == 4) {
  5128. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5129. }
  5130. #ifdef USE_IPV6
  5131. else if (ip_ver == 6) {
  5132. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5133. }
  5134. #endif
  5135. if (*sock == INVALID_SOCKET) {
  5136. mg_snprintf(NULL,
  5137. NULL, /* No truncation check for ebuf */
  5138. ebuf,
  5139. ebuf_len,
  5140. "socket(): %s",
  5141. strerror(ERRNO));
  5142. return 0;
  5143. }
  5144. set_close_on_exec(*sock, fc(ctx));
  5145. if ((ip_ver == 4)
  5146. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5147. == 0)) {
  5148. /* connected with IPv4 */
  5149. return 1;
  5150. }
  5151. #ifdef USE_IPV6
  5152. if ((ip_ver == 6)
  5153. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5154. == 0)) {
  5155. /* connected with IPv6 */
  5156. return 1;
  5157. }
  5158. #endif
  5159. /* Not connected */
  5160. mg_snprintf(NULL,
  5161. NULL, /* No truncation check for ebuf */
  5162. ebuf,
  5163. ebuf_len,
  5164. "connect(%s:%d): %s",
  5165. host,
  5166. port,
  5167. strerror(ERRNO));
  5168. closesocket(*sock);
  5169. *sock = INVALID_SOCKET;
  5170. return 0;
  5171. }
  5172. int
  5173. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5174. {
  5175. static const char *dont_escape = "._-$,;~()";
  5176. static const char *hex = "0123456789abcdef";
  5177. char *pos = dst;
  5178. const char *end = dst + dst_len - 1;
  5179. for (; *src != '\0' && pos < end; src++, pos++) {
  5180. if (isalnum(*(const unsigned char *)src)
  5181. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5182. *pos = *src;
  5183. } else if (pos + 2 < end) {
  5184. pos[0] = '%';
  5185. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5186. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5187. pos += 2;
  5188. } else {
  5189. break;
  5190. }
  5191. }
  5192. *pos = '\0';
  5193. return (*src == '\0') ? (int)(pos - dst) : -1;
  5194. }
  5195. static void
  5196. print_dir_entry(struct de *de)
  5197. {
  5198. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5199. struct tm *tm;
  5200. if (de->file.is_directory) {
  5201. mg_snprintf(de->conn,
  5202. NULL, /* Buffer is big enough */
  5203. size,
  5204. sizeof(size),
  5205. "%s",
  5206. "[DIRECTORY]");
  5207. } else {
  5208. /* We use (signed) cast below because MSVC 6 compiler cannot
  5209. * convert unsigned __int64 to double. Sigh. */
  5210. if (de->file.size < 1024) {
  5211. mg_snprintf(de->conn,
  5212. NULL, /* Buffer is big enough */
  5213. size,
  5214. sizeof(size),
  5215. "%d",
  5216. (int)de->file.size);
  5217. } else if (de->file.size < 0x100000) {
  5218. mg_snprintf(de->conn,
  5219. NULL, /* Buffer is big enough */
  5220. size,
  5221. sizeof(size),
  5222. "%.1fk",
  5223. (double)de->file.size / 1024.0);
  5224. } else if (de->file.size < 0x40000000) {
  5225. mg_snprintf(de->conn,
  5226. NULL, /* Buffer is big enough */
  5227. size,
  5228. sizeof(size),
  5229. "%.1fM",
  5230. (double)de->file.size / 1048576);
  5231. } else {
  5232. mg_snprintf(de->conn,
  5233. NULL, /* Buffer is big enough */
  5234. size,
  5235. sizeof(size),
  5236. "%.1fG",
  5237. (double)de->file.size / 1073741824);
  5238. }
  5239. }
  5240. /* Note: mg_snprintf will not cause a buffer overflow above.
  5241. * So, string truncation checks are not required here. */
  5242. tm = localtime(&de->file.last_modified);
  5243. if (tm != NULL) {
  5244. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5245. } else {
  5246. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5247. mod[sizeof(mod) - 1] = '\0';
  5248. }
  5249. mg_url_encode(de->file_name, href, sizeof(href));
  5250. de->conn->num_bytes_sent +=
  5251. mg_printf(de->conn,
  5252. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5253. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5254. de->conn->request_info.local_uri,
  5255. href,
  5256. de->file.is_directory ? "/" : "",
  5257. de->file_name,
  5258. de->file.is_directory ? "/" : "",
  5259. mod,
  5260. size);
  5261. }
  5262. /* This function is called from send_directory() and used for
  5263. * sorting directory entries by size, or name, or modification time.
  5264. * On windows, __cdecl specification is needed in case if project is built
  5265. * with __stdcall convention. qsort always requires __cdels callback. */
  5266. static int WINCDECL
  5267. compare_dir_entries(const void *p1, const void *p2)
  5268. {
  5269. if (p1 && p2) {
  5270. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5271. const char *query_string = a->conn->request_info.query_string;
  5272. int cmp_result = 0;
  5273. if (query_string == NULL) {
  5274. query_string = "na";
  5275. }
  5276. if (a->file.is_directory && !b->file.is_directory) {
  5277. return -1; /* Always put directories on top */
  5278. } else if (!a->file.is_directory && b->file.is_directory) {
  5279. return 1; /* Always put directories on top */
  5280. } else if (*query_string == 'n') {
  5281. cmp_result = strcmp(a->file_name, b->file_name);
  5282. } else if (*query_string == 's') {
  5283. cmp_result = a->file.size == b->file.size
  5284. ? 0
  5285. : a->file.size > b->file.size ? 1 : -1;
  5286. } else if (*query_string == 'd') {
  5287. cmp_result =
  5288. (a->file.last_modified == b->file.last_modified)
  5289. ? 0
  5290. : ((a->file.last_modified > b->file.last_modified) ? 1
  5291. : -1);
  5292. }
  5293. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  5294. }
  5295. return 0;
  5296. }
  5297. static int
  5298. must_hide_file(struct mg_connection *conn, const char *path)
  5299. {
  5300. if (conn && conn->ctx) {
  5301. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5302. const char *pattern = conn->ctx->config[HIDE_FILES];
  5303. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5304. || (pattern != NULL
  5305. && match_prefix(pattern, strlen(pattern), path) > 0);
  5306. }
  5307. return 0;
  5308. }
  5309. static int
  5310. scan_directory(struct mg_connection *conn,
  5311. const char *dir,
  5312. void *data,
  5313. void (*cb)(struct de *, void *))
  5314. {
  5315. char path[PATH_MAX];
  5316. struct dirent *dp;
  5317. DIR *dirp;
  5318. struct de de;
  5319. int truncated;
  5320. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5321. return 0;
  5322. } else {
  5323. de.conn = conn;
  5324. while ((dp = mg_readdir(dirp)) != NULL) {
  5325. /* Do not show current dir and hidden files */
  5326. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5327. || must_hide_file(conn, dp->d_name)) {
  5328. continue;
  5329. }
  5330. mg_snprintf(
  5331. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5332. /* If we don't memset stat structure to zero, mtime will have
  5333. * garbage and strftime() will segfault later on in
  5334. * print_dir_entry(). memset is required only if mg_stat()
  5335. * fails. For more details, see
  5336. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5337. memset(&de.file, 0, sizeof(de.file));
  5338. if (truncated) {
  5339. /* If the path is not complete, skip processing. */
  5340. continue;
  5341. }
  5342. if (!mg_stat(conn, path, &de.file)) {
  5343. mg_cry(conn,
  5344. "%s: mg_stat(%s) failed: %s",
  5345. __func__,
  5346. path,
  5347. strerror(ERRNO));
  5348. }
  5349. de.file_name = dp->d_name;
  5350. cb(&de, data);
  5351. }
  5352. (void)mg_closedir(dirp);
  5353. }
  5354. return 1;
  5355. }
  5356. #if !defined(NO_FILES)
  5357. static int
  5358. remove_directory(struct mg_connection *conn, const char *dir)
  5359. {
  5360. char path[PATH_MAX];
  5361. struct dirent *dp;
  5362. DIR *dirp;
  5363. struct de de;
  5364. int truncated;
  5365. int ok = 1;
  5366. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5367. return 0;
  5368. } else {
  5369. de.conn = conn;
  5370. while ((dp = mg_readdir(dirp)) != NULL) {
  5371. /* Do not show current dir (but show hidden files as they will
  5372. * also be removed) */
  5373. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5374. continue;
  5375. }
  5376. mg_snprintf(
  5377. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5378. /* If we don't memset stat structure to zero, mtime will have
  5379. * garbage and strftime() will segfault later on in
  5380. * print_dir_entry(). memset is required only if mg_stat()
  5381. * fails. For more details, see
  5382. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5383. memset(&de.file, 0, sizeof(de.file));
  5384. if (truncated) {
  5385. /* Do not delete anything shorter */
  5386. ok = 0;
  5387. continue;
  5388. }
  5389. if (!mg_stat(conn, path, &de.file)) {
  5390. mg_cry(conn,
  5391. "%s: mg_stat(%s) failed: %s",
  5392. __func__,
  5393. path,
  5394. strerror(ERRNO));
  5395. ok = 0;
  5396. }
  5397. if (de.file.membuf == NULL) {
  5398. /* file is not in memory */
  5399. if (de.file.is_directory) {
  5400. if (remove_directory(conn, path) == 0) {
  5401. ok = 0;
  5402. }
  5403. } else {
  5404. if (mg_remove(conn, path) == 0) {
  5405. ok = 0;
  5406. }
  5407. }
  5408. } else {
  5409. /* file is in memory. It can not be deleted. */
  5410. ok = 0;
  5411. }
  5412. }
  5413. (void)mg_closedir(dirp);
  5414. IGNORE_UNUSED_RESULT(rmdir(dir));
  5415. }
  5416. return ok;
  5417. }
  5418. #endif
  5419. struct dir_scan_data {
  5420. struct de *entries;
  5421. unsigned int num_entries;
  5422. unsigned int arr_size;
  5423. };
  5424. /* Behaves like realloc(), but frees original pointer on failure */
  5425. static void *
  5426. realloc2(void *ptr, size_t size)
  5427. {
  5428. void *new_ptr = mg_realloc(ptr, size);
  5429. if (new_ptr == NULL) {
  5430. mg_free(ptr);
  5431. }
  5432. return new_ptr;
  5433. }
  5434. static void
  5435. dir_scan_callback(struct de *de, void *data)
  5436. {
  5437. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5438. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5439. dsd->arr_size *= 2;
  5440. dsd->entries =
  5441. (struct de *)realloc2(dsd->entries,
  5442. dsd->arr_size * sizeof(dsd->entries[0]));
  5443. }
  5444. if (dsd->entries == NULL) {
  5445. /* TODO(lsm, low): propagate an error to the caller */
  5446. dsd->num_entries = 0;
  5447. } else {
  5448. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5449. dsd->entries[dsd->num_entries].file = de->file;
  5450. dsd->entries[dsd->num_entries].conn = de->conn;
  5451. dsd->num_entries++;
  5452. }
  5453. }
  5454. static void
  5455. handle_directory_request(struct mg_connection *conn, const char *dir)
  5456. {
  5457. unsigned int i;
  5458. int sort_direction;
  5459. struct dir_scan_data data = {NULL, 0, 128};
  5460. char date[64];
  5461. time_t curtime = time(NULL);
  5462. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5463. send_http_error(conn,
  5464. 500,
  5465. "Error: Cannot open directory\nopendir(%s): %s",
  5466. dir,
  5467. strerror(ERRNO));
  5468. return;
  5469. }
  5470. gmt_time_string(date, sizeof(date), &curtime);
  5471. if (!conn) {
  5472. return;
  5473. }
  5474. sort_direction = conn->request_info.query_string != NULL
  5475. && conn->request_info.query_string[1] == 'd'
  5476. ? 'a'
  5477. : 'd';
  5478. conn->must_close = 1;
  5479. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5480. send_static_cache_header(conn);
  5481. mg_printf(conn,
  5482. "Date: %s\r\n"
  5483. "Connection: close\r\n"
  5484. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5485. date);
  5486. conn->num_bytes_sent +=
  5487. mg_printf(conn,
  5488. "<html><head><title>Index of %s</title>"
  5489. "<style>th {text-align: left;}</style></head>"
  5490. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5491. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5492. "<th><a href=\"?d%c\">Modified</a></th>"
  5493. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5494. "<tr><td colspan=\"3\"><hr></td></tr>",
  5495. conn->request_info.local_uri,
  5496. conn->request_info.local_uri,
  5497. sort_direction,
  5498. sort_direction,
  5499. sort_direction);
  5500. /* Print first entry - link to a parent directory */
  5501. conn->num_bytes_sent +=
  5502. mg_printf(conn,
  5503. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5504. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5505. conn->request_info.local_uri,
  5506. "..",
  5507. "Parent directory",
  5508. "-",
  5509. "-");
  5510. /* Sort and print directory entries */
  5511. if (data.entries != NULL) {
  5512. qsort(data.entries,
  5513. (size_t)data.num_entries,
  5514. sizeof(data.entries[0]),
  5515. compare_dir_entries);
  5516. for (i = 0; i < data.num_entries; i++) {
  5517. print_dir_entry(&data.entries[i]);
  5518. mg_free(data.entries[i].file_name);
  5519. }
  5520. mg_free(data.entries);
  5521. }
  5522. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5523. conn->status_code = 200;
  5524. }
  5525. /* Send len bytes from the opened file to the client. */
  5526. static void
  5527. send_file_data(struct mg_connection *conn,
  5528. struct file *filep,
  5529. int64_t offset,
  5530. int64_t len)
  5531. {
  5532. char buf[MG_BUF_LEN];
  5533. int to_read, num_read, num_written;
  5534. int64_t size;
  5535. if (!filep || !conn) {
  5536. return;
  5537. }
  5538. /* Sanity check the offset */
  5539. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5540. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5541. if (len > 0 && filep->membuf != NULL && size > 0) {
  5542. /* file stored in memory */
  5543. if (len > size - offset) {
  5544. len = size - offset;
  5545. }
  5546. mg_write(conn, filep->membuf + offset, (size_t)len);
  5547. } else if (len > 0 && filep->fp != NULL) {
  5548. /* file stored on disk */
  5549. #if defined(__linux__)
  5550. /* sendfile is only available for Linux */
  5551. if (conn->throttle == 0 && conn->ssl == 0) {
  5552. off_t sf_offs = (off_t)offset;
  5553. ssize_t sf_sent;
  5554. int sf_file = fileno(filep->fp);
  5555. int loop_cnt = 0;
  5556. do {
  5557. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5558. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5559. size_t sf_tosend =
  5560. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5561. sf_sent =
  5562. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5563. if (sf_sent > 0) {
  5564. conn->num_bytes_sent += sf_sent;
  5565. len -= sf_sent;
  5566. offset += sf_sent;
  5567. } else if (loop_cnt == 0) {
  5568. /* This file can not be sent using sendfile.
  5569. * This might be the case for pseudo-files in the
  5570. * /sys/ and /proc/ file system.
  5571. * Use the regular user mode copy code instead. */
  5572. break;
  5573. } else if (sf_sent == 0) {
  5574. /* No error, but 0 bytes sent. May be EOF? */
  5575. return;
  5576. }
  5577. loop_cnt++;
  5578. } while ((len > 0) && (sf_sent >= 0));
  5579. if (sf_sent > 0) {
  5580. return; /* OK */
  5581. }
  5582. /* sf_sent<0 means error, thus fall back to the classic way */
  5583. /* This is always the case, if sf_file is not a "normal" file,
  5584. * e.g., for sending data from the output of a CGI process. */
  5585. offset = (int64_t)sf_offs;
  5586. }
  5587. #endif
  5588. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5589. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5590. send_http_error(
  5591. conn,
  5592. 500,
  5593. "%s",
  5594. "Error: Unable to access file at requested position.");
  5595. } else {
  5596. while (len > 0) {
  5597. /* Calculate how much to read from the file in the buffer */
  5598. to_read = sizeof(buf);
  5599. if ((int64_t)to_read > len) {
  5600. to_read = (int)len;
  5601. }
  5602. /* Read from file, exit the loop on error */
  5603. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5604. <= 0) {
  5605. break;
  5606. }
  5607. /* Send read bytes to the client, exit the loop on error */
  5608. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5609. != num_read) {
  5610. break;
  5611. }
  5612. /* Both read and were successful, adjust counters */
  5613. conn->num_bytes_sent += num_written;
  5614. len -= num_written;
  5615. }
  5616. }
  5617. }
  5618. }
  5619. static int
  5620. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5621. {
  5622. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5623. }
  5624. static void
  5625. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5626. {
  5627. if (filep != NULL && buf != NULL) {
  5628. mg_snprintf(NULL,
  5629. NULL, /* All calls to construct_etag use 64 byte buffer */
  5630. buf,
  5631. buf_len,
  5632. "\"%lx.%" INT64_FMT "\"",
  5633. (unsigned long)filep->last_modified,
  5634. filep->size);
  5635. }
  5636. }
  5637. static void
  5638. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5639. {
  5640. if (filep != NULL && filep->fp != NULL) {
  5641. #ifdef _WIN32
  5642. (void)conn; /* Unused. */
  5643. #else
  5644. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5645. mg_cry(conn,
  5646. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5647. __func__,
  5648. strerror(ERRNO));
  5649. }
  5650. #endif
  5651. }
  5652. }
  5653. static void
  5654. handle_static_file_request(struct mg_connection *conn,
  5655. const char *path,
  5656. struct file *filep,
  5657. const char *mime_type)
  5658. {
  5659. char date[64], lm[64], etag[64];
  5660. char range[128]; /* large enough, so there will be no overflow */
  5661. const char *msg = "OK", *hdr;
  5662. time_t curtime = time(NULL);
  5663. int64_t cl, r1, r2;
  5664. struct vec mime_vec;
  5665. int n, truncated;
  5666. char gz_path[PATH_MAX];
  5667. const char *encoding = "";
  5668. const char *cors1, *cors2, *cors3;
  5669. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5670. return;
  5671. }
  5672. if (mime_type == NULL) {
  5673. get_mime_type(conn->ctx, path, &mime_vec);
  5674. } else {
  5675. mime_vec.ptr = mime_type;
  5676. mime_vec.len = strlen(mime_type);
  5677. }
  5678. if (filep->size > INT64_MAX) {
  5679. send_http_error(conn,
  5680. 500,
  5681. "Error: File size is too large to send\n%" INT64_FMT,
  5682. filep->size);
  5683. }
  5684. cl = (int64_t)filep->size;
  5685. conn->status_code = 200;
  5686. range[0] = '\0';
  5687. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5688. * it's important to rewrite the filename after resolving
  5689. * the mime type from it, to preserve the actual file's type */
  5690. if (filep->gzipped) {
  5691. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5692. if (truncated) {
  5693. send_http_error(conn,
  5694. 500,
  5695. "Error: Path of zipped file too long (%s)",
  5696. path);
  5697. return;
  5698. }
  5699. path = gz_path;
  5700. encoding = "Content-Encoding: gzip\r\n";
  5701. }
  5702. if (!mg_fopen(conn, path, "rb", filep)) {
  5703. send_http_error(conn,
  5704. 500,
  5705. "Error: Cannot open file\nfopen(%s): %s",
  5706. path,
  5707. strerror(ERRNO));
  5708. return;
  5709. }
  5710. fclose_on_exec(filep, conn);
  5711. /* If Range: header specified, act accordingly */
  5712. r1 = r2 = 0;
  5713. hdr = mg_get_header(conn, "Range");
  5714. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5715. && r2 >= 0) {
  5716. /* actually, range requests don't play well with a pre-gzipped
  5717. * file (since the range is specified in the uncompressed space) */
  5718. if (filep->gzipped) {
  5719. send_http_error(
  5720. conn,
  5721. 501,
  5722. "%s",
  5723. "Error: Range requests in gzipped files are not supported");
  5724. mg_fclose(filep);
  5725. return;
  5726. }
  5727. conn->status_code = 206;
  5728. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5729. mg_snprintf(conn,
  5730. NULL, /* range buffer is big enough */
  5731. range,
  5732. sizeof(range),
  5733. "Content-Range: bytes "
  5734. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5735. r1,
  5736. r1 + cl - 1,
  5737. filep->size);
  5738. msg = "Partial Content";
  5739. }
  5740. hdr = mg_get_header(conn, "Origin");
  5741. if (hdr) {
  5742. /* Cross-origin resource sharing (CORS), see
  5743. * http://www.html5rocks.com/en/tutorials/cors/,
  5744. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5745. * preflight is not supported for files. */
  5746. cors1 = "Access-Control-Allow-Origin: ";
  5747. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5748. cors3 = "\r\n";
  5749. } else {
  5750. cors1 = cors2 = cors3 = "";
  5751. }
  5752. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5753. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5754. gmt_time_string(date, sizeof(date), &curtime);
  5755. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5756. construct_etag(etag, sizeof(etag), filep);
  5757. (void)mg_printf(conn,
  5758. "HTTP/1.1 %d %s\r\n"
  5759. "%s%s%s"
  5760. "Date: %s\r\n",
  5761. conn->status_code,
  5762. msg,
  5763. cors1,
  5764. cors2,
  5765. cors3,
  5766. date);
  5767. send_static_cache_header(conn);
  5768. (void)mg_printf(conn,
  5769. "Last-Modified: %s\r\n"
  5770. "Etag: %s\r\n"
  5771. "Content-Type: %.*s\r\n"
  5772. "Content-Length: %" INT64_FMT "\r\n"
  5773. "Connection: %s\r\n"
  5774. "Accept-Ranges: bytes\r\n"
  5775. "%s%s\r\n",
  5776. lm,
  5777. etag,
  5778. (int)mime_vec.len,
  5779. mime_vec.ptr,
  5780. cl,
  5781. suggest_connection_header(conn),
  5782. range,
  5783. encoding);
  5784. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5785. send_file_data(conn, filep, r1, cl);
  5786. }
  5787. mg_fclose(filep);
  5788. }
  5789. static void
  5790. handle_not_modified_static_file_request(struct mg_connection *conn,
  5791. struct file *filep)
  5792. {
  5793. char date[64], lm[64], etag[64];
  5794. time_t curtime = time(NULL);
  5795. if (conn == NULL || filep == NULL) {
  5796. return;
  5797. }
  5798. conn->status_code = 304;
  5799. gmt_time_string(date, sizeof(date), &curtime);
  5800. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5801. construct_etag(etag, sizeof(etag), filep);
  5802. (void)mg_printf(conn,
  5803. "HTTP/1.1 %d %s\r\n"
  5804. "Date: %s\r\n",
  5805. conn->status_code,
  5806. mg_get_response_code_text(conn, conn->status_code),
  5807. date);
  5808. send_static_cache_header(conn);
  5809. (void)mg_printf(conn,
  5810. "Last-Modified: %s\r\n"
  5811. "Etag: %s\r\n"
  5812. "Connection: %s\r\n"
  5813. "\r\n",
  5814. lm,
  5815. etag,
  5816. suggest_connection_header(conn));
  5817. }
  5818. void
  5819. mg_send_file(struct mg_connection *conn, const char *path)
  5820. {
  5821. mg_send_mime_file(conn, path, NULL);
  5822. }
  5823. void
  5824. mg_send_mime_file(struct mg_connection *conn,
  5825. const char *path,
  5826. const char *mime_type)
  5827. {
  5828. struct file file = STRUCT_FILE_INITIALIZER;
  5829. if (mg_stat(conn, path, &file)) {
  5830. if (file.is_directory) {
  5831. if (!conn) {
  5832. return;
  5833. }
  5834. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5835. "yes")) {
  5836. handle_directory_request(conn, path);
  5837. } else {
  5838. send_http_error(conn,
  5839. 403,
  5840. "%s",
  5841. "Error: Directory listing denied");
  5842. }
  5843. } else {
  5844. handle_static_file_request(conn, path, &file, mime_type);
  5845. }
  5846. } else {
  5847. send_http_error(conn, 404, "%s", "Error: File not found");
  5848. }
  5849. }
  5850. /* For a given PUT path, create all intermediate subdirectories.
  5851. * Return 0 if the path itself is a directory.
  5852. * Return 1 if the path leads to a file.
  5853. * Return -1 for if the path is too long.
  5854. * Return -2 if path can not be created.
  5855. */
  5856. static int
  5857. put_dir(struct mg_connection *conn, const char *path)
  5858. {
  5859. char buf[PATH_MAX];
  5860. const char *s, *p;
  5861. struct file file = STRUCT_FILE_INITIALIZER;
  5862. size_t len;
  5863. int res = 1;
  5864. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5865. len = (size_t)(p - path);
  5866. if (len >= sizeof(buf)) {
  5867. /* path too long */
  5868. res = -1;
  5869. break;
  5870. }
  5871. memcpy(buf, path, len);
  5872. buf[len] = '\0';
  5873. /* Try to create intermediate directory */
  5874. DEBUG_TRACE("mkdir(%s)", buf);
  5875. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  5876. /* path does not exixt and can not be created */
  5877. res = -2;
  5878. break;
  5879. }
  5880. /* Is path itself a directory? */
  5881. if (p[1] == '\0') {
  5882. res = 0;
  5883. }
  5884. }
  5885. return res;
  5886. }
  5887. static void
  5888. remove_bad_file(const struct mg_connection *conn, const char *path)
  5889. {
  5890. int r = mg_remove(conn, path);
  5891. if (r != 0) {
  5892. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  5893. }
  5894. }
  5895. long long
  5896. mg_store_body(struct mg_connection *conn, const char *path)
  5897. {
  5898. char buf[MG_BUF_LEN];
  5899. long long len = 0;
  5900. int ret, n;
  5901. struct file fi;
  5902. if (conn->consumed_content != 0) {
  5903. mg_cry(conn, "%s: Contents already consumed", __func__);
  5904. return -11;
  5905. }
  5906. ret = put_dir(conn, path);
  5907. if (ret < 0) {
  5908. /* -1 for path too long,
  5909. * -2 for path can not be created. */
  5910. return ret;
  5911. }
  5912. if (ret != 1) {
  5913. /* Return 0 means, path itself is a directory. */
  5914. return 0;
  5915. }
  5916. if (mg_fopen(conn, path, "w", &fi) == 0) {
  5917. return -12;
  5918. }
  5919. ret = mg_read(conn, buf, sizeof(buf));
  5920. while (ret > 0) {
  5921. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  5922. if (n != ret) {
  5923. mg_fclose(&fi);
  5924. remove_bad_file(conn, path);
  5925. return -13;
  5926. }
  5927. ret = mg_read(conn, buf, sizeof(buf));
  5928. }
  5929. /* TODO: mg_fclose should return an error,
  5930. * and every caller should check and handle it. */
  5931. if (fclose(fi.fp) != 0) {
  5932. remove_bad_file(conn, path);
  5933. return -14;
  5934. }
  5935. return len;
  5936. }
  5937. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5938. * where parsing stopped. */
  5939. static void
  5940. parse_http_headers(char **buf, struct mg_request_info *ri)
  5941. {
  5942. int i;
  5943. if (!ri) {
  5944. return;
  5945. }
  5946. ri->num_headers = 0;
  5947. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5948. char *dp = *buf;
  5949. while ((*dp != ':') && (*dp >= 32) && (*dp <= 126)) {
  5950. dp++;
  5951. }
  5952. if ((dp == *buf) || (*dp != ':')) {
  5953. /* This is not a valid field. */
  5954. break;
  5955. } else {
  5956. /* (*dp == ':') */
  5957. *dp = 0;
  5958. ri->http_headers[i].name = *buf;
  5959. do {
  5960. dp++;
  5961. } while (*dp == ' ');
  5962. ri->http_headers[i].value = dp;
  5963. *buf = dp + strcspn(dp, "\r\n");
  5964. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  5965. *buf = NULL;
  5966. }
  5967. }
  5968. ri->num_headers = i + 1;
  5969. if (*buf) {
  5970. (*buf)[0] = 0;
  5971. (*buf)[1] = 0;
  5972. *buf += 2;
  5973. } else {
  5974. *buf = dp;
  5975. break;
  5976. }
  5977. if ((*buf)[0] == '\r') {
  5978. /* This is the end of the header */
  5979. break;
  5980. }
  5981. }
  5982. }
  5983. static int
  5984. is_valid_http_method(const char *method)
  5985. {
  5986. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5987. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5988. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5989. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5990. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5991. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5992. /* TRACE method (RFC 2616) is not supported for security reasons */
  5993. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5994. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5995. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5996. /* Unsupported WEBDAV Methods: */
  5997. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5998. /* + 11 methods from RFC 3253 */
  5999. /* ORDERPATCH (RFC 3648) */
  6000. /* ACL (RFC 3744) */
  6001. /* SEARCH (RFC 5323) */
  6002. /* + MicroSoft extensions
  6003. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6004. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6005. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6006. }
  6007. /* Parse HTTP request, fill in mg_request_info structure.
  6008. * This function modifies the buffer by NUL-terminating
  6009. * HTTP request components, header names and header values. */
  6010. static int
  6011. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6012. {
  6013. int is_request, request_length;
  6014. if (!ri) {
  6015. return 0;
  6016. }
  6017. request_length = get_request_len(buf, len);
  6018. if (request_length > 0) {
  6019. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6020. * remote_port */
  6021. ri->remote_user = ri->request_method = ri->request_uri =
  6022. ri->http_version = NULL;
  6023. ri->num_headers = 0;
  6024. buf[request_length - 1] = '\0';
  6025. /* RFC says that all initial whitespaces should be ingored */
  6026. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6027. buf++;
  6028. }
  6029. ri->request_method = skip(&buf, " ");
  6030. ri->request_uri = skip(&buf, " ");
  6031. ri->http_version = skip(&buf, "\r\n");
  6032. /* HTTP message could be either HTTP request or HTTP response, e.g.
  6033. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  6034. is_request = is_valid_http_method(ri->request_method);
  6035. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6036. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6037. request_length = -1;
  6038. } else {
  6039. if (is_request) {
  6040. ri->http_version += 5;
  6041. }
  6042. parse_http_headers(&buf, ri);
  6043. }
  6044. }
  6045. return request_length;
  6046. }
  6047. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6048. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6049. * buffer (which marks the end of HTTP request). Buffer buf may already
  6050. * have some data. The length of the data is stored in nread.
  6051. * Upon every read operation, increase nread by the number of bytes read. */
  6052. static int
  6053. read_request(FILE *fp,
  6054. struct mg_connection *conn,
  6055. char *buf,
  6056. int bufsiz,
  6057. int *nread)
  6058. {
  6059. int request_len, n = 0;
  6060. struct timespec last_action_time;
  6061. double request_timeout;
  6062. if (!conn) {
  6063. return 0;
  6064. }
  6065. memset(&last_action_time, 0, sizeof(last_action_time));
  6066. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6067. /* value of request_timeout is in seconds, config in milliseconds */
  6068. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6069. } else {
  6070. request_timeout = -1.0;
  6071. }
  6072. request_len = get_request_len(buf, *nread);
  6073. /* first time reading from this connection */
  6074. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6075. while (
  6076. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6077. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6078. <= request_timeout) || (request_timeout < 0))
  6079. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6080. > 0)) {
  6081. *nread += n;
  6082. /* assert(*nread <= bufsiz); */
  6083. if (*nread > bufsiz) {
  6084. return -2;
  6085. }
  6086. request_len = get_request_len(buf, *nread);
  6087. if (request_timeout > 0.0) {
  6088. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6089. }
  6090. }
  6091. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  6092. }
  6093. #if !defined(NO_FILES)
  6094. /* For given directory path, substitute it to valid index file.
  6095. * Return 1 if index file has been found, 0 if not found.
  6096. * If the file is found, it's stats is returned in stp. */
  6097. static int
  6098. substitute_index_file(struct mg_connection *conn,
  6099. char *path,
  6100. size_t path_len,
  6101. struct file *filep)
  6102. {
  6103. if (conn && conn->ctx) {
  6104. const char *list = conn->ctx->config[INDEX_FILES];
  6105. struct file file = STRUCT_FILE_INITIALIZER;
  6106. struct vec filename_vec;
  6107. size_t n = strlen(path);
  6108. int found = 0;
  6109. /* The 'path' given to us points to the directory. Remove all trailing
  6110. * directory separator characters from the end of the path, and
  6111. * then append single directory separator character. */
  6112. while (n > 0 && path[n - 1] == '/') {
  6113. n--;
  6114. }
  6115. path[n] = '/';
  6116. /* Traverse index files list. For each entry, append it to the given
  6117. * path and see if the file exists. If it exists, break the loop */
  6118. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6119. /* Ignore too long entries that may overflow path buffer */
  6120. if (filename_vec.len > path_len - (n + 2)) {
  6121. continue;
  6122. }
  6123. /* Prepare full path to the index file */
  6124. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6125. /* Does it exist? */
  6126. if (mg_stat(conn, path, &file)) {
  6127. /* Yes it does, break the loop */
  6128. *filep = file;
  6129. found = 1;
  6130. break;
  6131. }
  6132. }
  6133. /* If no index file exists, restore directory path */
  6134. if (!found) {
  6135. path[n] = '\0';
  6136. }
  6137. return found;
  6138. }
  6139. return 0;
  6140. }
  6141. #endif
  6142. #if !defined(NO_CACHING)
  6143. /* Return True if we should reply 304 Not Modified. */
  6144. static int
  6145. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6146. {
  6147. char etag[64];
  6148. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6149. const char *inm = mg_get_header(conn, "If-None-Match");
  6150. construct_etag(etag, sizeof(etag), filep);
  6151. if (!filep) {
  6152. return 0;
  6153. }
  6154. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6155. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6156. }
  6157. #endif /* !NO_CACHING */
  6158. #if !defined(NO_CGI) || !defined(NO_FILES)
  6159. static int
  6160. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6161. {
  6162. const char *expect, *body;
  6163. char buf[MG_BUF_LEN];
  6164. int to_read, nread, success = 0;
  6165. int64_t buffered_len;
  6166. double timeout = -1.0;
  6167. if (!conn) {
  6168. return 0;
  6169. }
  6170. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6171. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6172. }
  6173. expect = mg_get_header(conn, "Expect");
  6174. /* assert(fp != NULL); */
  6175. if (!fp) {
  6176. send_http_error(conn, 500, "%s", "Error: NULL File");
  6177. return 0;
  6178. }
  6179. if (conn->content_len == -1 && !conn->is_chunked) {
  6180. /* Content length is not specified by the client. */
  6181. send_http_error(conn,
  6182. 411,
  6183. "%s",
  6184. "Error: Client did not specify content length");
  6185. } else if ((expect != NULL)
  6186. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6187. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6188. send_http_error(conn,
  6189. 417,
  6190. "Error: Can not fulfill expectation %s",
  6191. expect);
  6192. } else {
  6193. if (expect != NULL) {
  6194. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6195. conn->status_code = 100;
  6196. } else {
  6197. conn->status_code = 200;
  6198. }
  6199. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6200. - conn->consumed_content;
  6201. /* assert(buffered_len >= 0); */
  6202. /* assert(conn->consumed_content == 0); */
  6203. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6204. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6205. return 0;
  6206. }
  6207. if (buffered_len > 0) {
  6208. if ((int64_t)buffered_len > conn->content_len) {
  6209. buffered_len = (int)conn->content_len;
  6210. }
  6211. body = conn->buf + conn->request_len + conn->consumed_content;
  6212. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6213. conn->consumed_content += buffered_len;
  6214. }
  6215. nread = 0;
  6216. while (conn->consumed_content < conn->content_len) {
  6217. to_read = sizeof(buf);
  6218. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6219. to_read = (int)(conn->content_len - conn->consumed_content);
  6220. }
  6221. nread = pull(NULL, conn, buf, to_read, timeout);
  6222. if (nread <= 0
  6223. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6224. break;
  6225. }
  6226. conn->consumed_content += nread;
  6227. }
  6228. if (conn->consumed_content == conn->content_len) {
  6229. success = (nread >= 0);
  6230. }
  6231. /* Each error code path in this function must send an error */
  6232. if (!success) {
  6233. /* NOTE: Maybe some data has already been sent. */
  6234. /* TODO (low): If some data has been sent, a correct error
  6235. * reply can no longer be sent, so just close the connection */
  6236. send_http_error(conn, 500, "%s", "");
  6237. }
  6238. }
  6239. return success;
  6240. }
  6241. #endif
  6242. #if !defined(NO_CGI)
  6243. /* This structure helps to create an environment for the spawned CGI program.
  6244. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6245. * last element must be NULL.
  6246. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6247. * strings must reside in a contiguous buffer. The end of the buffer is
  6248. * marked by two '\0' characters.
  6249. * We satisfy both worlds: we create an envp array (which is vars), all
  6250. * entries are actually pointers inside buf. */
  6251. struct cgi_environment {
  6252. struct mg_connection *conn;
  6253. /* Data block */
  6254. char *buf; /* Environment buffer */
  6255. size_t buflen; /* Space available in buf */
  6256. size_t bufused; /* Space taken in buf */
  6257. /* Index block */
  6258. char **var; /* char **envp */
  6259. size_t varlen; /* Number of variables available in var */
  6260. size_t varused; /* Number of variables stored in var */
  6261. };
  6262. static void addenv(struct cgi_environment *env,
  6263. PRINTF_FORMAT_STRING(const char *fmt),
  6264. ...) PRINTF_ARGS(2, 3);
  6265. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6266. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6267. static void
  6268. addenv(struct cgi_environment *env, const char *fmt, ...)
  6269. {
  6270. size_t n, space;
  6271. int truncated;
  6272. char *added;
  6273. va_list ap;
  6274. /* Calculate how much space is left in the buffer */
  6275. space = (env->buflen - env->bufused);
  6276. /* Calculate an estimate for the required space */
  6277. n = strlen(fmt) + 2 + 128;
  6278. do {
  6279. if (space <= n) {
  6280. /* Allocate new buffer */
  6281. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6282. added = (char *)mg_realloc(env->buf, n);
  6283. if (!added) {
  6284. /* Out of memory */
  6285. mg_cry(env->conn,
  6286. "%s: Cannot allocate memory for CGI variable [%s]",
  6287. __func__,
  6288. fmt);
  6289. return;
  6290. }
  6291. env->buf = added;
  6292. env->buflen = n;
  6293. space = (env->buflen - env->bufused);
  6294. }
  6295. /* Make a pointer to the free space int the buffer */
  6296. added = env->buf + env->bufused;
  6297. /* Copy VARIABLE=VALUE\0 string into the free space */
  6298. va_start(ap, fmt);
  6299. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6300. va_end(ap);
  6301. /* Do not add truncated strings to the environment */
  6302. if (truncated) {
  6303. /* Reallocate the buffer */
  6304. space = 0;
  6305. n = 1;
  6306. }
  6307. } while (truncated);
  6308. /* Calculate number of bytes added to the environment */
  6309. n = strlen(added) + 1;
  6310. env->bufused += n;
  6311. /* Now update the variable index */
  6312. space = (env->varlen - env->varused);
  6313. if (space < 2) {
  6314. mg_cry(env->conn,
  6315. "%s: Cannot register CGI variable [%s]",
  6316. __func__,
  6317. fmt);
  6318. return;
  6319. }
  6320. /* Append a pointer to the added string into the envp array */
  6321. env->var[env->varused] = added;
  6322. env->varused++;
  6323. }
  6324. static void
  6325. prepare_cgi_environment(struct mg_connection *conn,
  6326. const char *prog,
  6327. struct cgi_environment *env)
  6328. {
  6329. const char *s;
  6330. struct vec var_vec;
  6331. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6332. int i, truncated;
  6333. if (conn == NULL || prog == NULL || env == NULL) {
  6334. return;
  6335. }
  6336. env->conn = conn;
  6337. env->buflen = CGI_ENVIRONMENT_SIZE;
  6338. env->bufused = 0;
  6339. env->buf = (char *)mg_malloc(env->buflen);
  6340. env->varlen = MAX_CGI_ENVIR_VARS;
  6341. env->varused = 0;
  6342. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6343. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6344. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6345. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6346. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6347. /* Prepare the environment block */
  6348. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6349. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6350. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6351. #if defined(USE_IPV6)
  6352. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6353. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6354. } else
  6355. #endif
  6356. {
  6357. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6358. }
  6359. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6360. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6361. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6362. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6363. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6364. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6365. /* SCRIPT_NAME */
  6366. addenv(env,
  6367. "SCRIPT_NAME=%.*s",
  6368. (int)strlen(conn->request_info.local_uri)
  6369. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6370. conn->request_info.local_uri);
  6371. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6372. if (conn->path_info == NULL) {
  6373. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6374. } else {
  6375. addenv(env,
  6376. "PATH_TRANSLATED=%s%s",
  6377. conn->ctx->config[DOCUMENT_ROOT],
  6378. conn->path_info);
  6379. }
  6380. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  6381. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6382. addenv(env, "CONTENT_TYPE=%s", s);
  6383. }
  6384. if (conn->request_info.query_string != NULL) {
  6385. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6386. }
  6387. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6388. addenv(env, "CONTENT_LENGTH=%s", s);
  6389. }
  6390. if ((s = getenv("PATH")) != NULL) {
  6391. addenv(env, "PATH=%s", s);
  6392. }
  6393. if (conn->path_info != NULL) {
  6394. addenv(env, "PATH_INFO=%s", conn->path_info);
  6395. }
  6396. if (conn->status_code > 0) {
  6397. /* CGI error handler should show the status code */
  6398. addenv(env, "STATUS=%d", conn->status_code);
  6399. }
  6400. #if defined(_WIN32)
  6401. if ((s = getenv("COMSPEC")) != NULL) {
  6402. addenv(env, "COMSPEC=%s", s);
  6403. }
  6404. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6405. addenv(env, "SYSTEMROOT=%s", s);
  6406. }
  6407. if ((s = getenv("SystemDrive")) != NULL) {
  6408. addenv(env, "SystemDrive=%s", s);
  6409. }
  6410. if ((s = getenv("ProgramFiles")) != NULL) {
  6411. addenv(env, "ProgramFiles=%s", s);
  6412. }
  6413. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6414. addenv(env, "ProgramFiles(x86)=%s", s);
  6415. }
  6416. #else
  6417. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6418. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6419. }
  6420. #endif /* _WIN32 */
  6421. if ((s = getenv("PERLLIB")) != NULL) {
  6422. addenv(env, "PERLLIB=%s", s);
  6423. }
  6424. if (conn->request_info.remote_user != NULL) {
  6425. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6426. addenv(env, "%s", "AUTH_TYPE=Digest");
  6427. }
  6428. /* Add all headers as HTTP_* variables */
  6429. for (i = 0; i < conn->request_info.num_headers; i++) {
  6430. (void)mg_snprintf(conn,
  6431. &truncated,
  6432. http_var_name,
  6433. sizeof(http_var_name),
  6434. "HTTP_%s",
  6435. conn->request_info.http_headers[i].name);
  6436. if (truncated) {
  6437. mg_cry(conn,
  6438. "%s: HTTP header variable too long [%s]",
  6439. __func__,
  6440. conn->request_info.http_headers[i].name);
  6441. continue;
  6442. }
  6443. /* Convert variable name into uppercase, and change - to _ */
  6444. for (p = http_var_name; *p != '\0'; p++) {
  6445. if (*p == '-') {
  6446. *p = '_';
  6447. }
  6448. *p = (char)toupper(*(unsigned char *)p);
  6449. }
  6450. addenv(env,
  6451. "%s=%s",
  6452. http_var_name,
  6453. conn->request_info.http_headers[i].value);
  6454. }
  6455. /* Add user-specified variables */
  6456. s = conn->ctx->config[CGI_ENVIRONMENT];
  6457. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6458. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6459. }
  6460. env->var[env->varused] = NULL;
  6461. env->buf[env->bufused] = '\0';
  6462. }
  6463. static void
  6464. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6465. {
  6466. char *buf;
  6467. size_t buflen;
  6468. int headers_len, data_len, i, truncated;
  6469. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6470. const char *status, *status_text, *connection_state;
  6471. char *pbuf, dir[PATH_MAX], *p;
  6472. struct mg_request_info ri;
  6473. struct cgi_environment blk;
  6474. FILE *in = NULL, *out = NULL, *err = NULL;
  6475. struct file fout = STRUCT_FILE_INITIALIZER;
  6476. pid_t pid = (pid_t)-1;
  6477. if (conn == NULL) {
  6478. return;
  6479. }
  6480. buf = NULL;
  6481. buflen = 16384;
  6482. prepare_cgi_environment(conn, prog, &blk);
  6483. /* CGI must be executed in its own directory. 'dir' must point to the
  6484. * directory containing executable program, 'p' must point to the
  6485. * executable program name relative to 'dir'. */
  6486. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6487. if (truncated) {
  6488. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6489. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6490. goto done;
  6491. }
  6492. if ((p = strrchr(dir, '/')) != NULL) {
  6493. *p++ = '\0';
  6494. } else {
  6495. dir[0] = '.', dir[1] = '\0';
  6496. p = (char *)prog;
  6497. }
  6498. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6499. status = strerror(ERRNO);
  6500. mg_cry(conn,
  6501. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6502. prog,
  6503. status);
  6504. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6505. goto done;
  6506. }
  6507. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6508. if (pid == (pid_t)-1) {
  6509. status = strerror(ERRNO);
  6510. mg_cry(conn,
  6511. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6512. prog,
  6513. status);
  6514. send_http_error(conn,
  6515. 500,
  6516. "Error: Cannot spawn CGI process [%s]: %s",
  6517. prog,
  6518. status);
  6519. goto done;
  6520. }
  6521. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6522. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6523. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6524. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6525. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6526. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6527. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6528. /* Parent closes only one side of the pipes.
  6529. * If we don't mark them as closed, close() attempt before
  6530. * return from this function throws an exception on Windows.
  6531. * Windows does not like when closed descriptor is closed again. */
  6532. (void)close(fdin[0]);
  6533. (void)close(fdout[1]);
  6534. (void)close(fderr[1]);
  6535. fdin[0] = fdout[1] = fderr[1] = -1;
  6536. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6537. status = strerror(ERRNO);
  6538. mg_cry(conn,
  6539. "Error: CGI program \"%s\": Can not open stdin: %s",
  6540. prog,
  6541. status);
  6542. send_http_error(conn,
  6543. 500,
  6544. "Error: CGI can not open fdin\nfopen: %s",
  6545. status);
  6546. goto done;
  6547. }
  6548. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6549. status = strerror(ERRNO);
  6550. mg_cry(conn,
  6551. "Error: CGI program \"%s\": Can not open stdout: %s",
  6552. prog,
  6553. status);
  6554. send_http_error(conn,
  6555. 500,
  6556. "Error: CGI can not open fdout\nfopen: %s",
  6557. status);
  6558. goto done;
  6559. }
  6560. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6561. status = strerror(ERRNO);
  6562. mg_cry(conn,
  6563. "Error: CGI program \"%s\": Can not open stderr: %s",
  6564. prog,
  6565. status);
  6566. send_http_error(conn,
  6567. 500,
  6568. "Error: CGI can not open fdout\nfopen: %s",
  6569. status);
  6570. goto done;
  6571. }
  6572. setbuf(in, NULL);
  6573. setbuf(out, NULL);
  6574. setbuf(err, NULL);
  6575. fout.fp = out;
  6576. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6577. /* This is a POST/PUT request, or another request with body data. */
  6578. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6579. /* Error sending the body data */
  6580. mg_cry(conn,
  6581. "Error: CGI program \"%s\": Forward body data failed",
  6582. prog);
  6583. goto done;
  6584. }
  6585. }
  6586. /* Close so child gets an EOF. */
  6587. fclose(in);
  6588. in = NULL;
  6589. fdin[1] = -1;
  6590. /* Now read CGI reply into a buffer. We need to set correct
  6591. * status code, thus we need to see all HTTP headers first.
  6592. * Do not send anything back to client, until we buffer in all
  6593. * HTTP headers. */
  6594. data_len = 0;
  6595. buf = (char *)mg_malloc(buflen);
  6596. if (buf == NULL) {
  6597. send_http_error(conn,
  6598. 500,
  6599. "Error: Not enough memory for CGI buffer (%u bytes)",
  6600. (unsigned int)buflen);
  6601. mg_cry(conn,
  6602. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6603. "bytes)",
  6604. prog,
  6605. (unsigned int)buflen);
  6606. goto done;
  6607. }
  6608. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6609. if (headers_len <= 0) {
  6610. /* Could not parse the CGI response. Check if some error message on
  6611. * stderr. */
  6612. i = pull_all(err, conn, buf, (int)buflen);
  6613. if (i > 0) {
  6614. mg_cry(conn,
  6615. "Error: CGI program \"%s\" sent error "
  6616. "message: [%.*s]",
  6617. prog,
  6618. i,
  6619. buf);
  6620. send_http_error(conn,
  6621. 500,
  6622. "Error: CGI program \"%s\" sent error "
  6623. "message: [%.*s]",
  6624. prog,
  6625. i,
  6626. buf);
  6627. } else {
  6628. mg_cry(conn,
  6629. "Error: CGI program sent malformed or too big "
  6630. "(>%u bytes) HTTP headers: [%.*s]",
  6631. (unsigned)buflen,
  6632. data_len,
  6633. buf);
  6634. send_http_error(conn,
  6635. 500,
  6636. "Error: CGI program sent malformed or too big "
  6637. "(>%u bytes) HTTP headers: [%.*s]",
  6638. (unsigned)buflen,
  6639. data_len,
  6640. buf);
  6641. }
  6642. goto done;
  6643. }
  6644. pbuf = buf;
  6645. buf[headers_len - 1] = '\0';
  6646. parse_http_headers(&pbuf, &ri);
  6647. /* Make up and send the status line */
  6648. status_text = "OK";
  6649. if ((status = get_header(&ri, "Status")) != NULL) {
  6650. conn->status_code = atoi(status);
  6651. status_text = status;
  6652. while (isdigit(*(const unsigned char *)status_text)
  6653. || *status_text == ' ') {
  6654. status_text++;
  6655. }
  6656. } else if (get_header(&ri, "Location") != NULL) {
  6657. conn->status_code = 302;
  6658. } else {
  6659. conn->status_code = 200;
  6660. }
  6661. connection_state = get_header(&ri, "Connection");
  6662. if (!header_has_option(connection_state, "keep-alive")) {
  6663. conn->must_close = 1;
  6664. }
  6665. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6666. /* Send headers */
  6667. for (i = 0; i < ri.num_headers; i++) {
  6668. mg_printf(conn,
  6669. "%s: %s\r\n",
  6670. ri.http_headers[i].name,
  6671. ri.http_headers[i].value);
  6672. }
  6673. mg_write(conn, "\r\n", 2);
  6674. /* Send chunk of data that may have been read after the headers */
  6675. conn->num_bytes_sent +=
  6676. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6677. /* Read the rest of CGI output and send to the client */
  6678. send_file_data(conn, &fout, 0, INT64_MAX);
  6679. done:
  6680. mg_free(blk.var);
  6681. mg_free(blk.buf);
  6682. if (pid != (pid_t)-1) {
  6683. kill(pid, SIGKILL);
  6684. #if !defined(_WIN32)
  6685. {
  6686. int st;
  6687. while (waitpid(pid, &st, 0) != -1)
  6688. ; /* clean zombies */
  6689. }
  6690. #endif
  6691. }
  6692. if (fdin[0] != -1) {
  6693. close(fdin[0]);
  6694. }
  6695. if (fdout[1] != -1) {
  6696. close(fdout[1]);
  6697. }
  6698. if (in != NULL) {
  6699. fclose(in);
  6700. } else if (fdin[1] != -1) {
  6701. close(fdin[1]);
  6702. }
  6703. if (out != NULL) {
  6704. fclose(out);
  6705. } else if (fdout[0] != -1) {
  6706. close(fdout[0]);
  6707. }
  6708. if (err != NULL) {
  6709. fclose(err);
  6710. } else if (fderr[0] != -1) {
  6711. close(fderr[0]);
  6712. }
  6713. if (buf != NULL) {
  6714. mg_free(buf);
  6715. }
  6716. }
  6717. #endif /* !NO_CGI */
  6718. #if !defined(NO_FILES)
  6719. static void
  6720. mkcol(struct mg_connection *conn, const char *path)
  6721. {
  6722. int rc, body_len;
  6723. struct de de;
  6724. char date[64];
  6725. time_t curtime = time(NULL);
  6726. if (conn == NULL) {
  6727. return;
  6728. }
  6729. /* TODO (mid): Check the send_http_error situations in this function */
  6730. memset(&de.file, 0, sizeof(de.file));
  6731. if (!mg_stat(conn, path, &de.file)) {
  6732. mg_cry(conn,
  6733. "%s: mg_stat(%s) failed: %s",
  6734. __func__,
  6735. path,
  6736. strerror(ERRNO));
  6737. }
  6738. if (de.file.last_modified) {
  6739. /* TODO (high): This check does not seem to make any sense ! */
  6740. send_http_error(
  6741. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6742. return;
  6743. }
  6744. body_len = conn->data_len - conn->request_len;
  6745. if (body_len > 0) {
  6746. send_http_error(
  6747. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6748. return;
  6749. }
  6750. rc = mg_mkdir(conn, path, 0755);
  6751. if (rc == 0) {
  6752. conn->status_code = 201;
  6753. gmt_time_string(date, sizeof(date), &curtime);
  6754. mg_printf(conn,
  6755. "HTTP/1.1 %d Created\r\n"
  6756. "Date: %s\r\n",
  6757. conn->status_code,
  6758. date);
  6759. send_static_cache_header(conn);
  6760. mg_printf(conn,
  6761. "Content-Length: 0\r\n"
  6762. "Connection: %s\r\n\r\n",
  6763. suggest_connection_header(conn));
  6764. } else if (rc == -1) {
  6765. if (errno == EEXIST) {
  6766. send_http_error(
  6767. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6768. } else if (errno == EACCES) {
  6769. send_http_error(
  6770. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6771. } else if (errno == ENOENT) {
  6772. send_http_error(
  6773. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6774. } else {
  6775. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6776. }
  6777. }
  6778. }
  6779. static void
  6780. put_file(struct mg_connection *conn, const char *path)
  6781. {
  6782. struct file file = STRUCT_FILE_INITIALIZER;
  6783. const char *range;
  6784. int64_t r1, r2;
  6785. int rc;
  6786. char date[64];
  6787. time_t curtime = time(NULL);
  6788. if (conn == NULL) {
  6789. return;
  6790. }
  6791. if (mg_stat(conn, path, &file)) {
  6792. /* File already exists */
  6793. conn->status_code = 200;
  6794. if (file.is_directory) {
  6795. /* This is an already existing directory,
  6796. * so there is nothing to do for the server. */
  6797. rc = 0;
  6798. } else {
  6799. /* File exists and is not a directory. */
  6800. /* Can it be replaced? */
  6801. if (file.membuf != NULL) {
  6802. /* This is an "in-memory" file, that can not be replaced */
  6803. send_http_error(
  6804. conn,
  6805. 405,
  6806. "Error: Put not possible\nReplacing %s is not supported",
  6807. path);
  6808. return;
  6809. }
  6810. /* Check if the server may write this file */
  6811. if (access(path, W_OK) == 0) {
  6812. /* Access granted */
  6813. conn->status_code = 200;
  6814. rc = 1;
  6815. } else {
  6816. send_http_error(
  6817. conn,
  6818. 403,
  6819. "Error: Put not possible\nReplacing %s is not allowed",
  6820. path);
  6821. return;
  6822. }
  6823. }
  6824. } else {
  6825. /* File should be created */
  6826. conn->status_code = 201;
  6827. rc = put_dir(conn, path);
  6828. }
  6829. if (rc == 0) {
  6830. /* put_dir returns 0 if path is a directory */
  6831. gmt_time_string(date, sizeof(date), &curtime);
  6832. mg_printf(conn,
  6833. "HTTP/1.1 %d %s\r\n",
  6834. conn->status_code,
  6835. mg_get_response_code_text(NULL, conn->status_code));
  6836. send_no_cache_header(conn);
  6837. mg_printf(conn,
  6838. "Date: %s\r\n"
  6839. "Content-Length: 0\r\n"
  6840. "Connection: %s\r\n\r\n",
  6841. date,
  6842. suggest_connection_header(conn));
  6843. /* Request to create a directory has been fulfilled successfully.
  6844. * No need to put a file. */
  6845. return;
  6846. }
  6847. if (rc == -1) {
  6848. /* put_dir returns -1 if the path is too long */
  6849. send_http_error(conn,
  6850. 414,
  6851. "Error: Path too long\nput_dir(%s): %s",
  6852. path,
  6853. strerror(ERRNO));
  6854. return;
  6855. }
  6856. if (rc == -2) {
  6857. /* put_dir returns -2 if the directory can not be created */
  6858. send_http_error(conn,
  6859. 500,
  6860. "Error: Can not create directory\nput_dir(%s): %s",
  6861. path,
  6862. strerror(ERRNO));
  6863. return;
  6864. }
  6865. /* A file should be created or overwritten. */
  6866. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6867. mg_fclose(&file);
  6868. send_http_error(conn,
  6869. 500,
  6870. "Error: Can not create file\nfopen(%s): %s",
  6871. path,
  6872. strerror(ERRNO));
  6873. return;
  6874. }
  6875. fclose_on_exec(&file, conn);
  6876. range = mg_get_header(conn, "Content-Range");
  6877. r1 = r2 = 0;
  6878. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6879. conn->status_code = 206; /* Partial content */
  6880. fseeko(file.fp, r1, SEEK_SET);
  6881. }
  6882. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6883. /* forward_body_data failed.
  6884. * The error code has already been sent to the client,
  6885. * and conn->status_code is already set. */
  6886. mg_fclose(&file);
  6887. return;
  6888. }
  6889. gmt_time_string(date, sizeof(date), &curtime);
  6890. mg_printf(conn,
  6891. "HTTP/1.1 %d %s\r\n",
  6892. conn->status_code,
  6893. mg_get_response_code_text(NULL, conn->status_code));
  6894. send_no_cache_header(conn);
  6895. mg_printf(conn,
  6896. "Date: %s\r\n"
  6897. "Content-Length: 0\r\n"
  6898. "Connection: %s\r\n\r\n",
  6899. date,
  6900. suggest_connection_header(conn));
  6901. mg_fclose(&file);
  6902. }
  6903. static void
  6904. delete_file(struct mg_connection *conn, const char *path)
  6905. {
  6906. struct de de;
  6907. memset(&de.file, 0, sizeof(de.file));
  6908. if (!mg_stat(conn, path, &de.file)) {
  6909. /* mg_stat returns 0 if the file does not exist */
  6910. send_http_error(conn,
  6911. 404,
  6912. "Error: Cannot delete file\nFile %s not found",
  6913. path);
  6914. return;
  6915. }
  6916. if (de.file.membuf != NULL) {
  6917. /* the file is cached in memory */
  6918. send_http_error(
  6919. conn,
  6920. 405,
  6921. "Error: Delete not possible\nDeleting %s is not supported",
  6922. path);
  6923. return;
  6924. }
  6925. if (de.file.is_directory) {
  6926. if (remove_directory(conn, path)) {
  6927. /* Delete is successful: Return 204 without content. */
  6928. send_http_error(conn, 204, "%s", "");
  6929. } else {
  6930. /* Delete is not successful: Return 500 (Server error). */
  6931. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6932. }
  6933. return;
  6934. }
  6935. /* This is an existing file (not a directory).
  6936. * Check if write permission is granted. */
  6937. if (access(path, W_OK) != 0) {
  6938. /* File is read only */
  6939. send_http_error(
  6940. conn,
  6941. 403,
  6942. "Error: Delete not possible\nDeleting %s is not allowed",
  6943. path);
  6944. return;
  6945. }
  6946. /* Try to delete it. */
  6947. if (mg_remove(conn, path) == 0) {
  6948. /* Delete was successful: Return 204 without content. */
  6949. send_http_error(conn, 204, "%s", "");
  6950. } else {
  6951. /* Delete not successful (file locked). */
  6952. send_http_error(conn,
  6953. 423,
  6954. "Error: Cannot delete file\nremove(%s): %s",
  6955. path,
  6956. strerror(ERRNO));
  6957. }
  6958. }
  6959. #endif /* !NO_FILES */
  6960. static void
  6961. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6962. static void
  6963. do_ssi_include(struct mg_connection *conn,
  6964. const char *ssi,
  6965. char *tag,
  6966. int include_level)
  6967. {
  6968. char file_name[MG_BUF_LEN], path[512], *p;
  6969. struct file file = STRUCT_FILE_INITIALIZER;
  6970. size_t len;
  6971. int truncated = 0;
  6972. if (conn == NULL) {
  6973. return;
  6974. }
  6975. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6976. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6977. * always < MG_BUF_LEN. */
  6978. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6979. /* File name is relative to the webserver root */
  6980. file_name[511] = 0;
  6981. (void)mg_snprintf(conn,
  6982. &truncated,
  6983. path,
  6984. sizeof(path),
  6985. "%s/%s",
  6986. conn->ctx->config[DOCUMENT_ROOT],
  6987. file_name);
  6988. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6989. /* File name is relative to the webserver working directory
  6990. * or it is absolute system path */
  6991. file_name[511] = 0;
  6992. (void)
  6993. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6994. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6995. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6996. /* File name is relative to the currect document */
  6997. file_name[511] = 0;
  6998. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6999. if (!truncated) {
  7000. if ((p = strrchr(path, '/')) != NULL) {
  7001. p[1] = '\0';
  7002. }
  7003. len = strlen(path);
  7004. (void)mg_snprintf(conn,
  7005. &truncated,
  7006. path + len,
  7007. sizeof(path) - len,
  7008. "%s",
  7009. file_name);
  7010. }
  7011. } else {
  7012. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7013. return;
  7014. }
  7015. if (truncated) {
  7016. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7017. return;
  7018. }
  7019. if (!mg_fopen(conn, path, "rb", &file)) {
  7020. mg_cry(conn,
  7021. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7022. tag,
  7023. path,
  7024. strerror(ERRNO));
  7025. } else {
  7026. fclose_on_exec(&file, conn);
  7027. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7028. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7029. path) > 0) {
  7030. send_ssi_file(conn, path, &file, include_level + 1);
  7031. } else {
  7032. send_file_data(conn, &file, 0, INT64_MAX);
  7033. }
  7034. mg_fclose(&file);
  7035. }
  7036. }
  7037. #if !defined(NO_POPEN)
  7038. static void
  7039. do_ssi_exec(struct mg_connection *conn, char *tag)
  7040. {
  7041. char cmd[1024] = "";
  7042. struct file file = STRUCT_FILE_INITIALIZER;
  7043. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7044. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7045. } else {
  7046. cmd[1023] = 0;
  7047. if ((file.fp = popen(cmd, "r")) == NULL) {
  7048. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7049. } else {
  7050. send_file_data(conn, &file, 0, INT64_MAX);
  7051. pclose(file.fp);
  7052. }
  7053. }
  7054. }
  7055. #endif /* !NO_POPEN */
  7056. static int
  7057. mg_fgetc(struct file *filep, int offset)
  7058. {
  7059. if (filep == NULL) {
  7060. return EOF;
  7061. }
  7062. if (filep->membuf != NULL && offset >= 0
  7063. && ((unsigned int)(offset)) < filep->size) {
  7064. return ((const unsigned char *)filep->membuf)[offset];
  7065. } else if (filep->fp != NULL) {
  7066. return fgetc(filep->fp);
  7067. } else {
  7068. return EOF;
  7069. }
  7070. }
  7071. static void
  7072. send_ssi_file(struct mg_connection *conn,
  7073. const char *path,
  7074. struct file *filep,
  7075. int include_level)
  7076. {
  7077. char buf[MG_BUF_LEN];
  7078. int ch, offset, len, in_ssi_tag;
  7079. if (include_level > 10) {
  7080. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7081. return;
  7082. }
  7083. in_ssi_tag = len = offset = 0;
  7084. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7085. if (in_ssi_tag && ch == '>') {
  7086. in_ssi_tag = 0;
  7087. buf[len++] = (char)ch;
  7088. buf[len] = '\0';
  7089. /* assert(len <= (int) sizeof(buf)); */
  7090. if (len > (int)sizeof(buf)) {
  7091. break;
  7092. }
  7093. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7094. /* Not an SSI tag, pass it */
  7095. (void)mg_write(conn, buf, (size_t)len);
  7096. } else {
  7097. if (!memcmp(buf + 5, "include", 7)) {
  7098. do_ssi_include(conn, path, buf + 12, include_level);
  7099. #if !defined(NO_POPEN)
  7100. } else if (!memcmp(buf + 5, "exec", 4)) {
  7101. do_ssi_exec(conn, buf + 9);
  7102. #endif /* !NO_POPEN */
  7103. } else {
  7104. mg_cry(conn,
  7105. "%s: unknown SSI "
  7106. "command: \"%s\"",
  7107. path,
  7108. buf);
  7109. }
  7110. }
  7111. len = 0;
  7112. } else if (in_ssi_tag) {
  7113. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7114. /* Not an SSI tag */
  7115. in_ssi_tag = 0;
  7116. } else if (len == (int)sizeof(buf) - 2) {
  7117. mg_cry(conn, "%s: SSI tag is too large", path);
  7118. len = 0;
  7119. }
  7120. buf[len++] = (char)(ch & 0xff);
  7121. } else if (ch == '<') {
  7122. in_ssi_tag = 1;
  7123. if (len > 0) {
  7124. mg_write(conn, buf, (size_t)len);
  7125. }
  7126. len = 0;
  7127. buf[len++] = (char)(ch & 0xff);
  7128. } else {
  7129. buf[len++] = (char)(ch & 0xff);
  7130. if (len == (int)sizeof(buf)) {
  7131. mg_write(conn, buf, (size_t)len);
  7132. len = 0;
  7133. }
  7134. }
  7135. }
  7136. /* Send the rest of buffered data */
  7137. if (len > 0) {
  7138. mg_write(conn, buf, (size_t)len);
  7139. }
  7140. }
  7141. static void
  7142. handle_ssi_file_request(struct mg_connection *conn,
  7143. const char *path,
  7144. struct file *filep)
  7145. {
  7146. char date[64];
  7147. time_t curtime = time(NULL);
  7148. const char *cors1, *cors2, *cors3;
  7149. if (conn == NULL || path == NULL || filep == NULL) {
  7150. return;
  7151. }
  7152. if (mg_get_header(conn, "Origin")) {
  7153. /* Cross-origin resource sharing (CORS). */
  7154. cors1 = "Access-Control-Allow-Origin: ";
  7155. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7156. cors3 = "\r\n";
  7157. } else {
  7158. cors1 = cors2 = cors3 = "";
  7159. }
  7160. if (!mg_fopen(conn, path, "rb", filep)) {
  7161. /* File exists (precondition for calling this function),
  7162. * but can not be opened by the server. */
  7163. send_http_error(conn,
  7164. 500,
  7165. "Error: Cannot read file\nfopen(%s): %s",
  7166. path,
  7167. strerror(ERRNO));
  7168. } else {
  7169. conn->must_close = 1;
  7170. gmt_time_string(date, sizeof(date), &curtime);
  7171. fclose_on_exec(filep, conn);
  7172. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7173. send_no_cache_header(conn);
  7174. mg_printf(conn,
  7175. "%s%s%s"
  7176. "Date: %s\r\n"
  7177. "Content-Type: text/html\r\n"
  7178. "Connection: %s\r\n\r\n",
  7179. cors1,
  7180. cors2,
  7181. cors3,
  7182. date,
  7183. suggest_connection_header(conn));
  7184. send_ssi_file(conn, path, filep, 0);
  7185. mg_fclose(filep);
  7186. }
  7187. }
  7188. #if !defined(NO_FILES)
  7189. static void
  7190. send_options(struct mg_connection *conn)
  7191. {
  7192. char date[64];
  7193. time_t curtime = time(NULL);
  7194. if (!conn) {
  7195. return;
  7196. }
  7197. conn->status_code = 200;
  7198. conn->must_close = 1;
  7199. gmt_time_string(date, sizeof(date), &curtime);
  7200. mg_printf(conn,
  7201. "HTTP/1.1 200 OK\r\n"
  7202. "Date: %s\r\n"
  7203. /* TODO: "Cache-Control" (?) */
  7204. "Connection: %s\r\n"
  7205. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7206. "PROPFIND, MKCOL\r\n"
  7207. "DAV: 1\r\n\r\n",
  7208. date,
  7209. suggest_connection_header(conn));
  7210. }
  7211. /* Writes PROPFIND properties for a collection element */
  7212. static void
  7213. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7214. {
  7215. char mtime[64];
  7216. if (conn == NULL || uri == NULL || filep == NULL) {
  7217. return;
  7218. }
  7219. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7220. conn->num_bytes_sent +=
  7221. mg_printf(conn,
  7222. "<d:response>"
  7223. "<d:href>%s</d:href>"
  7224. "<d:propstat>"
  7225. "<d:prop>"
  7226. "<d:resourcetype>%s</d:resourcetype>"
  7227. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7228. "<d:getlastmodified>%s</d:getlastmodified>"
  7229. "</d:prop>"
  7230. "<d:status>HTTP/1.1 200 OK</d:status>"
  7231. "</d:propstat>"
  7232. "</d:response>\n",
  7233. uri,
  7234. filep->is_directory ? "<d:collection/>" : "",
  7235. filep->size,
  7236. mtime);
  7237. }
  7238. static void
  7239. print_dav_dir_entry(struct de *de, void *data)
  7240. {
  7241. char href[PATH_MAX];
  7242. char href_encoded[PATH_MAX * 3 /* worst case */];
  7243. int truncated;
  7244. struct mg_connection *conn = (struct mg_connection *)data;
  7245. if (!de || !conn) {
  7246. return;
  7247. }
  7248. mg_snprintf(conn,
  7249. &truncated,
  7250. href,
  7251. sizeof(href),
  7252. "%s%s",
  7253. conn->request_info.local_uri,
  7254. de->file_name);
  7255. if (!truncated) {
  7256. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7257. print_props(conn, href_encoded, &de->file);
  7258. }
  7259. }
  7260. static void
  7261. handle_propfind(struct mg_connection *conn,
  7262. const char *path,
  7263. struct file *filep)
  7264. {
  7265. const char *depth = mg_get_header(conn, "Depth");
  7266. char date[64];
  7267. time_t curtime = time(NULL);
  7268. gmt_time_string(date, sizeof(date), &curtime);
  7269. if (!conn || !path || !filep || !conn->ctx) {
  7270. return;
  7271. }
  7272. conn->must_close = 1;
  7273. conn->status_code = 207;
  7274. mg_printf(conn,
  7275. "HTTP/1.1 207 Multi-Status\r\n"
  7276. "Date: %s\r\n",
  7277. date);
  7278. send_static_cache_header(conn);
  7279. mg_printf(conn,
  7280. "Connection: %s\r\n"
  7281. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7282. suggest_connection_header(conn));
  7283. conn->num_bytes_sent +=
  7284. mg_printf(conn,
  7285. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7286. "<d:multistatus xmlns:d='DAV:'>\n");
  7287. /* Print properties for the requested resource itself */
  7288. print_props(conn, conn->request_info.local_uri, filep);
  7289. /* If it is a directory, print directory entries too if Depth is not 0 */
  7290. if (filep && filep->is_directory
  7291. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7292. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7293. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7294. }
  7295. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7296. }
  7297. #endif
  7298. void
  7299. mg_lock_connection(struct mg_connection *conn)
  7300. {
  7301. if (conn) {
  7302. (void)pthread_mutex_lock(&conn->mutex);
  7303. }
  7304. }
  7305. void
  7306. mg_unlock_connection(struct mg_connection *conn)
  7307. {
  7308. if (conn) {
  7309. (void)pthread_mutex_unlock(&conn->mutex);
  7310. }
  7311. }
  7312. void
  7313. mg_lock_context(struct mg_context *ctx)
  7314. {
  7315. if (ctx) {
  7316. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7317. }
  7318. }
  7319. void
  7320. mg_unlock_context(struct mg_context *ctx)
  7321. {
  7322. if (ctx) {
  7323. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7324. }
  7325. }
  7326. #if defined(USE_TIMERS)
  7327. #include "timer.inl"
  7328. #endif /* USE_TIMERS */
  7329. #ifdef USE_LUA
  7330. #include "mod_lua.inl"
  7331. #endif /* USE_LUA */
  7332. #ifdef USE_DUKTAPE
  7333. #include "mod_duktape.inl"
  7334. #endif /* USE_DUKTAPE */
  7335. #if defined(USE_WEBSOCKET)
  7336. /* START OF SHA-1 code
  7337. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7338. #define SHA1HANDSOFF
  7339. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7340. *
  7341. * #if defined(__sun)
  7342. * #include "solarisfixes.h"
  7343. * #endif
  7344. */
  7345. static int
  7346. is_big_endian(void)
  7347. {
  7348. static const int n = 1;
  7349. return ((char *)&n)[0] == 0;
  7350. }
  7351. union char64long16 {
  7352. unsigned char c[64];
  7353. uint32_t l[16];
  7354. };
  7355. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7356. static uint32_t
  7357. blk0(union char64long16 *block, int i)
  7358. {
  7359. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7360. if (!is_big_endian()) {
  7361. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7362. | (rol(block->l[i], 8) & 0x00FF00FF);
  7363. }
  7364. return block->l[i];
  7365. }
  7366. #define blk(i) \
  7367. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7368. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7369. 1))
  7370. #define R0(v, w, x, y, z, i) \
  7371. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7372. w = rol(w, 30);
  7373. #define R1(v, w, x, y, z, i) \
  7374. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7375. w = rol(w, 30);
  7376. #define R2(v, w, x, y, z, i) \
  7377. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7378. w = rol(w, 30);
  7379. #define R3(v, w, x, y, z, i) \
  7380. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7381. w = rol(w, 30);
  7382. #define R4(v, w, x, y, z, i) \
  7383. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7384. w = rol(w, 30);
  7385. typedef struct {
  7386. uint32_t state[5];
  7387. uint32_t count[2];
  7388. unsigned char buffer[64];
  7389. } SHA1_CTX;
  7390. static void
  7391. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7392. {
  7393. uint32_t a, b, c, d, e;
  7394. union char64long16 block[1];
  7395. memcpy(block, buffer, 64);
  7396. a = state[0];
  7397. b = state[1];
  7398. c = state[2];
  7399. d = state[3];
  7400. e = state[4];
  7401. R0(a, b, c, d, e, 0);
  7402. R0(e, a, b, c, d, 1);
  7403. R0(d, e, a, b, c, 2);
  7404. R0(c, d, e, a, b, 3);
  7405. R0(b, c, d, e, a, 4);
  7406. R0(a, b, c, d, e, 5);
  7407. R0(e, a, b, c, d, 6);
  7408. R0(d, e, a, b, c, 7);
  7409. R0(c, d, e, a, b, 8);
  7410. R0(b, c, d, e, a, 9);
  7411. R0(a, b, c, d, e, 10);
  7412. R0(e, a, b, c, d, 11);
  7413. R0(d, e, a, b, c, 12);
  7414. R0(c, d, e, a, b, 13);
  7415. R0(b, c, d, e, a, 14);
  7416. R0(a, b, c, d, e, 15);
  7417. R1(e, a, b, c, d, 16);
  7418. R1(d, e, a, b, c, 17);
  7419. R1(c, d, e, a, b, 18);
  7420. R1(b, c, d, e, a, 19);
  7421. R2(a, b, c, d, e, 20);
  7422. R2(e, a, b, c, d, 21);
  7423. R2(d, e, a, b, c, 22);
  7424. R2(c, d, e, a, b, 23);
  7425. R2(b, c, d, e, a, 24);
  7426. R2(a, b, c, d, e, 25);
  7427. R2(e, a, b, c, d, 26);
  7428. R2(d, e, a, b, c, 27);
  7429. R2(c, d, e, a, b, 28);
  7430. R2(b, c, d, e, a, 29);
  7431. R2(a, b, c, d, e, 30);
  7432. R2(e, a, b, c, d, 31);
  7433. R2(d, e, a, b, c, 32);
  7434. R2(c, d, e, a, b, 33);
  7435. R2(b, c, d, e, a, 34);
  7436. R2(a, b, c, d, e, 35);
  7437. R2(e, a, b, c, d, 36);
  7438. R2(d, e, a, b, c, 37);
  7439. R2(c, d, e, a, b, 38);
  7440. R2(b, c, d, e, a, 39);
  7441. R3(a, b, c, d, e, 40);
  7442. R3(e, a, b, c, d, 41);
  7443. R3(d, e, a, b, c, 42);
  7444. R3(c, d, e, a, b, 43);
  7445. R3(b, c, d, e, a, 44);
  7446. R3(a, b, c, d, e, 45);
  7447. R3(e, a, b, c, d, 46);
  7448. R3(d, e, a, b, c, 47);
  7449. R3(c, d, e, a, b, 48);
  7450. R3(b, c, d, e, a, 49);
  7451. R3(a, b, c, d, e, 50);
  7452. R3(e, a, b, c, d, 51);
  7453. R3(d, e, a, b, c, 52);
  7454. R3(c, d, e, a, b, 53);
  7455. R3(b, c, d, e, a, 54);
  7456. R3(a, b, c, d, e, 55);
  7457. R3(e, a, b, c, d, 56);
  7458. R3(d, e, a, b, c, 57);
  7459. R3(c, d, e, a, b, 58);
  7460. R3(b, c, d, e, a, 59);
  7461. R4(a, b, c, d, e, 60);
  7462. R4(e, a, b, c, d, 61);
  7463. R4(d, e, a, b, c, 62);
  7464. R4(c, d, e, a, b, 63);
  7465. R4(b, c, d, e, a, 64);
  7466. R4(a, b, c, d, e, 65);
  7467. R4(e, a, b, c, d, 66);
  7468. R4(d, e, a, b, c, 67);
  7469. R4(c, d, e, a, b, 68);
  7470. R4(b, c, d, e, a, 69);
  7471. R4(a, b, c, d, e, 70);
  7472. R4(e, a, b, c, d, 71);
  7473. R4(d, e, a, b, c, 72);
  7474. R4(c, d, e, a, b, 73);
  7475. R4(b, c, d, e, a, 74);
  7476. R4(a, b, c, d, e, 75);
  7477. R4(e, a, b, c, d, 76);
  7478. R4(d, e, a, b, c, 77);
  7479. R4(c, d, e, a, b, 78);
  7480. R4(b, c, d, e, a, 79);
  7481. state[0] += a;
  7482. state[1] += b;
  7483. state[2] += c;
  7484. state[3] += d;
  7485. state[4] += e;
  7486. a = b = c = d = e = 0;
  7487. memset(block, '\0', sizeof(block));
  7488. }
  7489. static void
  7490. SHA1Init(SHA1_CTX *context)
  7491. {
  7492. context->state[0] = 0x67452301;
  7493. context->state[1] = 0xEFCDAB89;
  7494. context->state[2] = 0x98BADCFE;
  7495. context->state[3] = 0x10325476;
  7496. context->state[4] = 0xC3D2E1F0;
  7497. context->count[0] = context->count[1] = 0;
  7498. }
  7499. static void
  7500. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7501. {
  7502. uint32_t i, j;
  7503. j = context->count[0];
  7504. if ((context->count[0] += len << 3) < j) {
  7505. context->count[1]++;
  7506. }
  7507. context->count[1] += (len >> 29);
  7508. j = (j >> 3) & 63;
  7509. if ((j + len) > 63) {
  7510. memcpy(&context->buffer[j], data, (i = 64 - j));
  7511. SHA1Transform(context->state, context->buffer);
  7512. for (; i + 63 < len; i += 64) {
  7513. SHA1Transform(context->state, &data[i]);
  7514. }
  7515. j = 0;
  7516. } else
  7517. i = 0;
  7518. memcpy(&context->buffer[j], &data[i], len - i);
  7519. }
  7520. static void
  7521. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7522. {
  7523. unsigned i;
  7524. unsigned char finalcount[8], c;
  7525. for (i = 0; i < 8; i++) {
  7526. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7527. >> ((3 - (i & 3)) * 8)) & 255);
  7528. }
  7529. c = 0200;
  7530. SHA1Update(context, &c, 1);
  7531. while ((context->count[0] & 504) != 448) {
  7532. c = 0000;
  7533. SHA1Update(context, &c, 1);
  7534. }
  7535. SHA1Update(context, finalcount, 8);
  7536. for (i = 0; i < 20; i++) {
  7537. digest[i] = (unsigned char)((context->state[i >> 2]
  7538. >> ((3 - (i & 3)) * 8)) & 255);
  7539. }
  7540. memset(context, '\0', sizeof(*context));
  7541. memset(&finalcount, '\0', sizeof(finalcount));
  7542. }
  7543. /* END OF SHA1 CODE */
  7544. static int
  7545. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7546. {
  7547. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7548. const char *protocol = NULL;
  7549. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7550. SHA1_CTX sha_ctx;
  7551. int truncated;
  7552. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7553. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7554. if (truncated) {
  7555. conn->must_close = 1;
  7556. return 0;
  7557. }
  7558. SHA1Init(&sha_ctx);
  7559. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7560. SHA1Final((unsigned char *)sha, &sha_ctx);
  7561. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7562. mg_printf(conn,
  7563. "HTTP/1.1 101 Switching Protocols\r\n"
  7564. "Upgrade: websocket\r\n"
  7565. "Connection: Upgrade\r\n"
  7566. "Sec-WebSocket-Accept: %s\r\n",
  7567. b64_sha);
  7568. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7569. if (protocol) {
  7570. /* The protocol is a comma seperated list of names. */
  7571. /* The server must only return one value from this list. */
  7572. /* First check if it is a list or just a single value. */
  7573. const char *sep = strchr(protocol, ',');
  7574. if (sep == NULL) {
  7575. /* Just a single protocol -> accept it. */
  7576. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7577. } else {
  7578. /* Multiple protocols -> accept the first one. */
  7579. /* This is just a quick fix if the client offers multiple
  7580. * protocols. In order to get the behavior intended by
  7581. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7582. * required to have a list of websocket subprotocols accepted
  7583. * by the server. Then the server must either select a subprotocol
  7584. * supported by client and server, or the server has to abort the
  7585. * handshake by not returning a Sec-Websocket-Protocol header if
  7586. * no subprotocol is acceptable.
  7587. */
  7588. mg_printf(conn,
  7589. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7590. (int)(sep - protocol),
  7591. protocol);
  7592. }
  7593. /* TODO: Real subprotocol negotiation instead of just taking the first
  7594. * websocket subprotocol suggested by the client. */
  7595. } else {
  7596. mg_printf(conn, "%s", "\r\n");
  7597. }
  7598. return 1;
  7599. }
  7600. static void
  7601. read_websocket(struct mg_connection *conn,
  7602. mg_websocket_data_handler ws_data_handler,
  7603. void *callback_data)
  7604. {
  7605. /* Pointer to the beginning of the portion of the incoming websocket
  7606. * message queue.
  7607. * The original websocket upgrade request is never removed, so the queue
  7608. * begins after it. */
  7609. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7610. int n, error, exit_by_callback;
  7611. /* body_len is the length of the entire queue in bytes
  7612. * len is the length of the current message
  7613. * data_len is the length of the current message's data payload
  7614. * header_len is the length of the current message's header */
  7615. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7616. /* "The masking key is a 32-bit value chosen at random by the client."
  7617. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7618. */
  7619. unsigned char mask[4];
  7620. /* data points to the place where the message is stored when passed to
  7621. * the
  7622. * websocket_data callback. This is either mem on the stack, or a
  7623. * dynamically allocated buffer if it is too large. */
  7624. char mem[4096];
  7625. char *data = mem;
  7626. unsigned char mop; /* mask flag and opcode */
  7627. double timeout = -1.0;
  7628. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7629. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7630. }
  7631. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7632. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7633. }
  7634. mg_set_thread_name("wsock");
  7635. /* Loop continuously, reading messages from the socket, invoking the
  7636. * callback, and waiting repeatedly until an error occurs. */
  7637. while (!conn->ctx->stop_flag) {
  7638. header_len = 0;
  7639. assert(conn->data_len >= conn->request_len);
  7640. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7641. len = buf[1] & 127;
  7642. mask_len = buf[1] & 128 ? 4 : 0;
  7643. if (len < 126 && body_len >= mask_len) {
  7644. data_len = len;
  7645. header_len = 2 + mask_len;
  7646. } else if (len == 126 && body_len >= 4 + mask_len) {
  7647. header_len = 4 + mask_len;
  7648. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7649. } else if (body_len >= 10 + mask_len) {
  7650. header_len = 10 + mask_len;
  7651. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7652. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7653. }
  7654. }
  7655. if (header_len > 0 && body_len >= header_len) {
  7656. /* Allocate space to hold websocket payload */
  7657. data = mem;
  7658. if (data_len > sizeof(mem)) {
  7659. data = (char *)mg_malloc(data_len);
  7660. if (data == NULL) {
  7661. /* Allocation failed, exit the loop and then close the
  7662. * connection */
  7663. mg_cry(conn, "websocket out of memory; closing connection");
  7664. break;
  7665. }
  7666. }
  7667. /* Copy the mask before we shift the queue and destroy it */
  7668. if (mask_len > 0) {
  7669. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7670. } else {
  7671. memset(mask, 0, sizeof(mask));
  7672. }
  7673. /* Read frame payload from the first message in the queue into
  7674. * data and advance the queue by moving the memory in place. */
  7675. assert(body_len >= header_len);
  7676. if (data_len + header_len > body_len) {
  7677. mop = buf[0]; /* current mask and opcode */
  7678. /* Overflow case */
  7679. len = body_len - header_len;
  7680. memcpy(data, buf + header_len, len);
  7681. error = 0;
  7682. while (len < data_len) {
  7683. n = pull(
  7684. NULL, conn, data + len, (int)(data_len - len), timeout);
  7685. if (n <= 0) {
  7686. error = 1;
  7687. break;
  7688. }
  7689. len += (size_t)n;
  7690. }
  7691. if (error) {
  7692. mg_cry(conn, "Websocket pull failed; closing connection");
  7693. break;
  7694. }
  7695. conn->data_len = conn->request_len;
  7696. } else {
  7697. mop = buf[0]; /* current mask and opcode, overwritten by
  7698. * memmove() */
  7699. /* Length of the message being read at the front of the
  7700. * queue */
  7701. len = data_len + header_len;
  7702. /* Copy the data payload into the data pointer for the
  7703. * callback */
  7704. memcpy(data, buf + header_len, data_len);
  7705. /* Move the queue forward len bytes */
  7706. memmove(buf, buf + len, body_len - len);
  7707. /* Mark the queue as advanced */
  7708. conn->data_len -= (int)len;
  7709. }
  7710. /* Apply mask if necessary */
  7711. if (mask_len > 0) {
  7712. for (i = 0; i < data_len; ++i) {
  7713. data[i] ^= mask[i & 3];
  7714. }
  7715. }
  7716. /* Exit the loop if callback signals to exit (server side),
  7717. * or "connection close" opcode received (client side). */
  7718. exit_by_callback = 0;
  7719. if ((ws_data_handler != NULL)
  7720. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7721. exit_by_callback = 1;
  7722. }
  7723. if (data != mem) {
  7724. mg_free(data);
  7725. }
  7726. if (exit_by_callback
  7727. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7728. /* Opcode == 8, connection close */
  7729. break;
  7730. }
  7731. /* Not breaking the loop, process next websocket frame. */
  7732. } else {
  7733. /* Read from the socket into the next available location in the
  7734. * message queue. */
  7735. if ((n = pull(NULL,
  7736. conn,
  7737. conn->buf + conn->data_len,
  7738. conn->buf_size - conn->data_len,
  7739. timeout)) <= 0) {
  7740. /* Error, no bytes read */
  7741. break;
  7742. }
  7743. conn->data_len += n;
  7744. }
  7745. }
  7746. mg_set_thread_name("worker");
  7747. }
  7748. static int
  7749. mg_websocket_write_exec(struct mg_connection *conn,
  7750. int opcode,
  7751. const char *data,
  7752. size_t dataLen,
  7753. uint32_t masking_key)
  7754. {
  7755. unsigned char header[14];
  7756. size_t headerLen = 1;
  7757. int retval = -1;
  7758. header[0] = 0x80 + (opcode & 0xF);
  7759. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7760. if (dataLen < 126) {
  7761. /* inline 7-bit length field */
  7762. header[1] = (unsigned char)dataLen;
  7763. headerLen = 2;
  7764. } else if (dataLen <= 0xFFFF) {
  7765. /* 16-bit length field */
  7766. header[1] = 126;
  7767. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7768. headerLen = 4;
  7769. } else {
  7770. /* 64-bit length field */
  7771. header[1] = 127;
  7772. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7773. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7774. headerLen = 10;
  7775. }
  7776. if (masking_key) {
  7777. /* add mask */
  7778. header[1] |= 0x80;
  7779. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7780. headerLen += 4;
  7781. }
  7782. /* Note that POSIX/Winsock's send() is threadsafe
  7783. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7784. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7785. * push(), although that is only a problem if the packet is large or
  7786. * outgoing buffer is full). */
  7787. (void)mg_lock_connection(conn);
  7788. retval = mg_write(conn, header, headerLen);
  7789. if (dataLen > 0) {
  7790. retval = mg_write(conn, data, dataLen);
  7791. }
  7792. mg_unlock_connection(conn);
  7793. return retval;
  7794. }
  7795. int
  7796. mg_websocket_write(struct mg_connection *conn,
  7797. int opcode,
  7798. const char *data,
  7799. size_t dataLen)
  7800. {
  7801. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7802. }
  7803. static void
  7804. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7805. {
  7806. size_t i = 0;
  7807. i = 0;
  7808. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7809. /* Convert in 32 bit words, if data is 4 byte aligned */
  7810. while (i < (in_len - 3)) {
  7811. *(uint32_t *)(void *)(out + i) =
  7812. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7813. i += 4;
  7814. }
  7815. }
  7816. if (i != in_len) {
  7817. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7818. while (i < in_len) {
  7819. *(uint8_t *)(void *)(out + i) =
  7820. *(uint8_t *)(void *)(in + i)
  7821. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7822. i++;
  7823. }
  7824. }
  7825. }
  7826. int
  7827. mg_websocket_client_write(struct mg_connection *conn,
  7828. int opcode,
  7829. const char *data,
  7830. size_t dataLen)
  7831. {
  7832. int retval = -1;
  7833. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7834. uint32_t masking_key = (uint32_t)get_random();
  7835. if (masked_data == NULL) {
  7836. /* Return -1 in an error case */
  7837. mg_cry(conn,
  7838. "Cannot allocate buffer for masked websocket response: "
  7839. "Out of memory");
  7840. return -1;
  7841. }
  7842. mask_data(data, dataLen, masking_key, masked_data);
  7843. retval = mg_websocket_write_exec(
  7844. conn, opcode, masked_data, dataLen, masking_key);
  7845. mg_free(masked_data);
  7846. return retval;
  7847. }
  7848. static void
  7849. handle_websocket_request(struct mg_connection *conn,
  7850. const char *path,
  7851. int is_callback_resource,
  7852. mg_websocket_connect_handler ws_connect_handler,
  7853. mg_websocket_ready_handler ws_ready_handler,
  7854. mg_websocket_data_handler ws_data_handler,
  7855. mg_websocket_close_handler ws_close_handler,
  7856. void *cbData)
  7857. {
  7858. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7859. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7860. int lua_websock = 0;
  7861. #if !defined(USE_LUA)
  7862. (void)path;
  7863. #endif
  7864. /* Step 1: Check websocket protocol version. */
  7865. /* Step 1.1: Check Sec-WebSocket-Key. */
  7866. if (!websock_key) {
  7867. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  7868. * requires a Sec-WebSocket-Key header.
  7869. */
  7870. /* It could be the hixie draft version
  7871. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  7872. */
  7873. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  7874. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  7875. char key3[8];
  7876. if ((key1 != NULL) && (key2 != NULL)) {
  7877. /* This version uses 8 byte body data in a GET request */
  7878. conn->content_len = 8;
  7879. if (8 == mg_read(conn, key3, 8)) {
  7880. /* This is the hixie version */
  7881. send_http_error(conn,
  7882. 426,
  7883. "%s",
  7884. "Protocol upgrade to RFC 6455 required");
  7885. return;
  7886. }
  7887. }
  7888. /* This is an unknown version */
  7889. send_http_error(conn, 400, "%s", "Malformed websocket request");
  7890. return;
  7891. }
  7892. /* Step 1.2: Check websocket protocol version. */
  7893. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  7894. if (version == NULL || strcmp(version, "13") != 0) {
  7895. /* Reject wrong versions */
  7896. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7897. return;
  7898. }
  7899. /* Step 1.3: Could check for "Host", but we do not really nead this
  7900. * value for anything, so just ignore it. */
  7901. /* Step 2: If a callback is responsible, call it. */
  7902. if (is_callback_resource) {
  7903. if (ws_connect_handler != NULL
  7904. && ws_connect_handler(conn, cbData) != 0) {
  7905. /* C callback has returned non-zero, do not proceed with
  7906. * handshake.
  7907. */
  7908. /* Note that C callbacks are no longer called when Lua is
  7909. * responsible, so C can no longer filter callbacks for Lua. */
  7910. return;
  7911. }
  7912. }
  7913. #if defined(USE_LUA)
  7914. /* Step 3: No callback. Check if Lua is responsible. */
  7915. else {
  7916. /* Step 3.1: Check if Lua is responsible. */
  7917. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7918. lua_websock =
  7919. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7920. strlen(
  7921. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7922. path);
  7923. }
  7924. if (lua_websock) {
  7925. /* Step 3.2: Lua is responsible: call it. */
  7926. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7927. if (!conn->lua_websocket_state) {
  7928. /* Lua rejected the new client */
  7929. return;
  7930. }
  7931. }
  7932. }
  7933. #endif
  7934. /* Step 4: Check if there is a responsible websocket handler. */
  7935. if (!is_callback_resource && !lua_websock) {
  7936. /* There is no callback, an Lua is not responsible either. */
  7937. /* Reply with a 404 Not Found or with nothing at all?
  7938. * TODO (mid): check the websocket standards, how to reply to
  7939. * requests to invalid websocket addresses. */
  7940. send_http_error(conn, 404, "%s", "Not found");
  7941. return;
  7942. }
  7943. /* Step 5: The websocket connection has been accepted */
  7944. if (!send_websocket_handshake(conn, websock_key)) {
  7945. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7946. return;
  7947. }
  7948. /* Step 6: Call the ready handler */
  7949. if (is_callback_resource) {
  7950. if (ws_ready_handler != NULL) {
  7951. ws_ready_handler(conn, cbData);
  7952. }
  7953. #if defined(USE_LUA)
  7954. } else if (lua_websock) {
  7955. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7956. /* the ready handler returned false */
  7957. return;
  7958. }
  7959. #endif
  7960. }
  7961. /* Step 7: Enter the read loop */
  7962. if (is_callback_resource) {
  7963. read_websocket(conn, ws_data_handler, cbData);
  7964. #if defined(USE_LUA)
  7965. } else if (lua_websock) {
  7966. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7967. #endif
  7968. }
  7969. /* Step 8: Call the close handler */
  7970. if (ws_close_handler) {
  7971. ws_close_handler(conn, cbData);
  7972. }
  7973. }
  7974. static int
  7975. is_websocket_protocol(const struct mg_connection *conn)
  7976. {
  7977. const char *upgrade, *connection;
  7978. /* A websocket protocoll has the following HTTP headers:
  7979. *
  7980. * Connection: Upgrade
  7981. * Upgrade: Websocket
  7982. */
  7983. upgrade = mg_get_header(conn, "Upgrade");
  7984. if (upgrade == NULL) {
  7985. return 0; /* fail early, don't waste time checking other header
  7986. * fields
  7987. */
  7988. }
  7989. if (!mg_strcasestr(upgrade, "websocket")) {
  7990. return 0;
  7991. }
  7992. connection = mg_get_header(conn, "Connection");
  7993. if (connection == NULL) {
  7994. return 0;
  7995. }
  7996. if (!mg_strcasestr(connection, "upgrade")) {
  7997. return 0;
  7998. }
  7999. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8000. * "Sec-WebSocket-Version" are also required.
  8001. * Don't check them here, since even an unsupported websocket protocol
  8002. * request still IS a websocket request (in contrast to a standard HTTP
  8003. * request). It will fail later in handle_websocket_request.
  8004. */
  8005. return 1;
  8006. }
  8007. #endif /* !USE_WEBSOCKET */
  8008. static int
  8009. isbyte(int n)
  8010. {
  8011. return n >= 0 && n <= 255;
  8012. }
  8013. static int
  8014. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8015. {
  8016. int n, a, b, c, d, slash = 32, len = 0;
  8017. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8018. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8019. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8020. && slash < 33) {
  8021. len = n;
  8022. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8023. | (uint32_t)d;
  8024. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  8025. }
  8026. return len;
  8027. }
  8028. static int
  8029. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8030. {
  8031. int throttle = 0;
  8032. struct vec vec, val;
  8033. uint32_t net, mask;
  8034. char mult;
  8035. double v;
  8036. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8037. mult = ',';
  8038. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8039. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8040. && mult != ',')) {
  8041. continue;
  8042. }
  8043. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  8044. : 1;
  8045. if (vec.len == 1 && vec.ptr[0] == '*') {
  8046. throttle = (int)v;
  8047. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8048. if ((remote_ip & mask) == net) {
  8049. throttle = (int)v;
  8050. }
  8051. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8052. throttle = (int)v;
  8053. }
  8054. }
  8055. return throttle;
  8056. }
  8057. static uint32_t
  8058. get_remote_ip(const struct mg_connection *conn)
  8059. {
  8060. if (!conn) {
  8061. return 0;
  8062. }
  8063. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8064. }
  8065. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8066. #include "handle_form.inl"
  8067. #if defined(MG_LEGACY_INTERFACE)
  8068. /* Implement the deprecated mg_upload function by calling the new
  8069. * mg_handle_form_request function. While mg_upload could only handle
  8070. * HTML forms sent as POST request in multipart/form-data format
  8071. * containing only file input elements, mg_handle_form_request can
  8072. * handle all form input elements and all standard request methods. */
  8073. struct mg_upload_user_data {
  8074. struct mg_connection *conn;
  8075. const char *destination_dir;
  8076. int num_uploaded_files;
  8077. };
  8078. /* Helper function for deprecated mg_upload. */
  8079. static int
  8080. mg_upload_field_found(const char *key,
  8081. const char *filename,
  8082. char *path,
  8083. size_t pathlen,
  8084. void *user_data)
  8085. {
  8086. int truncated = 0;
  8087. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8088. (void)key;
  8089. if (!filename) {
  8090. mg_cry(fud->conn, "%s: No filename set", __func__);
  8091. return FORM_FIELD_STORAGE_ABORT;
  8092. }
  8093. mg_snprintf(fud->conn,
  8094. &truncated,
  8095. path,
  8096. pathlen - 1,
  8097. "%s/%s",
  8098. fud->destination_dir,
  8099. filename);
  8100. if (!truncated) {
  8101. mg_cry(fud->conn, "%s: File path too long", __func__);
  8102. return FORM_FIELD_STORAGE_ABORT;
  8103. }
  8104. return FORM_FIELD_STORAGE_STORE;
  8105. }
  8106. /* Helper function for deprecated mg_upload. */
  8107. static int
  8108. mg_upload_field_get(const char *key,
  8109. const char *value,
  8110. size_t value_size,
  8111. void *user_data)
  8112. {
  8113. /* Function should never be called */
  8114. (void)key;
  8115. (void)value;
  8116. (void)value_size;
  8117. (void)user_data;
  8118. return 0;
  8119. }
  8120. /* Helper function for deprecated mg_upload. */
  8121. static int
  8122. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8123. {
  8124. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8125. (void)file_size;
  8126. fud->num_uploaded_files++;
  8127. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8128. return 0;
  8129. }
  8130. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8131. int
  8132. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8133. {
  8134. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8135. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8136. mg_upload_field_get,
  8137. mg_upload_field_stored,
  8138. 0};
  8139. int ret;
  8140. fdh.user_data = (void *)&fud;
  8141. ret = mg_handle_form_request(conn, &fdh);
  8142. if (ret < 0) {
  8143. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8144. }
  8145. return fud.num_uploaded_files;
  8146. }
  8147. #endif
  8148. static int
  8149. get_first_ssl_listener_index(const struct mg_context *ctx)
  8150. {
  8151. unsigned int i;
  8152. int idx = -1;
  8153. if (ctx) {
  8154. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8155. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8156. }
  8157. }
  8158. return idx;
  8159. }
  8160. static void
  8161. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8162. {
  8163. char host[1025];
  8164. const char *host_header;
  8165. size_t hostlen;
  8166. host_header = mg_get_header(conn, "Host");
  8167. hostlen = sizeof(host);
  8168. if (host_header != NULL) {
  8169. char *pos;
  8170. mg_strlcpy(host, host_header, hostlen);
  8171. host[hostlen - 1] = '\0';
  8172. pos = strchr(host, ':');
  8173. if (pos != NULL) {
  8174. *pos = '\0';
  8175. }
  8176. } else {
  8177. /* Cannot get host from the Host: header.
  8178. * Fallback to our IP address. */
  8179. if (conn) {
  8180. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8181. }
  8182. }
  8183. /* Send host, port, uri and (if it exists) ?query_string */
  8184. if (conn) {
  8185. mg_printf(conn,
  8186. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8187. host,
  8188. (int)ntohs(
  8189. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  8190. conn->request_info.local_uri,
  8191. (conn->request_info.query_string == NULL) ? "" : "?",
  8192. (conn->request_info.query_string == NULL)
  8193. ? ""
  8194. : conn->request_info.query_string);
  8195. }
  8196. }
  8197. static void
  8198. mg_set_handler_type(struct mg_context *ctx,
  8199. const char *uri,
  8200. int handler_type,
  8201. int is_delete_request,
  8202. mg_request_handler handler,
  8203. mg_websocket_connect_handler connect_handler,
  8204. mg_websocket_ready_handler ready_handler,
  8205. mg_websocket_data_handler data_handler,
  8206. mg_websocket_close_handler close_handler,
  8207. mg_authorization_handler auth_handler,
  8208. void *cbdata)
  8209. {
  8210. struct mg_handler_info *tmp_rh, **lastref;
  8211. size_t urilen = strlen(uri);
  8212. if (handler_type == WEBSOCKET_HANDLER) {
  8213. /* assert(handler == NULL); */
  8214. /* assert(is_delete_request || connect_handler!=NULL ||
  8215. * ready_handler!=NULL || data_handler!=NULL ||
  8216. * close_handler!=NULL);
  8217. */
  8218. /* assert(auth_handler == NULL); */
  8219. if (handler != NULL) {
  8220. return;
  8221. }
  8222. if (!is_delete_request && connect_handler == NULL
  8223. && ready_handler == NULL
  8224. && data_handler == NULL
  8225. && close_handler == NULL) {
  8226. return;
  8227. }
  8228. if (auth_handler != NULL) {
  8229. return;
  8230. }
  8231. } else if (handler_type == REQUEST_HANDLER) {
  8232. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8233. * data_handler==NULL && close_handler==NULL); */
  8234. /* assert(is_delete_request || (handler!=NULL));
  8235. */
  8236. /* assert(auth_handler == NULL); */
  8237. if (connect_handler != NULL || ready_handler != NULL
  8238. || data_handler != NULL
  8239. || close_handler != NULL) {
  8240. return;
  8241. }
  8242. if (!is_delete_request && (handler == NULL)) {
  8243. return;
  8244. }
  8245. if (auth_handler != NULL) {
  8246. return;
  8247. }
  8248. } else { /* AUTH_HANDLER */
  8249. /* assert(handler == NULL); */
  8250. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8251. * data_handler==NULL && close_handler==NULL); */
  8252. /* assert(auth_handler != NULL); */
  8253. if (handler != NULL) {
  8254. return;
  8255. }
  8256. if (connect_handler != NULL || ready_handler != NULL
  8257. || data_handler != NULL
  8258. || close_handler != NULL) {
  8259. return;
  8260. }
  8261. if (!is_delete_request && (auth_handler == NULL)) {
  8262. return;
  8263. }
  8264. }
  8265. if (!ctx) {
  8266. return;
  8267. }
  8268. mg_lock_context(ctx);
  8269. /* first try to find an existing handler */
  8270. lastref = &(ctx->handlers);
  8271. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8272. if (tmp_rh->handler_type == handler_type) {
  8273. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8274. if (!is_delete_request) {
  8275. /* update existing handler */
  8276. if (handler_type == REQUEST_HANDLER) {
  8277. tmp_rh->handler = handler;
  8278. } else if (handler_type == WEBSOCKET_HANDLER) {
  8279. tmp_rh->connect_handler = connect_handler;
  8280. tmp_rh->ready_handler = ready_handler;
  8281. tmp_rh->data_handler = data_handler;
  8282. tmp_rh->close_handler = close_handler;
  8283. } else { /* AUTH_HANDLER */
  8284. tmp_rh->auth_handler = auth_handler;
  8285. }
  8286. tmp_rh->cbdata = cbdata;
  8287. } else {
  8288. /* remove existing handler */
  8289. *lastref = tmp_rh->next;
  8290. mg_free(tmp_rh->uri);
  8291. mg_free(tmp_rh);
  8292. }
  8293. mg_unlock_context(ctx);
  8294. return;
  8295. }
  8296. }
  8297. lastref = &(tmp_rh->next);
  8298. }
  8299. if (is_delete_request) {
  8300. /* no handler to set, this was a remove request to a non-existing
  8301. * handler */
  8302. mg_unlock_context(ctx);
  8303. return;
  8304. }
  8305. tmp_rh =
  8306. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8307. if (tmp_rh == NULL) {
  8308. mg_unlock_context(ctx);
  8309. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8310. return;
  8311. }
  8312. tmp_rh->uri = mg_strdup(uri);
  8313. if (!tmp_rh->uri) {
  8314. mg_unlock_context(ctx);
  8315. mg_free(tmp_rh);
  8316. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8317. return;
  8318. }
  8319. tmp_rh->uri_len = urilen;
  8320. if (handler_type == REQUEST_HANDLER) {
  8321. tmp_rh->handler = handler;
  8322. } else if (handler_type == WEBSOCKET_HANDLER) {
  8323. tmp_rh->connect_handler = connect_handler;
  8324. tmp_rh->ready_handler = ready_handler;
  8325. tmp_rh->data_handler = data_handler;
  8326. tmp_rh->close_handler = close_handler;
  8327. } else { /* AUTH_HANDLER */
  8328. tmp_rh->auth_handler = auth_handler;
  8329. }
  8330. tmp_rh->cbdata = cbdata;
  8331. tmp_rh->handler_type = handler_type;
  8332. tmp_rh->next = NULL;
  8333. *lastref = tmp_rh;
  8334. mg_unlock_context(ctx);
  8335. }
  8336. void
  8337. mg_set_request_handler(struct mg_context *ctx,
  8338. const char *uri,
  8339. mg_request_handler handler,
  8340. void *cbdata)
  8341. {
  8342. mg_set_handler_type(ctx,
  8343. uri,
  8344. REQUEST_HANDLER,
  8345. handler == NULL,
  8346. handler,
  8347. NULL,
  8348. NULL,
  8349. NULL,
  8350. NULL,
  8351. NULL,
  8352. cbdata);
  8353. }
  8354. void
  8355. mg_set_websocket_handler(struct mg_context *ctx,
  8356. const char *uri,
  8357. mg_websocket_connect_handler connect_handler,
  8358. mg_websocket_ready_handler ready_handler,
  8359. mg_websocket_data_handler data_handler,
  8360. mg_websocket_close_handler close_handler,
  8361. void *cbdata)
  8362. {
  8363. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8364. && (data_handler == NULL)
  8365. && (close_handler == NULL);
  8366. mg_set_handler_type(ctx,
  8367. uri,
  8368. WEBSOCKET_HANDLER,
  8369. is_delete_request,
  8370. NULL,
  8371. connect_handler,
  8372. ready_handler,
  8373. data_handler,
  8374. close_handler,
  8375. NULL,
  8376. cbdata);
  8377. }
  8378. void
  8379. mg_set_auth_handler(struct mg_context *ctx,
  8380. const char *uri,
  8381. mg_request_handler handler,
  8382. void *cbdata)
  8383. {
  8384. mg_set_handler_type(ctx,
  8385. uri,
  8386. AUTH_HANDLER,
  8387. handler == NULL,
  8388. NULL,
  8389. NULL,
  8390. NULL,
  8391. NULL,
  8392. NULL,
  8393. handler,
  8394. cbdata);
  8395. }
  8396. static int
  8397. get_request_handler(struct mg_connection *conn,
  8398. int handler_type,
  8399. mg_request_handler *handler,
  8400. mg_websocket_connect_handler *connect_handler,
  8401. mg_websocket_ready_handler *ready_handler,
  8402. mg_websocket_data_handler *data_handler,
  8403. mg_websocket_close_handler *close_handler,
  8404. mg_authorization_handler *auth_handler,
  8405. void **cbdata)
  8406. {
  8407. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8408. if (request_info) {
  8409. const char *uri = request_info->local_uri;
  8410. size_t urilen = strlen(uri);
  8411. struct mg_handler_info *tmp_rh;
  8412. if (!conn || !conn->ctx) {
  8413. return 0;
  8414. }
  8415. mg_lock_context(conn->ctx);
  8416. /* first try for an exact match */
  8417. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8418. tmp_rh = tmp_rh->next) {
  8419. if (tmp_rh->handler_type == handler_type) {
  8420. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8421. if (handler_type == WEBSOCKET_HANDLER) {
  8422. *connect_handler = tmp_rh->connect_handler;
  8423. *ready_handler = tmp_rh->ready_handler;
  8424. *data_handler = tmp_rh->data_handler;
  8425. *close_handler = tmp_rh->close_handler;
  8426. } else if (handler_type == REQUEST_HANDLER) {
  8427. *handler = tmp_rh->handler;
  8428. } else { /* AUTH_HANDLER */
  8429. *auth_handler = tmp_rh->auth_handler;
  8430. }
  8431. *cbdata = tmp_rh->cbdata;
  8432. mg_unlock_context(conn->ctx);
  8433. return 1;
  8434. }
  8435. }
  8436. }
  8437. /* next try for a partial match, we will accept uri/something */
  8438. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8439. tmp_rh = tmp_rh->next) {
  8440. if (tmp_rh->handler_type == handler_type) {
  8441. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8442. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8443. if (handler_type == WEBSOCKET_HANDLER) {
  8444. *connect_handler = tmp_rh->connect_handler;
  8445. *ready_handler = tmp_rh->ready_handler;
  8446. *data_handler = tmp_rh->data_handler;
  8447. *close_handler = tmp_rh->close_handler;
  8448. } else if (handler_type == REQUEST_HANDLER) {
  8449. *handler = tmp_rh->handler;
  8450. } else { /* AUTH_HANDLER */
  8451. *auth_handler = tmp_rh->auth_handler;
  8452. }
  8453. *cbdata = tmp_rh->cbdata;
  8454. mg_unlock_context(conn->ctx);
  8455. return 1;
  8456. }
  8457. }
  8458. }
  8459. /* finally try for pattern match */
  8460. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8461. tmp_rh = tmp_rh->next) {
  8462. if (tmp_rh->handler_type == handler_type) {
  8463. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8464. if (handler_type == WEBSOCKET_HANDLER) {
  8465. *connect_handler = tmp_rh->connect_handler;
  8466. *ready_handler = tmp_rh->ready_handler;
  8467. *data_handler = tmp_rh->data_handler;
  8468. *close_handler = tmp_rh->close_handler;
  8469. } else if (handler_type == REQUEST_HANDLER) {
  8470. *handler = tmp_rh->handler;
  8471. } else { /* AUTH_HANDLER */
  8472. *auth_handler = tmp_rh->auth_handler;
  8473. }
  8474. *cbdata = tmp_rh->cbdata;
  8475. mg_unlock_context(conn->ctx);
  8476. return 1;
  8477. }
  8478. }
  8479. }
  8480. mg_unlock_context(conn->ctx);
  8481. }
  8482. return 0; /* none found */
  8483. }
  8484. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8485. static int
  8486. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8487. void *cbdata)
  8488. {
  8489. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8490. if (pcallbacks->websocket_connect) {
  8491. return pcallbacks->websocket_connect(conn);
  8492. }
  8493. /* No handler set - assume "OK" */
  8494. return 0;
  8495. }
  8496. static void
  8497. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8498. {
  8499. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8500. if (pcallbacks->websocket_ready) {
  8501. pcallbacks->websocket_ready(conn);
  8502. }
  8503. }
  8504. static int
  8505. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8506. int bits,
  8507. char *data,
  8508. size_t len,
  8509. void *cbdata)
  8510. {
  8511. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8512. if (pcallbacks->websocket_data) {
  8513. return pcallbacks->websocket_data(conn, bits, data, len);
  8514. }
  8515. /* No handler set - assume "OK" */
  8516. return 1;
  8517. }
  8518. #endif
  8519. /* This is the heart of the Civetweb's logic.
  8520. * This function is called when the request is read, parsed and validated,
  8521. * and Civetweb must decide what action to take: serve a file, or
  8522. * a directory, or call embedded function, etcetera. */
  8523. static void
  8524. handle_request(struct mg_connection *conn)
  8525. {
  8526. if (conn) {
  8527. struct mg_request_info *ri = &conn->request_info;
  8528. char path[PATH_MAX];
  8529. int uri_len, ssl_index;
  8530. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8531. is_put_or_delete_request = 0, is_callback_resource = 0;
  8532. int i;
  8533. struct file file = STRUCT_FILE_INITIALIZER;
  8534. mg_request_handler callback_handler = NULL;
  8535. mg_websocket_connect_handler ws_connect_handler = NULL;
  8536. mg_websocket_ready_handler ws_ready_handler = NULL;
  8537. mg_websocket_data_handler ws_data_handler = NULL;
  8538. mg_websocket_close_handler ws_close_handler = NULL;
  8539. void *callback_data = NULL;
  8540. mg_authorization_handler auth_handler = NULL;
  8541. void *auth_callback_data = NULL;
  8542. #if !defined(NO_FILES)
  8543. time_t curtime = time(NULL);
  8544. char date[64];
  8545. #endif
  8546. path[0] = 0;
  8547. if (!ri) {
  8548. return;
  8549. }
  8550. /* 1. get the request url */
  8551. /* 1.1. split into url and query string */
  8552. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8553. != NULL) {
  8554. *((char *)conn->request_info.query_string++) = '\0';
  8555. }
  8556. uri_len = (int)strlen(ri->local_uri);
  8557. /* 1.2. decode url (if config says so) */
  8558. if (should_decode_url(conn)) {
  8559. mg_url_decode(
  8560. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8561. }
  8562. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is
  8563. * not possible */
  8564. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8565. /* step 1. completed, the url is known now */
  8566. DEBUG_TRACE("URL: %s", ri->local_uri);
  8567. /* 2. do a https redirect, if required */
  8568. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8569. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8570. if (ssl_index >= 0) {
  8571. redirect_to_https_port(conn, ssl_index);
  8572. } else {
  8573. /* A http to https forward port has been specified,
  8574. * but no https port to forward to. */
  8575. send_http_error(conn,
  8576. 503,
  8577. "%s",
  8578. "Error: SSL forward not configured properly");
  8579. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8580. }
  8581. return;
  8582. }
  8583. /* 3. if this ip has limited speed, set it for this connection */
  8584. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8585. get_remote_ip(conn),
  8586. ri->local_uri);
  8587. /* 4. call a "handle everything" callback, if registered */
  8588. if (conn->ctx->callbacks.begin_request != NULL) {
  8589. /* Note that since V1.7 the "begin_request" function is called
  8590. * before an authorization check. If an authorization check is
  8591. * required, use a request_handler instead. */
  8592. i = conn->ctx->callbacks.begin_request(conn);
  8593. if (i > 0) {
  8594. /* callback already processed the request. Store the
  8595. return value as a status code for the access log. */
  8596. conn->status_code = i;
  8597. return;
  8598. } else if (i == 0) {
  8599. /* civetweb should process the request */
  8600. } else {
  8601. /* unspecified - may change with the next version */
  8602. return;
  8603. }
  8604. }
  8605. /* request not yet handled by a handler or redirect, so the request
  8606. * is processed here */
  8607. /* 5. interpret the url to find out how the request must be handled
  8608. */
  8609. /* 5.1. first test, if the request targets the regular http(s)://
  8610. * protocol namespace or the websocket ws(s):// protocol namespace.
  8611. */
  8612. is_websocket_request = is_websocket_protocol(conn);
  8613. /* 5.2. check if the request will be handled by a callback */
  8614. if (get_request_handler(conn,
  8615. is_websocket_request ? WEBSOCKET_HANDLER
  8616. : REQUEST_HANDLER,
  8617. &callback_handler,
  8618. &ws_connect_handler,
  8619. &ws_ready_handler,
  8620. &ws_data_handler,
  8621. &ws_close_handler,
  8622. NULL,
  8623. &callback_data)) {
  8624. /* 5.2.1. A callback will handle this request. All requests
  8625. * handled
  8626. * by a callback have to be considered as requests to a script
  8627. * resource. */
  8628. is_callback_resource = 1;
  8629. is_script_resource = 1;
  8630. is_put_or_delete_request = is_put_or_delete_method(conn);
  8631. } else {
  8632. no_callback_resource:
  8633. /* 5.2.2. No callback is responsible for this request. The URI
  8634. * addresses a file based resource (static content or Lua/cgi
  8635. * scripts in the file system). */
  8636. is_callback_resource = 0;
  8637. interpret_uri(conn,
  8638. path,
  8639. sizeof(path),
  8640. &file,
  8641. &is_found,
  8642. &is_script_resource,
  8643. &is_websocket_request,
  8644. &is_put_or_delete_request);
  8645. }
  8646. /* 6. authorization check */
  8647. /* 6.1. a custom authorization handler is installed */
  8648. if (get_request_handler(conn,
  8649. AUTH_HANDLER,
  8650. NULL,
  8651. NULL,
  8652. NULL,
  8653. NULL,
  8654. NULL,
  8655. &auth_handler,
  8656. &auth_callback_data)) {
  8657. if (!auth_handler(conn, auth_callback_data)) {
  8658. return;
  8659. }
  8660. } else if (is_put_or_delete_request && !is_script_resource
  8661. && !is_callback_resource) {
  8662. /* 6.2. this request is a PUT/DELETE to a real file */
  8663. /* 6.2.1. thus, the server must have real files */
  8664. #if defined(NO_FILES)
  8665. if (1) {
  8666. #else
  8667. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8668. #endif
  8669. /* This server does not have any real files, thus the
  8670. * PUT/DELETE methods are not valid. */
  8671. send_http_error(conn,
  8672. 405,
  8673. "%s method not allowed",
  8674. conn->request_info.request_method);
  8675. return;
  8676. }
  8677. #if !defined(NO_FILES)
  8678. /* 6.2.2. Check if put authorization for static files is
  8679. * available.
  8680. */
  8681. if (!is_authorized_for_put(conn)) {
  8682. send_authorization_request(conn);
  8683. return;
  8684. }
  8685. #endif
  8686. } else {
  8687. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8688. * or it is a PUT or DELETE request to a resource that does not
  8689. * correspond to a file. Check authorization. */
  8690. if (!check_authorization(conn, path)) {
  8691. send_authorization_request(conn);
  8692. return;
  8693. }
  8694. }
  8695. /* request is authorized or does not need authorization */
  8696. /* 7. check if there are request handlers for this uri */
  8697. if (is_callback_resource) {
  8698. if (!is_websocket_request) {
  8699. i = callback_handler(conn, callback_data);
  8700. if (i > 0) {
  8701. /* Do nothing, callback has served the request. Store
  8702. * the
  8703. * return value as status code for the log and discard
  8704. * all
  8705. * data from the client not used by the callback. */
  8706. conn->status_code = i;
  8707. discard_unread_request_data(conn);
  8708. } else {
  8709. /* TODO (high): what if the handler did NOT handle the
  8710. * request */
  8711. /* The last version did handle this as a file request,
  8712. * but
  8713. * since a file request is not always a script resource,
  8714. * the authorization check might be different */
  8715. interpret_uri(conn,
  8716. path,
  8717. sizeof(path),
  8718. &file,
  8719. &is_found,
  8720. &is_script_resource,
  8721. &is_websocket_request,
  8722. &is_put_or_delete_request);
  8723. callback_handler = NULL;
  8724. /* TODO (very low): goto is deprecated but for the
  8725. * moment,
  8726. * a goto is simpler than some curious loop. */
  8727. /* The situation "callback does not handle the request"
  8728. * needs to be reconsidered anyway. */
  8729. goto no_callback_resource;
  8730. }
  8731. } else {
  8732. #if defined(USE_WEBSOCKET)
  8733. handle_websocket_request(conn,
  8734. path,
  8735. is_callback_resource,
  8736. ws_connect_handler,
  8737. ws_ready_handler,
  8738. ws_data_handler,
  8739. ws_close_handler,
  8740. callback_data);
  8741. #endif
  8742. }
  8743. return;
  8744. }
  8745. /* 8. handle websocket requests */
  8746. #if defined(USE_WEBSOCKET)
  8747. if (is_websocket_request) {
  8748. if (is_script_resource) {
  8749. /* Websocket Lua script */
  8750. handle_websocket_request(conn,
  8751. path,
  8752. 0 /* Lua Script */,
  8753. NULL,
  8754. NULL,
  8755. NULL,
  8756. NULL,
  8757. &conn->ctx->callbacks);
  8758. } else {
  8759. #if defined(MG_LEGACY_INTERFACE)
  8760. handle_websocket_request(
  8761. conn,
  8762. path,
  8763. !is_script_resource /* could be deprecated global callback */,
  8764. deprecated_websocket_connect_wrapper,
  8765. deprecated_websocket_ready_wrapper,
  8766. deprecated_websocket_data_wrapper,
  8767. NULL,
  8768. &conn->ctx->callbacks);
  8769. #else
  8770. send_http_error(conn, 404, "%s", "Not found");
  8771. #endif
  8772. }
  8773. return;
  8774. } else
  8775. #endif
  8776. #if defined(NO_FILES)
  8777. /* 9a. In case the server uses only callbacks, this uri is
  8778. * unknown.
  8779. * Then, all request handling ends here. */
  8780. send_http_error(conn, 404, "%s", "Not Found");
  8781. #else
  8782. /* 9b. This request is either for a static file or resource handled
  8783. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8784. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8785. send_http_error(conn, 404, "%s", "Not Found");
  8786. return;
  8787. }
  8788. /* 10. File is handled by a script. */
  8789. if (is_script_resource) {
  8790. handle_file_based_request(conn, path, &file);
  8791. return;
  8792. }
  8793. /* 11. Handle put/delete/mkcol requests */
  8794. if (is_put_or_delete_request) {
  8795. /* 11.1. PUT method */
  8796. if (!strcmp(ri->request_method, "PUT")) {
  8797. put_file(conn, path);
  8798. return;
  8799. }
  8800. /* 11.2. DELETE method */
  8801. if (!strcmp(ri->request_method, "DELETE")) {
  8802. delete_file(conn, path);
  8803. return;
  8804. }
  8805. /* 11.3. MKCOL method */
  8806. if (!strcmp(ri->request_method, "MKCOL")) {
  8807. mkcol(conn, path);
  8808. return;
  8809. }
  8810. /* 11.4. PATCH method
  8811. * This method is not supported for static resources,
  8812. * only for scripts (Lua, CGI) and callbacks. */
  8813. send_http_error(conn,
  8814. 405,
  8815. "%s method not allowed",
  8816. conn->request_info.request_method);
  8817. return;
  8818. }
  8819. /* 11. File does not exist, or it was configured that it should be
  8820. * hidden */
  8821. if (!is_found || (must_hide_file(conn, path))) {
  8822. send_http_error(conn, 404, "%s", "Not found");
  8823. return;
  8824. }
  8825. /* 12. Directory uris should end with a slash */
  8826. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8827. gmt_time_string(date, sizeof(date), &curtime);
  8828. mg_printf(conn,
  8829. "HTTP/1.1 301 Moved Permanently\r\n"
  8830. "Location: %s/\r\n"
  8831. "Date: %s\r\n"
  8832. /* "Cache-Control: private\r\n" (= default) */
  8833. "Content-Length: 0\r\n"
  8834. "Connection: %s\r\n\r\n",
  8835. ri->request_uri,
  8836. date,
  8837. suggest_connection_header(conn));
  8838. return;
  8839. }
  8840. /* 13. Handle other methods than GET/HEAD */
  8841. /* 13.1. Handle PROPFIND */
  8842. if (!strcmp(ri->request_method, "PROPFIND")) {
  8843. handle_propfind(conn, path, &file);
  8844. return;
  8845. }
  8846. /* 13.2. Handle OPTIONS for files */
  8847. if (!strcmp(ri->request_method, "OPTIONS")) {
  8848. /* This standard handler is only used for real files.
  8849. * Scripts should support the OPTIONS method themselves, to allow a
  8850. * maximum flexibility.
  8851. * Lua and CGI scripts may fully support CORS this way (including
  8852. * preflights). */
  8853. send_options(conn);
  8854. return;
  8855. }
  8856. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8857. if (0 != strcmp(ri->request_method, "GET")
  8858. && 0 != strcmp(ri->request_method, "HEAD")) {
  8859. send_http_error(conn,
  8860. 405,
  8861. "%s method not allowed",
  8862. conn->request_info.request_method);
  8863. return;
  8864. }
  8865. /* 14. directories */
  8866. if (file.is_directory) {
  8867. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8868. /* 14.1. use a substitute file */
  8869. /* TODO (high): substitute index may be a script resource.
  8870. * define what should be possible in this case. */
  8871. } else {
  8872. /* 14.2. no substitute file */
  8873. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8874. "yes")) {
  8875. handle_directory_request(conn, path);
  8876. } else {
  8877. send_http_error(conn,
  8878. 403,
  8879. "%s",
  8880. "Error: Directory listing denied");
  8881. }
  8882. return;
  8883. }
  8884. }
  8885. handle_file_based_request(conn, path, &file);
  8886. #endif /* !defined(NO_FILES) */
  8887. #if 0
  8888. /* Perform redirect and auth checks before calling begin_request()
  8889. * handler.
  8890. * Otherwise, begin_request() would need to perform auth checks and
  8891. * redirects. */
  8892. #endif
  8893. }
  8894. return;
  8895. }
  8896. static void
  8897. handle_file_based_request(struct mg_connection *conn,
  8898. const char *path,
  8899. struct file *file)
  8900. {
  8901. if (!conn || !conn->ctx) {
  8902. return;
  8903. }
  8904. if (0) {
  8905. #ifdef USE_LUA
  8906. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8907. strlen(
  8908. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8909. path) > 0) {
  8910. /* Lua server page: an SSI like page containing mostly plain html
  8911. * code
  8912. * plus some tags with server generated contents. */
  8913. handle_lsp_request(conn, path, file, NULL);
  8914. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8915. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8916. path) > 0) {
  8917. /* Lua in-server module script: a CGI like script used to generate
  8918. * the
  8919. * entire reply. */
  8920. mg_exec_lua_script(conn, path, NULL);
  8921. #endif
  8922. #if defined(USE_DUKTAPE)
  8923. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8924. strlen(
  8925. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8926. path) > 0) {
  8927. /* Call duktape to generate the page */
  8928. mg_exec_duktape_script(conn, path);
  8929. #endif
  8930. #if !defined(NO_CGI)
  8931. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8932. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8933. path) > 0) {
  8934. /* CGI scripts may support all HTTP methods */
  8935. handle_cgi_request(conn, path);
  8936. #endif /* !NO_CGI */
  8937. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8938. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8939. path) > 0) {
  8940. handle_ssi_file_request(conn, path, file);
  8941. #if !defined(NO_CACHING)
  8942. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8943. /* Send 304 "Not Modified" - this must not send any body data */
  8944. handle_not_modified_static_file_request(conn, file);
  8945. #endif /* !NO_CACHING */
  8946. } else {
  8947. handle_static_file_request(conn, path, file, NULL);
  8948. }
  8949. }
  8950. static void
  8951. close_all_listening_sockets(struct mg_context *ctx)
  8952. {
  8953. unsigned int i;
  8954. if (!ctx) {
  8955. return;
  8956. }
  8957. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8958. closesocket(ctx->listening_sockets[i].sock);
  8959. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8960. }
  8961. mg_free(ctx->listening_sockets);
  8962. ctx->listening_sockets = NULL;
  8963. mg_free(ctx->listening_ports);
  8964. ctx->listening_ports = NULL;
  8965. }
  8966. /* Valid listening port specification is: [ip_address:]port[s]
  8967. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8968. * Examples for IPv6: [::]:80, [::1]:80,
  8969. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8970. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8971. static int
  8972. parse_port_string(const struct vec *vec, struct socket *so)
  8973. {
  8974. unsigned int a, b, c, d, port;
  8975. int ch, len;
  8976. #if defined(USE_IPV6)
  8977. char buf[100] = {0};
  8978. #endif
  8979. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8980. * Also, all-zeroes in the socket address means binding to all addresses
  8981. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8982. memset(so, 0, sizeof(*so));
  8983. so->lsa.sin.sin_family = AF_INET;
  8984. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8985. == 5) {
  8986. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8987. so->lsa.sin.sin_addr.s_addr =
  8988. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8989. so->lsa.sin.sin_port = htons((uint16_t)port);
  8990. #if defined(USE_IPV6)
  8991. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8992. && mg_inet_pton(
  8993. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8994. /* IPv6 address, examples: see above */
  8995. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  8996. */
  8997. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8998. #endif
  8999. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9000. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9001. so->lsa.sin.sin_port = htons((uint16_t)port);
  9002. } else {
  9003. /* Parsing failure. Make port invalid. */
  9004. port = 0;
  9005. len = 0;
  9006. }
  9007. /* sscanf and the option splitting code ensure the following condition
  9008. */
  9009. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9010. return 0;
  9011. }
  9012. ch = vec->ptr[len]; /* Next character after the port number */
  9013. so->is_ssl = (ch == 's');
  9014. so->ssl_redir = (ch == 'r');
  9015. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9016. return is_valid_port(port)
  9017. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9018. }
  9019. static int
  9020. set_ports_option(struct mg_context *ctx)
  9021. {
  9022. const char *list;
  9023. int on = 1;
  9024. #if defined(USE_IPV6)
  9025. int off = 0;
  9026. #endif
  9027. struct vec vec;
  9028. struct socket so, *ptr;
  9029. in_port_t *portPtr;
  9030. union usa usa;
  9031. socklen_t len;
  9032. int portsTotal = 0;
  9033. int portsOk = 0;
  9034. if (!ctx) {
  9035. return 0;
  9036. }
  9037. memset(&so, 0, sizeof(so));
  9038. memset(&usa, 0, sizeof(usa));
  9039. len = sizeof(usa);
  9040. list = ctx->config[LISTENING_PORTS];
  9041. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9042. portsTotal++;
  9043. if (!parse_port_string(&vec, &so)) {
  9044. mg_cry(fc(ctx),
  9045. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9046. (int)vec.len,
  9047. vec.ptr,
  9048. portsTotal,
  9049. "[IP_ADDRESS:]PORT[s|r]");
  9050. continue;
  9051. }
  9052. #if !defined(NO_SSL)
  9053. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9054. mg_cry(fc(ctx),
  9055. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9056. "option set?",
  9057. portsTotal);
  9058. continue;
  9059. }
  9060. #endif
  9061. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9062. == INVALID_SOCKET) {
  9063. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9064. continue;
  9065. }
  9066. #ifdef _WIN32
  9067. /* Windows SO_REUSEADDR lets many procs binds to a
  9068. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9069. * if someone already has the socket -- DTL */
  9070. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9071. * Windows might need a few seconds before
  9072. * the same port can be used again in the
  9073. * same process, so a short Sleep may be
  9074. * required between mg_stop and mg_start.
  9075. */
  9076. if (setsockopt(so.sock,
  9077. SOL_SOCKET,
  9078. SO_EXCLUSIVEADDRUSE,
  9079. (SOCK_OPT_TYPE)&on,
  9080. sizeof(on)) != 0) {
  9081. mg_cry(fc(ctx),
  9082. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9083. portsTotal);
  9084. }
  9085. #else
  9086. if (setsockopt(so.sock,
  9087. SOL_SOCKET,
  9088. SO_REUSEADDR,
  9089. (SOCK_OPT_TYPE)&on,
  9090. sizeof(on)) != 0) {
  9091. mg_cry(fc(ctx),
  9092. "cannot set socket option SO_REUSEADDR (entry %i)",
  9093. portsTotal);
  9094. }
  9095. #endif
  9096. #if defined(USE_IPV6)
  9097. if (so.lsa.sa.sa_family == AF_INET6
  9098. && setsockopt(so.sock,
  9099. IPPROTO_IPV6,
  9100. IPV6_V6ONLY,
  9101. (void *)&off,
  9102. sizeof(off)) != 0) {
  9103. mg_cry(fc(ctx),
  9104. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9105. portsTotal);
  9106. }
  9107. #endif
  9108. if (so.lsa.sa.sa_family == AF_INET) {
  9109. len = sizeof(so.lsa.sin);
  9110. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9111. mg_cry(fc(ctx),
  9112. "cannot bind to %.*s: %d (%s)",
  9113. (int)vec.len,
  9114. vec.ptr,
  9115. (int)ERRNO,
  9116. strerror(errno));
  9117. closesocket(so.sock);
  9118. so.sock = INVALID_SOCKET;
  9119. continue;
  9120. }
  9121. }
  9122. #if defined(USE_IPV6)
  9123. else if (so.lsa.sa.sa_family == AF_INET6) {
  9124. len = sizeof(so.lsa.sin6);
  9125. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9126. mg_cry(fc(ctx),
  9127. "cannot bind to IPv6 %.*s: %d (%s)",
  9128. (int)vec.len,
  9129. vec.ptr,
  9130. (int)ERRNO,
  9131. strerror(errno));
  9132. closesocket(so.sock);
  9133. so.sock = INVALID_SOCKET;
  9134. continue;
  9135. }
  9136. }
  9137. #endif
  9138. else {
  9139. mg_cry(fc(ctx),
  9140. "cannot bind: address family not supported (entry %i)",
  9141. portsTotal);
  9142. continue;
  9143. }
  9144. if (listen(so.sock, SOMAXCONN) != 0) {
  9145. mg_cry(fc(ctx),
  9146. "cannot listen to %.*s: %d (%s)",
  9147. (int)vec.len,
  9148. vec.ptr,
  9149. (int)ERRNO,
  9150. strerror(errno));
  9151. closesocket(so.sock);
  9152. so.sock = INVALID_SOCKET;
  9153. continue;
  9154. }
  9155. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  9156. int err = (int)ERRNO;
  9157. mg_cry(fc(ctx),
  9158. "call to getsockname failed %.*s: %d (%s)",
  9159. (int)vec.len,
  9160. vec.ptr,
  9161. err,
  9162. strerror(errno));
  9163. closesocket(so.sock);
  9164. so.sock = INVALID_SOCKET;
  9165. continue;
  9166. }
  9167. if ((ptr = (struct socket *)
  9168. mg_realloc(ctx->listening_sockets,
  9169. (ctx->num_listening_sockets + 1)
  9170. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9171. mg_cry(fc(ctx), "%s", "Out of memory");
  9172. closesocket(so.sock);
  9173. so.sock = INVALID_SOCKET;
  9174. continue;
  9175. }
  9176. if ((portPtr =
  9177. (in_port_t *)mg_realloc(ctx->listening_ports,
  9178. (ctx->num_listening_sockets + 1)
  9179. * sizeof(ctx->listening_ports[0])))
  9180. == NULL) {
  9181. mg_cry(fc(ctx), "%s", "Out of memory");
  9182. closesocket(so.sock);
  9183. so.sock = INVALID_SOCKET;
  9184. mg_free(ptr);
  9185. continue;
  9186. }
  9187. set_close_on_exec(so.sock, fc(ctx));
  9188. ctx->listening_sockets = ptr;
  9189. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9190. ctx->listening_ports = portPtr;
  9191. ctx->listening_ports[ctx->num_listening_sockets] =
  9192. ntohs(usa.sin.sin_port);
  9193. ctx->num_listening_sockets++;
  9194. portsOk++;
  9195. }
  9196. if (portsOk != portsTotal) {
  9197. close_all_listening_sockets(ctx);
  9198. portsOk = 0;
  9199. }
  9200. return portsOk;
  9201. }
  9202. static const char *
  9203. header_val(const struct mg_connection *conn, const char *header)
  9204. {
  9205. const char *header_value;
  9206. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9207. return "-";
  9208. } else {
  9209. return header_value;
  9210. }
  9211. }
  9212. static void
  9213. log_access(const struct mg_connection *conn)
  9214. {
  9215. const struct mg_request_info *ri;
  9216. struct file fi;
  9217. char date[64], src_addr[IP_ADDR_STR_LEN];
  9218. struct tm *tm;
  9219. const char *referer;
  9220. const char *user_agent;
  9221. char buf[4096];
  9222. if (!conn || !conn->ctx) {
  9223. return;
  9224. }
  9225. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9226. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9227. == 0) {
  9228. fi.fp = NULL;
  9229. }
  9230. } else {
  9231. fi.fp = NULL;
  9232. }
  9233. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9234. return;
  9235. }
  9236. tm = localtime(&conn->conn_birth_time);
  9237. if (tm != NULL) {
  9238. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9239. } else {
  9240. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9241. date[sizeof(date) - 1] = '\0';
  9242. }
  9243. ri = &conn->request_info;
  9244. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9245. referer = header_val(conn, "Referer");
  9246. user_agent = header_val(conn, "User-Agent");
  9247. mg_snprintf(conn,
  9248. NULL, /* Ignore truncation in access log */
  9249. buf,
  9250. sizeof(buf),
  9251. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9252. src_addr,
  9253. ri->remote_user == NULL ? "-" : ri->remote_user,
  9254. date,
  9255. ri->request_method ? ri->request_method : "-",
  9256. ri->request_uri ? ri->request_uri : "-",
  9257. ri->query_string ? "?" : "",
  9258. ri->query_string ? ri->query_string : "",
  9259. ri->http_version,
  9260. conn->status_code,
  9261. conn->num_bytes_sent,
  9262. referer,
  9263. user_agent);
  9264. if (conn->ctx->callbacks.log_access) {
  9265. conn->ctx->callbacks.log_access(conn, buf);
  9266. }
  9267. if (fi.fp) {
  9268. flockfile(fi.fp);
  9269. fprintf(fi.fp, "%s\n", buf);
  9270. fflush(fi.fp);
  9271. funlockfile(fi.fp);
  9272. mg_fclose(&fi);
  9273. }
  9274. }
  9275. /* Verify given socket address against the ACL.
  9276. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9277. */
  9278. static int
  9279. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9280. {
  9281. int allowed, flag;
  9282. uint32_t net, mask;
  9283. struct vec vec;
  9284. if (ctx) {
  9285. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9286. /* If any ACL is set, deny by default */
  9287. allowed = list == NULL ? '+' : '-';
  9288. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9289. flag = vec.ptr[0];
  9290. if ((flag != '+' && flag != '-')
  9291. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9292. mg_cry(fc(ctx),
  9293. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9294. __func__);
  9295. return -1;
  9296. }
  9297. if (net == (remote_ip & mask)) {
  9298. allowed = flag;
  9299. }
  9300. }
  9301. return allowed == '+';
  9302. }
  9303. return -1;
  9304. }
  9305. #if !defined(_WIN32)
  9306. static int
  9307. set_uid_option(struct mg_context *ctx)
  9308. {
  9309. struct passwd *pw;
  9310. if (ctx) {
  9311. const char *uid = ctx->config[RUN_AS_USER];
  9312. int success = 0;
  9313. if (uid == NULL) {
  9314. success = 1;
  9315. } else {
  9316. if ((pw = getpwnam(uid)) == NULL) {
  9317. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9318. } else if (setgid(pw->pw_gid) == -1) {
  9319. mg_cry(fc(ctx),
  9320. "%s: setgid(%s): %s",
  9321. __func__,
  9322. uid,
  9323. strerror(errno));
  9324. } else if (setgroups(0, NULL)) {
  9325. mg_cry(fc(ctx),
  9326. "%s: setgroups(): %s",
  9327. __func__,
  9328. strerror(errno));
  9329. } else if (setuid(pw->pw_uid) == -1) {
  9330. mg_cry(fc(ctx),
  9331. "%s: setuid(%s): %s",
  9332. __func__,
  9333. uid,
  9334. strerror(errno));
  9335. } else {
  9336. success = 1;
  9337. }
  9338. }
  9339. return success;
  9340. }
  9341. return 0;
  9342. }
  9343. #endif /* !_WIN32 */
  9344. static void
  9345. tls_dtor(void *key)
  9346. {
  9347. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9348. /* key == pthread_getspecific(sTlsKey); */
  9349. if (tls) {
  9350. if (tls->is_master == 2) {
  9351. tls->is_master = -3; /* Mark memory as dead */
  9352. mg_free(tls);
  9353. }
  9354. }
  9355. pthread_setspecific(sTlsKey, NULL);
  9356. }
  9357. #if !defined(NO_SSL)
  9358. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9359. static unsigned long
  9360. ssl_id_callback(void)
  9361. {
  9362. #ifdef _WIN32
  9363. return GetCurrentThreadId();
  9364. #else
  9365. #ifdef __clang__
  9366. #pragma clang diagnostic push
  9367. #pragma clang diagnostic ignored "-Wunreachable-code"
  9368. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9369. * or not, so one of the two conditions will be unreachable by construction.
  9370. * Unfortunately the C standard does not define a way to check this at
  9371. * compile time, since the #if preprocessor conditions can not use the sizeof
  9372. * operator as an argument. */
  9373. #endif
  9374. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9375. /* This is the problematic case for CRYPTO_set_id_callback:
  9376. * The OS pthread_t can not be cast to unsigned long. */
  9377. struct mg_workerTLS *tls =
  9378. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9379. if (tls == NULL) {
  9380. /* SSL called from an unknown thread: Create some thread index.
  9381. */
  9382. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9383. tls->is_master = -2; /* -2 means "3rd party thread" */
  9384. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9385. pthread_setspecific(sTlsKey, tls);
  9386. }
  9387. return tls->thread_idx;
  9388. } else {
  9389. /* pthread_t may be any data type, so a simple cast to unsigned long
  9390. * can rise a warning/error, depending on the platform.
  9391. * Here memcpy is used as an anything-to-anything cast. */
  9392. unsigned long ret = 0;
  9393. pthread_t t = pthread_self();
  9394. memcpy(&ret, &t, sizeof(pthread_t));
  9395. return ret;
  9396. }
  9397. #ifdef __clang__
  9398. #pragma clang diagnostic pop
  9399. #endif
  9400. #endif
  9401. }
  9402. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9403. static const char *ssl_error(void);
  9404. static int
  9405. refresh_trust(struct mg_connection *conn)
  9406. {
  9407. static int reload_lock = 0;
  9408. static long int data_check = 0;
  9409. struct stat cert_buf;
  9410. long int t;
  9411. char *pem;
  9412. int should_verify_peer;
  9413. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9414. && conn->ctx->callbacks.init_ssl == NULL) {
  9415. return 0;
  9416. }
  9417. t = data_check;
  9418. if (stat(pem, &cert_buf) != -1) {
  9419. t = (long int)cert_buf.st_mtime;
  9420. }
  9421. if (data_check != t) {
  9422. data_check = t;
  9423. should_verify_peer =
  9424. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9425. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9426. == 0);
  9427. if (should_verify_peer) {
  9428. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9429. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9430. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9431. ca_file,
  9432. ca_path) != 1) {
  9433. mg_cry(fc(conn->ctx),
  9434. "SSL_CTX_load_verify_locations error: %s "
  9435. "ssl_verify_peer requires setting "
  9436. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9437. "present in "
  9438. "the .conf file?",
  9439. ssl_error());
  9440. return 0;
  9441. }
  9442. }
  9443. if (!reload_lock) {
  9444. reload_lock = 1;
  9445. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9446. return 0;
  9447. }
  9448. reload_lock = 0;
  9449. }
  9450. }
  9451. /* lock while cert is reloading */
  9452. while (reload_lock) {
  9453. sleep(1);
  9454. }
  9455. return 1;
  9456. }
  9457. static pthread_mutex_t *ssl_mutexes;
  9458. static int
  9459. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9460. {
  9461. int ret, err;
  9462. int short_trust;
  9463. if (!conn) {
  9464. return 0;
  9465. }
  9466. short_trust =
  9467. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9468. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9469. if (short_trust) {
  9470. int trust_ret = refresh_trust(conn);
  9471. if (!trust_ret) {
  9472. return trust_ret;
  9473. }
  9474. }
  9475. conn->ssl = SSL_new(s);
  9476. if (conn->ssl == NULL) {
  9477. return 0;
  9478. }
  9479. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9480. if (ret != 1) {
  9481. err = SSL_get_error(conn->ssl, ret);
  9482. (void)err; /* TODO: set some error message */
  9483. SSL_free(conn->ssl);
  9484. conn->ssl = NULL;
  9485. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9486. /* see
  9487. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9488. ERR_remove_state(0);
  9489. return 0;
  9490. }
  9491. ret = func(conn->ssl);
  9492. if (ret != 1) {
  9493. err = SSL_get_error(conn->ssl, ret);
  9494. (void)err; /* TODO: set some error message */
  9495. SSL_free(conn->ssl);
  9496. conn->ssl = NULL;
  9497. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9498. /* see
  9499. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9500. ERR_remove_state(0);
  9501. return 0;
  9502. }
  9503. return 1;
  9504. }
  9505. /* Return OpenSSL error message (from CRYPTO lib) */
  9506. static const char *
  9507. ssl_error(void)
  9508. {
  9509. unsigned long err;
  9510. err = ERR_get_error();
  9511. return err == 0 ? "" : ERR_error_string(err, NULL);
  9512. }
  9513. static void
  9514. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9515. {
  9516. (void)line;
  9517. (void)file;
  9518. if (mode & 1) {
  9519. /* 1 is CRYPTO_LOCK */
  9520. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9521. } else {
  9522. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9523. }
  9524. }
  9525. #if !defined(NO_SSL_DL)
  9526. static void *
  9527. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9528. {
  9529. union {
  9530. void *p;
  9531. void (*fp)(void);
  9532. } u;
  9533. void *dll_handle;
  9534. struct ssl_func *fp;
  9535. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9536. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9537. return NULL;
  9538. }
  9539. for (fp = sw; fp->name != NULL; fp++) {
  9540. #ifdef _WIN32
  9541. /* GetProcAddress() returns pointer to function */
  9542. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9543. #else
  9544. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9545. * pointers to function pointers. We need to use a union to make a
  9546. * cast. */
  9547. u.p = dlsym(dll_handle, fp->name);
  9548. #endif /* _WIN32 */
  9549. if (u.fp == NULL) {
  9550. mg_cry(fc(ctx),
  9551. "%s: %s: cannot find %s",
  9552. __func__,
  9553. dll_name,
  9554. fp->name);
  9555. dlclose(dll_handle);
  9556. return NULL;
  9557. } else {
  9558. fp->ptr = u.fp;
  9559. }
  9560. }
  9561. return dll_handle;
  9562. }
  9563. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9564. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9565. #endif /* NO_SSL_DL */
  9566. #if defined(SSL_ALREADY_INITIALIZED)
  9567. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9568. #else
  9569. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9570. #endif
  9571. static int
  9572. initialize_ssl(struct mg_context *ctx)
  9573. {
  9574. int i;
  9575. size_t size;
  9576. #if !defined(NO_SSL_DL)
  9577. if (!cryptolib_dll_handle) {
  9578. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9579. if (!cryptolib_dll_handle) {
  9580. return 0;
  9581. }
  9582. }
  9583. #endif /* NO_SSL_DL */
  9584. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9585. return 1;
  9586. }
  9587. /* Initialize locking callbacks, needed for thread safety.
  9588. * http://www.openssl.org/support/faq.html#PROG1
  9589. */
  9590. i = CRYPTO_num_locks();
  9591. if (i < 0) {
  9592. i = 0;
  9593. }
  9594. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9595. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9596. mg_cry(fc(ctx),
  9597. "%s: cannot allocate mutexes: %s",
  9598. __func__,
  9599. ssl_error());
  9600. return 0;
  9601. }
  9602. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9603. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9604. }
  9605. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9606. CRYPTO_set_id_callback(&ssl_id_callback);
  9607. return 1;
  9608. }
  9609. static int
  9610. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9611. {
  9612. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9613. mg_cry(fc(ctx),
  9614. "%s: cannot open certificate file %s: %s",
  9615. __func__,
  9616. pem,
  9617. ssl_error());
  9618. return 0;
  9619. }
  9620. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9621. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9622. mg_cry(fc(ctx),
  9623. "%s: cannot open private key file %s: %s",
  9624. __func__,
  9625. pem,
  9626. ssl_error());
  9627. return 0;
  9628. }
  9629. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9630. mg_cry(fc(ctx),
  9631. "%s: certificate and private key do not match: %s",
  9632. __func__,
  9633. pem);
  9634. return 0;
  9635. }
  9636. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9637. mg_cry(fc(ctx),
  9638. "%s: cannot use certificate chain file %s: %s",
  9639. __func__,
  9640. pem,
  9641. ssl_error());
  9642. return 0;
  9643. }
  9644. return 1;
  9645. }
  9646. static long
  9647. ssl_get_protocol(int version_id)
  9648. {
  9649. long ret = SSL_OP_ALL;
  9650. if (version_id > 0)
  9651. ret |= SSL_OP_NO_SSLv2;
  9652. if (version_id > 1)
  9653. ret |= SSL_OP_NO_SSLv3;
  9654. if (version_id > 2)
  9655. ret |= SSL_OP_NO_TLSv1;
  9656. if (version_id > 3)
  9657. ret |= SSL_OP_NO_TLSv1_1;
  9658. return ret;
  9659. }
  9660. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9661. static int
  9662. set_ssl_option(struct mg_context *ctx)
  9663. {
  9664. const char *pem;
  9665. int callback_ret;
  9666. int should_verify_peer;
  9667. const char *ca_path;
  9668. const char *ca_file;
  9669. int use_default_verify_paths;
  9670. int verify_depth;
  9671. time_t now_rt = time(NULL);
  9672. struct timespec now_mt;
  9673. md5_byte_t ssl_context_id[16];
  9674. md5_state_t md5state;
  9675. int protocol_ver;
  9676. /* If PEM file is not specified and the init_ssl callback
  9677. * is not specified, skip SSL initialization. */
  9678. if (!ctx) {
  9679. return 0;
  9680. }
  9681. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9682. && ctx->callbacks.init_ssl == NULL) {
  9683. return 1;
  9684. }
  9685. if (!initialize_ssl(ctx)) {
  9686. return 0;
  9687. }
  9688. #if !defined(NO_SSL_DL)
  9689. if (!ssllib_dll_handle) {
  9690. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9691. if (!ssllib_dll_handle) {
  9692. return 0;
  9693. }
  9694. }
  9695. #endif /* NO_SSL_DL */
  9696. /* Initialize SSL library */
  9697. SSL_library_init();
  9698. SSL_load_error_strings();
  9699. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9700. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9701. return 0;
  9702. }
  9703. SSL_CTX_clear_options(ctx->ssl_ctx,
  9704. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9705. | SSL_OP_NO_TLSv1_1);
  9706. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9707. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9708. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9709. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9710. /* If a callback has been specified, call it. */
  9711. callback_ret =
  9712. (ctx->callbacks.init_ssl == NULL)
  9713. ? 0
  9714. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9715. /* If callback returns 0, civetweb sets up the SSL certificate.
  9716. * If it returns 1, civetweb assumes the calback already did this.
  9717. * If it returns -1, initializing ssl fails. */
  9718. if (callback_ret < 0) {
  9719. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9720. return 0;
  9721. }
  9722. if (callback_ret > 0) {
  9723. if (pem != NULL) {
  9724. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9725. }
  9726. return 1;
  9727. }
  9728. /* Use some UID as session context ID. */
  9729. md5_init(&md5state);
  9730. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9731. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9732. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9733. md5_append(&md5state,
  9734. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9735. strlen(ctx->config[LISTENING_PORTS]));
  9736. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9737. md5_finish(&md5state, ssl_context_id);
  9738. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9739. (const unsigned char *)&ssl_context_id,
  9740. sizeof(ssl_context_id));
  9741. if (pem != NULL) {
  9742. if (!ssl_use_pem_file(ctx, pem)) {
  9743. return 0;
  9744. }
  9745. }
  9746. should_verify_peer =
  9747. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9748. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9749. use_default_verify_paths =
  9750. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9751. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9752. if (should_verify_peer) {
  9753. ca_path = ctx->config[SSL_CA_PATH];
  9754. ca_file = ctx->config[SSL_CA_FILE];
  9755. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9756. != 1) {
  9757. mg_cry(fc(ctx),
  9758. "SSL_CTX_load_verify_locations error: %s "
  9759. "ssl_verify_peer requires setting "
  9760. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9761. "present in "
  9762. "the .conf file?",
  9763. ssl_error());
  9764. return 0;
  9765. }
  9766. SSL_CTX_set_verify(ctx->ssl_ctx,
  9767. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9768. NULL);
  9769. if (use_default_verify_paths
  9770. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9771. mg_cry(fc(ctx),
  9772. "SSL_CTX_set_default_verify_paths error: %s",
  9773. ssl_error());
  9774. return 0;
  9775. }
  9776. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9777. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9778. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9779. }
  9780. }
  9781. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9782. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9783. != 1) {
  9784. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9785. }
  9786. }
  9787. return 1;
  9788. }
  9789. static void
  9790. uninitialize_ssl(struct mg_context *ctx)
  9791. {
  9792. int i;
  9793. (void)ctx;
  9794. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9795. /* Shutdown according to
  9796. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9797. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9798. */
  9799. CRYPTO_set_locking_callback(NULL);
  9800. CRYPTO_set_id_callback(NULL);
  9801. ENGINE_cleanup();
  9802. CONF_modules_unload(1);
  9803. ERR_free_strings();
  9804. EVP_cleanup();
  9805. CRYPTO_cleanup_all_ex_data();
  9806. ERR_remove_state(0);
  9807. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9808. pthread_mutex_destroy(&ssl_mutexes[i]);
  9809. }
  9810. mg_free(ssl_mutexes);
  9811. ssl_mutexes = NULL;
  9812. }
  9813. }
  9814. #endif /* !NO_SSL */
  9815. static int
  9816. set_gpass_option(struct mg_context *ctx)
  9817. {
  9818. if (ctx) {
  9819. struct file file = STRUCT_FILE_INITIALIZER;
  9820. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9821. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9822. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9823. return 0;
  9824. }
  9825. return 1;
  9826. }
  9827. return 0;
  9828. }
  9829. static int
  9830. set_acl_option(struct mg_context *ctx)
  9831. {
  9832. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9833. }
  9834. static void
  9835. reset_per_request_attributes(struct mg_connection *conn)
  9836. {
  9837. if (!conn) {
  9838. return;
  9839. }
  9840. conn->path_info = NULL;
  9841. conn->num_bytes_sent = conn->consumed_content = 0;
  9842. conn->status_code = -1;
  9843. conn->is_chunked = 0;
  9844. conn->must_close = conn->request_len = conn->throttle = 0;
  9845. conn->request_info.content_length = -1;
  9846. conn->request_info.remote_user = NULL;
  9847. conn->request_info.request_method = NULL;
  9848. conn->request_info.request_uri = NULL;
  9849. conn->request_info.local_uri = NULL;
  9850. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9851. * local_uri and request_uri */
  9852. conn->request_info.http_version = NULL;
  9853. conn->request_info.num_headers = 0;
  9854. conn->data_len = 0;
  9855. conn->chunk_remainder = 0;
  9856. conn->internal_error = 0;
  9857. }
  9858. static int
  9859. set_sock_timeout(SOCKET sock, int milliseconds)
  9860. {
  9861. int r0 = 0, r1, r2;
  9862. #ifdef _WIN32
  9863. /* Windows specific */
  9864. DWORD tv = (DWORD)milliseconds;
  9865. #else
  9866. /* Linux, ... (not Windows) */
  9867. struct timeval tv;
  9868. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9869. * max. time waiting for the acknowledged of TCP data before the connection
  9870. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9871. * If this option is not set, the default timeout of 20-30 minutes is used.
  9872. */
  9873. /* #define TCP_USER_TIMEOUT (18) */
  9874. #if defined(TCP_USER_TIMEOUT)
  9875. unsigned int uto = (unsigned int)milliseconds;
  9876. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9877. #endif
  9878. memset(&tv, 0, sizeof(tv));
  9879. tv.tv_sec = milliseconds / 1000;
  9880. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9881. #endif /* _WIN32 */
  9882. r1 = setsockopt(
  9883. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9884. r2 = setsockopt(
  9885. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9886. return r0 || r1 || r2;
  9887. }
  9888. static int
  9889. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  9890. {
  9891. if (setsockopt(sock,
  9892. IPPROTO_TCP,
  9893. TCP_NODELAY,
  9894. (SOCK_OPT_TYPE)&nodelay_on,
  9895. sizeof(nodelay_on)) != 0) {
  9896. /* Error */
  9897. return 1;
  9898. }
  9899. /* OK */
  9900. return 0;
  9901. }
  9902. static void
  9903. close_socket_gracefully(struct mg_connection *conn)
  9904. {
  9905. #if defined(_WIN32)
  9906. char buf[MG_BUF_LEN];
  9907. int n;
  9908. #endif
  9909. struct linger linger;
  9910. if (!conn) {
  9911. return;
  9912. }
  9913. /* Set linger option to avoid socket hanging out after close. This
  9914. * prevent
  9915. * ephemeral port exhaust problem under high QPS. */
  9916. linger.l_onoff = 1;
  9917. linger.l_linger = 1;
  9918. if (setsockopt(conn->client.sock,
  9919. SOL_SOCKET,
  9920. SO_LINGER,
  9921. (char *)&linger,
  9922. sizeof(linger)) != 0) {
  9923. mg_cry(conn,
  9924. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9925. __func__,
  9926. strerror(ERRNO));
  9927. }
  9928. /* Send FIN to the client */
  9929. shutdown(conn->client.sock, SHUT_WR);
  9930. set_non_blocking_mode(conn->client.sock);
  9931. #if defined(_WIN32)
  9932. /* Read and discard pending incoming data. If we do not do that and
  9933. * close
  9934. * the socket, the data in the send buffer may be discarded. This
  9935. * behaviour is seen on Windows, when client keeps sending data
  9936. * when server decides to close the connection; then when client
  9937. * does recv() it gets no data back. */
  9938. do {
  9939. n = pull(
  9940. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9941. } while (n > 0);
  9942. #endif
  9943. /* Now we know that our FIN is ACK-ed, safe to close */
  9944. closesocket(conn->client.sock);
  9945. conn->client.sock = INVALID_SOCKET;
  9946. }
  9947. static void
  9948. close_connection(struct mg_connection *conn)
  9949. {
  9950. if (!conn || !conn->ctx) {
  9951. return;
  9952. }
  9953. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9954. if (conn->lua_websocket_state) {
  9955. lua_websocket_close(conn, conn->lua_websocket_state);
  9956. conn->lua_websocket_state = NULL;
  9957. }
  9958. #endif
  9959. /* call the connection_close callback if assigned */
  9960. if ((conn->ctx->callbacks.connection_close != NULL)
  9961. && (conn->ctx->context_type == 1)) {
  9962. conn->ctx->callbacks.connection_close(conn);
  9963. }
  9964. mg_lock_connection(conn);
  9965. conn->must_close = 1;
  9966. #ifndef NO_SSL
  9967. if (conn->ssl != NULL) {
  9968. /* Run SSL_shutdown twice to ensure completly close SSL connection
  9969. */
  9970. SSL_shutdown(conn->ssl);
  9971. SSL_free(conn->ssl);
  9972. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9973. /* see
  9974. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9975. ERR_remove_state(0);
  9976. conn->ssl = NULL;
  9977. }
  9978. #endif
  9979. if (conn->client.sock != INVALID_SOCKET) {
  9980. close_socket_gracefully(conn);
  9981. conn->client.sock = INVALID_SOCKET;
  9982. }
  9983. mg_unlock_connection(conn);
  9984. }
  9985. void
  9986. mg_close_connection(struct mg_connection *conn)
  9987. {
  9988. struct mg_context *client_ctx = NULL;
  9989. unsigned int i;
  9990. if (conn == NULL) {
  9991. return;
  9992. }
  9993. if (conn->ctx->context_type == 2) {
  9994. client_ctx = conn->ctx;
  9995. /* client context: loops must end */
  9996. conn->ctx->stop_flag = 1;
  9997. }
  9998. #ifndef NO_SSL
  9999. if (conn->client_ssl_ctx != NULL) {
  10000. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10001. }
  10002. #endif
  10003. close_connection(conn);
  10004. if (client_ctx != NULL) {
  10005. /* join worker thread and free context */
  10006. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10007. if (client_ctx->workerthreadids[i] != 0) {
  10008. mg_join_thread(client_ctx->workerthreadids[i]);
  10009. }
  10010. }
  10011. mg_free(client_ctx->workerthreadids);
  10012. mg_free(client_ctx);
  10013. (void)pthread_mutex_destroy(&conn->mutex);
  10014. mg_free(conn);
  10015. }
  10016. }
  10017. static struct mg_connection *
  10018. mg_connect_client_impl(const struct mg_client_options *client_options,
  10019. int use_ssl,
  10020. char *ebuf,
  10021. size_t ebuf_len)
  10022. {
  10023. static struct mg_context fake_ctx;
  10024. struct mg_connection *conn = NULL;
  10025. SOCKET sock;
  10026. union usa sa;
  10027. if (!connect_socket(&fake_ctx,
  10028. client_options->host,
  10029. client_options->port,
  10030. use_ssl,
  10031. ebuf,
  10032. ebuf_len,
  10033. &sock,
  10034. &sa)) {
  10035. ;
  10036. } else if ((conn = (struct mg_connection *)
  10037. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10038. mg_snprintf(NULL,
  10039. NULL, /* No truncation check for ebuf */
  10040. ebuf,
  10041. ebuf_len,
  10042. "calloc(): %s",
  10043. strerror(ERRNO));
  10044. closesocket(sock);
  10045. #ifndef NO_SSL
  10046. } else if (use_ssl
  10047. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10048. == NULL) {
  10049. mg_snprintf(NULL,
  10050. NULL, /* No truncation check for ebuf */
  10051. ebuf,
  10052. ebuf_len,
  10053. "SSL_CTX_new error");
  10054. closesocket(sock);
  10055. mg_free(conn);
  10056. conn = NULL;
  10057. #endif /* NO_SSL */
  10058. } else {
  10059. #ifdef USE_IPV6
  10060. socklen_t len = (sa.sa.sa_family == AF_INET)
  10061. ? sizeof(conn->client.rsa.sin)
  10062. : sizeof(conn->client.rsa.sin6);
  10063. struct sockaddr *psa =
  10064. (sa.sa.sa_family == AF_INET)
  10065. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10066. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10067. #else
  10068. socklen_t len = sizeof(conn->client.rsa.sin);
  10069. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10070. #endif
  10071. conn->buf_size = MAX_REQUEST_SIZE;
  10072. conn->buf = (char *)(conn + 1);
  10073. conn->ctx = &fake_ctx;
  10074. conn->client.sock = sock;
  10075. conn->client.lsa = sa;
  10076. if (getsockname(sock, psa, &len) != 0) {
  10077. mg_cry(conn,
  10078. "%s: getsockname() failed: %s",
  10079. __func__,
  10080. strerror(ERRNO));
  10081. }
  10082. conn->client.is_ssl = use_ssl ? 1 : 0;
  10083. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10084. #ifndef NO_SSL
  10085. if (use_ssl) {
  10086. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10087. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10088. * SSL_CTX_set_verify call is needed to switch off server
  10089. * certificate checking, which is off by default in OpenSSL and
  10090. * on in yaSSL. */
  10091. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10092. * SSL_VERIFY_PEER, verify_ssl_server); */
  10093. if (client_options->client_cert) {
  10094. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10095. mg_snprintf(NULL,
  10096. NULL, /* No truncation check for ebuf */
  10097. ebuf,
  10098. ebuf_len,
  10099. "Can not use SSL client certificate");
  10100. SSL_CTX_free(conn->client_ssl_ctx);
  10101. closesocket(sock);
  10102. mg_free(conn);
  10103. conn = NULL;
  10104. }
  10105. }
  10106. if (client_options->server_cert) {
  10107. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10108. client_options->server_cert,
  10109. NULL);
  10110. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10111. } else {
  10112. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10113. }
  10114. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10115. mg_snprintf(NULL,
  10116. NULL, /* No truncation check for ebuf */
  10117. ebuf,
  10118. ebuf_len,
  10119. "SSL connection error");
  10120. SSL_CTX_free(conn->client_ssl_ctx);
  10121. closesocket(sock);
  10122. mg_free(conn);
  10123. conn = NULL;
  10124. }
  10125. }
  10126. #endif
  10127. }
  10128. return conn;
  10129. }
  10130. CIVETWEB_API struct mg_connection *
  10131. mg_connect_client_secure(const struct mg_client_options *client_options,
  10132. char *error_buffer,
  10133. size_t error_buffer_size)
  10134. {
  10135. return mg_connect_client_impl(client_options,
  10136. 1,
  10137. error_buffer,
  10138. error_buffer_size);
  10139. }
  10140. struct mg_connection *
  10141. mg_connect_client(const char *host,
  10142. int port,
  10143. int use_ssl,
  10144. char *error_buffer,
  10145. size_t error_buffer_size)
  10146. {
  10147. struct mg_client_options opts;
  10148. memset(&opts, 0, sizeof(opts));
  10149. opts.host = host;
  10150. opts.port = port;
  10151. return mg_connect_client_impl(&opts,
  10152. use_ssl,
  10153. error_buffer,
  10154. error_buffer_size);
  10155. }
  10156. static const struct {
  10157. const char *proto;
  10158. size_t proto_len;
  10159. unsigned default_port;
  10160. } abs_uri_protocols[] = {{"http://", 7, 80},
  10161. {"https://", 8, 443},
  10162. {"ws://", 5, 80},
  10163. {"wss://", 6, 443},
  10164. {NULL, 0, 0}};
  10165. /* Check if the uri is valid.
  10166. * return 0 for invalid uri,
  10167. * return 1 for *,
  10168. * return 2 for relative uri,
  10169. * return 3 for absolute uri without port,
  10170. * return 4 for absolute uri with port */
  10171. static int
  10172. get_uri_type(const char *uri)
  10173. {
  10174. int i;
  10175. char *hostend, *portbegin, *portend;
  10176. unsigned long port;
  10177. /* According to the HTTP standard
  10178. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10179. * URI can be an asterisk (*) or should start with slash (relative uri),
  10180. * or it should start with the protocol (absolute uri). */
  10181. if (uri[0] == '*' && uri[1] == '\0') {
  10182. /* asterisk */
  10183. return 1;
  10184. }
  10185. if (uri[0] == '/') {
  10186. /* relative uri */
  10187. return 2;
  10188. }
  10189. /* It could be an absolute uri: */
  10190. /* This function only checks if the uri is valid, not if it is
  10191. * addressing the current server. So civetweb can also be used
  10192. * as a proxy server. */
  10193. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10194. if (mg_strncasecmp(uri,
  10195. abs_uri_protocols[i].proto,
  10196. abs_uri_protocols[i].proto_len) == 0) {
  10197. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10198. if (!hostend) {
  10199. return 0;
  10200. }
  10201. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10202. if (!portbegin) {
  10203. return 3;
  10204. }
  10205. port = strtoul(portbegin + 1, &portend, 10);
  10206. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10207. return 0;
  10208. }
  10209. return 4;
  10210. }
  10211. }
  10212. return 0;
  10213. }
  10214. /* Return NULL or the relative uri at the current server */
  10215. static const char *
  10216. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10217. {
  10218. const char *server_domain;
  10219. size_t server_domain_len;
  10220. size_t request_domain_len = 0;
  10221. unsigned long port = 0;
  10222. int i;
  10223. const char *hostbegin = NULL;
  10224. const char *hostend = NULL;
  10225. const char *portbegin;
  10226. char *portend;
  10227. /* DNS is case insensitive, so use case insensitive string compare here
  10228. */
  10229. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10230. if (!server_domain) {
  10231. return 0;
  10232. }
  10233. server_domain_len = strlen(server_domain);
  10234. if (!server_domain_len) {
  10235. return 0;
  10236. }
  10237. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10238. if (mg_strncasecmp(uri,
  10239. abs_uri_protocols[i].proto,
  10240. abs_uri_protocols[i].proto_len) == 0) {
  10241. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10242. hostend = strchr(hostbegin, '/');
  10243. if (!hostend) {
  10244. return 0;
  10245. }
  10246. portbegin = strchr(hostbegin, ':');
  10247. if ((!portbegin) || (portbegin > hostend)) {
  10248. port = abs_uri_protocols[i].default_port;
  10249. request_domain_len = (size_t)(hostend - hostbegin);
  10250. } else {
  10251. port = strtoul(portbegin + 1, &portend, 10);
  10252. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10253. return 0;
  10254. }
  10255. request_domain_len = (size_t)(portbegin - hostbegin);
  10256. }
  10257. /* protocol found, port set */
  10258. break;
  10259. }
  10260. }
  10261. if (!port) {
  10262. /* port remains 0 if the protocol is not found */
  10263. return 0;
  10264. }
  10265. #if defined(USE_IPV6)
  10266. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10267. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10268. /* Request is directed to a different port */
  10269. return 0;
  10270. }
  10271. } else
  10272. #endif
  10273. {
  10274. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10275. /* Request is directed to a different port */
  10276. return 0;
  10277. }
  10278. }
  10279. if ((request_domain_len != server_domain_len)
  10280. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10281. /* Request is directed to another server */
  10282. return 0;
  10283. }
  10284. return hostend;
  10285. }
  10286. static int
  10287. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10288. {
  10289. const char *cl;
  10290. if (ebuf_len > 0) {
  10291. ebuf[0] = '\0';
  10292. }
  10293. *err = 0;
  10294. reset_per_request_attributes(conn);
  10295. if (!conn) {
  10296. mg_snprintf(conn,
  10297. NULL, /* No truncation check for ebuf */
  10298. ebuf,
  10299. ebuf_len,
  10300. "%s",
  10301. "Internal error");
  10302. *err = 500;
  10303. return 0;
  10304. }
  10305. /* Set the time the request was received. This value should be used for
  10306. * timeouts. */
  10307. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10308. conn->request_len =
  10309. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10310. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10311. */
  10312. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10313. mg_snprintf(conn,
  10314. NULL, /* No truncation check for ebuf */
  10315. ebuf,
  10316. ebuf_len,
  10317. "%s",
  10318. "Invalid request size");
  10319. *err = 500;
  10320. return 0;
  10321. }
  10322. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10323. mg_snprintf(conn,
  10324. NULL, /* No truncation check for ebuf */
  10325. ebuf,
  10326. ebuf_len,
  10327. "%s",
  10328. "Request Too Large");
  10329. *err = 413;
  10330. return 0;
  10331. } else if (conn->request_len <= 0) {
  10332. if (conn->data_len > 0) {
  10333. mg_snprintf(conn,
  10334. NULL, /* No truncation check for ebuf */
  10335. ebuf,
  10336. ebuf_len,
  10337. "%s",
  10338. "Client sent malformed request");
  10339. *err = 400;
  10340. } else {
  10341. /* Server did not send anything -> just close the connection */
  10342. conn->must_close = 1;
  10343. mg_snprintf(conn,
  10344. NULL, /* No truncation check for ebuf */
  10345. ebuf,
  10346. ebuf_len,
  10347. "%s",
  10348. "Client did not send a request");
  10349. *err = 0;
  10350. }
  10351. return 0;
  10352. } else if (parse_http_message(conn->buf,
  10353. conn->buf_size,
  10354. &conn->request_info) <= 0) {
  10355. mg_snprintf(conn,
  10356. NULL, /* No truncation check for ebuf */
  10357. ebuf,
  10358. ebuf_len,
  10359. "%s",
  10360. "Bad Request");
  10361. *err = 400;
  10362. return 0;
  10363. } else {
  10364. /* Message is a valid request or response */
  10365. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10366. /* Request/response has content length set */
  10367. char *endptr = NULL;
  10368. conn->content_len = strtoll(cl, &endptr, 10);
  10369. if (endptr == cl) {
  10370. mg_snprintf(conn,
  10371. NULL, /* No truncation check for ebuf */
  10372. ebuf,
  10373. ebuf_len,
  10374. "%s",
  10375. "Bad Request");
  10376. *err = 411;
  10377. return 0;
  10378. }
  10379. /* Publish the content length back to the request info. */
  10380. conn->request_info.content_length = conn->content_len;
  10381. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10382. != NULL
  10383. && !mg_strcasecmp(cl, "chunked")) {
  10384. conn->is_chunked = 1;
  10385. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10386. || !mg_strcasecmp(conn->request_info.request_method,
  10387. "PUT")) {
  10388. /* POST or PUT request without content length set */
  10389. conn->content_len = -1;
  10390. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10391. "HTTP/",
  10392. 5)) {
  10393. /* Response without content length set */
  10394. conn->content_len = -1;
  10395. } else {
  10396. /* Other request */
  10397. conn->content_len = 0;
  10398. }
  10399. }
  10400. return 1;
  10401. }
  10402. int
  10403. mg_get_response(struct mg_connection *conn,
  10404. char *ebuf,
  10405. size_t ebuf_len,
  10406. int timeout)
  10407. {
  10408. if (conn) {
  10409. /* Implementation of API function for HTTP clients */
  10410. int err, ret;
  10411. struct mg_context *octx = conn->ctx;
  10412. struct mg_context rctx = *(conn->ctx);
  10413. char txt[32]; /* will not overflow */
  10414. if (timeout >= 0) {
  10415. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10416. rctx.config[REQUEST_TIMEOUT] = txt;
  10417. set_sock_timeout(conn->client.sock, timeout);
  10418. } else {
  10419. rctx.config[REQUEST_TIMEOUT] = NULL;
  10420. }
  10421. conn->ctx = &rctx;
  10422. ret = getreq(conn, ebuf, ebuf_len, &err);
  10423. conn->ctx = octx;
  10424. /* TODO: 1) uri is deprecated;
  10425. * 2) here, ri.uri is the http response code */
  10426. conn->request_info.uri = conn->request_info.request_uri;
  10427. /* TODO (mid): Define proper return values - maybe return length?
  10428. * For the first test use <0 for error and >0 for OK */
  10429. return (ret == 0) ? -1 : +1;
  10430. }
  10431. return -1;
  10432. }
  10433. struct mg_connection *
  10434. mg_download(const char *host,
  10435. int port,
  10436. int use_ssl,
  10437. char *ebuf,
  10438. size_t ebuf_len,
  10439. const char *fmt,
  10440. ...)
  10441. {
  10442. struct mg_connection *conn;
  10443. va_list ap;
  10444. int i;
  10445. int reqerr;
  10446. va_start(ap, fmt);
  10447. ebuf[0] = '\0';
  10448. /* open a connection */
  10449. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10450. if (conn != NULL) {
  10451. i = mg_vprintf(conn, fmt, ap);
  10452. if (i <= 0) {
  10453. mg_snprintf(conn,
  10454. NULL, /* No truncation check for ebuf */
  10455. ebuf,
  10456. ebuf_len,
  10457. "%s",
  10458. "Error sending request");
  10459. } else {
  10460. getreq(conn, ebuf, ebuf_len, &reqerr);
  10461. /* TODO: 1) uri is deprecated;
  10462. * 2) here, ri.uri is the http response code */
  10463. conn->request_info.uri = conn->request_info.request_uri;
  10464. }
  10465. }
  10466. /* if an error occured, close the connection */
  10467. if (ebuf[0] != '\0' && conn != NULL) {
  10468. mg_close_connection(conn);
  10469. conn = NULL;
  10470. }
  10471. va_end(ap);
  10472. return conn;
  10473. }
  10474. struct websocket_client_thread_data {
  10475. struct mg_connection *conn;
  10476. mg_websocket_data_handler data_handler;
  10477. mg_websocket_close_handler close_handler;
  10478. void *callback_data;
  10479. };
  10480. #if defined(USE_WEBSOCKET)
  10481. #ifdef _WIN32
  10482. static unsigned __stdcall websocket_client_thread(void *data)
  10483. #else
  10484. static void *
  10485. websocket_client_thread(void *data)
  10486. #endif
  10487. {
  10488. struct websocket_client_thread_data *cdata =
  10489. (struct websocket_client_thread_data *)data;
  10490. mg_set_thread_name("ws-client");
  10491. if (cdata->conn->ctx) {
  10492. if (cdata->conn->ctx->callbacks.init_thread) {
  10493. /* 3 indicates a websocket client thread */
  10494. /* TODO: check if conn->ctx can be set */
  10495. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10496. }
  10497. }
  10498. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10499. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10500. if (cdata->close_handler != NULL) {
  10501. cdata->close_handler(cdata->conn, cdata->callback_data);
  10502. }
  10503. mg_free((void *)cdata);
  10504. #ifdef _WIN32
  10505. return 0;
  10506. #else
  10507. return NULL;
  10508. #endif
  10509. }
  10510. #endif
  10511. struct mg_connection *
  10512. mg_connect_websocket_client(const char *host,
  10513. int port,
  10514. int use_ssl,
  10515. char *error_buffer,
  10516. size_t error_buffer_size,
  10517. const char *path,
  10518. const char *origin,
  10519. mg_websocket_data_handler data_func,
  10520. mg_websocket_close_handler close_func,
  10521. void *user_data)
  10522. {
  10523. struct mg_connection *conn = NULL;
  10524. #if defined(USE_WEBSOCKET)
  10525. struct mg_context *newctx = NULL;
  10526. struct websocket_client_thread_data *thread_data;
  10527. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10528. static const char *handshake_req;
  10529. if (origin != NULL) {
  10530. handshake_req = "GET %s HTTP/1.1\r\n"
  10531. "Host: %s\r\n"
  10532. "Upgrade: websocket\r\n"
  10533. "Connection: Upgrade\r\n"
  10534. "Sec-WebSocket-Key: %s\r\n"
  10535. "Sec-WebSocket-Version: 13\r\n"
  10536. "Origin: %s\r\n"
  10537. "\r\n";
  10538. } else {
  10539. handshake_req = "GET %s HTTP/1.1\r\n"
  10540. "Host: %s\r\n"
  10541. "Upgrade: websocket\r\n"
  10542. "Connection: Upgrade\r\n"
  10543. "Sec-WebSocket-Key: %s\r\n"
  10544. "Sec-WebSocket-Version: 13\r\n"
  10545. "\r\n";
  10546. }
  10547. /* Establish the client connection and request upgrade */
  10548. conn = mg_download(host,
  10549. port,
  10550. use_ssl,
  10551. error_buffer,
  10552. error_buffer_size,
  10553. handshake_req,
  10554. path,
  10555. host,
  10556. magic,
  10557. origin);
  10558. /* Connection object will be null if something goes wrong */
  10559. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10560. if (!*error_buffer) {
  10561. /* if there is a connection, but it did not return 101,
  10562. * error_buffer is not yet set */
  10563. mg_snprintf(conn,
  10564. NULL, /* No truncation check for ebuf */
  10565. error_buffer,
  10566. error_buffer_size,
  10567. "Unexpected server reply");
  10568. }
  10569. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10570. if (conn != NULL) {
  10571. mg_free(conn);
  10572. conn = NULL;
  10573. }
  10574. return conn;
  10575. }
  10576. /* For client connections, mg_context is fake. Since we need to set a
  10577. * callback function, we need to create a copy and modify it. */
  10578. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10579. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10580. newctx->user_data = user_data;
  10581. newctx->context_type = 2; /* client context type */
  10582. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10583. newctx->workerthreadids =
  10584. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10585. conn->ctx = newctx;
  10586. thread_data = (struct websocket_client_thread_data *)
  10587. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10588. thread_data->conn = conn;
  10589. thread_data->data_handler = data_func;
  10590. thread_data->close_handler = close_func;
  10591. thread_data->callback_data = NULL;
  10592. /* Start a thread to read the websocket client connection
  10593. * This thread will automatically stop when mg_disconnect is
  10594. * called on the client connection */
  10595. if (mg_start_thread_with_id(websocket_client_thread,
  10596. (void *)thread_data,
  10597. newctx->workerthreadids) != 0) {
  10598. mg_free((void *)thread_data);
  10599. mg_free((void *)newctx->workerthreadids);
  10600. mg_free((void *)newctx);
  10601. mg_free((void *)conn);
  10602. conn = NULL;
  10603. DEBUG_TRACE("%s",
  10604. "Websocket client connect thread could not be started\r\n");
  10605. }
  10606. #else
  10607. /* Appease "unused parameter" warnings */
  10608. (void)host;
  10609. (void)port;
  10610. (void)use_ssl;
  10611. (void)error_buffer;
  10612. (void)error_buffer_size;
  10613. (void)path;
  10614. (void)origin;
  10615. (void)user_data;
  10616. (void)data_func;
  10617. (void)close_func;
  10618. #endif
  10619. return conn;
  10620. }
  10621. static void
  10622. process_new_connection(struct mg_connection *conn)
  10623. {
  10624. if (conn && conn->ctx) {
  10625. struct mg_request_info *ri = &conn->request_info;
  10626. int keep_alive_enabled, keep_alive, discard_len;
  10627. char ebuf[100];
  10628. const char *hostend;
  10629. int reqerr, uri_type;
  10630. keep_alive_enabled =
  10631. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10632. /* Important: on new connection, reset the receiving buffer. Credit
  10633. * goes to crule42. */
  10634. conn->data_len = 0;
  10635. do {
  10636. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10637. /* The request sent by the client could not be understood by
  10638. * the server, or it was incomplete or a timeout. Send an
  10639. * error message and close the connection. */
  10640. if (reqerr > 0) {
  10641. /*assert(ebuf[0] != '\0');*/
  10642. send_http_error(conn, reqerr, "%s", ebuf);
  10643. }
  10644. } else if (strcmp(ri->http_version, "1.0")
  10645. && strcmp(ri->http_version, "1.1")) {
  10646. mg_snprintf(conn,
  10647. NULL, /* No truncation check for ebuf */
  10648. ebuf,
  10649. sizeof(ebuf),
  10650. "Bad HTTP version: [%s]",
  10651. ri->http_version);
  10652. send_http_error(conn, 505, "%s", ebuf);
  10653. }
  10654. if (ebuf[0] == '\0') {
  10655. uri_type = get_uri_type(conn->request_info.request_uri);
  10656. switch (uri_type) {
  10657. case 1:
  10658. /* Asterisk */
  10659. conn->request_info.local_uri = NULL;
  10660. break;
  10661. case 2:
  10662. /* relative uri */
  10663. conn->request_info.local_uri =
  10664. conn->request_info.request_uri;
  10665. break;
  10666. case 3:
  10667. case 4:
  10668. /* absolute uri (with/without port) */
  10669. hostend = get_rel_url_at_current_server(
  10670. conn->request_info.request_uri, conn);
  10671. if (hostend) {
  10672. conn->request_info.local_uri = hostend;
  10673. } else {
  10674. conn->request_info.local_uri = NULL;
  10675. }
  10676. break;
  10677. default:
  10678. mg_snprintf(conn,
  10679. NULL, /* No truncation check for ebuf */
  10680. ebuf,
  10681. sizeof(ebuf),
  10682. "Invalid URI: [%s]",
  10683. ri->request_uri);
  10684. send_http_error(conn, 400, "%s", ebuf);
  10685. break;
  10686. }
  10687. /* TODO: cleanup uri, local_uri and request_uri */
  10688. conn->request_info.uri = conn->request_info.local_uri;
  10689. }
  10690. if (ebuf[0] == '\0') {
  10691. if (conn->request_info.local_uri) {
  10692. /* handle request to local server */
  10693. handle_request(conn);
  10694. if (conn->ctx->callbacks.end_request != NULL) {
  10695. conn->ctx->callbacks.end_request(conn,
  10696. conn->status_code);
  10697. }
  10698. log_access(conn);
  10699. } else {
  10700. /* TODO: handle non-local request (PROXY) */
  10701. conn->must_close = 1;
  10702. }
  10703. } else {
  10704. conn->must_close = 1;
  10705. }
  10706. if (ri->remote_user != NULL) {
  10707. mg_free((void *)ri->remote_user);
  10708. /* Important! When having connections with and without auth
  10709. * would cause double free and then crash */
  10710. ri->remote_user = NULL;
  10711. }
  10712. /* NOTE(lsm): order is important here. should_keep_alive() call
  10713. * is
  10714. * using parsed request, which will be invalid after memmove's
  10715. * below.
  10716. * Therefore, memorize should_keep_alive() result now for later
  10717. * use
  10718. * in loop exit condition. */
  10719. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10720. && conn->content_len >= 0 && should_keep_alive(conn);
  10721. /* Discard all buffered data for this request */
  10722. discard_len = conn->content_len >= 0 && conn->request_len > 0
  10723. && conn->request_len + conn->content_len
  10724. < (int64_t)conn->data_len
  10725. ? (int)(conn->request_len + conn->content_len)
  10726. : conn->data_len;
  10727. /*assert(discard_len >= 0);*/
  10728. if (discard_len < 0)
  10729. break;
  10730. conn->data_len -= discard_len;
  10731. if (conn->data_len > 0) {
  10732. memmove(conn->buf,
  10733. conn->buf + discard_len,
  10734. (size_t)conn->data_len);
  10735. }
  10736. /* assert(conn->data_len >= 0); */
  10737. /* assert(conn->data_len <= conn->buf_size); */
  10738. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10739. break;
  10740. }
  10741. } while (keep_alive);
  10742. }
  10743. }
  10744. /* Worker threads take accepted socket from the queue */
  10745. static int
  10746. consume_socket(struct mg_context *ctx, struct socket *sp)
  10747. {
  10748. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10749. if (!ctx) {
  10750. return 0;
  10751. }
  10752. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10753. DEBUG_TRACE("%s", "going idle");
  10754. /* If the queue is empty, wait. We're idle at this point. */
  10755. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10756. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10757. }
  10758. /* If we're stopping, sq_head may be equal to sq_tail. */
  10759. if (ctx->sq_head > ctx->sq_tail) {
  10760. /* Copy socket from the queue and increment tail */
  10761. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10762. ctx->sq_tail++;
  10763. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10764. /* Wrap pointers if needed */
  10765. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10766. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10767. ctx->sq_head -= QUEUE_SIZE(ctx);
  10768. }
  10769. }
  10770. (void)pthread_cond_signal(&ctx->sq_empty);
  10771. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10772. return !ctx->stop_flag;
  10773. #undef QUEUE_SIZE
  10774. }
  10775. static void *
  10776. worker_thread_run(void *thread_func_param)
  10777. {
  10778. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10779. struct mg_connection *conn;
  10780. struct mg_workerTLS tls;
  10781. #if defined(MG_LEGACY_INTERFACE)
  10782. uint32_t addr;
  10783. #endif
  10784. mg_set_thread_name("worker");
  10785. tls.is_master = 0;
  10786. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10787. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10788. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10789. #endif
  10790. if (ctx->callbacks.init_thread) {
  10791. /* call init_thread for a worker thread (type 1) */
  10792. ctx->callbacks.init_thread(ctx, 1);
  10793. }
  10794. conn =
  10795. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10796. if (conn == NULL) {
  10797. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10798. } else {
  10799. pthread_setspecific(sTlsKey, &tls);
  10800. conn->buf_size = MAX_REQUEST_SIZE;
  10801. conn->buf = (char *)(conn + 1);
  10802. conn->ctx = ctx;
  10803. conn->request_info.user_data = ctx->user_data;
  10804. /* Allocate a mutex for this connection to allow communication both
  10805. * within the request handler and from elsewhere in the application
  10806. */
  10807. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10808. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10809. * signal sq_empty condvar to wake up the master waiting in
  10810. * produce_socket() */
  10811. while (consume_socket(ctx, &conn->client)) {
  10812. conn->conn_birth_time = time(NULL);
  10813. /* Fill in IP, port info early so even if SSL setup below fails,
  10814. * error handler would have the corresponding info.
  10815. * Thanks to Johannes Winkelmann for the patch.
  10816. */
  10817. #if defined(USE_IPV6)
  10818. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10819. conn->request_info.remote_port =
  10820. ntohs(conn->client.rsa.sin6.sin6_port);
  10821. } else
  10822. #endif
  10823. {
  10824. conn->request_info.remote_port =
  10825. ntohs(conn->client.rsa.sin.sin_port);
  10826. }
  10827. sockaddr_to_string(conn->request_info.remote_addr,
  10828. sizeof(conn->request_info.remote_addr),
  10829. &conn->client.rsa);
  10830. #if defined(MG_LEGACY_INTERFACE)
  10831. /* This legacy interface only works for the IPv4 case */
  10832. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10833. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10834. #endif
  10835. conn->request_info.is_ssl = conn->client.is_ssl;
  10836. if (!conn->client.is_ssl
  10837. #ifndef NO_SSL
  10838. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10839. #endif
  10840. ) {
  10841. process_new_connection(conn);
  10842. }
  10843. close_connection(conn);
  10844. }
  10845. }
  10846. /* Signal master that we're done with connection and exiting */
  10847. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10848. ctx->running_worker_threads--;
  10849. (void)pthread_cond_signal(&ctx->thread_cond);
  10850. /* assert(ctx->running_worker_threads >= 0); */
  10851. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10852. pthread_setspecific(sTlsKey, NULL);
  10853. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10854. CloseHandle(tls.pthread_cond_helper_mutex);
  10855. #endif
  10856. pthread_mutex_destroy(&conn->mutex);
  10857. mg_free(conn);
  10858. DEBUG_TRACE("%s", "exiting");
  10859. return NULL;
  10860. }
  10861. /* Threads have different return types on Windows and Unix. */
  10862. #ifdef _WIN32
  10863. static unsigned __stdcall worker_thread(void *thread_func_param)
  10864. {
  10865. worker_thread_run(thread_func_param);
  10866. return 0;
  10867. }
  10868. #else
  10869. static void *
  10870. worker_thread(void *thread_func_param)
  10871. {
  10872. worker_thread_run(thread_func_param);
  10873. return NULL;
  10874. }
  10875. #endif /* _WIN32 */
  10876. /* Master thread adds accepted socket to a queue */
  10877. static void
  10878. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10879. {
  10880. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10881. if (!ctx) {
  10882. return;
  10883. }
  10884. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10885. /* If the queue is full, wait */
  10886. while (ctx->stop_flag == 0
  10887. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10888. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10889. }
  10890. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10891. /* Copy socket to the queue and increment head */
  10892. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10893. ctx->sq_head++;
  10894. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10895. }
  10896. (void)pthread_cond_signal(&ctx->sq_full);
  10897. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10898. #undef QUEUE_SIZE
  10899. }
  10900. static void
  10901. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10902. {
  10903. struct socket so;
  10904. char src_addr[IP_ADDR_STR_LEN];
  10905. socklen_t len = sizeof(so.rsa);
  10906. int on = 1;
  10907. int timeout;
  10908. if (!listener) {
  10909. return;
  10910. }
  10911. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10912. == INVALID_SOCKET) {
  10913. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10914. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10915. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10916. closesocket(so.sock);
  10917. so.sock = INVALID_SOCKET;
  10918. } else {
  10919. /* Put so socket structure into the queue */
  10920. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10921. set_close_on_exec(so.sock, fc(ctx));
  10922. so.is_ssl = listener->is_ssl;
  10923. so.ssl_redir = listener->ssl_redir;
  10924. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10925. mg_cry(fc(ctx),
  10926. "%s: getsockname() failed: %s",
  10927. __func__,
  10928. strerror(ERRNO));
  10929. }
  10930. /* Set TCP keep-alive. This is needed because if HTTP-level
  10931. * keep-alive
  10932. * is enabled, and client resets the connection, server won't get
  10933. * TCP FIN or RST and will keep the connection open forever. With
  10934. * TCP keep-alive, next keep-alive handshake will figure out that
  10935. * the client is down and will close the server end.
  10936. * Thanks to Igor Klopov who suggested the patch. */
  10937. if (setsockopt(so.sock,
  10938. SOL_SOCKET,
  10939. SO_KEEPALIVE,
  10940. (SOCK_OPT_TYPE)&on,
  10941. sizeof(on)) != 0) {
  10942. mg_cry(fc(ctx),
  10943. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10944. __func__,
  10945. strerror(ERRNO));
  10946. }
  10947. /* Disable TCP Nagle's algorithm. Normally TCP packets are
  10948. * coalesced
  10949. * to effectively fill up the underlying IP packet payload and
  10950. * reduce
  10951. * the overhead of sending lots of small buffers. However this hurts
  10952. * the server's throughput (ie. operations per second) when HTTP 1.1
  10953. * persistent connections are used and the responses are relatively
  10954. * small (eg. less than 1400 bytes).
  10955. */
  10956. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  10957. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  10958. if (set_tcp_nodelay(so.sock, 1) != 0) {
  10959. mg_cry(fc(ctx),
  10960. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  10961. __func__,
  10962. strerror(ERRNO));
  10963. }
  10964. }
  10965. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10966. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10967. } else {
  10968. timeout = -1;
  10969. }
  10970. /* Set socket timeout to the given value, but not more than a
  10971. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10972. * so the server can exit after that time if requested. */
  10973. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10974. set_sock_timeout(so.sock, timeout);
  10975. } else {
  10976. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10977. }
  10978. produce_socket(ctx, &so);
  10979. }
  10980. }
  10981. static void
  10982. master_thread_run(void *thread_func_param)
  10983. {
  10984. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10985. struct mg_workerTLS tls;
  10986. struct pollfd *pfd;
  10987. unsigned int i;
  10988. unsigned int workerthreadcount;
  10989. if (!ctx) {
  10990. return;
  10991. }
  10992. mg_set_thread_name("master");
  10993. /* Increase priority of the master thread */
  10994. #if defined(_WIN32)
  10995. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10996. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10997. int min_prio = sched_get_priority_min(SCHED_RR);
  10998. int max_prio = sched_get_priority_max(SCHED_RR);
  10999. if ((min_prio >= 0) && (max_prio >= 0)
  11000. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11001. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11002. struct sched_param sched_param = {0};
  11003. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11004. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11005. }
  11006. #endif
  11007. /* Initialize thread local storage */
  11008. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11009. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11010. #endif
  11011. tls.is_master = 1;
  11012. pthread_setspecific(sTlsKey, &tls);
  11013. if (ctx->callbacks.init_thread) {
  11014. /* Callback for the master thread (type 0) */
  11015. ctx->callbacks.init_thread(ctx, 0);
  11016. }
  11017. /* Server starts *now* */
  11018. ctx->start_time = time(NULL);
  11019. /* Allocate memory for the listening sockets, and start the server */
  11020. pfd =
  11021. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  11022. while (pfd != NULL && ctx->stop_flag == 0) {
  11023. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11024. pfd[i].fd = ctx->listening_sockets[i].sock;
  11025. pfd[i].events = POLLIN;
  11026. }
  11027. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11028. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11029. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11030. * successful poll, and POLLIN is defined as
  11031. * (POLLRDNORM | POLLRDBAND)
  11032. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11033. * pfd[i].revents == POLLIN. */
  11034. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11035. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11036. }
  11037. }
  11038. }
  11039. }
  11040. mg_free(pfd);
  11041. DEBUG_TRACE("%s", "stopping workers");
  11042. /* Stop signal received: somebody called mg_stop. Quit. */
  11043. close_all_listening_sockets(ctx);
  11044. /* Wakeup workers that are waiting for connections to handle. */
  11045. pthread_cond_broadcast(&ctx->sq_full);
  11046. /* Wait until all threads finish */
  11047. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11048. while (ctx->running_worker_threads > 0) {
  11049. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  11050. }
  11051. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11052. /* Join all worker threads to avoid leaking threads. */
  11053. workerthreadcount = ctx->cfg_worker_threads;
  11054. for (i = 0; i < workerthreadcount; i++) {
  11055. if (ctx->workerthreadids[i] != 0) {
  11056. mg_join_thread(ctx->workerthreadids[i]);
  11057. }
  11058. }
  11059. #if !defined(NO_SSL)
  11060. if (ctx->ssl_ctx != NULL) {
  11061. uninitialize_ssl(ctx);
  11062. }
  11063. #endif
  11064. DEBUG_TRACE("%s", "exiting");
  11065. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11066. CloseHandle(tls.pthread_cond_helper_mutex);
  11067. #endif
  11068. pthread_setspecific(sTlsKey, NULL);
  11069. /* Signal mg_stop() that we're done.
  11070. * WARNING: This must be the very last thing this
  11071. * thread does, as ctx becomes invalid after this line. */
  11072. ctx->stop_flag = 2;
  11073. }
  11074. /* Threads have different return types on Windows and Unix. */
  11075. #ifdef _WIN32
  11076. static unsigned __stdcall master_thread(void *thread_func_param)
  11077. {
  11078. master_thread_run(thread_func_param);
  11079. return 0;
  11080. }
  11081. #else
  11082. static void *
  11083. master_thread(void *thread_func_param)
  11084. {
  11085. master_thread_run(thread_func_param);
  11086. return NULL;
  11087. }
  11088. #endif /* _WIN32 */
  11089. static void
  11090. free_context(struct mg_context *ctx)
  11091. {
  11092. int i;
  11093. struct mg_handler_info *tmp_rh;
  11094. if (ctx == NULL) {
  11095. return;
  11096. }
  11097. if (ctx->callbacks.exit_context) {
  11098. ctx->callbacks.exit_context(ctx);
  11099. }
  11100. /* All threads exited, no sync is needed. Destroy thread mutex and
  11101. * condvars
  11102. */
  11103. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11104. (void)pthread_cond_destroy(&ctx->thread_cond);
  11105. (void)pthread_cond_destroy(&ctx->sq_empty);
  11106. (void)pthread_cond_destroy(&ctx->sq_full);
  11107. /* Destroy other context global data structures mutex */
  11108. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11109. #if defined(USE_TIMERS)
  11110. timers_exit(ctx);
  11111. #endif
  11112. /* Deallocate config parameters */
  11113. for (i = 0; i < NUM_OPTIONS; i++) {
  11114. if (ctx->config[i] != NULL) {
  11115. #if defined(_MSC_VER)
  11116. #pragma warning(suppress : 6001)
  11117. #endif
  11118. mg_free(ctx->config[i]);
  11119. }
  11120. }
  11121. /* Deallocate request handlers */
  11122. while (ctx->handlers) {
  11123. tmp_rh = ctx->handlers;
  11124. ctx->handlers = tmp_rh->next;
  11125. mg_free(tmp_rh->uri);
  11126. mg_free(tmp_rh);
  11127. }
  11128. #ifndef NO_SSL
  11129. /* Deallocate SSL context */
  11130. if (ctx->ssl_ctx != NULL) {
  11131. SSL_CTX_free(ctx->ssl_ctx);
  11132. }
  11133. #endif /* !NO_SSL */
  11134. /* Deallocate worker thread ID array */
  11135. if (ctx->workerthreadids != NULL) {
  11136. mg_free(ctx->workerthreadids);
  11137. }
  11138. /* Deallocate the tls variable */
  11139. if (mg_atomic_dec(&sTlsInit) == 0) {
  11140. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11141. DeleteCriticalSection(&global_log_file_lock);
  11142. #endif /* _WIN32 && !__SYMBIAN32__ */
  11143. #if !defined(_WIN32)
  11144. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11145. #endif
  11146. pthread_key_delete(sTlsKey);
  11147. }
  11148. /* deallocate system name string */
  11149. mg_free(ctx->systemName);
  11150. /* Deallocate context itself */
  11151. mg_free(ctx);
  11152. }
  11153. void
  11154. mg_stop(struct mg_context *ctx)
  11155. {
  11156. pthread_t mt;
  11157. if (!ctx) {
  11158. return;
  11159. }
  11160. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11161. * two threads is not allowed. */
  11162. mt = ctx->masterthreadid;
  11163. if (mt == 0) {
  11164. return;
  11165. }
  11166. ctx->masterthreadid = 0;
  11167. ctx->stop_flag = 1;
  11168. /* Wait until mg_fini() stops */
  11169. while (ctx->stop_flag != 2) {
  11170. (void)mg_sleep(10);
  11171. }
  11172. mg_join_thread(mt);
  11173. free_context(ctx);
  11174. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11175. (void)WSACleanup();
  11176. #endif /* _WIN32 && !__SYMBIAN32__ */
  11177. }
  11178. static void
  11179. get_system_name(char **sysName)
  11180. {
  11181. #if defined(_WIN32)
  11182. #if !defined(__SYMBIAN32__)
  11183. char name[128];
  11184. DWORD dwVersion = 0;
  11185. DWORD dwMajorVersion = 0;
  11186. DWORD dwMinorVersion = 0;
  11187. DWORD dwBuild = 0;
  11188. #ifdef _MSC_VER
  11189. #pragma warning(push)
  11190. // GetVersion was declared deprecated
  11191. #pragma warning(disable : 4996)
  11192. #endif
  11193. dwVersion = GetVersion();
  11194. #ifdef _MSC_VER
  11195. #pragma warning(pop)
  11196. #endif
  11197. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11198. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11199. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11200. (void)dwBuild;
  11201. sprintf(name,
  11202. "Windows %u.%u",
  11203. (unsigned)dwMajorVersion,
  11204. (unsigned)dwMinorVersion);
  11205. *sysName = mg_strdup(name);
  11206. #else
  11207. *sysName = mg_strdup("Symbian");
  11208. #endif
  11209. #else
  11210. struct utsname name;
  11211. memset(&name, 0, sizeof(name));
  11212. uname(&name);
  11213. *sysName = mg_strdup(name.sysname);
  11214. #endif
  11215. }
  11216. struct mg_context *
  11217. mg_start(const struct mg_callbacks *callbacks,
  11218. void *user_data,
  11219. const char **options)
  11220. {
  11221. struct mg_context *ctx;
  11222. const char *name, *value, *default_value;
  11223. int idx, ok, workerthreadcount;
  11224. unsigned int i;
  11225. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11226. struct mg_workerTLS tls;
  11227. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11228. WSADATA data;
  11229. WSAStartup(MAKEWORD(2, 2), &data);
  11230. #endif /* _WIN32 && !__SYMBIAN32__ */
  11231. /* Allocate context and initialize reasonable general case defaults. */
  11232. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11233. return NULL;
  11234. }
  11235. /* Random number generator will initialize at the first call */
  11236. ctx->auth_nonce_mask =
  11237. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11238. if (mg_atomic_inc(&sTlsInit) == 1) {
  11239. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11240. InitializeCriticalSection(&global_log_file_lock);
  11241. #endif /* _WIN32 && !__SYMBIAN32__ */
  11242. #if !defined(_WIN32)
  11243. pthread_mutexattr_init(&pthread_mutex_attr);
  11244. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11245. #endif
  11246. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11247. /* Fatal error - abort start. However, this situation should
  11248. * never
  11249. * occur in practice. */
  11250. mg_atomic_dec(&sTlsInit);
  11251. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11252. mg_free(ctx);
  11253. return NULL;
  11254. }
  11255. } else {
  11256. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11257. * initialized. */
  11258. mg_sleep(1);
  11259. }
  11260. tls.is_master = -1;
  11261. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11262. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11263. tls.pthread_cond_helper_mutex = NULL;
  11264. #endif
  11265. pthread_setspecific(sTlsKey, &tls);
  11266. #if defined(USE_LUA)
  11267. lua_init_optional_libraries();
  11268. #endif
  11269. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11270. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  11271. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11272. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11273. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11274. if (!ok) {
  11275. /* Fatal error - abort start. However, this situation should never
  11276. * occur in practice. */
  11277. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11278. mg_free(ctx);
  11279. pthread_setspecific(sTlsKey, NULL);
  11280. return NULL;
  11281. }
  11282. if (callbacks) {
  11283. ctx->callbacks = *callbacks;
  11284. exit_callback = callbacks->exit_context;
  11285. ctx->callbacks.exit_context = 0;
  11286. }
  11287. ctx->user_data = user_data;
  11288. ctx->handlers = NULL;
  11289. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11290. ctx->shared_lua_websockets = 0;
  11291. #endif
  11292. while (options && (name = *options++) != NULL) {
  11293. if ((idx = get_option_index(name)) == -1) {
  11294. mg_cry(fc(ctx), "Invalid option: %s", name);
  11295. free_context(ctx);
  11296. pthread_setspecific(sTlsKey, NULL);
  11297. return NULL;
  11298. } else if ((value = *options++) == NULL) {
  11299. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11300. free_context(ctx);
  11301. pthread_setspecific(sTlsKey, NULL);
  11302. return NULL;
  11303. }
  11304. if (ctx->config[idx] != NULL) {
  11305. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11306. mg_free(ctx->config[idx]);
  11307. }
  11308. ctx->config[idx] = mg_strdup(value);
  11309. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11310. }
  11311. /* Set default value if needed */
  11312. for (i = 0; config_options[i].name != NULL; i++) {
  11313. default_value = config_options[i].default_value;
  11314. if (ctx->config[i] == NULL && default_value != NULL) {
  11315. ctx->config[i] = mg_strdup(default_value);
  11316. }
  11317. }
  11318. #if defined(NO_FILES)
  11319. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11320. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11321. free_context(ctx);
  11322. pthread_setspecific(sTlsKey, NULL);
  11323. return NULL;
  11324. }
  11325. #endif
  11326. get_system_name(&ctx->systemName);
  11327. /* NOTE(lsm): order is important here. SSL certificates must
  11328. * be initialized before listening ports. UID must be set last. */
  11329. if (!set_gpass_option(ctx) ||
  11330. #if !defined(NO_SSL)
  11331. !set_ssl_option(ctx) ||
  11332. #endif
  11333. !set_ports_option(ctx) ||
  11334. #if !defined(_WIN32)
  11335. !set_uid_option(ctx) ||
  11336. #endif
  11337. !set_acl_option(ctx)) {
  11338. free_context(ctx);
  11339. pthread_setspecific(sTlsKey, NULL);
  11340. return NULL;
  11341. }
  11342. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11343. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11344. * won't kill the whole process. */
  11345. (void)signal(SIGPIPE, SIG_IGN);
  11346. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11347. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11348. if (workerthreadcount > MAX_WORKER_THREADS) {
  11349. mg_cry(fc(ctx), "Too many worker threads");
  11350. free_context(ctx);
  11351. pthread_setspecific(sTlsKey, NULL);
  11352. return NULL;
  11353. }
  11354. if (workerthreadcount > 0) {
  11355. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11356. ctx->workerthreadids =
  11357. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11358. if (ctx->workerthreadids == NULL) {
  11359. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11360. free_context(ctx);
  11361. pthread_setspecific(sTlsKey, NULL);
  11362. return NULL;
  11363. }
  11364. }
  11365. #if defined(USE_TIMERS)
  11366. if (timers_init(ctx) != 0) {
  11367. mg_cry(fc(ctx), "Error creating timers");
  11368. free_context(ctx);
  11369. pthread_setspecific(sTlsKey, NULL);
  11370. return NULL;
  11371. }
  11372. #endif
  11373. /* Context has been created - init user libraries */
  11374. if (ctx->callbacks.init_context) {
  11375. ctx->callbacks.init_context(ctx);
  11376. }
  11377. ctx->callbacks.exit_context = exit_callback;
  11378. ctx->context_type = 1; /* server context */
  11379. /* Start master (listening) thread */
  11380. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11381. /* Start worker threads */
  11382. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11383. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11384. ctx->running_worker_threads++;
  11385. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11386. if (mg_start_thread_with_id(worker_thread,
  11387. ctx,
  11388. &ctx->workerthreadids[i]) != 0) {
  11389. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11390. ctx->running_worker_threads--;
  11391. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11392. if (i > 0) {
  11393. mg_cry(fc(ctx),
  11394. "Cannot start worker thread %i: error %ld",
  11395. i + 1,
  11396. (long)ERRNO);
  11397. } else {
  11398. mg_cry(fc(ctx),
  11399. "Cannot create threads: error %ld",
  11400. (long)ERRNO);
  11401. free_context(ctx);
  11402. pthread_setspecific(sTlsKey, NULL);
  11403. return NULL;
  11404. }
  11405. break;
  11406. }
  11407. }
  11408. pthread_setspecific(sTlsKey, NULL);
  11409. return ctx;
  11410. }
  11411. /* Feature check API function */
  11412. unsigned
  11413. mg_check_feature(unsigned feature)
  11414. {
  11415. static const unsigned feature_set = 0
  11416. /* Set bits for available features according to API documentation.
  11417. * This bit mask is created at compile time, according to the active
  11418. * preprocessor defines. It is a single const value at runtime. */
  11419. #if !defined(NO_FILES)
  11420. | 0x0001u
  11421. #endif
  11422. #if !defined(NO_SSL)
  11423. | 0x0002u
  11424. #endif
  11425. #if !defined(NO_CGI)
  11426. | 0x0004u
  11427. #endif
  11428. #if defined(USE_IPV6)
  11429. | 0x0008u
  11430. #endif
  11431. #if defined(USE_WEBSOCKET)
  11432. | 0x0010u
  11433. #endif
  11434. #if defined(USE_LUA)
  11435. | 0x0020u
  11436. #endif
  11437. #if defined(USE_DUKTAPE)
  11438. | 0x0040u
  11439. #endif
  11440. #if !defined(NO_CACHING)
  11441. | 0x0080u
  11442. #endif
  11443. /* Set some extra bits not defined in the API documentation.
  11444. * These bits may change without further notice. */
  11445. #if defined(MG_LEGACY_INTERFACE)
  11446. | 0x8000u
  11447. #endif
  11448. #if defined(MEMORY_DEBUGGING)
  11449. | 0x0100u
  11450. #endif
  11451. #if defined(USE_TIMERS)
  11452. | 0x0200u
  11453. #endif
  11454. #if !defined(NO_NONCE_CHECK)
  11455. | 0x0400u
  11456. #endif
  11457. #if !defined(NO_POPEN)
  11458. | 0x0800u
  11459. #endif
  11460. ;
  11461. return (feature & feature_set);
  11462. }