civetweb.c 271 KB

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