civetweb.c 341 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  92. * type size check"); */
  93. /* DTL -- including winsock2.h works better if lean and mean */
  94. #ifndef WIN32_LEAN_AND_MEAN
  95. #define WIN32_LEAN_AND_MEAN
  96. #endif
  97. #if defined(__SYMBIAN32__)
  98. #define NO_SSL /* SSL is not supported */
  99. #define NO_CGI /* CGI is not supported */
  100. #define PATH_MAX FILENAME_MAX
  101. #endif /* __SYMBIAN32__ */
  102. /* Include the header file here, so the CivetWeb interface is defined for the
  103. * entire implementation, including the following forward definitions. */
  104. #include "civetweb.h"
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __MACH__
  116. #define CLOCK_MONOTONIC (1)
  117. #define CLOCK_REALTIME (2)
  118. #include <sys/time.h>
  119. #include <mach/clock.h>
  120. #include <mach/mach.h>
  121. #include <mach/mach_time.h>
  122. #include <assert.h>
  123. /* clock_gettime is not implemented on OSX */
  124. int clock_gettime(int clk_id, struct timespec *t);
  125. int
  126. clock_gettime(int clk_id, struct timespec *t)
  127. {
  128. memset(t, 0, sizeof(*t));
  129. if (clk_id == CLOCK_REALTIME) {
  130. struct timeval now;
  131. int rv = gettimeofday(&now, NULL);
  132. if (rv) {
  133. return rv;
  134. }
  135. t->tv_sec = now.tv_sec;
  136. t->tv_nsec = now.tv_usec * 1000;
  137. return 0;
  138. } else if (clk_id == CLOCK_MONOTONIC) {
  139. static uint64_t clock_start_time = 0;
  140. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  141. uint64_t now = mach_absolute_time();
  142. if (clock_start_time == 0) {
  143. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  144. #if defined(DEBUG)
  145. assert(mach_status == KERN_SUCCESS);
  146. #else
  147. /* appease "unused variable" warning for release builds */
  148. (void)mach_status;
  149. #endif
  150. clock_start_time = now;
  151. }
  152. now = (uint64_t)((double)(now - clock_start_time)
  153. * (double)timebase_ifo.numer
  154. / (double)timebase_ifo.denom);
  155. t->tv_sec = now / 1000000000;
  156. t->tv_nsec = now % 1000000000;
  157. return 0;
  158. }
  159. return -1; /* EINVAL - Clock ID is unknown */
  160. }
  161. #endif
  162. #include <time.h>
  163. #include <stdlib.h>
  164. #include <stdarg.h>
  165. #include <assert.h>
  166. #include <string.h>
  167. #include <ctype.h>
  168. #include <limits.h>
  169. #include <stddef.h>
  170. #include <stdio.h>
  171. #ifndef MAX_WORKER_THREADS
  172. #define MAX_WORKER_THREADS (1024 * 64)
  173. #endif
  174. #ifndef SOCKET_TIMEOUT_QUANTUM
  175. #define SOCKET_TIMEOUT_QUANTUM (10000)
  176. #endif
  177. mg_static_assert(MAX_WORKER_THREADS >= 1,
  178. "worker threads must be a positive number");
  179. #if defined(_WIN32) \
  180. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  181. #include <windows.h>
  182. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  183. #include <ws2tcpip.h>
  184. typedef const char *SOCK_OPT_TYPE;
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (MAX_PATH)
  187. #endif
  188. #if !defined(PATH_MAX)
  189. #define PATH_MAX (4096)
  190. #endif
  191. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  192. #ifndef _IN_PORT_T
  193. #ifndef in_port_t
  194. #define in_port_t u_short
  195. #endif
  196. #endif
  197. #ifndef _WIN32_WCE
  198. #include <process.h>
  199. #include <direct.h>
  200. #include <io.h>
  201. #else /* _WIN32_WCE */
  202. #define NO_CGI /* WinCE has no pipes */
  203. typedef long off_t;
  204. #define errno ((int)(GetLastError()))
  205. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  206. #endif /* _WIN32_WCE */
  207. #define MAKEUQUAD(lo, hi) \
  208. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  209. #define RATE_DIFF (10000000) /* 100 nsecs */
  210. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  211. #define SYS2UNIX_TIME(lo, hi) \
  212. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  213. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  214. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  215. * Also use _strtoui64 on modern M$ compilers */
  216. #if defined(_MSC_VER)
  217. #if (_MSC_VER < 1300)
  218. #define STRX(x) #x
  219. #define STR(x) STRX(x)
  220. #define __func__ __FILE__ ":" STR(__LINE__)
  221. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  222. #define strtoll(x, y, z) (_atoi64(x))
  223. #else
  224. #define __func__ __FUNCTION__
  225. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  226. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  227. #endif
  228. #endif /* _MSC_VER */
  229. #define ERRNO ((int)(GetLastError()))
  230. #define NO_SOCKLEN_T
  231. #if defined(_WIN64) || defined(__MINGW64__)
  232. #define SSL_LIB "ssleay64.dll"
  233. #define CRYPTO_LIB "libeay64.dll"
  234. #else
  235. #define SSL_LIB "ssleay32.dll"
  236. #define CRYPTO_LIB "libeay32.dll"
  237. #endif
  238. #define O_NONBLOCK (0)
  239. #ifndef W_OK
  240. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  241. #endif
  242. #if !defined(EWOULDBLOCK)
  243. #define EWOULDBLOCK WSAEWOULDBLOCK
  244. #endif /* !EWOULDBLOCK */
  245. #define _POSIX_
  246. #define INT64_FMT "I64d"
  247. #define UINT64_FMT "I64u"
  248. #define WINCDECL __cdecl
  249. #define SHUT_RD (0)
  250. #define SHUT_WR (1)
  251. #define SHUT_BOTH (2)
  252. #define vsnprintf_impl _vsnprintf
  253. #define access _access
  254. #define mg_sleep(x) (Sleep(x))
  255. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  256. #ifndef popen
  257. #define popen(x, y) (_popen(x, y))
  258. #endif
  259. #ifndef pclose
  260. #define pclose(x) (_pclose(x))
  261. #endif
  262. #define close(x) (_close(x))
  263. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  264. #define RTLD_LAZY (0)
  265. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  266. #define fdopen(x, y) (_fdopen((x), (y)))
  267. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  268. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  269. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  270. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  271. #define sleep(x) (Sleep((x)*1000))
  272. #define rmdir(x) (_rmdir(x))
  273. #define timegm(x) (_mkgmtime(x))
  274. #if !defined(fileno)
  275. #define fileno(x) (_fileno(x))
  276. #endif /* !fileno MINGW #defines fileno */
  277. typedef HANDLE pthread_mutex_t;
  278. typedef DWORD pthread_key_t;
  279. typedef HANDLE pthread_t;
  280. typedef struct {
  281. CRITICAL_SECTION threadIdSec;
  282. int waitingthreadcount; /* The number of threads queued. */
  283. pthread_t *waitingthreadhdls; /* The thread handles. */
  284. } pthread_cond_t;
  285. #ifndef __clockid_t_defined
  286. typedef DWORD clockid_t;
  287. #endif
  288. #ifndef CLOCK_MONOTONIC
  289. #define CLOCK_MONOTONIC (1)
  290. #endif
  291. #ifndef CLOCK_REALTIME
  292. #define CLOCK_REALTIME (2)
  293. #endif
  294. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  295. #define _TIMESPEC_DEFINED
  296. #endif
  297. #ifndef _TIMESPEC_DEFINED
  298. struct timespec {
  299. time_t tv_sec; /* seconds */
  300. long tv_nsec; /* nanoseconds */
  301. };
  302. #endif
  303. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  304. static int pthread_mutex_lock(pthread_mutex_t *);
  305. static int pthread_mutex_unlock(pthread_mutex_t *);
  306. static void path_to_unicode(const struct mg_connection *conn,
  307. const char *path,
  308. wchar_t *wbuf,
  309. size_t wbuf_len);
  310. struct file;
  311. static const char *
  312. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  313. #if defined(HAVE_STDINT)
  314. #include <stdint.h>
  315. #else
  316. typedef unsigned char uint8_t;
  317. typedef unsigned short uint16_t;
  318. typedef unsigned int uint32_t;
  319. typedef unsigned __int64 uint64_t;
  320. typedef __int64 int64_t;
  321. #define INT64_MAX (9223372036854775807)
  322. #endif /* HAVE_STDINT */
  323. /* POSIX dirent interface */
  324. struct dirent {
  325. char d_name[PATH_MAX];
  326. };
  327. typedef struct DIR {
  328. HANDLE handle;
  329. WIN32_FIND_DATAW info;
  330. struct dirent result;
  331. } DIR;
  332. #if defined(_WIN32) && !defined(POLLIN)
  333. #ifndef HAVE_POLL
  334. struct pollfd {
  335. SOCKET fd;
  336. short events;
  337. short revents;
  338. };
  339. #define POLLIN (0x0300)
  340. #endif
  341. #endif
  342. /* Mark required libraries */
  343. #if defined(_MSC_VER)
  344. #pragma comment(lib, "Ws2_32.lib")
  345. #endif
  346. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  347. block */
  348. #include <sys/wait.h>
  349. #include <sys/socket.h>
  350. #include <sys/poll.h>
  351. #include <netinet/in.h>
  352. #include <arpa/inet.h>
  353. #include <sys/time.h>
  354. #include <sys/utsname.h>
  355. #include <stdint.h>
  356. #include <inttypes.h>
  357. #include <netdb.h>
  358. #include <netinet/tcp.h>
  359. typedef const void *SOCK_OPT_TYPE;
  360. #if defined(ANDROID)
  361. typedef unsigned short int in_port_t;
  362. #endif
  363. #include <pwd.h>
  364. #include <unistd.h>
  365. #include <grp.h>
  366. #include <dirent.h>
  367. #define vsnprintf_impl vsnprintf
  368. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  369. #include <dlfcn.h>
  370. #endif
  371. #include <pthread.h>
  372. #if defined(__MACH__)
  373. #define SSL_LIB "libssl.dylib"
  374. #define CRYPTO_LIB "libcrypto.dylib"
  375. #else
  376. #if !defined(SSL_LIB)
  377. #define SSL_LIB "libssl.so"
  378. #endif
  379. #if !defined(CRYPTO_LIB)
  380. #define CRYPTO_LIB "libcrypto.so"
  381. #endif
  382. #endif
  383. #ifndef O_BINARY
  384. #define O_BINARY (0)
  385. #endif /* O_BINARY */
  386. #define closesocket(a) (close(a))
  387. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  388. #define mg_remove(conn, x) (remove(x))
  389. #define mg_sleep(x) (usleep((x)*1000))
  390. #define mg_opendir(conn, x) (opendir(x))
  391. #define mg_closedir(x) (closedir(x))
  392. #define mg_readdir(x) (readdir(x))
  393. #define ERRNO (errno)
  394. #define INVALID_SOCKET (-1)
  395. #define INT64_FMT PRId64
  396. #define UINT64_FMT PRIu64
  397. typedef int SOCKET;
  398. #define WINCDECL
  399. #if defined(__hpux)
  400. /* HPUX 11 does not have monotonic, fall back to realtime */
  401. #ifndef CLOCK_MONOTONIC
  402. #define CLOCK_MONOTONIC CLOCK_REALTIME
  403. #endif
  404. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  405. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  406. * the prototypes use int* rather than socklen_t* which matches the
  407. * actual library expectation. When called with the wrong size arg
  408. * accept() returns a zero client inet addr and check_acl() always
  409. * fails. Since socklen_t is widely used below, just force replace
  410. * their typedef with int. - DTL
  411. */
  412. #define socklen_t int
  413. #endif /* hpux */
  414. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  415. block */
  416. /* va_copy should always be a macro, C99 and C++11 - DTL */
  417. #ifndef va_copy
  418. #define va_copy(x, y) ((x) = (y))
  419. #endif
  420. #ifdef _WIN32
  421. /* Create substitutes for POSIX functions in Win32. */
  422. #if defined(__MINGW32__)
  423. /* Show no warning in case system functions are not used. */
  424. #pragma GCC diagnostic push
  425. #pragma GCC diagnostic ignored "-Wunused-function"
  426. #endif
  427. static CRITICAL_SECTION global_log_file_lock;
  428. static DWORD
  429. pthread_self(void)
  430. {
  431. return GetCurrentThreadId();
  432. }
  433. static int
  434. pthread_key_create(
  435. pthread_key_t *key,
  436. void (*_ignored)(void *) /* destructor not supported for Windows */
  437. )
  438. {
  439. (void)_ignored;
  440. if ((key != 0)) {
  441. *key = TlsAlloc();
  442. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  443. }
  444. return -2;
  445. }
  446. static int
  447. pthread_key_delete(pthread_key_t key)
  448. {
  449. return TlsFree(key) ? 0 : 1;
  450. }
  451. static int
  452. pthread_setspecific(pthread_key_t key, void *value)
  453. {
  454. return TlsSetValue(key, value) ? 0 : 1;
  455. }
  456. static void *
  457. pthread_getspecific(pthread_key_t key)
  458. {
  459. return TlsGetValue(key);
  460. }
  461. #if defined(__MINGW32__)
  462. /* Enable unused function warning again */
  463. #pragma GCC diagnostic pop
  464. #endif
  465. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  466. #else
  467. static pthread_mutexattr_t pthread_mutex_attr;
  468. #endif /* _WIN32 */
  469. #define PASSWORDS_FILE_NAME ".htpasswd"
  470. #define CGI_ENVIRONMENT_SIZE (4096)
  471. #define MAX_CGI_ENVIR_VARS (256)
  472. #define MG_BUF_LEN (8192)
  473. #ifndef MAX_REQUEST_SIZE
  474. #define MAX_REQUEST_SIZE (16384)
  475. #endif
  476. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  477. "request size length must be a positive number");
  478. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  479. #if !defined(DEBUG_TRACE)
  480. #if defined(DEBUG)
  481. static void DEBUG_TRACE_FUNC(const char *func,
  482. unsigned line,
  483. PRINTF_FORMAT_STRING(const char *fmt),
  484. ...) PRINTF_ARGS(3, 4);
  485. static void
  486. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  487. {
  488. va_list args;
  489. flockfile(stdout);
  490. printf("*** %lu.%p.%s.%u: ",
  491. (unsigned long)time(NULL),
  492. (void *)pthread_self(),
  493. func,
  494. line);
  495. va_start(args, fmt);
  496. vprintf(fmt, args);
  497. va_end(args);
  498. putchar('\n');
  499. fflush(stdout);
  500. funlockfile(stdout);
  501. }
  502. #define DEBUG_TRACE(fmt, ...) \
  503. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  504. #else
  505. #define DEBUG_TRACE(fmt, ...) \
  506. do { \
  507. } while (0)
  508. #endif /* DEBUG */
  509. #endif /* DEBUG_TRACE */
  510. #if defined(MEMORY_DEBUGGING)
  511. unsigned long mg_memory_debug_blockCount = 0;
  512. unsigned long mg_memory_debug_totalMemUsed = 0;
  513. static void *
  514. mg_malloc_ex(size_t size, const char *file, unsigned line)
  515. {
  516. void *data = malloc(size + sizeof(size_t));
  517. void *memory = 0;
  518. char mallocStr[256];
  519. if (data) {
  520. *(size_t *)data = size;
  521. mg_memory_debug_totalMemUsed += size;
  522. mg_memory_debug_blockCount++;
  523. memory = (void *)(((char *)data) + sizeof(size_t));
  524. }
  525. sprintf(mallocStr,
  526. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  527. memory,
  528. (unsigned long)size,
  529. mg_memory_debug_totalMemUsed,
  530. mg_memory_debug_blockCount,
  531. file,
  532. line);
  533. #if defined(_WIN32)
  534. OutputDebugStringA(mallocStr);
  535. #else
  536. DEBUG_TRACE("%s", mallocStr);
  537. #endif
  538. return memory;
  539. }
  540. static void *
  541. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  542. {
  543. void *data = mg_malloc_ex(size * count, file, line);
  544. if (data) {
  545. memset(data, 0, size);
  546. }
  547. return data;
  548. }
  549. static void
  550. mg_free_ex(void *memory, const char *file, unsigned line)
  551. {
  552. char mallocStr[256];
  553. void *data = (void *)(((char *)memory) - sizeof(size_t));
  554. size_t size;
  555. if (memory) {
  556. size = *(size_t *)data;
  557. mg_memory_debug_totalMemUsed -= size;
  558. mg_memory_debug_blockCount--;
  559. sprintf(mallocStr,
  560. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  561. memory,
  562. (unsigned long)size,
  563. mg_memory_debug_totalMemUsed,
  564. mg_memory_debug_blockCount,
  565. file,
  566. line);
  567. #if defined(_WIN32)
  568. OutputDebugStringA(mallocStr);
  569. #else
  570. DEBUG_TRACE("%s", mallocStr);
  571. #endif
  572. free(data);
  573. }
  574. }
  575. static void *
  576. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  577. {
  578. char mallocStr[256];
  579. void *data;
  580. void *_realloc;
  581. size_t oldsize;
  582. if (newsize) {
  583. if (memory) {
  584. data = (void *)(((char *)memory) - sizeof(size_t));
  585. oldsize = *(size_t *)data;
  586. _realloc = realloc(data, newsize + sizeof(size_t));
  587. if (_realloc) {
  588. data = _realloc;
  589. mg_memory_debug_totalMemUsed -= oldsize;
  590. sprintf(mallocStr,
  591. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  592. memory,
  593. (unsigned long)oldsize,
  594. mg_memory_debug_totalMemUsed,
  595. mg_memory_debug_blockCount,
  596. file,
  597. line);
  598. #if defined(_WIN32)
  599. OutputDebugStringA(mallocStr);
  600. #else
  601. DEBUG_TRACE("%s", mallocStr);
  602. #endif
  603. mg_memory_debug_totalMemUsed += newsize;
  604. sprintf(mallocStr,
  605. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  606. memory,
  607. (unsigned long)newsize,
  608. mg_memory_debug_totalMemUsed,
  609. mg_memory_debug_blockCount,
  610. file,
  611. line);
  612. #if defined(_WIN32)
  613. OutputDebugStringA(mallocStr);
  614. #else
  615. DEBUG_TRACE("%s", mallocStr);
  616. #endif
  617. *(size_t *)data = newsize;
  618. data = (void *)(((char *)data) + sizeof(size_t));
  619. } else {
  620. #if defined(_WIN32)
  621. OutputDebugStringA("MEM: realloc failed\n");
  622. #else
  623. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  624. #endif
  625. return _realloc;
  626. }
  627. } else {
  628. data = mg_malloc_ex(newsize, file, line);
  629. }
  630. } else {
  631. data = 0;
  632. mg_free_ex(memory, file, line);
  633. }
  634. return data;
  635. }
  636. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  637. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  638. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  639. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  640. #else
  641. static __inline void *
  642. mg_malloc(size_t a)
  643. {
  644. return malloc(a);
  645. }
  646. static __inline void *
  647. mg_calloc(size_t a, size_t b)
  648. {
  649. return calloc(a, b);
  650. }
  651. static __inline void *
  652. mg_realloc(void *a, size_t b)
  653. {
  654. return realloc(a, b);
  655. }
  656. static __inline void
  657. mg_free(void *a)
  658. {
  659. free(a);
  660. }
  661. #endif
  662. static void mg_vsnprintf(const struct mg_connection *conn,
  663. int *truncated,
  664. char *buf,
  665. size_t buflen,
  666. const char *fmt,
  667. va_list ap);
  668. static void mg_snprintf(const struct mg_connection *conn,
  669. int *truncated,
  670. char *buf,
  671. size_t buflen,
  672. PRINTF_FORMAT_STRING(const char *fmt),
  673. ...) PRINTF_ARGS(5, 6);
  674. /* This following lines are just meant as a reminder to use the mg-functions
  675. * for memory management */
  676. #ifdef malloc
  677. #undef malloc
  678. #endif
  679. #ifdef calloc
  680. #undef calloc
  681. #endif
  682. #ifdef realloc
  683. #undef realloc
  684. #endif
  685. #ifdef free
  686. #undef free
  687. #endif
  688. #ifdef snprintf
  689. #undef snprintf
  690. #endif
  691. #ifdef vsnprintf
  692. #undef vsnprintf
  693. #endif
  694. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  695. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  696. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  697. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  698. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  699. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  700. * but this define only works well for Windows. */
  701. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  702. #endif
  703. #define MD5_STATIC static
  704. #include "md5.inl"
  705. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  706. #ifdef NO_SOCKLEN_T
  707. typedef int socklen_t;
  708. #endif /* NO_SOCKLEN_T */
  709. #define _DARWIN_UNLIMITED_SELECT
  710. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  711. #if !defined(MSG_NOSIGNAL)
  712. #define MSG_NOSIGNAL (0)
  713. #endif
  714. #if !defined(SOMAXCONN)
  715. #define SOMAXCONN (100)
  716. #endif
  717. /* Size of the accepted socket queue */
  718. #if !defined(MGSQLEN)
  719. #define MGSQLEN (20)
  720. #endif
  721. #if defined(NO_SSL_DL)
  722. #include <openssl/ssl.h>
  723. #include <openssl/err.h>
  724. #include <openssl/crypto.h>
  725. #include <openssl/x509.h>
  726. #include <openssl/pem.h>
  727. #include <openssl/engine.h>
  728. #include <openssl/conf.h>
  729. #else
  730. /* SSL loaded dynamically from DLL.
  731. * I put the prototypes here to be independent from OpenSSL source
  732. * installation. */
  733. typedef struct ssl_st SSL;
  734. typedef struct ssl_method_st SSL_METHOD;
  735. typedef struct ssl_ctx_st SSL_CTX;
  736. typedef struct x509_store_ctx_st X509_STORE_CTX;
  737. #define SSL_CTRL_OPTIONS (32)
  738. #define SSL_CTRL_CLEAR_OPTIONS (77)
  739. #define SSL_CTRL_SET_ECDH_AUTO (94)
  740. #define SSL_VERIFY_NONE (0)
  741. #define SSL_VERIFY_PEER (1)
  742. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  743. #define SSL_VERIFY_CLIENT_ONCE (4)
  744. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  745. #define SSL_OP_NO_SSLv2 (0x01000000L)
  746. #define SSL_OP_NO_SSLv3 (0x02000000L)
  747. #define SSL_OP_NO_TLSv1 (0x04000000L)
  748. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  749. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  750. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  751. struct ssl_func {
  752. const char *name; /* SSL function name */
  753. void (*ptr)(void); /* Function pointer */
  754. };
  755. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  756. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  757. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  758. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  759. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  760. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  761. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  762. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  763. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  764. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  765. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  766. #define SSL_CTX_use_PrivateKey_file \
  767. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  768. #define SSL_CTX_use_certificate_file \
  769. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  770. #define SSL_CTX_set_default_passwd_cb \
  771. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  772. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  773. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  774. #define SSL_CTX_use_certificate_chain_file \
  775. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  776. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  777. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  778. #define SSL_CTX_set_verify \
  779. (*(void (*)(SSL_CTX *, \
  780. int, \
  781. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  782. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  783. #define SSL_CTX_load_verify_locations \
  784. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  785. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  786. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  787. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  788. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  789. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  790. #define SSL_CIPHER_get_name \
  791. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  792. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  793. #define SSL_CTX_set_session_id_context \
  794. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  795. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  796. #define SSL_CTX_set_cipher_list \
  797. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  798. #define SSL_CTX_set_options(ctx, op) \
  799. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  800. #define SSL_CTX_clear_options(ctx, op) \
  801. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  802. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  803. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  804. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  805. #define CRYPTO_set_locking_callback \
  806. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  807. #define CRYPTO_set_id_callback \
  808. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  809. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  810. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  811. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  812. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  813. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  814. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  815. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  816. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  817. /* set_ssl_option() function updates this array.
  818. * It loads SSL library dynamically and changes NULLs to the actual addresses
  819. * of respective functions. The macros above (like SSL_connect()) are really
  820. * just calling these functions indirectly via the pointer. */
  821. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  822. {"SSL_accept", NULL},
  823. {"SSL_connect", NULL},
  824. {"SSL_read", NULL},
  825. {"SSL_write", NULL},
  826. {"SSL_get_error", NULL},
  827. {"SSL_set_fd", NULL},
  828. {"SSL_new", NULL},
  829. {"SSL_CTX_new", NULL},
  830. {"SSLv23_server_method", NULL},
  831. {"SSL_library_init", NULL},
  832. {"SSL_CTX_use_PrivateKey_file", NULL},
  833. {"SSL_CTX_use_certificate_file", NULL},
  834. {"SSL_CTX_set_default_passwd_cb", NULL},
  835. {"SSL_CTX_free", NULL},
  836. {"SSL_load_error_strings", NULL},
  837. {"SSL_CTX_use_certificate_chain_file", NULL},
  838. {"SSLv23_client_method", NULL},
  839. {"SSL_pending", NULL},
  840. {"SSL_CTX_set_verify", NULL},
  841. {"SSL_shutdown", NULL},
  842. {"SSL_CTX_load_verify_locations", NULL},
  843. {"SSL_CTX_set_default_verify_paths", NULL},
  844. {"SSL_CTX_set_verify_depth", NULL},
  845. {"SSL_get_peer_certificate", NULL},
  846. {"SSL_get_version", NULL},
  847. {"SSL_get_current_cipher", NULL},
  848. {"SSL_CIPHER_get_name", NULL},
  849. {"SSL_CTX_check_private_key", NULL},
  850. {"SSL_CTX_set_session_id_context", NULL},
  851. {"SSL_CTX_ctrl", NULL},
  852. {"SSL_CTX_set_cipher_list", NULL},
  853. {NULL, NULL}};
  854. /* Similar array as ssl_sw. These functions could be located in different
  855. * lib. */
  856. #if !defined(NO_SSL)
  857. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  858. {"CRYPTO_set_locking_callback", NULL},
  859. {"CRYPTO_set_id_callback", NULL},
  860. {"ERR_get_error", NULL},
  861. {"ERR_error_string", NULL},
  862. {"ERR_remove_state", NULL},
  863. {"ERR_free_strings", NULL},
  864. {"ENGINE_cleanup", NULL},
  865. {"CONF_modules_unload", NULL},
  866. {"CRYPTO_cleanup_all_ex_data", NULL},
  867. {"EVP_cleanup", NULL},
  868. {NULL, NULL}};
  869. #endif /* NO_SSL */
  870. #endif /* NO_SSL_DL */
  871. #if !defined(NO_CACHING)
  872. static const char *month_names[] = {"Jan",
  873. "Feb",
  874. "Mar",
  875. "Apr",
  876. "May",
  877. "Jun",
  878. "Jul",
  879. "Aug",
  880. "Sep",
  881. "Oct",
  882. "Nov",
  883. "Dec"};
  884. #endif /* !NO_CACHING */
  885. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  886. * union u. */
  887. union usa {
  888. struct sockaddr sa;
  889. struct sockaddr_in sin;
  890. #if defined(USE_IPV6)
  891. struct sockaddr_in6 sin6;
  892. #endif
  893. };
  894. /* Describes a string (chunk of memory). */
  895. struct vec {
  896. const char *ptr;
  897. size_t len;
  898. };
  899. struct file {
  900. uint64_t size;
  901. time_t last_modified;
  902. FILE *fp;
  903. const char *membuf; /* Non-NULL if file data is in memory */
  904. int is_directory;
  905. int gzipped; /* set to 1 if the content is gzipped
  906. * in which case we need a content-encoding: gzip header */
  907. };
  908. #define STRUCT_FILE_INITIALIZER \
  909. { \
  910. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  911. }
  912. /* Describes listening socket, or socket which was accept()-ed by the master
  913. * thread and queued for future handling by the worker thread. */
  914. struct socket {
  915. SOCKET sock; /* Listening socket */
  916. union usa lsa; /* Local socket address */
  917. union usa rsa; /* Remote socket address */
  918. unsigned char is_ssl; /* Is port SSL-ed */
  919. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  920. * port */
  921. };
  922. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  923. enum {
  924. CGI_EXTENSIONS,
  925. CGI_ENVIRONMENT,
  926. PUT_DELETE_PASSWORDS_FILE,
  927. CGI_INTERPRETER,
  928. PROTECT_URI,
  929. AUTHENTICATION_DOMAIN,
  930. SSI_EXTENSIONS,
  931. THROTTLE,
  932. ACCESS_LOG_FILE,
  933. ENABLE_DIRECTORY_LISTING,
  934. ERROR_LOG_FILE,
  935. GLOBAL_PASSWORDS_FILE,
  936. INDEX_FILES,
  937. ENABLE_KEEP_ALIVE,
  938. ACCESS_CONTROL_LIST,
  939. EXTRA_MIME_TYPES,
  940. LISTENING_PORTS,
  941. DOCUMENT_ROOT,
  942. SSL_CERTIFICATE,
  943. NUM_THREADS,
  944. RUN_AS_USER,
  945. REWRITE,
  946. HIDE_FILES,
  947. REQUEST_TIMEOUT,
  948. SSL_DO_VERIFY_PEER,
  949. SSL_CA_PATH,
  950. SSL_CA_FILE,
  951. SSL_VERIFY_DEPTH,
  952. SSL_DEFAULT_VERIFY_PATHS,
  953. SSL_CIPHER_LIST,
  954. SSL_PROTOCOL_VERSION,
  955. SSL_SHORT_TRUST,
  956. #if defined(USE_WEBSOCKET)
  957. WEBSOCKET_TIMEOUT,
  958. #endif
  959. DECODE_URL,
  960. #if defined(USE_LUA)
  961. LUA_PRELOAD_FILE,
  962. LUA_SCRIPT_EXTENSIONS,
  963. LUA_SERVER_PAGE_EXTENSIONS,
  964. #endif
  965. #if defined(USE_DUKTAPE)
  966. DUKTAPE_SCRIPT_EXTENSIONS,
  967. #endif
  968. #if defined(USE_WEBSOCKET)
  969. WEBSOCKET_ROOT,
  970. #endif
  971. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  972. LUA_WEBSOCKET_EXTENSIONS,
  973. #endif
  974. ACCESS_CONTROL_ALLOW_ORIGIN,
  975. ERROR_PAGES,
  976. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  977. * socket option typedef TCP_NODELAY. */
  978. #if !defined(NO_CACHING)
  979. STATIC_FILE_MAX_AGE,
  980. #endif
  981. NUM_OPTIONS
  982. };
  983. /* Config option name, config types, default value */
  984. static struct mg_option config_options[] = {
  985. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  986. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  987. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  988. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  989. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  990. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  991. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  992. {"throttle", CONFIG_TYPE_STRING, NULL},
  993. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  994. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  995. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  996. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  997. {"index_files",
  998. CONFIG_TYPE_STRING,
  999. #ifdef USE_LUA
  1000. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1001. "index.shtml,index.php"},
  1002. #else
  1003. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1004. #endif
  1005. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1006. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1007. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1008. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1009. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1010. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1011. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1012. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1013. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1014. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1015. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1016. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1017. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1018. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1019. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1020. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1021. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1022. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1023. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1024. #if defined(USE_WEBSOCKET)
  1025. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1026. #endif
  1027. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1028. #if defined(USE_LUA)
  1029. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1030. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1031. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1032. #endif
  1033. #if defined(USE_DUKTAPE)
  1034. /* The support for duktape is still in alpha version state.
  1035. * The name of this config option might change. */
  1036. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1037. #endif
  1038. #if defined(USE_WEBSOCKET)
  1039. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1040. #endif
  1041. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1042. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1043. #endif
  1044. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1045. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1046. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1047. #if !defined(NO_CACHING)
  1048. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1049. #endif
  1050. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1051. /* Check if the config_options and the corresponding enum have compatible
  1052. * sizes. */
  1053. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1054. == (NUM_OPTIONS + 1),
  1055. "config_options and enum not sync");
  1056. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1057. struct mg_handler_info {
  1058. /* Name/Pattern of the URI. */
  1059. char *uri;
  1060. size_t uri_len;
  1061. /* handler type */
  1062. int handler_type;
  1063. /* Handler for http/https or authorization requests. */
  1064. mg_request_handler handler;
  1065. /* Handler for ws/wss (websocket) requests. */
  1066. mg_websocket_connect_handler connect_handler;
  1067. mg_websocket_ready_handler ready_handler;
  1068. mg_websocket_data_handler data_handler;
  1069. mg_websocket_close_handler close_handler;
  1070. /* Handler for authorization requests */
  1071. mg_authorization_handler auth_handler;
  1072. /* User supplied argument for the handler function. */
  1073. void *cbdata;
  1074. /* next handler in a linked list */
  1075. struct mg_handler_info *next;
  1076. };
  1077. struct mg_context {
  1078. volatile int stop_flag; /* Should we stop event loop */
  1079. SSL_CTX *ssl_ctx; /* SSL context */
  1080. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1081. struct mg_callbacks callbacks; /* User-defined callback function */
  1082. void *user_data; /* User-defined data */
  1083. int context_type; /* 1 = server context, 2 = client context */
  1084. struct socket *listening_sockets;
  1085. in_port_t *listening_ports;
  1086. unsigned int num_listening_sockets;
  1087. volatile int
  1088. running_worker_threads; /* Number of currently running worker threads */
  1089. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1090. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1091. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1092. volatile int sq_head; /* Head of the socket queue */
  1093. volatile int sq_tail; /* Tail of the socket queue */
  1094. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1095. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1096. pthread_t masterthreadid; /* The master thread ID */
  1097. unsigned int
  1098. cfg_worker_threads; /* The number of configured worker threads. */
  1099. pthread_t *workerthreadids; /* The worker thread IDs */
  1100. time_t start_time; /* Server start time, used for authentication */
  1101. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1102. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1103. unsigned long nonce_count; /* Used nonces, used for authentication */
  1104. char *systemName; /* What operating system is running */
  1105. /* linked list of uri handlers */
  1106. struct mg_handler_info *handlers;
  1107. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1108. /* linked list of shared lua websockets */
  1109. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1110. #endif
  1111. #ifdef USE_TIMERS
  1112. struct ttimers *timers;
  1113. #endif
  1114. };
  1115. struct mg_connection {
  1116. struct mg_request_info request_info;
  1117. struct mg_context *ctx;
  1118. SSL *ssl; /* SSL descriptor */
  1119. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1120. struct socket client; /* Connected client */
  1121. time_t conn_birth_time; /* Time (wall clock) when connection was
  1122. * established */
  1123. struct timespec req_time; /* Time (since system start) when the request
  1124. * was received */
  1125. int64_t num_bytes_sent; /* Total bytes sent to client */
  1126. int64_t content_len; /* Content-Length header value */
  1127. int64_t consumed_content; /* How many bytes of content have been read */
  1128. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1129. * data available, 2: all data read */
  1130. size_t chunk_remainder; /* Unread data from the last chunk */
  1131. char *buf; /* Buffer for received data */
  1132. char *path_info; /* PATH_INFO part of the URL */
  1133. int must_close; /* 1 if connection must be closed */
  1134. int in_error_handler; /* 1 if in handler for user defined error
  1135. * pages */
  1136. int internal_error; /* 1 if an error occured while processing the
  1137. * request */
  1138. int buf_size; /* Buffer size */
  1139. int request_len; /* Size of the request + headers in a buffer */
  1140. int data_len; /* Total size of data in a buffer */
  1141. int status_code; /* HTTP reply status code, e.g. 200 */
  1142. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1143. * throttle */
  1144. time_t last_throttle_time; /* Last time throttled data was sent */
  1145. int64_t last_throttle_bytes; /* Bytes sent this second */
  1146. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1147. * atomic transmissions for websockets */
  1148. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1149. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1150. #endif
  1151. };
  1152. static pthread_key_t sTlsKey; /* Thread local storage index */
  1153. static int sTlsInit = 0;
  1154. static int thread_idx_max = 0;
  1155. struct mg_workerTLS {
  1156. int is_master;
  1157. unsigned long thread_idx;
  1158. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1159. HANDLE pthread_cond_helper_mutex;
  1160. #endif
  1161. };
  1162. /* Directory entry */
  1163. struct de {
  1164. struct mg_connection *conn;
  1165. char *file_name;
  1166. struct file file;
  1167. };
  1168. #if defined(USE_WEBSOCKET)
  1169. static int is_websocket_protocol(const struct mg_connection *conn);
  1170. #else
  1171. #define is_websocket_protocol(conn) (0)
  1172. #endif
  1173. static int
  1174. mg_atomic_inc(volatile int *addr)
  1175. {
  1176. int ret;
  1177. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1178. /* Depending on the SDK, this function uses either
  1179. * (volatile unsigned int *) or (volatile LONG *),
  1180. * so whatever you use, the other SDK is likely to raise a warning. */
  1181. ret = InterlockedIncrement((volatile long *)addr);
  1182. #elif defined(__GNUC__) \
  1183. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1184. ret = __sync_add_and_fetch(addr, 1);
  1185. #else
  1186. ret = (++(*addr));
  1187. #endif
  1188. return ret;
  1189. }
  1190. static int
  1191. mg_atomic_dec(volatile int *addr)
  1192. {
  1193. int ret;
  1194. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1195. /* Depending on the SDK, this function uses either
  1196. * (volatile unsigned int *) or (volatile LONG *),
  1197. * so whatever you use, the other SDK is likely to raise a warning. */
  1198. ret = InterlockedDecrement((volatile long *)addr);
  1199. #elif defined(__GNUC__) \
  1200. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1201. ret = __sync_sub_and_fetch(addr, 1);
  1202. #else
  1203. ret = (--(*addr));
  1204. #endif
  1205. return ret;
  1206. }
  1207. #if !defined(NO_THREAD_NAME)
  1208. #if defined(_WIN32) && defined(_MSC_VER)
  1209. /* Set the thread name for debugging purposes in Visual Studio
  1210. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1211. */
  1212. #pragma pack(push, 8)
  1213. typedef struct tagTHREADNAME_INFO {
  1214. DWORD dwType; /* Must be 0x1000. */
  1215. LPCSTR szName; /* Pointer to name (in user addr space). */
  1216. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1217. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1218. } THREADNAME_INFO;
  1219. #pragma pack(pop)
  1220. #elif defined(__linux__)
  1221. #include <sys/prctl.h>
  1222. #include <sys/sendfile.h>
  1223. #endif
  1224. static void
  1225. mg_set_thread_name(const char *name)
  1226. {
  1227. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1228. mg_snprintf(
  1229. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1230. #if defined(_WIN32)
  1231. #if defined(_MSC_VER)
  1232. /* Windows and Visual Studio Compiler */
  1233. __try
  1234. {
  1235. THREADNAME_INFO info;
  1236. info.dwType = 0x1000;
  1237. info.szName = threadName;
  1238. info.dwThreadID = ~0U;
  1239. info.dwFlags = 0;
  1240. RaiseException(0x406D1388,
  1241. 0,
  1242. sizeof(info) / sizeof(ULONG_PTR),
  1243. (ULONG_PTR *)&info);
  1244. }
  1245. __except(EXCEPTION_EXECUTE_HANDLER)
  1246. {
  1247. }
  1248. #elif defined(__MINGW32__)
  1249. /* No option known to set thread name for MinGW */
  1250. #endif
  1251. #elif defined(__GLIBC__) \
  1252. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1253. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1254. (void)pthread_setname_np(pthread_self(), threadName);
  1255. #elif defined(__linux__)
  1256. /* on linux we can use the old prctl function */
  1257. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1258. #endif
  1259. }
  1260. #else /* !defined(NO_THREAD_NAME) */
  1261. void
  1262. mg_set_thread_name(const char *threadName)
  1263. {
  1264. }
  1265. #endif
  1266. #if defined(MG_LEGACY_INTERFACE)
  1267. const char **
  1268. mg_get_valid_option_names(void)
  1269. {
  1270. /* This function is deprecated. Use mg_get_valid_options instead. */
  1271. static const char *
  1272. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1273. int i;
  1274. for (i = 0; config_options[i].name != NULL; i++) {
  1275. data[i * 2] = config_options[i].name;
  1276. data[i * 2 + 1] = config_options[i].default_value;
  1277. }
  1278. return data;
  1279. }
  1280. #endif
  1281. const struct mg_option *
  1282. mg_get_valid_options(void)
  1283. {
  1284. return config_options;
  1285. }
  1286. static int
  1287. is_file_in_memory(const struct mg_connection *conn,
  1288. const char *path,
  1289. struct file *filep)
  1290. {
  1291. size_t size = 0;
  1292. if (!conn || !filep) {
  1293. return 0;
  1294. }
  1295. if (conn->ctx->callbacks.open_file) {
  1296. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1297. if (filep->membuf != NULL) {
  1298. /* NOTE: override filep->size only on success. Otherwise, it might
  1299. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1300. filep->size = size;
  1301. }
  1302. }
  1303. return filep->membuf != NULL;
  1304. }
  1305. static int
  1306. is_file_opened(const struct file *filep)
  1307. {
  1308. if (!filep) {
  1309. return 0;
  1310. }
  1311. return filep->membuf != NULL || filep->fp != NULL;
  1312. }
  1313. /* mg_fopen will open a file either in memory or on the disk.
  1314. * The input parameter path is a string in UTF-8 encoding.
  1315. * The input parameter mode is the same as for fopen.
  1316. * Either fp or membuf will be set in the output struct filep.
  1317. * The function returns 1 on success, 0 on error. */
  1318. static int
  1319. mg_fopen(const struct mg_connection *conn,
  1320. const char *path,
  1321. const char *mode,
  1322. struct file *filep)
  1323. {
  1324. struct stat st;
  1325. if (!filep) {
  1326. return 0;
  1327. }
  1328. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1329. * only get the file status. They should not work on different members of
  1330. * the same structure (bad cohesion). */
  1331. memset(filep, 0, sizeof(*filep));
  1332. if (stat(path, &st) == 0) {
  1333. filep->size = (uint64_t)(st.st_size);
  1334. }
  1335. if (!is_file_in_memory(conn, path, filep)) {
  1336. #ifdef _WIN32
  1337. wchar_t wbuf[PATH_MAX], wmode[20];
  1338. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1339. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1340. filep->fp = _wfopen(wbuf, wmode);
  1341. #else
  1342. /* Linux et al already use unicode. No need to convert. */
  1343. filep->fp = fopen(path, mode);
  1344. #endif
  1345. }
  1346. return is_file_opened(filep);
  1347. }
  1348. static void
  1349. mg_fclose(struct file *filep)
  1350. {
  1351. if (filep != NULL && filep->fp != NULL) {
  1352. fclose(filep->fp);
  1353. }
  1354. }
  1355. static void
  1356. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1357. {
  1358. for (; *src != '\0' && n > 1; n--) {
  1359. *dst++ = *src++;
  1360. }
  1361. *dst = '\0';
  1362. }
  1363. static int
  1364. lowercase(const char *s)
  1365. {
  1366. return tolower(*(const unsigned char *)s);
  1367. }
  1368. int
  1369. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1370. {
  1371. int diff = 0;
  1372. if (len > 0) {
  1373. do {
  1374. diff = lowercase(s1++) - lowercase(s2++);
  1375. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1376. }
  1377. return diff;
  1378. }
  1379. int
  1380. mg_strcasecmp(const char *s1, const char *s2)
  1381. {
  1382. int diff;
  1383. do {
  1384. diff = lowercase(s1++) - lowercase(s2++);
  1385. } while (diff == 0 && s1[-1] != '\0');
  1386. return diff;
  1387. }
  1388. static char *
  1389. mg_strndup(const char *ptr, size_t len)
  1390. {
  1391. char *p;
  1392. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1393. mg_strlcpy(p, ptr, len + 1);
  1394. }
  1395. return p;
  1396. }
  1397. static char *
  1398. mg_strdup(const char *str)
  1399. {
  1400. return mg_strndup(str, strlen(str));
  1401. }
  1402. static const char *
  1403. mg_strcasestr(const char *big_str, const char *small_str)
  1404. {
  1405. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1406. if (big_len >= small_len) {
  1407. for (i = 0; i <= (big_len - small_len); i++) {
  1408. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1409. return big_str + i;
  1410. }
  1411. }
  1412. }
  1413. return NULL;
  1414. }
  1415. /* Return null terminated string of given maximum length.
  1416. * Report errors if length is exceeded. */
  1417. static void
  1418. mg_vsnprintf(const struct mg_connection *conn,
  1419. int *truncated,
  1420. char *buf,
  1421. size_t buflen,
  1422. const char *fmt,
  1423. va_list ap)
  1424. {
  1425. int n, ok;
  1426. if (buflen == 0) {
  1427. return;
  1428. }
  1429. #ifdef __clang__
  1430. #pragma clang diagnostic push
  1431. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1432. /* Using fmt as a non-literal is intended here, since it is mostly called
  1433. * indirectly by mg_snprintf */
  1434. #endif
  1435. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1436. ok = (n >= 0) && ((size_t)n < buflen);
  1437. #ifdef __clang__
  1438. #pragma clang diagnostic pop
  1439. #endif
  1440. if (ok) {
  1441. if (truncated) {
  1442. *truncated = 0;
  1443. }
  1444. } else {
  1445. if (truncated) {
  1446. *truncated = 1;
  1447. }
  1448. mg_cry(conn,
  1449. "truncating vsnprintf buffer: [%.*s]",
  1450. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1451. buf);
  1452. n = (int)buflen - 1;
  1453. }
  1454. buf[n] = '\0';
  1455. }
  1456. static void
  1457. mg_snprintf(const struct mg_connection *conn,
  1458. int *truncated,
  1459. char *buf,
  1460. size_t buflen,
  1461. const char *fmt,
  1462. ...)
  1463. {
  1464. va_list ap;
  1465. va_start(ap, fmt);
  1466. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1467. va_end(ap);
  1468. }
  1469. static int
  1470. get_option_index(const char *name)
  1471. {
  1472. int i;
  1473. for (i = 0; config_options[i].name != NULL; i++) {
  1474. if (strcmp(config_options[i].name, name) == 0) {
  1475. return i;
  1476. }
  1477. }
  1478. return -1;
  1479. }
  1480. const char *
  1481. mg_get_option(const struct mg_context *ctx, const char *name)
  1482. {
  1483. int i;
  1484. if ((i = get_option_index(name)) == -1) {
  1485. return NULL;
  1486. } else if (!ctx || ctx->config[i] == NULL) {
  1487. return "";
  1488. } else {
  1489. return ctx->config[i];
  1490. }
  1491. }
  1492. struct mg_context *
  1493. mg_get_context(const struct mg_connection *conn)
  1494. {
  1495. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1496. }
  1497. void *
  1498. mg_get_user_data(const struct mg_context *ctx)
  1499. {
  1500. return (ctx == NULL) ? NULL : ctx->user_data;
  1501. }
  1502. void
  1503. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1504. {
  1505. if (conn != NULL) {
  1506. conn->request_info.conn_data = data;
  1507. }
  1508. }
  1509. void *
  1510. mg_get_user_connection_data(const struct mg_connection *conn)
  1511. {
  1512. if (conn != NULL) {
  1513. return conn->request_info.conn_data;
  1514. }
  1515. return NULL;
  1516. }
  1517. size_t
  1518. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1519. {
  1520. size_t i;
  1521. if (!ctx) {
  1522. return 0;
  1523. }
  1524. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1525. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1526. ports[i] = ctx->listening_ports[i];
  1527. }
  1528. return i;
  1529. }
  1530. int
  1531. mg_get_server_ports(const struct mg_context *ctx,
  1532. int size,
  1533. struct mg_server_ports *ports)
  1534. {
  1535. int i, cnt = 0;
  1536. if (size <= 0) {
  1537. return -1;
  1538. }
  1539. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1540. if (!ctx) {
  1541. return -1;
  1542. }
  1543. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1544. return -1;
  1545. }
  1546. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1547. ports[cnt].port = ctx->listening_ports[i];
  1548. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1549. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1550. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1551. /* IPv4 */
  1552. ports[cnt].protocol = 1;
  1553. cnt++;
  1554. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1555. /* IPv6 */
  1556. ports[cnt].protocol = 3;
  1557. cnt++;
  1558. }
  1559. }
  1560. return cnt;
  1561. }
  1562. static void
  1563. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1564. {
  1565. buf[0] = '\0';
  1566. if (!usa) {
  1567. return;
  1568. }
  1569. if (usa->sa.sa_family == AF_INET) {
  1570. getnameinfo(&usa->sa,
  1571. sizeof(usa->sin),
  1572. buf,
  1573. (unsigned)len,
  1574. NULL,
  1575. 0,
  1576. NI_NUMERICHOST);
  1577. }
  1578. #if defined(USE_IPV6)
  1579. else if (usa->sa.sa_family == AF_INET6) {
  1580. getnameinfo(&usa->sa,
  1581. sizeof(usa->sin6),
  1582. buf,
  1583. (unsigned)len,
  1584. NULL,
  1585. 0,
  1586. NI_NUMERICHOST);
  1587. }
  1588. #endif
  1589. }
  1590. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1591. * included in all responses other than 100, 101, 5xx. */
  1592. static void
  1593. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1594. {
  1595. struct tm *tm;
  1596. tm = ((t != NULL) ? gmtime(t) : NULL);
  1597. if (tm != NULL) {
  1598. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1599. } else {
  1600. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1601. buf[buf_len - 1] = '\0';
  1602. }
  1603. }
  1604. /* difftime for struct timespec. Return value is in seconds. */
  1605. static double
  1606. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1607. {
  1608. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1609. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1610. }
  1611. /* Print error message to the opened error log stream. */
  1612. void
  1613. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1614. {
  1615. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1616. va_list ap;
  1617. struct file fi;
  1618. time_t timestamp;
  1619. va_start(ap, fmt);
  1620. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1621. va_end(ap);
  1622. buf[sizeof(buf) - 1] = 0;
  1623. if (!conn) {
  1624. puts(buf);
  1625. return;
  1626. }
  1627. /* Do not lock when getting the callback value, here and below.
  1628. * I suppose this is fine, since function cannot disappear in the
  1629. * same way string option can. */
  1630. if ((conn->ctx->callbacks.log_message == NULL)
  1631. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1632. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1633. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1634. == 0) {
  1635. fi.fp = NULL;
  1636. }
  1637. } else {
  1638. fi.fp = NULL;
  1639. }
  1640. if (fi.fp != NULL) {
  1641. flockfile(fi.fp);
  1642. timestamp = time(NULL);
  1643. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1644. fprintf(fi.fp,
  1645. "[%010lu] [error] [client %s] ",
  1646. (unsigned long)timestamp,
  1647. src_addr);
  1648. if (conn->request_info.request_method != NULL) {
  1649. fprintf(fi.fp,
  1650. "%s %s: ",
  1651. conn->request_info.request_method,
  1652. conn->request_info.request_uri);
  1653. }
  1654. fprintf(fi.fp, "%s", buf);
  1655. fputc('\n', fi.fp);
  1656. fflush(fi.fp);
  1657. funlockfile(fi.fp);
  1658. mg_fclose(&fi);
  1659. }
  1660. }
  1661. }
  1662. /* Return fake connection structure. Used for logging, if connection
  1663. * is not applicable at the moment of logging. */
  1664. static struct mg_connection *
  1665. fc(struct mg_context *ctx)
  1666. {
  1667. static struct mg_connection fake_connection;
  1668. fake_connection.ctx = ctx;
  1669. return &fake_connection;
  1670. }
  1671. const char *
  1672. mg_version(void)
  1673. {
  1674. return CIVETWEB_VERSION;
  1675. }
  1676. const struct mg_request_info *
  1677. mg_get_request_info(const struct mg_connection *conn)
  1678. {
  1679. if (!conn) {
  1680. return NULL;
  1681. }
  1682. return &conn->request_info;
  1683. }
  1684. /* Skip the characters until one of the delimiters characters found.
  1685. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1686. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1687. * Delimiters can be quoted with quotechar. */
  1688. static char *
  1689. skip_quoted(char **buf,
  1690. const char *delimiters,
  1691. const char *whitespace,
  1692. char quotechar)
  1693. {
  1694. char *p, *begin_word, *end_word, *end_whitespace;
  1695. begin_word = *buf;
  1696. end_word = begin_word + strcspn(begin_word, delimiters);
  1697. /* Check for quotechar */
  1698. if (end_word > begin_word) {
  1699. p = end_word - 1;
  1700. while (*p == quotechar) {
  1701. /* While the delimiter is quoted, look for the next delimiter. */
  1702. /* This happens, e.g., in calls from parse_auth_header,
  1703. * if the user name contains a " character. */
  1704. /* If there is anything beyond end_word, copy it. */
  1705. if (*end_word != '\0') {
  1706. size_t end_off = strcspn(end_word + 1, delimiters);
  1707. memmove(p, end_word, end_off + 1);
  1708. p += end_off; /* p must correspond to end_word - 1 */
  1709. end_word += end_off + 1;
  1710. } else {
  1711. *p = '\0';
  1712. break;
  1713. }
  1714. }
  1715. for (p++; p < end_word; p++) {
  1716. *p = '\0';
  1717. }
  1718. }
  1719. if (*end_word == '\0') {
  1720. *buf = end_word;
  1721. } else {
  1722. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1723. for (p = end_word; p < end_whitespace; p++) {
  1724. *p = '\0';
  1725. }
  1726. *buf = end_whitespace;
  1727. }
  1728. return begin_word;
  1729. }
  1730. /* Simplified version of skip_quoted without quote char
  1731. * and whitespace == delimiters */
  1732. static char *
  1733. skip(char **buf, const char *delimiters)
  1734. {
  1735. return skip_quoted(buf, delimiters, delimiters, 0);
  1736. }
  1737. /* Return HTTP header value, or NULL if not found. */
  1738. static const char *
  1739. get_header(const struct mg_request_info *ri, const char *name)
  1740. {
  1741. int i;
  1742. if (ri) {
  1743. for (i = 0; i < ri->num_headers; i++) {
  1744. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1745. return ri->http_headers[i].value;
  1746. }
  1747. }
  1748. }
  1749. return NULL;
  1750. }
  1751. const char *
  1752. mg_get_header(const struct mg_connection *conn, const char *name)
  1753. {
  1754. if (!conn) {
  1755. return NULL;
  1756. }
  1757. return get_header(&conn->request_info, name);
  1758. }
  1759. /* A helper function for traversing a comma separated list of values.
  1760. * It returns a list pointer shifted to the next value, or NULL if the end
  1761. * of the list found.
  1762. * Value is stored in val vector. If value has form "x=y", then eq_val
  1763. * vector is initialized to point to the "y" part, and val vector length
  1764. * is adjusted to point only to "x". */
  1765. static const char *
  1766. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1767. {
  1768. int end;
  1769. reparse:
  1770. if (val == NULL || list == NULL || *list == '\0') {
  1771. /* End of the list */
  1772. list = NULL;
  1773. } else {
  1774. /* Skip over leading LWS */
  1775. while (*list == ' ' || *list == '\t')
  1776. list++;
  1777. val->ptr = list;
  1778. if ((list = strchr(val->ptr, ',')) != NULL) {
  1779. /* Comma found. Store length and shift the list ptr */
  1780. val->len = ((size_t)(list - val->ptr));
  1781. list++;
  1782. } else {
  1783. /* This value is the last one */
  1784. list = val->ptr + strlen(val->ptr);
  1785. val->len = ((size_t)(list - val->ptr));
  1786. }
  1787. /* Adjust length for trailing LWS */
  1788. end = (int)val->len - 1;
  1789. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  1790. end--;
  1791. val->len = (size_t)(end + 1);
  1792. if (val->len == 0) {
  1793. /* Ignore any empty entries. */
  1794. goto reparse;
  1795. }
  1796. if (eq_val != NULL) {
  1797. /* Value has form "x=y", adjust pointers and lengths
  1798. * so that val points to "x", and eq_val points to "y". */
  1799. eq_val->len = 0;
  1800. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1801. if (eq_val->ptr != NULL) {
  1802. eq_val->ptr++; /* Skip over '=' character */
  1803. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1804. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1805. }
  1806. }
  1807. }
  1808. return list;
  1809. }
  1810. /* A helper function for checking if a comma separated list of values contains
  1811. * the given option (case insensitvely).
  1812. * 'header' can be NULL, in which case false is returned. */
  1813. static int
  1814. header_has_option(const char *header, const char *option)
  1815. {
  1816. struct vec opt_vec;
  1817. struct vec eq_vec;
  1818. assert(option != NULL);
  1819. assert(option[0] != '\0');
  1820. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  1821. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  1822. return 1;
  1823. }
  1824. return 0;
  1825. }
  1826. /* Perform case-insensitive match of string against pattern */
  1827. static int
  1828. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1829. {
  1830. const char *or_str;
  1831. size_t i;
  1832. int j, len, res;
  1833. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1834. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1835. return res > 0 ? res : match_prefix(or_str + 1,
  1836. (size_t)((pattern + pattern_len)
  1837. - (or_str + 1)),
  1838. str);
  1839. }
  1840. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1841. if (pattern[i] == '?' && str[j] != '\0') {
  1842. continue;
  1843. } else if (pattern[i] == '$') {
  1844. return str[j] == '\0' ? j : -1;
  1845. } else if (pattern[i] == '*') {
  1846. i++;
  1847. if (pattern[i] == '*') {
  1848. i++;
  1849. len = (int)strlen(str + j);
  1850. } else {
  1851. len = (int)strcspn(str + j, "/");
  1852. }
  1853. if (i == pattern_len) {
  1854. return j + len;
  1855. }
  1856. do {
  1857. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1858. } while (res == -1 && len-- > 0);
  1859. return res == -1 ? -1 : j + res + len;
  1860. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1861. return -1;
  1862. }
  1863. }
  1864. return j;
  1865. }
  1866. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1867. * This function must tolerate situations when connection info is not
  1868. * set up, for example if request parsing failed. */
  1869. static int
  1870. should_keep_alive(const struct mg_connection *conn)
  1871. {
  1872. if (conn != NULL) {
  1873. const char *http_version = conn->request_info.http_version;
  1874. const char *header = mg_get_header(conn, "Connection");
  1875. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1876. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1877. || (header != NULL && !header_has_option(header, "keep-alive"))
  1878. || (header == NULL && http_version
  1879. && 0 != strcmp(http_version, "1.1"))) {
  1880. return 0;
  1881. }
  1882. return 1;
  1883. }
  1884. return 0;
  1885. }
  1886. static int
  1887. should_decode_url(const struct mg_connection *conn)
  1888. {
  1889. if (!conn || !conn->ctx) {
  1890. return 0;
  1891. }
  1892. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1893. }
  1894. static const char *
  1895. suggest_connection_header(const struct mg_connection *conn)
  1896. {
  1897. return should_keep_alive(conn) ? "keep-alive" : "close";
  1898. }
  1899. static int
  1900. send_no_cache_header(struct mg_connection *conn)
  1901. {
  1902. /* Send all current and obsolete cache opt-out directives. */
  1903. return mg_printf(conn,
  1904. "Cache-Control: no-cache, no-store, "
  1905. "must-revalidate, private, max-age=0\r\n"
  1906. "Pragma: no-cache\r\n"
  1907. "Expires: 0\r\n");
  1908. }
  1909. static int
  1910. send_static_cache_header(struct mg_connection *conn)
  1911. {
  1912. #if !defined(NO_CACHING)
  1913. /* Read the server config to check how long a file may be cached.
  1914. * The configuration is in seconds. */
  1915. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  1916. if (max_age <= 0) {
  1917. /* 0 means "do not cache". All values <0 are reserved
  1918. * and may be used differently in the future. */
  1919. /* If a file should not be cached, do not only send
  1920. * max-age=0, but also pragmas and Expires headers. */
  1921. return send_no_cache_header(conn);
  1922. }
  1923. /* Use "Cache-Control: max-age" instead of "Expires" header.
  1924. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  1925. /* See also https://www.mnot.net/cache_docs/ */
  1926. /* According to RFC 2616, Section 14.21, caching times should not exceed
  1927. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  1928. * year to 31622400 seconds. For the moment, we just send whatever has
  1929. * been configured, still the behavior for >1 year should be considered
  1930. * as undefined. */
  1931. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  1932. #else /* NO_CACHING */
  1933. return send_no_cache_header(conn);
  1934. #endif /* !NO_CACHING */
  1935. }
  1936. static void handle_file_based_request(struct mg_connection *conn,
  1937. const char *path,
  1938. struct file *filep);
  1939. static int
  1940. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1941. const char *
  1942. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  1943. {
  1944. /* See IANA HTTP status code assignment:
  1945. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  1946. */
  1947. switch (response_code) {
  1948. /* RFC2616 Section 10.1 - Informational 1xx */
  1949. case 100:
  1950. return "Continue"; /* RFC2616 Section 10.1.1 */
  1951. case 101:
  1952. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1953. case 102:
  1954. return "Processing"; /* RFC2518 Section 10.1 */
  1955. /* RFC2616 Section 10.2 - Successful 2xx */
  1956. case 200:
  1957. return "OK"; /* RFC2616 Section 10.2.1 */
  1958. case 201:
  1959. return "Created"; /* RFC2616 Section 10.2.2 */
  1960. case 202:
  1961. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1962. case 203:
  1963. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1964. case 204:
  1965. return "No Content"; /* RFC2616 Section 10.2.5 */
  1966. case 205:
  1967. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1968. case 206:
  1969. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1970. case 207:
  1971. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1972. case 208:
  1973. return "Already Reported"; /* RFC5842 Section 7.1 */
  1974. case 226:
  1975. return "IM used"; /* RFC3229 Section 10.4.1 */
  1976. /* RFC2616 Section 10.3 - Redirection 3xx */
  1977. case 300:
  1978. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1979. case 301:
  1980. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1981. case 302:
  1982. return "Found"; /* RFC2616 Section 10.3.3 */
  1983. case 303:
  1984. return "See Other"; /* RFC2616 Section 10.3.4 */
  1985. case 304:
  1986. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1987. case 305:
  1988. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1989. case 307:
  1990. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1991. case 308:
  1992. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1993. /* RFC2616 Section 10.4 - Client Error 4xx */
  1994. case 400:
  1995. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1996. case 401:
  1997. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1998. case 402:
  1999. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2000. case 403:
  2001. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2002. case 404:
  2003. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2004. case 405:
  2005. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2006. case 406:
  2007. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2008. case 407:
  2009. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2010. case 408:
  2011. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2012. case 409:
  2013. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2014. case 410:
  2015. return "Gone"; /* RFC2616 Section 10.4.11 */
  2016. case 411:
  2017. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2018. case 412:
  2019. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2020. case 413:
  2021. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2022. case 414:
  2023. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2024. case 415:
  2025. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2026. case 416:
  2027. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2028. case 417:
  2029. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2030. case 421:
  2031. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2032. case 422:
  2033. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2034. * Section 11.2 */
  2035. case 423:
  2036. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2037. case 424:
  2038. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2039. * Section 11.4 */
  2040. case 426:
  2041. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2042. case 428:
  2043. return "Precondition Required"; /* RFC 6585, Section 3 */
  2044. case 429:
  2045. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2046. case 431:
  2047. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2048. case 451:
  2049. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2050. * Section 3 */
  2051. /* RFC2616 Section 10.5 - Server Error 5xx */
  2052. case 500:
  2053. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2054. case 501:
  2055. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2056. case 502:
  2057. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2058. case 503:
  2059. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2060. case 504:
  2061. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2062. case 505:
  2063. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2064. case 506:
  2065. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2066. case 507:
  2067. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2068. * Section 11.5 */
  2069. case 508:
  2070. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2071. case 510:
  2072. return "Not Extended"; /* RFC 2774, Section 7 */
  2073. case 511:
  2074. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2075. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2076. * E.g., "de facto" standards due to common use, ... */
  2077. case 418:
  2078. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2079. case 419:
  2080. return "Authentication Timeout"; /* common use */
  2081. case 420:
  2082. return "Enhance Your Calm"; /* common use */
  2083. case 440:
  2084. return "Login Timeout"; /* common use */
  2085. case 509:
  2086. return "Bandwidth Limit Exceeded"; /* common use */
  2087. default:
  2088. /* This error code is unknown. This should not happen. */
  2089. if (conn) {
  2090. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2091. }
  2092. /* Return at least a category according to RFC 2616 Section 10. */
  2093. if (response_code >= 100 && response_code < 200) {
  2094. /* Unknown informational status code */
  2095. return "Information";
  2096. }
  2097. if (response_code >= 200 && response_code < 300) {
  2098. /* Unknown success code */
  2099. return "Success";
  2100. }
  2101. if (response_code >= 300 && response_code < 400) {
  2102. /* Unknown redirection code */
  2103. return "Redirection";
  2104. }
  2105. if (response_code >= 400 && response_code < 500) {
  2106. /* Unknown request error code */
  2107. return "Client Error";
  2108. }
  2109. if (response_code >= 500 && response_code < 600) {
  2110. /* Unknown server error code */
  2111. return "Server Error";
  2112. }
  2113. /* Response code not even within reasonable range */
  2114. return "";
  2115. }
  2116. }
  2117. static void send_http_error(struct mg_connection *,
  2118. int,
  2119. PRINTF_FORMAT_STRING(const char *fmt),
  2120. ...) PRINTF_ARGS(3, 4);
  2121. static void
  2122. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2123. {
  2124. char buf[MG_BUF_LEN];
  2125. va_list ap;
  2126. int len, i, page_handler_found, scope, truncated;
  2127. char date[64];
  2128. time_t curtime = time(NULL);
  2129. const char *error_handler = NULL;
  2130. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2131. const char *error_page_file_ext, *tstr;
  2132. const char *status_text = mg_get_response_code_text(conn, status);
  2133. if (conn == NULL) {
  2134. return;
  2135. }
  2136. conn->status_code = status;
  2137. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2138. || conn->ctx->callbacks.http_error(conn, status)) {
  2139. if (!conn->in_error_handler) {
  2140. /* Send user defined error pages, if defined */
  2141. error_handler = conn->ctx->config[ERROR_PAGES];
  2142. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2143. page_handler_found = 0;
  2144. if (error_handler != NULL) {
  2145. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2146. switch (scope) {
  2147. case 1: /* Handler for specific error, e.g. 404 error */
  2148. mg_snprintf(conn,
  2149. &truncated,
  2150. buf,
  2151. sizeof(buf) - 32,
  2152. "%serror%03u.",
  2153. error_handler,
  2154. status);
  2155. break;
  2156. case 2: /* Handler for error group, e.g., 5xx error handler
  2157. * for all server errors (500-599) */
  2158. mg_snprintf(conn,
  2159. &truncated,
  2160. buf,
  2161. sizeof(buf) - 32,
  2162. "%serror%01uxx.",
  2163. error_handler,
  2164. status / 100);
  2165. break;
  2166. default: /* Handler for all errors */
  2167. mg_snprintf(conn,
  2168. &truncated,
  2169. buf,
  2170. sizeof(buf) - 32,
  2171. "%serror.",
  2172. error_handler);
  2173. break;
  2174. }
  2175. /* String truncation in buf may only occur if error_handler
  2176. * is too long. This string is from the config, not from a
  2177. * client. */
  2178. (void)truncated;
  2179. len = (int)strlen(buf);
  2180. tstr = strchr(error_page_file_ext, '.');
  2181. while (tstr) {
  2182. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2183. i++)
  2184. buf[len + i - 1] = tstr[i];
  2185. buf[len + i - 1] = 0;
  2186. if (mg_stat(conn, buf, &error_page_file)) {
  2187. page_handler_found = 1;
  2188. break;
  2189. }
  2190. tstr = strchr(tstr + i, '.');
  2191. }
  2192. }
  2193. }
  2194. if (page_handler_found) {
  2195. conn->in_error_handler = 1;
  2196. handle_file_based_request(conn, buf, &error_page_file);
  2197. conn->in_error_handler = 0;
  2198. return;
  2199. }
  2200. }
  2201. /* No custom error page. Send default error page. */
  2202. gmt_time_string(date, sizeof(date), &curtime);
  2203. conn->must_close = 1;
  2204. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2205. send_no_cache_header(conn);
  2206. mg_printf(conn,
  2207. "Date: %s\r\n"
  2208. "Connection: close\r\n\r\n",
  2209. date);
  2210. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2211. if (status > 199 && status != 204 && status != 304) {
  2212. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2213. if (fmt != NULL) {
  2214. va_start(ap, fmt);
  2215. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2216. va_end(ap);
  2217. mg_write(conn, buf, strlen(buf));
  2218. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2219. }
  2220. } else {
  2221. /* No body allowed. Close the connection. */
  2222. DEBUG_TRACE("Error %i", status);
  2223. }
  2224. }
  2225. }
  2226. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2227. /* Create substitutes for POSIX functions in Win32. */
  2228. #if defined(__MINGW32__)
  2229. /* Show no warning in case system functions are not used. */
  2230. #pragma GCC diagnostic push
  2231. #pragma GCC diagnostic ignored "-Wunused-function"
  2232. #endif
  2233. static int
  2234. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2235. {
  2236. (void)unused;
  2237. *mutex = CreateMutex(NULL, FALSE, NULL);
  2238. return *mutex == NULL ? -1 : 0;
  2239. }
  2240. static int
  2241. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2242. {
  2243. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2244. }
  2245. static int
  2246. pthread_mutex_lock(pthread_mutex_t *mutex)
  2247. {
  2248. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2249. }
  2250. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2251. static int
  2252. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2253. {
  2254. switch (WaitForSingleObject(*mutex, 0)) {
  2255. case WAIT_OBJECT_0:
  2256. return 0;
  2257. case WAIT_TIMEOUT:
  2258. return -2; /* EBUSY */
  2259. }
  2260. return -1;
  2261. }
  2262. #endif
  2263. static int
  2264. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2265. {
  2266. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2267. }
  2268. #ifndef WIN_PTHREADS_TIME_H
  2269. static int
  2270. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2271. {
  2272. FILETIME ft;
  2273. ULARGE_INTEGER li;
  2274. BOOL ok = FALSE;
  2275. double d;
  2276. static double perfcnt_per_sec = 0.0;
  2277. if (tp) {
  2278. memset(tp, 0, sizeof(*tp));
  2279. if (clk_id == CLOCK_REALTIME) {
  2280. GetSystemTimeAsFileTime(&ft);
  2281. li.LowPart = ft.dwLowDateTime;
  2282. li.HighPart = ft.dwHighDateTime;
  2283. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2284. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2285. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2286. ok = TRUE;
  2287. } else if (clk_id == CLOCK_MONOTONIC) {
  2288. if (perfcnt_per_sec == 0.0) {
  2289. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2290. perfcnt_per_sec = 1.0 / li.QuadPart;
  2291. }
  2292. if (perfcnt_per_sec != 0.0) {
  2293. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2294. d = li.QuadPart * perfcnt_per_sec;
  2295. tp->tv_sec = (time_t)d;
  2296. d -= tp->tv_sec;
  2297. tp->tv_nsec = (long)(d * 1.0E9);
  2298. ok = TRUE;
  2299. }
  2300. }
  2301. }
  2302. return ok ? 0 : -1;
  2303. }
  2304. #endif
  2305. static int
  2306. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2307. {
  2308. (void)unused;
  2309. InitializeCriticalSection(&cv->threadIdSec);
  2310. cv->waitingthreadcount = 0;
  2311. cv->waitingthreadhdls =
  2312. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2313. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2314. }
  2315. static int
  2316. pthread_cond_timedwait(pthread_cond_t *cv,
  2317. pthread_mutex_t *mutex,
  2318. const struct timespec *abstime)
  2319. {
  2320. struct mg_workerTLS *tls =
  2321. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2322. int ok;
  2323. struct timespec tsnow;
  2324. int64_t nsnow, nswaitabs, nswaitrel;
  2325. DWORD mswaitrel;
  2326. EnterCriticalSection(&cv->threadIdSec);
  2327. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2328. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2329. tls->pthread_cond_helper_mutex;
  2330. cv->waitingthreadcount++;
  2331. LeaveCriticalSection(&cv->threadIdSec);
  2332. if (abstime) {
  2333. clock_gettime(CLOCK_REALTIME, &tsnow);
  2334. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2335. nswaitabs =
  2336. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2337. nswaitrel = nswaitabs - nsnow;
  2338. if (nswaitrel < 0) {
  2339. nswaitrel = 0;
  2340. }
  2341. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2342. } else {
  2343. mswaitrel = INFINITE;
  2344. }
  2345. pthread_mutex_unlock(mutex);
  2346. ok = (WAIT_OBJECT_0
  2347. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2348. pthread_mutex_lock(mutex);
  2349. return ok ? 0 : -1;
  2350. }
  2351. static int
  2352. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2353. {
  2354. return pthread_cond_timedwait(cv, mutex, NULL);
  2355. }
  2356. static int
  2357. pthread_cond_signal(pthread_cond_t *cv)
  2358. {
  2359. int i;
  2360. HANDLE wkup = NULL;
  2361. BOOL ok = FALSE;
  2362. EnterCriticalSection(&cv->threadIdSec);
  2363. if (cv->waitingthreadcount) {
  2364. wkup = cv->waitingthreadhdls[0];
  2365. ok = SetEvent(wkup);
  2366. for (i = 1; i < cv->waitingthreadcount; i++) {
  2367. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2368. }
  2369. cv->waitingthreadcount--;
  2370. assert(ok);
  2371. }
  2372. LeaveCriticalSection(&cv->threadIdSec);
  2373. return ok ? 0 : 1;
  2374. }
  2375. static int
  2376. pthread_cond_broadcast(pthread_cond_t *cv)
  2377. {
  2378. EnterCriticalSection(&cv->threadIdSec);
  2379. while (cv->waitingthreadcount) {
  2380. pthread_cond_signal(cv);
  2381. }
  2382. LeaveCriticalSection(&cv->threadIdSec);
  2383. return 0;
  2384. }
  2385. static int
  2386. pthread_cond_destroy(pthread_cond_t *cv)
  2387. {
  2388. EnterCriticalSection(&cv->threadIdSec);
  2389. assert(cv->waitingthreadcount == 0);
  2390. mg_free(cv->waitingthreadhdls);
  2391. cv->waitingthreadhdls = 0;
  2392. LeaveCriticalSection(&cv->threadIdSec);
  2393. DeleteCriticalSection(&cv->threadIdSec);
  2394. return 0;
  2395. }
  2396. #if defined(__MINGW32__)
  2397. /* Enable unused function warning again */
  2398. #pragma GCC diagnostic pop
  2399. #endif
  2400. /* For Windows, change all slashes to backslashes in path names. */
  2401. static void
  2402. change_slashes_to_backslashes(char *path)
  2403. {
  2404. int i;
  2405. for (i = 0; path[i] != '\0'; i++) {
  2406. if (path[i] == '/') {
  2407. path[i] = '\\';
  2408. }
  2409. /* remove double backslash (check i > 0 to preserve UNC paths,
  2410. * like \\server\file.txt) */
  2411. if ((path[i] == '\\') && (i > 0)) {
  2412. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2413. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2414. }
  2415. }
  2416. }
  2417. }
  2418. static int
  2419. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2420. {
  2421. int diff;
  2422. do {
  2423. diff = tolower(*s1) - tolower(*s2);
  2424. s1++;
  2425. s2++;
  2426. } while (diff == 0 && s1[-1] != '\0');
  2427. return diff;
  2428. }
  2429. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2430. * wbuf and wbuf_len is a target buffer and its length. */
  2431. static void
  2432. path_to_unicode(const struct mg_connection *conn,
  2433. const char *path,
  2434. wchar_t *wbuf,
  2435. size_t wbuf_len)
  2436. {
  2437. char buf[PATH_MAX], buf2[PATH_MAX];
  2438. wchar_t wbuf2[MAX_PATH + 1];
  2439. DWORD long_len, err;
  2440. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2441. mg_strlcpy(buf, path, sizeof(buf));
  2442. change_slashes_to_backslashes(buf);
  2443. /* Convert to Unicode and back. If doubly-converted string does not
  2444. * match the original, something is fishy, reject. */
  2445. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2446. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2447. WideCharToMultiByte(
  2448. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2449. if (strcmp(buf, buf2) != 0) {
  2450. wbuf[0] = L'\0';
  2451. }
  2452. /* TODO: Add a configuration to switch between case sensitive and
  2453. * case insensitive URIs for Windows server. */
  2454. /*
  2455. if (conn) {
  2456. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2457. fcompare = wcscmp;
  2458. }
  2459. }
  2460. */
  2461. (void)conn; /* conn is currently unused */
  2462. /* Only accept a full file path, not a Windows short (8.3) path. */
  2463. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2464. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2465. if (long_len == 0) {
  2466. err = GetLastError();
  2467. if (err == ERROR_FILE_NOT_FOUND) {
  2468. /* File does not exist. This is not always a problem here. */
  2469. return;
  2470. }
  2471. }
  2472. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2473. /* Short name is used. */
  2474. wbuf[0] = L'\0';
  2475. }
  2476. }
  2477. #if defined(_WIN32_WCE)
  2478. /* Create substitutes for POSIX functions in Win32. */
  2479. #if defined(__MINGW32__)
  2480. /* Show no warning in case system functions are not used. */
  2481. #pragma GCC diagnostic push
  2482. #pragma GCC diagnostic ignored "-Wunused-function"
  2483. #endif
  2484. static time_t
  2485. time(time_t *ptime)
  2486. {
  2487. time_t t;
  2488. SYSTEMTIME st;
  2489. FILETIME ft;
  2490. GetSystemTime(&st);
  2491. SystemTimeToFileTime(&st, &ft);
  2492. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2493. if (ptime != NULL) {
  2494. *ptime = t;
  2495. }
  2496. return t;
  2497. }
  2498. static struct tm *
  2499. localtime(const time_t *ptime, struct tm *ptm)
  2500. {
  2501. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2502. FILETIME ft, lft;
  2503. SYSTEMTIME st;
  2504. TIME_ZONE_INFORMATION tzinfo;
  2505. if (ptm == NULL) {
  2506. return NULL;
  2507. }
  2508. *(int64_t *)&ft = t;
  2509. FileTimeToLocalFileTime(&ft, &lft);
  2510. FileTimeToSystemTime(&lft, &st);
  2511. ptm->tm_year = st.wYear - 1900;
  2512. ptm->tm_mon = st.wMonth - 1;
  2513. ptm->tm_wday = st.wDayOfWeek;
  2514. ptm->tm_mday = st.wDay;
  2515. ptm->tm_hour = st.wHour;
  2516. ptm->tm_min = st.wMinute;
  2517. ptm->tm_sec = st.wSecond;
  2518. ptm->tm_yday = 0; /* hope nobody uses this */
  2519. ptm->tm_isdst =
  2520. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2521. return ptm;
  2522. }
  2523. static struct tm *
  2524. gmtime(const time_t *ptime, struct tm *ptm)
  2525. {
  2526. /* FIXME(lsm): fix this. */
  2527. return localtime(ptime, ptm);
  2528. }
  2529. static size_t
  2530. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2531. {
  2532. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2533. return 0;
  2534. }
  2535. #if defined(__MINGW32__)
  2536. /* Enable unused function warning again */
  2537. #pragma GCC diagnostic pop
  2538. #endif
  2539. #endif
  2540. /* Windows happily opens files with some garbage at the end of file name.
  2541. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2542. * "a.cgi", despite one would expect an error back.
  2543. * This function returns non-0 if path ends with some garbage. */
  2544. static int
  2545. path_cannot_disclose_cgi(const char *path)
  2546. {
  2547. static const char *allowed_last_characters = "_-";
  2548. int last = path[strlen(path) - 1];
  2549. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2550. }
  2551. static int
  2552. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2553. {
  2554. wchar_t wbuf[PATH_MAX];
  2555. WIN32_FILE_ATTRIBUTE_DATA info;
  2556. time_t creation_time;
  2557. if (!filep) {
  2558. return 0;
  2559. }
  2560. memset(filep, 0, sizeof(*filep));
  2561. if (conn && is_file_in_memory(conn, path, filep)) {
  2562. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2563. * memset */
  2564. filep->last_modified = time(NULL);
  2565. /* last_modified = now ... assumes the file may change during runtime,
  2566. * so every mg_fopen call may return different data */
  2567. /* last_modified = conn->ctx.start_time;
  2568. * May be used it the data does not change during runtime. This allows
  2569. * browser caching. Since we do not know, we have to assume the file
  2570. * in memory may change. */
  2571. return 1;
  2572. }
  2573. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2574. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2575. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2576. filep->last_modified =
  2577. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2578. info.ftLastWriteTime.dwHighDateTime);
  2579. /* On Windows, the file creation time can be higher than the
  2580. * modification time, e.g. when a file is copied.
  2581. * Since the Last-Modified timestamp is used for caching
  2582. * it should be based on the most recent timestamp. */
  2583. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2584. info.ftCreationTime.dwHighDateTime);
  2585. if (creation_time > filep->last_modified) {
  2586. filep->last_modified = creation_time;
  2587. }
  2588. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2589. /* If file name is fishy, reset the file structure and return
  2590. * error.
  2591. * Note it is important to reset, not just return the error, cause
  2592. * functions like is_file_opened() check the struct. */
  2593. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2594. memset(filep, 0, sizeof(*filep));
  2595. return 0;
  2596. }
  2597. return 1;
  2598. }
  2599. return 0;
  2600. }
  2601. static int
  2602. mg_remove(const struct mg_connection *conn, const char *path)
  2603. {
  2604. wchar_t wbuf[PATH_MAX];
  2605. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2606. return DeleteFileW(wbuf) ? 0 : -1;
  2607. }
  2608. static int
  2609. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2610. {
  2611. wchar_t wbuf[PATH_MAX];
  2612. (void)mode;
  2613. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2614. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2615. }
  2616. /* Create substitutes for POSIX functions in Win32. */
  2617. #if defined(__MINGW32__)
  2618. /* Show no warning in case system functions are not used. */
  2619. #pragma GCC diagnostic push
  2620. #pragma GCC diagnostic ignored "-Wunused-function"
  2621. #endif
  2622. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2623. static DIR *
  2624. mg_opendir(const struct mg_connection *conn, const char *name)
  2625. {
  2626. DIR *dir = NULL;
  2627. wchar_t wpath[PATH_MAX];
  2628. DWORD attrs;
  2629. if (name == NULL) {
  2630. SetLastError(ERROR_BAD_ARGUMENTS);
  2631. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2632. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2633. } else {
  2634. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2635. attrs = GetFileAttributesW(wpath);
  2636. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2637. == FILE_ATTRIBUTE_DIRECTORY)) {
  2638. (void)wcscat(wpath, L"\\*");
  2639. dir->handle = FindFirstFileW(wpath, &dir->info);
  2640. dir->result.d_name[0] = '\0';
  2641. } else {
  2642. mg_free(dir);
  2643. dir = NULL;
  2644. }
  2645. }
  2646. return dir;
  2647. }
  2648. static int
  2649. mg_closedir(DIR *dir)
  2650. {
  2651. int result = 0;
  2652. if (dir != NULL) {
  2653. if (dir->handle != INVALID_HANDLE_VALUE)
  2654. result = FindClose(dir->handle) ? 0 : -1;
  2655. mg_free(dir);
  2656. } else {
  2657. result = -1;
  2658. SetLastError(ERROR_BAD_ARGUMENTS);
  2659. }
  2660. return result;
  2661. }
  2662. static struct dirent *
  2663. mg_readdir(DIR *dir)
  2664. {
  2665. struct dirent *result = 0;
  2666. if (dir) {
  2667. if (dir->handle != INVALID_HANDLE_VALUE) {
  2668. result = &dir->result;
  2669. (void)WideCharToMultiByte(CP_UTF8,
  2670. 0,
  2671. dir->info.cFileName,
  2672. -1,
  2673. result->d_name,
  2674. sizeof(result->d_name),
  2675. NULL,
  2676. NULL);
  2677. if (!FindNextFileW(dir->handle, &dir->info)) {
  2678. (void)FindClose(dir->handle);
  2679. dir->handle = INVALID_HANDLE_VALUE;
  2680. }
  2681. } else {
  2682. SetLastError(ERROR_FILE_NOT_FOUND);
  2683. }
  2684. } else {
  2685. SetLastError(ERROR_BAD_ARGUMENTS);
  2686. }
  2687. return result;
  2688. }
  2689. #ifndef HAVE_POLL
  2690. static int
  2691. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2692. {
  2693. struct timeval tv;
  2694. fd_set set;
  2695. unsigned int i;
  2696. int result;
  2697. SOCKET maxfd = 0;
  2698. memset(&tv, 0, sizeof(tv));
  2699. tv.tv_sec = milliseconds / 1000;
  2700. tv.tv_usec = (milliseconds % 1000) * 1000;
  2701. FD_ZERO(&set);
  2702. for (i = 0; i < n; i++) {
  2703. FD_SET((SOCKET)pfd[i].fd, &set);
  2704. pfd[i].revents = 0;
  2705. if (pfd[i].fd > maxfd) {
  2706. maxfd = pfd[i].fd;
  2707. }
  2708. }
  2709. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2710. for (i = 0; i < n; i++) {
  2711. if (FD_ISSET(pfd[i].fd, &set)) {
  2712. pfd[i].revents = POLLIN;
  2713. }
  2714. }
  2715. }
  2716. return result;
  2717. }
  2718. #endif /* HAVE_POLL */
  2719. #if defined(__MINGW32__)
  2720. /* Enable unused function warning again */
  2721. #pragma GCC diagnostic pop
  2722. #endif
  2723. static void
  2724. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2725. {
  2726. (void)conn; /* Unused. */
  2727. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2728. }
  2729. int
  2730. mg_start_thread(mg_thread_func_t f, void *p)
  2731. {
  2732. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2733. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2734. */
  2735. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2736. == ((uintptr_t)(-1L)))
  2737. ? -1
  2738. : 0);
  2739. #else
  2740. return (
  2741. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2742. ? -1
  2743. : 0);
  2744. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2745. }
  2746. /* Start a thread storing the thread context. */
  2747. static int
  2748. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2749. void *p,
  2750. pthread_t *threadidptr)
  2751. {
  2752. uintptr_t uip;
  2753. HANDLE threadhandle;
  2754. int result = -1;
  2755. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2756. threadhandle = (HANDLE)uip;
  2757. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2758. *threadidptr = threadhandle;
  2759. result = 0;
  2760. }
  2761. return result;
  2762. }
  2763. /* Wait for a thread to finish. */
  2764. static int
  2765. mg_join_thread(pthread_t threadid)
  2766. {
  2767. int result;
  2768. DWORD dwevent;
  2769. result = -1;
  2770. dwevent = WaitForSingleObject(threadid, INFINITE);
  2771. if (dwevent == WAIT_FAILED) {
  2772. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2773. } else {
  2774. if (dwevent == WAIT_OBJECT_0) {
  2775. CloseHandle(threadid);
  2776. result = 0;
  2777. }
  2778. }
  2779. return result;
  2780. }
  2781. #if !defined(NO_SSL_DL)
  2782. /* Create substitutes for POSIX functions in Win32. */
  2783. #if defined(__MINGW32__)
  2784. /* Show no warning in case system functions are not used. */
  2785. #pragma GCC diagnostic push
  2786. #pragma GCC diagnostic ignored "-Wunused-function"
  2787. #endif
  2788. static HANDLE
  2789. dlopen(const char *dll_name, int flags)
  2790. {
  2791. wchar_t wbuf[PATH_MAX];
  2792. (void)flags;
  2793. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  2794. return LoadLibraryW(wbuf);
  2795. }
  2796. static int
  2797. dlclose(void *handle)
  2798. {
  2799. int result;
  2800. if (FreeLibrary((HMODULE)handle) != 0) {
  2801. result = 0;
  2802. } else {
  2803. result = -1;
  2804. }
  2805. return result;
  2806. }
  2807. #if defined(__MINGW32__)
  2808. /* Enable unused function warning again */
  2809. #pragma GCC diagnostic pop
  2810. #endif
  2811. #endif
  2812. #if !defined(NO_CGI)
  2813. #define SIGKILL (0)
  2814. static int
  2815. kill(pid_t pid, int sig_num)
  2816. {
  2817. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2818. (void)CloseHandle((HANDLE)pid);
  2819. return 0;
  2820. }
  2821. static void
  2822. trim_trailing_whitespaces(char *s)
  2823. {
  2824. char *e = s + strlen(s) - 1;
  2825. while (e > s && isspace(*(unsigned char *)e)) {
  2826. *e-- = '\0';
  2827. }
  2828. }
  2829. static pid_t
  2830. spawn_process(struct mg_connection *conn,
  2831. const char *prog,
  2832. char *envblk,
  2833. char *envp[],
  2834. int fdin[2],
  2835. int fdout[2],
  2836. int fderr[2],
  2837. const char *dir)
  2838. {
  2839. HANDLE me;
  2840. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2841. cmdline[PATH_MAX], buf[PATH_MAX];
  2842. int truncated;
  2843. struct file file = STRUCT_FILE_INITIALIZER;
  2844. STARTUPINFOA si;
  2845. PROCESS_INFORMATION pi = {0};
  2846. (void)envp;
  2847. memset(&si, 0, sizeof(si));
  2848. si.cb = sizeof(si);
  2849. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2850. si.wShowWindow = SW_HIDE;
  2851. me = GetCurrentProcess();
  2852. DuplicateHandle(me,
  2853. (HANDLE)_get_osfhandle(fdin[0]),
  2854. me,
  2855. &si.hStdInput,
  2856. 0,
  2857. TRUE,
  2858. DUPLICATE_SAME_ACCESS);
  2859. DuplicateHandle(me,
  2860. (HANDLE)_get_osfhandle(fdout[1]),
  2861. me,
  2862. &si.hStdOutput,
  2863. 0,
  2864. TRUE,
  2865. DUPLICATE_SAME_ACCESS);
  2866. DuplicateHandle(me,
  2867. (HANDLE)_get_osfhandle(fderr[1]),
  2868. me,
  2869. &si.hStdError,
  2870. 0,
  2871. TRUE,
  2872. DUPLICATE_SAME_ACCESS);
  2873. /* Mark handles that should not be inherited. See
  2874. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  2875. */
  2876. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  2877. HANDLE_FLAG_INHERIT,
  2878. 0);
  2879. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  2880. HANDLE_FLAG_INHERIT,
  2881. 0);
  2882. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  2883. HANDLE_FLAG_INHERIT,
  2884. 0);
  2885. /* If CGI file is a script, try to read the interpreter line */
  2886. interp = conn->ctx->config[CGI_INTERPRETER];
  2887. if (interp == NULL) {
  2888. buf[0] = buf[1] = '\0';
  2889. /* Read the first line of the script into the buffer */
  2890. mg_snprintf(
  2891. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2892. if (truncated) {
  2893. pi.hProcess = (pid_t)-1;
  2894. goto spawn_cleanup;
  2895. }
  2896. if (mg_fopen(conn, cmdline, "r", &file)) {
  2897. p = (char *)file.membuf;
  2898. mg_fgets(buf, sizeof(buf), &file, &p);
  2899. mg_fclose(&file);
  2900. buf[sizeof(buf) - 1] = '\0';
  2901. }
  2902. if (buf[0] == '#' && buf[1] == '!') {
  2903. trim_trailing_whitespaces(buf + 2);
  2904. } else {
  2905. buf[2] = '\0';
  2906. }
  2907. interp = buf + 2;
  2908. }
  2909. if (interp[0] != '\0') {
  2910. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2911. interp = full_interp;
  2912. }
  2913. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2914. if (interp[0] != '\0') {
  2915. mg_snprintf(conn,
  2916. &truncated,
  2917. cmdline,
  2918. sizeof(cmdline),
  2919. "\"%s\" \"%s\\%s\"",
  2920. interp,
  2921. full_dir,
  2922. prog);
  2923. } else {
  2924. mg_snprintf(conn,
  2925. &truncated,
  2926. cmdline,
  2927. sizeof(cmdline),
  2928. "\"%s\\%s\"",
  2929. full_dir,
  2930. prog);
  2931. }
  2932. if (truncated) {
  2933. pi.hProcess = (pid_t)-1;
  2934. goto spawn_cleanup;
  2935. }
  2936. DEBUG_TRACE("Running [%s]", cmdline);
  2937. if (CreateProcessA(NULL,
  2938. cmdline,
  2939. NULL,
  2940. NULL,
  2941. TRUE,
  2942. CREATE_NEW_PROCESS_GROUP,
  2943. envblk,
  2944. NULL,
  2945. &si,
  2946. &pi) == 0) {
  2947. mg_cry(
  2948. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2949. pi.hProcess = (pid_t)-1;
  2950. /* goto spawn_cleanup; */
  2951. }
  2952. spawn_cleanup:
  2953. (void)CloseHandle(si.hStdOutput);
  2954. (void)CloseHandle(si.hStdError);
  2955. (void)CloseHandle(si.hStdInput);
  2956. if (pi.hThread != NULL) {
  2957. (void)CloseHandle(pi.hThread);
  2958. }
  2959. return (pid_t)pi.hProcess;
  2960. }
  2961. #endif /* !NO_CGI */
  2962. static int
  2963. set_non_blocking_mode(SOCKET sock)
  2964. {
  2965. unsigned long on = 1;
  2966. return ioctlsocket(sock, (long)FIONBIO, &on);
  2967. }
  2968. #else
  2969. static int
  2970. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2971. {
  2972. struct stat st;
  2973. if (!filep) {
  2974. return 0;
  2975. }
  2976. memset(filep, 0, sizeof(*filep));
  2977. if (conn && is_file_in_memory(conn, path, filep)) {
  2978. return 1;
  2979. }
  2980. if (0 == stat(path, &st)) {
  2981. filep->size = (uint64_t)(st.st_size);
  2982. filep->last_modified = st.st_mtime;
  2983. filep->is_directory = S_ISDIR(st.st_mode);
  2984. return 1;
  2985. }
  2986. return 0;
  2987. }
  2988. static void
  2989. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2990. {
  2991. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2992. if (conn) {
  2993. mg_cry(conn,
  2994. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2995. __func__,
  2996. strerror(ERRNO));
  2997. }
  2998. }
  2999. }
  3000. int
  3001. mg_start_thread(mg_thread_func_t func, void *param)
  3002. {
  3003. pthread_t thread_id;
  3004. pthread_attr_t attr;
  3005. int result;
  3006. (void)pthread_attr_init(&attr);
  3007. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3008. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3009. /* Compile-time option to control stack size,
  3010. * e.g. -DUSE_STACK_SIZE=16384 */
  3011. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3012. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3013. result = pthread_create(&thread_id, &attr, func, param);
  3014. pthread_attr_destroy(&attr);
  3015. return result;
  3016. }
  3017. /* Start a thread storing the thread context. */
  3018. static int
  3019. mg_start_thread_with_id(mg_thread_func_t func,
  3020. void *param,
  3021. pthread_t *threadidptr)
  3022. {
  3023. pthread_t thread_id;
  3024. pthread_attr_t attr;
  3025. int result;
  3026. (void)pthread_attr_init(&attr);
  3027. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3028. /* Compile-time option to control stack size,
  3029. * e.g. -DUSE_STACK_SIZE=16384 */
  3030. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3031. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3032. result = pthread_create(&thread_id, &attr, func, param);
  3033. pthread_attr_destroy(&attr);
  3034. if ((result == 0) && (threadidptr != NULL)) {
  3035. *threadidptr = thread_id;
  3036. }
  3037. return result;
  3038. }
  3039. /* Wait for a thread to finish. */
  3040. static int
  3041. mg_join_thread(pthread_t threadid)
  3042. {
  3043. int result;
  3044. result = pthread_join(threadid, NULL);
  3045. return result;
  3046. }
  3047. #ifndef NO_CGI
  3048. static pid_t
  3049. spawn_process(struct mg_connection *conn,
  3050. const char *prog,
  3051. char *envblk,
  3052. char *envp[],
  3053. int fdin[2],
  3054. int fdout[2],
  3055. int fderr[2],
  3056. const char *dir)
  3057. {
  3058. pid_t pid;
  3059. const char *interp;
  3060. (void)envblk;
  3061. if (conn == NULL) {
  3062. return 0;
  3063. }
  3064. if ((pid = fork()) == -1) {
  3065. /* Parent */
  3066. send_http_error(conn,
  3067. 500,
  3068. "Error: Creating CGI process\nfork(): %s",
  3069. strerror(ERRNO));
  3070. } else if (pid == 0) {
  3071. /* Child */
  3072. if (chdir(dir) != 0) {
  3073. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3074. } else if (dup2(fdin[0], 0) == -1) {
  3075. mg_cry(conn,
  3076. "%s: dup2(%d, 0): %s",
  3077. __func__,
  3078. fdin[0],
  3079. strerror(ERRNO));
  3080. } else if (dup2(fdout[1], 1) == -1) {
  3081. mg_cry(conn,
  3082. "%s: dup2(%d, 1): %s",
  3083. __func__,
  3084. fdout[1],
  3085. strerror(ERRNO));
  3086. } else if (dup2(fderr[1], 2) == -1) {
  3087. mg_cry(conn,
  3088. "%s: dup2(%d, 2): %s",
  3089. __func__,
  3090. fderr[1],
  3091. strerror(ERRNO));
  3092. } else {
  3093. /* Keep stderr and stdout in two different pipes.
  3094. * Stdout will be sent back to the client,
  3095. * stderr should go into a server error log. */
  3096. (void)close(fdin[0]);
  3097. (void)close(fdout[1]);
  3098. (void)close(fderr[1]);
  3099. /* Close write end fdin and read end fdout and fderr */
  3100. (void)close(fdin[1]);
  3101. (void)close(fdout[0]);
  3102. (void)close(fderr[0]);
  3103. /* After exec, all signal handlers are restored to their default
  3104. * values, with one exception of SIGCHLD. According to
  3105. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3106. * leave unchanged after exec if it was set to be ignored. Restore
  3107. * it to default action. */
  3108. signal(SIGCHLD, SIG_DFL);
  3109. interp = conn->ctx->config[CGI_INTERPRETER];
  3110. if (interp == NULL) {
  3111. (void)execle(prog, prog, NULL, envp);
  3112. mg_cry(conn,
  3113. "%s: execle(%s): %s",
  3114. __func__,
  3115. prog,
  3116. strerror(ERRNO));
  3117. } else {
  3118. (void)execle(interp, interp, prog, NULL, envp);
  3119. mg_cry(conn,
  3120. "%s: execle(%s %s): %s",
  3121. __func__,
  3122. interp,
  3123. prog,
  3124. strerror(ERRNO));
  3125. }
  3126. }
  3127. exit(EXIT_FAILURE);
  3128. }
  3129. return pid;
  3130. }
  3131. #endif /* !NO_CGI */
  3132. static int
  3133. set_non_blocking_mode(SOCKET sock)
  3134. {
  3135. int flags;
  3136. flags = fcntl(sock, F_GETFL, 0);
  3137. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3138. return 0;
  3139. }
  3140. #endif /* _WIN32 */
  3141. /* End of initial operating system specific define block. */
  3142. /* Get a random number (independent of C rand function) */
  3143. static uint64_t
  3144. get_random(void)
  3145. {
  3146. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3147. static uint64_t lcg = 0; /* Linear congruential generator */
  3148. struct timespec now;
  3149. memset(&now, 0, sizeof(now));
  3150. clock_gettime(CLOCK_MONOTONIC, &now);
  3151. if (lfsr == 0) {
  3152. /* lfsr will be only 0 if has not been initialized,
  3153. * so this code is called only once. */
  3154. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3155. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3156. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3157. + (uint64_t)(ptrdiff_t)&now;
  3158. } else {
  3159. /* Get the next step of both random number generators. */
  3160. lfsr = (lfsr >> 1)
  3161. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3162. << 63);
  3163. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3164. }
  3165. /* Combining two pseudo-random number generators and a high resolution part
  3166. * of the current server time will make it hard (impossible?) to guess the
  3167. * next number. */
  3168. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3169. }
  3170. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3171. * descriptor. Return number of bytes written. */
  3172. static int
  3173. push(struct mg_context *ctx,
  3174. FILE *fp,
  3175. SOCKET sock,
  3176. SSL *ssl,
  3177. const char *buf,
  3178. int len,
  3179. double timeout)
  3180. {
  3181. struct timespec start, now;
  3182. int n, err;
  3183. #ifdef _WIN32
  3184. typedef int len_t;
  3185. #else
  3186. typedef size_t len_t;
  3187. #endif
  3188. if (timeout > 0) {
  3189. memset(&start, 0, sizeof(start));
  3190. memset(&now, 0, sizeof(now));
  3191. clock_gettime(CLOCK_MONOTONIC, &start);
  3192. }
  3193. if (ctx == NULL) {
  3194. return -1;
  3195. }
  3196. #ifdef NO_SSL
  3197. if (ssl) {
  3198. return -1;
  3199. }
  3200. #endif
  3201. do {
  3202. #ifndef NO_SSL
  3203. if (ssl != NULL) {
  3204. n = SSL_write(ssl, buf, len);
  3205. if (n <= 0) {
  3206. err = SSL_get_error(ssl, n);
  3207. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  3208. err = ERRNO;
  3209. } else {
  3210. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3211. return -1;
  3212. }
  3213. } else {
  3214. err = 0;
  3215. }
  3216. } else
  3217. #endif
  3218. if (fp != NULL) {
  3219. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3220. if (ferror(fp)) {
  3221. n = -1;
  3222. err = ERRNO;
  3223. } else {
  3224. err = 0;
  3225. }
  3226. } else {
  3227. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3228. err = (n < 0) ? ERRNO : 0;
  3229. }
  3230. if (ctx->stop_flag) {
  3231. return -1;
  3232. }
  3233. if ((n > 0) || (n == 0 && len == 0)) {
  3234. /* some data has been read, or no data was requested */
  3235. return n;
  3236. }
  3237. if (n == 0) {
  3238. /* shutdown of the socket at client side */
  3239. return -1;
  3240. }
  3241. if (n < 0) {
  3242. /* socket error - check errno */
  3243. DEBUG_TRACE("send() failed, error %d", err);
  3244. /* TODO: error handling depending on the error code.
  3245. * These codes are different between Windows and Linux.
  3246. */
  3247. return -1;
  3248. }
  3249. /* This code is not reached in the moment.
  3250. * ==> Fix the TODOs above first. */
  3251. if (timeout > 0) {
  3252. clock_gettime(CLOCK_MONOTONIC, &now);
  3253. }
  3254. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3255. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3256. used */
  3257. return -1;
  3258. }
  3259. static int64_t
  3260. push_all(struct mg_context *ctx,
  3261. FILE *fp,
  3262. SOCKET sock,
  3263. SSL *ssl,
  3264. const char *buf,
  3265. int64_t len)
  3266. {
  3267. double timeout = -1.0;
  3268. int64_t n, nwritten = 0;
  3269. if (ctx == NULL) {
  3270. return -1;
  3271. }
  3272. if (ctx->config[REQUEST_TIMEOUT]) {
  3273. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3274. }
  3275. while (len > 0 && ctx->stop_flag == 0) {
  3276. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3277. if (n < 0) {
  3278. if (nwritten == 0) {
  3279. nwritten = n; /* Propagate the error */
  3280. }
  3281. break;
  3282. } else if (n == 0) {
  3283. break; /* No more data to write */
  3284. } else {
  3285. nwritten += n;
  3286. len -= n;
  3287. }
  3288. }
  3289. return nwritten;
  3290. }
  3291. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3292. * Return negative value on error, or number of bytes read on success. */
  3293. static int
  3294. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3295. {
  3296. int nread, err;
  3297. struct timespec start, now;
  3298. #ifdef _WIN32
  3299. typedef int len_t;
  3300. #else
  3301. typedef size_t len_t;
  3302. #endif
  3303. if (timeout > 0) {
  3304. memset(&start, 0, sizeof(start));
  3305. memset(&now, 0, sizeof(now));
  3306. clock_gettime(CLOCK_MONOTONIC, &start);
  3307. }
  3308. do {
  3309. if (fp != NULL) {
  3310. /* Use read() instead of fread(), because if we're reading from the
  3311. * CGI pipe, fread() may block until IO buffer is filled up. We
  3312. * cannot afford to block and must pass all read bytes immediately
  3313. * to the client. */
  3314. nread = (int)read(fileno(fp), buf, (size_t)len);
  3315. err = (nread < 0) ? ERRNO : 0;
  3316. #ifndef NO_SSL
  3317. } else if (conn->ssl != NULL) {
  3318. nread = SSL_read(conn->ssl, buf, len);
  3319. if (nread <= 0) {
  3320. err = SSL_get_error(conn->ssl, nread);
  3321. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3322. err = ERRNO;
  3323. } else {
  3324. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3325. return -1;
  3326. }
  3327. } else {
  3328. err = 0;
  3329. }
  3330. #endif
  3331. } else {
  3332. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3333. err = (nread < 0) ? ERRNO : 0;
  3334. }
  3335. if (conn->ctx->stop_flag) {
  3336. return -1;
  3337. }
  3338. if ((nread > 0) || (nread == 0 && len == 0)) {
  3339. /* some data has been read, or no data was requested */
  3340. return nread;
  3341. }
  3342. if (nread == 0) {
  3343. /* shutdown of the socket at client side */
  3344. return -1;
  3345. }
  3346. if (nread < 0) {
  3347. /* socket error - check errno */
  3348. #ifdef _WIN32
  3349. if (err == WSAEWOULDBLOCK) {
  3350. /* standard case if called from close_socket_gracefully */
  3351. return -1;
  3352. } else if (err == WSAETIMEDOUT) {
  3353. /* timeout is handled by the while loop */
  3354. } else {
  3355. DEBUG_TRACE("recv() failed, error %d", err);
  3356. return -1;
  3357. }
  3358. #else
  3359. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3360. * if the timeout is reached and if the socket was set to non-
  3361. * blocking in close_socket_gracefully, so we can not distinguish
  3362. * here. We have to wait for the timeout in both cases for now.
  3363. */
  3364. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3365. /* EAGAIN/EWOULDBLOCK:
  3366. * standard case if called from close_socket_gracefully
  3367. * => should return -1 */
  3368. /* or timeout occured
  3369. * => the code must stay in the while loop */
  3370. /* EINTR can be generated on a socket with a timeout set even
  3371. * when SA_RESTART is effective for all relevant signals
  3372. * (see signal(7)).
  3373. * => stay in the while loop */
  3374. } else {
  3375. DEBUG_TRACE("recv() failed, error %d", err);
  3376. return -1;
  3377. }
  3378. #endif
  3379. }
  3380. if (timeout > 0) {
  3381. clock_gettime(CLOCK_MONOTONIC, &now);
  3382. }
  3383. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3384. /* Timeout occured, but no data available. */
  3385. return -1;
  3386. }
  3387. static int
  3388. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3389. {
  3390. int n, nread = 0;
  3391. double timeout = -1.0;
  3392. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3393. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3394. }
  3395. while (len > 0 && conn->ctx->stop_flag == 0) {
  3396. n = pull(fp, conn, buf + nread, len, timeout);
  3397. if (n < 0) {
  3398. if (nread == 0) {
  3399. nread = n; /* Propagate the error */
  3400. }
  3401. break;
  3402. } else if (n == 0) {
  3403. break; /* No more data to read */
  3404. } else {
  3405. conn->consumed_content += n;
  3406. nread += n;
  3407. len -= n;
  3408. }
  3409. }
  3410. return nread;
  3411. }
  3412. static void
  3413. discard_unread_request_data(struct mg_connection *conn)
  3414. {
  3415. char buf[MG_BUF_LEN];
  3416. size_t to_read;
  3417. int nread;
  3418. if (conn == NULL) {
  3419. return;
  3420. }
  3421. to_read = sizeof(buf);
  3422. if (conn->is_chunked) {
  3423. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3424. * completely */
  3425. while (conn->is_chunked == 1) {
  3426. nread = mg_read(conn, buf, to_read);
  3427. if (nread <= 0) {
  3428. break;
  3429. }
  3430. }
  3431. } else {
  3432. /* Not chunked: content length is known */
  3433. while (conn->consumed_content < conn->content_len) {
  3434. if (to_read
  3435. > (size_t)(conn->content_len - conn->consumed_content)) {
  3436. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3437. }
  3438. nread = mg_read(conn, buf, to_read);
  3439. if (nread <= 0) {
  3440. break;
  3441. }
  3442. }
  3443. }
  3444. }
  3445. static int
  3446. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3447. {
  3448. int64_t n, buffered_len, nread;
  3449. int64_t len64 =
  3450. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3451. * int, we may not read more
  3452. * bytes */
  3453. const char *body;
  3454. if (conn == NULL) {
  3455. return 0;
  3456. }
  3457. /* If Content-Length is not set for a PUT or POST request, read until
  3458. * socket is closed */
  3459. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3460. conn->content_len = INT64_MAX;
  3461. conn->must_close = 1;
  3462. }
  3463. nread = 0;
  3464. if (conn->consumed_content < conn->content_len) {
  3465. /* Adjust number of bytes to read. */
  3466. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3467. if (left_to_read < len64) {
  3468. /* Do not read more than the total content length of the request.
  3469. */
  3470. len64 = left_to_read;
  3471. }
  3472. /* Return buffered data */
  3473. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3474. - conn->consumed_content;
  3475. if (buffered_len > 0) {
  3476. if (len64 < buffered_len) {
  3477. buffered_len = len64;
  3478. }
  3479. body = conn->buf + conn->request_len + conn->consumed_content;
  3480. memcpy(buf, body, (size_t)buffered_len);
  3481. len64 -= buffered_len;
  3482. conn->consumed_content += buffered_len;
  3483. nread += buffered_len;
  3484. buf = (char *)buf + buffered_len;
  3485. }
  3486. /* We have returned all buffered data. Read new data from the remote
  3487. * socket.
  3488. */
  3489. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3490. nread += n;
  3491. } else {
  3492. nread = (nread > 0 ? nread : n);
  3493. }
  3494. }
  3495. return (int)nread;
  3496. }
  3497. static char
  3498. mg_getc(struct mg_connection *conn)
  3499. {
  3500. char c;
  3501. if (conn == NULL) {
  3502. return 0;
  3503. }
  3504. conn->content_len++;
  3505. if (mg_read_inner(conn, &c, 1) <= 0) {
  3506. return (char)0;
  3507. }
  3508. return c;
  3509. }
  3510. int
  3511. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3512. {
  3513. if (len > INT_MAX) {
  3514. len = INT_MAX;
  3515. }
  3516. if (conn == NULL) {
  3517. return 0;
  3518. }
  3519. if (conn->is_chunked) {
  3520. size_t all_read = 0;
  3521. while (len > 0) {
  3522. if (conn->is_chunked == 2) {
  3523. /* No more data left to read */
  3524. return 0;
  3525. }
  3526. if (conn->chunk_remainder) {
  3527. /* copy from the remainder of the last received chunk */
  3528. long read_ret;
  3529. size_t read_now =
  3530. ((conn->chunk_remainder > len) ? (len)
  3531. : (conn->chunk_remainder));
  3532. conn->content_len += (int)read_now;
  3533. read_ret =
  3534. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3535. all_read += (size_t)read_ret;
  3536. conn->chunk_remainder -= read_now;
  3537. len -= read_now;
  3538. if (conn->chunk_remainder == 0) {
  3539. /* the rest of the data in the current chunk has been read
  3540. */
  3541. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3542. /* Protocol violation */
  3543. return -1;
  3544. }
  3545. }
  3546. } else {
  3547. /* fetch a new chunk */
  3548. int i = 0;
  3549. char lenbuf[64];
  3550. char *end = 0;
  3551. unsigned long chunkSize = 0;
  3552. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3553. lenbuf[i] = mg_getc(conn);
  3554. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3555. continue;
  3556. }
  3557. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3558. lenbuf[i + 1] = 0;
  3559. chunkSize = strtoul(lenbuf, &end, 16);
  3560. if (chunkSize == 0) {
  3561. /* regular end of content */
  3562. conn->is_chunked = 2;
  3563. }
  3564. break;
  3565. }
  3566. if (!isalnum(lenbuf[i])) {
  3567. /* illegal character for chunk length */
  3568. return -1;
  3569. }
  3570. }
  3571. if ((end == NULL) || (*end != '\r')) {
  3572. /* chunksize not set correctly */
  3573. return -1;
  3574. }
  3575. if (chunkSize == 0) {
  3576. break;
  3577. }
  3578. conn->chunk_remainder = chunkSize;
  3579. }
  3580. }
  3581. return (int)all_read;
  3582. }
  3583. return mg_read_inner(conn, buf, len);
  3584. }
  3585. int
  3586. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3587. {
  3588. time_t now;
  3589. int64_t n, total, allowed;
  3590. if (conn == NULL) {
  3591. return 0;
  3592. }
  3593. if (conn->throttle > 0) {
  3594. if ((now = time(NULL)) != conn->last_throttle_time) {
  3595. conn->last_throttle_time = now;
  3596. conn->last_throttle_bytes = 0;
  3597. }
  3598. allowed = conn->throttle - conn->last_throttle_bytes;
  3599. if (allowed > (int64_t)len) {
  3600. allowed = (int64_t)len;
  3601. }
  3602. if ((total = push_all(conn->ctx,
  3603. NULL,
  3604. conn->client.sock,
  3605. conn->ssl,
  3606. (const char *)buf,
  3607. (int64_t)allowed)) == allowed) {
  3608. buf = (const char *)buf + total;
  3609. conn->last_throttle_bytes += total;
  3610. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3611. allowed = conn->throttle > (int64_t)len - total
  3612. ? (int64_t)len - total
  3613. : conn->throttle;
  3614. if ((n = push_all(conn->ctx,
  3615. NULL,
  3616. conn->client.sock,
  3617. conn->ssl,
  3618. (const char *)buf,
  3619. (int64_t)allowed)) != allowed) {
  3620. break;
  3621. }
  3622. sleep(1);
  3623. conn->last_throttle_bytes = allowed;
  3624. conn->last_throttle_time = time(NULL);
  3625. buf = (const char *)buf + n;
  3626. total += n;
  3627. }
  3628. }
  3629. } else {
  3630. total = push_all(conn->ctx,
  3631. NULL,
  3632. conn->client.sock,
  3633. conn->ssl,
  3634. (const char *)buf,
  3635. (int64_t)len);
  3636. }
  3637. return (int)total;
  3638. }
  3639. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3640. static int
  3641. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3642. {
  3643. va_list ap_copy;
  3644. size_t size = MG_BUF_LEN / 4;
  3645. int len = -1;
  3646. *buf = NULL;
  3647. while (len < 0) {
  3648. if (*buf) {
  3649. mg_free(*buf);
  3650. }
  3651. size *= 4;
  3652. *buf = (char *)mg_malloc(size);
  3653. if (!*buf) {
  3654. break;
  3655. }
  3656. va_copy(ap_copy, ap);
  3657. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3658. va_end(ap_copy);
  3659. (*buf)[size - 1] = 0;
  3660. }
  3661. return len;
  3662. }
  3663. /* Print message to buffer. If buffer is large enough to hold the message,
  3664. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3665. * and return allocated buffer. */
  3666. static int
  3667. alloc_vprintf(char **out_buf,
  3668. char *prealloc_buf,
  3669. size_t prealloc_size,
  3670. const char *fmt,
  3671. va_list ap)
  3672. {
  3673. va_list ap_copy;
  3674. int len;
  3675. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3676. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3677. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3678. * Therefore, we make two passes: on first pass, get required message
  3679. * length.
  3680. * On second pass, actually print the message. */
  3681. va_copy(ap_copy, ap);
  3682. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3683. va_end(ap_copy);
  3684. if (len < 0) {
  3685. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3686. * Switch to alternative code path that uses incremental allocations.
  3687. */
  3688. va_copy(ap_copy, ap);
  3689. len = alloc_vprintf2(out_buf, fmt, ap);
  3690. va_end(ap_copy);
  3691. } else if ((size_t)(len) >= prealloc_size) {
  3692. /* The pre-allocated buffer not large enough. */
  3693. /* Allocate a new buffer. */
  3694. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3695. if (!*out_buf) {
  3696. /* Allocation failed. Return -1 as "out of memory" error. */
  3697. return -1;
  3698. }
  3699. /* Buffer allocation successful. Store the string there. */
  3700. va_copy(ap_copy, ap);
  3701. IGNORE_UNUSED_RESULT(
  3702. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3703. va_end(ap_copy);
  3704. } else {
  3705. /* The pre-allocated buffer is large enough.
  3706. * Use it to store the string and return the address. */
  3707. va_copy(ap_copy, ap);
  3708. IGNORE_UNUSED_RESULT(
  3709. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3710. va_end(ap_copy);
  3711. *out_buf = prealloc_buf;
  3712. }
  3713. return len;
  3714. }
  3715. static int
  3716. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3717. {
  3718. char mem[MG_BUF_LEN];
  3719. char *buf = NULL;
  3720. int len;
  3721. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3722. len = mg_write(conn, buf, (size_t)len);
  3723. }
  3724. if (buf != mem && buf != NULL) {
  3725. mg_free(buf);
  3726. }
  3727. return len;
  3728. }
  3729. int
  3730. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3731. {
  3732. va_list ap;
  3733. int result;
  3734. va_start(ap, fmt);
  3735. result = mg_vprintf(conn, fmt, ap);
  3736. va_end(ap);
  3737. return result;
  3738. }
  3739. int
  3740. mg_url_decode(const char *src,
  3741. int src_len,
  3742. char *dst,
  3743. int dst_len,
  3744. int is_form_url_encoded)
  3745. {
  3746. int i, j, a, b;
  3747. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3748. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3749. if (i < src_len - 2 && src[i] == '%'
  3750. && isxdigit(*(const unsigned char *)(src + i + 1))
  3751. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3752. a = tolower(*(const unsigned char *)(src + i + 1));
  3753. b = tolower(*(const unsigned char *)(src + i + 2));
  3754. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3755. i += 2;
  3756. } else if (is_form_url_encoded && src[i] == '+') {
  3757. dst[j] = ' ';
  3758. } else {
  3759. dst[j] = src[i];
  3760. }
  3761. }
  3762. dst[j] = '\0'; /* Null-terminate the destination */
  3763. return i >= src_len ? j : -1;
  3764. }
  3765. int
  3766. mg_get_var(const char *data,
  3767. size_t data_len,
  3768. const char *name,
  3769. char *dst,
  3770. size_t dst_len)
  3771. {
  3772. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3773. }
  3774. int
  3775. mg_get_var2(const char *data,
  3776. size_t data_len,
  3777. const char *name,
  3778. char *dst,
  3779. size_t dst_len,
  3780. size_t occurrence)
  3781. {
  3782. const char *p, *e, *s;
  3783. size_t name_len;
  3784. int len;
  3785. if (dst == NULL || dst_len == 0) {
  3786. len = -2;
  3787. } else if (data == NULL || name == NULL || data_len == 0) {
  3788. len = -1;
  3789. dst[0] = '\0';
  3790. } else {
  3791. name_len = strlen(name);
  3792. e = data + data_len;
  3793. len = -1;
  3794. dst[0] = '\0';
  3795. /* data is "var1=val1&var2=val2...". Find variable first */
  3796. for (p = data; p + name_len < e; p++) {
  3797. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3798. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3799. /* Point p to variable value */
  3800. p += name_len + 1;
  3801. /* Point s to the end of the value */
  3802. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3803. if (s == NULL) {
  3804. s = e;
  3805. }
  3806. /* assert(s >= p); */
  3807. if (s < p) {
  3808. return -3;
  3809. }
  3810. /* Decode variable into destination buffer */
  3811. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3812. /* Redirect error code from -1 to -2 (destination buffer too
  3813. * small). */
  3814. if (len == -1) {
  3815. len = -2;
  3816. }
  3817. break;
  3818. }
  3819. }
  3820. }
  3821. return len;
  3822. }
  3823. int
  3824. mg_get_cookie(const char *cookie_header,
  3825. const char *var_name,
  3826. char *dst,
  3827. size_t dst_size)
  3828. {
  3829. const char *s, *p, *end;
  3830. int name_len, len = -1;
  3831. if (dst == NULL || dst_size == 0) {
  3832. len = -2;
  3833. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3834. len = -1;
  3835. dst[0] = '\0';
  3836. } else {
  3837. name_len = (int)strlen(var_name);
  3838. end = s + strlen(s);
  3839. dst[0] = '\0';
  3840. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3841. if (s[name_len] == '=') {
  3842. s += name_len + 1;
  3843. if ((p = strchr(s, ' ')) == NULL) {
  3844. p = end;
  3845. }
  3846. if (p[-1] == ';') {
  3847. p--;
  3848. }
  3849. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3850. s++;
  3851. p--;
  3852. }
  3853. if ((size_t)(p - s) < dst_size) {
  3854. len = (int)(p - s);
  3855. mg_strlcpy(dst, s, (size_t)len + 1);
  3856. } else {
  3857. len = -3;
  3858. }
  3859. break;
  3860. }
  3861. }
  3862. }
  3863. return len;
  3864. }
  3865. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3866. static void
  3867. base64_encode(const unsigned char *src, int src_len, char *dst)
  3868. {
  3869. static const char *b64 =
  3870. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3871. int i, j, a, b, c;
  3872. for (i = j = 0; i < src_len; i += 3) {
  3873. a = src[i];
  3874. b = i + 1 >= src_len ? 0 : src[i + 1];
  3875. c = i + 2 >= src_len ? 0 : src[i + 2];
  3876. dst[j++] = b64[a >> 2];
  3877. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3878. if (i + 1 < src_len) {
  3879. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3880. }
  3881. if (i + 2 < src_len) {
  3882. dst[j++] = b64[c & 63];
  3883. }
  3884. }
  3885. while (j % 4 != 0) {
  3886. dst[j++] = '=';
  3887. }
  3888. dst[j++] = '\0';
  3889. }
  3890. #endif
  3891. #if defined(USE_LUA)
  3892. static unsigned char
  3893. b64reverse(char letter)
  3894. {
  3895. if (letter >= 'A' && letter <= 'Z') {
  3896. return letter - 'A';
  3897. }
  3898. if (letter >= 'a' && letter <= 'z') {
  3899. return letter - 'a' + 26;
  3900. }
  3901. if (letter >= '0' && letter <= '9') {
  3902. return letter - '0' + 52;
  3903. }
  3904. if (letter == '+') {
  3905. return 62;
  3906. }
  3907. if (letter == '/') {
  3908. return 63;
  3909. }
  3910. if (letter == '=') {
  3911. return 255; /* normal end */
  3912. }
  3913. return 254; /* error */
  3914. }
  3915. static int
  3916. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3917. {
  3918. int i;
  3919. unsigned char a, b, c, d;
  3920. *dst_len = 0;
  3921. for (i = 0; i < src_len; i += 4) {
  3922. a = b64reverse(src[i]);
  3923. if (a >= 254) {
  3924. return i;
  3925. }
  3926. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3927. if (b >= 254) {
  3928. return i + 1;
  3929. }
  3930. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3931. if (c == 254) {
  3932. return i + 2;
  3933. }
  3934. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3935. if (d == 254) {
  3936. return i + 3;
  3937. }
  3938. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3939. if (c != 255) {
  3940. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3941. if (d != 255) {
  3942. dst[(*dst_len)++] = (c << 6) + d;
  3943. }
  3944. }
  3945. }
  3946. return -1;
  3947. }
  3948. #endif
  3949. static int
  3950. is_put_or_delete_method(const struct mg_connection *conn)
  3951. {
  3952. if (conn) {
  3953. const char *s = conn->request_info.request_method;
  3954. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3955. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3956. }
  3957. return 0;
  3958. }
  3959. static void
  3960. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  3961. char *filename, /* out: filename */
  3962. size_t filename_buf_len, /* in: size of filename buffer */
  3963. struct file *filep, /* out: file structure */
  3964. int *is_found, /* out: file is found (directly) */
  3965. int *is_script_resource, /* out: handled by a script? */
  3966. int *is_websocket_request, /* out: websocket connetion? */
  3967. int *is_put_or_delete_request /* out: put/delete a file? */
  3968. )
  3969. {
  3970. /* TODO (high): Restructure this function */
  3971. #if !defined(NO_FILES)
  3972. const char *uri = conn->request_info.local_uri;
  3973. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3974. const char *rewrite;
  3975. struct vec a, b;
  3976. int match_len;
  3977. char gz_path[PATH_MAX];
  3978. char const *accept_encoding;
  3979. int truncated;
  3980. #if !defined(NO_CGI) || defined(USE_LUA)
  3981. char *p;
  3982. #endif
  3983. #else
  3984. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3985. #endif
  3986. memset(filep, 0, sizeof(*filep));
  3987. *filename = 0;
  3988. *is_found = 0;
  3989. *is_script_resource = 0;
  3990. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3991. #if defined(USE_WEBSOCKET)
  3992. *is_websocket_request = is_websocket_protocol(conn);
  3993. #if !defined(NO_FILES)
  3994. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3995. root = conn->ctx->config[WEBSOCKET_ROOT];
  3996. }
  3997. #endif /* !NO_FILES */
  3998. #else /* USE_WEBSOCKET */
  3999. *is_websocket_request = 0;
  4000. #endif /* USE_WEBSOCKET */
  4001. #if !defined(NO_FILES)
  4002. /* Note that root == NULL is a regular use case here. This occurs,
  4003. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4004. * config is not required. */
  4005. if (root == NULL) {
  4006. /* all file related outputs have already been set to 0, just return
  4007. */
  4008. return;
  4009. }
  4010. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4011. * of the path one byte on the right.
  4012. * If document_root is NULL, leave the file empty. */
  4013. mg_snprintf(
  4014. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4015. if (truncated) {
  4016. goto interpret_cleanup;
  4017. }
  4018. rewrite = conn->ctx->config[REWRITE];
  4019. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4020. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4021. mg_snprintf(conn,
  4022. &truncated,
  4023. filename,
  4024. filename_buf_len - 1,
  4025. "%.*s%s",
  4026. (int)b.len,
  4027. b.ptr,
  4028. uri + match_len);
  4029. break;
  4030. }
  4031. }
  4032. if (truncated) {
  4033. goto interpret_cleanup;
  4034. }
  4035. /* Local file path and name, corresponding to requested URI
  4036. * is now stored in "filename" variable. */
  4037. if (mg_stat(conn, filename, filep)) {
  4038. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4039. /* File exists. Check if it is a script type. */
  4040. if (0
  4041. #if !defined(NO_CGI)
  4042. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4043. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4044. filename) > 0
  4045. #endif
  4046. #if defined(USE_LUA)
  4047. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4048. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4049. filename) > 0
  4050. #endif
  4051. #if defined(USE_DUKTAPE)
  4052. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4053. strlen(
  4054. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4055. filename) > 0
  4056. #endif
  4057. ) {
  4058. /* The request addresses a CGI script or a Lua script. The URI
  4059. * corresponds to the script itself (like /path/script.cgi),
  4060. * and there is no additional resource path
  4061. * (like /path/script.cgi/something).
  4062. * Requests that modify (replace or delete) a resource, like
  4063. * PUT and DELETE requests, should replace/delete the script
  4064. * file.
  4065. * Requests that read or write from/to a resource, like GET and
  4066. * POST requests, should call the script and return the
  4067. * generated response. */
  4068. *is_script_resource = !*is_put_or_delete_request;
  4069. }
  4070. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4071. *is_found = 1;
  4072. return;
  4073. }
  4074. /* If we can't find the actual file, look for the file
  4075. * with the same name but a .gz extension. If we find it,
  4076. * use that and set the gzipped flag in the file struct
  4077. * to indicate that the response need to have the content-
  4078. * encoding: gzip header.
  4079. * We can only do this if the browser declares support. */
  4080. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4081. if (strstr(accept_encoding, "gzip") != NULL) {
  4082. mg_snprintf(
  4083. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4084. if (truncated) {
  4085. goto interpret_cleanup;
  4086. }
  4087. if (mg_stat(conn, gz_path, filep)) {
  4088. if (filep) {
  4089. filep->gzipped = 1;
  4090. *is_found = 1;
  4091. }
  4092. /* Currently gz files can not be scripts. */
  4093. return;
  4094. }
  4095. }
  4096. }
  4097. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4098. /* Support PATH_INFO for CGI scripts. */
  4099. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4100. if (*p == '/') {
  4101. *p = '\0';
  4102. if ((0
  4103. #if !defined(NO_CGI)
  4104. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4105. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4106. filename) > 0
  4107. #endif
  4108. #if defined(USE_LUA)
  4109. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4110. strlen(
  4111. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4112. filename) > 0
  4113. #endif
  4114. #if defined(USE_DUKTAPE)
  4115. || match_prefix(
  4116. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4117. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4118. filename) > 0
  4119. #endif
  4120. ) && mg_stat(conn, filename, filep)) {
  4121. /* Shift PATH_INFO block one character right, e.g.
  4122. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4123. * conn->path_info is pointing to the local variable "path"
  4124. * declared in handle_request(), so PATH_INFO is not valid
  4125. * after handle_request returns. */
  4126. conn->path_info = p + 1;
  4127. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4128. * trailing \0 */
  4129. p[1] = '/';
  4130. *is_script_resource = 1;
  4131. break;
  4132. } else {
  4133. *p = '/';
  4134. }
  4135. }
  4136. }
  4137. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4138. #endif /* !defined(NO_FILES) */
  4139. return;
  4140. #if !defined(NO_FILES)
  4141. /* Reset all outputs */
  4142. interpret_cleanup:
  4143. memset(filep, 0, sizeof(*filep));
  4144. *filename = 0;
  4145. *is_found = 0;
  4146. *is_script_resource = 0;
  4147. *is_websocket_request = 0;
  4148. *is_put_or_delete_request = 0;
  4149. #endif /* !defined(NO_FILES) */
  4150. }
  4151. /* Check whether full request is buffered. Return:
  4152. * -1 if request is malformed
  4153. * 0 if request is not yet fully buffered
  4154. * >0 actual request length, including last \r\n\r\n */
  4155. static int
  4156. get_request_len(const char *buf, int buflen)
  4157. {
  4158. const char *s, *e;
  4159. int len = 0;
  4160. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4161. /* Control characters are not allowed but >=128 is. */
  4162. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4163. && *(const unsigned char *)s < 128) {
  4164. len = -1;
  4165. break; /* [i_a] abort scan as soon as one malformed character is
  4166. * found; */
  4167. /* don't let subsequent \r\n\r\n win us over anyhow */
  4168. } else if (s[0] == '\n' && s[1] == '\n') {
  4169. len = (int)(s - buf) + 2;
  4170. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4171. len = (int)(s - buf) + 3;
  4172. }
  4173. return len;
  4174. }
  4175. #if !defined(NO_CACHING)
  4176. /* Convert month to the month number. Return -1 on error, or month number */
  4177. static int
  4178. get_month_index(const char *s)
  4179. {
  4180. size_t i;
  4181. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4182. if (!strcmp(s, month_names[i])) {
  4183. return (int)i;
  4184. }
  4185. }
  4186. return -1;
  4187. }
  4188. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4189. static time_t
  4190. parse_date_string(const char *datetime)
  4191. {
  4192. char month_str[32] = {0};
  4193. int second, minute, hour, day, month, year;
  4194. time_t result = (time_t)0;
  4195. struct tm tm;
  4196. if ((sscanf(datetime,
  4197. "%d/%3s/%d %d:%d:%d",
  4198. &day,
  4199. month_str,
  4200. &year,
  4201. &hour,
  4202. &minute,
  4203. &second) == 6) || (sscanf(datetime,
  4204. "%d %3s %d %d:%d:%d",
  4205. &day,
  4206. month_str,
  4207. &year,
  4208. &hour,
  4209. &minute,
  4210. &second) == 6)
  4211. || (sscanf(datetime,
  4212. "%*3s, %d %3s %d %d:%d:%d",
  4213. &day,
  4214. month_str,
  4215. &year,
  4216. &hour,
  4217. &minute,
  4218. &second) == 6) || (sscanf(datetime,
  4219. "%d-%3s-%d %d:%d:%d",
  4220. &day,
  4221. month_str,
  4222. &year,
  4223. &hour,
  4224. &minute,
  4225. &second) == 6)) {
  4226. month = get_month_index(month_str);
  4227. if ((month >= 0) && (year >= 1970)) {
  4228. memset(&tm, 0, sizeof(tm));
  4229. tm.tm_year = year - 1900;
  4230. tm.tm_mon = month;
  4231. tm.tm_mday = day;
  4232. tm.tm_hour = hour;
  4233. tm.tm_min = minute;
  4234. tm.tm_sec = second;
  4235. result = timegm(&tm);
  4236. }
  4237. }
  4238. return result;
  4239. }
  4240. #endif /* !NO_CACHING */
  4241. /* Protect against directory disclosure attack by removing '..',
  4242. * excessive '/' and '\' characters */
  4243. static void
  4244. remove_double_dots_and_double_slashes(char *s)
  4245. {
  4246. char *p = s;
  4247. while (*s != '\0') {
  4248. *p++ = *s++;
  4249. if (s[-1] == '/' || s[-1] == '\\') {
  4250. /* Skip all following slashes, backslashes and double-dots */
  4251. while (s[0] != '\0') {
  4252. if (s[0] == '/' || s[0] == '\\') {
  4253. s++;
  4254. } else if (s[0] == '.' && s[1] == '.') {
  4255. s += 2;
  4256. } else {
  4257. break;
  4258. }
  4259. }
  4260. }
  4261. }
  4262. *p = '\0';
  4263. }
  4264. static const struct {
  4265. const char *extension;
  4266. size_t ext_len;
  4267. const char *mime_type;
  4268. } builtin_mime_types[] = {
  4269. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4270. * application types */
  4271. {".doc", 4, "application/msword"},
  4272. {".eps", 4, "application/postscript"},
  4273. {".exe", 4, "application/octet-stream"},
  4274. {".js", 3, "application/javascript"},
  4275. {".json", 5, "application/json"},
  4276. {".pdf", 4, "application/pdf"},
  4277. {".ps", 3, "application/postscript"},
  4278. {".rtf", 4, "application/rtf"},
  4279. {".xhtml", 6, "application/xhtml+xml"},
  4280. {".xsl", 4, "application/xml"},
  4281. {".xslt", 5, "application/xml"},
  4282. /* fonts */
  4283. {".ttf", 4, "application/font-sfnt"},
  4284. {".cff", 4, "application/font-sfnt"},
  4285. {".otf", 4, "application/font-sfnt"},
  4286. {".aat", 4, "application/font-sfnt"},
  4287. {".sil", 4, "application/font-sfnt"},
  4288. {".pfr", 4, "application/font-tdpfr"},
  4289. {".woff", 5, "application/font-woff"},
  4290. /* audio */
  4291. {".mp3", 4, "audio/mpeg"},
  4292. {".oga", 4, "audio/ogg"},
  4293. {".ogg", 4, "audio/ogg"},
  4294. /* image */
  4295. {".gif", 4, "image/gif"},
  4296. {".ief", 4, "image/ief"},
  4297. {".jpeg", 5, "image/jpeg"},
  4298. {".jpg", 4, "image/jpeg"},
  4299. {".jpm", 4, "image/jpm"},
  4300. {".jpx", 4, "image/jpx"},
  4301. {".png", 4, "image/png"},
  4302. {".svg", 4, "image/svg+xml"},
  4303. {".tif", 4, "image/tiff"},
  4304. {".tiff", 5, "image/tiff"},
  4305. /* model */
  4306. {".wrl", 4, "model/vrml"},
  4307. /* text */
  4308. {".css", 4, "text/css"},
  4309. {".csv", 4, "text/csv"},
  4310. {".htm", 4, "text/html"},
  4311. {".html", 5, "text/html"},
  4312. {".sgm", 4, "text/sgml"},
  4313. {".shtm", 5, "text/html"},
  4314. {".shtml", 6, "text/html"},
  4315. {".txt", 4, "text/plain"},
  4316. {".xml", 4, "text/xml"},
  4317. /* video */
  4318. {".mov", 4, "video/quicktime"},
  4319. {".mp4", 4, "video/mp4"},
  4320. {".mpeg", 5, "video/mpeg"},
  4321. {".mpg", 4, "video/mpeg"},
  4322. {".ogv", 4, "video/ogg"},
  4323. {".qt", 3, "video/quicktime"},
  4324. /* not registered types
  4325. * (http://reference.sitepoint.com/html/mime-types-full,
  4326. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4327. {".arj", 4, "application/x-arj-compressed"},
  4328. {".gz", 3, "application/x-gunzip"},
  4329. {".rar", 4, "application/x-arj-compressed"},
  4330. {".swf", 4, "application/x-shockwave-flash"},
  4331. {".tar", 4, "application/x-tar"},
  4332. {".tgz", 4, "application/x-tar-gz"},
  4333. {".torrent", 8, "application/x-bittorrent"},
  4334. {".ppt", 4, "application/x-mspowerpoint"},
  4335. {".xls", 4, "application/x-msexcel"},
  4336. {".zip", 4, "application/x-zip-compressed"},
  4337. {".aac",
  4338. 4,
  4339. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4340. {".aif", 4, "audio/x-aif"},
  4341. {".m3u", 4, "audio/x-mpegurl"},
  4342. {".mid", 4, "audio/x-midi"},
  4343. {".ra", 3, "audio/x-pn-realaudio"},
  4344. {".ram", 4, "audio/x-pn-realaudio"},
  4345. {".wav", 4, "audio/x-wav"},
  4346. {".bmp", 4, "image/bmp"},
  4347. {".ico", 4, "image/x-icon"},
  4348. {".pct", 4, "image/x-pct"},
  4349. {".pict", 5, "image/pict"},
  4350. {".rgb", 4, "image/x-rgb"},
  4351. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4352. {".asf", 4, "video/x-ms-asf"},
  4353. {".avi", 4, "video/x-msvideo"},
  4354. {".m4v", 4, "video/x-m4v"},
  4355. {NULL, 0, NULL}};
  4356. const char *
  4357. mg_get_builtin_mime_type(const char *path)
  4358. {
  4359. const char *ext;
  4360. size_t i, path_len;
  4361. path_len = strlen(path);
  4362. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4363. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4364. if (path_len > builtin_mime_types[i].ext_len
  4365. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4366. return builtin_mime_types[i].mime_type;
  4367. }
  4368. }
  4369. return "text/plain";
  4370. }
  4371. /* Look at the "path" extension and figure what mime type it has.
  4372. * Store mime type in the vector. */
  4373. static void
  4374. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4375. {
  4376. struct vec ext_vec, mime_vec;
  4377. const char *list, *ext;
  4378. size_t path_len;
  4379. path_len = strlen(path);
  4380. if (ctx == NULL || vec == NULL) {
  4381. return;
  4382. }
  4383. /* Scan user-defined mime types first, in case user wants to
  4384. * override default mime types. */
  4385. list = ctx->config[EXTRA_MIME_TYPES];
  4386. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4387. /* ext now points to the path suffix */
  4388. ext = path + path_len - ext_vec.len;
  4389. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4390. *vec = mime_vec;
  4391. return;
  4392. }
  4393. }
  4394. vec->ptr = mg_get_builtin_mime_type(path);
  4395. vec->len = strlen(vec->ptr);
  4396. }
  4397. /* Stringify binary data. Output buffer must be twice as big as input,
  4398. * because each byte takes 2 bytes in string representation */
  4399. static void
  4400. bin2str(char *to, const unsigned char *p, size_t len)
  4401. {
  4402. static const char *hex = "0123456789abcdef";
  4403. for (; len--; p++) {
  4404. *to++ = hex[p[0] >> 4];
  4405. *to++ = hex[p[0] & 0x0f];
  4406. }
  4407. *to = '\0';
  4408. }
  4409. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4410. char *
  4411. mg_md5(char buf[33], ...)
  4412. {
  4413. md5_byte_t hash[16];
  4414. const char *p;
  4415. va_list ap;
  4416. md5_state_t ctx;
  4417. md5_init(&ctx);
  4418. va_start(ap, buf);
  4419. while ((p = va_arg(ap, const char *)) != NULL) {
  4420. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4421. }
  4422. va_end(ap);
  4423. md5_finish(&ctx, hash);
  4424. bin2str(buf, hash, sizeof(hash));
  4425. return buf;
  4426. }
  4427. /* Check the user's password, return 1 if OK */
  4428. static int
  4429. check_password(const char *method,
  4430. const char *ha1,
  4431. const char *uri,
  4432. const char *nonce,
  4433. const char *nc,
  4434. const char *cnonce,
  4435. const char *qop,
  4436. const char *response)
  4437. {
  4438. char ha2[32 + 1], expected_response[32 + 1];
  4439. /* Some of the parameters may be NULL */
  4440. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4441. || qop == NULL
  4442. || response == NULL) {
  4443. return 0;
  4444. }
  4445. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4446. if (strlen(response) != 32) {
  4447. return 0;
  4448. }
  4449. mg_md5(ha2, method, ":", uri, NULL);
  4450. mg_md5(expected_response,
  4451. ha1,
  4452. ":",
  4453. nonce,
  4454. ":",
  4455. nc,
  4456. ":",
  4457. cnonce,
  4458. ":",
  4459. qop,
  4460. ":",
  4461. ha2,
  4462. NULL);
  4463. return mg_strcasecmp(response, expected_response) == 0;
  4464. }
  4465. /* Use the global passwords file, if specified by auth_gpass option,
  4466. * or search for .htpasswd in the requested directory. */
  4467. static void
  4468. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4469. {
  4470. if (conn != NULL && conn->ctx != NULL) {
  4471. char name[PATH_MAX];
  4472. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4473. struct file file = STRUCT_FILE_INITIALIZER;
  4474. int truncated;
  4475. if (gpass != NULL) {
  4476. /* Use global passwords file */
  4477. if (!mg_fopen(conn, gpass, "r", filep)) {
  4478. #ifdef DEBUG
  4479. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4480. #endif
  4481. }
  4482. /* Important: using local struct file to test path for is_directory
  4483. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4484. * was opened. */
  4485. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4486. mg_snprintf(conn,
  4487. &truncated,
  4488. name,
  4489. sizeof(name),
  4490. "%s/%s",
  4491. path,
  4492. PASSWORDS_FILE_NAME);
  4493. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4494. #ifdef DEBUG
  4495. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4496. #endif
  4497. }
  4498. } else {
  4499. /* Try to find .htpasswd in requested directory. */
  4500. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4501. if (e[0] == '/') {
  4502. break;
  4503. }
  4504. }
  4505. mg_snprintf(conn,
  4506. &truncated,
  4507. name,
  4508. sizeof(name),
  4509. "%.*s/%s",
  4510. (int)(e - p),
  4511. p,
  4512. PASSWORDS_FILE_NAME);
  4513. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4514. #ifdef DEBUG
  4515. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4516. #endif
  4517. }
  4518. }
  4519. }
  4520. }
  4521. /* Parsed Authorization header */
  4522. struct ah {
  4523. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4524. };
  4525. /* Return 1 on success. Always initializes the ah structure. */
  4526. static int
  4527. parse_auth_header(struct mg_connection *conn,
  4528. char *buf,
  4529. size_t buf_size,
  4530. struct ah *ah)
  4531. {
  4532. char *name, *value, *s;
  4533. const char *auth_header;
  4534. uint64_t nonce;
  4535. if (!ah || !conn) {
  4536. return 0;
  4537. }
  4538. (void)memset(ah, 0, sizeof(*ah));
  4539. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4540. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4541. return 0;
  4542. }
  4543. /* Make modifiable copy of the auth header */
  4544. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4545. s = buf;
  4546. /* Parse authorization header */
  4547. for (;;) {
  4548. /* Gobble initial spaces */
  4549. while (isspace(*(unsigned char *)s)) {
  4550. s++;
  4551. }
  4552. name = skip_quoted(&s, "=", " ", 0);
  4553. /* Value is either quote-delimited, or ends at first comma or space. */
  4554. if (s[0] == '\"') {
  4555. s++;
  4556. value = skip_quoted(&s, "\"", " ", '\\');
  4557. if (s[0] == ',') {
  4558. s++;
  4559. }
  4560. } else {
  4561. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4562. * spaces */
  4563. }
  4564. if (*name == '\0') {
  4565. break;
  4566. }
  4567. if (!strcmp(name, "username")) {
  4568. ah->user = value;
  4569. } else if (!strcmp(name, "cnonce")) {
  4570. ah->cnonce = value;
  4571. } else if (!strcmp(name, "response")) {
  4572. ah->response = value;
  4573. } else if (!strcmp(name, "uri")) {
  4574. ah->uri = value;
  4575. } else if (!strcmp(name, "qop")) {
  4576. ah->qop = value;
  4577. } else if (!strcmp(name, "nc")) {
  4578. ah->nc = value;
  4579. } else if (!strcmp(name, "nonce")) {
  4580. ah->nonce = value;
  4581. }
  4582. }
  4583. #ifndef NO_NONCE_CHECK
  4584. /* Read the nonce from the response. */
  4585. if (ah->nonce == NULL) {
  4586. return 0;
  4587. }
  4588. s = NULL;
  4589. nonce = strtoull(ah->nonce, &s, 10);
  4590. if ((s == NULL) || (*s != 0)) {
  4591. return 0;
  4592. }
  4593. /* Convert the nonce from the client to a number. */
  4594. nonce ^= conn->ctx->auth_nonce_mask;
  4595. /* The converted number corresponds to the time the nounce has been
  4596. * created. This should not be earlier than the server start. */
  4597. /* Server side nonce check is valuable in all situations but one:
  4598. * if the server restarts frequently, but the client should not see
  4599. * that, so the server should accept nonces from previous starts. */
  4600. /* However, the reasonable default is to not accept a nonce from a
  4601. * previous start, so if anyone changed the access rights between
  4602. * two restarts, a new login is required. */
  4603. if (nonce < (uint64_t)conn->ctx->start_time) {
  4604. /* nonce is from a previous start of the server and no longer valid
  4605. * (replay attack?) */
  4606. return 0;
  4607. }
  4608. /* Check if the nonce is too high, so it has not (yet) been used by the
  4609. * server. */
  4610. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4611. return 0;
  4612. }
  4613. #endif
  4614. /* CGI needs it as REMOTE_USER */
  4615. if (ah->user != NULL) {
  4616. conn->request_info.remote_user = mg_strdup(ah->user);
  4617. } else {
  4618. return 0;
  4619. }
  4620. return 1;
  4621. }
  4622. static const char *
  4623. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4624. {
  4625. const char *eof;
  4626. size_t len;
  4627. const char *memend;
  4628. if (!filep) {
  4629. return NULL;
  4630. }
  4631. if (filep->membuf != NULL && *p != NULL) {
  4632. memend = (const char *)&filep->membuf[filep->size];
  4633. /* Search for \n from p till the end of stream */
  4634. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4635. if (eof != NULL) {
  4636. eof += 1; /* Include \n */
  4637. } else {
  4638. eof = memend; /* Copy remaining data */
  4639. }
  4640. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4641. memcpy(buf, *p, len);
  4642. buf[len] = '\0';
  4643. *p += len;
  4644. return len ? eof : NULL;
  4645. } else if (filep->fp != NULL) {
  4646. return fgets(buf, (int)size, filep->fp);
  4647. } else {
  4648. return NULL;
  4649. }
  4650. }
  4651. struct read_auth_file_struct {
  4652. struct mg_connection *conn;
  4653. struct ah ah;
  4654. char *domain;
  4655. char buf[256 + 256 + 40];
  4656. char *f_user;
  4657. char *f_domain;
  4658. char *f_ha1;
  4659. };
  4660. static int
  4661. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4662. {
  4663. char *p;
  4664. int is_authorized = 0;
  4665. struct file fp;
  4666. size_t l;
  4667. if (!filep || !workdata) {
  4668. return 0;
  4669. }
  4670. /* Loop over passwords file */
  4671. p = (char *)filep->membuf;
  4672. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4673. l = strlen(workdata->buf);
  4674. while (l > 0) {
  4675. if (isspace(workdata->buf[l - 1])
  4676. || iscntrl(workdata->buf[l - 1])) {
  4677. l--;
  4678. workdata->buf[l] = 0;
  4679. } else
  4680. break;
  4681. }
  4682. if (l < 1) {
  4683. continue;
  4684. }
  4685. workdata->f_user = workdata->buf;
  4686. if (workdata->f_user[0] == ':') {
  4687. /* user names may not contain a ':' and may not be empty,
  4688. * so lines starting with ':' may be used for a special purpose */
  4689. if (workdata->f_user[1] == '#') {
  4690. /* :# is a comment */
  4691. continue;
  4692. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4693. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4694. is_authorized = read_auth_file(&fp, workdata);
  4695. mg_fclose(&fp);
  4696. } else {
  4697. mg_cry(workdata->conn,
  4698. "%s: cannot open authorization file: %s",
  4699. __func__,
  4700. workdata->buf);
  4701. }
  4702. continue;
  4703. }
  4704. /* everything is invalid for the moment (might change in the
  4705. * future) */
  4706. mg_cry(workdata->conn,
  4707. "%s: syntax error in authorization file: %s",
  4708. __func__,
  4709. workdata->buf);
  4710. continue;
  4711. }
  4712. workdata->f_domain = strchr(workdata->f_user, ':');
  4713. if (workdata->f_domain == NULL) {
  4714. mg_cry(workdata->conn,
  4715. "%s: syntax error in authorization file: %s",
  4716. __func__,
  4717. workdata->buf);
  4718. continue;
  4719. }
  4720. *(workdata->f_domain) = 0;
  4721. (workdata->f_domain)++;
  4722. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4723. if (workdata->f_ha1 == NULL) {
  4724. mg_cry(workdata->conn,
  4725. "%s: syntax error in authorization file: %s",
  4726. __func__,
  4727. workdata->buf);
  4728. continue;
  4729. }
  4730. *(workdata->f_ha1) = 0;
  4731. (workdata->f_ha1)++;
  4732. if (!strcmp(workdata->ah.user, workdata->f_user)
  4733. && !strcmp(workdata->domain, workdata->f_domain)) {
  4734. return check_password(workdata->conn->request_info.request_method,
  4735. workdata->f_ha1,
  4736. workdata->ah.uri,
  4737. workdata->ah.nonce,
  4738. workdata->ah.nc,
  4739. workdata->ah.cnonce,
  4740. workdata->ah.qop,
  4741. workdata->ah.response);
  4742. }
  4743. }
  4744. return is_authorized;
  4745. }
  4746. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4747. static int
  4748. authorize(struct mg_connection *conn, struct file *filep)
  4749. {
  4750. struct read_auth_file_struct workdata;
  4751. char buf[MG_BUF_LEN];
  4752. if (!conn || !conn->ctx) {
  4753. return 0;
  4754. }
  4755. memset(&workdata, 0, sizeof(workdata));
  4756. workdata.conn = conn;
  4757. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4758. return 0;
  4759. }
  4760. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4761. return read_auth_file(filep, &workdata);
  4762. }
  4763. /* Return 1 if request is authorised, 0 otherwise. */
  4764. static int
  4765. check_authorization(struct mg_connection *conn, const char *path)
  4766. {
  4767. char fname[PATH_MAX];
  4768. struct vec uri_vec, filename_vec;
  4769. const char *list;
  4770. struct file file = STRUCT_FILE_INITIALIZER;
  4771. int authorized = 1, truncated;
  4772. if (!conn || !conn->ctx) {
  4773. return 0;
  4774. }
  4775. list = conn->ctx->config[PROTECT_URI];
  4776. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4777. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4778. mg_snprintf(conn,
  4779. &truncated,
  4780. fname,
  4781. sizeof(fname),
  4782. "%.*s",
  4783. (int)filename_vec.len,
  4784. filename_vec.ptr);
  4785. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4786. mg_cry(conn,
  4787. "%s: cannot open %s: %s",
  4788. __func__,
  4789. fname,
  4790. strerror(errno));
  4791. }
  4792. break;
  4793. }
  4794. }
  4795. if (!is_file_opened(&file)) {
  4796. open_auth_file(conn, path, &file);
  4797. }
  4798. if (is_file_opened(&file)) {
  4799. authorized = authorize(conn, &file);
  4800. mg_fclose(&file);
  4801. }
  4802. return authorized;
  4803. }
  4804. static void
  4805. send_authorization_request(struct mg_connection *conn)
  4806. {
  4807. char date[64];
  4808. time_t curtime = time(NULL);
  4809. if (conn && conn->ctx) {
  4810. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4811. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4812. nonce += conn->ctx->nonce_count;
  4813. ++conn->ctx->nonce_count;
  4814. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4815. nonce ^= conn->ctx->auth_nonce_mask;
  4816. conn->status_code = 401;
  4817. conn->must_close = 1;
  4818. gmt_time_string(date, sizeof(date), &curtime);
  4819. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  4820. send_no_cache_header(conn);
  4821. mg_printf(conn,
  4822. "Date: %s\r\n"
  4823. "Connection: %s\r\n"
  4824. "Content-Length: 0\r\n"
  4825. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4826. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4827. date,
  4828. suggest_connection_header(conn),
  4829. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4830. nonce);
  4831. }
  4832. }
  4833. #if !defined(NO_FILES)
  4834. static int
  4835. is_authorized_for_put(struct mg_connection *conn)
  4836. {
  4837. if (conn) {
  4838. struct file file = STRUCT_FILE_INITIALIZER;
  4839. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4840. int ret = 0;
  4841. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4842. ret = authorize(conn, &file);
  4843. mg_fclose(&file);
  4844. }
  4845. return ret;
  4846. }
  4847. return 0;
  4848. }
  4849. #endif
  4850. int
  4851. mg_modify_passwords_file(const char *fname,
  4852. const char *domain,
  4853. const char *user,
  4854. const char *pass)
  4855. {
  4856. int found, i;
  4857. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4858. FILE *fp, *fp2;
  4859. found = 0;
  4860. fp = fp2 = NULL;
  4861. /* Regard empty password as no password - remove user record. */
  4862. if (pass != NULL && pass[0] == '\0') {
  4863. pass = NULL;
  4864. }
  4865. /* Other arguments must not be empty */
  4866. if (fname == NULL || domain == NULL || user == NULL) {
  4867. return 0;
  4868. }
  4869. /* Using the given file format, user name and domain must not contain ':'
  4870. */
  4871. if (strchr(user, ':') != NULL) {
  4872. return 0;
  4873. }
  4874. if (strchr(domain, ':') != NULL) {
  4875. return 0;
  4876. }
  4877. /* Do not allow control characters like newline in user name and domain.
  4878. * Do not allow excessively long names either. */
  4879. for (i = 0; i < 255 && user[i] != 0; i++) {
  4880. if (iscntrl(user[i])) {
  4881. return 0;
  4882. }
  4883. }
  4884. if (user[i]) {
  4885. return 0;
  4886. }
  4887. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4888. if (iscntrl(domain[i])) {
  4889. return 0;
  4890. }
  4891. }
  4892. if (domain[i]) {
  4893. return 0;
  4894. }
  4895. /* The maximum length of the path to the password file is limited */
  4896. if ((strlen(fname) + 4) >= PATH_MAX) {
  4897. return 0;
  4898. }
  4899. /* Create a temporary file name. Length has been checked before. */
  4900. strcpy(tmp, fname);
  4901. strcat(tmp, ".tmp");
  4902. /* Create the file if does not exist */
  4903. /* Use of fopen here is OK, since fname is only ASCII */
  4904. if ((fp = fopen(fname, "a+")) != NULL) {
  4905. (void)fclose(fp);
  4906. }
  4907. /* Open the given file and temporary file */
  4908. if ((fp = fopen(fname, "r")) == NULL) {
  4909. return 0;
  4910. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4911. fclose(fp);
  4912. return 0;
  4913. }
  4914. /* Copy the stuff to temporary file */
  4915. while (fgets(line, sizeof(line), fp) != NULL) {
  4916. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4917. continue;
  4918. }
  4919. u[255] = 0;
  4920. d[255] = 0;
  4921. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4922. found++;
  4923. if (pass != NULL) {
  4924. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4925. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4926. }
  4927. } else {
  4928. fprintf(fp2, "%s", line);
  4929. }
  4930. }
  4931. /* If new user, just add it */
  4932. if (!found && pass != NULL) {
  4933. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4934. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4935. }
  4936. /* Close files */
  4937. fclose(fp);
  4938. fclose(fp2);
  4939. /* Put the temp file in place of real file */
  4940. IGNORE_UNUSED_RESULT(remove(fname));
  4941. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4942. return 1;
  4943. }
  4944. static int
  4945. is_valid_port(unsigned long port)
  4946. {
  4947. return port < 0xffff;
  4948. }
  4949. static int
  4950. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4951. {
  4952. struct addrinfo hints, *res, *ressave;
  4953. int func_ret = 0;
  4954. int gai_ret;
  4955. memset(&hints, 0, sizeof(struct addrinfo));
  4956. hints.ai_family = af;
  4957. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  4958. if (gai_ret != 0) {
  4959. /* gai_strerror could be used to convert gai_ret to a string */
  4960. /* POSIX return values: see
  4961. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  4962. */
  4963. /* Windows return values: see
  4964. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  4965. */
  4966. return 0;
  4967. }
  4968. ressave = res;
  4969. while (res) {
  4970. if (dstlen >= res->ai_addrlen) {
  4971. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4972. func_ret = 1;
  4973. }
  4974. res = res->ai_next;
  4975. }
  4976. freeaddrinfo(ressave);
  4977. return func_ret;
  4978. }
  4979. static int
  4980. connect_socket(struct mg_context *ctx /* may be NULL */,
  4981. const char *host,
  4982. int port,
  4983. int use_ssl,
  4984. char *ebuf,
  4985. size_t ebuf_len,
  4986. SOCKET *sock /* output: socket, must not be NULL */,
  4987. union usa *sa /* output: socket address, must not be NULL */
  4988. )
  4989. {
  4990. int ip_ver = 0;
  4991. *sock = INVALID_SOCKET;
  4992. memset(sa, 0, sizeof(*sa));
  4993. if (ebuf_len > 0) {
  4994. *ebuf = 0;
  4995. }
  4996. if (host == NULL) {
  4997. mg_snprintf(NULL,
  4998. NULL, /* No truncation check for ebuf */
  4999. ebuf,
  5000. ebuf_len,
  5001. "%s",
  5002. "NULL host");
  5003. return 0;
  5004. }
  5005. if (port < 0 || !is_valid_port((unsigned)port)) {
  5006. mg_snprintf(NULL,
  5007. NULL, /* No truncation check for ebuf */
  5008. ebuf,
  5009. ebuf_len,
  5010. "%s",
  5011. "invalid port");
  5012. return 0;
  5013. }
  5014. #if !defined(NO_SSL_DL)
  5015. if (use_ssl && (SSLv23_client_method == NULL)) {
  5016. mg_snprintf(NULL,
  5017. NULL, /* No truncation check for ebuf */
  5018. ebuf,
  5019. ebuf_len,
  5020. "%s",
  5021. "SSL is not initialized");
  5022. return 0;
  5023. }
  5024. #else
  5025. (void)use_ssl;
  5026. #endif
  5027. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5028. sa->sin.sin_port = htons((uint16_t)port);
  5029. ip_ver = 4;
  5030. #ifdef USE_IPV6
  5031. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5032. sa->sin6.sin6_port = htons((uint16_t)port);
  5033. ip_ver = 6;
  5034. } else if (host[0] == '[') {
  5035. /* While getaddrinfo on Windows will work with [::1],
  5036. * getaddrinfo on Linux only works with ::1 (without []). */
  5037. size_t l = strlen(host + 1);
  5038. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  5039. if (h) {
  5040. h[l - 1] = 0;
  5041. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5042. sa->sin6.sin6_port = htons((uint16_t)port);
  5043. ip_ver = 6;
  5044. }
  5045. mg_free(h);
  5046. }
  5047. #endif
  5048. }
  5049. if (ip_ver == 0) {
  5050. mg_snprintf(NULL,
  5051. NULL, /* No truncation check for ebuf */
  5052. ebuf,
  5053. ebuf_len,
  5054. "%s",
  5055. "host not found");
  5056. return 0;
  5057. }
  5058. if (ip_ver == 4) {
  5059. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5060. }
  5061. #ifdef USE_IPV6
  5062. else if (ip_ver == 6) {
  5063. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5064. }
  5065. #endif
  5066. if (*sock == INVALID_SOCKET) {
  5067. mg_snprintf(NULL,
  5068. NULL, /* No truncation check for ebuf */
  5069. ebuf,
  5070. ebuf_len,
  5071. "socket(): %s",
  5072. strerror(ERRNO));
  5073. return 0;
  5074. }
  5075. set_close_on_exec(*sock, fc(ctx));
  5076. if ((ip_ver == 4)
  5077. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5078. == 0)) {
  5079. /* connected with IPv4 */
  5080. return 1;
  5081. }
  5082. #ifdef USE_IPV6
  5083. if ((ip_ver == 6)
  5084. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5085. == 0)) {
  5086. /* connected with IPv6 */
  5087. return 1;
  5088. }
  5089. #endif
  5090. /* Not connected */
  5091. mg_snprintf(NULL,
  5092. NULL, /* No truncation check for ebuf */
  5093. ebuf,
  5094. ebuf_len,
  5095. "connect(%s:%d): %s",
  5096. host,
  5097. port,
  5098. strerror(ERRNO));
  5099. closesocket(*sock);
  5100. *sock = INVALID_SOCKET;
  5101. return 0;
  5102. }
  5103. int
  5104. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5105. {
  5106. static const char *dont_escape = "._-$,;~()";
  5107. static const char *hex = "0123456789abcdef";
  5108. char *pos = dst;
  5109. const char *end = dst + dst_len - 1;
  5110. for (; *src != '\0' && pos < end; src++, pos++) {
  5111. if (isalnum(*(const unsigned char *)src)
  5112. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5113. *pos = *src;
  5114. } else if (pos + 2 < end) {
  5115. pos[0] = '%';
  5116. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5117. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5118. pos += 2;
  5119. } else {
  5120. break;
  5121. }
  5122. }
  5123. *pos = '\0';
  5124. return (*src == '\0') ? (int)(pos - dst) : -1;
  5125. }
  5126. static void
  5127. print_dir_entry(struct de *de)
  5128. {
  5129. char size[64], mod[64], href[PATH_MAX];
  5130. struct tm *tm;
  5131. if (de->file.is_directory) {
  5132. mg_snprintf(de->conn,
  5133. NULL, /* Buffer is big enough */
  5134. size,
  5135. sizeof(size),
  5136. "%s",
  5137. "[DIRECTORY]");
  5138. } else {
  5139. /* We use (signed) cast below because MSVC 6 compiler cannot
  5140. * convert unsigned __int64 to double. Sigh. */
  5141. if (de->file.size < 1024) {
  5142. mg_snprintf(de->conn,
  5143. NULL, /* Buffer is big enough */
  5144. size,
  5145. sizeof(size),
  5146. "%d",
  5147. (int)de->file.size);
  5148. } else if (de->file.size < 0x100000) {
  5149. mg_snprintf(de->conn,
  5150. NULL, /* Buffer is big enough */
  5151. size,
  5152. sizeof(size),
  5153. "%.1fk",
  5154. (double)de->file.size / 1024.0);
  5155. } else if (de->file.size < 0x40000000) {
  5156. mg_snprintf(de->conn,
  5157. NULL, /* Buffer is big enough */
  5158. size,
  5159. sizeof(size),
  5160. "%.1fM",
  5161. (double)de->file.size / 1048576);
  5162. } else {
  5163. mg_snprintf(de->conn,
  5164. NULL, /* Buffer is big enough */
  5165. size,
  5166. sizeof(size),
  5167. "%.1fG",
  5168. (double)de->file.size / 1073741824);
  5169. }
  5170. }
  5171. /* Note: mg_snprintf will not cause a buffer overflow above.
  5172. * So, string truncation checks are not required here. */
  5173. tm = localtime(&de->file.last_modified);
  5174. if (tm != NULL) {
  5175. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5176. } else {
  5177. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5178. mod[sizeof(mod) - 1] = '\0';
  5179. }
  5180. mg_url_encode(de->file_name, href, sizeof(href));
  5181. de->conn->num_bytes_sent +=
  5182. mg_printf(de->conn,
  5183. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5184. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5185. de->conn->request_info.local_uri,
  5186. href,
  5187. de->file.is_directory ? "/" : "",
  5188. de->file_name,
  5189. de->file.is_directory ? "/" : "",
  5190. mod,
  5191. size);
  5192. }
  5193. /* This function is called from send_directory() and used for
  5194. * sorting directory entries by size, or name, or modification time.
  5195. * On windows, __cdecl specification is needed in case if project is built
  5196. * with __stdcall convention. qsort always requires __cdels callback. */
  5197. static int WINCDECL
  5198. compare_dir_entries(const void *p1, const void *p2)
  5199. {
  5200. if (p1 && p2) {
  5201. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5202. const char *query_string = a->conn->request_info.query_string;
  5203. int cmp_result = 0;
  5204. if (query_string == NULL) {
  5205. query_string = "na";
  5206. }
  5207. if (a->file.is_directory && !b->file.is_directory) {
  5208. return -1; /* Always put directories on top */
  5209. } else if (!a->file.is_directory && b->file.is_directory) {
  5210. return 1; /* Always put directories on top */
  5211. } else if (*query_string == 'n') {
  5212. cmp_result = strcmp(a->file_name, b->file_name);
  5213. } else if (*query_string == 's') {
  5214. cmp_result = a->file.size == b->file.size
  5215. ? 0
  5216. : a->file.size > b->file.size ? 1 : -1;
  5217. } else if (*query_string == 'd') {
  5218. cmp_result =
  5219. (a->file.last_modified == b->file.last_modified)
  5220. ? 0
  5221. : ((a->file.last_modified > b->file.last_modified) ? 1
  5222. : -1);
  5223. }
  5224. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  5225. }
  5226. return 0;
  5227. }
  5228. static int
  5229. must_hide_file(struct mg_connection *conn, const char *path)
  5230. {
  5231. if (conn && conn->ctx) {
  5232. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5233. const char *pattern = conn->ctx->config[HIDE_FILES];
  5234. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5235. || (pattern != NULL
  5236. && match_prefix(pattern, strlen(pattern), path) > 0);
  5237. }
  5238. return 0;
  5239. }
  5240. static int
  5241. scan_directory(struct mg_connection *conn,
  5242. const char *dir,
  5243. void *data,
  5244. void (*cb)(struct de *, void *))
  5245. {
  5246. char path[PATH_MAX];
  5247. struct dirent *dp;
  5248. DIR *dirp;
  5249. struct de de;
  5250. int truncated;
  5251. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5252. return 0;
  5253. } else {
  5254. de.conn = conn;
  5255. while ((dp = mg_readdir(dirp)) != NULL) {
  5256. /* Do not show current dir and hidden files */
  5257. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5258. || must_hide_file(conn, dp->d_name)) {
  5259. continue;
  5260. }
  5261. mg_snprintf(
  5262. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5263. /* If we don't memset stat structure to zero, mtime will have
  5264. * garbage and strftime() will segfault later on in
  5265. * print_dir_entry(). memset is required only if mg_stat()
  5266. * fails. For more details, see
  5267. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5268. memset(&de.file, 0, sizeof(de.file));
  5269. if (truncated) {
  5270. /* If the path is not complete, skip processing. */
  5271. continue;
  5272. }
  5273. if (!mg_stat(conn, path, &de.file)) {
  5274. mg_cry(conn,
  5275. "%s: mg_stat(%s) failed: %s",
  5276. __func__,
  5277. path,
  5278. strerror(ERRNO));
  5279. }
  5280. de.file_name = dp->d_name;
  5281. cb(&de, data);
  5282. }
  5283. (void)mg_closedir(dirp);
  5284. }
  5285. return 1;
  5286. }
  5287. #if !defined(NO_FILES)
  5288. static int
  5289. remove_directory(struct mg_connection *conn, const char *dir)
  5290. {
  5291. char path[PATH_MAX];
  5292. struct dirent *dp;
  5293. DIR *dirp;
  5294. struct de de;
  5295. int truncated;
  5296. int ok = 1;
  5297. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5298. return 0;
  5299. } else {
  5300. de.conn = conn;
  5301. while ((dp = mg_readdir(dirp)) != NULL) {
  5302. /* Do not show current dir (but show hidden files as they will
  5303. * also be removed) */
  5304. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5305. continue;
  5306. }
  5307. mg_snprintf(
  5308. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5309. /* If we don't memset stat structure to zero, mtime will have
  5310. * garbage and strftime() will segfault later on in
  5311. * print_dir_entry(). memset is required only if mg_stat()
  5312. * fails. For more details, see
  5313. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5314. memset(&de.file, 0, sizeof(de.file));
  5315. if (truncated) {
  5316. /* Do not delete anything shorter */
  5317. ok = 0;
  5318. continue;
  5319. }
  5320. if (!mg_stat(conn, path, &de.file)) {
  5321. mg_cry(conn,
  5322. "%s: mg_stat(%s) failed: %s",
  5323. __func__,
  5324. path,
  5325. strerror(ERRNO));
  5326. ok = 0;
  5327. }
  5328. if (de.file.membuf == NULL) {
  5329. /* file is not in memory */
  5330. if (de.file.is_directory) {
  5331. if (remove_directory(conn, path) == 0) {
  5332. ok = 0;
  5333. }
  5334. } else {
  5335. if (mg_remove(conn, path) == 0) {
  5336. ok = 0;
  5337. }
  5338. }
  5339. } else {
  5340. /* file is in memory. It can not be deleted. */
  5341. ok = 0;
  5342. }
  5343. }
  5344. (void)mg_closedir(dirp);
  5345. IGNORE_UNUSED_RESULT(rmdir(dir));
  5346. }
  5347. return ok;
  5348. }
  5349. #endif
  5350. struct dir_scan_data {
  5351. struct de *entries;
  5352. unsigned int num_entries;
  5353. unsigned int arr_size;
  5354. };
  5355. /* Behaves like realloc(), but frees original pointer on failure */
  5356. static void *
  5357. realloc2(void *ptr, size_t size)
  5358. {
  5359. void *new_ptr = mg_realloc(ptr, size);
  5360. if (new_ptr == NULL) {
  5361. mg_free(ptr);
  5362. }
  5363. return new_ptr;
  5364. }
  5365. static void
  5366. dir_scan_callback(struct de *de, void *data)
  5367. {
  5368. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5369. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5370. dsd->arr_size *= 2;
  5371. dsd->entries =
  5372. (struct de *)realloc2(dsd->entries,
  5373. dsd->arr_size * sizeof(dsd->entries[0]));
  5374. }
  5375. if (dsd->entries == NULL) {
  5376. /* TODO(lsm, low): propagate an error to the caller */
  5377. dsd->num_entries = 0;
  5378. } else {
  5379. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5380. dsd->entries[dsd->num_entries].file = de->file;
  5381. dsd->entries[dsd->num_entries].conn = de->conn;
  5382. dsd->num_entries++;
  5383. }
  5384. }
  5385. static void
  5386. handle_directory_request(struct mg_connection *conn, const char *dir)
  5387. {
  5388. unsigned int i;
  5389. int sort_direction;
  5390. struct dir_scan_data data = {NULL, 0, 128};
  5391. char date[64];
  5392. time_t curtime = time(NULL);
  5393. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5394. send_http_error(conn,
  5395. 500,
  5396. "Error: Cannot open directory\nopendir(%s): %s",
  5397. dir,
  5398. strerror(ERRNO));
  5399. return;
  5400. }
  5401. gmt_time_string(date, sizeof(date), &curtime);
  5402. if (!conn) {
  5403. return;
  5404. }
  5405. sort_direction = conn->request_info.query_string != NULL
  5406. && conn->request_info.query_string[1] == 'd'
  5407. ? 'a'
  5408. : 'd';
  5409. conn->must_close = 1;
  5410. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5411. send_static_cache_header(conn);
  5412. mg_printf(conn,
  5413. "Date: %s\r\n"
  5414. "Connection: close\r\n"
  5415. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5416. date);
  5417. conn->num_bytes_sent +=
  5418. mg_printf(conn,
  5419. "<html><head><title>Index of %s</title>"
  5420. "<style>th {text-align: left;}</style></head>"
  5421. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5422. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5423. "<th><a href=\"?d%c\">Modified</a></th>"
  5424. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5425. "<tr><td colspan=\"3\"><hr></td></tr>",
  5426. conn->request_info.local_uri,
  5427. conn->request_info.local_uri,
  5428. sort_direction,
  5429. sort_direction,
  5430. sort_direction);
  5431. /* Print first entry - link to a parent directory */
  5432. conn->num_bytes_sent +=
  5433. mg_printf(conn,
  5434. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5435. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5436. conn->request_info.local_uri,
  5437. "..",
  5438. "Parent directory",
  5439. "-",
  5440. "-");
  5441. /* Sort and print directory entries */
  5442. if (data.entries != NULL) {
  5443. qsort(data.entries,
  5444. (size_t)data.num_entries,
  5445. sizeof(data.entries[0]),
  5446. compare_dir_entries);
  5447. for (i = 0; i < data.num_entries; i++) {
  5448. print_dir_entry(&data.entries[i]);
  5449. mg_free(data.entries[i].file_name);
  5450. }
  5451. mg_free(data.entries);
  5452. }
  5453. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5454. conn->status_code = 200;
  5455. }
  5456. /* Send len bytes from the opened file to the client. */
  5457. static void
  5458. send_file_data(struct mg_connection *conn,
  5459. struct file *filep,
  5460. int64_t offset,
  5461. int64_t len)
  5462. {
  5463. char buf[MG_BUF_LEN];
  5464. int to_read, num_read, num_written;
  5465. int64_t size;
  5466. if (!filep || !conn) {
  5467. return;
  5468. }
  5469. /* Sanity check the offset */
  5470. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5471. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5472. if (len > 0 && filep->membuf != NULL && size > 0) {
  5473. /* file stored in memory */
  5474. if (len > size - offset) {
  5475. len = size - offset;
  5476. }
  5477. mg_write(conn, filep->membuf + offset, (size_t)len);
  5478. } else if (len > 0 && filep->fp != NULL) {
  5479. /* file stored on disk */
  5480. #if defined(__linux__)
  5481. /* sendfile is only available for Linux */
  5482. if (conn->throttle == 0 && conn->ssl == 0) {
  5483. off_t sf_offs = (off_t)offset;
  5484. ssize_t sf_sent;
  5485. int sf_file = fileno(filep->fp);
  5486. int loop_cnt = 0;
  5487. do {
  5488. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5489. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5490. size_t sf_tosend =
  5491. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5492. sf_sent =
  5493. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5494. if (sf_sent > 0) {
  5495. conn->num_bytes_sent += sf_sent;
  5496. len -= sf_sent;
  5497. offset += sf_sent;
  5498. } else if (loop_cnt == 0) {
  5499. /* This file can not be sent using sendfile.
  5500. * This might be the case for pseudo-files in the
  5501. * /sys/ and /proc/ file system.
  5502. * Use the regular user mode copy code instead. */
  5503. break;
  5504. } else if (sf_sent == 0) {
  5505. /* No error, but 0 bytes sent. May be EOF? */
  5506. return;
  5507. }
  5508. loop_cnt++;
  5509. } while ((len > 0) && (sf_sent >= 0));
  5510. if (sf_sent > 0) {
  5511. return; /* OK */
  5512. }
  5513. /* sf_sent<0 means error, thus fall back to the classic way */
  5514. /* This is always the case, if sf_file is not a "normal" file,
  5515. * e.g., for sending data from the output of a CGI process. */
  5516. offset = (int64_t)sf_offs;
  5517. }
  5518. #endif
  5519. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5520. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5521. send_http_error(
  5522. conn,
  5523. 500,
  5524. "%s",
  5525. "Error: Unable to access file at requested position.");
  5526. } else {
  5527. while (len > 0) {
  5528. /* Calculate how much to read from the file in the buffer */
  5529. to_read = sizeof(buf);
  5530. if ((int64_t)to_read > len) {
  5531. to_read = (int)len;
  5532. }
  5533. /* Read from file, exit the loop on error */
  5534. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5535. <= 0) {
  5536. break;
  5537. }
  5538. /* Send read bytes to the client, exit the loop on error */
  5539. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5540. != num_read) {
  5541. break;
  5542. }
  5543. /* Both read and were successful, adjust counters */
  5544. conn->num_bytes_sent += num_written;
  5545. len -= num_written;
  5546. }
  5547. }
  5548. }
  5549. }
  5550. static int
  5551. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5552. {
  5553. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5554. }
  5555. static void
  5556. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5557. {
  5558. if (filep != NULL && buf != NULL) {
  5559. mg_snprintf(NULL,
  5560. NULL, /* All calls to construct_etag use 64 byte buffer */
  5561. buf,
  5562. buf_len,
  5563. "\"%lx.%" INT64_FMT "\"",
  5564. (unsigned long)filep->last_modified,
  5565. filep->size);
  5566. }
  5567. }
  5568. static void
  5569. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5570. {
  5571. if (filep != NULL && filep->fp != NULL) {
  5572. #ifdef _WIN32
  5573. (void)conn; /* Unused. */
  5574. #else
  5575. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5576. mg_cry(conn,
  5577. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5578. __func__,
  5579. strerror(ERRNO));
  5580. }
  5581. #endif
  5582. }
  5583. }
  5584. static void
  5585. handle_static_file_request(struct mg_connection *conn,
  5586. const char *path,
  5587. struct file *filep,
  5588. const char *mime_type)
  5589. {
  5590. char date[64], lm[64], etag[64];
  5591. char range[128]; /* large enough, so there will be no overflow */
  5592. const char *msg = "OK", *hdr;
  5593. time_t curtime = time(NULL);
  5594. int64_t cl, r1, r2;
  5595. struct vec mime_vec;
  5596. int n, truncated;
  5597. char gz_path[PATH_MAX];
  5598. const char *encoding = "";
  5599. const char *cors1, *cors2, *cors3;
  5600. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5601. return;
  5602. }
  5603. if (mime_type == NULL) {
  5604. get_mime_type(conn->ctx, path, &mime_vec);
  5605. } else {
  5606. mime_vec.ptr = mime_type;
  5607. mime_vec.len = strlen(mime_type);
  5608. }
  5609. if (filep->size > INT64_MAX) {
  5610. send_http_error(conn,
  5611. 500,
  5612. "Error: File size is too large to send\n%" INT64_FMT,
  5613. filep->size);
  5614. }
  5615. cl = (int64_t)filep->size;
  5616. conn->status_code = 200;
  5617. range[0] = '\0';
  5618. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5619. * it's important to rewrite the filename after resolving
  5620. * the mime type from it, to preserve the actual file's type */
  5621. if (filep->gzipped) {
  5622. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5623. if (truncated) {
  5624. send_http_error(conn,
  5625. 500,
  5626. "Error: Path of zipped file too long (%s)",
  5627. path);
  5628. return;
  5629. }
  5630. path = gz_path;
  5631. encoding = "Content-Encoding: gzip\r\n";
  5632. }
  5633. if (!mg_fopen(conn, path, "rb", filep)) {
  5634. send_http_error(conn,
  5635. 500,
  5636. "Error: Cannot open file\nfopen(%s): %s",
  5637. path,
  5638. strerror(ERRNO));
  5639. return;
  5640. }
  5641. fclose_on_exec(filep, conn);
  5642. /* If Range: header specified, act accordingly */
  5643. r1 = r2 = 0;
  5644. hdr = mg_get_header(conn, "Range");
  5645. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5646. && r2 >= 0) {
  5647. /* actually, range requests don't play well with a pre-gzipped
  5648. * file (since the range is specified in the uncompressed space) */
  5649. if (filep->gzipped) {
  5650. send_http_error(
  5651. conn,
  5652. 501,
  5653. "%s",
  5654. "Error: Range requests in gzipped files are not supported");
  5655. mg_fclose(filep);
  5656. return;
  5657. }
  5658. conn->status_code = 206;
  5659. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5660. mg_snprintf(conn,
  5661. NULL, /* range buffer is big enough */
  5662. range,
  5663. sizeof(range),
  5664. "Content-Range: bytes "
  5665. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5666. r1,
  5667. r1 + cl - 1,
  5668. filep->size);
  5669. msg = "Partial Content";
  5670. }
  5671. hdr = mg_get_header(conn, "Origin");
  5672. if (hdr) {
  5673. /* Cross-origin resource sharing (CORS), see
  5674. * http://www.html5rocks.com/en/tutorials/cors/,
  5675. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5676. * preflight is not supported for files. */
  5677. cors1 = "Access-Control-Allow-Origin: ";
  5678. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5679. cors3 = "\r\n";
  5680. } else {
  5681. cors1 = cors2 = cors3 = "";
  5682. }
  5683. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5684. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5685. gmt_time_string(date, sizeof(date), &curtime);
  5686. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5687. construct_etag(etag, sizeof(etag), filep);
  5688. (void)mg_printf(conn,
  5689. "HTTP/1.1 %d %s\r\n"
  5690. "%s%s%s"
  5691. "Date: %s\r\n",
  5692. conn->status_code,
  5693. msg,
  5694. cors1,
  5695. cors2,
  5696. cors3,
  5697. date);
  5698. send_static_cache_header(conn);
  5699. (void)mg_printf(conn,
  5700. "Last-Modified: %s\r\n"
  5701. "Etag: %s\r\n"
  5702. "Content-Type: %.*s\r\n"
  5703. "Content-Length: %" INT64_FMT "\r\n"
  5704. "Connection: %s\r\n"
  5705. "Accept-Ranges: bytes\r\n"
  5706. "%s%s\r\n",
  5707. lm,
  5708. etag,
  5709. (int)mime_vec.len,
  5710. mime_vec.ptr,
  5711. cl,
  5712. suggest_connection_header(conn),
  5713. range,
  5714. encoding);
  5715. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5716. send_file_data(conn, filep, r1, cl);
  5717. }
  5718. mg_fclose(filep);
  5719. }
  5720. void
  5721. mg_send_file(struct mg_connection *conn, const char *path)
  5722. {
  5723. mg_send_mime_file(conn, path, NULL);
  5724. }
  5725. void
  5726. mg_send_mime_file(struct mg_connection *conn,
  5727. const char *path,
  5728. const char *mime_type)
  5729. {
  5730. struct file file = STRUCT_FILE_INITIALIZER;
  5731. if (mg_stat(conn, path, &file)) {
  5732. if (file.is_directory) {
  5733. if (!conn) {
  5734. return;
  5735. }
  5736. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5737. "yes")) {
  5738. handle_directory_request(conn, path);
  5739. } else {
  5740. send_http_error(conn,
  5741. 403,
  5742. "%s",
  5743. "Error: Directory listing denied");
  5744. }
  5745. } else {
  5746. handle_static_file_request(conn, path, &file, mime_type);
  5747. }
  5748. } else {
  5749. send_http_error(conn, 404, "%s", "Error: File not found");
  5750. }
  5751. }
  5752. /* For a given PUT path, create all intermediate subdirectories.
  5753. * Return 0 if the path itself is a directory.
  5754. * Return 1 if the path leads to a file.
  5755. * Return -1 for if the path is too long.
  5756. * Return -2 if path can not be created.
  5757. */
  5758. static int
  5759. put_dir(struct mg_connection *conn, const char *path)
  5760. {
  5761. char buf[PATH_MAX];
  5762. const char *s, *p;
  5763. struct file file = STRUCT_FILE_INITIALIZER;
  5764. size_t len;
  5765. int res = 1;
  5766. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5767. len = (size_t)(p - path);
  5768. if (len >= sizeof(buf)) {
  5769. /* path too long */
  5770. res = -1;
  5771. break;
  5772. }
  5773. memcpy(buf, path, len);
  5774. buf[len] = '\0';
  5775. /* Try to create intermediate directory */
  5776. DEBUG_TRACE("mkdir(%s)", buf);
  5777. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  5778. /* path does not exixt and can not be created */
  5779. res = -2;
  5780. break;
  5781. }
  5782. /* Is path itself a directory? */
  5783. if (p[1] == '\0') {
  5784. res = 0;
  5785. }
  5786. }
  5787. return res;
  5788. }
  5789. static void
  5790. remove_bad_file(const struct mg_connection *conn, const char *path)
  5791. {
  5792. int r = mg_remove(conn, path);
  5793. if (r != 0) {
  5794. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  5795. }
  5796. }
  5797. long long
  5798. mg_store_body(struct mg_connection *conn, const char *path)
  5799. {
  5800. char buf[MG_BUF_LEN];
  5801. long long len = 0;
  5802. int ret, n;
  5803. struct file fi;
  5804. if (conn->consumed_content != 0) {
  5805. mg_cry(conn, "%s: Contents already consumed", __func__);
  5806. return -11;
  5807. }
  5808. ret = put_dir(conn, path);
  5809. if (ret < 0) {
  5810. /* -1 for path too long,
  5811. * -2 for path can not be created. */
  5812. return ret;
  5813. }
  5814. if (ret != 1) {
  5815. /* Return 0 means, path itself is a directory. */
  5816. return 0;
  5817. }
  5818. if (mg_fopen(conn, path, "w", &fi) == 0) {
  5819. return -12;
  5820. }
  5821. ret = mg_read(conn, buf, sizeof(buf));
  5822. while (ret > 0) {
  5823. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  5824. if (n != ret) {
  5825. mg_fclose(&fi);
  5826. remove_bad_file(conn, path);
  5827. return -13;
  5828. }
  5829. ret = mg_read(conn, buf, sizeof(buf));
  5830. }
  5831. /* TODO: mg_fclose should return an error,
  5832. * and every caller should check and handle it. */
  5833. if (fclose(fi.fp) != 0) {
  5834. remove_bad_file(conn, path);
  5835. return -14;
  5836. }
  5837. return len;
  5838. }
  5839. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5840. * where parsing stopped. */
  5841. static void
  5842. parse_http_headers(char **buf, struct mg_request_info *ri)
  5843. {
  5844. int i;
  5845. if (!ri) {
  5846. return;
  5847. }
  5848. ri->num_headers = 0;
  5849. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5850. char *dp = *buf;
  5851. while ((*dp != ':') && (*dp != '\r') && (*dp != 0)) {
  5852. dp++;
  5853. }
  5854. if (!*dp) {
  5855. /* neither : nor \r\n. This is not a valid field. */
  5856. break;
  5857. }
  5858. if (*dp == '\r') {
  5859. if (dp[1] == '\n') {
  5860. /* \r\n */
  5861. ri->http_headers[i].name = *buf;
  5862. ri->http_headers[i].value = 0;
  5863. *buf = dp;
  5864. } else {
  5865. /* stray \r. This is not valid. */
  5866. break;
  5867. }
  5868. } else {
  5869. /* (*dp == ':') */
  5870. *dp = 0;
  5871. ri->http_headers[i].name = *buf;
  5872. do {
  5873. dp++;
  5874. } while (*dp == ' ');
  5875. ri->http_headers[i].value = dp;
  5876. *buf = strstr(dp, "\r\n");
  5877. }
  5878. ri->num_headers = i + 1;
  5879. if (*buf) {
  5880. (*buf)[0] = 0;
  5881. (*buf)[1] = 0;
  5882. *buf += 2;
  5883. } else {
  5884. *buf = dp;
  5885. break;
  5886. }
  5887. if (*buf[0] == '\r') {
  5888. /* This is the end of the header */
  5889. break;
  5890. }
  5891. }
  5892. }
  5893. static int
  5894. is_valid_http_method(const char *method)
  5895. {
  5896. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5897. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5898. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5899. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5900. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5901. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5902. /* TRACE method (RFC 2616) is not supported for security reasons */
  5903. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5904. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5905. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5906. /* Unsupported WEBDAV Methods: */
  5907. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5908. /* + 11 methods from RFC 3253 */
  5909. /* ORDERPATCH (RFC 3648) */
  5910. /* ACL (RFC 3744) */
  5911. /* SEARCH (RFC 5323) */
  5912. /* + MicroSoft extensions
  5913. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  5914. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  5915. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  5916. }
  5917. /* Parse HTTP request, fill in mg_request_info structure.
  5918. * This function modifies the buffer by NUL-terminating
  5919. * HTTP request components, header names and header values. */
  5920. static int
  5921. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5922. {
  5923. int is_request, request_length;
  5924. if (!ri) {
  5925. return 0;
  5926. }
  5927. request_length = get_request_len(buf, len);
  5928. if (request_length > 0) {
  5929. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5930. * remote_port */
  5931. ri->remote_user = ri->request_method = ri->request_uri =
  5932. ri->http_version = NULL;
  5933. ri->num_headers = 0;
  5934. buf[request_length - 1] = '\0';
  5935. /* RFC says that all initial whitespaces should be ingored */
  5936. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5937. buf++;
  5938. }
  5939. ri->request_method = skip(&buf, " ");
  5940. ri->request_uri = skip(&buf, " ");
  5941. ri->http_version = skip(&buf, "\r\n");
  5942. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5943. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5944. is_request = is_valid_http_method(ri->request_method);
  5945. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5946. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5947. request_length = -1;
  5948. } else {
  5949. if (is_request) {
  5950. ri->http_version += 5;
  5951. }
  5952. parse_http_headers(&buf, ri);
  5953. }
  5954. }
  5955. return request_length;
  5956. }
  5957. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5958. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5959. * buffer (which marks the end of HTTP request). Buffer buf may already
  5960. * have some data. The length of the data is stored in nread.
  5961. * Upon every read operation, increase nread by the number of bytes read. */
  5962. static int
  5963. read_request(FILE *fp,
  5964. struct mg_connection *conn,
  5965. char *buf,
  5966. int bufsiz,
  5967. int *nread)
  5968. {
  5969. int request_len, n = 0;
  5970. struct timespec last_action_time;
  5971. double request_timeout;
  5972. if (!conn) {
  5973. return 0;
  5974. }
  5975. memset(&last_action_time, 0, sizeof(last_action_time));
  5976. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5977. /* value of request_timeout is in seconds, config in milliseconds */
  5978. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5979. } else {
  5980. request_timeout = -1.0;
  5981. }
  5982. request_len = get_request_len(buf, *nread);
  5983. /* first time reading from this connection */
  5984. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5985. while (
  5986. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5987. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5988. <= request_timeout) || (request_timeout < 0))
  5989. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5990. > 0)) {
  5991. *nread += n;
  5992. /* assert(*nread <= bufsiz); */
  5993. if (*nread > bufsiz) {
  5994. return -2;
  5995. }
  5996. request_len = get_request_len(buf, *nread);
  5997. if (request_timeout > 0.0) {
  5998. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5999. }
  6000. }
  6001. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  6002. }
  6003. #if !defined(NO_FILES)
  6004. /* For given directory path, substitute it to valid index file.
  6005. * Return 1 if index file has been found, 0 if not found.
  6006. * If the file is found, it's stats is returned in stp. */
  6007. static int
  6008. substitute_index_file(struct mg_connection *conn,
  6009. char *path,
  6010. size_t path_len,
  6011. struct file *filep)
  6012. {
  6013. if (conn && conn->ctx) {
  6014. const char *list = conn->ctx->config[INDEX_FILES];
  6015. struct file file = STRUCT_FILE_INITIALIZER;
  6016. struct vec filename_vec;
  6017. size_t n = strlen(path);
  6018. int found = 0;
  6019. /* The 'path' given to us points to the directory. Remove all trailing
  6020. * directory separator characters from the end of the path, and
  6021. * then append single directory separator character. */
  6022. while (n > 0 && path[n - 1] == '/') {
  6023. n--;
  6024. }
  6025. path[n] = '/';
  6026. /* Traverse index files list. For each entry, append it to the given
  6027. * path and see if the file exists. If it exists, break the loop */
  6028. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6029. /* Ignore too long entries that may overflow path buffer */
  6030. if (filename_vec.len > path_len - (n + 2)) {
  6031. continue;
  6032. }
  6033. /* Prepare full path to the index file */
  6034. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6035. /* Does it exist? */
  6036. if (mg_stat(conn, path, &file)) {
  6037. /* Yes it does, break the loop */
  6038. *filep = file;
  6039. found = 1;
  6040. break;
  6041. }
  6042. }
  6043. /* If no index file exists, restore directory path */
  6044. if (!found) {
  6045. path[n] = '\0';
  6046. }
  6047. return found;
  6048. }
  6049. return 0;
  6050. }
  6051. #endif
  6052. #if !defined(NO_CACHING)
  6053. /* Return True if we should reply 304 Not Modified. */
  6054. static int
  6055. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6056. {
  6057. char etag[64];
  6058. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6059. const char *inm = mg_get_header(conn, "If-None-Match");
  6060. construct_etag(etag, sizeof(etag), filep);
  6061. if (!filep) {
  6062. return 0;
  6063. }
  6064. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6065. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6066. }
  6067. #endif /* !NO_CACHING */
  6068. #if !defined(NO_CGI) || !defined(NO_FILES)
  6069. static int
  6070. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6071. {
  6072. const char *expect, *body;
  6073. char buf[MG_BUF_LEN];
  6074. int to_read, nread, success = 0;
  6075. int64_t buffered_len;
  6076. double timeout = -1.0;
  6077. if (!conn) {
  6078. return 0;
  6079. }
  6080. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6081. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6082. }
  6083. expect = mg_get_header(conn, "Expect");
  6084. /* assert(fp != NULL); */
  6085. if (!fp) {
  6086. send_http_error(conn, 500, "%s", "Error: NULL File");
  6087. return 0;
  6088. }
  6089. if (conn->content_len == -1 && !conn->is_chunked) {
  6090. /* Content length is not specified by the client. */
  6091. send_http_error(conn,
  6092. 411,
  6093. "%s",
  6094. "Error: Client did not specify content length");
  6095. } else if ((expect != NULL)
  6096. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6097. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6098. send_http_error(conn,
  6099. 417,
  6100. "Error: Can not fulfill expectation %s",
  6101. expect);
  6102. } else {
  6103. if (expect != NULL) {
  6104. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6105. conn->status_code = 100;
  6106. } else {
  6107. conn->status_code = 200;
  6108. }
  6109. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6110. - conn->consumed_content;
  6111. /* assert(buffered_len >= 0); */
  6112. /* assert(conn->consumed_content == 0); */
  6113. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6114. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6115. return 0;
  6116. }
  6117. if (buffered_len > 0) {
  6118. if ((int64_t)buffered_len > conn->content_len) {
  6119. buffered_len = (int)conn->content_len;
  6120. }
  6121. body = conn->buf + conn->request_len + conn->consumed_content;
  6122. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6123. conn->consumed_content += buffered_len;
  6124. }
  6125. nread = 0;
  6126. while (conn->consumed_content < conn->content_len) {
  6127. to_read = sizeof(buf);
  6128. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6129. to_read = (int)(conn->content_len - conn->consumed_content);
  6130. }
  6131. nread = pull(NULL, conn, buf, to_read, timeout);
  6132. if (nread <= 0
  6133. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6134. break;
  6135. }
  6136. conn->consumed_content += nread;
  6137. }
  6138. if (conn->consumed_content == conn->content_len) {
  6139. success = (nread >= 0);
  6140. }
  6141. /* Each error code path in this function must send an error */
  6142. if (!success) {
  6143. /* NOTE: Maybe some data has already been sent. */
  6144. /* TODO (low): If some data has been sent, a correct error
  6145. * reply can no longer be sent, so just close the connection */
  6146. send_http_error(conn, 500, "%s", "");
  6147. }
  6148. }
  6149. return success;
  6150. }
  6151. #endif
  6152. #if !defined(NO_CGI)
  6153. /* This structure helps to create an environment for the spawned CGI program.
  6154. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6155. * last element must be NULL.
  6156. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6157. * strings must reside in a contiguous buffer. The end of the buffer is
  6158. * marked by two '\0' characters.
  6159. * We satisfy both worlds: we create an envp array (which is vars), all
  6160. * entries are actually pointers inside buf. */
  6161. struct cgi_environment {
  6162. struct mg_connection *conn;
  6163. /* Data block */
  6164. char *buf; /* Environment buffer */
  6165. size_t buflen; /* Space available in buf */
  6166. size_t bufused; /* Space taken in buf */
  6167. /* Index block */
  6168. char **var; /* char **envp */
  6169. size_t varlen; /* Number of variables available in var */
  6170. size_t varused; /* Number of variables stored in var */
  6171. };
  6172. static void addenv(struct cgi_environment *env,
  6173. PRINTF_FORMAT_STRING(const char *fmt),
  6174. ...) PRINTF_ARGS(2, 3);
  6175. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6176. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6177. static void
  6178. addenv(struct cgi_environment *env, const char *fmt, ...)
  6179. {
  6180. size_t n, space;
  6181. int truncated;
  6182. char *added;
  6183. va_list ap;
  6184. /* Calculate how much space is left in the buffer */
  6185. space = (env->buflen - env->bufused);
  6186. /* Calculate an estimate for the required space */
  6187. n = strlen(fmt) + 2 + 128;
  6188. do {
  6189. if (space <= n) {
  6190. /* Allocate new buffer */
  6191. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6192. added = (char *)mg_realloc(env->buf, n);
  6193. if (!added) {
  6194. /* Out of memory */
  6195. mg_cry(env->conn,
  6196. "%s: Cannot allocate memory for CGI variable [%s]",
  6197. __func__,
  6198. fmt);
  6199. return;
  6200. }
  6201. env->buf = added;
  6202. env->buflen = n;
  6203. space = (env->buflen - env->bufused);
  6204. }
  6205. /* Make a pointer to the free space int the buffer */
  6206. added = env->buf + env->bufused;
  6207. /* Copy VARIABLE=VALUE\0 string into the free space */
  6208. va_start(ap, fmt);
  6209. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6210. va_end(ap);
  6211. /* Do not add truncated strings to the environment */
  6212. if (truncated) {
  6213. /* Reallocate the buffer */
  6214. space = 0;
  6215. n = 1;
  6216. }
  6217. } while (truncated);
  6218. /* Calculate number of bytes added to the environment */
  6219. n = strlen(added) + 1;
  6220. env->bufused += n;
  6221. /* Now update the variable index */
  6222. space = (env->varlen - env->varused);
  6223. if (space < 2) {
  6224. mg_cry(env->conn,
  6225. "%s: Cannot register CGI variable [%s]",
  6226. __func__,
  6227. fmt);
  6228. return;
  6229. }
  6230. /* Append a pointer to the added string into the envp array */
  6231. env->var[env->varused] = added;
  6232. env->varused++;
  6233. }
  6234. static void
  6235. prepare_cgi_environment(struct mg_connection *conn,
  6236. const char *prog,
  6237. struct cgi_environment *env)
  6238. {
  6239. const char *s;
  6240. struct vec var_vec;
  6241. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6242. int i, truncated;
  6243. if (conn == NULL || prog == NULL || env == NULL) {
  6244. return;
  6245. }
  6246. env->conn = conn;
  6247. env->buflen = CGI_ENVIRONMENT_SIZE;
  6248. env->bufused = 0;
  6249. env->buf = (char *)mg_malloc(env->buflen);
  6250. env->varlen = MAX_CGI_ENVIR_VARS;
  6251. env->varused = 0;
  6252. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6253. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6254. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6255. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6256. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6257. /* Prepare the environment block */
  6258. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6259. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6260. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6261. #if defined(USE_IPV6)
  6262. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6263. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6264. } else
  6265. #endif
  6266. {
  6267. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6268. }
  6269. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6270. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6271. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6272. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6273. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6274. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6275. /* SCRIPT_NAME */
  6276. addenv(env,
  6277. "SCRIPT_NAME=%.*s",
  6278. (int)strlen(conn->request_info.local_uri)
  6279. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6280. conn->request_info.local_uri);
  6281. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6282. if (conn->path_info == NULL) {
  6283. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6284. } else {
  6285. addenv(env,
  6286. "PATH_TRANSLATED=%s%s",
  6287. conn->ctx->config[DOCUMENT_ROOT],
  6288. conn->path_info);
  6289. }
  6290. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  6291. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6292. addenv(env, "CONTENT_TYPE=%s", s);
  6293. }
  6294. if (conn->request_info.query_string != NULL) {
  6295. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6296. }
  6297. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6298. addenv(env, "CONTENT_LENGTH=%s", s);
  6299. }
  6300. if ((s = getenv("PATH")) != NULL) {
  6301. addenv(env, "PATH=%s", s);
  6302. }
  6303. if (conn->path_info != NULL) {
  6304. addenv(env, "PATH_INFO=%s", conn->path_info);
  6305. }
  6306. if (conn->status_code > 0) {
  6307. /* CGI error handler should show the status code */
  6308. addenv(env, "STATUS=%d", conn->status_code);
  6309. }
  6310. #if defined(_WIN32)
  6311. if ((s = getenv("COMSPEC")) != NULL) {
  6312. addenv(env, "COMSPEC=%s", s);
  6313. }
  6314. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6315. addenv(env, "SYSTEMROOT=%s", s);
  6316. }
  6317. if ((s = getenv("SystemDrive")) != NULL) {
  6318. addenv(env, "SystemDrive=%s", s);
  6319. }
  6320. if ((s = getenv("ProgramFiles")) != NULL) {
  6321. addenv(env, "ProgramFiles=%s", s);
  6322. }
  6323. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6324. addenv(env, "ProgramFiles(x86)=%s", s);
  6325. }
  6326. #else
  6327. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6328. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6329. }
  6330. #endif /* _WIN32 */
  6331. if ((s = getenv("PERLLIB")) != NULL) {
  6332. addenv(env, "PERLLIB=%s", s);
  6333. }
  6334. if (conn->request_info.remote_user != NULL) {
  6335. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6336. addenv(env, "%s", "AUTH_TYPE=Digest");
  6337. }
  6338. /* Add all headers as HTTP_* variables */
  6339. for (i = 0; i < conn->request_info.num_headers; i++) {
  6340. (void)mg_snprintf(conn,
  6341. &truncated,
  6342. http_var_name,
  6343. sizeof(http_var_name),
  6344. "HTTP_%s",
  6345. conn->request_info.http_headers[i].name);
  6346. if (truncated) {
  6347. mg_cry(conn,
  6348. "%s: HTTP header variable too long [%s]",
  6349. __func__,
  6350. conn->request_info.http_headers[i].name);
  6351. continue;
  6352. }
  6353. /* Convert variable name into uppercase, and change - to _ */
  6354. for (p = http_var_name; *p != '\0'; p++) {
  6355. if (*p == '-') {
  6356. *p = '_';
  6357. }
  6358. *p = (char)toupper(*(unsigned char *)p);
  6359. }
  6360. addenv(env,
  6361. "%s=%s",
  6362. http_var_name,
  6363. conn->request_info.http_headers[i].value);
  6364. }
  6365. /* Add user-specified variables */
  6366. s = conn->ctx->config[CGI_ENVIRONMENT];
  6367. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6368. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6369. }
  6370. env->var[env->varused] = NULL;
  6371. env->buf[env->bufused] = '\0';
  6372. }
  6373. static void
  6374. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6375. {
  6376. char *buf;
  6377. size_t buflen;
  6378. int headers_len, data_len, i, truncated;
  6379. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6380. const char *status, *status_text, *connection_state;
  6381. char *pbuf, dir[PATH_MAX], *p;
  6382. struct mg_request_info ri;
  6383. struct cgi_environment blk;
  6384. FILE *in = NULL, *out = NULL, *err = NULL;
  6385. struct file fout = STRUCT_FILE_INITIALIZER;
  6386. pid_t pid = (pid_t)-1;
  6387. if (conn == NULL) {
  6388. return;
  6389. }
  6390. buf = NULL;
  6391. buflen = 16384;
  6392. prepare_cgi_environment(conn, prog, &blk);
  6393. /* CGI must be executed in its own directory. 'dir' must point to the
  6394. * directory containing executable program, 'p' must point to the
  6395. * executable program name relative to 'dir'. */
  6396. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6397. if (truncated) {
  6398. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6399. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6400. goto done;
  6401. }
  6402. if ((p = strrchr(dir, '/')) != NULL) {
  6403. *p++ = '\0';
  6404. } else {
  6405. dir[0] = '.', dir[1] = '\0';
  6406. p = (char *)prog;
  6407. }
  6408. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6409. status = strerror(ERRNO);
  6410. mg_cry(conn,
  6411. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6412. prog,
  6413. status);
  6414. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6415. goto done;
  6416. }
  6417. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6418. if (pid == (pid_t)-1) {
  6419. status = strerror(ERRNO);
  6420. mg_cry(conn,
  6421. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6422. prog,
  6423. status);
  6424. send_http_error(conn,
  6425. 500,
  6426. "Error: Cannot spawn CGI process [%s]: %s",
  6427. prog,
  6428. status);
  6429. goto done;
  6430. }
  6431. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6432. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6433. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6434. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6435. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6436. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6437. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6438. /* Parent closes only one side of the pipes.
  6439. * If we don't mark them as closed, close() attempt before
  6440. * return from this function throws an exception on Windows.
  6441. * Windows does not like when closed descriptor is closed again. */
  6442. (void)close(fdin[0]);
  6443. (void)close(fdout[1]);
  6444. (void)close(fderr[1]);
  6445. fdin[0] = fdout[1] = fderr[1] = -1;
  6446. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6447. status = strerror(ERRNO);
  6448. mg_cry(conn,
  6449. "Error: CGI program \"%s\": Can not open stdin: %s",
  6450. prog,
  6451. status);
  6452. send_http_error(conn,
  6453. 500,
  6454. "Error: CGI can not open fdin\nfopen: %s",
  6455. status);
  6456. goto done;
  6457. }
  6458. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6459. status = strerror(ERRNO);
  6460. mg_cry(conn,
  6461. "Error: CGI program \"%s\": Can not open stdout: %s",
  6462. prog,
  6463. status);
  6464. send_http_error(conn,
  6465. 500,
  6466. "Error: CGI can not open fdout\nfopen: %s",
  6467. status);
  6468. goto done;
  6469. }
  6470. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6471. status = strerror(ERRNO);
  6472. mg_cry(conn,
  6473. "Error: CGI program \"%s\": Can not open stderr: %s",
  6474. prog,
  6475. status);
  6476. send_http_error(conn,
  6477. 500,
  6478. "Error: CGI can not open fdout\nfopen: %s",
  6479. status);
  6480. goto done;
  6481. }
  6482. setbuf(in, NULL);
  6483. setbuf(out, NULL);
  6484. setbuf(err, NULL);
  6485. fout.fp = out;
  6486. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6487. /* This is a POST/PUT request, or another request with body data. */
  6488. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6489. /* Error sending the body data */
  6490. mg_cry(conn,
  6491. "Error: CGI program \"%s\": Forward body data failed",
  6492. prog);
  6493. goto done;
  6494. }
  6495. }
  6496. /* Close so child gets an EOF. */
  6497. fclose(in);
  6498. in = NULL;
  6499. fdin[1] = -1;
  6500. /* Now read CGI reply into a buffer. We need to set correct
  6501. * status code, thus we need to see all HTTP headers first.
  6502. * Do not send anything back to client, until we buffer in all
  6503. * HTTP headers. */
  6504. data_len = 0;
  6505. buf = (char *)mg_malloc(buflen);
  6506. if (buf == NULL) {
  6507. send_http_error(conn,
  6508. 500,
  6509. "Error: Not enough memory for CGI buffer (%u bytes)",
  6510. (unsigned int)buflen);
  6511. mg_cry(conn,
  6512. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6513. "bytes)",
  6514. prog,
  6515. (unsigned int)buflen);
  6516. goto done;
  6517. }
  6518. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6519. if (headers_len <= 0) {
  6520. /* Could not parse the CGI response. Check if some error message on
  6521. * stderr. */
  6522. i = pull_all(err, conn, buf, (int)buflen);
  6523. if (i > 0) {
  6524. mg_cry(conn,
  6525. "Error: CGI program \"%s\" sent error "
  6526. "message: [%.*s]",
  6527. prog,
  6528. i,
  6529. buf);
  6530. send_http_error(conn,
  6531. 500,
  6532. "Error: CGI program \"%s\" sent error "
  6533. "message: [%.*s]",
  6534. prog,
  6535. i,
  6536. buf);
  6537. } else {
  6538. mg_cry(conn,
  6539. "Error: CGI program sent malformed or too big "
  6540. "(>%u bytes) HTTP headers: [%.*s]",
  6541. (unsigned)buflen,
  6542. data_len,
  6543. buf);
  6544. send_http_error(conn,
  6545. 500,
  6546. "Error: CGI program sent malformed or too big "
  6547. "(>%u bytes) HTTP headers: [%.*s]",
  6548. (unsigned)buflen,
  6549. data_len,
  6550. buf);
  6551. }
  6552. goto done;
  6553. }
  6554. pbuf = buf;
  6555. buf[headers_len - 1] = '\0';
  6556. parse_http_headers(&pbuf, &ri);
  6557. /* Make up and send the status line */
  6558. status_text = "OK";
  6559. if ((status = get_header(&ri, "Status")) != NULL) {
  6560. conn->status_code = atoi(status);
  6561. status_text = status;
  6562. while (isdigit(*(const unsigned char *)status_text)
  6563. || *status_text == ' ') {
  6564. status_text++;
  6565. }
  6566. } else if (get_header(&ri, "Location") != NULL) {
  6567. conn->status_code = 302;
  6568. } else {
  6569. conn->status_code = 200;
  6570. }
  6571. connection_state = get_header(&ri, "Connection");
  6572. if (!header_has_option(connection_state, "keep-alive")) {
  6573. conn->must_close = 1;
  6574. }
  6575. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6576. /* Send headers */
  6577. for (i = 0; i < ri.num_headers; i++) {
  6578. mg_printf(conn,
  6579. "%s: %s\r\n",
  6580. ri.http_headers[i].name,
  6581. ri.http_headers[i].value);
  6582. }
  6583. mg_write(conn, "\r\n", 2);
  6584. /* Send chunk of data that may have been read after the headers */
  6585. conn->num_bytes_sent +=
  6586. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6587. /* Read the rest of CGI output and send to the client */
  6588. send_file_data(conn, &fout, 0, INT64_MAX);
  6589. done:
  6590. mg_free(blk.var);
  6591. mg_free(blk.buf);
  6592. if (pid != (pid_t)-1) {
  6593. kill(pid, SIGKILL);
  6594. #if !defined(_WIN32)
  6595. {
  6596. int st;
  6597. while (waitpid(pid, &st, 0) != -1)
  6598. ; /* clean zombies */
  6599. }
  6600. #endif
  6601. }
  6602. if (fdin[0] != -1) {
  6603. close(fdin[0]);
  6604. }
  6605. if (fdout[1] != -1) {
  6606. close(fdout[1]);
  6607. }
  6608. if (in != NULL) {
  6609. fclose(in);
  6610. } else if (fdin[1] != -1) {
  6611. close(fdin[1]);
  6612. }
  6613. if (out != NULL) {
  6614. fclose(out);
  6615. } else if (fdout[0] != -1) {
  6616. close(fdout[0]);
  6617. }
  6618. if (err != NULL) {
  6619. fclose(err);
  6620. } else if (fderr[0] != -1) {
  6621. close(fderr[0]);
  6622. }
  6623. if (buf != NULL) {
  6624. mg_free(buf);
  6625. }
  6626. }
  6627. #endif /* !NO_CGI */
  6628. #if !defined(NO_FILES)
  6629. static void
  6630. mkcol(struct mg_connection *conn, const char *path)
  6631. {
  6632. int rc, body_len;
  6633. struct de de;
  6634. char date[64];
  6635. time_t curtime = time(NULL);
  6636. if (conn == NULL) {
  6637. return;
  6638. }
  6639. /* TODO (mid): Check the send_http_error situations in this function */
  6640. memset(&de.file, 0, sizeof(de.file));
  6641. if (!mg_stat(conn, path, &de.file)) {
  6642. mg_cry(conn,
  6643. "%s: mg_stat(%s) failed: %s",
  6644. __func__,
  6645. path,
  6646. strerror(ERRNO));
  6647. }
  6648. if (de.file.last_modified) {
  6649. /* TODO (high): This check does not seem to make any sense ! */
  6650. send_http_error(
  6651. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6652. return;
  6653. }
  6654. body_len = conn->data_len - conn->request_len;
  6655. if (body_len > 0) {
  6656. send_http_error(
  6657. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6658. return;
  6659. }
  6660. rc = mg_mkdir(conn, path, 0755);
  6661. if (rc == 0) {
  6662. conn->status_code = 201;
  6663. gmt_time_string(date, sizeof(date), &curtime);
  6664. mg_printf(conn,
  6665. "HTTP/1.1 %d Created\r\n"
  6666. "Date: %s\r\n",
  6667. conn->status_code,
  6668. date);
  6669. send_static_cache_header(conn);
  6670. mg_printf(conn,
  6671. "Content-Length: 0\r\n"
  6672. "Connection: %s\r\n\r\n",
  6673. suggest_connection_header(conn));
  6674. } else if (rc == -1) {
  6675. if (errno == EEXIST) {
  6676. send_http_error(
  6677. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6678. } else if (errno == EACCES) {
  6679. send_http_error(
  6680. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6681. } else if (errno == ENOENT) {
  6682. send_http_error(
  6683. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6684. } else {
  6685. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6686. }
  6687. }
  6688. }
  6689. static void
  6690. put_file(struct mg_connection *conn, const char *path)
  6691. {
  6692. struct file file = STRUCT_FILE_INITIALIZER;
  6693. const char *range;
  6694. int64_t r1, r2;
  6695. int rc;
  6696. char date[64];
  6697. time_t curtime = time(NULL);
  6698. if (conn == NULL) {
  6699. return;
  6700. }
  6701. if (mg_stat(conn, path, &file)) {
  6702. /* File already exists */
  6703. conn->status_code = 200;
  6704. if (file.is_directory) {
  6705. /* This is an already existing directory,
  6706. * so there is nothing to do for the server. */
  6707. rc = 0;
  6708. } else {
  6709. /* File exists and is not a directory. */
  6710. /* Can it be replaced? */
  6711. if (file.membuf != NULL) {
  6712. /* This is an "in-memory" file, that can not be replaced */
  6713. send_http_error(
  6714. conn,
  6715. 405,
  6716. "Error: Put not possible\nReplacing %s is not supported",
  6717. path);
  6718. return;
  6719. }
  6720. /* Check if the server may write this file */
  6721. if (access(path, W_OK) == 0) {
  6722. /* Access granted */
  6723. conn->status_code = 200;
  6724. rc = 1;
  6725. } else {
  6726. send_http_error(
  6727. conn,
  6728. 403,
  6729. "Error: Put not possible\nReplacing %s is not allowed",
  6730. path);
  6731. return;
  6732. }
  6733. }
  6734. } else {
  6735. /* File should be created */
  6736. conn->status_code = 201;
  6737. rc = put_dir(conn, path);
  6738. }
  6739. if (rc == 0) {
  6740. /* put_dir returns 0 if path is a directory */
  6741. gmt_time_string(date, sizeof(date), &curtime);
  6742. mg_printf(conn,
  6743. "HTTP/1.1 %d %s\r\n",
  6744. conn->status_code,
  6745. mg_get_response_code_text(NULL, conn->status_code));
  6746. send_no_cache_header(conn);
  6747. mg_printf(conn,
  6748. "Date: %s\r\n"
  6749. "Content-Length: 0\r\n"
  6750. "Connection: %s\r\n\r\n",
  6751. date,
  6752. suggest_connection_header(conn));
  6753. /* Request to create a directory has been fulfilled successfully.
  6754. * No need to put a file. */
  6755. return;
  6756. }
  6757. if (rc == -1) {
  6758. /* put_dir returns -1 if the path is too long */
  6759. send_http_error(conn,
  6760. 414,
  6761. "Error: Path too long\nput_dir(%s): %s",
  6762. path,
  6763. strerror(ERRNO));
  6764. return;
  6765. }
  6766. if (rc == -2) {
  6767. /* put_dir returns -2 if the directory can not be created */
  6768. send_http_error(conn,
  6769. 500,
  6770. "Error: Can not create directory\nput_dir(%s): %s",
  6771. path,
  6772. strerror(ERRNO));
  6773. return;
  6774. }
  6775. /* A file should be created or overwritten. */
  6776. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6777. mg_fclose(&file);
  6778. send_http_error(conn,
  6779. 500,
  6780. "Error: Can not create file\nfopen(%s): %s",
  6781. path,
  6782. strerror(ERRNO));
  6783. return;
  6784. }
  6785. fclose_on_exec(&file, conn);
  6786. range = mg_get_header(conn, "Content-Range");
  6787. r1 = r2 = 0;
  6788. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6789. conn->status_code = 206; /* Partial content */
  6790. fseeko(file.fp, r1, SEEK_SET);
  6791. }
  6792. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6793. /* forward_body_data failed.
  6794. * The error code has already been sent to the client,
  6795. * and conn->status_code is already set. */
  6796. mg_fclose(&file);
  6797. return;
  6798. }
  6799. gmt_time_string(date, sizeof(date), &curtime);
  6800. mg_printf(conn,
  6801. "HTTP/1.1 %d %s\r\n",
  6802. conn->status_code,
  6803. mg_get_response_code_text(NULL, conn->status_code));
  6804. send_no_cache_header(conn);
  6805. mg_printf(conn,
  6806. "Date: %s\r\n"
  6807. "Content-Length: 0\r\n"
  6808. "Connection: %s\r\n\r\n",
  6809. date,
  6810. suggest_connection_header(conn));
  6811. mg_fclose(&file);
  6812. }
  6813. static void
  6814. delete_file(struct mg_connection *conn, const char *path)
  6815. {
  6816. struct de de;
  6817. memset(&de.file, 0, sizeof(de.file));
  6818. if (!mg_stat(conn, path, &de.file)) {
  6819. /* mg_stat returns 0 if the file does not exist */
  6820. send_http_error(conn,
  6821. 404,
  6822. "Error: Cannot delete file\nFile %s not found",
  6823. path);
  6824. return;
  6825. }
  6826. if (de.file.membuf != NULL) {
  6827. /* the file is cached in memory */
  6828. send_http_error(
  6829. conn,
  6830. 405,
  6831. "Error: Delete not possible\nDeleting %s is not supported",
  6832. path);
  6833. return;
  6834. }
  6835. if (de.file.is_directory) {
  6836. if (remove_directory(conn, path)) {
  6837. /* Delete is successful: Return 204 without content. */
  6838. send_http_error(conn, 204, "%s", "");
  6839. } else {
  6840. /* Delete is not successful: Return 500 (Server error). */
  6841. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6842. }
  6843. return;
  6844. }
  6845. /* This is an existing file (not a directory).
  6846. * Check if write permission is granted. */
  6847. if (access(path, W_OK) != 0) {
  6848. /* File is read only */
  6849. send_http_error(
  6850. conn,
  6851. 403,
  6852. "Error: Delete not possible\nDeleting %s is not allowed",
  6853. path);
  6854. return;
  6855. }
  6856. /* Try to delete it. */
  6857. if (mg_remove(conn, path) == 0) {
  6858. /* Delete was successful: Return 204 without content. */
  6859. send_http_error(conn, 204, "%s", "");
  6860. } else {
  6861. /* Delete not successful (file locked). */
  6862. send_http_error(conn,
  6863. 423,
  6864. "Error: Cannot delete file\nremove(%s): %s",
  6865. path,
  6866. strerror(ERRNO));
  6867. }
  6868. }
  6869. #endif /* !NO_FILES */
  6870. static void
  6871. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6872. static void
  6873. do_ssi_include(struct mg_connection *conn,
  6874. const char *ssi,
  6875. char *tag,
  6876. int include_level)
  6877. {
  6878. char file_name[MG_BUF_LEN], path[512], *p;
  6879. struct file file = STRUCT_FILE_INITIALIZER;
  6880. size_t len;
  6881. int truncated = 0;
  6882. if (conn == NULL) {
  6883. return;
  6884. }
  6885. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6886. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6887. * always < MG_BUF_LEN. */
  6888. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6889. /* File name is relative to the webserver root */
  6890. file_name[511] = 0;
  6891. (void)mg_snprintf(conn,
  6892. &truncated,
  6893. path,
  6894. sizeof(path),
  6895. "%s/%s",
  6896. conn->ctx->config[DOCUMENT_ROOT],
  6897. file_name);
  6898. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6899. /* File name is relative to the webserver working directory
  6900. * or it is absolute system path */
  6901. file_name[511] = 0;
  6902. (void)
  6903. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6904. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6905. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6906. /* File name is relative to the currect document */
  6907. file_name[511] = 0;
  6908. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6909. if (!truncated) {
  6910. if ((p = strrchr(path, '/')) != NULL) {
  6911. p[1] = '\0';
  6912. }
  6913. len = strlen(path);
  6914. (void)mg_snprintf(conn,
  6915. &truncated,
  6916. path + len,
  6917. sizeof(path) - len,
  6918. "%s",
  6919. file_name);
  6920. }
  6921. } else {
  6922. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6923. return;
  6924. }
  6925. if (truncated) {
  6926. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6927. return;
  6928. }
  6929. if (!mg_fopen(conn, path, "rb", &file)) {
  6930. mg_cry(conn,
  6931. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6932. tag,
  6933. path,
  6934. strerror(ERRNO));
  6935. } else {
  6936. fclose_on_exec(&file, conn);
  6937. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6938. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6939. path) > 0) {
  6940. send_ssi_file(conn, path, &file, include_level + 1);
  6941. } else {
  6942. send_file_data(conn, &file, 0, INT64_MAX);
  6943. }
  6944. mg_fclose(&file);
  6945. }
  6946. }
  6947. #if !defined(NO_POPEN)
  6948. static void
  6949. do_ssi_exec(struct mg_connection *conn, char *tag)
  6950. {
  6951. char cmd[1024] = "";
  6952. struct file file = STRUCT_FILE_INITIALIZER;
  6953. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6954. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6955. } else {
  6956. cmd[1023] = 0;
  6957. if ((file.fp = popen(cmd, "r")) == NULL) {
  6958. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6959. } else {
  6960. send_file_data(conn, &file, 0, INT64_MAX);
  6961. pclose(file.fp);
  6962. }
  6963. }
  6964. }
  6965. #endif /* !NO_POPEN */
  6966. static int
  6967. mg_fgetc(struct file *filep, int offset)
  6968. {
  6969. if (filep == NULL) {
  6970. return EOF;
  6971. }
  6972. if (filep->membuf != NULL && offset >= 0
  6973. && ((unsigned int)(offset)) < filep->size) {
  6974. return ((const unsigned char *)filep->membuf)[offset];
  6975. } else if (filep->fp != NULL) {
  6976. return fgetc(filep->fp);
  6977. } else {
  6978. return EOF;
  6979. }
  6980. }
  6981. static void
  6982. send_ssi_file(struct mg_connection *conn,
  6983. const char *path,
  6984. struct file *filep,
  6985. int include_level)
  6986. {
  6987. char buf[MG_BUF_LEN];
  6988. int ch, offset, len, in_ssi_tag;
  6989. if (include_level > 10) {
  6990. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6991. return;
  6992. }
  6993. in_ssi_tag = len = offset = 0;
  6994. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6995. if (in_ssi_tag && ch == '>') {
  6996. in_ssi_tag = 0;
  6997. buf[len++] = (char)ch;
  6998. buf[len] = '\0';
  6999. /* assert(len <= (int) sizeof(buf)); */
  7000. if (len > (int)sizeof(buf)) {
  7001. break;
  7002. }
  7003. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7004. /* Not an SSI tag, pass it */
  7005. (void)mg_write(conn, buf, (size_t)len);
  7006. } else {
  7007. if (!memcmp(buf + 5, "include", 7)) {
  7008. do_ssi_include(conn, path, buf + 12, include_level);
  7009. #if !defined(NO_POPEN)
  7010. } else if (!memcmp(buf + 5, "exec", 4)) {
  7011. do_ssi_exec(conn, buf + 9);
  7012. #endif /* !NO_POPEN */
  7013. } else {
  7014. mg_cry(conn,
  7015. "%s: unknown SSI "
  7016. "command: \"%s\"",
  7017. path,
  7018. buf);
  7019. }
  7020. }
  7021. len = 0;
  7022. } else if (in_ssi_tag) {
  7023. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7024. /* Not an SSI tag */
  7025. in_ssi_tag = 0;
  7026. } else if (len == (int)sizeof(buf) - 2) {
  7027. mg_cry(conn, "%s: SSI tag is too large", path);
  7028. len = 0;
  7029. }
  7030. buf[len++] = (char)(ch & 0xff);
  7031. } else if (ch == '<') {
  7032. in_ssi_tag = 1;
  7033. if (len > 0) {
  7034. mg_write(conn, buf, (size_t)len);
  7035. }
  7036. len = 0;
  7037. buf[len++] = (char)(ch & 0xff);
  7038. } else {
  7039. buf[len++] = (char)(ch & 0xff);
  7040. if (len == (int)sizeof(buf)) {
  7041. mg_write(conn, buf, (size_t)len);
  7042. len = 0;
  7043. }
  7044. }
  7045. }
  7046. /* Send the rest of buffered data */
  7047. if (len > 0) {
  7048. mg_write(conn, buf, (size_t)len);
  7049. }
  7050. }
  7051. static void
  7052. handle_ssi_file_request(struct mg_connection *conn,
  7053. const char *path,
  7054. struct file *filep)
  7055. {
  7056. char date[64];
  7057. time_t curtime = time(NULL);
  7058. const char *cors1, *cors2, *cors3;
  7059. if (conn == NULL || path == NULL || filep == NULL) {
  7060. return;
  7061. }
  7062. if (mg_get_header(conn, "Origin")) {
  7063. /* Cross-origin resource sharing (CORS). */
  7064. cors1 = "Access-Control-Allow-Origin: ";
  7065. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7066. cors3 = "\r\n";
  7067. } else {
  7068. cors1 = cors2 = cors3 = "";
  7069. }
  7070. if (!mg_fopen(conn, path, "rb", filep)) {
  7071. /* File exists (precondition for calling this function),
  7072. * but can not be opened by the server. */
  7073. send_http_error(conn,
  7074. 500,
  7075. "Error: Cannot read file\nfopen(%s): %s",
  7076. path,
  7077. strerror(ERRNO));
  7078. } else {
  7079. conn->must_close = 1;
  7080. gmt_time_string(date, sizeof(date), &curtime);
  7081. fclose_on_exec(filep, conn);
  7082. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7083. send_no_cache_header(conn);
  7084. mg_printf(conn,
  7085. "%s%s%s"
  7086. "Date: %s\r\n"
  7087. "Content-Type: text/html\r\n"
  7088. "Connection: %s\r\n\r\n",
  7089. cors1,
  7090. cors2,
  7091. cors3,
  7092. date,
  7093. suggest_connection_header(conn));
  7094. send_ssi_file(conn, path, filep, 0);
  7095. mg_fclose(filep);
  7096. }
  7097. }
  7098. #if !defined(NO_FILES)
  7099. static void
  7100. send_options(struct mg_connection *conn)
  7101. {
  7102. char date[64];
  7103. time_t curtime = time(NULL);
  7104. if (!conn) {
  7105. return;
  7106. }
  7107. conn->status_code = 200;
  7108. conn->must_close = 1;
  7109. gmt_time_string(date, sizeof(date), &curtime);
  7110. mg_printf(conn,
  7111. "HTTP/1.1 200 OK\r\n"
  7112. "Date: %s\r\n"
  7113. /* TODO: "Cache-Control" (?) */
  7114. "Connection: %s\r\n"
  7115. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7116. "PROPFIND, MKCOL\r\n"
  7117. "DAV: 1\r\n\r\n",
  7118. date,
  7119. suggest_connection_header(conn));
  7120. }
  7121. /* Writes PROPFIND properties for a collection element */
  7122. static void
  7123. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7124. {
  7125. char mtime[64];
  7126. if (conn == NULL || uri == NULL || filep == NULL) {
  7127. return;
  7128. }
  7129. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7130. conn->num_bytes_sent +=
  7131. mg_printf(conn,
  7132. "<d:response>"
  7133. "<d:href>%s</d:href>"
  7134. "<d:propstat>"
  7135. "<d:prop>"
  7136. "<d:resourcetype>%s</d:resourcetype>"
  7137. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7138. "<d:getlastmodified>%s</d:getlastmodified>"
  7139. "</d:prop>"
  7140. "<d:status>HTTP/1.1 200 OK</d:status>"
  7141. "</d:propstat>"
  7142. "</d:response>\n",
  7143. uri,
  7144. filep->is_directory ? "<d:collection/>" : "",
  7145. filep->size,
  7146. mtime);
  7147. }
  7148. static void
  7149. print_dav_dir_entry(struct de *de, void *data)
  7150. {
  7151. char href[PATH_MAX];
  7152. char href_encoded[PATH_MAX];
  7153. int truncated;
  7154. struct mg_connection *conn = (struct mg_connection *)data;
  7155. if (!de || !conn) {
  7156. return;
  7157. }
  7158. mg_snprintf(conn,
  7159. &truncated,
  7160. href,
  7161. sizeof(href),
  7162. "%s%s",
  7163. conn->request_info.local_uri,
  7164. de->file_name);
  7165. if (!truncated) {
  7166. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  7167. print_props(conn, href_encoded, &de->file);
  7168. }
  7169. }
  7170. static void
  7171. handle_propfind(struct mg_connection *conn,
  7172. const char *path,
  7173. struct file *filep)
  7174. {
  7175. const char *depth = mg_get_header(conn, "Depth");
  7176. char date[64];
  7177. time_t curtime = time(NULL);
  7178. gmt_time_string(date, sizeof(date), &curtime);
  7179. if (!conn || !path || !filep || !conn->ctx) {
  7180. return;
  7181. }
  7182. conn->must_close = 1;
  7183. conn->status_code = 207;
  7184. mg_printf(conn,
  7185. "HTTP/1.1 207 Multi-Status\r\n"
  7186. "Date: %s\r\n",
  7187. date);
  7188. send_static_cache_header(conn);
  7189. mg_printf(conn,
  7190. "Connection: %s\r\n"
  7191. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7192. suggest_connection_header(conn));
  7193. conn->num_bytes_sent +=
  7194. mg_printf(conn,
  7195. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7196. "<d:multistatus xmlns:d='DAV:'>\n");
  7197. /* Print properties for the requested resource itself */
  7198. print_props(conn, conn->request_info.local_uri, filep);
  7199. /* If it is a directory, print directory entries too if Depth is not 0 */
  7200. if (filep && filep->is_directory
  7201. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7202. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7203. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7204. }
  7205. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7206. }
  7207. #endif
  7208. void
  7209. mg_lock_connection(struct mg_connection *conn)
  7210. {
  7211. if (conn) {
  7212. (void)pthread_mutex_lock(&conn->mutex);
  7213. }
  7214. }
  7215. void
  7216. mg_unlock_connection(struct mg_connection *conn)
  7217. {
  7218. if (conn) {
  7219. (void)pthread_mutex_unlock(&conn->mutex);
  7220. }
  7221. }
  7222. void
  7223. mg_lock_context(struct mg_context *ctx)
  7224. {
  7225. if (ctx) {
  7226. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7227. }
  7228. }
  7229. void
  7230. mg_unlock_context(struct mg_context *ctx)
  7231. {
  7232. if (ctx) {
  7233. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7234. }
  7235. }
  7236. #if defined(USE_TIMERS)
  7237. #include "timer.inl"
  7238. #endif /* USE_TIMERS */
  7239. #ifdef USE_LUA
  7240. #include "mod_lua.inl"
  7241. #endif /* USE_LUA */
  7242. #ifdef USE_DUKTAPE
  7243. #include "mod_duktape.inl"
  7244. #endif /* USE_DUKTAPE */
  7245. #if defined(USE_WEBSOCKET)
  7246. /* START OF SHA-1 code
  7247. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7248. #define SHA1HANDSOFF
  7249. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7250. *
  7251. * #if defined(__sun)
  7252. * #include "solarisfixes.h"
  7253. * #endif
  7254. */
  7255. static int
  7256. is_big_endian(void)
  7257. {
  7258. static const int n = 1;
  7259. return ((char *)&n)[0] == 0;
  7260. }
  7261. union char64long16 {
  7262. unsigned char c[64];
  7263. uint32_t l[16];
  7264. };
  7265. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7266. static uint32_t
  7267. blk0(union char64long16 *block, int i)
  7268. {
  7269. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7270. if (!is_big_endian()) {
  7271. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7272. | (rol(block->l[i], 8) & 0x00FF00FF);
  7273. }
  7274. return block->l[i];
  7275. }
  7276. #define blk(i) \
  7277. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7278. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7279. 1))
  7280. #define R0(v, w, x, y, z, i) \
  7281. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7282. w = rol(w, 30);
  7283. #define R1(v, w, x, y, z, i) \
  7284. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7285. w = rol(w, 30);
  7286. #define R2(v, w, x, y, z, i) \
  7287. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7288. w = rol(w, 30);
  7289. #define R3(v, w, x, y, z, i) \
  7290. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7291. w = rol(w, 30);
  7292. #define R4(v, w, x, y, z, i) \
  7293. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7294. w = rol(w, 30);
  7295. typedef struct {
  7296. uint32_t state[5];
  7297. uint32_t count[2];
  7298. unsigned char buffer[64];
  7299. } SHA1_CTX;
  7300. static void
  7301. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7302. {
  7303. uint32_t a, b, c, d, e;
  7304. union char64long16 block[1];
  7305. memcpy(block, buffer, 64);
  7306. a = state[0];
  7307. b = state[1];
  7308. c = state[2];
  7309. d = state[3];
  7310. e = state[4];
  7311. R0(a, b, c, d, e, 0);
  7312. R0(e, a, b, c, d, 1);
  7313. R0(d, e, a, b, c, 2);
  7314. R0(c, d, e, a, b, 3);
  7315. R0(b, c, d, e, a, 4);
  7316. R0(a, b, c, d, e, 5);
  7317. R0(e, a, b, c, d, 6);
  7318. R0(d, e, a, b, c, 7);
  7319. R0(c, d, e, a, b, 8);
  7320. R0(b, c, d, e, a, 9);
  7321. R0(a, b, c, d, e, 10);
  7322. R0(e, a, b, c, d, 11);
  7323. R0(d, e, a, b, c, 12);
  7324. R0(c, d, e, a, b, 13);
  7325. R0(b, c, d, e, a, 14);
  7326. R0(a, b, c, d, e, 15);
  7327. R1(e, a, b, c, d, 16);
  7328. R1(d, e, a, b, c, 17);
  7329. R1(c, d, e, a, b, 18);
  7330. R1(b, c, d, e, a, 19);
  7331. R2(a, b, c, d, e, 20);
  7332. R2(e, a, b, c, d, 21);
  7333. R2(d, e, a, b, c, 22);
  7334. R2(c, d, e, a, b, 23);
  7335. R2(b, c, d, e, a, 24);
  7336. R2(a, b, c, d, e, 25);
  7337. R2(e, a, b, c, d, 26);
  7338. R2(d, e, a, b, c, 27);
  7339. R2(c, d, e, a, b, 28);
  7340. R2(b, c, d, e, a, 29);
  7341. R2(a, b, c, d, e, 30);
  7342. R2(e, a, b, c, d, 31);
  7343. R2(d, e, a, b, c, 32);
  7344. R2(c, d, e, a, b, 33);
  7345. R2(b, c, d, e, a, 34);
  7346. R2(a, b, c, d, e, 35);
  7347. R2(e, a, b, c, d, 36);
  7348. R2(d, e, a, b, c, 37);
  7349. R2(c, d, e, a, b, 38);
  7350. R2(b, c, d, e, a, 39);
  7351. R3(a, b, c, d, e, 40);
  7352. R3(e, a, b, c, d, 41);
  7353. R3(d, e, a, b, c, 42);
  7354. R3(c, d, e, a, b, 43);
  7355. R3(b, c, d, e, a, 44);
  7356. R3(a, b, c, d, e, 45);
  7357. R3(e, a, b, c, d, 46);
  7358. R3(d, e, a, b, c, 47);
  7359. R3(c, d, e, a, b, 48);
  7360. R3(b, c, d, e, a, 49);
  7361. R3(a, b, c, d, e, 50);
  7362. R3(e, a, b, c, d, 51);
  7363. R3(d, e, a, b, c, 52);
  7364. R3(c, d, e, a, b, 53);
  7365. R3(b, c, d, e, a, 54);
  7366. R3(a, b, c, d, e, 55);
  7367. R3(e, a, b, c, d, 56);
  7368. R3(d, e, a, b, c, 57);
  7369. R3(c, d, e, a, b, 58);
  7370. R3(b, c, d, e, a, 59);
  7371. R4(a, b, c, d, e, 60);
  7372. R4(e, a, b, c, d, 61);
  7373. R4(d, e, a, b, c, 62);
  7374. R4(c, d, e, a, b, 63);
  7375. R4(b, c, d, e, a, 64);
  7376. R4(a, b, c, d, e, 65);
  7377. R4(e, a, b, c, d, 66);
  7378. R4(d, e, a, b, c, 67);
  7379. R4(c, d, e, a, b, 68);
  7380. R4(b, c, d, e, a, 69);
  7381. R4(a, b, c, d, e, 70);
  7382. R4(e, a, b, c, d, 71);
  7383. R4(d, e, a, b, c, 72);
  7384. R4(c, d, e, a, b, 73);
  7385. R4(b, c, d, e, a, 74);
  7386. R4(a, b, c, d, e, 75);
  7387. R4(e, a, b, c, d, 76);
  7388. R4(d, e, a, b, c, 77);
  7389. R4(c, d, e, a, b, 78);
  7390. R4(b, c, d, e, a, 79);
  7391. state[0] += a;
  7392. state[1] += b;
  7393. state[2] += c;
  7394. state[3] += d;
  7395. state[4] += e;
  7396. a = b = c = d = e = 0;
  7397. memset(block, '\0', sizeof(block));
  7398. }
  7399. static void
  7400. SHA1Init(SHA1_CTX *context)
  7401. {
  7402. context->state[0] = 0x67452301;
  7403. context->state[1] = 0xEFCDAB89;
  7404. context->state[2] = 0x98BADCFE;
  7405. context->state[3] = 0x10325476;
  7406. context->state[4] = 0xC3D2E1F0;
  7407. context->count[0] = context->count[1] = 0;
  7408. }
  7409. static void
  7410. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7411. {
  7412. uint32_t i, j;
  7413. j = context->count[0];
  7414. if ((context->count[0] += len << 3) < j) {
  7415. context->count[1]++;
  7416. }
  7417. context->count[1] += (len >> 29);
  7418. j = (j >> 3) & 63;
  7419. if ((j + len) > 63) {
  7420. memcpy(&context->buffer[j], data, (i = 64 - j));
  7421. SHA1Transform(context->state, context->buffer);
  7422. for (; i + 63 < len; i += 64) {
  7423. SHA1Transform(context->state, &data[i]);
  7424. }
  7425. j = 0;
  7426. } else
  7427. i = 0;
  7428. memcpy(&context->buffer[j], &data[i], len - i);
  7429. }
  7430. static void
  7431. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7432. {
  7433. unsigned i;
  7434. unsigned char finalcount[8], c;
  7435. for (i = 0; i < 8; i++) {
  7436. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7437. >> ((3 - (i & 3)) * 8)) & 255);
  7438. }
  7439. c = 0200;
  7440. SHA1Update(context, &c, 1);
  7441. while ((context->count[0] & 504) != 448) {
  7442. c = 0000;
  7443. SHA1Update(context, &c, 1);
  7444. }
  7445. SHA1Update(context, finalcount, 8);
  7446. for (i = 0; i < 20; i++) {
  7447. digest[i] = (unsigned char)((context->state[i >> 2]
  7448. >> ((3 - (i & 3)) * 8)) & 255);
  7449. }
  7450. memset(context, '\0', sizeof(*context));
  7451. memset(&finalcount, '\0', sizeof(finalcount));
  7452. }
  7453. /* END OF SHA1 CODE */
  7454. static int
  7455. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7456. {
  7457. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7458. const char *protocol = NULL;
  7459. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7460. SHA1_CTX sha_ctx;
  7461. int truncated;
  7462. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7463. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7464. if (truncated) {
  7465. conn->must_close = 1;
  7466. return 0;
  7467. }
  7468. SHA1Init(&sha_ctx);
  7469. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7470. SHA1Final((unsigned char *)sha, &sha_ctx);
  7471. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7472. mg_printf(conn,
  7473. "HTTP/1.1 101 Switching Protocols\r\n"
  7474. "Upgrade: websocket\r\n"
  7475. "Connection: Upgrade\r\n"
  7476. "Sec-WebSocket-Accept: %s\r\n",
  7477. b64_sha);
  7478. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7479. if (protocol) {
  7480. /* The protocol is a comma seperated list of names. */
  7481. /* The server must only return one value from this list. */
  7482. /* First check if it is a list or just a single value. */
  7483. const char *sep = strchr(protocol, ',');
  7484. if (sep == NULL) {
  7485. /* Just a single protocol -> accept it. */
  7486. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7487. } else {
  7488. /* Multiple protocols -> accept the first one. */
  7489. /* This is just a quick fix if the client offers multiple
  7490. * protocols. In order to get the behavior intended by
  7491. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7492. * required to have a list of websocket subprotocols accepted
  7493. * by the server. Then the server must either select a subprotocol
  7494. * supported by client and server, or the server has to abort the
  7495. * handshake by not returning a Sec-Websocket-Protocol header if
  7496. * no subprotocol is acceptable.
  7497. */
  7498. mg_printf(conn,
  7499. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7500. (int)(sep - protocol),
  7501. protocol);
  7502. }
  7503. /* TODO: Real subprotocol negotiation instead of just taking the first
  7504. * websocket subprotocol suggested by the client. */
  7505. } else {
  7506. mg_printf(conn, "%s", "\r\n");
  7507. }
  7508. return 1;
  7509. }
  7510. static void
  7511. read_websocket(struct mg_connection *conn,
  7512. mg_websocket_data_handler ws_data_handler,
  7513. void *callback_data)
  7514. {
  7515. /* Pointer to the beginning of the portion of the incoming websocket
  7516. * message queue.
  7517. * The original websocket upgrade request is never removed, so the queue
  7518. * begins after it. */
  7519. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7520. int n, error, exit_by_callback;
  7521. /* body_len is the length of the entire queue in bytes
  7522. * len is the length of the current message
  7523. * data_len is the length of the current message's data payload
  7524. * header_len is the length of the current message's header */
  7525. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7526. /* "The masking key is a 32-bit value chosen at random by the client."
  7527. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7528. */
  7529. unsigned char mask[4];
  7530. /* data points to the place where the message is stored when passed to
  7531. * the
  7532. * websocket_data callback. This is either mem on the stack, or a
  7533. * dynamically allocated buffer if it is too large. */
  7534. char mem[4096];
  7535. char *data = mem;
  7536. unsigned char mop; /* mask flag and opcode */
  7537. double timeout = -1.0;
  7538. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7539. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7540. }
  7541. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7542. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7543. }
  7544. mg_set_thread_name("wsock");
  7545. /* Loop continuously, reading messages from the socket, invoking the
  7546. * callback, and waiting repeatedly until an error occurs. */
  7547. while (!conn->ctx->stop_flag) {
  7548. header_len = 0;
  7549. assert(conn->data_len >= conn->request_len);
  7550. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7551. len = buf[1] & 127;
  7552. mask_len = buf[1] & 128 ? 4 : 0;
  7553. if (len < 126 && body_len >= mask_len) {
  7554. data_len = len;
  7555. header_len = 2 + mask_len;
  7556. } else if (len == 126 && body_len >= 4 + mask_len) {
  7557. header_len = 4 + mask_len;
  7558. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7559. } else if (body_len >= 10 + mask_len) {
  7560. header_len = 10 + mask_len;
  7561. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7562. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7563. }
  7564. }
  7565. if (header_len > 0 && body_len >= header_len) {
  7566. /* Allocate space to hold websocket payload */
  7567. data = mem;
  7568. if (data_len > sizeof(mem)) {
  7569. data = (char *)mg_malloc(data_len);
  7570. if (data == NULL) {
  7571. /* Allocation failed, exit the loop and then close the
  7572. * connection */
  7573. mg_cry(conn, "websocket out of memory; closing connection");
  7574. break;
  7575. }
  7576. }
  7577. /* Copy the mask before we shift the queue and destroy it */
  7578. if (mask_len > 0) {
  7579. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7580. } else {
  7581. memset(mask, 0, sizeof(mask));
  7582. }
  7583. /* Read frame payload from the first message in the queue into
  7584. * data and advance the queue by moving the memory in place. */
  7585. assert(body_len >= header_len);
  7586. if (data_len + header_len > body_len) {
  7587. mop = buf[0]; /* current mask and opcode */
  7588. /* Overflow case */
  7589. len = body_len - header_len;
  7590. memcpy(data, buf + header_len, len);
  7591. error = 0;
  7592. while (len < data_len) {
  7593. n = pull(
  7594. NULL, conn, data + len, (int)(data_len - len), timeout);
  7595. if (n <= 0) {
  7596. error = 1;
  7597. break;
  7598. }
  7599. len += (size_t)n;
  7600. }
  7601. if (error) {
  7602. mg_cry(conn, "Websocket pull failed; closing connection");
  7603. break;
  7604. }
  7605. conn->data_len = conn->request_len;
  7606. } else {
  7607. mop = buf[0]; /* current mask and opcode, overwritten by
  7608. * memmove() */
  7609. /* Length of the message being read at the front of the
  7610. * queue */
  7611. len = data_len + header_len;
  7612. /* Copy the data payload into the data pointer for the
  7613. * callback */
  7614. memcpy(data, buf + header_len, data_len);
  7615. /* Move the queue forward len bytes */
  7616. memmove(buf, buf + len, body_len - len);
  7617. /* Mark the queue as advanced */
  7618. conn->data_len -= (int)len;
  7619. }
  7620. /* Apply mask if necessary */
  7621. if (mask_len > 0) {
  7622. for (i = 0; i < data_len; ++i) {
  7623. data[i] ^= mask[i & 3];
  7624. }
  7625. }
  7626. /* Exit the loop if callback signals to exit (server side),
  7627. * or "connection close" opcode received (client side). */
  7628. exit_by_callback = 0;
  7629. if ((ws_data_handler != NULL)
  7630. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7631. exit_by_callback = 1;
  7632. }
  7633. if (data != mem) {
  7634. mg_free(data);
  7635. }
  7636. if (exit_by_callback
  7637. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7638. /* Opcode == 8, connection close */
  7639. break;
  7640. }
  7641. /* Not breaking the loop, process next websocket frame. */
  7642. } else {
  7643. /* Read from the socket into the next available location in the
  7644. * message queue. */
  7645. if ((n = pull(NULL,
  7646. conn,
  7647. conn->buf + conn->data_len,
  7648. conn->buf_size - conn->data_len,
  7649. timeout)) <= 0) {
  7650. /* Error, no bytes read */
  7651. break;
  7652. }
  7653. conn->data_len += n;
  7654. }
  7655. }
  7656. mg_set_thread_name("worker");
  7657. }
  7658. static int
  7659. mg_websocket_write_exec(struct mg_connection *conn,
  7660. int opcode,
  7661. const char *data,
  7662. size_t dataLen,
  7663. uint32_t masking_key)
  7664. {
  7665. unsigned char header[14];
  7666. size_t headerLen = 1;
  7667. int retval = -1;
  7668. header[0] = 0x80 + (opcode & 0xF);
  7669. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7670. if (dataLen < 126) {
  7671. /* inline 7-bit length field */
  7672. header[1] = (unsigned char)dataLen;
  7673. headerLen = 2;
  7674. } else if (dataLen <= 0xFFFF) {
  7675. /* 16-bit length field */
  7676. header[1] = 126;
  7677. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7678. headerLen = 4;
  7679. } else {
  7680. /* 64-bit length field */
  7681. header[1] = 127;
  7682. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7683. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7684. headerLen = 10;
  7685. }
  7686. if (masking_key) {
  7687. /* add mask */
  7688. header[1] |= 0x80;
  7689. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7690. headerLen += 4;
  7691. }
  7692. /* Note that POSIX/Winsock's send() is threadsafe
  7693. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7694. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7695. * push(), although that is only a problem if the packet is large or
  7696. * outgoing buffer is full). */
  7697. (void)mg_lock_connection(conn);
  7698. retval = mg_write(conn, header, headerLen);
  7699. if (dataLen > 0) {
  7700. retval = mg_write(conn, data, dataLen);
  7701. }
  7702. mg_unlock_connection(conn);
  7703. return retval;
  7704. }
  7705. int
  7706. mg_websocket_write(struct mg_connection *conn,
  7707. int opcode,
  7708. const char *data,
  7709. size_t dataLen)
  7710. {
  7711. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7712. }
  7713. static void
  7714. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7715. {
  7716. size_t i = 0;
  7717. i = 0;
  7718. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7719. /* Convert in 32 bit words, if data is 4 byte aligned */
  7720. while (i < (in_len - 3)) {
  7721. *(uint32_t *)(void *)(out + i) =
  7722. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7723. i += 4;
  7724. }
  7725. }
  7726. if (i != in_len) {
  7727. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7728. while (i < in_len) {
  7729. *(uint8_t *)(void *)(out + i) =
  7730. *(uint8_t *)(void *)(in + i)
  7731. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7732. i++;
  7733. }
  7734. }
  7735. }
  7736. int
  7737. mg_websocket_client_write(struct mg_connection *conn,
  7738. int opcode,
  7739. const char *data,
  7740. size_t dataLen)
  7741. {
  7742. int retval = -1;
  7743. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7744. uint32_t masking_key = (uint32_t)get_random();
  7745. if (masked_data == NULL) {
  7746. /* Return -1 in an error case */
  7747. mg_cry(conn,
  7748. "Cannot allocate buffer for masked websocket response: "
  7749. "Out of memory");
  7750. return -1;
  7751. }
  7752. mask_data(data, dataLen, masking_key, masked_data);
  7753. retval = mg_websocket_write_exec(
  7754. conn, opcode, masked_data, dataLen, masking_key);
  7755. mg_free(masked_data);
  7756. return retval;
  7757. }
  7758. static void
  7759. handle_websocket_request(struct mg_connection *conn,
  7760. const char *path,
  7761. int is_callback_resource,
  7762. mg_websocket_connect_handler ws_connect_handler,
  7763. mg_websocket_ready_handler ws_ready_handler,
  7764. mg_websocket_data_handler ws_data_handler,
  7765. mg_websocket_close_handler ws_close_handler,
  7766. void *cbData)
  7767. {
  7768. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7769. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7770. int lua_websock = 0;
  7771. #if !defined(USE_LUA)
  7772. (void)path;
  7773. #endif
  7774. /* Step 1: Check websocket protocol version. */
  7775. /* Step 1.1: Check Sec-WebSocket-Key. */
  7776. if (!websock_key) {
  7777. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  7778. * requires a Sec-WebSocket-Key header.
  7779. */
  7780. /* It could be the hixie draft version
  7781. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  7782. */
  7783. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  7784. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  7785. char key3[8];
  7786. if ((key1 != NULL) && (key2 != NULL)) {
  7787. /* This version uses 8 byte body data in a GET request */
  7788. conn->content_len = 8;
  7789. if (8 == mg_read(conn, key3, 8)) {
  7790. /* This is the hixie version */
  7791. send_http_error(conn,
  7792. 426,
  7793. "%s",
  7794. "Protocol upgrade to RFC 6455 required");
  7795. return;
  7796. }
  7797. }
  7798. /* This is an unknown version */
  7799. send_http_error(conn, 400, "%s", "Malformed websocket request");
  7800. return;
  7801. }
  7802. /* Step 1.2: Check websocket protocol version. */
  7803. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  7804. if (version == NULL || strcmp(version, "13") != 0) {
  7805. /* Reject wrong versions */
  7806. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7807. return;
  7808. }
  7809. /* Step 1.3: Could check for "Host", but we do not really nead this
  7810. * value for anything, so just ignore it. */
  7811. /* Step 2: If a callback is responsible, call it. */
  7812. if (is_callback_resource) {
  7813. if (ws_connect_handler != NULL
  7814. && ws_connect_handler(conn, cbData) != 0) {
  7815. /* C callback has returned non-zero, do not proceed with
  7816. * handshake.
  7817. */
  7818. /* Note that C callbacks are no longer called when Lua is
  7819. * responsible, so C can no longer filter callbacks for Lua. */
  7820. return;
  7821. }
  7822. }
  7823. #if defined(USE_LUA)
  7824. /* Step 3: No callback. Check if Lua is responsible. */
  7825. else {
  7826. /* Step 3.1: Check if Lua is responsible. */
  7827. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7828. lua_websock =
  7829. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7830. strlen(
  7831. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7832. path);
  7833. }
  7834. if (lua_websock) {
  7835. /* Step 3.2: Lua is responsible: call it. */
  7836. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7837. if (!conn->lua_websocket_state) {
  7838. /* Lua rejected the new client */
  7839. return;
  7840. }
  7841. }
  7842. }
  7843. #endif
  7844. /* Step 4: Check if there is a responsible websocket handler. */
  7845. if (!is_callback_resource && !lua_websock) {
  7846. /* There is no callback, an Lua is not responsible either. */
  7847. /* Reply with a 404 Not Found or with nothing at all?
  7848. * TODO (mid): check the websocket standards, how to reply to
  7849. * requests to invalid websocket addresses. */
  7850. send_http_error(conn, 404, "%s", "Not found");
  7851. return;
  7852. }
  7853. /* Step 5: The websocket connection has been accepted */
  7854. if (!send_websocket_handshake(conn, websock_key)) {
  7855. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7856. return;
  7857. }
  7858. /* Step 6: Call the ready handler */
  7859. if (is_callback_resource) {
  7860. if (ws_ready_handler != NULL) {
  7861. ws_ready_handler(conn, cbData);
  7862. }
  7863. #if defined(USE_LUA)
  7864. } else if (lua_websock) {
  7865. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7866. /* the ready handler returned false */
  7867. return;
  7868. }
  7869. #endif
  7870. }
  7871. /* Step 7: Enter the read loop */
  7872. if (is_callback_resource) {
  7873. read_websocket(conn, ws_data_handler, cbData);
  7874. #if defined(USE_LUA)
  7875. } else if (lua_websock) {
  7876. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7877. #endif
  7878. }
  7879. /* Step 8: Call the close handler */
  7880. if (ws_close_handler) {
  7881. ws_close_handler(conn, cbData);
  7882. }
  7883. }
  7884. static int
  7885. is_websocket_protocol(const struct mg_connection *conn)
  7886. {
  7887. const char *upgrade, *connection;
  7888. /* A websocket protocoll has the following HTTP headers:
  7889. *
  7890. * Connection: Upgrade
  7891. * Upgrade: Websocket
  7892. */
  7893. upgrade = mg_get_header(conn, "Upgrade");
  7894. if (upgrade == NULL) {
  7895. return 0; /* fail early, don't waste time checking other header
  7896. * fields
  7897. */
  7898. }
  7899. if (!mg_strcasestr(upgrade, "websocket")) {
  7900. return 0;
  7901. }
  7902. connection = mg_get_header(conn, "Connection");
  7903. if (connection == NULL) {
  7904. return 0;
  7905. }
  7906. if (!mg_strcasestr(connection, "upgrade")) {
  7907. return 0;
  7908. }
  7909. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  7910. * "Sec-WebSocket-Version" are also required.
  7911. * Don't check them here, since even an unsupported websocket protocol
  7912. * request still IS a websocket request (in contrast to a standard HTTP
  7913. * request). It will fail later in handle_websocket_request.
  7914. */
  7915. return 1;
  7916. }
  7917. #endif /* !USE_WEBSOCKET */
  7918. static int
  7919. isbyte(int n)
  7920. {
  7921. return n >= 0 && n <= 255;
  7922. }
  7923. static int
  7924. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7925. {
  7926. int n, a, b, c, d, slash = 32, len = 0;
  7927. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7928. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7929. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7930. && slash < 33) {
  7931. len = n;
  7932. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7933. | (uint32_t)d;
  7934. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7935. }
  7936. return len;
  7937. }
  7938. static int
  7939. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7940. {
  7941. int throttle = 0;
  7942. struct vec vec, val;
  7943. uint32_t net, mask;
  7944. char mult;
  7945. double v;
  7946. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7947. mult = ',';
  7948. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7949. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7950. && mult != ',')) {
  7951. continue;
  7952. }
  7953. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7954. : 1;
  7955. if (vec.len == 1 && vec.ptr[0] == '*') {
  7956. throttle = (int)v;
  7957. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7958. if ((remote_ip & mask) == net) {
  7959. throttle = (int)v;
  7960. }
  7961. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7962. throttle = (int)v;
  7963. }
  7964. }
  7965. return throttle;
  7966. }
  7967. static uint32_t
  7968. get_remote_ip(const struct mg_connection *conn)
  7969. {
  7970. if (!conn) {
  7971. return 0;
  7972. }
  7973. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  7974. }
  7975. /* The mg_upload function is superseeded by mg_handle_form_request. */
  7976. #include "handle_form.inl"
  7977. #if defined(MG_LEGACY_INTERFACE)
  7978. /* Implement the deprecated mg_upload function by calling the new
  7979. * mg_handle_form_request function. While mg_upload could only handle
  7980. * HTML forms sent as POST request in multipart/form-data format
  7981. * containing only file input elements, mg_handle_form_request can
  7982. * handle all form input elements and all standard request methods. */
  7983. struct mg_upload_user_data {
  7984. struct mg_connection *conn;
  7985. const char *destination_dir;
  7986. int num_uploaded_files;
  7987. };
  7988. /* Helper function for deprecated mg_upload. */
  7989. static int
  7990. mg_upload_field_found(const char *key,
  7991. const char *filename,
  7992. char *path,
  7993. size_t pathlen,
  7994. void *user_data)
  7995. {
  7996. int truncated = 0;
  7997. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7998. (void)key;
  7999. if (!filename) {
  8000. mg_cry(fud->conn, "%s: No filename set", __func__);
  8001. return FORM_FIELD_STORAGE_ABORT;
  8002. }
  8003. mg_snprintf(fud->conn,
  8004. &truncated,
  8005. path,
  8006. pathlen - 1,
  8007. "%s/%s",
  8008. fud->destination_dir,
  8009. filename);
  8010. if (!truncated) {
  8011. mg_cry(fud->conn, "%s: File path too long", __func__);
  8012. return FORM_FIELD_STORAGE_ABORT;
  8013. }
  8014. return FORM_FIELD_STORAGE_STORE;
  8015. }
  8016. /* Helper function for deprecated mg_upload. */
  8017. static int
  8018. mg_upload_field_get(const char *key,
  8019. const char *value,
  8020. size_t value_size,
  8021. void *user_data)
  8022. {
  8023. /* Function should never be called */
  8024. (void)key;
  8025. (void)value;
  8026. (void)value_size;
  8027. (void)user_data;
  8028. return 0;
  8029. }
  8030. /* Helper function for deprecated mg_upload. */
  8031. static int
  8032. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8033. {
  8034. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8035. (void)file_size;
  8036. fud->num_uploaded_files++;
  8037. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8038. return 0;
  8039. }
  8040. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8041. int
  8042. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8043. {
  8044. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8045. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8046. mg_upload_field_get,
  8047. mg_upload_field_stored,
  8048. 0};
  8049. int ret;
  8050. fdh.user_data = (void *)&fud;
  8051. ret = mg_handle_form_request(conn, &fdh);
  8052. if (ret < 0) {
  8053. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8054. }
  8055. return fud.num_uploaded_files;
  8056. }
  8057. #endif
  8058. static int
  8059. get_first_ssl_listener_index(const struct mg_context *ctx)
  8060. {
  8061. unsigned int i;
  8062. int idx = -1;
  8063. if (ctx) {
  8064. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8065. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8066. }
  8067. }
  8068. return idx;
  8069. }
  8070. static void
  8071. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8072. {
  8073. char host[1025];
  8074. const char *host_header;
  8075. size_t hostlen;
  8076. host_header = mg_get_header(conn, "Host");
  8077. hostlen = sizeof(host);
  8078. if (host_header != NULL) {
  8079. char *pos;
  8080. mg_strlcpy(host, host_header, hostlen);
  8081. host[hostlen - 1] = '\0';
  8082. pos = strchr(host, ':');
  8083. if (pos != NULL) {
  8084. *pos = '\0';
  8085. }
  8086. } else {
  8087. /* Cannot get host from the Host: header.
  8088. * Fallback to our IP address. */
  8089. if (conn) {
  8090. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8091. }
  8092. }
  8093. /* Send host, port, uri and (if it exists) ?query_string */
  8094. if (conn) {
  8095. mg_printf(conn,
  8096. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8097. host,
  8098. (int)ntohs(
  8099. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  8100. conn->request_info.local_uri,
  8101. (conn->request_info.query_string == NULL) ? "" : "?",
  8102. (conn->request_info.query_string == NULL)
  8103. ? ""
  8104. : conn->request_info.query_string);
  8105. }
  8106. }
  8107. static void
  8108. mg_set_handler_type(struct mg_context *ctx,
  8109. const char *uri,
  8110. int handler_type,
  8111. int is_delete_request,
  8112. mg_request_handler handler,
  8113. mg_websocket_connect_handler connect_handler,
  8114. mg_websocket_ready_handler ready_handler,
  8115. mg_websocket_data_handler data_handler,
  8116. mg_websocket_close_handler close_handler,
  8117. mg_authorization_handler auth_handler,
  8118. void *cbdata)
  8119. {
  8120. struct mg_handler_info *tmp_rh, **lastref;
  8121. size_t urilen = strlen(uri);
  8122. if (handler_type == WEBSOCKET_HANDLER) {
  8123. /* assert(handler == NULL); */
  8124. /* assert(is_delete_request || connect_handler!=NULL ||
  8125. * ready_handler!=NULL || data_handler!=NULL ||
  8126. * close_handler!=NULL);
  8127. */
  8128. /* assert(auth_handler == NULL); */
  8129. if (handler != NULL) {
  8130. return;
  8131. }
  8132. if (!is_delete_request && connect_handler == NULL
  8133. && ready_handler == NULL
  8134. && data_handler == NULL
  8135. && close_handler == NULL) {
  8136. return;
  8137. }
  8138. if (auth_handler != NULL) {
  8139. return;
  8140. }
  8141. } else if (handler_type == REQUEST_HANDLER) {
  8142. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8143. * data_handler==NULL && close_handler==NULL); */
  8144. /* assert(is_delete_request || (handler!=NULL));
  8145. */
  8146. /* assert(auth_handler == NULL); */
  8147. if (connect_handler != NULL || ready_handler != NULL
  8148. || data_handler != NULL
  8149. || close_handler != NULL) {
  8150. return;
  8151. }
  8152. if (!is_delete_request && (handler == NULL)) {
  8153. return;
  8154. }
  8155. if (auth_handler != NULL) {
  8156. return;
  8157. }
  8158. } else { /* AUTH_HANDLER */
  8159. /* assert(handler == NULL); */
  8160. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8161. * data_handler==NULL && close_handler==NULL); */
  8162. /* assert(auth_handler != NULL); */
  8163. if (handler != NULL) {
  8164. return;
  8165. }
  8166. if (connect_handler != NULL || ready_handler != NULL
  8167. || data_handler != NULL
  8168. || close_handler != NULL) {
  8169. return;
  8170. }
  8171. if (!is_delete_request && (auth_handler == NULL)) {
  8172. return;
  8173. }
  8174. }
  8175. if (!ctx) {
  8176. return;
  8177. }
  8178. mg_lock_context(ctx);
  8179. /* first try to find an existing handler */
  8180. lastref = &(ctx->handlers);
  8181. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8182. if (tmp_rh->handler_type == handler_type) {
  8183. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8184. if (!is_delete_request) {
  8185. /* update existing handler */
  8186. if (handler_type == REQUEST_HANDLER) {
  8187. tmp_rh->handler = handler;
  8188. } else if (handler_type == WEBSOCKET_HANDLER) {
  8189. tmp_rh->connect_handler = connect_handler;
  8190. tmp_rh->ready_handler = ready_handler;
  8191. tmp_rh->data_handler = data_handler;
  8192. tmp_rh->close_handler = close_handler;
  8193. } else { /* AUTH_HANDLER */
  8194. tmp_rh->auth_handler = auth_handler;
  8195. }
  8196. tmp_rh->cbdata = cbdata;
  8197. } else {
  8198. /* remove existing handler */
  8199. *lastref = tmp_rh->next;
  8200. mg_free(tmp_rh->uri);
  8201. mg_free(tmp_rh);
  8202. }
  8203. mg_unlock_context(ctx);
  8204. return;
  8205. }
  8206. }
  8207. lastref = &(tmp_rh->next);
  8208. }
  8209. if (is_delete_request) {
  8210. /* no handler to set, this was a remove request to a non-existing
  8211. * handler */
  8212. mg_unlock_context(ctx);
  8213. return;
  8214. }
  8215. tmp_rh =
  8216. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8217. if (tmp_rh == NULL) {
  8218. mg_unlock_context(ctx);
  8219. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8220. return;
  8221. }
  8222. tmp_rh->uri = mg_strdup(uri);
  8223. if (!tmp_rh->uri) {
  8224. mg_unlock_context(ctx);
  8225. mg_free(tmp_rh);
  8226. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8227. return;
  8228. }
  8229. tmp_rh->uri_len = urilen;
  8230. if (handler_type == REQUEST_HANDLER) {
  8231. tmp_rh->handler = handler;
  8232. } else if (handler_type == WEBSOCKET_HANDLER) {
  8233. tmp_rh->connect_handler = connect_handler;
  8234. tmp_rh->ready_handler = ready_handler;
  8235. tmp_rh->data_handler = data_handler;
  8236. tmp_rh->close_handler = close_handler;
  8237. } else { /* AUTH_HANDLER */
  8238. tmp_rh->auth_handler = auth_handler;
  8239. }
  8240. tmp_rh->cbdata = cbdata;
  8241. tmp_rh->handler_type = handler_type;
  8242. tmp_rh->next = NULL;
  8243. *lastref = tmp_rh;
  8244. mg_unlock_context(ctx);
  8245. }
  8246. void
  8247. mg_set_request_handler(struct mg_context *ctx,
  8248. const char *uri,
  8249. mg_request_handler handler,
  8250. void *cbdata)
  8251. {
  8252. mg_set_handler_type(ctx,
  8253. uri,
  8254. REQUEST_HANDLER,
  8255. handler == NULL,
  8256. handler,
  8257. NULL,
  8258. NULL,
  8259. NULL,
  8260. NULL,
  8261. NULL,
  8262. cbdata);
  8263. }
  8264. void
  8265. mg_set_websocket_handler(struct mg_context *ctx,
  8266. const char *uri,
  8267. mg_websocket_connect_handler connect_handler,
  8268. mg_websocket_ready_handler ready_handler,
  8269. mg_websocket_data_handler data_handler,
  8270. mg_websocket_close_handler close_handler,
  8271. void *cbdata)
  8272. {
  8273. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8274. && (data_handler == NULL)
  8275. && (close_handler == NULL);
  8276. mg_set_handler_type(ctx,
  8277. uri,
  8278. WEBSOCKET_HANDLER,
  8279. is_delete_request,
  8280. NULL,
  8281. connect_handler,
  8282. ready_handler,
  8283. data_handler,
  8284. close_handler,
  8285. NULL,
  8286. cbdata);
  8287. }
  8288. void
  8289. mg_set_auth_handler(struct mg_context *ctx,
  8290. const char *uri,
  8291. mg_request_handler handler,
  8292. void *cbdata)
  8293. {
  8294. mg_set_handler_type(ctx,
  8295. uri,
  8296. AUTH_HANDLER,
  8297. handler == NULL,
  8298. NULL,
  8299. NULL,
  8300. NULL,
  8301. NULL,
  8302. NULL,
  8303. handler,
  8304. cbdata);
  8305. }
  8306. static int
  8307. get_request_handler(struct mg_connection *conn,
  8308. int handler_type,
  8309. mg_request_handler *handler,
  8310. mg_websocket_connect_handler *connect_handler,
  8311. mg_websocket_ready_handler *ready_handler,
  8312. mg_websocket_data_handler *data_handler,
  8313. mg_websocket_close_handler *close_handler,
  8314. mg_authorization_handler *auth_handler,
  8315. void **cbdata)
  8316. {
  8317. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8318. if (request_info) {
  8319. const char *uri = request_info->local_uri;
  8320. size_t urilen = strlen(uri);
  8321. struct mg_handler_info *tmp_rh;
  8322. if (!conn || !conn->ctx) {
  8323. return 0;
  8324. }
  8325. mg_lock_context(conn->ctx);
  8326. /* first try for an exact match */
  8327. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8328. tmp_rh = tmp_rh->next) {
  8329. if (tmp_rh->handler_type == handler_type) {
  8330. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8331. if (handler_type == WEBSOCKET_HANDLER) {
  8332. *connect_handler = tmp_rh->connect_handler;
  8333. *ready_handler = tmp_rh->ready_handler;
  8334. *data_handler = tmp_rh->data_handler;
  8335. *close_handler = tmp_rh->close_handler;
  8336. } else if (handler_type == REQUEST_HANDLER) {
  8337. *handler = tmp_rh->handler;
  8338. } else { /* AUTH_HANDLER */
  8339. *auth_handler = tmp_rh->auth_handler;
  8340. }
  8341. *cbdata = tmp_rh->cbdata;
  8342. mg_unlock_context(conn->ctx);
  8343. return 1;
  8344. }
  8345. }
  8346. }
  8347. /* next try for a partial match, we will accept uri/something */
  8348. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8349. tmp_rh = tmp_rh->next) {
  8350. if (tmp_rh->handler_type == handler_type) {
  8351. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8352. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8353. if (handler_type == WEBSOCKET_HANDLER) {
  8354. *connect_handler = tmp_rh->connect_handler;
  8355. *ready_handler = tmp_rh->ready_handler;
  8356. *data_handler = tmp_rh->data_handler;
  8357. *close_handler = tmp_rh->close_handler;
  8358. } else if (handler_type == REQUEST_HANDLER) {
  8359. *handler = tmp_rh->handler;
  8360. } else { /* AUTH_HANDLER */
  8361. *auth_handler = tmp_rh->auth_handler;
  8362. }
  8363. *cbdata = tmp_rh->cbdata;
  8364. mg_unlock_context(conn->ctx);
  8365. return 1;
  8366. }
  8367. }
  8368. }
  8369. /* finally try for pattern match */
  8370. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8371. tmp_rh = tmp_rh->next) {
  8372. if (tmp_rh->handler_type == handler_type) {
  8373. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8374. if (handler_type == WEBSOCKET_HANDLER) {
  8375. *connect_handler = tmp_rh->connect_handler;
  8376. *ready_handler = tmp_rh->ready_handler;
  8377. *data_handler = tmp_rh->data_handler;
  8378. *close_handler = tmp_rh->close_handler;
  8379. } else if (handler_type == REQUEST_HANDLER) {
  8380. *handler = tmp_rh->handler;
  8381. } else { /* AUTH_HANDLER */
  8382. *auth_handler = tmp_rh->auth_handler;
  8383. }
  8384. *cbdata = tmp_rh->cbdata;
  8385. mg_unlock_context(conn->ctx);
  8386. return 1;
  8387. }
  8388. }
  8389. }
  8390. mg_unlock_context(conn->ctx);
  8391. }
  8392. return 0; /* none found */
  8393. }
  8394. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8395. static int
  8396. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8397. void *cbdata)
  8398. {
  8399. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8400. if (pcallbacks->websocket_connect) {
  8401. return pcallbacks->websocket_connect(conn);
  8402. }
  8403. /* No handler set - assume "OK" */
  8404. return 0;
  8405. }
  8406. static void
  8407. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8408. {
  8409. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8410. if (pcallbacks->websocket_ready) {
  8411. pcallbacks->websocket_ready(conn);
  8412. }
  8413. }
  8414. static int
  8415. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8416. int bits,
  8417. char *data,
  8418. size_t len,
  8419. void *cbdata)
  8420. {
  8421. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8422. if (pcallbacks->websocket_data) {
  8423. return pcallbacks->websocket_data(conn, bits, data, len);
  8424. }
  8425. /* No handler set - assume "OK" */
  8426. return 1;
  8427. }
  8428. #endif
  8429. /* This is the heart of the Civetweb's logic.
  8430. * This function is called when the request is read, parsed and validated,
  8431. * and Civetweb must decide what action to take: serve a file, or
  8432. * a directory, or call embedded function, etcetera. */
  8433. static void
  8434. handle_request(struct mg_connection *conn)
  8435. {
  8436. if (conn) {
  8437. struct mg_request_info *ri = &conn->request_info;
  8438. char path[PATH_MAX];
  8439. int uri_len, ssl_index;
  8440. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8441. is_put_or_delete_request = 0, is_callback_resource = 0;
  8442. int i;
  8443. struct file file = STRUCT_FILE_INITIALIZER;
  8444. mg_request_handler callback_handler = NULL;
  8445. mg_websocket_connect_handler ws_connect_handler = NULL;
  8446. mg_websocket_ready_handler ws_ready_handler = NULL;
  8447. mg_websocket_data_handler ws_data_handler = NULL;
  8448. mg_websocket_close_handler ws_close_handler = NULL;
  8449. void *callback_data = NULL;
  8450. mg_authorization_handler auth_handler = NULL;
  8451. void *auth_callback_data = NULL;
  8452. #if !defined(NO_FILES)
  8453. time_t curtime = time(NULL);
  8454. char date[64];
  8455. #endif
  8456. path[0] = 0;
  8457. if (!ri) {
  8458. return;
  8459. }
  8460. /* 1. get the request url */
  8461. /* 1.1. split into url and query string */
  8462. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8463. != NULL) {
  8464. *((char *)conn->request_info.query_string++) = '\0';
  8465. }
  8466. uri_len = (int)strlen(ri->local_uri);
  8467. /* 1.2. decode url (if config says so) */
  8468. if (should_decode_url(conn)) {
  8469. mg_url_decode(
  8470. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8471. }
  8472. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is
  8473. * not possible */
  8474. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8475. /* step 1. completed, the url is known now */
  8476. DEBUG_TRACE("URL: %s", ri->local_uri);
  8477. /* 2. do a https redirect, if required */
  8478. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8479. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8480. if (ssl_index >= 0) {
  8481. redirect_to_https_port(conn, ssl_index);
  8482. } else {
  8483. /* A http to https forward port has been specified,
  8484. * but no https port to forward to. */
  8485. send_http_error(conn,
  8486. 503,
  8487. "%s",
  8488. "Error: SSL forward not configured properly");
  8489. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8490. }
  8491. return;
  8492. }
  8493. /* 3. if this ip has limited speed, set it for this connection */
  8494. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8495. get_remote_ip(conn),
  8496. ri->local_uri);
  8497. /* 4. call a "handle everything" callback, if registered */
  8498. if (conn->ctx->callbacks.begin_request != NULL) {
  8499. /* Note that since V1.7 the "begin_request" function is called
  8500. * before an authorization check. If an authorization check is
  8501. * required, use a request_handler instead. */
  8502. i = conn->ctx->callbacks.begin_request(conn);
  8503. if (i > 0) {
  8504. /* callback already processed the request. Store the
  8505. return value as a status code for the access log. */
  8506. conn->status_code = i;
  8507. return;
  8508. } else if (i == 0) {
  8509. /* civetweb should process the request */
  8510. } else {
  8511. /* unspecified - may change with the next version */
  8512. return;
  8513. }
  8514. }
  8515. /* request not yet handled by a handler or redirect, so the request
  8516. * is processed here */
  8517. /* 5. interpret the url to find out how the request must be handled
  8518. */
  8519. /* 5.1. first test, if the request targets the regular http(s)://
  8520. * protocol namespace or the websocket ws(s):// protocol namespace.
  8521. */
  8522. is_websocket_request = is_websocket_protocol(conn);
  8523. /* 5.2. check if the request will be handled by a callback */
  8524. if (get_request_handler(conn,
  8525. is_websocket_request ? WEBSOCKET_HANDLER
  8526. : REQUEST_HANDLER,
  8527. &callback_handler,
  8528. &ws_connect_handler,
  8529. &ws_ready_handler,
  8530. &ws_data_handler,
  8531. &ws_close_handler,
  8532. NULL,
  8533. &callback_data)) {
  8534. /* 5.2.1. A callback will handle this request. All requests
  8535. * handled
  8536. * by a callback have to be considered as requests to a script
  8537. * resource. */
  8538. is_callback_resource = 1;
  8539. is_script_resource = 1;
  8540. is_put_or_delete_request = is_put_or_delete_method(conn);
  8541. } else {
  8542. no_callback_resource:
  8543. /* 5.2.2. No callback is responsible for this request. The URI
  8544. * addresses a file based resource (static content or Lua/cgi
  8545. * scripts in the file system). */
  8546. is_callback_resource = 0;
  8547. interpret_uri(conn,
  8548. path,
  8549. sizeof(path),
  8550. &file,
  8551. &is_found,
  8552. &is_script_resource,
  8553. &is_websocket_request,
  8554. &is_put_or_delete_request);
  8555. }
  8556. /* 6. authorization check */
  8557. /* 6.1. a custom authorization handler is installed */
  8558. if (get_request_handler(conn,
  8559. AUTH_HANDLER,
  8560. NULL,
  8561. NULL,
  8562. NULL,
  8563. NULL,
  8564. NULL,
  8565. &auth_handler,
  8566. &auth_callback_data)) {
  8567. if (!auth_handler(conn, auth_callback_data)) {
  8568. return;
  8569. }
  8570. } else if (is_put_or_delete_request && !is_script_resource
  8571. && !is_callback_resource) {
  8572. /* 6.2. this request is a PUT/DELETE to a real file */
  8573. /* 6.2.1. thus, the server must have real files */
  8574. #if defined(NO_FILES)
  8575. if (1) {
  8576. #else
  8577. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8578. #endif
  8579. /* This server does not have any real files, thus the
  8580. * PUT/DELETE methods are not valid. */
  8581. send_http_error(conn,
  8582. 405,
  8583. "%s method not allowed",
  8584. conn->request_info.request_method);
  8585. return;
  8586. }
  8587. #if !defined(NO_FILES)
  8588. /* 6.2.2. Check if put authorization for static files is
  8589. * available.
  8590. */
  8591. if (!is_authorized_for_put(conn)) {
  8592. send_authorization_request(conn);
  8593. return;
  8594. }
  8595. #endif
  8596. } else {
  8597. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8598. * or it is a PUT or DELETE request to a resource that does not
  8599. * correspond to a file. Check authorization. */
  8600. if (!check_authorization(conn, path)) {
  8601. send_authorization_request(conn);
  8602. return;
  8603. }
  8604. }
  8605. /* request is authorized or does not need authorization */
  8606. /* 7. check if there are request handlers for this uri */
  8607. if (is_callback_resource) {
  8608. if (!is_websocket_request) {
  8609. i = callback_handler(conn, callback_data);
  8610. if (i > 0) {
  8611. /* Do nothing, callback has served the request. Store
  8612. * the
  8613. * return value as status code for the log and discard
  8614. * all
  8615. * data from the client not used by the callback. */
  8616. conn->status_code = i;
  8617. discard_unread_request_data(conn);
  8618. } else {
  8619. /* TODO (high): what if the handler did NOT handle the
  8620. * request */
  8621. /* The last version did handle this as a file request,
  8622. * but
  8623. * since a file request is not always a script resource,
  8624. * the authorization check might be different */
  8625. interpret_uri(conn,
  8626. path,
  8627. sizeof(path),
  8628. &file,
  8629. &is_found,
  8630. &is_script_resource,
  8631. &is_websocket_request,
  8632. &is_put_or_delete_request);
  8633. callback_handler = NULL;
  8634. /* TODO (very low): goto is deprecated but for the
  8635. * moment,
  8636. * a goto is simpler than some curious loop. */
  8637. /* The situation "callback does not handle the request"
  8638. * needs to be reconsidered anyway. */
  8639. goto no_callback_resource;
  8640. }
  8641. } else {
  8642. #if defined(USE_WEBSOCKET)
  8643. handle_websocket_request(conn,
  8644. path,
  8645. is_callback_resource,
  8646. ws_connect_handler,
  8647. ws_ready_handler,
  8648. ws_data_handler,
  8649. ws_close_handler,
  8650. callback_data);
  8651. #endif
  8652. }
  8653. return;
  8654. }
  8655. /* 8. handle websocket requests */
  8656. #if defined(USE_WEBSOCKET)
  8657. if (is_websocket_request) {
  8658. if (is_script_resource) {
  8659. /* Websocket Lua script */
  8660. handle_websocket_request(conn,
  8661. path,
  8662. 0 /* Lua Script */,
  8663. NULL,
  8664. NULL,
  8665. NULL,
  8666. NULL,
  8667. &conn->ctx->callbacks);
  8668. } else {
  8669. #if defined(MG_LEGACY_INTERFACE)
  8670. handle_websocket_request(
  8671. conn,
  8672. path,
  8673. !is_script_resource /* could be deprecated global callback */,
  8674. deprecated_websocket_connect_wrapper,
  8675. deprecated_websocket_ready_wrapper,
  8676. deprecated_websocket_data_wrapper,
  8677. NULL,
  8678. &conn->ctx->callbacks);
  8679. #else
  8680. send_http_error(conn, 404, "%s", "Not found");
  8681. #endif
  8682. }
  8683. return;
  8684. } else
  8685. #endif
  8686. #if defined(NO_FILES)
  8687. /* 9a. In case the server uses only callbacks, this uri is
  8688. * unknown.
  8689. * Then, all request handling ends here. */
  8690. send_http_error(conn, 404, "%s", "Not Found");
  8691. #else
  8692. /* 9b. This request is either for a static file or resource handled
  8693. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8694. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8695. send_http_error(conn, 404, "%s", "Not Found");
  8696. return;
  8697. }
  8698. /* 10. File is handled by a script. */
  8699. if (is_script_resource) {
  8700. handle_file_based_request(conn, path, &file);
  8701. return;
  8702. }
  8703. /* 11. Handle put/delete/mkcol requests */
  8704. if (is_put_or_delete_request) {
  8705. /* 11.1. PUT method */
  8706. if (!strcmp(ri->request_method, "PUT")) {
  8707. put_file(conn, path);
  8708. return;
  8709. }
  8710. /* 11.2. DELETE method */
  8711. if (!strcmp(ri->request_method, "DELETE")) {
  8712. delete_file(conn, path);
  8713. return;
  8714. }
  8715. /* 11.3. MKCOL method */
  8716. if (!strcmp(ri->request_method, "MKCOL")) {
  8717. mkcol(conn, path);
  8718. return;
  8719. }
  8720. /* 11.4. PATCH method
  8721. * This method is not supported for static resources,
  8722. * only for scripts (Lua, CGI) and callbacks. */
  8723. send_http_error(conn,
  8724. 405,
  8725. "%s method not allowed",
  8726. conn->request_info.request_method);
  8727. return;
  8728. }
  8729. /* 11. File does not exist, or it was configured that it should be
  8730. * hidden */
  8731. if (!is_found || (must_hide_file(conn, path))) {
  8732. send_http_error(conn, 404, "%s", "Not found");
  8733. return;
  8734. }
  8735. /* 12. Directory uris should end with a slash */
  8736. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8737. gmt_time_string(date, sizeof(date), &curtime);
  8738. mg_printf(conn,
  8739. "HTTP/1.1 301 Moved Permanently\r\n"
  8740. "Location: %s/\r\n"
  8741. "Date: %s\r\n"
  8742. /* "Cache-Control: private\r\n" (= default) */
  8743. "Content-Length: 0\r\n"
  8744. "Connection: %s\r\n\r\n",
  8745. ri->request_uri,
  8746. date,
  8747. suggest_connection_header(conn));
  8748. return;
  8749. }
  8750. /* 13. Handle other methods than GET/HEAD */
  8751. /* 13.1. Handle PROPFIND */
  8752. if (!strcmp(ri->request_method, "PROPFIND")) {
  8753. handle_propfind(conn, path, &file);
  8754. return;
  8755. }
  8756. /* 13.2. Handle OPTIONS for files */
  8757. if (!strcmp(ri->request_method, "OPTIONS")) {
  8758. /* This standard handler is only used for real files.
  8759. * Scripts should support the OPTIONS method themselves, to allow a
  8760. * maximum flexibility.
  8761. * Lua and CGI scripts may fully support CORS this way (including
  8762. * preflights). */
  8763. send_options(conn);
  8764. return;
  8765. }
  8766. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8767. if (0 != strcmp(ri->request_method, "GET")
  8768. && 0 != strcmp(ri->request_method, "HEAD")) {
  8769. send_http_error(conn,
  8770. 405,
  8771. "%s method not allowed",
  8772. conn->request_info.request_method);
  8773. return;
  8774. }
  8775. /* 14. directories */
  8776. if (file.is_directory) {
  8777. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8778. /* 14.1. use a substitute file */
  8779. /* TODO (high): substitute index may be a script resource.
  8780. * define what should be possible in this case. */
  8781. } else {
  8782. /* 14.2. no substitute file */
  8783. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8784. "yes")) {
  8785. handle_directory_request(conn, path);
  8786. } else {
  8787. send_http_error(conn,
  8788. 403,
  8789. "%s",
  8790. "Error: Directory listing denied");
  8791. }
  8792. return;
  8793. }
  8794. }
  8795. handle_file_based_request(conn, path, &file);
  8796. #endif /* !defined(NO_FILES) */
  8797. #if 0
  8798. /* Perform redirect and auth checks before calling begin_request()
  8799. * handler.
  8800. * Otherwise, begin_request() would need to perform auth checks and
  8801. * redirects. */
  8802. #endif
  8803. }
  8804. return;
  8805. }
  8806. static void
  8807. handle_file_based_request(struct mg_connection *conn,
  8808. const char *path,
  8809. struct file *file)
  8810. {
  8811. if (!conn || !conn->ctx) {
  8812. return;
  8813. }
  8814. if (0) {
  8815. #ifdef USE_LUA
  8816. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8817. strlen(
  8818. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8819. path) > 0) {
  8820. /* Lua server page: an SSI like page containing mostly plain html
  8821. * code
  8822. * plus some tags with server generated contents. */
  8823. handle_lsp_request(conn, path, file, NULL);
  8824. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8825. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8826. path) > 0) {
  8827. /* Lua in-server module script: a CGI like script used to generate
  8828. * the
  8829. * entire reply. */
  8830. mg_exec_lua_script(conn, path, NULL);
  8831. #endif
  8832. #if defined(USE_DUKTAPE)
  8833. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8834. strlen(
  8835. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8836. path) > 0) {
  8837. /* Call duktape to generate the page */
  8838. mg_exec_duktape_script(conn, path);
  8839. #endif
  8840. #if !defined(NO_CGI)
  8841. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8842. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8843. path) > 0) {
  8844. /* CGI scripts may support all HTTP methods */
  8845. handle_cgi_request(conn, path);
  8846. #endif /* !NO_CGI */
  8847. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8848. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8849. path) > 0) {
  8850. handle_ssi_file_request(conn, path, file);
  8851. #if !defined(NO_CACHING)
  8852. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8853. /* Send 304 "Not Modified" - this must not send any body data */
  8854. send_http_error(conn, 304, "%s", "");
  8855. #endif /* !NO_CACHING */
  8856. } else {
  8857. handle_static_file_request(conn, path, file, NULL);
  8858. }
  8859. }
  8860. static void
  8861. close_all_listening_sockets(struct mg_context *ctx)
  8862. {
  8863. unsigned int i;
  8864. if (!ctx) {
  8865. return;
  8866. }
  8867. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8868. closesocket(ctx->listening_sockets[i].sock);
  8869. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8870. }
  8871. mg_free(ctx->listening_sockets);
  8872. ctx->listening_sockets = NULL;
  8873. mg_free(ctx->listening_ports);
  8874. ctx->listening_ports = NULL;
  8875. }
  8876. /* Valid listening port specification is: [ip_address:]port[s]
  8877. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8878. * Examples for IPv6: [::]:80, [::1]:80,
  8879. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8880. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8881. static int
  8882. parse_port_string(const struct vec *vec, struct socket *so)
  8883. {
  8884. unsigned int a, b, c, d, port;
  8885. int ch, len;
  8886. #if defined(USE_IPV6)
  8887. char buf[100] = {0};
  8888. #endif
  8889. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8890. * Also, all-zeroes in the socket address means binding to all addresses
  8891. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8892. memset(so, 0, sizeof(*so));
  8893. so->lsa.sin.sin_family = AF_INET;
  8894. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8895. == 5) {
  8896. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8897. so->lsa.sin.sin_addr.s_addr =
  8898. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8899. so->lsa.sin.sin_port = htons((uint16_t)port);
  8900. #if defined(USE_IPV6)
  8901. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8902. && mg_inet_pton(
  8903. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8904. /* IPv6 address, examples: see above */
  8905. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  8906. */
  8907. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8908. #endif
  8909. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8910. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8911. so->lsa.sin.sin_port = htons((uint16_t)port);
  8912. } else {
  8913. /* Parsing failure. Make port invalid. */
  8914. port = 0;
  8915. len = 0;
  8916. }
  8917. /* sscanf and the option splitting code ensure the following condition
  8918. */
  8919. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8920. return 0;
  8921. }
  8922. ch = vec->ptr[len]; /* Next character after the port number */
  8923. so->is_ssl = (ch == 's');
  8924. so->ssl_redir = (ch == 'r');
  8925. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8926. return is_valid_port(port)
  8927. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8928. }
  8929. static int
  8930. set_ports_option(struct mg_context *ctx)
  8931. {
  8932. const char *list;
  8933. int on = 1;
  8934. #if defined(USE_IPV6)
  8935. int off = 0;
  8936. #endif
  8937. struct vec vec;
  8938. struct socket so, *ptr;
  8939. in_port_t *portPtr;
  8940. union usa usa;
  8941. socklen_t len;
  8942. int portsTotal = 0;
  8943. int portsOk = 0;
  8944. if (!ctx) {
  8945. return 0;
  8946. }
  8947. memset(&so, 0, sizeof(so));
  8948. memset(&usa, 0, sizeof(usa));
  8949. len = sizeof(usa);
  8950. list = ctx->config[LISTENING_PORTS];
  8951. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8952. portsTotal++;
  8953. if (!parse_port_string(&vec, &so)) {
  8954. mg_cry(fc(ctx),
  8955. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8956. (int)vec.len,
  8957. vec.ptr,
  8958. portsTotal,
  8959. "[IP_ADDRESS:]PORT[s|r]");
  8960. continue;
  8961. }
  8962. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8963. mg_cry(fc(ctx),
  8964. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8965. "option set?",
  8966. portsTotal);
  8967. continue;
  8968. }
  8969. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8970. == INVALID_SOCKET) {
  8971. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8972. continue;
  8973. }
  8974. #ifdef _WIN32
  8975. /* Windows SO_REUSEADDR lets many procs binds to a
  8976. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8977. * if someone already has the socket -- DTL */
  8978. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8979. * Windows might need a few seconds before
  8980. * the same port can be used again in the
  8981. * same process, so a short Sleep may be
  8982. * required between mg_stop and mg_start.
  8983. */
  8984. if (setsockopt(so.sock,
  8985. SOL_SOCKET,
  8986. SO_EXCLUSIVEADDRUSE,
  8987. (SOCK_OPT_TYPE)&on,
  8988. sizeof(on)) != 0) {
  8989. mg_cry(fc(ctx),
  8990. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8991. portsTotal);
  8992. }
  8993. #else
  8994. if (setsockopt(so.sock,
  8995. SOL_SOCKET,
  8996. SO_REUSEADDR,
  8997. (SOCK_OPT_TYPE)&on,
  8998. sizeof(on)) != 0) {
  8999. mg_cry(fc(ctx),
  9000. "cannot set socket option SO_REUSEADDR (entry %i)",
  9001. portsTotal);
  9002. }
  9003. #endif
  9004. #if defined(USE_IPV6)
  9005. if (so.lsa.sa.sa_family == AF_INET6
  9006. && setsockopt(so.sock,
  9007. IPPROTO_IPV6,
  9008. IPV6_V6ONLY,
  9009. (void *)&off,
  9010. sizeof(off)) != 0) {
  9011. mg_cry(fc(ctx),
  9012. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9013. portsTotal);
  9014. }
  9015. #endif
  9016. if (so.lsa.sa.sa_family == AF_INET) {
  9017. len = sizeof(so.lsa.sin);
  9018. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9019. mg_cry(fc(ctx),
  9020. "cannot bind to %.*s: %d (%s)",
  9021. (int)vec.len,
  9022. vec.ptr,
  9023. (int)ERRNO,
  9024. strerror(errno));
  9025. closesocket(so.sock);
  9026. so.sock = INVALID_SOCKET;
  9027. continue;
  9028. }
  9029. }
  9030. #if defined(USE_IPV6)
  9031. else if (so.lsa.sa.sa_family == AF_INET6) {
  9032. len = sizeof(so.lsa.sin6);
  9033. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9034. mg_cry(fc(ctx),
  9035. "cannot bind to IPv6 %.*s: %d (%s)",
  9036. (int)vec.len,
  9037. vec.ptr,
  9038. (int)ERRNO,
  9039. strerror(errno));
  9040. closesocket(so.sock);
  9041. so.sock = INVALID_SOCKET;
  9042. continue;
  9043. }
  9044. }
  9045. #endif
  9046. else {
  9047. mg_cry(fc(ctx),
  9048. "cannot bind: address family not supported (entry %i)",
  9049. portsTotal);
  9050. continue;
  9051. }
  9052. if (listen(so.sock, SOMAXCONN) != 0) {
  9053. mg_cry(fc(ctx),
  9054. "cannot listen to %.*s: %d (%s)",
  9055. (int)vec.len,
  9056. vec.ptr,
  9057. (int)ERRNO,
  9058. strerror(errno));
  9059. closesocket(so.sock);
  9060. so.sock = INVALID_SOCKET;
  9061. continue;
  9062. }
  9063. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  9064. int err = (int)ERRNO;
  9065. mg_cry(fc(ctx),
  9066. "call to getsockname failed %.*s: %d (%s)",
  9067. (int)vec.len,
  9068. vec.ptr,
  9069. err,
  9070. strerror(errno));
  9071. closesocket(so.sock);
  9072. so.sock = INVALID_SOCKET;
  9073. continue;
  9074. }
  9075. if ((ptr = (struct socket *)
  9076. mg_realloc(ctx->listening_sockets,
  9077. (ctx->num_listening_sockets + 1)
  9078. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9079. mg_cry(fc(ctx), "%s", "Out of memory");
  9080. closesocket(so.sock);
  9081. so.sock = INVALID_SOCKET;
  9082. continue;
  9083. }
  9084. if ((portPtr =
  9085. (in_port_t *)mg_realloc(ctx->listening_ports,
  9086. (ctx->num_listening_sockets + 1)
  9087. * sizeof(ctx->listening_ports[0])))
  9088. == NULL) {
  9089. mg_cry(fc(ctx), "%s", "Out of memory");
  9090. closesocket(so.sock);
  9091. so.sock = INVALID_SOCKET;
  9092. mg_free(ptr);
  9093. continue;
  9094. }
  9095. set_close_on_exec(so.sock, fc(ctx));
  9096. ctx->listening_sockets = ptr;
  9097. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9098. ctx->listening_ports = portPtr;
  9099. ctx->listening_ports[ctx->num_listening_sockets] =
  9100. ntohs(usa.sin.sin_port);
  9101. ctx->num_listening_sockets++;
  9102. portsOk++;
  9103. }
  9104. if (portsOk != portsTotal) {
  9105. close_all_listening_sockets(ctx);
  9106. portsOk = 0;
  9107. }
  9108. return portsOk;
  9109. }
  9110. static const char *
  9111. header_val(const struct mg_connection *conn, const char *header)
  9112. {
  9113. const char *header_value;
  9114. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9115. return "-";
  9116. } else {
  9117. return header_value;
  9118. }
  9119. }
  9120. static void
  9121. log_access(const struct mg_connection *conn)
  9122. {
  9123. const struct mg_request_info *ri;
  9124. struct file fi;
  9125. char date[64], src_addr[IP_ADDR_STR_LEN];
  9126. struct tm *tm;
  9127. const char *referer;
  9128. const char *user_agent;
  9129. char buf[4096];
  9130. if (!conn || !conn->ctx) {
  9131. return;
  9132. }
  9133. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9134. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9135. == 0) {
  9136. fi.fp = NULL;
  9137. }
  9138. } else {
  9139. fi.fp = NULL;
  9140. }
  9141. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9142. return;
  9143. }
  9144. tm = localtime(&conn->conn_birth_time);
  9145. if (tm != NULL) {
  9146. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9147. } else {
  9148. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9149. date[sizeof(date) - 1] = '\0';
  9150. }
  9151. ri = &conn->request_info;
  9152. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9153. referer = header_val(conn, "Referer");
  9154. user_agent = header_val(conn, "User-Agent");
  9155. mg_snprintf(conn,
  9156. NULL, /* Ignore truncation in access log */
  9157. buf,
  9158. sizeof(buf),
  9159. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9160. src_addr,
  9161. ri->remote_user == NULL ? "-" : ri->remote_user,
  9162. date,
  9163. ri->request_method ? ri->request_method : "-",
  9164. ri->request_uri ? ri->request_uri : "-",
  9165. ri->query_string ? "?" : "",
  9166. ri->query_string ? ri->query_string : "",
  9167. ri->http_version,
  9168. conn->status_code,
  9169. conn->num_bytes_sent,
  9170. referer,
  9171. user_agent);
  9172. if (conn->ctx->callbacks.log_access) {
  9173. conn->ctx->callbacks.log_access(conn, buf);
  9174. }
  9175. if (fi.fp) {
  9176. flockfile(fi.fp);
  9177. fprintf(fi.fp, "%s\n", buf);
  9178. fflush(fi.fp);
  9179. funlockfile(fi.fp);
  9180. mg_fclose(&fi);
  9181. }
  9182. }
  9183. /* Verify given socket address against the ACL.
  9184. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9185. */
  9186. static int
  9187. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9188. {
  9189. int allowed, flag;
  9190. uint32_t net, mask;
  9191. struct vec vec;
  9192. if (ctx) {
  9193. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9194. /* If any ACL is set, deny by default */
  9195. allowed = list == NULL ? '+' : '-';
  9196. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9197. flag = vec.ptr[0];
  9198. if ((flag != '+' && flag != '-')
  9199. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9200. mg_cry(fc(ctx),
  9201. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9202. __func__);
  9203. return -1;
  9204. }
  9205. if (net == (remote_ip & mask)) {
  9206. allowed = flag;
  9207. }
  9208. }
  9209. return allowed == '+';
  9210. }
  9211. return -1;
  9212. }
  9213. #if !defined(_WIN32)
  9214. static int
  9215. set_uid_option(struct mg_context *ctx)
  9216. {
  9217. struct passwd *pw;
  9218. if (ctx) {
  9219. const char *uid = ctx->config[RUN_AS_USER];
  9220. int success = 0;
  9221. if (uid == NULL) {
  9222. success = 1;
  9223. } else {
  9224. if ((pw = getpwnam(uid)) == NULL) {
  9225. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9226. } else if (setgid(pw->pw_gid) == -1) {
  9227. mg_cry(fc(ctx),
  9228. "%s: setgid(%s): %s",
  9229. __func__,
  9230. uid,
  9231. strerror(errno));
  9232. } else if (setgroups(0, NULL)) {
  9233. mg_cry(fc(ctx),
  9234. "%s: setgroups(): %s",
  9235. __func__,
  9236. strerror(errno));
  9237. } else if (setuid(pw->pw_uid) == -1) {
  9238. mg_cry(fc(ctx),
  9239. "%s: setuid(%s): %s",
  9240. __func__,
  9241. uid,
  9242. strerror(errno));
  9243. } else {
  9244. success = 1;
  9245. }
  9246. }
  9247. return success;
  9248. }
  9249. return 0;
  9250. }
  9251. #endif /* !_WIN32 */
  9252. static void
  9253. tls_dtor(void *key)
  9254. {
  9255. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9256. /* key == pthread_getspecific(sTlsKey); */
  9257. if (tls) {
  9258. if (tls->is_master == 2) {
  9259. tls->is_master = -3; /* Mark memory as dead */
  9260. mg_free(tls);
  9261. }
  9262. }
  9263. pthread_setspecific(sTlsKey, NULL);
  9264. }
  9265. #if !defined(NO_SSL)
  9266. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9267. static unsigned long
  9268. ssl_id_callback(void)
  9269. {
  9270. #ifdef _WIN32
  9271. return GetCurrentThreadId();
  9272. #else
  9273. #ifdef __clang__
  9274. #pragma clang diagnostic push
  9275. #pragma clang diagnostic ignored "-Wunreachable-code"
  9276. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9277. * or not, so one of the two conditions will be unreachable by construction.
  9278. * Unfortunately the C standard does not define a way to check this at
  9279. * compile time, since the #if preprocessor conditions can not use the sizeof
  9280. * operator as an argument. */
  9281. #endif
  9282. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9283. /* This is the problematic case for CRYPTO_set_id_callback:
  9284. * The OS pthread_t can not be cast to unsigned long. */
  9285. struct mg_workerTLS *tls =
  9286. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9287. if (tls == NULL) {
  9288. /* SSL called from an unknown thread: Create some thread index.
  9289. */
  9290. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9291. tls->is_master = -2; /* -2 means "3rd party thread" */
  9292. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9293. pthread_setspecific(sTlsKey, tls);
  9294. }
  9295. return tls->thread_idx;
  9296. } else {
  9297. /* pthread_t may be any data type, so a simple cast to unsigned long
  9298. * can rise a warning/error, depending on the platform.
  9299. * Here memcpy is used as an anything-to-anything cast. */
  9300. unsigned long ret = 0;
  9301. pthread_t t = pthread_self();
  9302. memcpy(&ret, &t, sizeof(pthread_t));
  9303. return ret;
  9304. }
  9305. #ifdef __clang__
  9306. #pragma clang diagnostic pop
  9307. #endif
  9308. #endif
  9309. }
  9310. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9311. static const char *ssl_error(void);
  9312. static int
  9313. refresh_trust(struct mg_connection *conn)
  9314. {
  9315. static int reload_lock = 0;
  9316. static long int data_check = 0;
  9317. struct stat cert_buf;
  9318. long int t;
  9319. char *pem;
  9320. int should_verify_peer;
  9321. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9322. && conn->ctx->callbacks.init_ssl == NULL) {
  9323. return 0;
  9324. }
  9325. t = data_check;
  9326. if (stat(pem, &cert_buf) != -1) {
  9327. t = (long int)cert_buf.st_mtime;
  9328. }
  9329. if (data_check != t) {
  9330. data_check = t;
  9331. should_verify_peer =
  9332. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9333. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9334. == 0);
  9335. if (should_verify_peer) {
  9336. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9337. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9338. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9339. ca_file,
  9340. ca_path) != 1) {
  9341. mg_cry(fc(conn->ctx),
  9342. "SSL_CTX_load_verify_locations error: %s "
  9343. "ssl_verify_peer requires setting "
  9344. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9345. "present in "
  9346. "the .conf file?",
  9347. ssl_error());
  9348. return 0;
  9349. }
  9350. }
  9351. if (!reload_lock) {
  9352. reload_lock = 1;
  9353. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9354. return 0;
  9355. }
  9356. reload_lock = 0;
  9357. }
  9358. }
  9359. /* lock while cert is reloading */
  9360. while (reload_lock) {
  9361. sleep(1);
  9362. }
  9363. return 1;
  9364. }
  9365. static pthread_mutex_t *ssl_mutexes;
  9366. static int
  9367. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9368. {
  9369. int ret, err;
  9370. int short_trust;
  9371. if (!conn) {
  9372. return 0;
  9373. }
  9374. short_trust =
  9375. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9376. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9377. if (short_trust) {
  9378. int trust_ret = refresh_trust(conn);
  9379. if (!trust_ret) {
  9380. return trust_ret;
  9381. }
  9382. }
  9383. conn->ssl = SSL_new(s);
  9384. if (conn->ssl == NULL) {
  9385. return 0;
  9386. }
  9387. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9388. if (ret != 1) {
  9389. err = SSL_get_error(conn->ssl, ret);
  9390. (void)err; /* TODO: set some error message */
  9391. SSL_free(conn->ssl);
  9392. conn->ssl = NULL;
  9393. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9394. /* see
  9395. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9396. ERR_remove_state(0);
  9397. return 0;
  9398. }
  9399. ret = func(conn->ssl);
  9400. if (ret != 1) {
  9401. err = SSL_get_error(conn->ssl, ret);
  9402. (void)err; /* TODO: set some error message */
  9403. SSL_free(conn->ssl);
  9404. conn->ssl = NULL;
  9405. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9406. /* see
  9407. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9408. ERR_remove_state(0);
  9409. return 0;
  9410. }
  9411. return 1;
  9412. }
  9413. /* Return OpenSSL error message (from CRYPTO lib) */
  9414. static const char *
  9415. ssl_error(void)
  9416. {
  9417. unsigned long err;
  9418. err = ERR_get_error();
  9419. return err == 0 ? "" : ERR_error_string(err, NULL);
  9420. }
  9421. static void
  9422. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9423. {
  9424. (void)line;
  9425. (void)file;
  9426. if (mode & 1) {
  9427. /* 1 is CRYPTO_LOCK */
  9428. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9429. } else {
  9430. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9431. }
  9432. }
  9433. #if !defined(NO_SSL_DL)
  9434. static void *
  9435. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9436. {
  9437. union {
  9438. void *p;
  9439. void (*fp)(void);
  9440. } u;
  9441. void *dll_handle;
  9442. struct ssl_func *fp;
  9443. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9444. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9445. return NULL;
  9446. }
  9447. for (fp = sw; fp->name != NULL; fp++) {
  9448. #ifdef _WIN32
  9449. /* GetProcAddress() returns pointer to function */
  9450. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9451. #else
  9452. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9453. * pointers to function pointers. We need to use a union to make a
  9454. * cast. */
  9455. u.p = dlsym(dll_handle, fp->name);
  9456. #endif /* _WIN32 */
  9457. if (u.fp == NULL) {
  9458. mg_cry(fc(ctx),
  9459. "%s: %s: cannot find %s",
  9460. __func__,
  9461. dll_name,
  9462. fp->name);
  9463. dlclose(dll_handle);
  9464. return NULL;
  9465. } else {
  9466. fp->ptr = u.fp;
  9467. }
  9468. }
  9469. return dll_handle;
  9470. }
  9471. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9472. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9473. #endif /* NO_SSL_DL */
  9474. #if defined(SSL_ALREADY_INITIALIZED)
  9475. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9476. #else
  9477. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9478. #endif
  9479. static int
  9480. initialize_ssl(struct mg_context *ctx)
  9481. {
  9482. int i;
  9483. size_t size;
  9484. #if !defined(NO_SSL_DL)
  9485. if (!cryptolib_dll_handle) {
  9486. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9487. if (!cryptolib_dll_handle) {
  9488. return 0;
  9489. }
  9490. }
  9491. #endif /* NO_SSL_DL */
  9492. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9493. return 1;
  9494. }
  9495. /* Initialize locking callbacks, needed for thread safety.
  9496. * http://www.openssl.org/support/faq.html#PROG1
  9497. */
  9498. i = CRYPTO_num_locks();
  9499. if (i < 0) {
  9500. i = 0;
  9501. }
  9502. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9503. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9504. mg_cry(fc(ctx),
  9505. "%s: cannot allocate mutexes: %s",
  9506. __func__,
  9507. ssl_error());
  9508. return 0;
  9509. }
  9510. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9511. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9512. }
  9513. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9514. CRYPTO_set_id_callback(&ssl_id_callback);
  9515. return 1;
  9516. }
  9517. static int
  9518. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9519. {
  9520. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9521. mg_cry(fc(ctx),
  9522. "%s: cannot open certificate file %s: %s",
  9523. __func__,
  9524. pem,
  9525. ssl_error());
  9526. return 0;
  9527. }
  9528. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9529. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9530. mg_cry(fc(ctx),
  9531. "%s: cannot open private key file %s: %s",
  9532. __func__,
  9533. pem,
  9534. ssl_error());
  9535. return 0;
  9536. }
  9537. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9538. mg_cry(fc(ctx),
  9539. "%s: certificate and private key do not match: %s",
  9540. __func__,
  9541. pem);
  9542. return 0;
  9543. }
  9544. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9545. mg_cry(fc(ctx),
  9546. "%s: cannot use certificate chain file %s: %s",
  9547. __func__,
  9548. pem,
  9549. ssl_error());
  9550. return 0;
  9551. }
  9552. return 1;
  9553. }
  9554. static long
  9555. ssl_get_protocol(int version_id)
  9556. {
  9557. long ret = SSL_OP_ALL;
  9558. if (version_id > 0)
  9559. ret |= SSL_OP_NO_SSLv2;
  9560. if (version_id > 1)
  9561. ret |= SSL_OP_NO_SSLv3;
  9562. if (version_id > 2)
  9563. ret |= SSL_OP_NO_TLSv1;
  9564. if (version_id > 3)
  9565. ret |= SSL_OP_NO_TLSv1_1;
  9566. return ret;
  9567. }
  9568. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9569. static int
  9570. set_ssl_option(struct mg_context *ctx)
  9571. {
  9572. const char *pem;
  9573. int callback_ret;
  9574. int should_verify_peer;
  9575. const char *ca_path;
  9576. const char *ca_file;
  9577. int use_default_verify_paths;
  9578. int verify_depth;
  9579. time_t now_rt = time(NULL);
  9580. struct timespec now_mt;
  9581. md5_byte_t ssl_context_id[16];
  9582. md5_state_t md5state;
  9583. int protocol_ver;
  9584. /* If PEM file is not specified and the init_ssl callback
  9585. * is not specified, skip SSL initialization. */
  9586. if (!ctx) {
  9587. return 0;
  9588. }
  9589. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9590. && ctx->callbacks.init_ssl == NULL) {
  9591. return 1;
  9592. }
  9593. if (!initialize_ssl(ctx)) {
  9594. return 0;
  9595. }
  9596. #if !defined(NO_SSL_DL)
  9597. if (!ssllib_dll_handle) {
  9598. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9599. if (!ssllib_dll_handle) {
  9600. return 0;
  9601. }
  9602. }
  9603. #endif /* NO_SSL_DL */
  9604. /* Initialize SSL library */
  9605. SSL_library_init();
  9606. SSL_load_error_strings();
  9607. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9608. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9609. return 0;
  9610. }
  9611. SSL_CTX_clear_options(ctx->ssl_ctx,
  9612. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9613. | SSL_OP_NO_TLSv1_1);
  9614. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9615. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9616. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9617. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9618. /* If a callback has been specified, call it. */
  9619. callback_ret =
  9620. (ctx->callbacks.init_ssl == NULL)
  9621. ? 0
  9622. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9623. /* If callback returns 0, civetweb sets up the SSL certificate.
  9624. * If it returns 1, civetweb assumes the calback already did this.
  9625. * If it returns -1, initializing ssl fails. */
  9626. if (callback_ret < 0) {
  9627. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9628. return 0;
  9629. }
  9630. if (callback_ret > 0) {
  9631. if (pem != NULL) {
  9632. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9633. }
  9634. return 1;
  9635. }
  9636. /* Use some UID as session context ID. */
  9637. md5_init(&md5state);
  9638. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9639. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9640. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9641. md5_append(&md5state,
  9642. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9643. strlen(ctx->config[LISTENING_PORTS]));
  9644. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9645. md5_finish(&md5state, ssl_context_id);
  9646. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9647. (const unsigned char *)&ssl_context_id,
  9648. sizeof(ssl_context_id));
  9649. if (pem != NULL) {
  9650. if (!ssl_use_pem_file(ctx, pem)) {
  9651. return 0;
  9652. }
  9653. }
  9654. should_verify_peer =
  9655. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9656. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9657. use_default_verify_paths =
  9658. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9659. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9660. if (should_verify_peer) {
  9661. ca_path = ctx->config[SSL_CA_PATH];
  9662. ca_file = ctx->config[SSL_CA_FILE];
  9663. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9664. != 1) {
  9665. mg_cry(fc(ctx),
  9666. "SSL_CTX_load_verify_locations error: %s "
  9667. "ssl_verify_peer requires setting "
  9668. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9669. "present in "
  9670. "the .conf file?",
  9671. ssl_error());
  9672. return 0;
  9673. }
  9674. SSL_CTX_set_verify(ctx->ssl_ctx,
  9675. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9676. NULL);
  9677. if (use_default_verify_paths
  9678. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9679. mg_cry(fc(ctx),
  9680. "SSL_CTX_set_default_verify_paths error: %s",
  9681. ssl_error());
  9682. return 0;
  9683. }
  9684. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9685. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9686. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9687. }
  9688. }
  9689. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9690. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9691. != 1) {
  9692. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9693. }
  9694. }
  9695. return 1;
  9696. }
  9697. static void
  9698. uninitialize_ssl(struct mg_context *ctx)
  9699. {
  9700. int i;
  9701. (void)ctx;
  9702. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9703. /* Shutdown according to
  9704. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9705. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9706. */
  9707. CRYPTO_set_locking_callback(NULL);
  9708. CRYPTO_set_id_callback(NULL);
  9709. ENGINE_cleanup();
  9710. CONF_modules_unload(1);
  9711. ERR_free_strings();
  9712. EVP_cleanup();
  9713. CRYPTO_cleanup_all_ex_data();
  9714. ERR_remove_state(0);
  9715. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9716. pthread_mutex_destroy(&ssl_mutexes[i]);
  9717. }
  9718. mg_free(ssl_mutexes);
  9719. ssl_mutexes = NULL;
  9720. }
  9721. }
  9722. #endif /* !NO_SSL */
  9723. static int
  9724. set_gpass_option(struct mg_context *ctx)
  9725. {
  9726. if (ctx) {
  9727. struct file file = STRUCT_FILE_INITIALIZER;
  9728. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9729. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9730. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9731. return 0;
  9732. }
  9733. return 1;
  9734. }
  9735. return 0;
  9736. }
  9737. static int
  9738. set_acl_option(struct mg_context *ctx)
  9739. {
  9740. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9741. }
  9742. static void
  9743. reset_per_request_attributes(struct mg_connection *conn)
  9744. {
  9745. if (!conn) {
  9746. return;
  9747. }
  9748. conn->path_info = NULL;
  9749. conn->num_bytes_sent = conn->consumed_content = 0;
  9750. conn->status_code = -1;
  9751. conn->is_chunked = 0;
  9752. conn->must_close = conn->request_len = conn->throttle = 0;
  9753. conn->request_info.content_length = -1;
  9754. conn->request_info.remote_user = NULL;
  9755. conn->request_info.request_method = NULL;
  9756. conn->request_info.request_uri = NULL;
  9757. conn->request_info.local_uri = NULL;
  9758. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9759. * local_uri and request_uri */
  9760. conn->request_info.http_version = NULL;
  9761. conn->request_info.num_headers = 0;
  9762. conn->data_len = 0;
  9763. conn->chunk_remainder = 0;
  9764. conn->internal_error = 0;
  9765. }
  9766. static int
  9767. set_sock_timeout(SOCKET sock, int milliseconds)
  9768. {
  9769. int r0 = 0, r1, r2;
  9770. #ifdef _WIN32
  9771. /* Windows specific */
  9772. DWORD tv = (DWORD)milliseconds;
  9773. #else
  9774. /* Linux, ... (not Windows) */
  9775. struct timeval tv;
  9776. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9777. * max. time waiting for the acknowledged of TCP data before the connection
  9778. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9779. * If this option is not set, the default timeout of 20-30 minutes is used.
  9780. */
  9781. /* #define TCP_USER_TIMEOUT (18) */
  9782. #if defined(TCP_USER_TIMEOUT)
  9783. unsigned int uto = (unsigned int)milliseconds;
  9784. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9785. #endif
  9786. memset(&tv, 0, sizeof(tv));
  9787. tv.tv_sec = milliseconds / 1000;
  9788. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9789. #endif /* _WIN32 */
  9790. r1 = setsockopt(
  9791. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9792. r2 = setsockopt(
  9793. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9794. return r0 || r1 || r2;
  9795. }
  9796. static int
  9797. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  9798. {
  9799. if (setsockopt(sock,
  9800. IPPROTO_TCP,
  9801. TCP_NODELAY,
  9802. (SOCK_OPT_TYPE)&nodelay_on,
  9803. sizeof(nodelay_on)) != 0) {
  9804. /* Error */
  9805. return 1;
  9806. }
  9807. /* OK */
  9808. return 0;
  9809. }
  9810. static void
  9811. close_socket_gracefully(struct mg_connection *conn)
  9812. {
  9813. #if defined(_WIN32)
  9814. char buf[MG_BUF_LEN];
  9815. int n;
  9816. #endif
  9817. struct linger linger;
  9818. if (!conn) {
  9819. return;
  9820. }
  9821. /* Set linger option to avoid socket hanging out after close. This
  9822. * prevent
  9823. * ephemeral port exhaust problem under high QPS. */
  9824. linger.l_onoff = 1;
  9825. linger.l_linger = 1;
  9826. if (setsockopt(conn->client.sock,
  9827. SOL_SOCKET,
  9828. SO_LINGER,
  9829. (char *)&linger,
  9830. sizeof(linger)) != 0) {
  9831. mg_cry(conn,
  9832. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9833. __func__,
  9834. strerror(ERRNO));
  9835. }
  9836. /* Send FIN to the client */
  9837. shutdown(conn->client.sock, SHUT_WR);
  9838. set_non_blocking_mode(conn->client.sock);
  9839. #if defined(_WIN32)
  9840. /* Read and discard pending incoming data. If we do not do that and
  9841. * close
  9842. * the socket, the data in the send buffer may be discarded. This
  9843. * behaviour is seen on Windows, when client keeps sending data
  9844. * when server decides to close the connection; then when client
  9845. * does recv() it gets no data back. */
  9846. do {
  9847. n = pull(
  9848. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9849. } while (n > 0);
  9850. #endif
  9851. /* Now we know that our FIN is ACK-ed, safe to close */
  9852. closesocket(conn->client.sock);
  9853. conn->client.sock = INVALID_SOCKET;
  9854. }
  9855. static void
  9856. close_connection(struct mg_connection *conn)
  9857. {
  9858. if (!conn || !conn->ctx) {
  9859. return;
  9860. }
  9861. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9862. if (conn->lua_websocket_state) {
  9863. lua_websocket_close(conn, conn->lua_websocket_state);
  9864. conn->lua_websocket_state = NULL;
  9865. }
  9866. #endif
  9867. /* call the connection_close callback if assigned */
  9868. if ((conn->ctx->callbacks.connection_close != NULL)
  9869. && (conn->ctx->context_type == 1)) {
  9870. conn->ctx->callbacks.connection_close(conn);
  9871. }
  9872. mg_lock_connection(conn);
  9873. conn->must_close = 1;
  9874. #ifndef NO_SSL
  9875. if (conn->ssl != NULL) {
  9876. /* Run SSL_shutdown twice to ensure completly close SSL connection
  9877. */
  9878. SSL_shutdown(conn->ssl);
  9879. SSL_free(conn->ssl);
  9880. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9881. /* see
  9882. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9883. ERR_remove_state(0);
  9884. conn->ssl = NULL;
  9885. }
  9886. #endif
  9887. if (conn->client.sock != INVALID_SOCKET) {
  9888. close_socket_gracefully(conn);
  9889. conn->client.sock = INVALID_SOCKET;
  9890. }
  9891. mg_unlock_connection(conn);
  9892. }
  9893. void
  9894. mg_close_connection(struct mg_connection *conn)
  9895. {
  9896. struct mg_context *client_ctx = NULL;
  9897. unsigned int i;
  9898. if (conn == NULL) {
  9899. return;
  9900. }
  9901. if (conn->ctx->context_type == 2) {
  9902. client_ctx = conn->ctx;
  9903. /* client context: loops must end */
  9904. conn->ctx->stop_flag = 1;
  9905. }
  9906. #ifndef NO_SSL
  9907. if (conn->client_ssl_ctx != NULL) {
  9908. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9909. }
  9910. #endif
  9911. close_connection(conn);
  9912. if (client_ctx != NULL) {
  9913. /* join worker thread and free context */
  9914. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9915. if (client_ctx->workerthreadids[i] != 0) {
  9916. mg_join_thread(client_ctx->workerthreadids[i]);
  9917. }
  9918. }
  9919. mg_free(client_ctx->workerthreadids);
  9920. mg_free(client_ctx);
  9921. (void)pthread_mutex_destroy(&conn->mutex);
  9922. mg_free(conn);
  9923. }
  9924. }
  9925. static struct mg_connection *
  9926. mg_connect_client_impl(const struct mg_client_options *client_options,
  9927. int use_ssl,
  9928. char *ebuf,
  9929. size_t ebuf_len)
  9930. {
  9931. static struct mg_context fake_ctx;
  9932. struct mg_connection *conn = NULL;
  9933. SOCKET sock;
  9934. union usa sa;
  9935. if (!connect_socket(&fake_ctx,
  9936. client_options->host,
  9937. client_options->port,
  9938. use_ssl,
  9939. ebuf,
  9940. ebuf_len,
  9941. &sock,
  9942. &sa)) {
  9943. ;
  9944. } else if ((conn = (struct mg_connection *)
  9945. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9946. mg_snprintf(NULL,
  9947. NULL, /* No truncation check for ebuf */
  9948. ebuf,
  9949. ebuf_len,
  9950. "calloc(): %s",
  9951. strerror(ERRNO));
  9952. closesocket(sock);
  9953. #ifndef NO_SSL
  9954. } else if (use_ssl
  9955. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9956. == NULL) {
  9957. mg_snprintf(NULL,
  9958. NULL, /* No truncation check for ebuf */
  9959. ebuf,
  9960. ebuf_len,
  9961. "SSL_CTX_new error");
  9962. closesocket(sock);
  9963. mg_free(conn);
  9964. conn = NULL;
  9965. #endif /* NO_SSL */
  9966. } else {
  9967. #ifdef USE_IPV6
  9968. socklen_t len = (sa.sa.sa_family == AF_INET)
  9969. ? sizeof(conn->client.rsa.sin)
  9970. : sizeof(conn->client.rsa.sin6);
  9971. struct sockaddr *psa =
  9972. (sa.sa.sa_family == AF_INET)
  9973. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9974. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9975. #else
  9976. socklen_t len = sizeof(conn->client.rsa.sin);
  9977. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9978. #endif
  9979. conn->buf_size = MAX_REQUEST_SIZE;
  9980. conn->buf = (char *)(conn + 1);
  9981. conn->ctx = &fake_ctx;
  9982. conn->client.sock = sock;
  9983. conn->client.lsa = sa;
  9984. if (getsockname(sock, psa, &len) != 0) {
  9985. mg_cry(conn,
  9986. "%s: getsockname() failed: %s",
  9987. __func__,
  9988. strerror(ERRNO));
  9989. }
  9990. conn->client.is_ssl = use_ssl ? 1 : 0;
  9991. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9992. #ifndef NO_SSL
  9993. if (use_ssl) {
  9994. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9995. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9996. * SSL_CTX_set_verify call is needed to switch off server
  9997. * certificate checking, which is off by default in OpenSSL and
  9998. * on in yaSSL. */
  9999. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10000. * SSL_VERIFY_PEER, verify_ssl_server); */
  10001. if (client_options->client_cert) {
  10002. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10003. mg_snprintf(NULL,
  10004. NULL, /* No truncation check for ebuf */
  10005. ebuf,
  10006. ebuf_len,
  10007. "Can not use SSL client certificate");
  10008. SSL_CTX_free(conn->client_ssl_ctx);
  10009. closesocket(sock);
  10010. mg_free(conn);
  10011. conn = NULL;
  10012. }
  10013. }
  10014. if (client_options->server_cert) {
  10015. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10016. client_options->server_cert,
  10017. NULL);
  10018. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10019. } else {
  10020. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10021. }
  10022. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10023. mg_snprintf(NULL,
  10024. NULL, /* No truncation check for ebuf */
  10025. ebuf,
  10026. ebuf_len,
  10027. "SSL connection error");
  10028. SSL_CTX_free(conn->client_ssl_ctx);
  10029. closesocket(sock);
  10030. mg_free(conn);
  10031. conn = NULL;
  10032. }
  10033. }
  10034. #endif
  10035. }
  10036. return conn;
  10037. }
  10038. CIVETWEB_API struct mg_connection *
  10039. mg_connect_client_secure(const struct mg_client_options *client_options,
  10040. char *error_buffer,
  10041. size_t error_buffer_size)
  10042. {
  10043. return mg_connect_client_impl(client_options,
  10044. 1,
  10045. error_buffer,
  10046. error_buffer_size);
  10047. }
  10048. struct mg_connection *
  10049. mg_connect_client(const char *host,
  10050. int port,
  10051. int use_ssl,
  10052. char *error_buffer,
  10053. size_t error_buffer_size)
  10054. {
  10055. struct mg_client_options opts;
  10056. memset(&opts, 0, sizeof(opts));
  10057. opts.host = host;
  10058. opts.port = port;
  10059. return mg_connect_client_impl(&opts,
  10060. use_ssl,
  10061. error_buffer,
  10062. error_buffer_size);
  10063. }
  10064. static const struct {
  10065. const char *proto;
  10066. size_t proto_len;
  10067. unsigned default_port;
  10068. } abs_uri_protocols[] = {{"http://", 7, 80},
  10069. {"https://", 8, 443},
  10070. {"ws://", 5, 80},
  10071. {"wss://", 6, 443},
  10072. {NULL, 0, 0}};
  10073. /* Check if the uri is valid.
  10074. * return 0 for invalid uri,
  10075. * return 1 for *,
  10076. * return 2 for relative uri,
  10077. * return 3 for absolute uri without port,
  10078. * return 4 for absolute uri with port */
  10079. static int
  10080. get_uri_type(const char *uri)
  10081. {
  10082. int i;
  10083. char *hostend, *portbegin, *portend;
  10084. unsigned long port;
  10085. /* According to the HTTP standard
  10086. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10087. * URI can be an asterisk (*) or should start with slash (relative uri),
  10088. * or it should start with the protocol (absolute uri). */
  10089. if (uri[0] == '*' && uri[1] == '\0') {
  10090. /* asterisk */
  10091. return 1;
  10092. }
  10093. if (uri[0] == '/') {
  10094. /* relative uri */
  10095. return 2;
  10096. }
  10097. /* It could be an absolute uri: */
  10098. /* This function only checks if the uri is valid, not if it is
  10099. * addressing the current server. So civetweb can also be used
  10100. * as a proxy server. */
  10101. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10102. if (mg_strncasecmp(uri,
  10103. abs_uri_protocols[i].proto,
  10104. abs_uri_protocols[i].proto_len) == 0) {
  10105. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10106. if (!hostend) {
  10107. return 0;
  10108. }
  10109. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10110. if (!portbegin) {
  10111. return 3;
  10112. }
  10113. port = strtoul(portbegin + 1, &portend, 10);
  10114. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10115. return 0;
  10116. }
  10117. return 4;
  10118. }
  10119. }
  10120. return 0;
  10121. }
  10122. /* Return NULL or the relative uri at the current server */
  10123. static const char *
  10124. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10125. {
  10126. const char *server_domain;
  10127. size_t server_domain_len;
  10128. size_t request_domain_len = 0;
  10129. unsigned long port = 0;
  10130. int i;
  10131. const char *hostbegin = NULL;
  10132. const char *hostend = NULL;
  10133. const char *portbegin;
  10134. char *portend;
  10135. /* DNS is case insensitive, so use case insensitive string compare here
  10136. */
  10137. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10138. if (!server_domain) {
  10139. return 0;
  10140. }
  10141. server_domain_len = strlen(server_domain);
  10142. if (!server_domain_len) {
  10143. return 0;
  10144. }
  10145. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10146. if (mg_strncasecmp(uri,
  10147. abs_uri_protocols[i].proto,
  10148. abs_uri_protocols[i].proto_len) == 0) {
  10149. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10150. hostend = strchr(hostbegin, '/');
  10151. if (!hostend) {
  10152. return 0;
  10153. }
  10154. portbegin = strchr(hostbegin, ':');
  10155. if ((!portbegin) || (portbegin > hostend)) {
  10156. port = abs_uri_protocols[i].default_port;
  10157. request_domain_len = (size_t)(hostend - hostbegin);
  10158. } else {
  10159. port = strtoul(portbegin + 1, &portend, 10);
  10160. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10161. return 0;
  10162. }
  10163. request_domain_len = (size_t)(portbegin - hostbegin);
  10164. }
  10165. /* protocol found, port set */
  10166. break;
  10167. }
  10168. }
  10169. if (!port) {
  10170. /* port remains 0 if the protocol is not found */
  10171. return 0;
  10172. }
  10173. #if defined(USE_IPV6)
  10174. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10175. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10176. /* Request is directed to a different port */
  10177. return 0;
  10178. }
  10179. } else
  10180. #endif
  10181. {
  10182. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10183. /* Request is directed to a different port */
  10184. return 0;
  10185. }
  10186. }
  10187. if ((request_domain_len != server_domain_len)
  10188. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10189. /* Request is directed to another server */
  10190. return 0;
  10191. }
  10192. return hostend;
  10193. }
  10194. static int
  10195. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10196. {
  10197. const char *cl;
  10198. if (ebuf_len > 0) {
  10199. ebuf[0] = '\0';
  10200. }
  10201. *err = 0;
  10202. reset_per_request_attributes(conn);
  10203. if (!conn) {
  10204. mg_snprintf(conn,
  10205. NULL, /* No truncation check for ebuf */
  10206. ebuf,
  10207. ebuf_len,
  10208. "%s",
  10209. "Internal error");
  10210. *err = 500;
  10211. return 0;
  10212. }
  10213. /* Set the time the request was received. This value should be used for
  10214. * timeouts. */
  10215. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10216. conn->request_len =
  10217. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10218. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10219. */
  10220. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10221. mg_snprintf(conn,
  10222. NULL, /* No truncation check for ebuf */
  10223. ebuf,
  10224. ebuf_len,
  10225. "%s",
  10226. "Invalid request size");
  10227. *err = 500;
  10228. return 0;
  10229. }
  10230. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10231. mg_snprintf(conn,
  10232. NULL, /* No truncation check for ebuf */
  10233. ebuf,
  10234. ebuf_len,
  10235. "%s",
  10236. "Request Too Large");
  10237. *err = 413;
  10238. return 0;
  10239. } else if (conn->request_len <= 0) {
  10240. if (conn->data_len > 0) {
  10241. mg_snprintf(conn,
  10242. NULL, /* No truncation check for ebuf */
  10243. ebuf,
  10244. ebuf_len,
  10245. "%s",
  10246. "Client sent malformed request");
  10247. *err = 400;
  10248. } else {
  10249. /* Server did not send anything -> just close the connection */
  10250. conn->must_close = 1;
  10251. mg_snprintf(conn,
  10252. NULL, /* No truncation check for ebuf */
  10253. ebuf,
  10254. ebuf_len,
  10255. "%s",
  10256. "Client did not send a request");
  10257. *err = 0;
  10258. }
  10259. return 0;
  10260. } else if (parse_http_message(conn->buf,
  10261. conn->buf_size,
  10262. &conn->request_info) <= 0) {
  10263. mg_snprintf(conn,
  10264. NULL, /* No truncation check for ebuf */
  10265. ebuf,
  10266. ebuf_len,
  10267. "%s",
  10268. "Bad Request");
  10269. *err = 400;
  10270. return 0;
  10271. } else {
  10272. /* Message is a valid request or response */
  10273. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10274. /* Request/response has content length set */
  10275. char *endptr = NULL;
  10276. conn->content_len = strtoll(cl, &endptr, 10);
  10277. if (endptr == cl) {
  10278. mg_snprintf(conn,
  10279. NULL, /* No truncation check for ebuf */
  10280. ebuf,
  10281. ebuf_len,
  10282. "%s",
  10283. "Bad Request");
  10284. *err = 411;
  10285. return 0;
  10286. }
  10287. /* Publish the content length back to the request info. */
  10288. conn->request_info.content_length = conn->content_len;
  10289. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10290. != NULL
  10291. && !mg_strcasecmp(cl, "chunked")) {
  10292. conn->is_chunked = 1;
  10293. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10294. || !mg_strcasecmp(conn->request_info.request_method,
  10295. "PUT")) {
  10296. /* POST or PUT request without content length set */
  10297. conn->content_len = -1;
  10298. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10299. "HTTP/",
  10300. 5)) {
  10301. /* Response without content length set */
  10302. conn->content_len = -1;
  10303. } else {
  10304. /* Other request */
  10305. conn->content_len = 0;
  10306. }
  10307. }
  10308. return 1;
  10309. }
  10310. int
  10311. mg_get_response(struct mg_connection *conn,
  10312. char *ebuf,
  10313. size_t ebuf_len,
  10314. int timeout)
  10315. {
  10316. if (conn) {
  10317. /* Implementation of API function for HTTP clients */
  10318. int err, ret;
  10319. struct mg_context *octx = conn->ctx;
  10320. struct mg_context rctx = *(conn->ctx);
  10321. char txt[32]; /* will not overflow */
  10322. if (timeout >= 0) {
  10323. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10324. rctx.config[REQUEST_TIMEOUT] = txt;
  10325. set_sock_timeout(conn->client.sock, timeout);
  10326. } else {
  10327. rctx.config[REQUEST_TIMEOUT] = NULL;
  10328. }
  10329. conn->ctx = &rctx;
  10330. ret = getreq(conn, ebuf, ebuf_len, &err);
  10331. conn->ctx = octx;
  10332. /* TODO: 1) uri is deprecated;
  10333. * 2) here, ri.uri is the http response code */
  10334. conn->request_info.uri = conn->request_info.request_uri;
  10335. /* TODO (mid): Define proper return values - maybe return length?
  10336. * For the first test use <0 for error and >0 for OK */
  10337. return (ret == 0) ? -1 : +1;
  10338. }
  10339. return -1;
  10340. }
  10341. struct mg_connection *
  10342. mg_download(const char *host,
  10343. int port,
  10344. int use_ssl,
  10345. char *ebuf,
  10346. size_t ebuf_len,
  10347. const char *fmt,
  10348. ...)
  10349. {
  10350. struct mg_connection *conn;
  10351. va_list ap;
  10352. int i;
  10353. int reqerr;
  10354. va_start(ap, fmt);
  10355. ebuf[0] = '\0';
  10356. /* open a connection */
  10357. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10358. if (conn != NULL) {
  10359. i = mg_vprintf(conn, fmt, ap);
  10360. if (i <= 0) {
  10361. mg_snprintf(conn,
  10362. NULL, /* No truncation check for ebuf */
  10363. ebuf,
  10364. ebuf_len,
  10365. "%s",
  10366. "Error sending request");
  10367. } else {
  10368. getreq(conn, ebuf, ebuf_len, &reqerr);
  10369. /* TODO: 1) uri is deprecated;
  10370. * 2) here, ri.uri is the http response code */
  10371. conn->request_info.uri = conn->request_info.request_uri;
  10372. }
  10373. }
  10374. /* if an error occured, close the connection */
  10375. if (ebuf[0] != '\0' && conn != NULL) {
  10376. mg_close_connection(conn);
  10377. conn = NULL;
  10378. }
  10379. va_end(ap);
  10380. return conn;
  10381. }
  10382. struct websocket_client_thread_data {
  10383. struct mg_connection *conn;
  10384. mg_websocket_data_handler data_handler;
  10385. mg_websocket_close_handler close_handler;
  10386. void *callback_data;
  10387. };
  10388. #if defined(USE_WEBSOCKET)
  10389. #ifdef _WIN32
  10390. static unsigned __stdcall websocket_client_thread(void *data)
  10391. #else
  10392. static void *
  10393. websocket_client_thread(void *data)
  10394. #endif
  10395. {
  10396. struct websocket_client_thread_data *cdata =
  10397. (struct websocket_client_thread_data *)data;
  10398. mg_set_thread_name("ws-client");
  10399. if (cdata->conn->ctx) {
  10400. if (cdata->conn->ctx->callbacks.init_thread) {
  10401. /* 3 indicates a websocket client thread */
  10402. /* TODO: check if conn->ctx can be set */
  10403. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10404. }
  10405. }
  10406. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10407. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10408. if (cdata->close_handler != NULL) {
  10409. cdata->close_handler(cdata->conn, cdata->callback_data);
  10410. }
  10411. mg_free((void *)cdata);
  10412. #ifdef _WIN32
  10413. return 0;
  10414. #else
  10415. return NULL;
  10416. #endif
  10417. }
  10418. #endif
  10419. struct mg_connection *
  10420. mg_connect_websocket_client(const char *host,
  10421. int port,
  10422. int use_ssl,
  10423. char *error_buffer,
  10424. size_t error_buffer_size,
  10425. const char *path,
  10426. const char *origin,
  10427. mg_websocket_data_handler data_func,
  10428. mg_websocket_close_handler close_func,
  10429. void *user_data)
  10430. {
  10431. struct mg_connection *conn = NULL;
  10432. #if defined(USE_WEBSOCKET)
  10433. struct mg_context *newctx = NULL;
  10434. struct websocket_client_thread_data *thread_data;
  10435. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10436. static const char *handshake_req;
  10437. if (origin != NULL) {
  10438. handshake_req = "GET %s HTTP/1.1\r\n"
  10439. "Host: %s\r\n"
  10440. "Upgrade: websocket\r\n"
  10441. "Connection: Upgrade\r\n"
  10442. "Sec-WebSocket-Key: %s\r\n"
  10443. "Sec-WebSocket-Version: 13\r\n"
  10444. "Origin: %s\r\n"
  10445. "\r\n";
  10446. } else {
  10447. handshake_req = "GET %s HTTP/1.1\r\n"
  10448. "Host: %s\r\n"
  10449. "Upgrade: websocket\r\n"
  10450. "Connection: Upgrade\r\n"
  10451. "Sec-WebSocket-Key: %s\r\n"
  10452. "Sec-WebSocket-Version: 13\r\n"
  10453. "\r\n";
  10454. }
  10455. /* Establish the client connection and request upgrade */
  10456. conn = mg_download(host,
  10457. port,
  10458. use_ssl,
  10459. error_buffer,
  10460. error_buffer_size,
  10461. handshake_req,
  10462. path,
  10463. host,
  10464. magic,
  10465. origin);
  10466. /* Connection object will be null if something goes wrong */
  10467. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10468. if (!*error_buffer) {
  10469. /* if there is a connection, but it did not return 101,
  10470. * error_buffer is not yet set */
  10471. mg_snprintf(conn,
  10472. NULL, /* No truncation check for ebuf */
  10473. error_buffer,
  10474. error_buffer_size,
  10475. "Unexpected server reply");
  10476. }
  10477. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10478. if (conn != NULL) {
  10479. mg_free(conn);
  10480. conn = NULL;
  10481. }
  10482. return conn;
  10483. }
  10484. /* For client connections, mg_context is fake. Since we need to set a
  10485. * callback function, we need to create a copy and modify it. */
  10486. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10487. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10488. newctx->user_data = user_data;
  10489. newctx->context_type = 2; /* client context type */
  10490. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10491. newctx->workerthreadids =
  10492. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10493. conn->ctx = newctx;
  10494. thread_data = (struct websocket_client_thread_data *)
  10495. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10496. thread_data->conn = conn;
  10497. thread_data->data_handler = data_func;
  10498. thread_data->close_handler = close_func;
  10499. thread_data->callback_data = NULL;
  10500. /* Start a thread to read the websocket client connection
  10501. * This thread will automatically stop when mg_disconnect is
  10502. * called on the client connection */
  10503. if (mg_start_thread_with_id(websocket_client_thread,
  10504. (void *)thread_data,
  10505. newctx->workerthreadids) != 0) {
  10506. mg_free((void *)thread_data);
  10507. mg_free((void *)newctx->workerthreadids);
  10508. mg_free((void *)newctx);
  10509. mg_free((void *)conn);
  10510. conn = NULL;
  10511. DEBUG_TRACE("%s",
  10512. "Websocket client connect thread could not be started\r\n");
  10513. }
  10514. #else
  10515. /* Appease "unused parameter" warnings */
  10516. (void)host;
  10517. (void)port;
  10518. (void)use_ssl;
  10519. (void)error_buffer;
  10520. (void)error_buffer_size;
  10521. (void)path;
  10522. (void)origin;
  10523. (void)user_data;
  10524. (void)data_func;
  10525. (void)close_func;
  10526. #endif
  10527. return conn;
  10528. }
  10529. static void
  10530. process_new_connection(struct mg_connection *conn)
  10531. {
  10532. if (conn && conn->ctx) {
  10533. struct mg_request_info *ri = &conn->request_info;
  10534. int keep_alive_enabled, keep_alive, discard_len;
  10535. char ebuf[100];
  10536. const char *hostend;
  10537. int reqerr, uri_type;
  10538. keep_alive_enabled =
  10539. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10540. /* Important: on new connection, reset the receiving buffer. Credit
  10541. * goes to crule42. */
  10542. conn->data_len = 0;
  10543. do {
  10544. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10545. /* The request sent by the client could not be understood by
  10546. * the server, or it was incomplete or a timeout. Send an
  10547. * error message and close the connection. */
  10548. if (reqerr > 0) {
  10549. /*assert(ebuf[0] != '\0');*/
  10550. send_http_error(conn, reqerr, "%s", ebuf);
  10551. }
  10552. } else if (strcmp(ri->http_version, "1.0")
  10553. && strcmp(ri->http_version, "1.1")) {
  10554. mg_snprintf(conn,
  10555. NULL, /* No truncation check for ebuf */
  10556. ebuf,
  10557. sizeof(ebuf),
  10558. "Bad HTTP version: [%s]",
  10559. ri->http_version);
  10560. send_http_error(conn, 505, "%s", ebuf);
  10561. }
  10562. if (ebuf[0] == '\0') {
  10563. uri_type = get_uri_type(conn->request_info.request_uri);
  10564. switch (uri_type) {
  10565. case 1:
  10566. /* Asterisk */
  10567. conn->request_info.local_uri = NULL;
  10568. break;
  10569. case 2:
  10570. /* relative uri */
  10571. conn->request_info.local_uri =
  10572. conn->request_info.request_uri;
  10573. break;
  10574. case 3:
  10575. case 4:
  10576. /* absolute uri (with/without port) */
  10577. hostend = get_rel_url_at_current_server(
  10578. conn->request_info.request_uri, conn);
  10579. if (hostend) {
  10580. conn->request_info.local_uri = hostend;
  10581. } else {
  10582. conn->request_info.local_uri = NULL;
  10583. }
  10584. break;
  10585. default:
  10586. mg_snprintf(conn,
  10587. NULL, /* No truncation check for ebuf */
  10588. ebuf,
  10589. sizeof(ebuf),
  10590. "Invalid URI: [%s]",
  10591. ri->request_uri);
  10592. send_http_error(conn, 400, "%s", ebuf);
  10593. break;
  10594. }
  10595. /* TODO: cleanup uri, local_uri and request_uri */
  10596. conn->request_info.uri = conn->request_info.local_uri;
  10597. }
  10598. if (ebuf[0] == '\0') {
  10599. if (conn->request_info.local_uri) {
  10600. /* handle request to local server */
  10601. handle_request(conn);
  10602. if (conn->ctx->callbacks.end_request != NULL) {
  10603. conn->ctx->callbacks.end_request(conn,
  10604. conn->status_code);
  10605. }
  10606. log_access(conn);
  10607. } else {
  10608. /* TODO: handle non-local request (PROXY) */
  10609. conn->must_close = 1;
  10610. }
  10611. } else {
  10612. conn->must_close = 1;
  10613. }
  10614. if (ri->remote_user != NULL) {
  10615. mg_free((void *)ri->remote_user);
  10616. /* Important! When having connections with and without auth
  10617. * would cause double free and then crash */
  10618. ri->remote_user = NULL;
  10619. }
  10620. /* NOTE(lsm): order is important here. should_keep_alive() call
  10621. * is
  10622. * using parsed request, which will be invalid after memmove's
  10623. * below.
  10624. * Therefore, memorize should_keep_alive() result now for later
  10625. * use
  10626. * in loop exit condition. */
  10627. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10628. && conn->content_len >= 0 && should_keep_alive(conn);
  10629. /* Discard all buffered data for this request */
  10630. discard_len = conn->content_len >= 0 && conn->request_len > 0
  10631. && conn->request_len + conn->content_len
  10632. < (int64_t)conn->data_len
  10633. ? (int)(conn->request_len + conn->content_len)
  10634. : conn->data_len;
  10635. /*assert(discard_len >= 0);*/
  10636. if (discard_len < 0)
  10637. break;
  10638. conn->data_len -= discard_len;
  10639. if (conn->data_len > 0) {
  10640. memmove(conn->buf,
  10641. conn->buf + discard_len,
  10642. (size_t)conn->data_len);
  10643. }
  10644. /* assert(conn->data_len >= 0); */
  10645. /* assert(conn->data_len <= conn->buf_size); */
  10646. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10647. break;
  10648. }
  10649. } while (keep_alive);
  10650. }
  10651. }
  10652. /* Worker threads take accepted socket from the queue */
  10653. static int
  10654. consume_socket(struct mg_context *ctx, struct socket *sp)
  10655. {
  10656. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10657. if (!ctx) {
  10658. return 0;
  10659. }
  10660. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10661. DEBUG_TRACE("%s", "going idle");
  10662. /* If the queue is empty, wait. We're idle at this point. */
  10663. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10664. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10665. }
  10666. /* If we're stopping, sq_head may be equal to sq_tail. */
  10667. if (ctx->sq_head > ctx->sq_tail) {
  10668. /* Copy socket from the queue and increment tail */
  10669. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10670. ctx->sq_tail++;
  10671. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10672. /* Wrap pointers if needed */
  10673. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10674. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10675. ctx->sq_head -= QUEUE_SIZE(ctx);
  10676. }
  10677. }
  10678. (void)pthread_cond_signal(&ctx->sq_empty);
  10679. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10680. return !ctx->stop_flag;
  10681. #undef QUEUE_SIZE
  10682. }
  10683. static void *
  10684. worker_thread_run(void *thread_func_param)
  10685. {
  10686. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10687. struct mg_connection *conn;
  10688. struct mg_workerTLS tls;
  10689. #if defined(MG_LEGACY_INTERFACE)
  10690. uint32_t addr;
  10691. #endif
  10692. mg_set_thread_name("worker");
  10693. tls.is_master = 0;
  10694. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10695. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10696. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10697. #endif
  10698. if (ctx->callbacks.init_thread) {
  10699. /* call init_thread for a worker thread (type 1) */
  10700. ctx->callbacks.init_thread(ctx, 1);
  10701. }
  10702. conn =
  10703. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10704. if (conn == NULL) {
  10705. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10706. } else {
  10707. pthread_setspecific(sTlsKey, &tls);
  10708. conn->buf_size = MAX_REQUEST_SIZE;
  10709. conn->buf = (char *)(conn + 1);
  10710. conn->ctx = ctx;
  10711. conn->request_info.user_data = ctx->user_data;
  10712. /* Allocate a mutex for this connection to allow communication both
  10713. * within the request handler and from elsewhere in the application
  10714. */
  10715. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10716. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10717. * signal sq_empty condvar to wake up the master waiting in
  10718. * produce_socket() */
  10719. while (consume_socket(ctx, &conn->client)) {
  10720. conn->conn_birth_time = time(NULL);
  10721. /* Fill in IP, port info early so even if SSL setup below fails,
  10722. * error handler would have the corresponding info.
  10723. * Thanks to Johannes Winkelmann for the patch.
  10724. */
  10725. #if defined(USE_IPV6)
  10726. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10727. conn->request_info.remote_port =
  10728. ntohs(conn->client.rsa.sin6.sin6_port);
  10729. } else
  10730. #endif
  10731. {
  10732. conn->request_info.remote_port =
  10733. ntohs(conn->client.rsa.sin.sin_port);
  10734. }
  10735. sockaddr_to_string(conn->request_info.remote_addr,
  10736. sizeof(conn->request_info.remote_addr),
  10737. &conn->client.rsa);
  10738. #if defined(MG_LEGACY_INTERFACE)
  10739. /* This legacy interface only works for the IPv4 case */
  10740. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10741. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10742. #endif
  10743. conn->request_info.is_ssl = conn->client.is_ssl;
  10744. if (!conn->client.is_ssl
  10745. #ifndef NO_SSL
  10746. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10747. #endif
  10748. ) {
  10749. process_new_connection(conn);
  10750. }
  10751. close_connection(conn);
  10752. }
  10753. }
  10754. /* Signal master that we're done with connection and exiting */
  10755. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10756. ctx->running_worker_threads--;
  10757. (void)pthread_cond_signal(&ctx->thread_cond);
  10758. /* assert(ctx->running_worker_threads >= 0); */
  10759. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10760. pthread_setspecific(sTlsKey, NULL);
  10761. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10762. CloseHandle(tls.pthread_cond_helper_mutex);
  10763. #endif
  10764. pthread_mutex_destroy(&conn->mutex);
  10765. mg_free(conn);
  10766. DEBUG_TRACE("%s", "exiting");
  10767. return NULL;
  10768. }
  10769. /* Threads have different return types on Windows and Unix. */
  10770. #ifdef _WIN32
  10771. static unsigned __stdcall worker_thread(void *thread_func_param)
  10772. {
  10773. worker_thread_run(thread_func_param);
  10774. return 0;
  10775. }
  10776. #else
  10777. static void *
  10778. worker_thread(void *thread_func_param)
  10779. {
  10780. worker_thread_run(thread_func_param);
  10781. return NULL;
  10782. }
  10783. #endif /* _WIN32 */
  10784. /* Master thread adds accepted socket to a queue */
  10785. static void
  10786. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10787. {
  10788. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10789. if (!ctx) {
  10790. return;
  10791. }
  10792. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10793. /* If the queue is full, wait */
  10794. while (ctx->stop_flag == 0
  10795. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10796. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10797. }
  10798. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10799. /* Copy socket to the queue and increment head */
  10800. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10801. ctx->sq_head++;
  10802. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10803. }
  10804. (void)pthread_cond_signal(&ctx->sq_full);
  10805. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10806. #undef QUEUE_SIZE
  10807. }
  10808. static void
  10809. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10810. {
  10811. struct socket so;
  10812. char src_addr[IP_ADDR_STR_LEN];
  10813. socklen_t len = sizeof(so.rsa);
  10814. int on = 1;
  10815. int timeout;
  10816. if (!listener) {
  10817. return;
  10818. }
  10819. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10820. == INVALID_SOCKET) {
  10821. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10822. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10823. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10824. closesocket(so.sock);
  10825. so.sock = INVALID_SOCKET;
  10826. } else {
  10827. /* Put so socket structure into the queue */
  10828. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10829. set_close_on_exec(so.sock, fc(ctx));
  10830. so.is_ssl = listener->is_ssl;
  10831. so.ssl_redir = listener->ssl_redir;
  10832. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10833. mg_cry(fc(ctx),
  10834. "%s: getsockname() failed: %s",
  10835. __func__,
  10836. strerror(ERRNO));
  10837. }
  10838. /* Set TCP keep-alive. This is needed because if HTTP-level
  10839. * keep-alive
  10840. * is enabled, and client resets the connection, server won't get
  10841. * TCP FIN or RST and will keep the connection open forever. With
  10842. * TCP keep-alive, next keep-alive handshake will figure out that
  10843. * the client is down and will close the server end.
  10844. * Thanks to Igor Klopov who suggested the patch. */
  10845. if (setsockopt(so.sock,
  10846. SOL_SOCKET,
  10847. SO_KEEPALIVE,
  10848. (SOCK_OPT_TYPE)&on,
  10849. sizeof(on)) != 0) {
  10850. mg_cry(fc(ctx),
  10851. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10852. __func__,
  10853. strerror(ERRNO));
  10854. }
  10855. /* Disable TCP Nagle's algorithm. Normally TCP packets are
  10856. * coalesced
  10857. * to effectively fill up the underlying IP packet payload and
  10858. * reduce
  10859. * the overhead of sending lots of small buffers. However this hurts
  10860. * the server's throughput (ie. operations per second) when HTTP 1.1
  10861. * persistent connections are used and the responses are relatively
  10862. * small (eg. less than 1400 bytes).
  10863. */
  10864. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  10865. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  10866. if (set_tcp_nodelay(so.sock, 1) != 0) {
  10867. mg_cry(fc(ctx),
  10868. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  10869. __func__,
  10870. strerror(ERRNO));
  10871. }
  10872. }
  10873. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10874. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10875. } else {
  10876. timeout = -1;
  10877. }
  10878. /* Set socket timeout to the given value, but not more than a
  10879. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10880. * so the server can exit after that time if requested. */
  10881. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10882. set_sock_timeout(so.sock, timeout);
  10883. } else {
  10884. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10885. }
  10886. produce_socket(ctx, &so);
  10887. }
  10888. }
  10889. static void
  10890. master_thread_run(void *thread_func_param)
  10891. {
  10892. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10893. struct mg_workerTLS tls;
  10894. struct pollfd *pfd;
  10895. unsigned int i;
  10896. unsigned int workerthreadcount;
  10897. if (!ctx) {
  10898. return;
  10899. }
  10900. mg_set_thread_name("master");
  10901. /* Increase priority of the master thread */
  10902. #if defined(_WIN32)
  10903. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10904. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10905. int min_prio = sched_get_priority_min(SCHED_RR);
  10906. int max_prio = sched_get_priority_max(SCHED_RR);
  10907. if ((min_prio >= 0) && (max_prio >= 0)
  10908. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10909. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10910. struct sched_param sched_param = {0};
  10911. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10912. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10913. }
  10914. #endif
  10915. /* Initialize thread local storage */
  10916. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10917. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10918. #endif
  10919. tls.is_master = 1;
  10920. pthread_setspecific(sTlsKey, &tls);
  10921. if (ctx->callbacks.init_thread) {
  10922. /* Callback for the master thread (type 0) */
  10923. ctx->callbacks.init_thread(ctx, 0);
  10924. }
  10925. /* Server starts *now* */
  10926. ctx->start_time = time(NULL);
  10927. /* Allocate memory for the listening sockets, and start the server */
  10928. pfd =
  10929. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10930. while (pfd != NULL && ctx->stop_flag == 0) {
  10931. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10932. pfd[i].fd = ctx->listening_sockets[i].sock;
  10933. pfd[i].events = POLLIN;
  10934. }
  10935. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10936. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10937. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10938. * successful poll, and POLLIN is defined as
  10939. * (POLLRDNORM | POLLRDBAND)
  10940. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10941. * pfd[i].revents == POLLIN. */
  10942. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10943. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10944. }
  10945. }
  10946. }
  10947. }
  10948. mg_free(pfd);
  10949. DEBUG_TRACE("%s", "stopping workers");
  10950. /* Stop signal received: somebody called mg_stop. Quit. */
  10951. close_all_listening_sockets(ctx);
  10952. /* Wakeup workers that are waiting for connections to handle. */
  10953. pthread_cond_broadcast(&ctx->sq_full);
  10954. /* Wait until all threads finish */
  10955. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10956. while (ctx->running_worker_threads > 0) {
  10957. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10958. }
  10959. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10960. /* Join all worker threads to avoid leaking threads. */
  10961. workerthreadcount = ctx->cfg_worker_threads;
  10962. for (i = 0; i < workerthreadcount; i++) {
  10963. if (ctx->workerthreadids[i] != 0) {
  10964. mg_join_thread(ctx->workerthreadids[i]);
  10965. }
  10966. }
  10967. #if !defined(NO_SSL)
  10968. if (ctx->ssl_ctx != NULL) {
  10969. uninitialize_ssl(ctx);
  10970. }
  10971. #endif
  10972. DEBUG_TRACE("%s", "exiting");
  10973. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10974. CloseHandle(tls.pthread_cond_helper_mutex);
  10975. #endif
  10976. pthread_setspecific(sTlsKey, NULL);
  10977. /* Signal mg_stop() that we're done.
  10978. * WARNING: This must be the very last thing this
  10979. * thread does, as ctx becomes invalid after this line. */
  10980. ctx->stop_flag = 2;
  10981. }
  10982. /* Threads have different return types on Windows and Unix. */
  10983. #ifdef _WIN32
  10984. static unsigned __stdcall master_thread(void *thread_func_param)
  10985. {
  10986. master_thread_run(thread_func_param);
  10987. return 0;
  10988. }
  10989. #else
  10990. static void *
  10991. master_thread(void *thread_func_param)
  10992. {
  10993. master_thread_run(thread_func_param);
  10994. return NULL;
  10995. }
  10996. #endif /* _WIN32 */
  10997. static void
  10998. free_context(struct mg_context *ctx)
  10999. {
  11000. int i;
  11001. struct mg_handler_info *tmp_rh;
  11002. if (ctx == NULL) {
  11003. return;
  11004. }
  11005. if (ctx->callbacks.exit_context) {
  11006. ctx->callbacks.exit_context(ctx);
  11007. }
  11008. /* All threads exited, no sync is needed. Destroy thread mutex and
  11009. * condvars
  11010. */
  11011. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11012. (void)pthread_cond_destroy(&ctx->thread_cond);
  11013. (void)pthread_cond_destroy(&ctx->sq_empty);
  11014. (void)pthread_cond_destroy(&ctx->sq_full);
  11015. /* Destroy other context global data structures mutex */
  11016. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11017. #if defined(USE_TIMERS)
  11018. timers_exit(ctx);
  11019. #endif
  11020. /* Deallocate config parameters */
  11021. for (i = 0; i < NUM_OPTIONS; i++) {
  11022. if (ctx->config[i] != NULL) {
  11023. #if defined(_MSC_VER)
  11024. #pragma warning(suppress : 6001)
  11025. #endif
  11026. mg_free(ctx->config[i]);
  11027. }
  11028. }
  11029. /* Deallocate request handlers */
  11030. while (ctx->handlers) {
  11031. tmp_rh = ctx->handlers;
  11032. ctx->handlers = tmp_rh->next;
  11033. mg_free(tmp_rh->uri);
  11034. mg_free(tmp_rh);
  11035. }
  11036. #ifndef NO_SSL
  11037. /* Deallocate SSL context */
  11038. if (ctx->ssl_ctx != NULL) {
  11039. SSL_CTX_free(ctx->ssl_ctx);
  11040. }
  11041. #endif /* !NO_SSL */
  11042. /* Deallocate worker thread ID array */
  11043. if (ctx->workerthreadids != NULL) {
  11044. mg_free(ctx->workerthreadids);
  11045. }
  11046. /* Deallocate the tls variable */
  11047. if (mg_atomic_dec(&sTlsInit) == 0) {
  11048. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11049. DeleteCriticalSection(&global_log_file_lock);
  11050. #endif /* _WIN32 && !__SYMBIAN32__ */
  11051. #if !defined(_WIN32)
  11052. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11053. #endif
  11054. pthread_key_delete(sTlsKey);
  11055. }
  11056. /* deallocate system name string */
  11057. mg_free(ctx->systemName);
  11058. /* Deallocate context itself */
  11059. mg_free(ctx);
  11060. }
  11061. void
  11062. mg_stop(struct mg_context *ctx)
  11063. {
  11064. pthread_t mt;
  11065. if (!ctx) {
  11066. return;
  11067. }
  11068. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11069. * two threads is not allowed. */
  11070. mt = ctx->masterthreadid;
  11071. if (mt == 0) {
  11072. return;
  11073. }
  11074. ctx->masterthreadid = 0;
  11075. ctx->stop_flag = 1;
  11076. /* Wait until mg_fini() stops */
  11077. while (ctx->stop_flag != 2) {
  11078. (void)mg_sleep(10);
  11079. }
  11080. mg_join_thread(mt);
  11081. free_context(ctx);
  11082. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11083. (void)WSACleanup();
  11084. #endif /* _WIN32 && !__SYMBIAN32__ */
  11085. }
  11086. static void
  11087. get_system_name(char **sysName)
  11088. {
  11089. #if defined(_WIN32)
  11090. #if !defined(__SYMBIAN32__)
  11091. char name[128];
  11092. DWORD dwVersion = 0;
  11093. DWORD dwMajorVersion = 0;
  11094. DWORD dwMinorVersion = 0;
  11095. DWORD dwBuild = 0;
  11096. #ifdef _MSC_VER
  11097. #pragma warning(push)
  11098. // GetVersion was declared deprecated
  11099. #pragma warning(disable : 4996)
  11100. #endif
  11101. dwVersion = GetVersion();
  11102. #ifdef _MSC_VER
  11103. #pragma warning(pop)
  11104. #endif
  11105. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11106. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11107. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11108. (void)dwBuild;
  11109. sprintf(name,
  11110. "Windows %u.%u",
  11111. (unsigned)dwMajorVersion,
  11112. (unsigned)dwMinorVersion);
  11113. *sysName = mg_strdup(name);
  11114. #else
  11115. *sysName = mg_strdup("Symbian");
  11116. #endif
  11117. #else
  11118. struct utsname name;
  11119. memset(&name, 0, sizeof(name));
  11120. uname(&name);
  11121. *sysName = mg_strdup(name.sysname);
  11122. #endif
  11123. }
  11124. struct mg_context *
  11125. mg_start(const struct mg_callbacks *callbacks,
  11126. void *user_data,
  11127. const char **options)
  11128. {
  11129. struct mg_context *ctx;
  11130. const char *name, *value, *default_value;
  11131. int idx, ok, workerthreadcount;
  11132. unsigned int i;
  11133. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11134. struct mg_workerTLS tls;
  11135. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11136. WSADATA data;
  11137. WSAStartup(MAKEWORD(2, 2), &data);
  11138. #endif /* _WIN32 && !__SYMBIAN32__ */
  11139. /* Allocate context and initialize reasonable general case defaults. */
  11140. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11141. return NULL;
  11142. }
  11143. /* Random number generator will initialize at the first call */
  11144. ctx->auth_nonce_mask =
  11145. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11146. if (mg_atomic_inc(&sTlsInit) == 1) {
  11147. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11148. InitializeCriticalSection(&global_log_file_lock);
  11149. #endif /* _WIN32 && !__SYMBIAN32__ */
  11150. #if !defined(_WIN32)
  11151. pthread_mutexattr_init(&pthread_mutex_attr);
  11152. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11153. #endif
  11154. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11155. /* Fatal error - abort start. However, this situation should
  11156. * never
  11157. * occur in practice. */
  11158. mg_atomic_dec(&sTlsInit);
  11159. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11160. mg_free(ctx);
  11161. return NULL;
  11162. }
  11163. } else {
  11164. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11165. * initialized. */
  11166. mg_sleep(1);
  11167. }
  11168. tls.is_master = -1;
  11169. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11170. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11171. tls.pthread_cond_helper_mutex = NULL;
  11172. #endif
  11173. pthread_setspecific(sTlsKey, &tls);
  11174. #if defined(USE_LUA)
  11175. lua_init_optional_libraries();
  11176. #endif
  11177. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11178. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  11179. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11180. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11181. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11182. if (!ok) {
  11183. /* Fatal error - abort start. However, this situation should never
  11184. * occur in practice. */
  11185. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11186. mg_free(ctx);
  11187. pthread_setspecific(sTlsKey, NULL);
  11188. return NULL;
  11189. }
  11190. if (callbacks) {
  11191. ctx->callbacks = *callbacks;
  11192. exit_callback = callbacks->exit_context;
  11193. ctx->callbacks.exit_context = 0;
  11194. }
  11195. ctx->user_data = user_data;
  11196. ctx->handlers = NULL;
  11197. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11198. ctx->shared_lua_websockets = 0;
  11199. #endif
  11200. while (options && (name = *options++) != NULL) {
  11201. if ((idx = get_option_index(name)) == -1) {
  11202. mg_cry(fc(ctx), "Invalid option: %s", name);
  11203. free_context(ctx);
  11204. pthread_setspecific(sTlsKey, NULL);
  11205. return NULL;
  11206. } else if ((value = *options++) == NULL) {
  11207. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11208. free_context(ctx);
  11209. pthread_setspecific(sTlsKey, NULL);
  11210. return NULL;
  11211. }
  11212. if (ctx->config[idx] != NULL) {
  11213. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11214. mg_free(ctx->config[idx]);
  11215. }
  11216. ctx->config[idx] = mg_strdup(value);
  11217. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11218. }
  11219. /* Set default value if needed */
  11220. for (i = 0; config_options[i].name != NULL; i++) {
  11221. default_value = config_options[i].default_value;
  11222. if (ctx->config[i] == NULL && default_value != NULL) {
  11223. ctx->config[i] = mg_strdup(default_value);
  11224. }
  11225. }
  11226. #if defined(NO_FILES)
  11227. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11228. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11229. free_context(ctx);
  11230. pthread_setspecific(sTlsKey, NULL);
  11231. return NULL;
  11232. }
  11233. #endif
  11234. get_system_name(&ctx->systemName);
  11235. /* NOTE(lsm): order is important here. SSL certificates must
  11236. * be initialized before listening ports. UID must be set last. */
  11237. if (!set_gpass_option(ctx) ||
  11238. #if !defined(NO_SSL)
  11239. !set_ssl_option(ctx) ||
  11240. #endif
  11241. !set_ports_option(ctx) ||
  11242. #if !defined(_WIN32)
  11243. !set_uid_option(ctx) ||
  11244. #endif
  11245. !set_acl_option(ctx)) {
  11246. free_context(ctx);
  11247. pthread_setspecific(sTlsKey, NULL);
  11248. return NULL;
  11249. }
  11250. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11251. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11252. * won't kill the whole process. */
  11253. (void)signal(SIGPIPE, SIG_IGN);
  11254. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11255. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11256. if (workerthreadcount > MAX_WORKER_THREADS) {
  11257. mg_cry(fc(ctx), "Too many worker threads");
  11258. free_context(ctx);
  11259. pthread_setspecific(sTlsKey, NULL);
  11260. return NULL;
  11261. }
  11262. if (workerthreadcount > 0) {
  11263. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11264. ctx->workerthreadids =
  11265. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11266. if (ctx->workerthreadids == NULL) {
  11267. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11268. free_context(ctx);
  11269. pthread_setspecific(sTlsKey, NULL);
  11270. return NULL;
  11271. }
  11272. }
  11273. #if defined(USE_TIMERS)
  11274. if (timers_init(ctx) != 0) {
  11275. mg_cry(fc(ctx), "Error creating timers");
  11276. free_context(ctx);
  11277. pthread_setspecific(sTlsKey, NULL);
  11278. return NULL;
  11279. }
  11280. #endif
  11281. /* Context has been created - init user libraries */
  11282. if (ctx->callbacks.init_context) {
  11283. ctx->callbacks.init_context(ctx);
  11284. }
  11285. ctx->callbacks.exit_context = exit_callback;
  11286. ctx->context_type = 1; /* server context */
  11287. /* Start master (listening) thread */
  11288. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11289. /* Start worker threads */
  11290. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11291. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11292. ctx->running_worker_threads++;
  11293. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11294. if (mg_start_thread_with_id(worker_thread,
  11295. ctx,
  11296. &ctx->workerthreadids[i]) != 0) {
  11297. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11298. ctx->running_worker_threads--;
  11299. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11300. if (i > 0) {
  11301. mg_cry(fc(ctx),
  11302. "Cannot start worker thread %i: error %ld",
  11303. i + 1,
  11304. (long)ERRNO);
  11305. } else {
  11306. mg_cry(fc(ctx),
  11307. "Cannot create threads: error %ld",
  11308. (long)ERRNO);
  11309. free_context(ctx);
  11310. pthread_setspecific(sTlsKey, NULL);
  11311. return NULL;
  11312. }
  11313. break;
  11314. }
  11315. }
  11316. pthread_setspecific(sTlsKey, NULL);
  11317. return ctx;
  11318. }
  11319. /* Feature check API function */
  11320. unsigned
  11321. mg_check_feature(unsigned feature)
  11322. {
  11323. static const unsigned feature_set = 0
  11324. /* Set bits for available features according to API documentation.
  11325. * This bit mask is created at compile time, according to the active
  11326. * preprocessor defines. It is a single const value at runtime. */
  11327. #if !defined(NO_FILES)
  11328. | 0x0001u
  11329. #endif
  11330. #if !defined(NO_SSL)
  11331. | 0x0002u
  11332. #endif
  11333. #if !defined(NO_CGI)
  11334. | 0x0004u
  11335. #endif
  11336. #if defined(USE_IPV6)
  11337. | 0x0008u
  11338. #endif
  11339. #if defined(USE_WEBSOCKET)
  11340. | 0x0010u
  11341. #endif
  11342. #if defined(USE_LUA)
  11343. | 0x0020u
  11344. #endif
  11345. #if defined(USE_DUKTAPE)
  11346. | 0x0040u
  11347. #endif
  11348. #if !defined(NO_CACHING)
  11349. | 0x0080u
  11350. #endif
  11351. /* Set some extra bits not defined in the API documentation.
  11352. * These bits may change without further notice. */
  11353. #if defined(MG_LEGACY_INTERFACE)
  11354. | 0x8000u
  11355. #endif
  11356. #if defined(MEMORY_DEBUGGING)
  11357. | 0x0100u
  11358. #endif
  11359. #if defined(USE_TIMERS)
  11360. | 0x0200u
  11361. #endif
  11362. #if !defined(NO_NONCE_CHECK)
  11363. | 0x0400u
  11364. #endif
  11365. #if !defined(NO_POPEN)
  11366. | 0x0800u
  11367. #endif
  11368. ;
  11369. return (feature & feature_set);
  11370. }