civetweb.c 293 KB

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