civetweb.c 350 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553
  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. #define ALTERNATIVE_QUEUE
  23. #if defined(_WIN32)
  24. #if !defined(_CRT_SECURE_NO_WARNINGS)
  25. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  26. #endif
  27. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  28. #define _WIN32_WINNT 0x0501
  29. #endif
  30. #else
  31. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  32. #define _GNU_SOURCE /* for setgroups() */
  33. #endif
  34. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  35. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  36. #endif
  37. #ifndef _LARGEFILE_SOURCE
  38. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  39. #endif
  40. #ifndef _FILE_OFFSET_BITS
  41. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  42. #endif
  43. #ifndef __STDC_FORMAT_MACROS
  44. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  45. #endif
  46. #ifndef __STDC_LIMIT_MACROS
  47. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  48. #endif
  49. #ifdef __sun
  50. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  51. #define __inline inline /* not recognized on older compiler versions */
  52. #endif
  53. #endif
  54. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  55. #define USE_TIMERS
  56. #endif
  57. #if defined(_MSC_VER)
  58. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  59. #pragma warning(disable : 4306)
  60. /* conditional expression is constant: introduced by FD_SET(..) */
  61. #pragma warning(disable : 4127)
  62. /* non-constant aggregate initializer: issued due to missing C99 support */
  63. #pragma warning(disable : 4204)
  64. /* padding added after data member */
  65. #pragma warning(disable : 4820)
  66. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  67. #pragma warning(disable : 4668)
  68. /* no function prototype given: converting '()' to '(void)' */
  69. #pragma warning(disable : 4255)
  70. /* function has been selected for automatic inline expansion */
  71. #pragma warning(disable : 4711)
  72. #endif
  73. /* This code uses static_assert to check some conditions.
  74. * Unfortunately some compilers still do not support it, so we have a
  75. * replacement function here. */
  76. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  77. #define mg_static_assert static_assert
  78. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  79. #define mg_static_assert static_assert
  80. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  81. #define mg_static_assert _Static_assert
  82. #else
  83. char static_assert_replacement[1];
  84. #define mg_static_assert(cond, txt) \
  85. extern char static_assert_replacement[(cond) ? 1 : -1]
  86. #endif
  87. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  88. "int data type size check");
  89. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  90. "pointer data type size check");
  91. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  92. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  93. * type size check"); */
  94. /* DTL -- including winsock2.h works better if lean and mean */
  95. #ifndef WIN32_LEAN_AND_MEAN
  96. #define WIN32_LEAN_AND_MEAN
  97. #endif
  98. #if defined(__SYMBIAN32__)
  99. #define NO_SSL /* SSL is not supported */
  100. #define NO_CGI /* CGI is not supported */
  101. #define PATH_MAX FILENAME_MAX
  102. #endif /* __SYMBIAN32__ */
  103. /* Include the header file here, so the CivetWeb interface is defined for the
  104. * entire implementation, including the following forward definitions. */
  105. #include "civetweb.h"
  106. #ifndef IGNORE_UNUSED_RESULT
  107. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  108. #endif
  109. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  110. #include <sys/types.h>
  111. #include <sys/stat.h>
  112. #include <errno.h>
  113. #include <signal.h>
  114. #include <fcntl.h>
  115. #endif /* !_WIN32_WCE */
  116. #ifdef __MACH__
  117. #define CLOCK_MONOTONIC (1)
  118. #define CLOCK_REALTIME (2)
  119. #include <sys/time.h>
  120. #include <mach/clock.h>
  121. #include <mach/mach.h>
  122. #include <mach/mach_time.h>
  123. #include <assert.h>
  124. /* clock_gettime is not implemented on OSX */
  125. int clock_gettime(int clk_id, struct timespec *t);
  126. int
  127. clock_gettime(int clk_id, struct timespec *t)
  128. {
  129. memset(t, 0, sizeof(*t));
  130. if (clk_id == CLOCK_REALTIME) {
  131. struct timeval now;
  132. int rv = gettimeofday(&now, NULL);
  133. if (rv) {
  134. return rv;
  135. }
  136. t->tv_sec = now.tv_sec;
  137. t->tv_nsec = now.tv_usec * 1000;
  138. return 0;
  139. } else if (clk_id == CLOCK_MONOTONIC) {
  140. static uint64_t clock_start_time = 0;
  141. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  142. uint64_t now = mach_absolute_time();
  143. if (clock_start_time == 0) {
  144. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  145. #if defined(DEBUG)
  146. assert(mach_status == KERN_SUCCESS);
  147. #else
  148. /* appease "unused variable" warning for release builds */
  149. (void)mach_status;
  150. #endif
  151. clock_start_time = now;
  152. }
  153. now = (uint64_t)((double)(now - clock_start_time)
  154. * (double)timebase_ifo.numer
  155. / (double)timebase_ifo.denom);
  156. t->tv_sec = now / 1000000000;
  157. t->tv_nsec = now % 1000000000;
  158. return 0;
  159. }
  160. return -1; /* EINVAL - Clock ID is unknown */
  161. }
  162. #endif
  163. #include <time.h>
  164. #include <stdlib.h>
  165. #include <stdarg.h>
  166. #include <assert.h>
  167. #include <string.h>
  168. #include <ctype.h>
  169. #include <limits.h>
  170. #include <stddef.h>
  171. #include <stdio.h>
  172. #ifndef MAX_WORKER_THREADS
  173. #define MAX_WORKER_THREADS (1024 * 64)
  174. #endif
  175. #ifndef SOCKET_TIMEOUT_QUANTUM
  176. #define SOCKET_TIMEOUT_QUANTUM (10000)
  177. #endif
  178. mg_static_assert(MAX_WORKER_THREADS >= 1,
  179. "worker threads must be a positive number");
  180. #if defined(_WIN32) \
  181. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  182. #include <windows.h>
  183. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  184. #include <ws2tcpip.h>
  185. typedef const char *SOCK_OPT_TYPE;
  186. #if !defined(PATH_MAX)
  187. #define PATH_MAX (MAX_PATH)
  188. #endif
  189. #if !defined(PATH_MAX)
  190. #define PATH_MAX (4096)
  191. #endif
  192. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  193. #ifndef _IN_PORT_T
  194. #ifndef in_port_t
  195. #define in_port_t u_short
  196. #endif
  197. #endif
  198. #ifndef _WIN32_WCE
  199. #include <process.h>
  200. #include <direct.h>
  201. #include <io.h>
  202. #else /* _WIN32_WCE */
  203. #define NO_CGI /* WinCE has no pipes */
  204. #define NO_POPEN /* WinCE has no popen */
  205. typedef long off_t;
  206. #define errno ((int)(GetLastError()))
  207. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  208. #endif /* _WIN32_WCE */
  209. #define MAKEUQUAD(lo, hi) \
  210. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  211. #define RATE_DIFF (10000000) /* 100 nsecs */
  212. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  213. #define SYS2UNIX_TIME(lo, hi) \
  214. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  215. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  216. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  217. * Also use _strtoui64 on modern M$ compilers */
  218. #if defined(_MSC_VER)
  219. #if (_MSC_VER < 1300)
  220. #define STRX(x) #x
  221. #define STR(x) STRX(x)
  222. #define __func__ __FILE__ ":" STR(__LINE__)
  223. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  224. #define strtoll(x, y, z) (_atoi64(x))
  225. #else
  226. #define __func__ __FUNCTION__
  227. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  228. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  229. #endif
  230. #endif /* _MSC_VER */
  231. #define ERRNO ((int)(GetLastError()))
  232. #define NO_SOCKLEN_T
  233. #if defined(_WIN64) || defined(__MINGW64__)
  234. #define SSL_LIB "ssleay64.dll"
  235. #define CRYPTO_LIB "libeay64.dll"
  236. #else
  237. #define SSL_LIB "ssleay32.dll"
  238. #define CRYPTO_LIB "libeay32.dll"
  239. #endif
  240. #define O_NONBLOCK (0)
  241. #ifndef W_OK
  242. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  243. #endif
  244. #if !defined(EWOULDBLOCK)
  245. #define EWOULDBLOCK WSAEWOULDBLOCK
  246. #endif /* !EWOULDBLOCK */
  247. #define _POSIX_
  248. #define INT64_FMT "I64d"
  249. #define UINT64_FMT "I64u"
  250. #define WINCDECL __cdecl
  251. #define SHUT_RD (0)
  252. #define SHUT_WR (1)
  253. #define SHUT_BOTH (2)
  254. #define vsnprintf_impl _vsnprintf
  255. #define access _access
  256. #define mg_sleep(x) (Sleep(x))
  257. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  258. #ifndef popen
  259. #define popen(x, y) (_popen(x, y))
  260. #endif
  261. #ifndef pclose
  262. #define pclose(x) (_pclose(x))
  263. #endif
  264. #define close(x) (_close(x))
  265. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  266. #define RTLD_LAZY (0)
  267. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  268. #define fdopen(x, y) (_fdopen((x), (y)))
  269. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  270. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  271. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  272. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  273. #define sleep(x) (Sleep((x)*1000))
  274. #define rmdir(x) (_rmdir(x))
  275. #define timegm(x) (_mkgmtime(x))
  276. #if !defined(fileno)
  277. #define fileno(x) (_fileno(x))
  278. #endif /* !fileno MINGW #defines fileno */
  279. typedef HANDLE pthread_mutex_t;
  280. typedef DWORD pthread_key_t;
  281. typedef HANDLE pthread_t;
  282. typedef struct {
  283. CRITICAL_SECTION threadIdSec;
  284. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  285. } pthread_cond_t;
  286. #ifndef __clockid_t_defined
  287. typedef DWORD clockid_t;
  288. #endif
  289. #ifndef CLOCK_MONOTONIC
  290. #define CLOCK_MONOTONIC (1)
  291. #endif
  292. #ifndef CLOCK_REALTIME
  293. #define CLOCK_REALTIME (2)
  294. #endif
  295. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  296. #define _TIMESPEC_DEFINED
  297. #endif
  298. #ifndef _TIMESPEC_DEFINED
  299. struct timespec {
  300. time_t tv_sec; /* seconds */
  301. long tv_nsec; /* nanoseconds */
  302. };
  303. #endif
  304. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  305. static int pthread_mutex_lock(pthread_mutex_t *);
  306. static int pthread_mutex_unlock(pthread_mutex_t *);
  307. static void path_to_unicode(const struct mg_connection *conn,
  308. const char *path,
  309. wchar_t *wbuf,
  310. size_t wbuf_len);
  311. struct file;
  312. static const char *
  313. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  314. #if defined(HAVE_STDINT)
  315. #include <stdint.h>
  316. #else
  317. typedef unsigned char uint8_t;
  318. typedef unsigned short uint16_t;
  319. typedef unsigned int uint32_t;
  320. typedef unsigned __int64 uint64_t;
  321. typedef __int64 int64_t;
  322. #ifndef INT64_MAX
  323. #define INT64_MAX (9223372036854775807)
  324. #endif
  325. #endif /* HAVE_STDINT */
  326. /* POSIX dirent interface */
  327. struct dirent {
  328. char d_name[PATH_MAX];
  329. };
  330. typedef struct DIR {
  331. HANDLE handle;
  332. WIN32_FIND_DATAW info;
  333. struct dirent result;
  334. } DIR;
  335. #if defined(_WIN32) && !defined(POLLIN)
  336. #ifndef HAVE_POLL
  337. struct pollfd {
  338. SOCKET fd;
  339. short events;
  340. short revents;
  341. };
  342. #define POLLIN (0x0300)
  343. #endif
  344. #endif
  345. /* Mark required libraries */
  346. #if defined(_MSC_VER)
  347. #pragma comment(lib, "Ws2_32.lib")
  348. #endif
  349. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  350. WINDOWS / UNIX include block */
  351. #include <sys/wait.h>
  352. #include <sys/socket.h>
  353. #include <sys/poll.h>
  354. #include <netinet/in.h>
  355. #include <arpa/inet.h>
  356. #include <sys/time.h>
  357. #include <sys/utsname.h>
  358. #include <stdint.h>
  359. #include <inttypes.h>
  360. #include <netdb.h>
  361. #include <netinet/tcp.h>
  362. typedef const void *SOCK_OPT_TYPE;
  363. #if defined(ANDROID)
  364. typedef unsigned short int in_port_t;
  365. #endif
  366. #include <pwd.h>
  367. #include <unistd.h>
  368. #include <grp.h>
  369. #include <dirent.h>
  370. #define vsnprintf_impl vsnprintf
  371. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  372. #include <dlfcn.h>
  373. #endif
  374. #include <pthread.h>
  375. #if defined(__MACH__)
  376. #define SSL_LIB "libssl.dylib"
  377. #define CRYPTO_LIB "libcrypto.dylib"
  378. #else
  379. #if !defined(SSL_LIB)
  380. #define SSL_LIB "libssl.so"
  381. #endif
  382. #if !defined(CRYPTO_LIB)
  383. #define CRYPTO_LIB "libcrypto.so"
  384. #endif
  385. #endif
  386. #ifndef O_BINARY
  387. #define O_BINARY (0)
  388. #endif /* O_BINARY */
  389. #define closesocket(a) (close(a))
  390. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  391. #define mg_remove(conn, x) (remove(x))
  392. #define mg_sleep(x) (usleep((x)*1000))
  393. #define mg_opendir(conn, x) (opendir(x))
  394. #define mg_closedir(x) (closedir(x))
  395. #define mg_readdir(x) (readdir(x))
  396. #define ERRNO (errno)
  397. #define INVALID_SOCKET (-1)
  398. #define INT64_FMT PRId64
  399. #define UINT64_FMT PRIu64
  400. typedef int SOCKET;
  401. #define WINCDECL
  402. #if defined(__hpux)
  403. /* HPUX 11 does not have monotonic, fall back to realtime */
  404. #ifndef CLOCK_MONOTONIC
  405. #define CLOCK_MONOTONIC CLOCK_REALTIME
  406. #endif
  407. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  408. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  409. * the prototypes use int* rather than socklen_t* which matches the
  410. * actual library expectation. When called with the wrong size arg
  411. * accept() returns a zero client inet addr and check_acl() always
  412. * fails. Since socklen_t is widely used below, just force replace
  413. * their typedef with int. - DTL
  414. */
  415. #define socklen_t int
  416. #endif /* hpux */
  417. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  418. WINDOWS / UNIX include block */
  419. /* va_copy should always be a macro, C99 and C++11 - DTL */
  420. #ifndef va_copy
  421. #define va_copy(x, y) ((x) = (y))
  422. #endif
  423. #ifdef _WIN32
  424. /* Create substitutes for POSIX functions in Win32. */
  425. #if defined(__MINGW32__)
  426. /* Show no warning in case system functions are not used. */
  427. #pragma GCC diagnostic push
  428. #pragma GCC diagnostic ignored "-Wunused-function"
  429. #endif
  430. static CRITICAL_SECTION global_log_file_lock;
  431. static DWORD
  432. pthread_self(void)
  433. {
  434. return GetCurrentThreadId();
  435. }
  436. static int
  437. pthread_key_create(
  438. pthread_key_t *key,
  439. void (*_ignored)(void *) /* destructor not supported for Windows */
  440. )
  441. {
  442. (void)_ignored;
  443. if ((key != 0)) {
  444. *key = TlsAlloc();
  445. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  446. }
  447. return -2;
  448. }
  449. static int
  450. pthread_key_delete(pthread_key_t key)
  451. {
  452. return TlsFree(key) ? 0 : 1;
  453. }
  454. static int
  455. pthread_setspecific(pthread_key_t key, void *value)
  456. {
  457. return TlsSetValue(key, value) ? 0 : 1;
  458. }
  459. static void *
  460. pthread_getspecific(pthread_key_t key)
  461. {
  462. return TlsGetValue(key);
  463. }
  464. #if defined(__MINGW32__)
  465. /* Enable unused function warning again */
  466. #pragma GCC diagnostic pop
  467. #endif
  468. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  469. #else
  470. static pthread_mutexattr_t pthread_mutex_attr;
  471. #endif /* _WIN32 */
  472. #define PASSWORDS_FILE_NAME ".htpasswd"
  473. #define CGI_ENVIRONMENT_SIZE (4096)
  474. #define MAX_CGI_ENVIR_VARS (256)
  475. #define MG_BUF_LEN (8192)
  476. #ifndef MAX_REQUEST_SIZE
  477. #define MAX_REQUEST_SIZE (16384)
  478. #endif
  479. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  480. "request size length must be a positive number");
  481. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  482. #if !defined(DEBUG_TRACE)
  483. #if defined(DEBUG)
  484. #if defined(_WIN32_WCE)
  485. /* Create substitutes for POSIX functions in Win32. */
  486. #if defined(__MINGW32__)
  487. /* Show no warning in case system functions are not used. */
  488. #pragma GCC diagnostic push
  489. #pragma GCC diagnostic ignored "-Wunused-function"
  490. #endif
  491. static time_t
  492. time(time_t *ptime)
  493. {
  494. time_t t;
  495. SYSTEMTIME st;
  496. FILETIME ft;
  497. GetSystemTime(&st);
  498. SystemTimeToFileTime(&st, &ft);
  499. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  500. if (ptime != NULL) {
  501. *ptime = t;
  502. }
  503. return t;
  504. }
  505. static struct tm *
  506. localtime_s(const time_t *ptime, struct tm *ptm)
  507. {
  508. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  509. FILETIME ft, lft;
  510. SYSTEMTIME st;
  511. TIME_ZONE_INFORMATION tzinfo;
  512. if (ptm == NULL) {
  513. return NULL;
  514. }
  515. *(int64_t *)&ft = t;
  516. FileTimeToLocalFileTime(&ft, &lft);
  517. FileTimeToSystemTime(&lft, &st);
  518. ptm->tm_year = st.wYear - 1900;
  519. ptm->tm_mon = st.wMonth - 1;
  520. ptm->tm_wday = st.wDayOfWeek;
  521. ptm->tm_mday = st.wDay;
  522. ptm->tm_hour = st.wHour;
  523. ptm->tm_min = st.wMinute;
  524. ptm->tm_sec = st.wSecond;
  525. ptm->tm_yday = 0; /* hope nobody uses this */
  526. ptm->tm_isdst =
  527. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  528. return ptm;
  529. }
  530. static struct tm *
  531. gmtime_s(const time_t *ptime, struct tm *ptm)
  532. {
  533. /* FIXME(lsm): fix this. */
  534. return localtime_s(ptime, ptm);
  535. }
  536. static int mg_atomic_inc(volatile int *addr);
  537. static struct tm tm_array[MAX_WORKER_THREADS];
  538. static int tm_index = 0;
  539. static struct tm *
  540. localtime(const time_t *ptime)
  541. {
  542. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  543. return localtime_s(ptime, tm_array + i);
  544. }
  545. static struct tm *
  546. gmtime(const time_t *ptime)
  547. {
  548. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  549. return gmtime_s(ptime, tm_array + i);
  550. }
  551. static size_t
  552. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  553. {
  554. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  555. // for WinCE");
  556. return 0;
  557. }
  558. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  559. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  560. #define remove(f) mg_remove(NULL, f)
  561. static int
  562. rename(const char *a, const char *b)
  563. {
  564. wchar_t wa[PATH_MAX];
  565. wchar_t wb[PATH_MAX];
  566. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  567. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  568. return MoveFileW(wa, wb) ? 0 : -1;
  569. }
  570. struct stat {
  571. int64_t st_size;
  572. time_t st_mtime;
  573. };
  574. static int
  575. stat(const char *name, struct stat *st)
  576. {
  577. wchar_t wbuf[PATH_MAX];
  578. WIN32_FILE_ATTRIBUTE_DATA attr;
  579. time_t creation_time, write_time;
  580. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  581. memset(&attr, 0, sizeof(attr));
  582. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  583. st->st_size =
  584. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  585. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  586. attr.ftLastWriteTime.dwHighDateTime);
  587. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  588. attr.ftCreationTime.dwHighDateTime);
  589. if (creation_time > write_time) {
  590. st->st_mtime = creation_time;
  591. } else {
  592. st->st_mtime = write_time;
  593. }
  594. return 0;
  595. }
  596. #define access(x, a) 1 /* not required anyway */
  597. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  598. #define EEXIST 1 /* TODO: See Windows error codes */
  599. #define EACCES 2 /* TODO: See Windows error codes */
  600. #define ENOENT 3 /* TODO: See Windows Error codes */
  601. #if defined(__MINGW32__)
  602. /* Enable unused function warning again */
  603. #pragma GCC diagnostic pop
  604. #endif
  605. #endif /* defined(_WIN32_WCE) */
  606. static void DEBUG_TRACE_FUNC(const char *func,
  607. unsigned line,
  608. PRINTF_FORMAT_STRING(const char *fmt),
  609. ...) PRINTF_ARGS(3, 4);
  610. static void
  611. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  612. {
  613. va_list args;
  614. flockfile(stdout);
  615. printf("*** %lu.%p.%s.%u: ",
  616. (unsigned long)time(NULL),
  617. (void *)pthread_self(),
  618. func,
  619. line);
  620. va_start(args, fmt);
  621. vprintf(fmt, args);
  622. va_end(args);
  623. putchar('\n');
  624. fflush(stdout);
  625. funlockfile(stdout);
  626. }
  627. #define DEBUG_TRACE(fmt, ...) \
  628. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  629. #else
  630. #define DEBUG_TRACE(fmt, ...) \
  631. do { \
  632. } while (0)
  633. #endif /* DEBUG */
  634. #endif /* DEBUG_TRACE */
  635. #if defined(MEMORY_DEBUGGING)
  636. unsigned long mg_memory_debug_blockCount = 0;
  637. unsigned long mg_memory_debug_totalMemUsed = 0;
  638. static void *
  639. mg_malloc_ex(size_t size, const char *file, unsigned line)
  640. {
  641. void *data = malloc(size + sizeof(size_t));
  642. void *memory = 0;
  643. char mallocStr[256];
  644. if (data) {
  645. *(size_t *)data = size;
  646. mg_memory_debug_totalMemUsed += size;
  647. mg_memory_debug_blockCount++;
  648. memory = (void *)(((char *)data) + sizeof(size_t));
  649. }
  650. sprintf(mallocStr,
  651. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  652. memory,
  653. (unsigned long)size,
  654. mg_memory_debug_totalMemUsed,
  655. mg_memory_debug_blockCount,
  656. file,
  657. line);
  658. #if defined(_WIN32)
  659. OutputDebugStringA(mallocStr);
  660. #else
  661. DEBUG_TRACE("%s", mallocStr);
  662. #endif
  663. return memory;
  664. }
  665. static void *
  666. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  667. {
  668. void *data = mg_malloc_ex(size * count, file, line);
  669. if (data) {
  670. memset(data, 0, size);
  671. }
  672. return data;
  673. }
  674. static void
  675. mg_free_ex(void *memory, const char *file, unsigned line)
  676. {
  677. char mallocStr[256];
  678. void *data = (void *)(((char *)memory) - sizeof(size_t));
  679. size_t size;
  680. if (memory) {
  681. size = *(size_t *)data;
  682. mg_memory_debug_totalMemUsed -= size;
  683. mg_memory_debug_blockCount--;
  684. sprintf(mallocStr,
  685. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  686. memory,
  687. (unsigned long)size,
  688. mg_memory_debug_totalMemUsed,
  689. mg_memory_debug_blockCount,
  690. file,
  691. line);
  692. #if defined(_WIN32)
  693. OutputDebugStringA(mallocStr);
  694. #else
  695. DEBUG_TRACE("%s", mallocStr);
  696. #endif
  697. free(data);
  698. }
  699. }
  700. static void *
  701. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  702. {
  703. char mallocStr[256];
  704. void *data;
  705. void *_realloc;
  706. size_t oldsize;
  707. if (newsize) {
  708. if (memory) {
  709. data = (void *)(((char *)memory) - sizeof(size_t));
  710. oldsize = *(size_t *)data;
  711. _realloc = realloc(data, newsize + sizeof(size_t));
  712. if (_realloc) {
  713. data = _realloc;
  714. mg_memory_debug_totalMemUsed -= oldsize;
  715. sprintf(mallocStr,
  716. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  717. memory,
  718. (unsigned long)oldsize,
  719. mg_memory_debug_totalMemUsed,
  720. mg_memory_debug_blockCount,
  721. file,
  722. line);
  723. #if defined(_WIN32)
  724. OutputDebugStringA(mallocStr);
  725. #else
  726. DEBUG_TRACE("%s", mallocStr);
  727. #endif
  728. mg_memory_debug_totalMemUsed += newsize;
  729. sprintf(mallocStr,
  730. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  731. memory,
  732. (unsigned long)newsize,
  733. mg_memory_debug_totalMemUsed,
  734. mg_memory_debug_blockCount,
  735. file,
  736. line);
  737. #if defined(_WIN32)
  738. OutputDebugStringA(mallocStr);
  739. #else
  740. DEBUG_TRACE("%s", mallocStr);
  741. #endif
  742. *(size_t *)data = newsize;
  743. data = (void *)(((char *)data) + sizeof(size_t));
  744. } else {
  745. #if defined(_WIN32)
  746. OutputDebugStringA("MEM: realloc failed\n");
  747. #else
  748. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  749. #endif
  750. return _realloc;
  751. }
  752. } else {
  753. data = mg_malloc_ex(newsize, file, line);
  754. }
  755. } else {
  756. data = 0;
  757. mg_free_ex(memory, file, line);
  758. }
  759. return data;
  760. }
  761. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  762. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  763. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  764. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  765. #else
  766. static __inline void *
  767. mg_malloc(size_t a)
  768. {
  769. return malloc(a);
  770. }
  771. static __inline void *
  772. mg_calloc(size_t a, size_t b)
  773. {
  774. return calloc(a, b);
  775. }
  776. static __inline void *
  777. mg_realloc(void *a, size_t b)
  778. {
  779. return realloc(a, b);
  780. }
  781. static __inline void
  782. mg_free(void *a)
  783. {
  784. free(a);
  785. }
  786. #endif
  787. static void mg_vsnprintf(const struct mg_connection *conn,
  788. int *truncated,
  789. char *buf,
  790. size_t buflen,
  791. const char *fmt,
  792. va_list ap);
  793. static void mg_snprintf(const struct mg_connection *conn,
  794. int *truncated,
  795. char *buf,
  796. size_t buflen,
  797. PRINTF_FORMAT_STRING(const char *fmt),
  798. ...) PRINTF_ARGS(5, 6);
  799. /* This following lines are just meant as a reminder to use the mg-functions
  800. * for memory management */
  801. #ifdef malloc
  802. #undef malloc
  803. #endif
  804. #ifdef calloc
  805. #undef calloc
  806. #endif
  807. #ifdef realloc
  808. #undef realloc
  809. #endif
  810. #ifdef free
  811. #undef free
  812. #endif
  813. #ifdef snprintf
  814. #undef snprintf
  815. #endif
  816. #ifdef vsnprintf
  817. #undef vsnprintf
  818. #endif
  819. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  820. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  821. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  822. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  823. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  824. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  825. * but this define only works well for Windows. */
  826. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  827. #endif
  828. #define MD5_STATIC static
  829. #include "md5.inl"
  830. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  831. #ifdef NO_SOCKLEN_T
  832. typedef int socklen_t;
  833. #endif /* NO_SOCKLEN_T */
  834. #define _DARWIN_UNLIMITED_SELECT
  835. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  836. #if !defined(MSG_NOSIGNAL)
  837. #define MSG_NOSIGNAL (0)
  838. #endif
  839. #if !defined(SOMAXCONN)
  840. #define SOMAXCONN (100)
  841. #endif
  842. /* Size of the accepted socket queue */
  843. #if !defined(MGSQLEN)
  844. #define MGSQLEN (20)
  845. #endif
  846. #if defined(NO_SSL)
  847. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  848. typedef struct SSL_CTX SSL_CTX;
  849. #else
  850. #if defined(NO_SSL_DL)
  851. #include <openssl/ssl.h>
  852. #include <openssl/err.h>
  853. #include <openssl/crypto.h>
  854. #include <openssl/x509.h>
  855. #include <openssl/pem.h>
  856. #include <openssl/engine.h>
  857. #include <openssl/conf.h>
  858. #else
  859. /* SSL loaded dynamically from DLL.
  860. * I put the prototypes here to be independent from OpenSSL source
  861. * installation. */
  862. typedef struct ssl_st SSL;
  863. typedef struct ssl_method_st SSL_METHOD;
  864. typedef struct ssl_ctx_st SSL_CTX;
  865. typedef struct x509_store_ctx_st X509_STORE_CTX;
  866. #define SSL_CTRL_OPTIONS (32)
  867. #define SSL_CTRL_CLEAR_OPTIONS (77)
  868. #define SSL_CTRL_SET_ECDH_AUTO (94)
  869. #define SSL_VERIFY_NONE (0)
  870. #define SSL_VERIFY_PEER (1)
  871. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  872. #define SSL_VERIFY_CLIENT_ONCE (4)
  873. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  874. #define SSL_OP_NO_SSLv2 (0x01000000L)
  875. #define SSL_OP_NO_SSLv3 (0x02000000L)
  876. #define SSL_OP_NO_TLSv1 (0x04000000L)
  877. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  878. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  879. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  880. #define SSL_ERROR_NONE (0)
  881. #define SSL_ERROR_SSL (1)
  882. #define SSL_ERROR_WANT_READ (2)
  883. #define SSL_ERROR_WANT_WRITE (3)
  884. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  885. #define SSL_ERROR_SYSCALL (5) /* see errno */
  886. #define SSL_ERROR_ZERO_RETURN (6)
  887. #define SSL_ERROR_WANT_CONNECT (7)
  888. #define SSL_ERROR_WANT_ACCEPT (8)
  889. struct ssl_func {
  890. const char *name; /* SSL function name */
  891. void (*ptr)(void); /* Function pointer */
  892. };
  893. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  894. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  895. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  896. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  897. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  898. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  899. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  900. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  901. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  902. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  903. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  904. #define SSL_CTX_use_PrivateKey_file \
  905. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  906. #define SSL_CTX_use_certificate_file \
  907. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  908. #define SSL_CTX_set_default_passwd_cb \
  909. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  910. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  911. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  912. #define SSL_CTX_use_certificate_chain_file \
  913. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  914. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  915. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  916. #define SSL_CTX_set_verify \
  917. (*(void (*)(SSL_CTX *, \
  918. int, \
  919. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  920. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  921. #define SSL_CTX_load_verify_locations \
  922. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  923. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  924. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  925. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  926. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  927. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  928. #define SSL_CIPHER_get_name \
  929. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  930. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  931. #define SSL_CTX_set_session_id_context \
  932. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  933. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  934. #define SSL_CTX_set_cipher_list \
  935. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  936. #define SSL_CTX_set_options(ctx, op) \
  937. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  938. #define SSL_CTX_clear_options(ctx, op) \
  939. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  940. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  941. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  942. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  943. #define CRYPTO_set_locking_callback \
  944. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  945. #define CRYPTO_set_id_callback \
  946. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  947. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  948. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  949. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  950. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  951. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  952. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  953. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  954. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  955. /* set_ssl_option() function updates this array.
  956. * It loads SSL library dynamically and changes NULLs to the actual addresses
  957. * of respective functions. The macros above (like SSL_connect()) are really
  958. * just calling these functions indirectly via the pointer. */
  959. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  960. {"SSL_accept", NULL},
  961. {"SSL_connect", NULL},
  962. {"SSL_read", NULL},
  963. {"SSL_write", NULL},
  964. {"SSL_get_error", NULL},
  965. {"SSL_set_fd", NULL},
  966. {"SSL_new", NULL},
  967. {"SSL_CTX_new", NULL},
  968. {"SSLv23_server_method", NULL},
  969. {"SSL_library_init", NULL},
  970. {"SSL_CTX_use_PrivateKey_file", NULL},
  971. {"SSL_CTX_use_certificate_file", NULL},
  972. {"SSL_CTX_set_default_passwd_cb", NULL},
  973. {"SSL_CTX_free", NULL},
  974. {"SSL_load_error_strings", NULL},
  975. {"SSL_CTX_use_certificate_chain_file", NULL},
  976. {"SSLv23_client_method", NULL},
  977. {"SSL_pending", NULL},
  978. {"SSL_CTX_set_verify", NULL},
  979. {"SSL_shutdown", NULL},
  980. {"SSL_CTX_load_verify_locations", NULL},
  981. {"SSL_CTX_set_default_verify_paths", NULL},
  982. {"SSL_CTX_set_verify_depth", NULL},
  983. {"SSL_get_peer_certificate", NULL},
  984. {"SSL_get_version", NULL},
  985. {"SSL_get_current_cipher", NULL},
  986. {"SSL_CIPHER_get_name", NULL},
  987. {"SSL_CTX_check_private_key", NULL},
  988. {"SSL_CTX_set_session_id_context", NULL},
  989. {"SSL_CTX_ctrl", NULL},
  990. {"SSL_CTX_set_cipher_list", NULL},
  991. {NULL, NULL}};
  992. /* Similar array as ssl_sw. These functions could be located in different
  993. * lib. */
  994. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  995. {"CRYPTO_set_locking_callback", NULL},
  996. {"CRYPTO_set_id_callback", NULL},
  997. {"ERR_get_error", NULL},
  998. {"ERR_error_string", NULL},
  999. {"ERR_remove_state", NULL},
  1000. {"ERR_free_strings", NULL},
  1001. {"ENGINE_cleanup", NULL},
  1002. {"CONF_modules_unload", NULL},
  1003. {"CRYPTO_cleanup_all_ex_data", NULL},
  1004. {"EVP_cleanup", NULL},
  1005. {NULL, NULL}};
  1006. #endif /* NO_SSL_DL */
  1007. #endif /* NO_SSL */
  1008. #if !defined(NO_CACHING)
  1009. static const char *month_names[] = {"Jan",
  1010. "Feb",
  1011. "Mar",
  1012. "Apr",
  1013. "May",
  1014. "Jun",
  1015. "Jul",
  1016. "Aug",
  1017. "Sep",
  1018. "Oct",
  1019. "Nov",
  1020. "Dec"};
  1021. #endif /* !NO_CACHING */
  1022. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1023. * union u. */
  1024. union usa {
  1025. struct sockaddr sa;
  1026. struct sockaddr_in sin;
  1027. #if defined(USE_IPV6)
  1028. struct sockaddr_in6 sin6;
  1029. #endif
  1030. };
  1031. /* Describes a string (chunk of memory). */
  1032. struct vec {
  1033. const char *ptr;
  1034. size_t len;
  1035. };
  1036. struct file {
  1037. uint64_t size;
  1038. time_t last_modified;
  1039. FILE *fp;
  1040. const char *membuf; /* Non-NULL if file data is in memory */
  1041. int is_directory;
  1042. int gzipped; /* set to 1 if the content is gzipped
  1043. * in which case we need a content-encoding: gzip header */
  1044. };
  1045. #define STRUCT_FILE_INITIALIZER \
  1046. { \
  1047. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1048. }
  1049. /* Describes listening socket, or socket which was accept()-ed by the master
  1050. * thread and queued for future handling by the worker thread. */
  1051. struct socket {
  1052. SOCKET sock; /* Listening socket */
  1053. union usa lsa; /* Local socket address */
  1054. union usa rsa; /* Remote socket address */
  1055. unsigned char is_ssl; /* Is port SSL-ed */
  1056. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1057. * port */
  1058. unsigned char in_use; /* Is valid */
  1059. };
  1060. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1061. enum {
  1062. CGI_EXTENSIONS,
  1063. CGI_ENVIRONMENT,
  1064. PUT_DELETE_PASSWORDS_FILE,
  1065. CGI_INTERPRETER,
  1066. PROTECT_URI,
  1067. AUTHENTICATION_DOMAIN,
  1068. SSI_EXTENSIONS,
  1069. THROTTLE,
  1070. ACCESS_LOG_FILE,
  1071. ENABLE_DIRECTORY_LISTING,
  1072. ERROR_LOG_FILE,
  1073. GLOBAL_PASSWORDS_FILE,
  1074. INDEX_FILES,
  1075. ENABLE_KEEP_ALIVE,
  1076. ACCESS_CONTROL_LIST,
  1077. EXTRA_MIME_TYPES,
  1078. LISTENING_PORTS,
  1079. DOCUMENT_ROOT,
  1080. SSL_CERTIFICATE,
  1081. NUM_THREADS,
  1082. RUN_AS_USER,
  1083. REWRITE,
  1084. HIDE_FILES,
  1085. REQUEST_TIMEOUT,
  1086. SSL_DO_VERIFY_PEER,
  1087. SSL_CA_PATH,
  1088. SSL_CA_FILE,
  1089. SSL_VERIFY_DEPTH,
  1090. SSL_DEFAULT_VERIFY_PATHS,
  1091. SSL_CIPHER_LIST,
  1092. SSL_PROTOCOL_VERSION,
  1093. SSL_SHORT_TRUST,
  1094. #if defined(USE_WEBSOCKET)
  1095. WEBSOCKET_TIMEOUT,
  1096. #endif
  1097. DECODE_URL,
  1098. #if defined(USE_LUA)
  1099. LUA_PRELOAD_FILE,
  1100. LUA_SCRIPT_EXTENSIONS,
  1101. LUA_SERVER_PAGE_EXTENSIONS,
  1102. #endif
  1103. #if defined(USE_DUKTAPE)
  1104. DUKTAPE_SCRIPT_EXTENSIONS,
  1105. #endif
  1106. #if defined(USE_WEBSOCKET)
  1107. WEBSOCKET_ROOT,
  1108. #endif
  1109. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1110. LUA_WEBSOCKET_EXTENSIONS,
  1111. #endif
  1112. ACCESS_CONTROL_ALLOW_ORIGIN,
  1113. ERROR_PAGES,
  1114. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1115. * socket option typedef TCP_NODELAY. */
  1116. #if !defined(NO_CACHING)
  1117. STATIC_FILE_MAX_AGE,
  1118. #endif
  1119. NUM_OPTIONS
  1120. };
  1121. /* Config option name, config types, default value */
  1122. static struct mg_option config_options[] = {
  1123. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1124. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1125. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1126. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1127. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1128. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1129. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1130. {"throttle", CONFIG_TYPE_STRING, NULL},
  1131. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1132. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1133. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1134. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1135. {"index_files",
  1136. CONFIG_TYPE_STRING,
  1137. #ifdef USE_LUA
  1138. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1139. "index.shtml,index.php"},
  1140. #else
  1141. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1142. #endif
  1143. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1144. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1145. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1146. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1147. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1148. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1149. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1150. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1151. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1152. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1153. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1154. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1155. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1156. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1157. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1158. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1159. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1160. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1161. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1162. #if defined(USE_WEBSOCKET)
  1163. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1164. #endif
  1165. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1166. #if defined(USE_LUA)
  1167. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1168. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1169. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1170. #endif
  1171. #if defined(USE_DUKTAPE)
  1172. /* The support for duktape is still in alpha version state.
  1173. * The name of this config option might change. */
  1174. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1175. #endif
  1176. #if defined(USE_WEBSOCKET)
  1177. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1178. #endif
  1179. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1180. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1181. #endif
  1182. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1183. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1184. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1185. #if !defined(NO_CACHING)
  1186. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1187. #endif
  1188. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1189. /* Check if the config_options and the corresponding enum have compatible
  1190. * sizes. */
  1191. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1192. == (NUM_OPTIONS + 1),
  1193. "config_options and enum not sync");
  1194. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1195. struct mg_handler_info {
  1196. /* Name/Pattern of the URI. */
  1197. char *uri;
  1198. size_t uri_len;
  1199. /* handler type */
  1200. int handler_type;
  1201. /* Handler for http/https or authorization requests. */
  1202. mg_request_handler handler;
  1203. /* Handler for ws/wss (websocket) requests. */
  1204. mg_websocket_connect_handler connect_handler;
  1205. mg_websocket_ready_handler ready_handler;
  1206. mg_websocket_data_handler data_handler;
  1207. mg_websocket_close_handler close_handler;
  1208. /* Handler for authorization requests */
  1209. mg_authorization_handler auth_handler;
  1210. /* User supplied argument for the handler function. */
  1211. void *cbdata;
  1212. /* next handler in a linked list */
  1213. struct mg_handler_info *next;
  1214. };
  1215. struct mg_context {
  1216. volatile int stop_flag; /* Should we stop event loop */
  1217. SSL_CTX *ssl_ctx; /* SSL context */
  1218. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1219. struct mg_callbacks callbacks; /* User-defined callback function */
  1220. void *user_data; /* User-defined data */
  1221. int context_type; /* 1 = server context, 2 = client context */
  1222. struct socket *listening_sockets;
  1223. struct pollfd *listening_socket_fds;
  1224. unsigned int num_listening_sockets;
  1225. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1226. #ifdef ALTERNATIVE_QUEUE
  1227. struct socket *client_socks;
  1228. int *client_wait_events;
  1229. #else
  1230. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1231. volatile int sq_head; /* Head of the socket queue */
  1232. volatile int sq_tail; /* Tail of the socket queue */
  1233. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1234. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1235. #endif
  1236. pthread_t masterthreadid; /* The master thread ID */
  1237. unsigned int
  1238. cfg_worker_threads; /* The number of configured worker threads. */
  1239. pthread_t *workerthreadids; /* The worker thread IDs */
  1240. time_t start_time; /* Server start time, used for authentication */
  1241. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1242. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1243. unsigned long nonce_count; /* Used nonces, used for authentication */
  1244. char *systemName; /* What operating system is running */
  1245. /* linked list of uri handlers */
  1246. struct mg_handler_info *handlers;
  1247. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1248. /* linked list of shared lua websockets */
  1249. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1250. #endif
  1251. #ifdef USE_TIMERS
  1252. struct ttimers *timers;
  1253. #endif
  1254. };
  1255. struct mg_connection {
  1256. struct mg_request_info request_info;
  1257. struct mg_context *ctx;
  1258. SSL *ssl; /* SSL descriptor */
  1259. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1260. struct socket client; /* Connected client */
  1261. time_t conn_birth_time; /* Time (wall clock) when connection was
  1262. * established */
  1263. struct timespec req_time; /* Time (since system start) when the request
  1264. * was received */
  1265. int64_t num_bytes_sent; /* Total bytes sent to client */
  1266. int64_t content_len; /* Content-Length header value */
  1267. int64_t consumed_content; /* How many bytes of content have been read */
  1268. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1269. * data available, 2: all data read */
  1270. size_t chunk_remainder; /* Unread data from the last chunk */
  1271. char *buf; /* Buffer for received data */
  1272. char *path_info; /* PATH_INFO part of the URL */
  1273. int must_close; /* 1 if connection must be closed */
  1274. int in_error_handler; /* 1 if in handler for user defined error
  1275. * pages */
  1276. int internal_error; /* 1 if an error occured while processing the
  1277. * request */
  1278. int buf_size; /* Buffer size */
  1279. int request_len; /* Size of the request + headers in a buffer */
  1280. int data_len; /* Total size of data in a buffer */
  1281. int status_code; /* HTTP reply status code, e.g. 200 */
  1282. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1283. * throttle */
  1284. time_t last_throttle_time; /* Last time throttled data was sent */
  1285. int64_t last_throttle_bytes; /* Bytes sent this second */
  1286. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1287. * atomic transmissions for websockets */
  1288. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1289. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1290. #endif
  1291. int thread_index; /* Thread index within ctx */
  1292. };
  1293. static pthread_key_t sTlsKey; /* Thread local storage index */
  1294. static int sTlsInit = 0;
  1295. static int thread_idx_max = 0;
  1296. struct mg_workerTLS {
  1297. int is_master;
  1298. unsigned long thread_idx;
  1299. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1300. HANDLE pthread_cond_helper_mutex;
  1301. struct mg_workerTLS *next_waiting_thread;
  1302. #endif
  1303. };
  1304. /* Directory entry */
  1305. struct de {
  1306. struct mg_connection *conn;
  1307. char *file_name;
  1308. struct file file;
  1309. };
  1310. #if defined(USE_WEBSOCKET)
  1311. static int is_websocket_protocol(const struct mg_connection *conn);
  1312. #else
  1313. #define is_websocket_protocol(conn) (0)
  1314. #endif
  1315. static int
  1316. mg_atomic_inc(volatile int *addr)
  1317. {
  1318. int ret;
  1319. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1320. /* Depending on the SDK, this function uses either
  1321. * (volatile unsigned int *) or (volatile LONG *),
  1322. * so whatever you use, the other SDK is likely to raise a warning. */
  1323. ret = InterlockedIncrement((volatile long *)addr);
  1324. #elif defined(__GNUC__) \
  1325. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1326. ret = __sync_add_and_fetch(addr, 1);
  1327. #else
  1328. ret = (++(*addr));
  1329. #endif
  1330. return ret;
  1331. }
  1332. static int
  1333. mg_atomic_dec(volatile int *addr)
  1334. {
  1335. int ret;
  1336. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1337. /* Depending on the SDK, this function uses either
  1338. * (volatile unsigned int *) or (volatile LONG *),
  1339. * so whatever you use, the other SDK is likely to raise a warning. */
  1340. ret = InterlockedDecrement((volatile long *)addr);
  1341. #elif defined(__GNUC__) \
  1342. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1343. ret = __sync_sub_and_fetch(addr, 1);
  1344. #else
  1345. ret = (--(*addr));
  1346. #endif
  1347. return ret;
  1348. }
  1349. #if !defined(NO_THREAD_NAME)
  1350. #if defined(_WIN32) && defined(_MSC_VER)
  1351. /* Set the thread name for debugging purposes in Visual Studio
  1352. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1353. */
  1354. #pragma pack(push, 8)
  1355. typedef struct tagTHREADNAME_INFO {
  1356. DWORD dwType; /* Must be 0x1000. */
  1357. LPCSTR szName; /* Pointer to name (in user addr space). */
  1358. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1359. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1360. } THREADNAME_INFO;
  1361. #pragma pack(pop)
  1362. #elif defined(__linux__)
  1363. #include <sys/prctl.h>
  1364. #include <sys/sendfile.h>
  1365. #include <sys/eventfd.h>
  1366. static int
  1367. event_create(void)
  1368. {
  1369. int ret = eventfd(0, EFD_CLOEXEC);
  1370. if (ret == -1) {
  1371. /* Linux uses -1 on error, Windows NULL. */
  1372. /* However, Linux does not return 0 on success either. */
  1373. return 0;
  1374. }
  1375. return ret;
  1376. }
  1377. static int
  1378. event_wait(int eventhdl)
  1379. {
  1380. uint64_t u;
  1381. int s = read(eventhdl, &u, sizeof(u));
  1382. if (s != sizeof(uint64_t)) {
  1383. /* error */
  1384. return 0;
  1385. }
  1386. (void)u; /* the value is not required */
  1387. return 1;
  1388. }
  1389. static int
  1390. event_signal(int eventhdl)
  1391. {
  1392. uint64_t u = 1;
  1393. int s = write(eventhdl, &u, sizeof(u));
  1394. if (s != sizeof(uint64_t)) {
  1395. /* error */
  1396. return 0;
  1397. }
  1398. return 1;
  1399. }
  1400. static void
  1401. event_destroy(int eventhdl)
  1402. {
  1403. close(eventhdl);
  1404. }
  1405. #endif
  1406. static void
  1407. mg_set_thread_name(const char *name)
  1408. {
  1409. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1410. mg_snprintf(
  1411. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1412. #if defined(_WIN32)
  1413. #if defined(_MSC_VER)
  1414. /* Windows and Visual Studio Compiler */
  1415. __try
  1416. {
  1417. THREADNAME_INFO info;
  1418. info.dwType = 0x1000;
  1419. info.szName = threadName;
  1420. info.dwThreadID = ~0U;
  1421. info.dwFlags = 0;
  1422. RaiseException(0x406D1388,
  1423. 0,
  1424. sizeof(info) / sizeof(ULONG_PTR),
  1425. (ULONG_PTR *)&info);
  1426. }
  1427. __except(EXCEPTION_EXECUTE_HANDLER)
  1428. {
  1429. }
  1430. #elif defined(__MINGW32__)
  1431. /* No option known to set thread name for MinGW */
  1432. #endif
  1433. #elif defined(__GLIBC__) \
  1434. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1435. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1436. (void)pthread_setname_np(pthread_self(), threadName);
  1437. #elif defined(__linux__)
  1438. /* on linux we can use the old prctl function */
  1439. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1440. #endif
  1441. }
  1442. #else /* !defined(NO_THREAD_NAME) */
  1443. void
  1444. mg_set_thread_name(const char *threadName)
  1445. {
  1446. }
  1447. #endif
  1448. #if defined(MG_LEGACY_INTERFACE)
  1449. const char **
  1450. mg_get_valid_option_names(void)
  1451. {
  1452. /* This function is deprecated. Use mg_get_valid_options instead. */
  1453. static const char *
  1454. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1455. int i;
  1456. for (i = 0; config_options[i].name != NULL; i++) {
  1457. data[i * 2] = config_options[i].name;
  1458. data[i * 2 + 1] = config_options[i].default_value;
  1459. }
  1460. return data;
  1461. }
  1462. #endif
  1463. const struct mg_option *
  1464. mg_get_valid_options(void)
  1465. {
  1466. return config_options;
  1467. }
  1468. static int
  1469. is_file_in_memory(const struct mg_connection *conn,
  1470. const char *path,
  1471. struct file *filep)
  1472. {
  1473. size_t size = 0;
  1474. if (!conn || !filep) {
  1475. return 0;
  1476. }
  1477. if (conn->ctx->callbacks.open_file) {
  1478. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1479. if (filep->membuf != NULL) {
  1480. /* NOTE: override filep->size only on success. Otherwise, it might
  1481. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1482. filep->size = size;
  1483. }
  1484. }
  1485. return filep->membuf != NULL;
  1486. }
  1487. static int
  1488. is_file_opened(const struct file *filep)
  1489. {
  1490. if (!filep) {
  1491. return 0;
  1492. }
  1493. return filep->membuf != NULL || filep->fp != NULL;
  1494. }
  1495. /* mg_fopen will open a file either in memory or on the disk.
  1496. * The input parameter path is a string in UTF-8 encoding.
  1497. * The input parameter mode is the same as for fopen.
  1498. * Either fp or membuf will be set in the output struct filep.
  1499. * The function returns 1 on success, 0 on error. */
  1500. static int
  1501. mg_fopen(const struct mg_connection *conn,
  1502. const char *path,
  1503. const char *mode,
  1504. struct file *filep)
  1505. {
  1506. struct stat st;
  1507. if (!filep) {
  1508. return 0;
  1509. }
  1510. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1511. * only get the file status. They should not work on different members of
  1512. * the same structure (bad cohesion). */
  1513. memset(filep, 0, sizeof(*filep));
  1514. if (stat(path, &st) == 0) {
  1515. filep->size = (uint64_t)(st.st_size);
  1516. }
  1517. if (!is_file_in_memory(conn, path, filep)) {
  1518. #ifdef _WIN32
  1519. wchar_t wbuf[PATH_MAX], wmode[20];
  1520. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1521. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1522. filep->fp = _wfopen(wbuf, wmode);
  1523. #else
  1524. /* Linux et al already use unicode. No need to convert. */
  1525. filep->fp = fopen(path, mode);
  1526. #endif
  1527. }
  1528. return is_file_opened(filep);
  1529. }
  1530. static void
  1531. mg_fclose(struct file *filep)
  1532. {
  1533. if (filep != NULL && filep->fp != NULL) {
  1534. fclose(filep->fp);
  1535. }
  1536. }
  1537. static void
  1538. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1539. {
  1540. for (; *src != '\0' && n > 1; n--) {
  1541. *dst++ = *src++;
  1542. }
  1543. *dst = '\0';
  1544. }
  1545. static int
  1546. lowercase(const char *s)
  1547. {
  1548. return tolower(*(const unsigned char *)s);
  1549. }
  1550. int
  1551. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1552. {
  1553. int diff = 0;
  1554. if (len > 0) {
  1555. do {
  1556. diff = lowercase(s1++) - lowercase(s2++);
  1557. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1558. }
  1559. return diff;
  1560. }
  1561. int
  1562. mg_strcasecmp(const char *s1, const char *s2)
  1563. {
  1564. int diff;
  1565. do {
  1566. diff = lowercase(s1++) - lowercase(s2++);
  1567. } while (diff == 0 && s1[-1] != '\0');
  1568. return diff;
  1569. }
  1570. static char *
  1571. mg_strndup(const char *ptr, size_t len)
  1572. {
  1573. char *p;
  1574. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1575. mg_strlcpy(p, ptr, len + 1);
  1576. }
  1577. return p;
  1578. }
  1579. static char *
  1580. mg_strdup(const char *str)
  1581. {
  1582. return mg_strndup(str, strlen(str));
  1583. }
  1584. static const char *
  1585. mg_strcasestr(const char *big_str, const char *small_str)
  1586. {
  1587. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1588. if (big_len >= small_len) {
  1589. for (i = 0; i <= (big_len - small_len); i++) {
  1590. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1591. return big_str + i;
  1592. }
  1593. }
  1594. }
  1595. return NULL;
  1596. }
  1597. /* Return null terminated string of given maximum length.
  1598. * Report errors if length is exceeded. */
  1599. static void
  1600. mg_vsnprintf(const struct mg_connection *conn,
  1601. int *truncated,
  1602. char *buf,
  1603. size_t buflen,
  1604. const char *fmt,
  1605. va_list ap)
  1606. {
  1607. int n, ok;
  1608. if (buflen == 0) {
  1609. return;
  1610. }
  1611. #ifdef __clang__
  1612. #pragma clang diagnostic push
  1613. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1614. /* Using fmt as a non-literal is intended here, since it is mostly called
  1615. * indirectly by mg_snprintf */
  1616. #endif
  1617. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1618. ok = (n >= 0) && ((size_t)n < buflen);
  1619. #ifdef __clang__
  1620. #pragma clang diagnostic pop
  1621. #endif
  1622. if (ok) {
  1623. if (truncated) {
  1624. *truncated = 0;
  1625. }
  1626. } else {
  1627. if (truncated) {
  1628. *truncated = 1;
  1629. }
  1630. mg_cry(conn,
  1631. "truncating vsnprintf buffer: [%.*s]",
  1632. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1633. buf);
  1634. n = (int)buflen - 1;
  1635. }
  1636. buf[n] = '\0';
  1637. }
  1638. static void
  1639. mg_snprintf(const struct mg_connection *conn,
  1640. int *truncated,
  1641. char *buf,
  1642. size_t buflen,
  1643. const char *fmt,
  1644. ...)
  1645. {
  1646. va_list ap;
  1647. va_start(ap, fmt);
  1648. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1649. va_end(ap);
  1650. }
  1651. static int
  1652. get_option_index(const char *name)
  1653. {
  1654. int i;
  1655. for (i = 0; config_options[i].name != NULL; i++) {
  1656. if (strcmp(config_options[i].name, name) == 0) {
  1657. return i;
  1658. }
  1659. }
  1660. return -1;
  1661. }
  1662. const char *
  1663. mg_get_option(const struct mg_context *ctx, const char *name)
  1664. {
  1665. int i;
  1666. if ((i = get_option_index(name)) == -1) {
  1667. return NULL;
  1668. } else if (!ctx || ctx->config[i] == NULL) {
  1669. return "";
  1670. } else {
  1671. return ctx->config[i];
  1672. }
  1673. }
  1674. struct mg_context *
  1675. mg_get_context(const struct mg_connection *conn)
  1676. {
  1677. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1678. }
  1679. void *
  1680. mg_get_user_data(const struct mg_context *ctx)
  1681. {
  1682. return (ctx == NULL) ? NULL : ctx->user_data;
  1683. }
  1684. void
  1685. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1686. {
  1687. if (conn != NULL) {
  1688. conn->request_info.conn_data = data;
  1689. }
  1690. }
  1691. void *
  1692. mg_get_user_connection_data(const struct mg_connection *conn)
  1693. {
  1694. if (conn != NULL) {
  1695. return conn->request_info.conn_data;
  1696. }
  1697. return NULL;
  1698. }
  1699. size_t
  1700. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1701. {
  1702. size_t i;
  1703. if (!ctx) {
  1704. return 0;
  1705. }
  1706. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1707. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1708. ports[i] =
  1709. #if defined(USE_IPV6)
  1710. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1711. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1712. :
  1713. #endif
  1714. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1715. }
  1716. return i;
  1717. }
  1718. int
  1719. mg_get_server_ports(const struct mg_context *ctx,
  1720. int size,
  1721. struct mg_server_ports *ports)
  1722. {
  1723. int i, cnt = 0;
  1724. if (size <= 0) {
  1725. return -1;
  1726. }
  1727. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1728. if (!ctx) {
  1729. return -1;
  1730. }
  1731. if (!ctx->listening_sockets) {
  1732. return -1;
  1733. }
  1734. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1735. ports[cnt].port =
  1736. #if defined(USE_IPV6)
  1737. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1738. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1739. :
  1740. #endif
  1741. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1742. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1743. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1744. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1745. /* IPv4 */
  1746. ports[cnt].protocol = 1;
  1747. cnt++;
  1748. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1749. /* IPv6 */
  1750. ports[cnt].protocol = 3;
  1751. cnt++;
  1752. }
  1753. }
  1754. return cnt;
  1755. }
  1756. static void
  1757. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1758. {
  1759. buf[0] = '\0';
  1760. if (!usa) {
  1761. return;
  1762. }
  1763. if (usa->sa.sa_family == AF_INET) {
  1764. getnameinfo(&usa->sa,
  1765. sizeof(usa->sin),
  1766. buf,
  1767. (unsigned)len,
  1768. NULL,
  1769. 0,
  1770. NI_NUMERICHOST);
  1771. }
  1772. #if defined(USE_IPV6)
  1773. else if (usa->sa.sa_family == AF_INET6) {
  1774. getnameinfo(&usa->sa,
  1775. sizeof(usa->sin6),
  1776. buf,
  1777. (unsigned)len,
  1778. NULL,
  1779. 0,
  1780. NI_NUMERICHOST);
  1781. }
  1782. #endif
  1783. }
  1784. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1785. * included in all responses other than 100, 101, 5xx. */
  1786. static void
  1787. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1788. {
  1789. struct tm *tm;
  1790. tm = ((t != NULL) ? gmtime(t) : NULL);
  1791. if (tm != NULL) {
  1792. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1793. } else {
  1794. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1795. buf[buf_len - 1] = '\0';
  1796. }
  1797. }
  1798. /* difftime for struct timespec. Return value is in seconds. */
  1799. static double
  1800. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1801. {
  1802. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1803. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1804. }
  1805. /* Print error message to the opened error log stream. */
  1806. void
  1807. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1808. {
  1809. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1810. va_list ap;
  1811. struct file fi;
  1812. time_t timestamp;
  1813. va_start(ap, fmt);
  1814. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1815. va_end(ap);
  1816. buf[sizeof(buf) - 1] = 0;
  1817. if (!conn) {
  1818. puts(buf);
  1819. return;
  1820. }
  1821. /* Do not lock when getting the callback value, here and below.
  1822. * I suppose this is fine, since function cannot disappear in the
  1823. * same way string option can. */
  1824. if ((conn->ctx->callbacks.log_message == NULL)
  1825. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1826. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1827. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1828. == 0) {
  1829. fi.fp = NULL;
  1830. }
  1831. } else {
  1832. fi.fp = NULL;
  1833. }
  1834. if (fi.fp != NULL) {
  1835. flockfile(fi.fp);
  1836. timestamp = time(NULL);
  1837. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1838. fprintf(fi.fp,
  1839. "[%010lu] [error] [client %s] ",
  1840. (unsigned long)timestamp,
  1841. src_addr);
  1842. if (conn->request_info.request_method != NULL) {
  1843. fprintf(fi.fp,
  1844. "%s %s: ",
  1845. conn->request_info.request_method,
  1846. conn->request_info.request_uri);
  1847. }
  1848. fprintf(fi.fp, "%s", buf);
  1849. fputc('\n', fi.fp);
  1850. fflush(fi.fp);
  1851. funlockfile(fi.fp);
  1852. mg_fclose(&fi);
  1853. }
  1854. }
  1855. }
  1856. /* Return fake connection structure. Used for logging, if connection
  1857. * is not applicable at the moment of logging. */
  1858. static struct mg_connection *
  1859. fc(struct mg_context *ctx)
  1860. {
  1861. static struct mg_connection fake_connection;
  1862. fake_connection.ctx = ctx;
  1863. return &fake_connection;
  1864. }
  1865. const char *
  1866. mg_version(void)
  1867. {
  1868. return CIVETWEB_VERSION;
  1869. }
  1870. const struct mg_request_info *
  1871. mg_get_request_info(const struct mg_connection *conn)
  1872. {
  1873. if (!conn) {
  1874. return NULL;
  1875. }
  1876. return &conn->request_info;
  1877. }
  1878. /* Skip the characters until one of the delimiters characters found.
  1879. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1880. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1881. * Delimiters can be quoted with quotechar. */
  1882. static char *
  1883. skip_quoted(char **buf,
  1884. const char *delimiters,
  1885. const char *whitespace,
  1886. char quotechar)
  1887. {
  1888. char *p, *begin_word, *end_word, *end_whitespace;
  1889. begin_word = *buf;
  1890. end_word = begin_word + strcspn(begin_word, delimiters);
  1891. /* Check for quotechar */
  1892. if (end_word > begin_word) {
  1893. p = end_word - 1;
  1894. while (*p == quotechar) {
  1895. /* While the delimiter is quoted, look for the next delimiter. */
  1896. /* This happens, e.g., in calls from parse_auth_header,
  1897. * if the user name contains a " character. */
  1898. /* If there is anything beyond end_word, copy it. */
  1899. if (*end_word != '\0') {
  1900. size_t end_off = strcspn(end_word + 1, delimiters);
  1901. memmove(p, end_word, end_off + 1);
  1902. p += end_off; /* p must correspond to end_word - 1 */
  1903. end_word += end_off + 1;
  1904. } else {
  1905. *p = '\0';
  1906. break;
  1907. }
  1908. }
  1909. for (p++; p < end_word; p++) {
  1910. *p = '\0';
  1911. }
  1912. }
  1913. if (*end_word == '\0') {
  1914. *buf = end_word;
  1915. } else {
  1916. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1917. for (p = end_word; p < end_whitespace; p++) {
  1918. *p = '\0';
  1919. }
  1920. *buf = end_whitespace;
  1921. }
  1922. return begin_word;
  1923. }
  1924. /* Simplified version of skip_quoted without quote char
  1925. * and whitespace == delimiters */
  1926. static char *
  1927. skip(char **buf, const char *delimiters)
  1928. {
  1929. return skip_quoted(buf, delimiters, delimiters, 0);
  1930. }
  1931. /* Return HTTP header value, or NULL if not found. */
  1932. static const char *
  1933. get_header(const struct mg_request_info *ri, const char *name)
  1934. {
  1935. int i;
  1936. if (ri) {
  1937. for (i = 0; i < ri->num_headers; i++) {
  1938. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1939. return ri->http_headers[i].value;
  1940. }
  1941. }
  1942. }
  1943. return NULL;
  1944. }
  1945. const char *
  1946. mg_get_header(const struct mg_connection *conn, const char *name)
  1947. {
  1948. if (!conn) {
  1949. return NULL;
  1950. }
  1951. return get_header(&conn->request_info, name);
  1952. }
  1953. /* A helper function for traversing a comma separated list of values.
  1954. * It returns a list pointer shifted to the next value, or NULL if the end
  1955. * of the list found.
  1956. * Value is stored in val vector. If value has form "x=y", then eq_val
  1957. * vector is initialized to point to the "y" part, and val vector length
  1958. * is adjusted to point only to "x". */
  1959. static const char *
  1960. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1961. {
  1962. int end;
  1963. reparse:
  1964. if (val == NULL || list == NULL || *list == '\0') {
  1965. /* End of the list */
  1966. list = NULL;
  1967. } else {
  1968. /* Skip over leading LWS */
  1969. while (*list == ' ' || *list == '\t')
  1970. list++;
  1971. val->ptr = list;
  1972. if ((list = strchr(val->ptr, ',')) != NULL) {
  1973. /* Comma found. Store length and shift the list ptr */
  1974. val->len = ((size_t)(list - val->ptr));
  1975. list++;
  1976. } else {
  1977. /* This value is the last one */
  1978. list = val->ptr + strlen(val->ptr);
  1979. val->len = ((size_t)(list - val->ptr));
  1980. }
  1981. /* Adjust length for trailing LWS */
  1982. end = (int)val->len - 1;
  1983. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  1984. end--;
  1985. val->len = (size_t)(end + 1);
  1986. if (val->len == 0) {
  1987. /* Ignore any empty entries. */
  1988. goto reparse;
  1989. }
  1990. if (eq_val != NULL) {
  1991. /* Value has form "x=y", adjust pointers and lengths
  1992. * so that val points to "x", and eq_val points to "y". */
  1993. eq_val->len = 0;
  1994. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1995. if (eq_val->ptr != NULL) {
  1996. eq_val->ptr++; /* Skip over '=' character */
  1997. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1998. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1999. }
  2000. }
  2001. }
  2002. return list;
  2003. }
  2004. /* A helper function for checking if a comma separated list of values contains
  2005. * the given option (case insensitvely).
  2006. * 'header' can be NULL, in which case false is returned. */
  2007. static int
  2008. header_has_option(const char *header, const char *option)
  2009. {
  2010. struct vec opt_vec;
  2011. struct vec eq_vec;
  2012. assert(option != NULL);
  2013. assert(option[0] != '\0');
  2014. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2015. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2016. return 1;
  2017. }
  2018. return 0;
  2019. }
  2020. /* Perform case-insensitive match of string against pattern */
  2021. static int
  2022. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2023. {
  2024. const char *or_str;
  2025. size_t i;
  2026. int j, len, res;
  2027. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2028. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2029. return (res > 0) ? res : match_prefix(or_str + 1,
  2030. (size_t)((pattern + pattern_len)
  2031. - (or_str + 1)),
  2032. str);
  2033. }
  2034. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2035. if (pattern[i] == '?' && str[j] != '\0') {
  2036. continue;
  2037. } else if (pattern[i] == '$') {
  2038. return (str[j] == '\0') ? j : -1;
  2039. } else if (pattern[i] == '*') {
  2040. i++;
  2041. if (pattern[i] == '*') {
  2042. i++;
  2043. len = (int)strlen(str + j);
  2044. } else {
  2045. len = (int)strcspn(str + j, "/");
  2046. }
  2047. if (i == pattern_len) {
  2048. return j + len;
  2049. }
  2050. do {
  2051. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2052. } while (res == -1 && len-- > 0);
  2053. return (res == -1) ? -1 : j + res + len;
  2054. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2055. return -1;
  2056. }
  2057. }
  2058. return j;
  2059. }
  2060. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2061. * This function must tolerate situations when connection info is not
  2062. * set up, for example if request parsing failed. */
  2063. static int
  2064. should_keep_alive(const struct mg_connection *conn)
  2065. {
  2066. if (conn != NULL) {
  2067. const char *http_version = conn->request_info.http_version;
  2068. const char *header = mg_get_header(conn, "Connection");
  2069. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2070. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2071. || (header != NULL && !header_has_option(header, "keep-alive"))
  2072. || (header == NULL && http_version
  2073. && 0 != strcmp(http_version, "1.1"))) {
  2074. return 0;
  2075. }
  2076. return 1;
  2077. }
  2078. return 0;
  2079. }
  2080. static int
  2081. should_decode_url(const struct mg_connection *conn)
  2082. {
  2083. if (!conn || !conn->ctx) {
  2084. return 0;
  2085. }
  2086. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2087. }
  2088. static const char *
  2089. suggest_connection_header(const struct mg_connection *conn)
  2090. {
  2091. return should_keep_alive(conn) ? "keep-alive" : "close";
  2092. }
  2093. static int
  2094. send_no_cache_header(struct mg_connection *conn)
  2095. {
  2096. /* Send all current and obsolete cache opt-out directives. */
  2097. return mg_printf(conn,
  2098. "Cache-Control: no-cache, no-store, "
  2099. "must-revalidate, private, max-age=0\r\n"
  2100. "Pragma: no-cache\r\n"
  2101. "Expires: 0\r\n");
  2102. }
  2103. static int
  2104. send_static_cache_header(struct mg_connection *conn)
  2105. {
  2106. #if !defined(NO_CACHING)
  2107. /* Read the server config to check how long a file may be cached.
  2108. * The configuration is in seconds. */
  2109. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2110. if (max_age <= 0) {
  2111. /* 0 means "do not cache". All values <0 are reserved
  2112. * and may be used differently in the future. */
  2113. /* If a file should not be cached, do not only send
  2114. * max-age=0, but also pragmas and Expires headers. */
  2115. return send_no_cache_header(conn);
  2116. }
  2117. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2118. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2119. /* See also https://www.mnot.net/cache_docs/ */
  2120. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2121. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2122. * year to 31622400 seconds. For the moment, we just send whatever has
  2123. * been configured, still the behavior for >1 year should be considered
  2124. * as undefined. */
  2125. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2126. #else /* NO_CACHING */
  2127. return send_no_cache_header(conn);
  2128. #endif /* !NO_CACHING */
  2129. }
  2130. static void handle_file_based_request(struct mg_connection *conn,
  2131. const char *path,
  2132. struct file *filep);
  2133. static int
  2134. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2135. const char *
  2136. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2137. {
  2138. /* See IANA HTTP status code assignment:
  2139. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2140. */
  2141. switch (response_code) {
  2142. /* RFC2616 Section 10.1 - Informational 1xx */
  2143. case 100:
  2144. return "Continue"; /* RFC2616 Section 10.1.1 */
  2145. case 101:
  2146. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2147. case 102:
  2148. return "Processing"; /* RFC2518 Section 10.1 */
  2149. /* RFC2616 Section 10.2 - Successful 2xx */
  2150. case 200:
  2151. return "OK"; /* RFC2616 Section 10.2.1 */
  2152. case 201:
  2153. return "Created"; /* RFC2616 Section 10.2.2 */
  2154. case 202:
  2155. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2156. case 203:
  2157. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2158. case 204:
  2159. return "No Content"; /* RFC2616 Section 10.2.5 */
  2160. case 205:
  2161. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2162. case 206:
  2163. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2164. case 207:
  2165. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2166. case 208:
  2167. return "Already Reported"; /* RFC5842 Section 7.1 */
  2168. case 226:
  2169. return "IM used"; /* RFC3229 Section 10.4.1 */
  2170. /* RFC2616 Section 10.3 - Redirection 3xx */
  2171. case 300:
  2172. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2173. case 301:
  2174. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2175. case 302:
  2176. return "Found"; /* RFC2616 Section 10.3.3 */
  2177. case 303:
  2178. return "See Other"; /* RFC2616 Section 10.3.4 */
  2179. case 304:
  2180. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2181. case 305:
  2182. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2183. case 307:
  2184. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2185. case 308:
  2186. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2187. /* RFC2616 Section 10.4 - Client Error 4xx */
  2188. case 400:
  2189. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2190. case 401:
  2191. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2192. case 402:
  2193. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2194. case 403:
  2195. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2196. case 404:
  2197. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2198. case 405:
  2199. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2200. case 406:
  2201. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2202. case 407:
  2203. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2204. case 408:
  2205. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2206. case 409:
  2207. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2208. case 410:
  2209. return "Gone"; /* RFC2616 Section 10.4.11 */
  2210. case 411:
  2211. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2212. case 412:
  2213. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2214. case 413:
  2215. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2216. case 414:
  2217. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2218. case 415:
  2219. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2220. case 416:
  2221. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2222. case 417:
  2223. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2224. case 421:
  2225. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2226. case 422:
  2227. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2228. * Section 11.2 */
  2229. case 423:
  2230. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2231. case 424:
  2232. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2233. * Section 11.4 */
  2234. case 426:
  2235. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2236. case 428:
  2237. return "Precondition Required"; /* RFC 6585, Section 3 */
  2238. case 429:
  2239. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2240. case 431:
  2241. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2242. case 451:
  2243. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2244. * Section 3 */
  2245. /* RFC2616 Section 10.5 - Server Error 5xx */
  2246. case 500:
  2247. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2248. case 501:
  2249. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2250. case 502:
  2251. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2252. case 503:
  2253. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2254. case 504:
  2255. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2256. case 505:
  2257. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2258. case 506:
  2259. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2260. case 507:
  2261. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2262. * Section 11.5 */
  2263. case 508:
  2264. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2265. case 510:
  2266. return "Not Extended"; /* RFC 2774, Section 7 */
  2267. case 511:
  2268. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2269. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2270. * E.g., "de facto" standards due to common use, ... */
  2271. case 418:
  2272. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2273. case 419:
  2274. return "Authentication Timeout"; /* common use */
  2275. case 420:
  2276. return "Enhance Your Calm"; /* common use */
  2277. case 440:
  2278. return "Login Timeout"; /* common use */
  2279. case 509:
  2280. return "Bandwidth Limit Exceeded"; /* common use */
  2281. default:
  2282. /* This error code is unknown. This should not happen. */
  2283. if (conn) {
  2284. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2285. }
  2286. /* Return at least a category according to RFC 2616 Section 10. */
  2287. if (response_code >= 100 && response_code < 200) {
  2288. /* Unknown informational status code */
  2289. return "Information";
  2290. }
  2291. if (response_code >= 200 && response_code < 300) {
  2292. /* Unknown success code */
  2293. return "Success";
  2294. }
  2295. if (response_code >= 300 && response_code < 400) {
  2296. /* Unknown redirection code */
  2297. return "Redirection";
  2298. }
  2299. if (response_code >= 400 && response_code < 500) {
  2300. /* Unknown request error code */
  2301. return "Client Error";
  2302. }
  2303. if (response_code >= 500 && response_code < 600) {
  2304. /* Unknown server error code */
  2305. return "Server Error";
  2306. }
  2307. /* Response code not even within reasonable range */
  2308. return "";
  2309. }
  2310. }
  2311. static void send_http_error(struct mg_connection *,
  2312. int,
  2313. PRINTF_FORMAT_STRING(const char *fmt),
  2314. ...) PRINTF_ARGS(3, 4);
  2315. static void
  2316. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2317. {
  2318. char buf[MG_BUF_LEN];
  2319. va_list ap;
  2320. int len, i, page_handler_found, scope, truncated;
  2321. char date[64];
  2322. time_t curtime = time(NULL);
  2323. const char *error_handler = NULL;
  2324. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2325. const char *error_page_file_ext, *tstr;
  2326. const char *status_text = mg_get_response_code_text(conn, status);
  2327. if (conn == NULL) {
  2328. return;
  2329. }
  2330. conn->status_code = status;
  2331. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2332. || conn->ctx->callbacks.http_error(conn, status)) {
  2333. if (!conn->in_error_handler) {
  2334. /* Send user defined error pages, if defined */
  2335. error_handler = conn->ctx->config[ERROR_PAGES];
  2336. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2337. page_handler_found = 0;
  2338. if (error_handler != NULL) {
  2339. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2340. switch (scope) {
  2341. case 1: /* Handler for specific error, e.g. 404 error */
  2342. mg_snprintf(conn,
  2343. &truncated,
  2344. buf,
  2345. sizeof(buf) - 32,
  2346. "%serror%03u.",
  2347. error_handler,
  2348. status);
  2349. break;
  2350. case 2: /* Handler for error group, e.g., 5xx error handler
  2351. * for all server errors (500-599) */
  2352. mg_snprintf(conn,
  2353. &truncated,
  2354. buf,
  2355. sizeof(buf) - 32,
  2356. "%serror%01uxx.",
  2357. error_handler,
  2358. status / 100);
  2359. break;
  2360. default: /* Handler for all errors */
  2361. mg_snprintf(conn,
  2362. &truncated,
  2363. buf,
  2364. sizeof(buf) - 32,
  2365. "%serror.",
  2366. error_handler);
  2367. break;
  2368. }
  2369. /* String truncation in buf may only occur if error_handler
  2370. * is too long. This string is from the config, not from a
  2371. * client. */
  2372. (void)truncated;
  2373. len = (int)strlen(buf);
  2374. tstr = strchr(error_page_file_ext, '.');
  2375. while (tstr) {
  2376. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2377. i++)
  2378. buf[len + i - 1] = tstr[i];
  2379. buf[len + i - 1] = 0;
  2380. if (mg_stat(conn, buf, &error_page_file)) {
  2381. page_handler_found = 1;
  2382. break;
  2383. }
  2384. tstr = strchr(tstr + i, '.');
  2385. }
  2386. }
  2387. }
  2388. if (page_handler_found) {
  2389. conn->in_error_handler = 1;
  2390. handle_file_based_request(conn, buf, &error_page_file);
  2391. conn->in_error_handler = 0;
  2392. return;
  2393. }
  2394. }
  2395. /* No custom error page. Send default error page. */
  2396. gmt_time_string(date, sizeof(date), &curtime);
  2397. conn->must_close = 1;
  2398. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2399. send_no_cache_header(conn);
  2400. mg_printf(conn,
  2401. "Date: %s\r\n"
  2402. "Connection: close\r\n\r\n",
  2403. date);
  2404. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2405. if (status > 199 && status != 204 && status != 304) {
  2406. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2407. if (fmt != NULL) {
  2408. va_start(ap, fmt);
  2409. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2410. va_end(ap);
  2411. mg_write(conn, buf, strlen(buf));
  2412. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2413. }
  2414. } else {
  2415. /* No body allowed. Close the connection. */
  2416. DEBUG_TRACE("Error %i", status);
  2417. }
  2418. }
  2419. }
  2420. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2421. /* Create substitutes for POSIX functions in Win32. */
  2422. #if defined(__MINGW32__)
  2423. /* Show no warning in case system functions are not used. */
  2424. #pragma GCC diagnostic push
  2425. #pragma GCC diagnostic ignored "-Wunused-function"
  2426. #endif
  2427. static int
  2428. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2429. {
  2430. (void)unused;
  2431. *mutex = CreateMutex(NULL, FALSE, NULL);
  2432. return (*mutex == NULL) ? -1 : 0;
  2433. }
  2434. static int
  2435. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2436. {
  2437. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2438. }
  2439. static int
  2440. pthread_mutex_lock(pthread_mutex_t *mutex)
  2441. {
  2442. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2443. }
  2444. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2445. static int
  2446. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2447. {
  2448. switch (WaitForSingleObject(*mutex, 0)) {
  2449. case WAIT_OBJECT_0:
  2450. return 0;
  2451. case WAIT_TIMEOUT:
  2452. return -2; /* EBUSY */
  2453. }
  2454. return -1;
  2455. }
  2456. #endif
  2457. static int
  2458. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2459. {
  2460. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2461. }
  2462. #ifndef WIN_PTHREADS_TIME_H
  2463. static int
  2464. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2465. {
  2466. FILETIME ft;
  2467. ULARGE_INTEGER li;
  2468. BOOL ok = FALSE;
  2469. double d;
  2470. static double perfcnt_per_sec = 0.0;
  2471. if (tp) {
  2472. memset(tp, 0, sizeof(*tp));
  2473. if (clk_id == CLOCK_REALTIME) {
  2474. GetSystemTimeAsFileTime(&ft);
  2475. li.LowPart = ft.dwLowDateTime;
  2476. li.HighPart = ft.dwHighDateTime;
  2477. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2478. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2479. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2480. ok = TRUE;
  2481. } else if (clk_id == CLOCK_MONOTONIC) {
  2482. if (perfcnt_per_sec == 0.0) {
  2483. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2484. perfcnt_per_sec = 1.0 / li.QuadPart;
  2485. }
  2486. if (perfcnt_per_sec != 0.0) {
  2487. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2488. d = li.QuadPart * perfcnt_per_sec;
  2489. tp->tv_sec = (time_t)d;
  2490. d -= tp->tv_sec;
  2491. tp->tv_nsec = (long)(d * 1.0E9);
  2492. ok = TRUE;
  2493. }
  2494. }
  2495. }
  2496. return ok ? 0 : -1;
  2497. }
  2498. #endif
  2499. static int
  2500. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2501. {
  2502. (void)unused;
  2503. InitializeCriticalSection(&cv->threadIdSec);
  2504. cv->waiting_thread = NULL;
  2505. return 0;
  2506. }
  2507. static int
  2508. pthread_cond_timedwait(pthread_cond_t *cv,
  2509. pthread_mutex_t *mutex,
  2510. const struct timespec *abstime)
  2511. {
  2512. struct mg_workerTLS **ptls,
  2513. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2514. int ok;
  2515. struct timespec tsnow;
  2516. int64_t nsnow, nswaitabs, nswaitrel;
  2517. DWORD mswaitrel;
  2518. EnterCriticalSection(&cv->threadIdSec);
  2519. /* Add this thread to cv's waiting list */
  2520. ptls = &cv->waiting_thread;
  2521. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2522. ;
  2523. tls->next_waiting_thread = NULL;
  2524. *ptls = tls;
  2525. LeaveCriticalSection(&cv->threadIdSec);
  2526. if (abstime) {
  2527. clock_gettime(CLOCK_REALTIME, &tsnow);
  2528. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2529. nswaitabs =
  2530. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2531. nswaitrel = nswaitabs - nsnow;
  2532. if (nswaitrel < 0) {
  2533. nswaitrel = 0;
  2534. }
  2535. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2536. } else {
  2537. mswaitrel = INFINITE;
  2538. }
  2539. pthread_mutex_unlock(mutex);
  2540. ok = (WAIT_OBJECT_0
  2541. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2542. if (!ok) {
  2543. ok = 1;
  2544. EnterCriticalSection(&cv->threadIdSec);
  2545. ptls = &cv->waiting_thread;
  2546. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2547. if (*ptls == tls) {
  2548. *ptls = tls->next_waiting_thread;
  2549. ok = 0;
  2550. break;
  2551. }
  2552. }
  2553. LeaveCriticalSection(&cv->threadIdSec);
  2554. if (ok) {
  2555. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2556. }
  2557. }
  2558. /* This thread has been removed from cv's waiting list */
  2559. pthread_mutex_lock(mutex);
  2560. return ok ? 0 : -1;
  2561. }
  2562. static int
  2563. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2564. {
  2565. return pthread_cond_timedwait(cv, mutex, NULL);
  2566. }
  2567. static int
  2568. pthread_cond_signal(pthread_cond_t *cv)
  2569. {
  2570. HANDLE wkup = NULL;
  2571. BOOL ok = FALSE;
  2572. EnterCriticalSection(&cv->threadIdSec);
  2573. if (cv->waiting_thread) {
  2574. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2575. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2576. ok = SetEvent(wkup);
  2577. assert(ok);
  2578. }
  2579. LeaveCriticalSection(&cv->threadIdSec);
  2580. return ok ? 0 : 1;
  2581. }
  2582. static int
  2583. pthread_cond_broadcast(pthread_cond_t *cv)
  2584. {
  2585. EnterCriticalSection(&cv->threadIdSec);
  2586. while (cv->waiting_thread) {
  2587. pthread_cond_signal(cv);
  2588. }
  2589. LeaveCriticalSection(&cv->threadIdSec);
  2590. return 0;
  2591. }
  2592. static int
  2593. pthread_cond_destroy(pthread_cond_t *cv)
  2594. {
  2595. EnterCriticalSection(&cv->threadIdSec);
  2596. assert(cv->waiting_thread == NULL);
  2597. LeaveCriticalSection(&cv->threadIdSec);
  2598. DeleteCriticalSection(&cv->threadIdSec);
  2599. return 0;
  2600. }
  2601. static int
  2602. event_create(void)
  2603. {
  2604. return (int)CreateEvent(NULL, FALSE, FALSE, NULL);
  2605. }
  2606. static int
  2607. event_wait(int eventhdl)
  2608. {
  2609. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2610. return (res == WAIT_OBJECT_0);
  2611. }
  2612. static int
  2613. event_signal(int eventhdl)
  2614. {
  2615. return (int)SetEvent((HANDLE)eventhdl);
  2616. }
  2617. static void
  2618. event_destroy(int eventhdl)
  2619. {
  2620. CloseHandle((HANDLE)eventhdl);
  2621. }
  2622. #if defined(__MINGW32__)
  2623. /* Enable unused function warning again */
  2624. #pragma GCC diagnostic pop
  2625. #endif
  2626. /* For Windows, change all slashes to backslashes in path names. */
  2627. static void
  2628. change_slashes_to_backslashes(char *path)
  2629. {
  2630. int i;
  2631. for (i = 0; path[i] != '\0'; i++) {
  2632. if (path[i] == '/') {
  2633. path[i] = '\\';
  2634. }
  2635. /* remove double backslash (check i > 0 to preserve UNC paths,
  2636. * like \\server\file.txt) */
  2637. if ((path[i] == '\\') && (i > 0)) {
  2638. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2639. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2640. }
  2641. }
  2642. }
  2643. }
  2644. static int
  2645. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2646. {
  2647. int diff;
  2648. do {
  2649. diff = tolower(*s1) - tolower(*s2);
  2650. s1++;
  2651. s2++;
  2652. } while (diff == 0 && s1[-1] != '\0');
  2653. return diff;
  2654. }
  2655. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2656. * wbuf and wbuf_len is a target buffer and its length. */
  2657. static void
  2658. path_to_unicode(const struct mg_connection *conn,
  2659. const char *path,
  2660. wchar_t *wbuf,
  2661. size_t wbuf_len)
  2662. {
  2663. char buf[PATH_MAX], buf2[PATH_MAX];
  2664. wchar_t wbuf2[MAX_PATH + 1];
  2665. DWORD long_len, err;
  2666. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2667. mg_strlcpy(buf, path, sizeof(buf));
  2668. change_slashes_to_backslashes(buf);
  2669. /* Convert to Unicode and back. If doubly-converted string does not
  2670. * match the original, something is fishy, reject. */
  2671. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2672. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2673. WideCharToMultiByte(
  2674. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2675. if (strcmp(buf, buf2) != 0) {
  2676. wbuf[0] = L'\0';
  2677. }
  2678. /* TODO: Add a configuration to switch between case sensitive and
  2679. * case insensitive URIs for Windows server. */
  2680. /*
  2681. if (conn) {
  2682. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2683. fcompare = wcscmp;
  2684. }
  2685. }
  2686. */
  2687. (void)conn; /* conn is currently unused */
  2688. #if !defined(_WIN32_WCE)
  2689. /* Only accept a full file path, not a Windows short (8.3) path. */
  2690. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2691. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2692. if (long_len == 0) {
  2693. err = GetLastError();
  2694. if (err == ERROR_FILE_NOT_FOUND) {
  2695. /* File does not exist. This is not always a problem here. */
  2696. return;
  2697. }
  2698. }
  2699. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2700. /* Short name is used. */
  2701. wbuf[0] = L'\0';
  2702. }
  2703. #else
  2704. (void)long_len;
  2705. (void)wbuf2;
  2706. (void)err;
  2707. if (strchr(path, '~')) {
  2708. wbuf[0] = L'\0';
  2709. }
  2710. #endif
  2711. }
  2712. /* Windows happily opens files with some garbage at the end of file name.
  2713. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2714. * "a.cgi", despite one would expect an error back.
  2715. * This function returns non-0 if path ends with some garbage. */
  2716. static int
  2717. path_cannot_disclose_cgi(const char *path)
  2718. {
  2719. static const char *allowed_last_characters = "_-";
  2720. int last = path[strlen(path) - 1];
  2721. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2722. }
  2723. static int
  2724. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2725. {
  2726. wchar_t wbuf[PATH_MAX];
  2727. WIN32_FILE_ATTRIBUTE_DATA info;
  2728. time_t creation_time;
  2729. if (!filep) {
  2730. return 0;
  2731. }
  2732. memset(filep, 0, sizeof(*filep));
  2733. if (conn && is_file_in_memory(conn, path, filep)) {
  2734. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2735. * memset */
  2736. filep->last_modified = time(NULL);
  2737. /* last_modified = now ... assumes the file may change during runtime,
  2738. * so every mg_fopen call may return different data */
  2739. /* last_modified = conn->ctx.start_time;
  2740. * May be used it the data does not change during runtime. This allows
  2741. * browser caching. Since we do not know, we have to assume the file
  2742. * in memory may change. */
  2743. return 1;
  2744. }
  2745. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2746. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2747. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2748. filep->last_modified =
  2749. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2750. info.ftLastWriteTime.dwHighDateTime);
  2751. /* On Windows, the file creation time can be higher than the
  2752. * modification time, e.g. when a file is copied.
  2753. * Since the Last-Modified timestamp is used for caching
  2754. * it should be based on the most recent timestamp. */
  2755. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2756. info.ftCreationTime.dwHighDateTime);
  2757. if (creation_time > filep->last_modified) {
  2758. filep->last_modified = creation_time;
  2759. }
  2760. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2761. /* If file name is fishy, reset the file structure and return
  2762. * error.
  2763. * Note it is important to reset, not just return the error, cause
  2764. * functions like is_file_opened() check the struct. */
  2765. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2766. memset(filep, 0, sizeof(*filep));
  2767. return 0;
  2768. }
  2769. return 1;
  2770. }
  2771. return 0;
  2772. }
  2773. static int
  2774. mg_remove(const struct mg_connection *conn, const char *path)
  2775. {
  2776. wchar_t wbuf[PATH_MAX];
  2777. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2778. return DeleteFileW(wbuf) ? 0 : -1;
  2779. }
  2780. static int
  2781. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2782. {
  2783. wchar_t wbuf[PATH_MAX];
  2784. (void)mode;
  2785. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2786. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2787. }
  2788. /* Create substitutes for POSIX functions in Win32. */
  2789. #if defined(__MINGW32__)
  2790. /* Show no warning in case system functions are not used. */
  2791. #pragma GCC diagnostic push
  2792. #pragma GCC diagnostic ignored "-Wunused-function"
  2793. #endif
  2794. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2795. static DIR *
  2796. mg_opendir(const struct mg_connection *conn, const char *name)
  2797. {
  2798. DIR *dir = NULL;
  2799. wchar_t wpath[PATH_MAX];
  2800. DWORD attrs;
  2801. if (name == NULL) {
  2802. SetLastError(ERROR_BAD_ARGUMENTS);
  2803. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2804. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2805. } else {
  2806. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2807. attrs = GetFileAttributesW(wpath);
  2808. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2809. == FILE_ATTRIBUTE_DIRECTORY)) {
  2810. (void)wcscat(wpath, L"\\*");
  2811. dir->handle = FindFirstFileW(wpath, &dir->info);
  2812. dir->result.d_name[0] = '\0';
  2813. } else {
  2814. mg_free(dir);
  2815. dir = NULL;
  2816. }
  2817. }
  2818. return dir;
  2819. }
  2820. static int
  2821. mg_closedir(DIR *dir)
  2822. {
  2823. int result = 0;
  2824. if (dir != NULL) {
  2825. if (dir->handle != INVALID_HANDLE_VALUE)
  2826. result = FindClose(dir->handle) ? 0 : -1;
  2827. mg_free(dir);
  2828. } else {
  2829. result = -1;
  2830. SetLastError(ERROR_BAD_ARGUMENTS);
  2831. }
  2832. return result;
  2833. }
  2834. static struct dirent *
  2835. mg_readdir(DIR *dir)
  2836. {
  2837. struct dirent *result = 0;
  2838. if (dir) {
  2839. if (dir->handle != INVALID_HANDLE_VALUE) {
  2840. result = &dir->result;
  2841. (void)WideCharToMultiByte(CP_UTF8,
  2842. 0,
  2843. dir->info.cFileName,
  2844. -1,
  2845. result->d_name,
  2846. sizeof(result->d_name),
  2847. NULL,
  2848. NULL);
  2849. if (!FindNextFileW(dir->handle, &dir->info)) {
  2850. (void)FindClose(dir->handle);
  2851. dir->handle = INVALID_HANDLE_VALUE;
  2852. }
  2853. } else {
  2854. SetLastError(ERROR_FILE_NOT_FOUND);
  2855. }
  2856. } else {
  2857. SetLastError(ERROR_BAD_ARGUMENTS);
  2858. }
  2859. return result;
  2860. }
  2861. #ifndef HAVE_POLL
  2862. static int
  2863. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2864. {
  2865. struct timeval tv;
  2866. fd_set set;
  2867. unsigned int i;
  2868. int result;
  2869. SOCKET maxfd = 0;
  2870. memset(&tv, 0, sizeof(tv));
  2871. tv.tv_sec = milliseconds / 1000;
  2872. tv.tv_usec = (milliseconds % 1000) * 1000;
  2873. FD_ZERO(&set);
  2874. for (i = 0; i < n; i++) {
  2875. FD_SET((SOCKET)pfd[i].fd, &set);
  2876. pfd[i].revents = 0;
  2877. if (pfd[i].fd > maxfd) {
  2878. maxfd = pfd[i].fd;
  2879. }
  2880. }
  2881. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2882. for (i = 0; i < n; i++) {
  2883. if (FD_ISSET(pfd[i].fd, &set)) {
  2884. pfd[i].revents = POLLIN;
  2885. }
  2886. }
  2887. }
  2888. return result;
  2889. }
  2890. #endif /* HAVE_POLL */
  2891. #if defined(__MINGW32__)
  2892. /* Enable unused function warning again */
  2893. #pragma GCC diagnostic pop
  2894. #endif
  2895. static void
  2896. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2897. {
  2898. (void)conn; /* Unused. */
  2899. #if defined(_WIN32_WCE)
  2900. (void)sock;
  2901. #else
  2902. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2903. #endif
  2904. }
  2905. int
  2906. mg_start_thread(mg_thread_func_t f, void *p)
  2907. {
  2908. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2909. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2910. */
  2911. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2912. == ((uintptr_t)(-1L)))
  2913. ? -1
  2914. : 0);
  2915. #else
  2916. return (
  2917. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2918. ? -1
  2919. : 0);
  2920. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2921. }
  2922. /* Start a thread storing the thread context. */
  2923. static int
  2924. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2925. void *p,
  2926. pthread_t *threadidptr)
  2927. {
  2928. uintptr_t uip;
  2929. HANDLE threadhandle;
  2930. int result = -1;
  2931. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2932. threadhandle = (HANDLE)uip;
  2933. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2934. *threadidptr = threadhandle;
  2935. result = 0;
  2936. }
  2937. return result;
  2938. }
  2939. /* Wait for a thread to finish. */
  2940. static int
  2941. mg_join_thread(pthread_t threadid)
  2942. {
  2943. int result;
  2944. DWORD dwevent;
  2945. result = -1;
  2946. dwevent = WaitForSingleObject(threadid, INFINITE);
  2947. if (dwevent == WAIT_FAILED) {
  2948. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2949. } else {
  2950. if (dwevent == WAIT_OBJECT_0) {
  2951. CloseHandle(threadid);
  2952. result = 0;
  2953. }
  2954. }
  2955. return result;
  2956. }
  2957. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  2958. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  2959. /* Create substitutes for POSIX functions in Win32. */
  2960. #if defined(__MINGW32__)
  2961. /* Show no warning in case system functions are not used. */
  2962. #pragma GCC diagnostic push
  2963. #pragma GCC diagnostic ignored "-Wunused-function"
  2964. #endif
  2965. static HANDLE
  2966. dlopen(const char *dll_name, int flags)
  2967. {
  2968. wchar_t wbuf[PATH_MAX];
  2969. (void)flags;
  2970. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  2971. return LoadLibraryW(wbuf);
  2972. }
  2973. static int
  2974. dlclose(void *handle)
  2975. {
  2976. int result;
  2977. if (FreeLibrary((HMODULE)handle) != 0) {
  2978. result = 0;
  2979. } else {
  2980. result = -1;
  2981. }
  2982. return result;
  2983. }
  2984. #if defined(__MINGW32__)
  2985. /* Enable unused function warning again */
  2986. #pragma GCC diagnostic pop
  2987. #endif
  2988. #endif
  2989. #if !defined(NO_CGI)
  2990. #define SIGKILL (0)
  2991. static int
  2992. kill(pid_t pid, int sig_num)
  2993. {
  2994. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2995. (void)CloseHandle((HANDLE)pid);
  2996. return 0;
  2997. }
  2998. static void
  2999. trim_trailing_whitespaces(char *s)
  3000. {
  3001. char *e = s + strlen(s) - 1;
  3002. while (e > s && isspace(*(unsigned char *)e)) {
  3003. *e-- = '\0';
  3004. }
  3005. }
  3006. static pid_t
  3007. spawn_process(struct mg_connection *conn,
  3008. const char *prog,
  3009. char *envblk,
  3010. char *envp[],
  3011. int fdin[2],
  3012. int fdout[2],
  3013. int fderr[2],
  3014. const char *dir)
  3015. {
  3016. HANDLE me;
  3017. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3018. cmdline[PATH_MAX], buf[PATH_MAX];
  3019. int truncated;
  3020. struct file file = STRUCT_FILE_INITIALIZER;
  3021. STARTUPINFOA si;
  3022. PROCESS_INFORMATION pi = {0};
  3023. (void)envp;
  3024. memset(&si, 0, sizeof(si));
  3025. si.cb = sizeof(si);
  3026. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3027. si.wShowWindow = SW_HIDE;
  3028. me = GetCurrentProcess();
  3029. DuplicateHandle(me,
  3030. (HANDLE)_get_osfhandle(fdin[0]),
  3031. me,
  3032. &si.hStdInput,
  3033. 0,
  3034. TRUE,
  3035. DUPLICATE_SAME_ACCESS);
  3036. DuplicateHandle(me,
  3037. (HANDLE)_get_osfhandle(fdout[1]),
  3038. me,
  3039. &si.hStdOutput,
  3040. 0,
  3041. TRUE,
  3042. DUPLICATE_SAME_ACCESS);
  3043. DuplicateHandle(me,
  3044. (HANDLE)_get_osfhandle(fderr[1]),
  3045. me,
  3046. &si.hStdError,
  3047. 0,
  3048. TRUE,
  3049. DUPLICATE_SAME_ACCESS);
  3050. /* Mark handles that should not be inherited. See
  3051. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3052. */
  3053. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3054. HANDLE_FLAG_INHERIT,
  3055. 0);
  3056. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3057. HANDLE_FLAG_INHERIT,
  3058. 0);
  3059. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3060. HANDLE_FLAG_INHERIT,
  3061. 0);
  3062. /* If CGI file is a script, try to read the interpreter line */
  3063. interp = conn->ctx->config[CGI_INTERPRETER];
  3064. if (interp == NULL) {
  3065. buf[0] = buf[1] = '\0';
  3066. /* Read the first line of the script into the buffer */
  3067. mg_snprintf(
  3068. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3069. if (truncated) {
  3070. pi.hProcess = (pid_t)-1;
  3071. goto spawn_cleanup;
  3072. }
  3073. if (mg_fopen(conn, cmdline, "r", &file)) {
  3074. p = (char *)file.membuf;
  3075. mg_fgets(buf, sizeof(buf), &file, &p);
  3076. mg_fclose(&file);
  3077. buf[sizeof(buf) - 1] = '\0';
  3078. }
  3079. if (buf[0] == '#' && buf[1] == '!') {
  3080. trim_trailing_whitespaces(buf + 2);
  3081. } else {
  3082. buf[2] = '\0';
  3083. }
  3084. interp = buf + 2;
  3085. }
  3086. if (interp[0] != '\0') {
  3087. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3088. interp = full_interp;
  3089. }
  3090. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3091. if (interp[0] != '\0') {
  3092. mg_snprintf(conn,
  3093. &truncated,
  3094. cmdline,
  3095. sizeof(cmdline),
  3096. "\"%s\" \"%s\\%s\"",
  3097. interp,
  3098. full_dir,
  3099. prog);
  3100. } else {
  3101. mg_snprintf(conn,
  3102. &truncated,
  3103. cmdline,
  3104. sizeof(cmdline),
  3105. "\"%s\\%s\"",
  3106. full_dir,
  3107. prog);
  3108. }
  3109. if (truncated) {
  3110. pi.hProcess = (pid_t)-1;
  3111. goto spawn_cleanup;
  3112. }
  3113. DEBUG_TRACE("Running [%s]", cmdline);
  3114. if (CreateProcessA(NULL,
  3115. cmdline,
  3116. NULL,
  3117. NULL,
  3118. TRUE,
  3119. CREATE_NEW_PROCESS_GROUP,
  3120. envblk,
  3121. NULL,
  3122. &si,
  3123. &pi) == 0) {
  3124. mg_cry(
  3125. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3126. pi.hProcess = (pid_t)-1;
  3127. /* goto spawn_cleanup; */
  3128. }
  3129. spawn_cleanup:
  3130. (void)CloseHandle(si.hStdOutput);
  3131. (void)CloseHandle(si.hStdError);
  3132. (void)CloseHandle(si.hStdInput);
  3133. if (pi.hThread != NULL) {
  3134. (void)CloseHandle(pi.hThread);
  3135. }
  3136. return (pid_t)pi.hProcess;
  3137. }
  3138. #endif /* !NO_CGI */
  3139. static int
  3140. set_non_blocking_mode(SOCKET sock)
  3141. {
  3142. unsigned long on = 1;
  3143. return ioctlsocket(sock, (long)FIONBIO, &on);
  3144. }
  3145. #else
  3146. static int
  3147. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3148. {
  3149. struct stat st;
  3150. if (!filep) {
  3151. return 0;
  3152. }
  3153. memset(filep, 0, sizeof(*filep));
  3154. if (conn && is_file_in_memory(conn, path, filep)) {
  3155. return 1;
  3156. }
  3157. if (0 == stat(path, &st)) {
  3158. filep->size = (uint64_t)(st.st_size);
  3159. filep->last_modified = st.st_mtime;
  3160. filep->is_directory = S_ISDIR(st.st_mode);
  3161. return 1;
  3162. }
  3163. return 0;
  3164. }
  3165. static void
  3166. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3167. {
  3168. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3169. if (conn) {
  3170. mg_cry(conn,
  3171. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3172. __func__,
  3173. strerror(ERRNO));
  3174. }
  3175. }
  3176. }
  3177. int
  3178. mg_start_thread(mg_thread_func_t func, void *param)
  3179. {
  3180. pthread_t thread_id;
  3181. pthread_attr_t attr;
  3182. int result;
  3183. (void)pthread_attr_init(&attr);
  3184. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3185. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3186. /* Compile-time option to control stack size,
  3187. * e.g. -DUSE_STACK_SIZE=16384 */
  3188. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3189. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3190. result = pthread_create(&thread_id, &attr, func, param);
  3191. pthread_attr_destroy(&attr);
  3192. return result;
  3193. }
  3194. /* Start a thread storing the thread context. */
  3195. static int
  3196. mg_start_thread_with_id(mg_thread_func_t func,
  3197. void *param,
  3198. pthread_t *threadidptr)
  3199. {
  3200. pthread_t thread_id;
  3201. pthread_attr_t attr;
  3202. int result;
  3203. (void)pthread_attr_init(&attr);
  3204. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3205. /* Compile-time option to control stack size,
  3206. * e.g. -DUSE_STACK_SIZE=16384 */
  3207. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3208. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3209. result = pthread_create(&thread_id, &attr, func, param);
  3210. pthread_attr_destroy(&attr);
  3211. if ((result == 0) && (threadidptr != NULL)) {
  3212. *threadidptr = thread_id;
  3213. }
  3214. return result;
  3215. }
  3216. /* Wait for a thread to finish. */
  3217. static int
  3218. mg_join_thread(pthread_t threadid)
  3219. {
  3220. int result;
  3221. result = pthread_join(threadid, NULL);
  3222. return result;
  3223. }
  3224. #ifndef NO_CGI
  3225. static pid_t
  3226. spawn_process(struct mg_connection *conn,
  3227. const char *prog,
  3228. char *envblk,
  3229. char *envp[],
  3230. int fdin[2],
  3231. int fdout[2],
  3232. int fderr[2],
  3233. const char *dir)
  3234. {
  3235. pid_t pid;
  3236. const char *interp;
  3237. (void)envblk;
  3238. if (conn == NULL) {
  3239. return 0;
  3240. }
  3241. if ((pid = fork()) == -1) {
  3242. /* Parent */
  3243. send_http_error(conn,
  3244. 500,
  3245. "Error: Creating CGI process\nfork(): %s",
  3246. strerror(ERRNO));
  3247. } else if (pid == 0) {
  3248. /* Child */
  3249. if (chdir(dir) != 0) {
  3250. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3251. } else if (dup2(fdin[0], 0) == -1) {
  3252. mg_cry(conn,
  3253. "%s: dup2(%d, 0): %s",
  3254. __func__,
  3255. fdin[0],
  3256. strerror(ERRNO));
  3257. } else if (dup2(fdout[1], 1) == -1) {
  3258. mg_cry(conn,
  3259. "%s: dup2(%d, 1): %s",
  3260. __func__,
  3261. fdout[1],
  3262. strerror(ERRNO));
  3263. } else if (dup2(fderr[1], 2) == -1) {
  3264. mg_cry(conn,
  3265. "%s: dup2(%d, 2): %s",
  3266. __func__,
  3267. fderr[1],
  3268. strerror(ERRNO));
  3269. } else {
  3270. /* Keep stderr and stdout in two different pipes.
  3271. * Stdout will be sent back to the client,
  3272. * stderr should go into a server error log. */
  3273. (void)close(fdin[0]);
  3274. (void)close(fdout[1]);
  3275. (void)close(fderr[1]);
  3276. /* Close write end fdin and read end fdout and fderr */
  3277. (void)close(fdin[1]);
  3278. (void)close(fdout[0]);
  3279. (void)close(fderr[0]);
  3280. /* After exec, all signal handlers are restored to their default
  3281. * values, with one exception of SIGCHLD. According to
  3282. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3283. * leave unchanged after exec if it was set to be ignored. Restore
  3284. * it to default action. */
  3285. signal(SIGCHLD, SIG_DFL);
  3286. interp = conn->ctx->config[CGI_INTERPRETER];
  3287. if (interp == NULL) {
  3288. (void)execle(prog, prog, NULL, envp);
  3289. mg_cry(conn,
  3290. "%s: execle(%s): %s",
  3291. __func__,
  3292. prog,
  3293. strerror(ERRNO));
  3294. } else {
  3295. (void)execle(interp, interp, prog, NULL, envp);
  3296. mg_cry(conn,
  3297. "%s: execle(%s %s): %s",
  3298. __func__,
  3299. interp,
  3300. prog,
  3301. strerror(ERRNO));
  3302. }
  3303. }
  3304. exit(EXIT_FAILURE);
  3305. }
  3306. return pid;
  3307. }
  3308. #endif /* !NO_CGI */
  3309. static int
  3310. set_non_blocking_mode(SOCKET sock)
  3311. {
  3312. int flags;
  3313. flags = fcntl(sock, F_GETFL, 0);
  3314. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3315. return 0;
  3316. }
  3317. #endif /* _WIN32 */
  3318. /* End of initial operating system specific define block. */
  3319. /* Get a random number (independent of C rand function) */
  3320. static uint64_t
  3321. get_random(void)
  3322. {
  3323. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3324. static uint64_t lcg = 0; /* Linear congruential generator */
  3325. struct timespec now;
  3326. memset(&now, 0, sizeof(now));
  3327. clock_gettime(CLOCK_MONOTONIC, &now);
  3328. if (lfsr == 0) {
  3329. /* lfsr will be only 0 if has not been initialized,
  3330. * so this code is called only once. */
  3331. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3332. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3333. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3334. + (uint64_t)(ptrdiff_t)&now;
  3335. } else {
  3336. /* Get the next step of both random number generators. */
  3337. lfsr = (lfsr >> 1)
  3338. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3339. << 63);
  3340. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3341. }
  3342. /* Combining two pseudo-random number generators and a high resolution part
  3343. * of the current server time will make it hard (impossible?) to guess the
  3344. * next number. */
  3345. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3346. }
  3347. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3348. * descriptor. Return number of bytes written. */
  3349. static int
  3350. push(struct mg_context *ctx,
  3351. FILE *fp,
  3352. SOCKET sock,
  3353. SSL *ssl,
  3354. const char *buf,
  3355. int len,
  3356. double timeout)
  3357. {
  3358. struct timespec start, now;
  3359. int n, err;
  3360. #ifdef _WIN32
  3361. typedef int len_t;
  3362. #else
  3363. typedef size_t len_t;
  3364. #endif
  3365. if (timeout > 0) {
  3366. memset(&start, 0, sizeof(start));
  3367. memset(&now, 0, sizeof(now));
  3368. clock_gettime(CLOCK_MONOTONIC, &start);
  3369. }
  3370. if (ctx == NULL) {
  3371. return -1;
  3372. }
  3373. #ifdef NO_SSL
  3374. if (ssl) {
  3375. return -1;
  3376. }
  3377. #endif
  3378. do {
  3379. #ifndef NO_SSL
  3380. if (ssl != NULL) {
  3381. n = SSL_write(ssl, buf, len);
  3382. if (n <= 0) {
  3383. err = SSL_get_error(ssl, n);
  3384. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3385. err = ERRNO;
  3386. } else if ((err == SSL_ERROR_WANT_READ)
  3387. || (err == SSL_ERROR_WANT_WRITE)) {
  3388. n = 0;
  3389. } else {
  3390. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3391. return -1;
  3392. }
  3393. } else {
  3394. err = 0;
  3395. }
  3396. } else
  3397. #endif
  3398. if (fp != NULL) {
  3399. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3400. if (ferror(fp)) {
  3401. n = -1;
  3402. err = ERRNO;
  3403. } else {
  3404. err = 0;
  3405. }
  3406. } else {
  3407. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3408. err = (n < 0) ? ERRNO : 0;
  3409. if (n == 0) {
  3410. /* shutdown of the socket at client side */
  3411. return -1;
  3412. }
  3413. }
  3414. if (ctx->stop_flag) {
  3415. return -1;
  3416. }
  3417. if ((n > 0) || (n == 0 && len == 0)) {
  3418. /* some data has been read, or no data was requested */
  3419. return n;
  3420. }
  3421. if (n < 0) {
  3422. /* socket error - check errno */
  3423. DEBUG_TRACE("send() failed, error %d", err);
  3424. /* TODO: error handling depending on the error code.
  3425. * These codes are different between Windows and Linux.
  3426. */
  3427. return -1;
  3428. }
  3429. /* This code is not reached in the moment.
  3430. * ==> Fix the TODOs above first. */
  3431. if (timeout > 0) {
  3432. clock_gettime(CLOCK_MONOTONIC, &now);
  3433. }
  3434. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3435. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3436. used */
  3437. return -1;
  3438. }
  3439. static int64_t
  3440. push_all(struct mg_context *ctx,
  3441. FILE *fp,
  3442. SOCKET sock,
  3443. SSL *ssl,
  3444. const char *buf,
  3445. int64_t len)
  3446. {
  3447. double timeout = -1.0;
  3448. int64_t n, nwritten = 0;
  3449. if (ctx == NULL) {
  3450. return -1;
  3451. }
  3452. if (ctx->config[REQUEST_TIMEOUT]) {
  3453. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3454. }
  3455. while (len > 0 && ctx->stop_flag == 0) {
  3456. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3457. if (n < 0) {
  3458. if (nwritten == 0) {
  3459. nwritten = n; /* Propagate the error */
  3460. }
  3461. break;
  3462. } else if (n == 0) {
  3463. break; /* No more data to write */
  3464. } else {
  3465. nwritten += n;
  3466. len -= n;
  3467. }
  3468. }
  3469. return nwritten;
  3470. }
  3471. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3472. * Return negative value on error, or number of bytes read on success. */
  3473. static int
  3474. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3475. {
  3476. int nread, err;
  3477. struct timespec start, now;
  3478. #ifdef _WIN32
  3479. typedef int len_t;
  3480. #else
  3481. typedef size_t len_t;
  3482. #endif
  3483. if (timeout > 0) {
  3484. memset(&start, 0, sizeof(start));
  3485. memset(&now, 0, sizeof(now));
  3486. clock_gettime(CLOCK_MONOTONIC, &start);
  3487. }
  3488. do {
  3489. if (fp != NULL) {
  3490. #if !defined(_WIN32_WCE)
  3491. /* Use read() instead of fread(), because if we're reading from the
  3492. * CGI pipe, fread() may block until IO buffer is filled up. We
  3493. * cannot afford to block and must pass all read bytes immediately
  3494. * to the client. */
  3495. nread = (int)read(fileno(fp), buf, (size_t)len);
  3496. #else
  3497. /* WinCE does not support CGI pipes */
  3498. nread = (int)fread(buf, 1, (size_t)len, fp);
  3499. #endif
  3500. err = (nread < 0) ? ERRNO : 0;
  3501. #ifndef NO_SSL
  3502. } else if (conn->ssl != NULL) {
  3503. nread = SSL_read(conn->ssl, buf, len);
  3504. if (nread <= 0) {
  3505. err = SSL_get_error(conn->ssl, nread);
  3506. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3507. err = ERRNO;
  3508. } else if ((err == SSL_ERROR_WANT_READ)
  3509. || (err == SSL_ERROR_WANT_WRITE)) {
  3510. nread = 0;
  3511. } else {
  3512. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3513. return -1;
  3514. }
  3515. } else {
  3516. err = 0;
  3517. }
  3518. #endif
  3519. } else {
  3520. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3521. err = (nread < 0) ? ERRNO : 0;
  3522. if (nread == 0) {
  3523. /* shutdown of the socket at client side */
  3524. return -1;
  3525. }
  3526. }
  3527. if (conn->ctx->stop_flag) {
  3528. return -1;
  3529. }
  3530. if ((nread > 0) || (nread == 0 && len == 0)) {
  3531. /* some data has been read, or no data was requested */
  3532. return nread;
  3533. }
  3534. if (nread < 0) {
  3535. /* socket error - check errno */
  3536. #ifdef _WIN32
  3537. if (err == WSAEWOULDBLOCK) {
  3538. /* standard case if called from close_socket_gracefully */
  3539. return -1;
  3540. } else if (err == WSAETIMEDOUT) {
  3541. /* timeout is handled by the while loop */
  3542. } else {
  3543. DEBUG_TRACE("recv() failed, error %d", err);
  3544. return -1;
  3545. }
  3546. #else
  3547. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3548. * if the timeout is reached and if the socket was set to non-
  3549. * blocking in close_socket_gracefully, so we can not distinguish
  3550. * here. We have to wait for the timeout in both cases for now.
  3551. */
  3552. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3553. /* EAGAIN/EWOULDBLOCK:
  3554. * standard case if called from close_socket_gracefully
  3555. * => should return -1 */
  3556. /* or timeout occured
  3557. * => the code must stay in the while loop */
  3558. /* EINTR can be generated on a socket with a timeout set even
  3559. * when SA_RESTART is effective for all relevant signals
  3560. * (see signal(7)).
  3561. * => stay in the while loop */
  3562. } else {
  3563. DEBUG_TRACE("recv() failed, error %d", err);
  3564. return -1;
  3565. }
  3566. #endif
  3567. }
  3568. if (timeout > 0) {
  3569. clock_gettime(CLOCK_MONOTONIC, &now);
  3570. }
  3571. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3572. /* Timeout occured, but no data available. */
  3573. return -1;
  3574. }
  3575. static int
  3576. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3577. {
  3578. int n, nread = 0;
  3579. double timeout = -1.0;
  3580. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3581. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3582. }
  3583. while (len > 0 && conn->ctx->stop_flag == 0) {
  3584. n = pull(fp, conn, buf + nread, len, timeout);
  3585. if (n < 0) {
  3586. if (nread == 0) {
  3587. nread = n; /* Propagate the error */
  3588. }
  3589. break;
  3590. } else if (n == 0) {
  3591. break; /* No more data to read */
  3592. } else {
  3593. conn->consumed_content += n;
  3594. nread += n;
  3595. len -= n;
  3596. }
  3597. }
  3598. return nread;
  3599. }
  3600. static void
  3601. discard_unread_request_data(struct mg_connection *conn)
  3602. {
  3603. char buf[MG_BUF_LEN];
  3604. size_t to_read;
  3605. int nread;
  3606. if (conn == NULL) {
  3607. return;
  3608. }
  3609. to_read = sizeof(buf);
  3610. if (conn->is_chunked) {
  3611. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3612. * completely */
  3613. while (conn->is_chunked == 1) {
  3614. nread = mg_read(conn, buf, to_read);
  3615. if (nread <= 0) {
  3616. break;
  3617. }
  3618. }
  3619. } else {
  3620. /* Not chunked: content length is known */
  3621. while (conn->consumed_content < conn->content_len) {
  3622. if (to_read
  3623. > (size_t)(conn->content_len - conn->consumed_content)) {
  3624. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3625. }
  3626. nread = mg_read(conn, buf, to_read);
  3627. if (nread <= 0) {
  3628. break;
  3629. }
  3630. }
  3631. }
  3632. }
  3633. static int
  3634. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3635. {
  3636. int64_t n, buffered_len, nread;
  3637. int64_t len64 =
  3638. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3639. * int, we may not read more
  3640. * bytes */
  3641. const char *body;
  3642. if (conn == NULL) {
  3643. return 0;
  3644. }
  3645. /* If Content-Length is not set for a PUT or POST request, read until
  3646. * socket is closed */
  3647. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3648. conn->content_len = INT64_MAX;
  3649. conn->must_close = 1;
  3650. }
  3651. nread = 0;
  3652. if (conn->consumed_content < conn->content_len) {
  3653. /* Adjust number of bytes to read. */
  3654. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3655. if (left_to_read < len64) {
  3656. /* Do not read more than the total content length of the request.
  3657. */
  3658. len64 = left_to_read;
  3659. }
  3660. /* Return buffered data */
  3661. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3662. - conn->consumed_content;
  3663. if (buffered_len > 0) {
  3664. if (len64 < buffered_len) {
  3665. buffered_len = len64;
  3666. }
  3667. body = conn->buf + conn->request_len + conn->consumed_content;
  3668. memcpy(buf, body, (size_t)buffered_len);
  3669. len64 -= buffered_len;
  3670. conn->consumed_content += buffered_len;
  3671. nread += buffered_len;
  3672. buf = (char *)buf + buffered_len;
  3673. }
  3674. /* We have returned all buffered data. Read new data from the remote
  3675. * socket.
  3676. */
  3677. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3678. nread += n;
  3679. } else {
  3680. nread = ((nread > 0) ? nread : n);
  3681. }
  3682. }
  3683. return (int)nread;
  3684. }
  3685. static char
  3686. mg_getc(struct mg_connection *conn)
  3687. {
  3688. char c;
  3689. if (conn == NULL) {
  3690. return 0;
  3691. }
  3692. conn->content_len++;
  3693. if (mg_read_inner(conn, &c, 1) <= 0) {
  3694. return (char)0;
  3695. }
  3696. return c;
  3697. }
  3698. int
  3699. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3700. {
  3701. if (len > INT_MAX) {
  3702. len = INT_MAX;
  3703. }
  3704. if (conn == NULL) {
  3705. return 0;
  3706. }
  3707. if (conn->is_chunked) {
  3708. size_t all_read = 0;
  3709. while (len > 0) {
  3710. if (conn->is_chunked == 2) {
  3711. /* No more data left to read */
  3712. return 0;
  3713. }
  3714. if (conn->chunk_remainder) {
  3715. /* copy from the remainder of the last received chunk */
  3716. long read_ret;
  3717. size_t read_now =
  3718. ((conn->chunk_remainder > len) ? (len)
  3719. : (conn->chunk_remainder));
  3720. conn->content_len += (int)read_now;
  3721. read_ret =
  3722. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3723. all_read += (size_t)read_ret;
  3724. conn->chunk_remainder -= read_now;
  3725. len -= read_now;
  3726. if (conn->chunk_remainder == 0) {
  3727. /* the rest of the data in the current chunk has been read
  3728. */
  3729. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3730. /* Protocol violation */
  3731. return -1;
  3732. }
  3733. }
  3734. } else {
  3735. /* fetch a new chunk */
  3736. int i = 0;
  3737. char lenbuf[64];
  3738. char *end = 0;
  3739. unsigned long chunkSize = 0;
  3740. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3741. lenbuf[i] = mg_getc(conn);
  3742. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3743. continue;
  3744. }
  3745. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3746. lenbuf[i + 1] = 0;
  3747. chunkSize = strtoul(lenbuf, &end, 16);
  3748. if (chunkSize == 0) {
  3749. /* regular end of content */
  3750. conn->is_chunked = 2;
  3751. }
  3752. break;
  3753. }
  3754. if (!isalnum(lenbuf[i])) {
  3755. /* illegal character for chunk length */
  3756. return -1;
  3757. }
  3758. }
  3759. if ((end == NULL) || (*end != '\r')) {
  3760. /* chunksize not set correctly */
  3761. return -1;
  3762. }
  3763. if (chunkSize == 0) {
  3764. break;
  3765. }
  3766. conn->chunk_remainder = chunkSize;
  3767. }
  3768. }
  3769. return (int)all_read;
  3770. }
  3771. return mg_read_inner(conn, buf, len);
  3772. }
  3773. int
  3774. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3775. {
  3776. time_t now;
  3777. int64_t n, total, allowed;
  3778. if (conn == NULL) {
  3779. return 0;
  3780. }
  3781. if (conn->throttle > 0) {
  3782. if ((now = time(NULL)) != conn->last_throttle_time) {
  3783. conn->last_throttle_time = now;
  3784. conn->last_throttle_bytes = 0;
  3785. }
  3786. allowed = conn->throttle - conn->last_throttle_bytes;
  3787. if (allowed > (int64_t)len) {
  3788. allowed = (int64_t)len;
  3789. }
  3790. if ((total = push_all(conn->ctx,
  3791. NULL,
  3792. conn->client.sock,
  3793. conn->ssl,
  3794. (const char *)buf,
  3795. (int64_t)allowed)) == allowed) {
  3796. buf = (const char *)buf + total;
  3797. conn->last_throttle_bytes += total;
  3798. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3799. allowed = (conn->throttle > ((int64_t)len - total))
  3800. ? (int64_t)len - total
  3801. : conn->throttle;
  3802. if ((n = push_all(conn->ctx,
  3803. NULL,
  3804. conn->client.sock,
  3805. conn->ssl,
  3806. (const char *)buf,
  3807. (int64_t)allowed)) != allowed) {
  3808. break;
  3809. }
  3810. sleep(1);
  3811. conn->last_throttle_bytes = allowed;
  3812. conn->last_throttle_time = time(NULL);
  3813. buf = (const char *)buf + n;
  3814. total += n;
  3815. }
  3816. }
  3817. } else {
  3818. total = push_all(conn->ctx,
  3819. NULL,
  3820. conn->client.sock,
  3821. conn->ssl,
  3822. (const char *)buf,
  3823. (int64_t)len);
  3824. }
  3825. return (int)total;
  3826. }
  3827. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3828. static int
  3829. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3830. {
  3831. va_list ap_copy;
  3832. size_t size = MG_BUF_LEN / 4;
  3833. int len = -1;
  3834. *buf = NULL;
  3835. while (len < 0) {
  3836. if (*buf) {
  3837. mg_free(*buf);
  3838. }
  3839. size *= 4;
  3840. *buf = (char *)mg_malloc(size);
  3841. if (!*buf) {
  3842. break;
  3843. }
  3844. va_copy(ap_copy, ap);
  3845. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3846. va_end(ap_copy);
  3847. (*buf)[size - 1] = 0;
  3848. }
  3849. return len;
  3850. }
  3851. /* Print message to buffer. If buffer is large enough to hold the message,
  3852. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3853. * and return allocated buffer. */
  3854. static int
  3855. alloc_vprintf(char **out_buf,
  3856. char *prealloc_buf,
  3857. size_t prealloc_size,
  3858. const char *fmt,
  3859. va_list ap)
  3860. {
  3861. va_list ap_copy;
  3862. int len;
  3863. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3864. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3865. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3866. * Therefore, we make two passes: on first pass, get required message
  3867. * length.
  3868. * On second pass, actually print the message. */
  3869. va_copy(ap_copy, ap);
  3870. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3871. va_end(ap_copy);
  3872. if (len < 0) {
  3873. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3874. * Switch to alternative code path that uses incremental allocations.
  3875. */
  3876. va_copy(ap_copy, ap);
  3877. len = alloc_vprintf2(out_buf, fmt, ap);
  3878. va_end(ap_copy);
  3879. } else if ((size_t)(len) >= prealloc_size) {
  3880. /* The pre-allocated buffer not large enough. */
  3881. /* Allocate a new buffer. */
  3882. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3883. if (!*out_buf) {
  3884. /* Allocation failed. Return -1 as "out of memory" error. */
  3885. return -1;
  3886. }
  3887. /* Buffer allocation successful. Store the string there. */
  3888. va_copy(ap_copy, ap);
  3889. IGNORE_UNUSED_RESULT(
  3890. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3891. va_end(ap_copy);
  3892. } else {
  3893. /* The pre-allocated buffer is large enough.
  3894. * Use it to store the string and return the address. */
  3895. va_copy(ap_copy, ap);
  3896. IGNORE_UNUSED_RESULT(
  3897. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3898. va_end(ap_copy);
  3899. *out_buf = prealloc_buf;
  3900. }
  3901. return len;
  3902. }
  3903. static int
  3904. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3905. {
  3906. char mem[MG_BUF_LEN];
  3907. char *buf = NULL;
  3908. int len;
  3909. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3910. len = mg_write(conn, buf, (size_t)len);
  3911. }
  3912. if (buf != mem && buf != NULL) {
  3913. mg_free(buf);
  3914. }
  3915. return len;
  3916. }
  3917. int
  3918. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3919. {
  3920. va_list ap;
  3921. int result;
  3922. va_start(ap, fmt);
  3923. result = mg_vprintf(conn, fmt, ap);
  3924. va_end(ap);
  3925. return result;
  3926. }
  3927. int
  3928. mg_url_decode(const char *src,
  3929. int src_len,
  3930. char *dst,
  3931. int dst_len,
  3932. int is_form_url_encoded)
  3933. {
  3934. int i, j, a, b;
  3935. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  3936. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  3937. if (i < src_len - 2 && src[i] == '%'
  3938. && isxdigit(*(const unsigned char *)(src + i + 1))
  3939. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3940. a = tolower(*(const unsigned char *)(src + i + 1));
  3941. b = tolower(*(const unsigned char *)(src + i + 2));
  3942. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3943. i += 2;
  3944. } else if (is_form_url_encoded && src[i] == '+') {
  3945. dst[j] = ' ';
  3946. } else {
  3947. dst[j] = src[i];
  3948. }
  3949. }
  3950. dst[j] = '\0'; /* Null-terminate the destination */
  3951. return (i >= src_len) ? j : -1;
  3952. }
  3953. int
  3954. mg_get_var(const char *data,
  3955. size_t data_len,
  3956. const char *name,
  3957. char *dst,
  3958. size_t dst_len)
  3959. {
  3960. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3961. }
  3962. int
  3963. mg_get_var2(const char *data,
  3964. size_t data_len,
  3965. const char *name,
  3966. char *dst,
  3967. size_t dst_len,
  3968. size_t occurrence)
  3969. {
  3970. const char *p, *e, *s;
  3971. size_t name_len;
  3972. int len;
  3973. if (dst == NULL || dst_len == 0) {
  3974. len = -2;
  3975. } else if (data == NULL || name == NULL || data_len == 0) {
  3976. len = -1;
  3977. dst[0] = '\0';
  3978. } else {
  3979. name_len = strlen(name);
  3980. e = data + data_len;
  3981. len = -1;
  3982. dst[0] = '\0';
  3983. /* data is "var1=val1&var2=val2...". Find variable first */
  3984. for (p = data; p + name_len < e; p++) {
  3985. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3986. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3987. /* Point p to variable value */
  3988. p += name_len + 1;
  3989. /* Point s to the end of the value */
  3990. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3991. if (s == NULL) {
  3992. s = e;
  3993. }
  3994. /* assert(s >= p); */
  3995. if (s < p) {
  3996. return -3;
  3997. }
  3998. /* Decode variable into destination buffer */
  3999. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4000. /* Redirect error code from -1 to -2 (destination buffer too
  4001. * small). */
  4002. if (len == -1) {
  4003. len = -2;
  4004. }
  4005. break;
  4006. }
  4007. }
  4008. }
  4009. return len;
  4010. }
  4011. int
  4012. mg_get_cookie(const char *cookie_header,
  4013. const char *var_name,
  4014. char *dst,
  4015. size_t dst_size)
  4016. {
  4017. const char *s, *p, *end;
  4018. int name_len, len = -1;
  4019. if (dst == NULL || dst_size == 0) {
  4020. len = -2;
  4021. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  4022. len = -1;
  4023. dst[0] = '\0';
  4024. } else {
  4025. name_len = (int)strlen(var_name);
  4026. end = s + strlen(s);
  4027. dst[0] = '\0';
  4028. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4029. if (s[name_len] == '=') {
  4030. s += name_len + 1;
  4031. if ((p = strchr(s, ' ')) == NULL) {
  4032. p = end;
  4033. }
  4034. if (p[-1] == ';') {
  4035. p--;
  4036. }
  4037. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4038. s++;
  4039. p--;
  4040. }
  4041. if ((size_t)(p - s) < dst_size) {
  4042. len = (int)(p - s);
  4043. mg_strlcpy(dst, s, (size_t)len + 1);
  4044. } else {
  4045. len = -3;
  4046. }
  4047. break;
  4048. }
  4049. }
  4050. }
  4051. return len;
  4052. }
  4053. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4054. static void
  4055. base64_encode(const unsigned char *src, int src_len, char *dst)
  4056. {
  4057. static const char *b64 =
  4058. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4059. int i, j, a, b, c;
  4060. for (i = j = 0; i < src_len; i += 3) {
  4061. a = src[i];
  4062. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4063. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4064. dst[j++] = b64[a >> 2];
  4065. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4066. if (i + 1 < src_len) {
  4067. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4068. }
  4069. if (i + 2 < src_len) {
  4070. dst[j++] = b64[c & 63];
  4071. }
  4072. }
  4073. while (j % 4 != 0) {
  4074. dst[j++] = '=';
  4075. }
  4076. dst[j++] = '\0';
  4077. }
  4078. #endif
  4079. #if defined(USE_LUA)
  4080. static unsigned char
  4081. b64reverse(char letter)
  4082. {
  4083. if (letter >= 'A' && letter <= 'Z') {
  4084. return letter - 'A';
  4085. }
  4086. if (letter >= 'a' && letter <= 'z') {
  4087. return letter - 'a' + 26;
  4088. }
  4089. if (letter >= '0' && letter <= '9') {
  4090. return letter - '0' + 52;
  4091. }
  4092. if (letter == '+') {
  4093. return 62;
  4094. }
  4095. if (letter == '/') {
  4096. return 63;
  4097. }
  4098. if (letter == '=') {
  4099. return 255; /* normal end */
  4100. }
  4101. return 254; /* error */
  4102. }
  4103. static int
  4104. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4105. {
  4106. int i;
  4107. unsigned char a, b, c, d;
  4108. *dst_len = 0;
  4109. for (i = 0; i < src_len; i += 4) {
  4110. a = b64reverse(src[i]);
  4111. if (a >= 254) {
  4112. return i;
  4113. }
  4114. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4115. if (b >= 254) {
  4116. return i + 1;
  4117. }
  4118. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4119. if (c == 254) {
  4120. return i + 2;
  4121. }
  4122. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4123. if (d == 254) {
  4124. return i + 3;
  4125. }
  4126. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4127. if (c != 255) {
  4128. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4129. if (d != 255) {
  4130. dst[(*dst_len)++] = (c << 6) + d;
  4131. }
  4132. }
  4133. }
  4134. return -1;
  4135. }
  4136. #endif
  4137. static int
  4138. is_put_or_delete_method(const struct mg_connection *conn)
  4139. {
  4140. if (conn) {
  4141. const char *s = conn->request_info.request_method;
  4142. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4143. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4144. }
  4145. return 0;
  4146. }
  4147. static void
  4148. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4149. char *filename, /* out: filename */
  4150. size_t filename_buf_len, /* in: size of filename buffer */
  4151. struct file *filep, /* out: file structure */
  4152. int *is_found, /* out: file is found (directly) */
  4153. int *is_script_resource, /* out: handled by a script? */
  4154. int *is_websocket_request, /* out: websocket connetion? */
  4155. int *is_put_or_delete_request /* out: put/delete a file? */
  4156. )
  4157. {
  4158. /* TODO (high): Restructure this function */
  4159. #if !defined(NO_FILES)
  4160. const char *uri = conn->request_info.local_uri;
  4161. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4162. const char *rewrite;
  4163. struct vec a, b;
  4164. int match_len;
  4165. char gz_path[PATH_MAX];
  4166. char const *accept_encoding;
  4167. int truncated;
  4168. #if !defined(NO_CGI) || defined(USE_LUA)
  4169. char *p;
  4170. #endif
  4171. #else
  4172. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4173. #endif
  4174. memset(filep, 0, sizeof(*filep));
  4175. *filename = 0;
  4176. *is_found = 0;
  4177. *is_script_resource = 0;
  4178. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4179. #if defined(USE_WEBSOCKET)
  4180. *is_websocket_request = is_websocket_protocol(conn);
  4181. #if !defined(NO_FILES)
  4182. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4183. root = conn->ctx->config[WEBSOCKET_ROOT];
  4184. }
  4185. #endif /* !NO_FILES */
  4186. #else /* USE_WEBSOCKET */
  4187. *is_websocket_request = 0;
  4188. #endif /* USE_WEBSOCKET */
  4189. #if !defined(NO_FILES)
  4190. /* Note that root == NULL is a regular use case here. This occurs,
  4191. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4192. * config is not required. */
  4193. if (root == NULL) {
  4194. /* all file related outputs have already been set to 0, just return
  4195. */
  4196. return;
  4197. }
  4198. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4199. * of the path one byte on the right.
  4200. * If document_root is NULL, leave the file empty. */
  4201. mg_snprintf(
  4202. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4203. if (truncated) {
  4204. goto interpret_cleanup;
  4205. }
  4206. rewrite = conn->ctx->config[REWRITE];
  4207. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4208. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4209. mg_snprintf(conn,
  4210. &truncated,
  4211. filename,
  4212. filename_buf_len - 1,
  4213. "%.*s%s",
  4214. (int)b.len,
  4215. b.ptr,
  4216. uri + match_len);
  4217. break;
  4218. }
  4219. }
  4220. if (truncated) {
  4221. goto interpret_cleanup;
  4222. }
  4223. /* Local file path and name, corresponding to requested URI
  4224. * is now stored in "filename" variable. */
  4225. if (mg_stat(conn, filename, filep)) {
  4226. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4227. /* File exists. Check if it is a script type. */
  4228. if (0
  4229. #if !defined(NO_CGI)
  4230. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4231. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4232. filename) > 0
  4233. #endif
  4234. #if defined(USE_LUA)
  4235. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4236. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4237. filename) > 0
  4238. #endif
  4239. #if defined(USE_DUKTAPE)
  4240. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4241. strlen(
  4242. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4243. filename) > 0
  4244. #endif
  4245. ) {
  4246. /* The request addresses a CGI script or a Lua script. The URI
  4247. * corresponds to the script itself (like /path/script.cgi),
  4248. * and there is no additional resource path
  4249. * (like /path/script.cgi/something).
  4250. * Requests that modify (replace or delete) a resource, like
  4251. * PUT and DELETE requests, should replace/delete the script
  4252. * file.
  4253. * Requests that read or write from/to a resource, like GET and
  4254. * POST requests, should call the script and return the
  4255. * generated response. */
  4256. *is_script_resource = !*is_put_or_delete_request;
  4257. }
  4258. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4259. *is_found = 1;
  4260. return;
  4261. }
  4262. /* If we can't find the actual file, look for the file
  4263. * with the same name but a .gz extension. If we find it,
  4264. * use that and set the gzipped flag in the file struct
  4265. * to indicate that the response need to have the content-
  4266. * encoding: gzip header.
  4267. * We can only do this if the browser declares support. */
  4268. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4269. if (strstr(accept_encoding, "gzip") != NULL) {
  4270. mg_snprintf(
  4271. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4272. if (truncated) {
  4273. goto interpret_cleanup;
  4274. }
  4275. if (mg_stat(conn, gz_path, filep)) {
  4276. if (filep) {
  4277. filep->gzipped = 1;
  4278. *is_found = 1;
  4279. }
  4280. /* Currently gz files can not be scripts. */
  4281. return;
  4282. }
  4283. }
  4284. }
  4285. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4286. /* Support PATH_INFO for CGI scripts. */
  4287. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4288. if (*p == '/') {
  4289. *p = '\0';
  4290. if ((0
  4291. #if !defined(NO_CGI)
  4292. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4293. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4294. filename) > 0
  4295. #endif
  4296. #if defined(USE_LUA)
  4297. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4298. strlen(
  4299. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4300. filename) > 0
  4301. #endif
  4302. #if defined(USE_DUKTAPE)
  4303. || match_prefix(
  4304. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4305. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4306. filename) > 0
  4307. #endif
  4308. ) && mg_stat(conn, filename, filep)) {
  4309. /* Shift PATH_INFO block one character right, e.g.
  4310. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4311. * conn->path_info is pointing to the local variable "path"
  4312. * declared in handle_request(), so PATH_INFO is not valid
  4313. * after handle_request returns. */
  4314. conn->path_info = p + 1;
  4315. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4316. * trailing \0 */
  4317. p[1] = '/';
  4318. *is_script_resource = 1;
  4319. break;
  4320. } else {
  4321. *p = '/';
  4322. }
  4323. }
  4324. }
  4325. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4326. #endif /* !defined(NO_FILES) */
  4327. return;
  4328. #if !defined(NO_FILES)
  4329. /* Reset all outputs */
  4330. interpret_cleanup:
  4331. memset(filep, 0, sizeof(*filep));
  4332. *filename = 0;
  4333. *is_found = 0;
  4334. *is_script_resource = 0;
  4335. *is_websocket_request = 0;
  4336. *is_put_or_delete_request = 0;
  4337. #endif /* !defined(NO_FILES) */
  4338. }
  4339. /* Check whether full request is buffered. Return:
  4340. * -1 if request is malformed
  4341. * 0 if request is not yet fully buffered
  4342. * >0 actual request length, including last \r\n\r\n */
  4343. static int
  4344. get_request_len(const char *buf, int buflen)
  4345. {
  4346. const char *s, *e;
  4347. int len = 0;
  4348. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4349. /* Control characters are not allowed but >=128 is. */
  4350. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4351. && *(const unsigned char *)s < 128) {
  4352. len = -1;
  4353. break; /* [i_a] abort scan as soon as one malformed character is
  4354. * found; */
  4355. /* don't let subsequent \r\n\r\n win us over anyhow */
  4356. } else if (s[0] == '\n' && s[1] == '\n') {
  4357. len = (int)(s - buf) + 2;
  4358. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4359. len = (int)(s - buf) + 3;
  4360. }
  4361. return len;
  4362. }
  4363. #if !defined(NO_CACHING)
  4364. /* Convert month to the month number. Return -1 on error, or month number */
  4365. static int
  4366. get_month_index(const char *s)
  4367. {
  4368. size_t i;
  4369. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4370. if (!strcmp(s, month_names[i])) {
  4371. return (int)i;
  4372. }
  4373. }
  4374. return -1;
  4375. }
  4376. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4377. static time_t
  4378. parse_date_string(const char *datetime)
  4379. {
  4380. char month_str[32] = {0};
  4381. int second, minute, hour, day, month, year;
  4382. time_t result = (time_t)0;
  4383. struct tm tm;
  4384. if ((sscanf(datetime,
  4385. "%d/%3s/%d %d:%d:%d",
  4386. &day,
  4387. month_str,
  4388. &year,
  4389. &hour,
  4390. &minute,
  4391. &second) == 6) || (sscanf(datetime,
  4392. "%d %3s %d %d:%d:%d",
  4393. &day,
  4394. month_str,
  4395. &year,
  4396. &hour,
  4397. &minute,
  4398. &second) == 6)
  4399. || (sscanf(datetime,
  4400. "%*3s, %d %3s %d %d:%d:%d",
  4401. &day,
  4402. month_str,
  4403. &year,
  4404. &hour,
  4405. &minute,
  4406. &second) == 6) || (sscanf(datetime,
  4407. "%d-%3s-%d %d:%d:%d",
  4408. &day,
  4409. month_str,
  4410. &year,
  4411. &hour,
  4412. &minute,
  4413. &second) == 6)) {
  4414. month = get_month_index(month_str);
  4415. if ((month >= 0) && (year >= 1970)) {
  4416. memset(&tm, 0, sizeof(tm));
  4417. tm.tm_year = year - 1900;
  4418. tm.tm_mon = month;
  4419. tm.tm_mday = day;
  4420. tm.tm_hour = hour;
  4421. tm.tm_min = minute;
  4422. tm.tm_sec = second;
  4423. result = timegm(&tm);
  4424. }
  4425. }
  4426. return result;
  4427. }
  4428. #endif /* !NO_CACHING */
  4429. /* Protect against directory disclosure attack by removing '..',
  4430. * excessive '/' and '\' characters */
  4431. static void
  4432. remove_double_dots_and_double_slashes(char *s)
  4433. {
  4434. char *p = s;
  4435. while (*s != '\0') {
  4436. *p++ = *s++;
  4437. if (s[-1] == '/' || s[-1] == '\\') {
  4438. /* Skip all following slashes, backslashes and double-dots */
  4439. while (s[0] != '\0') {
  4440. if (s[0] == '/' || s[0] == '\\') {
  4441. s++;
  4442. } else if (s[0] == '.' && s[1] == '.') {
  4443. s += 2;
  4444. } else {
  4445. break;
  4446. }
  4447. }
  4448. }
  4449. }
  4450. *p = '\0';
  4451. }
  4452. static const struct {
  4453. const char *extension;
  4454. size_t ext_len;
  4455. const char *mime_type;
  4456. } builtin_mime_types[] = {
  4457. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4458. * application types */
  4459. {".doc", 4, "application/msword"},
  4460. {".eps", 4, "application/postscript"},
  4461. {".exe", 4, "application/octet-stream"},
  4462. {".js", 3, "application/javascript"},
  4463. {".json", 5, "application/json"},
  4464. {".pdf", 4, "application/pdf"},
  4465. {".ps", 3, "application/postscript"},
  4466. {".rtf", 4, "application/rtf"},
  4467. {".xhtml", 6, "application/xhtml+xml"},
  4468. {".xsl", 4, "application/xml"},
  4469. {".xslt", 5, "application/xml"},
  4470. /* fonts */
  4471. {".ttf", 4, "application/font-sfnt"},
  4472. {".cff", 4, "application/font-sfnt"},
  4473. {".otf", 4, "application/font-sfnt"},
  4474. {".aat", 4, "application/font-sfnt"},
  4475. {".sil", 4, "application/font-sfnt"},
  4476. {".pfr", 4, "application/font-tdpfr"},
  4477. {".woff", 5, "application/font-woff"},
  4478. /* audio */
  4479. {".mp3", 4, "audio/mpeg"},
  4480. {".oga", 4, "audio/ogg"},
  4481. {".ogg", 4, "audio/ogg"},
  4482. /* image */
  4483. {".gif", 4, "image/gif"},
  4484. {".ief", 4, "image/ief"},
  4485. {".jpeg", 5, "image/jpeg"},
  4486. {".jpg", 4, "image/jpeg"},
  4487. {".jpm", 4, "image/jpm"},
  4488. {".jpx", 4, "image/jpx"},
  4489. {".png", 4, "image/png"},
  4490. {".svg", 4, "image/svg+xml"},
  4491. {".tif", 4, "image/tiff"},
  4492. {".tiff", 5, "image/tiff"},
  4493. /* model */
  4494. {".wrl", 4, "model/vrml"},
  4495. /* text */
  4496. {".css", 4, "text/css"},
  4497. {".csv", 4, "text/csv"},
  4498. {".htm", 4, "text/html"},
  4499. {".html", 5, "text/html"},
  4500. {".sgm", 4, "text/sgml"},
  4501. {".shtm", 5, "text/html"},
  4502. {".shtml", 6, "text/html"},
  4503. {".txt", 4, "text/plain"},
  4504. {".xml", 4, "text/xml"},
  4505. /* video */
  4506. {".mov", 4, "video/quicktime"},
  4507. {".mp4", 4, "video/mp4"},
  4508. {".mpeg", 5, "video/mpeg"},
  4509. {".mpg", 4, "video/mpeg"},
  4510. {".ogv", 4, "video/ogg"},
  4511. {".qt", 3, "video/quicktime"},
  4512. /* not registered types
  4513. * (http://reference.sitepoint.com/html/mime-types-full,
  4514. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4515. {".arj", 4, "application/x-arj-compressed"},
  4516. {".gz", 3, "application/x-gunzip"},
  4517. {".rar", 4, "application/x-arj-compressed"},
  4518. {".swf", 4, "application/x-shockwave-flash"},
  4519. {".tar", 4, "application/x-tar"},
  4520. {".tgz", 4, "application/x-tar-gz"},
  4521. {".torrent", 8, "application/x-bittorrent"},
  4522. {".ppt", 4, "application/x-mspowerpoint"},
  4523. {".xls", 4, "application/x-msexcel"},
  4524. {".zip", 4, "application/x-zip-compressed"},
  4525. {".aac",
  4526. 4,
  4527. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4528. {".aif", 4, "audio/x-aif"},
  4529. {".m3u", 4, "audio/x-mpegurl"},
  4530. {".mid", 4, "audio/x-midi"},
  4531. {".ra", 3, "audio/x-pn-realaudio"},
  4532. {".ram", 4, "audio/x-pn-realaudio"},
  4533. {".wav", 4, "audio/x-wav"},
  4534. {".bmp", 4, "image/bmp"},
  4535. {".ico", 4, "image/x-icon"},
  4536. {".pct", 4, "image/x-pct"},
  4537. {".pict", 5, "image/pict"},
  4538. {".rgb", 4, "image/x-rgb"},
  4539. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4540. {".asf", 4, "video/x-ms-asf"},
  4541. {".avi", 4, "video/x-msvideo"},
  4542. {".m4v", 4, "video/x-m4v"},
  4543. {NULL, 0, NULL}};
  4544. const char *
  4545. mg_get_builtin_mime_type(const char *path)
  4546. {
  4547. const char *ext;
  4548. size_t i, path_len;
  4549. path_len = strlen(path);
  4550. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4551. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4552. if (path_len > builtin_mime_types[i].ext_len
  4553. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4554. return builtin_mime_types[i].mime_type;
  4555. }
  4556. }
  4557. return "text/plain";
  4558. }
  4559. /* Look at the "path" extension and figure what mime type it has.
  4560. * Store mime type in the vector. */
  4561. static void
  4562. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4563. {
  4564. struct vec ext_vec, mime_vec;
  4565. const char *list, *ext;
  4566. size_t path_len;
  4567. path_len = strlen(path);
  4568. if (ctx == NULL || vec == NULL) {
  4569. return;
  4570. }
  4571. /* Scan user-defined mime types first, in case user wants to
  4572. * override default mime types. */
  4573. list = ctx->config[EXTRA_MIME_TYPES];
  4574. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4575. /* ext now points to the path suffix */
  4576. ext = path + path_len - ext_vec.len;
  4577. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4578. *vec = mime_vec;
  4579. return;
  4580. }
  4581. }
  4582. vec->ptr = mg_get_builtin_mime_type(path);
  4583. vec->len = strlen(vec->ptr);
  4584. }
  4585. /* Stringify binary data. Output buffer must be twice as big as input,
  4586. * because each byte takes 2 bytes in string representation */
  4587. static void
  4588. bin2str(char *to, const unsigned char *p, size_t len)
  4589. {
  4590. static const char *hex = "0123456789abcdef";
  4591. for (; len--; p++) {
  4592. *to++ = hex[p[0] >> 4];
  4593. *to++ = hex[p[0] & 0x0f];
  4594. }
  4595. *to = '\0';
  4596. }
  4597. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4598. char *
  4599. mg_md5(char buf[33], ...)
  4600. {
  4601. md5_byte_t hash[16];
  4602. const char *p;
  4603. va_list ap;
  4604. md5_state_t ctx;
  4605. md5_init(&ctx);
  4606. va_start(ap, buf);
  4607. while ((p = va_arg(ap, const char *)) != NULL) {
  4608. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4609. }
  4610. va_end(ap);
  4611. md5_finish(&ctx, hash);
  4612. bin2str(buf, hash, sizeof(hash));
  4613. return buf;
  4614. }
  4615. /* Check the user's password, return 1 if OK */
  4616. static int
  4617. check_password(const char *method,
  4618. const char *ha1,
  4619. const char *uri,
  4620. const char *nonce,
  4621. const char *nc,
  4622. const char *cnonce,
  4623. const char *qop,
  4624. const char *response)
  4625. {
  4626. char ha2[32 + 1], expected_response[32 + 1];
  4627. /* Some of the parameters may be NULL */
  4628. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4629. || qop == NULL
  4630. || response == NULL) {
  4631. return 0;
  4632. }
  4633. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4634. if (strlen(response) != 32) {
  4635. return 0;
  4636. }
  4637. mg_md5(ha2, method, ":", uri, NULL);
  4638. mg_md5(expected_response,
  4639. ha1,
  4640. ":",
  4641. nonce,
  4642. ":",
  4643. nc,
  4644. ":",
  4645. cnonce,
  4646. ":",
  4647. qop,
  4648. ":",
  4649. ha2,
  4650. NULL);
  4651. return mg_strcasecmp(response, expected_response) == 0;
  4652. }
  4653. /* Use the global passwords file, if specified by auth_gpass option,
  4654. * or search for .htpasswd in the requested directory. */
  4655. static void
  4656. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4657. {
  4658. if (conn != NULL && conn->ctx != NULL) {
  4659. char name[PATH_MAX];
  4660. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4661. struct file file = STRUCT_FILE_INITIALIZER;
  4662. int truncated;
  4663. if (gpass != NULL) {
  4664. /* Use global passwords file */
  4665. if (!mg_fopen(conn, gpass, "r", filep)) {
  4666. #ifdef DEBUG
  4667. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4668. #endif
  4669. }
  4670. /* Important: using local struct file to test path for is_directory
  4671. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4672. * was opened. */
  4673. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4674. mg_snprintf(conn,
  4675. &truncated,
  4676. name,
  4677. sizeof(name),
  4678. "%s/%s",
  4679. path,
  4680. PASSWORDS_FILE_NAME);
  4681. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4682. #ifdef DEBUG
  4683. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4684. #endif
  4685. }
  4686. } else {
  4687. /* Try to find .htpasswd in requested directory. */
  4688. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4689. if (e[0] == '/') {
  4690. break;
  4691. }
  4692. }
  4693. mg_snprintf(conn,
  4694. &truncated,
  4695. name,
  4696. sizeof(name),
  4697. "%.*s/%s",
  4698. (int)(e - p),
  4699. p,
  4700. PASSWORDS_FILE_NAME);
  4701. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4702. #ifdef DEBUG
  4703. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4704. #endif
  4705. }
  4706. }
  4707. }
  4708. }
  4709. /* Parsed Authorization header */
  4710. struct ah {
  4711. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4712. };
  4713. /* Return 1 on success. Always initializes the ah structure. */
  4714. static int
  4715. parse_auth_header(struct mg_connection *conn,
  4716. char *buf,
  4717. size_t buf_size,
  4718. struct ah *ah)
  4719. {
  4720. char *name, *value, *s;
  4721. const char *auth_header;
  4722. uint64_t nonce;
  4723. if (!ah || !conn) {
  4724. return 0;
  4725. }
  4726. (void)memset(ah, 0, sizeof(*ah));
  4727. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4728. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4729. return 0;
  4730. }
  4731. /* Make modifiable copy of the auth header */
  4732. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4733. s = buf;
  4734. /* Parse authorization header */
  4735. for (;;) {
  4736. /* Gobble initial spaces */
  4737. while (isspace(*(unsigned char *)s)) {
  4738. s++;
  4739. }
  4740. name = skip_quoted(&s, "=", " ", 0);
  4741. /* Value is either quote-delimited, or ends at first comma or space. */
  4742. if (s[0] == '\"') {
  4743. s++;
  4744. value = skip_quoted(&s, "\"", " ", '\\');
  4745. if (s[0] == ',') {
  4746. s++;
  4747. }
  4748. } else {
  4749. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4750. * spaces */
  4751. }
  4752. if (*name == '\0') {
  4753. break;
  4754. }
  4755. if (!strcmp(name, "username")) {
  4756. ah->user = value;
  4757. } else if (!strcmp(name, "cnonce")) {
  4758. ah->cnonce = value;
  4759. } else if (!strcmp(name, "response")) {
  4760. ah->response = value;
  4761. } else if (!strcmp(name, "uri")) {
  4762. ah->uri = value;
  4763. } else if (!strcmp(name, "qop")) {
  4764. ah->qop = value;
  4765. } else if (!strcmp(name, "nc")) {
  4766. ah->nc = value;
  4767. } else if (!strcmp(name, "nonce")) {
  4768. ah->nonce = value;
  4769. }
  4770. }
  4771. #ifndef NO_NONCE_CHECK
  4772. /* Read the nonce from the response. */
  4773. if (ah->nonce == NULL) {
  4774. return 0;
  4775. }
  4776. s = NULL;
  4777. nonce = strtoull(ah->nonce, &s, 10);
  4778. if ((s == NULL) || (*s != 0)) {
  4779. return 0;
  4780. }
  4781. /* Convert the nonce from the client to a number. */
  4782. nonce ^= conn->ctx->auth_nonce_mask;
  4783. /* The converted number corresponds to the time the nounce has been
  4784. * created. This should not be earlier than the server start. */
  4785. /* Server side nonce check is valuable in all situations but one:
  4786. * if the server restarts frequently, but the client should not see
  4787. * that, so the server should accept nonces from previous starts. */
  4788. /* However, the reasonable default is to not accept a nonce from a
  4789. * previous start, so if anyone changed the access rights between
  4790. * two restarts, a new login is required. */
  4791. if (nonce < (uint64_t)conn->ctx->start_time) {
  4792. /* nonce is from a previous start of the server and no longer valid
  4793. * (replay attack?) */
  4794. return 0;
  4795. }
  4796. /* Check if the nonce is too high, so it has not (yet) been used by the
  4797. * server. */
  4798. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4799. return 0;
  4800. }
  4801. #else
  4802. (void)nonce;
  4803. #endif
  4804. /* CGI needs it as REMOTE_USER */
  4805. if (ah->user != NULL) {
  4806. conn->request_info.remote_user = mg_strdup(ah->user);
  4807. } else {
  4808. return 0;
  4809. }
  4810. return 1;
  4811. }
  4812. static const char *
  4813. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4814. {
  4815. const char *eof;
  4816. size_t len;
  4817. const char *memend;
  4818. if (!filep) {
  4819. return NULL;
  4820. }
  4821. if (filep->membuf != NULL && *p != NULL) {
  4822. memend = (const char *)&filep->membuf[filep->size];
  4823. /* Search for \n from p till the end of stream */
  4824. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4825. if (eof != NULL) {
  4826. eof += 1; /* Include \n */
  4827. } else {
  4828. eof = memend; /* Copy remaining data */
  4829. }
  4830. len =
  4831. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  4832. memcpy(buf, *p, len);
  4833. buf[len] = '\0';
  4834. *p += len;
  4835. return len ? eof : NULL;
  4836. } else if (filep->fp != NULL) {
  4837. return fgets(buf, (int)size, filep->fp);
  4838. } else {
  4839. return NULL;
  4840. }
  4841. }
  4842. struct read_auth_file_struct {
  4843. struct mg_connection *conn;
  4844. struct ah ah;
  4845. char *domain;
  4846. char buf[256 + 256 + 40];
  4847. char *f_user;
  4848. char *f_domain;
  4849. char *f_ha1;
  4850. };
  4851. static int
  4852. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4853. {
  4854. char *p;
  4855. int is_authorized = 0;
  4856. struct file fp;
  4857. size_t l;
  4858. if (!filep || !workdata) {
  4859. return 0;
  4860. }
  4861. /* Loop over passwords file */
  4862. p = (char *)filep->membuf;
  4863. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4864. l = strlen(workdata->buf);
  4865. while (l > 0) {
  4866. if (isspace(workdata->buf[l - 1])
  4867. || iscntrl(workdata->buf[l - 1])) {
  4868. l--;
  4869. workdata->buf[l] = 0;
  4870. } else
  4871. break;
  4872. }
  4873. if (l < 1) {
  4874. continue;
  4875. }
  4876. workdata->f_user = workdata->buf;
  4877. if (workdata->f_user[0] == ':') {
  4878. /* user names may not contain a ':' and may not be empty,
  4879. * so lines starting with ':' may be used for a special purpose */
  4880. if (workdata->f_user[1] == '#') {
  4881. /* :# is a comment */
  4882. continue;
  4883. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4884. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4885. is_authorized = read_auth_file(&fp, workdata);
  4886. mg_fclose(&fp);
  4887. } else {
  4888. mg_cry(workdata->conn,
  4889. "%s: cannot open authorization file: %s",
  4890. __func__,
  4891. workdata->buf);
  4892. }
  4893. continue;
  4894. }
  4895. /* everything is invalid for the moment (might change in the
  4896. * future) */
  4897. mg_cry(workdata->conn,
  4898. "%s: syntax error in authorization file: %s",
  4899. __func__,
  4900. workdata->buf);
  4901. continue;
  4902. }
  4903. workdata->f_domain = strchr(workdata->f_user, ':');
  4904. if (workdata->f_domain == NULL) {
  4905. mg_cry(workdata->conn,
  4906. "%s: syntax error in authorization file: %s",
  4907. __func__,
  4908. workdata->buf);
  4909. continue;
  4910. }
  4911. *(workdata->f_domain) = 0;
  4912. (workdata->f_domain)++;
  4913. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4914. if (workdata->f_ha1 == NULL) {
  4915. mg_cry(workdata->conn,
  4916. "%s: syntax error in authorization file: %s",
  4917. __func__,
  4918. workdata->buf);
  4919. continue;
  4920. }
  4921. *(workdata->f_ha1) = 0;
  4922. (workdata->f_ha1)++;
  4923. if (!strcmp(workdata->ah.user, workdata->f_user)
  4924. && !strcmp(workdata->domain, workdata->f_domain)) {
  4925. return check_password(workdata->conn->request_info.request_method,
  4926. workdata->f_ha1,
  4927. workdata->ah.uri,
  4928. workdata->ah.nonce,
  4929. workdata->ah.nc,
  4930. workdata->ah.cnonce,
  4931. workdata->ah.qop,
  4932. workdata->ah.response);
  4933. }
  4934. }
  4935. return is_authorized;
  4936. }
  4937. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4938. static int
  4939. authorize(struct mg_connection *conn, struct file *filep)
  4940. {
  4941. struct read_auth_file_struct workdata;
  4942. char buf[MG_BUF_LEN];
  4943. if (!conn || !conn->ctx) {
  4944. return 0;
  4945. }
  4946. memset(&workdata, 0, sizeof(workdata));
  4947. workdata.conn = conn;
  4948. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4949. return 0;
  4950. }
  4951. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4952. return read_auth_file(filep, &workdata);
  4953. }
  4954. /* Return 1 if request is authorised, 0 otherwise. */
  4955. static int
  4956. check_authorization(struct mg_connection *conn, const char *path)
  4957. {
  4958. char fname[PATH_MAX];
  4959. struct vec uri_vec, filename_vec;
  4960. const char *list;
  4961. struct file file = STRUCT_FILE_INITIALIZER;
  4962. int authorized = 1, truncated;
  4963. if (!conn || !conn->ctx) {
  4964. return 0;
  4965. }
  4966. list = conn->ctx->config[PROTECT_URI];
  4967. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4968. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4969. mg_snprintf(conn,
  4970. &truncated,
  4971. fname,
  4972. sizeof(fname),
  4973. "%.*s",
  4974. (int)filename_vec.len,
  4975. filename_vec.ptr);
  4976. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4977. mg_cry(conn,
  4978. "%s: cannot open %s: %s",
  4979. __func__,
  4980. fname,
  4981. strerror(errno));
  4982. }
  4983. break;
  4984. }
  4985. }
  4986. if (!is_file_opened(&file)) {
  4987. open_auth_file(conn, path, &file);
  4988. }
  4989. if (is_file_opened(&file)) {
  4990. authorized = authorize(conn, &file);
  4991. mg_fclose(&file);
  4992. }
  4993. return authorized;
  4994. }
  4995. static void
  4996. send_authorization_request(struct mg_connection *conn)
  4997. {
  4998. char date[64];
  4999. time_t curtime = time(NULL);
  5000. if (conn && conn->ctx) {
  5001. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5002. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5003. nonce += conn->ctx->nonce_count;
  5004. ++conn->ctx->nonce_count;
  5005. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5006. nonce ^= conn->ctx->auth_nonce_mask;
  5007. conn->status_code = 401;
  5008. conn->must_close = 1;
  5009. gmt_time_string(date, sizeof(date), &curtime);
  5010. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5011. send_no_cache_header(conn);
  5012. mg_printf(conn,
  5013. "Date: %s\r\n"
  5014. "Connection: %s\r\n"
  5015. "Content-Length: 0\r\n"
  5016. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5017. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5018. date,
  5019. suggest_connection_header(conn),
  5020. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5021. nonce);
  5022. }
  5023. }
  5024. #if !defined(NO_FILES)
  5025. static int
  5026. is_authorized_for_put(struct mg_connection *conn)
  5027. {
  5028. if (conn) {
  5029. struct file file = STRUCT_FILE_INITIALIZER;
  5030. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5031. int ret = 0;
  5032. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5033. ret = authorize(conn, &file);
  5034. mg_fclose(&file);
  5035. }
  5036. return ret;
  5037. }
  5038. return 0;
  5039. }
  5040. #endif
  5041. int
  5042. mg_modify_passwords_file(const char *fname,
  5043. const char *domain,
  5044. const char *user,
  5045. const char *pass)
  5046. {
  5047. int found, i;
  5048. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5049. FILE *fp, *fp2;
  5050. found = 0;
  5051. fp = fp2 = NULL;
  5052. /* Regard empty password as no password - remove user record. */
  5053. if (pass != NULL && pass[0] == '\0') {
  5054. pass = NULL;
  5055. }
  5056. /* Other arguments must not be empty */
  5057. if (fname == NULL || domain == NULL || user == NULL) {
  5058. return 0;
  5059. }
  5060. /* Using the given file format, user name and domain must not contain ':'
  5061. */
  5062. if (strchr(user, ':') != NULL) {
  5063. return 0;
  5064. }
  5065. if (strchr(domain, ':') != NULL) {
  5066. return 0;
  5067. }
  5068. /* Do not allow control characters like newline in user name and domain.
  5069. * Do not allow excessively long names either. */
  5070. for (i = 0; i < 255 && user[i] != 0; i++) {
  5071. if (iscntrl(user[i])) {
  5072. return 0;
  5073. }
  5074. }
  5075. if (user[i]) {
  5076. return 0;
  5077. }
  5078. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5079. if (iscntrl(domain[i])) {
  5080. return 0;
  5081. }
  5082. }
  5083. if (domain[i]) {
  5084. return 0;
  5085. }
  5086. /* The maximum length of the path to the password file is limited */
  5087. if ((strlen(fname) + 4) >= PATH_MAX) {
  5088. return 0;
  5089. }
  5090. /* Create a temporary file name. Length has been checked before. */
  5091. strcpy(tmp, fname);
  5092. strcat(tmp, ".tmp");
  5093. /* Create the file if does not exist */
  5094. /* Use of fopen here is OK, since fname is only ASCII */
  5095. if ((fp = fopen(fname, "a+")) != NULL) {
  5096. (void)fclose(fp);
  5097. }
  5098. /* Open the given file and temporary file */
  5099. if ((fp = fopen(fname, "r")) == NULL) {
  5100. return 0;
  5101. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5102. fclose(fp);
  5103. return 0;
  5104. }
  5105. /* Copy the stuff to temporary file */
  5106. while (fgets(line, sizeof(line), fp) != NULL) {
  5107. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5108. continue;
  5109. }
  5110. u[255] = 0;
  5111. d[255] = 0;
  5112. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5113. found++;
  5114. if (pass != NULL) {
  5115. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5116. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5117. }
  5118. } else {
  5119. fprintf(fp2, "%s", line);
  5120. }
  5121. }
  5122. /* If new user, just add it */
  5123. if (!found && pass != NULL) {
  5124. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5125. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5126. }
  5127. /* Close files */
  5128. fclose(fp);
  5129. fclose(fp2);
  5130. /* Put the temp file in place of real file */
  5131. IGNORE_UNUSED_RESULT(remove(fname));
  5132. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5133. return 1;
  5134. }
  5135. static int
  5136. is_valid_port(unsigned long port)
  5137. {
  5138. return port < 0xffff;
  5139. }
  5140. static int
  5141. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5142. {
  5143. struct addrinfo hints, *res, *ressave;
  5144. int func_ret = 0;
  5145. int gai_ret;
  5146. memset(&hints, 0, sizeof(struct addrinfo));
  5147. hints.ai_family = af;
  5148. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5149. if (gai_ret != 0) {
  5150. /* gai_strerror could be used to convert gai_ret to a string */
  5151. /* POSIX return values: see
  5152. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5153. */
  5154. /* Windows return values: see
  5155. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5156. */
  5157. return 0;
  5158. }
  5159. ressave = res;
  5160. while (res) {
  5161. if (dstlen >= res->ai_addrlen) {
  5162. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5163. func_ret = 1;
  5164. }
  5165. res = res->ai_next;
  5166. }
  5167. freeaddrinfo(ressave);
  5168. return func_ret;
  5169. }
  5170. static int
  5171. connect_socket(struct mg_context *ctx /* may be NULL */,
  5172. const char *host,
  5173. int port,
  5174. int use_ssl,
  5175. char *ebuf,
  5176. size_t ebuf_len,
  5177. SOCKET *sock /* output: socket, must not be NULL */,
  5178. union usa *sa /* output: socket address, must not be NULL */
  5179. )
  5180. {
  5181. int ip_ver = 0;
  5182. *sock = INVALID_SOCKET;
  5183. memset(sa, 0, sizeof(*sa));
  5184. if (ebuf_len > 0) {
  5185. *ebuf = 0;
  5186. }
  5187. if (host == NULL) {
  5188. mg_snprintf(NULL,
  5189. NULL, /* No truncation check for ebuf */
  5190. ebuf,
  5191. ebuf_len,
  5192. "%s",
  5193. "NULL host");
  5194. return 0;
  5195. }
  5196. if (port < 0 || !is_valid_port((unsigned)port)) {
  5197. mg_snprintf(NULL,
  5198. NULL, /* No truncation check for ebuf */
  5199. ebuf,
  5200. ebuf_len,
  5201. "%s",
  5202. "invalid port");
  5203. return 0;
  5204. }
  5205. #if !defined(NO_SSL)
  5206. if (use_ssl && (SSLv23_client_method == NULL)) {
  5207. mg_snprintf(NULL,
  5208. NULL, /* No truncation check for ebuf */
  5209. ebuf,
  5210. ebuf_len,
  5211. "%s",
  5212. "SSL is not initialized");
  5213. return 0;
  5214. }
  5215. #else
  5216. (void)use_ssl;
  5217. #endif
  5218. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5219. sa->sin.sin_port = htons((uint16_t)port);
  5220. ip_ver = 4;
  5221. #ifdef USE_IPV6
  5222. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5223. sa->sin6.sin6_port = htons((uint16_t)port);
  5224. ip_ver = 6;
  5225. } else if (host[0] == '[') {
  5226. /* While getaddrinfo on Windows will work with [::1],
  5227. * getaddrinfo on Linux only works with ::1 (without []). */
  5228. size_t l = strlen(host + 1);
  5229. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5230. if (h) {
  5231. h[l - 1] = 0;
  5232. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5233. sa->sin6.sin6_port = htons((uint16_t)port);
  5234. ip_ver = 6;
  5235. }
  5236. mg_free(h);
  5237. }
  5238. #endif
  5239. }
  5240. if (ip_ver == 0) {
  5241. mg_snprintf(NULL,
  5242. NULL, /* No truncation check for ebuf */
  5243. ebuf,
  5244. ebuf_len,
  5245. "%s",
  5246. "host not found");
  5247. return 0;
  5248. }
  5249. if (ip_ver == 4) {
  5250. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5251. }
  5252. #ifdef USE_IPV6
  5253. else if (ip_ver == 6) {
  5254. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5255. }
  5256. #endif
  5257. if (*sock == INVALID_SOCKET) {
  5258. mg_snprintf(NULL,
  5259. NULL, /* No truncation check for ebuf */
  5260. ebuf,
  5261. ebuf_len,
  5262. "socket(): %s",
  5263. strerror(ERRNO));
  5264. return 0;
  5265. }
  5266. set_close_on_exec(*sock, fc(ctx));
  5267. if ((ip_ver == 4)
  5268. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5269. == 0)) {
  5270. /* connected with IPv4 */
  5271. return 1;
  5272. }
  5273. #ifdef USE_IPV6
  5274. if ((ip_ver == 6)
  5275. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5276. == 0)) {
  5277. /* connected with IPv6 */
  5278. return 1;
  5279. }
  5280. #endif
  5281. /* Not connected */
  5282. mg_snprintf(NULL,
  5283. NULL, /* No truncation check for ebuf */
  5284. ebuf,
  5285. ebuf_len,
  5286. "connect(%s:%d): %s",
  5287. host,
  5288. port,
  5289. strerror(ERRNO));
  5290. closesocket(*sock);
  5291. *sock = INVALID_SOCKET;
  5292. return 0;
  5293. }
  5294. int
  5295. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5296. {
  5297. static const char *dont_escape = "._-$,;~()";
  5298. static const char *hex = "0123456789abcdef";
  5299. char *pos = dst;
  5300. const char *end = dst + dst_len - 1;
  5301. for (; *src != '\0' && pos < end; src++, pos++) {
  5302. if (isalnum(*(const unsigned char *)src)
  5303. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5304. *pos = *src;
  5305. } else if (pos + 2 < end) {
  5306. pos[0] = '%';
  5307. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5308. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5309. pos += 2;
  5310. } else {
  5311. break;
  5312. }
  5313. }
  5314. *pos = '\0';
  5315. return (*src == '\0') ? (int)(pos - dst) : -1;
  5316. }
  5317. static void
  5318. print_dir_entry(struct de *de)
  5319. {
  5320. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5321. struct tm *tm;
  5322. if (de->file.is_directory) {
  5323. mg_snprintf(de->conn,
  5324. NULL, /* Buffer is big enough */
  5325. size,
  5326. sizeof(size),
  5327. "%s",
  5328. "[DIRECTORY]");
  5329. } else {
  5330. /* We use (signed) cast below because MSVC 6 compiler cannot
  5331. * convert unsigned __int64 to double. Sigh. */
  5332. if (de->file.size < 1024) {
  5333. mg_snprintf(de->conn,
  5334. NULL, /* Buffer is big enough */
  5335. size,
  5336. sizeof(size),
  5337. "%d",
  5338. (int)de->file.size);
  5339. } else if (de->file.size < 0x100000) {
  5340. mg_snprintf(de->conn,
  5341. NULL, /* Buffer is big enough */
  5342. size,
  5343. sizeof(size),
  5344. "%.1fk",
  5345. (double)de->file.size / 1024.0);
  5346. } else if (de->file.size < 0x40000000) {
  5347. mg_snprintf(de->conn,
  5348. NULL, /* Buffer is big enough */
  5349. size,
  5350. sizeof(size),
  5351. "%.1fM",
  5352. (double)de->file.size / 1048576);
  5353. } else {
  5354. mg_snprintf(de->conn,
  5355. NULL, /* Buffer is big enough */
  5356. size,
  5357. sizeof(size),
  5358. "%.1fG",
  5359. (double)de->file.size / 1073741824);
  5360. }
  5361. }
  5362. /* Note: mg_snprintf will not cause a buffer overflow above.
  5363. * So, string truncation checks are not required here. */
  5364. tm = localtime(&de->file.last_modified);
  5365. if (tm != NULL) {
  5366. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5367. } else {
  5368. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5369. mod[sizeof(mod) - 1] = '\0';
  5370. }
  5371. mg_url_encode(de->file_name, href, sizeof(href));
  5372. de->conn->num_bytes_sent +=
  5373. mg_printf(de->conn,
  5374. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5375. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5376. de->conn->request_info.local_uri,
  5377. href,
  5378. de->file.is_directory ? "/" : "",
  5379. de->file_name,
  5380. de->file.is_directory ? "/" : "",
  5381. mod,
  5382. size);
  5383. }
  5384. /* This function is called from send_directory() and used for
  5385. * sorting directory entries by size, or name, or modification time.
  5386. * On windows, __cdecl specification is needed in case if project is built
  5387. * with __stdcall convention. qsort always requires __cdels callback. */
  5388. static int WINCDECL
  5389. compare_dir_entries(const void *p1, const void *p2)
  5390. {
  5391. if (p1 && p2) {
  5392. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5393. const char *query_string = a->conn->request_info.query_string;
  5394. int cmp_result = 0;
  5395. if (query_string == NULL) {
  5396. query_string = "na";
  5397. }
  5398. if (a->file.is_directory && !b->file.is_directory) {
  5399. return -1; /* Always put directories on top */
  5400. } else if (!a->file.is_directory && b->file.is_directory) {
  5401. return 1; /* Always put directories on top */
  5402. } else if (*query_string == 'n') {
  5403. cmp_result = strcmp(a->file_name, b->file_name);
  5404. } else if (*query_string == 's') {
  5405. cmp_result = (a->file.size == b->file.size)
  5406. ? 0
  5407. : ((a->file.size > b->file.size) ? 1 : -1);
  5408. } else if (*query_string == 'd') {
  5409. cmp_result =
  5410. (a->file.last_modified == b->file.last_modified)
  5411. ? 0
  5412. : ((a->file.last_modified > b->file.last_modified) ? 1
  5413. : -1);
  5414. }
  5415. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5416. }
  5417. return 0;
  5418. }
  5419. static int
  5420. must_hide_file(struct mg_connection *conn, const char *path)
  5421. {
  5422. if (conn && conn->ctx) {
  5423. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5424. const char *pattern = conn->ctx->config[HIDE_FILES];
  5425. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5426. || (pattern != NULL
  5427. && match_prefix(pattern, strlen(pattern), path) > 0);
  5428. }
  5429. return 0;
  5430. }
  5431. static int
  5432. scan_directory(struct mg_connection *conn,
  5433. const char *dir,
  5434. void *data,
  5435. void (*cb)(struct de *, void *))
  5436. {
  5437. char path[PATH_MAX];
  5438. struct dirent *dp;
  5439. DIR *dirp;
  5440. struct de de;
  5441. int truncated;
  5442. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5443. return 0;
  5444. } else {
  5445. de.conn = conn;
  5446. while ((dp = mg_readdir(dirp)) != NULL) {
  5447. /* Do not show current dir and hidden files */
  5448. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5449. || must_hide_file(conn, dp->d_name)) {
  5450. continue;
  5451. }
  5452. mg_snprintf(
  5453. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5454. /* If we don't memset stat structure to zero, mtime will have
  5455. * garbage and strftime() will segfault later on in
  5456. * print_dir_entry(). memset is required only if mg_stat()
  5457. * fails. For more details, see
  5458. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5459. memset(&de.file, 0, sizeof(de.file));
  5460. if (truncated) {
  5461. /* If the path is not complete, skip processing. */
  5462. continue;
  5463. }
  5464. if (!mg_stat(conn, path, &de.file)) {
  5465. mg_cry(conn,
  5466. "%s: mg_stat(%s) failed: %s",
  5467. __func__,
  5468. path,
  5469. strerror(ERRNO));
  5470. }
  5471. de.file_name = dp->d_name;
  5472. cb(&de, data);
  5473. }
  5474. (void)mg_closedir(dirp);
  5475. }
  5476. return 1;
  5477. }
  5478. #if !defined(NO_FILES)
  5479. static int
  5480. remove_directory(struct mg_connection *conn, const char *dir)
  5481. {
  5482. char path[PATH_MAX];
  5483. struct dirent *dp;
  5484. DIR *dirp;
  5485. struct de de;
  5486. int truncated;
  5487. int ok = 1;
  5488. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5489. return 0;
  5490. } else {
  5491. de.conn = conn;
  5492. while ((dp = mg_readdir(dirp)) != NULL) {
  5493. /* Do not show current dir (but show hidden files as they will
  5494. * also be removed) */
  5495. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5496. continue;
  5497. }
  5498. mg_snprintf(
  5499. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5500. /* If we don't memset stat structure to zero, mtime will have
  5501. * garbage and strftime() will segfault later on in
  5502. * print_dir_entry(). memset is required only if mg_stat()
  5503. * fails. For more details, see
  5504. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5505. memset(&de.file, 0, sizeof(de.file));
  5506. if (truncated) {
  5507. /* Do not delete anything shorter */
  5508. ok = 0;
  5509. continue;
  5510. }
  5511. if (!mg_stat(conn, path, &de.file)) {
  5512. mg_cry(conn,
  5513. "%s: mg_stat(%s) failed: %s",
  5514. __func__,
  5515. path,
  5516. strerror(ERRNO));
  5517. ok = 0;
  5518. }
  5519. if (de.file.membuf == NULL) {
  5520. /* file is not in memory */
  5521. if (de.file.is_directory) {
  5522. if (remove_directory(conn, path) == 0) {
  5523. ok = 0;
  5524. }
  5525. } else {
  5526. if (mg_remove(conn, path) == 0) {
  5527. ok = 0;
  5528. }
  5529. }
  5530. } else {
  5531. /* file is in memory. It can not be deleted. */
  5532. ok = 0;
  5533. }
  5534. }
  5535. (void)mg_closedir(dirp);
  5536. IGNORE_UNUSED_RESULT(rmdir(dir));
  5537. }
  5538. return ok;
  5539. }
  5540. #endif
  5541. struct dir_scan_data {
  5542. struct de *entries;
  5543. unsigned int num_entries;
  5544. unsigned int arr_size;
  5545. };
  5546. /* Behaves like realloc(), but frees original pointer on failure */
  5547. static void *
  5548. realloc2(void *ptr, size_t size)
  5549. {
  5550. void *new_ptr = mg_realloc(ptr, size);
  5551. if (new_ptr == NULL) {
  5552. mg_free(ptr);
  5553. }
  5554. return new_ptr;
  5555. }
  5556. static void
  5557. dir_scan_callback(struct de *de, void *data)
  5558. {
  5559. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5560. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5561. dsd->arr_size *= 2;
  5562. dsd->entries =
  5563. (struct de *)realloc2(dsd->entries,
  5564. dsd->arr_size * sizeof(dsd->entries[0]));
  5565. }
  5566. if (dsd->entries == NULL) {
  5567. /* TODO(lsm, low): propagate an error to the caller */
  5568. dsd->num_entries = 0;
  5569. } else {
  5570. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5571. dsd->entries[dsd->num_entries].file = de->file;
  5572. dsd->entries[dsd->num_entries].conn = de->conn;
  5573. dsd->num_entries++;
  5574. }
  5575. }
  5576. static void
  5577. handle_directory_request(struct mg_connection *conn, const char *dir)
  5578. {
  5579. unsigned int i;
  5580. int sort_direction;
  5581. struct dir_scan_data data = {NULL, 0, 128};
  5582. char date[64];
  5583. time_t curtime = time(NULL);
  5584. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5585. send_http_error(conn,
  5586. 500,
  5587. "Error: Cannot open directory\nopendir(%s): %s",
  5588. dir,
  5589. strerror(ERRNO));
  5590. return;
  5591. }
  5592. gmt_time_string(date, sizeof(date), &curtime);
  5593. if (!conn) {
  5594. return;
  5595. }
  5596. sort_direction = ((conn->request_info.query_string != NULL)
  5597. && (conn->request_info.query_string[1] == 'd'))
  5598. ? 'a'
  5599. : 'd';
  5600. conn->must_close = 1;
  5601. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5602. send_static_cache_header(conn);
  5603. mg_printf(conn,
  5604. "Date: %s\r\n"
  5605. "Connection: close\r\n"
  5606. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5607. date);
  5608. conn->num_bytes_sent +=
  5609. mg_printf(conn,
  5610. "<html><head><title>Index of %s</title>"
  5611. "<style>th {text-align: left;}</style></head>"
  5612. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5613. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5614. "<th><a href=\"?d%c\">Modified</a></th>"
  5615. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5616. "<tr><td colspan=\"3\"><hr></td></tr>",
  5617. conn->request_info.local_uri,
  5618. conn->request_info.local_uri,
  5619. sort_direction,
  5620. sort_direction,
  5621. sort_direction);
  5622. /* Print first entry - link to a parent directory */
  5623. conn->num_bytes_sent +=
  5624. mg_printf(conn,
  5625. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5626. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5627. conn->request_info.local_uri,
  5628. "..",
  5629. "Parent directory",
  5630. "-",
  5631. "-");
  5632. /* Sort and print directory entries */
  5633. if (data.entries != NULL) {
  5634. qsort(data.entries,
  5635. (size_t)data.num_entries,
  5636. sizeof(data.entries[0]),
  5637. compare_dir_entries);
  5638. for (i = 0; i < data.num_entries; i++) {
  5639. print_dir_entry(&data.entries[i]);
  5640. mg_free(data.entries[i].file_name);
  5641. }
  5642. mg_free(data.entries);
  5643. }
  5644. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5645. conn->status_code = 200;
  5646. }
  5647. /* Send len bytes from the opened file to the client. */
  5648. static void
  5649. send_file_data(struct mg_connection *conn,
  5650. struct file *filep,
  5651. int64_t offset,
  5652. int64_t len)
  5653. {
  5654. char buf[MG_BUF_LEN];
  5655. int to_read, num_read, num_written;
  5656. int64_t size;
  5657. if (!filep || !conn) {
  5658. return;
  5659. }
  5660. /* Sanity check the offset */
  5661. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5662. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5663. if (len > 0 && filep->membuf != NULL && size > 0) {
  5664. /* file stored in memory */
  5665. if (len > size - offset) {
  5666. len = size - offset;
  5667. }
  5668. mg_write(conn, filep->membuf + offset, (size_t)len);
  5669. } else if (len > 0 && filep->fp != NULL) {
  5670. /* file stored on disk */
  5671. #if defined(__linux__)
  5672. /* sendfile is only available for Linux */
  5673. if (conn->throttle == 0 && conn->ssl == 0) {
  5674. off_t sf_offs = (off_t)offset;
  5675. ssize_t sf_sent;
  5676. int sf_file = fileno(filep->fp);
  5677. int loop_cnt = 0;
  5678. do {
  5679. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5680. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5681. size_t sf_tosend =
  5682. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5683. sf_sent =
  5684. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5685. if (sf_sent > 0) {
  5686. conn->num_bytes_sent += sf_sent;
  5687. len -= sf_sent;
  5688. offset += sf_sent;
  5689. } else if (loop_cnt == 0) {
  5690. /* This file can not be sent using sendfile.
  5691. * This might be the case for pseudo-files in the
  5692. * /sys/ and /proc/ file system.
  5693. * Use the regular user mode copy code instead. */
  5694. break;
  5695. } else if (sf_sent == 0) {
  5696. /* No error, but 0 bytes sent. May be EOF? */
  5697. return;
  5698. }
  5699. loop_cnt++;
  5700. } while ((len > 0) && (sf_sent >= 0));
  5701. if (sf_sent > 0) {
  5702. return; /* OK */
  5703. }
  5704. /* sf_sent<0 means error, thus fall back to the classic way */
  5705. /* This is always the case, if sf_file is not a "normal" file,
  5706. * e.g., for sending data from the output of a CGI process. */
  5707. offset = (int64_t)sf_offs;
  5708. }
  5709. #endif
  5710. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5711. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5712. send_http_error(
  5713. conn,
  5714. 500,
  5715. "%s",
  5716. "Error: Unable to access file at requested position.");
  5717. } else {
  5718. while (len > 0) {
  5719. /* Calculate how much to read from the file in the buffer */
  5720. to_read = sizeof(buf);
  5721. if ((int64_t)to_read > len) {
  5722. to_read = (int)len;
  5723. }
  5724. /* Read from file, exit the loop on error */
  5725. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5726. <= 0) {
  5727. break;
  5728. }
  5729. /* Send read bytes to the client, exit the loop on error */
  5730. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5731. != num_read) {
  5732. break;
  5733. }
  5734. /* Both read and were successful, adjust counters */
  5735. conn->num_bytes_sent += num_written;
  5736. len -= num_written;
  5737. }
  5738. }
  5739. }
  5740. }
  5741. static int
  5742. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5743. {
  5744. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5745. }
  5746. static void
  5747. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5748. {
  5749. if (filep != NULL && buf != NULL) {
  5750. mg_snprintf(NULL,
  5751. NULL, /* All calls to construct_etag use 64 byte buffer */
  5752. buf,
  5753. buf_len,
  5754. "\"%lx.%" INT64_FMT "\"",
  5755. (unsigned long)filep->last_modified,
  5756. filep->size);
  5757. }
  5758. }
  5759. static void
  5760. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5761. {
  5762. if (filep != NULL && filep->fp != NULL) {
  5763. #ifdef _WIN32
  5764. (void)conn; /* Unused. */
  5765. #else
  5766. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5767. mg_cry(conn,
  5768. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5769. __func__,
  5770. strerror(ERRNO));
  5771. }
  5772. #endif
  5773. }
  5774. }
  5775. static void
  5776. handle_static_file_request(struct mg_connection *conn,
  5777. const char *path,
  5778. struct file *filep,
  5779. const char *mime_type)
  5780. {
  5781. char date[64], lm[64], etag[64];
  5782. char range[128]; /* large enough, so there will be no overflow */
  5783. const char *msg = "OK", *hdr;
  5784. time_t curtime = time(NULL);
  5785. int64_t cl, r1, r2;
  5786. struct vec mime_vec;
  5787. int n, truncated;
  5788. char gz_path[PATH_MAX];
  5789. const char *encoding = "";
  5790. const char *cors1, *cors2, *cors3;
  5791. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5792. return;
  5793. }
  5794. if (mime_type == NULL) {
  5795. get_mime_type(conn->ctx, path, &mime_vec);
  5796. } else {
  5797. mime_vec.ptr = mime_type;
  5798. mime_vec.len = strlen(mime_type);
  5799. }
  5800. if (filep->size > INT64_MAX) {
  5801. send_http_error(conn,
  5802. 500,
  5803. "Error: File size is too large to send\n%" INT64_FMT,
  5804. filep->size);
  5805. }
  5806. cl = (int64_t)filep->size;
  5807. conn->status_code = 200;
  5808. range[0] = '\0';
  5809. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5810. * it's important to rewrite the filename after resolving
  5811. * the mime type from it, to preserve the actual file's type */
  5812. if (filep->gzipped) {
  5813. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5814. if (truncated) {
  5815. send_http_error(conn,
  5816. 500,
  5817. "Error: Path of zipped file too long (%s)",
  5818. path);
  5819. return;
  5820. }
  5821. path = gz_path;
  5822. encoding = "Content-Encoding: gzip\r\n";
  5823. }
  5824. if (!mg_fopen(conn, path, "rb", filep)) {
  5825. send_http_error(conn,
  5826. 500,
  5827. "Error: Cannot open file\nfopen(%s): %s",
  5828. path,
  5829. strerror(ERRNO));
  5830. return;
  5831. }
  5832. fclose_on_exec(filep, conn);
  5833. /* If Range: header specified, act accordingly */
  5834. r1 = r2 = 0;
  5835. hdr = mg_get_header(conn, "Range");
  5836. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5837. && r2 >= 0) {
  5838. /* actually, range requests don't play well with a pre-gzipped
  5839. * file (since the range is specified in the uncompressed space) */
  5840. if (filep->gzipped) {
  5841. send_http_error(
  5842. conn,
  5843. 501,
  5844. "%s",
  5845. "Error: Range requests in gzipped files are not supported");
  5846. mg_fclose(filep);
  5847. return;
  5848. }
  5849. conn->status_code = 206;
  5850. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  5851. mg_snprintf(conn,
  5852. NULL, /* range buffer is big enough */
  5853. range,
  5854. sizeof(range),
  5855. "Content-Range: bytes "
  5856. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5857. r1,
  5858. r1 + cl - 1,
  5859. filep->size);
  5860. msg = "Partial Content";
  5861. }
  5862. hdr = mg_get_header(conn, "Origin");
  5863. if (hdr) {
  5864. /* Cross-origin resource sharing (CORS), see
  5865. * http://www.html5rocks.com/en/tutorials/cors/,
  5866. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5867. * preflight is not supported for files. */
  5868. cors1 = "Access-Control-Allow-Origin: ";
  5869. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5870. cors3 = "\r\n";
  5871. } else {
  5872. cors1 = cors2 = cors3 = "";
  5873. }
  5874. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5875. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5876. gmt_time_string(date, sizeof(date), &curtime);
  5877. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5878. construct_etag(etag, sizeof(etag), filep);
  5879. (void)mg_printf(conn,
  5880. "HTTP/1.1 %d %s\r\n"
  5881. "%s%s%s"
  5882. "Date: %s\r\n",
  5883. conn->status_code,
  5884. msg,
  5885. cors1,
  5886. cors2,
  5887. cors3,
  5888. date);
  5889. send_static_cache_header(conn);
  5890. (void)mg_printf(conn,
  5891. "Last-Modified: %s\r\n"
  5892. "Etag: %s\r\n"
  5893. "Content-Type: %.*s\r\n"
  5894. "Content-Length: %" INT64_FMT "\r\n"
  5895. "Connection: %s\r\n"
  5896. "Accept-Ranges: bytes\r\n"
  5897. "%s%s\r\n",
  5898. lm,
  5899. etag,
  5900. (int)mime_vec.len,
  5901. mime_vec.ptr,
  5902. cl,
  5903. suggest_connection_header(conn),
  5904. range,
  5905. encoding);
  5906. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5907. send_file_data(conn, filep, r1, cl);
  5908. }
  5909. mg_fclose(filep);
  5910. }
  5911. #if !defined(NO_CACHING)
  5912. static void
  5913. handle_not_modified_static_file_request(struct mg_connection *conn,
  5914. struct file *filep)
  5915. {
  5916. char date[64], lm[64], etag[64];
  5917. time_t curtime = time(NULL);
  5918. if (conn == NULL || filep == NULL) {
  5919. return;
  5920. }
  5921. conn->status_code = 304;
  5922. gmt_time_string(date, sizeof(date), &curtime);
  5923. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5924. construct_etag(etag, sizeof(etag), filep);
  5925. (void)mg_printf(conn,
  5926. "HTTP/1.1 %d %s\r\n"
  5927. "Date: %s\r\n",
  5928. conn->status_code,
  5929. mg_get_response_code_text(conn, conn->status_code),
  5930. date);
  5931. send_static_cache_header(conn);
  5932. (void)mg_printf(conn,
  5933. "Last-Modified: %s\r\n"
  5934. "Etag: %s\r\n"
  5935. "Connection: %s\r\n"
  5936. "\r\n",
  5937. lm,
  5938. etag,
  5939. suggest_connection_header(conn));
  5940. }
  5941. #endif
  5942. void
  5943. mg_send_file(struct mg_connection *conn, const char *path)
  5944. {
  5945. mg_send_mime_file(conn, path, NULL);
  5946. }
  5947. void
  5948. mg_send_mime_file(struct mg_connection *conn,
  5949. const char *path,
  5950. const char *mime_type)
  5951. {
  5952. struct file file = STRUCT_FILE_INITIALIZER;
  5953. if (mg_stat(conn, path, &file)) {
  5954. if (file.is_directory) {
  5955. if (!conn) {
  5956. return;
  5957. }
  5958. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5959. "yes")) {
  5960. handle_directory_request(conn, path);
  5961. } else {
  5962. send_http_error(conn,
  5963. 403,
  5964. "%s",
  5965. "Error: Directory listing denied");
  5966. }
  5967. } else {
  5968. handle_static_file_request(conn, path, &file, mime_type);
  5969. }
  5970. } else {
  5971. send_http_error(conn, 404, "%s", "Error: File not found");
  5972. }
  5973. }
  5974. /* For a given PUT path, create all intermediate subdirectories.
  5975. * Return 0 if the path itself is a directory.
  5976. * Return 1 if the path leads to a file.
  5977. * Return -1 for if the path is too long.
  5978. * Return -2 if path can not be created.
  5979. */
  5980. static int
  5981. put_dir(struct mg_connection *conn, const char *path)
  5982. {
  5983. char buf[PATH_MAX];
  5984. const char *s, *p;
  5985. struct file file = STRUCT_FILE_INITIALIZER;
  5986. size_t len;
  5987. int res = 1;
  5988. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5989. len = (size_t)(p - path);
  5990. if (len >= sizeof(buf)) {
  5991. /* path too long */
  5992. res = -1;
  5993. break;
  5994. }
  5995. memcpy(buf, path, len);
  5996. buf[len] = '\0';
  5997. /* Try to create intermediate directory */
  5998. DEBUG_TRACE("mkdir(%s)", buf);
  5999. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  6000. /* path does not exixt and can not be created */
  6001. res = -2;
  6002. break;
  6003. }
  6004. /* Is path itself a directory? */
  6005. if (p[1] == '\0') {
  6006. res = 0;
  6007. }
  6008. }
  6009. return res;
  6010. }
  6011. static void
  6012. remove_bad_file(const struct mg_connection *conn, const char *path)
  6013. {
  6014. int r = mg_remove(conn, path);
  6015. if (r != 0) {
  6016. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6017. }
  6018. }
  6019. long long
  6020. mg_store_body(struct mg_connection *conn, const char *path)
  6021. {
  6022. char buf[MG_BUF_LEN];
  6023. long long len = 0;
  6024. int ret, n;
  6025. struct file fi;
  6026. if (conn->consumed_content != 0) {
  6027. mg_cry(conn, "%s: Contents already consumed", __func__);
  6028. return -11;
  6029. }
  6030. ret = put_dir(conn, path);
  6031. if (ret < 0) {
  6032. /* -1 for path too long,
  6033. * -2 for path can not be created. */
  6034. return ret;
  6035. }
  6036. if (ret != 1) {
  6037. /* Return 0 means, path itself is a directory. */
  6038. return 0;
  6039. }
  6040. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6041. return -12;
  6042. }
  6043. ret = mg_read(conn, buf, sizeof(buf));
  6044. while (ret > 0) {
  6045. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6046. if (n != ret) {
  6047. mg_fclose(&fi);
  6048. remove_bad_file(conn, path);
  6049. return -13;
  6050. }
  6051. ret = mg_read(conn, buf, sizeof(buf));
  6052. }
  6053. /* TODO: mg_fclose should return an error,
  6054. * and every caller should check and handle it. */
  6055. if (fclose(fi.fp) != 0) {
  6056. remove_bad_file(conn, path);
  6057. return -14;
  6058. }
  6059. return len;
  6060. }
  6061. /* Parse HTTP headers from the given buffer, advance buf pointer
  6062. * to the point where parsing stopped.
  6063. * All parameters must be valid pointers (not NULL).
  6064. * Return <0 on error. */
  6065. static int
  6066. parse_http_headers(char **buf, struct mg_request_info *ri)
  6067. {
  6068. int i;
  6069. ri->num_headers = 0;
  6070. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6071. char *dp = *buf;
  6072. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6073. dp++;
  6074. }
  6075. if (dp == *buf) {
  6076. /* End of headers reached. */
  6077. break;
  6078. }
  6079. if (*dp != ':') {
  6080. /* This is not a valid field. */
  6081. return -1;
  6082. }
  6083. /* End of header key (*dp == ':') */
  6084. /* Truncate here and set the key name */
  6085. *dp = 0;
  6086. ri->http_headers[i].name = *buf;
  6087. do {
  6088. dp++;
  6089. } while (*dp == ' ');
  6090. /* The rest of the line is the value */
  6091. ri->http_headers[i].value = dp;
  6092. *buf = dp + strcspn(dp, "\r\n");
  6093. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6094. *buf = NULL;
  6095. }
  6096. ri->num_headers = i + 1;
  6097. if (*buf) {
  6098. (*buf)[0] = 0;
  6099. (*buf)[1] = 0;
  6100. *buf += 2;
  6101. } else {
  6102. *buf = dp;
  6103. break;
  6104. }
  6105. if ((*buf)[0] == '\r') {
  6106. /* This is the end of the header */
  6107. break;
  6108. }
  6109. }
  6110. return ri->num_headers;
  6111. }
  6112. static int
  6113. is_valid_http_method(const char *method)
  6114. {
  6115. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6116. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6117. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6118. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6119. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6120. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6121. /* TRACE method (RFC 2616) is not supported for security reasons */
  6122. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6123. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6124. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6125. /* Unsupported WEBDAV Methods: */
  6126. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6127. /* + 11 methods from RFC 3253 */
  6128. /* ORDERPATCH (RFC 3648) */
  6129. /* ACL (RFC 3744) */
  6130. /* SEARCH (RFC 5323) */
  6131. /* + MicroSoft extensions
  6132. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6133. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6134. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6135. }
  6136. /* Parse HTTP request, fill in mg_request_info structure.
  6137. * This function modifies the buffer by NUL-terminating
  6138. * HTTP request components, header names and header values.
  6139. * Parameters:
  6140. * buf (in/out): pointer to the HTTP header to parse and split
  6141. * len (in): length of HTTP header buffer
  6142. * re (out): parsed header as mg_request_info
  6143. * buf and ri must be valid pointers (not NULL), len>0.
  6144. * Returns <0 on error. */
  6145. static int
  6146. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6147. {
  6148. int is_request, request_length;
  6149. char *start_line;
  6150. request_length = get_request_len(buf, len);
  6151. if (request_length > 0) {
  6152. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6153. * remote_port */
  6154. ri->remote_user = ri->request_method = ri->request_uri =
  6155. ri->http_version = NULL;
  6156. ri->num_headers = 0;
  6157. buf[request_length - 1] = '\0';
  6158. /* RFC says that all initial whitespaces should be ingored */
  6159. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6160. buf++;
  6161. }
  6162. start_line = skip(&buf, "\r\n");
  6163. ri->request_method = skip(&start_line, " ");
  6164. ri->request_uri = skip(&start_line, " ");
  6165. ri->http_version = start_line;
  6166. /* HTTP message could be either HTTP request:
  6167. * "GET / HTTP/1.0 ..."
  6168. * or a HTTP response:
  6169. * "HTTP/1.0 200 OK ..."
  6170. * otherwise it is invalid.
  6171. */
  6172. is_request = is_valid_http_method(ri->request_method);
  6173. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6174. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6175. /* Not a valid request or response: invalid */
  6176. return -1;
  6177. }
  6178. if (is_request) {
  6179. ri->http_version += 5;
  6180. }
  6181. if (parse_http_headers(&buf, ri) < 0) {
  6182. /* Error while parsing headers */
  6183. return -1;
  6184. }
  6185. }
  6186. return request_length;
  6187. }
  6188. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6189. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6190. * buffer (which marks the end of HTTP request). Buffer buf may already
  6191. * have some data. The length of the data is stored in nread.
  6192. * Upon every read operation, increase nread by the number of bytes read. */
  6193. static int
  6194. read_request(FILE *fp,
  6195. struct mg_connection *conn,
  6196. char *buf,
  6197. int bufsiz,
  6198. int *nread)
  6199. {
  6200. int request_len, n = 0;
  6201. struct timespec last_action_time;
  6202. double request_timeout;
  6203. if (!conn) {
  6204. return 0;
  6205. }
  6206. memset(&last_action_time, 0, sizeof(last_action_time));
  6207. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6208. /* value of request_timeout is in seconds, config in milliseconds */
  6209. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6210. } else {
  6211. request_timeout = -1.0;
  6212. }
  6213. request_len = get_request_len(buf, *nread);
  6214. /* first time reading from this connection */
  6215. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6216. while (
  6217. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6218. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6219. <= request_timeout) || (request_timeout < 0))
  6220. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6221. > 0)) {
  6222. *nread += n;
  6223. /* assert(*nread <= bufsiz); */
  6224. if (*nread > bufsiz) {
  6225. return -2;
  6226. }
  6227. request_len = get_request_len(buf, *nread);
  6228. if (request_timeout > 0.0) {
  6229. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6230. }
  6231. }
  6232. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6233. }
  6234. #if !defined(NO_FILES)
  6235. /* For given directory path, substitute it to valid index file.
  6236. * Return 1 if index file has been found, 0 if not found.
  6237. * If the file is found, it's stats is returned in stp. */
  6238. static int
  6239. substitute_index_file(struct mg_connection *conn,
  6240. char *path,
  6241. size_t path_len,
  6242. struct file *filep)
  6243. {
  6244. if (conn && conn->ctx) {
  6245. const char *list = conn->ctx->config[INDEX_FILES];
  6246. struct file file = STRUCT_FILE_INITIALIZER;
  6247. struct vec filename_vec;
  6248. size_t n = strlen(path);
  6249. int found = 0;
  6250. /* The 'path' given to us points to the directory. Remove all trailing
  6251. * directory separator characters from the end of the path, and
  6252. * then append single directory separator character. */
  6253. while (n > 0 && path[n - 1] == '/') {
  6254. n--;
  6255. }
  6256. path[n] = '/';
  6257. /* Traverse index files list. For each entry, append it to the given
  6258. * path and see if the file exists. If it exists, break the loop */
  6259. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6260. /* Ignore too long entries that may overflow path buffer */
  6261. if (filename_vec.len > path_len - (n + 2)) {
  6262. continue;
  6263. }
  6264. /* Prepare full path to the index file */
  6265. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6266. /* Does it exist? */
  6267. if (mg_stat(conn, path, &file)) {
  6268. /* Yes it does, break the loop */
  6269. *filep = file;
  6270. found = 1;
  6271. break;
  6272. }
  6273. }
  6274. /* If no index file exists, restore directory path */
  6275. if (!found) {
  6276. path[n] = '\0';
  6277. }
  6278. return found;
  6279. }
  6280. return 0;
  6281. }
  6282. #endif
  6283. #if !defined(NO_CACHING)
  6284. /* Return True if we should reply 304 Not Modified. */
  6285. static int
  6286. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6287. {
  6288. char etag[64];
  6289. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6290. const char *inm = mg_get_header(conn, "If-None-Match");
  6291. construct_etag(etag, sizeof(etag), filep);
  6292. if (!filep) {
  6293. return 0;
  6294. }
  6295. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6296. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6297. }
  6298. #endif /* !NO_CACHING */
  6299. #if !defined(NO_CGI) || !defined(NO_FILES)
  6300. static int
  6301. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6302. {
  6303. const char *expect, *body;
  6304. char buf[MG_BUF_LEN];
  6305. int to_read, nread, success = 0;
  6306. int64_t buffered_len;
  6307. double timeout = -1.0;
  6308. if (!conn) {
  6309. return 0;
  6310. }
  6311. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6312. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6313. }
  6314. expect = mg_get_header(conn, "Expect");
  6315. /* assert(fp != NULL); */
  6316. if (!fp) {
  6317. send_http_error(conn, 500, "%s", "Error: NULL File");
  6318. return 0;
  6319. }
  6320. if (conn->content_len == -1 && !conn->is_chunked) {
  6321. /* Content length is not specified by the client. */
  6322. send_http_error(conn,
  6323. 411,
  6324. "%s",
  6325. "Error: Client did not specify content length");
  6326. } else if ((expect != NULL)
  6327. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6328. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6329. send_http_error(conn,
  6330. 417,
  6331. "Error: Can not fulfill expectation %s",
  6332. expect);
  6333. } else {
  6334. if (expect != NULL) {
  6335. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6336. conn->status_code = 100;
  6337. } else {
  6338. conn->status_code = 200;
  6339. }
  6340. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6341. - conn->consumed_content;
  6342. /* assert(buffered_len >= 0); */
  6343. /* assert(conn->consumed_content == 0); */
  6344. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6345. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6346. return 0;
  6347. }
  6348. if (buffered_len > 0) {
  6349. if ((int64_t)buffered_len > conn->content_len) {
  6350. buffered_len = (int)conn->content_len;
  6351. }
  6352. body = conn->buf + conn->request_len + conn->consumed_content;
  6353. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6354. conn->consumed_content += buffered_len;
  6355. }
  6356. nread = 0;
  6357. while (conn->consumed_content < conn->content_len) {
  6358. to_read = sizeof(buf);
  6359. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6360. to_read = (int)(conn->content_len - conn->consumed_content);
  6361. }
  6362. nread = pull(NULL, conn, buf, to_read, timeout);
  6363. if (nread <= 0
  6364. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6365. break;
  6366. }
  6367. conn->consumed_content += nread;
  6368. }
  6369. if (conn->consumed_content == conn->content_len) {
  6370. success = (nread >= 0);
  6371. }
  6372. /* Each error code path in this function must send an error */
  6373. if (!success) {
  6374. /* NOTE: Maybe some data has already been sent. */
  6375. /* TODO (low): If some data has been sent, a correct error
  6376. * reply can no longer be sent, so just close the connection */
  6377. send_http_error(conn, 500, "%s", "");
  6378. }
  6379. }
  6380. return success;
  6381. }
  6382. #endif
  6383. #if !defined(NO_CGI)
  6384. /* This structure helps to create an environment for the spawned CGI program.
  6385. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6386. * last element must be NULL.
  6387. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6388. * strings must reside in a contiguous buffer. The end of the buffer is
  6389. * marked by two '\0' characters.
  6390. * We satisfy both worlds: we create an envp array (which is vars), all
  6391. * entries are actually pointers inside buf. */
  6392. struct cgi_environment {
  6393. struct mg_connection *conn;
  6394. /* Data block */
  6395. char *buf; /* Environment buffer */
  6396. size_t buflen; /* Space available in buf */
  6397. size_t bufused; /* Space taken in buf */
  6398. /* Index block */
  6399. char **var; /* char **envp */
  6400. size_t varlen; /* Number of variables available in var */
  6401. size_t varused; /* Number of variables stored in var */
  6402. };
  6403. static void addenv(struct cgi_environment *env,
  6404. PRINTF_FORMAT_STRING(const char *fmt),
  6405. ...) PRINTF_ARGS(2, 3);
  6406. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6407. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6408. static void
  6409. addenv(struct cgi_environment *env, const char *fmt, ...)
  6410. {
  6411. size_t n, space;
  6412. int truncated;
  6413. char *added;
  6414. va_list ap;
  6415. /* Calculate how much space is left in the buffer */
  6416. space = (env->buflen - env->bufused);
  6417. /* Calculate an estimate for the required space */
  6418. n = strlen(fmt) + 2 + 128;
  6419. do {
  6420. if (space <= n) {
  6421. /* Allocate new buffer */
  6422. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6423. added = (char *)mg_realloc(env->buf, n);
  6424. if (!added) {
  6425. /* Out of memory */
  6426. mg_cry(env->conn,
  6427. "%s: Cannot allocate memory for CGI variable [%s]",
  6428. __func__,
  6429. fmt);
  6430. return;
  6431. }
  6432. env->buf = added;
  6433. env->buflen = n;
  6434. space = (env->buflen - env->bufused);
  6435. }
  6436. /* Make a pointer to the free space int the buffer */
  6437. added = env->buf + env->bufused;
  6438. /* Copy VARIABLE=VALUE\0 string into the free space */
  6439. va_start(ap, fmt);
  6440. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6441. va_end(ap);
  6442. /* Do not add truncated strings to the environment */
  6443. if (truncated) {
  6444. /* Reallocate the buffer */
  6445. space = 0;
  6446. n = 1;
  6447. }
  6448. } while (truncated);
  6449. /* Calculate number of bytes added to the environment */
  6450. n = strlen(added) + 1;
  6451. env->bufused += n;
  6452. /* Now update the variable index */
  6453. space = (env->varlen - env->varused);
  6454. if (space < 2) {
  6455. mg_cry(env->conn,
  6456. "%s: Cannot register CGI variable [%s]",
  6457. __func__,
  6458. fmt);
  6459. return;
  6460. }
  6461. /* Append a pointer to the added string into the envp array */
  6462. env->var[env->varused] = added;
  6463. env->varused++;
  6464. }
  6465. static void
  6466. prepare_cgi_environment(struct mg_connection *conn,
  6467. const char *prog,
  6468. struct cgi_environment *env)
  6469. {
  6470. const char *s;
  6471. struct vec var_vec;
  6472. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6473. int i, truncated;
  6474. if (conn == NULL || prog == NULL || env == NULL) {
  6475. return;
  6476. }
  6477. env->conn = conn;
  6478. env->buflen = CGI_ENVIRONMENT_SIZE;
  6479. env->bufused = 0;
  6480. env->buf = (char *)mg_malloc(env->buflen);
  6481. env->varlen = MAX_CGI_ENVIR_VARS;
  6482. env->varused = 0;
  6483. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6484. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6485. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6486. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6487. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6488. /* Prepare the environment block */
  6489. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6490. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6491. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6492. #if defined(USE_IPV6)
  6493. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6494. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6495. } else
  6496. #endif
  6497. {
  6498. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6499. }
  6500. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6501. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6502. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6503. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6504. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6505. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6506. /* SCRIPT_NAME */
  6507. addenv(env,
  6508. "SCRIPT_NAME=%.*s",
  6509. (int)strlen(conn->request_info.local_uri)
  6510. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6511. conn->request_info.local_uri);
  6512. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6513. if (conn->path_info == NULL) {
  6514. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6515. } else {
  6516. addenv(env,
  6517. "PATH_TRANSLATED=%s%s",
  6518. conn->ctx->config[DOCUMENT_ROOT],
  6519. conn->path_info);
  6520. }
  6521. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6522. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6523. addenv(env, "CONTENT_TYPE=%s", s);
  6524. }
  6525. if (conn->request_info.query_string != NULL) {
  6526. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6527. }
  6528. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6529. addenv(env, "CONTENT_LENGTH=%s", s);
  6530. }
  6531. if ((s = getenv("PATH")) != NULL) {
  6532. addenv(env, "PATH=%s", s);
  6533. }
  6534. if (conn->path_info != NULL) {
  6535. addenv(env, "PATH_INFO=%s", conn->path_info);
  6536. }
  6537. if (conn->status_code > 0) {
  6538. /* CGI error handler should show the status code */
  6539. addenv(env, "STATUS=%d", conn->status_code);
  6540. }
  6541. #if defined(_WIN32)
  6542. if ((s = getenv("COMSPEC")) != NULL) {
  6543. addenv(env, "COMSPEC=%s", s);
  6544. }
  6545. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6546. addenv(env, "SYSTEMROOT=%s", s);
  6547. }
  6548. if ((s = getenv("SystemDrive")) != NULL) {
  6549. addenv(env, "SystemDrive=%s", s);
  6550. }
  6551. if ((s = getenv("ProgramFiles")) != NULL) {
  6552. addenv(env, "ProgramFiles=%s", s);
  6553. }
  6554. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6555. addenv(env, "ProgramFiles(x86)=%s", s);
  6556. }
  6557. #else
  6558. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6559. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6560. }
  6561. #endif /* _WIN32 */
  6562. if ((s = getenv("PERLLIB")) != NULL) {
  6563. addenv(env, "PERLLIB=%s", s);
  6564. }
  6565. if (conn->request_info.remote_user != NULL) {
  6566. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6567. addenv(env, "%s", "AUTH_TYPE=Digest");
  6568. }
  6569. /* Add all headers as HTTP_* variables */
  6570. for (i = 0; i < conn->request_info.num_headers; i++) {
  6571. (void)mg_snprintf(conn,
  6572. &truncated,
  6573. http_var_name,
  6574. sizeof(http_var_name),
  6575. "HTTP_%s",
  6576. conn->request_info.http_headers[i].name);
  6577. if (truncated) {
  6578. mg_cry(conn,
  6579. "%s: HTTP header variable too long [%s]",
  6580. __func__,
  6581. conn->request_info.http_headers[i].name);
  6582. continue;
  6583. }
  6584. /* Convert variable name into uppercase, and change - to _ */
  6585. for (p = http_var_name; *p != '\0'; p++) {
  6586. if (*p == '-') {
  6587. *p = '_';
  6588. }
  6589. *p = (char)toupper(*(unsigned char *)p);
  6590. }
  6591. addenv(env,
  6592. "%s=%s",
  6593. http_var_name,
  6594. conn->request_info.http_headers[i].value);
  6595. }
  6596. /* Add user-specified variables */
  6597. s = conn->ctx->config[CGI_ENVIRONMENT];
  6598. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6599. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6600. }
  6601. env->var[env->varused] = NULL;
  6602. env->buf[env->bufused] = '\0';
  6603. }
  6604. static void
  6605. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6606. {
  6607. char *buf;
  6608. size_t buflen;
  6609. int headers_len, data_len, i, truncated;
  6610. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6611. const char *status, *status_text, *connection_state;
  6612. char *pbuf, dir[PATH_MAX], *p;
  6613. struct mg_request_info ri;
  6614. struct cgi_environment blk;
  6615. FILE *in = NULL, *out = NULL, *err = NULL;
  6616. struct file fout = STRUCT_FILE_INITIALIZER;
  6617. pid_t pid = (pid_t)-1;
  6618. if (conn == NULL) {
  6619. return;
  6620. }
  6621. buf = NULL;
  6622. buflen = 16384;
  6623. prepare_cgi_environment(conn, prog, &blk);
  6624. /* CGI must be executed in its own directory. 'dir' must point to the
  6625. * directory containing executable program, 'p' must point to the
  6626. * executable program name relative to 'dir'. */
  6627. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6628. if (truncated) {
  6629. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6630. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6631. goto done;
  6632. }
  6633. if ((p = strrchr(dir, '/')) != NULL) {
  6634. *p++ = '\0';
  6635. } else {
  6636. dir[0] = '.', dir[1] = '\0';
  6637. p = (char *)prog;
  6638. }
  6639. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6640. status = strerror(ERRNO);
  6641. mg_cry(conn,
  6642. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6643. prog,
  6644. status);
  6645. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6646. goto done;
  6647. }
  6648. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6649. if (pid == (pid_t)-1) {
  6650. status = strerror(ERRNO);
  6651. mg_cry(conn,
  6652. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6653. prog,
  6654. status);
  6655. send_http_error(conn,
  6656. 500,
  6657. "Error: Cannot spawn CGI process [%s]: %s",
  6658. prog,
  6659. status);
  6660. goto done;
  6661. }
  6662. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6663. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6664. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6665. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6666. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6667. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6668. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6669. /* Parent closes only one side of the pipes.
  6670. * If we don't mark them as closed, close() attempt before
  6671. * return from this function throws an exception on Windows.
  6672. * Windows does not like when closed descriptor is closed again. */
  6673. (void)close(fdin[0]);
  6674. (void)close(fdout[1]);
  6675. (void)close(fderr[1]);
  6676. fdin[0] = fdout[1] = fderr[1] = -1;
  6677. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6678. status = strerror(ERRNO);
  6679. mg_cry(conn,
  6680. "Error: CGI program \"%s\": Can not open stdin: %s",
  6681. prog,
  6682. status);
  6683. send_http_error(conn,
  6684. 500,
  6685. "Error: CGI can not open fdin\nfopen: %s",
  6686. status);
  6687. goto done;
  6688. }
  6689. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6690. status = strerror(ERRNO);
  6691. mg_cry(conn,
  6692. "Error: CGI program \"%s\": Can not open stdout: %s",
  6693. prog,
  6694. status);
  6695. send_http_error(conn,
  6696. 500,
  6697. "Error: CGI can not open fdout\nfopen: %s",
  6698. status);
  6699. goto done;
  6700. }
  6701. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6702. status = strerror(ERRNO);
  6703. mg_cry(conn,
  6704. "Error: CGI program \"%s\": Can not open stderr: %s",
  6705. prog,
  6706. status);
  6707. send_http_error(conn,
  6708. 500,
  6709. "Error: CGI can not open fdout\nfopen: %s",
  6710. status);
  6711. goto done;
  6712. }
  6713. setbuf(in, NULL);
  6714. setbuf(out, NULL);
  6715. setbuf(err, NULL);
  6716. fout.fp = out;
  6717. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6718. /* This is a POST/PUT request, or another request with body data. */
  6719. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6720. /* Error sending the body data */
  6721. mg_cry(conn,
  6722. "Error: CGI program \"%s\": Forward body data failed",
  6723. prog);
  6724. goto done;
  6725. }
  6726. }
  6727. /* Close so child gets an EOF. */
  6728. fclose(in);
  6729. in = NULL;
  6730. fdin[1] = -1;
  6731. /* Now read CGI reply into a buffer. We need to set correct
  6732. * status code, thus we need to see all HTTP headers first.
  6733. * Do not send anything back to client, until we buffer in all
  6734. * HTTP headers. */
  6735. data_len = 0;
  6736. buf = (char *)mg_malloc(buflen);
  6737. if (buf == NULL) {
  6738. send_http_error(conn,
  6739. 500,
  6740. "Error: Not enough memory for CGI buffer (%u bytes)",
  6741. (unsigned int)buflen);
  6742. mg_cry(conn,
  6743. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6744. "bytes)",
  6745. prog,
  6746. (unsigned int)buflen);
  6747. goto done;
  6748. }
  6749. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6750. if (headers_len <= 0) {
  6751. /* Could not parse the CGI response. Check if some error message on
  6752. * stderr. */
  6753. i = pull_all(err, conn, buf, (int)buflen);
  6754. if (i > 0) {
  6755. mg_cry(conn,
  6756. "Error: CGI program \"%s\" sent error "
  6757. "message: [%.*s]",
  6758. prog,
  6759. i,
  6760. buf);
  6761. send_http_error(conn,
  6762. 500,
  6763. "Error: CGI program \"%s\" sent error "
  6764. "message: [%.*s]",
  6765. prog,
  6766. i,
  6767. buf);
  6768. } else {
  6769. mg_cry(conn,
  6770. "Error: CGI program sent malformed or too big "
  6771. "(>%u bytes) HTTP headers: [%.*s]",
  6772. (unsigned)buflen,
  6773. data_len,
  6774. buf);
  6775. send_http_error(conn,
  6776. 500,
  6777. "Error: CGI program sent malformed or too big "
  6778. "(>%u bytes) HTTP headers: [%.*s]",
  6779. (unsigned)buflen,
  6780. data_len,
  6781. buf);
  6782. }
  6783. goto done;
  6784. }
  6785. pbuf = buf;
  6786. buf[headers_len - 1] = '\0';
  6787. parse_http_headers(&pbuf, &ri);
  6788. /* Make up and send the status line */
  6789. status_text = "OK";
  6790. if ((status = get_header(&ri, "Status")) != NULL) {
  6791. conn->status_code = atoi(status);
  6792. status_text = status;
  6793. while (isdigit(*(const unsigned char *)status_text)
  6794. || *status_text == ' ') {
  6795. status_text++;
  6796. }
  6797. } else if (get_header(&ri, "Location") != NULL) {
  6798. conn->status_code = 302;
  6799. } else {
  6800. conn->status_code = 200;
  6801. }
  6802. connection_state = get_header(&ri, "Connection");
  6803. if (!header_has_option(connection_state, "keep-alive")) {
  6804. conn->must_close = 1;
  6805. }
  6806. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6807. /* Send headers */
  6808. for (i = 0; i < ri.num_headers; i++) {
  6809. mg_printf(conn,
  6810. "%s: %s\r\n",
  6811. ri.http_headers[i].name,
  6812. ri.http_headers[i].value);
  6813. }
  6814. mg_write(conn, "\r\n", 2);
  6815. /* Send chunk of data that may have been read after the headers */
  6816. conn->num_bytes_sent +=
  6817. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6818. /* Read the rest of CGI output and send to the client */
  6819. send_file_data(conn, &fout, 0, INT64_MAX);
  6820. done:
  6821. mg_free(blk.var);
  6822. mg_free(blk.buf);
  6823. if (pid != (pid_t)-1) {
  6824. kill(pid, SIGKILL);
  6825. #if !defined(_WIN32)
  6826. {
  6827. int st;
  6828. while (waitpid(pid, &st, 0) != -1)
  6829. ; /* clean zombies */
  6830. }
  6831. #endif
  6832. }
  6833. if (fdin[0] != -1) {
  6834. close(fdin[0]);
  6835. }
  6836. if (fdout[1] != -1) {
  6837. close(fdout[1]);
  6838. }
  6839. if (in != NULL) {
  6840. fclose(in);
  6841. } else if (fdin[1] != -1) {
  6842. close(fdin[1]);
  6843. }
  6844. if (out != NULL) {
  6845. fclose(out);
  6846. } else if (fdout[0] != -1) {
  6847. close(fdout[0]);
  6848. }
  6849. if (err != NULL) {
  6850. fclose(err);
  6851. } else if (fderr[0] != -1) {
  6852. close(fderr[0]);
  6853. }
  6854. if (buf != NULL) {
  6855. mg_free(buf);
  6856. }
  6857. }
  6858. #endif /* !NO_CGI */
  6859. #if !defined(NO_FILES)
  6860. static void
  6861. mkcol(struct mg_connection *conn, const char *path)
  6862. {
  6863. int rc, body_len;
  6864. struct de de;
  6865. char date[64];
  6866. time_t curtime = time(NULL);
  6867. if (conn == NULL) {
  6868. return;
  6869. }
  6870. /* TODO (mid): Check the send_http_error situations in this function */
  6871. memset(&de.file, 0, sizeof(de.file));
  6872. if (!mg_stat(conn, path, &de.file)) {
  6873. mg_cry(conn,
  6874. "%s: mg_stat(%s) failed: %s",
  6875. __func__,
  6876. path,
  6877. strerror(ERRNO));
  6878. }
  6879. if (de.file.last_modified) {
  6880. /* TODO (high): This check does not seem to make any sense ! */
  6881. send_http_error(
  6882. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6883. return;
  6884. }
  6885. body_len = conn->data_len - conn->request_len;
  6886. if (body_len > 0) {
  6887. send_http_error(
  6888. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6889. return;
  6890. }
  6891. rc = mg_mkdir(conn, path, 0755);
  6892. if (rc == 0) {
  6893. conn->status_code = 201;
  6894. gmt_time_string(date, sizeof(date), &curtime);
  6895. mg_printf(conn,
  6896. "HTTP/1.1 %d Created\r\n"
  6897. "Date: %s\r\n",
  6898. conn->status_code,
  6899. date);
  6900. send_static_cache_header(conn);
  6901. mg_printf(conn,
  6902. "Content-Length: 0\r\n"
  6903. "Connection: %s\r\n\r\n",
  6904. suggest_connection_header(conn));
  6905. } else if (rc == -1) {
  6906. if (errno == EEXIST) {
  6907. send_http_error(
  6908. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6909. } else if (errno == EACCES) {
  6910. send_http_error(
  6911. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6912. } else if (errno == ENOENT) {
  6913. send_http_error(
  6914. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6915. } else {
  6916. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6917. }
  6918. }
  6919. }
  6920. static void
  6921. put_file(struct mg_connection *conn, const char *path)
  6922. {
  6923. struct file file = STRUCT_FILE_INITIALIZER;
  6924. const char *range;
  6925. int64_t r1, r2;
  6926. int rc;
  6927. char date[64];
  6928. time_t curtime = time(NULL);
  6929. if (conn == NULL) {
  6930. return;
  6931. }
  6932. if (mg_stat(conn, path, &file)) {
  6933. /* File already exists */
  6934. conn->status_code = 200;
  6935. if (file.is_directory) {
  6936. /* This is an already existing directory,
  6937. * so there is nothing to do for the server. */
  6938. rc = 0;
  6939. } else {
  6940. /* File exists and is not a directory. */
  6941. /* Can it be replaced? */
  6942. if (file.membuf != NULL) {
  6943. /* This is an "in-memory" file, that can not be replaced */
  6944. send_http_error(
  6945. conn,
  6946. 405,
  6947. "Error: Put not possible\nReplacing %s is not supported",
  6948. path);
  6949. return;
  6950. }
  6951. /* Check if the server may write this file */
  6952. if (access(path, W_OK) == 0) {
  6953. /* Access granted */
  6954. conn->status_code = 200;
  6955. rc = 1;
  6956. } else {
  6957. send_http_error(
  6958. conn,
  6959. 403,
  6960. "Error: Put not possible\nReplacing %s is not allowed",
  6961. path);
  6962. return;
  6963. }
  6964. }
  6965. } else {
  6966. /* File should be created */
  6967. conn->status_code = 201;
  6968. rc = put_dir(conn, path);
  6969. }
  6970. if (rc == 0) {
  6971. /* put_dir returns 0 if path is a directory */
  6972. gmt_time_string(date, sizeof(date), &curtime);
  6973. mg_printf(conn,
  6974. "HTTP/1.1 %d %s\r\n",
  6975. conn->status_code,
  6976. mg_get_response_code_text(NULL, conn->status_code));
  6977. send_no_cache_header(conn);
  6978. mg_printf(conn,
  6979. "Date: %s\r\n"
  6980. "Content-Length: 0\r\n"
  6981. "Connection: %s\r\n\r\n",
  6982. date,
  6983. suggest_connection_header(conn));
  6984. /* Request to create a directory has been fulfilled successfully.
  6985. * No need to put a file. */
  6986. return;
  6987. }
  6988. if (rc == -1) {
  6989. /* put_dir returns -1 if the path is too long */
  6990. send_http_error(conn,
  6991. 414,
  6992. "Error: Path too long\nput_dir(%s): %s",
  6993. path,
  6994. strerror(ERRNO));
  6995. return;
  6996. }
  6997. if (rc == -2) {
  6998. /* put_dir returns -2 if the directory can not be created */
  6999. send_http_error(conn,
  7000. 500,
  7001. "Error: Can not create directory\nput_dir(%s): %s",
  7002. path,
  7003. strerror(ERRNO));
  7004. return;
  7005. }
  7006. /* A file should be created or overwritten. */
  7007. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7008. mg_fclose(&file);
  7009. send_http_error(conn,
  7010. 500,
  7011. "Error: Can not create file\nfopen(%s): %s",
  7012. path,
  7013. strerror(ERRNO));
  7014. return;
  7015. }
  7016. fclose_on_exec(&file, conn);
  7017. range = mg_get_header(conn, "Content-Range");
  7018. r1 = r2 = 0;
  7019. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7020. conn->status_code = 206; /* Partial content */
  7021. fseeko(file.fp, r1, SEEK_SET);
  7022. }
  7023. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7024. /* forward_body_data failed.
  7025. * The error code has already been sent to the client,
  7026. * and conn->status_code is already set. */
  7027. mg_fclose(&file);
  7028. return;
  7029. }
  7030. gmt_time_string(date, sizeof(date), &curtime);
  7031. mg_printf(conn,
  7032. "HTTP/1.1 %d %s\r\n",
  7033. conn->status_code,
  7034. mg_get_response_code_text(NULL, conn->status_code));
  7035. send_no_cache_header(conn);
  7036. mg_printf(conn,
  7037. "Date: %s\r\n"
  7038. "Content-Length: 0\r\n"
  7039. "Connection: %s\r\n\r\n",
  7040. date,
  7041. suggest_connection_header(conn));
  7042. mg_fclose(&file);
  7043. }
  7044. static void
  7045. delete_file(struct mg_connection *conn, const char *path)
  7046. {
  7047. struct de de;
  7048. memset(&de.file, 0, sizeof(de.file));
  7049. if (!mg_stat(conn, path, &de.file)) {
  7050. /* mg_stat returns 0 if the file does not exist */
  7051. send_http_error(conn,
  7052. 404,
  7053. "Error: Cannot delete file\nFile %s not found",
  7054. path);
  7055. return;
  7056. }
  7057. if (de.file.membuf != NULL) {
  7058. /* the file is cached in memory */
  7059. send_http_error(
  7060. conn,
  7061. 405,
  7062. "Error: Delete not possible\nDeleting %s is not supported",
  7063. path);
  7064. return;
  7065. }
  7066. if (de.file.is_directory) {
  7067. if (remove_directory(conn, path)) {
  7068. /* Delete is successful: Return 204 without content. */
  7069. send_http_error(conn, 204, "%s", "");
  7070. } else {
  7071. /* Delete is not successful: Return 500 (Server error). */
  7072. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7073. }
  7074. return;
  7075. }
  7076. /* This is an existing file (not a directory).
  7077. * Check if write permission is granted. */
  7078. if (access(path, W_OK) != 0) {
  7079. /* File is read only */
  7080. send_http_error(
  7081. conn,
  7082. 403,
  7083. "Error: Delete not possible\nDeleting %s is not allowed",
  7084. path);
  7085. return;
  7086. }
  7087. /* Try to delete it. */
  7088. if (mg_remove(conn, path) == 0) {
  7089. /* Delete was successful: Return 204 without content. */
  7090. send_http_error(conn, 204, "%s", "");
  7091. } else {
  7092. /* Delete not successful (file locked). */
  7093. send_http_error(conn,
  7094. 423,
  7095. "Error: Cannot delete file\nremove(%s): %s",
  7096. path,
  7097. strerror(ERRNO));
  7098. }
  7099. }
  7100. #endif /* !NO_FILES */
  7101. static void
  7102. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7103. static void
  7104. do_ssi_include(struct mg_connection *conn,
  7105. const char *ssi,
  7106. char *tag,
  7107. int include_level)
  7108. {
  7109. char file_name[MG_BUF_LEN], path[512], *p;
  7110. struct file file = STRUCT_FILE_INITIALIZER;
  7111. size_t len;
  7112. int truncated = 0;
  7113. if (conn == NULL) {
  7114. return;
  7115. }
  7116. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7117. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7118. * always < MG_BUF_LEN. */
  7119. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7120. /* File name is relative to the webserver root */
  7121. file_name[511] = 0;
  7122. (void)mg_snprintf(conn,
  7123. &truncated,
  7124. path,
  7125. sizeof(path),
  7126. "%s/%s",
  7127. conn->ctx->config[DOCUMENT_ROOT],
  7128. file_name);
  7129. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7130. /* File name is relative to the webserver working directory
  7131. * or it is absolute system path */
  7132. file_name[511] = 0;
  7133. (void)
  7134. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7135. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7136. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7137. /* File name is relative to the currect document */
  7138. file_name[511] = 0;
  7139. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7140. if (!truncated) {
  7141. if ((p = strrchr(path, '/')) != NULL) {
  7142. p[1] = '\0';
  7143. }
  7144. len = strlen(path);
  7145. (void)mg_snprintf(conn,
  7146. &truncated,
  7147. path + len,
  7148. sizeof(path) - len,
  7149. "%s",
  7150. file_name);
  7151. }
  7152. } else {
  7153. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7154. return;
  7155. }
  7156. if (truncated) {
  7157. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7158. return;
  7159. }
  7160. if (!mg_fopen(conn, path, "rb", &file)) {
  7161. mg_cry(conn,
  7162. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7163. tag,
  7164. path,
  7165. strerror(ERRNO));
  7166. } else {
  7167. fclose_on_exec(&file, conn);
  7168. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7169. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7170. path) > 0) {
  7171. send_ssi_file(conn, path, &file, include_level + 1);
  7172. } else {
  7173. send_file_data(conn, &file, 0, INT64_MAX);
  7174. }
  7175. mg_fclose(&file);
  7176. }
  7177. }
  7178. #if !defined(NO_POPEN)
  7179. static void
  7180. do_ssi_exec(struct mg_connection *conn, char *tag)
  7181. {
  7182. char cmd[1024] = "";
  7183. struct file file = STRUCT_FILE_INITIALIZER;
  7184. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7185. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7186. } else {
  7187. cmd[1023] = 0;
  7188. if ((file.fp = popen(cmd, "r")) == NULL) {
  7189. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7190. } else {
  7191. send_file_data(conn, &file, 0, INT64_MAX);
  7192. pclose(file.fp);
  7193. }
  7194. }
  7195. }
  7196. #endif /* !NO_POPEN */
  7197. static int
  7198. mg_fgetc(struct file *filep, int offset)
  7199. {
  7200. if (filep == NULL) {
  7201. return EOF;
  7202. }
  7203. if (filep->membuf != NULL && offset >= 0
  7204. && ((unsigned int)(offset)) < filep->size) {
  7205. return ((const unsigned char *)filep->membuf)[offset];
  7206. } else if (filep->fp != NULL) {
  7207. return fgetc(filep->fp);
  7208. } else {
  7209. return EOF;
  7210. }
  7211. }
  7212. static void
  7213. send_ssi_file(struct mg_connection *conn,
  7214. const char *path,
  7215. struct file *filep,
  7216. int include_level)
  7217. {
  7218. char buf[MG_BUF_LEN];
  7219. int ch, offset, len, in_ssi_tag;
  7220. if (include_level > 10) {
  7221. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7222. return;
  7223. }
  7224. in_ssi_tag = len = offset = 0;
  7225. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7226. if (in_ssi_tag && ch == '>') {
  7227. in_ssi_tag = 0;
  7228. buf[len++] = (char)ch;
  7229. buf[len] = '\0';
  7230. /* assert(len <= (int) sizeof(buf)); */
  7231. if (len > (int)sizeof(buf)) {
  7232. break;
  7233. }
  7234. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7235. /* Not an SSI tag, pass it */
  7236. (void)mg_write(conn, buf, (size_t)len);
  7237. } else {
  7238. if (!memcmp(buf + 5, "include", 7)) {
  7239. do_ssi_include(conn, path, buf + 12, include_level);
  7240. #if !defined(NO_POPEN)
  7241. } else if (!memcmp(buf + 5, "exec", 4)) {
  7242. do_ssi_exec(conn, buf + 9);
  7243. #endif /* !NO_POPEN */
  7244. } else {
  7245. mg_cry(conn,
  7246. "%s: unknown SSI "
  7247. "command: \"%s\"",
  7248. path,
  7249. buf);
  7250. }
  7251. }
  7252. len = 0;
  7253. } else if (in_ssi_tag) {
  7254. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7255. /* Not an SSI tag */
  7256. in_ssi_tag = 0;
  7257. } else if (len == (int)sizeof(buf) - 2) {
  7258. mg_cry(conn, "%s: SSI tag is too large", path);
  7259. len = 0;
  7260. }
  7261. buf[len++] = (char)(ch & 0xff);
  7262. } else if (ch == '<') {
  7263. in_ssi_tag = 1;
  7264. if (len > 0) {
  7265. mg_write(conn, buf, (size_t)len);
  7266. }
  7267. len = 0;
  7268. buf[len++] = (char)(ch & 0xff);
  7269. } else {
  7270. buf[len++] = (char)(ch & 0xff);
  7271. if (len == (int)sizeof(buf)) {
  7272. mg_write(conn, buf, (size_t)len);
  7273. len = 0;
  7274. }
  7275. }
  7276. }
  7277. /* Send the rest of buffered data */
  7278. if (len > 0) {
  7279. mg_write(conn, buf, (size_t)len);
  7280. }
  7281. }
  7282. static void
  7283. handle_ssi_file_request(struct mg_connection *conn,
  7284. const char *path,
  7285. struct file *filep)
  7286. {
  7287. char date[64];
  7288. time_t curtime = time(NULL);
  7289. const char *cors1, *cors2, *cors3;
  7290. if (conn == NULL || path == NULL || filep == NULL) {
  7291. return;
  7292. }
  7293. if (mg_get_header(conn, "Origin")) {
  7294. /* Cross-origin resource sharing (CORS). */
  7295. cors1 = "Access-Control-Allow-Origin: ";
  7296. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7297. cors3 = "\r\n";
  7298. } else {
  7299. cors1 = cors2 = cors3 = "";
  7300. }
  7301. if (!mg_fopen(conn, path, "rb", filep)) {
  7302. /* File exists (precondition for calling this function),
  7303. * but can not be opened by the server. */
  7304. send_http_error(conn,
  7305. 500,
  7306. "Error: Cannot read file\nfopen(%s): %s",
  7307. path,
  7308. strerror(ERRNO));
  7309. } else {
  7310. conn->must_close = 1;
  7311. gmt_time_string(date, sizeof(date), &curtime);
  7312. fclose_on_exec(filep, conn);
  7313. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7314. send_no_cache_header(conn);
  7315. mg_printf(conn,
  7316. "%s%s%s"
  7317. "Date: %s\r\n"
  7318. "Content-Type: text/html\r\n"
  7319. "Connection: %s\r\n\r\n",
  7320. cors1,
  7321. cors2,
  7322. cors3,
  7323. date,
  7324. suggest_connection_header(conn));
  7325. send_ssi_file(conn, path, filep, 0);
  7326. mg_fclose(filep);
  7327. }
  7328. }
  7329. #if !defined(NO_FILES)
  7330. static void
  7331. send_options(struct mg_connection *conn)
  7332. {
  7333. char date[64];
  7334. time_t curtime = time(NULL);
  7335. if (!conn) {
  7336. return;
  7337. }
  7338. conn->status_code = 200;
  7339. conn->must_close = 1;
  7340. gmt_time_string(date, sizeof(date), &curtime);
  7341. mg_printf(conn,
  7342. "HTTP/1.1 200 OK\r\n"
  7343. "Date: %s\r\n"
  7344. /* TODO: "Cache-Control" (?) */
  7345. "Connection: %s\r\n"
  7346. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7347. "PROPFIND, MKCOL\r\n"
  7348. "DAV: 1\r\n\r\n",
  7349. date,
  7350. suggest_connection_header(conn));
  7351. }
  7352. /* Writes PROPFIND properties for a collection element */
  7353. static void
  7354. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7355. {
  7356. char mtime[64];
  7357. if (conn == NULL || uri == NULL || filep == NULL) {
  7358. return;
  7359. }
  7360. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7361. conn->num_bytes_sent +=
  7362. mg_printf(conn,
  7363. "<d:response>"
  7364. "<d:href>%s</d:href>"
  7365. "<d:propstat>"
  7366. "<d:prop>"
  7367. "<d:resourcetype>%s</d:resourcetype>"
  7368. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7369. "<d:getlastmodified>%s</d:getlastmodified>"
  7370. "</d:prop>"
  7371. "<d:status>HTTP/1.1 200 OK</d:status>"
  7372. "</d:propstat>"
  7373. "</d:response>\n",
  7374. uri,
  7375. filep->is_directory ? "<d:collection/>" : "",
  7376. filep->size,
  7377. mtime);
  7378. }
  7379. static void
  7380. print_dav_dir_entry(struct de *de, void *data)
  7381. {
  7382. char href[PATH_MAX];
  7383. char href_encoded[PATH_MAX * 3 /* worst case */];
  7384. int truncated;
  7385. struct mg_connection *conn = (struct mg_connection *)data;
  7386. if (!de || !conn) {
  7387. return;
  7388. }
  7389. mg_snprintf(conn,
  7390. &truncated,
  7391. href,
  7392. sizeof(href),
  7393. "%s%s",
  7394. conn->request_info.local_uri,
  7395. de->file_name);
  7396. if (!truncated) {
  7397. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7398. print_props(conn, href_encoded, &de->file);
  7399. }
  7400. }
  7401. static void
  7402. handle_propfind(struct mg_connection *conn,
  7403. const char *path,
  7404. struct file *filep)
  7405. {
  7406. const char *depth = mg_get_header(conn, "Depth");
  7407. char date[64];
  7408. time_t curtime = time(NULL);
  7409. gmt_time_string(date, sizeof(date), &curtime);
  7410. if (!conn || !path || !filep || !conn->ctx) {
  7411. return;
  7412. }
  7413. conn->must_close = 1;
  7414. conn->status_code = 207;
  7415. mg_printf(conn,
  7416. "HTTP/1.1 207 Multi-Status\r\n"
  7417. "Date: %s\r\n",
  7418. date);
  7419. send_static_cache_header(conn);
  7420. mg_printf(conn,
  7421. "Connection: %s\r\n"
  7422. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7423. suggest_connection_header(conn));
  7424. conn->num_bytes_sent +=
  7425. mg_printf(conn,
  7426. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7427. "<d:multistatus xmlns:d='DAV:'>\n");
  7428. /* Print properties for the requested resource itself */
  7429. print_props(conn, conn->request_info.local_uri, filep);
  7430. /* If it is a directory, print directory entries too if Depth is not 0 */
  7431. if (filep && filep->is_directory
  7432. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7433. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7434. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7435. }
  7436. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7437. }
  7438. #endif
  7439. void
  7440. mg_lock_connection(struct mg_connection *conn)
  7441. {
  7442. if (conn) {
  7443. (void)pthread_mutex_lock(&conn->mutex);
  7444. }
  7445. }
  7446. void
  7447. mg_unlock_connection(struct mg_connection *conn)
  7448. {
  7449. if (conn) {
  7450. (void)pthread_mutex_unlock(&conn->mutex);
  7451. }
  7452. }
  7453. void
  7454. mg_lock_context(struct mg_context *ctx)
  7455. {
  7456. if (ctx) {
  7457. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7458. }
  7459. }
  7460. void
  7461. mg_unlock_context(struct mg_context *ctx)
  7462. {
  7463. if (ctx) {
  7464. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7465. }
  7466. }
  7467. #if defined(USE_TIMERS)
  7468. #include "timer.inl"
  7469. #endif /* USE_TIMERS */
  7470. #ifdef USE_LUA
  7471. #include "mod_lua.inl"
  7472. #endif /* USE_LUA */
  7473. #ifdef USE_DUKTAPE
  7474. #include "mod_duktape.inl"
  7475. #endif /* USE_DUKTAPE */
  7476. #if defined(USE_WEBSOCKET)
  7477. /* START OF SHA-1 code
  7478. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7479. #define SHA1HANDSOFF
  7480. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7481. *
  7482. * #if defined(__sun)
  7483. * #include "solarisfixes.h"
  7484. * #endif
  7485. */
  7486. static int
  7487. is_big_endian(void)
  7488. {
  7489. static const int n = 1;
  7490. return ((char *)&n)[0] == 0;
  7491. }
  7492. union char64long16 {
  7493. unsigned char c[64];
  7494. uint32_t l[16];
  7495. };
  7496. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7497. static uint32_t
  7498. blk0(union char64long16 *block, int i)
  7499. {
  7500. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7501. if (!is_big_endian()) {
  7502. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7503. | (rol(block->l[i], 8) & 0x00FF00FF);
  7504. }
  7505. return block->l[i];
  7506. }
  7507. #define blk(i) \
  7508. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7509. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7510. 1))
  7511. #define R0(v, w, x, y, z, i) \
  7512. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7513. w = rol(w, 30);
  7514. #define R1(v, w, x, y, z, i) \
  7515. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7516. w = rol(w, 30);
  7517. #define R2(v, w, x, y, z, i) \
  7518. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7519. w = rol(w, 30);
  7520. #define R3(v, w, x, y, z, i) \
  7521. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7522. w = rol(w, 30);
  7523. #define R4(v, w, x, y, z, i) \
  7524. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7525. w = rol(w, 30);
  7526. typedef struct {
  7527. uint32_t state[5];
  7528. uint32_t count[2];
  7529. unsigned char buffer[64];
  7530. } SHA1_CTX;
  7531. static void
  7532. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7533. {
  7534. uint32_t a, b, c, d, e;
  7535. union char64long16 block[1];
  7536. memcpy(block, buffer, 64);
  7537. a = state[0];
  7538. b = state[1];
  7539. c = state[2];
  7540. d = state[3];
  7541. e = state[4];
  7542. R0(a, b, c, d, e, 0);
  7543. R0(e, a, b, c, d, 1);
  7544. R0(d, e, a, b, c, 2);
  7545. R0(c, d, e, a, b, 3);
  7546. R0(b, c, d, e, a, 4);
  7547. R0(a, b, c, d, e, 5);
  7548. R0(e, a, b, c, d, 6);
  7549. R0(d, e, a, b, c, 7);
  7550. R0(c, d, e, a, b, 8);
  7551. R0(b, c, d, e, a, 9);
  7552. R0(a, b, c, d, e, 10);
  7553. R0(e, a, b, c, d, 11);
  7554. R0(d, e, a, b, c, 12);
  7555. R0(c, d, e, a, b, 13);
  7556. R0(b, c, d, e, a, 14);
  7557. R0(a, b, c, d, e, 15);
  7558. R1(e, a, b, c, d, 16);
  7559. R1(d, e, a, b, c, 17);
  7560. R1(c, d, e, a, b, 18);
  7561. R1(b, c, d, e, a, 19);
  7562. R2(a, b, c, d, e, 20);
  7563. R2(e, a, b, c, d, 21);
  7564. R2(d, e, a, b, c, 22);
  7565. R2(c, d, e, a, b, 23);
  7566. R2(b, c, d, e, a, 24);
  7567. R2(a, b, c, d, e, 25);
  7568. R2(e, a, b, c, d, 26);
  7569. R2(d, e, a, b, c, 27);
  7570. R2(c, d, e, a, b, 28);
  7571. R2(b, c, d, e, a, 29);
  7572. R2(a, b, c, d, e, 30);
  7573. R2(e, a, b, c, d, 31);
  7574. R2(d, e, a, b, c, 32);
  7575. R2(c, d, e, a, b, 33);
  7576. R2(b, c, d, e, a, 34);
  7577. R2(a, b, c, d, e, 35);
  7578. R2(e, a, b, c, d, 36);
  7579. R2(d, e, a, b, c, 37);
  7580. R2(c, d, e, a, b, 38);
  7581. R2(b, c, d, e, a, 39);
  7582. R3(a, b, c, d, e, 40);
  7583. R3(e, a, b, c, d, 41);
  7584. R3(d, e, a, b, c, 42);
  7585. R3(c, d, e, a, b, 43);
  7586. R3(b, c, d, e, a, 44);
  7587. R3(a, b, c, d, e, 45);
  7588. R3(e, a, b, c, d, 46);
  7589. R3(d, e, a, b, c, 47);
  7590. R3(c, d, e, a, b, 48);
  7591. R3(b, c, d, e, a, 49);
  7592. R3(a, b, c, d, e, 50);
  7593. R3(e, a, b, c, d, 51);
  7594. R3(d, e, a, b, c, 52);
  7595. R3(c, d, e, a, b, 53);
  7596. R3(b, c, d, e, a, 54);
  7597. R3(a, b, c, d, e, 55);
  7598. R3(e, a, b, c, d, 56);
  7599. R3(d, e, a, b, c, 57);
  7600. R3(c, d, e, a, b, 58);
  7601. R3(b, c, d, e, a, 59);
  7602. R4(a, b, c, d, e, 60);
  7603. R4(e, a, b, c, d, 61);
  7604. R4(d, e, a, b, c, 62);
  7605. R4(c, d, e, a, b, 63);
  7606. R4(b, c, d, e, a, 64);
  7607. R4(a, b, c, d, e, 65);
  7608. R4(e, a, b, c, d, 66);
  7609. R4(d, e, a, b, c, 67);
  7610. R4(c, d, e, a, b, 68);
  7611. R4(b, c, d, e, a, 69);
  7612. R4(a, b, c, d, e, 70);
  7613. R4(e, a, b, c, d, 71);
  7614. R4(d, e, a, b, c, 72);
  7615. R4(c, d, e, a, b, 73);
  7616. R4(b, c, d, e, a, 74);
  7617. R4(a, b, c, d, e, 75);
  7618. R4(e, a, b, c, d, 76);
  7619. R4(d, e, a, b, c, 77);
  7620. R4(c, d, e, a, b, 78);
  7621. R4(b, c, d, e, a, 79);
  7622. state[0] += a;
  7623. state[1] += b;
  7624. state[2] += c;
  7625. state[3] += d;
  7626. state[4] += e;
  7627. a = b = c = d = e = 0;
  7628. memset(block, '\0', sizeof(block));
  7629. }
  7630. static void
  7631. SHA1Init(SHA1_CTX *context)
  7632. {
  7633. context->state[0] = 0x67452301;
  7634. context->state[1] = 0xEFCDAB89;
  7635. context->state[2] = 0x98BADCFE;
  7636. context->state[3] = 0x10325476;
  7637. context->state[4] = 0xC3D2E1F0;
  7638. context->count[0] = context->count[1] = 0;
  7639. }
  7640. static void
  7641. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7642. {
  7643. uint32_t i, j;
  7644. j = context->count[0];
  7645. if ((context->count[0] += len << 3) < j) {
  7646. context->count[1]++;
  7647. }
  7648. context->count[1] += (len >> 29);
  7649. j = (j >> 3) & 63;
  7650. if ((j + len) > 63) {
  7651. memcpy(&context->buffer[j], data, (i = 64 - j));
  7652. SHA1Transform(context->state, context->buffer);
  7653. for (; i + 63 < len; i += 64) {
  7654. SHA1Transform(context->state, &data[i]);
  7655. }
  7656. j = 0;
  7657. } else
  7658. i = 0;
  7659. memcpy(&context->buffer[j], &data[i], len - i);
  7660. }
  7661. static void
  7662. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7663. {
  7664. unsigned i;
  7665. unsigned char finalcount[8], c;
  7666. for (i = 0; i < 8; i++) {
  7667. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7668. >> ((3 - (i & 3)) * 8)) & 255);
  7669. }
  7670. c = 0200;
  7671. SHA1Update(context, &c, 1);
  7672. while ((context->count[0] & 504) != 448) {
  7673. c = 0000;
  7674. SHA1Update(context, &c, 1);
  7675. }
  7676. SHA1Update(context, finalcount, 8);
  7677. for (i = 0; i < 20; i++) {
  7678. digest[i] = (unsigned char)((context->state[i >> 2]
  7679. >> ((3 - (i & 3)) * 8)) & 255);
  7680. }
  7681. memset(context, '\0', sizeof(*context));
  7682. memset(&finalcount, '\0', sizeof(finalcount));
  7683. }
  7684. /* END OF SHA1 CODE */
  7685. static int
  7686. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7687. {
  7688. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7689. const char *protocol = NULL;
  7690. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7691. SHA1_CTX sha_ctx;
  7692. int truncated;
  7693. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7694. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7695. if (truncated) {
  7696. conn->must_close = 1;
  7697. return 0;
  7698. }
  7699. SHA1Init(&sha_ctx);
  7700. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7701. SHA1Final((unsigned char *)sha, &sha_ctx);
  7702. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7703. mg_printf(conn,
  7704. "HTTP/1.1 101 Switching Protocols\r\n"
  7705. "Upgrade: websocket\r\n"
  7706. "Connection: Upgrade\r\n"
  7707. "Sec-WebSocket-Accept: %s\r\n",
  7708. b64_sha);
  7709. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7710. if (protocol) {
  7711. /* The protocol is a comma seperated list of names. */
  7712. /* The server must only return one value from this list. */
  7713. /* First check if it is a list or just a single value. */
  7714. const char *sep = strchr(protocol, ',');
  7715. if (sep == NULL) {
  7716. /* Just a single protocol -> accept it. */
  7717. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7718. } else {
  7719. /* Multiple protocols -> accept the first one. */
  7720. /* This is just a quick fix if the client offers multiple
  7721. * protocols. In order to get the behavior intended by
  7722. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7723. * required to have a list of websocket subprotocols accepted
  7724. * by the server. Then the server must either select a subprotocol
  7725. * supported by client and server, or the server has to abort the
  7726. * handshake by not returning a Sec-Websocket-Protocol header if
  7727. * no subprotocol is acceptable.
  7728. */
  7729. mg_printf(conn,
  7730. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7731. (int)(sep - protocol),
  7732. protocol);
  7733. }
  7734. /* TODO: Real subprotocol negotiation instead of just taking the first
  7735. * websocket subprotocol suggested by the client. */
  7736. } else {
  7737. mg_printf(conn, "%s", "\r\n");
  7738. }
  7739. return 1;
  7740. }
  7741. static void
  7742. read_websocket(struct mg_connection *conn,
  7743. mg_websocket_data_handler ws_data_handler,
  7744. void *callback_data)
  7745. {
  7746. /* Pointer to the beginning of the portion of the incoming websocket
  7747. * message queue.
  7748. * The original websocket upgrade request is never removed, so the queue
  7749. * begins after it. */
  7750. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7751. int n, error, exit_by_callback;
  7752. /* body_len is the length of the entire queue in bytes
  7753. * len is the length of the current message
  7754. * data_len is the length of the current message's data payload
  7755. * header_len is the length of the current message's header */
  7756. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7757. /* "The masking key is a 32-bit value chosen at random by the client."
  7758. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7759. */
  7760. unsigned char mask[4];
  7761. /* data points to the place where the message is stored when passed to
  7762. * the
  7763. * websocket_data callback. This is either mem on the stack, or a
  7764. * dynamically allocated buffer if it is too large. */
  7765. char mem[4096];
  7766. char *data = mem;
  7767. unsigned char mop; /* mask flag and opcode */
  7768. double timeout = -1.0;
  7769. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7770. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7771. }
  7772. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7773. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7774. }
  7775. mg_set_thread_name("wsock");
  7776. /* Loop continuously, reading messages from the socket, invoking the
  7777. * callback, and waiting repeatedly until an error occurs. */
  7778. while (!conn->ctx->stop_flag) {
  7779. header_len = 0;
  7780. assert(conn->data_len >= conn->request_len);
  7781. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7782. len = buf[1] & 127;
  7783. mask_len = (buf[1] & 128) ? 4 : 0;
  7784. if ((len < 126) && (body_len >= mask_len)) {
  7785. data_len = len;
  7786. header_len = 2 + mask_len;
  7787. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  7788. header_len = 4 + mask_len;
  7789. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7790. } else if (body_len >= (10 + mask_len)) {
  7791. header_len = 10 + mask_len;
  7792. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7793. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7794. }
  7795. }
  7796. if (header_len > 0 && body_len >= header_len) {
  7797. /* Allocate space to hold websocket payload */
  7798. data = mem;
  7799. if (data_len > sizeof(mem)) {
  7800. data = (char *)mg_malloc(data_len);
  7801. if (data == NULL) {
  7802. /* Allocation failed, exit the loop and then close the
  7803. * connection */
  7804. mg_cry(conn, "websocket out of memory; closing connection");
  7805. break;
  7806. }
  7807. }
  7808. /* Copy the mask before we shift the queue and destroy it */
  7809. if (mask_len > 0) {
  7810. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7811. } else {
  7812. memset(mask, 0, sizeof(mask));
  7813. }
  7814. /* Read frame payload from the first message in the queue into
  7815. * data and advance the queue by moving the memory in place. */
  7816. assert(body_len >= header_len);
  7817. if (data_len + header_len > body_len) {
  7818. mop = buf[0]; /* current mask and opcode */
  7819. /* Overflow case */
  7820. len = body_len - header_len;
  7821. memcpy(data, buf + header_len, len);
  7822. error = 0;
  7823. while (len < data_len) {
  7824. n = pull(
  7825. NULL, conn, data + len, (int)(data_len - len), timeout);
  7826. if (n <= 0) {
  7827. error = 1;
  7828. break;
  7829. }
  7830. len += (size_t)n;
  7831. }
  7832. if (error) {
  7833. mg_cry(conn, "Websocket pull failed; closing connection");
  7834. break;
  7835. }
  7836. conn->data_len = conn->request_len;
  7837. } else {
  7838. mop = buf[0]; /* current mask and opcode, overwritten by
  7839. * memmove() */
  7840. /* Length of the message being read at the front of the
  7841. * queue */
  7842. len = data_len + header_len;
  7843. /* Copy the data payload into the data pointer for the
  7844. * callback */
  7845. memcpy(data, buf + header_len, data_len);
  7846. /* Move the queue forward len bytes */
  7847. memmove(buf, buf + len, body_len - len);
  7848. /* Mark the queue as advanced */
  7849. conn->data_len -= (int)len;
  7850. }
  7851. /* Apply mask if necessary */
  7852. if (mask_len > 0) {
  7853. for (i = 0; i < data_len; ++i) {
  7854. data[i] ^= mask[i & 3];
  7855. }
  7856. }
  7857. /* Exit the loop if callback signals to exit (server side),
  7858. * or "connection close" opcode received (client side). */
  7859. exit_by_callback = 0;
  7860. if ((ws_data_handler != NULL)
  7861. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7862. exit_by_callback = 1;
  7863. }
  7864. if (data != mem) {
  7865. mg_free(data);
  7866. }
  7867. if (exit_by_callback
  7868. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7869. /* Opcode == 8, connection close */
  7870. break;
  7871. }
  7872. /* Not breaking the loop, process next websocket frame. */
  7873. } else {
  7874. /* Read from the socket into the next available location in the
  7875. * message queue. */
  7876. if ((n = pull(NULL,
  7877. conn,
  7878. conn->buf + conn->data_len,
  7879. conn->buf_size - conn->data_len,
  7880. timeout)) <= 0) {
  7881. /* Error, no bytes read */
  7882. break;
  7883. }
  7884. conn->data_len += n;
  7885. }
  7886. }
  7887. mg_set_thread_name("worker");
  7888. }
  7889. static int
  7890. mg_websocket_write_exec(struct mg_connection *conn,
  7891. int opcode,
  7892. const char *data,
  7893. size_t dataLen,
  7894. uint32_t masking_key)
  7895. {
  7896. unsigned char header[14];
  7897. size_t headerLen = 1;
  7898. int retval = -1;
  7899. header[0] = 0x80 + (opcode & 0xF);
  7900. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7901. if (dataLen < 126) {
  7902. /* inline 7-bit length field */
  7903. header[1] = (unsigned char)dataLen;
  7904. headerLen = 2;
  7905. } else if (dataLen <= 0xFFFF) {
  7906. /* 16-bit length field */
  7907. header[1] = 126;
  7908. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7909. headerLen = 4;
  7910. } else {
  7911. /* 64-bit length field */
  7912. header[1] = 127;
  7913. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7914. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7915. headerLen = 10;
  7916. }
  7917. if (masking_key) {
  7918. /* add mask */
  7919. header[1] |= 0x80;
  7920. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7921. headerLen += 4;
  7922. }
  7923. /* Note that POSIX/Winsock's send() is threadsafe
  7924. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7925. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7926. * push(), although that is only a problem if the packet is large or
  7927. * outgoing buffer is full). */
  7928. (void)mg_lock_connection(conn);
  7929. retval = mg_write(conn, header, headerLen);
  7930. if (dataLen > 0) {
  7931. retval = mg_write(conn, data, dataLen);
  7932. }
  7933. mg_unlock_connection(conn);
  7934. return retval;
  7935. }
  7936. int
  7937. mg_websocket_write(struct mg_connection *conn,
  7938. int opcode,
  7939. const char *data,
  7940. size_t dataLen)
  7941. {
  7942. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7943. }
  7944. static void
  7945. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7946. {
  7947. size_t i = 0;
  7948. i = 0;
  7949. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7950. /* Convert in 32 bit words, if data is 4 byte aligned */
  7951. while (i < (in_len - 3)) {
  7952. *(uint32_t *)(void *)(out + i) =
  7953. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7954. i += 4;
  7955. }
  7956. }
  7957. if (i != in_len) {
  7958. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7959. while (i < in_len) {
  7960. *(uint8_t *)(void *)(out + i) =
  7961. *(uint8_t *)(void *)(in + i)
  7962. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7963. i++;
  7964. }
  7965. }
  7966. }
  7967. int
  7968. mg_websocket_client_write(struct mg_connection *conn,
  7969. int opcode,
  7970. const char *data,
  7971. size_t dataLen)
  7972. {
  7973. int retval = -1;
  7974. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7975. uint32_t masking_key = (uint32_t)get_random();
  7976. if (masked_data == NULL) {
  7977. /* Return -1 in an error case */
  7978. mg_cry(conn,
  7979. "Cannot allocate buffer for masked websocket response: "
  7980. "Out of memory");
  7981. return -1;
  7982. }
  7983. mask_data(data, dataLen, masking_key, masked_data);
  7984. retval = mg_websocket_write_exec(
  7985. conn, opcode, masked_data, dataLen, masking_key);
  7986. mg_free(masked_data);
  7987. return retval;
  7988. }
  7989. static void
  7990. handle_websocket_request(struct mg_connection *conn,
  7991. const char *path,
  7992. int is_callback_resource,
  7993. mg_websocket_connect_handler ws_connect_handler,
  7994. mg_websocket_ready_handler ws_ready_handler,
  7995. mg_websocket_data_handler ws_data_handler,
  7996. mg_websocket_close_handler ws_close_handler,
  7997. void *cbData)
  7998. {
  7999. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8000. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8001. int lua_websock = 0;
  8002. #if !defined(USE_LUA)
  8003. (void)path;
  8004. #endif
  8005. /* Step 1: Check websocket protocol version. */
  8006. /* Step 1.1: Check Sec-WebSocket-Key. */
  8007. if (!websock_key) {
  8008. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8009. * requires a Sec-WebSocket-Key header.
  8010. */
  8011. /* It could be the hixie draft version
  8012. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8013. */
  8014. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8015. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8016. char key3[8];
  8017. if ((key1 != NULL) && (key2 != NULL)) {
  8018. /* This version uses 8 byte body data in a GET request */
  8019. conn->content_len = 8;
  8020. if (8 == mg_read(conn, key3, 8)) {
  8021. /* This is the hixie version */
  8022. send_http_error(conn,
  8023. 426,
  8024. "%s",
  8025. "Protocol upgrade to RFC 6455 required");
  8026. return;
  8027. }
  8028. }
  8029. /* This is an unknown version */
  8030. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8031. return;
  8032. }
  8033. /* Step 1.2: Check websocket protocol version. */
  8034. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8035. if (version == NULL || strcmp(version, "13") != 0) {
  8036. /* Reject wrong versions */
  8037. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8038. return;
  8039. }
  8040. /* Step 1.3: Could check for "Host", but we do not really nead this
  8041. * value for anything, so just ignore it. */
  8042. /* Step 2: If a callback is responsible, call it. */
  8043. if (is_callback_resource) {
  8044. if (ws_connect_handler != NULL
  8045. && ws_connect_handler(conn, cbData) != 0) {
  8046. /* C callback has returned non-zero, do not proceed with
  8047. * handshake.
  8048. */
  8049. /* Note that C callbacks are no longer called when Lua is
  8050. * responsible, so C can no longer filter callbacks for Lua. */
  8051. return;
  8052. }
  8053. }
  8054. #if defined(USE_LUA)
  8055. /* Step 3: No callback. Check if Lua is responsible. */
  8056. else {
  8057. /* Step 3.1: Check if Lua is responsible. */
  8058. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8059. lua_websock =
  8060. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8061. strlen(
  8062. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8063. path);
  8064. }
  8065. if (lua_websock) {
  8066. /* Step 3.2: Lua is responsible: call it. */
  8067. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8068. if (!conn->lua_websocket_state) {
  8069. /* Lua rejected the new client */
  8070. return;
  8071. }
  8072. }
  8073. }
  8074. #endif
  8075. /* Step 4: Check if there is a responsible websocket handler. */
  8076. if (!is_callback_resource && !lua_websock) {
  8077. /* There is no callback, an Lua is not responsible either. */
  8078. /* Reply with a 404 Not Found or with nothing at all?
  8079. * TODO (mid): check the websocket standards, how to reply to
  8080. * requests to invalid websocket addresses. */
  8081. send_http_error(conn, 404, "%s", "Not found");
  8082. return;
  8083. }
  8084. /* Step 5: The websocket connection has been accepted */
  8085. if (!send_websocket_handshake(conn, websock_key)) {
  8086. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8087. return;
  8088. }
  8089. /* Step 6: Call the ready handler */
  8090. if (is_callback_resource) {
  8091. if (ws_ready_handler != NULL) {
  8092. ws_ready_handler(conn, cbData);
  8093. }
  8094. #if defined(USE_LUA)
  8095. } else if (lua_websock) {
  8096. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8097. /* the ready handler returned false */
  8098. return;
  8099. }
  8100. #endif
  8101. }
  8102. /* Step 7: Enter the read loop */
  8103. if (is_callback_resource) {
  8104. read_websocket(conn, ws_data_handler, cbData);
  8105. #if defined(USE_LUA)
  8106. } else if (lua_websock) {
  8107. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8108. #endif
  8109. }
  8110. /* Step 8: Call the close handler */
  8111. if (ws_close_handler) {
  8112. ws_close_handler(conn, cbData);
  8113. }
  8114. }
  8115. static int
  8116. is_websocket_protocol(const struct mg_connection *conn)
  8117. {
  8118. const char *upgrade, *connection;
  8119. /* A websocket protocoll has the following HTTP headers:
  8120. *
  8121. * Connection: Upgrade
  8122. * Upgrade: Websocket
  8123. */
  8124. upgrade = mg_get_header(conn, "Upgrade");
  8125. if (upgrade == NULL) {
  8126. return 0; /* fail early, don't waste time checking other header
  8127. * fields
  8128. */
  8129. }
  8130. if (!mg_strcasestr(upgrade, "websocket")) {
  8131. return 0;
  8132. }
  8133. connection = mg_get_header(conn, "Connection");
  8134. if (connection == NULL) {
  8135. return 0;
  8136. }
  8137. if (!mg_strcasestr(connection, "upgrade")) {
  8138. return 0;
  8139. }
  8140. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8141. * "Sec-WebSocket-Version" are also required.
  8142. * Don't check them here, since even an unsupported websocket protocol
  8143. * request still IS a websocket request (in contrast to a standard HTTP
  8144. * request). It will fail later in handle_websocket_request.
  8145. */
  8146. return 1;
  8147. }
  8148. #endif /* !USE_WEBSOCKET */
  8149. static int
  8150. isbyte(int n)
  8151. {
  8152. return n >= 0 && n <= 255;
  8153. }
  8154. static int
  8155. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8156. {
  8157. int n, a, b, c, d, slash = 32, len = 0;
  8158. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8159. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8160. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8161. && slash < 33) {
  8162. len = n;
  8163. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8164. | (uint32_t)d;
  8165. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8166. }
  8167. return len;
  8168. }
  8169. static int
  8170. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8171. {
  8172. int throttle = 0;
  8173. struct vec vec, val;
  8174. uint32_t net, mask;
  8175. char mult;
  8176. double v;
  8177. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8178. mult = ',';
  8179. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8180. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8181. && mult != ',')) {
  8182. continue;
  8183. }
  8184. v *= (lowercase(&mult) == 'k')
  8185. ? 1024
  8186. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8187. if (vec.len == 1 && vec.ptr[0] == '*') {
  8188. throttle = (int)v;
  8189. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8190. if ((remote_ip & mask) == net) {
  8191. throttle = (int)v;
  8192. }
  8193. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8194. throttle = (int)v;
  8195. }
  8196. }
  8197. return throttle;
  8198. }
  8199. static uint32_t
  8200. get_remote_ip(const struct mg_connection *conn)
  8201. {
  8202. if (!conn) {
  8203. return 0;
  8204. }
  8205. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8206. }
  8207. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8208. #include "handle_form.inl"
  8209. #if defined(MG_LEGACY_INTERFACE)
  8210. /* Implement the deprecated mg_upload function by calling the new
  8211. * mg_handle_form_request function. While mg_upload could only handle
  8212. * HTML forms sent as POST request in multipart/form-data format
  8213. * containing only file input elements, mg_handle_form_request can
  8214. * handle all form input elements and all standard request methods. */
  8215. struct mg_upload_user_data {
  8216. struct mg_connection *conn;
  8217. const char *destination_dir;
  8218. int num_uploaded_files;
  8219. };
  8220. /* Helper function for deprecated mg_upload. */
  8221. static int
  8222. mg_upload_field_found(const char *key,
  8223. const char *filename,
  8224. char *path,
  8225. size_t pathlen,
  8226. void *user_data)
  8227. {
  8228. int truncated = 0;
  8229. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8230. (void)key;
  8231. if (!filename) {
  8232. mg_cry(fud->conn, "%s: No filename set", __func__);
  8233. return FORM_FIELD_STORAGE_ABORT;
  8234. }
  8235. mg_snprintf(fud->conn,
  8236. &truncated,
  8237. path,
  8238. pathlen - 1,
  8239. "%s/%s",
  8240. fud->destination_dir,
  8241. filename);
  8242. if (!truncated) {
  8243. mg_cry(fud->conn, "%s: File path too long", __func__);
  8244. return FORM_FIELD_STORAGE_ABORT;
  8245. }
  8246. return FORM_FIELD_STORAGE_STORE;
  8247. }
  8248. /* Helper function for deprecated mg_upload. */
  8249. static int
  8250. mg_upload_field_get(const char *key,
  8251. const char *value,
  8252. size_t value_size,
  8253. void *user_data)
  8254. {
  8255. /* Function should never be called */
  8256. (void)key;
  8257. (void)value;
  8258. (void)value_size;
  8259. (void)user_data;
  8260. return 0;
  8261. }
  8262. /* Helper function for deprecated mg_upload. */
  8263. static int
  8264. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8265. {
  8266. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8267. (void)file_size;
  8268. fud->num_uploaded_files++;
  8269. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8270. return 0;
  8271. }
  8272. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8273. int
  8274. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8275. {
  8276. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8277. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8278. mg_upload_field_get,
  8279. mg_upload_field_stored,
  8280. 0};
  8281. int ret;
  8282. fdh.user_data = (void *)&fud;
  8283. ret = mg_handle_form_request(conn, &fdh);
  8284. if (ret < 0) {
  8285. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8286. }
  8287. return fud.num_uploaded_files;
  8288. }
  8289. #endif
  8290. static int
  8291. get_first_ssl_listener_index(const struct mg_context *ctx)
  8292. {
  8293. unsigned int i;
  8294. int idx = -1;
  8295. if (ctx) {
  8296. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8297. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8298. }
  8299. }
  8300. return idx;
  8301. }
  8302. static void
  8303. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8304. {
  8305. char host[1025];
  8306. const char *host_header;
  8307. size_t hostlen;
  8308. host_header = mg_get_header(conn, "Host");
  8309. hostlen = sizeof(host);
  8310. if (host_header != NULL) {
  8311. char *pos;
  8312. mg_strlcpy(host, host_header, hostlen);
  8313. host[hostlen - 1] = '\0';
  8314. pos = strchr(host, ':');
  8315. if (pos != NULL) {
  8316. *pos = '\0';
  8317. }
  8318. } else {
  8319. /* Cannot get host from the Host: header.
  8320. * Fallback to our IP address. */
  8321. if (conn) {
  8322. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8323. }
  8324. }
  8325. /* Send host, port, uri and (if it exists) ?query_string */
  8326. if (conn) {
  8327. mg_printf(conn,
  8328. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8329. host,
  8330. #if defined(USE_IPV6)
  8331. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8332. == AF_INET6)
  8333. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8334. .lsa.sin6.sin6_port)
  8335. :
  8336. #endif
  8337. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8338. .lsa.sin.sin_port),
  8339. conn->request_info.local_uri,
  8340. (conn->request_info.query_string == NULL) ? "" : "?",
  8341. (conn->request_info.query_string == NULL)
  8342. ? ""
  8343. : conn->request_info.query_string);
  8344. }
  8345. }
  8346. static void
  8347. mg_set_handler_type(struct mg_context *ctx,
  8348. const char *uri,
  8349. int handler_type,
  8350. int is_delete_request,
  8351. mg_request_handler handler,
  8352. mg_websocket_connect_handler connect_handler,
  8353. mg_websocket_ready_handler ready_handler,
  8354. mg_websocket_data_handler data_handler,
  8355. mg_websocket_close_handler close_handler,
  8356. mg_authorization_handler auth_handler,
  8357. void *cbdata)
  8358. {
  8359. struct mg_handler_info *tmp_rh, **lastref;
  8360. size_t urilen = strlen(uri);
  8361. if (handler_type == WEBSOCKET_HANDLER) {
  8362. /* assert(handler == NULL); */
  8363. /* assert(is_delete_request || connect_handler!=NULL ||
  8364. * ready_handler!=NULL || data_handler!=NULL ||
  8365. * close_handler!=NULL);
  8366. */
  8367. /* assert(auth_handler == NULL); */
  8368. if (handler != NULL) {
  8369. return;
  8370. }
  8371. if (!is_delete_request && connect_handler == NULL
  8372. && ready_handler == NULL
  8373. && data_handler == NULL
  8374. && close_handler == NULL) {
  8375. return;
  8376. }
  8377. if (auth_handler != NULL) {
  8378. return;
  8379. }
  8380. } else if (handler_type == REQUEST_HANDLER) {
  8381. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8382. * data_handler==NULL && close_handler==NULL); */
  8383. /* assert(is_delete_request || (handler!=NULL));
  8384. */
  8385. /* assert(auth_handler == NULL); */
  8386. if (connect_handler != NULL || ready_handler != NULL
  8387. || data_handler != NULL
  8388. || close_handler != NULL) {
  8389. return;
  8390. }
  8391. if (!is_delete_request && (handler == NULL)) {
  8392. return;
  8393. }
  8394. if (auth_handler != NULL) {
  8395. return;
  8396. }
  8397. } else { /* AUTH_HANDLER */
  8398. /* assert(handler == NULL); */
  8399. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8400. * data_handler==NULL && close_handler==NULL); */
  8401. /* assert(auth_handler != NULL); */
  8402. if (handler != NULL) {
  8403. return;
  8404. }
  8405. if (connect_handler != NULL || ready_handler != NULL
  8406. || data_handler != NULL
  8407. || close_handler != NULL) {
  8408. return;
  8409. }
  8410. if (!is_delete_request && (auth_handler == NULL)) {
  8411. return;
  8412. }
  8413. }
  8414. if (!ctx) {
  8415. return;
  8416. }
  8417. mg_lock_context(ctx);
  8418. /* first try to find an existing handler */
  8419. lastref = &(ctx->handlers);
  8420. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8421. if (tmp_rh->handler_type == handler_type) {
  8422. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8423. if (!is_delete_request) {
  8424. /* update existing handler */
  8425. if (handler_type == REQUEST_HANDLER) {
  8426. tmp_rh->handler = handler;
  8427. } else if (handler_type == WEBSOCKET_HANDLER) {
  8428. tmp_rh->connect_handler = connect_handler;
  8429. tmp_rh->ready_handler = ready_handler;
  8430. tmp_rh->data_handler = data_handler;
  8431. tmp_rh->close_handler = close_handler;
  8432. } else { /* AUTH_HANDLER */
  8433. tmp_rh->auth_handler = auth_handler;
  8434. }
  8435. tmp_rh->cbdata = cbdata;
  8436. } else {
  8437. /* remove existing handler */
  8438. *lastref = tmp_rh->next;
  8439. mg_free(tmp_rh->uri);
  8440. mg_free(tmp_rh);
  8441. }
  8442. mg_unlock_context(ctx);
  8443. return;
  8444. }
  8445. }
  8446. lastref = &(tmp_rh->next);
  8447. }
  8448. if (is_delete_request) {
  8449. /* no handler to set, this was a remove request to a non-existing
  8450. * handler */
  8451. mg_unlock_context(ctx);
  8452. return;
  8453. }
  8454. tmp_rh =
  8455. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8456. if (tmp_rh == NULL) {
  8457. mg_unlock_context(ctx);
  8458. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8459. return;
  8460. }
  8461. tmp_rh->uri = mg_strdup(uri);
  8462. if (!tmp_rh->uri) {
  8463. mg_unlock_context(ctx);
  8464. mg_free(tmp_rh);
  8465. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8466. return;
  8467. }
  8468. tmp_rh->uri_len = urilen;
  8469. if (handler_type == REQUEST_HANDLER) {
  8470. tmp_rh->handler = handler;
  8471. } else if (handler_type == WEBSOCKET_HANDLER) {
  8472. tmp_rh->connect_handler = connect_handler;
  8473. tmp_rh->ready_handler = ready_handler;
  8474. tmp_rh->data_handler = data_handler;
  8475. tmp_rh->close_handler = close_handler;
  8476. } else { /* AUTH_HANDLER */
  8477. tmp_rh->auth_handler = auth_handler;
  8478. }
  8479. tmp_rh->cbdata = cbdata;
  8480. tmp_rh->handler_type = handler_type;
  8481. tmp_rh->next = NULL;
  8482. *lastref = tmp_rh;
  8483. mg_unlock_context(ctx);
  8484. }
  8485. void
  8486. mg_set_request_handler(struct mg_context *ctx,
  8487. const char *uri,
  8488. mg_request_handler handler,
  8489. void *cbdata)
  8490. {
  8491. mg_set_handler_type(ctx,
  8492. uri,
  8493. REQUEST_HANDLER,
  8494. handler == NULL,
  8495. handler,
  8496. NULL,
  8497. NULL,
  8498. NULL,
  8499. NULL,
  8500. NULL,
  8501. cbdata);
  8502. }
  8503. void
  8504. mg_set_websocket_handler(struct mg_context *ctx,
  8505. const char *uri,
  8506. mg_websocket_connect_handler connect_handler,
  8507. mg_websocket_ready_handler ready_handler,
  8508. mg_websocket_data_handler data_handler,
  8509. mg_websocket_close_handler close_handler,
  8510. void *cbdata)
  8511. {
  8512. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8513. && (data_handler == NULL)
  8514. && (close_handler == NULL);
  8515. mg_set_handler_type(ctx,
  8516. uri,
  8517. WEBSOCKET_HANDLER,
  8518. is_delete_request,
  8519. NULL,
  8520. connect_handler,
  8521. ready_handler,
  8522. data_handler,
  8523. close_handler,
  8524. NULL,
  8525. cbdata);
  8526. }
  8527. void
  8528. mg_set_auth_handler(struct mg_context *ctx,
  8529. const char *uri,
  8530. mg_request_handler handler,
  8531. void *cbdata)
  8532. {
  8533. mg_set_handler_type(ctx,
  8534. uri,
  8535. AUTH_HANDLER,
  8536. handler == NULL,
  8537. NULL,
  8538. NULL,
  8539. NULL,
  8540. NULL,
  8541. NULL,
  8542. handler,
  8543. cbdata);
  8544. }
  8545. static int
  8546. get_request_handler(struct mg_connection *conn,
  8547. int handler_type,
  8548. mg_request_handler *handler,
  8549. mg_websocket_connect_handler *connect_handler,
  8550. mg_websocket_ready_handler *ready_handler,
  8551. mg_websocket_data_handler *data_handler,
  8552. mg_websocket_close_handler *close_handler,
  8553. mg_authorization_handler *auth_handler,
  8554. void **cbdata)
  8555. {
  8556. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8557. if (request_info) {
  8558. const char *uri = request_info->local_uri;
  8559. size_t urilen = strlen(uri);
  8560. struct mg_handler_info *tmp_rh;
  8561. if (!conn || !conn->ctx) {
  8562. return 0;
  8563. }
  8564. mg_lock_context(conn->ctx);
  8565. /* first try for an exact match */
  8566. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8567. tmp_rh = tmp_rh->next) {
  8568. if (tmp_rh->handler_type == handler_type) {
  8569. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8570. if (handler_type == WEBSOCKET_HANDLER) {
  8571. *connect_handler = tmp_rh->connect_handler;
  8572. *ready_handler = tmp_rh->ready_handler;
  8573. *data_handler = tmp_rh->data_handler;
  8574. *close_handler = tmp_rh->close_handler;
  8575. } else if (handler_type == REQUEST_HANDLER) {
  8576. *handler = tmp_rh->handler;
  8577. } else { /* AUTH_HANDLER */
  8578. *auth_handler = tmp_rh->auth_handler;
  8579. }
  8580. *cbdata = tmp_rh->cbdata;
  8581. mg_unlock_context(conn->ctx);
  8582. return 1;
  8583. }
  8584. }
  8585. }
  8586. /* next try for a partial match, we will accept uri/something */
  8587. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8588. tmp_rh = tmp_rh->next) {
  8589. if (tmp_rh->handler_type == handler_type) {
  8590. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8591. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8592. if (handler_type == WEBSOCKET_HANDLER) {
  8593. *connect_handler = tmp_rh->connect_handler;
  8594. *ready_handler = tmp_rh->ready_handler;
  8595. *data_handler = tmp_rh->data_handler;
  8596. *close_handler = tmp_rh->close_handler;
  8597. } else if (handler_type == REQUEST_HANDLER) {
  8598. *handler = tmp_rh->handler;
  8599. } else { /* AUTH_HANDLER */
  8600. *auth_handler = tmp_rh->auth_handler;
  8601. }
  8602. *cbdata = tmp_rh->cbdata;
  8603. mg_unlock_context(conn->ctx);
  8604. return 1;
  8605. }
  8606. }
  8607. }
  8608. /* finally try for pattern match */
  8609. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8610. tmp_rh = tmp_rh->next) {
  8611. if (tmp_rh->handler_type == handler_type) {
  8612. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8613. if (handler_type == WEBSOCKET_HANDLER) {
  8614. *connect_handler = tmp_rh->connect_handler;
  8615. *ready_handler = tmp_rh->ready_handler;
  8616. *data_handler = tmp_rh->data_handler;
  8617. *close_handler = tmp_rh->close_handler;
  8618. } else if (handler_type == REQUEST_HANDLER) {
  8619. *handler = tmp_rh->handler;
  8620. } else { /* AUTH_HANDLER */
  8621. *auth_handler = tmp_rh->auth_handler;
  8622. }
  8623. *cbdata = tmp_rh->cbdata;
  8624. mg_unlock_context(conn->ctx);
  8625. return 1;
  8626. }
  8627. }
  8628. }
  8629. mg_unlock_context(conn->ctx);
  8630. }
  8631. return 0; /* none found */
  8632. }
  8633. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8634. static int
  8635. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8636. void *cbdata)
  8637. {
  8638. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8639. if (pcallbacks->websocket_connect) {
  8640. return pcallbacks->websocket_connect(conn);
  8641. }
  8642. /* No handler set - assume "OK" */
  8643. return 0;
  8644. }
  8645. static void
  8646. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8647. {
  8648. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8649. if (pcallbacks->websocket_ready) {
  8650. pcallbacks->websocket_ready(conn);
  8651. }
  8652. }
  8653. static int
  8654. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8655. int bits,
  8656. char *data,
  8657. size_t len,
  8658. void *cbdata)
  8659. {
  8660. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8661. if (pcallbacks->websocket_data) {
  8662. return pcallbacks->websocket_data(conn, bits, data, len);
  8663. }
  8664. /* No handler set - assume "OK" */
  8665. return 1;
  8666. }
  8667. #endif
  8668. /* This is the heart of the Civetweb's logic.
  8669. * This function is called when the request is read, parsed and validated,
  8670. * and Civetweb must decide what action to take: serve a file, or
  8671. * a directory, or call embedded function, etcetera. */
  8672. static void
  8673. handle_request(struct mg_connection *conn)
  8674. {
  8675. if (conn) {
  8676. struct mg_request_info *ri = &conn->request_info;
  8677. char path[PATH_MAX];
  8678. int uri_len, ssl_index;
  8679. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8680. is_put_or_delete_request = 0, is_callback_resource = 0;
  8681. int i;
  8682. struct file file = STRUCT_FILE_INITIALIZER;
  8683. mg_request_handler callback_handler = NULL;
  8684. mg_websocket_connect_handler ws_connect_handler = NULL;
  8685. mg_websocket_ready_handler ws_ready_handler = NULL;
  8686. mg_websocket_data_handler ws_data_handler = NULL;
  8687. mg_websocket_close_handler ws_close_handler = NULL;
  8688. void *callback_data = NULL;
  8689. mg_authorization_handler auth_handler = NULL;
  8690. void *auth_callback_data = NULL;
  8691. #if !defined(NO_FILES)
  8692. time_t curtime = time(NULL);
  8693. char date[64];
  8694. #endif
  8695. path[0] = 0;
  8696. if (!ri) {
  8697. return;
  8698. }
  8699. /* 1. get the request url */
  8700. /* 1.1. split into url and query string */
  8701. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8702. != NULL) {
  8703. *((char *)conn->request_info.query_string++) = '\0';
  8704. }
  8705. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8706. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8707. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8708. if (ssl_index >= 0) {
  8709. redirect_to_https_port(conn, ssl_index);
  8710. } else {
  8711. /* A http to https forward port has been specified,
  8712. * but no https port to forward to. */
  8713. send_http_error(conn,
  8714. 503,
  8715. "%s",
  8716. "Error: SSL forward not configured properly");
  8717. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8718. }
  8719. return;
  8720. }
  8721. uri_len = (int)strlen(ri->local_uri);
  8722. /* 1.3. decode url (if config says so) */
  8723. if (should_decode_url(conn)) {
  8724. mg_url_decode(
  8725. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8726. }
  8727. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8728. * not possible */
  8729. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8730. /* step 1. completed, the url is known now */
  8731. DEBUG_TRACE("URL: %s", ri->local_uri);
  8732. /* 3. if this ip has limited speed, set it for this connection */
  8733. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8734. get_remote_ip(conn),
  8735. ri->local_uri);
  8736. /* 4. call a "handle everything" callback, if registered */
  8737. if (conn->ctx->callbacks.begin_request != NULL) {
  8738. /* Note that since V1.7 the "begin_request" function is called
  8739. * before an authorization check. If an authorization check is
  8740. * required, use a request_handler instead. */
  8741. i = conn->ctx->callbacks.begin_request(conn);
  8742. if (i > 0) {
  8743. /* callback already processed the request. Store the
  8744. return value as a status code for the access log. */
  8745. conn->status_code = i;
  8746. return;
  8747. } else if (i == 0) {
  8748. /* civetweb should process the request */
  8749. } else {
  8750. /* unspecified - may change with the next version */
  8751. return;
  8752. }
  8753. }
  8754. /* request not yet handled by a handler or redirect, so the request
  8755. * is processed here */
  8756. /* 5. interpret the url to find out how the request must be handled
  8757. */
  8758. /* 5.1. first test, if the request targets the regular http(s)://
  8759. * protocol namespace or the websocket ws(s):// protocol namespace.
  8760. */
  8761. is_websocket_request = is_websocket_protocol(conn);
  8762. /* 5.2. check if the request will be handled by a callback */
  8763. if (get_request_handler(conn,
  8764. is_websocket_request ? WEBSOCKET_HANDLER
  8765. : REQUEST_HANDLER,
  8766. &callback_handler,
  8767. &ws_connect_handler,
  8768. &ws_ready_handler,
  8769. &ws_data_handler,
  8770. &ws_close_handler,
  8771. NULL,
  8772. &callback_data)) {
  8773. /* 5.2.1. A callback will handle this request. All requests
  8774. * handled
  8775. * by a callback have to be considered as requests to a script
  8776. * resource. */
  8777. is_callback_resource = 1;
  8778. is_script_resource = 1;
  8779. is_put_or_delete_request = is_put_or_delete_method(conn);
  8780. } else {
  8781. no_callback_resource:
  8782. /* 5.2.2. No callback is responsible for this request. The URI
  8783. * addresses a file based resource (static content or Lua/cgi
  8784. * scripts in the file system). */
  8785. is_callback_resource = 0;
  8786. interpret_uri(conn,
  8787. path,
  8788. sizeof(path),
  8789. &file,
  8790. &is_found,
  8791. &is_script_resource,
  8792. &is_websocket_request,
  8793. &is_put_or_delete_request);
  8794. }
  8795. /* 6. authorization check */
  8796. /* 6.1. a custom authorization handler is installed */
  8797. if (get_request_handler(conn,
  8798. AUTH_HANDLER,
  8799. NULL,
  8800. NULL,
  8801. NULL,
  8802. NULL,
  8803. NULL,
  8804. &auth_handler,
  8805. &auth_callback_data)) {
  8806. if (!auth_handler(conn, auth_callback_data)) {
  8807. return;
  8808. }
  8809. } else if (is_put_or_delete_request && !is_script_resource
  8810. && !is_callback_resource) {
  8811. /* 6.2. this request is a PUT/DELETE to a real file */
  8812. /* 6.2.1. thus, the server must have real files */
  8813. #if defined(NO_FILES)
  8814. if (1) {
  8815. #else
  8816. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8817. #endif
  8818. /* This server does not have any real files, thus the
  8819. * PUT/DELETE methods are not valid. */
  8820. send_http_error(conn,
  8821. 405,
  8822. "%s method not allowed",
  8823. conn->request_info.request_method);
  8824. return;
  8825. }
  8826. #if !defined(NO_FILES)
  8827. /* 6.2.2. Check if put authorization for static files is
  8828. * available.
  8829. */
  8830. if (!is_authorized_for_put(conn)) {
  8831. send_authorization_request(conn);
  8832. return;
  8833. }
  8834. #endif
  8835. } else {
  8836. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8837. * or it is a PUT or DELETE request to a resource that does not
  8838. * correspond to a file. Check authorization. */
  8839. if (!check_authorization(conn, path)) {
  8840. send_authorization_request(conn);
  8841. return;
  8842. }
  8843. }
  8844. /* request is authorized or does not need authorization */
  8845. /* 7. check if there are request handlers for this uri */
  8846. if (is_callback_resource) {
  8847. if (!is_websocket_request) {
  8848. i = callback_handler(conn, callback_data);
  8849. if (i > 0) {
  8850. /* Do nothing, callback has served the request. Store
  8851. * the
  8852. * return value as status code for the log and discard
  8853. * all
  8854. * data from the client not used by the callback. */
  8855. conn->status_code = i;
  8856. discard_unread_request_data(conn);
  8857. } else {
  8858. /* TODO (high): what if the handler did NOT handle the
  8859. * request */
  8860. /* The last version did handle this as a file request,
  8861. * but
  8862. * since a file request is not always a script resource,
  8863. * the authorization check might be different */
  8864. interpret_uri(conn,
  8865. path,
  8866. sizeof(path),
  8867. &file,
  8868. &is_found,
  8869. &is_script_resource,
  8870. &is_websocket_request,
  8871. &is_put_or_delete_request);
  8872. callback_handler = NULL;
  8873. /* TODO (very low): goto is deprecated but for the
  8874. * moment,
  8875. * a goto is simpler than some curious loop. */
  8876. /* The situation "callback does not handle the request"
  8877. * needs to be reconsidered anyway. */
  8878. goto no_callback_resource;
  8879. }
  8880. } else {
  8881. #if defined(USE_WEBSOCKET)
  8882. handle_websocket_request(conn,
  8883. path,
  8884. is_callback_resource,
  8885. ws_connect_handler,
  8886. ws_ready_handler,
  8887. ws_data_handler,
  8888. ws_close_handler,
  8889. callback_data);
  8890. #endif
  8891. }
  8892. return;
  8893. }
  8894. /* 8. handle websocket requests */
  8895. #if defined(USE_WEBSOCKET)
  8896. if (is_websocket_request) {
  8897. if (is_script_resource) {
  8898. /* Websocket Lua script */
  8899. handle_websocket_request(conn,
  8900. path,
  8901. 0 /* Lua Script */,
  8902. NULL,
  8903. NULL,
  8904. NULL,
  8905. NULL,
  8906. &conn->ctx->callbacks);
  8907. } else {
  8908. #if defined(MG_LEGACY_INTERFACE)
  8909. handle_websocket_request(
  8910. conn,
  8911. path,
  8912. !is_script_resource /* could be deprecated global callback */,
  8913. deprecated_websocket_connect_wrapper,
  8914. deprecated_websocket_ready_wrapper,
  8915. deprecated_websocket_data_wrapper,
  8916. NULL,
  8917. &conn->ctx->callbacks);
  8918. #else
  8919. send_http_error(conn, 404, "%s", "Not found");
  8920. #endif
  8921. }
  8922. return;
  8923. } else
  8924. #endif
  8925. #if defined(NO_FILES)
  8926. /* 9a. In case the server uses only callbacks, this uri is
  8927. * unknown.
  8928. * Then, all request handling ends here. */
  8929. send_http_error(conn, 404, "%s", "Not Found");
  8930. #else
  8931. /* 9b. This request is either for a static file or resource handled
  8932. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8933. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8934. send_http_error(conn, 404, "%s", "Not Found");
  8935. return;
  8936. }
  8937. /* 10. File is handled by a script. */
  8938. if (is_script_resource) {
  8939. handle_file_based_request(conn, path, &file);
  8940. return;
  8941. }
  8942. /* 11. Handle put/delete/mkcol requests */
  8943. if (is_put_or_delete_request) {
  8944. /* 11.1. PUT method */
  8945. if (!strcmp(ri->request_method, "PUT")) {
  8946. put_file(conn, path);
  8947. return;
  8948. }
  8949. /* 11.2. DELETE method */
  8950. if (!strcmp(ri->request_method, "DELETE")) {
  8951. delete_file(conn, path);
  8952. return;
  8953. }
  8954. /* 11.3. MKCOL method */
  8955. if (!strcmp(ri->request_method, "MKCOL")) {
  8956. mkcol(conn, path);
  8957. return;
  8958. }
  8959. /* 11.4. PATCH method
  8960. * This method is not supported for static resources,
  8961. * only for scripts (Lua, CGI) and callbacks. */
  8962. send_http_error(conn,
  8963. 405,
  8964. "%s method not allowed",
  8965. conn->request_info.request_method);
  8966. return;
  8967. }
  8968. /* 11. File does not exist, or it was configured that it should be
  8969. * hidden */
  8970. if (!is_found || (must_hide_file(conn, path))) {
  8971. send_http_error(conn, 404, "%s", "Not found");
  8972. return;
  8973. }
  8974. /* 12. Directory uris should end with a slash */
  8975. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8976. gmt_time_string(date, sizeof(date), &curtime);
  8977. mg_printf(conn,
  8978. "HTTP/1.1 301 Moved Permanently\r\n"
  8979. "Location: %s/\r\n"
  8980. "Date: %s\r\n"
  8981. /* "Cache-Control: private\r\n" (= default) */
  8982. "Content-Length: 0\r\n"
  8983. "Connection: %s\r\n\r\n",
  8984. ri->request_uri,
  8985. date,
  8986. suggest_connection_header(conn));
  8987. return;
  8988. }
  8989. /* 13. Handle other methods than GET/HEAD */
  8990. /* 13.1. Handle PROPFIND */
  8991. if (!strcmp(ri->request_method, "PROPFIND")) {
  8992. handle_propfind(conn, path, &file);
  8993. return;
  8994. }
  8995. /* 13.2. Handle OPTIONS for files */
  8996. if (!strcmp(ri->request_method, "OPTIONS")) {
  8997. /* This standard handler is only used for real files.
  8998. * Scripts should support the OPTIONS method themselves, to allow a
  8999. * maximum flexibility.
  9000. * Lua and CGI scripts may fully support CORS this way (including
  9001. * preflights). */
  9002. send_options(conn);
  9003. return;
  9004. }
  9005. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9006. if (0 != strcmp(ri->request_method, "GET")
  9007. && 0 != strcmp(ri->request_method, "HEAD")) {
  9008. send_http_error(conn,
  9009. 405,
  9010. "%s method not allowed",
  9011. conn->request_info.request_method);
  9012. return;
  9013. }
  9014. /* 14. directories */
  9015. if (file.is_directory) {
  9016. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9017. /* 14.1. use a substitute file */
  9018. /* TODO (high): substitute index may be a script resource.
  9019. * define what should be possible in this case. */
  9020. } else {
  9021. /* 14.2. no substitute file */
  9022. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9023. "yes")) {
  9024. handle_directory_request(conn, path);
  9025. } else {
  9026. send_http_error(conn,
  9027. 403,
  9028. "%s",
  9029. "Error: Directory listing denied");
  9030. }
  9031. return;
  9032. }
  9033. }
  9034. handle_file_based_request(conn, path, &file);
  9035. #endif /* !defined(NO_FILES) */
  9036. #if 0
  9037. /* Perform redirect and auth checks before calling begin_request()
  9038. * handler.
  9039. * Otherwise, begin_request() would need to perform auth checks and
  9040. * redirects. */
  9041. #endif
  9042. }
  9043. return;
  9044. }
  9045. static void
  9046. handle_file_based_request(struct mg_connection *conn,
  9047. const char *path,
  9048. struct file *file)
  9049. {
  9050. if (!conn || !conn->ctx) {
  9051. return;
  9052. }
  9053. if (0) {
  9054. #ifdef USE_LUA
  9055. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9056. strlen(
  9057. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9058. path) > 0) {
  9059. /* Lua server page: an SSI like page containing mostly plain html
  9060. * code
  9061. * plus some tags with server generated contents. */
  9062. handle_lsp_request(conn, path, file, NULL);
  9063. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9064. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9065. path) > 0) {
  9066. /* Lua in-server module script: a CGI like script used to generate
  9067. * the
  9068. * entire reply. */
  9069. mg_exec_lua_script(conn, path, NULL);
  9070. #endif
  9071. #if defined(USE_DUKTAPE)
  9072. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9073. strlen(
  9074. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9075. path) > 0) {
  9076. /* Call duktape to generate the page */
  9077. mg_exec_duktape_script(conn, path);
  9078. #endif
  9079. #if !defined(NO_CGI)
  9080. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9081. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9082. path) > 0) {
  9083. /* CGI scripts may support all HTTP methods */
  9084. handle_cgi_request(conn, path);
  9085. #endif /* !NO_CGI */
  9086. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9087. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9088. path) > 0) {
  9089. handle_ssi_file_request(conn, path, file);
  9090. #if !defined(NO_CACHING)
  9091. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9092. /* Send 304 "Not Modified" - this must not send any body data */
  9093. handle_not_modified_static_file_request(conn, file);
  9094. #endif /* !NO_CACHING */
  9095. } else {
  9096. handle_static_file_request(conn, path, file, NULL);
  9097. }
  9098. }
  9099. static void
  9100. close_all_listening_sockets(struct mg_context *ctx)
  9101. {
  9102. unsigned int i;
  9103. if (!ctx) {
  9104. return;
  9105. }
  9106. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9107. closesocket(ctx->listening_sockets[i].sock);
  9108. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9109. }
  9110. mg_free(ctx->listening_sockets);
  9111. ctx->listening_sockets = NULL;
  9112. mg_free(ctx->listening_socket_fds);
  9113. ctx->listening_socket_fds = NULL;
  9114. }
  9115. /* Valid listening port specification is: [ip_address:]port[s]
  9116. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  9117. * Examples for IPv6: [::]:80, [::1]:80,
  9118. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  9119. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  9120. static int
  9121. parse_port_string(const struct vec *vec, struct socket *so)
  9122. {
  9123. unsigned int a, b, c, d, port;
  9124. int ch, len;
  9125. #if defined(USE_IPV6)
  9126. char buf[100] = {0};
  9127. #endif
  9128. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9129. * Also, all-zeroes in the socket address means binding to all addresses
  9130. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9131. memset(so, 0, sizeof(*so));
  9132. so->lsa.sin.sin_family = AF_INET;
  9133. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9134. == 5) {
  9135. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9136. so->lsa.sin.sin_addr.s_addr =
  9137. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9138. so->lsa.sin.sin_port = htons((uint16_t)port);
  9139. #if defined(USE_IPV6)
  9140. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9141. && mg_inet_pton(
  9142. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9143. /* IPv6 address, examples: see above */
  9144. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9145. */
  9146. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9147. #endif
  9148. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9149. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9150. so->lsa.sin.sin_port = htons((uint16_t)port);
  9151. } else {
  9152. /* Parsing failure. Make port invalid. */
  9153. port = 0;
  9154. len = 0;
  9155. }
  9156. /* sscanf and the option splitting code ensure the following condition
  9157. */
  9158. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9159. return 0;
  9160. }
  9161. ch = vec->ptr[len]; /* Next character after the port number */
  9162. so->is_ssl = (ch == 's');
  9163. so->ssl_redir = (ch == 'r');
  9164. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9165. return is_valid_port(port)
  9166. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9167. }
  9168. static int
  9169. set_ports_option(struct mg_context *ctx)
  9170. {
  9171. const char *list;
  9172. int on = 1;
  9173. #if defined(USE_IPV6)
  9174. int off = 0;
  9175. #endif
  9176. struct vec vec;
  9177. struct socket so, *ptr;
  9178. struct pollfd *pfd;
  9179. union usa usa;
  9180. socklen_t len;
  9181. int portsTotal = 0;
  9182. int portsOk = 0;
  9183. if (!ctx) {
  9184. return 0;
  9185. }
  9186. memset(&so, 0, sizeof(so));
  9187. memset(&usa, 0, sizeof(usa));
  9188. len = sizeof(usa);
  9189. list = ctx->config[LISTENING_PORTS];
  9190. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9191. portsTotal++;
  9192. if (!parse_port_string(&vec, &so)) {
  9193. mg_cry(fc(ctx),
  9194. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9195. (int)vec.len,
  9196. vec.ptr,
  9197. portsTotal,
  9198. "[IP_ADDRESS:]PORT[s|r]");
  9199. continue;
  9200. }
  9201. #if !defined(NO_SSL)
  9202. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9203. mg_cry(fc(ctx),
  9204. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9205. "option set?",
  9206. portsTotal);
  9207. continue;
  9208. }
  9209. #endif
  9210. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9211. == INVALID_SOCKET) {
  9212. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9213. continue;
  9214. }
  9215. #ifdef _WIN32
  9216. /* Windows SO_REUSEADDR lets many procs binds to a
  9217. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9218. * if someone already has the socket -- DTL */
  9219. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9220. * Windows might need a few seconds before
  9221. * the same port can be used again in the
  9222. * same process, so a short Sleep may be
  9223. * required between mg_stop and mg_start.
  9224. */
  9225. if (setsockopt(so.sock,
  9226. SOL_SOCKET,
  9227. SO_EXCLUSIVEADDRUSE,
  9228. (SOCK_OPT_TYPE)&on,
  9229. sizeof(on)) != 0) {
  9230. mg_cry(fc(ctx),
  9231. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9232. portsTotal);
  9233. }
  9234. #else
  9235. if (setsockopt(so.sock,
  9236. SOL_SOCKET,
  9237. SO_REUSEADDR,
  9238. (SOCK_OPT_TYPE)&on,
  9239. sizeof(on)) != 0) {
  9240. mg_cry(fc(ctx),
  9241. "cannot set socket option SO_REUSEADDR (entry %i)",
  9242. portsTotal);
  9243. }
  9244. #endif
  9245. #if defined(USE_IPV6)
  9246. if (so.lsa.sa.sa_family == AF_INET6
  9247. && setsockopt(so.sock,
  9248. IPPROTO_IPV6,
  9249. IPV6_V6ONLY,
  9250. (void *)&off,
  9251. sizeof(off)) != 0) {
  9252. mg_cry(fc(ctx),
  9253. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9254. portsTotal);
  9255. }
  9256. #endif
  9257. if (so.lsa.sa.sa_family == AF_INET) {
  9258. len = sizeof(so.lsa.sin);
  9259. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9260. mg_cry(fc(ctx),
  9261. "cannot bind to %.*s: %d (%s)",
  9262. (int)vec.len,
  9263. vec.ptr,
  9264. (int)ERRNO,
  9265. strerror(errno));
  9266. closesocket(so.sock);
  9267. so.sock = INVALID_SOCKET;
  9268. continue;
  9269. }
  9270. }
  9271. #if defined(USE_IPV6)
  9272. else if (so.lsa.sa.sa_family == AF_INET6) {
  9273. len = sizeof(so.lsa.sin6);
  9274. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9275. mg_cry(fc(ctx),
  9276. "cannot bind to IPv6 %.*s: %d (%s)",
  9277. (int)vec.len,
  9278. vec.ptr,
  9279. (int)ERRNO,
  9280. strerror(errno));
  9281. closesocket(so.sock);
  9282. so.sock = INVALID_SOCKET;
  9283. continue;
  9284. }
  9285. }
  9286. #endif
  9287. else {
  9288. mg_cry(fc(ctx),
  9289. "cannot bind: address family not supported (entry %i)",
  9290. portsTotal);
  9291. continue;
  9292. }
  9293. if (listen(so.sock, SOMAXCONN) != 0) {
  9294. mg_cry(fc(ctx),
  9295. "cannot listen to %.*s: %d (%s)",
  9296. (int)vec.len,
  9297. vec.ptr,
  9298. (int)ERRNO,
  9299. strerror(errno));
  9300. closesocket(so.sock);
  9301. so.sock = INVALID_SOCKET;
  9302. continue;
  9303. }
  9304. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9305. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9306. int err = (int)ERRNO;
  9307. mg_cry(fc(ctx),
  9308. "call to getsockname failed %.*s: %d (%s)",
  9309. (int)vec.len,
  9310. vec.ptr,
  9311. err,
  9312. strerror(errno));
  9313. closesocket(so.sock);
  9314. so.sock = INVALID_SOCKET;
  9315. continue;
  9316. }
  9317. /* Update lsa port in case of random free ports */
  9318. #if defined(USE_IPV6)
  9319. if (so.lsa.sa.sa_family == AF_INET6) {
  9320. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9321. } else
  9322. #endif
  9323. {
  9324. so.lsa.sin.sin_port = usa.sin.sin_port;
  9325. }
  9326. if ((ptr = (struct socket *)
  9327. mg_realloc(ctx->listening_sockets,
  9328. (ctx->num_listening_sockets + 1)
  9329. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9330. mg_cry(fc(ctx), "%s", "Out of memory");
  9331. closesocket(so.sock);
  9332. so.sock = INVALID_SOCKET;
  9333. continue;
  9334. }
  9335. if ((pfd = (struct pollfd *)mg_realloc(
  9336. ctx->listening_socket_fds,
  9337. (ctx->num_listening_sockets + 1)
  9338. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9339. mg_cry(fc(ctx), "%s", "Out of memory");
  9340. closesocket(so.sock);
  9341. so.sock = INVALID_SOCKET;
  9342. mg_free(ptr);
  9343. continue;
  9344. }
  9345. set_close_on_exec(so.sock, fc(ctx));
  9346. ctx->listening_sockets = ptr;
  9347. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9348. ctx->listening_socket_fds = pfd;
  9349. ctx->num_listening_sockets++;
  9350. portsOk++;
  9351. }
  9352. if (portsOk != portsTotal) {
  9353. close_all_listening_sockets(ctx);
  9354. portsOk = 0;
  9355. }
  9356. return portsOk;
  9357. }
  9358. static const char *
  9359. header_val(const struct mg_connection *conn, const char *header)
  9360. {
  9361. const char *header_value;
  9362. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9363. return "-";
  9364. } else {
  9365. return header_value;
  9366. }
  9367. }
  9368. static void
  9369. log_access(const struct mg_connection *conn)
  9370. {
  9371. const struct mg_request_info *ri;
  9372. struct file fi;
  9373. char date[64], src_addr[IP_ADDR_STR_LEN];
  9374. struct tm *tm;
  9375. const char *referer;
  9376. const char *user_agent;
  9377. char buf[4096];
  9378. if (!conn || !conn->ctx) {
  9379. return;
  9380. }
  9381. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9382. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9383. == 0) {
  9384. fi.fp = NULL;
  9385. }
  9386. } else {
  9387. fi.fp = NULL;
  9388. }
  9389. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9390. return;
  9391. }
  9392. tm = localtime(&conn->conn_birth_time);
  9393. if (tm != NULL) {
  9394. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9395. } else {
  9396. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9397. date[sizeof(date) - 1] = '\0';
  9398. }
  9399. ri = &conn->request_info;
  9400. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9401. referer = header_val(conn, "Referer");
  9402. user_agent = header_val(conn, "User-Agent");
  9403. mg_snprintf(conn,
  9404. NULL, /* Ignore truncation in access log */
  9405. buf,
  9406. sizeof(buf),
  9407. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9408. src_addr,
  9409. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9410. date,
  9411. ri->request_method ? ri->request_method : "-",
  9412. ri->request_uri ? ri->request_uri : "-",
  9413. ri->query_string ? "?" : "",
  9414. ri->query_string ? ri->query_string : "",
  9415. ri->http_version,
  9416. conn->status_code,
  9417. conn->num_bytes_sent,
  9418. referer,
  9419. user_agent);
  9420. if (conn->ctx->callbacks.log_access) {
  9421. conn->ctx->callbacks.log_access(conn, buf);
  9422. }
  9423. if (fi.fp) {
  9424. flockfile(fi.fp);
  9425. fprintf(fi.fp, "%s\n", buf);
  9426. fflush(fi.fp);
  9427. funlockfile(fi.fp);
  9428. mg_fclose(&fi);
  9429. }
  9430. }
  9431. /* Verify given socket address against the ACL.
  9432. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9433. */
  9434. static int
  9435. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9436. {
  9437. int allowed, flag;
  9438. uint32_t net, mask;
  9439. struct vec vec;
  9440. if (ctx) {
  9441. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9442. /* If any ACL is set, deny by default */
  9443. allowed = (list == NULL) ? '+' : '-';
  9444. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9445. flag = vec.ptr[0];
  9446. if ((flag != '+' && flag != '-')
  9447. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9448. mg_cry(fc(ctx),
  9449. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9450. __func__);
  9451. return -1;
  9452. }
  9453. if (net == (remote_ip & mask)) {
  9454. allowed = flag;
  9455. }
  9456. }
  9457. return allowed == '+';
  9458. }
  9459. return -1;
  9460. }
  9461. #if !defined(_WIN32)
  9462. static int
  9463. set_uid_option(struct mg_context *ctx)
  9464. {
  9465. struct passwd *pw;
  9466. if (ctx) {
  9467. const char *uid = ctx->config[RUN_AS_USER];
  9468. int success = 0;
  9469. if (uid == NULL) {
  9470. success = 1;
  9471. } else {
  9472. if ((pw = getpwnam(uid)) == NULL) {
  9473. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9474. } else if (setgid(pw->pw_gid) == -1) {
  9475. mg_cry(fc(ctx),
  9476. "%s: setgid(%s): %s",
  9477. __func__,
  9478. uid,
  9479. strerror(errno));
  9480. } else if (setgroups(0, NULL)) {
  9481. mg_cry(fc(ctx),
  9482. "%s: setgroups(): %s",
  9483. __func__,
  9484. strerror(errno));
  9485. } else if (setuid(pw->pw_uid) == -1) {
  9486. mg_cry(fc(ctx),
  9487. "%s: setuid(%s): %s",
  9488. __func__,
  9489. uid,
  9490. strerror(errno));
  9491. } else {
  9492. success = 1;
  9493. }
  9494. }
  9495. return success;
  9496. }
  9497. return 0;
  9498. }
  9499. #endif /* !_WIN32 */
  9500. static void
  9501. tls_dtor(void *key)
  9502. {
  9503. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9504. /* key == pthread_getspecific(sTlsKey); */
  9505. if (tls) {
  9506. if (tls->is_master == 2) {
  9507. tls->is_master = -3; /* Mark memory as dead */
  9508. mg_free(tls);
  9509. }
  9510. }
  9511. pthread_setspecific(sTlsKey, NULL);
  9512. }
  9513. #if !defined(NO_SSL)
  9514. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9515. static unsigned long
  9516. ssl_id_callback(void)
  9517. {
  9518. #ifdef _WIN32
  9519. return GetCurrentThreadId();
  9520. #else
  9521. #ifdef __clang__
  9522. #pragma clang diagnostic push
  9523. #pragma clang diagnostic ignored "-Wunreachable-code"
  9524. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9525. * or not, so one of the two conditions will be unreachable by construction.
  9526. * Unfortunately the C standard does not define a way to check this at
  9527. * compile time, since the #if preprocessor conditions can not use the sizeof
  9528. * operator as an argument. */
  9529. #endif
  9530. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9531. /* This is the problematic case for CRYPTO_set_id_callback:
  9532. * The OS pthread_t can not be cast to unsigned long. */
  9533. struct mg_workerTLS *tls =
  9534. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9535. if (tls == NULL) {
  9536. /* SSL called from an unknown thread: Create some thread index.
  9537. */
  9538. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9539. tls->is_master = -2; /* -2 means "3rd party thread" */
  9540. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9541. pthread_setspecific(sTlsKey, tls);
  9542. }
  9543. return tls->thread_idx;
  9544. } else {
  9545. /* pthread_t may be any data type, so a simple cast to unsigned long
  9546. * can rise a warning/error, depending on the platform.
  9547. * Here memcpy is used as an anything-to-anything cast. */
  9548. unsigned long ret = 0;
  9549. pthread_t t = pthread_self();
  9550. memcpy(&ret, &t, sizeof(pthread_t));
  9551. return ret;
  9552. }
  9553. #ifdef __clang__
  9554. #pragma clang diagnostic pop
  9555. #endif
  9556. #endif
  9557. }
  9558. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9559. static const char *ssl_error(void);
  9560. static int
  9561. refresh_trust(struct mg_connection *conn)
  9562. {
  9563. static int reload_lock = 0;
  9564. static long int data_check = 0;
  9565. struct stat cert_buf;
  9566. long int t;
  9567. char *pem;
  9568. int should_verify_peer;
  9569. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9570. && conn->ctx->callbacks.init_ssl == NULL) {
  9571. return 0;
  9572. }
  9573. t = data_check;
  9574. if (stat(pem, &cert_buf) != -1) {
  9575. t = (long int)cert_buf.st_mtime;
  9576. }
  9577. if (data_check != t) {
  9578. data_check = t;
  9579. should_verify_peer =
  9580. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9581. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9582. == 0);
  9583. if (should_verify_peer) {
  9584. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9585. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9586. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9587. ca_file,
  9588. ca_path) != 1) {
  9589. mg_cry(fc(conn->ctx),
  9590. "SSL_CTX_load_verify_locations error: %s "
  9591. "ssl_verify_peer requires setting "
  9592. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9593. "present in "
  9594. "the .conf file?",
  9595. ssl_error());
  9596. return 0;
  9597. }
  9598. }
  9599. if (!reload_lock) {
  9600. reload_lock = 1;
  9601. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9602. return 0;
  9603. }
  9604. reload_lock = 0;
  9605. }
  9606. }
  9607. /* lock while cert is reloading */
  9608. while (reload_lock) {
  9609. sleep(1);
  9610. }
  9611. return 1;
  9612. }
  9613. static pthread_mutex_t *ssl_mutexes;
  9614. static int
  9615. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9616. {
  9617. int ret, err;
  9618. int short_trust;
  9619. unsigned i;
  9620. if (!conn) {
  9621. return 0;
  9622. }
  9623. short_trust =
  9624. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9625. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9626. if (short_trust) {
  9627. int trust_ret = refresh_trust(conn);
  9628. if (!trust_ret) {
  9629. return trust_ret;
  9630. }
  9631. }
  9632. conn->ssl = SSL_new(s);
  9633. if (conn->ssl == NULL) {
  9634. return 0;
  9635. }
  9636. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9637. if (ret != 1) {
  9638. err = SSL_get_error(conn->ssl, ret);
  9639. (void)err; /* TODO: set some error message */
  9640. SSL_free(conn->ssl);
  9641. conn->ssl = NULL;
  9642. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9643. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9644. ERR_remove_state(0);
  9645. return 0;
  9646. }
  9647. /* SSL functions may fail and require to be called again:
  9648. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9649. * Here "func" could be SSL_connect or SSL_accept. */
  9650. for (i = 0; i <= 16; i *= 2) {
  9651. ret = func(conn->ssl);
  9652. if (ret != 1) {
  9653. err = SSL_get_error(conn->ssl, ret);
  9654. if ((err == SSL_ERROR_WANT_CONNECT)
  9655. || (err == SSL_ERROR_WANT_ACCEPT)) {
  9656. /* Retry */
  9657. mg_sleep(i);
  9658. } else {
  9659. /* This is an error */
  9660. /* TODO: set some error message */
  9661. break;
  9662. }
  9663. } else {
  9664. /* success */
  9665. break;
  9666. }
  9667. }
  9668. if (ret != 1) {
  9669. SSL_free(conn->ssl);
  9670. conn->ssl = NULL;
  9671. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9672. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9673. ERR_remove_state(0);
  9674. return 0;
  9675. }
  9676. return 1;
  9677. }
  9678. /* Return OpenSSL error message (from CRYPTO lib) */
  9679. static const char *
  9680. ssl_error(void)
  9681. {
  9682. unsigned long err;
  9683. err = ERR_get_error();
  9684. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  9685. }
  9686. static void
  9687. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9688. {
  9689. (void)line;
  9690. (void)file;
  9691. if (mode & 1) {
  9692. /* 1 is CRYPTO_LOCK */
  9693. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9694. } else {
  9695. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9696. }
  9697. }
  9698. #if !defined(NO_SSL_DL)
  9699. static void *
  9700. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9701. {
  9702. union {
  9703. void *p;
  9704. void (*fp)(void);
  9705. } u;
  9706. void *dll_handle;
  9707. struct ssl_func *fp;
  9708. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9709. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9710. return NULL;
  9711. }
  9712. for (fp = sw; fp->name != NULL; fp++) {
  9713. #ifdef _WIN32
  9714. /* GetProcAddress() returns pointer to function */
  9715. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9716. #else
  9717. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9718. * pointers to function pointers. We need to use a union to make a
  9719. * cast. */
  9720. u.p = dlsym(dll_handle, fp->name);
  9721. #endif /* _WIN32 */
  9722. if (u.fp == NULL) {
  9723. mg_cry(fc(ctx),
  9724. "%s: %s: cannot find %s",
  9725. __func__,
  9726. dll_name,
  9727. fp->name);
  9728. dlclose(dll_handle);
  9729. return NULL;
  9730. } else {
  9731. fp->ptr = u.fp;
  9732. }
  9733. }
  9734. return dll_handle;
  9735. }
  9736. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9737. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9738. #endif /* NO_SSL_DL */
  9739. #if defined(SSL_ALREADY_INITIALIZED)
  9740. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9741. #else
  9742. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9743. #endif
  9744. static int
  9745. initialize_ssl(struct mg_context *ctx)
  9746. {
  9747. int i;
  9748. size_t size;
  9749. #if !defined(NO_SSL_DL)
  9750. if (!cryptolib_dll_handle) {
  9751. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9752. if (!cryptolib_dll_handle) {
  9753. return 0;
  9754. }
  9755. }
  9756. #endif /* NO_SSL_DL */
  9757. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9758. return 1;
  9759. }
  9760. /* Initialize locking callbacks, needed for thread safety.
  9761. * http://www.openssl.org/support/faq.html#PROG1
  9762. */
  9763. i = CRYPTO_num_locks();
  9764. if (i < 0) {
  9765. i = 0;
  9766. }
  9767. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9768. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9769. mg_cry(fc(ctx),
  9770. "%s: cannot allocate mutexes: %s",
  9771. __func__,
  9772. ssl_error());
  9773. return 0;
  9774. }
  9775. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9776. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9777. }
  9778. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9779. CRYPTO_set_id_callback(&ssl_id_callback);
  9780. return 1;
  9781. }
  9782. static int
  9783. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9784. {
  9785. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9786. mg_cry(fc(ctx),
  9787. "%s: cannot open certificate file %s: %s",
  9788. __func__,
  9789. pem,
  9790. ssl_error());
  9791. return 0;
  9792. }
  9793. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9794. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9795. mg_cry(fc(ctx),
  9796. "%s: cannot open private key file %s: %s",
  9797. __func__,
  9798. pem,
  9799. ssl_error());
  9800. return 0;
  9801. }
  9802. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9803. mg_cry(fc(ctx),
  9804. "%s: certificate and private key do not match: %s",
  9805. __func__,
  9806. pem);
  9807. return 0;
  9808. }
  9809. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9810. mg_cry(fc(ctx),
  9811. "%s: cannot use certificate chain file %s: %s",
  9812. __func__,
  9813. pem,
  9814. ssl_error());
  9815. return 0;
  9816. }
  9817. return 1;
  9818. }
  9819. static long
  9820. ssl_get_protocol(int version_id)
  9821. {
  9822. long ret = SSL_OP_ALL;
  9823. if (version_id > 0)
  9824. ret |= SSL_OP_NO_SSLv2;
  9825. if (version_id > 1)
  9826. ret |= SSL_OP_NO_SSLv3;
  9827. if (version_id > 2)
  9828. ret |= SSL_OP_NO_TLSv1;
  9829. if (version_id > 3)
  9830. ret |= SSL_OP_NO_TLSv1_1;
  9831. return ret;
  9832. }
  9833. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9834. static int
  9835. set_ssl_option(struct mg_context *ctx)
  9836. {
  9837. const char *pem;
  9838. int callback_ret;
  9839. int should_verify_peer;
  9840. const char *ca_path;
  9841. const char *ca_file;
  9842. int use_default_verify_paths;
  9843. int verify_depth;
  9844. time_t now_rt = time(NULL);
  9845. struct timespec now_mt;
  9846. md5_byte_t ssl_context_id[16];
  9847. md5_state_t md5state;
  9848. int protocol_ver;
  9849. /* If PEM file is not specified and the init_ssl callback
  9850. * is not specified, skip SSL initialization. */
  9851. if (!ctx) {
  9852. return 0;
  9853. }
  9854. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9855. && ctx->callbacks.init_ssl == NULL) {
  9856. return 1;
  9857. }
  9858. if (!initialize_ssl(ctx)) {
  9859. return 0;
  9860. }
  9861. #if !defined(NO_SSL_DL)
  9862. if (!ssllib_dll_handle) {
  9863. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9864. if (!ssllib_dll_handle) {
  9865. return 0;
  9866. }
  9867. }
  9868. #endif /* NO_SSL_DL */
  9869. /* Initialize SSL library */
  9870. SSL_library_init();
  9871. SSL_load_error_strings();
  9872. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9873. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9874. return 0;
  9875. }
  9876. SSL_CTX_clear_options(ctx->ssl_ctx,
  9877. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9878. | SSL_OP_NO_TLSv1_1);
  9879. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9880. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9881. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9882. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9883. /* If a callback has been specified, call it. */
  9884. callback_ret =
  9885. (ctx->callbacks.init_ssl == NULL)
  9886. ? 0
  9887. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9888. /* If callback returns 0, civetweb sets up the SSL certificate.
  9889. * If it returns 1, civetweb assumes the calback already did this.
  9890. * If it returns -1, initializing ssl fails. */
  9891. if (callback_ret < 0) {
  9892. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9893. return 0;
  9894. }
  9895. if (callback_ret > 0) {
  9896. if (pem != NULL) {
  9897. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9898. }
  9899. return 1;
  9900. }
  9901. /* Use some UID as session context ID. */
  9902. md5_init(&md5state);
  9903. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9904. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9905. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9906. md5_append(&md5state,
  9907. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9908. strlen(ctx->config[LISTENING_PORTS]));
  9909. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9910. md5_finish(&md5state, ssl_context_id);
  9911. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9912. (const unsigned char *)&ssl_context_id,
  9913. sizeof(ssl_context_id));
  9914. if (pem != NULL) {
  9915. if (!ssl_use_pem_file(ctx, pem)) {
  9916. return 0;
  9917. }
  9918. }
  9919. should_verify_peer =
  9920. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9921. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9922. use_default_verify_paths =
  9923. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9924. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9925. if (should_verify_peer) {
  9926. ca_path = ctx->config[SSL_CA_PATH];
  9927. ca_file = ctx->config[SSL_CA_FILE];
  9928. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9929. != 1) {
  9930. mg_cry(fc(ctx),
  9931. "SSL_CTX_load_verify_locations error: %s "
  9932. "ssl_verify_peer requires setting "
  9933. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9934. "present in "
  9935. "the .conf file?",
  9936. ssl_error());
  9937. return 0;
  9938. }
  9939. SSL_CTX_set_verify(ctx->ssl_ctx,
  9940. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9941. NULL);
  9942. if (use_default_verify_paths
  9943. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9944. mg_cry(fc(ctx),
  9945. "SSL_CTX_set_default_verify_paths error: %s",
  9946. ssl_error());
  9947. return 0;
  9948. }
  9949. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9950. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9951. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9952. }
  9953. }
  9954. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9955. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9956. != 1) {
  9957. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9958. }
  9959. }
  9960. return 1;
  9961. }
  9962. static void
  9963. uninitialize_ssl(struct mg_context *ctx)
  9964. {
  9965. int i;
  9966. (void)ctx;
  9967. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9968. /* Shutdown according to
  9969. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9970. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9971. */
  9972. CRYPTO_set_locking_callback(NULL);
  9973. CRYPTO_set_id_callback(NULL);
  9974. ENGINE_cleanup();
  9975. CONF_modules_unload(1);
  9976. ERR_free_strings();
  9977. EVP_cleanup();
  9978. CRYPTO_cleanup_all_ex_data();
  9979. ERR_remove_state(0);
  9980. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9981. pthread_mutex_destroy(&ssl_mutexes[i]);
  9982. }
  9983. mg_free(ssl_mutexes);
  9984. ssl_mutexes = NULL;
  9985. }
  9986. }
  9987. #endif /* !NO_SSL */
  9988. static int
  9989. set_gpass_option(struct mg_context *ctx)
  9990. {
  9991. if (ctx) {
  9992. struct file file = STRUCT_FILE_INITIALIZER;
  9993. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9994. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9995. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9996. return 0;
  9997. }
  9998. return 1;
  9999. }
  10000. return 0;
  10001. }
  10002. static int
  10003. set_acl_option(struct mg_context *ctx)
  10004. {
  10005. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10006. }
  10007. static void
  10008. reset_per_request_attributes(struct mg_connection *conn)
  10009. {
  10010. if (!conn) {
  10011. return;
  10012. }
  10013. conn->path_info = NULL;
  10014. conn->num_bytes_sent = conn->consumed_content = 0;
  10015. conn->status_code = -1;
  10016. conn->is_chunked = 0;
  10017. conn->must_close = conn->request_len = conn->throttle = 0;
  10018. conn->request_info.content_length = -1;
  10019. conn->request_info.remote_user = NULL;
  10020. conn->request_info.request_method = NULL;
  10021. conn->request_info.request_uri = NULL;
  10022. conn->request_info.local_uri = NULL;
  10023. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10024. * local_uri and request_uri */
  10025. conn->request_info.http_version = NULL;
  10026. conn->request_info.num_headers = 0;
  10027. conn->data_len = 0;
  10028. conn->chunk_remainder = 0;
  10029. conn->internal_error = 0;
  10030. }
  10031. static int
  10032. set_sock_timeout(SOCKET sock, int milliseconds)
  10033. {
  10034. int r0 = 0, r1, r2;
  10035. #ifdef _WIN32
  10036. /* Windows specific */
  10037. DWORD tv = (DWORD)milliseconds;
  10038. #else
  10039. /* Linux, ... (not Windows) */
  10040. struct timeval tv;
  10041. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10042. * max. time waiting for the acknowledged of TCP data before the connection
  10043. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10044. * If this option is not set, the default timeout of 20-30 minutes is used.
  10045. */
  10046. /* #define TCP_USER_TIMEOUT (18) */
  10047. #if defined(TCP_USER_TIMEOUT)
  10048. unsigned int uto = (unsigned int)milliseconds;
  10049. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10050. #endif
  10051. memset(&tv, 0, sizeof(tv));
  10052. tv.tv_sec = milliseconds / 1000;
  10053. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10054. #endif /* _WIN32 */
  10055. r1 = setsockopt(
  10056. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10057. r2 = setsockopt(
  10058. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10059. return r0 || r1 || r2;
  10060. }
  10061. static int
  10062. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10063. {
  10064. if (setsockopt(sock,
  10065. IPPROTO_TCP,
  10066. TCP_NODELAY,
  10067. (SOCK_OPT_TYPE)&nodelay_on,
  10068. sizeof(nodelay_on)) != 0) {
  10069. /* Error */
  10070. return 1;
  10071. }
  10072. /* OK */
  10073. return 0;
  10074. }
  10075. static void
  10076. close_socket_gracefully(struct mg_connection *conn)
  10077. {
  10078. #if defined(_WIN32)
  10079. char buf[MG_BUF_LEN];
  10080. int n;
  10081. #endif
  10082. struct linger linger;
  10083. if (!conn) {
  10084. return;
  10085. }
  10086. /* Set linger option to avoid socket hanging out after close. This
  10087. * prevent
  10088. * ephemeral port exhaust problem under high QPS. */
  10089. linger.l_onoff = 1;
  10090. linger.l_linger = 1;
  10091. if (setsockopt(conn->client.sock,
  10092. SOL_SOCKET,
  10093. SO_LINGER,
  10094. (char *)&linger,
  10095. sizeof(linger)) != 0) {
  10096. mg_cry(conn,
  10097. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10098. __func__,
  10099. strerror(ERRNO));
  10100. }
  10101. /* Send FIN to the client */
  10102. shutdown(conn->client.sock, SHUT_WR);
  10103. set_non_blocking_mode(conn->client.sock);
  10104. #if defined(_WIN32)
  10105. /* Read and discard pending incoming data. If we do not do that and
  10106. * close
  10107. * the socket, the data in the send buffer may be discarded. This
  10108. * behaviour is seen on Windows, when client keeps sending data
  10109. * when server decides to close the connection; then when client
  10110. * does recv() it gets no data back. */
  10111. do {
  10112. n = pull(
  10113. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10114. } while (n > 0);
  10115. #endif
  10116. /* Now we know that our FIN is ACK-ed, safe to close */
  10117. closesocket(conn->client.sock);
  10118. conn->client.sock = INVALID_SOCKET;
  10119. }
  10120. static void
  10121. close_connection(struct mg_connection *conn)
  10122. {
  10123. if (!conn || !conn->ctx) {
  10124. return;
  10125. }
  10126. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10127. if (conn->lua_websocket_state) {
  10128. lua_websocket_close(conn, conn->lua_websocket_state);
  10129. conn->lua_websocket_state = NULL;
  10130. }
  10131. #endif
  10132. /* call the connection_close callback if assigned */
  10133. if ((conn->ctx->callbacks.connection_close != NULL)
  10134. && (conn->ctx->context_type == 1)) {
  10135. conn->ctx->callbacks.connection_close(conn);
  10136. }
  10137. mg_lock_connection(conn);
  10138. conn->must_close = 1;
  10139. #ifndef NO_SSL
  10140. if (conn->ssl != NULL) {
  10141. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10142. */
  10143. SSL_shutdown(conn->ssl);
  10144. SSL_free(conn->ssl);
  10145. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10146. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10147. ERR_remove_state(0);
  10148. conn->ssl = NULL;
  10149. }
  10150. #endif
  10151. if (conn->client.sock != INVALID_SOCKET) {
  10152. close_socket_gracefully(conn);
  10153. conn->client.sock = INVALID_SOCKET;
  10154. }
  10155. mg_unlock_connection(conn);
  10156. }
  10157. void
  10158. mg_close_connection(struct mg_connection *conn)
  10159. {
  10160. struct mg_context *client_ctx = NULL;
  10161. unsigned int i;
  10162. if (conn == NULL) {
  10163. return;
  10164. }
  10165. if (conn->ctx->context_type == 2) {
  10166. client_ctx = conn->ctx;
  10167. /* client context: loops must end */
  10168. conn->ctx->stop_flag = 1;
  10169. }
  10170. #ifndef NO_SSL
  10171. if (conn->client_ssl_ctx != NULL) {
  10172. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10173. }
  10174. #endif
  10175. close_connection(conn);
  10176. if (client_ctx != NULL) {
  10177. /* join worker thread and free context */
  10178. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10179. if (client_ctx->workerthreadids[i] != 0) {
  10180. mg_join_thread(client_ctx->workerthreadids[i]);
  10181. }
  10182. }
  10183. mg_free(client_ctx->workerthreadids);
  10184. mg_free(client_ctx);
  10185. (void)pthread_mutex_destroy(&conn->mutex);
  10186. mg_free(conn);
  10187. }
  10188. }
  10189. static struct mg_connection *
  10190. mg_connect_client_impl(const struct mg_client_options *client_options,
  10191. int use_ssl,
  10192. char *ebuf,
  10193. size_t ebuf_len)
  10194. {
  10195. static struct mg_context fake_ctx;
  10196. struct mg_connection *conn = NULL;
  10197. SOCKET sock;
  10198. union usa sa;
  10199. if (!connect_socket(&fake_ctx,
  10200. client_options->host,
  10201. client_options->port,
  10202. use_ssl,
  10203. ebuf,
  10204. ebuf_len,
  10205. &sock,
  10206. &sa)) {
  10207. ;
  10208. } else if ((conn = (struct mg_connection *)
  10209. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10210. mg_snprintf(NULL,
  10211. NULL, /* No truncation check for ebuf */
  10212. ebuf,
  10213. ebuf_len,
  10214. "calloc(): %s",
  10215. strerror(ERRNO));
  10216. closesocket(sock);
  10217. #ifndef NO_SSL
  10218. } else if (use_ssl
  10219. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10220. == NULL) {
  10221. mg_snprintf(NULL,
  10222. NULL, /* No truncation check for ebuf */
  10223. ebuf,
  10224. ebuf_len,
  10225. "SSL_CTX_new error");
  10226. closesocket(sock);
  10227. mg_free(conn);
  10228. conn = NULL;
  10229. #endif /* NO_SSL */
  10230. } else {
  10231. #ifdef USE_IPV6
  10232. socklen_t len = (sa.sa.sa_family == AF_INET)
  10233. ? sizeof(conn->client.rsa.sin)
  10234. : sizeof(conn->client.rsa.sin6);
  10235. struct sockaddr *psa =
  10236. (sa.sa.sa_family == AF_INET)
  10237. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10238. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10239. #else
  10240. socklen_t len = sizeof(conn->client.rsa.sin);
  10241. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10242. #endif
  10243. conn->buf_size = MAX_REQUEST_SIZE;
  10244. conn->buf = (char *)(conn + 1);
  10245. conn->ctx = &fake_ctx;
  10246. conn->client.sock = sock;
  10247. conn->client.lsa = sa;
  10248. if (getsockname(sock, psa, &len) != 0) {
  10249. mg_cry(conn,
  10250. "%s: getsockname() failed: %s",
  10251. __func__,
  10252. strerror(ERRNO));
  10253. }
  10254. conn->client.is_ssl = use_ssl ? 1 : 0;
  10255. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10256. #ifndef NO_SSL
  10257. if (use_ssl) {
  10258. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10259. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10260. * SSL_CTX_set_verify call is needed to switch off server
  10261. * certificate checking, which is off by default in OpenSSL and
  10262. * on in yaSSL. */
  10263. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10264. * SSL_VERIFY_PEER, verify_ssl_server); */
  10265. if (client_options->client_cert) {
  10266. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10267. mg_snprintf(NULL,
  10268. NULL, /* No truncation check for ebuf */
  10269. ebuf,
  10270. ebuf_len,
  10271. "Can not use SSL client certificate");
  10272. SSL_CTX_free(conn->client_ssl_ctx);
  10273. closesocket(sock);
  10274. mg_free(conn);
  10275. conn = NULL;
  10276. }
  10277. }
  10278. if (client_options->server_cert) {
  10279. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10280. client_options->server_cert,
  10281. NULL);
  10282. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10283. } else {
  10284. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10285. }
  10286. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10287. mg_snprintf(NULL,
  10288. NULL, /* No truncation check for ebuf */
  10289. ebuf,
  10290. ebuf_len,
  10291. "SSL connection error");
  10292. SSL_CTX_free(conn->client_ssl_ctx);
  10293. closesocket(sock);
  10294. mg_free(conn);
  10295. conn = NULL;
  10296. }
  10297. }
  10298. #endif
  10299. }
  10300. return conn;
  10301. }
  10302. CIVETWEB_API struct mg_connection *
  10303. mg_connect_client_secure(const struct mg_client_options *client_options,
  10304. char *error_buffer,
  10305. size_t error_buffer_size)
  10306. {
  10307. return mg_connect_client_impl(client_options,
  10308. 1,
  10309. error_buffer,
  10310. error_buffer_size);
  10311. }
  10312. struct mg_connection *
  10313. mg_connect_client(const char *host,
  10314. int port,
  10315. int use_ssl,
  10316. char *error_buffer,
  10317. size_t error_buffer_size)
  10318. {
  10319. struct mg_client_options opts;
  10320. memset(&opts, 0, sizeof(opts));
  10321. opts.host = host;
  10322. opts.port = port;
  10323. return mg_connect_client_impl(&opts,
  10324. use_ssl,
  10325. error_buffer,
  10326. error_buffer_size);
  10327. }
  10328. static const struct {
  10329. const char *proto;
  10330. size_t proto_len;
  10331. unsigned default_port;
  10332. } abs_uri_protocols[] = {{"http://", 7, 80},
  10333. {"https://", 8, 443},
  10334. {"ws://", 5, 80},
  10335. {"wss://", 6, 443},
  10336. {NULL, 0, 0}};
  10337. /* Check if the uri is valid.
  10338. * return 0 for invalid uri,
  10339. * return 1 for *,
  10340. * return 2 for relative uri,
  10341. * return 3 for absolute uri without port,
  10342. * return 4 for absolute uri with port */
  10343. static int
  10344. get_uri_type(const char *uri)
  10345. {
  10346. int i;
  10347. char *hostend, *portbegin, *portend;
  10348. unsigned long port;
  10349. /* According to the HTTP standard
  10350. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10351. * URI can be an asterisk (*) or should start with slash (relative uri),
  10352. * or it should start with the protocol (absolute uri). */
  10353. if (uri[0] == '*' && uri[1] == '\0') {
  10354. /* asterisk */
  10355. return 1;
  10356. }
  10357. if (uri[0] == '/') {
  10358. /* relative uri */
  10359. return 2;
  10360. }
  10361. /* It could be an absolute uri: */
  10362. /* This function only checks if the uri is valid, not if it is
  10363. * addressing the current server. So civetweb can also be used
  10364. * as a proxy server. */
  10365. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10366. if (mg_strncasecmp(uri,
  10367. abs_uri_protocols[i].proto,
  10368. abs_uri_protocols[i].proto_len) == 0) {
  10369. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10370. if (!hostend) {
  10371. return 0;
  10372. }
  10373. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10374. if (!portbegin) {
  10375. return 3;
  10376. }
  10377. port = strtoul(portbegin + 1, &portend, 10);
  10378. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10379. return 0;
  10380. }
  10381. return 4;
  10382. }
  10383. }
  10384. return 0;
  10385. }
  10386. /* Return NULL or the relative uri at the current server */
  10387. static const char *
  10388. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10389. {
  10390. const char *server_domain;
  10391. size_t server_domain_len;
  10392. size_t request_domain_len = 0;
  10393. unsigned long port = 0;
  10394. int i;
  10395. const char *hostbegin = NULL;
  10396. const char *hostend = NULL;
  10397. const char *portbegin;
  10398. char *portend;
  10399. /* DNS is case insensitive, so use case insensitive string compare here
  10400. */
  10401. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10402. if (!server_domain) {
  10403. return 0;
  10404. }
  10405. server_domain_len = strlen(server_domain);
  10406. if (!server_domain_len) {
  10407. return 0;
  10408. }
  10409. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10410. if (mg_strncasecmp(uri,
  10411. abs_uri_protocols[i].proto,
  10412. abs_uri_protocols[i].proto_len) == 0) {
  10413. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10414. hostend = strchr(hostbegin, '/');
  10415. if (!hostend) {
  10416. return 0;
  10417. }
  10418. portbegin = strchr(hostbegin, ':');
  10419. if ((!portbegin) || (portbegin > hostend)) {
  10420. port = abs_uri_protocols[i].default_port;
  10421. request_domain_len = (size_t)(hostend - hostbegin);
  10422. } else {
  10423. port = strtoul(portbegin + 1, &portend, 10);
  10424. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10425. return 0;
  10426. }
  10427. request_domain_len = (size_t)(portbegin - hostbegin);
  10428. }
  10429. /* protocol found, port set */
  10430. break;
  10431. }
  10432. }
  10433. if (!port) {
  10434. /* port remains 0 if the protocol is not found */
  10435. return 0;
  10436. }
  10437. #if defined(USE_IPV6)
  10438. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10439. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10440. /* Request is directed to a different port */
  10441. return 0;
  10442. }
  10443. } else
  10444. #endif
  10445. {
  10446. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10447. /* Request is directed to a different port */
  10448. return 0;
  10449. }
  10450. }
  10451. if ((request_domain_len != server_domain_len)
  10452. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10453. /* Request is directed to another server */
  10454. return 0;
  10455. }
  10456. return hostend;
  10457. }
  10458. static int
  10459. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10460. {
  10461. const char *cl;
  10462. if (ebuf_len > 0) {
  10463. ebuf[0] = '\0';
  10464. }
  10465. *err = 0;
  10466. reset_per_request_attributes(conn);
  10467. if (!conn) {
  10468. mg_snprintf(conn,
  10469. NULL, /* No truncation check for ebuf */
  10470. ebuf,
  10471. ebuf_len,
  10472. "%s",
  10473. "Internal error");
  10474. *err = 500;
  10475. return 0;
  10476. }
  10477. /* Set the time the request was received. This value should be used for
  10478. * timeouts. */
  10479. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10480. conn->request_len =
  10481. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10482. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10483. */
  10484. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10485. mg_snprintf(conn,
  10486. NULL, /* No truncation check for ebuf */
  10487. ebuf,
  10488. ebuf_len,
  10489. "%s",
  10490. "Invalid request size");
  10491. *err = 500;
  10492. return 0;
  10493. }
  10494. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10495. mg_snprintf(conn,
  10496. NULL, /* No truncation check for ebuf */
  10497. ebuf,
  10498. ebuf_len,
  10499. "%s",
  10500. "Request Too Large");
  10501. *err = 413;
  10502. return 0;
  10503. } else if (conn->request_len <= 0) {
  10504. if (conn->data_len > 0) {
  10505. mg_snprintf(conn,
  10506. NULL, /* No truncation check for ebuf */
  10507. ebuf,
  10508. ebuf_len,
  10509. "%s",
  10510. "Client sent malformed request");
  10511. *err = 400;
  10512. } else {
  10513. /* Server did not send anything -> just close the connection */
  10514. conn->must_close = 1;
  10515. mg_snprintf(conn,
  10516. NULL, /* No truncation check for ebuf */
  10517. ebuf,
  10518. ebuf_len,
  10519. "%s",
  10520. "Client did not send a request");
  10521. *err = 0;
  10522. }
  10523. return 0;
  10524. } else if (parse_http_message(conn->buf,
  10525. conn->buf_size,
  10526. &conn->request_info) <= 0) {
  10527. mg_snprintf(conn,
  10528. NULL, /* No truncation check for ebuf */
  10529. ebuf,
  10530. ebuf_len,
  10531. "%s",
  10532. "Bad Request");
  10533. *err = 400;
  10534. return 0;
  10535. } else {
  10536. /* Message is a valid request or response */
  10537. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10538. /* Request/response has content length set */
  10539. char *endptr = NULL;
  10540. conn->content_len = strtoll(cl, &endptr, 10);
  10541. if (endptr == cl) {
  10542. mg_snprintf(conn,
  10543. NULL, /* No truncation check for ebuf */
  10544. ebuf,
  10545. ebuf_len,
  10546. "%s",
  10547. "Bad Request");
  10548. *err = 411;
  10549. return 0;
  10550. }
  10551. /* Publish the content length back to the request info. */
  10552. conn->request_info.content_length = conn->content_len;
  10553. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10554. != NULL
  10555. && !mg_strcasecmp(cl, "chunked")) {
  10556. conn->is_chunked = 1;
  10557. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10558. || !mg_strcasecmp(conn->request_info.request_method,
  10559. "PUT")) {
  10560. /* POST or PUT request without content length set */
  10561. conn->content_len = -1;
  10562. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10563. "HTTP/",
  10564. 5)) {
  10565. /* Response without content length set */
  10566. conn->content_len = -1;
  10567. } else {
  10568. /* Other request */
  10569. conn->content_len = 0;
  10570. }
  10571. }
  10572. return 1;
  10573. }
  10574. int
  10575. mg_get_response(struct mg_connection *conn,
  10576. char *ebuf,
  10577. size_t ebuf_len,
  10578. int timeout)
  10579. {
  10580. if (conn) {
  10581. /* Implementation of API function for HTTP clients */
  10582. int err, ret;
  10583. struct mg_context *octx = conn->ctx;
  10584. struct mg_context rctx = *(conn->ctx);
  10585. char txt[32]; /* will not overflow */
  10586. if (timeout >= 0) {
  10587. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10588. rctx.config[REQUEST_TIMEOUT] = txt;
  10589. set_sock_timeout(conn->client.sock, timeout);
  10590. } else {
  10591. rctx.config[REQUEST_TIMEOUT] = NULL;
  10592. }
  10593. conn->ctx = &rctx;
  10594. ret = getreq(conn, ebuf, ebuf_len, &err);
  10595. conn->ctx = octx;
  10596. /* TODO: 1) uri is deprecated;
  10597. * 2) here, ri.uri is the http response code */
  10598. conn->request_info.uri = conn->request_info.request_uri;
  10599. /* TODO (mid): Define proper return values - maybe return length?
  10600. * For the first test use <0 for error and >0 for OK */
  10601. return (ret == 0) ? -1 : +1;
  10602. }
  10603. return -1;
  10604. }
  10605. struct mg_connection *
  10606. mg_download(const char *host,
  10607. int port,
  10608. int use_ssl,
  10609. char *ebuf,
  10610. size_t ebuf_len,
  10611. const char *fmt,
  10612. ...)
  10613. {
  10614. struct mg_connection *conn;
  10615. va_list ap;
  10616. int i;
  10617. int reqerr;
  10618. va_start(ap, fmt);
  10619. ebuf[0] = '\0';
  10620. /* open a connection */
  10621. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10622. if (conn != NULL) {
  10623. i = mg_vprintf(conn, fmt, ap);
  10624. if (i <= 0) {
  10625. mg_snprintf(conn,
  10626. NULL, /* No truncation check for ebuf */
  10627. ebuf,
  10628. ebuf_len,
  10629. "%s",
  10630. "Error sending request");
  10631. } else {
  10632. getreq(conn, ebuf, ebuf_len, &reqerr);
  10633. /* TODO: 1) uri is deprecated;
  10634. * 2) here, ri.uri is the http response code */
  10635. conn->request_info.uri = conn->request_info.request_uri;
  10636. }
  10637. }
  10638. /* if an error occured, close the connection */
  10639. if (ebuf[0] != '\0' && conn != NULL) {
  10640. mg_close_connection(conn);
  10641. conn = NULL;
  10642. }
  10643. va_end(ap);
  10644. return conn;
  10645. }
  10646. struct websocket_client_thread_data {
  10647. struct mg_connection *conn;
  10648. mg_websocket_data_handler data_handler;
  10649. mg_websocket_close_handler close_handler;
  10650. void *callback_data;
  10651. };
  10652. #if defined(USE_WEBSOCKET)
  10653. #ifdef _WIN32
  10654. static unsigned __stdcall websocket_client_thread(void *data)
  10655. #else
  10656. static void *
  10657. websocket_client_thread(void *data)
  10658. #endif
  10659. {
  10660. struct websocket_client_thread_data *cdata =
  10661. (struct websocket_client_thread_data *)data;
  10662. mg_set_thread_name("ws-client");
  10663. if (cdata->conn->ctx) {
  10664. if (cdata->conn->ctx->callbacks.init_thread) {
  10665. /* 3 indicates a websocket client thread */
  10666. /* TODO: check if conn->ctx can be set */
  10667. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10668. }
  10669. }
  10670. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10671. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10672. if (cdata->close_handler != NULL) {
  10673. cdata->close_handler(cdata->conn, cdata->callback_data);
  10674. }
  10675. mg_free((void *)cdata);
  10676. #ifdef _WIN32
  10677. return 0;
  10678. #else
  10679. return NULL;
  10680. #endif
  10681. }
  10682. #endif
  10683. struct mg_connection *
  10684. mg_connect_websocket_client(const char *host,
  10685. int port,
  10686. int use_ssl,
  10687. char *error_buffer,
  10688. size_t error_buffer_size,
  10689. const char *path,
  10690. const char *origin,
  10691. mg_websocket_data_handler data_func,
  10692. mg_websocket_close_handler close_func,
  10693. void *user_data)
  10694. {
  10695. struct mg_connection *conn = NULL;
  10696. #if defined(USE_WEBSOCKET)
  10697. struct mg_context *newctx = NULL;
  10698. struct websocket_client_thread_data *thread_data;
  10699. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10700. static const char *handshake_req;
  10701. if (origin != NULL) {
  10702. handshake_req = "GET %s HTTP/1.1\r\n"
  10703. "Host: %s\r\n"
  10704. "Upgrade: websocket\r\n"
  10705. "Connection: Upgrade\r\n"
  10706. "Sec-WebSocket-Key: %s\r\n"
  10707. "Sec-WebSocket-Version: 13\r\n"
  10708. "Origin: %s\r\n"
  10709. "\r\n";
  10710. } else {
  10711. handshake_req = "GET %s HTTP/1.1\r\n"
  10712. "Host: %s\r\n"
  10713. "Upgrade: websocket\r\n"
  10714. "Connection: Upgrade\r\n"
  10715. "Sec-WebSocket-Key: %s\r\n"
  10716. "Sec-WebSocket-Version: 13\r\n"
  10717. "\r\n";
  10718. }
  10719. /* Establish the client connection and request upgrade */
  10720. conn = mg_download(host,
  10721. port,
  10722. use_ssl,
  10723. error_buffer,
  10724. error_buffer_size,
  10725. handshake_req,
  10726. path,
  10727. host,
  10728. magic,
  10729. origin);
  10730. /* Connection object will be null if something goes wrong */
  10731. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10732. if (!*error_buffer) {
  10733. /* if there is a connection, but it did not return 101,
  10734. * error_buffer is not yet set */
  10735. mg_snprintf(conn,
  10736. NULL, /* No truncation check for ebuf */
  10737. error_buffer,
  10738. error_buffer_size,
  10739. "Unexpected server reply");
  10740. }
  10741. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10742. if (conn != NULL) {
  10743. mg_free(conn);
  10744. conn = NULL;
  10745. }
  10746. return conn;
  10747. }
  10748. /* For client connections, mg_context is fake. Since we need to set a
  10749. * callback function, we need to create a copy and modify it. */
  10750. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10751. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10752. newctx->user_data = user_data;
  10753. newctx->context_type = 2; /* client context type */
  10754. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10755. newctx->workerthreadids =
  10756. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10757. conn->ctx = newctx;
  10758. thread_data = (struct websocket_client_thread_data *)
  10759. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10760. thread_data->conn = conn;
  10761. thread_data->data_handler = data_func;
  10762. thread_data->close_handler = close_func;
  10763. thread_data->callback_data = NULL;
  10764. /* Start a thread to read the websocket client connection
  10765. * This thread will automatically stop when mg_disconnect is
  10766. * called on the client connection */
  10767. if (mg_start_thread_with_id(websocket_client_thread,
  10768. (void *)thread_data,
  10769. newctx->workerthreadids) != 0) {
  10770. mg_free((void *)thread_data);
  10771. mg_free((void *)newctx->workerthreadids);
  10772. mg_free((void *)newctx);
  10773. mg_free((void *)conn);
  10774. conn = NULL;
  10775. DEBUG_TRACE("%s",
  10776. "Websocket client connect thread could not be started\r\n");
  10777. }
  10778. #else
  10779. /* Appease "unused parameter" warnings */
  10780. (void)host;
  10781. (void)port;
  10782. (void)use_ssl;
  10783. (void)error_buffer;
  10784. (void)error_buffer_size;
  10785. (void)path;
  10786. (void)origin;
  10787. (void)user_data;
  10788. (void)data_func;
  10789. (void)close_func;
  10790. #endif
  10791. return conn;
  10792. }
  10793. static void
  10794. process_new_connection(struct mg_connection *conn)
  10795. {
  10796. if (conn && conn->ctx) {
  10797. struct mg_request_info *ri = &conn->request_info;
  10798. int keep_alive_enabled, keep_alive, discard_len;
  10799. char ebuf[100];
  10800. const char *hostend;
  10801. int reqerr, uri_type;
  10802. keep_alive_enabled =
  10803. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10804. /* Important: on new connection, reset the receiving buffer. Credit
  10805. * goes to crule42. */
  10806. conn->data_len = 0;
  10807. do {
  10808. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10809. /* The request sent by the client could not be understood by
  10810. * the server, or it was incomplete or a timeout. Send an
  10811. * error message and close the connection. */
  10812. if (reqerr > 0) {
  10813. /*assert(ebuf[0] != '\0');*/
  10814. send_http_error(conn, reqerr, "%s", ebuf);
  10815. }
  10816. } else if (strcmp(ri->http_version, "1.0")
  10817. && strcmp(ri->http_version, "1.1")) {
  10818. mg_snprintf(conn,
  10819. NULL, /* No truncation check for ebuf */
  10820. ebuf,
  10821. sizeof(ebuf),
  10822. "Bad HTTP version: [%s]",
  10823. ri->http_version);
  10824. send_http_error(conn, 505, "%s", ebuf);
  10825. }
  10826. if (ebuf[0] == '\0') {
  10827. uri_type = get_uri_type(conn->request_info.request_uri);
  10828. switch (uri_type) {
  10829. case 1:
  10830. /* Asterisk */
  10831. conn->request_info.local_uri = NULL;
  10832. break;
  10833. case 2:
  10834. /* relative uri */
  10835. conn->request_info.local_uri =
  10836. conn->request_info.request_uri;
  10837. break;
  10838. case 3:
  10839. case 4:
  10840. /* absolute uri (with/without port) */
  10841. hostend = get_rel_url_at_current_server(
  10842. conn->request_info.request_uri, conn);
  10843. if (hostend) {
  10844. conn->request_info.local_uri = hostend;
  10845. } else {
  10846. conn->request_info.local_uri = NULL;
  10847. }
  10848. break;
  10849. default:
  10850. mg_snprintf(conn,
  10851. NULL, /* No truncation check for ebuf */
  10852. ebuf,
  10853. sizeof(ebuf),
  10854. "Invalid URI: [%s]",
  10855. ri->request_uri);
  10856. send_http_error(conn, 400, "%s", ebuf);
  10857. break;
  10858. }
  10859. /* TODO: cleanup uri, local_uri and request_uri */
  10860. conn->request_info.uri = conn->request_info.local_uri;
  10861. }
  10862. if (ebuf[0] == '\0') {
  10863. if (conn->request_info.local_uri) {
  10864. /* handle request to local server */
  10865. handle_request(conn);
  10866. if (conn->ctx->callbacks.end_request != NULL) {
  10867. conn->ctx->callbacks.end_request(conn,
  10868. conn->status_code);
  10869. }
  10870. log_access(conn);
  10871. } else {
  10872. /* TODO: handle non-local request (PROXY) */
  10873. conn->must_close = 1;
  10874. }
  10875. } else {
  10876. conn->must_close = 1;
  10877. }
  10878. if (ri->remote_user != NULL) {
  10879. mg_free((void *)ri->remote_user);
  10880. /* Important! When having connections with and without auth
  10881. * would cause double free and then crash */
  10882. ri->remote_user = NULL;
  10883. }
  10884. /* NOTE(lsm): order is important here. should_keep_alive() call
  10885. * is
  10886. * using parsed request, which will be invalid after memmove's
  10887. * below.
  10888. * Therefore, memorize should_keep_alive() result now for later
  10889. * use
  10890. * in loop exit condition. */
  10891. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10892. && conn->content_len >= 0 && should_keep_alive(conn);
  10893. /* Discard all buffered data for this request */
  10894. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  10895. && ((conn->request_len + conn->content_len)
  10896. < (int64_t)conn->data_len))
  10897. ? (int)(conn->request_len + conn->content_len)
  10898. : conn->data_len;
  10899. /*assert(discard_len >= 0);*/
  10900. if (discard_len < 0)
  10901. break;
  10902. conn->data_len -= discard_len;
  10903. if (conn->data_len > 0) {
  10904. memmove(conn->buf,
  10905. conn->buf + discard_len,
  10906. (size_t)conn->data_len);
  10907. }
  10908. /* assert(conn->data_len >= 0); */
  10909. /* assert(conn->data_len <= conn->buf_size); */
  10910. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10911. break;
  10912. }
  10913. } while (keep_alive);
  10914. }
  10915. }
  10916. #if defined(ALTERNATIVE_QUEUE)
  10917. static void
  10918. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10919. {
  10920. unsigned int i;
  10921. for (;;) {
  10922. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  10923. /* find a free worker slot and signal it */
  10924. if (ctx->client_socks[i].in_use == 0) {
  10925. ctx->client_socks[i] = *sp;
  10926. ctx->client_socks[i].in_use = 1;
  10927. event_signal(ctx->client_wait_events[i]);
  10928. return;
  10929. }
  10930. }
  10931. /* queue is full */
  10932. mg_sleep(1);
  10933. }
  10934. }
  10935. static int
  10936. consume_socket(struct mg_context *ctx, struct socket *sp, int index)
  10937. {
  10938. ctx->client_socks[index].in_use = 0;
  10939. event_wait(ctx->client_wait_events[index]);
  10940. *sp = ctx->client_socks[index];
  10941. return !ctx->stop_flag;
  10942. }
  10943. #else /* ALTERNATIVE_QUEUE */
  10944. /* Worker threads take accepted socket from the queue */
  10945. static int
  10946. consume_socket(struct mg_context *ctx, struct socket *sp, int index)
  10947. {
  10948. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10949. (void)index;
  10950. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10951. DEBUG_TRACE("%s", "going idle");
  10952. /* If the queue is empty, wait. We're idle at this point. */
  10953. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10954. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10955. }
  10956. /* If we're stopping, sq_head may be equal to sq_tail. */
  10957. if (ctx->sq_head > ctx->sq_tail) {
  10958. /* Copy socket from the queue and increment tail */
  10959. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10960. ctx->sq_tail++;
  10961. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10962. /* Wrap pointers if needed */
  10963. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10964. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10965. ctx->sq_head -= QUEUE_SIZE(ctx);
  10966. }
  10967. }
  10968. (void)pthread_cond_signal(&ctx->sq_empty);
  10969. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10970. return !ctx->stop_flag;
  10971. #undef QUEUE_SIZE
  10972. }
  10973. /* Master thread adds accepted socket to a queue */
  10974. static void
  10975. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10976. {
  10977. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10978. if (!ctx) {
  10979. return;
  10980. }
  10981. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10982. /* If the queue is full, wait */
  10983. while (ctx->stop_flag == 0
  10984. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10985. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10986. }
  10987. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10988. /* Copy socket to the queue and increment head */
  10989. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10990. ctx->sq_head++;
  10991. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10992. }
  10993. (void)pthread_cond_signal(&ctx->sq_full);
  10994. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10995. #undef QUEUE_SIZE
  10996. }
  10997. #endif /* ALTERNATIVE_QUEUE */
  10998. struct worker_thread_args {
  10999. struct mg_context *ctx;
  11000. int index;
  11001. };
  11002. static void *
  11003. worker_thread_run(struct worker_thread_args *thread_args)
  11004. {
  11005. struct mg_context *ctx = thread_args->ctx;
  11006. struct mg_connection *conn;
  11007. struct mg_workerTLS tls;
  11008. #if defined(MG_LEGACY_INTERFACE)
  11009. uint32_t addr;
  11010. #endif
  11011. mg_set_thread_name("worker");
  11012. tls.is_master = 0;
  11013. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11014. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11015. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11016. #endif
  11017. if (ctx->callbacks.init_thread) {
  11018. /* call init_thread for a worker thread (type 1) */
  11019. ctx->callbacks.init_thread(ctx, 1);
  11020. }
  11021. conn =
  11022. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11023. if (conn == NULL) {
  11024. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11025. } else {
  11026. pthread_setspecific(sTlsKey, &tls);
  11027. conn->buf_size = MAX_REQUEST_SIZE;
  11028. conn->buf = (char *)(conn + 1);
  11029. conn->ctx = ctx;
  11030. conn->thread_index = thread_args->index;
  11031. conn->request_info.user_data = ctx->user_data;
  11032. /* Allocate a mutex for this connection to allow communication both
  11033. * within the request handler and from elsewhere in the application
  11034. */
  11035. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11036. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11037. * signal sq_empty condvar to wake up the master waiting in
  11038. * produce_socket() */
  11039. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11040. conn->conn_birth_time = time(NULL);
  11041. /* Fill in IP, port info early so even if SSL setup below fails,
  11042. * error handler would have the corresponding info.
  11043. * Thanks to Johannes Winkelmann for the patch.
  11044. */
  11045. #if defined(USE_IPV6)
  11046. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11047. conn->request_info.remote_port =
  11048. ntohs(conn->client.rsa.sin6.sin6_port);
  11049. } else
  11050. #endif
  11051. {
  11052. conn->request_info.remote_port =
  11053. ntohs(conn->client.rsa.sin.sin_port);
  11054. }
  11055. sockaddr_to_string(conn->request_info.remote_addr,
  11056. sizeof(conn->request_info.remote_addr),
  11057. &conn->client.rsa);
  11058. #if defined(MG_LEGACY_INTERFACE)
  11059. /* This legacy interface only works for the IPv4 case */
  11060. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11061. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11062. #endif
  11063. conn->request_info.is_ssl = conn->client.is_ssl;
  11064. if (!conn->client.is_ssl
  11065. #ifndef NO_SSL
  11066. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  11067. #endif
  11068. ) {
  11069. process_new_connection(conn);
  11070. }
  11071. close_connection(conn);
  11072. }
  11073. }
  11074. pthread_setspecific(sTlsKey, NULL);
  11075. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11076. CloseHandle(tls.pthread_cond_helper_mutex);
  11077. #endif
  11078. pthread_mutex_destroy(&conn->mutex);
  11079. mg_free(conn);
  11080. DEBUG_TRACE("%s", "exiting");
  11081. return NULL;
  11082. }
  11083. /* Threads have different return types on Windows and Unix. */
  11084. #ifdef _WIN32
  11085. static unsigned __stdcall worker_thread(void *thread_func_param)
  11086. {
  11087. struct worker_thread_args *pwta =
  11088. (struct worker_thread_args *)thread_func_param;
  11089. worker_thread_run(thread_func_param);
  11090. mg_free(thread_func_param);
  11091. return 0;
  11092. }
  11093. #else
  11094. static void *
  11095. worker_thread(void *thread_func_param)
  11096. {
  11097. struct worker_thread_args *pwta =
  11098. (struct worker_thread_args *)thread_func_param;
  11099. worker_thread_run(thread_func_param);
  11100. mg_free(thread_func_param);
  11101. return NULL;
  11102. }
  11103. #endif /* _WIN32 */
  11104. static void
  11105. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11106. {
  11107. struct socket so;
  11108. char src_addr[IP_ADDR_STR_LEN];
  11109. socklen_t len = sizeof(so.rsa);
  11110. int on = 1;
  11111. int timeout;
  11112. if (!listener) {
  11113. return;
  11114. }
  11115. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11116. == INVALID_SOCKET) {
  11117. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11118. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11119. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11120. closesocket(so.sock);
  11121. so.sock = INVALID_SOCKET;
  11122. } else {
  11123. /* Put so socket structure into the queue */
  11124. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11125. set_close_on_exec(so.sock, fc(ctx));
  11126. so.is_ssl = listener->is_ssl;
  11127. so.ssl_redir = listener->ssl_redir;
  11128. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11129. mg_cry(fc(ctx),
  11130. "%s: getsockname() failed: %s",
  11131. __func__,
  11132. strerror(ERRNO));
  11133. }
  11134. /* Set TCP keep-alive. This is needed because if HTTP-level
  11135. * keep-alive
  11136. * is enabled, and client resets the connection, server won't get
  11137. * TCP FIN or RST and will keep the connection open forever. With
  11138. * TCP keep-alive, next keep-alive handshake will figure out that
  11139. * the client is down and will close the server end.
  11140. * Thanks to Igor Klopov who suggested the patch. */
  11141. if (setsockopt(so.sock,
  11142. SOL_SOCKET,
  11143. SO_KEEPALIVE,
  11144. (SOCK_OPT_TYPE)&on,
  11145. sizeof(on)) != 0) {
  11146. mg_cry(fc(ctx),
  11147. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11148. __func__,
  11149. strerror(ERRNO));
  11150. }
  11151. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11152. * to effectively fill up the underlying IP packet payload and
  11153. * reduce the overhead of sending lots of small buffers. However
  11154. * this hurts the server's throughput (ie. operations per second)
  11155. * when HTTP 1.1 persistent connections are used and the responses
  11156. * are relatively small (eg. less than 1400 bytes).
  11157. */
  11158. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11159. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11160. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11161. mg_cry(fc(ctx),
  11162. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11163. __func__,
  11164. strerror(ERRNO));
  11165. }
  11166. }
  11167. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11168. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11169. } else {
  11170. timeout = -1;
  11171. }
  11172. /* Set socket timeout to the given value, but not more than a
  11173. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  11174. * so the server can exit after that time if requested. */
  11175. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  11176. set_sock_timeout(so.sock, timeout);
  11177. } else {
  11178. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  11179. }
  11180. produce_socket(ctx, &so);
  11181. }
  11182. }
  11183. static void
  11184. master_thread_run(void *thread_func_param)
  11185. {
  11186. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11187. struct mg_workerTLS tls;
  11188. struct pollfd *pfd;
  11189. unsigned int i;
  11190. unsigned int workerthreadcount;
  11191. if (!ctx) {
  11192. return;
  11193. }
  11194. mg_set_thread_name("master");
  11195. /* Increase priority of the master thread */
  11196. #if defined(_WIN32)
  11197. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11198. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11199. int min_prio = sched_get_priority_min(SCHED_RR);
  11200. int max_prio = sched_get_priority_max(SCHED_RR);
  11201. if ((min_prio >= 0) && (max_prio >= 0)
  11202. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11203. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11204. struct sched_param sched_param = {0};
  11205. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11206. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11207. }
  11208. #endif
  11209. /* Initialize thread local storage */
  11210. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11211. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11212. #endif
  11213. tls.is_master = 1;
  11214. pthread_setspecific(sTlsKey, &tls);
  11215. if (ctx->callbacks.init_thread) {
  11216. /* Callback for the master thread (type 0) */
  11217. ctx->callbacks.init_thread(ctx, 0);
  11218. }
  11219. /* Server starts *now* */
  11220. ctx->start_time = time(NULL);
  11221. /* Start the server */
  11222. pfd = ctx->listening_socket_fds;
  11223. while (ctx->stop_flag == 0) {
  11224. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11225. pfd[i].fd = ctx->listening_sockets[i].sock;
  11226. pfd[i].events = POLLIN;
  11227. }
  11228. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11229. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11230. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11231. * successful poll, and POLLIN is defined as
  11232. * (POLLRDNORM | POLLRDBAND)
  11233. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11234. * pfd[i].revents == POLLIN. */
  11235. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11236. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11237. }
  11238. }
  11239. }
  11240. }
  11241. DEBUG_TRACE("%s", "stopping workers");
  11242. /* Stop signal received: somebody called mg_stop. Quit. */
  11243. close_all_listening_sockets(ctx);
  11244. /* Wakeup workers that are waiting for connections to handle. */
  11245. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11246. #if defined(ALTERNATIVE_QUEUE)
  11247. /* TODO: signal all workers */
  11248. /* TODO: close all socket handles (will avoid SOCKET_TIMEOUT_QUANTUM) */
  11249. #else
  11250. pthread_cond_broadcast(&ctx->sq_full);
  11251. #endif
  11252. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11253. /* Join all worker threads to avoid leaking threads. */
  11254. workerthreadcount = ctx->cfg_worker_threads;
  11255. for (i = 0; i < workerthreadcount; i++) {
  11256. if (ctx->workerthreadids[i] != 0) {
  11257. mg_join_thread(ctx->workerthreadids[i]);
  11258. }
  11259. }
  11260. #if !defined(NO_SSL)
  11261. if (ctx->ssl_ctx != NULL) {
  11262. uninitialize_ssl(ctx);
  11263. }
  11264. #endif
  11265. DEBUG_TRACE("%s", "exiting");
  11266. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11267. CloseHandle(tls.pthread_cond_helper_mutex);
  11268. #endif
  11269. pthread_setspecific(sTlsKey, NULL);
  11270. /* Signal mg_stop() that we're done.
  11271. * WARNING: This must be the very last thing this
  11272. * thread does, as ctx becomes invalid after this line. */
  11273. ctx->stop_flag = 2;
  11274. }
  11275. /* Threads have different return types on Windows and Unix. */
  11276. #ifdef _WIN32
  11277. static unsigned __stdcall master_thread(void *thread_func_param)
  11278. {
  11279. master_thread_run(thread_func_param);
  11280. return 0;
  11281. }
  11282. #else
  11283. static void *
  11284. master_thread(void *thread_func_param)
  11285. {
  11286. master_thread_run(thread_func_param);
  11287. return NULL;
  11288. }
  11289. #endif /* _WIN32 */
  11290. static void
  11291. free_context(struct mg_context *ctx)
  11292. {
  11293. int i;
  11294. struct mg_handler_info *tmp_rh;
  11295. if (ctx == NULL) {
  11296. return;
  11297. }
  11298. if (ctx->callbacks.exit_context) {
  11299. ctx->callbacks.exit_context(ctx);
  11300. }
  11301. /* All threads exited, no sync is needed. Destroy thread mutex and
  11302. * condvars
  11303. */
  11304. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11305. #if defined(ALTERNATIVE_QUEUE)
  11306. mg_free(ctx->client_socks);
  11307. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11308. event_destroy(ctx->client_wait_events[i]);
  11309. }
  11310. mg_free(ctx->client_wait_events);
  11311. /* TODO: free allocated memory */
  11312. #else
  11313. (void)pthread_cond_destroy(&ctx->sq_empty);
  11314. (void)pthread_cond_destroy(&ctx->sq_full);
  11315. #endif
  11316. /* Destroy other context global data structures mutex */
  11317. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11318. #if defined(USE_TIMERS)
  11319. timers_exit(ctx);
  11320. #endif
  11321. /* Deallocate config parameters */
  11322. for (i = 0; i < NUM_OPTIONS; i++) {
  11323. if (ctx->config[i] != NULL) {
  11324. #if defined(_MSC_VER)
  11325. #pragma warning(suppress : 6001)
  11326. #endif
  11327. mg_free(ctx->config[i]);
  11328. }
  11329. }
  11330. /* Deallocate request handlers */
  11331. while (ctx->handlers) {
  11332. tmp_rh = ctx->handlers;
  11333. ctx->handlers = tmp_rh->next;
  11334. mg_free(tmp_rh->uri);
  11335. mg_free(tmp_rh);
  11336. }
  11337. #ifndef NO_SSL
  11338. /* Deallocate SSL context */
  11339. if (ctx->ssl_ctx != NULL) {
  11340. SSL_CTX_free(ctx->ssl_ctx);
  11341. }
  11342. #endif /* !NO_SSL */
  11343. /* Deallocate worker thread ID array */
  11344. if (ctx->workerthreadids != NULL) {
  11345. mg_free(ctx->workerthreadids);
  11346. }
  11347. /* Deallocate the tls variable */
  11348. if (mg_atomic_dec(&sTlsInit) == 0) {
  11349. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11350. DeleteCriticalSection(&global_log_file_lock);
  11351. #endif /* _WIN32 && !__SYMBIAN32__ */
  11352. #if !defined(_WIN32)
  11353. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11354. #endif
  11355. pthread_key_delete(sTlsKey);
  11356. }
  11357. /* deallocate system name string */
  11358. mg_free(ctx->systemName);
  11359. /* Deallocate context itself */
  11360. mg_free(ctx);
  11361. }
  11362. void
  11363. mg_stop(struct mg_context *ctx)
  11364. {
  11365. pthread_t mt;
  11366. if (!ctx) {
  11367. return;
  11368. }
  11369. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11370. * two threads is not allowed. */
  11371. mt = ctx->masterthreadid;
  11372. if (mt == 0) {
  11373. return;
  11374. }
  11375. ctx->masterthreadid = 0;
  11376. /* Set stop flag, so all threads know they have to exit. */
  11377. ctx->stop_flag = 1;
  11378. /* Wait until everything has stopped. */
  11379. while (ctx->stop_flag != 2) {
  11380. (void)mg_sleep(10);
  11381. }
  11382. mg_join_thread(mt);
  11383. free_context(ctx);
  11384. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11385. (void)WSACleanup();
  11386. #endif /* _WIN32 && !__SYMBIAN32__ */
  11387. }
  11388. static void
  11389. get_system_name(char **sysName)
  11390. {
  11391. #if defined(_WIN32)
  11392. #if !defined(__SYMBIAN32__)
  11393. #if defined(_WIN32_WCE)
  11394. *sysName = mg_strdup("WinCE");
  11395. #else
  11396. char name[128];
  11397. DWORD dwVersion = 0;
  11398. DWORD dwMajorVersion = 0;
  11399. DWORD dwMinorVersion = 0;
  11400. DWORD dwBuild = 0;
  11401. #ifdef _MSC_VER
  11402. #pragma warning(push)
  11403. // GetVersion was declared deprecated
  11404. #pragma warning(disable : 4996)
  11405. #endif
  11406. dwVersion = GetVersion();
  11407. #ifdef _MSC_VER
  11408. #pragma warning(pop)
  11409. #endif
  11410. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11411. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11412. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11413. (void)dwBuild;
  11414. sprintf(name,
  11415. "Windows %u.%u",
  11416. (unsigned)dwMajorVersion,
  11417. (unsigned)dwMinorVersion);
  11418. *sysName = mg_strdup(name);
  11419. #endif
  11420. #else
  11421. *sysName = mg_strdup("Symbian");
  11422. #endif
  11423. #else
  11424. struct utsname name;
  11425. memset(&name, 0, sizeof(name));
  11426. uname(&name);
  11427. *sysName = mg_strdup(name.sysname);
  11428. #endif
  11429. }
  11430. struct mg_context *
  11431. mg_start(const struct mg_callbacks *callbacks,
  11432. void *user_data,
  11433. const char **options)
  11434. {
  11435. struct mg_context *ctx;
  11436. const char *name, *value, *default_value;
  11437. int idx, ok, workerthreadcount;
  11438. unsigned int i;
  11439. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11440. struct mg_workerTLS tls;
  11441. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11442. WSADATA data;
  11443. WSAStartup(MAKEWORD(2, 2), &data);
  11444. #endif /* _WIN32 && !__SYMBIAN32__ */
  11445. /* Allocate context and initialize reasonable general case defaults. */
  11446. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11447. return NULL;
  11448. }
  11449. /* Random number generator will initialize at the first call */
  11450. ctx->auth_nonce_mask =
  11451. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11452. if (mg_atomic_inc(&sTlsInit) == 1) {
  11453. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11454. InitializeCriticalSection(&global_log_file_lock);
  11455. #endif /* _WIN32 && !__SYMBIAN32__ */
  11456. #if !defined(_WIN32)
  11457. pthread_mutexattr_init(&pthread_mutex_attr);
  11458. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11459. #endif
  11460. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11461. /* Fatal error - abort start. However, this situation should
  11462. * never
  11463. * occur in practice. */
  11464. mg_atomic_dec(&sTlsInit);
  11465. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11466. mg_free(ctx);
  11467. return NULL;
  11468. }
  11469. } else {
  11470. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11471. * initialized. */
  11472. mg_sleep(1);
  11473. }
  11474. tls.is_master = -1;
  11475. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11476. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11477. tls.pthread_cond_helper_mutex = NULL;
  11478. #endif
  11479. pthread_setspecific(sTlsKey, &tls);
  11480. #if defined(USE_LUA)
  11481. lua_init_optional_libraries();
  11482. #endif
  11483. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11484. #if !defined(ALTERNATIVE_QUEUE)
  11485. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11486. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11487. #endif
  11488. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11489. if (!ok) {
  11490. /* Fatal error - abort start. However, this situation should never
  11491. * occur in practice. */
  11492. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11493. mg_free(ctx);
  11494. pthread_setspecific(sTlsKey, NULL);
  11495. return NULL;
  11496. }
  11497. if (callbacks) {
  11498. ctx->callbacks = *callbacks;
  11499. exit_callback = callbacks->exit_context;
  11500. ctx->callbacks.exit_context = 0;
  11501. }
  11502. ctx->user_data = user_data;
  11503. ctx->handlers = NULL;
  11504. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11505. ctx->shared_lua_websockets = 0;
  11506. #endif
  11507. while (options && (name = *options++) != NULL) {
  11508. if ((idx = get_option_index(name)) == -1) {
  11509. mg_cry(fc(ctx), "Invalid option: %s", name);
  11510. free_context(ctx);
  11511. pthread_setspecific(sTlsKey, NULL);
  11512. return NULL;
  11513. } else if ((value = *options++) == NULL) {
  11514. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11515. free_context(ctx);
  11516. pthread_setspecific(sTlsKey, NULL);
  11517. return NULL;
  11518. }
  11519. if (ctx->config[idx] != NULL) {
  11520. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11521. mg_free(ctx->config[idx]);
  11522. }
  11523. ctx->config[idx] = mg_strdup(value);
  11524. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11525. }
  11526. /* Set default value if needed */
  11527. for (i = 0; config_options[i].name != NULL; i++) {
  11528. default_value = config_options[i].default_value;
  11529. if (ctx->config[i] == NULL && default_value != NULL) {
  11530. ctx->config[i] = mg_strdup(default_value);
  11531. }
  11532. }
  11533. #if defined(NO_FILES)
  11534. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11535. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11536. free_context(ctx);
  11537. pthread_setspecific(sTlsKey, NULL);
  11538. return NULL;
  11539. }
  11540. #endif
  11541. get_system_name(&ctx->systemName);
  11542. /* NOTE(lsm): order is important here. SSL certificates must
  11543. * be initialized before listening ports. UID must be set last. */
  11544. if (!set_gpass_option(ctx) ||
  11545. #if !defined(NO_SSL)
  11546. !set_ssl_option(ctx) ||
  11547. #endif
  11548. !set_ports_option(ctx) ||
  11549. #if !defined(_WIN32)
  11550. !set_uid_option(ctx) ||
  11551. #endif
  11552. !set_acl_option(ctx)) {
  11553. free_context(ctx);
  11554. pthread_setspecific(sTlsKey, NULL);
  11555. return NULL;
  11556. }
  11557. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11558. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11559. * won't kill the whole process. */
  11560. (void)signal(SIGPIPE, SIG_IGN);
  11561. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11562. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11563. if (workerthreadcount > MAX_WORKER_THREADS) {
  11564. mg_cry(fc(ctx), "Too many worker threads");
  11565. free_context(ctx);
  11566. pthread_setspecific(sTlsKey, NULL);
  11567. return NULL;
  11568. }
  11569. if (workerthreadcount > 0) {
  11570. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11571. ctx->workerthreadids =
  11572. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11573. if (ctx->workerthreadids == NULL) {
  11574. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11575. free_context(ctx);
  11576. pthread_setspecific(sTlsKey, NULL);
  11577. return NULL;
  11578. }
  11579. #if defined(ALTERNATIVE_QUEUE)
  11580. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  11581. ctx->cfg_worker_threads);
  11582. if (ctx->client_wait_events == NULL) {
  11583. mg_cry(fc(ctx), "Not enough memory for worker event array");
  11584. mg_free(ctx->workerthreadids);
  11585. free_context(ctx);
  11586. pthread_setspecific(sTlsKey, NULL);
  11587. return NULL;
  11588. }
  11589. ctx->client_socks =
  11590. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  11591. if (ctx->client_wait_events == NULL) {
  11592. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  11593. mg_free(ctx->client_socks);
  11594. mg_free(ctx->workerthreadids);
  11595. free_context(ctx);
  11596. pthread_setspecific(sTlsKey, NULL);
  11597. return NULL;
  11598. }
  11599. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11600. ctx->client_wait_events[i] = event_create();
  11601. if (ctx->client_wait_events[i] == 0) {
  11602. mg_cry(fc(ctx), "Error creating worker event %i", i);
  11603. /* TODO: clean all and exit */
  11604. }
  11605. }
  11606. #endif
  11607. }
  11608. #if defined(USE_TIMERS)
  11609. if (timers_init(ctx) != 0) {
  11610. mg_cry(fc(ctx), "Error creating timers");
  11611. free_context(ctx);
  11612. pthread_setspecific(sTlsKey, NULL);
  11613. return NULL;
  11614. }
  11615. #endif
  11616. /* Context has been created - init user libraries */
  11617. if (ctx->callbacks.init_context) {
  11618. ctx->callbacks.init_context(ctx);
  11619. }
  11620. ctx->callbacks.exit_context = exit_callback;
  11621. ctx->context_type = 1; /* server context */
  11622. /* Start master (listening) thread */
  11623. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11624. /* Start worker threads */
  11625. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11626. struct worker_thread_args *wta =
  11627. mg_malloc(sizeof(struct worker_thread_args));
  11628. if (wta) {
  11629. wta->ctx = ctx;
  11630. wta->index = i;
  11631. }
  11632. if ((wta == NULL)
  11633. || (mg_start_thread_with_id(worker_thread,
  11634. wta,
  11635. &ctx->workerthreadids[i]) != 0)) {
  11636. /* thread was not created */
  11637. if (wta != NULL) {
  11638. mg_free(wta);
  11639. }
  11640. if (i > 0) {
  11641. mg_cry(fc(ctx),
  11642. "Cannot start worker thread %i: error %ld",
  11643. i + 1,
  11644. (long)ERRNO);
  11645. } else {
  11646. mg_cry(fc(ctx),
  11647. "Cannot create threads: error %ld",
  11648. (long)ERRNO);
  11649. free_context(ctx);
  11650. pthread_setspecific(sTlsKey, NULL);
  11651. return NULL;
  11652. }
  11653. break;
  11654. }
  11655. }
  11656. pthread_setspecific(sTlsKey, NULL);
  11657. return ctx;
  11658. }
  11659. /* Feature check API function */
  11660. unsigned
  11661. mg_check_feature(unsigned feature)
  11662. {
  11663. static const unsigned feature_set = 0
  11664. /* Set bits for available features according to API documentation.
  11665. * This bit mask is created at compile time, according to the active
  11666. * preprocessor defines. It is a single const value at runtime. */
  11667. #if !defined(NO_FILES)
  11668. | 0x0001u
  11669. #endif
  11670. #if !defined(NO_SSL)
  11671. | 0x0002u
  11672. #endif
  11673. #if !defined(NO_CGI)
  11674. | 0x0004u
  11675. #endif
  11676. #if defined(USE_IPV6)
  11677. | 0x0008u
  11678. #endif
  11679. #if defined(USE_WEBSOCKET)
  11680. | 0x0010u
  11681. #endif
  11682. #if defined(USE_LUA)
  11683. | 0x0020u
  11684. #endif
  11685. #if defined(USE_DUKTAPE)
  11686. | 0x0040u
  11687. #endif
  11688. #if !defined(NO_CACHING)
  11689. | 0x0080u
  11690. #endif
  11691. /* Set some extra bits not defined in the API documentation.
  11692. * These bits may change without further notice. */
  11693. #if defined(MG_LEGACY_INTERFACE)
  11694. | 0x8000u
  11695. #endif
  11696. #if defined(MEMORY_DEBUGGING)
  11697. | 0x0100u
  11698. #endif
  11699. #if defined(USE_TIMERS)
  11700. | 0x0200u
  11701. #endif
  11702. #if !defined(NO_NONCE_CHECK)
  11703. | 0x0400u
  11704. #endif
  11705. #if !defined(NO_POPEN)
  11706. | 0x0800u
  11707. #endif
  11708. ;
  11709. return (feature & feature_set);
  11710. }