civetweb.c 270 KB

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