civetweb.c 356 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781
  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. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __MACH__
  114. #define CLOCK_MONOTONIC (1)
  115. #define CLOCK_REALTIME (2)
  116. #include <sys/time.h>
  117. #include <mach/clock.h>
  118. #include <mach/mach.h>
  119. #include <mach/mach_time.h>
  120. #include <assert.h>
  121. /* clock_gettime is not implemented on OSX */
  122. int clock_gettime(int clk_id, struct timespec *t);
  123. int
  124. clock_gettime(int clk_id, struct timespec *t)
  125. {
  126. memset(t, 0, sizeof(*t));
  127. if (clk_id == CLOCK_REALTIME) {
  128. struct timeval now;
  129. int rv = gettimeofday(&now, NULL);
  130. if (rv) {
  131. return rv;
  132. }
  133. t->tv_sec = now.tv_sec;
  134. t->tv_nsec = now.tv_usec * 1000;
  135. return 0;
  136. } else if (clk_id == CLOCK_MONOTONIC) {
  137. static uint64_t clock_start_time = 0;
  138. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  139. uint64_t now = mach_absolute_time();
  140. if (clock_start_time == 0) {
  141. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  142. #if defined(DEBUG)
  143. assert(mach_status == KERN_SUCCESS);
  144. #else
  145. /* appease "unused variable" warning for release builds */
  146. (void)mach_status;
  147. #endif
  148. clock_start_time = now;
  149. }
  150. now = (uint64_t)((double)(now - clock_start_time)
  151. * (double)timebase_ifo.numer
  152. / (double)timebase_ifo.denom);
  153. t->tv_sec = now / 1000000000;
  154. t->tv_nsec = now % 1000000000;
  155. return 0;
  156. }
  157. return -1; /* EINVAL - Clock ID is unknown */
  158. }
  159. #endif
  160. #include <time.h>
  161. #include <stdlib.h>
  162. #include <stdarg.h>
  163. #include <assert.h>
  164. #include <string.h>
  165. #include <ctype.h>
  166. #include <limits.h>
  167. #include <stddef.h>
  168. #include <stdio.h>
  169. #ifndef MAX_WORKER_THREADS
  170. #define MAX_WORKER_THREADS (1024 * 64)
  171. #endif
  172. #define SHUTDOWN_RD (0)
  173. #define SHUTDOWN_WR (1)
  174. #define SHUTDOWN_BOTH (2)
  175. mg_static_assert(MAX_WORKER_THREADS >= 1,
  176. "worker threads must be a positive number");
  177. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  178. "size_t data type size check");
  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 vsnprintf_impl _vsnprintf
  251. #define access _access
  252. #define mg_sleep(x) (Sleep(x))
  253. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  254. #ifndef popen
  255. #define popen(x, y) (_popen(x, y))
  256. #endif
  257. #ifndef pclose
  258. #define pclose(x) (_pclose(x))
  259. #endif
  260. #define close(x) (_close(x))
  261. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  262. #define RTLD_LAZY (0)
  263. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  264. #define fdopen(x, y) (_fdopen((x), (y)))
  265. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  266. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  267. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  268. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  269. #define sleep(x) (Sleep((x)*1000))
  270. #define rmdir(x) (_rmdir(x))
  271. #define timegm(x) (_mkgmtime(x))
  272. #if !defined(fileno)
  273. #define fileno(x) (_fileno(x))
  274. #endif /* !fileno MINGW #defines fileno */
  275. typedef HANDLE pthread_mutex_t;
  276. typedef DWORD pthread_key_t;
  277. typedef HANDLE pthread_t;
  278. typedef struct {
  279. CRITICAL_SECTION threadIdSec;
  280. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  281. } pthread_cond_t;
  282. #ifndef __clockid_t_defined
  283. typedef DWORD clockid_t;
  284. #endif
  285. #ifndef CLOCK_MONOTONIC
  286. #define CLOCK_MONOTONIC (1)
  287. #endif
  288. #ifndef CLOCK_REALTIME
  289. #define CLOCK_REALTIME (2)
  290. #endif
  291. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  292. #define _TIMESPEC_DEFINED
  293. #endif
  294. #ifndef _TIMESPEC_DEFINED
  295. struct timespec {
  296. time_t tv_sec; /* seconds */
  297. long tv_nsec; /* nanoseconds */
  298. };
  299. #endif
  300. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  301. static int pthread_mutex_lock(pthread_mutex_t *);
  302. static int pthread_mutex_unlock(pthread_mutex_t *);
  303. static void path_to_unicode(const struct mg_connection *conn,
  304. const char *path,
  305. wchar_t *wbuf,
  306. size_t wbuf_len);
  307. struct file;
  308. static const char *
  309. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  310. #if defined(HAVE_STDINT)
  311. #include <stdint.h>
  312. #else
  313. typedef unsigned char uint8_t;
  314. typedef unsigned short uint16_t;
  315. typedef unsigned int uint32_t;
  316. typedef unsigned __int64 uint64_t;
  317. typedef __int64 int64_t;
  318. #ifndef INT64_MAX
  319. #define INT64_MAX (9223372036854775807)
  320. #endif
  321. #endif /* HAVE_STDINT */
  322. /* POSIX dirent interface */
  323. struct dirent {
  324. char d_name[PATH_MAX];
  325. };
  326. typedef struct DIR {
  327. HANDLE handle;
  328. WIN32_FIND_DATAW info;
  329. struct dirent result;
  330. } DIR;
  331. #if defined(_WIN32) && !defined(POLLIN)
  332. #ifndef HAVE_POLL
  333. struct pollfd {
  334. SOCKET fd;
  335. short events;
  336. short revents;
  337. };
  338. #define POLLIN (0x0300)
  339. #endif
  340. #endif
  341. /* Mark required libraries */
  342. #if defined(_MSC_VER)
  343. #pragma comment(lib, "Ws2_32.lib")
  344. #endif
  345. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  346. WINDOWS / UNIX include block */
  347. #include <sys/wait.h>
  348. #include <sys/socket.h>
  349. #include <sys/poll.h>
  350. #include <netinet/in.h>
  351. #include <arpa/inet.h>
  352. #include <sys/time.h>
  353. #include <sys/utsname.h>
  354. #include <stdint.h>
  355. #include <inttypes.h>
  356. #include <netdb.h>
  357. #include <netinet/tcp.h>
  358. typedef const void *SOCK_OPT_TYPE;
  359. #if defined(ANDROID)
  360. typedef unsigned short int in_port_t;
  361. #endif
  362. #include <pwd.h>
  363. #include <unistd.h>
  364. #include <grp.h>
  365. #include <dirent.h>
  366. #define vsnprintf_impl vsnprintf
  367. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  368. #include <dlfcn.h>
  369. #endif
  370. #include <pthread.h>
  371. #if defined(__MACH__)
  372. #define SSL_LIB "libssl.dylib"
  373. #define CRYPTO_LIB "libcrypto.dylib"
  374. #else
  375. #if !defined(SSL_LIB)
  376. #define SSL_LIB "libssl.so"
  377. #endif
  378. #if !defined(CRYPTO_LIB)
  379. #define CRYPTO_LIB "libcrypto.so"
  380. #endif
  381. #endif
  382. #ifndef O_BINARY
  383. #define O_BINARY (0)
  384. #endif /* O_BINARY */
  385. #define closesocket(a) (close(a))
  386. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  387. #define mg_remove(conn, x) (remove(x))
  388. #define mg_sleep(x) (usleep((x)*1000))
  389. #define mg_opendir(conn, x) (opendir(x))
  390. #define mg_closedir(x) (closedir(x))
  391. #define mg_readdir(x) (readdir(x))
  392. #define ERRNO (errno)
  393. #define INVALID_SOCKET (-1)
  394. #define INT64_FMT PRId64
  395. #define UINT64_FMT PRIu64
  396. typedef int SOCKET;
  397. #define WINCDECL
  398. #if defined(__hpux)
  399. /* HPUX 11 does not have monotonic, fall back to realtime */
  400. #ifndef CLOCK_MONOTONIC
  401. #define CLOCK_MONOTONIC CLOCK_REALTIME
  402. #endif
  403. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  404. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  405. * the prototypes use int* rather than socklen_t* which matches the
  406. * actual library expectation. When called with the wrong size arg
  407. * accept() returns a zero client inet addr and check_acl() always
  408. * fails. Since socklen_t is widely used below, just force replace
  409. * their typedef with int. - DTL
  410. */
  411. #define socklen_t int
  412. #endif /* hpux */
  413. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. /* va_copy should always be a macro, C99 and C++11 - DTL */
  416. #ifndef va_copy
  417. #define va_copy(x, y) ((x) = (y))
  418. #endif
  419. #ifdef _WIN32
  420. /* Create substitutes for POSIX functions in Win32. */
  421. #if defined(__MINGW32__)
  422. /* Show no warning in case system functions are not used. */
  423. #pragma GCC diagnostic push
  424. #pragma GCC diagnostic ignored "-Wunused-function"
  425. #endif
  426. static CRITICAL_SECTION global_log_file_lock;
  427. static DWORD
  428. pthread_self(void)
  429. {
  430. return GetCurrentThreadId();
  431. }
  432. static int
  433. pthread_key_create(
  434. pthread_key_t *key,
  435. void (*_ignored)(void *) /* destructor not supported for Windows */
  436. )
  437. {
  438. (void)_ignored;
  439. if ((key != 0)) {
  440. *key = TlsAlloc();
  441. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  442. }
  443. return -2;
  444. }
  445. static int
  446. pthread_key_delete(pthread_key_t key)
  447. {
  448. return TlsFree(key) ? 0 : 1;
  449. }
  450. static int
  451. pthread_setspecific(pthread_key_t key, void *value)
  452. {
  453. return TlsSetValue(key, value) ? 0 : 1;
  454. }
  455. static void *
  456. pthread_getspecific(pthread_key_t key)
  457. {
  458. return TlsGetValue(key);
  459. }
  460. #if defined(__MINGW32__)
  461. /* Enable unused function warning again */
  462. #pragma GCC diagnostic pop
  463. #endif
  464. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  465. #else
  466. static pthread_mutexattr_t pthread_mutex_attr;
  467. #endif /* _WIN32 */
  468. #define PASSWORDS_FILE_NAME ".htpasswd"
  469. #define CGI_ENVIRONMENT_SIZE (4096)
  470. #define MAX_CGI_ENVIR_VARS (256)
  471. #define MG_BUF_LEN (8192)
  472. #ifndef MAX_REQUEST_SIZE
  473. #define MAX_REQUEST_SIZE (16384)
  474. #endif
  475. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  476. "request size length must be a positive number");
  477. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  478. #if !defined(DEBUG_TRACE)
  479. #if defined(DEBUG)
  480. #if defined(_WIN32_WCE)
  481. /* Create substitutes for POSIX functions in Win32. */
  482. #if defined(__MINGW32__)
  483. /* Show no warning in case system functions are not used. */
  484. #pragma GCC diagnostic push
  485. #pragma GCC diagnostic ignored "-Wunused-function"
  486. #endif
  487. static time_t
  488. time(time_t *ptime)
  489. {
  490. time_t t;
  491. SYSTEMTIME st;
  492. FILETIME ft;
  493. GetSystemTime(&st);
  494. SystemTimeToFileTime(&st, &ft);
  495. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  496. if (ptime != NULL) {
  497. *ptime = t;
  498. }
  499. return t;
  500. }
  501. static struct tm *
  502. localtime_s(const time_t *ptime, struct tm *ptm)
  503. {
  504. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  505. FILETIME ft, lft;
  506. SYSTEMTIME st;
  507. TIME_ZONE_INFORMATION tzinfo;
  508. if (ptm == NULL) {
  509. return NULL;
  510. }
  511. *(int64_t *)&ft = t;
  512. FileTimeToLocalFileTime(&ft, &lft);
  513. FileTimeToSystemTime(&lft, &st);
  514. ptm->tm_year = st.wYear - 1900;
  515. ptm->tm_mon = st.wMonth - 1;
  516. ptm->tm_wday = st.wDayOfWeek;
  517. ptm->tm_mday = st.wDay;
  518. ptm->tm_hour = st.wHour;
  519. ptm->tm_min = st.wMinute;
  520. ptm->tm_sec = st.wSecond;
  521. ptm->tm_yday = 0; /* hope nobody uses this */
  522. ptm->tm_isdst =
  523. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  524. return ptm;
  525. }
  526. static struct tm *
  527. gmtime_s(const time_t *ptime, struct tm *ptm)
  528. {
  529. /* FIXME(lsm): fix this. */
  530. return localtime_s(ptime, ptm);
  531. }
  532. static int mg_atomic_inc(volatile int *addr);
  533. static struct tm tm_array[MAX_WORKER_THREADS];
  534. static int tm_index = 0;
  535. static struct tm *
  536. localtime(const time_t *ptime)
  537. {
  538. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  539. return localtime_s(ptime, tm_array + i);
  540. }
  541. static struct tm *
  542. gmtime(const time_t *ptime)
  543. {
  544. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  545. return gmtime_s(ptime, tm_array + i);
  546. }
  547. static size_t
  548. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  549. {
  550. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  551. // for WinCE");
  552. return 0;
  553. }
  554. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  555. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  556. #define remove(f) mg_remove(NULL, f)
  557. static int
  558. rename(const char *a, const char *b)
  559. {
  560. wchar_t wa[PATH_MAX];
  561. wchar_t wb[PATH_MAX];
  562. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  563. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  564. return MoveFileW(wa, wb) ? 0 : -1;
  565. }
  566. struct stat {
  567. int64_t st_size;
  568. time_t st_mtime;
  569. };
  570. static int
  571. stat(const char *name, struct stat *st)
  572. {
  573. wchar_t wbuf[PATH_MAX];
  574. WIN32_FILE_ATTRIBUTE_DATA attr;
  575. time_t creation_time, write_time;
  576. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  577. memset(&attr, 0, sizeof(attr));
  578. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  579. st->st_size =
  580. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  581. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  582. attr.ftLastWriteTime.dwHighDateTime);
  583. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  584. attr.ftCreationTime.dwHighDateTime);
  585. if (creation_time > write_time) {
  586. st->st_mtime = creation_time;
  587. } else {
  588. st->st_mtime = write_time;
  589. }
  590. return 0;
  591. }
  592. #define access(x, a) 1 /* not required anyway */
  593. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  594. #define EEXIST 1 /* TODO: See Windows error codes */
  595. #define EACCES 2 /* TODO: See Windows error codes */
  596. #define ENOENT 3 /* TODO: See Windows Error codes */
  597. #if defined(__MINGW32__)
  598. /* Enable unused function warning again */
  599. #pragma GCC diagnostic pop
  600. #endif
  601. #endif /* defined(_WIN32_WCE) */
  602. static void DEBUG_TRACE_FUNC(const char *func,
  603. unsigned line,
  604. PRINTF_FORMAT_STRING(const char *fmt),
  605. ...) PRINTF_ARGS(3, 4);
  606. static void
  607. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  608. {
  609. va_list args;
  610. flockfile(stdout);
  611. printf("*** %lu.%p.%s.%u: ",
  612. (unsigned long)time(NULL),
  613. (void *)pthread_self(),
  614. func,
  615. line);
  616. va_start(args, fmt);
  617. vprintf(fmt, args);
  618. va_end(args);
  619. putchar('\n');
  620. fflush(stdout);
  621. funlockfile(stdout);
  622. }
  623. #define DEBUG_TRACE(fmt, ...) \
  624. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  625. #else
  626. #define DEBUG_TRACE(fmt, ...) \
  627. do { \
  628. } while (0)
  629. #endif /* DEBUG */
  630. #endif /* DEBUG_TRACE */
  631. #if defined(MEMORY_DEBUGGING)
  632. unsigned long mg_memory_debug_blockCount = 0;
  633. unsigned long mg_memory_debug_totalMemUsed = 0;
  634. static void *
  635. mg_malloc_ex(size_t size, const char *file, unsigned line)
  636. {
  637. void *data = malloc(size + sizeof(size_t));
  638. void *memory = 0;
  639. char mallocStr[256];
  640. if (data) {
  641. *(size_t *)data = size;
  642. mg_memory_debug_totalMemUsed += size;
  643. mg_memory_debug_blockCount++;
  644. memory = (void *)(((char *)data) + sizeof(size_t));
  645. }
  646. sprintf(mallocStr,
  647. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  648. memory,
  649. (unsigned long)size,
  650. mg_memory_debug_totalMemUsed,
  651. mg_memory_debug_blockCount,
  652. file,
  653. line);
  654. #if defined(_WIN32)
  655. OutputDebugStringA(mallocStr);
  656. #else
  657. DEBUG_TRACE("%s", mallocStr);
  658. #endif
  659. return memory;
  660. }
  661. static void *
  662. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  663. {
  664. void *data = mg_malloc_ex(size * count, file, line);
  665. if (data) {
  666. memset(data, 0, size * count);
  667. }
  668. return data;
  669. }
  670. static void
  671. mg_free_ex(void *memory, const char *file, unsigned line)
  672. {
  673. char mallocStr[256];
  674. void *data = (void *)(((char *)memory) - sizeof(size_t));
  675. size_t size;
  676. if (memory) {
  677. size = *(size_t *)data;
  678. mg_memory_debug_totalMemUsed -= size;
  679. mg_memory_debug_blockCount--;
  680. sprintf(mallocStr,
  681. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  682. memory,
  683. (unsigned long)size,
  684. mg_memory_debug_totalMemUsed,
  685. mg_memory_debug_blockCount,
  686. file,
  687. line);
  688. #if defined(_WIN32)
  689. OutputDebugStringA(mallocStr);
  690. #else
  691. DEBUG_TRACE("%s", mallocStr);
  692. #endif
  693. free(data);
  694. }
  695. }
  696. static void *
  697. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  698. {
  699. char mallocStr[256];
  700. void *data;
  701. void *_realloc;
  702. size_t oldsize;
  703. if (newsize) {
  704. if (memory) {
  705. data = (void *)(((char *)memory) - sizeof(size_t));
  706. oldsize = *(size_t *)data;
  707. _realloc = realloc(data, newsize + sizeof(size_t));
  708. if (_realloc) {
  709. data = _realloc;
  710. mg_memory_debug_totalMemUsed -= oldsize;
  711. sprintf(mallocStr,
  712. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  713. memory,
  714. (unsigned long)oldsize,
  715. mg_memory_debug_totalMemUsed,
  716. mg_memory_debug_blockCount,
  717. file,
  718. line);
  719. #if defined(_WIN32)
  720. OutputDebugStringA(mallocStr);
  721. #else
  722. DEBUG_TRACE("%s", mallocStr);
  723. #endif
  724. mg_memory_debug_totalMemUsed += newsize;
  725. sprintf(mallocStr,
  726. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  727. memory,
  728. (unsigned long)newsize,
  729. mg_memory_debug_totalMemUsed,
  730. mg_memory_debug_blockCount,
  731. file,
  732. line);
  733. #if defined(_WIN32)
  734. OutputDebugStringA(mallocStr);
  735. #else
  736. DEBUG_TRACE("%s", mallocStr);
  737. #endif
  738. *(size_t *)data = newsize;
  739. data = (void *)(((char *)data) + sizeof(size_t));
  740. } else {
  741. #if defined(_WIN32)
  742. OutputDebugStringA("MEM: realloc failed\n");
  743. #else
  744. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  745. #endif
  746. return _realloc;
  747. }
  748. } else {
  749. data = mg_malloc_ex(newsize, file, line);
  750. }
  751. } else {
  752. data = 0;
  753. mg_free_ex(memory, file, line);
  754. }
  755. return data;
  756. }
  757. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  758. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  759. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  760. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  761. #else
  762. static __inline void *
  763. mg_malloc(size_t a)
  764. {
  765. return malloc(a);
  766. }
  767. static __inline void *
  768. mg_calloc(size_t a, size_t b)
  769. {
  770. return calloc(a, b);
  771. }
  772. static __inline void *
  773. mg_realloc(void *a, size_t b)
  774. {
  775. return realloc(a, b);
  776. }
  777. static __inline void
  778. mg_free(void *a)
  779. {
  780. free(a);
  781. }
  782. #endif
  783. static void mg_vsnprintf(const struct mg_connection *conn,
  784. int *truncated,
  785. char *buf,
  786. size_t buflen,
  787. const char *fmt,
  788. va_list ap);
  789. static void mg_snprintf(const struct mg_connection *conn,
  790. int *truncated,
  791. char *buf,
  792. size_t buflen,
  793. PRINTF_FORMAT_STRING(const char *fmt),
  794. ...) PRINTF_ARGS(5, 6);
  795. /* This following lines are just meant as a reminder to use the mg-functions
  796. * for memory management */
  797. #ifdef malloc
  798. #undef malloc
  799. #endif
  800. #ifdef calloc
  801. #undef calloc
  802. #endif
  803. #ifdef realloc
  804. #undef realloc
  805. #endif
  806. #ifdef free
  807. #undef free
  808. #endif
  809. #ifdef snprintf
  810. #undef snprintf
  811. #endif
  812. #ifdef vsnprintf
  813. #undef vsnprintf
  814. #endif
  815. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  816. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  817. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  818. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  819. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  820. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  821. * but this define only works well for Windows. */
  822. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  823. #endif
  824. #define MD5_STATIC static
  825. #include "md5.inl"
  826. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  827. #ifdef NO_SOCKLEN_T
  828. typedef int socklen_t;
  829. #endif /* NO_SOCKLEN_T */
  830. #define _DARWIN_UNLIMITED_SELECT
  831. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  832. #if !defined(MSG_NOSIGNAL)
  833. #define MSG_NOSIGNAL (0)
  834. #endif
  835. #if !defined(SOMAXCONN)
  836. #define SOMAXCONN (100)
  837. #endif
  838. /* Size of the accepted socket queue */
  839. #if !defined(MGSQLEN)
  840. #define MGSQLEN (20)
  841. #endif
  842. #if defined(NO_SSL)
  843. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  844. typedef struct SSL_CTX SSL_CTX;
  845. #else
  846. #if defined(NO_SSL_DL)
  847. #include <openssl/ssl.h>
  848. #include <openssl/err.h>
  849. #include <openssl/crypto.h>
  850. #include <openssl/x509.h>
  851. #include <openssl/pem.h>
  852. #include <openssl/engine.h>
  853. #include <openssl/conf.h>
  854. #else
  855. /* SSL loaded dynamically from DLL.
  856. * I put the prototypes here to be independent from OpenSSL source
  857. * installation. */
  858. typedef struct ssl_st SSL;
  859. typedef struct ssl_method_st SSL_METHOD;
  860. typedef struct ssl_ctx_st SSL_CTX;
  861. typedef struct x509_store_ctx_st X509_STORE_CTX;
  862. typedef struct x509_name X509_NAME;
  863. typedef struct asn1_integer ASN1_INTEGER;
  864. typedef struct evp_md EVP_MD;
  865. typedef struct x509 X509;
  866. #define SSL_CTRL_OPTIONS (32)
  867. #define SSL_CTRL_CLEAR_OPTIONS (77)
  868. #define SSL_CTRL_SET_ECDH_AUTO (94)
  869. #define SSL_VERIFY_NONE (0)
  870. #define SSL_VERIFY_PEER (1)
  871. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  872. #define SSL_VERIFY_CLIENT_ONCE (4)
  873. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  874. #define SSL_OP_NO_SSLv2 (0x01000000L)
  875. #define SSL_OP_NO_SSLv3 (0x02000000L)
  876. #define SSL_OP_NO_TLSv1 (0x04000000L)
  877. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  878. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  879. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  880. #define SSL_ERROR_NONE (0)
  881. #define SSL_ERROR_SSL (1)
  882. #define SSL_ERROR_WANT_READ (2)
  883. #define SSL_ERROR_WANT_WRITE (3)
  884. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  885. #define SSL_ERROR_SYSCALL (5) /* see errno */
  886. #define SSL_ERROR_ZERO_RETURN (6)
  887. #define SSL_ERROR_WANT_CONNECT (7)
  888. #define SSL_ERROR_WANT_ACCEPT (8)
  889. struct ssl_func {
  890. const char *name; /* SSL function name */
  891. void (*ptr)(void); /* Function pointer */
  892. };
  893. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  894. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  895. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  896. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  897. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  898. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  899. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  900. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  901. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  902. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  903. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  904. #define SSL_CTX_use_PrivateKey_file \
  905. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  906. #define SSL_CTX_use_certificate_file \
  907. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  908. #define SSL_CTX_set_default_passwd_cb \
  909. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  910. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  911. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  912. #define SSL_CTX_use_certificate_chain_file \
  913. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  914. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  915. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  916. #define SSL_CTX_set_verify \
  917. (*(void (*)(SSL_CTX *, \
  918. int, \
  919. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  920. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  921. #define SSL_CTX_load_verify_locations \
  922. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  923. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  924. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  925. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  926. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  927. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  928. #define SSL_CIPHER_get_name \
  929. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  930. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  931. #define SSL_CTX_set_session_id_context \
  932. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  933. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  934. #define SSL_CTX_set_cipher_list \
  935. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  936. #define SSL_CTX_set_options(ctx, op) \
  937. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  938. #define SSL_CTX_clear_options(ctx, op) \
  939. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  940. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  941. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  942. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  943. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  944. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  945. #define CRYPTO_set_locking_callback \
  946. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  947. #define CRYPTO_set_id_callback \
  948. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  949. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  950. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  951. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  952. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  953. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  954. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  955. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  956. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  957. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  958. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  959. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  960. #define X509_NAME_oneline \
  961. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  962. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  963. #define i2c_ASN1_INTEGER \
  964. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  965. #define EVP_get_digestbyname \
  966. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  967. #define ASN1_digest \
  968. (*(int (*)(int (*)(), \
  969. const EVP_MD *, \
  970. char *, \
  971. unsigned char *, \
  972. unsigned int *))crypto_sw[18].ptr)
  973. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  974. /* set_ssl_option() function updates this array.
  975. * It loads SSL library dynamically and changes NULLs to the actual addresses
  976. * of respective functions. The macros above (like SSL_connect()) are really
  977. * just calling these functions indirectly via the pointer. */
  978. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  979. {"SSL_accept", NULL},
  980. {"SSL_connect", NULL},
  981. {"SSL_read", NULL},
  982. {"SSL_write", NULL},
  983. {"SSL_get_error", NULL},
  984. {"SSL_set_fd", NULL},
  985. {"SSL_new", NULL},
  986. {"SSL_CTX_new", NULL},
  987. {"SSLv23_server_method", NULL},
  988. {"SSL_library_init", NULL},
  989. {"SSL_CTX_use_PrivateKey_file", NULL},
  990. {"SSL_CTX_use_certificate_file", NULL},
  991. {"SSL_CTX_set_default_passwd_cb", NULL},
  992. {"SSL_CTX_free", NULL},
  993. {"SSL_load_error_strings", NULL},
  994. {"SSL_CTX_use_certificate_chain_file", NULL},
  995. {"SSLv23_client_method", NULL},
  996. {"SSL_pending", NULL},
  997. {"SSL_CTX_set_verify", NULL},
  998. {"SSL_shutdown", NULL},
  999. {"SSL_CTX_load_verify_locations", NULL},
  1000. {"SSL_CTX_set_default_verify_paths", NULL},
  1001. {"SSL_CTX_set_verify_depth", NULL},
  1002. {"SSL_get_peer_certificate", NULL},
  1003. {"SSL_get_version", NULL},
  1004. {"SSL_get_current_cipher", NULL},
  1005. {"SSL_CIPHER_get_name", NULL},
  1006. {"SSL_CTX_check_private_key", NULL},
  1007. {"SSL_CTX_set_session_id_context", NULL},
  1008. {"SSL_CTX_ctrl", NULL},
  1009. {"SSL_CTX_set_cipher_list", NULL},
  1010. {NULL, NULL}};
  1011. /* Similar array as ssl_sw. These functions could be located in different
  1012. * lib. */
  1013. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1014. {"CRYPTO_set_locking_callback", NULL},
  1015. {"CRYPTO_set_id_callback", NULL},
  1016. {"ERR_get_error", NULL},
  1017. {"ERR_error_string", NULL},
  1018. {"ERR_remove_state", NULL},
  1019. {"ERR_free_strings", NULL},
  1020. {"ENGINE_cleanup", NULL},
  1021. {"CONF_modules_unload", NULL},
  1022. {"CRYPTO_cleanup_all_ex_data", NULL},
  1023. {"EVP_cleanup", NULL},
  1024. {"X509_free", NULL},
  1025. {"X509_get_subject_name", NULL},
  1026. {"X509_get_issuer_name", NULL},
  1027. {"X509_NAME_oneline", NULL},
  1028. {"X509_get_serialNumber", NULL},
  1029. {"i2c_ASN1_INTEGER", NULL},
  1030. {"EVP_get_digestbyname", NULL},
  1031. {"ASN1_digest", NULL},
  1032. {"i2d_X509", NULL},
  1033. {NULL, NULL}};
  1034. #endif /* NO_SSL_DL */
  1035. #endif /* NO_SSL */
  1036. #if !defined(NO_CACHING)
  1037. static const char *month_names[] = {"Jan",
  1038. "Feb",
  1039. "Mar",
  1040. "Apr",
  1041. "May",
  1042. "Jun",
  1043. "Jul",
  1044. "Aug",
  1045. "Sep",
  1046. "Oct",
  1047. "Nov",
  1048. "Dec"};
  1049. #endif /* !NO_CACHING */
  1050. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1051. * union u. */
  1052. union usa {
  1053. struct sockaddr sa;
  1054. struct sockaddr_in sin;
  1055. #if defined(USE_IPV6)
  1056. struct sockaddr_in6 sin6;
  1057. #endif
  1058. };
  1059. /* Describes a string (chunk of memory). */
  1060. struct vec {
  1061. const char *ptr;
  1062. size_t len;
  1063. };
  1064. struct file {
  1065. uint64_t size;
  1066. time_t last_modified;
  1067. FILE *fp;
  1068. const char *membuf; /* Non-NULL if file data is in memory */
  1069. int is_directory;
  1070. int gzipped; /* set to 1 if the content is gzipped
  1071. * in which case we need a content-encoding: gzip header */
  1072. };
  1073. #define STRUCT_FILE_INITIALIZER \
  1074. { \
  1075. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1076. }
  1077. /* Describes listening socket, or socket which was accept()-ed by the master
  1078. * thread and queued for future handling by the worker thread. */
  1079. struct socket {
  1080. SOCKET sock; /* Listening socket */
  1081. union usa lsa; /* Local socket address */
  1082. union usa rsa; /* Remote socket address */
  1083. unsigned char is_ssl; /* Is port SSL-ed */
  1084. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1085. * port */
  1086. unsigned char in_use; /* Is valid */
  1087. };
  1088. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1089. enum {
  1090. CGI_EXTENSIONS,
  1091. CGI_ENVIRONMENT,
  1092. PUT_DELETE_PASSWORDS_FILE,
  1093. CGI_INTERPRETER,
  1094. PROTECT_URI,
  1095. AUTHENTICATION_DOMAIN,
  1096. SSI_EXTENSIONS,
  1097. THROTTLE,
  1098. ACCESS_LOG_FILE,
  1099. ENABLE_DIRECTORY_LISTING,
  1100. ERROR_LOG_FILE,
  1101. GLOBAL_PASSWORDS_FILE,
  1102. INDEX_FILES,
  1103. ENABLE_KEEP_ALIVE,
  1104. ACCESS_CONTROL_LIST,
  1105. EXTRA_MIME_TYPES,
  1106. LISTENING_PORTS,
  1107. DOCUMENT_ROOT,
  1108. SSL_CERTIFICATE,
  1109. NUM_THREADS,
  1110. RUN_AS_USER,
  1111. REWRITE,
  1112. HIDE_FILES,
  1113. REQUEST_TIMEOUT,
  1114. SSL_DO_VERIFY_PEER,
  1115. SSL_CA_PATH,
  1116. SSL_CA_FILE,
  1117. SSL_VERIFY_DEPTH,
  1118. SSL_DEFAULT_VERIFY_PATHS,
  1119. SSL_CIPHER_LIST,
  1120. SSL_PROTOCOL_VERSION,
  1121. SSL_SHORT_TRUST,
  1122. #if defined(USE_WEBSOCKET)
  1123. WEBSOCKET_TIMEOUT,
  1124. #endif
  1125. DECODE_URL,
  1126. #if defined(USE_LUA)
  1127. LUA_PRELOAD_FILE,
  1128. LUA_SCRIPT_EXTENSIONS,
  1129. LUA_SERVER_PAGE_EXTENSIONS,
  1130. #endif
  1131. #if defined(USE_DUKTAPE)
  1132. DUKTAPE_SCRIPT_EXTENSIONS,
  1133. #endif
  1134. #if defined(USE_WEBSOCKET)
  1135. WEBSOCKET_ROOT,
  1136. #endif
  1137. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1138. LUA_WEBSOCKET_EXTENSIONS,
  1139. #endif
  1140. ACCESS_CONTROL_ALLOW_ORIGIN,
  1141. ERROR_PAGES,
  1142. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1143. * socket option typedef TCP_NODELAY. */
  1144. #if !defined(NO_CACHING)
  1145. STATIC_FILE_MAX_AGE,
  1146. #endif
  1147. NUM_OPTIONS
  1148. };
  1149. /* Config option name, config types, default value */
  1150. static struct mg_option config_options[] = {
  1151. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1152. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1153. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1154. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1155. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1156. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1157. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1158. {"throttle", CONFIG_TYPE_STRING, NULL},
  1159. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1160. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1161. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1162. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1163. {"index_files",
  1164. CONFIG_TYPE_STRING,
  1165. #ifdef USE_LUA
  1166. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1167. "index.shtml,index.php"},
  1168. #else
  1169. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1170. #endif
  1171. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1172. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1173. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1174. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1175. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1176. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1177. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1178. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1179. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1180. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1181. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1182. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1183. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1184. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1185. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1186. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1187. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1188. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1189. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1190. #if defined(USE_WEBSOCKET)
  1191. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1192. #endif
  1193. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1194. #if defined(USE_LUA)
  1195. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1196. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1197. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1198. #endif
  1199. #if defined(USE_DUKTAPE)
  1200. /* The support for duktape is still in alpha version state.
  1201. * The name of this config option might change. */
  1202. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1203. #endif
  1204. #if defined(USE_WEBSOCKET)
  1205. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1206. #endif
  1207. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1208. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1209. #endif
  1210. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1211. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1212. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1213. #if !defined(NO_CACHING)
  1214. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1215. #endif
  1216. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1217. /* Check if the config_options and the corresponding enum have compatible
  1218. * sizes. */
  1219. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1220. == (NUM_OPTIONS + 1),
  1221. "config_options and enum not sync");
  1222. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1223. struct mg_handler_info {
  1224. /* Name/Pattern of the URI. */
  1225. char *uri;
  1226. size_t uri_len;
  1227. /* handler type */
  1228. int handler_type;
  1229. /* Handler for http/https or authorization requests. */
  1230. mg_request_handler handler;
  1231. /* Handler for ws/wss (websocket) requests. */
  1232. mg_websocket_connect_handler connect_handler;
  1233. mg_websocket_ready_handler ready_handler;
  1234. mg_websocket_data_handler data_handler;
  1235. mg_websocket_close_handler close_handler;
  1236. /* Handler for authorization requests */
  1237. mg_authorization_handler auth_handler;
  1238. /* User supplied argument for the handler function. */
  1239. void *cbdata;
  1240. /* next handler in a linked list */
  1241. struct mg_handler_info *next;
  1242. };
  1243. struct mg_context {
  1244. volatile int stop_flag; /* Should we stop event loop */
  1245. SSL_CTX *ssl_ctx; /* SSL context */
  1246. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1247. struct mg_callbacks callbacks; /* User-defined callback function */
  1248. void *user_data; /* User-defined data */
  1249. int context_type; /* 1 = server context, 2 = client context */
  1250. struct socket *listening_sockets;
  1251. struct pollfd *listening_socket_fds;
  1252. unsigned int num_listening_sockets;
  1253. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1254. #ifdef ALTERNATIVE_QUEUE
  1255. struct socket *client_socks;
  1256. void **client_wait_events;
  1257. #else
  1258. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1259. volatile int sq_head; /* Head of the socket queue */
  1260. volatile int sq_tail; /* Tail of the socket queue */
  1261. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1262. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1263. #endif
  1264. pthread_t masterthreadid; /* The master thread ID */
  1265. unsigned int
  1266. cfg_worker_threads; /* The number of configured worker threads. */
  1267. pthread_t *workerthreadids; /* The worker thread IDs */
  1268. time_t start_time; /* Server start time, used for authentication */
  1269. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1270. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1271. unsigned long nonce_count; /* Used nonces, used for authentication */
  1272. char *systemName; /* What operating system is running */
  1273. /* linked list of uri handlers */
  1274. struct mg_handler_info *handlers;
  1275. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1276. /* linked list of shared lua websockets */
  1277. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1278. #endif
  1279. #ifdef USE_TIMERS
  1280. struct ttimers *timers;
  1281. #endif
  1282. };
  1283. struct mg_connection {
  1284. struct mg_request_info request_info;
  1285. struct mg_context *ctx;
  1286. SSL *ssl; /* SSL descriptor */
  1287. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1288. struct socket client; /* Connected client */
  1289. time_t conn_birth_time; /* Time (wall clock) when connection was
  1290. * established */
  1291. struct timespec req_time; /* Time (since system start) when the request
  1292. * was received */
  1293. int64_t num_bytes_sent; /* Total bytes sent to client */
  1294. int64_t content_len; /* Content-Length header value */
  1295. int64_t consumed_content; /* How many bytes of content have been read */
  1296. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1297. * data available, 2: all data read */
  1298. size_t chunk_remainder; /* Unread data from the last chunk */
  1299. char *buf; /* Buffer for received data */
  1300. char *path_info; /* PATH_INFO part of the URL */
  1301. int must_close; /* 1 if connection must be closed */
  1302. int in_error_handler; /* 1 if in handler for user defined error
  1303. * pages */
  1304. int internal_error; /* 1 if an error occured while processing the
  1305. * request */
  1306. int buf_size; /* Buffer size */
  1307. int request_len; /* Size of the request + headers in a buffer */
  1308. int data_len; /* Total size of data in a buffer */
  1309. int status_code; /* HTTP reply status code, e.g. 200 */
  1310. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1311. * throttle */
  1312. time_t last_throttle_time; /* Last time throttled data was sent */
  1313. int64_t last_throttle_bytes; /* Bytes sent this second */
  1314. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1315. * atomic transmissions for websockets */
  1316. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1317. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1318. #endif
  1319. int thread_index; /* Thread index within ctx */
  1320. };
  1321. static pthread_key_t sTlsKey; /* Thread local storage index */
  1322. static int sTlsInit = 0;
  1323. static int thread_idx_max = 0;
  1324. struct mg_workerTLS {
  1325. int is_master;
  1326. unsigned long thread_idx;
  1327. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1328. HANDLE pthread_cond_helper_mutex;
  1329. struct mg_workerTLS *next_waiting_thread;
  1330. #endif
  1331. };
  1332. /* Directory entry */
  1333. struct de {
  1334. struct mg_connection *conn;
  1335. char *file_name;
  1336. struct file file;
  1337. };
  1338. #if defined(USE_WEBSOCKET)
  1339. static int is_websocket_protocol(const struct mg_connection *conn);
  1340. #else
  1341. #define is_websocket_protocol(conn) (0)
  1342. #endif
  1343. static int
  1344. mg_atomic_inc(volatile int *addr)
  1345. {
  1346. int ret;
  1347. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1348. /* Depending on the SDK, this function uses either
  1349. * (volatile unsigned int *) or (volatile LONG *),
  1350. * so whatever you use, the other SDK is likely to raise a warning. */
  1351. ret = InterlockedIncrement((volatile long *)addr);
  1352. #elif defined(__GNUC__) \
  1353. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1354. ret = __sync_add_and_fetch(addr, 1);
  1355. #else
  1356. ret = (++(*addr));
  1357. #endif
  1358. return ret;
  1359. }
  1360. static int
  1361. mg_atomic_dec(volatile int *addr)
  1362. {
  1363. int ret;
  1364. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1365. /* Depending on the SDK, this function uses either
  1366. * (volatile unsigned int *) or (volatile LONG *),
  1367. * so whatever you use, the other SDK is likely to raise a warning. */
  1368. ret = InterlockedDecrement((volatile long *)addr);
  1369. #elif defined(__GNUC__) \
  1370. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1371. ret = __sync_sub_and_fetch(addr, 1);
  1372. #else
  1373. ret = (--(*addr));
  1374. #endif
  1375. return ret;
  1376. }
  1377. #if !defined(NO_THREAD_NAME)
  1378. #if defined(_WIN32) && defined(_MSC_VER)
  1379. /* Set the thread name for debugging purposes in Visual Studio
  1380. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1381. */
  1382. #pragma pack(push, 8)
  1383. typedef struct tagTHREADNAME_INFO {
  1384. DWORD dwType; /* Must be 0x1000. */
  1385. LPCSTR szName; /* Pointer to name (in user addr space). */
  1386. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1387. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1388. } THREADNAME_INFO;
  1389. #pragma pack(pop)
  1390. #elif defined(__linux__)
  1391. #include <sys/prctl.h>
  1392. #include <sys/sendfile.h>
  1393. #include <sys/eventfd.h>
  1394. #if defined(ALTERNATIVE_QUEUE)
  1395. static void *
  1396. event_create(void)
  1397. {
  1398. int ret = eventfd(0, EFD_CLOEXEC);
  1399. if (ret == -1) {
  1400. /* Linux uses -1 on error, Windows NULL. */
  1401. /* However, Linux does not return 0 on success either. */
  1402. return 0;
  1403. }
  1404. return (void *)ret;
  1405. }
  1406. static int
  1407. event_wait(void *eventhdl)
  1408. {
  1409. uint64_t u;
  1410. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1411. if (s != sizeof(uint64_t)) {
  1412. /* error */
  1413. return 0;
  1414. }
  1415. (void)u; /* the value is not required */
  1416. return 1;
  1417. }
  1418. static int
  1419. event_signal(void *eventhdl)
  1420. {
  1421. uint64_t u = 1;
  1422. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1423. if (s != sizeof(uint64_t)) {
  1424. /* error */
  1425. return 0;
  1426. }
  1427. return 1;
  1428. }
  1429. static void
  1430. event_destroy(void *eventhdl)
  1431. {
  1432. close((int)eventhdl);
  1433. }
  1434. #endif
  1435. #endif
  1436. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1437. struct posix_event {
  1438. pthread_mutex_t mutex;
  1439. pthread_cond_t cond;
  1440. };
  1441. static void *
  1442. event_create(void)
  1443. {
  1444. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1445. if (ret == 0) {
  1446. /* out of memory */
  1447. return 0;
  1448. }
  1449. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1450. /* pthread mutex not available */
  1451. mg_free(ret);
  1452. return 0;
  1453. }
  1454. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1455. /* pthread cond not available */
  1456. pthread_mutex_destroy(&(ret->mutex));
  1457. mg_free(ret);
  1458. return 0;
  1459. }
  1460. return (void *)ret;
  1461. }
  1462. static int
  1463. event_wait(void *eventhdl)
  1464. {
  1465. struct posix_event *ev = (struct posix_event *)eventhdl;
  1466. pthread_mutex_lock(&(ev->mutex));
  1467. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1468. pthread_mutex_unlock(&(ev->mutex));
  1469. return 1;
  1470. }
  1471. static int
  1472. event_signal(void *eventhdl)
  1473. {
  1474. struct posix_event *ev = (struct posix_event *)eventhdl;
  1475. pthread_mutex_lock(&(ev->mutex));
  1476. pthread_cond_signal(&(ev->cond));
  1477. pthread_mutex_unlock(&(ev->mutex));
  1478. return 1;
  1479. }
  1480. static void
  1481. event_destroy(void *eventhdl)
  1482. {
  1483. struct posix_event *ev = (struct posix_event *)eventhdl;
  1484. pthread_cond_destroy(&(ev->cond));
  1485. pthread_mutex_destroy(&(ev->mutex));
  1486. mg_free(ev);
  1487. }
  1488. #endif
  1489. static void
  1490. mg_set_thread_name(const char *name)
  1491. {
  1492. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1493. mg_snprintf(
  1494. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1495. #if defined(_WIN32)
  1496. #if defined(_MSC_VER)
  1497. /* Windows and Visual Studio Compiler */
  1498. __try
  1499. {
  1500. THREADNAME_INFO info;
  1501. info.dwType = 0x1000;
  1502. info.szName = threadName;
  1503. info.dwThreadID = ~0U;
  1504. info.dwFlags = 0;
  1505. RaiseException(0x406D1388,
  1506. 0,
  1507. sizeof(info) / sizeof(ULONG_PTR),
  1508. (ULONG_PTR *)&info);
  1509. }
  1510. __except(EXCEPTION_EXECUTE_HANDLER)
  1511. {
  1512. }
  1513. #elif defined(__MINGW32__)
  1514. /* No option known to set thread name for MinGW */
  1515. #endif
  1516. #elif defined(__GLIBC__) \
  1517. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1518. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1519. (void)pthread_setname_np(pthread_self(), threadName);
  1520. #elif defined(__linux__)
  1521. /* on linux we can use the old prctl function */
  1522. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1523. #endif
  1524. }
  1525. #else /* !defined(NO_THREAD_NAME) */
  1526. void
  1527. mg_set_thread_name(const char *threadName)
  1528. {
  1529. }
  1530. #endif
  1531. #if defined(MG_LEGACY_INTERFACE)
  1532. const char **
  1533. mg_get_valid_option_names(void)
  1534. {
  1535. /* This function is deprecated. Use mg_get_valid_options instead. */
  1536. static const char *
  1537. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1538. int i;
  1539. for (i = 0; config_options[i].name != NULL; i++) {
  1540. data[i * 2] = config_options[i].name;
  1541. data[i * 2 + 1] = config_options[i].default_value;
  1542. }
  1543. return data;
  1544. }
  1545. #endif
  1546. const struct mg_option *
  1547. mg_get_valid_options(void)
  1548. {
  1549. return config_options;
  1550. }
  1551. static int
  1552. is_file_in_memory(const struct mg_connection *conn,
  1553. const char *path,
  1554. struct file *filep)
  1555. {
  1556. size_t size = 0;
  1557. if (!conn || !filep) {
  1558. return 0;
  1559. }
  1560. if (conn->ctx->callbacks.open_file) {
  1561. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1562. if (filep->membuf != NULL) {
  1563. /* NOTE: override filep->size only on success. Otherwise, it might
  1564. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1565. filep->size = size;
  1566. }
  1567. }
  1568. return filep->membuf != NULL;
  1569. }
  1570. static int
  1571. is_file_opened(const struct file *filep)
  1572. {
  1573. if (!filep) {
  1574. return 0;
  1575. }
  1576. return filep->membuf != NULL || filep->fp != NULL;
  1577. }
  1578. /* mg_fopen will open a file either in memory or on the disk.
  1579. * The input parameter path is a string in UTF-8 encoding.
  1580. * The input parameter mode is the same as for fopen.
  1581. * Either fp or membuf will be set in the output struct filep.
  1582. * The function returns 1 on success, 0 on error. */
  1583. static int
  1584. mg_fopen(const struct mg_connection *conn,
  1585. const char *path,
  1586. const char *mode,
  1587. struct file *filep)
  1588. {
  1589. struct stat st;
  1590. if (!filep) {
  1591. return 0;
  1592. }
  1593. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1594. * only get the file status. They should not work on different members of
  1595. * the same structure (bad cohesion). */
  1596. memset(filep, 0, sizeof(*filep));
  1597. if (stat(path, &st) == 0) {
  1598. filep->size = (uint64_t)(st.st_size);
  1599. }
  1600. if (!is_file_in_memory(conn, path, filep)) {
  1601. #ifdef _WIN32
  1602. wchar_t wbuf[PATH_MAX], wmode[20];
  1603. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1604. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1605. filep->fp = _wfopen(wbuf, wmode);
  1606. #else
  1607. /* Linux et al already use unicode. No need to convert. */
  1608. filep->fp = fopen(path, mode);
  1609. #endif
  1610. }
  1611. return is_file_opened(filep);
  1612. }
  1613. static void
  1614. mg_fclose(struct file *filep)
  1615. {
  1616. if (filep != NULL && filep->fp != NULL) {
  1617. fclose(filep->fp);
  1618. }
  1619. }
  1620. static void
  1621. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1622. {
  1623. for (; *src != '\0' && n > 1; n--) {
  1624. *dst++ = *src++;
  1625. }
  1626. *dst = '\0';
  1627. }
  1628. static int
  1629. lowercase(const char *s)
  1630. {
  1631. return tolower(*(const unsigned char *)s);
  1632. }
  1633. int
  1634. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1635. {
  1636. int diff = 0;
  1637. if (len > 0) {
  1638. do {
  1639. diff = lowercase(s1++) - lowercase(s2++);
  1640. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1641. }
  1642. return diff;
  1643. }
  1644. int
  1645. mg_strcasecmp(const char *s1, const char *s2)
  1646. {
  1647. int diff;
  1648. do {
  1649. diff = lowercase(s1++) - lowercase(s2++);
  1650. } while (diff == 0 && s1[-1] != '\0');
  1651. return diff;
  1652. }
  1653. static char *
  1654. mg_strndup(const char *ptr, size_t len)
  1655. {
  1656. char *p;
  1657. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1658. mg_strlcpy(p, ptr, len + 1);
  1659. }
  1660. return p;
  1661. }
  1662. static char *
  1663. mg_strdup(const char *str)
  1664. {
  1665. return mg_strndup(str, strlen(str));
  1666. }
  1667. static const char *
  1668. mg_strcasestr(const char *big_str, const char *small_str)
  1669. {
  1670. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1671. if (big_len >= small_len) {
  1672. for (i = 0; i <= (big_len - small_len); i++) {
  1673. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1674. return big_str + i;
  1675. }
  1676. }
  1677. }
  1678. return NULL;
  1679. }
  1680. /* Return null terminated string of given maximum length.
  1681. * Report errors if length is exceeded. */
  1682. static void
  1683. mg_vsnprintf(const struct mg_connection *conn,
  1684. int *truncated,
  1685. char *buf,
  1686. size_t buflen,
  1687. const char *fmt,
  1688. va_list ap)
  1689. {
  1690. int n, ok;
  1691. if (buflen == 0) {
  1692. return;
  1693. }
  1694. #ifdef __clang__
  1695. #pragma clang diagnostic push
  1696. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1697. /* Using fmt as a non-literal is intended here, since it is mostly called
  1698. * indirectly by mg_snprintf */
  1699. #endif
  1700. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1701. ok = (n >= 0) && ((size_t)n < buflen);
  1702. #ifdef __clang__
  1703. #pragma clang diagnostic pop
  1704. #endif
  1705. if (ok) {
  1706. if (truncated) {
  1707. *truncated = 0;
  1708. }
  1709. } else {
  1710. if (truncated) {
  1711. *truncated = 1;
  1712. }
  1713. mg_cry(conn,
  1714. "truncating vsnprintf buffer: [%.*s]",
  1715. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1716. buf);
  1717. n = (int)buflen - 1;
  1718. }
  1719. buf[n] = '\0';
  1720. }
  1721. static void
  1722. mg_snprintf(const struct mg_connection *conn,
  1723. int *truncated,
  1724. char *buf,
  1725. size_t buflen,
  1726. const char *fmt,
  1727. ...)
  1728. {
  1729. va_list ap;
  1730. va_start(ap, fmt);
  1731. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1732. va_end(ap);
  1733. }
  1734. static int
  1735. get_option_index(const char *name)
  1736. {
  1737. int i;
  1738. for (i = 0; config_options[i].name != NULL; i++) {
  1739. if (strcmp(config_options[i].name, name) == 0) {
  1740. return i;
  1741. }
  1742. }
  1743. return -1;
  1744. }
  1745. const char *
  1746. mg_get_option(const struct mg_context *ctx, const char *name)
  1747. {
  1748. int i;
  1749. if ((i = get_option_index(name)) == -1) {
  1750. return NULL;
  1751. } else if (!ctx || ctx->config[i] == NULL) {
  1752. return "";
  1753. } else {
  1754. return ctx->config[i];
  1755. }
  1756. }
  1757. struct mg_context *
  1758. mg_get_context(const struct mg_connection *conn)
  1759. {
  1760. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1761. }
  1762. void *
  1763. mg_get_user_data(const struct mg_context *ctx)
  1764. {
  1765. return (ctx == NULL) ? NULL : ctx->user_data;
  1766. }
  1767. void
  1768. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1769. {
  1770. if (conn != NULL) {
  1771. conn->request_info.conn_data = data;
  1772. }
  1773. }
  1774. void *
  1775. mg_get_user_connection_data(const struct mg_connection *conn)
  1776. {
  1777. if (conn != NULL) {
  1778. return conn->request_info.conn_data;
  1779. }
  1780. return NULL;
  1781. }
  1782. size_t
  1783. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1784. {
  1785. size_t i;
  1786. if (!ctx) {
  1787. return 0;
  1788. }
  1789. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1790. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1791. ports[i] =
  1792. #if defined(USE_IPV6)
  1793. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1794. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1795. :
  1796. #endif
  1797. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1798. }
  1799. return i;
  1800. }
  1801. int
  1802. mg_get_server_ports(const struct mg_context *ctx,
  1803. int size,
  1804. struct mg_server_ports *ports)
  1805. {
  1806. int i, cnt = 0;
  1807. if (size <= 0) {
  1808. return -1;
  1809. }
  1810. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1811. if (!ctx) {
  1812. return -1;
  1813. }
  1814. if (!ctx->listening_sockets) {
  1815. return -1;
  1816. }
  1817. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1818. ports[cnt].port =
  1819. #if defined(USE_IPV6)
  1820. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1821. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1822. :
  1823. #endif
  1824. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1825. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1826. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1827. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1828. /* IPv4 */
  1829. ports[cnt].protocol = 1;
  1830. cnt++;
  1831. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1832. /* IPv6 */
  1833. ports[cnt].protocol = 3;
  1834. cnt++;
  1835. }
  1836. }
  1837. return cnt;
  1838. }
  1839. static void
  1840. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1841. {
  1842. buf[0] = '\0';
  1843. if (!usa) {
  1844. return;
  1845. }
  1846. if (usa->sa.sa_family == AF_INET) {
  1847. getnameinfo(&usa->sa,
  1848. sizeof(usa->sin),
  1849. buf,
  1850. (unsigned)len,
  1851. NULL,
  1852. 0,
  1853. NI_NUMERICHOST);
  1854. }
  1855. #if defined(USE_IPV6)
  1856. else if (usa->sa.sa_family == AF_INET6) {
  1857. getnameinfo(&usa->sa,
  1858. sizeof(usa->sin6),
  1859. buf,
  1860. (unsigned)len,
  1861. NULL,
  1862. 0,
  1863. NI_NUMERICHOST);
  1864. }
  1865. #endif
  1866. }
  1867. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1868. * included in all responses other than 100, 101, 5xx. */
  1869. static void
  1870. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1871. {
  1872. struct tm *tm;
  1873. tm = ((t != NULL) ? gmtime(t) : NULL);
  1874. if (tm != NULL) {
  1875. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1876. } else {
  1877. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1878. buf[buf_len - 1] = '\0';
  1879. }
  1880. }
  1881. /* difftime for struct timespec. Return value is in seconds. */
  1882. static double
  1883. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1884. {
  1885. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1886. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1887. }
  1888. /* Print error message to the opened error log stream. */
  1889. void
  1890. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1891. {
  1892. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1893. va_list ap;
  1894. struct file fi;
  1895. time_t timestamp;
  1896. va_start(ap, fmt);
  1897. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1898. va_end(ap);
  1899. buf[sizeof(buf) - 1] = 0;
  1900. if (!conn) {
  1901. puts(buf);
  1902. return;
  1903. }
  1904. /* Do not lock when getting the callback value, here and below.
  1905. * I suppose this is fine, since function cannot disappear in the
  1906. * same way string option can. */
  1907. if ((conn->ctx->callbacks.log_message == NULL)
  1908. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1909. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1910. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1911. == 0) {
  1912. fi.fp = NULL;
  1913. }
  1914. } else {
  1915. fi.fp = NULL;
  1916. }
  1917. if (fi.fp != NULL) {
  1918. flockfile(fi.fp);
  1919. timestamp = time(NULL);
  1920. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1921. fprintf(fi.fp,
  1922. "[%010lu] [error] [client %s] ",
  1923. (unsigned long)timestamp,
  1924. src_addr);
  1925. if (conn->request_info.request_method != NULL) {
  1926. fprintf(fi.fp,
  1927. "%s %s: ",
  1928. conn->request_info.request_method,
  1929. conn->request_info.request_uri);
  1930. }
  1931. fprintf(fi.fp, "%s", buf);
  1932. fputc('\n', fi.fp);
  1933. fflush(fi.fp);
  1934. funlockfile(fi.fp);
  1935. mg_fclose(&fi);
  1936. }
  1937. }
  1938. }
  1939. /* Return fake connection structure. Used for logging, if connection
  1940. * is not applicable at the moment of logging. */
  1941. static struct mg_connection *
  1942. fc(struct mg_context *ctx)
  1943. {
  1944. static struct mg_connection fake_connection;
  1945. fake_connection.ctx = ctx;
  1946. return &fake_connection;
  1947. }
  1948. const char *
  1949. mg_version(void)
  1950. {
  1951. return CIVETWEB_VERSION;
  1952. }
  1953. const struct mg_request_info *
  1954. mg_get_request_info(const struct mg_connection *conn)
  1955. {
  1956. if (!conn) {
  1957. return NULL;
  1958. }
  1959. return &conn->request_info;
  1960. }
  1961. /* Skip the characters until one of the delimiters characters found.
  1962. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1963. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1964. * Delimiters can be quoted with quotechar. */
  1965. static char *
  1966. skip_quoted(char **buf,
  1967. const char *delimiters,
  1968. const char *whitespace,
  1969. char quotechar)
  1970. {
  1971. char *p, *begin_word, *end_word, *end_whitespace;
  1972. begin_word = *buf;
  1973. end_word = begin_word + strcspn(begin_word, delimiters);
  1974. /* Check for quotechar */
  1975. if (end_word > begin_word) {
  1976. p = end_word - 1;
  1977. while (*p == quotechar) {
  1978. /* While the delimiter is quoted, look for the next delimiter. */
  1979. /* This happens, e.g., in calls from parse_auth_header,
  1980. * if the user name contains a " character. */
  1981. /* If there is anything beyond end_word, copy it. */
  1982. if (*end_word != '\0') {
  1983. size_t end_off = strcspn(end_word + 1, delimiters);
  1984. memmove(p, end_word, end_off + 1);
  1985. p += end_off; /* p must correspond to end_word - 1 */
  1986. end_word += end_off + 1;
  1987. } else {
  1988. *p = '\0';
  1989. break;
  1990. }
  1991. }
  1992. for (p++; p < end_word; p++) {
  1993. *p = '\0';
  1994. }
  1995. }
  1996. if (*end_word == '\0') {
  1997. *buf = end_word;
  1998. } else {
  1999. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  2000. for (p = end_word; p < end_whitespace; p++) {
  2001. *p = '\0';
  2002. }
  2003. *buf = end_whitespace;
  2004. }
  2005. return begin_word;
  2006. }
  2007. /* Simplified version of skip_quoted without quote char
  2008. * and whitespace == delimiters */
  2009. static char *
  2010. skip(char **buf, const char *delimiters)
  2011. {
  2012. return skip_quoted(buf, delimiters, delimiters, 0);
  2013. }
  2014. /* Return HTTP header value, or NULL if not found. */
  2015. static const char *
  2016. get_header(const struct mg_request_info *ri, const char *name)
  2017. {
  2018. int i;
  2019. if (ri) {
  2020. for (i = 0; i < ri->num_headers; i++) {
  2021. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2022. return ri->http_headers[i].value;
  2023. }
  2024. }
  2025. }
  2026. return NULL;
  2027. }
  2028. const char *
  2029. mg_get_header(const struct mg_connection *conn, const char *name)
  2030. {
  2031. if (!conn) {
  2032. return NULL;
  2033. }
  2034. return get_header(&conn->request_info, name);
  2035. }
  2036. /* A helper function for traversing a comma separated list of values.
  2037. * It returns a list pointer shifted to the next value, or NULL if the end
  2038. * of the list found.
  2039. * Value is stored in val vector. If value has form "x=y", then eq_val
  2040. * vector is initialized to point to the "y" part, and val vector length
  2041. * is adjusted to point only to "x". */
  2042. static const char *
  2043. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2044. {
  2045. int end;
  2046. reparse:
  2047. if (val == NULL || list == NULL || *list == '\0') {
  2048. /* End of the list */
  2049. list = NULL;
  2050. } else {
  2051. /* Skip over leading LWS */
  2052. while (*list == ' ' || *list == '\t')
  2053. list++;
  2054. val->ptr = list;
  2055. if ((list = strchr(val->ptr, ',')) != NULL) {
  2056. /* Comma found. Store length and shift the list ptr */
  2057. val->len = ((size_t)(list - val->ptr));
  2058. list++;
  2059. } else {
  2060. /* This value is the last one */
  2061. list = val->ptr + strlen(val->ptr);
  2062. val->len = ((size_t)(list - val->ptr));
  2063. }
  2064. /* Adjust length for trailing LWS */
  2065. end = (int)val->len - 1;
  2066. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2067. end--;
  2068. val->len = (size_t)(end + 1);
  2069. if (val->len == 0) {
  2070. /* Ignore any empty entries. */
  2071. goto reparse;
  2072. }
  2073. if (eq_val != NULL) {
  2074. /* Value has form "x=y", adjust pointers and lengths
  2075. * so that val points to "x", and eq_val points to "y". */
  2076. eq_val->len = 0;
  2077. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2078. if (eq_val->ptr != NULL) {
  2079. eq_val->ptr++; /* Skip over '=' character */
  2080. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2081. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2082. }
  2083. }
  2084. }
  2085. return list;
  2086. }
  2087. /* A helper function for checking if a comma separated list of values contains
  2088. * the given option (case insensitvely).
  2089. * 'header' can be NULL, in which case false is returned. */
  2090. static int
  2091. header_has_option(const char *header, const char *option)
  2092. {
  2093. struct vec opt_vec;
  2094. struct vec eq_vec;
  2095. assert(option != NULL);
  2096. assert(option[0] != '\0');
  2097. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2098. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2099. return 1;
  2100. }
  2101. return 0;
  2102. }
  2103. /* Perform case-insensitive match of string against pattern */
  2104. static int
  2105. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2106. {
  2107. const char *or_str;
  2108. size_t i;
  2109. int j, len, res;
  2110. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2111. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2112. return (res > 0) ? res : match_prefix(or_str + 1,
  2113. (size_t)((pattern + pattern_len)
  2114. - (or_str + 1)),
  2115. str);
  2116. }
  2117. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2118. if (pattern[i] == '?' && str[j] != '\0') {
  2119. continue;
  2120. } else if (pattern[i] == '$') {
  2121. return (str[j] == '\0') ? j : -1;
  2122. } else if (pattern[i] == '*') {
  2123. i++;
  2124. if (pattern[i] == '*') {
  2125. i++;
  2126. len = (int)strlen(str + j);
  2127. } else {
  2128. len = (int)strcspn(str + j, "/");
  2129. }
  2130. if (i == pattern_len) {
  2131. return j + len;
  2132. }
  2133. do {
  2134. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2135. } while (res == -1 && len-- > 0);
  2136. return (res == -1) ? -1 : j + res + len;
  2137. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2138. return -1;
  2139. }
  2140. }
  2141. return j;
  2142. }
  2143. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2144. * This function must tolerate situations when connection info is not
  2145. * set up, for example if request parsing failed. */
  2146. static int
  2147. should_keep_alive(const struct mg_connection *conn)
  2148. {
  2149. if (conn != NULL) {
  2150. const char *http_version = conn->request_info.http_version;
  2151. const char *header = mg_get_header(conn, "Connection");
  2152. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2153. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2154. || (header != NULL && !header_has_option(header, "keep-alive"))
  2155. || (header == NULL && http_version
  2156. && 0 != strcmp(http_version, "1.1"))) {
  2157. return 0;
  2158. }
  2159. return 1;
  2160. }
  2161. return 0;
  2162. }
  2163. static int
  2164. should_decode_url(const struct mg_connection *conn)
  2165. {
  2166. if (!conn || !conn->ctx) {
  2167. return 0;
  2168. }
  2169. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2170. }
  2171. static const char *
  2172. suggest_connection_header(const struct mg_connection *conn)
  2173. {
  2174. return should_keep_alive(conn) ? "keep-alive" : "close";
  2175. }
  2176. static int
  2177. send_no_cache_header(struct mg_connection *conn)
  2178. {
  2179. /* Send all current and obsolete cache opt-out directives. */
  2180. return mg_printf(conn,
  2181. "Cache-Control: no-cache, no-store, "
  2182. "must-revalidate, private, max-age=0\r\n"
  2183. "Pragma: no-cache\r\n"
  2184. "Expires: 0\r\n");
  2185. }
  2186. static int
  2187. send_static_cache_header(struct mg_connection *conn)
  2188. {
  2189. #if !defined(NO_CACHING)
  2190. /* Read the server config to check how long a file may be cached.
  2191. * The configuration is in seconds. */
  2192. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2193. if (max_age <= 0) {
  2194. /* 0 means "do not cache". All values <0 are reserved
  2195. * and may be used differently in the future. */
  2196. /* If a file should not be cached, do not only send
  2197. * max-age=0, but also pragmas and Expires headers. */
  2198. return send_no_cache_header(conn);
  2199. }
  2200. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2201. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2202. /* See also https://www.mnot.net/cache_docs/ */
  2203. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2204. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2205. * year to 31622400 seconds. For the moment, we just send whatever has
  2206. * been configured, still the behavior for >1 year should be considered
  2207. * as undefined. */
  2208. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2209. #else /* NO_CACHING */
  2210. return send_no_cache_header(conn);
  2211. #endif /* !NO_CACHING */
  2212. }
  2213. static void handle_file_based_request(struct mg_connection *conn,
  2214. const char *path,
  2215. struct file *filep);
  2216. static int
  2217. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2218. const char *
  2219. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2220. {
  2221. /* See IANA HTTP status code assignment:
  2222. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2223. */
  2224. switch (response_code) {
  2225. /* RFC2616 Section 10.1 - Informational 1xx */
  2226. case 100:
  2227. return "Continue"; /* RFC2616 Section 10.1.1 */
  2228. case 101:
  2229. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2230. case 102:
  2231. return "Processing"; /* RFC2518 Section 10.1 */
  2232. /* RFC2616 Section 10.2 - Successful 2xx */
  2233. case 200:
  2234. return "OK"; /* RFC2616 Section 10.2.1 */
  2235. case 201:
  2236. return "Created"; /* RFC2616 Section 10.2.2 */
  2237. case 202:
  2238. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2239. case 203:
  2240. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2241. case 204:
  2242. return "No Content"; /* RFC2616 Section 10.2.5 */
  2243. case 205:
  2244. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2245. case 206:
  2246. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2247. case 207:
  2248. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2249. case 208:
  2250. return "Already Reported"; /* RFC5842 Section 7.1 */
  2251. case 226:
  2252. return "IM used"; /* RFC3229 Section 10.4.1 */
  2253. /* RFC2616 Section 10.3 - Redirection 3xx */
  2254. case 300:
  2255. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2256. case 301:
  2257. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2258. case 302:
  2259. return "Found"; /* RFC2616 Section 10.3.3 */
  2260. case 303:
  2261. return "See Other"; /* RFC2616 Section 10.3.4 */
  2262. case 304:
  2263. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2264. case 305:
  2265. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2266. case 307:
  2267. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2268. case 308:
  2269. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2270. /* RFC2616 Section 10.4 - Client Error 4xx */
  2271. case 400:
  2272. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2273. case 401:
  2274. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2275. case 402:
  2276. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2277. case 403:
  2278. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2279. case 404:
  2280. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2281. case 405:
  2282. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2283. case 406:
  2284. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2285. case 407:
  2286. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2287. case 408:
  2288. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2289. case 409:
  2290. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2291. case 410:
  2292. return "Gone"; /* RFC2616 Section 10.4.11 */
  2293. case 411:
  2294. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2295. case 412:
  2296. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2297. case 413:
  2298. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2299. case 414:
  2300. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2301. case 415:
  2302. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2303. case 416:
  2304. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2305. case 417:
  2306. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2307. case 421:
  2308. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2309. case 422:
  2310. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2311. * Section 11.2 */
  2312. case 423:
  2313. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2314. case 424:
  2315. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2316. * Section 11.4 */
  2317. case 426:
  2318. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2319. case 428:
  2320. return "Precondition Required"; /* RFC 6585, Section 3 */
  2321. case 429:
  2322. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2323. case 431:
  2324. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2325. case 451:
  2326. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2327. * Section 3 */
  2328. /* RFC2616 Section 10.5 - Server Error 5xx */
  2329. case 500:
  2330. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2331. case 501:
  2332. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2333. case 502:
  2334. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2335. case 503:
  2336. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2337. case 504:
  2338. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2339. case 505:
  2340. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2341. case 506:
  2342. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2343. case 507:
  2344. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2345. * Section 11.5 */
  2346. case 508:
  2347. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2348. case 510:
  2349. return "Not Extended"; /* RFC 2774, Section 7 */
  2350. case 511:
  2351. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2352. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2353. * E.g., "de facto" standards due to common use, ... */
  2354. case 418:
  2355. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2356. case 419:
  2357. return "Authentication Timeout"; /* common use */
  2358. case 420:
  2359. return "Enhance Your Calm"; /* common use */
  2360. case 440:
  2361. return "Login Timeout"; /* common use */
  2362. case 509:
  2363. return "Bandwidth Limit Exceeded"; /* common use */
  2364. default:
  2365. /* This error code is unknown. This should not happen. */
  2366. if (conn) {
  2367. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2368. }
  2369. /* Return at least a category according to RFC 2616 Section 10. */
  2370. if (response_code >= 100 && response_code < 200) {
  2371. /* Unknown informational status code */
  2372. return "Information";
  2373. }
  2374. if (response_code >= 200 && response_code < 300) {
  2375. /* Unknown success code */
  2376. return "Success";
  2377. }
  2378. if (response_code >= 300 && response_code < 400) {
  2379. /* Unknown redirection code */
  2380. return "Redirection";
  2381. }
  2382. if (response_code >= 400 && response_code < 500) {
  2383. /* Unknown request error code */
  2384. return "Client Error";
  2385. }
  2386. if (response_code >= 500 && response_code < 600) {
  2387. /* Unknown server error code */
  2388. return "Server Error";
  2389. }
  2390. /* Response code not even within reasonable range */
  2391. return "";
  2392. }
  2393. }
  2394. static void send_http_error(struct mg_connection *,
  2395. int,
  2396. PRINTF_FORMAT_STRING(const char *fmt),
  2397. ...) PRINTF_ARGS(3, 4);
  2398. static void
  2399. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2400. {
  2401. char buf[MG_BUF_LEN];
  2402. va_list ap;
  2403. int len, i, page_handler_found, scope, truncated;
  2404. char date[64];
  2405. time_t curtime = time(NULL);
  2406. const char *error_handler = NULL;
  2407. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2408. const char *error_page_file_ext, *tstr;
  2409. const char *status_text = mg_get_response_code_text(conn, status);
  2410. if (conn == NULL) {
  2411. return;
  2412. }
  2413. conn->status_code = status;
  2414. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2415. || conn->ctx->callbacks.http_error(conn, status)) {
  2416. if (!conn->in_error_handler) {
  2417. /* Send user defined error pages, if defined */
  2418. error_handler = conn->ctx->config[ERROR_PAGES];
  2419. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2420. page_handler_found = 0;
  2421. if (error_handler != NULL) {
  2422. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2423. switch (scope) {
  2424. case 1: /* Handler for specific error, e.g. 404 error */
  2425. mg_snprintf(conn,
  2426. &truncated,
  2427. buf,
  2428. sizeof(buf) - 32,
  2429. "%serror%03u.",
  2430. error_handler,
  2431. status);
  2432. break;
  2433. case 2: /* Handler for error group, e.g., 5xx error handler
  2434. * for all server errors (500-599) */
  2435. mg_snprintf(conn,
  2436. &truncated,
  2437. buf,
  2438. sizeof(buf) - 32,
  2439. "%serror%01uxx.",
  2440. error_handler,
  2441. status / 100);
  2442. break;
  2443. default: /* Handler for all errors */
  2444. mg_snprintf(conn,
  2445. &truncated,
  2446. buf,
  2447. sizeof(buf) - 32,
  2448. "%serror.",
  2449. error_handler);
  2450. break;
  2451. }
  2452. /* String truncation in buf may only occur if error_handler
  2453. * is too long. This string is from the config, not from a
  2454. * client. */
  2455. (void)truncated;
  2456. len = (int)strlen(buf);
  2457. tstr = strchr(error_page_file_ext, '.');
  2458. while (tstr) {
  2459. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2460. i++)
  2461. buf[len + i - 1] = tstr[i];
  2462. buf[len + i - 1] = 0;
  2463. if (mg_stat(conn, buf, &error_page_file)) {
  2464. page_handler_found = 1;
  2465. break;
  2466. }
  2467. tstr = strchr(tstr + i, '.');
  2468. }
  2469. }
  2470. }
  2471. if (page_handler_found) {
  2472. conn->in_error_handler = 1;
  2473. handle_file_based_request(conn, buf, &error_page_file);
  2474. conn->in_error_handler = 0;
  2475. return;
  2476. }
  2477. }
  2478. /* No custom error page. Send default error page. */
  2479. gmt_time_string(date, sizeof(date), &curtime);
  2480. conn->must_close = 1;
  2481. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2482. send_no_cache_header(conn);
  2483. mg_printf(conn,
  2484. "Date: %s\r\n"
  2485. "Connection: close\r\n\r\n",
  2486. date);
  2487. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2488. if (status > 199 && status != 204 && status != 304) {
  2489. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2490. if (fmt != NULL) {
  2491. va_start(ap, fmt);
  2492. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2493. va_end(ap);
  2494. mg_write(conn, buf, strlen(buf));
  2495. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2496. }
  2497. } else {
  2498. /* No body allowed. Close the connection. */
  2499. DEBUG_TRACE("Error %i", status);
  2500. }
  2501. }
  2502. }
  2503. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2504. /* Create substitutes for POSIX functions in Win32. */
  2505. #if defined(__MINGW32__)
  2506. /* Show no warning in case system functions are not used. */
  2507. #pragma GCC diagnostic push
  2508. #pragma GCC diagnostic ignored "-Wunused-function"
  2509. #endif
  2510. static int
  2511. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2512. {
  2513. (void)unused;
  2514. *mutex = CreateMutex(NULL, FALSE, NULL);
  2515. return (*mutex == NULL) ? -1 : 0;
  2516. }
  2517. static int
  2518. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2519. {
  2520. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2521. }
  2522. static int
  2523. pthread_mutex_lock(pthread_mutex_t *mutex)
  2524. {
  2525. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2526. }
  2527. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2528. static int
  2529. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2530. {
  2531. switch (WaitForSingleObject(*mutex, 0)) {
  2532. case WAIT_OBJECT_0:
  2533. return 0;
  2534. case WAIT_TIMEOUT:
  2535. return -2; /* EBUSY */
  2536. }
  2537. return -1;
  2538. }
  2539. #endif
  2540. static int
  2541. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2542. {
  2543. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2544. }
  2545. #ifndef WIN_PTHREADS_TIME_H
  2546. static int
  2547. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2548. {
  2549. FILETIME ft;
  2550. ULARGE_INTEGER li;
  2551. BOOL ok = FALSE;
  2552. double d;
  2553. static double perfcnt_per_sec = 0.0;
  2554. if (tp) {
  2555. memset(tp, 0, sizeof(*tp));
  2556. if (clk_id == CLOCK_REALTIME) {
  2557. GetSystemTimeAsFileTime(&ft);
  2558. li.LowPart = ft.dwLowDateTime;
  2559. li.HighPart = ft.dwHighDateTime;
  2560. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2561. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2562. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2563. ok = TRUE;
  2564. } else if (clk_id == CLOCK_MONOTONIC) {
  2565. if (perfcnt_per_sec == 0.0) {
  2566. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2567. perfcnt_per_sec = 1.0 / li.QuadPart;
  2568. }
  2569. if (perfcnt_per_sec != 0.0) {
  2570. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2571. d = li.QuadPart * perfcnt_per_sec;
  2572. tp->tv_sec = (time_t)d;
  2573. d -= tp->tv_sec;
  2574. tp->tv_nsec = (long)(d * 1.0E9);
  2575. ok = TRUE;
  2576. }
  2577. }
  2578. }
  2579. return ok ? 0 : -1;
  2580. }
  2581. #endif
  2582. static int
  2583. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2584. {
  2585. (void)unused;
  2586. InitializeCriticalSection(&cv->threadIdSec);
  2587. cv->waiting_thread = NULL;
  2588. return 0;
  2589. }
  2590. static int
  2591. pthread_cond_timedwait(pthread_cond_t *cv,
  2592. pthread_mutex_t *mutex,
  2593. const struct timespec *abstime)
  2594. {
  2595. struct mg_workerTLS **ptls,
  2596. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2597. int ok;
  2598. struct timespec tsnow;
  2599. int64_t nsnow, nswaitabs, nswaitrel;
  2600. DWORD mswaitrel;
  2601. EnterCriticalSection(&cv->threadIdSec);
  2602. /* Add this thread to cv's waiting list */
  2603. ptls = &cv->waiting_thread;
  2604. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2605. ;
  2606. tls->next_waiting_thread = NULL;
  2607. *ptls = tls;
  2608. LeaveCriticalSection(&cv->threadIdSec);
  2609. if (abstime) {
  2610. clock_gettime(CLOCK_REALTIME, &tsnow);
  2611. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2612. nswaitabs =
  2613. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2614. nswaitrel = nswaitabs - nsnow;
  2615. if (nswaitrel < 0) {
  2616. nswaitrel = 0;
  2617. }
  2618. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2619. } else {
  2620. mswaitrel = INFINITE;
  2621. }
  2622. pthread_mutex_unlock(mutex);
  2623. ok = (WAIT_OBJECT_0
  2624. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2625. if (!ok) {
  2626. ok = 1;
  2627. EnterCriticalSection(&cv->threadIdSec);
  2628. ptls = &cv->waiting_thread;
  2629. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2630. if (*ptls == tls) {
  2631. *ptls = tls->next_waiting_thread;
  2632. ok = 0;
  2633. break;
  2634. }
  2635. }
  2636. LeaveCriticalSection(&cv->threadIdSec);
  2637. if (ok) {
  2638. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2639. }
  2640. }
  2641. /* This thread has been removed from cv's waiting list */
  2642. pthread_mutex_lock(mutex);
  2643. return ok ? 0 : -1;
  2644. }
  2645. static int
  2646. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2647. {
  2648. return pthread_cond_timedwait(cv, mutex, NULL);
  2649. }
  2650. static int
  2651. pthread_cond_signal(pthread_cond_t *cv)
  2652. {
  2653. HANDLE wkup = NULL;
  2654. BOOL ok = FALSE;
  2655. EnterCriticalSection(&cv->threadIdSec);
  2656. if (cv->waiting_thread) {
  2657. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2658. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2659. ok = SetEvent(wkup);
  2660. assert(ok);
  2661. }
  2662. LeaveCriticalSection(&cv->threadIdSec);
  2663. return ok ? 0 : 1;
  2664. }
  2665. static int
  2666. pthread_cond_broadcast(pthread_cond_t *cv)
  2667. {
  2668. EnterCriticalSection(&cv->threadIdSec);
  2669. while (cv->waiting_thread) {
  2670. pthread_cond_signal(cv);
  2671. }
  2672. LeaveCriticalSection(&cv->threadIdSec);
  2673. return 0;
  2674. }
  2675. static int
  2676. pthread_cond_destroy(pthread_cond_t *cv)
  2677. {
  2678. EnterCriticalSection(&cv->threadIdSec);
  2679. assert(cv->waiting_thread == NULL);
  2680. LeaveCriticalSection(&cv->threadIdSec);
  2681. DeleteCriticalSection(&cv->threadIdSec);
  2682. return 0;
  2683. }
  2684. #ifdef ALTERNATIVE_QUEUE
  2685. static void *
  2686. event_create(void)
  2687. {
  2688. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2689. }
  2690. static int
  2691. event_wait(void *eventhdl)
  2692. {
  2693. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2694. return (res == WAIT_OBJECT_0);
  2695. }
  2696. static int
  2697. event_signal(void *eventhdl)
  2698. {
  2699. return (int)SetEvent((HANDLE)eventhdl);
  2700. }
  2701. static void
  2702. event_destroy(void *eventhdl)
  2703. {
  2704. CloseHandle((HANDLE)eventhdl);
  2705. }
  2706. #endif
  2707. #if defined(__MINGW32__)
  2708. /* Enable unused function warning again */
  2709. #pragma GCC diagnostic pop
  2710. #endif
  2711. /* For Windows, change all slashes to backslashes in path names. */
  2712. static void
  2713. change_slashes_to_backslashes(char *path)
  2714. {
  2715. int i;
  2716. for (i = 0; path[i] != '\0'; i++) {
  2717. if (path[i] == '/') {
  2718. path[i] = '\\';
  2719. }
  2720. /* remove double backslash (check i > 0 to preserve UNC paths,
  2721. * like \\server\file.txt) */
  2722. if ((path[i] == '\\') && (i > 0)) {
  2723. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2724. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2725. }
  2726. }
  2727. }
  2728. }
  2729. static int
  2730. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2731. {
  2732. int diff;
  2733. do {
  2734. diff = tolower(*s1) - tolower(*s2);
  2735. s1++;
  2736. s2++;
  2737. } while (diff == 0 && s1[-1] != '\0');
  2738. return diff;
  2739. }
  2740. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2741. * wbuf and wbuf_len is a target buffer and its length. */
  2742. static void
  2743. path_to_unicode(const struct mg_connection *conn,
  2744. const char *path,
  2745. wchar_t *wbuf,
  2746. size_t wbuf_len)
  2747. {
  2748. char buf[PATH_MAX], buf2[PATH_MAX];
  2749. wchar_t wbuf2[MAX_PATH + 1];
  2750. DWORD long_len, err;
  2751. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2752. mg_strlcpy(buf, path, sizeof(buf));
  2753. change_slashes_to_backslashes(buf);
  2754. /* Convert to Unicode and back. If doubly-converted string does not
  2755. * match the original, something is fishy, reject. */
  2756. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2757. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2758. WideCharToMultiByte(
  2759. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2760. if (strcmp(buf, buf2) != 0) {
  2761. wbuf[0] = L'\0';
  2762. }
  2763. /* TODO: Add a configuration to switch between case sensitive and
  2764. * case insensitive URIs for Windows server. */
  2765. /*
  2766. if (conn) {
  2767. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2768. fcompare = wcscmp;
  2769. }
  2770. }
  2771. */
  2772. (void)conn; /* conn is currently unused */
  2773. #if !defined(_WIN32_WCE)
  2774. /* Only accept a full file path, not a Windows short (8.3) path. */
  2775. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2776. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2777. if (long_len == 0) {
  2778. err = GetLastError();
  2779. if (err == ERROR_FILE_NOT_FOUND) {
  2780. /* File does not exist. This is not always a problem here. */
  2781. return;
  2782. }
  2783. }
  2784. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2785. /* Short name is used. */
  2786. wbuf[0] = L'\0';
  2787. }
  2788. #else
  2789. (void)long_len;
  2790. (void)wbuf2;
  2791. (void)err;
  2792. if (strchr(path, '~')) {
  2793. wbuf[0] = L'\0';
  2794. }
  2795. #endif
  2796. }
  2797. /* Windows happily opens files with some garbage at the end of file name.
  2798. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2799. * "a.cgi", despite one would expect an error back.
  2800. * This function returns non-0 if path ends with some garbage. */
  2801. static int
  2802. path_cannot_disclose_cgi(const char *path)
  2803. {
  2804. static const char *allowed_last_characters = "_-";
  2805. int last = path[strlen(path) - 1];
  2806. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2807. }
  2808. static int
  2809. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2810. {
  2811. wchar_t wbuf[PATH_MAX];
  2812. WIN32_FILE_ATTRIBUTE_DATA info;
  2813. time_t creation_time;
  2814. if (!filep) {
  2815. return 0;
  2816. }
  2817. memset(filep, 0, sizeof(*filep));
  2818. if (conn && is_file_in_memory(conn, path, filep)) {
  2819. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2820. * memset */
  2821. filep->last_modified = time(NULL);
  2822. /* last_modified = now ... assumes the file may change during runtime,
  2823. * so every mg_fopen call may return different data */
  2824. /* last_modified = conn->ctx.start_time;
  2825. * May be used it the data does not change during runtime. This allows
  2826. * browser caching. Since we do not know, we have to assume the file
  2827. * in memory may change. */
  2828. return 1;
  2829. }
  2830. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2831. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2832. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2833. filep->last_modified =
  2834. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2835. info.ftLastWriteTime.dwHighDateTime);
  2836. /* On Windows, the file creation time can be higher than the
  2837. * modification time, e.g. when a file is copied.
  2838. * Since the Last-Modified timestamp is used for caching
  2839. * it should be based on the most recent timestamp. */
  2840. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2841. info.ftCreationTime.dwHighDateTime);
  2842. if (creation_time > filep->last_modified) {
  2843. filep->last_modified = creation_time;
  2844. }
  2845. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2846. /* If file name is fishy, reset the file structure and return
  2847. * error.
  2848. * Note it is important to reset, not just return the error, cause
  2849. * functions like is_file_opened() check the struct. */
  2850. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2851. memset(filep, 0, sizeof(*filep));
  2852. return 0;
  2853. }
  2854. return 1;
  2855. }
  2856. return 0;
  2857. }
  2858. static int
  2859. mg_remove(const struct mg_connection *conn, const char *path)
  2860. {
  2861. wchar_t wbuf[PATH_MAX];
  2862. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2863. return DeleteFileW(wbuf) ? 0 : -1;
  2864. }
  2865. static int
  2866. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2867. {
  2868. wchar_t wbuf[PATH_MAX];
  2869. (void)mode;
  2870. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2871. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2872. }
  2873. /* Create substitutes for POSIX functions in Win32. */
  2874. #if defined(__MINGW32__)
  2875. /* Show no warning in case system functions are not used. */
  2876. #pragma GCC diagnostic push
  2877. #pragma GCC diagnostic ignored "-Wunused-function"
  2878. #endif
  2879. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2880. static DIR *
  2881. mg_opendir(const struct mg_connection *conn, const char *name)
  2882. {
  2883. DIR *dir = NULL;
  2884. wchar_t wpath[PATH_MAX];
  2885. DWORD attrs;
  2886. if (name == NULL) {
  2887. SetLastError(ERROR_BAD_ARGUMENTS);
  2888. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2889. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2890. } else {
  2891. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2892. attrs = GetFileAttributesW(wpath);
  2893. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2894. == FILE_ATTRIBUTE_DIRECTORY)) {
  2895. (void)wcscat(wpath, L"\\*");
  2896. dir->handle = FindFirstFileW(wpath, &dir->info);
  2897. dir->result.d_name[0] = '\0';
  2898. } else {
  2899. mg_free(dir);
  2900. dir = NULL;
  2901. }
  2902. }
  2903. return dir;
  2904. }
  2905. static int
  2906. mg_closedir(DIR *dir)
  2907. {
  2908. int result = 0;
  2909. if (dir != NULL) {
  2910. if (dir->handle != INVALID_HANDLE_VALUE)
  2911. result = FindClose(dir->handle) ? 0 : -1;
  2912. mg_free(dir);
  2913. } else {
  2914. result = -1;
  2915. SetLastError(ERROR_BAD_ARGUMENTS);
  2916. }
  2917. return result;
  2918. }
  2919. static struct dirent *
  2920. mg_readdir(DIR *dir)
  2921. {
  2922. struct dirent *result = 0;
  2923. if (dir) {
  2924. if (dir->handle != INVALID_HANDLE_VALUE) {
  2925. result = &dir->result;
  2926. (void)WideCharToMultiByte(CP_UTF8,
  2927. 0,
  2928. dir->info.cFileName,
  2929. -1,
  2930. result->d_name,
  2931. sizeof(result->d_name),
  2932. NULL,
  2933. NULL);
  2934. if (!FindNextFileW(dir->handle, &dir->info)) {
  2935. (void)FindClose(dir->handle);
  2936. dir->handle = INVALID_HANDLE_VALUE;
  2937. }
  2938. } else {
  2939. SetLastError(ERROR_FILE_NOT_FOUND);
  2940. }
  2941. } else {
  2942. SetLastError(ERROR_BAD_ARGUMENTS);
  2943. }
  2944. return result;
  2945. }
  2946. #ifndef HAVE_POLL
  2947. static int
  2948. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2949. {
  2950. struct timeval tv;
  2951. fd_set set;
  2952. unsigned int i;
  2953. int result;
  2954. SOCKET maxfd = 0;
  2955. memset(&tv, 0, sizeof(tv));
  2956. tv.tv_sec = milliseconds / 1000;
  2957. tv.tv_usec = (milliseconds % 1000) * 1000;
  2958. FD_ZERO(&set);
  2959. for (i = 0; i < n; i++) {
  2960. FD_SET((SOCKET)pfd[i].fd, &set);
  2961. pfd[i].revents = 0;
  2962. if (pfd[i].fd > maxfd) {
  2963. maxfd = pfd[i].fd;
  2964. }
  2965. }
  2966. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2967. for (i = 0; i < n; i++) {
  2968. if (FD_ISSET(pfd[i].fd, &set)) {
  2969. pfd[i].revents = POLLIN;
  2970. }
  2971. }
  2972. }
  2973. return result;
  2974. }
  2975. #endif /* HAVE_POLL */
  2976. #if defined(__MINGW32__)
  2977. /* Enable unused function warning again */
  2978. #pragma GCC diagnostic pop
  2979. #endif
  2980. static void
  2981. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2982. {
  2983. (void)conn; /* Unused. */
  2984. #if defined(_WIN32_WCE)
  2985. (void)sock;
  2986. #else
  2987. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2988. #endif
  2989. }
  2990. int
  2991. mg_start_thread(mg_thread_func_t f, void *p)
  2992. {
  2993. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2994. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2995. */
  2996. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2997. == ((uintptr_t)(-1L)))
  2998. ? -1
  2999. : 0);
  3000. #else
  3001. return (
  3002. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3003. ? -1
  3004. : 0);
  3005. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3006. }
  3007. /* Start a thread storing the thread context. */
  3008. static int
  3009. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3010. void *p,
  3011. pthread_t *threadidptr)
  3012. {
  3013. uintptr_t uip;
  3014. HANDLE threadhandle;
  3015. int result = -1;
  3016. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3017. threadhandle = (HANDLE)uip;
  3018. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3019. *threadidptr = threadhandle;
  3020. result = 0;
  3021. }
  3022. return result;
  3023. }
  3024. /* Wait for a thread to finish. */
  3025. static int
  3026. mg_join_thread(pthread_t threadid)
  3027. {
  3028. int result;
  3029. DWORD dwevent;
  3030. result = -1;
  3031. dwevent = WaitForSingleObject(threadid, INFINITE);
  3032. if (dwevent == WAIT_FAILED) {
  3033. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3034. } else {
  3035. if (dwevent == WAIT_OBJECT_0) {
  3036. CloseHandle(threadid);
  3037. result = 0;
  3038. }
  3039. }
  3040. return result;
  3041. }
  3042. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3043. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3044. /* Create substitutes for POSIX functions in Win32. */
  3045. #if defined(__MINGW32__)
  3046. /* Show no warning in case system functions are not used. */
  3047. #pragma GCC diagnostic push
  3048. #pragma GCC diagnostic ignored "-Wunused-function"
  3049. #endif
  3050. static HANDLE
  3051. dlopen(const char *dll_name, int flags)
  3052. {
  3053. wchar_t wbuf[PATH_MAX];
  3054. (void)flags;
  3055. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3056. return LoadLibraryW(wbuf);
  3057. }
  3058. static int
  3059. dlclose(void *handle)
  3060. {
  3061. int result;
  3062. if (FreeLibrary((HMODULE)handle) != 0) {
  3063. result = 0;
  3064. } else {
  3065. result = -1;
  3066. }
  3067. return result;
  3068. }
  3069. #if defined(__MINGW32__)
  3070. /* Enable unused function warning again */
  3071. #pragma GCC diagnostic pop
  3072. #endif
  3073. #endif
  3074. #if !defined(NO_CGI)
  3075. #define SIGKILL (0)
  3076. static int
  3077. kill(pid_t pid, int sig_num)
  3078. {
  3079. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3080. (void)CloseHandle((HANDLE)pid);
  3081. return 0;
  3082. }
  3083. static void
  3084. trim_trailing_whitespaces(char *s)
  3085. {
  3086. char *e = s + strlen(s) - 1;
  3087. while (e > s && isspace(*(unsigned char *)e)) {
  3088. *e-- = '\0';
  3089. }
  3090. }
  3091. static pid_t
  3092. spawn_process(struct mg_connection *conn,
  3093. const char *prog,
  3094. char *envblk,
  3095. char *envp[],
  3096. int fdin[2],
  3097. int fdout[2],
  3098. int fderr[2],
  3099. const char *dir)
  3100. {
  3101. HANDLE me;
  3102. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3103. cmdline[PATH_MAX], buf[PATH_MAX];
  3104. int truncated;
  3105. struct file file = STRUCT_FILE_INITIALIZER;
  3106. STARTUPINFOA si;
  3107. PROCESS_INFORMATION pi = {0};
  3108. (void)envp;
  3109. memset(&si, 0, sizeof(si));
  3110. si.cb = sizeof(si);
  3111. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3112. si.wShowWindow = SW_HIDE;
  3113. me = GetCurrentProcess();
  3114. DuplicateHandle(me,
  3115. (HANDLE)_get_osfhandle(fdin[0]),
  3116. me,
  3117. &si.hStdInput,
  3118. 0,
  3119. TRUE,
  3120. DUPLICATE_SAME_ACCESS);
  3121. DuplicateHandle(me,
  3122. (HANDLE)_get_osfhandle(fdout[1]),
  3123. me,
  3124. &si.hStdOutput,
  3125. 0,
  3126. TRUE,
  3127. DUPLICATE_SAME_ACCESS);
  3128. DuplicateHandle(me,
  3129. (HANDLE)_get_osfhandle(fderr[1]),
  3130. me,
  3131. &si.hStdError,
  3132. 0,
  3133. TRUE,
  3134. DUPLICATE_SAME_ACCESS);
  3135. /* Mark handles that should not be inherited. See
  3136. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3137. */
  3138. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3139. HANDLE_FLAG_INHERIT,
  3140. 0);
  3141. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3142. HANDLE_FLAG_INHERIT,
  3143. 0);
  3144. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3145. HANDLE_FLAG_INHERIT,
  3146. 0);
  3147. /* If CGI file is a script, try to read the interpreter line */
  3148. interp = conn->ctx->config[CGI_INTERPRETER];
  3149. if (interp == NULL) {
  3150. buf[0] = buf[1] = '\0';
  3151. /* Read the first line of the script into the buffer */
  3152. mg_snprintf(
  3153. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3154. if (truncated) {
  3155. pi.hProcess = (pid_t)-1;
  3156. goto spawn_cleanup;
  3157. }
  3158. if (mg_fopen(conn, cmdline, "r", &file)) {
  3159. p = (char *)file.membuf;
  3160. mg_fgets(buf, sizeof(buf), &file, &p);
  3161. mg_fclose(&file);
  3162. buf[sizeof(buf) - 1] = '\0';
  3163. }
  3164. if (buf[0] == '#' && buf[1] == '!') {
  3165. trim_trailing_whitespaces(buf + 2);
  3166. } else {
  3167. buf[2] = '\0';
  3168. }
  3169. interp = buf + 2;
  3170. }
  3171. if (interp[0] != '\0') {
  3172. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3173. interp = full_interp;
  3174. }
  3175. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3176. if (interp[0] != '\0') {
  3177. mg_snprintf(conn,
  3178. &truncated,
  3179. cmdline,
  3180. sizeof(cmdline),
  3181. "\"%s\" \"%s\\%s\"",
  3182. interp,
  3183. full_dir,
  3184. prog);
  3185. } else {
  3186. mg_snprintf(conn,
  3187. &truncated,
  3188. cmdline,
  3189. sizeof(cmdline),
  3190. "\"%s\\%s\"",
  3191. full_dir,
  3192. prog);
  3193. }
  3194. if (truncated) {
  3195. pi.hProcess = (pid_t)-1;
  3196. goto spawn_cleanup;
  3197. }
  3198. DEBUG_TRACE("Running [%s]", cmdline);
  3199. if (CreateProcessA(NULL,
  3200. cmdline,
  3201. NULL,
  3202. NULL,
  3203. TRUE,
  3204. CREATE_NEW_PROCESS_GROUP,
  3205. envblk,
  3206. NULL,
  3207. &si,
  3208. &pi) == 0) {
  3209. mg_cry(
  3210. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3211. pi.hProcess = (pid_t)-1;
  3212. /* goto spawn_cleanup; */
  3213. }
  3214. spawn_cleanup:
  3215. (void)CloseHandle(si.hStdOutput);
  3216. (void)CloseHandle(si.hStdError);
  3217. (void)CloseHandle(si.hStdInput);
  3218. if (pi.hThread != NULL) {
  3219. (void)CloseHandle(pi.hThread);
  3220. }
  3221. return (pid_t)pi.hProcess;
  3222. }
  3223. #endif /* !NO_CGI */
  3224. static int
  3225. set_non_blocking_mode(SOCKET sock)
  3226. {
  3227. unsigned long on = 1;
  3228. return ioctlsocket(sock, (long)FIONBIO, &on);
  3229. }
  3230. #else
  3231. static int
  3232. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3233. {
  3234. struct stat st;
  3235. if (!filep) {
  3236. return 0;
  3237. }
  3238. memset(filep, 0, sizeof(*filep));
  3239. if (conn && is_file_in_memory(conn, path, filep)) {
  3240. return 1;
  3241. }
  3242. if (0 == stat(path, &st)) {
  3243. filep->size = (uint64_t)(st.st_size);
  3244. filep->last_modified = st.st_mtime;
  3245. filep->is_directory = S_ISDIR(st.st_mode);
  3246. return 1;
  3247. }
  3248. return 0;
  3249. }
  3250. static void
  3251. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3252. {
  3253. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3254. if (conn) {
  3255. mg_cry(conn,
  3256. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3257. __func__,
  3258. strerror(ERRNO));
  3259. }
  3260. }
  3261. }
  3262. int
  3263. mg_start_thread(mg_thread_func_t func, void *param)
  3264. {
  3265. pthread_t thread_id;
  3266. pthread_attr_t attr;
  3267. int result;
  3268. (void)pthread_attr_init(&attr);
  3269. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3270. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3271. /* Compile-time option to control stack size,
  3272. * e.g. -DUSE_STACK_SIZE=16384 */
  3273. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3274. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3275. result = pthread_create(&thread_id, &attr, func, param);
  3276. pthread_attr_destroy(&attr);
  3277. return result;
  3278. }
  3279. /* Start a thread storing the thread context. */
  3280. static int
  3281. mg_start_thread_with_id(mg_thread_func_t func,
  3282. void *param,
  3283. pthread_t *threadidptr)
  3284. {
  3285. pthread_t thread_id;
  3286. pthread_attr_t attr;
  3287. int result;
  3288. (void)pthread_attr_init(&attr);
  3289. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3290. /* Compile-time option to control stack size,
  3291. * e.g. -DUSE_STACK_SIZE=16384 */
  3292. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3293. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3294. result = pthread_create(&thread_id, &attr, func, param);
  3295. pthread_attr_destroy(&attr);
  3296. if ((result == 0) && (threadidptr != NULL)) {
  3297. *threadidptr = thread_id;
  3298. }
  3299. return result;
  3300. }
  3301. /* Wait for a thread to finish. */
  3302. static int
  3303. mg_join_thread(pthread_t threadid)
  3304. {
  3305. int result;
  3306. result = pthread_join(threadid, NULL);
  3307. return result;
  3308. }
  3309. #ifndef NO_CGI
  3310. static pid_t
  3311. spawn_process(struct mg_connection *conn,
  3312. const char *prog,
  3313. char *envblk,
  3314. char *envp[],
  3315. int fdin[2],
  3316. int fdout[2],
  3317. int fderr[2],
  3318. const char *dir)
  3319. {
  3320. pid_t pid;
  3321. const char *interp;
  3322. (void)envblk;
  3323. if (conn == NULL) {
  3324. return 0;
  3325. }
  3326. if ((pid = fork()) == -1) {
  3327. /* Parent */
  3328. send_http_error(conn,
  3329. 500,
  3330. "Error: Creating CGI process\nfork(): %s",
  3331. strerror(ERRNO));
  3332. } else if (pid == 0) {
  3333. /* Child */
  3334. if (chdir(dir) != 0) {
  3335. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3336. } else if (dup2(fdin[0], 0) == -1) {
  3337. mg_cry(conn,
  3338. "%s: dup2(%d, 0): %s",
  3339. __func__,
  3340. fdin[0],
  3341. strerror(ERRNO));
  3342. } else if (dup2(fdout[1], 1) == -1) {
  3343. mg_cry(conn,
  3344. "%s: dup2(%d, 1): %s",
  3345. __func__,
  3346. fdout[1],
  3347. strerror(ERRNO));
  3348. } else if (dup2(fderr[1], 2) == -1) {
  3349. mg_cry(conn,
  3350. "%s: dup2(%d, 2): %s",
  3351. __func__,
  3352. fderr[1],
  3353. strerror(ERRNO));
  3354. } else {
  3355. /* Keep stderr and stdout in two different pipes.
  3356. * Stdout will be sent back to the client,
  3357. * stderr should go into a server error log. */
  3358. (void)close(fdin[0]);
  3359. (void)close(fdout[1]);
  3360. (void)close(fderr[1]);
  3361. /* Close write end fdin and read end fdout and fderr */
  3362. (void)close(fdin[1]);
  3363. (void)close(fdout[0]);
  3364. (void)close(fderr[0]);
  3365. /* After exec, all signal handlers are restored to their default
  3366. * values, with one exception of SIGCHLD. According to
  3367. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3368. * leave unchanged after exec if it was set to be ignored. Restore
  3369. * it to default action. */
  3370. signal(SIGCHLD, SIG_DFL);
  3371. interp = conn->ctx->config[CGI_INTERPRETER];
  3372. if (interp == NULL) {
  3373. (void)execle(prog, prog, NULL, envp);
  3374. mg_cry(conn,
  3375. "%s: execle(%s): %s",
  3376. __func__,
  3377. prog,
  3378. strerror(ERRNO));
  3379. } else {
  3380. (void)execle(interp, interp, prog, NULL, envp);
  3381. mg_cry(conn,
  3382. "%s: execle(%s %s): %s",
  3383. __func__,
  3384. interp,
  3385. prog,
  3386. strerror(ERRNO));
  3387. }
  3388. }
  3389. exit(EXIT_FAILURE);
  3390. }
  3391. return pid;
  3392. }
  3393. #endif /* !NO_CGI */
  3394. static int
  3395. set_non_blocking_mode(SOCKET sock)
  3396. {
  3397. int flags;
  3398. flags = fcntl(sock, F_GETFL, 0);
  3399. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3400. return 0;
  3401. }
  3402. #endif /* _WIN32 */
  3403. /* End of initial operating system specific define block. */
  3404. /* Get a random number (independent of C rand function) */
  3405. static uint64_t
  3406. get_random(void)
  3407. {
  3408. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3409. static uint64_t lcg = 0; /* Linear congruential generator */
  3410. struct timespec now;
  3411. memset(&now, 0, sizeof(now));
  3412. clock_gettime(CLOCK_MONOTONIC, &now);
  3413. if (lfsr == 0) {
  3414. /* lfsr will be only 0 if has not been initialized,
  3415. * so this code is called only once. */
  3416. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3417. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3418. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3419. + (uint64_t)(ptrdiff_t)&now;
  3420. } else {
  3421. /* Get the next step of both random number generators. */
  3422. lfsr = (lfsr >> 1)
  3423. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3424. << 63);
  3425. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3426. }
  3427. /* Combining two pseudo-random number generators and a high resolution part
  3428. * of the current server time will make it hard (impossible?) to guess the
  3429. * next number. */
  3430. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3431. }
  3432. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3433. * descriptor. Return number of bytes written. */
  3434. static int
  3435. push(struct mg_context *ctx,
  3436. FILE *fp,
  3437. SOCKET sock,
  3438. SSL *ssl,
  3439. const char *buf,
  3440. int len,
  3441. double timeout)
  3442. {
  3443. struct timespec start, now;
  3444. int n, err;
  3445. #ifdef _WIN32
  3446. typedef int len_t;
  3447. #else
  3448. typedef size_t len_t;
  3449. #endif
  3450. if (timeout > 0) {
  3451. memset(&start, 0, sizeof(start));
  3452. memset(&now, 0, sizeof(now));
  3453. clock_gettime(CLOCK_MONOTONIC, &start);
  3454. }
  3455. if (ctx == NULL) {
  3456. return -1;
  3457. }
  3458. #ifdef NO_SSL
  3459. if (ssl) {
  3460. return -1;
  3461. }
  3462. #endif
  3463. do {
  3464. #ifndef NO_SSL
  3465. if (ssl != NULL) {
  3466. n = SSL_write(ssl, buf, len);
  3467. if (n <= 0) {
  3468. err = SSL_get_error(ssl, n);
  3469. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3470. err = ERRNO;
  3471. } else if ((err == SSL_ERROR_WANT_READ)
  3472. || (err == SSL_ERROR_WANT_WRITE)) {
  3473. n = 0;
  3474. } else {
  3475. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3476. return -1;
  3477. }
  3478. } else {
  3479. err = 0;
  3480. }
  3481. } else
  3482. #endif
  3483. if (fp != NULL) {
  3484. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3485. if (ferror(fp)) {
  3486. n = -1;
  3487. err = ERRNO;
  3488. } else {
  3489. err = 0;
  3490. }
  3491. } else {
  3492. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3493. err = (n < 0) ? ERRNO : 0;
  3494. if (n == 0) {
  3495. /* shutdown of the socket at client side */
  3496. return -1;
  3497. }
  3498. }
  3499. if (ctx->stop_flag) {
  3500. return -1;
  3501. }
  3502. if ((n > 0) || (n == 0 && len == 0)) {
  3503. /* some data has been read, or no data was requested */
  3504. return n;
  3505. }
  3506. if (n < 0) {
  3507. /* socket error - check errno */
  3508. DEBUG_TRACE("send() failed, error %d", err);
  3509. /* TODO: error handling depending on the error code.
  3510. * These codes are different between Windows and Linux.
  3511. */
  3512. return -1;
  3513. }
  3514. /* This code is not reached in the moment.
  3515. * ==> Fix the TODOs above first. */
  3516. if (timeout > 0) {
  3517. clock_gettime(CLOCK_MONOTONIC, &now);
  3518. }
  3519. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3520. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3521. used */
  3522. return -1;
  3523. }
  3524. static int64_t
  3525. push_all(struct mg_context *ctx,
  3526. FILE *fp,
  3527. SOCKET sock,
  3528. SSL *ssl,
  3529. const char *buf,
  3530. int64_t len)
  3531. {
  3532. double timeout = -1.0;
  3533. int64_t n, nwritten = 0;
  3534. if (ctx == NULL) {
  3535. return -1;
  3536. }
  3537. if (ctx->config[REQUEST_TIMEOUT]) {
  3538. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3539. }
  3540. while (len > 0 && ctx->stop_flag == 0) {
  3541. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3542. if (n < 0) {
  3543. if (nwritten == 0) {
  3544. nwritten = n; /* Propagate the error */
  3545. }
  3546. break;
  3547. } else if (n == 0) {
  3548. break; /* No more data to write */
  3549. } else {
  3550. nwritten += n;
  3551. len -= n;
  3552. }
  3553. }
  3554. return nwritten;
  3555. }
  3556. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3557. * Return negative value on error, or number of bytes read on success. */
  3558. static int
  3559. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3560. {
  3561. int nread, err;
  3562. struct timespec start, now;
  3563. #ifdef _WIN32
  3564. typedef int len_t;
  3565. #else
  3566. typedef size_t len_t;
  3567. #endif
  3568. if (timeout > 0) {
  3569. memset(&start, 0, sizeof(start));
  3570. memset(&now, 0, sizeof(now));
  3571. clock_gettime(CLOCK_MONOTONIC, &start);
  3572. }
  3573. do {
  3574. if (fp != NULL) {
  3575. #if !defined(_WIN32_WCE)
  3576. /* Use read() instead of fread(), because if we're reading from the
  3577. * CGI pipe, fread() may block until IO buffer is filled up. We
  3578. * cannot afford to block and must pass all read bytes immediately
  3579. * to the client. */
  3580. nread = (int)read(fileno(fp), buf, (size_t)len);
  3581. #else
  3582. /* WinCE does not support CGI pipes */
  3583. nread = (int)fread(buf, 1, (size_t)len, fp);
  3584. #endif
  3585. err = (nread < 0) ? ERRNO : 0;
  3586. #ifndef NO_SSL
  3587. } else if (conn->ssl != NULL) {
  3588. nread = SSL_read(conn->ssl, buf, len);
  3589. if (nread <= 0) {
  3590. err = SSL_get_error(conn->ssl, nread);
  3591. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3592. err = ERRNO;
  3593. } else if ((err == SSL_ERROR_WANT_READ)
  3594. || (err == SSL_ERROR_WANT_WRITE)) {
  3595. nread = 0;
  3596. } else {
  3597. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3598. return -1;
  3599. }
  3600. } else {
  3601. err = 0;
  3602. }
  3603. #endif
  3604. } else {
  3605. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3606. err = (nread < 0) ? ERRNO : 0;
  3607. if (nread == 0) {
  3608. /* shutdown of the socket at client side */
  3609. return -1;
  3610. }
  3611. }
  3612. if (conn->ctx->stop_flag) {
  3613. return -1;
  3614. }
  3615. if ((nread > 0) || (nread == 0 && len == 0)) {
  3616. /* some data has been read, or no data was requested */
  3617. return nread;
  3618. }
  3619. if (nread < 0) {
  3620. /* socket error - check errno */
  3621. #ifdef _WIN32
  3622. if (err == WSAEWOULDBLOCK) {
  3623. /* standard case if called from close_socket_gracefully */
  3624. return -1;
  3625. } else if (err == WSAETIMEDOUT) {
  3626. /* timeout is handled by the while loop */
  3627. } else {
  3628. DEBUG_TRACE("recv() failed, error %d", err);
  3629. return -1;
  3630. }
  3631. #else
  3632. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3633. * if the timeout is reached and if the socket was set to non-
  3634. * blocking in close_socket_gracefully, so we can not distinguish
  3635. * here. We have to wait for the timeout in both cases for now.
  3636. */
  3637. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3638. /* EAGAIN/EWOULDBLOCK:
  3639. * standard case if called from close_socket_gracefully
  3640. * => should return -1 */
  3641. /* or timeout occured
  3642. * => the code must stay in the while loop */
  3643. /* EINTR can be generated on a socket with a timeout set even
  3644. * when SA_RESTART is effective for all relevant signals
  3645. * (see signal(7)).
  3646. * => stay in the while loop */
  3647. } else {
  3648. DEBUG_TRACE("recv() failed, error %d", err);
  3649. return -1;
  3650. }
  3651. #endif
  3652. }
  3653. if (timeout > 0) {
  3654. clock_gettime(CLOCK_MONOTONIC, &now);
  3655. }
  3656. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3657. /* Timeout occured, but no data available. */
  3658. return -1;
  3659. }
  3660. static int
  3661. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3662. {
  3663. int n, nread = 0;
  3664. double timeout = -1.0;
  3665. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3666. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3667. }
  3668. while (len > 0 && conn->ctx->stop_flag == 0) {
  3669. n = pull(fp, conn, buf + nread, len, timeout);
  3670. if (n < 0) {
  3671. if (nread == 0) {
  3672. nread = n; /* Propagate the error */
  3673. }
  3674. break;
  3675. } else if (n == 0) {
  3676. break; /* No more data to read */
  3677. } else {
  3678. conn->consumed_content += n;
  3679. nread += n;
  3680. len -= n;
  3681. }
  3682. }
  3683. return nread;
  3684. }
  3685. static void
  3686. discard_unread_request_data(struct mg_connection *conn)
  3687. {
  3688. char buf[MG_BUF_LEN];
  3689. size_t to_read;
  3690. int nread;
  3691. if (conn == NULL) {
  3692. return;
  3693. }
  3694. to_read = sizeof(buf);
  3695. if (conn->is_chunked) {
  3696. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3697. * completely */
  3698. while (conn->is_chunked == 1) {
  3699. nread = mg_read(conn, buf, to_read);
  3700. if (nread <= 0) {
  3701. break;
  3702. }
  3703. }
  3704. } else {
  3705. /* Not chunked: content length is known */
  3706. while (conn->consumed_content < conn->content_len) {
  3707. if (to_read
  3708. > (size_t)(conn->content_len - conn->consumed_content)) {
  3709. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3710. }
  3711. nread = mg_read(conn, buf, to_read);
  3712. if (nread <= 0) {
  3713. break;
  3714. }
  3715. }
  3716. }
  3717. }
  3718. static int
  3719. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3720. {
  3721. int64_t n, buffered_len, nread;
  3722. int64_t len64 =
  3723. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3724. * int, we may not read more
  3725. * bytes */
  3726. const char *body;
  3727. if (conn == NULL) {
  3728. return 0;
  3729. }
  3730. /* If Content-Length is not set for a PUT or POST request, read until
  3731. * socket is closed */
  3732. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3733. conn->content_len = INT64_MAX;
  3734. conn->must_close = 1;
  3735. }
  3736. nread = 0;
  3737. if (conn->consumed_content < conn->content_len) {
  3738. /* Adjust number of bytes to read. */
  3739. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3740. if (left_to_read < len64) {
  3741. /* Do not read more than the total content length of the request.
  3742. */
  3743. len64 = left_to_read;
  3744. }
  3745. /* Return buffered data */
  3746. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3747. - conn->consumed_content;
  3748. if (buffered_len > 0) {
  3749. if (len64 < buffered_len) {
  3750. buffered_len = len64;
  3751. }
  3752. body = conn->buf + conn->request_len + conn->consumed_content;
  3753. memcpy(buf, body, (size_t)buffered_len);
  3754. len64 -= buffered_len;
  3755. conn->consumed_content += buffered_len;
  3756. nread += buffered_len;
  3757. buf = (char *)buf + buffered_len;
  3758. }
  3759. /* We have returned all buffered data. Read new data from the remote
  3760. * socket.
  3761. */
  3762. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3763. nread += n;
  3764. } else {
  3765. nread = ((nread > 0) ? nread : n);
  3766. }
  3767. }
  3768. return (int)nread;
  3769. }
  3770. static char
  3771. mg_getc(struct mg_connection *conn)
  3772. {
  3773. char c;
  3774. if (conn == NULL) {
  3775. return 0;
  3776. }
  3777. conn->content_len++;
  3778. if (mg_read_inner(conn, &c, 1) <= 0) {
  3779. return (char)0;
  3780. }
  3781. return c;
  3782. }
  3783. int
  3784. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3785. {
  3786. if (len > INT_MAX) {
  3787. len = INT_MAX;
  3788. }
  3789. if (conn == NULL) {
  3790. return 0;
  3791. }
  3792. if (conn->is_chunked) {
  3793. size_t all_read = 0;
  3794. while (len > 0) {
  3795. if (conn->is_chunked == 2) {
  3796. /* No more data left to read */
  3797. return 0;
  3798. }
  3799. if (conn->chunk_remainder) {
  3800. /* copy from the remainder of the last received chunk */
  3801. long read_ret;
  3802. size_t read_now =
  3803. ((conn->chunk_remainder > len) ? (len)
  3804. : (conn->chunk_remainder));
  3805. conn->content_len += (int)read_now;
  3806. read_ret =
  3807. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3808. all_read += (size_t)read_ret;
  3809. conn->chunk_remainder -= read_now;
  3810. len -= read_now;
  3811. if (conn->chunk_remainder == 0) {
  3812. /* the rest of the data in the current chunk has been read
  3813. */
  3814. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3815. /* Protocol violation */
  3816. return -1;
  3817. }
  3818. }
  3819. } else {
  3820. /* fetch a new chunk */
  3821. int i = 0;
  3822. char lenbuf[64];
  3823. char *end = 0;
  3824. unsigned long chunkSize = 0;
  3825. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3826. lenbuf[i] = mg_getc(conn);
  3827. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3828. continue;
  3829. }
  3830. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3831. lenbuf[i + 1] = 0;
  3832. chunkSize = strtoul(lenbuf, &end, 16);
  3833. if (chunkSize == 0) {
  3834. /* regular end of content */
  3835. conn->is_chunked = 2;
  3836. }
  3837. break;
  3838. }
  3839. if (!isalnum(lenbuf[i])) {
  3840. /* illegal character for chunk length */
  3841. return -1;
  3842. }
  3843. }
  3844. if ((end == NULL) || (*end != '\r')) {
  3845. /* chunksize not set correctly */
  3846. return -1;
  3847. }
  3848. if (chunkSize == 0) {
  3849. break;
  3850. }
  3851. conn->chunk_remainder = chunkSize;
  3852. }
  3853. }
  3854. return (int)all_read;
  3855. }
  3856. return mg_read_inner(conn, buf, len);
  3857. }
  3858. int
  3859. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3860. {
  3861. time_t now;
  3862. int64_t n, total, allowed;
  3863. if (conn == NULL) {
  3864. return 0;
  3865. }
  3866. if (conn->throttle > 0) {
  3867. if ((now = time(NULL)) != conn->last_throttle_time) {
  3868. conn->last_throttle_time = now;
  3869. conn->last_throttle_bytes = 0;
  3870. }
  3871. allowed = conn->throttle - conn->last_throttle_bytes;
  3872. if (allowed > (int64_t)len) {
  3873. allowed = (int64_t)len;
  3874. }
  3875. if ((total = push_all(conn->ctx,
  3876. NULL,
  3877. conn->client.sock,
  3878. conn->ssl,
  3879. (const char *)buf,
  3880. (int64_t)allowed)) == allowed) {
  3881. buf = (const char *)buf + total;
  3882. conn->last_throttle_bytes += total;
  3883. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3884. allowed = (conn->throttle > ((int64_t)len - total))
  3885. ? (int64_t)len - total
  3886. : conn->throttle;
  3887. if ((n = push_all(conn->ctx,
  3888. NULL,
  3889. conn->client.sock,
  3890. conn->ssl,
  3891. (const char *)buf,
  3892. (int64_t)allowed)) != allowed) {
  3893. break;
  3894. }
  3895. sleep(1);
  3896. conn->last_throttle_bytes = allowed;
  3897. conn->last_throttle_time = time(NULL);
  3898. buf = (const char *)buf + n;
  3899. total += n;
  3900. }
  3901. }
  3902. } else {
  3903. total = push_all(conn->ctx,
  3904. NULL,
  3905. conn->client.sock,
  3906. conn->ssl,
  3907. (const char *)buf,
  3908. (int64_t)len);
  3909. }
  3910. return (int)total;
  3911. }
  3912. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3913. static int
  3914. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3915. {
  3916. va_list ap_copy;
  3917. size_t size = MG_BUF_LEN / 4;
  3918. int len = -1;
  3919. *buf = NULL;
  3920. while (len < 0) {
  3921. if (*buf) {
  3922. mg_free(*buf);
  3923. }
  3924. size *= 4;
  3925. *buf = (char *)mg_malloc(size);
  3926. if (!*buf) {
  3927. break;
  3928. }
  3929. va_copy(ap_copy, ap);
  3930. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3931. va_end(ap_copy);
  3932. (*buf)[size - 1] = 0;
  3933. }
  3934. return len;
  3935. }
  3936. /* Print message to buffer. If buffer is large enough to hold the message,
  3937. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3938. * and return allocated buffer. */
  3939. static int
  3940. alloc_vprintf(char **out_buf,
  3941. char *prealloc_buf,
  3942. size_t prealloc_size,
  3943. const char *fmt,
  3944. va_list ap)
  3945. {
  3946. va_list ap_copy;
  3947. int len;
  3948. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3949. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3950. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3951. * Therefore, we make two passes: on first pass, get required message
  3952. * length.
  3953. * On second pass, actually print the message. */
  3954. va_copy(ap_copy, ap);
  3955. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3956. va_end(ap_copy);
  3957. if (len < 0) {
  3958. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3959. * Switch to alternative code path that uses incremental allocations.
  3960. */
  3961. va_copy(ap_copy, ap);
  3962. len = alloc_vprintf2(out_buf, fmt, ap);
  3963. va_end(ap_copy);
  3964. } else if ((size_t)(len) >= prealloc_size) {
  3965. /* The pre-allocated buffer not large enough. */
  3966. /* Allocate a new buffer. */
  3967. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3968. if (!*out_buf) {
  3969. /* Allocation failed. Return -1 as "out of memory" error. */
  3970. return -1;
  3971. }
  3972. /* Buffer allocation successful. Store the string there. */
  3973. va_copy(ap_copy, ap);
  3974. IGNORE_UNUSED_RESULT(
  3975. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3976. va_end(ap_copy);
  3977. } else {
  3978. /* The pre-allocated buffer is large enough.
  3979. * Use it to store the string and return the address. */
  3980. va_copy(ap_copy, ap);
  3981. IGNORE_UNUSED_RESULT(
  3982. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3983. va_end(ap_copy);
  3984. *out_buf = prealloc_buf;
  3985. }
  3986. return len;
  3987. }
  3988. static int
  3989. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3990. {
  3991. char mem[MG_BUF_LEN];
  3992. char *buf = NULL;
  3993. int len;
  3994. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3995. len = mg_write(conn, buf, (size_t)len);
  3996. }
  3997. if (buf != mem && buf != NULL) {
  3998. mg_free(buf);
  3999. }
  4000. return len;
  4001. }
  4002. int
  4003. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4004. {
  4005. va_list ap;
  4006. int result;
  4007. va_start(ap, fmt);
  4008. result = mg_vprintf(conn, fmt, ap);
  4009. va_end(ap);
  4010. return result;
  4011. }
  4012. int
  4013. mg_url_decode(const char *src,
  4014. int src_len,
  4015. char *dst,
  4016. int dst_len,
  4017. int is_form_url_encoded)
  4018. {
  4019. int i, j, a, b;
  4020. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4021. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4022. if (i < src_len - 2 && src[i] == '%'
  4023. && isxdigit(*(const unsigned char *)(src + i + 1))
  4024. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4025. a = tolower(*(const unsigned char *)(src + i + 1));
  4026. b = tolower(*(const unsigned char *)(src + i + 2));
  4027. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4028. i += 2;
  4029. } else if (is_form_url_encoded && src[i] == '+') {
  4030. dst[j] = ' ';
  4031. } else {
  4032. dst[j] = src[i];
  4033. }
  4034. }
  4035. dst[j] = '\0'; /* Null-terminate the destination */
  4036. return (i >= src_len) ? j : -1;
  4037. }
  4038. int
  4039. mg_get_var(const char *data,
  4040. size_t data_len,
  4041. const char *name,
  4042. char *dst,
  4043. size_t dst_len)
  4044. {
  4045. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4046. }
  4047. int
  4048. mg_get_var2(const char *data,
  4049. size_t data_len,
  4050. const char *name,
  4051. char *dst,
  4052. size_t dst_len,
  4053. size_t occurrence)
  4054. {
  4055. const char *p, *e, *s;
  4056. size_t name_len;
  4057. int len;
  4058. if (dst == NULL || dst_len == 0) {
  4059. len = -2;
  4060. } else if (data == NULL || name == NULL || data_len == 0) {
  4061. len = -1;
  4062. dst[0] = '\0';
  4063. } else {
  4064. name_len = strlen(name);
  4065. e = data + data_len;
  4066. len = -1;
  4067. dst[0] = '\0';
  4068. /* data is "var1=val1&var2=val2...". Find variable first */
  4069. for (p = data; p + name_len < e; p++) {
  4070. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4071. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4072. /* Point p to variable value */
  4073. p += name_len + 1;
  4074. /* Point s to the end of the value */
  4075. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4076. if (s == NULL) {
  4077. s = e;
  4078. }
  4079. /* assert(s >= p); */
  4080. if (s < p) {
  4081. return -3;
  4082. }
  4083. /* Decode variable into destination buffer */
  4084. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4085. /* Redirect error code from -1 to -2 (destination buffer too
  4086. * small). */
  4087. if (len == -1) {
  4088. len = -2;
  4089. }
  4090. break;
  4091. }
  4092. }
  4093. }
  4094. return len;
  4095. }
  4096. int
  4097. mg_get_cookie(const char *cookie_header,
  4098. const char *var_name,
  4099. char *dst,
  4100. size_t dst_size)
  4101. {
  4102. const char *s, *p, *end;
  4103. int name_len, len = -1;
  4104. if (dst == NULL || dst_size == 0) {
  4105. len = -2;
  4106. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  4107. len = -1;
  4108. dst[0] = '\0';
  4109. } else {
  4110. name_len = (int)strlen(var_name);
  4111. end = s + strlen(s);
  4112. dst[0] = '\0';
  4113. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4114. if (s[name_len] == '=') {
  4115. s += name_len + 1;
  4116. if ((p = strchr(s, ' ')) == NULL) {
  4117. p = end;
  4118. }
  4119. if (p[-1] == ';') {
  4120. p--;
  4121. }
  4122. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4123. s++;
  4124. p--;
  4125. }
  4126. if ((size_t)(p - s) < dst_size) {
  4127. len = (int)(p - s);
  4128. mg_strlcpy(dst, s, (size_t)len + 1);
  4129. } else {
  4130. len = -3;
  4131. }
  4132. break;
  4133. }
  4134. }
  4135. }
  4136. return len;
  4137. }
  4138. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4139. static void
  4140. base64_encode(const unsigned char *src, int src_len, char *dst)
  4141. {
  4142. static const char *b64 =
  4143. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4144. int i, j, a, b, c;
  4145. for (i = j = 0; i < src_len; i += 3) {
  4146. a = src[i];
  4147. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4148. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4149. dst[j++] = b64[a >> 2];
  4150. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4151. if (i + 1 < src_len) {
  4152. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4153. }
  4154. if (i + 2 < src_len) {
  4155. dst[j++] = b64[c & 63];
  4156. }
  4157. }
  4158. while (j % 4 != 0) {
  4159. dst[j++] = '=';
  4160. }
  4161. dst[j++] = '\0';
  4162. }
  4163. #endif
  4164. #if defined(USE_LUA)
  4165. static unsigned char
  4166. b64reverse(char letter)
  4167. {
  4168. if (letter >= 'A' && letter <= 'Z') {
  4169. return letter - 'A';
  4170. }
  4171. if (letter >= 'a' && letter <= 'z') {
  4172. return letter - 'a' + 26;
  4173. }
  4174. if (letter >= '0' && letter <= '9') {
  4175. return letter - '0' + 52;
  4176. }
  4177. if (letter == '+') {
  4178. return 62;
  4179. }
  4180. if (letter == '/') {
  4181. return 63;
  4182. }
  4183. if (letter == '=') {
  4184. return 255; /* normal end */
  4185. }
  4186. return 254; /* error */
  4187. }
  4188. static int
  4189. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4190. {
  4191. int i;
  4192. unsigned char a, b, c, d;
  4193. *dst_len = 0;
  4194. for (i = 0; i < src_len; i += 4) {
  4195. a = b64reverse(src[i]);
  4196. if (a >= 254) {
  4197. return i;
  4198. }
  4199. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4200. if (b >= 254) {
  4201. return i + 1;
  4202. }
  4203. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4204. if (c == 254) {
  4205. return i + 2;
  4206. }
  4207. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4208. if (d == 254) {
  4209. return i + 3;
  4210. }
  4211. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4212. if (c != 255) {
  4213. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4214. if (d != 255) {
  4215. dst[(*dst_len)++] = (c << 6) + d;
  4216. }
  4217. }
  4218. }
  4219. return -1;
  4220. }
  4221. #endif
  4222. static int
  4223. is_put_or_delete_method(const struct mg_connection *conn)
  4224. {
  4225. if (conn) {
  4226. const char *s = conn->request_info.request_method;
  4227. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4228. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4229. }
  4230. return 0;
  4231. }
  4232. static void
  4233. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4234. char *filename, /* out: filename */
  4235. size_t filename_buf_len, /* in: size of filename buffer */
  4236. struct file *filep, /* out: file structure */
  4237. int *is_found, /* out: file is found (directly) */
  4238. int *is_script_resource, /* out: handled by a script? */
  4239. int *is_websocket_request, /* out: websocket connetion? */
  4240. int *is_put_or_delete_request /* out: put/delete a file? */
  4241. )
  4242. {
  4243. /* TODO (high): Restructure this function */
  4244. #if !defined(NO_FILES)
  4245. const char *uri = conn->request_info.local_uri;
  4246. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4247. const char *rewrite;
  4248. struct vec a, b;
  4249. int match_len;
  4250. char gz_path[PATH_MAX];
  4251. char const *accept_encoding;
  4252. int truncated;
  4253. #if !defined(NO_CGI) || defined(USE_LUA)
  4254. char *p;
  4255. #endif
  4256. #else
  4257. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4258. #endif
  4259. memset(filep, 0, sizeof(*filep));
  4260. *filename = 0;
  4261. *is_found = 0;
  4262. *is_script_resource = 0;
  4263. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4264. #if defined(USE_WEBSOCKET)
  4265. *is_websocket_request = is_websocket_protocol(conn);
  4266. #if !defined(NO_FILES)
  4267. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4268. root = conn->ctx->config[WEBSOCKET_ROOT];
  4269. }
  4270. #endif /* !NO_FILES */
  4271. #else /* USE_WEBSOCKET */
  4272. *is_websocket_request = 0;
  4273. #endif /* USE_WEBSOCKET */
  4274. #if !defined(NO_FILES)
  4275. /* Note that root == NULL is a regular use case here. This occurs,
  4276. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4277. * config is not required. */
  4278. if (root == NULL) {
  4279. /* all file related outputs have already been set to 0, just return
  4280. */
  4281. return;
  4282. }
  4283. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4284. * of the path one byte on the right.
  4285. * If document_root is NULL, leave the file empty. */
  4286. mg_snprintf(
  4287. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4288. if (truncated) {
  4289. goto interpret_cleanup;
  4290. }
  4291. rewrite = conn->ctx->config[REWRITE];
  4292. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4293. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4294. mg_snprintf(conn,
  4295. &truncated,
  4296. filename,
  4297. filename_buf_len - 1,
  4298. "%.*s%s",
  4299. (int)b.len,
  4300. b.ptr,
  4301. uri + match_len);
  4302. break;
  4303. }
  4304. }
  4305. if (truncated) {
  4306. goto interpret_cleanup;
  4307. }
  4308. /* Local file path and name, corresponding to requested URI
  4309. * is now stored in "filename" variable. */
  4310. if (mg_stat(conn, filename, filep)) {
  4311. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4312. /* File exists. Check if it is a script type. */
  4313. if (0
  4314. #if !defined(NO_CGI)
  4315. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4316. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4317. filename) > 0
  4318. #endif
  4319. #if defined(USE_LUA)
  4320. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4321. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4322. filename) > 0
  4323. #endif
  4324. #if defined(USE_DUKTAPE)
  4325. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4326. strlen(
  4327. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4328. filename) > 0
  4329. #endif
  4330. ) {
  4331. /* The request addresses a CGI script or a Lua script. The URI
  4332. * corresponds to the script itself (like /path/script.cgi),
  4333. * and there is no additional resource path
  4334. * (like /path/script.cgi/something).
  4335. * Requests that modify (replace or delete) a resource, like
  4336. * PUT and DELETE requests, should replace/delete the script
  4337. * file.
  4338. * Requests that read or write from/to a resource, like GET and
  4339. * POST requests, should call the script and return the
  4340. * generated response. */
  4341. *is_script_resource = !*is_put_or_delete_request;
  4342. }
  4343. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4344. *is_found = 1;
  4345. return;
  4346. }
  4347. /* If we can't find the actual file, look for the file
  4348. * with the same name but a .gz extension. If we find it,
  4349. * use that and set the gzipped flag in the file struct
  4350. * to indicate that the response need to have the content-
  4351. * encoding: gzip header.
  4352. * We can only do this if the browser declares support. */
  4353. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4354. if (strstr(accept_encoding, "gzip") != NULL) {
  4355. mg_snprintf(
  4356. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4357. if (truncated) {
  4358. goto interpret_cleanup;
  4359. }
  4360. if (mg_stat(conn, gz_path, filep)) {
  4361. if (filep) {
  4362. filep->gzipped = 1;
  4363. *is_found = 1;
  4364. }
  4365. /* Currently gz files can not be scripts. */
  4366. return;
  4367. }
  4368. }
  4369. }
  4370. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4371. /* Support PATH_INFO for CGI scripts. */
  4372. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4373. if (*p == '/') {
  4374. *p = '\0';
  4375. if ((0
  4376. #if !defined(NO_CGI)
  4377. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4378. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4379. filename) > 0
  4380. #endif
  4381. #if defined(USE_LUA)
  4382. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4383. strlen(
  4384. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4385. filename) > 0
  4386. #endif
  4387. #if defined(USE_DUKTAPE)
  4388. || match_prefix(
  4389. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4390. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4391. filename) > 0
  4392. #endif
  4393. ) && mg_stat(conn, filename, filep)) {
  4394. /* Shift PATH_INFO block one character right, e.g.
  4395. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4396. * conn->path_info is pointing to the local variable "path"
  4397. * declared in handle_request(), so PATH_INFO is not valid
  4398. * after handle_request returns. */
  4399. conn->path_info = p + 1;
  4400. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4401. * trailing \0 */
  4402. p[1] = '/';
  4403. *is_script_resource = 1;
  4404. break;
  4405. } else {
  4406. *p = '/';
  4407. }
  4408. }
  4409. }
  4410. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4411. #endif /* !defined(NO_FILES) */
  4412. return;
  4413. #if !defined(NO_FILES)
  4414. /* Reset all outputs */
  4415. interpret_cleanup:
  4416. memset(filep, 0, sizeof(*filep));
  4417. *filename = 0;
  4418. *is_found = 0;
  4419. *is_script_resource = 0;
  4420. *is_websocket_request = 0;
  4421. *is_put_or_delete_request = 0;
  4422. #endif /* !defined(NO_FILES) */
  4423. }
  4424. /* Check whether full request is buffered. Return:
  4425. * -1 if request is malformed
  4426. * 0 if request is not yet fully buffered
  4427. * >0 actual request length, including last \r\n\r\n */
  4428. static int
  4429. get_request_len(const char *buf, int buflen)
  4430. {
  4431. const char *s, *e;
  4432. int len = 0;
  4433. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4434. /* Control characters are not allowed but >=128 is. */
  4435. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4436. && *(const unsigned char *)s < 128) {
  4437. len = -1;
  4438. break; /* [i_a] abort scan as soon as one malformed character is
  4439. * found; */
  4440. /* don't let subsequent \r\n\r\n win us over anyhow */
  4441. } else if (s[0] == '\n' && s[1] == '\n') {
  4442. len = (int)(s - buf) + 2;
  4443. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4444. len = (int)(s - buf) + 3;
  4445. }
  4446. return len;
  4447. }
  4448. #if !defined(NO_CACHING)
  4449. /* Convert month to the month number. Return -1 on error, or month number */
  4450. static int
  4451. get_month_index(const char *s)
  4452. {
  4453. size_t i;
  4454. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4455. if (!strcmp(s, month_names[i])) {
  4456. return (int)i;
  4457. }
  4458. }
  4459. return -1;
  4460. }
  4461. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4462. static time_t
  4463. parse_date_string(const char *datetime)
  4464. {
  4465. char month_str[32] = {0};
  4466. int second, minute, hour, day, month, year;
  4467. time_t result = (time_t)0;
  4468. struct tm tm;
  4469. if ((sscanf(datetime,
  4470. "%d/%3s/%d %d:%d:%d",
  4471. &day,
  4472. month_str,
  4473. &year,
  4474. &hour,
  4475. &minute,
  4476. &second) == 6) || (sscanf(datetime,
  4477. "%d %3s %d %d:%d:%d",
  4478. &day,
  4479. month_str,
  4480. &year,
  4481. &hour,
  4482. &minute,
  4483. &second) == 6)
  4484. || (sscanf(datetime,
  4485. "%*3s, %d %3s %d %d:%d:%d",
  4486. &day,
  4487. month_str,
  4488. &year,
  4489. &hour,
  4490. &minute,
  4491. &second) == 6) || (sscanf(datetime,
  4492. "%d-%3s-%d %d:%d:%d",
  4493. &day,
  4494. month_str,
  4495. &year,
  4496. &hour,
  4497. &minute,
  4498. &second) == 6)) {
  4499. month = get_month_index(month_str);
  4500. if ((month >= 0) && (year >= 1970)) {
  4501. memset(&tm, 0, sizeof(tm));
  4502. tm.tm_year = year - 1900;
  4503. tm.tm_mon = month;
  4504. tm.tm_mday = day;
  4505. tm.tm_hour = hour;
  4506. tm.tm_min = minute;
  4507. tm.tm_sec = second;
  4508. result = timegm(&tm);
  4509. }
  4510. }
  4511. return result;
  4512. }
  4513. #endif /* !NO_CACHING */
  4514. /* Protect against directory disclosure attack by removing '..',
  4515. * excessive '/' and '\' characters */
  4516. static void
  4517. remove_double_dots_and_double_slashes(char *s)
  4518. {
  4519. char *p = s;
  4520. while ((s[0] == '.') && (s[1] == '.')) {
  4521. s++;
  4522. }
  4523. while (*s != '\0') {
  4524. *p++ = *s++;
  4525. if (s[-1] == '/' || s[-1] == '\\') {
  4526. /* Skip all following slashes, backslashes and double-dots */
  4527. while (s[0] != '\0') {
  4528. if (s[0] == '/' || s[0] == '\\') {
  4529. s++;
  4530. } else if (s[0] == '.' && s[1] == '.') {
  4531. s += 2;
  4532. } else {
  4533. break;
  4534. }
  4535. }
  4536. }
  4537. }
  4538. *p = '\0';
  4539. }
  4540. static const struct {
  4541. const char *extension;
  4542. size_t ext_len;
  4543. const char *mime_type;
  4544. } builtin_mime_types[] = {
  4545. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4546. * application types */
  4547. {".doc", 4, "application/msword"},
  4548. {".eps", 4, "application/postscript"},
  4549. {".exe", 4, "application/octet-stream"},
  4550. {".js", 3, "application/javascript"},
  4551. {".json", 5, "application/json"},
  4552. {".pdf", 4, "application/pdf"},
  4553. {".ps", 3, "application/postscript"},
  4554. {".rtf", 4, "application/rtf"},
  4555. {".xhtml", 6, "application/xhtml+xml"},
  4556. {".xsl", 4, "application/xml"},
  4557. {".xslt", 5, "application/xml"},
  4558. /* fonts */
  4559. {".ttf", 4, "application/font-sfnt"},
  4560. {".cff", 4, "application/font-sfnt"},
  4561. {".otf", 4, "application/font-sfnt"},
  4562. {".aat", 4, "application/font-sfnt"},
  4563. {".sil", 4, "application/font-sfnt"},
  4564. {".pfr", 4, "application/font-tdpfr"},
  4565. {".woff", 5, "application/font-woff"},
  4566. /* audio */
  4567. {".mp3", 4, "audio/mpeg"},
  4568. {".oga", 4, "audio/ogg"},
  4569. {".ogg", 4, "audio/ogg"},
  4570. /* image */
  4571. {".gif", 4, "image/gif"},
  4572. {".ief", 4, "image/ief"},
  4573. {".jpeg", 5, "image/jpeg"},
  4574. {".jpg", 4, "image/jpeg"},
  4575. {".jpm", 4, "image/jpm"},
  4576. {".jpx", 4, "image/jpx"},
  4577. {".png", 4, "image/png"},
  4578. {".svg", 4, "image/svg+xml"},
  4579. {".tif", 4, "image/tiff"},
  4580. {".tiff", 5, "image/tiff"},
  4581. /* model */
  4582. {".wrl", 4, "model/vrml"},
  4583. /* text */
  4584. {".css", 4, "text/css"},
  4585. {".csv", 4, "text/csv"},
  4586. {".htm", 4, "text/html"},
  4587. {".html", 5, "text/html"},
  4588. {".sgm", 4, "text/sgml"},
  4589. {".shtm", 5, "text/html"},
  4590. {".shtml", 6, "text/html"},
  4591. {".txt", 4, "text/plain"},
  4592. {".xml", 4, "text/xml"},
  4593. /* video */
  4594. {".mov", 4, "video/quicktime"},
  4595. {".mp4", 4, "video/mp4"},
  4596. {".mpeg", 5, "video/mpeg"},
  4597. {".mpg", 4, "video/mpeg"},
  4598. {".ogv", 4, "video/ogg"},
  4599. {".qt", 3, "video/quicktime"},
  4600. /* not registered types
  4601. * (http://reference.sitepoint.com/html/mime-types-full,
  4602. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4603. {".arj", 4, "application/x-arj-compressed"},
  4604. {".gz", 3, "application/x-gunzip"},
  4605. {".rar", 4, "application/x-arj-compressed"},
  4606. {".swf", 4, "application/x-shockwave-flash"},
  4607. {".tar", 4, "application/x-tar"},
  4608. {".tgz", 4, "application/x-tar-gz"},
  4609. {".torrent", 8, "application/x-bittorrent"},
  4610. {".ppt", 4, "application/x-mspowerpoint"},
  4611. {".xls", 4, "application/x-msexcel"},
  4612. {".zip", 4, "application/x-zip-compressed"},
  4613. {".aac",
  4614. 4,
  4615. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4616. {".aif", 4, "audio/x-aif"},
  4617. {".m3u", 4, "audio/x-mpegurl"},
  4618. {".mid", 4, "audio/x-midi"},
  4619. {".ra", 3, "audio/x-pn-realaudio"},
  4620. {".ram", 4, "audio/x-pn-realaudio"},
  4621. {".wav", 4, "audio/x-wav"},
  4622. {".bmp", 4, "image/bmp"},
  4623. {".ico", 4, "image/x-icon"},
  4624. {".pct", 4, "image/x-pct"},
  4625. {".pict", 5, "image/pict"},
  4626. {".rgb", 4, "image/x-rgb"},
  4627. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4628. {".asf", 4, "video/x-ms-asf"},
  4629. {".avi", 4, "video/x-msvideo"},
  4630. {".m4v", 4, "video/x-m4v"},
  4631. {NULL, 0, NULL}};
  4632. const char *
  4633. mg_get_builtin_mime_type(const char *path)
  4634. {
  4635. const char *ext;
  4636. size_t i, path_len;
  4637. path_len = strlen(path);
  4638. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4639. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4640. if (path_len > builtin_mime_types[i].ext_len
  4641. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4642. return builtin_mime_types[i].mime_type;
  4643. }
  4644. }
  4645. return "text/plain";
  4646. }
  4647. /* Look at the "path" extension and figure what mime type it has.
  4648. * Store mime type in the vector. */
  4649. static void
  4650. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4651. {
  4652. struct vec ext_vec, mime_vec;
  4653. const char *list, *ext;
  4654. size_t path_len;
  4655. path_len = strlen(path);
  4656. if (ctx == NULL || vec == NULL) {
  4657. return;
  4658. }
  4659. /* Scan user-defined mime types first, in case user wants to
  4660. * override default mime types. */
  4661. list = ctx->config[EXTRA_MIME_TYPES];
  4662. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4663. /* ext now points to the path suffix */
  4664. ext = path + path_len - ext_vec.len;
  4665. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4666. *vec = mime_vec;
  4667. return;
  4668. }
  4669. }
  4670. vec->ptr = mg_get_builtin_mime_type(path);
  4671. vec->len = strlen(vec->ptr);
  4672. }
  4673. /* Stringify binary data. Output buffer must be twice as big as input,
  4674. * because each byte takes 2 bytes in string representation */
  4675. static void
  4676. bin2str(char *to, const unsigned char *p, size_t len)
  4677. {
  4678. static const char *hex = "0123456789abcdef";
  4679. for (; len--; p++) {
  4680. *to++ = hex[p[0] >> 4];
  4681. *to++ = hex[p[0] & 0x0f];
  4682. }
  4683. *to = '\0';
  4684. }
  4685. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4686. char *
  4687. mg_md5(char buf[33], ...)
  4688. {
  4689. md5_byte_t hash[16];
  4690. const char *p;
  4691. va_list ap;
  4692. md5_state_t ctx;
  4693. md5_init(&ctx);
  4694. va_start(ap, buf);
  4695. while ((p = va_arg(ap, const char *)) != NULL) {
  4696. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4697. }
  4698. va_end(ap);
  4699. md5_finish(&ctx, hash);
  4700. bin2str(buf, hash, sizeof(hash));
  4701. return buf;
  4702. }
  4703. /* Check the user's password, return 1 if OK */
  4704. static int
  4705. check_password(const char *method,
  4706. const char *ha1,
  4707. const char *uri,
  4708. const char *nonce,
  4709. const char *nc,
  4710. const char *cnonce,
  4711. const char *qop,
  4712. const char *response)
  4713. {
  4714. char ha2[32 + 1], expected_response[32 + 1];
  4715. /* Some of the parameters may be NULL */
  4716. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4717. || qop == NULL
  4718. || response == NULL) {
  4719. return 0;
  4720. }
  4721. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4722. if (strlen(response) != 32) {
  4723. return 0;
  4724. }
  4725. mg_md5(ha2, method, ":", uri, NULL);
  4726. mg_md5(expected_response,
  4727. ha1,
  4728. ":",
  4729. nonce,
  4730. ":",
  4731. nc,
  4732. ":",
  4733. cnonce,
  4734. ":",
  4735. qop,
  4736. ":",
  4737. ha2,
  4738. NULL);
  4739. return mg_strcasecmp(response, expected_response) == 0;
  4740. }
  4741. /* Use the global passwords file, if specified by auth_gpass option,
  4742. * or search for .htpasswd in the requested directory. */
  4743. static void
  4744. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4745. {
  4746. if (conn != NULL && conn->ctx != NULL) {
  4747. char name[PATH_MAX];
  4748. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4749. struct file file = STRUCT_FILE_INITIALIZER;
  4750. int truncated;
  4751. if (gpass != NULL) {
  4752. /* Use global passwords file */
  4753. if (!mg_fopen(conn, gpass, "r", filep)) {
  4754. #ifdef DEBUG
  4755. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4756. #endif
  4757. }
  4758. /* Important: using local struct file to test path for is_directory
  4759. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4760. * was opened. */
  4761. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4762. mg_snprintf(conn,
  4763. &truncated,
  4764. name,
  4765. sizeof(name),
  4766. "%s/%s",
  4767. path,
  4768. PASSWORDS_FILE_NAME);
  4769. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4770. #ifdef DEBUG
  4771. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4772. #endif
  4773. }
  4774. } else {
  4775. /* Try to find .htpasswd in requested directory. */
  4776. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4777. if (e[0] == '/') {
  4778. break;
  4779. }
  4780. }
  4781. mg_snprintf(conn,
  4782. &truncated,
  4783. name,
  4784. sizeof(name),
  4785. "%.*s/%s",
  4786. (int)(e - p),
  4787. p,
  4788. PASSWORDS_FILE_NAME);
  4789. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4790. #ifdef DEBUG
  4791. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4792. #endif
  4793. }
  4794. }
  4795. }
  4796. }
  4797. /* Parsed Authorization header */
  4798. struct ah {
  4799. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4800. };
  4801. /* Return 1 on success. Always initializes the ah structure. */
  4802. static int
  4803. parse_auth_header(struct mg_connection *conn,
  4804. char *buf,
  4805. size_t buf_size,
  4806. struct ah *ah)
  4807. {
  4808. char *name, *value, *s;
  4809. const char *auth_header;
  4810. uint64_t nonce;
  4811. if (!ah || !conn) {
  4812. return 0;
  4813. }
  4814. (void)memset(ah, 0, sizeof(*ah));
  4815. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4816. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4817. return 0;
  4818. }
  4819. /* Make modifiable copy of the auth header */
  4820. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4821. s = buf;
  4822. /* Parse authorization header */
  4823. for (;;) {
  4824. /* Gobble initial spaces */
  4825. while (isspace(*(unsigned char *)s)) {
  4826. s++;
  4827. }
  4828. name = skip_quoted(&s, "=", " ", 0);
  4829. /* Value is either quote-delimited, or ends at first comma or space. */
  4830. if (s[0] == '\"') {
  4831. s++;
  4832. value = skip_quoted(&s, "\"", " ", '\\');
  4833. if (s[0] == ',') {
  4834. s++;
  4835. }
  4836. } else {
  4837. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4838. * spaces */
  4839. }
  4840. if (*name == '\0') {
  4841. break;
  4842. }
  4843. if (!strcmp(name, "username")) {
  4844. ah->user = value;
  4845. } else if (!strcmp(name, "cnonce")) {
  4846. ah->cnonce = value;
  4847. } else if (!strcmp(name, "response")) {
  4848. ah->response = value;
  4849. } else if (!strcmp(name, "uri")) {
  4850. ah->uri = value;
  4851. } else if (!strcmp(name, "qop")) {
  4852. ah->qop = value;
  4853. } else if (!strcmp(name, "nc")) {
  4854. ah->nc = value;
  4855. } else if (!strcmp(name, "nonce")) {
  4856. ah->nonce = value;
  4857. }
  4858. }
  4859. #ifndef NO_NONCE_CHECK
  4860. /* Read the nonce from the response. */
  4861. if (ah->nonce == NULL) {
  4862. return 0;
  4863. }
  4864. s = NULL;
  4865. nonce = strtoull(ah->nonce, &s, 10);
  4866. if ((s == NULL) || (*s != 0)) {
  4867. return 0;
  4868. }
  4869. /* Convert the nonce from the client to a number. */
  4870. nonce ^= conn->ctx->auth_nonce_mask;
  4871. /* The converted number corresponds to the time the nounce has been
  4872. * created. This should not be earlier than the server start. */
  4873. /* Server side nonce check is valuable in all situations but one:
  4874. * if the server restarts frequently, but the client should not see
  4875. * that, so the server should accept nonces from previous starts. */
  4876. /* However, the reasonable default is to not accept a nonce from a
  4877. * previous start, so if anyone changed the access rights between
  4878. * two restarts, a new login is required. */
  4879. if (nonce < (uint64_t)conn->ctx->start_time) {
  4880. /* nonce is from a previous start of the server and no longer valid
  4881. * (replay attack?) */
  4882. return 0;
  4883. }
  4884. /* Check if the nonce is too high, so it has not (yet) been used by the
  4885. * server. */
  4886. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4887. return 0;
  4888. }
  4889. #else
  4890. (void)nonce;
  4891. #endif
  4892. /* CGI needs it as REMOTE_USER */
  4893. if (ah->user != NULL) {
  4894. conn->request_info.remote_user = mg_strdup(ah->user);
  4895. } else {
  4896. return 0;
  4897. }
  4898. return 1;
  4899. }
  4900. static const char *
  4901. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4902. {
  4903. const char *eof;
  4904. size_t len;
  4905. const char *memend;
  4906. if (!filep) {
  4907. return NULL;
  4908. }
  4909. if (filep->membuf != NULL && *p != NULL) {
  4910. memend = (const char *)&filep->membuf[filep->size];
  4911. /* Search for \n from p till the end of stream */
  4912. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4913. if (eof != NULL) {
  4914. eof += 1; /* Include \n */
  4915. } else {
  4916. eof = memend; /* Copy remaining data */
  4917. }
  4918. len =
  4919. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  4920. memcpy(buf, *p, len);
  4921. buf[len] = '\0';
  4922. *p += len;
  4923. return len ? eof : NULL;
  4924. } else if (filep->fp != NULL) {
  4925. return fgets(buf, (int)size, filep->fp);
  4926. } else {
  4927. return NULL;
  4928. }
  4929. }
  4930. struct read_auth_file_struct {
  4931. struct mg_connection *conn;
  4932. struct ah ah;
  4933. char *domain;
  4934. char buf[256 + 256 + 40];
  4935. char *f_user;
  4936. char *f_domain;
  4937. char *f_ha1;
  4938. };
  4939. static int
  4940. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4941. {
  4942. char *p;
  4943. int is_authorized = 0;
  4944. struct file fp;
  4945. size_t l;
  4946. if (!filep || !workdata) {
  4947. return 0;
  4948. }
  4949. /* Loop over passwords file */
  4950. p = (char *)filep->membuf;
  4951. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4952. l = strlen(workdata->buf);
  4953. while (l > 0) {
  4954. if (isspace(workdata->buf[l - 1])
  4955. || iscntrl(workdata->buf[l - 1])) {
  4956. l--;
  4957. workdata->buf[l] = 0;
  4958. } else
  4959. break;
  4960. }
  4961. if (l < 1) {
  4962. continue;
  4963. }
  4964. workdata->f_user = workdata->buf;
  4965. if (workdata->f_user[0] == ':') {
  4966. /* user names may not contain a ':' and may not be empty,
  4967. * so lines starting with ':' may be used for a special purpose */
  4968. if (workdata->f_user[1] == '#') {
  4969. /* :# is a comment */
  4970. continue;
  4971. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4972. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4973. is_authorized = read_auth_file(&fp, workdata);
  4974. mg_fclose(&fp);
  4975. } else {
  4976. mg_cry(workdata->conn,
  4977. "%s: cannot open authorization file: %s",
  4978. __func__,
  4979. workdata->buf);
  4980. }
  4981. continue;
  4982. }
  4983. /* everything is invalid for the moment (might change in the
  4984. * future) */
  4985. mg_cry(workdata->conn,
  4986. "%s: syntax error in authorization file: %s",
  4987. __func__,
  4988. workdata->buf);
  4989. continue;
  4990. }
  4991. workdata->f_domain = strchr(workdata->f_user, ':');
  4992. if (workdata->f_domain == NULL) {
  4993. mg_cry(workdata->conn,
  4994. "%s: syntax error in authorization file: %s",
  4995. __func__,
  4996. workdata->buf);
  4997. continue;
  4998. }
  4999. *(workdata->f_domain) = 0;
  5000. (workdata->f_domain)++;
  5001. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5002. if (workdata->f_ha1 == NULL) {
  5003. mg_cry(workdata->conn,
  5004. "%s: syntax error in authorization file: %s",
  5005. __func__,
  5006. workdata->buf);
  5007. continue;
  5008. }
  5009. *(workdata->f_ha1) = 0;
  5010. (workdata->f_ha1)++;
  5011. if (!strcmp(workdata->ah.user, workdata->f_user)
  5012. && !strcmp(workdata->domain, workdata->f_domain)) {
  5013. return check_password(workdata->conn->request_info.request_method,
  5014. workdata->f_ha1,
  5015. workdata->ah.uri,
  5016. workdata->ah.nonce,
  5017. workdata->ah.nc,
  5018. workdata->ah.cnonce,
  5019. workdata->ah.qop,
  5020. workdata->ah.response);
  5021. }
  5022. }
  5023. return is_authorized;
  5024. }
  5025. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5026. static int
  5027. authorize(struct mg_connection *conn, struct file *filep)
  5028. {
  5029. struct read_auth_file_struct workdata;
  5030. char buf[MG_BUF_LEN];
  5031. if (!conn || !conn->ctx) {
  5032. return 0;
  5033. }
  5034. memset(&workdata, 0, sizeof(workdata));
  5035. workdata.conn = conn;
  5036. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5037. return 0;
  5038. }
  5039. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5040. return read_auth_file(filep, &workdata);
  5041. }
  5042. /* Return 1 if request is authorised, 0 otherwise. */
  5043. static int
  5044. check_authorization(struct mg_connection *conn, const char *path)
  5045. {
  5046. char fname[PATH_MAX];
  5047. struct vec uri_vec, filename_vec;
  5048. const char *list;
  5049. struct file file = STRUCT_FILE_INITIALIZER;
  5050. int authorized = 1, truncated;
  5051. if (!conn || !conn->ctx) {
  5052. return 0;
  5053. }
  5054. list = conn->ctx->config[PROTECT_URI];
  5055. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5056. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5057. mg_snprintf(conn,
  5058. &truncated,
  5059. fname,
  5060. sizeof(fname),
  5061. "%.*s",
  5062. (int)filename_vec.len,
  5063. filename_vec.ptr);
  5064. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  5065. mg_cry(conn,
  5066. "%s: cannot open %s: %s",
  5067. __func__,
  5068. fname,
  5069. strerror(errno));
  5070. }
  5071. break;
  5072. }
  5073. }
  5074. if (!is_file_opened(&file)) {
  5075. open_auth_file(conn, path, &file);
  5076. }
  5077. if (is_file_opened(&file)) {
  5078. authorized = authorize(conn, &file);
  5079. mg_fclose(&file);
  5080. }
  5081. return authorized;
  5082. }
  5083. static void
  5084. send_authorization_request(struct mg_connection *conn)
  5085. {
  5086. char date[64];
  5087. time_t curtime = time(NULL);
  5088. if (conn && conn->ctx) {
  5089. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5090. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5091. nonce += conn->ctx->nonce_count;
  5092. ++conn->ctx->nonce_count;
  5093. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5094. nonce ^= conn->ctx->auth_nonce_mask;
  5095. conn->status_code = 401;
  5096. conn->must_close = 1;
  5097. gmt_time_string(date, sizeof(date), &curtime);
  5098. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5099. send_no_cache_header(conn);
  5100. mg_printf(conn,
  5101. "Date: %s\r\n"
  5102. "Connection: %s\r\n"
  5103. "Content-Length: 0\r\n"
  5104. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5105. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5106. date,
  5107. suggest_connection_header(conn),
  5108. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5109. nonce);
  5110. }
  5111. }
  5112. #if !defined(NO_FILES)
  5113. static int
  5114. is_authorized_for_put(struct mg_connection *conn)
  5115. {
  5116. if (conn) {
  5117. struct file file = STRUCT_FILE_INITIALIZER;
  5118. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5119. int ret = 0;
  5120. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5121. ret = authorize(conn, &file);
  5122. mg_fclose(&file);
  5123. }
  5124. return ret;
  5125. }
  5126. return 0;
  5127. }
  5128. #endif
  5129. int
  5130. mg_modify_passwords_file(const char *fname,
  5131. const char *domain,
  5132. const char *user,
  5133. const char *pass)
  5134. {
  5135. int found, i;
  5136. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5137. FILE *fp, *fp2;
  5138. found = 0;
  5139. fp = fp2 = NULL;
  5140. /* Regard empty password as no password - remove user record. */
  5141. if (pass != NULL && pass[0] == '\0') {
  5142. pass = NULL;
  5143. }
  5144. /* Other arguments must not be empty */
  5145. if (fname == NULL || domain == NULL || user == NULL) {
  5146. return 0;
  5147. }
  5148. /* Using the given file format, user name and domain must not contain ':'
  5149. */
  5150. if (strchr(user, ':') != NULL) {
  5151. return 0;
  5152. }
  5153. if (strchr(domain, ':') != NULL) {
  5154. return 0;
  5155. }
  5156. /* Do not allow control characters like newline in user name and domain.
  5157. * Do not allow excessively long names either. */
  5158. for (i = 0; i < 255 && user[i] != 0; i++) {
  5159. if (iscntrl(user[i])) {
  5160. return 0;
  5161. }
  5162. }
  5163. if (user[i]) {
  5164. return 0;
  5165. }
  5166. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5167. if (iscntrl(domain[i])) {
  5168. return 0;
  5169. }
  5170. }
  5171. if (domain[i]) {
  5172. return 0;
  5173. }
  5174. /* The maximum length of the path to the password file is limited */
  5175. if ((strlen(fname) + 4) >= PATH_MAX) {
  5176. return 0;
  5177. }
  5178. /* Create a temporary file name. Length has been checked before. */
  5179. strcpy(tmp, fname);
  5180. strcat(tmp, ".tmp");
  5181. /* Create the file if does not exist */
  5182. /* Use of fopen here is OK, since fname is only ASCII */
  5183. if ((fp = fopen(fname, "a+")) != NULL) {
  5184. (void)fclose(fp);
  5185. }
  5186. /* Open the given file and temporary file */
  5187. if ((fp = fopen(fname, "r")) == NULL) {
  5188. return 0;
  5189. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5190. fclose(fp);
  5191. return 0;
  5192. }
  5193. /* Copy the stuff to temporary file */
  5194. while (fgets(line, sizeof(line), fp) != NULL) {
  5195. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5196. continue;
  5197. }
  5198. u[255] = 0;
  5199. d[255] = 0;
  5200. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5201. found++;
  5202. if (pass != NULL) {
  5203. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5204. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5205. }
  5206. } else {
  5207. fprintf(fp2, "%s", line);
  5208. }
  5209. }
  5210. /* If new user, just add it */
  5211. if (!found && pass != NULL) {
  5212. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5213. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5214. }
  5215. /* Close files */
  5216. fclose(fp);
  5217. fclose(fp2);
  5218. /* Put the temp file in place of real file */
  5219. IGNORE_UNUSED_RESULT(remove(fname));
  5220. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5221. return 1;
  5222. }
  5223. static int
  5224. is_valid_port(unsigned long port)
  5225. {
  5226. return port < 0xffff;
  5227. }
  5228. static int
  5229. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5230. {
  5231. struct addrinfo hints, *res, *ressave;
  5232. int func_ret = 0;
  5233. int gai_ret;
  5234. memset(&hints, 0, sizeof(struct addrinfo));
  5235. hints.ai_family = af;
  5236. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5237. if (gai_ret != 0) {
  5238. /* gai_strerror could be used to convert gai_ret to a string */
  5239. /* POSIX return values: see
  5240. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5241. */
  5242. /* Windows return values: see
  5243. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5244. */
  5245. return 0;
  5246. }
  5247. ressave = res;
  5248. while (res) {
  5249. if (dstlen >= res->ai_addrlen) {
  5250. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5251. func_ret = 1;
  5252. }
  5253. res = res->ai_next;
  5254. }
  5255. freeaddrinfo(ressave);
  5256. return func_ret;
  5257. }
  5258. static int
  5259. connect_socket(struct mg_context *ctx /* may be NULL */,
  5260. const char *host,
  5261. int port,
  5262. int use_ssl,
  5263. char *ebuf,
  5264. size_t ebuf_len,
  5265. SOCKET *sock /* output: socket, must not be NULL */,
  5266. union usa *sa /* output: socket address, must not be NULL */
  5267. )
  5268. {
  5269. int ip_ver = 0;
  5270. *sock = INVALID_SOCKET;
  5271. memset(sa, 0, sizeof(*sa));
  5272. if (ebuf_len > 0) {
  5273. *ebuf = 0;
  5274. }
  5275. if (host == NULL) {
  5276. mg_snprintf(NULL,
  5277. NULL, /* No truncation check for ebuf */
  5278. ebuf,
  5279. ebuf_len,
  5280. "%s",
  5281. "NULL host");
  5282. return 0;
  5283. }
  5284. if (port < 0 || !is_valid_port((unsigned)port)) {
  5285. mg_snprintf(NULL,
  5286. NULL, /* No truncation check for ebuf */
  5287. ebuf,
  5288. ebuf_len,
  5289. "%s",
  5290. "invalid port");
  5291. return 0;
  5292. }
  5293. #if !defined(NO_SSL)
  5294. if (use_ssl && (SSLv23_client_method == NULL)) {
  5295. mg_snprintf(NULL,
  5296. NULL, /* No truncation check for ebuf */
  5297. ebuf,
  5298. ebuf_len,
  5299. "%s",
  5300. "SSL is not initialized");
  5301. return 0;
  5302. }
  5303. #else
  5304. (void)use_ssl;
  5305. #endif
  5306. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5307. sa->sin.sin_port = htons((uint16_t)port);
  5308. ip_ver = 4;
  5309. #ifdef USE_IPV6
  5310. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5311. sa->sin6.sin6_port = htons((uint16_t)port);
  5312. ip_ver = 6;
  5313. } else if (host[0] == '[') {
  5314. /* While getaddrinfo on Windows will work with [::1],
  5315. * getaddrinfo on Linux only works with ::1 (without []). */
  5316. size_t l = strlen(host + 1);
  5317. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5318. if (h) {
  5319. h[l - 1] = 0;
  5320. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5321. sa->sin6.sin6_port = htons((uint16_t)port);
  5322. ip_ver = 6;
  5323. }
  5324. mg_free(h);
  5325. }
  5326. #endif
  5327. }
  5328. if (ip_ver == 0) {
  5329. mg_snprintf(NULL,
  5330. NULL, /* No truncation check for ebuf */
  5331. ebuf,
  5332. ebuf_len,
  5333. "%s",
  5334. "host not found");
  5335. return 0;
  5336. }
  5337. if (ip_ver == 4) {
  5338. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5339. }
  5340. #ifdef USE_IPV6
  5341. else if (ip_ver == 6) {
  5342. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5343. }
  5344. #endif
  5345. if (*sock == INVALID_SOCKET) {
  5346. mg_snprintf(NULL,
  5347. NULL, /* No truncation check for ebuf */
  5348. ebuf,
  5349. ebuf_len,
  5350. "socket(): %s",
  5351. strerror(ERRNO));
  5352. return 0;
  5353. }
  5354. set_close_on_exec(*sock, fc(ctx));
  5355. if ((ip_ver == 4)
  5356. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5357. == 0)) {
  5358. /* connected with IPv4 */
  5359. return 1;
  5360. }
  5361. #ifdef USE_IPV6
  5362. if ((ip_ver == 6)
  5363. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5364. == 0)) {
  5365. /* connected with IPv6 */
  5366. return 1;
  5367. }
  5368. #endif
  5369. /* Not connected */
  5370. mg_snprintf(NULL,
  5371. NULL, /* No truncation check for ebuf */
  5372. ebuf,
  5373. ebuf_len,
  5374. "connect(%s:%d): %s",
  5375. host,
  5376. port,
  5377. strerror(ERRNO));
  5378. closesocket(*sock);
  5379. *sock = INVALID_SOCKET;
  5380. return 0;
  5381. }
  5382. int
  5383. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5384. {
  5385. static const char *dont_escape = "._-$,;~()";
  5386. static const char *hex = "0123456789abcdef";
  5387. char *pos = dst;
  5388. const char *end = dst + dst_len - 1;
  5389. for (; *src != '\0' && pos < end; src++, pos++) {
  5390. if (isalnum(*(const unsigned char *)src)
  5391. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5392. *pos = *src;
  5393. } else if (pos + 2 < end) {
  5394. pos[0] = '%';
  5395. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5396. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5397. pos += 2;
  5398. } else {
  5399. break;
  5400. }
  5401. }
  5402. *pos = '\0';
  5403. return (*src == '\0') ? (int)(pos - dst) : -1;
  5404. }
  5405. static void
  5406. print_dir_entry(struct de *de)
  5407. {
  5408. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5409. struct tm *tm;
  5410. if (de->file.is_directory) {
  5411. mg_snprintf(de->conn,
  5412. NULL, /* Buffer is big enough */
  5413. size,
  5414. sizeof(size),
  5415. "%s",
  5416. "[DIRECTORY]");
  5417. } else {
  5418. /* We use (signed) cast below because MSVC 6 compiler cannot
  5419. * convert unsigned __int64 to double. Sigh. */
  5420. if (de->file.size < 1024) {
  5421. mg_snprintf(de->conn,
  5422. NULL, /* Buffer is big enough */
  5423. size,
  5424. sizeof(size),
  5425. "%d",
  5426. (int)de->file.size);
  5427. } else if (de->file.size < 0x100000) {
  5428. mg_snprintf(de->conn,
  5429. NULL, /* Buffer is big enough */
  5430. size,
  5431. sizeof(size),
  5432. "%.1fk",
  5433. (double)de->file.size / 1024.0);
  5434. } else if (de->file.size < 0x40000000) {
  5435. mg_snprintf(de->conn,
  5436. NULL, /* Buffer is big enough */
  5437. size,
  5438. sizeof(size),
  5439. "%.1fM",
  5440. (double)de->file.size / 1048576);
  5441. } else {
  5442. mg_snprintf(de->conn,
  5443. NULL, /* Buffer is big enough */
  5444. size,
  5445. sizeof(size),
  5446. "%.1fG",
  5447. (double)de->file.size / 1073741824);
  5448. }
  5449. }
  5450. /* Note: mg_snprintf will not cause a buffer overflow above.
  5451. * So, string truncation checks are not required here. */
  5452. tm = localtime(&de->file.last_modified);
  5453. if (tm != NULL) {
  5454. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5455. } else {
  5456. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5457. mod[sizeof(mod) - 1] = '\0';
  5458. }
  5459. mg_url_encode(de->file_name, href, sizeof(href));
  5460. de->conn->num_bytes_sent +=
  5461. mg_printf(de->conn,
  5462. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5463. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5464. de->conn->request_info.local_uri,
  5465. href,
  5466. de->file.is_directory ? "/" : "",
  5467. de->file_name,
  5468. de->file.is_directory ? "/" : "",
  5469. mod,
  5470. size);
  5471. }
  5472. /* This function is called from send_directory() and used for
  5473. * sorting directory entries by size, or name, or modification time.
  5474. * On windows, __cdecl specification is needed in case if project is built
  5475. * with __stdcall convention. qsort always requires __cdels callback. */
  5476. static int WINCDECL
  5477. compare_dir_entries(const void *p1, const void *p2)
  5478. {
  5479. if (p1 && p2) {
  5480. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5481. const char *query_string = a->conn->request_info.query_string;
  5482. int cmp_result = 0;
  5483. if (query_string == NULL) {
  5484. query_string = "na";
  5485. }
  5486. if (a->file.is_directory && !b->file.is_directory) {
  5487. return -1; /* Always put directories on top */
  5488. } else if (!a->file.is_directory && b->file.is_directory) {
  5489. return 1; /* Always put directories on top */
  5490. } else if (*query_string == 'n') {
  5491. cmp_result = strcmp(a->file_name, b->file_name);
  5492. } else if (*query_string == 's') {
  5493. cmp_result = (a->file.size == b->file.size)
  5494. ? 0
  5495. : ((a->file.size > b->file.size) ? 1 : -1);
  5496. } else if (*query_string == 'd') {
  5497. cmp_result =
  5498. (a->file.last_modified == b->file.last_modified)
  5499. ? 0
  5500. : ((a->file.last_modified > b->file.last_modified) ? 1
  5501. : -1);
  5502. }
  5503. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5504. }
  5505. return 0;
  5506. }
  5507. static int
  5508. must_hide_file(struct mg_connection *conn, const char *path)
  5509. {
  5510. if (conn && conn->ctx) {
  5511. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5512. const char *pattern = conn->ctx->config[HIDE_FILES];
  5513. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5514. || (pattern != NULL
  5515. && match_prefix(pattern, strlen(pattern), path) > 0);
  5516. }
  5517. return 0;
  5518. }
  5519. static int
  5520. scan_directory(struct mg_connection *conn,
  5521. const char *dir,
  5522. void *data,
  5523. void (*cb)(struct de *, void *))
  5524. {
  5525. char path[PATH_MAX];
  5526. struct dirent *dp;
  5527. DIR *dirp;
  5528. struct de de;
  5529. int truncated;
  5530. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5531. return 0;
  5532. } else {
  5533. de.conn = conn;
  5534. while ((dp = mg_readdir(dirp)) != NULL) {
  5535. /* Do not show current dir and hidden files */
  5536. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5537. || must_hide_file(conn, dp->d_name)) {
  5538. continue;
  5539. }
  5540. mg_snprintf(
  5541. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5542. /* If we don't memset stat structure to zero, mtime will have
  5543. * garbage and strftime() will segfault later on in
  5544. * print_dir_entry(). memset is required only if mg_stat()
  5545. * fails. For more details, see
  5546. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5547. memset(&de.file, 0, sizeof(de.file));
  5548. if (truncated) {
  5549. /* If the path is not complete, skip processing. */
  5550. continue;
  5551. }
  5552. if (!mg_stat(conn, path, &de.file)) {
  5553. mg_cry(conn,
  5554. "%s: mg_stat(%s) failed: %s",
  5555. __func__,
  5556. path,
  5557. strerror(ERRNO));
  5558. }
  5559. de.file_name = dp->d_name;
  5560. cb(&de, data);
  5561. }
  5562. (void)mg_closedir(dirp);
  5563. }
  5564. return 1;
  5565. }
  5566. #if !defined(NO_FILES)
  5567. static int
  5568. remove_directory(struct mg_connection *conn, const char *dir)
  5569. {
  5570. char path[PATH_MAX];
  5571. struct dirent *dp;
  5572. DIR *dirp;
  5573. struct de de;
  5574. int truncated;
  5575. int ok = 1;
  5576. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5577. return 0;
  5578. } else {
  5579. de.conn = conn;
  5580. while ((dp = mg_readdir(dirp)) != NULL) {
  5581. /* Do not show current dir (but show hidden files as they will
  5582. * also be removed) */
  5583. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5584. continue;
  5585. }
  5586. mg_snprintf(
  5587. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5588. /* If we don't memset stat structure to zero, mtime will have
  5589. * garbage and strftime() will segfault later on in
  5590. * print_dir_entry(). memset is required only if mg_stat()
  5591. * fails. For more details, see
  5592. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5593. memset(&de.file, 0, sizeof(de.file));
  5594. if (truncated) {
  5595. /* Do not delete anything shorter */
  5596. ok = 0;
  5597. continue;
  5598. }
  5599. if (!mg_stat(conn, path, &de.file)) {
  5600. mg_cry(conn,
  5601. "%s: mg_stat(%s) failed: %s",
  5602. __func__,
  5603. path,
  5604. strerror(ERRNO));
  5605. ok = 0;
  5606. }
  5607. if (de.file.membuf == NULL) {
  5608. /* file is not in memory */
  5609. if (de.file.is_directory) {
  5610. if (remove_directory(conn, path) == 0) {
  5611. ok = 0;
  5612. }
  5613. } else {
  5614. if (mg_remove(conn, path) == 0) {
  5615. ok = 0;
  5616. }
  5617. }
  5618. } else {
  5619. /* file is in memory. It can not be deleted. */
  5620. ok = 0;
  5621. }
  5622. }
  5623. (void)mg_closedir(dirp);
  5624. IGNORE_UNUSED_RESULT(rmdir(dir));
  5625. }
  5626. return ok;
  5627. }
  5628. #endif
  5629. struct dir_scan_data {
  5630. struct de *entries;
  5631. unsigned int num_entries;
  5632. unsigned int arr_size;
  5633. };
  5634. /* Behaves like realloc(), but frees original pointer on failure */
  5635. static void *
  5636. realloc2(void *ptr, size_t size)
  5637. {
  5638. void *new_ptr = mg_realloc(ptr, size);
  5639. if (new_ptr == NULL) {
  5640. mg_free(ptr);
  5641. }
  5642. return new_ptr;
  5643. }
  5644. static void
  5645. dir_scan_callback(struct de *de, void *data)
  5646. {
  5647. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5648. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5649. dsd->arr_size *= 2;
  5650. dsd->entries =
  5651. (struct de *)realloc2(dsd->entries,
  5652. dsd->arr_size * sizeof(dsd->entries[0]));
  5653. }
  5654. if (dsd->entries == NULL) {
  5655. /* TODO(lsm, low): propagate an error to the caller */
  5656. dsd->num_entries = 0;
  5657. } else {
  5658. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5659. dsd->entries[dsd->num_entries].file = de->file;
  5660. dsd->entries[dsd->num_entries].conn = de->conn;
  5661. dsd->num_entries++;
  5662. }
  5663. }
  5664. static void
  5665. handle_directory_request(struct mg_connection *conn, const char *dir)
  5666. {
  5667. unsigned int i;
  5668. int sort_direction;
  5669. struct dir_scan_data data = {NULL, 0, 128};
  5670. char date[64];
  5671. time_t curtime = time(NULL);
  5672. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5673. send_http_error(conn,
  5674. 500,
  5675. "Error: Cannot open directory\nopendir(%s): %s",
  5676. dir,
  5677. strerror(ERRNO));
  5678. return;
  5679. }
  5680. gmt_time_string(date, sizeof(date), &curtime);
  5681. if (!conn) {
  5682. return;
  5683. }
  5684. sort_direction = ((conn->request_info.query_string != NULL)
  5685. && (conn->request_info.query_string[1] == 'd'))
  5686. ? 'a'
  5687. : 'd';
  5688. conn->must_close = 1;
  5689. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5690. send_static_cache_header(conn);
  5691. mg_printf(conn,
  5692. "Date: %s\r\n"
  5693. "Connection: close\r\n"
  5694. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5695. date);
  5696. conn->num_bytes_sent +=
  5697. mg_printf(conn,
  5698. "<html><head><title>Index of %s</title>"
  5699. "<style>th {text-align: left;}</style></head>"
  5700. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5701. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5702. "<th><a href=\"?d%c\">Modified</a></th>"
  5703. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5704. "<tr><td colspan=\"3\"><hr></td></tr>",
  5705. conn->request_info.local_uri,
  5706. conn->request_info.local_uri,
  5707. sort_direction,
  5708. sort_direction,
  5709. sort_direction);
  5710. /* Print first entry - link to a parent directory */
  5711. conn->num_bytes_sent +=
  5712. mg_printf(conn,
  5713. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5714. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5715. conn->request_info.local_uri,
  5716. "..",
  5717. "Parent directory",
  5718. "-",
  5719. "-");
  5720. /* Sort and print directory entries */
  5721. if (data.entries != NULL) {
  5722. qsort(data.entries,
  5723. (size_t)data.num_entries,
  5724. sizeof(data.entries[0]),
  5725. compare_dir_entries);
  5726. for (i = 0; i < data.num_entries; i++) {
  5727. print_dir_entry(&data.entries[i]);
  5728. mg_free(data.entries[i].file_name);
  5729. }
  5730. mg_free(data.entries);
  5731. }
  5732. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5733. conn->status_code = 200;
  5734. }
  5735. /* Send len bytes from the opened file to the client. */
  5736. static void
  5737. send_file_data(struct mg_connection *conn,
  5738. struct file *filep,
  5739. int64_t offset,
  5740. int64_t len)
  5741. {
  5742. char buf[MG_BUF_LEN];
  5743. int to_read, num_read, num_written;
  5744. int64_t size;
  5745. if (!filep || !conn) {
  5746. return;
  5747. }
  5748. /* Sanity check the offset */
  5749. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5750. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5751. if (len > 0 && filep->membuf != NULL && size > 0) {
  5752. /* file stored in memory */
  5753. if (len > size - offset) {
  5754. len = size - offset;
  5755. }
  5756. mg_write(conn, filep->membuf + offset, (size_t)len);
  5757. } else if (len > 0 && filep->fp != NULL) {
  5758. /* file stored on disk */
  5759. #if defined(__linux__)
  5760. /* sendfile is only available for Linux */
  5761. if (conn->throttle == 0 && conn->ssl == 0) {
  5762. off_t sf_offs = (off_t)offset;
  5763. ssize_t sf_sent;
  5764. int sf_file = fileno(filep->fp);
  5765. int loop_cnt = 0;
  5766. do {
  5767. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5768. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5769. size_t sf_tosend =
  5770. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5771. sf_sent =
  5772. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5773. if (sf_sent > 0) {
  5774. conn->num_bytes_sent += sf_sent;
  5775. len -= sf_sent;
  5776. offset += sf_sent;
  5777. } else if (loop_cnt == 0) {
  5778. /* This file can not be sent using sendfile.
  5779. * This might be the case for pseudo-files in the
  5780. * /sys/ and /proc/ file system.
  5781. * Use the regular user mode copy code instead. */
  5782. break;
  5783. } else if (sf_sent == 0) {
  5784. /* No error, but 0 bytes sent. May be EOF? */
  5785. return;
  5786. }
  5787. loop_cnt++;
  5788. } while ((len > 0) && (sf_sent >= 0));
  5789. if (sf_sent > 0) {
  5790. return; /* OK */
  5791. }
  5792. /* sf_sent<0 means error, thus fall back to the classic way */
  5793. /* This is always the case, if sf_file is not a "normal" file,
  5794. * e.g., for sending data from the output of a CGI process. */
  5795. offset = (int64_t)sf_offs;
  5796. }
  5797. #endif
  5798. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5799. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5800. send_http_error(
  5801. conn,
  5802. 500,
  5803. "%s",
  5804. "Error: Unable to access file at requested position.");
  5805. } else {
  5806. while (len > 0) {
  5807. /* Calculate how much to read from the file in the buffer */
  5808. to_read = sizeof(buf);
  5809. if ((int64_t)to_read > len) {
  5810. to_read = (int)len;
  5811. }
  5812. /* Read from file, exit the loop on error */
  5813. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5814. <= 0) {
  5815. break;
  5816. }
  5817. /* Send read bytes to the client, exit the loop on error */
  5818. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5819. != num_read) {
  5820. break;
  5821. }
  5822. /* Both read and were successful, adjust counters */
  5823. conn->num_bytes_sent += num_written;
  5824. len -= num_written;
  5825. }
  5826. }
  5827. }
  5828. }
  5829. static int
  5830. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5831. {
  5832. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5833. }
  5834. static void
  5835. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5836. {
  5837. if (filep != NULL && buf != NULL) {
  5838. mg_snprintf(NULL,
  5839. NULL, /* All calls to construct_etag use 64 byte buffer */
  5840. buf,
  5841. buf_len,
  5842. "\"%lx.%" INT64_FMT "\"",
  5843. (unsigned long)filep->last_modified,
  5844. filep->size);
  5845. }
  5846. }
  5847. static void
  5848. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5849. {
  5850. if (filep != NULL && filep->fp != NULL) {
  5851. #ifdef _WIN32
  5852. (void)conn; /* Unused. */
  5853. #else
  5854. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5855. mg_cry(conn,
  5856. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5857. __func__,
  5858. strerror(ERRNO));
  5859. }
  5860. #endif
  5861. }
  5862. }
  5863. static void
  5864. handle_static_file_request(struct mg_connection *conn,
  5865. const char *path,
  5866. struct file *filep,
  5867. const char *mime_type)
  5868. {
  5869. char date[64], lm[64], etag[64];
  5870. char range[128]; /* large enough, so there will be no overflow */
  5871. const char *msg = "OK", *hdr;
  5872. time_t curtime = time(NULL);
  5873. int64_t cl, r1, r2;
  5874. struct vec mime_vec;
  5875. int n, truncated;
  5876. char gz_path[PATH_MAX];
  5877. const char *encoding = "";
  5878. const char *cors1, *cors2, *cors3;
  5879. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5880. return;
  5881. }
  5882. if (mime_type == NULL) {
  5883. get_mime_type(conn->ctx, path, &mime_vec);
  5884. } else {
  5885. mime_vec.ptr = mime_type;
  5886. mime_vec.len = strlen(mime_type);
  5887. }
  5888. if (filep->size > INT64_MAX) {
  5889. send_http_error(conn,
  5890. 500,
  5891. "Error: File size is too large to send\n%" INT64_FMT,
  5892. filep->size);
  5893. }
  5894. cl = (int64_t)filep->size;
  5895. conn->status_code = 200;
  5896. range[0] = '\0';
  5897. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5898. * it's important to rewrite the filename after resolving
  5899. * the mime type from it, to preserve the actual file's type */
  5900. if (filep->gzipped) {
  5901. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5902. if (truncated) {
  5903. send_http_error(conn,
  5904. 500,
  5905. "Error: Path of zipped file too long (%s)",
  5906. path);
  5907. return;
  5908. }
  5909. path = gz_path;
  5910. encoding = "Content-Encoding: gzip\r\n";
  5911. }
  5912. if (!mg_fopen(conn, path, "rb", filep)) {
  5913. send_http_error(conn,
  5914. 500,
  5915. "Error: Cannot open file\nfopen(%s): %s",
  5916. path,
  5917. strerror(ERRNO));
  5918. return;
  5919. }
  5920. fclose_on_exec(filep, conn);
  5921. /* If Range: header specified, act accordingly */
  5922. r1 = r2 = 0;
  5923. hdr = mg_get_header(conn, "Range");
  5924. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5925. && r2 >= 0) {
  5926. /* actually, range requests don't play well with a pre-gzipped
  5927. * file (since the range is specified in the uncompressed space) */
  5928. if (filep->gzipped) {
  5929. send_http_error(
  5930. conn,
  5931. 501,
  5932. "%s",
  5933. "Error: Range requests in gzipped files are not supported");
  5934. mg_fclose(filep);
  5935. return;
  5936. }
  5937. conn->status_code = 206;
  5938. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  5939. mg_snprintf(conn,
  5940. NULL, /* range buffer is big enough */
  5941. range,
  5942. sizeof(range),
  5943. "Content-Range: bytes "
  5944. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5945. r1,
  5946. r1 + cl - 1,
  5947. filep->size);
  5948. msg = "Partial Content";
  5949. }
  5950. hdr = mg_get_header(conn, "Origin");
  5951. if (hdr) {
  5952. /* Cross-origin resource sharing (CORS), see
  5953. * http://www.html5rocks.com/en/tutorials/cors/,
  5954. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5955. * preflight is not supported for files. */
  5956. cors1 = "Access-Control-Allow-Origin: ";
  5957. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5958. cors3 = "\r\n";
  5959. } else {
  5960. cors1 = cors2 = cors3 = "";
  5961. }
  5962. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5963. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5964. gmt_time_string(date, sizeof(date), &curtime);
  5965. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5966. construct_etag(etag, sizeof(etag), filep);
  5967. (void)mg_printf(conn,
  5968. "HTTP/1.1 %d %s\r\n"
  5969. "%s%s%s"
  5970. "Date: %s\r\n",
  5971. conn->status_code,
  5972. msg,
  5973. cors1,
  5974. cors2,
  5975. cors3,
  5976. date);
  5977. send_static_cache_header(conn);
  5978. (void)mg_printf(conn,
  5979. "Last-Modified: %s\r\n"
  5980. "Etag: %s\r\n"
  5981. "Content-Type: %.*s\r\n"
  5982. "Content-Length: %" INT64_FMT "\r\n"
  5983. "Connection: %s\r\n"
  5984. "Accept-Ranges: bytes\r\n"
  5985. "%s%s\r\n",
  5986. lm,
  5987. etag,
  5988. (int)mime_vec.len,
  5989. mime_vec.ptr,
  5990. cl,
  5991. suggest_connection_header(conn),
  5992. range,
  5993. encoding);
  5994. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5995. send_file_data(conn, filep, r1, cl);
  5996. }
  5997. mg_fclose(filep);
  5998. }
  5999. #if !defined(NO_CACHING)
  6000. static void
  6001. handle_not_modified_static_file_request(struct mg_connection *conn,
  6002. struct file *filep)
  6003. {
  6004. char date[64], lm[64], etag[64];
  6005. time_t curtime = time(NULL);
  6006. if (conn == NULL || filep == NULL) {
  6007. return;
  6008. }
  6009. conn->status_code = 304;
  6010. gmt_time_string(date, sizeof(date), &curtime);
  6011. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  6012. construct_etag(etag, sizeof(etag), filep);
  6013. (void)mg_printf(conn,
  6014. "HTTP/1.1 %d %s\r\n"
  6015. "Date: %s\r\n",
  6016. conn->status_code,
  6017. mg_get_response_code_text(conn, conn->status_code),
  6018. date);
  6019. send_static_cache_header(conn);
  6020. (void)mg_printf(conn,
  6021. "Last-Modified: %s\r\n"
  6022. "Etag: %s\r\n"
  6023. "Connection: %s\r\n"
  6024. "\r\n",
  6025. lm,
  6026. etag,
  6027. suggest_connection_header(conn));
  6028. }
  6029. #endif
  6030. void
  6031. mg_send_file(struct mg_connection *conn, const char *path)
  6032. {
  6033. mg_send_mime_file(conn, path, NULL);
  6034. }
  6035. void
  6036. mg_send_mime_file(struct mg_connection *conn,
  6037. const char *path,
  6038. const char *mime_type)
  6039. {
  6040. struct file file = STRUCT_FILE_INITIALIZER;
  6041. if (mg_stat(conn, path, &file)) {
  6042. if (file.is_directory) {
  6043. if (!conn) {
  6044. return;
  6045. }
  6046. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6047. "yes")) {
  6048. handle_directory_request(conn, path);
  6049. } else {
  6050. send_http_error(conn,
  6051. 403,
  6052. "%s",
  6053. "Error: Directory listing denied");
  6054. }
  6055. } else {
  6056. handle_static_file_request(conn, path, &file, mime_type);
  6057. }
  6058. } else {
  6059. send_http_error(conn, 404, "%s", "Error: File not found");
  6060. }
  6061. }
  6062. /* For a given PUT path, create all intermediate subdirectories.
  6063. * Return 0 if the path itself is a directory.
  6064. * Return 1 if the path leads to a file.
  6065. * Return -1 for if the path is too long.
  6066. * Return -2 if path can not be created.
  6067. */
  6068. static int
  6069. put_dir(struct mg_connection *conn, const char *path)
  6070. {
  6071. char buf[PATH_MAX];
  6072. const char *s, *p;
  6073. struct file file = STRUCT_FILE_INITIALIZER;
  6074. size_t len;
  6075. int res = 1;
  6076. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6077. len = (size_t)(p - path);
  6078. if (len >= sizeof(buf)) {
  6079. /* path too long */
  6080. res = -1;
  6081. break;
  6082. }
  6083. memcpy(buf, path, len);
  6084. buf[len] = '\0';
  6085. /* Try to create intermediate directory */
  6086. DEBUG_TRACE("mkdir(%s)", buf);
  6087. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  6088. /* path does not exixt and can not be created */
  6089. res = -2;
  6090. break;
  6091. }
  6092. /* Is path itself a directory? */
  6093. if (p[1] == '\0') {
  6094. res = 0;
  6095. }
  6096. }
  6097. return res;
  6098. }
  6099. static void
  6100. remove_bad_file(const struct mg_connection *conn, const char *path)
  6101. {
  6102. int r = mg_remove(conn, path);
  6103. if (r != 0) {
  6104. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6105. }
  6106. }
  6107. long long
  6108. mg_store_body(struct mg_connection *conn, const char *path)
  6109. {
  6110. char buf[MG_BUF_LEN];
  6111. long long len = 0;
  6112. int ret, n;
  6113. struct file fi;
  6114. if (conn->consumed_content != 0) {
  6115. mg_cry(conn, "%s: Contents already consumed", __func__);
  6116. return -11;
  6117. }
  6118. ret = put_dir(conn, path);
  6119. if (ret < 0) {
  6120. /* -1 for path too long,
  6121. * -2 for path can not be created. */
  6122. return ret;
  6123. }
  6124. if (ret != 1) {
  6125. /* Return 0 means, path itself is a directory. */
  6126. return 0;
  6127. }
  6128. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6129. return -12;
  6130. }
  6131. ret = mg_read(conn, buf, sizeof(buf));
  6132. while (ret > 0) {
  6133. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6134. if (n != ret) {
  6135. mg_fclose(&fi);
  6136. remove_bad_file(conn, path);
  6137. return -13;
  6138. }
  6139. ret = mg_read(conn, buf, sizeof(buf));
  6140. }
  6141. /* TODO: mg_fclose should return an error,
  6142. * and every caller should check and handle it. */
  6143. if (fclose(fi.fp) != 0) {
  6144. remove_bad_file(conn, path);
  6145. return -14;
  6146. }
  6147. return len;
  6148. }
  6149. /* Parse HTTP headers from the given buffer, advance buf pointer
  6150. * to the point where parsing stopped.
  6151. * All parameters must be valid pointers (not NULL).
  6152. * Return <0 on error. */
  6153. static int
  6154. parse_http_headers(char **buf, struct mg_request_info *ri)
  6155. {
  6156. int i;
  6157. ri->num_headers = 0;
  6158. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6159. char *dp = *buf;
  6160. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6161. dp++;
  6162. }
  6163. if (dp == *buf) {
  6164. /* End of headers reached. */
  6165. break;
  6166. }
  6167. if (*dp != ':') {
  6168. /* This is not a valid field. */
  6169. return -1;
  6170. }
  6171. /* End of header key (*dp == ':') */
  6172. /* Truncate here and set the key name */
  6173. *dp = 0;
  6174. ri->http_headers[i].name = *buf;
  6175. do {
  6176. dp++;
  6177. } while (*dp == ' ');
  6178. /* The rest of the line is the value */
  6179. ri->http_headers[i].value = dp;
  6180. *buf = dp + strcspn(dp, "\r\n");
  6181. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6182. *buf = NULL;
  6183. }
  6184. ri->num_headers = i + 1;
  6185. if (*buf) {
  6186. (*buf)[0] = 0;
  6187. (*buf)[1] = 0;
  6188. *buf += 2;
  6189. } else {
  6190. *buf = dp;
  6191. break;
  6192. }
  6193. if ((*buf)[0] == '\r') {
  6194. /* This is the end of the header */
  6195. break;
  6196. }
  6197. }
  6198. return ri->num_headers;
  6199. }
  6200. static int
  6201. is_valid_http_method(const char *method)
  6202. {
  6203. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6204. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6205. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6206. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6207. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6208. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6209. /* TRACE method (RFC 2616) is not supported for security reasons */
  6210. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6211. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6212. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6213. /* Unsupported WEBDAV Methods: */
  6214. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6215. /* + 11 methods from RFC 3253 */
  6216. /* ORDERPATCH (RFC 3648) */
  6217. /* ACL (RFC 3744) */
  6218. /* SEARCH (RFC 5323) */
  6219. /* + MicroSoft extensions
  6220. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6221. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6222. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6223. }
  6224. /* Parse HTTP request, fill in mg_request_info structure.
  6225. * This function modifies the buffer by NUL-terminating
  6226. * HTTP request components, header names and header values.
  6227. * Parameters:
  6228. * buf (in/out): pointer to the HTTP header to parse and split
  6229. * len (in): length of HTTP header buffer
  6230. * re (out): parsed header as mg_request_info
  6231. * buf and ri must be valid pointers (not NULL), len>0.
  6232. * Returns <0 on error. */
  6233. static int
  6234. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6235. {
  6236. int is_request, request_length;
  6237. char *start_line;
  6238. request_length = get_request_len(buf, len);
  6239. if (request_length > 0) {
  6240. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6241. * remote_port */
  6242. ri->remote_user = ri->request_method = ri->request_uri =
  6243. ri->http_version = NULL;
  6244. ri->num_headers = 0;
  6245. buf[request_length - 1] = '\0';
  6246. /* RFC says that all initial whitespaces should be ingored */
  6247. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6248. buf++;
  6249. }
  6250. start_line = skip(&buf, "\r\n");
  6251. ri->request_method = skip(&start_line, " ");
  6252. ri->request_uri = skip(&start_line, " ");
  6253. ri->http_version = start_line;
  6254. /* HTTP message could be either HTTP request:
  6255. * "GET / HTTP/1.0 ..."
  6256. * or a HTTP response:
  6257. * "HTTP/1.0 200 OK ..."
  6258. * otherwise it is invalid.
  6259. */
  6260. is_request = is_valid_http_method(ri->request_method);
  6261. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6262. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6263. /* Not a valid request or response: invalid */
  6264. return -1;
  6265. }
  6266. if (is_request) {
  6267. ri->http_version += 5;
  6268. }
  6269. if (parse_http_headers(&buf, ri) < 0) {
  6270. /* Error while parsing headers */
  6271. return -1;
  6272. }
  6273. }
  6274. return request_length;
  6275. }
  6276. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6277. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6278. * buffer (which marks the end of HTTP request). Buffer buf may already
  6279. * have some data. The length of the data is stored in nread.
  6280. * Upon every read operation, increase nread by the number of bytes read. */
  6281. static int
  6282. read_request(FILE *fp,
  6283. struct mg_connection *conn,
  6284. char *buf,
  6285. int bufsiz,
  6286. int *nread)
  6287. {
  6288. int request_len, n = 0;
  6289. struct timespec last_action_time;
  6290. double request_timeout;
  6291. if (!conn) {
  6292. return 0;
  6293. }
  6294. memset(&last_action_time, 0, sizeof(last_action_time));
  6295. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6296. /* value of request_timeout is in seconds, config in milliseconds */
  6297. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6298. } else {
  6299. request_timeout = -1.0;
  6300. }
  6301. request_len = get_request_len(buf, *nread);
  6302. /* first time reading from this connection */
  6303. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6304. while (
  6305. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6306. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6307. <= request_timeout) || (request_timeout < 0))
  6308. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6309. > 0)) {
  6310. *nread += n;
  6311. /* assert(*nread <= bufsiz); */
  6312. if (*nread > bufsiz) {
  6313. return -2;
  6314. }
  6315. request_len = get_request_len(buf, *nread);
  6316. if (request_timeout > 0.0) {
  6317. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6318. }
  6319. }
  6320. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6321. }
  6322. #if !defined(NO_FILES)
  6323. /* For given directory path, substitute it to valid index file.
  6324. * Return 1 if index file has been found, 0 if not found.
  6325. * If the file is found, it's stats is returned in stp. */
  6326. static int
  6327. substitute_index_file(struct mg_connection *conn,
  6328. char *path,
  6329. size_t path_len,
  6330. struct file *filep)
  6331. {
  6332. if (conn && conn->ctx) {
  6333. const char *list = conn->ctx->config[INDEX_FILES];
  6334. struct file file = STRUCT_FILE_INITIALIZER;
  6335. struct vec filename_vec;
  6336. size_t n = strlen(path);
  6337. int found = 0;
  6338. /* The 'path' given to us points to the directory. Remove all trailing
  6339. * directory separator characters from the end of the path, and
  6340. * then append single directory separator character. */
  6341. while (n > 0 && path[n - 1] == '/') {
  6342. n--;
  6343. }
  6344. path[n] = '/';
  6345. /* Traverse index files list. For each entry, append it to the given
  6346. * path and see if the file exists. If it exists, break the loop */
  6347. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6348. /* Ignore too long entries that may overflow path buffer */
  6349. if (filename_vec.len > path_len - (n + 2)) {
  6350. continue;
  6351. }
  6352. /* Prepare full path to the index file */
  6353. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6354. /* Does it exist? */
  6355. if (mg_stat(conn, path, &file)) {
  6356. /* Yes it does, break the loop */
  6357. *filep = file;
  6358. found = 1;
  6359. break;
  6360. }
  6361. }
  6362. /* If no index file exists, restore directory path */
  6363. if (!found) {
  6364. path[n] = '\0';
  6365. }
  6366. return found;
  6367. }
  6368. return 0;
  6369. }
  6370. #endif
  6371. #if !defined(NO_CACHING)
  6372. /* Return True if we should reply 304 Not Modified. */
  6373. static int
  6374. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6375. {
  6376. char etag[64];
  6377. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6378. const char *inm = mg_get_header(conn, "If-None-Match");
  6379. construct_etag(etag, sizeof(etag), filep);
  6380. if (!filep) {
  6381. return 0;
  6382. }
  6383. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6384. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6385. }
  6386. #endif /* !NO_CACHING */
  6387. #if !defined(NO_CGI) || !defined(NO_FILES)
  6388. static int
  6389. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6390. {
  6391. const char *expect, *body;
  6392. char buf[MG_BUF_LEN];
  6393. int to_read, nread, success = 0;
  6394. int64_t buffered_len;
  6395. double timeout = -1.0;
  6396. if (!conn) {
  6397. return 0;
  6398. }
  6399. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6400. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6401. }
  6402. expect = mg_get_header(conn, "Expect");
  6403. /* assert(fp != NULL); */
  6404. if (!fp) {
  6405. send_http_error(conn, 500, "%s", "Error: NULL File");
  6406. return 0;
  6407. }
  6408. if (conn->content_len == -1 && !conn->is_chunked) {
  6409. /* Content length is not specified by the client. */
  6410. send_http_error(conn,
  6411. 411,
  6412. "%s",
  6413. "Error: Client did not specify content length");
  6414. } else if ((expect != NULL)
  6415. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6416. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6417. send_http_error(conn,
  6418. 417,
  6419. "Error: Can not fulfill expectation %s",
  6420. expect);
  6421. } else {
  6422. if (expect != NULL) {
  6423. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6424. conn->status_code = 100;
  6425. } else {
  6426. conn->status_code = 200;
  6427. }
  6428. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6429. - conn->consumed_content;
  6430. /* assert(buffered_len >= 0); */
  6431. /* assert(conn->consumed_content == 0); */
  6432. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6433. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6434. return 0;
  6435. }
  6436. if (buffered_len > 0) {
  6437. if ((int64_t)buffered_len > conn->content_len) {
  6438. buffered_len = (int)conn->content_len;
  6439. }
  6440. body = conn->buf + conn->request_len + conn->consumed_content;
  6441. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6442. conn->consumed_content += buffered_len;
  6443. }
  6444. nread = 0;
  6445. while (conn->consumed_content < conn->content_len) {
  6446. to_read = sizeof(buf);
  6447. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6448. to_read = (int)(conn->content_len - conn->consumed_content);
  6449. }
  6450. nread = pull(NULL, conn, buf, to_read, timeout);
  6451. if (nread <= 0
  6452. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6453. break;
  6454. }
  6455. conn->consumed_content += nread;
  6456. }
  6457. if (conn->consumed_content == conn->content_len) {
  6458. success = (nread >= 0);
  6459. }
  6460. /* Each error code path in this function must send an error */
  6461. if (!success) {
  6462. /* NOTE: Maybe some data has already been sent. */
  6463. /* TODO (low): If some data has been sent, a correct error
  6464. * reply can no longer be sent, so just close the connection */
  6465. send_http_error(conn, 500, "%s", "");
  6466. }
  6467. }
  6468. return success;
  6469. }
  6470. #endif
  6471. #if !defined(NO_CGI)
  6472. /* This structure helps to create an environment for the spawned CGI program.
  6473. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6474. * last element must be NULL.
  6475. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6476. * strings must reside in a contiguous buffer. The end of the buffer is
  6477. * marked by two '\0' characters.
  6478. * We satisfy both worlds: we create an envp array (which is vars), all
  6479. * entries are actually pointers inside buf. */
  6480. struct cgi_environment {
  6481. struct mg_connection *conn;
  6482. /* Data block */
  6483. char *buf; /* Environment buffer */
  6484. size_t buflen; /* Space available in buf */
  6485. size_t bufused; /* Space taken in buf */
  6486. /* Index block */
  6487. char **var; /* char **envp */
  6488. size_t varlen; /* Number of variables available in var */
  6489. size_t varused; /* Number of variables stored in var */
  6490. };
  6491. static void addenv(struct cgi_environment *env,
  6492. PRINTF_FORMAT_STRING(const char *fmt),
  6493. ...) PRINTF_ARGS(2, 3);
  6494. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6495. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6496. static void
  6497. addenv(struct cgi_environment *env, const char *fmt, ...)
  6498. {
  6499. size_t n, space;
  6500. int truncated;
  6501. char *added;
  6502. va_list ap;
  6503. /* Calculate how much space is left in the buffer */
  6504. space = (env->buflen - env->bufused);
  6505. /* Calculate an estimate for the required space */
  6506. n = strlen(fmt) + 2 + 128;
  6507. do {
  6508. if (space <= n) {
  6509. /* Allocate new buffer */
  6510. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6511. added = (char *)mg_realloc(env->buf, n);
  6512. if (!added) {
  6513. /* Out of memory */
  6514. mg_cry(env->conn,
  6515. "%s: Cannot allocate memory for CGI variable [%s]",
  6516. __func__,
  6517. fmt);
  6518. return;
  6519. }
  6520. env->buf = added;
  6521. env->buflen = n;
  6522. space = (env->buflen - env->bufused);
  6523. }
  6524. /* Make a pointer to the free space int the buffer */
  6525. added = env->buf + env->bufused;
  6526. /* Copy VARIABLE=VALUE\0 string into the free space */
  6527. va_start(ap, fmt);
  6528. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6529. va_end(ap);
  6530. /* Do not add truncated strings to the environment */
  6531. if (truncated) {
  6532. /* Reallocate the buffer */
  6533. space = 0;
  6534. n = 1;
  6535. }
  6536. } while (truncated);
  6537. /* Calculate number of bytes added to the environment */
  6538. n = strlen(added) + 1;
  6539. env->bufused += n;
  6540. /* Now update the variable index */
  6541. space = (env->varlen - env->varused);
  6542. if (space < 2) {
  6543. mg_cry(env->conn,
  6544. "%s: Cannot register CGI variable [%s]",
  6545. __func__,
  6546. fmt);
  6547. return;
  6548. }
  6549. /* Append a pointer to the added string into the envp array */
  6550. env->var[env->varused] = added;
  6551. env->varused++;
  6552. }
  6553. static void
  6554. prepare_cgi_environment(struct mg_connection *conn,
  6555. const char *prog,
  6556. struct cgi_environment *env)
  6557. {
  6558. const char *s;
  6559. struct vec var_vec;
  6560. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6561. int i, truncated;
  6562. if (conn == NULL || prog == NULL || env == NULL) {
  6563. return;
  6564. }
  6565. env->conn = conn;
  6566. env->buflen = CGI_ENVIRONMENT_SIZE;
  6567. env->bufused = 0;
  6568. env->buf = (char *)mg_malloc(env->buflen);
  6569. env->varlen = MAX_CGI_ENVIR_VARS;
  6570. env->varused = 0;
  6571. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6572. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6573. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6574. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6575. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6576. /* Prepare the environment block */
  6577. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6578. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6579. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6580. #if defined(USE_IPV6)
  6581. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6582. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6583. } else
  6584. #endif
  6585. {
  6586. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6587. }
  6588. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6589. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6590. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6591. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6592. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6593. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6594. /* SCRIPT_NAME */
  6595. addenv(env,
  6596. "SCRIPT_NAME=%.*s",
  6597. (int)strlen(conn->request_info.local_uri)
  6598. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6599. conn->request_info.local_uri);
  6600. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6601. if (conn->path_info == NULL) {
  6602. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6603. } else {
  6604. addenv(env,
  6605. "PATH_TRANSLATED=%s%s",
  6606. conn->ctx->config[DOCUMENT_ROOT],
  6607. conn->path_info);
  6608. }
  6609. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6610. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6611. addenv(env, "CONTENT_TYPE=%s", s);
  6612. }
  6613. if (conn->request_info.query_string != NULL) {
  6614. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6615. }
  6616. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6617. addenv(env, "CONTENT_LENGTH=%s", s);
  6618. }
  6619. if ((s = getenv("PATH")) != NULL) {
  6620. addenv(env, "PATH=%s", s);
  6621. }
  6622. if (conn->path_info != NULL) {
  6623. addenv(env, "PATH_INFO=%s", conn->path_info);
  6624. }
  6625. if (conn->status_code > 0) {
  6626. /* CGI error handler should show the status code */
  6627. addenv(env, "STATUS=%d", conn->status_code);
  6628. }
  6629. #if defined(_WIN32)
  6630. if ((s = getenv("COMSPEC")) != NULL) {
  6631. addenv(env, "COMSPEC=%s", s);
  6632. }
  6633. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6634. addenv(env, "SYSTEMROOT=%s", s);
  6635. }
  6636. if ((s = getenv("SystemDrive")) != NULL) {
  6637. addenv(env, "SystemDrive=%s", s);
  6638. }
  6639. if ((s = getenv("ProgramFiles")) != NULL) {
  6640. addenv(env, "ProgramFiles=%s", s);
  6641. }
  6642. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6643. addenv(env, "ProgramFiles(x86)=%s", s);
  6644. }
  6645. #else
  6646. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6647. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6648. }
  6649. #endif /* _WIN32 */
  6650. if ((s = getenv("PERLLIB")) != NULL) {
  6651. addenv(env, "PERLLIB=%s", s);
  6652. }
  6653. if (conn->request_info.remote_user != NULL) {
  6654. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6655. addenv(env, "%s", "AUTH_TYPE=Digest");
  6656. }
  6657. /* Add all headers as HTTP_* variables */
  6658. for (i = 0; i < conn->request_info.num_headers; i++) {
  6659. (void)mg_snprintf(conn,
  6660. &truncated,
  6661. http_var_name,
  6662. sizeof(http_var_name),
  6663. "HTTP_%s",
  6664. conn->request_info.http_headers[i].name);
  6665. if (truncated) {
  6666. mg_cry(conn,
  6667. "%s: HTTP header variable too long [%s]",
  6668. __func__,
  6669. conn->request_info.http_headers[i].name);
  6670. continue;
  6671. }
  6672. /* Convert variable name into uppercase, and change - to _ */
  6673. for (p = http_var_name; *p != '\0'; p++) {
  6674. if (*p == '-') {
  6675. *p = '_';
  6676. }
  6677. *p = (char)toupper(*(unsigned char *)p);
  6678. }
  6679. addenv(env,
  6680. "%s=%s",
  6681. http_var_name,
  6682. conn->request_info.http_headers[i].value);
  6683. }
  6684. /* Add user-specified variables */
  6685. s = conn->ctx->config[CGI_ENVIRONMENT];
  6686. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6687. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6688. }
  6689. env->var[env->varused] = NULL;
  6690. env->buf[env->bufused] = '\0';
  6691. }
  6692. static void
  6693. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6694. {
  6695. char *buf;
  6696. size_t buflen;
  6697. int headers_len, data_len, i, truncated;
  6698. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6699. const char *status, *status_text, *connection_state;
  6700. char *pbuf, dir[PATH_MAX], *p;
  6701. struct mg_request_info ri;
  6702. struct cgi_environment blk;
  6703. FILE *in = NULL, *out = NULL, *err = NULL;
  6704. struct file fout = STRUCT_FILE_INITIALIZER;
  6705. pid_t pid = (pid_t)-1;
  6706. if (conn == NULL) {
  6707. return;
  6708. }
  6709. buf = NULL;
  6710. buflen = 16384;
  6711. prepare_cgi_environment(conn, prog, &blk);
  6712. /* CGI must be executed in its own directory. 'dir' must point to the
  6713. * directory containing executable program, 'p' must point to the
  6714. * executable program name relative to 'dir'. */
  6715. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6716. if (truncated) {
  6717. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6718. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6719. goto done;
  6720. }
  6721. if ((p = strrchr(dir, '/')) != NULL) {
  6722. *p++ = '\0';
  6723. } else {
  6724. dir[0] = '.', dir[1] = '\0';
  6725. p = (char *)prog;
  6726. }
  6727. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6728. status = strerror(ERRNO);
  6729. mg_cry(conn,
  6730. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6731. prog,
  6732. status);
  6733. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6734. goto done;
  6735. }
  6736. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6737. if (pid == (pid_t)-1) {
  6738. status = strerror(ERRNO);
  6739. mg_cry(conn,
  6740. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6741. prog,
  6742. status);
  6743. send_http_error(conn,
  6744. 500,
  6745. "Error: Cannot spawn CGI process [%s]: %s",
  6746. prog,
  6747. status);
  6748. goto done;
  6749. }
  6750. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6751. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6752. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6753. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6754. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6755. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6756. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6757. /* Parent closes only one side of the pipes.
  6758. * If we don't mark them as closed, close() attempt before
  6759. * return from this function throws an exception on Windows.
  6760. * Windows does not like when closed descriptor is closed again. */
  6761. (void)close(fdin[0]);
  6762. (void)close(fdout[1]);
  6763. (void)close(fderr[1]);
  6764. fdin[0] = fdout[1] = fderr[1] = -1;
  6765. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6766. status = strerror(ERRNO);
  6767. mg_cry(conn,
  6768. "Error: CGI program \"%s\": Can not open stdin: %s",
  6769. prog,
  6770. status);
  6771. send_http_error(conn,
  6772. 500,
  6773. "Error: CGI can not open fdin\nfopen: %s",
  6774. status);
  6775. goto done;
  6776. }
  6777. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6778. status = strerror(ERRNO);
  6779. mg_cry(conn,
  6780. "Error: CGI program \"%s\": Can not open stdout: %s",
  6781. prog,
  6782. status);
  6783. send_http_error(conn,
  6784. 500,
  6785. "Error: CGI can not open fdout\nfopen: %s",
  6786. status);
  6787. goto done;
  6788. }
  6789. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6790. status = strerror(ERRNO);
  6791. mg_cry(conn,
  6792. "Error: CGI program \"%s\": Can not open stderr: %s",
  6793. prog,
  6794. status);
  6795. send_http_error(conn,
  6796. 500,
  6797. "Error: CGI can not open fdout\nfopen: %s",
  6798. status);
  6799. goto done;
  6800. }
  6801. setbuf(in, NULL);
  6802. setbuf(out, NULL);
  6803. setbuf(err, NULL);
  6804. fout.fp = out;
  6805. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6806. /* This is a POST/PUT request, or another request with body data. */
  6807. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6808. /* Error sending the body data */
  6809. mg_cry(conn,
  6810. "Error: CGI program \"%s\": Forward body data failed",
  6811. prog);
  6812. goto done;
  6813. }
  6814. }
  6815. /* Close so child gets an EOF. */
  6816. fclose(in);
  6817. in = NULL;
  6818. fdin[1] = -1;
  6819. /* Now read CGI reply into a buffer. We need to set correct
  6820. * status code, thus we need to see all HTTP headers first.
  6821. * Do not send anything back to client, until we buffer in all
  6822. * HTTP headers. */
  6823. data_len = 0;
  6824. buf = (char *)mg_malloc(buflen);
  6825. if (buf == NULL) {
  6826. send_http_error(conn,
  6827. 500,
  6828. "Error: Not enough memory for CGI buffer (%u bytes)",
  6829. (unsigned int)buflen);
  6830. mg_cry(conn,
  6831. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6832. "bytes)",
  6833. prog,
  6834. (unsigned int)buflen);
  6835. goto done;
  6836. }
  6837. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6838. if (headers_len <= 0) {
  6839. /* Could not parse the CGI response. Check if some error message on
  6840. * stderr. */
  6841. i = pull_all(err, conn, buf, (int)buflen);
  6842. if (i > 0) {
  6843. mg_cry(conn,
  6844. "Error: CGI program \"%s\" sent error "
  6845. "message: [%.*s]",
  6846. prog,
  6847. i,
  6848. buf);
  6849. send_http_error(conn,
  6850. 500,
  6851. "Error: CGI program \"%s\" sent error "
  6852. "message: [%.*s]",
  6853. prog,
  6854. i,
  6855. buf);
  6856. } else {
  6857. mg_cry(conn,
  6858. "Error: CGI program sent malformed or too big "
  6859. "(>%u bytes) HTTP headers: [%.*s]",
  6860. (unsigned)buflen,
  6861. data_len,
  6862. buf);
  6863. send_http_error(conn,
  6864. 500,
  6865. "Error: CGI program sent malformed or too big "
  6866. "(>%u bytes) HTTP headers: [%.*s]",
  6867. (unsigned)buflen,
  6868. data_len,
  6869. buf);
  6870. }
  6871. goto done;
  6872. }
  6873. pbuf = buf;
  6874. buf[headers_len - 1] = '\0';
  6875. parse_http_headers(&pbuf, &ri);
  6876. /* Make up and send the status line */
  6877. status_text = "OK";
  6878. if ((status = get_header(&ri, "Status")) != NULL) {
  6879. conn->status_code = atoi(status);
  6880. status_text = status;
  6881. while (isdigit(*(const unsigned char *)status_text)
  6882. || *status_text == ' ') {
  6883. status_text++;
  6884. }
  6885. } else if (get_header(&ri, "Location") != NULL) {
  6886. conn->status_code = 302;
  6887. } else {
  6888. conn->status_code = 200;
  6889. }
  6890. connection_state = get_header(&ri, "Connection");
  6891. if (!header_has_option(connection_state, "keep-alive")) {
  6892. conn->must_close = 1;
  6893. }
  6894. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6895. /* Send headers */
  6896. for (i = 0; i < ri.num_headers; i++) {
  6897. mg_printf(conn,
  6898. "%s: %s\r\n",
  6899. ri.http_headers[i].name,
  6900. ri.http_headers[i].value);
  6901. }
  6902. mg_write(conn, "\r\n", 2);
  6903. /* Send chunk of data that may have been read after the headers */
  6904. conn->num_bytes_sent +=
  6905. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6906. /* Read the rest of CGI output and send to the client */
  6907. send_file_data(conn, &fout, 0, INT64_MAX);
  6908. done:
  6909. mg_free(blk.var);
  6910. mg_free(blk.buf);
  6911. if (pid != (pid_t)-1) {
  6912. kill(pid, SIGKILL);
  6913. #if !defined(_WIN32)
  6914. {
  6915. int st;
  6916. while (waitpid(pid, &st, 0) != -1)
  6917. ; /* clean zombies */
  6918. }
  6919. #endif
  6920. }
  6921. if (fdin[0] != -1) {
  6922. close(fdin[0]);
  6923. }
  6924. if (fdout[1] != -1) {
  6925. close(fdout[1]);
  6926. }
  6927. if (in != NULL) {
  6928. fclose(in);
  6929. } else if (fdin[1] != -1) {
  6930. close(fdin[1]);
  6931. }
  6932. if (out != NULL) {
  6933. fclose(out);
  6934. } else if (fdout[0] != -1) {
  6935. close(fdout[0]);
  6936. }
  6937. if (err != NULL) {
  6938. fclose(err);
  6939. } else if (fderr[0] != -1) {
  6940. close(fderr[0]);
  6941. }
  6942. if (buf != NULL) {
  6943. mg_free(buf);
  6944. }
  6945. }
  6946. #endif /* !NO_CGI */
  6947. #if !defined(NO_FILES)
  6948. static void
  6949. mkcol(struct mg_connection *conn, const char *path)
  6950. {
  6951. int rc, body_len;
  6952. struct de de;
  6953. char date[64];
  6954. time_t curtime = time(NULL);
  6955. if (conn == NULL) {
  6956. return;
  6957. }
  6958. /* TODO (mid): Check the send_http_error situations in this function */
  6959. memset(&de.file, 0, sizeof(de.file));
  6960. if (!mg_stat(conn, path, &de.file)) {
  6961. mg_cry(conn,
  6962. "%s: mg_stat(%s) failed: %s",
  6963. __func__,
  6964. path,
  6965. strerror(ERRNO));
  6966. }
  6967. if (de.file.last_modified) {
  6968. /* TODO (high): This check does not seem to make any sense ! */
  6969. send_http_error(
  6970. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6971. return;
  6972. }
  6973. body_len = conn->data_len - conn->request_len;
  6974. if (body_len > 0) {
  6975. send_http_error(
  6976. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6977. return;
  6978. }
  6979. rc = mg_mkdir(conn, path, 0755);
  6980. if (rc == 0) {
  6981. conn->status_code = 201;
  6982. gmt_time_string(date, sizeof(date), &curtime);
  6983. mg_printf(conn,
  6984. "HTTP/1.1 %d Created\r\n"
  6985. "Date: %s\r\n",
  6986. conn->status_code,
  6987. date);
  6988. send_static_cache_header(conn);
  6989. mg_printf(conn,
  6990. "Content-Length: 0\r\n"
  6991. "Connection: %s\r\n\r\n",
  6992. suggest_connection_header(conn));
  6993. } else if (rc == -1) {
  6994. if (errno == EEXIST) {
  6995. send_http_error(
  6996. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6997. } else if (errno == EACCES) {
  6998. send_http_error(
  6999. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7000. } else if (errno == ENOENT) {
  7001. send_http_error(
  7002. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7003. } else {
  7004. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7005. }
  7006. }
  7007. }
  7008. static void
  7009. put_file(struct mg_connection *conn, const char *path)
  7010. {
  7011. struct file file = STRUCT_FILE_INITIALIZER;
  7012. const char *range;
  7013. int64_t r1, r2;
  7014. int rc;
  7015. char date[64];
  7016. time_t curtime = time(NULL);
  7017. if (conn == NULL) {
  7018. return;
  7019. }
  7020. if (mg_stat(conn, path, &file)) {
  7021. /* File already exists */
  7022. conn->status_code = 200;
  7023. if (file.is_directory) {
  7024. /* This is an already existing directory,
  7025. * so there is nothing to do for the server. */
  7026. rc = 0;
  7027. } else {
  7028. /* File exists and is not a directory. */
  7029. /* Can it be replaced? */
  7030. if (file.membuf != NULL) {
  7031. /* This is an "in-memory" file, that can not be replaced */
  7032. send_http_error(
  7033. conn,
  7034. 405,
  7035. "Error: Put not possible\nReplacing %s is not supported",
  7036. path);
  7037. return;
  7038. }
  7039. /* Check if the server may write this file */
  7040. if (access(path, W_OK) == 0) {
  7041. /* Access granted */
  7042. conn->status_code = 200;
  7043. rc = 1;
  7044. } else {
  7045. send_http_error(
  7046. conn,
  7047. 403,
  7048. "Error: Put not possible\nReplacing %s is not allowed",
  7049. path);
  7050. return;
  7051. }
  7052. }
  7053. } else {
  7054. /* File should be created */
  7055. conn->status_code = 201;
  7056. rc = put_dir(conn, path);
  7057. }
  7058. if (rc == 0) {
  7059. /* put_dir returns 0 if path is a directory */
  7060. gmt_time_string(date, sizeof(date), &curtime);
  7061. mg_printf(conn,
  7062. "HTTP/1.1 %d %s\r\n",
  7063. conn->status_code,
  7064. mg_get_response_code_text(NULL, conn->status_code));
  7065. send_no_cache_header(conn);
  7066. mg_printf(conn,
  7067. "Date: %s\r\n"
  7068. "Content-Length: 0\r\n"
  7069. "Connection: %s\r\n\r\n",
  7070. date,
  7071. suggest_connection_header(conn));
  7072. /* Request to create a directory has been fulfilled successfully.
  7073. * No need to put a file. */
  7074. return;
  7075. }
  7076. if (rc == -1) {
  7077. /* put_dir returns -1 if the path is too long */
  7078. send_http_error(conn,
  7079. 414,
  7080. "Error: Path too long\nput_dir(%s): %s",
  7081. path,
  7082. strerror(ERRNO));
  7083. return;
  7084. }
  7085. if (rc == -2) {
  7086. /* put_dir returns -2 if the directory can not be created */
  7087. send_http_error(conn,
  7088. 500,
  7089. "Error: Can not create directory\nput_dir(%s): %s",
  7090. path,
  7091. strerror(ERRNO));
  7092. return;
  7093. }
  7094. /* A file should be created or overwritten. */
  7095. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7096. mg_fclose(&file);
  7097. send_http_error(conn,
  7098. 500,
  7099. "Error: Can not create file\nfopen(%s): %s",
  7100. path,
  7101. strerror(ERRNO));
  7102. return;
  7103. }
  7104. fclose_on_exec(&file, conn);
  7105. range = mg_get_header(conn, "Content-Range");
  7106. r1 = r2 = 0;
  7107. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7108. conn->status_code = 206; /* Partial content */
  7109. fseeko(file.fp, r1, SEEK_SET);
  7110. }
  7111. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7112. /* forward_body_data failed.
  7113. * The error code has already been sent to the client,
  7114. * and conn->status_code is already set. */
  7115. mg_fclose(&file);
  7116. return;
  7117. }
  7118. gmt_time_string(date, sizeof(date), &curtime);
  7119. mg_printf(conn,
  7120. "HTTP/1.1 %d %s\r\n",
  7121. conn->status_code,
  7122. mg_get_response_code_text(NULL, conn->status_code));
  7123. send_no_cache_header(conn);
  7124. mg_printf(conn,
  7125. "Date: %s\r\n"
  7126. "Content-Length: 0\r\n"
  7127. "Connection: %s\r\n\r\n",
  7128. date,
  7129. suggest_connection_header(conn));
  7130. mg_fclose(&file);
  7131. }
  7132. static void
  7133. delete_file(struct mg_connection *conn, const char *path)
  7134. {
  7135. struct de de;
  7136. memset(&de.file, 0, sizeof(de.file));
  7137. if (!mg_stat(conn, path, &de.file)) {
  7138. /* mg_stat returns 0 if the file does not exist */
  7139. send_http_error(conn,
  7140. 404,
  7141. "Error: Cannot delete file\nFile %s not found",
  7142. path);
  7143. return;
  7144. }
  7145. if (de.file.membuf != NULL) {
  7146. /* the file is cached in memory */
  7147. send_http_error(
  7148. conn,
  7149. 405,
  7150. "Error: Delete not possible\nDeleting %s is not supported",
  7151. path);
  7152. return;
  7153. }
  7154. if (de.file.is_directory) {
  7155. if (remove_directory(conn, path)) {
  7156. /* Delete is successful: Return 204 without content. */
  7157. send_http_error(conn, 204, "%s", "");
  7158. } else {
  7159. /* Delete is not successful: Return 500 (Server error). */
  7160. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7161. }
  7162. return;
  7163. }
  7164. /* This is an existing file (not a directory).
  7165. * Check if write permission is granted. */
  7166. if (access(path, W_OK) != 0) {
  7167. /* File is read only */
  7168. send_http_error(
  7169. conn,
  7170. 403,
  7171. "Error: Delete not possible\nDeleting %s is not allowed",
  7172. path);
  7173. return;
  7174. }
  7175. /* Try to delete it. */
  7176. if (mg_remove(conn, path) == 0) {
  7177. /* Delete was successful: Return 204 without content. */
  7178. send_http_error(conn, 204, "%s", "");
  7179. } else {
  7180. /* Delete not successful (file locked). */
  7181. send_http_error(conn,
  7182. 423,
  7183. "Error: Cannot delete file\nremove(%s): %s",
  7184. path,
  7185. strerror(ERRNO));
  7186. }
  7187. }
  7188. #endif /* !NO_FILES */
  7189. static void
  7190. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7191. static void
  7192. do_ssi_include(struct mg_connection *conn,
  7193. const char *ssi,
  7194. char *tag,
  7195. int include_level)
  7196. {
  7197. char file_name[MG_BUF_LEN], path[512], *p;
  7198. struct file file = STRUCT_FILE_INITIALIZER;
  7199. size_t len;
  7200. int truncated = 0;
  7201. if (conn == NULL) {
  7202. return;
  7203. }
  7204. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7205. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7206. * always < MG_BUF_LEN. */
  7207. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7208. /* File name is relative to the webserver root */
  7209. file_name[511] = 0;
  7210. (void)mg_snprintf(conn,
  7211. &truncated,
  7212. path,
  7213. sizeof(path),
  7214. "%s/%s",
  7215. conn->ctx->config[DOCUMENT_ROOT],
  7216. file_name);
  7217. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7218. /* File name is relative to the webserver working directory
  7219. * or it is absolute system path */
  7220. file_name[511] = 0;
  7221. (void)
  7222. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7223. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7224. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7225. /* File name is relative to the currect document */
  7226. file_name[511] = 0;
  7227. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7228. if (!truncated) {
  7229. if ((p = strrchr(path, '/')) != NULL) {
  7230. p[1] = '\0';
  7231. }
  7232. len = strlen(path);
  7233. (void)mg_snprintf(conn,
  7234. &truncated,
  7235. path + len,
  7236. sizeof(path) - len,
  7237. "%s",
  7238. file_name);
  7239. }
  7240. } else {
  7241. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7242. return;
  7243. }
  7244. if (truncated) {
  7245. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7246. return;
  7247. }
  7248. if (!mg_fopen(conn, path, "rb", &file)) {
  7249. mg_cry(conn,
  7250. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7251. tag,
  7252. path,
  7253. strerror(ERRNO));
  7254. } else {
  7255. fclose_on_exec(&file, conn);
  7256. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7257. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7258. path) > 0) {
  7259. send_ssi_file(conn, path, &file, include_level + 1);
  7260. } else {
  7261. send_file_data(conn, &file, 0, INT64_MAX);
  7262. }
  7263. mg_fclose(&file);
  7264. }
  7265. }
  7266. #if !defined(NO_POPEN)
  7267. static void
  7268. do_ssi_exec(struct mg_connection *conn, char *tag)
  7269. {
  7270. char cmd[1024] = "";
  7271. struct file file = STRUCT_FILE_INITIALIZER;
  7272. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7273. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7274. } else {
  7275. cmd[1023] = 0;
  7276. if ((file.fp = popen(cmd, "r")) == NULL) {
  7277. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7278. } else {
  7279. send_file_data(conn, &file, 0, INT64_MAX);
  7280. pclose(file.fp);
  7281. }
  7282. }
  7283. }
  7284. #endif /* !NO_POPEN */
  7285. static int
  7286. mg_fgetc(struct file *filep, int offset)
  7287. {
  7288. if (filep == NULL) {
  7289. return EOF;
  7290. }
  7291. if (filep->membuf != NULL && offset >= 0
  7292. && ((unsigned int)(offset)) < filep->size) {
  7293. return ((const unsigned char *)filep->membuf)[offset];
  7294. } else if (filep->fp != NULL) {
  7295. return fgetc(filep->fp);
  7296. } else {
  7297. return EOF;
  7298. }
  7299. }
  7300. static void
  7301. send_ssi_file(struct mg_connection *conn,
  7302. const char *path,
  7303. struct file *filep,
  7304. int include_level)
  7305. {
  7306. char buf[MG_BUF_LEN];
  7307. int ch, offset, len, in_ssi_tag;
  7308. if (include_level > 10) {
  7309. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7310. return;
  7311. }
  7312. in_ssi_tag = len = offset = 0;
  7313. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7314. if (in_ssi_tag && ch == '>') {
  7315. in_ssi_tag = 0;
  7316. buf[len++] = (char)ch;
  7317. buf[len] = '\0';
  7318. /* assert(len <= (int) sizeof(buf)); */
  7319. if (len > (int)sizeof(buf)) {
  7320. break;
  7321. }
  7322. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7323. /* Not an SSI tag, pass it */
  7324. (void)mg_write(conn, buf, (size_t)len);
  7325. } else {
  7326. if (!memcmp(buf + 5, "include", 7)) {
  7327. do_ssi_include(conn, path, buf + 12, include_level);
  7328. #if !defined(NO_POPEN)
  7329. } else if (!memcmp(buf + 5, "exec", 4)) {
  7330. do_ssi_exec(conn, buf + 9);
  7331. #endif /* !NO_POPEN */
  7332. } else {
  7333. mg_cry(conn,
  7334. "%s: unknown SSI "
  7335. "command: \"%s\"",
  7336. path,
  7337. buf);
  7338. }
  7339. }
  7340. len = 0;
  7341. } else if (in_ssi_tag) {
  7342. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7343. /* Not an SSI tag */
  7344. in_ssi_tag = 0;
  7345. } else if (len == (int)sizeof(buf) - 2) {
  7346. mg_cry(conn, "%s: SSI tag is too large", path);
  7347. len = 0;
  7348. }
  7349. buf[len++] = (char)(ch & 0xff);
  7350. } else if (ch == '<') {
  7351. in_ssi_tag = 1;
  7352. if (len > 0) {
  7353. mg_write(conn, buf, (size_t)len);
  7354. }
  7355. len = 0;
  7356. buf[len++] = (char)(ch & 0xff);
  7357. } else {
  7358. buf[len++] = (char)(ch & 0xff);
  7359. if (len == (int)sizeof(buf)) {
  7360. mg_write(conn, buf, (size_t)len);
  7361. len = 0;
  7362. }
  7363. }
  7364. }
  7365. /* Send the rest of buffered data */
  7366. if (len > 0) {
  7367. mg_write(conn, buf, (size_t)len);
  7368. }
  7369. }
  7370. static void
  7371. handle_ssi_file_request(struct mg_connection *conn,
  7372. const char *path,
  7373. struct file *filep)
  7374. {
  7375. char date[64];
  7376. time_t curtime = time(NULL);
  7377. const char *cors1, *cors2, *cors3;
  7378. if (conn == NULL || path == NULL || filep == NULL) {
  7379. return;
  7380. }
  7381. if (mg_get_header(conn, "Origin")) {
  7382. /* Cross-origin resource sharing (CORS). */
  7383. cors1 = "Access-Control-Allow-Origin: ";
  7384. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7385. cors3 = "\r\n";
  7386. } else {
  7387. cors1 = cors2 = cors3 = "";
  7388. }
  7389. if (!mg_fopen(conn, path, "rb", filep)) {
  7390. /* File exists (precondition for calling this function),
  7391. * but can not be opened by the server. */
  7392. send_http_error(conn,
  7393. 500,
  7394. "Error: Cannot read file\nfopen(%s): %s",
  7395. path,
  7396. strerror(ERRNO));
  7397. } else {
  7398. conn->must_close = 1;
  7399. gmt_time_string(date, sizeof(date), &curtime);
  7400. fclose_on_exec(filep, conn);
  7401. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7402. send_no_cache_header(conn);
  7403. mg_printf(conn,
  7404. "%s%s%s"
  7405. "Date: %s\r\n"
  7406. "Content-Type: text/html\r\n"
  7407. "Connection: %s\r\n\r\n",
  7408. cors1,
  7409. cors2,
  7410. cors3,
  7411. date,
  7412. suggest_connection_header(conn));
  7413. send_ssi_file(conn, path, filep, 0);
  7414. mg_fclose(filep);
  7415. }
  7416. }
  7417. #if !defined(NO_FILES)
  7418. static void
  7419. send_options(struct mg_connection *conn)
  7420. {
  7421. char date[64];
  7422. time_t curtime = time(NULL);
  7423. if (!conn) {
  7424. return;
  7425. }
  7426. conn->status_code = 200;
  7427. conn->must_close = 1;
  7428. gmt_time_string(date, sizeof(date), &curtime);
  7429. mg_printf(conn,
  7430. "HTTP/1.1 200 OK\r\n"
  7431. "Date: %s\r\n"
  7432. /* TODO: "Cache-Control" (?) */
  7433. "Connection: %s\r\n"
  7434. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7435. "PROPFIND, MKCOL\r\n"
  7436. "DAV: 1\r\n\r\n",
  7437. date,
  7438. suggest_connection_header(conn));
  7439. }
  7440. /* Writes PROPFIND properties for a collection element */
  7441. static void
  7442. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7443. {
  7444. char mtime[64];
  7445. if (conn == NULL || uri == NULL || filep == NULL) {
  7446. return;
  7447. }
  7448. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7449. conn->num_bytes_sent +=
  7450. mg_printf(conn,
  7451. "<d:response>"
  7452. "<d:href>%s</d:href>"
  7453. "<d:propstat>"
  7454. "<d:prop>"
  7455. "<d:resourcetype>%s</d:resourcetype>"
  7456. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7457. "<d:getlastmodified>%s</d:getlastmodified>"
  7458. "</d:prop>"
  7459. "<d:status>HTTP/1.1 200 OK</d:status>"
  7460. "</d:propstat>"
  7461. "</d:response>\n",
  7462. uri,
  7463. filep->is_directory ? "<d:collection/>" : "",
  7464. filep->size,
  7465. mtime);
  7466. }
  7467. static void
  7468. print_dav_dir_entry(struct de *de, void *data)
  7469. {
  7470. char href[PATH_MAX];
  7471. char href_encoded[PATH_MAX * 3 /* worst case */];
  7472. int truncated;
  7473. struct mg_connection *conn = (struct mg_connection *)data;
  7474. if (!de || !conn) {
  7475. return;
  7476. }
  7477. mg_snprintf(conn,
  7478. &truncated,
  7479. href,
  7480. sizeof(href),
  7481. "%s%s",
  7482. conn->request_info.local_uri,
  7483. de->file_name);
  7484. if (!truncated) {
  7485. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7486. print_props(conn, href_encoded, &de->file);
  7487. }
  7488. }
  7489. static void
  7490. handle_propfind(struct mg_connection *conn,
  7491. const char *path,
  7492. struct file *filep)
  7493. {
  7494. const char *depth = mg_get_header(conn, "Depth");
  7495. char date[64];
  7496. time_t curtime = time(NULL);
  7497. gmt_time_string(date, sizeof(date), &curtime);
  7498. if (!conn || !path || !filep || !conn->ctx) {
  7499. return;
  7500. }
  7501. conn->must_close = 1;
  7502. conn->status_code = 207;
  7503. mg_printf(conn,
  7504. "HTTP/1.1 207 Multi-Status\r\n"
  7505. "Date: %s\r\n",
  7506. date);
  7507. send_static_cache_header(conn);
  7508. mg_printf(conn,
  7509. "Connection: %s\r\n"
  7510. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7511. suggest_connection_header(conn));
  7512. conn->num_bytes_sent +=
  7513. mg_printf(conn,
  7514. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7515. "<d:multistatus xmlns:d='DAV:'>\n");
  7516. /* Print properties for the requested resource itself */
  7517. print_props(conn, conn->request_info.local_uri, filep);
  7518. /* If it is a directory, print directory entries too if Depth is not 0 */
  7519. if (filep && filep->is_directory
  7520. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7521. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7522. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7523. }
  7524. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7525. }
  7526. #endif
  7527. void
  7528. mg_lock_connection(struct mg_connection *conn)
  7529. {
  7530. if (conn) {
  7531. (void)pthread_mutex_lock(&conn->mutex);
  7532. }
  7533. }
  7534. void
  7535. mg_unlock_connection(struct mg_connection *conn)
  7536. {
  7537. if (conn) {
  7538. (void)pthread_mutex_unlock(&conn->mutex);
  7539. }
  7540. }
  7541. void
  7542. mg_lock_context(struct mg_context *ctx)
  7543. {
  7544. if (ctx) {
  7545. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7546. }
  7547. }
  7548. void
  7549. mg_unlock_context(struct mg_context *ctx)
  7550. {
  7551. if (ctx) {
  7552. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7553. }
  7554. }
  7555. #if defined(USE_TIMERS)
  7556. #include "timer.inl"
  7557. #endif /* USE_TIMERS */
  7558. #ifdef USE_LUA
  7559. #include "mod_lua.inl"
  7560. #endif /* USE_LUA */
  7561. #ifdef USE_DUKTAPE
  7562. #include "mod_duktape.inl"
  7563. #endif /* USE_DUKTAPE */
  7564. #if defined(USE_WEBSOCKET)
  7565. /* START OF SHA-1 code
  7566. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7567. #define SHA1HANDSOFF
  7568. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7569. *
  7570. * #if defined(__sun)
  7571. * #include "solarisfixes.h"
  7572. * #endif
  7573. */
  7574. static int
  7575. is_big_endian(void)
  7576. {
  7577. static const int n = 1;
  7578. return ((char *)&n)[0] == 0;
  7579. }
  7580. union char64long16 {
  7581. unsigned char c[64];
  7582. uint32_t l[16];
  7583. };
  7584. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7585. static uint32_t
  7586. blk0(union char64long16 *block, int i)
  7587. {
  7588. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7589. if (!is_big_endian()) {
  7590. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7591. | (rol(block->l[i], 8) & 0x00FF00FF);
  7592. }
  7593. return block->l[i];
  7594. }
  7595. #define blk(i) \
  7596. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7597. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7598. 1))
  7599. #define R0(v, w, x, y, z, i) \
  7600. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7601. w = rol(w, 30);
  7602. #define R1(v, w, x, y, z, i) \
  7603. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7604. w = rol(w, 30);
  7605. #define R2(v, w, x, y, z, i) \
  7606. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7607. w = rol(w, 30);
  7608. #define R3(v, w, x, y, z, i) \
  7609. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7610. w = rol(w, 30);
  7611. #define R4(v, w, x, y, z, i) \
  7612. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7613. w = rol(w, 30);
  7614. typedef struct {
  7615. uint32_t state[5];
  7616. uint32_t count[2];
  7617. unsigned char buffer[64];
  7618. } SHA1_CTX;
  7619. static void
  7620. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7621. {
  7622. uint32_t a, b, c, d, e;
  7623. union char64long16 block[1];
  7624. memcpy(block, buffer, 64);
  7625. a = state[0];
  7626. b = state[1];
  7627. c = state[2];
  7628. d = state[3];
  7629. e = state[4];
  7630. R0(a, b, c, d, e, 0);
  7631. R0(e, a, b, c, d, 1);
  7632. R0(d, e, a, b, c, 2);
  7633. R0(c, d, e, a, b, 3);
  7634. R0(b, c, d, e, a, 4);
  7635. R0(a, b, c, d, e, 5);
  7636. R0(e, a, b, c, d, 6);
  7637. R0(d, e, a, b, c, 7);
  7638. R0(c, d, e, a, b, 8);
  7639. R0(b, c, d, e, a, 9);
  7640. R0(a, b, c, d, e, 10);
  7641. R0(e, a, b, c, d, 11);
  7642. R0(d, e, a, b, c, 12);
  7643. R0(c, d, e, a, b, 13);
  7644. R0(b, c, d, e, a, 14);
  7645. R0(a, b, c, d, e, 15);
  7646. R1(e, a, b, c, d, 16);
  7647. R1(d, e, a, b, c, 17);
  7648. R1(c, d, e, a, b, 18);
  7649. R1(b, c, d, e, a, 19);
  7650. R2(a, b, c, d, e, 20);
  7651. R2(e, a, b, c, d, 21);
  7652. R2(d, e, a, b, c, 22);
  7653. R2(c, d, e, a, b, 23);
  7654. R2(b, c, d, e, a, 24);
  7655. R2(a, b, c, d, e, 25);
  7656. R2(e, a, b, c, d, 26);
  7657. R2(d, e, a, b, c, 27);
  7658. R2(c, d, e, a, b, 28);
  7659. R2(b, c, d, e, a, 29);
  7660. R2(a, b, c, d, e, 30);
  7661. R2(e, a, b, c, d, 31);
  7662. R2(d, e, a, b, c, 32);
  7663. R2(c, d, e, a, b, 33);
  7664. R2(b, c, d, e, a, 34);
  7665. R2(a, b, c, d, e, 35);
  7666. R2(e, a, b, c, d, 36);
  7667. R2(d, e, a, b, c, 37);
  7668. R2(c, d, e, a, b, 38);
  7669. R2(b, c, d, e, a, 39);
  7670. R3(a, b, c, d, e, 40);
  7671. R3(e, a, b, c, d, 41);
  7672. R3(d, e, a, b, c, 42);
  7673. R3(c, d, e, a, b, 43);
  7674. R3(b, c, d, e, a, 44);
  7675. R3(a, b, c, d, e, 45);
  7676. R3(e, a, b, c, d, 46);
  7677. R3(d, e, a, b, c, 47);
  7678. R3(c, d, e, a, b, 48);
  7679. R3(b, c, d, e, a, 49);
  7680. R3(a, b, c, d, e, 50);
  7681. R3(e, a, b, c, d, 51);
  7682. R3(d, e, a, b, c, 52);
  7683. R3(c, d, e, a, b, 53);
  7684. R3(b, c, d, e, a, 54);
  7685. R3(a, b, c, d, e, 55);
  7686. R3(e, a, b, c, d, 56);
  7687. R3(d, e, a, b, c, 57);
  7688. R3(c, d, e, a, b, 58);
  7689. R3(b, c, d, e, a, 59);
  7690. R4(a, b, c, d, e, 60);
  7691. R4(e, a, b, c, d, 61);
  7692. R4(d, e, a, b, c, 62);
  7693. R4(c, d, e, a, b, 63);
  7694. R4(b, c, d, e, a, 64);
  7695. R4(a, b, c, d, e, 65);
  7696. R4(e, a, b, c, d, 66);
  7697. R4(d, e, a, b, c, 67);
  7698. R4(c, d, e, a, b, 68);
  7699. R4(b, c, d, e, a, 69);
  7700. R4(a, b, c, d, e, 70);
  7701. R4(e, a, b, c, d, 71);
  7702. R4(d, e, a, b, c, 72);
  7703. R4(c, d, e, a, b, 73);
  7704. R4(b, c, d, e, a, 74);
  7705. R4(a, b, c, d, e, 75);
  7706. R4(e, a, b, c, d, 76);
  7707. R4(d, e, a, b, c, 77);
  7708. R4(c, d, e, a, b, 78);
  7709. R4(b, c, d, e, a, 79);
  7710. state[0] += a;
  7711. state[1] += b;
  7712. state[2] += c;
  7713. state[3] += d;
  7714. state[4] += e;
  7715. a = b = c = d = e = 0;
  7716. memset(block, '\0', sizeof(block));
  7717. }
  7718. static void
  7719. SHA1Init(SHA1_CTX *context)
  7720. {
  7721. context->state[0] = 0x67452301;
  7722. context->state[1] = 0xEFCDAB89;
  7723. context->state[2] = 0x98BADCFE;
  7724. context->state[3] = 0x10325476;
  7725. context->state[4] = 0xC3D2E1F0;
  7726. context->count[0] = context->count[1] = 0;
  7727. }
  7728. static void
  7729. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7730. {
  7731. uint32_t i, j;
  7732. j = context->count[0];
  7733. if ((context->count[0] += len << 3) < j) {
  7734. context->count[1]++;
  7735. }
  7736. context->count[1] += (len >> 29);
  7737. j = (j >> 3) & 63;
  7738. if ((j + len) > 63) {
  7739. memcpy(&context->buffer[j], data, (i = 64 - j));
  7740. SHA1Transform(context->state, context->buffer);
  7741. for (; i + 63 < len; i += 64) {
  7742. SHA1Transform(context->state, &data[i]);
  7743. }
  7744. j = 0;
  7745. } else
  7746. i = 0;
  7747. memcpy(&context->buffer[j], &data[i], len - i);
  7748. }
  7749. static void
  7750. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7751. {
  7752. unsigned i;
  7753. unsigned char finalcount[8], c;
  7754. for (i = 0; i < 8; i++) {
  7755. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7756. >> ((3 - (i & 3)) * 8)) & 255);
  7757. }
  7758. c = 0200;
  7759. SHA1Update(context, &c, 1);
  7760. while ((context->count[0] & 504) != 448) {
  7761. c = 0000;
  7762. SHA1Update(context, &c, 1);
  7763. }
  7764. SHA1Update(context, finalcount, 8);
  7765. for (i = 0; i < 20; i++) {
  7766. digest[i] = (unsigned char)((context->state[i >> 2]
  7767. >> ((3 - (i & 3)) * 8)) & 255);
  7768. }
  7769. memset(context, '\0', sizeof(*context));
  7770. memset(&finalcount, '\0', sizeof(finalcount));
  7771. }
  7772. /* END OF SHA1 CODE */
  7773. static int
  7774. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7775. {
  7776. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7777. const char *protocol = NULL;
  7778. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7779. SHA1_CTX sha_ctx;
  7780. int truncated;
  7781. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7782. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7783. if (truncated) {
  7784. conn->must_close = 1;
  7785. return 0;
  7786. }
  7787. SHA1Init(&sha_ctx);
  7788. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7789. SHA1Final((unsigned char *)sha, &sha_ctx);
  7790. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7791. mg_printf(conn,
  7792. "HTTP/1.1 101 Switching Protocols\r\n"
  7793. "Upgrade: websocket\r\n"
  7794. "Connection: Upgrade\r\n"
  7795. "Sec-WebSocket-Accept: %s\r\n",
  7796. b64_sha);
  7797. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7798. if (protocol) {
  7799. /* The protocol is a comma seperated list of names. */
  7800. /* The server must only return one value from this list. */
  7801. /* First check if it is a list or just a single value. */
  7802. const char *sep = strchr(protocol, ',');
  7803. if (sep == NULL) {
  7804. /* Just a single protocol -> accept it. */
  7805. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7806. } else {
  7807. /* Multiple protocols -> accept the first one. */
  7808. /* This is just a quick fix if the client offers multiple
  7809. * protocols. In order to get the behavior intended by
  7810. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7811. * required to have a list of websocket subprotocols accepted
  7812. * by the server. Then the server must either select a subprotocol
  7813. * supported by client and server, or the server has to abort the
  7814. * handshake by not returning a Sec-Websocket-Protocol header if
  7815. * no subprotocol is acceptable.
  7816. */
  7817. mg_printf(conn,
  7818. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7819. (int)(sep - protocol),
  7820. protocol);
  7821. }
  7822. /* TODO: Real subprotocol negotiation instead of just taking the first
  7823. * websocket subprotocol suggested by the client. */
  7824. } else {
  7825. mg_printf(conn, "%s", "\r\n");
  7826. }
  7827. return 1;
  7828. }
  7829. static void
  7830. read_websocket(struct mg_connection *conn,
  7831. mg_websocket_data_handler ws_data_handler,
  7832. void *callback_data)
  7833. {
  7834. /* Pointer to the beginning of the portion of the incoming websocket
  7835. * message queue.
  7836. * The original websocket upgrade request is never removed, so the queue
  7837. * begins after it. */
  7838. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7839. int n, error, exit_by_callback;
  7840. /* body_len is the length of the entire queue in bytes
  7841. * len is the length of the current message
  7842. * data_len is the length of the current message's data payload
  7843. * header_len is the length of the current message's header */
  7844. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7845. /* "The masking key is a 32-bit value chosen at random by the client."
  7846. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7847. */
  7848. unsigned char mask[4];
  7849. /* data points to the place where the message is stored when passed to
  7850. * the
  7851. * websocket_data callback. This is either mem on the stack, or a
  7852. * dynamically allocated buffer if it is too large. */
  7853. char mem[4096];
  7854. char *data = mem;
  7855. unsigned char mop; /* mask flag and opcode */
  7856. double timeout = -1.0;
  7857. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7858. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7859. }
  7860. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7861. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7862. }
  7863. mg_set_thread_name("wsock");
  7864. /* Loop continuously, reading messages from the socket, invoking the
  7865. * callback, and waiting repeatedly until an error occurs. */
  7866. while (!conn->ctx->stop_flag) {
  7867. header_len = 0;
  7868. assert(conn->data_len >= conn->request_len);
  7869. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7870. len = buf[1] & 127;
  7871. mask_len = (buf[1] & 128) ? 4 : 0;
  7872. if ((len < 126) && (body_len >= mask_len)) {
  7873. data_len = len;
  7874. header_len = 2 + mask_len;
  7875. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  7876. header_len = 4 + mask_len;
  7877. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7878. } else if (body_len >= (10 + mask_len)) {
  7879. header_len = 10 + mask_len;
  7880. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7881. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7882. }
  7883. }
  7884. if (header_len > 0 && body_len >= header_len) {
  7885. /* Allocate space to hold websocket payload */
  7886. data = mem;
  7887. if (data_len > sizeof(mem)) {
  7888. data = (char *)mg_malloc(data_len);
  7889. if (data == NULL) {
  7890. /* Allocation failed, exit the loop and then close the
  7891. * connection */
  7892. mg_cry(conn, "websocket out of memory; closing connection");
  7893. break;
  7894. }
  7895. }
  7896. /* Copy the mask before we shift the queue and destroy it */
  7897. if (mask_len > 0) {
  7898. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7899. } else {
  7900. memset(mask, 0, sizeof(mask));
  7901. }
  7902. /* Read frame payload from the first message in the queue into
  7903. * data and advance the queue by moving the memory in place. */
  7904. assert(body_len >= header_len);
  7905. if (data_len + header_len > body_len) {
  7906. mop = buf[0]; /* current mask and opcode */
  7907. /* Overflow case */
  7908. len = body_len - header_len;
  7909. memcpy(data, buf + header_len, len);
  7910. error = 0;
  7911. while (len < data_len) {
  7912. n = pull(
  7913. NULL, conn, data + len, (int)(data_len - len), timeout);
  7914. if (n <= 0) {
  7915. error = 1;
  7916. break;
  7917. }
  7918. len += (size_t)n;
  7919. }
  7920. if (error) {
  7921. mg_cry(conn, "Websocket pull failed; closing connection");
  7922. break;
  7923. }
  7924. conn->data_len = conn->request_len;
  7925. } else {
  7926. mop = buf[0]; /* current mask and opcode, overwritten by
  7927. * memmove() */
  7928. /* Length of the message being read at the front of the
  7929. * queue */
  7930. len = data_len + header_len;
  7931. /* Copy the data payload into the data pointer for the
  7932. * callback */
  7933. memcpy(data, buf + header_len, data_len);
  7934. /* Move the queue forward len bytes */
  7935. memmove(buf, buf + len, body_len - len);
  7936. /* Mark the queue as advanced */
  7937. conn->data_len -= (int)len;
  7938. }
  7939. /* Apply mask if necessary */
  7940. if (mask_len > 0) {
  7941. for (i = 0; i < data_len; ++i) {
  7942. data[i] ^= mask[i & 3];
  7943. }
  7944. }
  7945. /* Exit the loop if callback signals to exit (server side),
  7946. * or "connection close" opcode received (client side). */
  7947. exit_by_callback = 0;
  7948. if ((ws_data_handler != NULL)
  7949. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7950. exit_by_callback = 1;
  7951. }
  7952. if (data != mem) {
  7953. mg_free(data);
  7954. }
  7955. if (exit_by_callback
  7956. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7957. /* Opcode == 8, connection close */
  7958. break;
  7959. }
  7960. /* Not breaking the loop, process next websocket frame. */
  7961. } else {
  7962. /* Read from the socket into the next available location in the
  7963. * message queue. */
  7964. if ((n = pull(NULL,
  7965. conn,
  7966. conn->buf + conn->data_len,
  7967. conn->buf_size - conn->data_len,
  7968. timeout)) <= 0) {
  7969. /* Error, no bytes read */
  7970. break;
  7971. }
  7972. conn->data_len += n;
  7973. }
  7974. }
  7975. mg_set_thread_name("worker");
  7976. }
  7977. static int
  7978. mg_websocket_write_exec(struct mg_connection *conn,
  7979. int opcode,
  7980. const char *data,
  7981. size_t dataLen,
  7982. uint32_t masking_key)
  7983. {
  7984. unsigned char header[14];
  7985. size_t headerLen = 1;
  7986. int retval = -1;
  7987. header[0] = 0x80 + (opcode & 0xF);
  7988. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7989. if (dataLen < 126) {
  7990. /* inline 7-bit length field */
  7991. header[1] = (unsigned char)dataLen;
  7992. headerLen = 2;
  7993. } else if (dataLen <= 0xFFFF) {
  7994. /* 16-bit length field */
  7995. uint16_t len = htons((uint16_t)dataLen);
  7996. header[1] = 126;
  7997. memcpy(header + 2, &len, 2);
  7998. headerLen = 4;
  7999. } else {
  8000. /* 64-bit length field */
  8001. uint32_t len1 = htonl((uint64_t)dataLen >> 32);
  8002. uint32_t len2 = htonl(dataLen & 0xFFFFFFFF);
  8003. header[1] = 127;
  8004. memcpy(header + 2, &len1, 4);
  8005. memcpy(header + 6, &len2, 4);
  8006. headerLen = 10;
  8007. }
  8008. if (masking_key) {
  8009. /* add mask */
  8010. header[1] |= 0x80;
  8011. memcpy(header + headerLen, &masking_key, 4);
  8012. headerLen += 4;
  8013. }
  8014. /* Note that POSIX/Winsock's send() is threadsafe
  8015. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8016. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8017. * push(), although that is only a problem if the packet is large or
  8018. * outgoing buffer is full). */
  8019. (void)mg_lock_connection(conn);
  8020. retval = mg_write(conn, header, headerLen);
  8021. if (dataLen > 0) {
  8022. retval = mg_write(conn, data, dataLen);
  8023. }
  8024. mg_unlock_connection(conn);
  8025. return retval;
  8026. }
  8027. int
  8028. mg_websocket_write(struct mg_connection *conn,
  8029. int opcode,
  8030. const char *data,
  8031. size_t dataLen)
  8032. {
  8033. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8034. }
  8035. static void
  8036. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8037. {
  8038. size_t i = 0;
  8039. i = 0;
  8040. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8041. /* Convert in 32 bit words, if data is 4 byte aligned */
  8042. while (i < (in_len - 3)) {
  8043. *(uint32_t *)(void *)(out + i) =
  8044. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8045. i += 4;
  8046. }
  8047. }
  8048. if (i != in_len) {
  8049. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8050. while (i < in_len) {
  8051. *(uint8_t *)(void *)(out + i) =
  8052. *(uint8_t *)(void *)(in + i)
  8053. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8054. i++;
  8055. }
  8056. }
  8057. }
  8058. int
  8059. mg_websocket_client_write(struct mg_connection *conn,
  8060. int opcode,
  8061. const char *data,
  8062. size_t dataLen)
  8063. {
  8064. int retval = -1;
  8065. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8066. uint32_t masking_key = (uint32_t)get_random();
  8067. if (masked_data == NULL) {
  8068. /* Return -1 in an error case */
  8069. mg_cry(conn,
  8070. "Cannot allocate buffer for masked websocket response: "
  8071. "Out of memory");
  8072. return -1;
  8073. }
  8074. mask_data(data, dataLen, masking_key, masked_data);
  8075. retval = mg_websocket_write_exec(
  8076. conn, opcode, masked_data, dataLen, masking_key);
  8077. mg_free(masked_data);
  8078. return retval;
  8079. }
  8080. static void
  8081. handle_websocket_request(struct mg_connection *conn,
  8082. const char *path,
  8083. int is_callback_resource,
  8084. mg_websocket_connect_handler ws_connect_handler,
  8085. mg_websocket_ready_handler ws_ready_handler,
  8086. mg_websocket_data_handler ws_data_handler,
  8087. mg_websocket_close_handler ws_close_handler,
  8088. void *cbData)
  8089. {
  8090. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8091. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8092. int lua_websock = 0;
  8093. #if !defined(USE_LUA)
  8094. (void)path;
  8095. #endif
  8096. /* Step 1: Check websocket protocol version. */
  8097. /* Step 1.1: Check Sec-WebSocket-Key. */
  8098. if (!websock_key) {
  8099. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8100. * requires a Sec-WebSocket-Key header.
  8101. */
  8102. /* It could be the hixie draft version
  8103. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8104. */
  8105. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8106. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8107. char key3[8];
  8108. if ((key1 != NULL) && (key2 != NULL)) {
  8109. /* This version uses 8 byte body data in a GET request */
  8110. conn->content_len = 8;
  8111. if (8 == mg_read(conn, key3, 8)) {
  8112. /* This is the hixie version */
  8113. send_http_error(conn,
  8114. 426,
  8115. "%s",
  8116. "Protocol upgrade to RFC 6455 required");
  8117. return;
  8118. }
  8119. }
  8120. /* This is an unknown version */
  8121. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8122. return;
  8123. }
  8124. /* Step 1.2: Check websocket protocol version. */
  8125. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8126. if (version == NULL || strcmp(version, "13") != 0) {
  8127. /* Reject wrong versions */
  8128. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8129. return;
  8130. }
  8131. /* Step 1.3: Could check for "Host", but we do not really nead this
  8132. * value for anything, so just ignore it. */
  8133. /* Step 2: If a callback is responsible, call it. */
  8134. if (is_callback_resource) {
  8135. if (ws_connect_handler != NULL
  8136. && ws_connect_handler(conn, cbData) != 0) {
  8137. /* C callback has returned non-zero, do not proceed with
  8138. * handshake.
  8139. */
  8140. /* Note that C callbacks are no longer called when Lua is
  8141. * responsible, so C can no longer filter callbacks for Lua. */
  8142. return;
  8143. }
  8144. }
  8145. #if defined(USE_LUA)
  8146. /* Step 3: No callback. Check if Lua is responsible. */
  8147. else {
  8148. /* Step 3.1: Check if Lua is responsible. */
  8149. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8150. lua_websock =
  8151. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8152. strlen(
  8153. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8154. path);
  8155. }
  8156. if (lua_websock) {
  8157. /* Step 3.2: Lua is responsible: call it. */
  8158. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8159. if (!conn->lua_websocket_state) {
  8160. /* Lua rejected the new client */
  8161. return;
  8162. }
  8163. }
  8164. }
  8165. #endif
  8166. /* Step 4: Check if there is a responsible websocket handler. */
  8167. if (!is_callback_resource && !lua_websock) {
  8168. /* There is no callback, an Lua is not responsible either. */
  8169. /* Reply with a 404 Not Found or with nothing at all?
  8170. * TODO (mid): check the websocket standards, how to reply to
  8171. * requests to invalid websocket addresses. */
  8172. send_http_error(conn, 404, "%s", "Not found");
  8173. return;
  8174. }
  8175. /* Step 5: The websocket connection has been accepted */
  8176. if (!send_websocket_handshake(conn, websock_key)) {
  8177. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8178. return;
  8179. }
  8180. /* Step 6: Call the ready handler */
  8181. if (is_callback_resource) {
  8182. if (ws_ready_handler != NULL) {
  8183. ws_ready_handler(conn, cbData);
  8184. }
  8185. #if defined(USE_LUA)
  8186. } else if (lua_websock) {
  8187. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8188. /* the ready handler returned false */
  8189. return;
  8190. }
  8191. #endif
  8192. }
  8193. /* Step 7: Enter the read loop */
  8194. if (is_callback_resource) {
  8195. read_websocket(conn, ws_data_handler, cbData);
  8196. #if defined(USE_LUA)
  8197. } else if (lua_websock) {
  8198. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8199. #endif
  8200. }
  8201. /* Step 8: Call the close handler */
  8202. if (ws_close_handler) {
  8203. ws_close_handler(conn, cbData);
  8204. }
  8205. }
  8206. static int
  8207. is_websocket_protocol(const struct mg_connection *conn)
  8208. {
  8209. const char *upgrade, *connection;
  8210. /* A websocket protocoll has the following HTTP headers:
  8211. *
  8212. * Connection: Upgrade
  8213. * Upgrade: Websocket
  8214. */
  8215. upgrade = mg_get_header(conn, "Upgrade");
  8216. if (upgrade == NULL) {
  8217. return 0; /* fail early, don't waste time checking other header
  8218. * fields
  8219. */
  8220. }
  8221. if (!mg_strcasestr(upgrade, "websocket")) {
  8222. return 0;
  8223. }
  8224. connection = mg_get_header(conn, "Connection");
  8225. if (connection == NULL) {
  8226. return 0;
  8227. }
  8228. if (!mg_strcasestr(connection, "upgrade")) {
  8229. return 0;
  8230. }
  8231. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8232. * "Sec-WebSocket-Version" are also required.
  8233. * Don't check them here, since even an unsupported websocket protocol
  8234. * request still IS a websocket request (in contrast to a standard HTTP
  8235. * request). It will fail later in handle_websocket_request.
  8236. */
  8237. return 1;
  8238. }
  8239. #endif /* !USE_WEBSOCKET */
  8240. static int
  8241. isbyte(int n)
  8242. {
  8243. return n >= 0 && n <= 255;
  8244. }
  8245. static int
  8246. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8247. {
  8248. int n, a, b, c, d, slash = 32, len = 0;
  8249. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8250. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8251. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8252. && slash < 33) {
  8253. len = n;
  8254. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8255. | (uint32_t)d;
  8256. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8257. }
  8258. return len;
  8259. }
  8260. static int
  8261. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8262. {
  8263. int throttle = 0;
  8264. struct vec vec, val;
  8265. uint32_t net, mask;
  8266. char mult;
  8267. double v;
  8268. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8269. mult = ',';
  8270. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8271. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8272. && mult != ',')) {
  8273. continue;
  8274. }
  8275. v *= (lowercase(&mult) == 'k')
  8276. ? 1024
  8277. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8278. if (vec.len == 1 && vec.ptr[0] == '*') {
  8279. throttle = (int)v;
  8280. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8281. if ((remote_ip & mask) == net) {
  8282. throttle = (int)v;
  8283. }
  8284. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8285. throttle = (int)v;
  8286. }
  8287. }
  8288. return throttle;
  8289. }
  8290. static uint32_t
  8291. get_remote_ip(const struct mg_connection *conn)
  8292. {
  8293. if (!conn) {
  8294. return 0;
  8295. }
  8296. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8297. }
  8298. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8299. #include "handle_form.inl"
  8300. #if defined(MG_LEGACY_INTERFACE)
  8301. /* Implement the deprecated mg_upload function by calling the new
  8302. * mg_handle_form_request function. While mg_upload could only handle
  8303. * HTML forms sent as POST request in multipart/form-data format
  8304. * containing only file input elements, mg_handle_form_request can
  8305. * handle all form input elements and all standard request methods. */
  8306. struct mg_upload_user_data {
  8307. struct mg_connection *conn;
  8308. const char *destination_dir;
  8309. int num_uploaded_files;
  8310. };
  8311. /* Helper function for deprecated mg_upload. */
  8312. static int
  8313. mg_upload_field_found(const char *key,
  8314. const char *filename,
  8315. char *path,
  8316. size_t pathlen,
  8317. void *user_data)
  8318. {
  8319. int truncated = 0;
  8320. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8321. (void)key;
  8322. if (!filename) {
  8323. mg_cry(fud->conn, "%s: No filename set", __func__);
  8324. return FORM_FIELD_STORAGE_ABORT;
  8325. }
  8326. mg_snprintf(fud->conn,
  8327. &truncated,
  8328. path,
  8329. pathlen - 1,
  8330. "%s/%s",
  8331. fud->destination_dir,
  8332. filename);
  8333. if (!truncated) {
  8334. mg_cry(fud->conn, "%s: File path too long", __func__);
  8335. return FORM_FIELD_STORAGE_ABORT;
  8336. }
  8337. return FORM_FIELD_STORAGE_STORE;
  8338. }
  8339. /* Helper function for deprecated mg_upload. */
  8340. static int
  8341. mg_upload_field_get(const char *key,
  8342. const char *value,
  8343. size_t value_size,
  8344. void *user_data)
  8345. {
  8346. /* Function should never be called */
  8347. (void)key;
  8348. (void)value;
  8349. (void)value_size;
  8350. (void)user_data;
  8351. return 0;
  8352. }
  8353. /* Helper function for deprecated mg_upload. */
  8354. static int
  8355. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8356. {
  8357. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8358. (void)file_size;
  8359. fud->num_uploaded_files++;
  8360. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8361. return 0;
  8362. }
  8363. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8364. int
  8365. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8366. {
  8367. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8368. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8369. mg_upload_field_get,
  8370. mg_upload_field_stored,
  8371. 0};
  8372. int ret;
  8373. fdh.user_data = (void *)&fud;
  8374. ret = mg_handle_form_request(conn, &fdh);
  8375. if (ret < 0) {
  8376. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8377. }
  8378. return fud.num_uploaded_files;
  8379. }
  8380. #endif
  8381. static int
  8382. get_first_ssl_listener_index(const struct mg_context *ctx)
  8383. {
  8384. unsigned int i;
  8385. int idx = -1;
  8386. if (ctx) {
  8387. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8388. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8389. }
  8390. }
  8391. return idx;
  8392. }
  8393. static void
  8394. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8395. {
  8396. char host[1025];
  8397. const char *host_header;
  8398. size_t hostlen;
  8399. host_header = mg_get_header(conn, "Host");
  8400. hostlen = sizeof(host);
  8401. if (host_header != NULL) {
  8402. char *pos;
  8403. mg_strlcpy(host, host_header, hostlen);
  8404. host[hostlen - 1] = '\0';
  8405. pos = strchr(host, ':');
  8406. if (pos != NULL) {
  8407. *pos = '\0';
  8408. }
  8409. } else {
  8410. /* Cannot get host from the Host: header.
  8411. * Fallback to our IP address. */
  8412. if (conn) {
  8413. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8414. }
  8415. }
  8416. /* Send host, port, uri and (if it exists) ?query_string */
  8417. if (conn) {
  8418. mg_printf(conn,
  8419. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8420. host,
  8421. #if defined(USE_IPV6)
  8422. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8423. == AF_INET6)
  8424. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8425. .lsa.sin6.sin6_port)
  8426. :
  8427. #endif
  8428. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8429. .lsa.sin.sin_port),
  8430. conn->request_info.local_uri,
  8431. (conn->request_info.query_string == NULL) ? "" : "?",
  8432. (conn->request_info.query_string == NULL)
  8433. ? ""
  8434. : conn->request_info.query_string);
  8435. }
  8436. }
  8437. static void
  8438. mg_set_handler_type(struct mg_context *ctx,
  8439. const char *uri,
  8440. int handler_type,
  8441. int is_delete_request,
  8442. mg_request_handler handler,
  8443. mg_websocket_connect_handler connect_handler,
  8444. mg_websocket_ready_handler ready_handler,
  8445. mg_websocket_data_handler data_handler,
  8446. mg_websocket_close_handler close_handler,
  8447. mg_authorization_handler auth_handler,
  8448. void *cbdata)
  8449. {
  8450. struct mg_handler_info *tmp_rh, **lastref;
  8451. size_t urilen = strlen(uri);
  8452. if (handler_type == WEBSOCKET_HANDLER) {
  8453. /* assert(handler == NULL); */
  8454. /* assert(is_delete_request || connect_handler!=NULL ||
  8455. * ready_handler!=NULL || data_handler!=NULL ||
  8456. * close_handler!=NULL);
  8457. */
  8458. /* assert(auth_handler == NULL); */
  8459. if (handler != NULL) {
  8460. return;
  8461. }
  8462. if (!is_delete_request && connect_handler == NULL
  8463. && ready_handler == NULL
  8464. && data_handler == NULL
  8465. && close_handler == NULL) {
  8466. return;
  8467. }
  8468. if (auth_handler != NULL) {
  8469. return;
  8470. }
  8471. } else if (handler_type == REQUEST_HANDLER) {
  8472. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8473. * data_handler==NULL && close_handler==NULL); */
  8474. /* assert(is_delete_request || (handler!=NULL));
  8475. */
  8476. /* assert(auth_handler == NULL); */
  8477. if (connect_handler != NULL || ready_handler != NULL
  8478. || data_handler != NULL
  8479. || close_handler != NULL) {
  8480. return;
  8481. }
  8482. if (!is_delete_request && (handler == NULL)) {
  8483. return;
  8484. }
  8485. if (auth_handler != NULL) {
  8486. return;
  8487. }
  8488. } else { /* AUTH_HANDLER */
  8489. /* assert(handler == NULL); */
  8490. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8491. * data_handler==NULL && close_handler==NULL); */
  8492. /* assert(auth_handler != NULL); */
  8493. if (handler != NULL) {
  8494. return;
  8495. }
  8496. if (connect_handler != NULL || ready_handler != NULL
  8497. || data_handler != NULL
  8498. || close_handler != NULL) {
  8499. return;
  8500. }
  8501. if (!is_delete_request && (auth_handler == NULL)) {
  8502. return;
  8503. }
  8504. }
  8505. if (!ctx) {
  8506. return;
  8507. }
  8508. mg_lock_context(ctx);
  8509. /* first try to find an existing handler */
  8510. lastref = &(ctx->handlers);
  8511. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8512. if (tmp_rh->handler_type == handler_type) {
  8513. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8514. if (!is_delete_request) {
  8515. /* update existing handler */
  8516. if (handler_type == REQUEST_HANDLER) {
  8517. tmp_rh->handler = handler;
  8518. } else if (handler_type == WEBSOCKET_HANDLER) {
  8519. tmp_rh->connect_handler = connect_handler;
  8520. tmp_rh->ready_handler = ready_handler;
  8521. tmp_rh->data_handler = data_handler;
  8522. tmp_rh->close_handler = close_handler;
  8523. } else { /* AUTH_HANDLER */
  8524. tmp_rh->auth_handler = auth_handler;
  8525. }
  8526. tmp_rh->cbdata = cbdata;
  8527. } else {
  8528. /* remove existing handler */
  8529. *lastref = tmp_rh->next;
  8530. mg_free(tmp_rh->uri);
  8531. mg_free(tmp_rh);
  8532. }
  8533. mg_unlock_context(ctx);
  8534. return;
  8535. }
  8536. }
  8537. lastref = &(tmp_rh->next);
  8538. }
  8539. if (is_delete_request) {
  8540. /* no handler to set, this was a remove request to a non-existing
  8541. * handler */
  8542. mg_unlock_context(ctx);
  8543. return;
  8544. }
  8545. tmp_rh =
  8546. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8547. if (tmp_rh == NULL) {
  8548. mg_unlock_context(ctx);
  8549. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8550. return;
  8551. }
  8552. tmp_rh->uri = mg_strdup(uri);
  8553. if (!tmp_rh->uri) {
  8554. mg_unlock_context(ctx);
  8555. mg_free(tmp_rh);
  8556. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8557. return;
  8558. }
  8559. tmp_rh->uri_len = urilen;
  8560. if (handler_type == REQUEST_HANDLER) {
  8561. tmp_rh->handler = handler;
  8562. } else if (handler_type == WEBSOCKET_HANDLER) {
  8563. tmp_rh->connect_handler = connect_handler;
  8564. tmp_rh->ready_handler = ready_handler;
  8565. tmp_rh->data_handler = data_handler;
  8566. tmp_rh->close_handler = close_handler;
  8567. } else { /* AUTH_HANDLER */
  8568. tmp_rh->auth_handler = auth_handler;
  8569. }
  8570. tmp_rh->cbdata = cbdata;
  8571. tmp_rh->handler_type = handler_type;
  8572. tmp_rh->next = NULL;
  8573. *lastref = tmp_rh;
  8574. mg_unlock_context(ctx);
  8575. }
  8576. void
  8577. mg_set_request_handler(struct mg_context *ctx,
  8578. const char *uri,
  8579. mg_request_handler handler,
  8580. void *cbdata)
  8581. {
  8582. mg_set_handler_type(ctx,
  8583. uri,
  8584. REQUEST_HANDLER,
  8585. handler == NULL,
  8586. handler,
  8587. NULL,
  8588. NULL,
  8589. NULL,
  8590. NULL,
  8591. NULL,
  8592. cbdata);
  8593. }
  8594. void
  8595. mg_set_websocket_handler(struct mg_context *ctx,
  8596. const char *uri,
  8597. mg_websocket_connect_handler connect_handler,
  8598. mg_websocket_ready_handler ready_handler,
  8599. mg_websocket_data_handler data_handler,
  8600. mg_websocket_close_handler close_handler,
  8601. void *cbdata)
  8602. {
  8603. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8604. && (data_handler == NULL)
  8605. && (close_handler == NULL);
  8606. mg_set_handler_type(ctx,
  8607. uri,
  8608. WEBSOCKET_HANDLER,
  8609. is_delete_request,
  8610. NULL,
  8611. connect_handler,
  8612. ready_handler,
  8613. data_handler,
  8614. close_handler,
  8615. NULL,
  8616. cbdata);
  8617. }
  8618. void
  8619. mg_set_auth_handler(struct mg_context *ctx,
  8620. const char *uri,
  8621. mg_request_handler handler,
  8622. void *cbdata)
  8623. {
  8624. mg_set_handler_type(ctx,
  8625. uri,
  8626. AUTH_HANDLER,
  8627. handler == NULL,
  8628. NULL,
  8629. NULL,
  8630. NULL,
  8631. NULL,
  8632. NULL,
  8633. handler,
  8634. cbdata);
  8635. }
  8636. static int
  8637. get_request_handler(struct mg_connection *conn,
  8638. int handler_type,
  8639. mg_request_handler *handler,
  8640. mg_websocket_connect_handler *connect_handler,
  8641. mg_websocket_ready_handler *ready_handler,
  8642. mg_websocket_data_handler *data_handler,
  8643. mg_websocket_close_handler *close_handler,
  8644. mg_authorization_handler *auth_handler,
  8645. void **cbdata)
  8646. {
  8647. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8648. if (request_info) {
  8649. const char *uri = request_info->local_uri;
  8650. size_t urilen = strlen(uri);
  8651. struct mg_handler_info *tmp_rh;
  8652. if (!conn || !conn->ctx) {
  8653. return 0;
  8654. }
  8655. mg_lock_context(conn->ctx);
  8656. /* first try for an exact match */
  8657. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8658. tmp_rh = tmp_rh->next) {
  8659. if (tmp_rh->handler_type == handler_type) {
  8660. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8661. if (handler_type == WEBSOCKET_HANDLER) {
  8662. *connect_handler = tmp_rh->connect_handler;
  8663. *ready_handler = tmp_rh->ready_handler;
  8664. *data_handler = tmp_rh->data_handler;
  8665. *close_handler = tmp_rh->close_handler;
  8666. } else if (handler_type == REQUEST_HANDLER) {
  8667. *handler = tmp_rh->handler;
  8668. } else { /* AUTH_HANDLER */
  8669. *auth_handler = tmp_rh->auth_handler;
  8670. }
  8671. *cbdata = tmp_rh->cbdata;
  8672. mg_unlock_context(conn->ctx);
  8673. return 1;
  8674. }
  8675. }
  8676. }
  8677. /* next try for a partial match, we will accept uri/something */
  8678. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8679. tmp_rh = tmp_rh->next) {
  8680. if (tmp_rh->handler_type == handler_type) {
  8681. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8682. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8683. if (handler_type == WEBSOCKET_HANDLER) {
  8684. *connect_handler = tmp_rh->connect_handler;
  8685. *ready_handler = tmp_rh->ready_handler;
  8686. *data_handler = tmp_rh->data_handler;
  8687. *close_handler = tmp_rh->close_handler;
  8688. } else if (handler_type == REQUEST_HANDLER) {
  8689. *handler = tmp_rh->handler;
  8690. } else { /* AUTH_HANDLER */
  8691. *auth_handler = tmp_rh->auth_handler;
  8692. }
  8693. *cbdata = tmp_rh->cbdata;
  8694. mg_unlock_context(conn->ctx);
  8695. return 1;
  8696. }
  8697. }
  8698. }
  8699. /* finally try for pattern match */
  8700. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8701. tmp_rh = tmp_rh->next) {
  8702. if (tmp_rh->handler_type == handler_type) {
  8703. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8704. if (handler_type == WEBSOCKET_HANDLER) {
  8705. *connect_handler = tmp_rh->connect_handler;
  8706. *ready_handler = tmp_rh->ready_handler;
  8707. *data_handler = tmp_rh->data_handler;
  8708. *close_handler = tmp_rh->close_handler;
  8709. } else if (handler_type == REQUEST_HANDLER) {
  8710. *handler = tmp_rh->handler;
  8711. } else { /* AUTH_HANDLER */
  8712. *auth_handler = tmp_rh->auth_handler;
  8713. }
  8714. *cbdata = tmp_rh->cbdata;
  8715. mg_unlock_context(conn->ctx);
  8716. return 1;
  8717. }
  8718. }
  8719. }
  8720. mg_unlock_context(conn->ctx);
  8721. }
  8722. return 0; /* none found */
  8723. }
  8724. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8725. static int
  8726. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8727. void *cbdata)
  8728. {
  8729. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8730. if (pcallbacks->websocket_connect) {
  8731. return pcallbacks->websocket_connect(conn);
  8732. }
  8733. /* No handler set - assume "OK" */
  8734. return 0;
  8735. }
  8736. static void
  8737. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8738. {
  8739. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8740. if (pcallbacks->websocket_ready) {
  8741. pcallbacks->websocket_ready(conn);
  8742. }
  8743. }
  8744. static int
  8745. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8746. int bits,
  8747. char *data,
  8748. size_t len,
  8749. void *cbdata)
  8750. {
  8751. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8752. if (pcallbacks->websocket_data) {
  8753. return pcallbacks->websocket_data(conn, bits, data, len);
  8754. }
  8755. /* No handler set - assume "OK" */
  8756. return 1;
  8757. }
  8758. #endif
  8759. /* This is the heart of the Civetweb's logic.
  8760. * This function is called when the request is read, parsed and validated,
  8761. * and Civetweb must decide what action to take: serve a file, or
  8762. * a directory, or call embedded function, etcetera. */
  8763. static void
  8764. handle_request(struct mg_connection *conn)
  8765. {
  8766. if (conn) {
  8767. struct mg_request_info *ri = &conn->request_info;
  8768. char path[PATH_MAX];
  8769. int uri_len, ssl_index;
  8770. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8771. is_put_or_delete_request = 0, is_callback_resource = 0;
  8772. int i;
  8773. struct file file = STRUCT_FILE_INITIALIZER;
  8774. mg_request_handler callback_handler = NULL;
  8775. mg_websocket_connect_handler ws_connect_handler = NULL;
  8776. mg_websocket_ready_handler ws_ready_handler = NULL;
  8777. mg_websocket_data_handler ws_data_handler = NULL;
  8778. mg_websocket_close_handler ws_close_handler = NULL;
  8779. void *callback_data = NULL;
  8780. mg_authorization_handler auth_handler = NULL;
  8781. void *auth_callback_data = NULL;
  8782. #if !defined(NO_FILES)
  8783. time_t curtime = time(NULL);
  8784. char date[64];
  8785. #endif
  8786. path[0] = 0;
  8787. if (!ri) {
  8788. return;
  8789. }
  8790. /* 1. get the request url */
  8791. /* 1.1. split into url and query string */
  8792. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8793. != NULL) {
  8794. *((char *)conn->request_info.query_string++) = '\0';
  8795. }
  8796. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8797. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8798. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8799. if (ssl_index >= 0) {
  8800. redirect_to_https_port(conn, ssl_index);
  8801. } else {
  8802. /* A http to https forward port has been specified,
  8803. * but no https port to forward to. */
  8804. send_http_error(conn,
  8805. 503,
  8806. "%s",
  8807. "Error: SSL forward not configured properly");
  8808. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8809. }
  8810. return;
  8811. }
  8812. uri_len = (int)strlen(ri->local_uri);
  8813. /* 1.3. decode url (if config says so) */
  8814. if (should_decode_url(conn)) {
  8815. mg_url_decode(
  8816. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8817. }
  8818. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8819. * not possible */
  8820. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8821. /* step 1. completed, the url is known now */
  8822. uri_len = (int)strlen(ri->local_uri);
  8823. DEBUG_TRACE("URL: %s", ri->local_uri);
  8824. /* 3. if this ip has limited speed, set it for this connection */
  8825. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8826. get_remote_ip(conn),
  8827. ri->local_uri);
  8828. /* 4. call a "handle everything" callback, if registered */
  8829. if (conn->ctx->callbacks.begin_request != NULL) {
  8830. /* Note that since V1.7 the "begin_request" function is called
  8831. * before an authorization check. If an authorization check is
  8832. * required, use a request_handler instead. */
  8833. i = conn->ctx->callbacks.begin_request(conn);
  8834. if (i > 0) {
  8835. /* callback already processed the request. Store the
  8836. return value as a status code for the access log. */
  8837. conn->status_code = i;
  8838. return;
  8839. } else if (i == 0) {
  8840. /* civetweb should process the request */
  8841. } else {
  8842. /* unspecified - may change with the next version */
  8843. return;
  8844. }
  8845. }
  8846. /* request not yet handled by a handler or redirect, so the request
  8847. * is processed here */
  8848. /* 5. interpret the url to find out how the request must be handled
  8849. */
  8850. /* 5.1. first test, if the request targets the regular http(s)://
  8851. * protocol namespace or the websocket ws(s):// protocol namespace.
  8852. */
  8853. is_websocket_request = is_websocket_protocol(conn);
  8854. /* 5.2. check if the request will be handled by a callback */
  8855. if (get_request_handler(conn,
  8856. is_websocket_request ? WEBSOCKET_HANDLER
  8857. : REQUEST_HANDLER,
  8858. &callback_handler,
  8859. &ws_connect_handler,
  8860. &ws_ready_handler,
  8861. &ws_data_handler,
  8862. &ws_close_handler,
  8863. NULL,
  8864. &callback_data)) {
  8865. /* 5.2.1. A callback will handle this request. All requests
  8866. * handled
  8867. * by a callback have to be considered as requests to a script
  8868. * resource. */
  8869. is_callback_resource = 1;
  8870. is_script_resource = 1;
  8871. is_put_or_delete_request = is_put_or_delete_method(conn);
  8872. } else {
  8873. no_callback_resource:
  8874. /* 5.2.2. No callback is responsible for this request. The URI
  8875. * addresses a file based resource (static content or Lua/cgi
  8876. * scripts in the file system). */
  8877. is_callback_resource = 0;
  8878. interpret_uri(conn,
  8879. path,
  8880. sizeof(path),
  8881. &file,
  8882. &is_found,
  8883. &is_script_resource,
  8884. &is_websocket_request,
  8885. &is_put_or_delete_request);
  8886. }
  8887. /* 6. authorization check */
  8888. /* 6.1. a custom authorization handler is installed */
  8889. if (get_request_handler(conn,
  8890. AUTH_HANDLER,
  8891. NULL,
  8892. NULL,
  8893. NULL,
  8894. NULL,
  8895. NULL,
  8896. &auth_handler,
  8897. &auth_callback_data)) {
  8898. if (!auth_handler(conn, auth_callback_data)) {
  8899. return;
  8900. }
  8901. } else if (is_put_or_delete_request && !is_script_resource
  8902. && !is_callback_resource) {
  8903. /* 6.2. this request is a PUT/DELETE to a real file */
  8904. /* 6.2.1. thus, the server must have real files */
  8905. #if defined(NO_FILES)
  8906. if (1) {
  8907. #else
  8908. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8909. #endif
  8910. /* This server does not have any real files, thus the
  8911. * PUT/DELETE methods are not valid. */
  8912. send_http_error(conn,
  8913. 405,
  8914. "%s method not allowed",
  8915. conn->request_info.request_method);
  8916. return;
  8917. }
  8918. #if !defined(NO_FILES)
  8919. /* 6.2.2. Check if put authorization for static files is
  8920. * available.
  8921. */
  8922. if (!is_authorized_for_put(conn)) {
  8923. send_authorization_request(conn);
  8924. return;
  8925. }
  8926. #endif
  8927. } else {
  8928. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8929. * or it is a PUT or DELETE request to a resource that does not
  8930. * correspond to a file. Check authorization. */
  8931. if (!check_authorization(conn, path)) {
  8932. send_authorization_request(conn);
  8933. return;
  8934. }
  8935. }
  8936. /* request is authorized or does not need authorization */
  8937. /* 7. check if there are request handlers for this uri */
  8938. if (is_callback_resource) {
  8939. if (!is_websocket_request) {
  8940. i = callback_handler(conn, callback_data);
  8941. if (i > 0) {
  8942. /* Do nothing, callback has served the request. Store
  8943. * the
  8944. * return value as status code for the log and discard
  8945. * all
  8946. * data from the client not used by the callback. */
  8947. conn->status_code = i;
  8948. discard_unread_request_data(conn);
  8949. } else {
  8950. /* TODO (high): what if the handler did NOT handle the
  8951. * request */
  8952. /* The last version did handle this as a file request,
  8953. * but
  8954. * since a file request is not always a script resource,
  8955. * the authorization check might be different */
  8956. interpret_uri(conn,
  8957. path,
  8958. sizeof(path),
  8959. &file,
  8960. &is_found,
  8961. &is_script_resource,
  8962. &is_websocket_request,
  8963. &is_put_or_delete_request);
  8964. callback_handler = NULL;
  8965. /* TODO (very low): goto is deprecated but for the
  8966. * moment,
  8967. * a goto is simpler than some curious loop. */
  8968. /* The situation "callback does not handle the request"
  8969. * needs to be reconsidered anyway. */
  8970. goto no_callback_resource;
  8971. }
  8972. } else {
  8973. #if defined(USE_WEBSOCKET)
  8974. handle_websocket_request(conn,
  8975. path,
  8976. is_callback_resource,
  8977. ws_connect_handler,
  8978. ws_ready_handler,
  8979. ws_data_handler,
  8980. ws_close_handler,
  8981. callback_data);
  8982. #endif
  8983. }
  8984. return;
  8985. }
  8986. /* 8. handle websocket requests */
  8987. #if defined(USE_WEBSOCKET)
  8988. if (is_websocket_request) {
  8989. if (is_script_resource) {
  8990. /* Websocket Lua script */
  8991. handle_websocket_request(conn,
  8992. path,
  8993. 0 /* Lua Script */,
  8994. NULL,
  8995. NULL,
  8996. NULL,
  8997. NULL,
  8998. &conn->ctx->callbacks);
  8999. } else {
  9000. #if defined(MG_LEGACY_INTERFACE)
  9001. handle_websocket_request(
  9002. conn,
  9003. path,
  9004. !is_script_resource /* could be deprecated global callback */,
  9005. deprecated_websocket_connect_wrapper,
  9006. deprecated_websocket_ready_wrapper,
  9007. deprecated_websocket_data_wrapper,
  9008. NULL,
  9009. &conn->ctx->callbacks);
  9010. #else
  9011. send_http_error(conn, 404, "%s", "Not found");
  9012. #endif
  9013. }
  9014. return;
  9015. } else
  9016. #endif
  9017. #if defined(NO_FILES)
  9018. /* 9a. In case the server uses only callbacks, this uri is
  9019. * unknown.
  9020. * Then, all request handling ends here. */
  9021. send_http_error(conn, 404, "%s", "Not Found");
  9022. #else
  9023. /* 9b. This request is either for a static file or resource handled
  9024. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9025. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9026. send_http_error(conn, 404, "%s", "Not Found");
  9027. return;
  9028. }
  9029. /* 10. File is handled by a script. */
  9030. if (is_script_resource) {
  9031. handle_file_based_request(conn, path, &file);
  9032. return;
  9033. }
  9034. /* 11. Handle put/delete/mkcol requests */
  9035. if (is_put_or_delete_request) {
  9036. /* 11.1. PUT method */
  9037. if (!strcmp(ri->request_method, "PUT")) {
  9038. put_file(conn, path);
  9039. return;
  9040. }
  9041. /* 11.2. DELETE method */
  9042. if (!strcmp(ri->request_method, "DELETE")) {
  9043. delete_file(conn, path);
  9044. return;
  9045. }
  9046. /* 11.3. MKCOL method */
  9047. if (!strcmp(ri->request_method, "MKCOL")) {
  9048. mkcol(conn, path);
  9049. return;
  9050. }
  9051. /* 11.4. PATCH method
  9052. * This method is not supported for static resources,
  9053. * only for scripts (Lua, CGI) and callbacks. */
  9054. send_http_error(conn,
  9055. 405,
  9056. "%s method not allowed",
  9057. conn->request_info.request_method);
  9058. return;
  9059. }
  9060. /* 11. File does not exist, or it was configured that it should be
  9061. * hidden */
  9062. if (!is_found || (must_hide_file(conn, path))) {
  9063. send_http_error(conn, 404, "%s", "Not found");
  9064. return;
  9065. }
  9066. /* 12. Directory uris should end with a slash */
  9067. if (file.is_directory && (uri_len > 0)
  9068. && (ri->local_uri[uri_len - 1] != '/')) {
  9069. gmt_time_string(date, sizeof(date), &curtime);
  9070. mg_printf(conn,
  9071. "HTTP/1.1 301 Moved Permanently\r\n"
  9072. "Location: %s/\r\n"
  9073. "Date: %s\r\n"
  9074. /* "Cache-Control: private\r\n" (= default) */
  9075. "Content-Length: 0\r\n"
  9076. "Connection: %s\r\n\r\n",
  9077. ri->request_uri,
  9078. date,
  9079. suggest_connection_header(conn));
  9080. return;
  9081. }
  9082. /* 13. Handle other methods than GET/HEAD */
  9083. /* 13.1. Handle PROPFIND */
  9084. if (!strcmp(ri->request_method, "PROPFIND")) {
  9085. handle_propfind(conn, path, &file);
  9086. return;
  9087. }
  9088. /* 13.2. Handle OPTIONS for files */
  9089. if (!strcmp(ri->request_method, "OPTIONS")) {
  9090. /* This standard handler is only used for real files.
  9091. * Scripts should support the OPTIONS method themselves, to allow a
  9092. * maximum flexibility.
  9093. * Lua and CGI scripts may fully support CORS this way (including
  9094. * preflights). */
  9095. send_options(conn);
  9096. return;
  9097. }
  9098. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9099. if (0 != strcmp(ri->request_method, "GET")
  9100. && 0 != strcmp(ri->request_method, "HEAD")) {
  9101. send_http_error(conn,
  9102. 405,
  9103. "%s method not allowed",
  9104. conn->request_info.request_method);
  9105. return;
  9106. }
  9107. /* 14. directories */
  9108. if (file.is_directory) {
  9109. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9110. /* 14.1. use a substitute file */
  9111. /* TODO (high): substitute index may be a script resource.
  9112. * define what should be possible in this case. */
  9113. } else {
  9114. /* 14.2. no substitute file */
  9115. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9116. "yes")) {
  9117. handle_directory_request(conn, path);
  9118. } else {
  9119. send_http_error(conn,
  9120. 403,
  9121. "%s",
  9122. "Error: Directory listing denied");
  9123. }
  9124. return;
  9125. }
  9126. }
  9127. handle_file_based_request(conn, path, &file);
  9128. #endif /* !defined(NO_FILES) */
  9129. #if 0
  9130. /* Perform redirect and auth checks before calling begin_request()
  9131. * handler.
  9132. * Otherwise, begin_request() would need to perform auth checks and
  9133. * redirects. */
  9134. #endif
  9135. }
  9136. return;
  9137. }
  9138. static void
  9139. handle_file_based_request(struct mg_connection *conn,
  9140. const char *path,
  9141. struct file *file)
  9142. {
  9143. if (!conn || !conn->ctx) {
  9144. return;
  9145. }
  9146. if (0) {
  9147. #ifdef USE_LUA
  9148. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9149. strlen(
  9150. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9151. path) > 0) {
  9152. /* Lua server page: an SSI like page containing mostly plain html
  9153. * code
  9154. * plus some tags with server generated contents. */
  9155. handle_lsp_request(conn, path, file, NULL);
  9156. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9157. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9158. path) > 0) {
  9159. /* Lua in-server module script: a CGI like script used to generate
  9160. * the
  9161. * entire reply. */
  9162. mg_exec_lua_script(conn, path, NULL);
  9163. #endif
  9164. #if defined(USE_DUKTAPE)
  9165. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9166. strlen(
  9167. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9168. path) > 0) {
  9169. /* Call duktape to generate the page */
  9170. mg_exec_duktape_script(conn, path);
  9171. #endif
  9172. #if !defined(NO_CGI)
  9173. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9174. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9175. path) > 0) {
  9176. /* CGI scripts may support all HTTP methods */
  9177. handle_cgi_request(conn, path);
  9178. #endif /* !NO_CGI */
  9179. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9180. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9181. path) > 0) {
  9182. handle_ssi_file_request(conn, path, file);
  9183. #if !defined(NO_CACHING)
  9184. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9185. /* Send 304 "Not Modified" - this must not send any body data */
  9186. handle_not_modified_static_file_request(conn, file);
  9187. #endif /* !NO_CACHING */
  9188. } else {
  9189. handle_static_file_request(conn, path, file, NULL);
  9190. }
  9191. }
  9192. static void
  9193. close_all_listening_sockets(struct mg_context *ctx)
  9194. {
  9195. unsigned int i;
  9196. if (!ctx) {
  9197. return;
  9198. }
  9199. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9200. closesocket(ctx->listening_sockets[i].sock);
  9201. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9202. }
  9203. mg_free(ctx->listening_sockets);
  9204. ctx->listening_sockets = NULL;
  9205. mg_free(ctx->listening_socket_fds);
  9206. ctx->listening_socket_fds = NULL;
  9207. }
  9208. /* Valid listening port specification is: [ip_address:]port[s]
  9209. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  9210. * Examples for IPv6: [::]:80, [::1]:80,
  9211. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  9212. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  9213. static int
  9214. parse_port_string(const struct vec *vec, struct socket *so)
  9215. {
  9216. unsigned int a, b, c, d, port;
  9217. int ch, len;
  9218. #if defined(USE_IPV6)
  9219. char buf[100] = {0};
  9220. #endif
  9221. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9222. * Also, all-zeroes in the socket address means binding to all addresses
  9223. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9224. memset(so, 0, sizeof(*so));
  9225. so->lsa.sin.sin_family = AF_INET;
  9226. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9227. == 5) {
  9228. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9229. so->lsa.sin.sin_addr.s_addr =
  9230. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9231. so->lsa.sin.sin_port = htons((uint16_t)port);
  9232. #if defined(USE_IPV6)
  9233. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9234. && mg_inet_pton(
  9235. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9236. /* IPv6 address, examples: see above */
  9237. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9238. */
  9239. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9240. #endif
  9241. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9242. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9243. so->lsa.sin.sin_port = htons((uint16_t)port);
  9244. } else {
  9245. /* Parsing failure. Make port invalid. */
  9246. port = 0;
  9247. len = 0;
  9248. }
  9249. /* sscanf and the option splitting code ensure the following condition
  9250. */
  9251. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9252. return 0;
  9253. }
  9254. ch = vec->ptr[len]; /* Next character after the port number */
  9255. so->is_ssl = (ch == 's');
  9256. so->ssl_redir = (ch == 'r');
  9257. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9258. return is_valid_port(port)
  9259. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9260. }
  9261. static int
  9262. set_ports_option(struct mg_context *ctx)
  9263. {
  9264. const char *list;
  9265. int on = 1;
  9266. #if defined(USE_IPV6)
  9267. int off = 0;
  9268. #endif
  9269. struct vec vec;
  9270. struct socket so, *ptr;
  9271. struct pollfd *pfd;
  9272. union usa usa;
  9273. socklen_t len;
  9274. int portsTotal = 0;
  9275. int portsOk = 0;
  9276. if (!ctx) {
  9277. return 0;
  9278. }
  9279. memset(&so, 0, sizeof(so));
  9280. memset(&usa, 0, sizeof(usa));
  9281. len = sizeof(usa);
  9282. list = ctx->config[LISTENING_PORTS];
  9283. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9284. portsTotal++;
  9285. if (!parse_port_string(&vec, &so)) {
  9286. mg_cry(fc(ctx),
  9287. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9288. (int)vec.len,
  9289. vec.ptr,
  9290. portsTotal,
  9291. "[IP_ADDRESS:]PORT[s|r]");
  9292. continue;
  9293. }
  9294. #if !defined(NO_SSL)
  9295. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9296. mg_cry(fc(ctx),
  9297. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9298. "option set?",
  9299. portsTotal);
  9300. continue;
  9301. }
  9302. #endif
  9303. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9304. == INVALID_SOCKET) {
  9305. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9306. continue;
  9307. }
  9308. #ifdef _WIN32
  9309. /* Windows SO_REUSEADDR lets many procs binds to a
  9310. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9311. * if someone already has the socket -- DTL */
  9312. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9313. * Windows might need a few seconds before
  9314. * the same port can be used again in the
  9315. * same process, so a short Sleep may be
  9316. * required between mg_stop and mg_start.
  9317. */
  9318. if (setsockopt(so.sock,
  9319. SOL_SOCKET,
  9320. SO_EXCLUSIVEADDRUSE,
  9321. (SOCK_OPT_TYPE)&on,
  9322. sizeof(on)) != 0) {
  9323. mg_cry(fc(ctx),
  9324. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9325. portsTotal);
  9326. }
  9327. #else
  9328. if (setsockopt(so.sock,
  9329. SOL_SOCKET,
  9330. SO_REUSEADDR,
  9331. (SOCK_OPT_TYPE)&on,
  9332. sizeof(on)) != 0) {
  9333. mg_cry(fc(ctx),
  9334. "cannot set socket option SO_REUSEADDR (entry %i)",
  9335. portsTotal);
  9336. }
  9337. #endif
  9338. #if defined(USE_IPV6)
  9339. if (so.lsa.sa.sa_family == AF_INET6
  9340. && setsockopt(so.sock,
  9341. IPPROTO_IPV6,
  9342. IPV6_V6ONLY,
  9343. (void *)&off,
  9344. sizeof(off)) != 0) {
  9345. mg_cry(fc(ctx),
  9346. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9347. portsTotal);
  9348. }
  9349. #endif
  9350. if (so.lsa.sa.sa_family == AF_INET) {
  9351. len = sizeof(so.lsa.sin);
  9352. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9353. mg_cry(fc(ctx),
  9354. "cannot bind to %.*s: %d (%s)",
  9355. (int)vec.len,
  9356. vec.ptr,
  9357. (int)ERRNO,
  9358. strerror(errno));
  9359. closesocket(so.sock);
  9360. so.sock = INVALID_SOCKET;
  9361. continue;
  9362. }
  9363. }
  9364. #if defined(USE_IPV6)
  9365. else if (so.lsa.sa.sa_family == AF_INET6) {
  9366. len = sizeof(so.lsa.sin6);
  9367. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9368. mg_cry(fc(ctx),
  9369. "cannot bind to IPv6 %.*s: %d (%s)",
  9370. (int)vec.len,
  9371. vec.ptr,
  9372. (int)ERRNO,
  9373. strerror(errno));
  9374. closesocket(so.sock);
  9375. so.sock = INVALID_SOCKET;
  9376. continue;
  9377. }
  9378. }
  9379. #endif
  9380. else {
  9381. mg_cry(fc(ctx),
  9382. "cannot bind: address family not supported (entry %i)",
  9383. portsTotal);
  9384. continue;
  9385. }
  9386. if (listen(so.sock, SOMAXCONN) != 0) {
  9387. mg_cry(fc(ctx),
  9388. "cannot listen to %.*s: %d (%s)",
  9389. (int)vec.len,
  9390. vec.ptr,
  9391. (int)ERRNO,
  9392. strerror(errno));
  9393. closesocket(so.sock);
  9394. so.sock = INVALID_SOCKET;
  9395. continue;
  9396. }
  9397. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9398. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9399. int err = (int)ERRNO;
  9400. mg_cry(fc(ctx),
  9401. "call to getsockname failed %.*s: %d (%s)",
  9402. (int)vec.len,
  9403. vec.ptr,
  9404. err,
  9405. strerror(errno));
  9406. closesocket(so.sock);
  9407. so.sock = INVALID_SOCKET;
  9408. continue;
  9409. }
  9410. /* Update lsa port in case of random free ports */
  9411. #if defined(USE_IPV6)
  9412. if (so.lsa.sa.sa_family == AF_INET6) {
  9413. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9414. } else
  9415. #endif
  9416. {
  9417. so.lsa.sin.sin_port = usa.sin.sin_port;
  9418. }
  9419. if ((ptr = (struct socket *)
  9420. mg_realloc(ctx->listening_sockets,
  9421. (ctx->num_listening_sockets + 1)
  9422. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9423. mg_cry(fc(ctx), "%s", "Out of memory");
  9424. closesocket(so.sock);
  9425. so.sock = INVALID_SOCKET;
  9426. continue;
  9427. }
  9428. if ((pfd = (struct pollfd *)mg_realloc(
  9429. ctx->listening_socket_fds,
  9430. (ctx->num_listening_sockets + 1)
  9431. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9432. mg_cry(fc(ctx), "%s", "Out of memory");
  9433. closesocket(so.sock);
  9434. so.sock = INVALID_SOCKET;
  9435. mg_free(ptr);
  9436. continue;
  9437. }
  9438. set_close_on_exec(so.sock, fc(ctx));
  9439. ctx->listening_sockets = ptr;
  9440. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9441. ctx->listening_socket_fds = pfd;
  9442. ctx->num_listening_sockets++;
  9443. portsOk++;
  9444. }
  9445. if (portsOk != portsTotal) {
  9446. close_all_listening_sockets(ctx);
  9447. portsOk = 0;
  9448. }
  9449. return portsOk;
  9450. }
  9451. static const char *
  9452. header_val(const struct mg_connection *conn, const char *header)
  9453. {
  9454. const char *header_value;
  9455. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9456. return "-";
  9457. } else {
  9458. return header_value;
  9459. }
  9460. }
  9461. static void
  9462. log_access(const struct mg_connection *conn)
  9463. {
  9464. const struct mg_request_info *ri;
  9465. struct file fi;
  9466. char date[64], src_addr[IP_ADDR_STR_LEN];
  9467. struct tm *tm;
  9468. const char *referer;
  9469. const char *user_agent;
  9470. char buf[4096];
  9471. if (!conn || !conn->ctx) {
  9472. return;
  9473. }
  9474. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9475. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9476. == 0) {
  9477. fi.fp = NULL;
  9478. }
  9479. } else {
  9480. fi.fp = NULL;
  9481. }
  9482. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9483. return;
  9484. }
  9485. tm = localtime(&conn->conn_birth_time);
  9486. if (tm != NULL) {
  9487. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9488. } else {
  9489. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9490. date[sizeof(date) - 1] = '\0';
  9491. }
  9492. ri = &conn->request_info;
  9493. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9494. referer = header_val(conn, "Referer");
  9495. user_agent = header_val(conn, "User-Agent");
  9496. mg_snprintf(conn,
  9497. NULL, /* Ignore truncation in access log */
  9498. buf,
  9499. sizeof(buf),
  9500. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9501. src_addr,
  9502. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9503. date,
  9504. ri->request_method ? ri->request_method : "-",
  9505. ri->request_uri ? ri->request_uri : "-",
  9506. ri->query_string ? "?" : "",
  9507. ri->query_string ? ri->query_string : "",
  9508. ri->http_version,
  9509. conn->status_code,
  9510. conn->num_bytes_sent,
  9511. referer,
  9512. user_agent);
  9513. if (conn->ctx->callbacks.log_access) {
  9514. conn->ctx->callbacks.log_access(conn, buf);
  9515. }
  9516. if (fi.fp) {
  9517. flockfile(fi.fp);
  9518. fprintf(fi.fp, "%s\n", buf);
  9519. fflush(fi.fp);
  9520. funlockfile(fi.fp);
  9521. mg_fclose(&fi);
  9522. }
  9523. }
  9524. /* Verify given socket address against the ACL.
  9525. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9526. */
  9527. static int
  9528. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9529. {
  9530. int allowed, flag;
  9531. uint32_t net, mask;
  9532. struct vec vec;
  9533. if (ctx) {
  9534. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9535. /* If any ACL is set, deny by default */
  9536. allowed = (list == NULL) ? '+' : '-';
  9537. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9538. flag = vec.ptr[0];
  9539. if ((flag != '+' && flag != '-')
  9540. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9541. mg_cry(fc(ctx),
  9542. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9543. __func__);
  9544. return -1;
  9545. }
  9546. if (net == (remote_ip & mask)) {
  9547. allowed = flag;
  9548. }
  9549. }
  9550. return allowed == '+';
  9551. }
  9552. return -1;
  9553. }
  9554. #if !defined(_WIN32)
  9555. static int
  9556. set_uid_option(struct mg_context *ctx)
  9557. {
  9558. struct passwd *pw;
  9559. if (ctx) {
  9560. const char *uid = ctx->config[RUN_AS_USER];
  9561. int success = 0;
  9562. if (uid == NULL) {
  9563. success = 1;
  9564. } else {
  9565. if ((pw = getpwnam(uid)) == NULL) {
  9566. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9567. } else if (setgid(pw->pw_gid) == -1) {
  9568. mg_cry(fc(ctx),
  9569. "%s: setgid(%s): %s",
  9570. __func__,
  9571. uid,
  9572. strerror(errno));
  9573. } else if (setgroups(0, NULL)) {
  9574. mg_cry(fc(ctx),
  9575. "%s: setgroups(): %s",
  9576. __func__,
  9577. strerror(errno));
  9578. } else if (setuid(pw->pw_uid) == -1) {
  9579. mg_cry(fc(ctx),
  9580. "%s: setuid(%s): %s",
  9581. __func__,
  9582. uid,
  9583. strerror(errno));
  9584. } else {
  9585. success = 1;
  9586. }
  9587. }
  9588. return success;
  9589. }
  9590. return 0;
  9591. }
  9592. #endif /* !_WIN32 */
  9593. static void
  9594. tls_dtor(void *key)
  9595. {
  9596. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9597. /* key == pthread_getspecific(sTlsKey); */
  9598. if (tls) {
  9599. if (tls->is_master == 2) {
  9600. tls->is_master = -3; /* Mark memory as dead */
  9601. mg_free(tls);
  9602. }
  9603. }
  9604. pthread_setspecific(sTlsKey, NULL);
  9605. }
  9606. #if !defined(NO_SSL)
  9607. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9608. static unsigned long
  9609. ssl_id_callback(void)
  9610. {
  9611. #ifdef _WIN32
  9612. return GetCurrentThreadId();
  9613. #else
  9614. #ifdef __clang__
  9615. #pragma clang diagnostic push
  9616. #pragma clang diagnostic ignored "-Wunreachable-code"
  9617. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9618. * or not, so one of the two conditions will be unreachable by construction.
  9619. * Unfortunately the C standard does not define a way to check this at
  9620. * compile time, since the #if preprocessor conditions can not use the sizeof
  9621. * operator as an argument. */
  9622. #endif
  9623. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9624. /* This is the problematic case for CRYPTO_set_id_callback:
  9625. * The OS pthread_t can not be cast to unsigned long. */
  9626. struct mg_workerTLS *tls =
  9627. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9628. if (tls == NULL) {
  9629. /* SSL called from an unknown thread: Create some thread index.
  9630. */
  9631. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9632. tls->is_master = -2; /* -2 means "3rd party thread" */
  9633. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9634. pthread_setspecific(sTlsKey, tls);
  9635. }
  9636. return tls->thread_idx;
  9637. } else {
  9638. /* pthread_t may be any data type, so a simple cast to unsigned long
  9639. * can rise a warning/error, depending on the platform.
  9640. * Here memcpy is used as an anything-to-anything cast. */
  9641. unsigned long ret = 0;
  9642. pthread_t t = pthread_self();
  9643. memcpy(&ret, &t, sizeof(pthread_t));
  9644. return ret;
  9645. }
  9646. #ifdef __clang__
  9647. #pragma clang diagnostic pop
  9648. #endif
  9649. #endif
  9650. }
  9651. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9652. static const char *ssl_error(void);
  9653. static int
  9654. refresh_trust(struct mg_connection *conn)
  9655. {
  9656. static int reload_lock = 0;
  9657. static long int data_check = 0;
  9658. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  9659. struct stat cert_buf;
  9660. long int t;
  9661. char *pem;
  9662. int should_verify_peer;
  9663. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9664. && conn->ctx->callbacks.init_ssl == NULL) {
  9665. return 0;
  9666. }
  9667. t = data_check;
  9668. if (stat(pem, &cert_buf) != -1) {
  9669. t = (long int)cert_buf.st_mtime;
  9670. }
  9671. if (data_check != t) {
  9672. data_check = t;
  9673. should_verify_peer =
  9674. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9675. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9676. == 0);
  9677. if (should_verify_peer) {
  9678. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9679. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9680. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9681. ca_file,
  9682. ca_path) != 1) {
  9683. mg_cry(fc(conn->ctx),
  9684. "SSL_CTX_load_verify_locations error: %s "
  9685. "ssl_verify_peer requires setting "
  9686. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9687. "present in "
  9688. "the .conf file?",
  9689. ssl_error());
  9690. return 0;
  9691. }
  9692. }
  9693. if (1 == mg_atomic_inc(p_reload_lock)) {
  9694. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9695. return 0;
  9696. }
  9697. *p_reload_lock = 0;
  9698. }
  9699. }
  9700. /* lock while cert is reloading */
  9701. while (*p_reload_lock) {
  9702. sleep(1);
  9703. }
  9704. return 1;
  9705. }
  9706. static pthread_mutex_t *ssl_mutexes;
  9707. static int
  9708. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9709. {
  9710. int ret, err;
  9711. int short_trust;
  9712. unsigned i;
  9713. if (!conn) {
  9714. return 0;
  9715. }
  9716. short_trust =
  9717. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9718. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9719. if (short_trust) {
  9720. int trust_ret = refresh_trust(conn);
  9721. if (!trust_ret) {
  9722. return trust_ret;
  9723. }
  9724. }
  9725. conn->ssl = SSL_new(s);
  9726. if (conn->ssl == NULL) {
  9727. return 0;
  9728. }
  9729. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9730. if (ret != 1) {
  9731. err = SSL_get_error(conn->ssl, ret);
  9732. (void)err; /* TODO: set some error message */
  9733. SSL_free(conn->ssl);
  9734. conn->ssl = NULL;
  9735. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9736. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9737. ERR_remove_state(0);
  9738. return 0;
  9739. }
  9740. /* SSL functions may fail and require to be called again:
  9741. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9742. * Here "func" could be SSL_connect or SSL_accept. */
  9743. for (i = 0; i <= 16; i *= 2) {
  9744. ret = func(conn->ssl);
  9745. if (ret != 1) {
  9746. err = SSL_get_error(conn->ssl, ret);
  9747. if ((err == SSL_ERROR_WANT_CONNECT)
  9748. || (err == SSL_ERROR_WANT_ACCEPT)) {
  9749. /* Retry */
  9750. mg_sleep(i);
  9751. } else {
  9752. /* This is an error */
  9753. /* TODO: set some error message */
  9754. break;
  9755. }
  9756. } else {
  9757. /* success */
  9758. break;
  9759. }
  9760. }
  9761. if (ret != 1) {
  9762. SSL_free(conn->ssl);
  9763. conn->ssl = NULL;
  9764. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9765. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9766. ERR_remove_state(0);
  9767. return 0;
  9768. }
  9769. return 1;
  9770. }
  9771. /* Return OpenSSL error message (from CRYPTO lib) */
  9772. static const char *
  9773. ssl_error(void)
  9774. {
  9775. unsigned long err;
  9776. err = ERR_get_error();
  9777. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  9778. }
  9779. static int
  9780. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  9781. {
  9782. int i;
  9783. const char hexdigit[] = "0123456789abcdef";
  9784. if (memlen <= 0 || buflen <= 0) {
  9785. return 0;
  9786. }
  9787. if (buflen < (3 * memlen)) {
  9788. return 0;
  9789. }
  9790. for (i = 0; i < memlen; i++) {
  9791. if (i > 0) {
  9792. buf[3 * i - 1] = ' ';
  9793. }
  9794. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  9795. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  9796. }
  9797. buf[3 * memlen - 1] = 0;
  9798. return 1;
  9799. }
  9800. static void
  9801. ssl_get_client_cert_info(struct mg_connection *conn)
  9802. {
  9803. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  9804. if (cert) {
  9805. char str_subject[1024];
  9806. char str_issuer[1024];
  9807. char str_serial[1024];
  9808. char str_finger[1024];
  9809. unsigned char buf[256];
  9810. int len;
  9811. unsigned int ulen;
  9812. /* Handle to algorithm used for fingerprint */
  9813. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  9814. /* Get Subject and issuer */
  9815. X509_NAME *subj = X509_get_subject_name(cert);
  9816. X509_NAME *iss = X509_get_issuer_name(cert);
  9817. /* Get serial number */
  9818. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  9819. /* Translate subject and issuer to a string */
  9820. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  9821. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  9822. /* Translate serial number to a hex string */
  9823. len = i2c_ASN1_INTEGER(serial, NULL);
  9824. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  9825. unsigned char *pbuf = buf;
  9826. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  9827. if (!hexdump2string(
  9828. buf, len2, str_serial, (int)sizeof(str_serial))) {
  9829. *str_serial = 0;
  9830. }
  9831. } else {
  9832. *str_serial = 0;
  9833. }
  9834. /* Calculate SHA1 fingerprint and store as a hex string */
  9835. ulen = 0;
  9836. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  9837. if (!hexdump2string(buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  9838. *str_finger = 0;
  9839. }
  9840. conn->request_info.client_cert =
  9841. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  9842. if (conn->request_info.client_cert) {
  9843. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  9844. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  9845. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  9846. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  9847. } else {
  9848. /* TODO: write some OOM message */
  9849. }
  9850. X509_free(cert);
  9851. }
  9852. }
  9853. static void
  9854. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9855. {
  9856. (void)line;
  9857. (void)file;
  9858. if (mode & 1) {
  9859. /* 1 is CRYPTO_LOCK */
  9860. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9861. } else {
  9862. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9863. }
  9864. }
  9865. #if !defined(NO_SSL_DL)
  9866. static void *
  9867. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9868. {
  9869. union {
  9870. void *p;
  9871. void (*fp)(void);
  9872. } u;
  9873. void *dll_handle;
  9874. struct ssl_func *fp;
  9875. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9876. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9877. return NULL;
  9878. }
  9879. for (fp = sw; fp->name != NULL; fp++) {
  9880. #ifdef _WIN32
  9881. /* GetProcAddress() returns pointer to function */
  9882. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9883. #else
  9884. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9885. * pointers to function pointers. We need to use a union to make a
  9886. * cast. */
  9887. u.p = dlsym(dll_handle, fp->name);
  9888. #endif /* _WIN32 */
  9889. if (u.fp == NULL) {
  9890. mg_cry(fc(ctx),
  9891. "%s: %s: cannot find %s",
  9892. __func__,
  9893. dll_name,
  9894. fp->name);
  9895. dlclose(dll_handle);
  9896. return NULL;
  9897. } else {
  9898. fp->ptr = u.fp;
  9899. }
  9900. }
  9901. return dll_handle;
  9902. }
  9903. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9904. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9905. #endif /* NO_SSL_DL */
  9906. #if defined(SSL_ALREADY_INITIALIZED)
  9907. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9908. #else
  9909. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9910. #endif
  9911. static int
  9912. initialize_ssl(struct mg_context *ctx)
  9913. {
  9914. int i;
  9915. size_t size;
  9916. #if !defined(NO_SSL_DL)
  9917. if (!cryptolib_dll_handle) {
  9918. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9919. if (!cryptolib_dll_handle) {
  9920. return 0;
  9921. }
  9922. }
  9923. #endif /* NO_SSL_DL */
  9924. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9925. return 1;
  9926. }
  9927. /* Initialize locking callbacks, needed for thread safety.
  9928. * http://www.openssl.org/support/faq.html#PROG1
  9929. */
  9930. i = CRYPTO_num_locks();
  9931. if (i < 0) {
  9932. i = 0;
  9933. }
  9934. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9935. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9936. mg_cry(fc(ctx),
  9937. "%s: cannot allocate mutexes: %s",
  9938. __func__,
  9939. ssl_error());
  9940. return 0;
  9941. }
  9942. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9943. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9944. }
  9945. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9946. CRYPTO_set_id_callback(&ssl_id_callback);
  9947. return 1;
  9948. }
  9949. static int
  9950. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9951. {
  9952. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9953. mg_cry(fc(ctx),
  9954. "%s: cannot open certificate file %s: %s",
  9955. __func__,
  9956. pem,
  9957. ssl_error());
  9958. return 0;
  9959. }
  9960. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9961. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9962. mg_cry(fc(ctx),
  9963. "%s: cannot open private key file %s: %s",
  9964. __func__,
  9965. pem,
  9966. ssl_error());
  9967. return 0;
  9968. }
  9969. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9970. mg_cry(fc(ctx),
  9971. "%s: certificate and private key do not match: %s",
  9972. __func__,
  9973. pem);
  9974. return 0;
  9975. }
  9976. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9977. mg_cry(fc(ctx),
  9978. "%s: cannot use certificate chain file %s: %s",
  9979. __func__,
  9980. pem,
  9981. ssl_error());
  9982. return 0;
  9983. }
  9984. return 1;
  9985. }
  9986. static long
  9987. ssl_get_protocol(int version_id)
  9988. {
  9989. long ret = SSL_OP_ALL;
  9990. if (version_id > 0)
  9991. ret |= SSL_OP_NO_SSLv2;
  9992. if (version_id > 1)
  9993. ret |= SSL_OP_NO_SSLv3;
  9994. if (version_id > 2)
  9995. ret |= SSL_OP_NO_TLSv1;
  9996. if (version_id > 3)
  9997. ret |= SSL_OP_NO_TLSv1_1;
  9998. return ret;
  9999. }
  10000. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10001. static int
  10002. set_ssl_option(struct mg_context *ctx)
  10003. {
  10004. const char *pem;
  10005. int callback_ret;
  10006. int should_verify_peer;
  10007. const char *ca_path;
  10008. const char *ca_file;
  10009. int use_default_verify_paths;
  10010. int verify_depth;
  10011. time_t now_rt = time(NULL);
  10012. struct timespec now_mt;
  10013. md5_byte_t ssl_context_id[16];
  10014. md5_state_t md5state;
  10015. int protocol_ver;
  10016. /* If PEM file is not specified and the init_ssl callback
  10017. * is not specified, skip SSL initialization. */
  10018. if (!ctx) {
  10019. return 0;
  10020. }
  10021. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10022. && ctx->callbacks.init_ssl == NULL) {
  10023. return 1;
  10024. }
  10025. if (!initialize_ssl(ctx)) {
  10026. return 0;
  10027. }
  10028. #if !defined(NO_SSL_DL)
  10029. if (!ssllib_dll_handle) {
  10030. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10031. if (!ssllib_dll_handle) {
  10032. return 0;
  10033. }
  10034. }
  10035. #endif /* NO_SSL_DL */
  10036. /* Initialize SSL library */
  10037. SSL_library_init();
  10038. SSL_load_error_strings();
  10039. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10040. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10041. return 0;
  10042. }
  10043. SSL_CTX_clear_options(ctx->ssl_ctx,
  10044. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10045. | SSL_OP_NO_TLSv1_1);
  10046. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10047. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10048. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10049. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10050. /* If a callback has been specified, call it. */
  10051. callback_ret =
  10052. (ctx->callbacks.init_ssl == NULL)
  10053. ? 0
  10054. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10055. /* If callback returns 0, civetweb sets up the SSL certificate.
  10056. * If it returns 1, civetweb assumes the calback already did this.
  10057. * If it returns -1, initializing ssl fails. */
  10058. if (callback_ret < 0) {
  10059. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10060. return 0;
  10061. }
  10062. if (callback_ret > 0) {
  10063. if (pem != NULL) {
  10064. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10065. }
  10066. return 1;
  10067. }
  10068. /* Use some UID as session context ID. */
  10069. md5_init(&md5state);
  10070. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10071. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10072. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10073. md5_append(&md5state,
  10074. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10075. strlen(ctx->config[LISTENING_PORTS]));
  10076. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10077. md5_finish(&md5state, ssl_context_id);
  10078. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10079. (const unsigned char *)&ssl_context_id,
  10080. sizeof(ssl_context_id));
  10081. if (pem != NULL) {
  10082. if (!ssl_use_pem_file(ctx, pem)) {
  10083. return 0;
  10084. }
  10085. }
  10086. should_verify_peer =
  10087. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10088. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10089. use_default_verify_paths =
  10090. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10091. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10092. if (should_verify_peer) {
  10093. ca_path = ctx->config[SSL_CA_PATH];
  10094. ca_file = ctx->config[SSL_CA_FILE];
  10095. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10096. != 1) {
  10097. mg_cry(fc(ctx),
  10098. "SSL_CTX_load_verify_locations error: %s "
  10099. "ssl_verify_peer requires setting "
  10100. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10101. "present in "
  10102. "the .conf file?",
  10103. ssl_error());
  10104. return 0;
  10105. }
  10106. SSL_CTX_set_verify(ctx->ssl_ctx,
  10107. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10108. NULL);
  10109. if (use_default_verify_paths
  10110. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10111. mg_cry(fc(ctx),
  10112. "SSL_CTX_set_default_verify_paths error: %s",
  10113. ssl_error());
  10114. return 0;
  10115. }
  10116. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10117. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10118. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10119. }
  10120. }
  10121. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10122. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10123. != 1) {
  10124. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10125. }
  10126. }
  10127. return 1;
  10128. }
  10129. static void
  10130. uninitialize_ssl(struct mg_context *ctx)
  10131. {
  10132. int i;
  10133. (void)ctx;
  10134. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10135. /* Shutdown according to
  10136. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10137. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10138. */
  10139. CRYPTO_set_locking_callback(NULL);
  10140. CRYPTO_set_id_callback(NULL);
  10141. ENGINE_cleanup();
  10142. CONF_modules_unload(1);
  10143. ERR_free_strings();
  10144. EVP_cleanup();
  10145. CRYPTO_cleanup_all_ex_data();
  10146. ERR_remove_state(0);
  10147. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10148. pthread_mutex_destroy(&ssl_mutexes[i]);
  10149. }
  10150. mg_free(ssl_mutexes);
  10151. ssl_mutexes = NULL;
  10152. }
  10153. }
  10154. #endif /* !NO_SSL */
  10155. static int
  10156. set_gpass_option(struct mg_context *ctx)
  10157. {
  10158. if (ctx) {
  10159. struct file file = STRUCT_FILE_INITIALIZER;
  10160. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10161. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  10162. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10163. return 0;
  10164. }
  10165. return 1;
  10166. }
  10167. return 0;
  10168. }
  10169. static int
  10170. set_acl_option(struct mg_context *ctx)
  10171. {
  10172. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10173. }
  10174. static void
  10175. reset_per_request_attributes(struct mg_connection *conn)
  10176. {
  10177. if (!conn) {
  10178. return;
  10179. }
  10180. conn->path_info = NULL;
  10181. conn->num_bytes_sent = conn->consumed_content = 0;
  10182. conn->status_code = -1;
  10183. conn->is_chunked = 0;
  10184. conn->must_close = conn->request_len = conn->throttle = 0;
  10185. conn->request_info.content_length = -1;
  10186. conn->request_info.remote_user = NULL;
  10187. conn->request_info.request_method = NULL;
  10188. conn->request_info.request_uri = NULL;
  10189. conn->request_info.local_uri = NULL;
  10190. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10191. * local_uri and request_uri */
  10192. conn->request_info.http_version = NULL;
  10193. conn->request_info.num_headers = 0;
  10194. conn->data_len = 0;
  10195. conn->chunk_remainder = 0;
  10196. conn->internal_error = 0;
  10197. }
  10198. static int
  10199. set_sock_timeout(SOCKET sock, int milliseconds)
  10200. {
  10201. int r0 = 0, r1, r2;
  10202. #ifdef _WIN32
  10203. /* Windows specific */
  10204. DWORD tv = (DWORD)milliseconds;
  10205. #else
  10206. /* Linux, ... (not Windows) */
  10207. struct timeval tv;
  10208. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10209. * max. time waiting for the acknowledged of TCP data before the connection
  10210. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10211. * If this option is not set, the default timeout of 20-30 minutes is used.
  10212. */
  10213. /* #define TCP_USER_TIMEOUT (18) */
  10214. #if defined(TCP_USER_TIMEOUT)
  10215. unsigned int uto = (unsigned int)milliseconds;
  10216. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10217. #endif
  10218. memset(&tv, 0, sizeof(tv));
  10219. tv.tv_sec = milliseconds / 1000;
  10220. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10221. #endif /* _WIN32 */
  10222. r1 = setsockopt(
  10223. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10224. r2 = setsockopt(
  10225. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10226. return r0 || r1 || r2;
  10227. }
  10228. static int
  10229. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10230. {
  10231. if (setsockopt(sock,
  10232. IPPROTO_TCP,
  10233. TCP_NODELAY,
  10234. (SOCK_OPT_TYPE)&nodelay_on,
  10235. sizeof(nodelay_on)) != 0) {
  10236. /* Error */
  10237. return 1;
  10238. }
  10239. /* OK */
  10240. return 0;
  10241. }
  10242. static void
  10243. close_socket_gracefully(struct mg_connection *conn)
  10244. {
  10245. #if defined(_WIN32)
  10246. char buf[MG_BUF_LEN];
  10247. int n;
  10248. #endif
  10249. struct linger linger;
  10250. if (!conn) {
  10251. return;
  10252. }
  10253. /* Set linger option to avoid socket hanging out after close. This
  10254. * prevent
  10255. * ephemeral port exhaust problem under high QPS. */
  10256. linger.l_onoff = 1;
  10257. linger.l_linger = 1;
  10258. if (setsockopt(conn->client.sock,
  10259. SOL_SOCKET,
  10260. SO_LINGER,
  10261. (char *)&linger,
  10262. sizeof(linger)) != 0) {
  10263. mg_cry(conn,
  10264. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10265. __func__,
  10266. strerror(ERRNO));
  10267. }
  10268. /* Send FIN to the client */
  10269. shutdown(conn->client.sock, SHUTDOWN_WR);
  10270. set_non_blocking_mode(conn->client.sock);
  10271. #if defined(_WIN32)
  10272. /* Read and discard pending incoming data. If we do not do that and
  10273. * close
  10274. * the socket, the data in the send buffer may be discarded. This
  10275. * behaviour is seen on Windows, when client keeps sending data
  10276. * when server decides to close the connection; then when client
  10277. * does recv() it gets no data back. */
  10278. do {
  10279. n = pull(
  10280. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10281. } while (n > 0);
  10282. #endif
  10283. /* Now we know that our FIN is ACK-ed, safe to close */
  10284. closesocket(conn->client.sock);
  10285. conn->client.sock = INVALID_SOCKET;
  10286. }
  10287. static void
  10288. close_connection(struct mg_connection *conn)
  10289. {
  10290. if (!conn || !conn->ctx) {
  10291. return;
  10292. }
  10293. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10294. if (conn->lua_websocket_state) {
  10295. lua_websocket_close(conn, conn->lua_websocket_state);
  10296. conn->lua_websocket_state = NULL;
  10297. }
  10298. #endif
  10299. /* call the connection_close callback if assigned */
  10300. if ((conn->ctx->callbacks.connection_close != NULL)
  10301. && (conn->ctx->context_type == 1)) {
  10302. conn->ctx->callbacks.connection_close(conn);
  10303. }
  10304. mg_lock_connection(conn);
  10305. conn->must_close = 1;
  10306. #ifndef NO_SSL
  10307. if (conn->ssl != NULL) {
  10308. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10309. */
  10310. SSL_shutdown(conn->ssl);
  10311. SSL_free(conn->ssl);
  10312. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10313. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10314. ERR_remove_state(0);
  10315. conn->ssl = NULL;
  10316. }
  10317. #endif
  10318. if (conn->client.sock != INVALID_SOCKET) {
  10319. close_socket_gracefully(conn);
  10320. conn->client.sock = INVALID_SOCKET;
  10321. }
  10322. mg_unlock_connection(conn);
  10323. }
  10324. void
  10325. mg_close_connection(struct mg_connection *conn)
  10326. {
  10327. struct mg_context *client_ctx = NULL;
  10328. unsigned int i;
  10329. if (conn == NULL) {
  10330. return;
  10331. }
  10332. if (conn->ctx->context_type == 2) {
  10333. client_ctx = conn->ctx;
  10334. /* client context: loops must end */
  10335. conn->ctx->stop_flag = 1;
  10336. }
  10337. #ifndef NO_SSL
  10338. if (conn->client_ssl_ctx != NULL) {
  10339. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10340. }
  10341. #endif
  10342. close_connection(conn);
  10343. if (client_ctx != NULL) {
  10344. /* join worker thread and free context */
  10345. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10346. if (client_ctx->workerthreadids[i] != 0) {
  10347. mg_join_thread(client_ctx->workerthreadids[i]);
  10348. }
  10349. }
  10350. mg_free(client_ctx->workerthreadids);
  10351. mg_free(client_ctx);
  10352. (void)pthread_mutex_destroy(&conn->mutex);
  10353. mg_free(conn);
  10354. }
  10355. }
  10356. static struct mg_connection *
  10357. mg_connect_client_impl(const struct mg_client_options *client_options,
  10358. int use_ssl,
  10359. char *ebuf,
  10360. size_t ebuf_len)
  10361. {
  10362. static struct mg_context fake_ctx;
  10363. struct mg_connection *conn = NULL;
  10364. SOCKET sock;
  10365. union usa sa;
  10366. if (!connect_socket(&fake_ctx,
  10367. client_options->host,
  10368. client_options->port,
  10369. use_ssl,
  10370. ebuf,
  10371. ebuf_len,
  10372. &sock,
  10373. &sa)) {
  10374. ;
  10375. } else if ((conn = (struct mg_connection *)
  10376. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10377. mg_snprintf(NULL,
  10378. NULL, /* No truncation check for ebuf */
  10379. ebuf,
  10380. ebuf_len,
  10381. "calloc(): %s",
  10382. strerror(ERRNO));
  10383. closesocket(sock);
  10384. #ifndef NO_SSL
  10385. } else if (use_ssl
  10386. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10387. == NULL) {
  10388. mg_snprintf(NULL,
  10389. NULL, /* No truncation check for ebuf */
  10390. ebuf,
  10391. ebuf_len,
  10392. "SSL_CTX_new error");
  10393. closesocket(sock);
  10394. mg_free(conn);
  10395. conn = NULL;
  10396. #endif /* NO_SSL */
  10397. } else {
  10398. #ifdef USE_IPV6
  10399. socklen_t len = (sa.sa.sa_family == AF_INET)
  10400. ? sizeof(conn->client.rsa.sin)
  10401. : sizeof(conn->client.rsa.sin6);
  10402. struct sockaddr *psa =
  10403. (sa.sa.sa_family == AF_INET)
  10404. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10405. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10406. #else
  10407. socklen_t len = sizeof(conn->client.rsa.sin);
  10408. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10409. #endif
  10410. conn->buf_size = MAX_REQUEST_SIZE;
  10411. conn->buf = (char *)(conn + 1);
  10412. conn->ctx = &fake_ctx;
  10413. conn->client.sock = sock;
  10414. conn->client.lsa = sa;
  10415. if (getsockname(sock, psa, &len) != 0) {
  10416. mg_cry(conn,
  10417. "%s: getsockname() failed: %s",
  10418. __func__,
  10419. strerror(ERRNO));
  10420. }
  10421. conn->client.is_ssl = use_ssl ? 1 : 0;
  10422. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10423. #ifndef NO_SSL
  10424. if (use_ssl) {
  10425. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10426. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10427. * SSL_CTX_set_verify call is needed to switch off server
  10428. * certificate checking, which is off by default in OpenSSL and
  10429. * on in yaSSL. */
  10430. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10431. * SSL_VERIFY_PEER, verify_ssl_server); */
  10432. if (client_options->client_cert) {
  10433. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10434. mg_snprintf(NULL,
  10435. NULL, /* No truncation check for ebuf */
  10436. ebuf,
  10437. ebuf_len,
  10438. "Can not use SSL client certificate");
  10439. SSL_CTX_free(conn->client_ssl_ctx);
  10440. closesocket(sock);
  10441. mg_free(conn);
  10442. conn = NULL;
  10443. }
  10444. }
  10445. if (client_options->server_cert) {
  10446. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10447. client_options->server_cert,
  10448. NULL);
  10449. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10450. } else {
  10451. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10452. }
  10453. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10454. mg_snprintf(NULL,
  10455. NULL, /* No truncation check for ebuf */
  10456. ebuf,
  10457. ebuf_len,
  10458. "SSL connection error");
  10459. SSL_CTX_free(conn->client_ssl_ctx);
  10460. closesocket(sock);
  10461. mg_free(conn);
  10462. conn = NULL;
  10463. }
  10464. }
  10465. #endif
  10466. }
  10467. return conn;
  10468. }
  10469. CIVETWEB_API struct mg_connection *
  10470. mg_connect_client_secure(const struct mg_client_options *client_options,
  10471. char *error_buffer,
  10472. size_t error_buffer_size)
  10473. {
  10474. return mg_connect_client_impl(client_options,
  10475. 1,
  10476. error_buffer,
  10477. error_buffer_size);
  10478. }
  10479. struct mg_connection *
  10480. mg_connect_client(const char *host,
  10481. int port,
  10482. int use_ssl,
  10483. char *error_buffer,
  10484. size_t error_buffer_size)
  10485. {
  10486. struct mg_client_options opts;
  10487. memset(&opts, 0, sizeof(opts));
  10488. opts.host = host;
  10489. opts.port = port;
  10490. return mg_connect_client_impl(&opts,
  10491. use_ssl,
  10492. error_buffer,
  10493. error_buffer_size);
  10494. }
  10495. static const struct {
  10496. const char *proto;
  10497. size_t proto_len;
  10498. unsigned default_port;
  10499. } abs_uri_protocols[] = {{"http://", 7, 80},
  10500. {"https://", 8, 443},
  10501. {"ws://", 5, 80},
  10502. {"wss://", 6, 443},
  10503. {NULL, 0, 0}};
  10504. /* Check if the uri is valid.
  10505. * return 0 for invalid uri,
  10506. * return 1 for *,
  10507. * return 2 for relative uri,
  10508. * return 3 for absolute uri without port,
  10509. * return 4 for absolute uri with port */
  10510. static int
  10511. get_uri_type(const char *uri)
  10512. {
  10513. int i;
  10514. char *hostend, *portbegin, *portend;
  10515. unsigned long port;
  10516. /* According to the HTTP standard
  10517. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10518. * URI can be an asterisk (*) or should start with slash (relative uri),
  10519. * or it should start with the protocol (absolute uri). */
  10520. if (uri[0] == '*' && uri[1] == '\0') {
  10521. /* asterisk */
  10522. return 1;
  10523. }
  10524. if (uri[0] == '/') {
  10525. /* relative uri */
  10526. return 2;
  10527. }
  10528. /* It could be an absolute uri: */
  10529. /* This function only checks if the uri is valid, not if it is
  10530. * addressing the current server. So civetweb can also be used
  10531. * as a proxy server. */
  10532. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10533. if (mg_strncasecmp(uri,
  10534. abs_uri_protocols[i].proto,
  10535. abs_uri_protocols[i].proto_len) == 0) {
  10536. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10537. if (!hostend) {
  10538. return 0;
  10539. }
  10540. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10541. if (!portbegin) {
  10542. return 3;
  10543. }
  10544. port = strtoul(portbegin + 1, &portend, 10);
  10545. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10546. return 0;
  10547. }
  10548. return 4;
  10549. }
  10550. }
  10551. return 0;
  10552. }
  10553. /* Return NULL or the relative uri at the current server */
  10554. static const char *
  10555. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10556. {
  10557. const char *server_domain;
  10558. size_t server_domain_len;
  10559. size_t request_domain_len = 0;
  10560. unsigned long port = 0;
  10561. int i;
  10562. const char *hostbegin = NULL;
  10563. const char *hostend = NULL;
  10564. const char *portbegin;
  10565. char *portend;
  10566. /* DNS is case insensitive, so use case insensitive string compare here
  10567. */
  10568. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10569. if (!server_domain) {
  10570. return 0;
  10571. }
  10572. server_domain_len = strlen(server_domain);
  10573. if (!server_domain_len) {
  10574. return 0;
  10575. }
  10576. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10577. if (mg_strncasecmp(uri,
  10578. abs_uri_protocols[i].proto,
  10579. abs_uri_protocols[i].proto_len) == 0) {
  10580. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10581. hostend = strchr(hostbegin, '/');
  10582. if (!hostend) {
  10583. return 0;
  10584. }
  10585. portbegin = strchr(hostbegin, ':');
  10586. if ((!portbegin) || (portbegin > hostend)) {
  10587. port = abs_uri_protocols[i].default_port;
  10588. request_domain_len = (size_t)(hostend - hostbegin);
  10589. } else {
  10590. port = strtoul(portbegin + 1, &portend, 10);
  10591. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10592. return 0;
  10593. }
  10594. request_domain_len = (size_t)(portbegin - hostbegin);
  10595. }
  10596. /* protocol found, port set */
  10597. break;
  10598. }
  10599. }
  10600. if (!port) {
  10601. /* port remains 0 if the protocol is not found */
  10602. return 0;
  10603. }
  10604. #if defined(USE_IPV6)
  10605. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10606. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10607. /* Request is directed to a different port */
  10608. return 0;
  10609. }
  10610. } else
  10611. #endif
  10612. {
  10613. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10614. /* Request is directed to a different port */
  10615. return 0;
  10616. }
  10617. }
  10618. if ((request_domain_len != server_domain_len)
  10619. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10620. /* Request is directed to another server */
  10621. return 0;
  10622. }
  10623. return hostend;
  10624. }
  10625. static int
  10626. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10627. {
  10628. const char *cl;
  10629. if (ebuf_len > 0) {
  10630. ebuf[0] = '\0';
  10631. }
  10632. *err = 0;
  10633. reset_per_request_attributes(conn);
  10634. if (!conn) {
  10635. mg_snprintf(conn,
  10636. NULL, /* No truncation check for ebuf */
  10637. ebuf,
  10638. ebuf_len,
  10639. "%s",
  10640. "Internal error");
  10641. *err = 500;
  10642. return 0;
  10643. }
  10644. /* Set the time the request was received. This value should be used for
  10645. * timeouts. */
  10646. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10647. conn->request_len =
  10648. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10649. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10650. */
  10651. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10652. mg_snprintf(conn,
  10653. NULL, /* No truncation check for ebuf */
  10654. ebuf,
  10655. ebuf_len,
  10656. "%s",
  10657. "Invalid request size");
  10658. *err = 500;
  10659. return 0;
  10660. }
  10661. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10662. mg_snprintf(conn,
  10663. NULL, /* No truncation check for ebuf */
  10664. ebuf,
  10665. ebuf_len,
  10666. "%s",
  10667. "Request Too Large");
  10668. *err = 413;
  10669. return 0;
  10670. } else if (conn->request_len <= 0) {
  10671. if (conn->data_len > 0) {
  10672. mg_snprintf(conn,
  10673. NULL, /* No truncation check for ebuf */
  10674. ebuf,
  10675. ebuf_len,
  10676. "%s",
  10677. "Client sent malformed request");
  10678. *err = 400;
  10679. } else {
  10680. /* Server did not send anything -> just close the connection */
  10681. conn->must_close = 1;
  10682. mg_snprintf(conn,
  10683. NULL, /* No truncation check for ebuf */
  10684. ebuf,
  10685. ebuf_len,
  10686. "%s",
  10687. "Client did not send a request");
  10688. *err = 0;
  10689. }
  10690. return 0;
  10691. } else if (parse_http_message(conn->buf,
  10692. conn->buf_size,
  10693. &conn->request_info) <= 0) {
  10694. mg_snprintf(conn,
  10695. NULL, /* No truncation check for ebuf */
  10696. ebuf,
  10697. ebuf_len,
  10698. "%s",
  10699. "Bad Request");
  10700. *err = 400;
  10701. return 0;
  10702. } else {
  10703. /* Message is a valid request or response */
  10704. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10705. /* Request/response has content length set */
  10706. char *endptr = NULL;
  10707. conn->content_len = strtoll(cl, &endptr, 10);
  10708. if (endptr == cl) {
  10709. mg_snprintf(conn,
  10710. NULL, /* No truncation check for ebuf */
  10711. ebuf,
  10712. ebuf_len,
  10713. "%s",
  10714. "Bad Request");
  10715. *err = 411;
  10716. return 0;
  10717. }
  10718. /* Publish the content length back to the request info. */
  10719. conn->request_info.content_length = conn->content_len;
  10720. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10721. != NULL
  10722. && !mg_strcasecmp(cl, "chunked")) {
  10723. conn->is_chunked = 1;
  10724. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10725. || !mg_strcasecmp(conn->request_info.request_method,
  10726. "PUT")) {
  10727. /* POST or PUT request without content length set */
  10728. conn->content_len = -1;
  10729. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10730. "HTTP/",
  10731. 5)) {
  10732. /* Response without content length set */
  10733. conn->content_len = -1;
  10734. } else {
  10735. /* Other request */
  10736. conn->content_len = 0;
  10737. }
  10738. }
  10739. return 1;
  10740. }
  10741. int
  10742. mg_get_response(struct mg_connection *conn,
  10743. char *ebuf,
  10744. size_t ebuf_len,
  10745. int timeout)
  10746. {
  10747. if (conn) {
  10748. /* Implementation of API function for HTTP clients */
  10749. int err, ret;
  10750. struct mg_context *octx = conn->ctx;
  10751. struct mg_context rctx = *(conn->ctx);
  10752. char txt[32]; /* will not overflow */
  10753. if (timeout >= 0) {
  10754. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10755. rctx.config[REQUEST_TIMEOUT] = txt;
  10756. set_sock_timeout(conn->client.sock, timeout);
  10757. } else {
  10758. rctx.config[REQUEST_TIMEOUT] = NULL;
  10759. }
  10760. conn->ctx = &rctx;
  10761. ret = getreq(conn, ebuf, ebuf_len, &err);
  10762. conn->ctx = octx;
  10763. /* TODO: 1) uri is deprecated;
  10764. * 2) here, ri.uri is the http response code */
  10765. conn->request_info.uri = conn->request_info.request_uri;
  10766. /* TODO (mid): Define proper return values - maybe return length?
  10767. * For the first test use <0 for error and >0 for OK */
  10768. return (ret == 0) ? -1 : +1;
  10769. }
  10770. return -1;
  10771. }
  10772. struct mg_connection *
  10773. mg_download(const char *host,
  10774. int port,
  10775. int use_ssl,
  10776. char *ebuf,
  10777. size_t ebuf_len,
  10778. const char *fmt,
  10779. ...)
  10780. {
  10781. struct mg_connection *conn;
  10782. va_list ap;
  10783. int i;
  10784. int reqerr;
  10785. va_start(ap, fmt);
  10786. ebuf[0] = '\0';
  10787. /* open a connection */
  10788. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10789. if (conn != NULL) {
  10790. i = mg_vprintf(conn, fmt, ap);
  10791. if (i <= 0) {
  10792. mg_snprintf(conn,
  10793. NULL, /* No truncation check for ebuf */
  10794. ebuf,
  10795. ebuf_len,
  10796. "%s",
  10797. "Error sending request");
  10798. } else {
  10799. getreq(conn, ebuf, ebuf_len, &reqerr);
  10800. /* TODO: 1) uri is deprecated;
  10801. * 2) here, ri.uri is the http response code */
  10802. conn->request_info.uri = conn->request_info.request_uri;
  10803. }
  10804. }
  10805. /* if an error occured, close the connection */
  10806. if (ebuf[0] != '\0' && conn != NULL) {
  10807. mg_close_connection(conn);
  10808. conn = NULL;
  10809. }
  10810. va_end(ap);
  10811. return conn;
  10812. }
  10813. struct websocket_client_thread_data {
  10814. struct mg_connection *conn;
  10815. mg_websocket_data_handler data_handler;
  10816. mg_websocket_close_handler close_handler;
  10817. void *callback_data;
  10818. };
  10819. #if defined(USE_WEBSOCKET)
  10820. #ifdef _WIN32
  10821. static unsigned __stdcall websocket_client_thread(void *data)
  10822. #else
  10823. static void *
  10824. websocket_client_thread(void *data)
  10825. #endif
  10826. {
  10827. struct websocket_client_thread_data *cdata =
  10828. (struct websocket_client_thread_data *)data;
  10829. mg_set_thread_name("ws-client");
  10830. if (cdata->conn->ctx) {
  10831. if (cdata->conn->ctx->callbacks.init_thread) {
  10832. /* 3 indicates a websocket client thread */
  10833. /* TODO: check if conn->ctx can be set */
  10834. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10835. }
  10836. }
  10837. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10838. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10839. if (cdata->close_handler != NULL) {
  10840. cdata->close_handler(cdata->conn, cdata->callback_data);
  10841. }
  10842. mg_free((void *)cdata);
  10843. #ifdef _WIN32
  10844. return 0;
  10845. #else
  10846. return NULL;
  10847. #endif
  10848. }
  10849. #endif
  10850. struct mg_connection *
  10851. mg_connect_websocket_client(const char *host,
  10852. int port,
  10853. int use_ssl,
  10854. char *error_buffer,
  10855. size_t error_buffer_size,
  10856. const char *path,
  10857. const char *origin,
  10858. mg_websocket_data_handler data_func,
  10859. mg_websocket_close_handler close_func,
  10860. void *user_data)
  10861. {
  10862. struct mg_connection *conn = NULL;
  10863. #if defined(USE_WEBSOCKET)
  10864. struct mg_context *newctx = NULL;
  10865. struct websocket_client_thread_data *thread_data;
  10866. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10867. static const char *handshake_req;
  10868. if (origin != NULL) {
  10869. handshake_req = "GET %s HTTP/1.1\r\n"
  10870. "Host: %s\r\n"
  10871. "Upgrade: websocket\r\n"
  10872. "Connection: Upgrade\r\n"
  10873. "Sec-WebSocket-Key: %s\r\n"
  10874. "Sec-WebSocket-Version: 13\r\n"
  10875. "Origin: %s\r\n"
  10876. "\r\n";
  10877. } else {
  10878. handshake_req = "GET %s HTTP/1.1\r\n"
  10879. "Host: %s\r\n"
  10880. "Upgrade: websocket\r\n"
  10881. "Connection: Upgrade\r\n"
  10882. "Sec-WebSocket-Key: %s\r\n"
  10883. "Sec-WebSocket-Version: 13\r\n"
  10884. "\r\n";
  10885. }
  10886. /* Establish the client connection and request upgrade */
  10887. conn = mg_download(host,
  10888. port,
  10889. use_ssl,
  10890. error_buffer,
  10891. error_buffer_size,
  10892. handshake_req,
  10893. path,
  10894. host,
  10895. magic,
  10896. origin);
  10897. /* Connection object will be null if something goes wrong */
  10898. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10899. if (!*error_buffer) {
  10900. /* if there is a connection, but it did not return 101,
  10901. * error_buffer is not yet set */
  10902. mg_snprintf(conn,
  10903. NULL, /* No truncation check for ebuf */
  10904. error_buffer,
  10905. error_buffer_size,
  10906. "Unexpected server reply");
  10907. }
  10908. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10909. if (conn != NULL) {
  10910. mg_free(conn);
  10911. conn = NULL;
  10912. }
  10913. return conn;
  10914. }
  10915. /* For client connections, mg_context is fake. Since we need to set a
  10916. * callback function, we need to create a copy and modify it. */
  10917. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10918. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10919. newctx->user_data = user_data;
  10920. newctx->context_type = 2; /* client context type */
  10921. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10922. newctx->workerthreadids =
  10923. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10924. conn->ctx = newctx;
  10925. thread_data = (struct websocket_client_thread_data *)
  10926. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10927. thread_data->conn = conn;
  10928. thread_data->data_handler = data_func;
  10929. thread_data->close_handler = close_func;
  10930. thread_data->callback_data = NULL;
  10931. /* Start a thread to read the websocket client connection
  10932. * This thread will automatically stop when mg_disconnect is
  10933. * called on the client connection */
  10934. if (mg_start_thread_with_id(websocket_client_thread,
  10935. (void *)thread_data,
  10936. newctx->workerthreadids) != 0) {
  10937. mg_free((void *)thread_data);
  10938. mg_free((void *)newctx->workerthreadids);
  10939. mg_free((void *)newctx);
  10940. mg_free((void *)conn);
  10941. conn = NULL;
  10942. DEBUG_TRACE("%s",
  10943. "Websocket client connect thread could not be started\r\n");
  10944. }
  10945. #else
  10946. /* Appease "unused parameter" warnings */
  10947. (void)host;
  10948. (void)port;
  10949. (void)use_ssl;
  10950. (void)error_buffer;
  10951. (void)error_buffer_size;
  10952. (void)path;
  10953. (void)origin;
  10954. (void)user_data;
  10955. (void)data_func;
  10956. (void)close_func;
  10957. #endif
  10958. return conn;
  10959. }
  10960. static void
  10961. process_new_connection(struct mg_connection *conn)
  10962. {
  10963. if (conn && conn->ctx) {
  10964. struct mg_request_info *ri = &conn->request_info;
  10965. int keep_alive_enabled, keep_alive, discard_len;
  10966. char ebuf[100];
  10967. const char *hostend;
  10968. int reqerr, uri_type;
  10969. keep_alive_enabled =
  10970. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10971. /* Important: on new connection, reset the receiving buffer. Credit
  10972. * goes to crule42. */
  10973. conn->data_len = 0;
  10974. do {
  10975. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10976. /* The request sent by the client could not be understood by
  10977. * the server, or it was incomplete or a timeout. Send an
  10978. * error message and close the connection. */
  10979. if (reqerr > 0) {
  10980. /*assert(ebuf[0] != '\0');*/
  10981. send_http_error(conn, reqerr, "%s", ebuf);
  10982. }
  10983. } else if (strcmp(ri->http_version, "1.0")
  10984. && strcmp(ri->http_version, "1.1")) {
  10985. mg_snprintf(conn,
  10986. NULL, /* No truncation check for ebuf */
  10987. ebuf,
  10988. sizeof(ebuf),
  10989. "Bad HTTP version: [%s]",
  10990. ri->http_version);
  10991. send_http_error(conn, 505, "%s", ebuf);
  10992. }
  10993. if (ebuf[0] == '\0') {
  10994. uri_type = get_uri_type(conn->request_info.request_uri);
  10995. switch (uri_type) {
  10996. case 1:
  10997. /* Asterisk */
  10998. conn->request_info.local_uri = NULL;
  10999. break;
  11000. case 2:
  11001. /* relative uri */
  11002. conn->request_info.local_uri =
  11003. conn->request_info.request_uri;
  11004. break;
  11005. case 3:
  11006. case 4:
  11007. /* absolute uri (with/without port) */
  11008. hostend = get_rel_url_at_current_server(
  11009. conn->request_info.request_uri, conn);
  11010. if (hostend) {
  11011. conn->request_info.local_uri = hostend;
  11012. } else {
  11013. conn->request_info.local_uri = NULL;
  11014. }
  11015. break;
  11016. default:
  11017. mg_snprintf(conn,
  11018. NULL, /* No truncation check for ebuf */
  11019. ebuf,
  11020. sizeof(ebuf),
  11021. "Invalid URI: [%s]",
  11022. ri->request_uri);
  11023. send_http_error(conn, 400, "%s", ebuf);
  11024. break;
  11025. }
  11026. /* TODO: cleanup uri, local_uri and request_uri */
  11027. conn->request_info.uri = conn->request_info.local_uri;
  11028. }
  11029. if (ebuf[0] == '\0') {
  11030. if (conn->request_info.local_uri) {
  11031. /* handle request to local server */
  11032. handle_request(conn);
  11033. if (conn->ctx->callbacks.end_request != NULL) {
  11034. conn->ctx->callbacks.end_request(conn,
  11035. conn->status_code);
  11036. }
  11037. log_access(conn);
  11038. } else {
  11039. /* TODO: handle non-local request (PROXY) */
  11040. conn->must_close = 1;
  11041. }
  11042. } else {
  11043. conn->must_close = 1;
  11044. }
  11045. if (ri->remote_user != NULL) {
  11046. mg_free((void *)ri->remote_user);
  11047. /* Important! When having connections with and without auth
  11048. * would cause double free and then crash */
  11049. ri->remote_user = NULL;
  11050. }
  11051. /* NOTE(lsm): order is important here. should_keep_alive() call
  11052. * is
  11053. * using parsed request, which will be invalid after memmove's
  11054. * below.
  11055. * Therefore, memorize should_keep_alive() result now for later
  11056. * use
  11057. * in loop exit condition. */
  11058. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  11059. && conn->content_len >= 0 && should_keep_alive(conn);
  11060. /* Discard all buffered data for this request */
  11061. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11062. && ((conn->request_len + conn->content_len)
  11063. < (int64_t)conn->data_len))
  11064. ? (int)(conn->request_len + conn->content_len)
  11065. : conn->data_len;
  11066. /*assert(discard_len >= 0);*/
  11067. if (discard_len < 0)
  11068. break;
  11069. conn->data_len -= discard_len;
  11070. if (conn->data_len > 0) {
  11071. memmove(conn->buf,
  11072. conn->buf + discard_len,
  11073. (size_t)conn->data_len);
  11074. }
  11075. /* assert(conn->data_len >= 0); */
  11076. /* assert(conn->data_len <= conn->buf_size); */
  11077. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11078. break;
  11079. }
  11080. } while (keep_alive);
  11081. }
  11082. }
  11083. #if defined(ALTERNATIVE_QUEUE)
  11084. static void
  11085. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11086. {
  11087. unsigned int i;
  11088. for (;;) {
  11089. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11090. /* find a free worker slot and signal it */
  11091. if (ctx->client_socks[i].in_use == 0) {
  11092. ctx->client_socks[i] = *sp;
  11093. ctx->client_socks[i].in_use = 1;
  11094. event_signal(ctx->client_wait_events[i]);
  11095. return;
  11096. }
  11097. }
  11098. /* queue is full */
  11099. mg_sleep(1);
  11100. }
  11101. }
  11102. static int
  11103. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11104. {
  11105. ctx->client_socks[thread_index].in_use = 0;
  11106. event_wait(ctx->client_wait_events[thread_index]);
  11107. *sp = ctx->client_socks[thread_index];
  11108. return !ctx->stop_flag;
  11109. }
  11110. #else /* ALTERNATIVE_QUEUE */
  11111. /* Worker threads take accepted socket from the queue */
  11112. static int
  11113. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11114. {
  11115. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11116. (void)thread_index;
  11117. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11118. DEBUG_TRACE("%s", "going idle");
  11119. /* If the queue is empty, wait. We're idle at this point. */
  11120. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11121. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11122. }
  11123. /* If we're stopping, sq_head may be equal to sq_tail. */
  11124. if (ctx->sq_head > ctx->sq_tail) {
  11125. /* Copy socket from the queue and increment tail */
  11126. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11127. ctx->sq_tail++;
  11128. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11129. /* Wrap pointers if needed */
  11130. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11131. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11132. ctx->sq_head -= QUEUE_SIZE(ctx);
  11133. }
  11134. }
  11135. (void)pthread_cond_signal(&ctx->sq_empty);
  11136. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11137. return !ctx->stop_flag;
  11138. #undef QUEUE_SIZE
  11139. }
  11140. /* Master thread adds accepted socket to a queue */
  11141. static void
  11142. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11143. {
  11144. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11145. if (!ctx) {
  11146. return;
  11147. }
  11148. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11149. /* If the queue is full, wait */
  11150. while (ctx->stop_flag == 0
  11151. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11152. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11153. }
  11154. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11155. /* Copy socket to the queue and increment head */
  11156. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11157. ctx->sq_head++;
  11158. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11159. }
  11160. (void)pthread_cond_signal(&ctx->sq_full);
  11161. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11162. #undef QUEUE_SIZE
  11163. }
  11164. #endif /* ALTERNATIVE_QUEUE */
  11165. struct worker_thread_args {
  11166. struct mg_context *ctx;
  11167. int index;
  11168. };
  11169. static void *
  11170. worker_thread_run(struct worker_thread_args *thread_args)
  11171. {
  11172. struct mg_context *ctx = thread_args->ctx;
  11173. struct mg_connection *conn;
  11174. struct mg_workerTLS tls;
  11175. #if defined(MG_LEGACY_INTERFACE)
  11176. uint32_t addr;
  11177. #endif
  11178. mg_set_thread_name("worker");
  11179. tls.is_master = 0;
  11180. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11181. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11182. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11183. #endif
  11184. if (ctx->callbacks.init_thread) {
  11185. /* call init_thread for a worker thread (type 1) */
  11186. ctx->callbacks.init_thread(ctx, 1);
  11187. }
  11188. conn =
  11189. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11190. if (conn == NULL) {
  11191. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11192. } else {
  11193. pthread_setspecific(sTlsKey, &tls);
  11194. conn->buf_size = MAX_REQUEST_SIZE;
  11195. conn->buf = (char *)(conn + 1);
  11196. conn->ctx = ctx;
  11197. conn->thread_index = thread_args->index;
  11198. conn->request_info.user_data = ctx->user_data;
  11199. /* Allocate a mutex for this connection to allow communication both
  11200. * within the request handler and from elsewhere in the application
  11201. */
  11202. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11203. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11204. * signal sq_empty condvar to wake up the master waiting in
  11205. * produce_socket() */
  11206. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11207. conn->conn_birth_time = time(NULL);
  11208. /* Fill in IP, port info early so even if SSL setup below fails,
  11209. * error handler would have the corresponding info.
  11210. * Thanks to Johannes Winkelmann for the patch.
  11211. */
  11212. #if defined(USE_IPV6)
  11213. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11214. conn->request_info.remote_port =
  11215. ntohs(conn->client.rsa.sin6.sin6_port);
  11216. } else
  11217. #endif
  11218. {
  11219. conn->request_info.remote_port =
  11220. ntohs(conn->client.rsa.sin.sin_port);
  11221. }
  11222. sockaddr_to_string(conn->request_info.remote_addr,
  11223. sizeof(conn->request_info.remote_addr),
  11224. &conn->client.rsa);
  11225. #if defined(MG_LEGACY_INTERFACE)
  11226. /* This legacy interface only works for the IPv4 case */
  11227. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11228. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11229. #endif
  11230. conn->request_info.is_ssl = conn->client.is_ssl;
  11231. if (conn->client.is_ssl) {
  11232. #ifndef NO_SSL
  11233. /* HTTPS connection */
  11234. if (sslize(conn, conn->ctx->ssl_ctx, SSL_accept)) {
  11235. /* Get SSL client certificate information (if set) */
  11236. ssl_get_client_cert_info(conn);
  11237. /* process HTTPS connection */
  11238. process_new_connection(conn);
  11239. /* Free client certificate info */
  11240. if (conn->request_info.client_cert) {
  11241. mg_free(
  11242. (void *)(conn->request_info.client_cert->subject));
  11243. mg_free(
  11244. (void *)(conn->request_info.client_cert->issuer));
  11245. mg_free(
  11246. (void *)(conn->request_info.client_cert->serial));
  11247. mg_free(
  11248. (void *)(conn->request_info.client_cert->finger));
  11249. conn->request_info.client_cert->subject = 0;
  11250. conn->request_info.client_cert->issuer = 0;
  11251. conn->request_info.client_cert->serial = 0;
  11252. conn->request_info.client_cert->finger = 0;
  11253. mg_free(conn->request_info.client_cert);
  11254. conn->request_info.client_cert = 0;
  11255. }
  11256. }
  11257. #endif
  11258. } else {
  11259. /* process HTTP connection */
  11260. process_new_connection(conn);
  11261. }
  11262. close_connection(conn);
  11263. }
  11264. }
  11265. pthread_setspecific(sTlsKey, NULL);
  11266. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11267. CloseHandle(tls.pthread_cond_helper_mutex);
  11268. #endif
  11269. pthread_mutex_destroy(&conn->mutex);
  11270. mg_free(conn);
  11271. DEBUG_TRACE("%s", "exiting");
  11272. return NULL;
  11273. }
  11274. /* Threads have different return types on Windows and Unix. */
  11275. #ifdef _WIN32
  11276. static unsigned __stdcall worker_thread(void *thread_func_param)
  11277. {
  11278. struct worker_thread_args *pwta =
  11279. (struct worker_thread_args *)thread_func_param;
  11280. worker_thread_run(pwta);
  11281. mg_free(thread_func_param);
  11282. return 0;
  11283. }
  11284. #else
  11285. static void *
  11286. worker_thread(void *thread_func_param)
  11287. {
  11288. struct worker_thread_args *pwta =
  11289. (struct worker_thread_args *)thread_func_param;
  11290. worker_thread_run(pwta);
  11291. mg_free(thread_func_param);
  11292. return NULL;
  11293. }
  11294. #endif /* _WIN32 */
  11295. static void
  11296. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11297. {
  11298. struct socket so;
  11299. char src_addr[IP_ADDR_STR_LEN];
  11300. socklen_t len = sizeof(so.rsa);
  11301. int on = 1;
  11302. int timeout;
  11303. if (!listener) {
  11304. return;
  11305. }
  11306. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11307. == INVALID_SOCKET) {
  11308. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11309. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11310. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11311. closesocket(so.sock);
  11312. so.sock = INVALID_SOCKET;
  11313. } else {
  11314. /* Put so socket structure into the queue */
  11315. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11316. set_close_on_exec(so.sock, fc(ctx));
  11317. so.is_ssl = listener->is_ssl;
  11318. so.ssl_redir = listener->ssl_redir;
  11319. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11320. mg_cry(fc(ctx),
  11321. "%s: getsockname() failed: %s",
  11322. __func__,
  11323. strerror(ERRNO));
  11324. }
  11325. /* Set TCP keep-alive. This is needed because if HTTP-level
  11326. * keep-alive
  11327. * is enabled, and client resets the connection, server won't get
  11328. * TCP FIN or RST and will keep the connection open forever. With
  11329. * TCP keep-alive, next keep-alive handshake will figure out that
  11330. * the client is down and will close the server end.
  11331. * Thanks to Igor Klopov who suggested the patch. */
  11332. if (setsockopt(so.sock,
  11333. SOL_SOCKET,
  11334. SO_KEEPALIVE,
  11335. (SOCK_OPT_TYPE)&on,
  11336. sizeof(on)) != 0) {
  11337. mg_cry(fc(ctx),
  11338. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11339. __func__,
  11340. strerror(ERRNO));
  11341. }
  11342. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11343. * to effectively fill up the underlying IP packet payload and
  11344. * reduce the overhead of sending lots of small buffers. However
  11345. * this hurts the server's throughput (ie. operations per second)
  11346. * when HTTP 1.1 persistent connections are used and the responses
  11347. * are relatively small (eg. less than 1400 bytes).
  11348. */
  11349. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11350. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11351. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11352. mg_cry(fc(ctx),
  11353. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11354. __func__,
  11355. strerror(ERRNO));
  11356. }
  11357. }
  11358. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11359. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11360. } else {
  11361. timeout = -1;
  11362. }
  11363. if (timeout > 0) {
  11364. set_sock_timeout(so.sock, timeout);
  11365. }
  11366. produce_socket(ctx, &so);
  11367. }
  11368. }
  11369. static void
  11370. master_thread_run(void *thread_func_param)
  11371. {
  11372. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11373. struct mg_workerTLS tls;
  11374. struct pollfd *pfd;
  11375. unsigned int i;
  11376. unsigned int workerthreadcount;
  11377. if (!ctx) {
  11378. return;
  11379. }
  11380. mg_set_thread_name("master");
  11381. /* Increase priority of the master thread */
  11382. #if defined(_WIN32)
  11383. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11384. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11385. int min_prio = sched_get_priority_min(SCHED_RR);
  11386. int max_prio = sched_get_priority_max(SCHED_RR);
  11387. if ((min_prio >= 0) && (max_prio >= 0)
  11388. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11389. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11390. struct sched_param sched_param = {0};
  11391. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11392. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11393. }
  11394. #endif
  11395. /* Initialize thread local storage */
  11396. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11397. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11398. #endif
  11399. tls.is_master = 1;
  11400. pthread_setspecific(sTlsKey, &tls);
  11401. if (ctx->callbacks.init_thread) {
  11402. /* Callback for the master thread (type 0) */
  11403. ctx->callbacks.init_thread(ctx, 0);
  11404. }
  11405. /* Server starts *now* */
  11406. ctx->start_time = time(NULL);
  11407. /* Start the server */
  11408. pfd = ctx->listening_socket_fds;
  11409. while (ctx->stop_flag == 0) {
  11410. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11411. pfd[i].fd = ctx->listening_sockets[i].sock;
  11412. pfd[i].events = POLLIN;
  11413. }
  11414. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11415. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11416. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11417. * successful poll, and POLLIN is defined as
  11418. * (POLLRDNORM | POLLRDBAND)
  11419. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11420. * pfd[i].revents == POLLIN. */
  11421. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11422. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11423. }
  11424. }
  11425. }
  11426. }
  11427. /* Here stop_flag is 1 - Initiate shutdown. */
  11428. DEBUG_TRACE("%s", "stopping workers");
  11429. /* Stop signal received: somebody called mg_stop. Quit. */
  11430. close_all_listening_sockets(ctx);
  11431. /* Wakeup workers that are waiting for connections to handle. */
  11432. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11433. #if defined(ALTERNATIVE_QUEUE)
  11434. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11435. event_signal(ctx->client_wait_events[i]);
  11436. /* Since we know all sockets, we can shutdown the connections. */
  11437. if (ctx->client_socks[i].in_use) {
  11438. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11439. }
  11440. }
  11441. #else
  11442. pthread_cond_broadcast(&ctx->sq_full);
  11443. #endif
  11444. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11445. /* Join all worker threads to avoid leaking threads. */
  11446. workerthreadcount = ctx->cfg_worker_threads;
  11447. for (i = 0; i < workerthreadcount; i++) {
  11448. if (ctx->workerthreadids[i] != 0) {
  11449. mg_join_thread(ctx->workerthreadids[i]);
  11450. }
  11451. }
  11452. #if !defined(NO_SSL)
  11453. if (ctx->ssl_ctx != NULL) {
  11454. uninitialize_ssl(ctx);
  11455. }
  11456. #endif
  11457. DEBUG_TRACE("%s", "exiting");
  11458. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11459. CloseHandle(tls.pthread_cond_helper_mutex);
  11460. #endif
  11461. pthread_setspecific(sTlsKey, NULL);
  11462. /* Signal mg_stop() that we're done.
  11463. * WARNING: This must be the very last thing this
  11464. * thread does, as ctx becomes invalid after this line. */
  11465. ctx->stop_flag = 2;
  11466. }
  11467. /* Threads have different return types on Windows and Unix. */
  11468. #ifdef _WIN32
  11469. static unsigned __stdcall master_thread(void *thread_func_param)
  11470. {
  11471. master_thread_run(thread_func_param);
  11472. return 0;
  11473. }
  11474. #else
  11475. static void *
  11476. master_thread(void *thread_func_param)
  11477. {
  11478. master_thread_run(thread_func_param);
  11479. return NULL;
  11480. }
  11481. #endif /* _WIN32 */
  11482. static void
  11483. free_context(struct mg_context *ctx)
  11484. {
  11485. int i;
  11486. struct mg_handler_info *tmp_rh;
  11487. if (ctx == NULL) {
  11488. return;
  11489. }
  11490. if (ctx->callbacks.exit_context) {
  11491. ctx->callbacks.exit_context(ctx);
  11492. }
  11493. /* All threads exited, no sync is needed. Destroy thread mutex and
  11494. * condvars
  11495. */
  11496. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11497. #if defined(ALTERNATIVE_QUEUE)
  11498. mg_free(ctx->client_socks);
  11499. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11500. event_destroy(ctx->client_wait_events[i]);
  11501. }
  11502. mg_free(ctx->client_wait_events);
  11503. #else
  11504. (void)pthread_cond_destroy(&ctx->sq_empty);
  11505. (void)pthread_cond_destroy(&ctx->sq_full);
  11506. #endif
  11507. /* Destroy other context global data structures mutex */
  11508. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11509. #if defined(USE_TIMERS)
  11510. timers_exit(ctx);
  11511. #endif
  11512. /* Deallocate config parameters */
  11513. for (i = 0; i < NUM_OPTIONS; i++) {
  11514. if (ctx->config[i] != NULL) {
  11515. #if defined(_MSC_VER)
  11516. #pragma warning(suppress : 6001)
  11517. #endif
  11518. mg_free(ctx->config[i]);
  11519. }
  11520. }
  11521. /* Deallocate request handlers */
  11522. while (ctx->handlers) {
  11523. tmp_rh = ctx->handlers;
  11524. ctx->handlers = tmp_rh->next;
  11525. mg_free(tmp_rh->uri);
  11526. mg_free(tmp_rh);
  11527. }
  11528. #ifndef NO_SSL
  11529. /* Deallocate SSL context */
  11530. if (ctx->ssl_ctx != NULL) {
  11531. SSL_CTX_free(ctx->ssl_ctx);
  11532. }
  11533. #endif /* !NO_SSL */
  11534. /* Deallocate worker thread ID array */
  11535. if (ctx->workerthreadids != NULL) {
  11536. mg_free(ctx->workerthreadids);
  11537. }
  11538. /* Deallocate the tls variable */
  11539. if (mg_atomic_dec(&sTlsInit) == 0) {
  11540. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11541. DeleteCriticalSection(&global_log_file_lock);
  11542. #endif /* _WIN32 && !__SYMBIAN32__ */
  11543. #if !defined(_WIN32)
  11544. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11545. #endif
  11546. pthread_key_delete(sTlsKey);
  11547. }
  11548. /* deallocate system name string */
  11549. mg_free(ctx->systemName);
  11550. /* Deallocate context itself */
  11551. mg_free(ctx);
  11552. }
  11553. void
  11554. mg_stop(struct mg_context *ctx)
  11555. {
  11556. pthread_t mt;
  11557. if (!ctx) {
  11558. return;
  11559. }
  11560. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11561. * two threads is not allowed. */
  11562. mt = ctx->masterthreadid;
  11563. if (mt == 0) {
  11564. return;
  11565. }
  11566. ctx->masterthreadid = 0;
  11567. /* Set stop flag, so all threads know they have to exit. */
  11568. ctx->stop_flag = 1;
  11569. /* Wait until everything has stopped. */
  11570. while (ctx->stop_flag != 2) {
  11571. (void)mg_sleep(10);
  11572. }
  11573. mg_join_thread(mt);
  11574. free_context(ctx);
  11575. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11576. (void)WSACleanup();
  11577. #endif /* _WIN32 && !__SYMBIAN32__ */
  11578. }
  11579. static void
  11580. get_system_name(char **sysName)
  11581. {
  11582. #if defined(_WIN32)
  11583. #if !defined(__SYMBIAN32__)
  11584. #if defined(_WIN32_WCE)
  11585. *sysName = mg_strdup("WinCE");
  11586. #else
  11587. char name[128];
  11588. DWORD dwVersion = 0;
  11589. DWORD dwMajorVersion = 0;
  11590. DWORD dwMinorVersion = 0;
  11591. DWORD dwBuild = 0;
  11592. #ifdef _MSC_VER
  11593. #pragma warning(push)
  11594. // GetVersion was declared deprecated
  11595. #pragma warning(disable : 4996)
  11596. #endif
  11597. dwVersion = GetVersion();
  11598. #ifdef _MSC_VER
  11599. #pragma warning(pop)
  11600. #endif
  11601. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11602. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11603. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11604. (void)dwBuild;
  11605. sprintf(name,
  11606. "Windows %u.%u",
  11607. (unsigned)dwMajorVersion,
  11608. (unsigned)dwMinorVersion);
  11609. *sysName = mg_strdup(name);
  11610. #endif
  11611. #else
  11612. *sysName = mg_strdup("Symbian");
  11613. #endif
  11614. #else
  11615. struct utsname name;
  11616. memset(&name, 0, sizeof(name));
  11617. uname(&name);
  11618. *sysName = mg_strdup(name.sysname);
  11619. #endif
  11620. }
  11621. struct mg_context *
  11622. mg_start(const struct mg_callbacks *callbacks,
  11623. void *user_data,
  11624. const char **options)
  11625. {
  11626. struct mg_context *ctx;
  11627. const char *name, *value, *default_value;
  11628. int idx, ok, workerthreadcount;
  11629. unsigned int i;
  11630. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11631. struct mg_workerTLS tls;
  11632. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11633. WSADATA data;
  11634. WSAStartup(MAKEWORD(2, 2), &data);
  11635. #endif /* _WIN32 && !__SYMBIAN32__ */
  11636. /* Allocate context and initialize reasonable general case defaults. */
  11637. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11638. return NULL;
  11639. }
  11640. /* Random number generator will initialize at the first call */
  11641. ctx->auth_nonce_mask =
  11642. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11643. if (mg_atomic_inc(&sTlsInit) == 1) {
  11644. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11645. InitializeCriticalSection(&global_log_file_lock);
  11646. #endif /* _WIN32 && !__SYMBIAN32__ */
  11647. #if !defined(_WIN32)
  11648. pthread_mutexattr_init(&pthread_mutex_attr);
  11649. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11650. #endif
  11651. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11652. /* Fatal error - abort start. However, this situation should
  11653. * never
  11654. * occur in practice. */
  11655. mg_atomic_dec(&sTlsInit);
  11656. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11657. mg_free(ctx);
  11658. return NULL;
  11659. }
  11660. } else {
  11661. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11662. * initialized. */
  11663. mg_sleep(1);
  11664. }
  11665. tls.is_master = -1;
  11666. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11667. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11668. tls.pthread_cond_helper_mutex = NULL;
  11669. #endif
  11670. pthread_setspecific(sTlsKey, &tls);
  11671. #if defined(USE_LUA)
  11672. lua_init_optional_libraries();
  11673. #endif
  11674. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11675. #if !defined(ALTERNATIVE_QUEUE)
  11676. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11677. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11678. #endif
  11679. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11680. if (!ok) {
  11681. /* Fatal error - abort start. However, this situation should never
  11682. * occur in practice. */
  11683. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11684. mg_free(ctx);
  11685. pthread_setspecific(sTlsKey, NULL);
  11686. return NULL;
  11687. }
  11688. if (callbacks) {
  11689. ctx->callbacks = *callbacks;
  11690. exit_callback = callbacks->exit_context;
  11691. ctx->callbacks.exit_context = 0;
  11692. }
  11693. ctx->user_data = user_data;
  11694. ctx->handlers = NULL;
  11695. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11696. ctx->shared_lua_websockets = 0;
  11697. #endif
  11698. while (options && (name = *options++) != NULL) {
  11699. if ((idx = get_option_index(name)) == -1) {
  11700. mg_cry(fc(ctx), "Invalid option: %s", name);
  11701. free_context(ctx);
  11702. pthread_setspecific(sTlsKey, NULL);
  11703. return NULL;
  11704. } else if ((value = *options++) == NULL) {
  11705. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11706. free_context(ctx);
  11707. pthread_setspecific(sTlsKey, NULL);
  11708. return NULL;
  11709. }
  11710. if (ctx->config[idx] != NULL) {
  11711. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11712. mg_free(ctx->config[idx]);
  11713. }
  11714. ctx->config[idx] = mg_strdup(value);
  11715. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11716. }
  11717. /* Set default value if needed */
  11718. for (i = 0; config_options[i].name != NULL; i++) {
  11719. default_value = config_options[i].default_value;
  11720. if (ctx->config[i] == NULL && default_value != NULL) {
  11721. ctx->config[i] = mg_strdup(default_value);
  11722. }
  11723. }
  11724. #if defined(NO_FILES)
  11725. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11726. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11727. free_context(ctx);
  11728. pthread_setspecific(sTlsKey, NULL);
  11729. return NULL;
  11730. }
  11731. #endif
  11732. get_system_name(&ctx->systemName);
  11733. /* NOTE(lsm): order is important here. SSL certificates must
  11734. * be initialized before listening ports. UID must be set last. */
  11735. if (!set_gpass_option(ctx) ||
  11736. #if !defined(NO_SSL)
  11737. !set_ssl_option(ctx) ||
  11738. #endif
  11739. !set_ports_option(ctx) ||
  11740. #if !defined(_WIN32)
  11741. !set_uid_option(ctx) ||
  11742. #endif
  11743. !set_acl_option(ctx)) {
  11744. free_context(ctx);
  11745. pthread_setspecific(sTlsKey, NULL);
  11746. return NULL;
  11747. }
  11748. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11749. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11750. * won't kill the whole process. */
  11751. (void)signal(SIGPIPE, SIG_IGN);
  11752. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11753. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11754. if (workerthreadcount > MAX_WORKER_THREADS) {
  11755. mg_cry(fc(ctx), "Too many worker threads");
  11756. free_context(ctx);
  11757. pthread_setspecific(sTlsKey, NULL);
  11758. return NULL;
  11759. }
  11760. if (workerthreadcount > 0) {
  11761. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11762. ctx->workerthreadids =
  11763. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11764. if (ctx->workerthreadids == NULL) {
  11765. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11766. free_context(ctx);
  11767. pthread_setspecific(sTlsKey, NULL);
  11768. return NULL;
  11769. }
  11770. #if defined(ALTERNATIVE_QUEUE)
  11771. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  11772. ctx->cfg_worker_threads);
  11773. if (ctx->client_wait_events == NULL) {
  11774. mg_cry(fc(ctx), "Not enough memory for worker event array");
  11775. mg_free(ctx->workerthreadids);
  11776. free_context(ctx);
  11777. pthread_setspecific(sTlsKey, NULL);
  11778. return NULL;
  11779. }
  11780. ctx->client_socks =
  11781. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  11782. if (ctx->client_wait_events == NULL) {
  11783. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  11784. mg_free(ctx->client_socks);
  11785. mg_free(ctx->workerthreadids);
  11786. free_context(ctx);
  11787. pthread_setspecific(sTlsKey, NULL);
  11788. return NULL;
  11789. }
  11790. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11791. ctx->client_wait_events[i] = event_create();
  11792. if (ctx->client_wait_events[i] == 0) {
  11793. mg_cry(fc(ctx), "Error creating worker event %i", i);
  11794. /* TODO: clean all and exit */
  11795. }
  11796. }
  11797. #endif
  11798. }
  11799. #if defined(USE_TIMERS)
  11800. if (timers_init(ctx) != 0) {
  11801. mg_cry(fc(ctx), "Error creating timers");
  11802. free_context(ctx);
  11803. pthread_setspecific(sTlsKey, NULL);
  11804. return NULL;
  11805. }
  11806. #endif
  11807. /* Context has been created - init user libraries */
  11808. if (ctx->callbacks.init_context) {
  11809. ctx->callbacks.init_context(ctx);
  11810. }
  11811. ctx->callbacks.exit_context = exit_callback;
  11812. ctx->context_type = 1; /* server context */
  11813. /* Start master (listening) thread */
  11814. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11815. /* Start worker threads */
  11816. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11817. struct worker_thread_args *wta =
  11818. mg_malloc(sizeof(struct worker_thread_args));
  11819. if (wta) {
  11820. wta->ctx = ctx;
  11821. wta->index = (int)i;
  11822. }
  11823. if ((wta == NULL)
  11824. || (mg_start_thread_with_id(worker_thread,
  11825. wta,
  11826. &ctx->workerthreadids[i]) != 0)) {
  11827. /* thread was not created */
  11828. if (wta != NULL) {
  11829. mg_free(wta);
  11830. }
  11831. if (i > 0) {
  11832. mg_cry(fc(ctx),
  11833. "Cannot start worker thread %i: error %ld",
  11834. i + 1,
  11835. (long)ERRNO);
  11836. } else {
  11837. mg_cry(fc(ctx),
  11838. "Cannot create threads: error %ld",
  11839. (long)ERRNO);
  11840. free_context(ctx);
  11841. pthread_setspecific(sTlsKey, NULL);
  11842. return NULL;
  11843. }
  11844. break;
  11845. }
  11846. }
  11847. pthread_setspecific(sTlsKey, NULL);
  11848. return ctx;
  11849. }
  11850. /* Feature check API function */
  11851. unsigned
  11852. mg_check_feature(unsigned feature)
  11853. {
  11854. static const unsigned feature_set = 0
  11855. /* Set bits for available features according to API documentation.
  11856. * This bit mask is created at compile time, according to the active
  11857. * preprocessor defines. It is a single const value at runtime. */
  11858. #if !defined(NO_FILES)
  11859. | 0x0001u
  11860. #endif
  11861. #if !defined(NO_SSL)
  11862. | 0x0002u
  11863. #endif
  11864. #if !defined(NO_CGI)
  11865. | 0x0004u
  11866. #endif
  11867. #if defined(USE_IPV6)
  11868. | 0x0008u
  11869. #endif
  11870. #if defined(USE_WEBSOCKET)
  11871. | 0x0010u
  11872. #endif
  11873. #if defined(USE_LUA)
  11874. | 0x0020u
  11875. #endif
  11876. #if defined(USE_DUKTAPE)
  11877. | 0x0040u
  11878. #endif
  11879. #if !defined(NO_CACHING)
  11880. | 0x0080u
  11881. #endif
  11882. /* Set some extra bits not defined in the API documentation.
  11883. * These bits may change without further notice. */
  11884. #if defined(MG_LEGACY_INTERFACE)
  11885. | 0x8000u
  11886. #endif
  11887. #if defined(MEMORY_DEBUGGING)
  11888. | 0x0100u
  11889. #endif
  11890. #if defined(USE_TIMERS)
  11891. | 0x0200u
  11892. #endif
  11893. #if !defined(NO_NONCE_CHECK)
  11894. | 0x0400u
  11895. #endif
  11896. #if !defined(NO_POPEN)
  11897. | 0x0800u
  11898. #endif
  11899. ;
  11900. return (feature & feature_set);
  11901. }