civetweb.c 388 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __clang__
  114. /* When using -Weverything, clang does not accept it's own headers
  115. * in a release build configuration. Disable what is too much in
  116. * -Weverything. */
  117. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  118. #endif
  119. #ifdef __MACH__ /* Apple OSX section */
  120. #ifdef __clang__
  121. /* Avoid warnings for Xopen 7.00 and higher */
  122. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  123. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  124. #endif
  125. #define CLOCK_MONOTONIC (1)
  126. #define CLOCK_REALTIME (2)
  127. #include <sys/errno.h>
  128. #include <sys/time.h>
  129. #include <mach/clock.h>
  130. #include <mach/mach.h>
  131. #include <mach/mach_time.h>
  132. #include <assert.h>
  133. /* clock_gettime is not implemented on OSX prior to 10.12 */
  134. static int
  135. _civet_clock_gettime(int clk_id, struct timespec *t)
  136. {
  137. memset(t, 0, sizeof(*t));
  138. if (clk_id == CLOCK_REALTIME) {
  139. struct timeval now;
  140. int rv = gettimeofday(&now, NULL);
  141. if (rv) {
  142. return rv;
  143. }
  144. t->tv_sec = now.tv_sec;
  145. t->tv_nsec = now.tv_usec * 1000;
  146. return 0;
  147. } else if (clk_id == CLOCK_MONOTONIC) {
  148. static uint64_t clock_start_time = 0;
  149. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  150. uint64_t now = mach_absolute_time();
  151. if (clock_start_time == 0) {
  152. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  153. #if defined(DEBUG)
  154. assert(mach_status == KERN_SUCCESS);
  155. #else
  156. /* appease "unused variable" warning for release builds */
  157. (void)mach_status;
  158. #endif
  159. clock_start_time = now;
  160. }
  161. now = (uint64_t)((double)(now - clock_start_time)
  162. * (double)timebase_ifo.numer
  163. / (double)timebase_ifo.denom);
  164. t->tv_sec = now / 1000000000;
  165. t->tv_nsec = now % 1000000000;
  166. return 0;
  167. }
  168. return -1; /* EINVAL - Clock ID is unknown */
  169. }
  170. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  171. #ifdef __CLOCK_AVAILABILITY
  172. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  173. * declared but it may be NULL at runtime. So we need to check before using
  174. * it. */
  175. static int
  176. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  177. {
  178. if (clock_gettime) {
  179. return clock_gettime(clk_id, t);
  180. }
  181. return _civet_clock_gettime(clk_id, t);
  182. }
  183. #define clock_gettime _civet_safe_clock_gettime
  184. #else
  185. #define clock_gettime _civet_clock_gettime
  186. #endif
  187. #endif
  188. #include <time.h>
  189. #include <stdlib.h>
  190. #include <stdarg.h>
  191. #include <assert.h>
  192. #include <string.h>
  193. #include <ctype.h>
  194. #include <limits.h>
  195. #include <stddef.h>
  196. #include <stdio.h>
  197. #include <stdint.h>
  198. #ifndef INT64_MAX
  199. #define INT64_MAX (9223372036854775807)
  200. #endif
  201. #ifndef MAX_WORKER_THREADS
  202. #define MAX_WORKER_THREADS (1024 * 64)
  203. #endif
  204. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  205. #define SOCKET_TIMEOUT_QUANTUM (2000)
  206. #endif
  207. #define SHUTDOWN_RD (0)
  208. #define SHUTDOWN_WR (1)
  209. #define SHUTDOWN_BOTH (2)
  210. mg_static_assert(MAX_WORKER_THREADS >= 1,
  211. "worker threads must be a positive number");
  212. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  213. "size_t data type size check");
  214. #if defined(_WIN32) \
  215. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  216. #include <windows.h>
  217. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  218. #include <ws2tcpip.h>
  219. typedef const char *SOCK_OPT_TYPE;
  220. #if !defined(PATH_MAX)
  221. #define PATH_MAX (MAX_PATH)
  222. #endif
  223. #if !defined(PATH_MAX)
  224. #define PATH_MAX (4096)
  225. #endif
  226. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  227. #ifndef _IN_PORT_T
  228. #ifndef in_port_t
  229. #define in_port_t u_short
  230. #endif
  231. #endif
  232. #ifndef _WIN32_WCE
  233. #include <process.h>
  234. #include <direct.h>
  235. #include <io.h>
  236. #else /* _WIN32_WCE */
  237. #define NO_CGI /* WinCE has no pipes */
  238. #define NO_POPEN /* WinCE has no popen */
  239. typedef long off_t;
  240. #define errno ((int)(GetLastError()))
  241. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  242. #endif /* _WIN32_WCE */
  243. #define MAKEUQUAD(lo, hi) \
  244. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  245. #define RATE_DIFF (10000000) /* 100 nsecs */
  246. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  247. #define SYS2UNIX_TIME(lo, hi) \
  248. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  249. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  250. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  251. * Also use _strtoui64 on modern M$ compilers */
  252. #if defined(_MSC_VER)
  253. #if (_MSC_VER < 1300)
  254. #define STRX(x) #x
  255. #define STR(x) STRX(x)
  256. #define __func__ __FILE__ ":" STR(__LINE__)
  257. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  258. #define strtoll(x, y, z) (_atoi64(x))
  259. #else
  260. #define __func__ __FUNCTION__
  261. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  262. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  263. #endif
  264. #endif /* _MSC_VER */
  265. #define ERRNO ((int)(GetLastError()))
  266. #define NO_SOCKLEN_T
  267. #if defined(_WIN64) || defined(__MINGW64__)
  268. #define SSL_LIB "ssleay64.dll"
  269. #define CRYPTO_LIB "libeay64.dll"
  270. #else
  271. #define SSL_LIB "ssleay32.dll"
  272. #define CRYPTO_LIB "libeay32.dll"
  273. #endif
  274. #define O_NONBLOCK (0)
  275. #ifndef W_OK
  276. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  277. #endif
  278. #if !defined(EWOULDBLOCK)
  279. #define EWOULDBLOCK WSAEWOULDBLOCK
  280. #endif /* !EWOULDBLOCK */
  281. #define _POSIX_
  282. #define INT64_FMT "I64d"
  283. #define UINT64_FMT "I64u"
  284. #define WINCDECL __cdecl
  285. #define vsnprintf_impl _vsnprintf
  286. #define access _access
  287. #define mg_sleep(x) (Sleep(x))
  288. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  289. #ifndef popen
  290. #define popen(x, y) (_popen(x, y))
  291. #endif
  292. #ifndef pclose
  293. #define pclose(x) (_pclose(x))
  294. #endif
  295. #define close(x) (_close(x))
  296. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  297. #define RTLD_LAZY (0)
  298. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  299. #define fdopen(x, y) (_fdopen((x), (y)))
  300. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  301. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  302. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  303. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  304. #define sleep(x) (Sleep((x)*1000))
  305. #define rmdir(x) (_rmdir(x))
  306. #define timegm(x) (_mkgmtime(x))
  307. #if !defined(fileno)
  308. #define fileno(x) (_fileno(x))
  309. #endif /* !fileno MINGW #defines fileno */
  310. typedef HANDLE pthread_mutex_t;
  311. typedef DWORD pthread_key_t;
  312. typedef HANDLE pthread_t;
  313. typedef struct {
  314. CRITICAL_SECTION threadIdSec;
  315. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  316. } pthread_cond_t;
  317. #ifndef __clockid_t_defined
  318. typedef DWORD clockid_t;
  319. #endif
  320. #ifndef CLOCK_MONOTONIC
  321. #define CLOCK_MONOTONIC (1)
  322. #endif
  323. #ifndef CLOCK_REALTIME
  324. #define CLOCK_REALTIME (2)
  325. #endif
  326. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  327. #define _TIMESPEC_DEFINED
  328. #endif
  329. #ifndef _TIMESPEC_DEFINED
  330. struct timespec {
  331. time_t tv_sec; /* seconds */
  332. long tv_nsec; /* nanoseconds */
  333. };
  334. #endif
  335. #if !defined(WIN_PTHREADS_TIME_H)
  336. #define MUST_IMPLEMENT_CLOCK_GETTIME
  337. #endif
  338. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  339. #define clock_gettime mg_clock_gettime
  340. static int
  341. clock_gettime(clockid_t clk_id, struct timespec *tp)
  342. {
  343. FILETIME ft;
  344. ULARGE_INTEGER li;
  345. BOOL ok = FALSE;
  346. double d;
  347. static double perfcnt_per_sec = 0.0;
  348. if (tp) {
  349. memset(tp, 0, sizeof(*tp));
  350. if (clk_id == CLOCK_REALTIME) {
  351. GetSystemTimeAsFileTime(&ft);
  352. li.LowPart = ft.dwLowDateTime;
  353. li.HighPart = ft.dwHighDateTime;
  354. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  355. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  356. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  357. ok = TRUE;
  358. } else if (clk_id == CLOCK_MONOTONIC) {
  359. if (perfcnt_per_sec == 0.0) {
  360. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  361. perfcnt_per_sec = 1.0 / li.QuadPart;
  362. }
  363. if (perfcnt_per_sec != 0.0) {
  364. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  365. d = li.QuadPart * perfcnt_per_sec;
  366. tp->tv_sec = (time_t)d;
  367. d -= tp->tv_sec;
  368. tp->tv_nsec = (long)(d * 1.0E9);
  369. ok = TRUE;
  370. }
  371. }
  372. }
  373. return ok ? 0 : -1;
  374. }
  375. #endif
  376. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  377. static int pthread_mutex_lock(pthread_mutex_t *);
  378. static int pthread_mutex_unlock(pthread_mutex_t *);
  379. static void path_to_unicode(const struct mg_connection *conn,
  380. const char *path,
  381. wchar_t *wbuf,
  382. size_t wbuf_len);
  383. /* All file operations need to be rewritten to solve #246. */
  384. #include "file_ops.inl"
  385. struct mg_file;
  386. static const char *
  387. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  388. /* POSIX dirent interface */
  389. struct dirent {
  390. char d_name[PATH_MAX];
  391. };
  392. typedef struct DIR {
  393. HANDLE handle;
  394. WIN32_FIND_DATAW info;
  395. struct dirent result;
  396. } DIR;
  397. #if defined(_WIN32) && !defined(POLLIN)
  398. #ifndef HAVE_POLL
  399. struct pollfd {
  400. SOCKET fd;
  401. short events;
  402. short revents;
  403. };
  404. #define POLLIN (0x0300)
  405. #endif
  406. #endif
  407. /* Mark required libraries */
  408. #if defined(_MSC_VER)
  409. #pragma comment(lib, "Ws2_32.lib")
  410. #endif
  411. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  412. WINDOWS / UNIX include block */
  413. #include <sys/wait.h>
  414. #include <sys/socket.h>
  415. #include <sys/poll.h>
  416. #include <netinet/in.h>
  417. #include <arpa/inet.h>
  418. #include <sys/time.h>
  419. #include <sys/utsname.h>
  420. #include <stdint.h>
  421. #include <inttypes.h>
  422. #include <netdb.h>
  423. #include <netinet/tcp.h>
  424. typedef const void *SOCK_OPT_TYPE;
  425. #if defined(ANDROID)
  426. typedef unsigned short int in_port_t;
  427. #endif
  428. #include <pwd.h>
  429. #include <unistd.h>
  430. #include <grp.h>
  431. #include <dirent.h>
  432. #define vsnprintf_impl vsnprintf
  433. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  434. #include <dlfcn.h>
  435. #endif
  436. #include <pthread.h>
  437. #if defined(__MACH__)
  438. #define SSL_LIB "libssl.dylib"
  439. #define CRYPTO_LIB "libcrypto.dylib"
  440. #else
  441. #if !defined(SSL_LIB)
  442. #define SSL_LIB "libssl.so"
  443. #endif
  444. #if !defined(CRYPTO_LIB)
  445. #define CRYPTO_LIB "libcrypto.so"
  446. #endif
  447. #endif
  448. #ifndef O_BINARY
  449. #define O_BINARY (0)
  450. #endif /* O_BINARY */
  451. #define closesocket(a) (close(a))
  452. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  453. #define mg_remove(conn, x) (remove(x))
  454. #define mg_sleep(x) (usleep((x)*1000))
  455. #define mg_opendir(conn, x) (opendir(x))
  456. #define mg_closedir(x) (closedir(x))
  457. #define mg_readdir(x) (readdir(x))
  458. #define ERRNO (errno)
  459. #define INVALID_SOCKET (-1)
  460. #define INT64_FMT PRId64
  461. #define UINT64_FMT PRIu64
  462. typedef int SOCKET;
  463. #define WINCDECL
  464. #if defined(__hpux)
  465. /* HPUX 11 does not have monotonic, fall back to realtime */
  466. #ifndef CLOCK_MONOTONIC
  467. #define CLOCK_MONOTONIC CLOCK_REALTIME
  468. #endif
  469. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  470. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  471. * the prototypes use int* rather than socklen_t* which matches the
  472. * actual library expectation. When called with the wrong size arg
  473. * accept() returns a zero client inet addr and check_acl() always
  474. * fails. Since socklen_t is widely used below, just force replace
  475. * their typedef with int. - DTL
  476. */
  477. #define socklen_t int
  478. #endif /* hpux */
  479. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  480. WINDOWS / UNIX include block */
  481. /* va_copy should always be a macro, C99 and C++11 - DTL */
  482. #ifndef va_copy
  483. #define va_copy(x, y) ((x) = (y))
  484. #endif
  485. #ifdef _WIN32
  486. /* Create substitutes for POSIX functions in Win32. */
  487. #if defined(__MINGW32__)
  488. /* Show no warning in case system functions are not used. */
  489. #pragma GCC diagnostic push
  490. #pragma GCC diagnostic ignored "-Wunused-function"
  491. #endif
  492. static CRITICAL_SECTION global_log_file_lock;
  493. static DWORD
  494. pthread_self(void)
  495. {
  496. return GetCurrentThreadId();
  497. }
  498. static int
  499. pthread_key_create(
  500. pthread_key_t *key,
  501. void (*_ignored)(void *) /* destructor not supported for Windows */
  502. )
  503. {
  504. (void)_ignored;
  505. if ((key != 0)) {
  506. *key = TlsAlloc();
  507. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  508. }
  509. return -2;
  510. }
  511. static int
  512. pthread_key_delete(pthread_key_t key)
  513. {
  514. return TlsFree(key) ? 0 : 1;
  515. }
  516. static int
  517. pthread_setspecific(pthread_key_t key, void *value)
  518. {
  519. return TlsSetValue(key, value) ? 0 : 1;
  520. }
  521. static void *
  522. pthread_getspecific(pthread_key_t key)
  523. {
  524. return TlsGetValue(key);
  525. }
  526. #if defined(__MINGW32__)
  527. /* Enable unused function warning again */
  528. #pragma GCC diagnostic pop
  529. #endif
  530. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  531. #else
  532. static pthread_mutexattr_t pthread_mutex_attr;
  533. #endif /* _WIN32 */
  534. #define PASSWORDS_FILE_NAME ".htpasswd"
  535. #define CGI_ENVIRONMENT_SIZE (4096)
  536. #define MAX_CGI_ENVIR_VARS (256)
  537. #define MG_BUF_LEN (8192)
  538. #ifndef MAX_REQUEST_SIZE
  539. #define MAX_REQUEST_SIZE (16384)
  540. #endif
  541. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  542. "request size length must be a positive number");
  543. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  544. #if defined(_WIN32_WCE)
  545. /* Create substitutes for POSIX functions in Win32. */
  546. #if defined(__MINGW32__)
  547. /* Show no warning in case system functions are not used. */
  548. #pragma GCC diagnostic push
  549. #pragma GCC diagnostic ignored "-Wunused-function"
  550. #endif
  551. static time_t
  552. time(time_t *ptime)
  553. {
  554. time_t t;
  555. SYSTEMTIME st;
  556. FILETIME ft;
  557. GetSystemTime(&st);
  558. SystemTimeToFileTime(&st, &ft);
  559. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  560. if (ptime != NULL) {
  561. *ptime = t;
  562. }
  563. return t;
  564. }
  565. static struct tm *
  566. localtime_s(const time_t *ptime, struct tm *ptm)
  567. {
  568. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  569. FILETIME ft, lft;
  570. SYSTEMTIME st;
  571. TIME_ZONE_INFORMATION tzinfo;
  572. if (ptm == NULL) {
  573. return NULL;
  574. }
  575. *(int64_t *)&ft = t;
  576. FileTimeToLocalFileTime(&ft, &lft);
  577. FileTimeToSystemTime(&lft, &st);
  578. ptm->tm_year = st.wYear - 1900;
  579. ptm->tm_mon = st.wMonth - 1;
  580. ptm->tm_wday = st.wDayOfWeek;
  581. ptm->tm_mday = st.wDay;
  582. ptm->tm_hour = st.wHour;
  583. ptm->tm_min = st.wMinute;
  584. ptm->tm_sec = st.wSecond;
  585. ptm->tm_yday = 0; /* hope nobody uses this */
  586. ptm->tm_isdst =
  587. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  588. return ptm;
  589. }
  590. static struct tm *
  591. gmtime_s(const time_t *ptime, struct tm *ptm)
  592. {
  593. /* FIXME(lsm): fix this. */
  594. return localtime_s(ptime, ptm);
  595. }
  596. static int mg_atomic_inc(volatile int *addr);
  597. static struct tm tm_array[MAX_WORKER_THREADS];
  598. static int tm_index = 0;
  599. static struct tm *
  600. localtime(const time_t *ptime)
  601. {
  602. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  603. return localtime_s(ptime, tm_array + i);
  604. }
  605. static struct tm *
  606. gmtime(const time_t *ptime)
  607. {
  608. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  609. return gmtime_s(ptime, tm_array + i);
  610. }
  611. static size_t
  612. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  613. {
  614. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  615. * for WinCE"); */
  616. return 0;
  617. }
  618. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  619. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  620. #define remove(f) mg_remove(NULL, f)
  621. static int
  622. rename(const char *a, const char *b)
  623. {
  624. wchar_t wa[PATH_MAX];
  625. wchar_t wb[PATH_MAX];
  626. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  627. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  628. return MoveFileW(wa, wb) ? 0 : -1;
  629. }
  630. struct stat {
  631. int64_t st_size;
  632. time_t st_mtime;
  633. };
  634. static int
  635. stat(const char *name, struct stat *st)
  636. {
  637. wchar_t wbuf[PATH_MAX];
  638. WIN32_FILE_ATTRIBUTE_DATA attr;
  639. time_t creation_time, write_time;
  640. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  641. memset(&attr, 0, sizeof(attr));
  642. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  643. st->st_size =
  644. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  645. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  646. attr.ftLastWriteTime.dwHighDateTime);
  647. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  648. attr.ftCreationTime.dwHighDateTime);
  649. if (creation_time > write_time) {
  650. st->st_mtime = creation_time;
  651. } else {
  652. st->st_mtime = write_time;
  653. }
  654. return 0;
  655. }
  656. #define access(x, a) 1 /* not required anyway */
  657. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  658. #define EEXIST 1 /* TODO: See Windows error codes */
  659. #define EACCES 2 /* TODO: See Windows error codes */
  660. #define ENOENT 3 /* TODO: See Windows Error codes */
  661. #if defined(__MINGW32__)
  662. /* Enable unused function warning again */
  663. #pragma GCC diagnostic pop
  664. #endif
  665. #endif /* defined(_WIN32_WCE) */
  666. static int
  667. mg_atomic_inc(volatile int *addr)
  668. {
  669. int ret;
  670. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  671. /* Depending on the SDK, this function uses either
  672. * (volatile unsigned int *) or (volatile LONG *),
  673. * so whatever you use, the other SDK is likely to raise a warning. */
  674. ret = InterlockedIncrement((volatile long *)addr);
  675. #elif defined(__GNUC__) \
  676. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  677. ret = __sync_add_and_fetch(addr, 1);
  678. #else
  679. ret = (++(*addr));
  680. #endif
  681. return ret;
  682. }
  683. static int
  684. mg_atomic_dec(volatile int *addr)
  685. {
  686. int ret;
  687. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  688. /* Depending on the SDK, this function uses either
  689. * (volatile unsigned int *) or (volatile LONG *),
  690. * so whatever you use, the other SDK is likely to raise a warning. */
  691. ret = InterlockedDecrement((volatile long *)addr);
  692. #elif defined(__GNUC__) \
  693. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  694. ret = __sync_sub_and_fetch(addr, 1);
  695. #else
  696. ret = (--(*addr));
  697. #endif
  698. return ret;
  699. }
  700. #if defined(MEMORY_DEBUGGING)
  701. static unsigned long mg_memory_debug_blockCount = 0;
  702. static unsigned long mg_memory_debug_totalMemUsed = 0;
  703. static void *
  704. mg_malloc_ex(size_t size, const char *file, unsigned line)
  705. {
  706. void *data = malloc(size + sizeof(size_t));
  707. void *memory = 0;
  708. char mallocStr[256];
  709. if (data) {
  710. *(size_t *)data = size;
  711. mg_memory_debug_totalMemUsed += size;
  712. mg_memory_debug_blockCount++;
  713. memory = (void *)(((char *)data) + sizeof(size_t));
  714. }
  715. sprintf(mallocStr,
  716. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  717. memory,
  718. (unsigned long)size,
  719. mg_memory_debug_totalMemUsed,
  720. mg_memory_debug_blockCount,
  721. file,
  722. line);
  723. #if defined(_WIN32)
  724. OutputDebugStringA(mallocStr);
  725. #else
  726. DEBUG_TRACE("%s", mallocStr);
  727. #endif
  728. return memory;
  729. }
  730. static void *
  731. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  732. {
  733. void *data = mg_malloc_ex(size * count, file, line);
  734. if (data) {
  735. memset(data, 0, size * count);
  736. }
  737. return data;
  738. }
  739. static void
  740. mg_free_ex(void *memory, const char *file, unsigned line)
  741. {
  742. char mallocStr[256];
  743. void *data = (void *)(((char *)memory) - sizeof(size_t));
  744. size_t size;
  745. if (memory) {
  746. size = *(size_t *)data;
  747. mg_memory_debug_totalMemUsed -= size;
  748. mg_memory_debug_blockCount--;
  749. sprintf(mallocStr,
  750. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  751. memory,
  752. (unsigned long)size,
  753. mg_memory_debug_totalMemUsed,
  754. mg_memory_debug_blockCount,
  755. file,
  756. line);
  757. #if defined(_WIN32)
  758. OutputDebugStringA(mallocStr);
  759. #else
  760. DEBUG_TRACE("%s", mallocStr);
  761. #endif
  762. free(data);
  763. }
  764. }
  765. static void *
  766. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  767. {
  768. char mallocStr[256];
  769. void *data;
  770. void *_realloc;
  771. size_t oldsize;
  772. if (newsize) {
  773. if (memory) {
  774. data = (void *)(((char *)memory) - sizeof(size_t));
  775. oldsize = *(size_t *)data;
  776. _realloc = realloc(data, newsize + sizeof(size_t));
  777. if (_realloc) {
  778. data = _realloc;
  779. mg_memory_debug_totalMemUsed -= oldsize;
  780. sprintf(mallocStr,
  781. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  782. memory,
  783. (unsigned long)oldsize,
  784. mg_memory_debug_totalMemUsed,
  785. mg_memory_debug_blockCount,
  786. file,
  787. line);
  788. #if defined(_WIN32)
  789. OutputDebugStringA(mallocStr);
  790. #else
  791. DEBUG_TRACE("%s", mallocStr);
  792. #endif
  793. mg_memory_debug_totalMemUsed += newsize;
  794. sprintf(mallocStr,
  795. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  796. memory,
  797. (unsigned long)newsize,
  798. mg_memory_debug_totalMemUsed,
  799. mg_memory_debug_blockCount,
  800. file,
  801. line);
  802. #if defined(_WIN32)
  803. OutputDebugStringA(mallocStr);
  804. #else
  805. DEBUG_TRACE("%s", mallocStr);
  806. #endif
  807. *(size_t *)data = newsize;
  808. data = (void *)(((char *)data) + sizeof(size_t));
  809. } else {
  810. #if defined(_WIN32)
  811. OutputDebugStringA("MEM: realloc failed\n");
  812. #else
  813. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  814. #endif
  815. return _realloc;
  816. }
  817. } else {
  818. data = mg_malloc_ex(newsize, file, line);
  819. }
  820. } else {
  821. data = 0;
  822. mg_free_ex(memory, file, line);
  823. }
  824. return data;
  825. }
  826. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  827. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  828. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  829. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  830. #else
  831. static __inline void *
  832. mg_malloc(size_t a)
  833. {
  834. return malloc(a);
  835. }
  836. static __inline void *
  837. mg_calloc(size_t a, size_t b)
  838. {
  839. return calloc(a, b);
  840. }
  841. static __inline void *
  842. mg_realloc(void *a, size_t b)
  843. {
  844. return realloc(a, b);
  845. }
  846. static __inline void
  847. mg_free(void *a)
  848. {
  849. free(a);
  850. }
  851. #endif
  852. static void mg_vsnprintf(const struct mg_connection *conn,
  853. int *truncated,
  854. char *buf,
  855. size_t buflen,
  856. const char *fmt,
  857. va_list ap);
  858. static void mg_snprintf(const struct mg_connection *conn,
  859. int *truncated,
  860. char *buf,
  861. size_t buflen,
  862. PRINTF_FORMAT_STRING(const char *fmt),
  863. ...) PRINTF_ARGS(5, 6);
  864. /* This following lines are just meant as a reminder to use the mg-functions
  865. * for memory management */
  866. #ifdef malloc
  867. #undef malloc
  868. #endif
  869. #ifdef calloc
  870. #undef calloc
  871. #endif
  872. #ifdef realloc
  873. #undef realloc
  874. #endif
  875. #ifdef free
  876. #undef free
  877. #endif
  878. #ifdef snprintf
  879. #undef snprintf
  880. #endif
  881. #ifdef vsnprintf
  882. #undef vsnprintf
  883. #endif
  884. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  885. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  886. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  887. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  888. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  889. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  890. * but this define only works well for Windows. */
  891. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  892. #endif
  893. static pthread_key_t sTlsKey; /* Thread local storage index */
  894. static int sTlsInit = 0;
  895. static int thread_idx_max = 0;
  896. struct mg_workerTLS {
  897. int is_master;
  898. unsigned long thread_idx;
  899. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  900. HANDLE pthread_cond_helper_mutex;
  901. struct mg_workerTLS *next_waiting_thread;
  902. #endif
  903. };
  904. #if defined(__GNUC__) || defined(__MINGW32__)
  905. /* Show no warning in case system functions are not used. */
  906. #pragma GCC diagnostic push
  907. #pragma GCC diagnostic ignored "-Wunused-function"
  908. #endif
  909. #if defined(__clang__)
  910. /* Show no warning in case system functions are not used. */
  911. #pragma clang diagnostic push
  912. #pragma clang diagnostic ignored "-Wunused-function"
  913. #endif
  914. /* Get a unique thread ID as unsigned long, independent from the data type
  915. * of thread IDs defined by the operating system API.
  916. * If two calls to mg_current_thread_id return the same value, they calls
  917. * are done from the same thread. If they return different values, they are
  918. * done from different threads. (Provided this function is used in the same
  919. * process context and threads are not repeatedly created and deleted, but
  920. * CivetWeb does not do that).
  921. * This function must match the signature required for SSL id callbacks:
  922. * CRYPTO_set_id_callback
  923. */
  924. static unsigned long
  925. mg_current_thread_id(void)
  926. {
  927. #ifdef _WIN32
  928. return GetCurrentThreadId();
  929. #else
  930. #ifdef __clang__
  931. #pragma clang diagnostic push
  932. #pragma clang diagnostic ignored "-Wunreachable-code"
  933. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  934. * or not, so one of the two conditions will be unreachable by construction.
  935. * Unfortunately the C standard does not define a way to check this at
  936. * compile time, since the #if preprocessor conditions can not use the sizeof
  937. * operator as an argument. */
  938. #endif
  939. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  940. /* This is the problematic case for CRYPTO_set_id_callback:
  941. * The OS pthread_t can not be cast to unsigned long. */
  942. struct mg_workerTLS *tls =
  943. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  944. if (tls == NULL) {
  945. /* SSL called from an unknown thread: Create some thread index.
  946. */
  947. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  948. tls->is_master = -2; /* -2 means "3rd party thread" */
  949. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  950. pthread_setspecific(sTlsKey, tls);
  951. }
  952. return tls->thread_idx;
  953. } else {
  954. /* pthread_t may be any data type, so a simple cast to unsigned long
  955. * can rise a warning/error, depending on the platform.
  956. * Here memcpy is used as an anything-to-anything cast. */
  957. unsigned long ret = 0;
  958. pthread_t t = pthread_self();
  959. memcpy(&ret, &t, sizeof(pthread_t));
  960. return ret;
  961. }
  962. #ifdef __clang__
  963. #pragma clang diagnostic pop
  964. #endif
  965. #endif
  966. }
  967. #if defined(__GNUC__)
  968. /* Show no warning in case system functions are not used. */
  969. #pragma GCC diagnostic pop
  970. #endif
  971. #if defined(__clang__)
  972. /* Show no warning in case system functions are not used. */
  973. #pragma clang diagnostic pop
  974. #endif
  975. #if !defined(DEBUG_TRACE)
  976. #if defined(DEBUG)
  977. static void DEBUG_TRACE_FUNC(const char *func,
  978. unsigned line,
  979. PRINTF_FORMAT_STRING(const char *fmt),
  980. ...) PRINTF_ARGS(3, 4);
  981. static void
  982. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  983. {
  984. va_list args;
  985. struct timespec tsnow;
  986. uint64_t nsnow;
  987. static uint64_t nslast;
  988. /* Get some operating system independent thread id */
  989. unsigned long thread_id = mg_current_thread_id();
  990. clock_gettime(CLOCK_REALTIME, &tsnow);
  991. nsnow = (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  992. flockfile(stdout);
  993. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  994. (unsigned long)tsnow.tv_sec,
  995. (unsigned long)tsnow.tv_nsec,
  996. nsnow - nslast,
  997. thread_id,
  998. func,
  999. line);
  1000. va_start(args, fmt);
  1001. vprintf(fmt, args);
  1002. va_end(args);
  1003. putchar('\n');
  1004. fflush(stdout);
  1005. funlockfile(stdout);
  1006. nslast = nsnow;
  1007. }
  1008. #define DEBUG_TRACE(fmt, ...) \
  1009. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1010. #else
  1011. #define DEBUG_TRACE(fmt, ...) \
  1012. do { \
  1013. } while (0)
  1014. #endif /* DEBUG */
  1015. #endif /* DEBUG_TRACE */
  1016. #define MD5_STATIC static
  1017. #include "md5.inl"
  1018. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1019. #ifdef NO_SOCKLEN_T
  1020. typedef int socklen_t;
  1021. #endif /* NO_SOCKLEN_T */
  1022. #define _DARWIN_UNLIMITED_SELECT
  1023. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1024. #if !defined(MSG_NOSIGNAL)
  1025. #define MSG_NOSIGNAL (0)
  1026. #endif
  1027. #if !defined(SOMAXCONN)
  1028. #define SOMAXCONN (100)
  1029. #endif
  1030. /* Size of the accepted socket queue */
  1031. #if !defined(MGSQLEN)
  1032. #define MGSQLEN (20)
  1033. #endif
  1034. #if defined(NO_SSL)
  1035. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1036. typedef struct SSL_CTX SSL_CTX;
  1037. #else
  1038. #if defined(NO_SSL_DL)
  1039. #include <openssl/ssl.h>
  1040. #include <openssl/err.h>
  1041. #include <openssl/crypto.h>
  1042. #include <openssl/x509.h>
  1043. #include <openssl/pem.h>
  1044. #include <openssl/engine.h>
  1045. #include <openssl/conf.h>
  1046. #include <openssl/dh.h>
  1047. #else
  1048. /* SSL loaded dynamically from DLL.
  1049. * I put the prototypes here to be independent from OpenSSL source
  1050. * installation. */
  1051. typedef struct ssl_st SSL;
  1052. typedef struct ssl_method_st SSL_METHOD;
  1053. typedef struct ssl_ctx_st SSL_CTX;
  1054. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1055. typedef struct x509_name X509_NAME;
  1056. typedef struct asn1_integer ASN1_INTEGER;
  1057. typedef struct evp_md EVP_MD;
  1058. typedef struct x509 X509;
  1059. #define SSL_CTRL_OPTIONS (32)
  1060. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1061. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1062. #define SSL_VERIFY_NONE (0)
  1063. #define SSL_VERIFY_PEER (1)
  1064. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1065. #define SSL_VERIFY_CLIENT_ONCE (4)
  1066. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1067. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1068. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1069. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1070. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1071. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1072. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1073. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1074. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1075. #define SSL_ERROR_NONE (0)
  1076. #define SSL_ERROR_SSL (1)
  1077. #define SSL_ERROR_WANT_READ (2)
  1078. #define SSL_ERROR_WANT_WRITE (3)
  1079. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1080. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1081. #define SSL_ERROR_ZERO_RETURN (6)
  1082. #define SSL_ERROR_WANT_CONNECT (7)
  1083. #define SSL_ERROR_WANT_ACCEPT (8)
  1084. struct ssl_func {
  1085. const char *name; /* SSL function name */
  1086. void (*ptr)(void); /* Function pointer */
  1087. };
  1088. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1089. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1090. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1091. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1092. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1093. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1094. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1095. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1096. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1097. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1098. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1099. #define SSL_CTX_use_PrivateKey_file \
  1100. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1101. #define SSL_CTX_use_certificate_file \
  1102. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1103. #define SSL_CTX_set_default_passwd_cb \
  1104. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1105. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1106. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1107. #define SSL_CTX_use_certificate_chain_file \
  1108. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1109. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1110. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1111. #define SSL_CTX_set_verify \
  1112. (*(void (*)(SSL_CTX *, \
  1113. int, \
  1114. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1115. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1116. #define SSL_CTX_load_verify_locations \
  1117. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1118. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1119. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1120. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1121. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1122. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1123. #define SSL_CIPHER_get_name \
  1124. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1125. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1126. #define SSL_CTX_set_session_id_context \
  1127. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1128. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1129. #define SSL_CTX_set_cipher_list \
  1130. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1131. #define SSL_CTX_set_options(ctx, op) \
  1132. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1133. #define SSL_CTX_clear_options(ctx, op) \
  1134. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1135. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1136. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1137. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1138. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1139. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1140. #define CRYPTO_set_locking_callback \
  1141. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1142. #define CRYPTO_set_id_callback \
  1143. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1144. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1145. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1146. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1147. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1148. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1149. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1150. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1151. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1152. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1153. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1154. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1155. #define X509_NAME_oneline \
  1156. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1157. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1158. #define i2c_ASN1_INTEGER \
  1159. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1160. #define EVP_get_digestbyname \
  1161. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1162. #define ASN1_digest \
  1163. (*(int (*)(int (*)(), \
  1164. const EVP_MD *, \
  1165. char *, \
  1166. unsigned char *, \
  1167. unsigned int *))crypto_sw[18].ptr)
  1168. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1169. /* set_ssl_option() function updates this array.
  1170. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1171. * of respective functions. The macros above (like SSL_connect()) are really
  1172. * just calling these functions indirectly via the pointer. */
  1173. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1174. {"SSL_accept", NULL},
  1175. {"SSL_connect", NULL},
  1176. {"SSL_read", NULL},
  1177. {"SSL_write", NULL},
  1178. {"SSL_get_error", NULL},
  1179. {"SSL_set_fd", NULL},
  1180. {"SSL_new", NULL},
  1181. {"SSL_CTX_new", NULL},
  1182. {"SSLv23_server_method", NULL},
  1183. {"SSL_library_init", NULL},
  1184. {"SSL_CTX_use_PrivateKey_file", NULL},
  1185. {"SSL_CTX_use_certificate_file", NULL},
  1186. {"SSL_CTX_set_default_passwd_cb", NULL},
  1187. {"SSL_CTX_free", NULL},
  1188. {"SSL_load_error_strings", NULL},
  1189. {"SSL_CTX_use_certificate_chain_file", NULL},
  1190. {"SSLv23_client_method", NULL},
  1191. {"SSL_pending", NULL},
  1192. {"SSL_CTX_set_verify", NULL},
  1193. {"SSL_shutdown", NULL},
  1194. {"SSL_CTX_load_verify_locations", NULL},
  1195. {"SSL_CTX_set_default_verify_paths", NULL},
  1196. {"SSL_CTX_set_verify_depth", NULL},
  1197. {"SSL_get_peer_certificate", NULL},
  1198. {"SSL_get_version", NULL},
  1199. {"SSL_get_current_cipher", NULL},
  1200. {"SSL_CIPHER_get_name", NULL},
  1201. {"SSL_CTX_check_private_key", NULL},
  1202. {"SSL_CTX_set_session_id_context", NULL},
  1203. {"SSL_CTX_ctrl", NULL},
  1204. {"SSL_CTX_set_cipher_list", NULL},
  1205. {NULL, NULL}};
  1206. /* Similar array as ssl_sw. These functions could be located in different
  1207. * lib. */
  1208. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1209. {"CRYPTO_set_locking_callback", NULL},
  1210. {"CRYPTO_set_id_callback", NULL},
  1211. {"ERR_get_error", NULL},
  1212. {"ERR_error_string", NULL},
  1213. {"ERR_remove_state", NULL},
  1214. {"ERR_free_strings", NULL},
  1215. {"ENGINE_cleanup", NULL},
  1216. {"CONF_modules_unload", NULL},
  1217. {"CRYPTO_cleanup_all_ex_data", NULL},
  1218. {"EVP_cleanup", NULL},
  1219. {"X509_free", NULL},
  1220. {"X509_get_subject_name", NULL},
  1221. {"X509_get_issuer_name", NULL},
  1222. {"X509_NAME_oneline", NULL},
  1223. {"X509_get_serialNumber", NULL},
  1224. {"i2c_ASN1_INTEGER", NULL},
  1225. {"EVP_get_digestbyname", NULL},
  1226. {"ASN1_digest", NULL},
  1227. {"i2d_X509", NULL},
  1228. {NULL, NULL}};
  1229. #endif /* NO_SSL_DL */
  1230. #endif /* NO_SSL */
  1231. #if !defined(NO_CACHING)
  1232. static const char *month_names[] = {"Jan",
  1233. "Feb",
  1234. "Mar",
  1235. "Apr",
  1236. "May",
  1237. "Jun",
  1238. "Jul",
  1239. "Aug",
  1240. "Sep",
  1241. "Oct",
  1242. "Nov",
  1243. "Dec"};
  1244. #endif /* !NO_CACHING */
  1245. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1246. * union u. */
  1247. union usa {
  1248. struct sockaddr sa;
  1249. struct sockaddr_in sin;
  1250. #if defined(USE_IPV6)
  1251. struct sockaddr_in6 sin6;
  1252. #endif
  1253. };
  1254. /* Describes a string (chunk of memory). */
  1255. struct vec {
  1256. const char *ptr;
  1257. size_t len;
  1258. };
  1259. struct mg_file_stat {
  1260. /* File properties filled by mg_stat: */
  1261. uint64_t size;
  1262. time_t last_modified;
  1263. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1264. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1265. * case we need a "Content-Eencoding: gzip" header */
  1266. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1267. };
  1268. struct mg_file_in_memory {
  1269. char *p;
  1270. uint32_t pos;
  1271. char mode;
  1272. };
  1273. struct mg_file_access {
  1274. /* File properties filled by mg_fopen: */
  1275. FILE *fp;
  1276. /* TODO: struct mg_file_in_memory *mf; */
  1277. const char *membuf; /* TODO: remove */
  1278. };
  1279. struct mg_file {
  1280. struct mg_file_stat stat;
  1281. struct mg_file_access access;
  1282. };
  1283. #define STRUCT_FILE_INITIALIZER \
  1284. { \
  1285. { \
  1286. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1287. } \
  1288. , \
  1289. { \
  1290. (FILE *) NULL, (const char *)NULL \
  1291. } \
  1292. }
  1293. /* Describes listening socket, or socket which was accept()-ed by the master
  1294. * thread and queued for future handling by the worker thread. */
  1295. struct socket {
  1296. SOCKET sock; /* Listening socket */
  1297. union usa lsa; /* Local socket address */
  1298. union usa rsa; /* Remote socket address */
  1299. unsigned char is_ssl; /* Is port SSL-ed */
  1300. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1301. * port */
  1302. unsigned char in_use; /* Is valid */
  1303. };
  1304. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1305. enum {
  1306. CGI_EXTENSIONS,
  1307. CGI_ENVIRONMENT,
  1308. PUT_DELETE_PASSWORDS_FILE,
  1309. CGI_INTERPRETER,
  1310. PROTECT_URI,
  1311. AUTHENTICATION_DOMAIN,
  1312. SSI_EXTENSIONS,
  1313. THROTTLE,
  1314. ACCESS_LOG_FILE,
  1315. ENABLE_DIRECTORY_LISTING,
  1316. ERROR_LOG_FILE,
  1317. GLOBAL_PASSWORDS_FILE,
  1318. INDEX_FILES,
  1319. ENABLE_KEEP_ALIVE,
  1320. ACCESS_CONTROL_LIST,
  1321. EXTRA_MIME_TYPES,
  1322. LISTENING_PORTS,
  1323. DOCUMENT_ROOT,
  1324. SSL_CERTIFICATE,
  1325. NUM_THREADS,
  1326. RUN_AS_USER,
  1327. REWRITE,
  1328. HIDE_FILES,
  1329. REQUEST_TIMEOUT,
  1330. KEEP_ALIVE_TIMEOUT,
  1331. LINGER_TIMEOUT,
  1332. SSL_DO_VERIFY_PEER,
  1333. SSL_CA_PATH,
  1334. SSL_CA_FILE,
  1335. SSL_VERIFY_DEPTH,
  1336. SSL_DEFAULT_VERIFY_PATHS,
  1337. SSL_CIPHER_LIST,
  1338. SSL_PROTOCOL_VERSION,
  1339. SSL_SHORT_TRUST,
  1340. #if defined(USE_WEBSOCKET)
  1341. WEBSOCKET_TIMEOUT,
  1342. #endif
  1343. DECODE_URL,
  1344. #if defined(USE_LUA)
  1345. LUA_PRELOAD_FILE,
  1346. LUA_SCRIPT_EXTENSIONS,
  1347. LUA_SERVER_PAGE_EXTENSIONS,
  1348. #endif
  1349. #if defined(USE_DUKTAPE)
  1350. DUKTAPE_SCRIPT_EXTENSIONS,
  1351. #endif
  1352. #if defined(USE_WEBSOCKET)
  1353. WEBSOCKET_ROOT,
  1354. #endif
  1355. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1356. LUA_WEBSOCKET_EXTENSIONS,
  1357. #endif
  1358. ACCESS_CONTROL_ALLOW_ORIGIN,
  1359. ERROR_PAGES,
  1360. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1361. * socket option typedef TCP_NODELAY. */
  1362. #if !defined(NO_CACHING)
  1363. STATIC_FILE_MAX_AGE,
  1364. #endif
  1365. #if defined(__linux__)
  1366. ALLOW_SENDFILE_CALL,
  1367. #endif
  1368. #if defined(_WIN32)
  1369. CASE_SENSITIVE_FILES,
  1370. #endif
  1371. #if defined(USE_LUA)
  1372. LUA_BACKGROUND_SCRIPT,
  1373. #endif
  1374. NUM_OPTIONS
  1375. };
  1376. /* Config option name, config types, default value */
  1377. static struct mg_option config_options[] = {
  1378. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1379. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1380. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1381. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1382. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1383. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1384. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1385. {"throttle", CONFIG_TYPE_STRING, NULL},
  1386. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1387. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1388. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1389. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1390. {"index_files",
  1391. CONFIG_TYPE_STRING,
  1392. #ifdef USE_LUA
  1393. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1394. "index.shtml,index.php"},
  1395. #else
  1396. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1397. #endif
  1398. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1399. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1400. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1401. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1402. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1403. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1404. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1405. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1406. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1407. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1408. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1409. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1410. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1411. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1412. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1413. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1414. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1415. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1416. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1417. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1418. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1419. #if defined(USE_WEBSOCKET)
  1420. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1421. #endif
  1422. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1423. #if defined(USE_LUA)
  1424. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1425. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1426. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1427. #endif
  1428. #if defined(USE_DUKTAPE)
  1429. /* The support for duktape is still in alpha version state.
  1430. * The name of this config option might change. */
  1431. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1432. #endif
  1433. #if defined(USE_WEBSOCKET)
  1434. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1435. #endif
  1436. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1437. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1438. #endif
  1439. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1440. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1441. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1442. #if !defined(NO_CACHING)
  1443. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1444. #endif
  1445. #if defined(__linux__)
  1446. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1447. #endif
  1448. #if defined(_WIN32)
  1449. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1450. #endif
  1451. #if defined(USE_LUA)
  1452. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1453. #endif
  1454. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1455. /* Check if the config_options and the corresponding enum have compatible
  1456. * sizes. */
  1457. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1458. == (NUM_OPTIONS + 1),
  1459. "config_options and enum not sync");
  1460. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1461. struct mg_handler_info {
  1462. /* Name/Pattern of the URI. */
  1463. char *uri;
  1464. size_t uri_len;
  1465. /* handler type */
  1466. int handler_type;
  1467. /* Handler for http/https or authorization requests. */
  1468. mg_request_handler handler;
  1469. /* Handler for ws/wss (websocket) requests. */
  1470. mg_websocket_connect_handler connect_handler;
  1471. mg_websocket_ready_handler ready_handler;
  1472. mg_websocket_data_handler data_handler;
  1473. mg_websocket_close_handler close_handler;
  1474. /* accepted subprotocols for ws/wss requests. */
  1475. struct mg_websocket_subprotocols *subprotocols;
  1476. /* Handler for authorization requests */
  1477. mg_authorization_handler auth_handler;
  1478. /* User supplied argument for the handler function. */
  1479. void *cbdata;
  1480. /* next handler in a linked list */
  1481. struct mg_handler_info *next;
  1482. };
  1483. struct mg_context {
  1484. volatile int stop_flag; /* Should we stop event loop */
  1485. SSL_CTX *ssl_ctx; /* SSL context */
  1486. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1487. struct mg_callbacks callbacks; /* User-defined callback function */
  1488. void *user_data; /* User-defined data */
  1489. int context_type; /* 1 = server context,
  1490. * 2 = ws/wss client context,
  1491. */
  1492. struct socket *listening_sockets;
  1493. struct pollfd *listening_socket_fds;
  1494. unsigned int num_listening_sockets;
  1495. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1496. #ifdef ALTERNATIVE_QUEUE
  1497. struct socket *client_socks;
  1498. void **client_wait_events;
  1499. #else
  1500. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1501. volatile int sq_head; /* Head of the socket queue */
  1502. volatile int sq_tail; /* Tail of the socket queue */
  1503. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1504. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1505. #endif
  1506. pthread_t masterthreadid; /* The master thread ID */
  1507. unsigned int
  1508. cfg_worker_threads; /* The number of configured worker threads. */
  1509. pthread_t *worker_threadids; /* The worker thread IDs */
  1510. struct mg_connection *worker_connections; /* The connection struct, pre-
  1511. * allocated for each worker */
  1512. time_t start_time; /* Server start time, used for authentication */
  1513. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1514. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1515. unsigned long nonce_count; /* Used nonces, used for authentication */
  1516. char *systemName; /* What operating system is running */
  1517. /* linked list of uri handlers */
  1518. struct mg_handler_info *handlers;
  1519. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1520. /* linked list of shared lua websockets */
  1521. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1522. #endif
  1523. #if defined(USE_TIMERS)
  1524. struct ttimers *timers;
  1525. #endif
  1526. #if defined(USE_LUA)
  1527. void *lua_background_state;
  1528. #endif
  1529. };
  1530. struct mg_connection {
  1531. struct mg_request_info request_info;
  1532. struct mg_context *ctx;
  1533. SSL *ssl; /* SSL descriptor */
  1534. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1535. struct socket client; /* Connected client */
  1536. time_t conn_birth_time; /* Time (wall clock) when connection was
  1537. * established */
  1538. struct timespec req_time; /* Time (since system start) when the request
  1539. * was received */
  1540. int64_t num_bytes_sent; /* Total bytes sent to client */
  1541. int64_t content_len; /* Content-Length header value */
  1542. int64_t consumed_content; /* How many bytes of content have been read */
  1543. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1544. * data available, 2: all data read */
  1545. size_t chunk_remainder; /* Unread data from the last chunk */
  1546. char *buf; /* Buffer for received data */
  1547. char *path_info; /* PATH_INFO part of the URL */
  1548. int must_close; /* 1 if connection must be closed */
  1549. int in_error_handler; /* 1 if in handler for user defined error
  1550. * pages */
  1551. int handled_requests; /* Number of requests handled by this connection */
  1552. int buf_size; /* Buffer size */
  1553. int request_len; /* Size of the request + headers in a buffer */
  1554. int data_len; /* Total size of data in a buffer */
  1555. int status_code; /* HTTP reply status code, e.g. 200 */
  1556. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1557. * throttle */
  1558. time_t last_throttle_time; /* Last time throttled data was sent */
  1559. int64_t last_throttle_bytes; /* Bytes sent this second */
  1560. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1561. * atomic transmissions for websockets */
  1562. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1563. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1564. #endif
  1565. int thread_index; /* Thread index within ctx */
  1566. };
  1567. /* Directory entry */
  1568. struct de {
  1569. struct mg_connection *conn;
  1570. char *file_name;
  1571. struct mg_file_stat file;
  1572. };
  1573. #if defined(USE_WEBSOCKET)
  1574. static int is_websocket_protocol(const struct mg_connection *conn);
  1575. #else
  1576. #define is_websocket_protocol(conn) (0)
  1577. #endif
  1578. #if !defined(NO_THREAD_NAME)
  1579. #if defined(_WIN32) && defined(_MSC_VER)
  1580. /* Set the thread name for debugging purposes in Visual Studio
  1581. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1582. */
  1583. #pragma pack(push, 8)
  1584. typedef struct tagTHREADNAME_INFO {
  1585. DWORD dwType; /* Must be 0x1000. */
  1586. LPCSTR szName; /* Pointer to name (in user addr space). */
  1587. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1588. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1589. } THREADNAME_INFO;
  1590. #pragma pack(pop)
  1591. #elif defined(__linux__)
  1592. #include <sys/prctl.h>
  1593. #include <sys/sendfile.h>
  1594. #include <sys/eventfd.h>
  1595. #if defined(ALTERNATIVE_QUEUE)
  1596. static void *
  1597. event_create(void)
  1598. {
  1599. int ret = eventfd(0, EFD_CLOEXEC);
  1600. if (ret == -1) {
  1601. /* Linux uses -1 on error, Windows NULL. */
  1602. /* However, Linux does not return 0 on success either. */
  1603. return 0;
  1604. }
  1605. return (void *)ret;
  1606. }
  1607. static int
  1608. event_wait(void *eventhdl)
  1609. {
  1610. uint64_t u;
  1611. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1612. if (s != sizeof(uint64_t)) {
  1613. /* error */
  1614. return 0;
  1615. }
  1616. (void)u; /* the value is not required */
  1617. return 1;
  1618. }
  1619. static int
  1620. event_signal(void *eventhdl)
  1621. {
  1622. uint64_t u = 1;
  1623. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1624. if (s != sizeof(uint64_t)) {
  1625. /* error */
  1626. return 0;
  1627. }
  1628. return 1;
  1629. }
  1630. static void
  1631. event_destroy(void *eventhdl)
  1632. {
  1633. close((int)eventhdl);
  1634. }
  1635. #endif
  1636. #endif
  1637. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1638. struct posix_event {
  1639. pthread_mutex_t mutex;
  1640. pthread_cond_t cond;
  1641. };
  1642. static void *
  1643. event_create(void)
  1644. {
  1645. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1646. if (ret == 0) {
  1647. /* out of memory */
  1648. return 0;
  1649. }
  1650. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1651. /* pthread mutex not available */
  1652. mg_free(ret);
  1653. return 0;
  1654. }
  1655. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1656. /* pthread cond not available */
  1657. pthread_mutex_destroy(&(ret->mutex));
  1658. mg_free(ret);
  1659. return 0;
  1660. }
  1661. return (void *)ret;
  1662. }
  1663. static int
  1664. event_wait(void *eventhdl)
  1665. {
  1666. struct posix_event *ev = (struct posix_event *)eventhdl;
  1667. pthread_mutex_lock(&(ev->mutex));
  1668. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1669. pthread_mutex_unlock(&(ev->mutex));
  1670. return 1;
  1671. }
  1672. static int
  1673. event_signal(void *eventhdl)
  1674. {
  1675. struct posix_event *ev = (struct posix_event *)eventhdl;
  1676. pthread_mutex_lock(&(ev->mutex));
  1677. pthread_cond_signal(&(ev->cond));
  1678. pthread_mutex_unlock(&(ev->mutex));
  1679. return 1;
  1680. }
  1681. static void
  1682. event_destroy(void *eventhdl)
  1683. {
  1684. struct posix_event *ev = (struct posix_event *)eventhdl;
  1685. pthread_cond_destroy(&(ev->cond));
  1686. pthread_mutex_destroy(&(ev->mutex));
  1687. mg_free(ev);
  1688. }
  1689. #endif
  1690. static void
  1691. mg_set_thread_name(const char *name)
  1692. {
  1693. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1694. mg_snprintf(
  1695. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1696. #if defined(_WIN32)
  1697. #if defined(_MSC_VER)
  1698. /* Windows and Visual Studio Compiler */
  1699. __try
  1700. {
  1701. THREADNAME_INFO info;
  1702. info.dwType = 0x1000;
  1703. info.szName = threadName;
  1704. info.dwThreadID = ~0U;
  1705. info.dwFlags = 0;
  1706. RaiseException(0x406D1388,
  1707. 0,
  1708. sizeof(info) / sizeof(ULONG_PTR),
  1709. (ULONG_PTR *)&info);
  1710. }
  1711. __except(EXCEPTION_EXECUTE_HANDLER)
  1712. {
  1713. }
  1714. #elif defined(__MINGW32__)
  1715. /* No option known to set thread name for MinGW */
  1716. #endif
  1717. #elif defined(__GLIBC__) \
  1718. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1719. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1720. (void)pthread_setname_np(pthread_self(), threadName);
  1721. #elif defined(__linux__)
  1722. /* on linux we can use the old prctl function */
  1723. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1724. #endif
  1725. }
  1726. #else /* !defined(NO_THREAD_NAME) */
  1727. void
  1728. mg_set_thread_name(const char *threadName)
  1729. {
  1730. }
  1731. #endif
  1732. #if defined(MG_LEGACY_INTERFACE)
  1733. const char **
  1734. mg_get_valid_option_names(void)
  1735. {
  1736. /* This function is deprecated. Use mg_get_valid_options instead. */
  1737. static const char *
  1738. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1739. int i;
  1740. for (i = 0; config_options[i].name != NULL; i++) {
  1741. data[i * 2] = config_options[i].name;
  1742. data[i * 2 + 1] = config_options[i].default_value;
  1743. }
  1744. return data;
  1745. }
  1746. #endif
  1747. const struct mg_option *
  1748. mg_get_valid_options(void)
  1749. {
  1750. return config_options;
  1751. }
  1752. /* Do not open file (used in is_file_in_memory) */
  1753. #define MG_FOPEN_MODE_NONE (0)
  1754. /* Open file for read only access */
  1755. #define MG_FOPEN_MODE_READ (1)
  1756. /* Open file for writing, create and overwrite */
  1757. #define MG_FOPEN_MODE_WRITE (2)
  1758. /* Open file for writing, create and append */
  1759. #define MG_FOPEN_MODE_APPEND (4)
  1760. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1761. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1762. static int
  1763. open_file_in_memory(const struct mg_connection *conn,
  1764. const char *path,
  1765. struct mg_file *filep,
  1766. int mode)
  1767. {
  1768. size_t size = 0;
  1769. const char *buf = NULL;
  1770. if (!conn) {
  1771. return 0;
  1772. }
  1773. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1774. return 0;
  1775. }
  1776. if (conn->ctx->callbacks.open_file) {
  1777. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1778. if (buf != NULL) {
  1779. if (filep == NULL) {
  1780. /* This is a file in memory, but we cannot store the properties
  1781. * now.
  1782. * Called from "is_file_in_memory" function. */
  1783. return 1;
  1784. }
  1785. /* NOTE: override filep->size only on success. Otherwise, it might
  1786. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1787. filep->access.membuf = buf;
  1788. filep->access.fp = NULL;
  1789. /* Size was set by the callback */
  1790. filep->stat.size = size;
  1791. /* Assume the data may change during runtime by setting
  1792. * last_modified = now */
  1793. filep->stat.last_modified = time(NULL);
  1794. filep->stat.is_directory = 0;
  1795. filep->stat.is_gzipped = 0;
  1796. }
  1797. }
  1798. return (buf != NULL);
  1799. }
  1800. static int
  1801. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1802. {
  1803. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1804. }
  1805. static int
  1806. is_file_opened(const struct mg_file_access *fileacc)
  1807. {
  1808. if (!fileacc) {
  1809. return 0;
  1810. }
  1811. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1812. }
  1813. static int mg_stat(const struct mg_connection *conn,
  1814. const char *path,
  1815. struct mg_file_stat *filep);
  1816. /* mg_fopen will open a file either in memory or on the disk.
  1817. * The input parameter path is a string in UTF-8 encoding.
  1818. * The input parameter mode is MG_FOPEN_MODE_*
  1819. * On success, either fp or membuf will be set in the output
  1820. * struct file. All status members will also be set.
  1821. * The function returns 1 on success, 0 on error. */
  1822. static int
  1823. mg_fopen(const struct mg_connection *conn,
  1824. const char *path,
  1825. int mode,
  1826. struct mg_file *filep)
  1827. {
  1828. int found;
  1829. if (!filep) {
  1830. return 0;
  1831. }
  1832. filep->access.fp = NULL;
  1833. filep->access.membuf = NULL;
  1834. if (!is_file_in_memory(conn, path)) {
  1835. /* filep is initialized in mg_stat: all fields with memset to,
  1836. * some fields like size and modification date with values */
  1837. found = mg_stat(conn, path, &(filep->stat));
  1838. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  1839. /* file does not exist and will not be created */
  1840. return 0;
  1841. }
  1842. #ifdef _WIN32
  1843. {
  1844. wchar_t wbuf[PATH_MAX];
  1845. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1846. switch (mode) {
  1847. case MG_FOPEN_MODE_READ:
  1848. filep->access.fp = _wfopen(wbuf, L"rb");
  1849. break;
  1850. case MG_FOPEN_MODE_WRITE:
  1851. filep->access.fp = _wfopen(wbuf, L"wb");
  1852. break;
  1853. case MG_FOPEN_MODE_APPEND:
  1854. filep->access.fp = _wfopen(wbuf, L"ab");
  1855. break;
  1856. }
  1857. }
  1858. #else
  1859. /* Linux et al already use unicode. No need to convert. */
  1860. switch (mode) {
  1861. case MG_FOPEN_MODE_READ:
  1862. filep->access.fp = fopen(path, "r");
  1863. break;
  1864. case MG_FOPEN_MODE_WRITE:
  1865. filep->access.fp = fopen(path, "w");
  1866. break;
  1867. case MG_FOPEN_MODE_APPEND:
  1868. filep->access.fp = fopen(path, "a");
  1869. break;
  1870. }
  1871. #endif
  1872. if (!found) {
  1873. /* File did not exist before fopen was called.
  1874. * Maybe it has been created now. Get stat info
  1875. * like creation time now. */
  1876. found = mg_stat(conn, path, &(filep->stat));
  1877. (void)found;
  1878. }
  1879. /* file is on disk */
  1880. return (filep->access.fp != NULL);
  1881. } else {
  1882. /* is_file_in_memory returned true */
  1883. if (open_file_in_memory(conn, path, filep, mode)) {
  1884. /* file is in memory */
  1885. return (filep->access.membuf != NULL);
  1886. }
  1887. }
  1888. /* Open failed */
  1889. return 0;
  1890. }
  1891. /* return 0 on success, just like fclose */
  1892. static int
  1893. mg_fclose(struct mg_file_access *fileacc)
  1894. {
  1895. int ret = -1;
  1896. if (fileacc != NULL) {
  1897. if (fileacc->fp != NULL) {
  1898. ret = fclose(fileacc->fp);
  1899. } else if (fileacc->membuf != NULL) {
  1900. ret = 0;
  1901. }
  1902. /* reset all members of fileacc */
  1903. memset(fileacc, 0, sizeof(*fileacc));
  1904. }
  1905. return ret;
  1906. }
  1907. static void
  1908. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1909. {
  1910. for (; *src != '\0' && n > 1; n--) {
  1911. *dst++ = *src++;
  1912. }
  1913. *dst = '\0';
  1914. }
  1915. static int
  1916. lowercase(const char *s)
  1917. {
  1918. return tolower(*(const unsigned char *)s);
  1919. }
  1920. int
  1921. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1922. {
  1923. int diff = 0;
  1924. if (len > 0) {
  1925. do {
  1926. diff = lowercase(s1++) - lowercase(s2++);
  1927. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1928. }
  1929. return diff;
  1930. }
  1931. int
  1932. mg_strcasecmp(const char *s1, const char *s2)
  1933. {
  1934. int diff;
  1935. do {
  1936. diff = lowercase(s1++) - lowercase(s2++);
  1937. } while (diff == 0 && s1[-1] != '\0');
  1938. return diff;
  1939. }
  1940. static char *
  1941. mg_strndup(const char *ptr, size_t len)
  1942. {
  1943. char *p;
  1944. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1945. mg_strlcpy(p, ptr, len + 1);
  1946. }
  1947. return p;
  1948. }
  1949. static char *
  1950. mg_strdup(const char *str)
  1951. {
  1952. return mg_strndup(str, strlen(str));
  1953. }
  1954. static const char *
  1955. mg_strcasestr(const char *big_str, const char *small_str)
  1956. {
  1957. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1958. if (big_len >= small_len) {
  1959. for (i = 0; i <= (big_len - small_len); i++) {
  1960. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1961. return big_str + i;
  1962. }
  1963. }
  1964. }
  1965. return NULL;
  1966. }
  1967. /* Return null terminated string of given maximum length.
  1968. * Report errors if length is exceeded. */
  1969. static void
  1970. mg_vsnprintf(const struct mg_connection *conn,
  1971. int *truncated,
  1972. char *buf,
  1973. size_t buflen,
  1974. const char *fmt,
  1975. va_list ap)
  1976. {
  1977. int n, ok;
  1978. if (buflen == 0) {
  1979. return;
  1980. }
  1981. #ifdef __clang__
  1982. #pragma clang diagnostic push
  1983. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1984. /* Using fmt as a non-literal is intended here, since it is mostly called
  1985. * indirectly by mg_snprintf */
  1986. #endif
  1987. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1988. ok = (n >= 0) && ((size_t)n < buflen);
  1989. #ifdef __clang__
  1990. #pragma clang diagnostic pop
  1991. #endif
  1992. if (ok) {
  1993. if (truncated) {
  1994. *truncated = 0;
  1995. }
  1996. } else {
  1997. if (truncated) {
  1998. *truncated = 1;
  1999. }
  2000. mg_cry(conn,
  2001. "truncating vsnprintf buffer: [%.*s]",
  2002. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2003. buf);
  2004. n = (int)buflen - 1;
  2005. }
  2006. buf[n] = '\0';
  2007. }
  2008. static void
  2009. mg_snprintf(const struct mg_connection *conn,
  2010. int *truncated,
  2011. char *buf,
  2012. size_t buflen,
  2013. const char *fmt,
  2014. ...)
  2015. {
  2016. va_list ap;
  2017. va_start(ap, fmt);
  2018. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2019. va_end(ap);
  2020. }
  2021. static int
  2022. get_option_index(const char *name)
  2023. {
  2024. int i;
  2025. for (i = 0; config_options[i].name != NULL; i++) {
  2026. if (strcmp(config_options[i].name, name) == 0) {
  2027. return i;
  2028. }
  2029. }
  2030. return -1;
  2031. }
  2032. const char *
  2033. mg_get_option(const struct mg_context *ctx, const char *name)
  2034. {
  2035. int i;
  2036. if ((i = get_option_index(name)) == -1) {
  2037. return NULL;
  2038. } else if (!ctx || ctx->config[i] == NULL) {
  2039. return "";
  2040. } else {
  2041. return ctx->config[i];
  2042. }
  2043. }
  2044. struct mg_context *
  2045. mg_get_context(const struct mg_connection *conn)
  2046. {
  2047. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2048. }
  2049. void *
  2050. mg_get_user_data(const struct mg_context *ctx)
  2051. {
  2052. return (ctx == NULL) ? NULL : ctx->user_data;
  2053. }
  2054. void
  2055. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2056. {
  2057. if (conn != NULL) {
  2058. conn->request_info.conn_data = data;
  2059. }
  2060. }
  2061. void *
  2062. mg_get_user_connection_data(const struct mg_connection *conn)
  2063. {
  2064. if (conn != NULL) {
  2065. return conn->request_info.conn_data;
  2066. }
  2067. return NULL;
  2068. }
  2069. size_t
  2070. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2071. {
  2072. size_t i;
  2073. if (!ctx) {
  2074. return 0;
  2075. }
  2076. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2077. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2078. ports[i] =
  2079. #if defined(USE_IPV6)
  2080. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2081. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2082. :
  2083. #endif
  2084. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2085. }
  2086. return i;
  2087. }
  2088. int
  2089. mg_get_server_ports(const struct mg_context *ctx,
  2090. int size,
  2091. struct mg_server_ports *ports)
  2092. {
  2093. int i, cnt = 0;
  2094. if (size <= 0) {
  2095. return -1;
  2096. }
  2097. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2098. if (!ctx) {
  2099. return -1;
  2100. }
  2101. if (!ctx->listening_sockets) {
  2102. return -1;
  2103. }
  2104. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2105. ports[cnt].port =
  2106. #if defined(USE_IPV6)
  2107. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2108. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2109. :
  2110. #endif
  2111. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2112. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2113. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2114. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2115. /* IPv4 */
  2116. ports[cnt].protocol = 1;
  2117. cnt++;
  2118. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2119. /* IPv6 */
  2120. ports[cnt].protocol = 3;
  2121. cnt++;
  2122. }
  2123. }
  2124. return cnt;
  2125. }
  2126. static void
  2127. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2128. {
  2129. buf[0] = '\0';
  2130. if (!usa) {
  2131. return;
  2132. }
  2133. if (usa->sa.sa_family == AF_INET) {
  2134. getnameinfo(&usa->sa,
  2135. sizeof(usa->sin),
  2136. buf,
  2137. (unsigned)len,
  2138. NULL,
  2139. 0,
  2140. NI_NUMERICHOST);
  2141. }
  2142. #if defined(USE_IPV6)
  2143. else if (usa->sa.sa_family == AF_INET6) {
  2144. getnameinfo(&usa->sa,
  2145. sizeof(usa->sin6),
  2146. buf,
  2147. (unsigned)len,
  2148. NULL,
  2149. 0,
  2150. NI_NUMERICHOST);
  2151. }
  2152. #endif
  2153. }
  2154. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2155. * included in all responses other than 100, 101, 5xx. */
  2156. static void
  2157. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2158. {
  2159. struct tm *tm;
  2160. tm = ((t != NULL) ? gmtime(t) : NULL);
  2161. if (tm != NULL) {
  2162. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2163. } else {
  2164. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2165. buf[buf_len - 1] = '\0';
  2166. }
  2167. }
  2168. /* difftime for struct timespec. Return value is in seconds. */
  2169. static double
  2170. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2171. {
  2172. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2173. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2174. }
  2175. /* Print error message to the opened error log stream. */
  2176. void
  2177. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2178. {
  2179. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2180. va_list ap;
  2181. struct mg_file fi;
  2182. time_t timestamp;
  2183. va_start(ap, fmt);
  2184. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2185. va_end(ap);
  2186. buf[sizeof(buf) - 1] = 0;
  2187. if (!conn) {
  2188. puts(buf);
  2189. return;
  2190. }
  2191. /* Do not lock when getting the callback value, here and below.
  2192. * I suppose this is fine, since function cannot disappear in the
  2193. * same way string option can. */
  2194. if ((conn->ctx->callbacks.log_message == NULL)
  2195. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2196. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2197. if (mg_fopen(conn,
  2198. conn->ctx->config[ERROR_LOG_FILE],
  2199. MG_FOPEN_MODE_APPEND,
  2200. &fi) == 0) {
  2201. fi.access.fp = NULL;
  2202. }
  2203. } else {
  2204. fi.access.fp = NULL;
  2205. }
  2206. if (fi.access.fp != NULL) {
  2207. flockfile(fi.access.fp);
  2208. timestamp = time(NULL);
  2209. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2210. fprintf(fi.access.fp,
  2211. "[%010lu] [error] [client %s] ",
  2212. (unsigned long)timestamp,
  2213. src_addr);
  2214. if (conn->request_info.request_method != NULL) {
  2215. fprintf(fi.access.fp,
  2216. "%s %s: ",
  2217. conn->request_info.request_method,
  2218. conn->request_info.request_uri);
  2219. }
  2220. fprintf(fi.access.fp, "%s", buf);
  2221. fputc('\n', fi.access.fp);
  2222. fflush(fi.access.fp);
  2223. funlockfile(fi.access.fp);
  2224. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2225. * mg_cry here anyway ;-) */
  2226. }
  2227. }
  2228. }
  2229. /* Return fake connection structure. Used for logging, if connection
  2230. * is not applicable at the moment of logging. */
  2231. static struct mg_connection *
  2232. fc(struct mg_context *ctx)
  2233. {
  2234. static struct mg_connection fake_connection;
  2235. fake_connection.ctx = ctx;
  2236. return &fake_connection;
  2237. }
  2238. const char *
  2239. mg_version(void)
  2240. {
  2241. return CIVETWEB_VERSION;
  2242. }
  2243. const struct mg_request_info *
  2244. mg_get_request_info(const struct mg_connection *conn)
  2245. {
  2246. if (!conn) {
  2247. return NULL;
  2248. }
  2249. return &conn->request_info;
  2250. }
  2251. /* Skip the characters until one of the delimiters characters found.
  2252. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2253. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2254. * Delimiters can be quoted with quotechar. */
  2255. static char *
  2256. skip_quoted(char **buf,
  2257. const char *delimiters,
  2258. const char *whitespace,
  2259. char quotechar)
  2260. {
  2261. char *p, *begin_word, *end_word, *end_whitespace;
  2262. begin_word = *buf;
  2263. end_word = begin_word + strcspn(begin_word, delimiters);
  2264. /* Check for quotechar */
  2265. if (end_word > begin_word) {
  2266. p = end_word - 1;
  2267. while (*p == quotechar) {
  2268. /* While the delimiter is quoted, look for the next delimiter. */
  2269. /* This happens, e.g., in calls from parse_auth_header,
  2270. * if the user name contains a " character. */
  2271. /* If there is anything beyond end_word, copy it. */
  2272. if (*end_word != '\0') {
  2273. size_t end_off = strcspn(end_word + 1, delimiters);
  2274. memmove(p, end_word, end_off + 1);
  2275. p += end_off; /* p must correspond to end_word - 1 */
  2276. end_word += end_off + 1;
  2277. } else {
  2278. *p = '\0';
  2279. break;
  2280. }
  2281. }
  2282. for (p++; p < end_word; p++) {
  2283. *p = '\0';
  2284. }
  2285. }
  2286. if (*end_word == '\0') {
  2287. *buf = end_word;
  2288. } else {
  2289. #if defined(__GNUC__) || defined(__MINGW32__)
  2290. /* Disable spurious conversion warning for GCC */
  2291. #pragma GCC diagnostic push
  2292. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2293. #endif
  2294. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2295. #if defined(__GNUC__) || defined(__MINGW32__)
  2296. #pragma GCC diagnostic pop
  2297. #endif
  2298. for (p = end_word; p < end_whitespace; p++) {
  2299. *p = '\0';
  2300. }
  2301. *buf = end_whitespace;
  2302. }
  2303. return begin_word;
  2304. }
  2305. /* Simplified version of skip_quoted without quote char
  2306. * and whitespace == delimiters */
  2307. static char *
  2308. skip(char **buf, const char *delimiters)
  2309. {
  2310. return skip_quoted(buf, delimiters, delimiters, 0);
  2311. }
  2312. /* Return HTTP header value, or NULL if not found. */
  2313. static const char *
  2314. get_header(const struct mg_request_info *ri, const char *name)
  2315. {
  2316. int i;
  2317. if (ri) {
  2318. for (i = 0; i < ri->num_headers; i++) {
  2319. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2320. return ri->http_headers[i].value;
  2321. }
  2322. }
  2323. }
  2324. return NULL;
  2325. }
  2326. const char *
  2327. mg_get_header(const struct mg_connection *conn, const char *name)
  2328. {
  2329. if (!conn) {
  2330. return NULL;
  2331. }
  2332. return get_header(&conn->request_info, name);
  2333. }
  2334. /* A helper function for traversing a comma separated list of values.
  2335. * It returns a list pointer shifted to the next value, or NULL if the end
  2336. * of the list found.
  2337. * Value is stored in val vector. If value has form "x=y", then eq_val
  2338. * vector is initialized to point to the "y" part, and val vector length
  2339. * is adjusted to point only to "x". */
  2340. static const char *
  2341. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2342. {
  2343. int end;
  2344. reparse:
  2345. if (val == NULL || list == NULL || *list == '\0') {
  2346. /* End of the list */
  2347. list = NULL;
  2348. } else {
  2349. /* Skip over leading LWS */
  2350. while (*list == ' ' || *list == '\t')
  2351. list++;
  2352. val->ptr = list;
  2353. if ((list = strchr(val->ptr, ',')) != NULL) {
  2354. /* Comma found. Store length and shift the list ptr */
  2355. val->len = ((size_t)(list - val->ptr));
  2356. list++;
  2357. } else {
  2358. /* This value is the last one */
  2359. list = val->ptr + strlen(val->ptr);
  2360. val->len = ((size_t)(list - val->ptr));
  2361. }
  2362. /* Adjust length for trailing LWS */
  2363. end = (int)val->len - 1;
  2364. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2365. end--;
  2366. val->len = (size_t)(end + 1);
  2367. if (val->len == 0) {
  2368. /* Ignore any empty entries. */
  2369. goto reparse;
  2370. }
  2371. if (eq_val != NULL) {
  2372. /* Value has form "x=y", adjust pointers and lengths
  2373. * so that val points to "x", and eq_val points to "y". */
  2374. eq_val->len = 0;
  2375. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2376. if (eq_val->ptr != NULL) {
  2377. eq_val->ptr++; /* Skip over '=' character */
  2378. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2379. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2380. }
  2381. }
  2382. }
  2383. return list;
  2384. }
  2385. /* A helper function for checking if a comma separated list of values contains
  2386. * the given option (case insensitvely).
  2387. * 'header' can be NULL, in which case false is returned. */
  2388. static int
  2389. header_has_option(const char *header, const char *option)
  2390. {
  2391. struct vec opt_vec;
  2392. struct vec eq_vec;
  2393. assert(option != NULL);
  2394. assert(option[0] != '\0');
  2395. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2396. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2397. return 1;
  2398. }
  2399. return 0;
  2400. }
  2401. /* Perform case-insensitive match of string against pattern */
  2402. static int
  2403. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2404. {
  2405. const char *or_str;
  2406. size_t i;
  2407. int j, len, res;
  2408. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2409. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2410. return (res > 0) ? res : match_prefix(or_str + 1,
  2411. (size_t)((pattern + pattern_len)
  2412. - (or_str + 1)),
  2413. str);
  2414. }
  2415. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2416. if (pattern[i] == '?' && str[j] != '\0') {
  2417. continue;
  2418. } else if (pattern[i] == '$') {
  2419. return (str[j] == '\0') ? j : -1;
  2420. } else if (pattern[i] == '*') {
  2421. i++;
  2422. if (pattern[i] == '*') {
  2423. i++;
  2424. len = (int)strlen(str + j);
  2425. } else {
  2426. len = (int)strcspn(str + j, "/");
  2427. }
  2428. if (i == pattern_len) {
  2429. return j + len;
  2430. }
  2431. do {
  2432. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2433. } while (res == -1 && len-- > 0);
  2434. return (res == -1) ? -1 : j + res + len;
  2435. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2436. return -1;
  2437. }
  2438. }
  2439. return j;
  2440. }
  2441. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2442. * This function must tolerate situations when connection info is not
  2443. * set up, for example if request parsing failed. */
  2444. static int
  2445. should_keep_alive(const struct mg_connection *conn)
  2446. {
  2447. if (conn != NULL) {
  2448. const char *http_version = conn->request_info.http_version;
  2449. const char *header = mg_get_header(conn, "Connection");
  2450. if (conn->must_close || conn->status_code == 401
  2451. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2452. || (header != NULL && !header_has_option(header, "keep-alive"))
  2453. || (header == NULL && http_version
  2454. && 0 != strcmp(http_version, "1.1"))) {
  2455. return 0;
  2456. }
  2457. return 1;
  2458. }
  2459. return 0;
  2460. }
  2461. static int
  2462. should_decode_url(const struct mg_connection *conn)
  2463. {
  2464. if (!conn || !conn->ctx) {
  2465. return 0;
  2466. }
  2467. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2468. }
  2469. static const char *
  2470. suggest_connection_header(const struct mg_connection *conn)
  2471. {
  2472. return should_keep_alive(conn) ? "keep-alive" : "close";
  2473. }
  2474. static int
  2475. send_no_cache_header(struct mg_connection *conn)
  2476. {
  2477. /* Send all current and obsolete cache opt-out directives. */
  2478. return mg_printf(conn,
  2479. "Cache-Control: no-cache, no-store, "
  2480. "must-revalidate, private, max-age=0\r\n"
  2481. "Pragma: no-cache\r\n"
  2482. "Expires: 0\r\n");
  2483. }
  2484. static int
  2485. send_static_cache_header(struct mg_connection *conn)
  2486. {
  2487. #if !defined(NO_CACHING)
  2488. /* Read the server config to check how long a file may be cached.
  2489. * The configuration is in seconds. */
  2490. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2491. if (max_age <= 0) {
  2492. /* 0 means "do not cache". All values <0 are reserved
  2493. * and may be used differently in the future. */
  2494. /* If a file should not be cached, do not only send
  2495. * max-age=0, but also pragmas and Expires headers. */
  2496. return send_no_cache_header(conn);
  2497. }
  2498. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2499. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2500. /* See also https://www.mnot.net/cache_docs/ */
  2501. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2502. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2503. * year to 31622400 seconds. For the moment, we just send whatever has
  2504. * been configured, still the behavior for >1 year should be considered
  2505. * as undefined. */
  2506. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2507. #else /* NO_CACHING */
  2508. return send_no_cache_header(conn);
  2509. #endif /* !NO_CACHING */
  2510. }
  2511. static void handle_file_based_request(struct mg_connection *conn,
  2512. const char *path,
  2513. struct mg_file *filep);
  2514. const char *
  2515. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2516. {
  2517. /* See IANA HTTP status code assignment:
  2518. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2519. */
  2520. switch (response_code) {
  2521. /* RFC2616 Section 10.1 - Informational 1xx */
  2522. case 100:
  2523. return "Continue"; /* RFC2616 Section 10.1.1 */
  2524. case 101:
  2525. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2526. case 102:
  2527. return "Processing"; /* RFC2518 Section 10.1 */
  2528. /* RFC2616 Section 10.2 - Successful 2xx */
  2529. case 200:
  2530. return "OK"; /* RFC2616 Section 10.2.1 */
  2531. case 201:
  2532. return "Created"; /* RFC2616 Section 10.2.2 */
  2533. case 202:
  2534. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2535. case 203:
  2536. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2537. case 204:
  2538. return "No Content"; /* RFC2616 Section 10.2.5 */
  2539. case 205:
  2540. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2541. case 206:
  2542. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2543. case 207:
  2544. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2545. case 208:
  2546. return "Already Reported"; /* RFC5842 Section 7.1 */
  2547. case 226:
  2548. return "IM used"; /* RFC3229 Section 10.4.1 */
  2549. /* RFC2616 Section 10.3 - Redirection 3xx */
  2550. case 300:
  2551. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2552. case 301:
  2553. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2554. case 302:
  2555. return "Found"; /* RFC2616 Section 10.3.3 */
  2556. case 303:
  2557. return "See Other"; /* RFC2616 Section 10.3.4 */
  2558. case 304:
  2559. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2560. case 305:
  2561. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2562. case 307:
  2563. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2564. case 308:
  2565. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2566. /* RFC2616 Section 10.4 - Client Error 4xx */
  2567. case 400:
  2568. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2569. case 401:
  2570. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2571. case 402:
  2572. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2573. case 403:
  2574. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2575. case 404:
  2576. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2577. case 405:
  2578. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2579. case 406:
  2580. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2581. case 407:
  2582. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2583. case 408:
  2584. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2585. case 409:
  2586. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2587. case 410:
  2588. return "Gone"; /* RFC2616 Section 10.4.11 */
  2589. case 411:
  2590. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2591. case 412:
  2592. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2593. case 413:
  2594. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2595. case 414:
  2596. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2597. case 415:
  2598. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2599. case 416:
  2600. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2601. case 417:
  2602. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2603. case 421:
  2604. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2605. case 422:
  2606. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2607. * Section 11.2 */
  2608. case 423:
  2609. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2610. case 424:
  2611. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2612. * Section 11.4 */
  2613. case 426:
  2614. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2615. case 428:
  2616. return "Precondition Required"; /* RFC 6585, Section 3 */
  2617. case 429:
  2618. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2619. case 431:
  2620. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2621. case 451:
  2622. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2623. * Section 3 */
  2624. /* RFC2616 Section 10.5 - Server Error 5xx */
  2625. case 500:
  2626. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2627. case 501:
  2628. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2629. case 502:
  2630. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2631. case 503:
  2632. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2633. case 504:
  2634. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2635. case 505:
  2636. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2637. case 506:
  2638. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2639. case 507:
  2640. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2641. * Section 11.5 */
  2642. case 508:
  2643. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2644. case 510:
  2645. return "Not Extended"; /* RFC 2774, Section 7 */
  2646. case 511:
  2647. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2648. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2649. * E.g., "de facto" standards due to common use, ... */
  2650. case 418:
  2651. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2652. case 419:
  2653. return "Authentication Timeout"; /* common use */
  2654. case 420:
  2655. return "Enhance Your Calm"; /* common use */
  2656. case 440:
  2657. return "Login Timeout"; /* common use */
  2658. case 509:
  2659. return "Bandwidth Limit Exceeded"; /* common use */
  2660. default:
  2661. /* This error code is unknown. This should not happen. */
  2662. if (conn) {
  2663. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2664. }
  2665. /* Return at least a category according to RFC 2616 Section 10. */
  2666. if (response_code >= 100 && response_code < 200) {
  2667. /* Unknown informational status code */
  2668. return "Information";
  2669. }
  2670. if (response_code >= 200 && response_code < 300) {
  2671. /* Unknown success code */
  2672. return "Success";
  2673. }
  2674. if (response_code >= 300 && response_code < 400) {
  2675. /* Unknown redirection code */
  2676. return "Redirection";
  2677. }
  2678. if (response_code >= 400 && response_code < 500) {
  2679. /* Unknown request error code */
  2680. return "Client Error";
  2681. }
  2682. if (response_code >= 500 && response_code < 600) {
  2683. /* Unknown server error code */
  2684. return "Server Error";
  2685. }
  2686. /* Response code not even within reasonable range */
  2687. return "";
  2688. }
  2689. }
  2690. static void send_http_error(struct mg_connection *,
  2691. int,
  2692. PRINTF_FORMAT_STRING(const char *fmt),
  2693. ...) PRINTF_ARGS(3, 4);
  2694. static void
  2695. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2696. {
  2697. char buf[MG_BUF_LEN];
  2698. va_list ap;
  2699. int len, i, page_handler_found, scope, truncated, has_body;
  2700. char date[64];
  2701. time_t curtime = time(NULL);
  2702. const char *error_handler = NULL;
  2703. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2704. const char *error_page_file_ext, *tstr;
  2705. const char *status_text = mg_get_response_code_text(conn, status);
  2706. if (conn == NULL) {
  2707. return;
  2708. }
  2709. conn->status_code = status;
  2710. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2711. || conn->ctx->callbacks.http_error(conn, status)) {
  2712. if (!conn->in_error_handler) {
  2713. /* Send user defined error pages, if defined */
  2714. error_handler = conn->ctx->config[ERROR_PAGES];
  2715. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2716. page_handler_found = 0;
  2717. if (error_handler != NULL) {
  2718. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2719. switch (scope) {
  2720. case 1: /* Handler for specific error, e.g. 404 error */
  2721. mg_snprintf(conn,
  2722. &truncated,
  2723. buf,
  2724. sizeof(buf) - 32,
  2725. "%serror%03u.",
  2726. error_handler,
  2727. status);
  2728. break;
  2729. case 2: /* Handler for error group, e.g., 5xx error handler
  2730. * for all server errors (500-599) */
  2731. mg_snprintf(conn,
  2732. &truncated,
  2733. buf,
  2734. sizeof(buf) - 32,
  2735. "%serror%01uxx.",
  2736. error_handler,
  2737. status / 100);
  2738. break;
  2739. default: /* Handler for all errors */
  2740. mg_snprintf(conn,
  2741. &truncated,
  2742. buf,
  2743. sizeof(buf) - 32,
  2744. "%serror.",
  2745. error_handler);
  2746. break;
  2747. }
  2748. /* String truncation in buf may only occur if error_handler
  2749. * is too long. This string is from the config, not from a
  2750. * client. */
  2751. (void)truncated;
  2752. len = (int)strlen(buf);
  2753. tstr = strchr(error_page_file_ext, '.');
  2754. while (tstr) {
  2755. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2756. i++)
  2757. buf[len + i - 1] = tstr[i];
  2758. buf[len + i - 1] = 0;
  2759. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2760. page_handler_found = 1;
  2761. break;
  2762. }
  2763. tstr = strchr(tstr + i, '.');
  2764. }
  2765. }
  2766. }
  2767. if (page_handler_found) {
  2768. conn->in_error_handler = 1;
  2769. handle_file_based_request(conn, buf, &error_page_file);
  2770. conn->in_error_handler = 0;
  2771. return;
  2772. }
  2773. }
  2774. /* No custom error page. Send default error page. */
  2775. gmt_time_string(date, sizeof(date), &curtime);
  2776. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2777. has_body = (status > 199 && status != 204 && status != 304);
  2778. conn->must_close = 1;
  2779. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2780. send_no_cache_header(conn);
  2781. if (has_body) {
  2782. mg_printf(conn,
  2783. "%s",
  2784. "Content-Type: text/plain; charset=utf-8\r\n");
  2785. }
  2786. mg_printf(conn,
  2787. "Date: %s\r\n"
  2788. "Connection: close\r\n\r\n",
  2789. date);
  2790. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2791. if (has_body) {
  2792. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2793. if (fmt != NULL) {
  2794. va_start(ap, fmt);
  2795. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2796. va_end(ap);
  2797. mg_write(conn, buf, strlen(buf));
  2798. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2799. }
  2800. } else {
  2801. /* No body allowed. Close the connection. */
  2802. DEBUG_TRACE("Error %i", status);
  2803. }
  2804. }
  2805. }
  2806. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2807. /* Create substitutes for POSIX functions in Win32. */
  2808. #if defined(__MINGW32__)
  2809. /* Show no warning in case system functions are not used. */
  2810. #pragma GCC diagnostic push
  2811. #pragma GCC diagnostic ignored "-Wunused-function"
  2812. #endif
  2813. static int
  2814. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2815. {
  2816. (void)unused;
  2817. *mutex = CreateMutex(NULL, FALSE, NULL);
  2818. return (*mutex == NULL) ? -1 : 0;
  2819. }
  2820. static int
  2821. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2822. {
  2823. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2824. }
  2825. static int
  2826. pthread_mutex_lock(pthread_mutex_t *mutex)
  2827. {
  2828. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2829. }
  2830. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2831. static int
  2832. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2833. {
  2834. switch (WaitForSingleObject(*mutex, 0)) {
  2835. case WAIT_OBJECT_0:
  2836. return 0;
  2837. case WAIT_TIMEOUT:
  2838. return -2; /* EBUSY */
  2839. }
  2840. return -1;
  2841. }
  2842. #endif
  2843. static int
  2844. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2845. {
  2846. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2847. }
  2848. static int
  2849. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2850. {
  2851. (void)unused;
  2852. InitializeCriticalSection(&cv->threadIdSec);
  2853. cv->waiting_thread = NULL;
  2854. return 0;
  2855. }
  2856. static int
  2857. pthread_cond_timedwait(pthread_cond_t *cv,
  2858. pthread_mutex_t *mutex,
  2859. const struct timespec *abstime)
  2860. {
  2861. struct mg_workerTLS **ptls,
  2862. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2863. int ok;
  2864. struct timespec tsnow;
  2865. int64_t nsnow, nswaitabs, nswaitrel;
  2866. DWORD mswaitrel;
  2867. EnterCriticalSection(&cv->threadIdSec);
  2868. /* Add this thread to cv's waiting list */
  2869. ptls = &cv->waiting_thread;
  2870. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2871. ;
  2872. tls->next_waiting_thread = NULL;
  2873. *ptls = tls;
  2874. LeaveCriticalSection(&cv->threadIdSec);
  2875. if (abstime) {
  2876. clock_gettime(CLOCK_REALTIME, &tsnow);
  2877. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2878. nswaitabs =
  2879. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2880. nswaitrel = nswaitabs - nsnow;
  2881. if (nswaitrel < 0) {
  2882. nswaitrel = 0;
  2883. }
  2884. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2885. } else {
  2886. mswaitrel = INFINITE;
  2887. }
  2888. pthread_mutex_unlock(mutex);
  2889. ok = (WAIT_OBJECT_0
  2890. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2891. if (!ok) {
  2892. ok = 1;
  2893. EnterCriticalSection(&cv->threadIdSec);
  2894. ptls = &cv->waiting_thread;
  2895. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2896. if (*ptls == tls) {
  2897. *ptls = tls->next_waiting_thread;
  2898. ok = 0;
  2899. break;
  2900. }
  2901. }
  2902. LeaveCriticalSection(&cv->threadIdSec);
  2903. if (ok) {
  2904. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2905. }
  2906. }
  2907. /* This thread has been removed from cv's waiting list */
  2908. pthread_mutex_lock(mutex);
  2909. return ok ? 0 : -1;
  2910. }
  2911. static int
  2912. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2913. {
  2914. return pthread_cond_timedwait(cv, mutex, NULL);
  2915. }
  2916. static int
  2917. pthread_cond_signal(pthread_cond_t *cv)
  2918. {
  2919. HANDLE wkup = NULL;
  2920. BOOL ok = FALSE;
  2921. EnterCriticalSection(&cv->threadIdSec);
  2922. if (cv->waiting_thread) {
  2923. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2924. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2925. ok = SetEvent(wkup);
  2926. assert(ok);
  2927. }
  2928. LeaveCriticalSection(&cv->threadIdSec);
  2929. return ok ? 0 : 1;
  2930. }
  2931. static int
  2932. pthread_cond_broadcast(pthread_cond_t *cv)
  2933. {
  2934. EnterCriticalSection(&cv->threadIdSec);
  2935. while (cv->waiting_thread) {
  2936. pthread_cond_signal(cv);
  2937. }
  2938. LeaveCriticalSection(&cv->threadIdSec);
  2939. return 0;
  2940. }
  2941. static int
  2942. pthread_cond_destroy(pthread_cond_t *cv)
  2943. {
  2944. EnterCriticalSection(&cv->threadIdSec);
  2945. assert(cv->waiting_thread == NULL);
  2946. LeaveCriticalSection(&cv->threadIdSec);
  2947. DeleteCriticalSection(&cv->threadIdSec);
  2948. return 0;
  2949. }
  2950. #ifdef ALTERNATIVE_QUEUE
  2951. static void *
  2952. event_create(void)
  2953. {
  2954. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2955. }
  2956. static int
  2957. event_wait(void *eventhdl)
  2958. {
  2959. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2960. return (res == WAIT_OBJECT_0);
  2961. }
  2962. static int
  2963. event_signal(void *eventhdl)
  2964. {
  2965. return (int)SetEvent((HANDLE)eventhdl);
  2966. }
  2967. static void
  2968. event_destroy(void *eventhdl)
  2969. {
  2970. CloseHandle((HANDLE)eventhdl);
  2971. }
  2972. #endif
  2973. #if defined(__MINGW32__)
  2974. /* Enable unused function warning again */
  2975. #pragma GCC diagnostic pop
  2976. #endif
  2977. /* For Windows, change all slashes to backslashes in path names. */
  2978. static void
  2979. change_slashes_to_backslashes(char *path)
  2980. {
  2981. int i;
  2982. for (i = 0; path[i] != '\0'; i++) {
  2983. if (path[i] == '/') {
  2984. path[i] = '\\';
  2985. }
  2986. /* remove double backslash (check i > 0 to preserve UNC paths,
  2987. * like \\server\file.txt) */
  2988. if ((path[i] == '\\') && (i > 0)) {
  2989. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2990. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2991. }
  2992. }
  2993. }
  2994. }
  2995. static int
  2996. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2997. {
  2998. int diff;
  2999. do {
  3000. diff = tolower(*s1) - tolower(*s2);
  3001. s1++;
  3002. s2++;
  3003. } while (diff == 0 && s1[-1] != '\0');
  3004. return diff;
  3005. }
  3006. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3007. * wbuf and wbuf_len is a target buffer and its length. */
  3008. static void
  3009. path_to_unicode(const struct mg_connection *conn,
  3010. const char *path,
  3011. wchar_t *wbuf,
  3012. size_t wbuf_len)
  3013. {
  3014. char buf[PATH_MAX], buf2[PATH_MAX];
  3015. wchar_t wbuf2[MAX_PATH + 1];
  3016. DWORD long_len, err;
  3017. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3018. mg_strlcpy(buf, path, sizeof(buf));
  3019. change_slashes_to_backslashes(buf);
  3020. /* Convert to Unicode and back. If doubly-converted string does not
  3021. * match the original, something is fishy, reject. */
  3022. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3023. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3024. WideCharToMultiByte(
  3025. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3026. if (strcmp(buf, buf2) != 0) {
  3027. wbuf[0] = L'\0';
  3028. }
  3029. /* Windows file systems are not case sensitive, but you can still use
  3030. * uppercase and lowercase letters (on all modern file systems).
  3031. * The server can check if the URI uses the same upper/lowercase
  3032. * letters an the file system, effectively making Windows servers
  3033. * case sensitive (like Linux servers are). It is still not possible
  3034. * to use two files with the same name in different cases on Windows
  3035. * (like /a and /A) - this would be possible in Linux.
  3036. * As a default, Windows is not case sensitive, but the case sensitive
  3037. * file name check can be activated by an additional configuration. */
  3038. if (conn) {
  3039. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3040. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3041. /* Use case sensitive compare function */
  3042. fcompare = wcscmp;
  3043. }
  3044. }
  3045. (void)conn; /* conn is currently unused */
  3046. #if !defined(_WIN32_WCE)
  3047. /* Only accept a full file path, not a Windows short (8.3) path. */
  3048. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3049. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3050. if (long_len == 0) {
  3051. err = GetLastError();
  3052. if (err == ERROR_FILE_NOT_FOUND) {
  3053. /* File does not exist. This is not always a problem here. */
  3054. return;
  3055. }
  3056. }
  3057. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3058. /* Short name is used. */
  3059. wbuf[0] = L'\0';
  3060. }
  3061. #else
  3062. (void)long_len;
  3063. (void)wbuf2;
  3064. (void)err;
  3065. if (strchr(path, '~')) {
  3066. wbuf[0] = L'\0';
  3067. }
  3068. #endif
  3069. }
  3070. /* Windows happily opens files with some garbage at the end of file name.
  3071. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3072. * "a.cgi", despite one would expect an error back.
  3073. * This function returns non-0 if path ends with some garbage. */
  3074. static int
  3075. path_cannot_disclose_cgi(const char *path)
  3076. {
  3077. static const char *allowed_last_characters = "_-";
  3078. int last = path[strlen(path) - 1];
  3079. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3080. }
  3081. static int
  3082. mg_stat(const struct mg_connection *conn,
  3083. const char *path,
  3084. struct mg_file_stat *filep)
  3085. {
  3086. wchar_t wbuf[PATH_MAX];
  3087. WIN32_FILE_ATTRIBUTE_DATA info;
  3088. time_t creation_time;
  3089. if (!filep) {
  3090. return 0;
  3091. }
  3092. memset(filep, 0, sizeof(*filep));
  3093. if (conn && is_file_in_memory(conn, path)) {
  3094. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3095. * memset */
  3096. filep->last_modified = time(NULL); /* xxxxxxxx */
  3097. /* last_modified = now ... assumes the file may change during runtime,
  3098. * so every mg_fopen call may return different data */
  3099. /* last_modified = conn->ctx.start_time;
  3100. * May be used it the data does not change during runtime. This allows
  3101. * browser caching. Since we do not know, we have to assume the file
  3102. * in memory may change. */
  3103. return 1;
  3104. }
  3105. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3106. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3107. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3108. filep->last_modified =
  3109. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3110. info.ftLastWriteTime.dwHighDateTime);
  3111. /* On Windows, the file creation time can be higher than the
  3112. * modification time, e.g. when a file is copied.
  3113. * Since the Last-Modified timestamp is used for caching
  3114. * it should be based on the most recent timestamp. */
  3115. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3116. info.ftCreationTime.dwHighDateTime);
  3117. if (creation_time > filep->last_modified) {
  3118. filep->last_modified = creation_time;
  3119. }
  3120. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3121. /* If file name is fishy, reset the file structure and return
  3122. * error.
  3123. * Note it is important to reset, not just return the error, cause
  3124. * functions like is_file_opened() check the struct. */
  3125. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3126. memset(filep, 0, sizeof(*filep));
  3127. return 0;
  3128. }
  3129. return 1;
  3130. }
  3131. return 0;
  3132. }
  3133. static int
  3134. mg_remove(const struct mg_connection *conn, const char *path)
  3135. {
  3136. wchar_t wbuf[PATH_MAX];
  3137. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3138. return DeleteFileW(wbuf) ? 0 : -1;
  3139. }
  3140. static int
  3141. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3142. {
  3143. wchar_t wbuf[PATH_MAX];
  3144. (void)mode;
  3145. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3146. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3147. }
  3148. /* Create substitutes for POSIX functions in Win32. */
  3149. #if defined(__MINGW32__)
  3150. /* Show no warning in case system functions are not used. */
  3151. #pragma GCC diagnostic push
  3152. #pragma GCC diagnostic ignored "-Wunused-function"
  3153. #endif
  3154. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3155. static DIR *
  3156. mg_opendir(const struct mg_connection *conn, const char *name)
  3157. {
  3158. DIR *dir = NULL;
  3159. wchar_t wpath[PATH_MAX];
  3160. DWORD attrs;
  3161. if (name == NULL) {
  3162. SetLastError(ERROR_BAD_ARGUMENTS);
  3163. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3164. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3165. } else {
  3166. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3167. attrs = GetFileAttributesW(wpath);
  3168. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3169. == FILE_ATTRIBUTE_DIRECTORY)) {
  3170. (void)wcscat(wpath, L"\\*");
  3171. dir->handle = FindFirstFileW(wpath, &dir->info);
  3172. dir->result.d_name[0] = '\0';
  3173. } else {
  3174. mg_free(dir);
  3175. dir = NULL;
  3176. }
  3177. }
  3178. return dir;
  3179. }
  3180. static int
  3181. mg_closedir(DIR *dir)
  3182. {
  3183. int result = 0;
  3184. if (dir != NULL) {
  3185. if (dir->handle != INVALID_HANDLE_VALUE)
  3186. result = FindClose(dir->handle) ? 0 : -1;
  3187. mg_free(dir);
  3188. } else {
  3189. result = -1;
  3190. SetLastError(ERROR_BAD_ARGUMENTS);
  3191. }
  3192. return result;
  3193. }
  3194. static struct dirent *
  3195. mg_readdir(DIR *dir)
  3196. {
  3197. struct dirent *result = 0;
  3198. if (dir) {
  3199. if (dir->handle != INVALID_HANDLE_VALUE) {
  3200. result = &dir->result;
  3201. (void)WideCharToMultiByte(CP_UTF8,
  3202. 0,
  3203. dir->info.cFileName,
  3204. -1,
  3205. result->d_name,
  3206. sizeof(result->d_name),
  3207. NULL,
  3208. NULL);
  3209. if (!FindNextFileW(dir->handle, &dir->info)) {
  3210. (void)FindClose(dir->handle);
  3211. dir->handle = INVALID_HANDLE_VALUE;
  3212. }
  3213. } else {
  3214. SetLastError(ERROR_FILE_NOT_FOUND);
  3215. }
  3216. } else {
  3217. SetLastError(ERROR_BAD_ARGUMENTS);
  3218. }
  3219. return result;
  3220. }
  3221. #ifndef HAVE_POLL
  3222. static int
  3223. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3224. {
  3225. struct timeval tv;
  3226. fd_set set;
  3227. unsigned int i;
  3228. int result;
  3229. SOCKET maxfd = 0;
  3230. memset(&tv, 0, sizeof(tv));
  3231. tv.tv_sec = milliseconds / 1000;
  3232. tv.tv_usec = (milliseconds % 1000) * 1000;
  3233. FD_ZERO(&set);
  3234. for (i = 0; i < n; i++) {
  3235. FD_SET((SOCKET)pfd[i].fd, &set);
  3236. pfd[i].revents = 0;
  3237. if (pfd[i].fd > maxfd) {
  3238. maxfd = pfd[i].fd;
  3239. }
  3240. }
  3241. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3242. for (i = 0; i < n; i++) {
  3243. if (FD_ISSET(pfd[i].fd, &set)) {
  3244. pfd[i].revents = POLLIN;
  3245. }
  3246. }
  3247. }
  3248. /* We should subtract the time used in select from remaining
  3249. * "milliseconds", in particular if called from mg_poll with a
  3250. * timeout quantum.
  3251. * Unfortunately, the remaining time is not stored in "tv" in all
  3252. * implementations, so the result in "tv" must be considered undefined.
  3253. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3254. return result;
  3255. }
  3256. #endif /* HAVE_POLL */
  3257. #if defined(__MINGW32__)
  3258. /* Enable unused function warning again */
  3259. #pragma GCC diagnostic pop
  3260. #endif
  3261. static void
  3262. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3263. {
  3264. (void)conn; /* Unused. */
  3265. #if defined(_WIN32_WCE)
  3266. (void)sock;
  3267. #else
  3268. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3269. #endif
  3270. }
  3271. int
  3272. mg_start_thread(mg_thread_func_t f, void *p)
  3273. {
  3274. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3275. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3276. */
  3277. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3278. == ((uintptr_t)(-1L)))
  3279. ? -1
  3280. : 0);
  3281. #else
  3282. return (
  3283. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3284. ? -1
  3285. : 0);
  3286. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3287. }
  3288. /* Start a thread storing the thread context. */
  3289. static int
  3290. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3291. void *p,
  3292. pthread_t *threadidptr)
  3293. {
  3294. uintptr_t uip;
  3295. HANDLE threadhandle;
  3296. int result = -1;
  3297. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3298. threadhandle = (HANDLE)uip;
  3299. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3300. *threadidptr = threadhandle;
  3301. result = 0;
  3302. }
  3303. return result;
  3304. }
  3305. /* Wait for a thread to finish. */
  3306. static int
  3307. mg_join_thread(pthread_t threadid)
  3308. {
  3309. int result;
  3310. DWORD dwevent;
  3311. result = -1;
  3312. dwevent = WaitForSingleObject(threadid, INFINITE);
  3313. if (dwevent == WAIT_FAILED) {
  3314. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3315. } else {
  3316. if (dwevent == WAIT_OBJECT_0) {
  3317. CloseHandle(threadid);
  3318. result = 0;
  3319. }
  3320. }
  3321. return result;
  3322. }
  3323. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3324. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3325. /* Create substitutes for POSIX functions in Win32. */
  3326. #if defined(__MINGW32__)
  3327. /* Show no warning in case system functions are not used. */
  3328. #pragma GCC diagnostic push
  3329. #pragma GCC diagnostic ignored "-Wunused-function"
  3330. #endif
  3331. static HANDLE
  3332. dlopen(const char *dll_name, int flags)
  3333. {
  3334. wchar_t wbuf[PATH_MAX];
  3335. (void)flags;
  3336. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3337. return LoadLibraryW(wbuf);
  3338. }
  3339. static int
  3340. dlclose(void *handle)
  3341. {
  3342. int result;
  3343. if (FreeLibrary((HMODULE)handle) != 0) {
  3344. result = 0;
  3345. } else {
  3346. result = -1;
  3347. }
  3348. return result;
  3349. }
  3350. #if defined(__MINGW32__)
  3351. /* Enable unused function warning again */
  3352. #pragma GCC diagnostic pop
  3353. #endif
  3354. #endif
  3355. #if !defined(NO_CGI)
  3356. #define SIGKILL (0)
  3357. static int
  3358. kill(pid_t pid, int sig_num)
  3359. {
  3360. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3361. (void)CloseHandle((HANDLE)pid);
  3362. return 0;
  3363. }
  3364. static void
  3365. trim_trailing_whitespaces(char *s)
  3366. {
  3367. char *e = s + strlen(s) - 1;
  3368. while (e > s && isspace(*(unsigned char *)e)) {
  3369. *e-- = '\0';
  3370. }
  3371. }
  3372. static pid_t
  3373. spawn_process(struct mg_connection *conn,
  3374. const char *prog,
  3375. char *envblk,
  3376. char *envp[],
  3377. int fdin[2],
  3378. int fdout[2],
  3379. int fderr[2],
  3380. const char *dir)
  3381. {
  3382. HANDLE me;
  3383. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3384. cmdline[PATH_MAX], buf[PATH_MAX];
  3385. int truncated;
  3386. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3387. STARTUPINFOA si;
  3388. PROCESS_INFORMATION pi = {0};
  3389. (void)envp;
  3390. memset(&si, 0, sizeof(si));
  3391. si.cb = sizeof(si);
  3392. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3393. si.wShowWindow = SW_HIDE;
  3394. me = GetCurrentProcess();
  3395. DuplicateHandle(me,
  3396. (HANDLE)_get_osfhandle(fdin[0]),
  3397. me,
  3398. &si.hStdInput,
  3399. 0,
  3400. TRUE,
  3401. DUPLICATE_SAME_ACCESS);
  3402. DuplicateHandle(me,
  3403. (HANDLE)_get_osfhandle(fdout[1]),
  3404. me,
  3405. &si.hStdOutput,
  3406. 0,
  3407. TRUE,
  3408. DUPLICATE_SAME_ACCESS);
  3409. DuplicateHandle(me,
  3410. (HANDLE)_get_osfhandle(fderr[1]),
  3411. me,
  3412. &si.hStdError,
  3413. 0,
  3414. TRUE,
  3415. DUPLICATE_SAME_ACCESS);
  3416. /* Mark handles that should not be inherited. See
  3417. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3418. */
  3419. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3420. HANDLE_FLAG_INHERIT,
  3421. 0);
  3422. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3423. HANDLE_FLAG_INHERIT,
  3424. 0);
  3425. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3426. HANDLE_FLAG_INHERIT,
  3427. 0);
  3428. /* If CGI file is a script, try to read the interpreter line */
  3429. interp = conn->ctx->config[CGI_INTERPRETER];
  3430. if (interp == NULL) {
  3431. buf[0] = buf[1] = '\0';
  3432. /* Read the first line of the script into the buffer */
  3433. mg_snprintf(
  3434. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3435. if (truncated) {
  3436. pi.hProcess = (pid_t)-1;
  3437. goto spawn_cleanup;
  3438. }
  3439. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3440. p = (char *)file.access.membuf;
  3441. mg_fgets(buf, sizeof(buf), &file, &p);
  3442. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3443. buf[sizeof(buf) - 1] = '\0';
  3444. }
  3445. if (buf[0] == '#' && buf[1] == '!') {
  3446. trim_trailing_whitespaces(buf + 2);
  3447. } else {
  3448. buf[2] = '\0';
  3449. }
  3450. interp = buf + 2;
  3451. }
  3452. if (interp[0] != '\0') {
  3453. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3454. interp = full_interp;
  3455. }
  3456. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3457. if (interp[0] != '\0') {
  3458. mg_snprintf(conn,
  3459. &truncated,
  3460. cmdline,
  3461. sizeof(cmdline),
  3462. "\"%s\" \"%s\\%s\"",
  3463. interp,
  3464. full_dir,
  3465. prog);
  3466. } else {
  3467. mg_snprintf(conn,
  3468. &truncated,
  3469. cmdline,
  3470. sizeof(cmdline),
  3471. "\"%s\\%s\"",
  3472. full_dir,
  3473. prog);
  3474. }
  3475. if (truncated) {
  3476. pi.hProcess = (pid_t)-1;
  3477. goto spawn_cleanup;
  3478. }
  3479. DEBUG_TRACE("Running [%s]", cmdline);
  3480. if (CreateProcessA(NULL,
  3481. cmdline,
  3482. NULL,
  3483. NULL,
  3484. TRUE,
  3485. CREATE_NEW_PROCESS_GROUP,
  3486. envblk,
  3487. NULL,
  3488. &si,
  3489. &pi) == 0) {
  3490. mg_cry(
  3491. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3492. pi.hProcess = (pid_t)-1;
  3493. /* goto spawn_cleanup; */
  3494. }
  3495. spawn_cleanup:
  3496. (void)CloseHandle(si.hStdOutput);
  3497. (void)CloseHandle(si.hStdError);
  3498. (void)CloseHandle(si.hStdInput);
  3499. if (pi.hThread != NULL) {
  3500. (void)CloseHandle(pi.hThread);
  3501. }
  3502. return (pid_t)pi.hProcess;
  3503. }
  3504. #endif /* !NO_CGI */
  3505. static int
  3506. set_blocking_mode(SOCKET sock, int blocking)
  3507. {
  3508. unsigned long non_blocking = !blocking;
  3509. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3510. }
  3511. #else
  3512. static int
  3513. mg_stat(const struct mg_connection *conn,
  3514. const char *path,
  3515. struct mg_file_stat *filep)
  3516. {
  3517. struct stat st;
  3518. if (!filep) {
  3519. return 0;
  3520. }
  3521. memset(filep, 0, sizeof(*filep));
  3522. if (conn && is_file_in_memory(conn, path)) {
  3523. return 1;
  3524. }
  3525. if (0 == stat(path, &st)) {
  3526. filep->size = (uint64_t)(st.st_size);
  3527. filep->last_modified = st.st_mtime;
  3528. filep->is_directory = S_ISDIR(st.st_mode);
  3529. return 1;
  3530. }
  3531. return 0;
  3532. }
  3533. static void
  3534. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3535. {
  3536. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3537. if (conn) {
  3538. mg_cry(conn,
  3539. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3540. __func__,
  3541. strerror(ERRNO));
  3542. }
  3543. }
  3544. }
  3545. int
  3546. mg_start_thread(mg_thread_func_t func, void *param)
  3547. {
  3548. pthread_t thread_id;
  3549. pthread_attr_t attr;
  3550. int result;
  3551. (void)pthread_attr_init(&attr);
  3552. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3553. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3554. /* Compile-time option to control stack size,
  3555. * e.g. -DUSE_STACK_SIZE=16384 */
  3556. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3557. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3558. result = pthread_create(&thread_id, &attr, func, param);
  3559. pthread_attr_destroy(&attr);
  3560. return result;
  3561. }
  3562. /* Start a thread storing the thread context. */
  3563. static int
  3564. mg_start_thread_with_id(mg_thread_func_t func,
  3565. void *param,
  3566. pthread_t *threadidptr)
  3567. {
  3568. pthread_t thread_id;
  3569. pthread_attr_t attr;
  3570. int result;
  3571. (void)pthread_attr_init(&attr);
  3572. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3573. /* Compile-time option to control stack size,
  3574. * e.g. -DUSE_STACK_SIZE=16384 */
  3575. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3576. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3577. result = pthread_create(&thread_id, &attr, func, param);
  3578. pthread_attr_destroy(&attr);
  3579. if ((result == 0) && (threadidptr != NULL)) {
  3580. *threadidptr = thread_id;
  3581. }
  3582. return result;
  3583. }
  3584. /* Wait for a thread to finish. */
  3585. static int
  3586. mg_join_thread(pthread_t threadid)
  3587. {
  3588. int result;
  3589. result = pthread_join(threadid, NULL);
  3590. return result;
  3591. }
  3592. #ifndef NO_CGI
  3593. static pid_t
  3594. spawn_process(struct mg_connection *conn,
  3595. const char *prog,
  3596. char *envblk,
  3597. char *envp[],
  3598. int fdin[2],
  3599. int fdout[2],
  3600. int fderr[2],
  3601. const char *dir)
  3602. {
  3603. pid_t pid;
  3604. const char *interp;
  3605. (void)envblk;
  3606. if (conn == NULL) {
  3607. return 0;
  3608. }
  3609. if ((pid = fork()) == -1) {
  3610. /* Parent */
  3611. send_http_error(conn,
  3612. 500,
  3613. "Error: Creating CGI process\nfork(): %s",
  3614. strerror(ERRNO));
  3615. } else if (pid == 0) {
  3616. /* Child */
  3617. if (chdir(dir) != 0) {
  3618. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3619. } else if (dup2(fdin[0], 0) == -1) {
  3620. mg_cry(conn,
  3621. "%s: dup2(%d, 0): %s",
  3622. __func__,
  3623. fdin[0],
  3624. strerror(ERRNO));
  3625. } else if (dup2(fdout[1], 1) == -1) {
  3626. mg_cry(conn,
  3627. "%s: dup2(%d, 1): %s",
  3628. __func__,
  3629. fdout[1],
  3630. strerror(ERRNO));
  3631. } else if (dup2(fderr[1], 2) == -1) {
  3632. mg_cry(conn,
  3633. "%s: dup2(%d, 2): %s",
  3634. __func__,
  3635. fderr[1],
  3636. strerror(ERRNO));
  3637. } else {
  3638. /* Keep stderr and stdout in two different pipes.
  3639. * Stdout will be sent back to the client,
  3640. * stderr should go into a server error log. */
  3641. (void)close(fdin[0]);
  3642. (void)close(fdout[1]);
  3643. (void)close(fderr[1]);
  3644. /* Close write end fdin and read end fdout and fderr */
  3645. (void)close(fdin[1]);
  3646. (void)close(fdout[0]);
  3647. (void)close(fderr[0]);
  3648. /* After exec, all signal handlers are restored to their default
  3649. * values, with one exception of SIGCHLD. According to
  3650. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3651. * leave unchanged after exec if it was set to be ignored. Restore
  3652. * it to default action. */
  3653. signal(SIGCHLD, SIG_DFL);
  3654. interp = conn->ctx->config[CGI_INTERPRETER];
  3655. if (interp == NULL) {
  3656. (void)execle(prog, prog, NULL, envp);
  3657. mg_cry(conn,
  3658. "%s: execle(%s): %s",
  3659. __func__,
  3660. prog,
  3661. strerror(ERRNO));
  3662. } else {
  3663. (void)execle(interp, interp, prog, NULL, envp);
  3664. mg_cry(conn,
  3665. "%s: execle(%s %s): %s",
  3666. __func__,
  3667. interp,
  3668. prog,
  3669. strerror(ERRNO));
  3670. }
  3671. }
  3672. exit(EXIT_FAILURE);
  3673. }
  3674. return pid;
  3675. }
  3676. #endif /* !NO_CGI */
  3677. static int
  3678. set_blocking_mode(SOCKET sock, int blocking)
  3679. {
  3680. int flags;
  3681. flags = fcntl(sock, F_GETFL, 0);
  3682. if (blocking) {
  3683. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3684. } else {
  3685. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3686. }
  3687. return 0;
  3688. }
  3689. #endif /* _WIN32 */
  3690. /* End of initial operating system specific define block. */
  3691. /* Get a random number (independent of C rand function) */
  3692. static uint64_t
  3693. get_random(void)
  3694. {
  3695. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3696. static uint64_t lcg = 0; /* Linear congruential generator */
  3697. struct timespec now;
  3698. memset(&now, 0, sizeof(now));
  3699. clock_gettime(CLOCK_MONOTONIC, &now);
  3700. if (lfsr == 0) {
  3701. /* lfsr will be only 0 if has not been initialized,
  3702. * so this code is called only once. */
  3703. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3704. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3705. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3706. + (uint64_t)(ptrdiff_t)&now;
  3707. } else {
  3708. /* Get the next step of both random number generators. */
  3709. lfsr = (lfsr >> 1)
  3710. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3711. << 63);
  3712. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3713. }
  3714. /* Combining two pseudo-random number generators and a high resolution part
  3715. * of the current server time will make it hard (impossible?) to guess the
  3716. * next number. */
  3717. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3718. }
  3719. static int
  3720. mg_poll(struct pollfd *pfd,
  3721. unsigned int n,
  3722. int milliseconds,
  3723. volatile int *stop_server)
  3724. {
  3725. int ms_now, result;
  3726. /* Call poll, but only for a maximum time of a few seconds.
  3727. * This will allow to stop the server after some seconds, instead
  3728. * of having to wait for a long socket timeout. */
  3729. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3730. do {
  3731. if (*stop_server) {
  3732. /* Shut down signal */
  3733. return -2;
  3734. }
  3735. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3736. ms_now = milliseconds;
  3737. }
  3738. result = poll(pfd, n, ms_now);
  3739. if (result != 0) {
  3740. /* Poll returned either success (1) or error (-1).
  3741. * Forward both to the caller. */
  3742. return result;
  3743. }
  3744. /* Poll returned timeout (0). */
  3745. if (milliseconds > 0) {
  3746. milliseconds -= ms_now;
  3747. }
  3748. } while (milliseconds != 0);
  3749. return result;
  3750. }
  3751. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3752. * descriptor. Return number of bytes written. */
  3753. static int
  3754. push(struct mg_context *ctx,
  3755. FILE *fp,
  3756. SOCKET sock,
  3757. SSL *ssl,
  3758. const char *buf,
  3759. int len,
  3760. double timeout)
  3761. {
  3762. struct timespec start, now;
  3763. int n, err;
  3764. #ifdef _WIN32
  3765. typedef int len_t;
  3766. #else
  3767. typedef size_t len_t;
  3768. #endif
  3769. if (timeout > 0) {
  3770. memset(&start, 0, sizeof(start));
  3771. memset(&now, 0, sizeof(now));
  3772. clock_gettime(CLOCK_MONOTONIC, &start);
  3773. }
  3774. if (ctx == NULL) {
  3775. return -1;
  3776. }
  3777. #ifdef NO_SSL
  3778. if (ssl) {
  3779. return -1;
  3780. }
  3781. #endif
  3782. do {
  3783. #ifndef NO_SSL
  3784. if (ssl != NULL) {
  3785. n = SSL_write(ssl, buf, len);
  3786. if (n <= 0) {
  3787. err = SSL_get_error(ssl, n);
  3788. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3789. err = ERRNO;
  3790. } else if ((err == SSL_ERROR_WANT_READ)
  3791. || (err == SSL_ERROR_WANT_WRITE)) {
  3792. n = 0;
  3793. } else {
  3794. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3795. return -1;
  3796. }
  3797. } else {
  3798. err = 0;
  3799. }
  3800. } else
  3801. #endif
  3802. if (fp != NULL) {
  3803. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3804. if (ferror(fp)) {
  3805. n = -1;
  3806. err = ERRNO;
  3807. } else {
  3808. err = 0;
  3809. }
  3810. } else {
  3811. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3812. err = (n < 0) ? ERRNO : 0;
  3813. if (n <= 0) {
  3814. /* shutdown of the socket at client side */
  3815. return -1;
  3816. }
  3817. #if defined(TEMPORARY_INSTRUMENTATION)
  3818. {
  3819. FILE *f = fopen("r:\\all.txt", "ab");
  3820. fprintf(f, "\r\n%010u SEND:\r\n", GetTickCount());
  3821. fwrite(buf, 1, n, f);
  3822. fclose(f);
  3823. }
  3824. #endif
  3825. }
  3826. if (ctx->stop_flag) {
  3827. return -1;
  3828. }
  3829. if ((n > 0) || (n == 0 && len == 0)) {
  3830. /* some data has been read, or no data was requested */
  3831. return n;
  3832. }
  3833. if (n < 0) {
  3834. /* socket error - check errno */
  3835. DEBUG_TRACE("send() failed, error %d", err);
  3836. /* TODO: error handling depending on the error code.
  3837. * These codes are different between Windows and Linux.
  3838. */
  3839. return -1;
  3840. }
  3841. /* Only in case n=0 (timeout), repeat calling the write function */
  3842. if (timeout > 0) {
  3843. clock_gettime(CLOCK_MONOTONIC, &now);
  3844. }
  3845. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3846. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3847. used */
  3848. return -1;
  3849. }
  3850. static int64_t
  3851. push_all(struct mg_context *ctx,
  3852. FILE *fp,
  3853. SOCKET sock,
  3854. SSL *ssl,
  3855. const char *buf,
  3856. int64_t len)
  3857. {
  3858. double timeout = -1.0;
  3859. int64_t n, nwritten = 0;
  3860. if (ctx == NULL) {
  3861. return -1;
  3862. }
  3863. if (ctx->config[REQUEST_TIMEOUT]) {
  3864. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3865. }
  3866. while (len > 0 && ctx->stop_flag == 0) {
  3867. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3868. if (n < 0) {
  3869. if (nwritten == 0) {
  3870. nwritten = n; /* Propagate the error */
  3871. }
  3872. break;
  3873. } else if (n == 0) {
  3874. break; /* No more data to write */
  3875. } else {
  3876. nwritten += n;
  3877. len -= n;
  3878. }
  3879. }
  3880. return nwritten;
  3881. }
  3882. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3883. * Return negative value on error, or number of bytes read on success. */
  3884. static int
  3885. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3886. {
  3887. int nread, err = 0;
  3888. #ifdef _WIN32
  3889. typedef int len_t;
  3890. #else
  3891. typedef size_t len_t;
  3892. #endif
  3893. if (fp != NULL) {
  3894. #if !defined(_WIN32_WCE)
  3895. /* Use read() instead of fread(), because if we're reading from the
  3896. * CGI pipe, fread() may block until IO buffer is filled up. We
  3897. * cannot afford to block and must pass all read bytes immediately
  3898. * to the client. */
  3899. nread = (int)read(fileno(fp), buf, (size_t)len);
  3900. #else
  3901. /* WinCE does not support CGI pipes */
  3902. nread = (int)fread(buf, 1, (size_t)len, fp);
  3903. #endif
  3904. err = (nread < 0) ? ERRNO : 0;
  3905. #ifndef NO_SSL
  3906. } else if (conn->ssl != NULL) {
  3907. struct pollfd pfd[1];
  3908. int pollres;
  3909. pfd[0].fd = conn->client.sock;
  3910. pfd[0].events = POLLIN;
  3911. pollres =
  3912. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3913. if (conn->ctx->stop_flag) {
  3914. return -1;
  3915. }
  3916. if (pollres > 0) {
  3917. nread = SSL_read(conn->ssl, buf, len);
  3918. if (nread <= 0) {
  3919. err = SSL_get_error(conn->ssl, nread);
  3920. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3921. err = ERRNO;
  3922. } else if ((err == SSL_ERROR_WANT_READ)
  3923. || (err == SSL_ERROR_WANT_WRITE)) {
  3924. nread = 0;
  3925. } else {
  3926. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3927. return -1;
  3928. }
  3929. } else {
  3930. err = 0;
  3931. }
  3932. } else if (pollres < 0) {
  3933. /* Error */
  3934. return -1;
  3935. } else {
  3936. /* pollres = 0 means timeout */
  3937. nread = 0;
  3938. }
  3939. #endif
  3940. } else {
  3941. struct pollfd pfd[1];
  3942. int pollres;
  3943. pfd[0].fd = conn->client.sock;
  3944. pfd[0].events = POLLIN;
  3945. pollres =
  3946. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3947. if (conn->ctx->stop_flag) {
  3948. return -1;
  3949. }
  3950. if (pollres > 0) {
  3951. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3952. err = (nread < 0) ? ERRNO : 0;
  3953. if (nread <= 0) {
  3954. /* shutdown of the socket at client side */
  3955. return -1;
  3956. }
  3957. #if defined(TEMPORARY_INSTRUMENTATION)
  3958. {
  3959. FILE *f = fopen("r:\\all.txt", "ab");
  3960. fprintf(f, "\r\n%010u RECV:\r\n", GetTickCount());
  3961. fwrite(buf, 1, nread, f);
  3962. fclose(f);
  3963. }
  3964. #endif
  3965. } else if (pollres < 0) {
  3966. /* error callint poll */
  3967. return -1;
  3968. } else {
  3969. /* pollres = 0 means timeout */
  3970. nread = 0;
  3971. }
  3972. }
  3973. if (conn->ctx->stop_flag) {
  3974. return -1;
  3975. }
  3976. if ((nread > 0) || (nread == 0 && len == 0)) {
  3977. /* some data has been read, or no data was requested */
  3978. return nread;
  3979. }
  3980. if (nread < 0) {
  3981. /* socket error - check errno */
  3982. #ifdef _WIN32
  3983. if (err == WSAEWOULDBLOCK) {
  3984. /* TODO: check if this is still required */
  3985. /* standard case if called from close_socket_gracefully */
  3986. return -1;
  3987. } else if (err == WSAETIMEDOUT) {
  3988. /* TODO: check if this is still required */
  3989. /* timeout is handled by the while loop */
  3990. return 0;
  3991. } else if (err == WSAECONNABORTED) {
  3992. /* See https://www.chilkatsoft.com/p/p_299.asp */
  3993. return -1;
  3994. } else {
  3995. DEBUG_TRACE("recv() failed, error %d", err);
  3996. return -1;
  3997. }
  3998. #else
  3999. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4000. * if the timeout is reached and if the socket was set to non-
  4001. * blocking in close_socket_gracefully, so we can not distinguish
  4002. * here. We have to wait for the timeout in both cases for now.
  4003. */
  4004. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4005. /* TODO: check if this is still required */
  4006. /* EAGAIN/EWOULDBLOCK:
  4007. * standard case if called from close_socket_gracefully
  4008. * => should return -1 */
  4009. /* or timeout occured
  4010. * => the code must stay in the while loop */
  4011. /* EINTR can be generated on a socket with a timeout set even
  4012. * when SA_RESTART is effective for all relevant signals
  4013. * (see signal(7)).
  4014. * => stay in the while loop */
  4015. } else {
  4016. DEBUG_TRACE("recv() failed, error %d", err);
  4017. return -1;
  4018. }
  4019. #endif
  4020. }
  4021. /* Timeout occured, but no data available. */
  4022. return -1;
  4023. }
  4024. static int
  4025. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4026. {
  4027. int n, nread = 0;
  4028. double timeout = -1.0;
  4029. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4030. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4031. }
  4032. while (len > 0 && conn->ctx->stop_flag == 0) {
  4033. n = pull(fp, conn, buf + nread, len, timeout);
  4034. if (n < 0) {
  4035. if (nread == 0) {
  4036. nread = n; /* Propagate the error */
  4037. }
  4038. break;
  4039. } else if (n == 0) {
  4040. break; /* No more data to read */
  4041. } else {
  4042. conn->consumed_content += n;
  4043. nread += n;
  4044. len -= n;
  4045. }
  4046. }
  4047. return nread;
  4048. }
  4049. static void
  4050. discard_unread_request_data(struct mg_connection *conn)
  4051. {
  4052. char buf[MG_BUF_LEN];
  4053. size_t to_read;
  4054. int nread;
  4055. if (conn == NULL) {
  4056. return;
  4057. }
  4058. to_read = sizeof(buf);
  4059. if (conn->is_chunked) {
  4060. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4061. * completely */
  4062. while (conn->is_chunked == 1) {
  4063. nread = mg_read(conn, buf, to_read);
  4064. if (nread <= 0) {
  4065. break;
  4066. }
  4067. }
  4068. } else {
  4069. /* Not chunked: content length is known */
  4070. while (conn->consumed_content < conn->content_len) {
  4071. if (to_read
  4072. > (size_t)(conn->content_len - conn->consumed_content)) {
  4073. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4074. }
  4075. nread = mg_read(conn, buf, to_read);
  4076. if (nread <= 0) {
  4077. break;
  4078. }
  4079. }
  4080. }
  4081. }
  4082. static int
  4083. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4084. {
  4085. int64_t n, buffered_len, nread;
  4086. int64_t len64 =
  4087. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4088. * int, we may not read more
  4089. * bytes */
  4090. const char *body;
  4091. if (conn == NULL) {
  4092. return 0;
  4093. }
  4094. /* If Content-Length is not set for a PUT or POST request, read until
  4095. * socket is closed */
  4096. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4097. conn->content_len = INT64_MAX;
  4098. conn->must_close = 1;
  4099. }
  4100. nread = 0;
  4101. if (conn->consumed_content < conn->content_len) {
  4102. /* Adjust number of bytes to read. */
  4103. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4104. if (left_to_read < len64) {
  4105. /* Do not read more than the total content length of the request.
  4106. */
  4107. len64 = left_to_read;
  4108. }
  4109. /* Return buffered data */
  4110. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4111. - conn->consumed_content;
  4112. if (buffered_len > 0) {
  4113. if (len64 < buffered_len) {
  4114. buffered_len = len64;
  4115. }
  4116. body = conn->buf + conn->request_len + conn->consumed_content;
  4117. memcpy(buf, body, (size_t)buffered_len);
  4118. len64 -= buffered_len;
  4119. conn->consumed_content += buffered_len;
  4120. nread += buffered_len;
  4121. buf = (char *)buf + buffered_len;
  4122. }
  4123. /* We have returned all buffered data. Read new data from the remote
  4124. * socket.
  4125. */
  4126. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4127. nread += n;
  4128. } else {
  4129. nread = ((nread > 0) ? nread : n);
  4130. }
  4131. }
  4132. return (int)nread;
  4133. }
  4134. static char
  4135. mg_getc(struct mg_connection *conn)
  4136. {
  4137. char c;
  4138. if (conn == NULL) {
  4139. return 0;
  4140. }
  4141. conn->content_len++;
  4142. if (mg_read_inner(conn, &c, 1) <= 0) {
  4143. return (char)0;
  4144. }
  4145. return c;
  4146. }
  4147. int
  4148. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4149. {
  4150. if (len > INT_MAX) {
  4151. len = INT_MAX;
  4152. }
  4153. if (conn == NULL) {
  4154. return 0;
  4155. }
  4156. if (conn->is_chunked) {
  4157. size_t all_read = 0;
  4158. while (len > 0) {
  4159. if (conn->is_chunked == 2) {
  4160. /* No more data left to read */
  4161. return 0;
  4162. }
  4163. if (conn->chunk_remainder) {
  4164. /* copy from the remainder of the last received chunk */
  4165. long read_ret;
  4166. size_t read_now =
  4167. ((conn->chunk_remainder > len) ? (len)
  4168. : (conn->chunk_remainder));
  4169. conn->content_len += (int)read_now;
  4170. read_ret =
  4171. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4172. if (read_ret < 1) {
  4173. /* read error */
  4174. return -1;
  4175. }
  4176. all_read += (size_t)read_ret;
  4177. conn->chunk_remainder -= (size_t)read_ret;
  4178. len -= (size_t)read_ret;
  4179. if (conn->chunk_remainder == 0) {
  4180. /* Add data bytes in the current chunk have been read,
  4181. * so we are expecting \r\n now. */
  4182. char x1 = mg_getc(conn);
  4183. char x2 = mg_getc(conn);
  4184. if ((x1 != '\r') || (x2 != '\n')) {
  4185. /* Protocol violation */
  4186. return -1;
  4187. }
  4188. }
  4189. } else {
  4190. /* fetch a new chunk */
  4191. int i = 0;
  4192. char lenbuf[64];
  4193. char *end = 0;
  4194. unsigned long chunkSize = 0;
  4195. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4196. lenbuf[i] = mg_getc(conn);
  4197. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4198. continue;
  4199. }
  4200. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4201. lenbuf[i + 1] = 0;
  4202. chunkSize = strtoul(lenbuf, &end, 16);
  4203. if (chunkSize == 0) {
  4204. /* regular end of content */
  4205. conn->is_chunked = 2;
  4206. }
  4207. break;
  4208. }
  4209. if (!isxdigit(lenbuf[i])) {
  4210. /* illegal character for chunk length */
  4211. return -1;
  4212. }
  4213. }
  4214. if ((end == NULL) || (*end != '\r')) {
  4215. /* chunksize not set correctly */
  4216. return -1;
  4217. }
  4218. if (chunkSize == 0) {
  4219. break;
  4220. }
  4221. conn->chunk_remainder = chunkSize;
  4222. }
  4223. }
  4224. return (int)all_read;
  4225. }
  4226. return mg_read_inner(conn, buf, len);
  4227. }
  4228. int
  4229. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4230. {
  4231. time_t now;
  4232. int64_t n, total, allowed;
  4233. if (conn == NULL) {
  4234. return 0;
  4235. }
  4236. if (conn->throttle > 0) {
  4237. if ((now = time(NULL)) != conn->last_throttle_time) {
  4238. conn->last_throttle_time = now;
  4239. conn->last_throttle_bytes = 0;
  4240. }
  4241. allowed = conn->throttle - conn->last_throttle_bytes;
  4242. if (allowed > (int64_t)len) {
  4243. allowed = (int64_t)len;
  4244. }
  4245. if ((total = push_all(conn->ctx,
  4246. NULL,
  4247. conn->client.sock,
  4248. conn->ssl,
  4249. (const char *)buf,
  4250. (int64_t)allowed)) == allowed) {
  4251. buf = (const char *)buf + total;
  4252. conn->last_throttle_bytes += total;
  4253. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4254. allowed = (conn->throttle > ((int64_t)len - total))
  4255. ? (int64_t)len - total
  4256. : conn->throttle;
  4257. if ((n = push_all(conn->ctx,
  4258. NULL,
  4259. conn->client.sock,
  4260. conn->ssl,
  4261. (const char *)buf,
  4262. (int64_t)allowed)) != allowed) {
  4263. break;
  4264. }
  4265. sleep(1);
  4266. conn->last_throttle_bytes = allowed;
  4267. conn->last_throttle_time = time(NULL);
  4268. buf = (const char *)buf + n;
  4269. total += n;
  4270. }
  4271. }
  4272. } else {
  4273. total = push_all(conn->ctx,
  4274. NULL,
  4275. conn->client.sock,
  4276. conn->ssl,
  4277. (const char *)buf,
  4278. (int64_t)len);
  4279. }
  4280. return (int)total;
  4281. }
  4282. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4283. static int
  4284. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4285. {
  4286. va_list ap_copy;
  4287. size_t size = MG_BUF_LEN / 4;
  4288. int len = -1;
  4289. *buf = NULL;
  4290. while (len < 0) {
  4291. if (*buf) {
  4292. mg_free(*buf);
  4293. }
  4294. size *= 4;
  4295. *buf = (char *)mg_malloc(size);
  4296. if (!*buf) {
  4297. break;
  4298. }
  4299. va_copy(ap_copy, ap);
  4300. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4301. va_end(ap_copy);
  4302. (*buf)[size - 1] = 0;
  4303. }
  4304. return len;
  4305. }
  4306. /* Print message to buffer. If buffer is large enough to hold the message,
  4307. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4308. * and return allocated buffer. */
  4309. static int
  4310. alloc_vprintf(char **out_buf,
  4311. char *prealloc_buf,
  4312. size_t prealloc_size,
  4313. const char *fmt,
  4314. va_list ap)
  4315. {
  4316. va_list ap_copy;
  4317. int len;
  4318. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4319. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4320. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4321. * Therefore, we make two passes: on first pass, get required message
  4322. * length.
  4323. * On second pass, actually print the message. */
  4324. va_copy(ap_copy, ap);
  4325. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4326. va_end(ap_copy);
  4327. if (len < 0) {
  4328. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4329. * Switch to alternative code path that uses incremental allocations.
  4330. */
  4331. va_copy(ap_copy, ap);
  4332. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4333. va_end(ap_copy);
  4334. } else if ((size_t)(len) >= prealloc_size) {
  4335. /* The pre-allocated buffer not large enough. */
  4336. /* Allocate a new buffer. */
  4337. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4338. if (!*out_buf) {
  4339. /* Allocation failed. Return -1 as "out of memory" error. */
  4340. return -1;
  4341. }
  4342. /* Buffer allocation successful. Store the string there. */
  4343. va_copy(ap_copy, ap);
  4344. IGNORE_UNUSED_RESULT(
  4345. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4346. va_end(ap_copy);
  4347. } else {
  4348. /* The pre-allocated buffer is large enough.
  4349. * Use it to store the string and return the address. */
  4350. va_copy(ap_copy, ap);
  4351. IGNORE_UNUSED_RESULT(
  4352. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4353. va_end(ap_copy);
  4354. *out_buf = prealloc_buf;
  4355. }
  4356. return len;
  4357. }
  4358. static int
  4359. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4360. {
  4361. char mem[MG_BUF_LEN];
  4362. char *buf = NULL;
  4363. int len;
  4364. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4365. len = mg_write(conn, buf, (size_t)len);
  4366. }
  4367. if (buf != mem && buf != NULL) {
  4368. mg_free(buf);
  4369. }
  4370. return len;
  4371. }
  4372. int
  4373. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4374. {
  4375. va_list ap;
  4376. int result;
  4377. va_start(ap, fmt);
  4378. result = mg_vprintf(conn, fmt, ap);
  4379. va_end(ap);
  4380. return result;
  4381. }
  4382. int
  4383. mg_url_decode(const char *src,
  4384. int src_len,
  4385. char *dst,
  4386. int dst_len,
  4387. int is_form_url_encoded)
  4388. {
  4389. int i, j, a, b;
  4390. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4391. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4392. if (i < src_len - 2 && src[i] == '%'
  4393. && isxdigit(*(const unsigned char *)(src + i + 1))
  4394. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4395. a = tolower(*(const unsigned char *)(src + i + 1));
  4396. b = tolower(*(const unsigned char *)(src + i + 2));
  4397. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4398. i += 2;
  4399. } else if (is_form_url_encoded && src[i] == '+') {
  4400. dst[j] = ' ';
  4401. } else {
  4402. dst[j] = src[i];
  4403. }
  4404. }
  4405. dst[j] = '\0'; /* Null-terminate the destination */
  4406. return (i >= src_len) ? j : -1;
  4407. }
  4408. int
  4409. mg_get_var(const char *data,
  4410. size_t data_len,
  4411. const char *name,
  4412. char *dst,
  4413. size_t dst_len)
  4414. {
  4415. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4416. }
  4417. int
  4418. mg_get_var2(const char *data,
  4419. size_t data_len,
  4420. const char *name,
  4421. char *dst,
  4422. size_t dst_len,
  4423. size_t occurrence)
  4424. {
  4425. const char *p, *e, *s;
  4426. size_t name_len;
  4427. int len;
  4428. if (dst == NULL || dst_len == 0) {
  4429. len = -2;
  4430. } else if (data == NULL || name == NULL || data_len == 0) {
  4431. len = -1;
  4432. dst[0] = '\0';
  4433. } else {
  4434. name_len = strlen(name);
  4435. e = data + data_len;
  4436. len = -1;
  4437. dst[0] = '\0';
  4438. /* data is "var1=val1&var2=val2...". Find variable first */
  4439. for (p = data; p + name_len < e; p++) {
  4440. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4441. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4442. /* Point p to variable value */
  4443. p += name_len + 1;
  4444. /* Point s to the end of the value */
  4445. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4446. if (s == NULL) {
  4447. s = e;
  4448. }
  4449. /* assert(s >= p); */
  4450. if (s < p) {
  4451. return -3;
  4452. }
  4453. /* Decode variable into destination buffer */
  4454. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4455. /* Redirect error code from -1 to -2 (destination buffer too
  4456. * small). */
  4457. if (len == -1) {
  4458. len = -2;
  4459. }
  4460. break;
  4461. }
  4462. }
  4463. }
  4464. return len;
  4465. }
  4466. /* HCP24: some changes to compare hole var_name */
  4467. int
  4468. mg_get_cookie(const char *cookie_header,
  4469. const char *var_name,
  4470. char *dst,
  4471. size_t dst_size)
  4472. {
  4473. const char *s, *p, *end;
  4474. int name_len, len = -1;
  4475. if (dst == NULL || dst_size == 0) {
  4476. return -2;
  4477. }
  4478. dst[0] = '\0';
  4479. if (var_name == NULL || (s = cookie_header) == NULL) {
  4480. return -1;
  4481. }
  4482. name_len = (int)strlen(var_name);
  4483. end = s + strlen(s);
  4484. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4485. if (s[name_len] == '=') {
  4486. /* HCP24: now check is it a substring or a full cookie name */
  4487. if ((s == cookie_header) || (s[-1] == ' ')) {
  4488. s += name_len + 1;
  4489. if ((p = strchr(s, ' ')) == NULL) {
  4490. p = end;
  4491. }
  4492. if (p[-1] == ';') {
  4493. p--;
  4494. }
  4495. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4496. s++;
  4497. p--;
  4498. }
  4499. if ((size_t)(p - s) < dst_size) {
  4500. len = (int)(p - s);
  4501. mg_strlcpy(dst, s, (size_t)len + 1);
  4502. } else {
  4503. len = -3;
  4504. }
  4505. break;
  4506. }
  4507. }
  4508. }
  4509. return len;
  4510. }
  4511. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4512. static void
  4513. base64_encode(const unsigned char *src, int src_len, char *dst)
  4514. {
  4515. static const char *b64 =
  4516. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4517. int i, j, a, b, c;
  4518. for (i = j = 0; i < src_len; i += 3) {
  4519. a = src[i];
  4520. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4521. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4522. dst[j++] = b64[a >> 2];
  4523. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4524. if (i + 1 < src_len) {
  4525. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4526. }
  4527. if (i + 2 < src_len) {
  4528. dst[j++] = b64[c & 63];
  4529. }
  4530. }
  4531. while (j % 4 != 0) {
  4532. dst[j++] = '=';
  4533. }
  4534. dst[j++] = '\0';
  4535. }
  4536. #endif
  4537. #if defined(USE_LUA)
  4538. static unsigned char
  4539. b64reverse(char letter)
  4540. {
  4541. if (letter >= 'A' && letter <= 'Z') {
  4542. return letter - 'A';
  4543. }
  4544. if (letter >= 'a' && letter <= 'z') {
  4545. return letter - 'a' + 26;
  4546. }
  4547. if (letter >= '0' && letter <= '9') {
  4548. return letter - '0' + 52;
  4549. }
  4550. if (letter == '+') {
  4551. return 62;
  4552. }
  4553. if (letter == '/') {
  4554. return 63;
  4555. }
  4556. if (letter == '=') {
  4557. return 255; /* normal end */
  4558. }
  4559. return 254; /* error */
  4560. }
  4561. static int
  4562. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4563. {
  4564. int i;
  4565. unsigned char a, b, c, d;
  4566. *dst_len = 0;
  4567. for (i = 0; i < src_len; i += 4) {
  4568. a = b64reverse(src[i]);
  4569. if (a >= 254) {
  4570. return i;
  4571. }
  4572. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4573. if (b >= 254) {
  4574. return i + 1;
  4575. }
  4576. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4577. if (c == 254) {
  4578. return i + 2;
  4579. }
  4580. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4581. if (d == 254) {
  4582. return i + 3;
  4583. }
  4584. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4585. if (c != 255) {
  4586. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4587. if (d != 255) {
  4588. dst[(*dst_len)++] = (c << 6) + d;
  4589. }
  4590. }
  4591. }
  4592. return -1;
  4593. }
  4594. #endif
  4595. static int
  4596. is_put_or_delete_method(const struct mg_connection *conn)
  4597. {
  4598. if (conn) {
  4599. const char *s = conn->request_info.request_method;
  4600. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4601. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4602. }
  4603. return 0;
  4604. }
  4605. static void
  4606. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4607. char *filename, /* out: filename */
  4608. size_t filename_buf_len, /* in: size of filename buffer */
  4609. struct mg_file_stat *filestat, /* out: file structure */
  4610. int *is_found, /* out: file found (directly) */
  4611. int *is_script_resource, /* out: handled by a script? */
  4612. int *is_websocket_request, /* out: websocket connetion? */
  4613. int *is_put_or_delete_request /* out: put/delete a file? */
  4614. )
  4615. {
  4616. /* TODO (high): Restructure this function */
  4617. #if !defined(NO_FILES)
  4618. const char *uri = conn->request_info.local_uri;
  4619. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4620. const char *rewrite;
  4621. struct vec a, b;
  4622. int match_len;
  4623. char gz_path[PATH_MAX];
  4624. char const *accept_encoding;
  4625. int truncated;
  4626. #if !defined(NO_CGI) || defined(USE_LUA)
  4627. char *p;
  4628. #endif
  4629. #else
  4630. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4631. #endif
  4632. memset(filestat, 0, sizeof(*filestat));
  4633. *filename = 0;
  4634. *is_found = 0;
  4635. *is_script_resource = 0;
  4636. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4637. #if defined(USE_WEBSOCKET)
  4638. *is_websocket_request = is_websocket_protocol(conn);
  4639. #if !defined(NO_FILES)
  4640. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4641. root = conn->ctx->config[WEBSOCKET_ROOT];
  4642. }
  4643. #endif /* !NO_FILES */
  4644. #else /* USE_WEBSOCKET */
  4645. *is_websocket_request = 0;
  4646. #endif /* USE_WEBSOCKET */
  4647. #if !defined(NO_FILES)
  4648. /* Note that root == NULL is a regular use case here. This occurs,
  4649. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4650. * config is not required. */
  4651. if (root == NULL) {
  4652. /* all file related outputs have already been set to 0, just return
  4653. */
  4654. return;
  4655. }
  4656. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4657. * of the path one byte on the right.
  4658. * If document_root is NULL, leave the file empty. */
  4659. mg_snprintf(
  4660. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4661. if (truncated) {
  4662. goto interpret_cleanup;
  4663. }
  4664. rewrite = conn->ctx->config[REWRITE];
  4665. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4666. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4667. mg_snprintf(conn,
  4668. &truncated,
  4669. filename,
  4670. filename_buf_len - 1,
  4671. "%.*s%s",
  4672. (int)b.len,
  4673. b.ptr,
  4674. uri + match_len);
  4675. break;
  4676. }
  4677. }
  4678. if (truncated) {
  4679. goto interpret_cleanup;
  4680. }
  4681. /* Local file path and name, corresponding to requested URI
  4682. * is now stored in "filename" variable. */
  4683. if (mg_stat(conn, filename, filestat)) {
  4684. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4685. /* File exists. Check if it is a script type. */
  4686. if (0
  4687. #if !defined(NO_CGI)
  4688. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4689. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4690. filename) > 0
  4691. #endif
  4692. #if defined(USE_LUA)
  4693. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4694. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4695. filename) > 0
  4696. #endif
  4697. #if defined(USE_DUKTAPE)
  4698. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4699. strlen(
  4700. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4701. filename) > 0
  4702. #endif
  4703. ) {
  4704. /* The request addresses a CGI script or a Lua script. The URI
  4705. * corresponds to the script itself (like /path/script.cgi),
  4706. * and there is no additional resource path
  4707. * (like /path/script.cgi/something).
  4708. * Requests that modify (replace or delete) a resource, like
  4709. * PUT and DELETE requests, should replace/delete the script
  4710. * file.
  4711. * Requests that read or write from/to a resource, like GET and
  4712. * POST requests, should call the script and return the
  4713. * generated response. */
  4714. *is_script_resource = !*is_put_or_delete_request;
  4715. }
  4716. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4717. *is_found = 1;
  4718. return;
  4719. }
  4720. /* If we can't find the actual file, look for the file
  4721. * with the same name but a .gz extension. If we find it,
  4722. * use that and set the gzipped flag in the file struct
  4723. * to indicate that the response need to have the content-
  4724. * encoding: gzip header.
  4725. * We can only do this if the browser declares support. */
  4726. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4727. if (strstr(accept_encoding, "gzip") != NULL) {
  4728. mg_snprintf(
  4729. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4730. if (truncated) {
  4731. goto interpret_cleanup;
  4732. }
  4733. if (mg_stat(conn, gz_path, filestat)) {
  4734. if (filestat) {
  4735. filestat->is_gzipped = 1;
  4736. *is_found = 1;
  4737. }
  4738. /* Currently gz files can not be scripts. */
  4739. return;
  4740. }
  4741. }
  4742. }
  4743. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4744. /* Support PATH_INFO for CGI scripts. */
  4745. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4746. if (*p == '/') {
  4747. *p = '\0';
  4748. if ((0
  4749. #if !defined(NO_CGI)
  4750. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4751. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4752. filename) > 0
  4753. #endif
  4754. #if defined(USE_LUA)
  4755. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4756. strlen(
  4757. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4758. filename) > 0
  4759. #endif
  4760. #if defined(USE_DUKTAPE)
  4761. || match_prefix(
  4762. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4763. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4764. filename) > 0
  4765. #endif
  4766. ) && mg_stat(conn, filename, filestat)) {
  4767. /* Shift PATH_INFO block one character right, e.g.
  4768. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4769. * conn->path_info is pointing to the local variable "path"
  4770. * declared in handle_request(), so PATH_INFO is not valid
  4771. * after handle_request returns. */
  4772. conn->path_info = p + 1;
  4773. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4774. * trailing \0 */
  4775. p[1] = '/';
  4776. *is_script_resource = 1;
  4777. break;
  4778. } else {
  4779. *p = '/';
  4780. }
  4781. }
  4782. }
  4783. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4784. #endif /* !defined(NO_FILES) */
  4785. return;
  4786. #if !defined(NO_FILES)
  4787. /* Reset all outputs */
  4788. interpret_cleanup:
  4789. memset(filestat, 0, sizeof(*filestat));
  4790. *filename = 0;
  4791. *is_found = 0;
  4792. *is_script_resource = 0;
  4793. *is_websocket_request = 0;
  4794. *is_put_or_delete_request = 0;
  4795. #endif /* !defined(NO_FILES) */
  4796. }
  4797. /* Check whether full request is buffered. Return:
  4798. * -1 if request is malformed
  4799. * 0 if request is not yet fully buffered
  4800. * >0 actual request length, including last \r\n\r\n */
  4801. static int
  4802. get_request_len(const char *buf, int buflen)
  4803. {
  4804. const char *s, *e;
  4805. int len = 0;
  4806. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4807. /* Control characters are not allowed but >=128 is. */
  4808. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4809. && *(const unsigned char *)s < 128) {
  4810. len = -1;
  4811. break; /* [i_a] abort scan as soon as one malformed character is
  4812. * found; */
  4813. /* don't let subsequent \r\n\r\n win us over anyhow */
  4814. } else if (s[0] == '\n' && s[1] == '\n') {
  4815. len = (int)(s - buf) + 2;
  4816. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4817. len = (int)(s - buf) + 3;
  4818. }
  4819. return len;
  4820. }
  4821. #if !defined(NO_CACHING)
  4822. /* Convert month to the month number. Return -1 on error, or month number */
  4823. static int
  4824. get_month_index(const char *s)
  4825. {
  4826. size_t i;
  4827. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4828. if (!strcmp(s, month_names[i])) {
  4829. return (int)i;
  4830. }
  4831. }
  4832. return -1;
  4833. }
  4834. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4835. static time_t
  4836. parse_date_string(const char *datetime)
  4837. {
  4838. char month_str[32] = {0};
  4839. int second, minute, hour, day, month, year;
  4840. time_t result = (time_t)0;
  4841. struct tm tm;
  4842. if ((sscanf(datetime,
  4843. "%d/%3s/%d %d:%d:%d",
  4844. &day,
  4845. month_str,
  4846. &year,
  4847. &hour,
  4848. &minute,
  4849. &second) == 6) || (sscanf(datetime,
  4850. "%d %3s %d %d:%d:%d",
  4851. &day,
  4852. month_str,
  4853. &year,
  4854. &hour,
  4855. &minute,
  4856. &second) == 6)
  4857. || (sscanf(datetime,
  4858. "%*3s, %d %3s %d %d:%d:%d",
  4859. &day,
  4860. month_str,
  4861. &year,
  4862. &hour,
  4863. &minute,
  4864. &second) == 6) || (sscanf(datetime,
  4865. "%d-%3s-%d %d:%d:%d",
  4866. &day,
  4867. month_str,
  4868. &year,
  4869. &hour,
  4870. &minute,
  4871. &second) == 6)) {
  4872. month = get_month_index(month_str);
  4873. if ((month >= 0) && (year >= 1970)) {
  4874. memset(&tm, 0, sizeof(tm));
  4875. tm.tm_year = year - 1900;
  4876. tm.tm_mon = month;
  4877. tm.tm_mday = day;
  4878. tm.tm_hour = hour;
  4879. tm.tm_min = minute;
  4880. tm.tm_sec = second;
  4881. result = timegm(&tm);
  4882. }
  4883. }
  4884. return result;
  4885. }
  4886. #endif /* !NO_CACHING */
  4887. /* Protect against directory disclosure attack by removing '..',
  4888. * excessive '/' and '\' characters */
  4889. static void
  4890. remove_double_dots_and_double_slashes(char *s)
  4891. {
  4892. char *p = s;
  4893. while ((s[0] == '.') && (s[1] == '.')) {
  4894. s++;
  4895. }
  4896. while (*s != '\0') {
  4897. *p++ = *s++;
  4898. if (s[-1] == '/' || s[-1] == '\\') {
  4899. /* Skip all following slashes, backslashes and double-dots */
  4900. while (s[0] != '\0') {
  4901. if (s[0] == '/' || s[0] == '\\') {
  4902. s++;
  4903. } else if (s[0] == '.' && s[1] == '.') {
  4904. s += 2;
  4905. } else {
  4906. break;
  4907. }
  4908. }
  4909. }
  4910. }
  4911. *p = '\0';
  4912. }
  4913. static const struct {
  4914. const char *extension;
  4915. size_t ext_len;
  4916. const char *mime_type;
  4917. } builtin_mime_types[] = {
  4918. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4919. * application types */
  4920. {".doc", 4, "application/msword"},
  4921. {".eps", 4, "application/postscript"},
  4922. {".exe", 4, "application/octet-stream"},
  4923. {".js", 3, "application/javascript"},
  4924. {".json", 5, "application/json"},
  4925. {".pdf", 4, "application/pdf"},
  4926. {".ps", 3, "application/postscript"},
  4927. {".rtf", 4, "application/rtf"},
  4928. {".xhtml", 6, "application/xhtml+xml"},
  4929. {".xsl", 4, "application/xml"},
  4930. {".xslt", 5, "application/xml"},
  4931. /* fonts */
  4932. {".ttf", 4, "application/font-sfnt"},
  4933. {".cff", 4, "application/font-sfnt"},
  4934. {".otf", 4, "application/font-sfnt"},
  4935. {".aat", 4, "application/font-sfnt"},
  4936. {".sil", 4, "application/font-sfnt"},
  4937. {".pfr", 4, "application/font-tdpfr"},
  4938. {".woff", 5, "application/font-woff"},
  4939. /* audio */
  4940. {".mp3", 4, "audio/mpeg"},
  4941. {".oga", 4, "audio/ogg"},
  4942. {".ogg", 4, "audio/ogg"},
  4943. /* image */
  4944. {".gif", 4, "image/gif"},
  4945. {".ief", 4, "image/ief"},
  4946. {".jpeg", 5, "image/jpeg"},
  4947. {".jpg", 4, "image/jpeg"},
  4948. {".jpm", 4, "image/jpm"},
  4949. {".jpx", 4, "image/jpx"},
  4950. {".png", 4, "image/png"},
  4951. {".svg", 4, "image/svg+xml"},
  4952. {".tif", 4, "image/tiff"},
  4953. {".tiff", 5, "image/tiff"},
  4954. /* model */
  4955. {".wrl", 4, "model/vrml"},
  4956. /* text */
  4957. {".css", 4, "text/css"},
  4958. {".csv", 4, "text/csv"},
  4959. {".htm", 4, "text/html"},
  4960. {".html", 5, "text/html"},
  4961. {".sgm", 4, "text/sgml"},
  4962. {".shtm", 5, "text/html"},
  4963. {".shtml", 6, "text/html"},
  4964. {".txt", 4, "text/plain"},
  4965. {".xml", 4, "text/xml"},
  4966. /* video */
  4967. {".mov", 4, "video/quicktime"},
  4968. {".mp4", 4, "video/mp4"},
  4969. {".mpeg", 5, "video/mpeg"},
  4970. {".mpg", 4, "video/mpeg"},
  4971. {".ogv", 4, "video/ogg"},
  4972. {".qt", 3, "video/quicktime"},
  4973. /* not registered types
  4974. * (http://reference.sitepoint.com/html/mime-types-full,
  4975. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4976. {".arj", 4, "application/x-arj-compressed"},
  4977. {".gz", 3, "application/x-gunzip"},
  4978. {".rar", 4, "application/x-arj-compressed"},
  4979. {".swf", 4, "application/x-shockwave-flash"},
  4980. {".tar", 4, "application/x-tar"},
  4981. {".tgz", 4, "application/x-tar-gz"},
  4982. {".torrent", 8, "application/x-bittorrent"},
  4983. {".ppt", 4, "application/x-mspowerpoint"},
  4984. {".xls", 4, "application/x-msexcel"},
  4985. {".zip", 4, "application/x-zip-compressed"},
  4986. {".aac",
  4987. 4,
  4988. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4989. {".aif", 4, "audio/x-aif"},
  4990. {".m3u", 4, "audio/x-mpegurl"},
  4991. {".mid", 4, "audio/x-midi"},
  4992. {".ra", 3, "audio/x-pn-realaudio"},
  4993. {".ram", 4, "audio/x-pn-realaudio"},
  4994. {".wav", 4, "audio/x-wav"},
  4995. {".bmp", 4, "image/bmp"},
  4996. {".ico", 4, "image/x-icon"},
  4997. {".pct", 4, "image/x-pct"},
  4998. {".pict", 5, "image/pict"},
  4999. {".rgb", 4, "image/x-rgb"},
  5000. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5001. {".asf", 4, "video/x-ms-asf"},
  5002. {".avi", 4, "video/x-msvideo"},
  5003. {".m4v", 4, "video/x-m4v"},
  5004. {NULL, 0, NULL}};
  5005. const char *
  5006. mg_get_builtin_mime_type(const char *path)
  5007. {
  5008. const char *ext;
  5009. size_t i, path_len;
  5010. path_len = strlen(path);
  5011. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5012. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5013. if (path_len > builtin_mime_types[i].ext_len
  5014. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5015. return builtin_mime_types[i].mime_type;
  5016. }
  5017. }
  5018. return "text/plain";
  5019. }
  5020. /* Look at the "path" extension and figure what mime type it has.
  5021. * Store mime type in the vector. */
  5022. static void
  5023. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5024. {
  5025. struct vec ext_vec, mime_vec;
  5026. const char *list, *ext;
  5027. size_t path_len;
  5028. path_len = strlen(path);
  5029. if (ctx == NULL || vec == NULL) {
  5030. return;
  5031. }
  5032. /* Scan user-defined mime types first, in case user wants to
  5033. * override default mime types. */
  5034. list = ctx->config[EXTRA_MIME_TYPES];
  5035. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5036. /* ext now points to the path suffix */
  5037. ext = path + path_len - ext_vec.len;
  5038. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5039. *vec = mime_vec;
  5040. return;
  5041. }
  5042. }
  5043. vec->ptr = mg_get_builtin_mime_type(path);
  5044. vec->len = strlen(vec->ptr);
  5045. }
  5046. /* Stringify binary data. Output buffer must be twice as big as input,
  5047. * because each byte takes 2 bytes in string representation */
  5048. static void
  5049. bin2str(char *to, const unsigned char *p, size_t len)
  5050. {
  5051. static const char *hex = "0123456789abcdef";
  5052. for (; len--; p++) {
  5053. *to++ = hex[p[0] >> 4];
  5054. *to++ = hex[p[0] & 0x0f];
  5055. }
  5056. *to = '\0';
  5057. }
  5058. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5059. char *
  5060. mg_md5(char buf[33], ...)
  5061. {
  5062. md5_byte_t hash[16];
  5063. const char *p;
  5064. va_list ap;
  5065. md5_state_t ctx;
  5066. md5_init(&ctx);
  5067. va_start(ap, buf);
  5068. while ((p = va_arg(ap, const char *)) != NULL) {
  5069. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5070. }
  5071. va_end(ap);
  5072. md5_finish(&ctx, hash);
  5073. bin2str(buf, hash, sizeof(hash));
  5074. return buf;
  5075. }
  5076. /* Check the user's password, return 1 if OK */
  5077. static int
  5078. check_password(const char *method,
  5079. const char *ha1,
  5080. const char *uri,
  5081. const char *nonce,
  5082. const char *nc,
  5083. const char *cnonce,
  5084. const char *qop,
  5085. const char *response)
  5086. {
  5087. char ha2[32 + 1], expected_response[32 + 1];
  5088. /* Some of the parameters may be NULL */
  5089. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5090. || qop == NULL
  5091. || response == NULL) {
  5092. return 0;
  5093. }
  5094. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5095. if (strlen(response) != 32) {
  5096. return 0;
  5097. }
  5098. mg_md5(ha2, method, ":", uri, NULL);
  5099. mg_md5(expected_response,
  5100. ha1,
  5101. ":",
  5102. nonce,
  5103. ":",
  5104. nc,
  5105. ":",
  5106. cnonce,
  5107. ":",
  5108. qop,
  5109. ":",
  5110. ha2,
  5111. NULL);
  5112. return mg_strcasecmp(response, expected_response) == 0;
  5113. }
  5114. /* Use the global passwords file, if specified by auth_gpass option,
  5115. * or search for .htpasswd in the requested directory. */
  5116. static void
  5117. open_auth_file(struct mg_connection *conn,
  5118. const char *path,
  5119. struct mg_file *filep)
  5120. {
  5121. if (conn != NULL && conn->ctx != NULL) {
  5122. char name[PATH_MAX];
  5123. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5124. int truncated;
  5125. if (gpass != NULL) {
  5126. /* Use global passwords file */
  5127. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5128. #ifdef DEBUG
  5129. /* Use mg_cry here, since gpass has been configured. */
  5130. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5131. #endif
  5132. }
  5133. /* Important: using local struct mg_file to test path for
  5134. * is_directory
  5135. * flag. If filep is used, mg_stat() makes it appear as if auth file
  5136. * was opened. TODO: mg_stat must not make anything appear to be
  5137. * opened */
  5138. } else if (mg_stat(conn, path, &filep->stat)
  5139. && filep->stat.is_directory) {
  5140. mg_snprintf(conn,
  5141. &truncated,
  5142. name,
  5143. sizeof(name),
  5144. "%s/%s",
  5145. path,
  5146. PASSWORDS_FILE_NAME);
  5147. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5148. #ifdef DEBUG
  5149. /* Don't use mg_cry here, but only a trace, since this is
  5150. * a typical case. It will occur for every directory
  5151. * without a password file. */
  5152. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5153. #endif
  5154. }
  5155. } else {
  5156. /* Try to find .htpasswd in requested directory. */
  5157. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5158. if (e[0] == '/') {
  5159. break;
  5160. }
  5161. }
  5162. mg_snprintf(conn,
  5163. &truncated,
  5164. name,
  5165. sizeof(name),
  5166. "%.*s/%s",
  5167. (int)(e - p),
  5168. p,
  5169. PASSWORDS_FILE_NAME);
  5170. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5171. #ifdef DEBUG
  5172. /* Don't use mg_cry here, but only a trace, since this is
  5173. * a typical case. It will occur for every directory
  5174. * without a password file. */
  5175. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5176. #endif
  5177. }
  5178. }
  5179. }
  5180. }
  5181. /* Parsed Authorization header */
  5182. struct ah {
  5183. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5184. };
  5185. /* Return 1 on success. Always initializes the ah structure. */
  5186. static int
  5187. parse_auth_header(struct mg_connection *conn,
  5188. char *buf,
  5189. size_t buf_size,
  5190. struct ah *ah)
  5191. {
  5192. char *name, *value, *s;
  5193. const char *auth_header;
  5194. uint64_t nonce;
  5195. if (!ah || !conn) {
  5196. return 0;
  5197. }
  5198. (void)memset(ah, 0, sizeof(*ah));
  5199. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5200. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5201. return 0;
  5202. }
  5203. /* Make modifiable copy of the auth header */
  5204. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5205. s = buf;
  5206. /* Parse authorization header */
  5207. for (;;) {
  5208. /* Gobble initial spaces */
  5209. while (isspace(*(unsigned char *)s)) {
  5210. s++;
  5211. }
  5212. name = skip_quoted(&s, "=", " ", 0);
  5213. /* Value is either quote-delimited, or ends at first comma or space. */
  5214. if (s[0] == '\"') {
  5215. s++;
  5216. value = skip_quoted(&s, "\"", " ", '\\');
  5217. if (s[0] == ',') {
  5218. s++;
  5219. }
  5220. } else {
  5221. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5222. * spaces */
  5223. }
  5224. if (*name == '\0') {
  5225. break;
  5226. }
  5227. if (!strcmp(name, "username")) {
  5228. ah->user = value;
  5229. } else if (!strcmp(name, "cnonce")) {
  5230. ah->cnonce = value;
  5231. } else if (!strcmp(name, "response")) {
  5232. ah->response = value;
  5233. } else if (!strcmp(name, "uri")) {
  5234. ah->uri = value;
  5235. } else if (!strcmp(name, "qop")) {
  5236. ah->qop = value;
  5237. } else if (!strcmp(name, "nc")) {
  5238. ah->nc = value;
  5239. } else if (!strcmp(name, "nonce")) {
  5240. ah->nonce = value;
  5241. }
  5242. }
  5243. #ifndef NO_NONCE_CHECK
  5244. /* Read the nonce from the response. */
  5245. if (ah->nonce == NULL) {
  5246. return 0;
  5247. }
  5248. s = NULL;
  5249. nonce = strtoull(ah->nonce, &s, 10);
  5250. if ((s == NULL) || (*s != 0)) {
  5251. return 0;
  5252. }
  5253. /* Convert the nonce from the client to a number. */
  5254. nonce ^= conn->ctx->auth_nonce_mask;
  5255. /* The converted number corresponds to the time the nounce has been
  5256. * created. This should not be earlier than the server start. */
  5257. /* Server side nonce check is valuable in all situations but one:
  5258. * if the server restarts frequently, but the client should not see
  5259. * that, so the server should accept nonces from previous starts. */
  5260. /* However, the reasonable default is to not accept a nonce from a
  5261. * previous start, so if anyone changed the access rights between
  5262. * two restarts, a new login is required. */
  5263. if (nonce < (uint64_t)conn->ctx->start_time) {
  5264. /* nonce is from a previous start of the server and no longer valid
  5265. * (replay attack?) */
  5266. return 0;
  5267. }
  5268. /* Check if the nonce is too high, so it has not (yet) been used by the
  5269. * server. */
  5270. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5271. return 0;
  5272. }
  5273. #else
  5274. (void)nonce;
  5275. #endif
  5276. /* CGI needs it as REMOTE_USER */
  5277. if (ah->user != NULL) {
  5278. conn->request_info.remote_user = mg_strdup(ah->user);
  5279. } else {
  5280. return 0;
  5281. }
  5282. return 1;
  5283. }
  5284. static const char *
  5285. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5286. {
  5287. const char *eof;
  5288. size_t len;
  5289. const char *memend;
  5290. if (!filep) {
  5291. return NULL;
  5292. }
  5293. if (filep->access.membuf != NULL && *p != NULL) {
  5294. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5295. /* Search for \n from p till the end of stream */
  5296. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5297. if (eof != NULL) {
  5298. eof += 1; /* Include \n */
  5299. } else {
  5300. eof = memend; /* Copy remaining data */
  5301. }
  5302. len =
  5303. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5304. memcpy(buf, *p, len);
  5305. buf[len] = '\0';
  5306. *p += len;
  5307. return len ? eof : NULL;
  5308. } else if (filep->access.fp != NULL) {
  5309. return fgets(buf, (int)size, filep->access.fp);
  5310. } else {
  5311. return NULL;
  5312. }
  5313. }
  5314. /* Define the initial recursion depth for procesesing htpasswd files that
  5315. * include other htpasswd
  5316. * (or even the same) files. It is not difficult to provide a file or files
  5317. * s.t. they force civetweb
  5318. * to infinitely recurse and then crash.
  5319. */
  5320. #define INITIAL_DEPTH 9
  5321. #if INITIAL_DEPTH <= 0
  5322. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5323. #endif
  5324. struct read_auth_file_struct {
  5325. struct mg_connection *conn;
  5326. struct ah ah;
  5327. char *domain;
  5328. char buf[256 + 256 + 40];
  5329. char *f_user;
  5330. char *f_domain;
  5331. char *f_ha1;
  5332. };
  5333. static int
  5334. read_auth_file(struct mg_file *filep,
  5335. struct read_auth_file_struct *workdata,
  5336. int depth)
  5337. {
  5338. char *p;
  5339. int is_authorized = 0;
  5340. struct mg_file fp;
  5341. size_t l;
  5342. if (!filep || !workdata || 0 == depth) {
  5343. return 0;
  5344. }
  5345. /* Loop over passwords file */
  5346. p = (char *)filep->access.membuf;
  5347. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5348. l = strlen(workdata->buf);
  5349. while (l > 0) {
  5350. if (isspace(workdata->buf[l - 1])
  5351. || iscntrl(workdata->buf[l - 1])) {
  5352. l--;
  5353. workdata->buf[l] = 0;
  5354. } else
  5355. break;
  5356. }
  5357. if (l < 1) {
  5358. continue;
  5359. }
  5360. workdata->f_user = workdata->buf;
  5361. if (workdata->f_user[0] == ':') {
  5362. /* user names may not contain a ':' and may not be empty,
  5363. * so lines starting with ':' may be used for a special purpose */
  5364. if (workdata->f_user[1] == '#') {
  5365. /* :# is a comment */
  5366. continue;
  5367. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5368. if (mg_fopen(workdata->conn,
  5369. workdata->f_user + 9,
  5370. MG_FOPEN_MODE_READ,
  5371. &fp)) {
  5372. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5373. (void)mg_fclose(
  5374. &fp.access); /* ignore error on read only file */
  5375. /* No need to continue processing files once we have a
  5376. * match, since nothing will reset it back
  5377. * to 0.
  5378. */
  5379. if (is_authorized) {
  5380. return is_authorized;
  5381. }
  5382. } else {
  5383. mg_cry(workdata->conn,
  5384. "%s: cannot open authorization file: %s",
  5385. __func__,
  5386. workdata->buf);
  5387. }
  5388. continue;
  5389. }
  5390. /* everything is invalid for the moment (might change in the
  5391. * future) */
  5392. mg_cry(workdata->conn,
  5393. "%s: syntax error in authorization file: %s",
  5394. __func__,
  5395. workdata->buf);
  5396. continue;
  5397. }
  5398. workdata->f_domain = strchr(workdata->f_user, ':');
  5399. if (workdata->f_domain == NULL) {
  5400. mg_cry(workdata->conn,
  5401. "%s: syntax error in authorization file: %s",
  5402. __func__,
  5403. workdata->buf);
  5404. continue;
  5405. }
  5406. *(workdata->f_domain) = 0;
  5407. (workdata->f_domain)++;
  5408. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5409. if (workdata->f_ha1 == NULL) {
  5410. mg_cry(workdata->conn,
  5411. "%s: syntax error in authorization file: %s",
  5412. __func__,
  5413. workdata->buf);
  5414. continue;
  5415. }
  5416. *(workdata->f_ha1) = 0;
  5417. (workdata->f_ha1)++;
  5418. if (!strcmp(workdata->ah.user, workdata->f_user)
  5419. && !strcmp(workdata->domain, workdata->f_domain)) {
  5420. return check_password(workdata->conn->request_info.request_method,
  5421. workdata->f_ha1,
  5422. workdata->ah.uri,
  5423. workdata->ah.nonce,
  5424. workdata->ah.nc,
  5425. workdata->ah.cnonce,
  5426. workdata->ah.qop,
  5427. workdata->ah.response);
  5428. }
  5429. }
  5430. return is_authorized;
  5431. }
  5432. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5433. static int
  5434. authorize(struct mg_connection *conn, struct mg_file *filep)
  5435. {
  5436. struct read_auth_file_struct workdata;
  5437. char buf[MG_BUF_LEN];
  5438. if (!conn || !conn->ctx) {
  5439. return 0;
  5440. }
  5441. memset(&workdata, 0, sizeof(workdata));
  5442. workdata.conn = conn;
  5443. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5444. return 0;
  5445. }
  5446. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5447. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5448. }
  5449. /* Return 1 if request is authorised, 0 otherwise. */
  5450. static int
  5451. check_authorization(struct mg_connection *conn, const char *path)
  5452. {
  5453. char fname[PATH_MAX];
  5454. struct vec uri_vec, filename_vec;
  5455. const char *list;
  5456. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5457. int authorized = 1, truncated;
  5458. if (!conn || !conn->ctx) {
  5459. return 0;
  5460. }
  5461. list = conn->ctx->config[PROTECT_URI];
  5462. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5463. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5464. mg_snprintf(conn,
  5465. &truncated,
  5466. fname,
  5467. sizeof(fname),
  5468. "%.*s",
  5469. (int)filename_vec.len,
  5470. filename_vec.ptr);
  5471. if (truncated
  5472. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5473. mg_cry(conn,
  5474. "%s: cannot open %s: %s",
  5475. __func__,
  5476. fname,
  5477. strerror(errno));
  5478. }
  5479. break;
  5480. }
  5481. }
  5482. if (!is_file_opened(&file.access)) {
  5483. open_auth_file(conn, path, &file);
  5484. }
  5485. if (is_file_opened(&file.access)) {
  5486. authorized = authorize(conn, &file);
  5487. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5488. }
  5489. return authorized;
  5490. }
  5491. static void
  5492. send_authorization_request(struct mg_connection *conn)
  5493. {
  5494. char date[64];
  5495. time_t curtime = time(NULL);
  5496. if (conn && conn->ctx) {
  5497. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5498. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5499. nonce += conn->ctx->nonce_count;
  5500. ++conn->ctx->nonce_count;
  5501. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5502. nonce ^= conn->ctx->auth_nonce_mask;
  5503. conn->status_code = 401;
  5504. conn->must_close = 1;
  5505. gmt_time_string(date, sizeof(date), &curtime);
  5506. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5507. send_no_cache_header(conn);
  5508. mg_printf(conn,
  5509. "Date: %s\r\n"
  5510. "Connection: %s\r\n"
  5511. "Content-Length: 0\r\n"
  5512. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5513. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5514. date,
  5515. suggest_connection_header(conn),
  5516. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5517. nonce);
  5518. }
  5519. }
  5520. #if !defined(NO_FILES)
  5521. static int
  5522. is_authorized_for_put(struct mg_connection *conn)
  5523. {
  5524. if (conn) {
  5525. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5526. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5527. int ret = 0;
  5528. if (passfile != NULL
  5529. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5530. ret = authorize(conn, &file);
  5531. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5532. }
  5533. return ret;
  5534. }
  5535. return 0;
  5536. }
  5537. #endif
  5538. int
  5539. mg_modify_passwords_file(const char *fname,
  5540. const char *domain,
  5541. const char *user,
  5542. const char *pass)
  5543. {
  5544. int found, i;
  5545. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5546. FILE *fp, *fp2;
  5547. found = 0;
  5548. fp = fp2 = NULL;
  5549. /* Regard empty password as no password - remove user record. */
  5550. if (pass != NULL && pass[0] == '\0') {
  5551. pass = NULL;
  5552. }
  5553. /* Other arguments must not be empty */
  5554. if (fname == NULL || domain == NULL || user == NULL) {
  5555. return 0;
  5556. }
  5557. /* Using the given file format, user name and domain must not contain ':'
  5558. */
  5559. if (strchr(user, ':') != NULL) {
  5560. return 0;
  5561. }
  5562. if (strchr(domain, ':') != NULL) {
  5563. return 0;
  5564. }
  5565. /* Do not allow control characters like newline in user name and domain.
  5566. * Do not allow excessively long names either. */
  5567. for (i = 0; i < 255 && user[i] != 0; i++) {
  5568. if (iscntrl(user[i])) {
  5569. return 0;
  5570. }
  5571. }
  5572. if (user[i]) {
  5573. return 0;
  5574. }
  5575. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5576. if (iscntrl(domain[i])) {
  5577. return 0;
  5578. }
  5579. }
  5580. if (domain[i]) {
  5581. return 0;
  5582. }
  5583. /* The maximum length of the path to the password file is limited */
  5584. if ((strlen(fname) + 4) >= PATH_MAX) {
  5585. return 0;
  5586. }
  5587. /* Create a temporary file name. Length has been checked before. */
  5588. strcpy(tmp, fname);
  5589. strcat(tmp, ".tmp");
  5590. /* Create the file if does not exist */
  5591. /* Use of fopen here is OK, since fname is only ASCII */
  5592. if ((fp = fopen(fname, "a+")) != NULL) {
  5593. (void)fclose(fp);
  5594. }
  5595. /* Open the given file and temporary file */
  5596. if ((fp = fopen(fname, "r")) == NULL) {
  5597. return 0;
  5598. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5599. fclose(fp);
  5600. return 0;
  5601. }
  5602. /* Copy the stuff to temporary file */
  5603. while (fgets(line, sizeof(line), fp) != NULL) {
  5604. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5605. continue;
  5606. }
  5607. u[255] = 0;
  5608. d[255] = 0;
  5609. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5610. found++;
  5611. if (pass != NULL) {
  5612. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5613. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5614. }
  5615. } else {
  5616. fprintf(fp2, "%s", line);
  5617. }
  5618. }
  5619. /* If new user, just add it */
  5620. if (!found && pass != NULL) {
  5621. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5622. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5623. }
  5624. /* Close files */
  5625. fclose(fp);
  5626. fclose(fp2);
  5627. /* Put the temp file in place of real file */
  5628. IGNORE_UNUSED_RESULT(remove(fname));
  5629. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5630. return 1;
  5631. }
  5632. static int
  5633. is_valid_port(unsigned long port)
  5634. {
  5635. return port < 0xffff;
  5636. }
  5637. static int
  5638. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5639. {
  5640. struct addrinfo hints, *res, *ressave;
  5641. int func_ret = 0;
  5642. int gai_ret;
  5643. memset(&hints, 0, sizeof(struct addrinfo));
  5644. hints.ai_family = af;
  5645. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5646. if (gai_ret != 0) {
  5647. /* gai_strerror could be used to convert gai_ret to a string */
  5648. /* POSIX return values: see
  5649. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5650. */
  5651. /* Windows return values: see
  5652. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5653. */
  5654. return 0;
  5655. }
  5656. ressave = res;
  5657. while (res) {
  5658. if (dstlen >= res->ai_addrlen) {
  5659. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5660. func_ret = 1;
  5661. }
  5662. res = res->ai_next;
  5663. }
  5664. freeaddrinfo(ressave);
  5665. return func_ret;
  5666. }
  5667. static int
  5668. connect_socket(struct mg_context *ctx /* may be NULL */,
  5669. const char *host,
  5670. int port,
  5671. int use_ssl,
  5672. char *ebuf,
  5673. size_t ebuf_len,
  5674. SOCKET *sock /* output: socket, must not be NULL */,
  5675. union usa *sa /* output: socket address, must not be NULL */
  5676. )
  5677. {
  5678. int ip_ver = 0;
  5679. *sock = INVALID_SOCKET;
  5680. memset(sa, 0, sizeof(*sa));
  5681. if (ebuf_len > 0) {
  5682. *ebuf = 0;
  5683. }
  5684. if (host == NULL) {
  5685. mg_snprintf(NULL,
  5686. NULL, /* No truncation check for ebuf */
  5687. ebuf,
  5688. ebuf_len,
  5689. "%s",
  5690. "NULL host");
  5691. return 0;
  5692. }
  5693. if (port < 0 || !is_valid_port((unsigned)port)) {
  5694. mg_snprintf(NULL,
  5695. NULL, /* No truncation check for ebuf */
  5696. ebuf,
  5697. ebuf_len,
  5698. "%s",
  5699. "invalid port");
  5700. return 0;
  5701. }
  5702. #if !defined(NO_SSL)
  5703. if (use_ssl && (SSLv23_client_method == NULL)) {
  5704. mg_snprintf(NULL,
  5705. NULL, /* No truncation check for ebuf */
  5706. ebuf,
  5707. ebuf_len,
  5708. "%s",
  5709. "SSL is not initialized");
  5710. return 0;
  5711. }
  5712. #else
  5713. (void)use_ssl;
  5714. #endif
  5715. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5716. sa->sin.sin_port = htons((uint16_t)port);
  5717. ip_ver = 4;
  5718. #ifdef USE_IPV6
  5719. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5720. sa->sin6.sin6_port = htons((uint16_t)port);
  5721. ip_ver = 6;
  5722. } else if (host[0] == '[') {
  5723. /* While getaddrinfo on Windows will work with [::1],
  5724. * getaddrinfo on Linux only works with ::1 (without []). */
  5725. size_t l = strlen(host + 1);
  5726. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5727. if (h) {
  5728. h[l - 1] = 0;
  5729. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5730. sa->sin6.sin6_port = htons((uint16_t)port);
  5731. ip_ver = 6;
  5732. }
  5733. mg_free(h);
  5734. }
  5735. #endif
  5736. }
  5737. if (ip_ver == 0) {
  5738. mg_snprintf(NULL,
  5739. NULL, /* No truncation check for ebuf */
  5740. ebuf,
  5741. ebuf_len,
  5742. "%s",
  5743. "host not found");
  5744. return 0;
  5745. }
  5746. if (ip_ver == 4) {
  5747. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5748. }
  5749. #ifdef USE_IPV6
  5750. else if (ip_ver == 6) {
  5751. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5752. }
  5753. #endif
  5754. if (*sock == INVALID_SOCKET) {
  5755. mg_snprintf(NULL,
  5756. NULL, /* No truncation check for ebuf */
  5757. ebuf,
  5758. ebuf_len,
  5759. "socket(): %s",
  5760. strerror(ERRNO));
  5761. return 0;
  5762. }
  5763. set_close_on_exec(*sock, fc(ctx));
  5764. if ((ip_ver == 4)
  5765. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5766. == 0)) {
  5767. /* connected with IPv4 */
  5768. set_blocking_mode(*sock, 0);
  5769. return 1;
  5770. }
  5771. #ifdef USE_IPV6
  5772. if ((ip_ver == 6)
  5773. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5774. == 0)) {
  5775. /* connected with IPv6 */
  5776. set_blocking_mode(*sock, 0);
  5777. return 1;
  5778. }
  5779. #endif
  5780. /* Not connected */
  5781. mg_snprintf(NULL,
  5782. NULL, /* No truncation check for ebuf */
  5783. ebuf,
  5784. ebuf_len,
  5785. "connect(%s:%d): %s",
  5786. host,
  5787. port,
  5788. strerror(ERRNO));
  5789. closesocket(*sock);
  5790. *sock = INVALID_SOCKET;
  5791. return 0;
  5792. }
  5793. int
  5794. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5795. {
  5796. static const char *dont_escape = "._-$,;~()";
  5797. static const char *hex = "0123456789abcdef";
  5798. char *pos = dst;
  5799. const char *end = dst + dst_len - 1;
  5800. for (; *src != '\0' && pos < end; src++, pos++) {
  5801. if (isalnum(*(const unsigned char *)src)
  5802. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5803. *pos = *src;
  5804. } else if (pos + 2 < end) {
  5805. pos[0] = '%';
  5806. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5807. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5808. pos += 2;
  5809. } else {
  5810. break;
  5811. }
  5812. }
  5813. *pos = '\0';
  5814. return (*src == '\0') ? (int)(pos - dst) : -1;
  5815. }
  5816. static void
  5817. print_dir_entry(struct de *de)
  5818. {
  5819. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5820. struct tm *tm;
  5821. if (de->file.is_directory) {
  5822. mg_snprintf(de->conn,
  5823. NULL, /* Buffer is big enough */
  5824. size,
  5825. sizeof(size),
  5826. "%s",
  5827. "[DIRECTORY]");
  5828. } else {
  5829. /* We use (signed) cast below because MSVC 6 compiler cannot
  5830. * convert unsigned __int64 to double. Sigh. */
  5831. if (de->file.size < 1024) {
  5832. mg_snprintf(de->conn,
  5833. NULL, /* Buffer is big enough */
  5834. size,
  5835. sizeof(size),
  5836. "%d",
  5837. (int)de->file.size);
  5838. } else if (de->file.size < 0x100000) {
  5839. mg_snprintf(de->conn,
  5840. NULL, /* Buffer is big enough */
  5841. size,
  5842. sizeof(size),
  5843. "%.1fk",
  5844. (double)de->file.size / 1024.0);
  5845. } else if (de->file.size < 0x40000000) {
  5846. mg_snprintf(de->conn,
  5847. NULL, /* Buffer is big enough */
  5848. size,
  5849. sizeof(size),
  5850. "%.1fM",
  5851. (double)de->file.size / 1048576);
  5852. } else {
  5853. mg_snprintf(de->conn,
  5854. NULL, /* Buffer is big enough */
  5855. size,
  5856. sizeof(size),
  5857. "%.1fG",
  5858. (double)de->file.size / 1073741824);
  5859. }
  5860. }
  5861. /* Note: mg_snprintf will not cause a buffer overflow above.
  5862. * So, string truncation checks are not required here. */
  5863. tm = localtime(&de->file.last_modified);
  5864. if (tm != NULL) {
  5865. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5866. } else {
  5867. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5868. mod[sizeof(mod) - 1] = '\0';
  5869. }
  5870. mg_url_encode(de->file_name, href, sizeof(href));
  5871. de->conn->num_bytes_sent +=
  5872. mg_printf(de->conn,
  5873. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5874. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5875. de->conn->request_info.local_uri,
  5876. href,
  5877. de->file.is_directory ? "/" : "",
  5878. de->file_name,
  5879. de->file.is_directory ? "/" : "",
  5880. mod,
  5881. size);
  5882. }
  5883. /* This function is called from send_directory() and used for
  5884. * sorting directory entries by size, or name, or modification time.
  5885. * On windows, __cdecl specification is needed in case if project is built
  5886. * with __stdcall convention. qsort always requires __cdels callback. */
  5887. static int WINCDECL
  5888. compare_dir_entries(const void *p1, const void *p2)
  5889. {
  5890. if (p1 && p2) {
  5891. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5892. const char *query_string = a->conn->request_info.query_string;
  5893. int cmp_result = 0;
  5894. if (query_string == NULL) {
  5895. query_string = "na";
  5896. }
  5897. if (a->file.is_directory && !b->file.is_directory) {
  5898. return -1; /* Always put directories on top */
  5899. } else if (!a->file.is_directory && b->file.is_directory) {
  5900. return 1; /* Always put directories on top */
  5901. } else if (*query_string == 'n') {
  5902. cmp_result = strcmp(a->file_name, b->file_name);
  5903. } else if (*query_string == 's') {
  5904. cmp_result = (a->file.size == b->file.size)
  5905. ? 0
  5906. : ((a->file.size > b->file.size) ? 1 : -1);
  5907. } else if (*query_string == 'd') {
  5908. cmp_result =
  5909. (a->file.last_modified == b->file.last_modified)
  5910. ? 0
  5911. : ((a->file.last_modified > b->file.last_modified) ? 1
  5912. : -1);
  5913. }
  5914. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5915. }
  5916. return 0;
  5917. }
  5918. static int
  5919. must_hide_file(struct mg_connection *conn, const char *path)
  5920. {
  5921. if (conn && conn->ctx) {
  5922. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5923. const char *pattern = conn->ctx->config[HIDE_FILES];
  5924. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5925. || (pattern != NULL
  5926. && match_prefix(pattern, strlen(pattern), path) > 0);
  5927. }
  5928. return 0;
  5929. }
  5930. static int
  5931. scan_directory(struct mg_connection *conn,
  5932. const char *dir,
  5933. void *data,
  5934. void (*cb)(struct de *, void *))
  5935. {
  5936. char path[PATH_MAX];
  5937. struct dirent *dp;
  5938. DIR *dirp;
  5939. struct de de;
  5940. int truncated;
  5941. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5942. return 0;
  5943. } else {
  5944. de.conn = conn;
  5945. while ((dp = mg_readdir(dirp)) != NULL) {
  5946. /* Do not show current dir and hidden files */
  5947. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5948. || must_hide_file(conn, dp->d_name)) {
  5949. continue;
  5950. }
  5951. mg_snprintf(
  5952. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5953. /* If we don't memset stat structure to zero, mtime will have
  5954. * garbage and strftime() will segfault later on in
  5955. * print_dir_entry(). memset is required only if mg_stat()
  5956. * fails. For more details, see
  5957. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5958. memset(&de.file, 0, sizeof(de.file));
  5959. if (truncated) {
  5960. /* If the path is not complete, skip processing. */
  5961. continue;
  5962. }
  5963. if (!mg_stat(conn, path, &de.file)) {
  5964. mg_cry(conn,
  5965. "%s: mg_stat(%s) failed: %s",
  5966. __func__,
  5967. path,
  5968. strerror(ERRNO));
  5969. }
  5970. de.file_name = dp->d_name;
  5971. cb(&de, data);
  5972. }
  5973. (void)mg_closedir(dirp);
  5974. }
  5975. return 1;
  5976. }
  5977. #if !defined(NO_FILES)
  5978. static int
  5979. remove_directory(struct mg_connection *conn, const char *dir)
  5980. {
  5981. char path[PATH_MAX];
  5982. struct dirent *dp;
  5983. DIR *dirp;
  5984. struct de de;
  5985. int truncated;
  5986. int ok = 1;
  5987. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5988. return 0;
  5989. } else {
  5990. de.conn = conn;
  5991. while ((dp = mg_readdir(dirp)) != NULL) {
  5992. /* Do not show current dir (but show hidden files as they will
  5993. * also be removed) */
  5994. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5995. continue;
  5996. }
  5997. mg_snprintf(
  5998. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5999. /* If we don't memset stat structure to zero, mtime will have
  6000. * garbage and strftime() will segfault later on in
  6001. * print_dir_entry(). memset is required only if mg_stat()
  6002. * fails. For more details, see
  6003. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6004. memset(&de.file, 0, sizeof(de.file));
  6005. if (truncated) {
  6006. /* Do not delete anything shorter */
  6007. ok = 0;
  6008. continue;
  6009. }
  6010. if (!mg_stat(conn, path, &de.file)) {
  6011. mg_cry(conn,
  6012. "%s: mg_stat(%s) failed: %s",
  6013. __func__,
  6014. path,
  6015. strerror(ERRNO));
  6016. ok = 0;
  6017. }
  6018. if (de.file.is_directory) {
  6019. if (remove_directory(conn, path) == 0) {
  6020. ok = 0;
  6021. }
  6022. } else {
  6023. /* This will fail file is the file is in memory */
  6024. if (mg_remove(conn, path) == 0) {
  6025. ok = 0;
  6026. }
  6027. }
  6028. }
  6029. (void)mg_closedir(dirp);
  6030. IGNORE_UNUSED_RESULT(rmdir(dir));
  6031. }
  6032. return ok;
  6033. }
  6034. #endif
  6035. struct dir_scan_data {
  6036. struct de *entries;
  6037. unsigned int num_entries;
  6038. unsigned int arr_size;
  6039. };
  6040. /* Behaves like realloc(), but frees original pointer on failure */
  6041. static void *
  6042. realloc2(void *ptr, size_t size)
  6043. {
  6044. void *new_ptr = mg_realloc(ptr, size);
  6045. if (new_ptr == NULL) {
  6046. mg_free(ptr);
  6047. }
  6048. return new_ptr;
  6049. }
  6050. static void
  6051. dir_scan_callback(struct de *de, void *data)
  6052. {
  6053. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6054. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6055. dsd->arr_size *= 2;
  6056. dsd->entries =
  6057. (struct de *)realloc2(dsd->entries,
  6058. dsd->arr_size * sizeof(dsd->entries[0]));
  6059. }
  6060. if (dsd->entries == NULL) {
  6061. /* TODO(lsm, low): propagate an error to the caller */
  6062. dsd->num_entries = 0;
  6063. } else {
  6064. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6065. dsd->entries[dsd->num_entries].file = de->file;
  6066. dsd->entries[dsd->num_entries].conn = de->conn;
  6067. dsd->num_entries++;
  6068. }
  6069. }
  6070. static void
  6071. handle_directory_request(struct mg_connection *conn, const char *dir)
  6072. {
  6073. unsigned int i;
  6074. int sort_direction;
  6075. struct dir_scan_data data = {NULL, 0, 128};
  6076. char date[64];
  6077. time_t curtime = time(NULL);
  6078. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6079. send_http_error(conn,
  6080. 500,
  6081. "Error: Cannot open directory\nopendir(%s): %s",
  6082. dir,
  6083. strerror(ERRNO));
  6084. return;
  6085. }
  6086. gmt_time_string(date, sizeof(date), &curtime);
  6087. if (!conn) {
  6088. return;
  6089. }
  6090. sort_direction = ((conn->request_info.query_string != NULL)
  6091. && (conn->request_info.query_string[1] == 'd'))
  6092. ? 'a'
  6093. : 'd';
  6094. conn->must_close = 1;
  6095. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6096. send_static_cache_header(conn);
  6097. mg_printf(conn,
  6098. "Date: %s\r\n"
  6099. "Connection: close\r\n"
  6100. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6101. date);
  6102. conn->num_bytes_sent +=
  6103. mg_printf(conn,
  6104. "<html><head><title>Index of %s</title>"
  6105. "<style>th {text-align: left;}</style></head>"
  6106. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6107. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6108. "<th><a href=\"?d%c\">Modified</a></th>"
  6109. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6110. "<tr><td colspan=\"3\"><hr></td></tr>",
  6111. conn->request_info.local_uri,
  6112. conn->request_info.local_uri,
  6113. sort_direction,
  6114. sort_direction,
  6115. sort_direction);
  6116. /* Print first entry - link to a parent directory */
  6117. conn->num_bytes_sent +=
  6118. mg_printf(conn,
  6119. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6120. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6121. conn->request_info.local_uri,
  6122. "..",
  6123. "Parent directory",
  6124. "-",
  6125. "-");
  6126. /* Sort and print directory entries */
  6127. if (data.entries != NULL) {
  6128. qsort(data.entries,
  6129. (size_t)data.num_entries,
  6130. sizeof(data.entries[0]),
  6131. compare_dir_entries);
  6132. for (i = 0; i < data.num_entries; i++) {
  6133. print_dir_entry(&data.entries[i]);
  6134. mg_free(data.entries[i].file_name);
  6135. }
  6136. mg_free(data.entries);
  6137. }
  6138. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6139. conn->status_code = 200;
  6140. }
  6141. /* Send len bytes from the opened file to the client. */
  6142. static void
  6143. send_file_data(struct mg_connection *conn,
  6144. struct mg_file *filep,
  6145. int64_t offset,
  6146. int64_t len)
  6147. {
  6148. char buf[MG_BUF_LEN];
  6149. int to_read, num_read, num_written;
  6150. int64_t size;
  6151. if (!filep || !conn) {
  6152. return;
  6153. }
  6154. /* Sanity check the offset */
  6155. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6156. : (int64_t)(filep->stat.size);
  6157. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6158. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6159. /* file stored in memory */
  6160. if (len > size - offset) {
  6161. len = size - offset;
  6162. }
  6163. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6164. } else if (len > 0 && filep->access.fp != NULL) {
  6165. /* file stored on disk */
  6166. #if defined(__linux__)
  6167. /* sendfile is only available for Linux */
  6168. if ((conn->ssl == 0) && (conn->throttle == 0)
  6169. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6170. "yes"))) {
  6171. off_t sf_offs = (off_t)offset;
  6172. ssize_t sf_sent;
  6173. int sf_file = fileno(filep->access.fp);
  6174. int loop_cnt = 0;
  6175. do {
  6176. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6177. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6178. size_t sf_tosend =
  6179. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6180. sf_sent =
  6181. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6182. if (sf_sent > 0) {
  6183. conn->num_bytes_sent += sf_sent;
  6184. len -= sf_sent;
  6185. offset += sf_sent;
  6186. } else if (loop_cnt == 0) {
  6187. /* This file can not be sent using sendfile.
  6188. * This might be the case for pseudo-files in the
  6189. * /sys/ and /proc/ file system.
  6190. * Use the regular user mode copy code instead. */
  6191. break;
  6192. } else if (sf_sent == 0) {
  6193. /* No error, but 0 bytes sent. May be EOF? */
  6194. return;
  6195. }
  6196. loop_cnt++;
  6197. } while ((len > 0) && (sf_sent >= 0));
  6198. if (sf_sent > 0) {
  6199. return; /* OK */
  6200. }
  6201. /* sf_sent<0 means error, thus fall back to the classic way */
  6202. /* This is always the case, if sf_file is not a "normal" file,
  6203. * e.g., for sending data from the output of a CGI process. */
  6204. offset = (int64_t)sf_offs;
  6205. }
  6206. #endif
  6207. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6208. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6209. send_http_error(
  6210. conn,
  6211. 500,
  6212. "%s",
  6213. "Error: Unable to access file at requested position.");
  6214. } else {
  6215. while (len > 0) {
  6216. /* Calculate how much to read from the file in the buffer */
  6217. to_read = sizeof(buf);
  6218. if ((int64_t)to_read > len) {
  6219. to_read = (int)len;
  6220. }
  6221. /* Read from file, exit the loop on error */
  6222. if ((num_read =
  6223. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6224. <= 0) {
  6225. break;
  6226. }
  6227. /* Send read bytes to the client, exit the loop on error */
  6228. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6229. != num_read) {
  6230. break;
  6231. }
  6232. /* Both read and were successful, adjust counters */
  6233. conn->num_bytes_sent += num_written;
  6234. len -= num_written;
  6235. }
  6236. }
  6237. }
  6238. }
  6239. static int
  6240. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6241. {
  6242. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6243. }
  6244. static void
  6245. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6246. {
  6247. if (filestat != NULL && buf != NULL) {
  6248. mg_snprintf(NULL,
  6249. NULL, /* All calls to construct_etag use 64 byte buffer */
  6250. buf,
  6251. buf_len,
  6252. "\"%lx.%" INT64_FMT "\"",
  6253. (unsigned long)filestat->last_modified,
  6254. filestat->size);
  6255. }
  6256. }
  6257. static void
  6258. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6259. {
  6260. if (filep != NULL && filep->fp != NULL) {
  6261. #ifdef _WIN32
  6262. (void)conn; /* Unused. */
  6263. #else
  6264. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6265. mg_cry(conn,
  6266. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6267. __func__,
  6268. strerror(ERRNO));
  6269. }
  6270. #endif
  6271. }
  6272. }
  6273. static void
  6274. handle_static_file_request(struct mg_connection *conn,
  6275. const char *path,
  6276. struct mg_file *filep,
  6277. const char *mime_type,
  6278. const char *additional_headers)
  6279. {
  6280. char date[64], lm[64], etag[64];
  6281. char range[128]; /* large enough, so there will be no overflow */
  6282. const char *msg = "OK", *hdr;
  6283. time_t curtime = time(NULL);
  6284. int64_t cl, r1, r2;
  6285. struct vec mime_vec;
  6286. int n, truncated;
  6287. char gz_path[PATH_MAX];
  6288. const char *encoding = "";
  6289. const char *cors1, *cors2, *cors3;
  6290. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6291. return;
  6292. }
  6293. if (mime_type == NULL) {
  6294. get_mime_type(conn->ctx, path, &mime_vec);
  6295. } else {
  6296. mime_vec.ptr = mime_type;
  6297. mime_vec.len = strlen(mime_type);
  6298. }
  6299. if (filep->stat.size > INT64_MAX) {
  6300. send_http_error(conn,
  6301. 500,
  6302. "Error: File size is too large to send\n%" INT64_FMT,
  6303. filep->stat.size);
  6304. }
  6305. cl = (int64_t)filep->stat.size;
  6306. conn->status_code = 200;
  6307. range[0] = '\0';
  6308. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6309. * it's important to rewrite the filename after resolving
  6310. * the mime type from it, to preserve the actual file's type */
  6311. if (filep->stat.is_gzipped) {
  6312. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6313. if (truncated) {
  6314. send_http_error(conn,
  6315. 500,
  6316. "Error: Path of zipped file too long (%s)",
  6317. path);
  6318. return;
  6319. }
  6320. path = gz_path;
  6321. encoding = "Content-Encoding: gzip\r\n";
  6322. }
  6323. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6324. send_http_error(conn,
  6325. 500,
  6326. "Error: Cannot open file\nfopen(%s): %s",
  6327. path,
  6328. strerror(ERRNO));
  6329. return;
  6330. }
  6331. fclose_on_exec(&filep->access, conn);
  6332. /* If Range: header specified, act accordingly */
  6333. r1 = r2 = 0;
  6334. hdr = mg_get_header(conn, "Range");
  6335. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6336. && r2 >= 0) {
  6337. /* actually, range requests don't play well with a pre-gzipped
  6338. * file (since the range is specified in the uncompressed space) */
  6339. if (filep->stat.is_gzipped) {
  6340. send_http_error(
  6341. conn,
  6342. 501,
  6343. "%s",
  6344. "Error: Range requests in gzipped files are not supported");
  6345. (void)mg_fclose(
  6346. &filep->access); /* ignore error on read only file */
  6347. return;
  6348. }
  6349. conn->status_code = 206;
  6350. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6351. mg_snprintf(conn,
  6352. NULL, /* range buffer is big enough */
  6353. range,
  6354. sizeof(range),
  6355. "Content-Range: bytes "
  6356. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6357. r1,
  6358. r1 + cl - 1,
  6359. filep->stat.size);
  6360. msg = "Partial Content";
  6361. }
  6362. hdr = mg_get_header(conn, "Origin");
  6363. if (hdr) {
  6364. /* Cross-origin resource sharing (CORS), see
  6365. * http://www.html5rocks.com/en/tutorials/cors/,
  6366. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6367. * preflight is not supported for files. */
  6368. cors1 = "Access-Control-Allow-Origin: ";
  6369. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6370. cors3 = "\r\n";
  6371. } else {
  6372. cors1 = cors2 = cors3 = "";
  6373. }
  6374. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6375. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6376. gmt_time_string(date, sizeof(date), &curtime);
  6377. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6378. construct_etag(etag, sizeof(etag), &filep->stat);
  6379. (void)mg_printf(conn,
  6380. "HTTP/1.1 %d %s\r\n"
  6381. "%s%s%s"
  6382. "Date: %s\r\n",
  6383. conn->status_code,
  6384. msg,
  6385. cors1,
  6386. cors2,
  6387. cors3,
  6388. date);
  6389. send_static_cache_header(conn);
  6390. (void)mg_printf(conn,
  6391. "Last-Modified: %s\r\n"
  6392. "Etag: %s\r\n"
  6393. "Content-Type: %.*s\r\n"
  6394. "Content-Length: %" INT64_FMT "\r\n"
  6395. "Connection: %s\r\n"
  6396. "Accept-Ranges: bytes\r\n"
  6397. "%s%s",
  6398. lm,
  6399. etag,
  6400. (int)mime_vec.len,
  6401. mime_vec.ptr,
  6402. cl,
  6403. suggest_connection_header(conn),
  6404. range,
  6405. encoding);
  6406. /* The previous code must not add any header starting with X- to make
  6407. * sure no one of the additional_headers is included twice */
  6408. if (additional_headers != NULL) {
  6409. (void)mg_printf(conn,
  6410. "%.*s\r\n\r\n",
  6411. (int)strlen(additional_headers),
  6412. additional_headers);
  6413. } else {
  6414. (void)mg_printf(conn, "\r\n");
  6415. }
  6416. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6417. send_file_data(conn, filep, r1, cl);
  6418. }
  6419. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6420. }
  6421. #if !defined(NO_CACHING)
  6422. static void
  6423. handle_not_modified_static_file_request(struct mg_connection *conn,
  6424. struct mg_file *filep)
  6425. {
  6426. char date[64], lm[64], etag[64];
  6427. time_t curtime = time(NULL);
  6428. if (conn == NULL || filep == NULL) {
  6429. return;
  6430. }
  6431. conn->status_code = 304;
  6432. gmt_time_string(date, sizeof(date), &curtime);
  6433. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6434. construct_etag(etag, sizeof(etag), &filep->stat);
  6435. (void)mg_printf(conn,
  6436. "HTTP/1.1 %d %s\r\n"
  6437. "Date: %s\r\n",
  6438. conn->status_code,
  6439. mg_get_response_code_text(conn, conn->status_code),
  6440. date);
  6441. send_static_cache_header(conn);
  6442. (void)mg_printf(conn,
  6443. "Last-Modified: %s\r\n"
  6444. "Etag: %s\r\n"
  6445. "Connection: %s\r\n"
  6446. "\r\n",
  6447. lm,
  6448. etag,
  6449. suggest_connection_header(conn));
  6450. }
  6451. #endif
  6452. void
  6453. mg_send_file(struct mg_connection *conn, const char *path)
  6454. {
  6455. mg_send_mime_file(conn, path, NULL);
  6456. }
  6457. void
  6458. mg_send_mime_file(struct mg_connection *conn,
  6459. const char *path,
  6460. const char *mime_type)
  6461. {
  6462. mg_send_mime_file2(conn, path, mime_type, NULL);
  6463. }
  6464. void
  6465. mg_send_mime_file2(struct mg_connection *conn,
  6466. const char *path,
  6467. const char *mime_type,
  6468. const char *additional_headers)
  6469. {
  6470. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6471. if (mg_stat(conn, path, &file.stat)) {
  6472. if (file.stat.is_directory) {
  6473. if (!conn) {
  6474. return;
  6475. }
  6476. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6477. "yes")) {
  6478. handle_directory_request(conn, path);
  6479. } else {
  6480. send_http_error(conn,
  6481. 403,
  6482. "%s",
  6483. "Error: Directory listing denied");
  6484. }
  6485. } else {
  6486. handle_static_file_request(
  6487. conn, path, &file, mime_type, additional_headers);
  6488. }
  6489. } else {
  6490. send_http_error(conn, 404, "%s", "Error: File not found");
  6491. }
  6492. }
  6493. /* For a given PUT path, create all intermediate subdirectories.
  6494. * Return 0 if the path itself is a directory.
  6495. * Return 1 if the path leads to a file.
  6496. * Return -1 for if the path is too long.
  6497. * Return -2 if path can not be created.
  6498. */
  6499. static int
  6500. put_dir(struct mg_connection *conn, const char *path)
  6501. {
  6502. char buf[PATH_MAX];
  6503. const char *s, *p;
  6504. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6505. size_t len;
  6506. int res = 1;
  6507. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6508. len = (size_t)(p - path);
  6509. if (len >= sizeof(buf)) {
  6510. /* path too long */
  6511. res = -1;
  6512. break;
  6513. }
  6514. memcpy(buf, path, len);
  6515. buf[len] = '\0';
  6516. /* Try to create intermediate directory */
  6517. DEBUG_TRACE("mkdir(%s)", buf);
  6518. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6519. /* path does not exixt and can not be created */
  6520. res = -2;
  6521. break;
  6522. }
  6523. /* Is path itself a directory? */
  6524. if (p[1] == '\0') {
  6525. res = 0;
  6526. }
  6527. }
  6528. return res;
  6529. }
  6530. static void
  6531. remove_bad_file(const struct mg_connection *conn, const char *path)
  6532. {
  6533. int r = mg_remove(conn, path);
  6534. if (r != 0) {
  6535. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6536. }
  6537. }
  6538. long long
  6539. mg_store_body(struct mg_connection *conn, const char *path)
  6540. {
  6541. char buf[MG_BUF_LEN];
  6542. long long len = 0;
  6543. int ret, n;
  6544. struct mg_file fi;
  6545. if (conn->consumed_content != 0) {
  6546. mg_cry(conn, "%s: Contents already consumed", __func__);
  6547. return -11;
  6548. }
  6549. ret = put_dir(conn, path);
  6550. if (ret < 0) {
  6551. /* -1 for path too long,
  6552. * -2 for path can not be created. */
  6553. return ret;
  6554. }
  6555. if (ret != 1) {
  6556. /* Return 0 means, path itself is a directory. */
  6557. return 0;
  6558. }
  6559. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6560. return -12;
  6561. }
  6562. ret = mg_read(conn, buf, sizeof(buf));
  6563. while (ret > 0) {
  6564. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6565. if (n != ret) {
  6566. (void)mg_fclose(
  6567. &fi.access); /* File is bad and will be removed anyway. */
  6568. remove_bad_file(conn, path);
  6569. return -13;
  6570. }
  6571. ret = mg_read(conn, buf, sizeof(buf));
  6572. }
  6573. /* File is open for writing. If fclose fails, there was probably an
  6574. * error flushing the buffer to disk, so the file on disk might be
  6575. * broken. Delete it and return an error to the caller. */
  6576. if (mg_fclose(&fi.access) != 0) {
  6577. remove_bad_file(conn, path);
  6578. return -14;
  6579. }
  6580. return len;
  6581. }
  6582. /* Parse HTTP headers from the given buffer, advance buf pointer
  6583. * to the point where parsing stopped.
  6584. * All parameters must be valid pointers (not NULL).
  6585. * Return <0 on error. */
  6586. static int
  6587. parse_http_headers(char **buf, struct mg_request_info *ri)
  6588. {
  6589. int i;
  6590. ri->num_headers = 0;
  6591. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6592. char *dp = *buf;
  6593. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6594. dp++;
  6595. }
  6596. if (dp == *buf) {
  6597. /* End of headers reached. */
  6598. break;
  6599. }
  6600. if (*dp != ':') {
  6601. /* This is not a valid field. */
  6602. return -1;
  6603. }
  6604. /* End of header key (*dp == ':') */
  6605. /* Truncate here and set the key name */
  6606. *dp = 0;
  6607. ri->http_headers[i].name = *buf;
  6608. do {
  6609. dp++;
  6610. } while (*dp == ' ');
  6611. /* The rest of the line is the value */
  6612. ri->http_headers[i].value = dp;
  6613. *buf = dp + strcspn(dp, "\r\n");
  6614. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6615. *buf = NULL;
  6616. }
  6617. ri->num_headers = i + 1;
  6618. if (*buf) {
  6619. (*buf)[0] = 0;
  6620. (*buf)[1] = 0;
  6621. *buf += 2;
  6622. } else {
  6623. *buf = dp;
  6624. break;
  6625. }
  6626. if ((*buf)[0] == '\r') {
  6627. /* This is the end of the header */
  6628. break;
  6629. }
  6630. }
  6631. return ri->num_headers;
  6632. }
  6633. static int
  6634. is_valid_http_method(const char *method)
  6635. {
  6636. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6637. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6638. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6639. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6640. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6641. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6642. /* TRACE method (RFC 2616) is not supported for security reasons */
  6643. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6644. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6645. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6646. /* Unsupported WEBDAV Methods: */
  6647. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6648. /* + 11 methods from RFC 3253 */
  6649. /* ORDERPATCH (RFC 3648) */
  6650. /* ACL (RFC 3744) */
  6651. /* SEARCH (RFC 5323) */
  6652. /* + MicroSoft extensions
  6653. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6654. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6655. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6656. }
  6657. /* Parse HTTP request, fill in mg_request_info structure.
  6658. * This function modifies the buffer by NUL-terminating
  6659. * HTTP request components, header names and header values.
  6660. * Parameters:
  6661. * buf (in/out): pointer to the HTTP header to parse and split
  6662. * len (in): length of HTTP header buffer
  6663. * re (out): parsed header as mg_request_info
  6664. * buf and ri must be valid pointers (not NULL), len>0.
  6665. * Returns <0 on error. */
  6666. static int
  6667. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6668. {
  6669. int is_request, request_length;
  6670. char *start_line;
  6671. request_length = get_request_len(buf, len);
  6672. if (request_length > 0) {
  6673. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6674. * remote_port */
  6675. ri->remote_user = ri->request_method = ri->request_uri =
  6676. ri->http_version = NULL;
  6677. ri->num_headers = 0;
  6678. buf[request_length - 1] = '\0';
  6679. /* RFC says that all initial whitespaces should be ingored */
  6680. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6681. buf++;
  6682. }
  6683. start_line = skip(&buf, "\r\n");
  6684. ri->request_method = skip(&start_line, " ");
  6685. ri->request_uri = skip(&start_line, " ");
  6686. ri->http_version = start_line;
  6687. /* HTTP message could be either HTTP request:
  6688. * "GET / HTTP/1.0 ..."
  6689. * or a HTTP response:
  6690. * "HTTP/1.0 200 OK ..."
  6691. * otherwise it is invalid.
  6692. */
  6693. is_request = is_valid_http_method(ri->request_method);
  6694. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6695. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6696. /* Not a valid request or response: invalid */
  6697. return -1;
  6698. }
  6699. if (is_request) {
  6700. ri->http_version += 5;
  6701. }
  6702. if (parse_http_headers(&buf, ri) < 0) {
  6703. /* Error while parsing headers */
  6704. return -1;
  6705. }
  6706. }
  6707. return request_length;
  6708. }
  6709. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6710. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6711. * buffer (which marks the end of HTTP request). Buffer buf may already
  6712. * have some data. The length of the data is stored in nread.
  6713. * Upon every read operation, increase nread by the number of bytes read. */
  6714. static int
  6715. read_request(FILE *fp,
  6716. struct mg_connection *conn,
  6717. char *buf,
  6718. int bufsiz,
  6719. int *nread)
  6720. {
  6721. int request_len, n = 0;
  6722. struct timespec last_action_time;
  6723. double request_timeout;
  6724. if (!conn) {
  6725. return 0;
  6726. }
  6727. memset(&last_action_time, 0, sizeof(last_action_time));
  6728. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6729. /* value of request_timeout is in seconds, config in milliseconds */
  6730. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6731. } else {
  6732. request_timeout = -1.0;
  6733. }
  6734. if (conn->handled_requests > 0) {
  6735. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6736. request_timeout =
  6737. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6738. }
  6739. }
  6740. request_len = get_request_len(buf, *nread);
  6741. /* first time reading from this connection */
  6742. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6743. while (request_len == 0) {
  6744. /* Full request not yet received */
  6745. if (conn->ctx->stop_flag != 0) {
  6746. /* Server is to be stopped. */
  6747. return -1;
  6748. }
  6749. if (*nread >= bufsiz) {
  6750. /* Request too long */
  6751. return -2;
  6752. }
  6753. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6754. if (n < 0) {
  6755. /* Receive error */
  6756. return -1;
  6757. }
  6758. *nread += n;
  6759. request_len = get_request_len(buf, *nread);
  6760. if ((request_len == 0) && (request_timeout >= 0)) {
  6761. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6762. > request_timeout) {
  6763. /* Timeout */
  6764. return -1;
  6765. }
  6766. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6767. }
  6768. }
  6769. return request_len;
  6770. }
  6771. #if !defined(NO_FILES)
  6772. /* For given directory path, substitute it to valid index file.
  6773. * Return 1 if index file has been found, 0 if not found.
  6774. * If the file is found, it's stats is returned in stp. */
  6775. static int
  6776. substitute_index_file(struct mg_connection *conn,
  6777. char *path,
  6778. size_t path_len,
  6779. struct mg_file *filep)
  6780. {
  6781. if (conn && conn->ctx) {
  6782. const char *list = conn->ctx->config[INDEX_FILES];
  6783. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6784. struct vec filename_vec;
  6785. size_t n = strlen(path);
  6786. int found = 0;
  6787. /* The 'path' given to us points to the directory. Remove all trailing
  6788. * directory separator characters from the end of the path, and
  6789. * then append single directory separator character. */
  6790. while (n > 0 && path[n - 1] == '/') {
  6791. n--;
  6792. }
  6793. path[n] = '/';
  6794. /* Traverse index files list. For each entry, append it to the given
  6795. * path and see if the file exists. If it exists, break the loop */
  6796. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6797. /* Ignore too long entries that may overflow path buffer */
  6798. if (filename_vec.len > path_len - (n + 2)) {
  6799. continue;
  6800. }
  6801. /* Prepare full path to the index file */
  6802. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6803. /* Does it exist? */
  6804. if (mg_stat(conn, path, &file.stat)) {
  6805. /* Yes it does, break the loop */
  6806. *filep = file;
  6807. found = 1;
  6808. break;
  6809. }
  6810. }
  6811. /* If no index file exists, restore directory path */
  6812. if (!found) {
  6813. path[n] = '\0';
  6814. }
  6815. return found;
  6816. }
  6817. return 0;
  6818. }
  6819. #endif
  6820. #if !defined(NO_CACHING)
  6821. /* Return True if we should reply 304 Not Modified. */
  6822. static int
  6823. is_not_modified(const struct mg_connection *conn,
  6824. const struct mg_file_stat *filestat)
  6825. {
  6826. char etag[64];
  6827. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6828. const char *inm = mg_get_header(conn, "If-None-Match");
  6829. construct_etag(etag, sizeof(etag), filestat);
  6830. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6831. || ((ims != NULL)
  6832. && (filestat->last_modified <= parse_date_string(ims)));
  6833. }
  6834. #endif /* !NO_CACHING */
  6835. #if !defined(NO_CGI) || !defined(NO_FILES)
  6836. static int
  6837. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6838. {
  6839. const char *expect, *body;
  6840. char buf[MG_BUF_LEN];
  6841. int to_read, nread, success = 0;
  6842. int64_t buffered_len;
  6843. double timeout = -1.0;
  6844. if (!conn) {
  6845. return 0;
  6846. }
  6847. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6848. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6849. }
  6850. expect = mg_get_header(conn, "Expect");
  6851. /* assert(fp != NULL); */
  6852. if (!fp) {
  6853. send_http_error(conn, 500, "%s", "Error: NULL File");
  6854. return 0;
  6855. }
  6856. if (conn->content_len == -1 && !conn->is_chunked) {
  6857. /* Content length is not specified by the client. */
  6858. send_http_error(conn,
  6859. 411,
  6860. "%s",
  6861. "Error: Client did not specify content length");
  6862. } else if ((expect != NULL)
  6863. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6864. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6865. send_http_error(conn,
  6866. 417,
  6867. "Error: Can not fulfill expectation %s",
  6868. expect);
  6869. } else {
  6870. if (expect != NULL) {
  6871. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6872. conn->status_code = 100;
  6873. } else {
  6874. conn->status_code = 200;
  6875. }
  6876. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6877. - conn->consumed_content;
  6878. /* assert(buffered_len >= 0); */
  6879. /* assert(conn->consumed_content == 0); */
  6880. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6881. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6882. return 0;
  6883. }
  6884. if (buffered_len > 0) {
  6885. if ((int64_t)buffered_len > conn->content_len) {
  6886. buffered_len = (int)conn->content_len;
  6887. }
  6888. body = conn->buf + conn->request_len + conn->consumed_content;
  6889. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6890. conn->consumed_content += buffered_len;
  6891. }
  6892. nread = 0;
  6893. while (conn->consumed_content < conn->content_len) {
  6894. to_read = sizeof(buf);
  6895. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6896. to_read = (int)(conn->content_len - conn->consumed_content);
  6897. }
  6898. nread = pull(NULL, conn, buf, to_read, timeout);
  6899. if (nread <= 0
  6900. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6901. break;
  6902. }
  6903. conn->consumed_content += nread;
  6904. }
  6905. if (conn->consumed_content == conn->content_len) {
  6906. success = (nread >= 0);
  6907. }
  6908. /* Each error code path in this function must send an error */
  6909. if (!success) {
  6910. /* NOTE: Maybe some data has already been sent. */
  6911. /* TODO (low): If some data has been sent, a correct error
  6912. * reply can no longer be sent, so just close the connection */
  6913. send_http_error(conn, 500, "%s", "");
  6914. }
  6915. }
  6916. return success;
  6917. }
  6918. #endif
  6919. #if !defined(NO_CGI)
  6920. /* This structure helps to create an environment for the spawned CGI program.
  6921. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6922. * last element must be NULL.
  6923. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6924. * strings must reside in a contiguous buffer. The end of the buffer is
  6925. * marked by two '\0' characters.
  6926. * We satisfy both worlds: we create an envp array (which is vars), all
  6927. * entries are actually pointers inside buf. */
  6928. struct cgi_environment {
  6929. struct mg_connection *conn;
  6930. /* Data block */
  6931. char *buf; /* Environment buffer */
  6932. size_t buflen; /* Space available in buf */
  6933. size_t bufused; /* Space taken in buf */
  6934. /* Index block */
  6935. char **var; /* char **envp */
  6936. size_t varlen; /* Number of variables available in var */
  6937. size_t varused; /* Number of variables stored in var */
  6938. };
  6939. static void addenv(struct cgi_environment *env,
  6940. PRINTF_FORMAT_STRING(const char *fmt),
  6941. ...) PRINTF_ARGS(2, 3);
  6942. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6943. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6944. static void
  6945. addenv(struct cgi_environment *env, const char *fmt, ...)
  6946. {
  6947. size_t n, space;
  6948. int truncated = 0;
  6949. char *added;
  6950. va_list ap;
  6951. /* Calculate how much space is left in the buffer */
  6952. space = (env->buflen - env->bufused);
  6953. /* Calculate an estimate for the required space */
  6954. n = strlen(fmt) + 2 + 128;
  6955. do {
  6956. if (space <= n) {
  6957. /* Allocate new buffer */
  6958. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6959. added = (char *)mg_realloc(env->buf, n);
  6960. if (!added) {
  6961. /* Out of memory */
  6962. mg_cry(env->conn,
  6963. "%s: Cannot allocate memory for CGI variable [%s]",
  6964. __func__,
  6965. fmt);
  6966. return;
  6967. }
  6968. env->buf = added;
  6969. env->buflen = n;
  6970. space = (env->buflen - env->bufused);
  6971. }
  6972. /* Make a pointer to the free space int the buffer */
  6973. added = env->buf + env->bufused;
  6974. /* Copy VARIABLE=VALUE\0 string into the free space */
  6975. va_start(ap, fmt);
  6976. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6977. va_end(ap);
  6978. /* Do not add truncated strings to the environment */
  6979. if (truncated) {
  6980. /* Reallocate the buffer */
  6981. space = 0;
  6982. n = 1;
  6983. }
  6984. } while (truncated);
  6985. /* Calculate number of bytes added to the environment */
  6986. n = strlen(added) + 1;
  6987. env->bufused += n;
  6988. /* Now update the variable index */
  6989. space = (env->varlen - env->varused);
  6990. if (space < 2) {
  6991. mg_cry(env->conn,
  6992. "%s: Cannot register CGI variable [%s]",
  6993. __func__,
  6994. fmt);
  6995. return;
  6996. }
  6997. /* Append a pointer to the added string into the envp array */
  6998. env->var[env->varused] = added;
  6999. env->varused++;
  7000. }
  7001. static void
  7002. prepare_cgi_environment(struct mg_connection *conn,
  7003. const char *prog,
  7004. struct cgi_environment *env)
  7005. {
  7006. const char *s;
  7007. struct vec var_vec;
  7008. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7009. int i, truncated, uri_len;
  7010. if (conn == NULL || prog == NULL || env == NULL) {
  7011. return;
  7012. }
  7013. env->conn = conn;
  7014. env->buflen = CGI_ENVIRONMENT_SIZE;
  7015. env->bufused = 0;
  7016. env->buf = (char *)mg_malloc(env->buflen);
  7017. env->varlen = MAX_CGI_ENVIR_VARS;
  7018. env->varused = 0;
  7019. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7020. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7021. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7022. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7023. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7024. /* Prepare the environment block */
  7025. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7026. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7027. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7028. #if defined(USE_IPV6)
  7029. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7030. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7031. } else
  7032. #endif
  7033. {
  7034. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7035. }
  7036. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7037. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7038. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7039. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7040. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7041. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7042. /* SCRIPT_NAME */
  7043. uri_len = (int)strlen(conn->request_info.local_uri);
  7044. if (conn->path_info == NULL) {
  7045. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7046. /* URI: /path_to_script/script.cgi */
  7047. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7048. } else {
  7049. /* URI: /path_to_script/ ... using index.cgi */
  7050. char *index_file = strrchr(prog, '/');
  7051. if (index_file) {
  7052. addenv(env,
  7053. "SCRIPT_NAME=%s%s",
  7054. conn->request_info.local_uri,
  7055. index_file + 1);
  7056. }
  7057. }
  7058. } else {
  7059. /* URI: /path_to_script/script.cgi/path_info */
  7060. addenv(env,
  7061. "SCRIPT_NAME=%.*s",
  7062. uri_len - (int)strlen(conn->path_info),
  7063. conn->request_info.local_uri);
  7064. }
  7065. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7066. if (conn->path_info == NULL) {
  7067. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7068. } else {
  7069. addenv(env,
  7070. "PATH_TRANSLATED=%s%s",
  7071. conn->ctx->config[DOCUMENT_ROOT],
  7072. conn->path_info);
  7073. }
  7074. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7075. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7076. addenv(env, "CONTENT_TYPE=%s", s);
  7077. }
  7078. if (conn->request_info.query_string != NULL) {
  7079. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7080. }
  7081. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7082. addenv(env, "CONTENT_LENGTH=%s", s);
  7083. }
  7084. if ((s = getenv("PATH")) != NULL) {
  7085. addenv(env, "PATH=%s", s);
  7086. }
  7087. if (conn->path_info != NULL) {
  7088. addenv(env, "PATH_INFO=%s", conn->path_info);
  7089. }
  7090. if (conn->status_code > 0) {
  7091. /* CGI error handler should show the status code */
  7092. addenv(env, "STATUS=%d", conn->status_code);
  7093. }
  7094. #if defined(_WIN32)
  7095. if ((s = getenv("COMSPEC")) != NULL) {
  7096. addenv(env, "COMSPEC=%s", s);
  7097. }
  7098. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7099. addenv(env, "SYSTEMROOT=%s", s);
  7100. }
  7101. if ((s = getenv("SystemDrive")) != NULL) {
  7102. addenv(env, "SystemDrive=%s", s);
  7103. }
  7104. if ((s = getenv("ProgramFiles")) != NULL) {
  7105. addenv(env, "ProgramFiles=%s", s);
  7106. }
  7107. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7108. addenv(env, "ProgramFiles(x86)=%s", s);
  7109. }
  7110. #else
  7111. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7112. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7113. }
  7114. #endif /* _WIN32 */
  7115. if ((s = getenv("PERLLIB")) != NULL) {
  7116. addenv(env, "PERLLIB=%s", s);
  7117. }
  7118. if (conn->request_info.remote_user != NULL) {
  7119. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7120. addenv(env, "%s", "AUTH_TYPE=Digest");
  7121. }
  7122. /* Add all headers as HTTP_* variables */
  7123. for (i = 0; i < conn->request_info.num_headers; i++) {
  7124. (void)mg_snprintf(conn,
  7125. &truncated,
  7126. http_var_name,
  7127. sizeof(http_var_name),
  7128. "HTTP_%s",
  7129. conn->request_info.http_headers[i].name);
  7130. if (truncated) {
  7131. mg_cry(conn,
  7132. "%s: HTTP header variable too long [%s]",
  7133. __func__,
  7134. conn->request_info.http_headers[i].name);
  7135. continue;
  7136. }
  7137. /* Convert variable name into uppercase, and change - to _ */
  7138. for (p = http_var_name; *p != '\0'; p++) {
  7139. if (*p == '-') {
  7140. *p = '_';
  7141. }
  7142. *p = (char)toupper(*(unsigned char *)p);
  7143. }
  7144. addenv(env,
  7145. "%s=%s",
  7146. http_var_name,
  7147. conn->request_info.http_headers[i].value);
  7148. }
  7149. /* Add user-specified variables */
  7150. s = conn->ctx->config[CGI_ENVIRONMENT];
  7151. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7152. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7153. }
  7154. env->var[env->varused] = NULL;
  7155. env->buf[env->bufused] = '\0';
  7156. }
  7157. static void
  7158. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7159. {
  7160. char *buf;
  7161. size_t buflen;
  7162. int headers_len, data_len, i, truncated;
  7163. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7164. const char *status, *status_text, *connection_state;
  7165. char *pbuf, dir[PATH_MAX], *p;
  7166. struct mg_request_info ri;
  7167. struct cgi_environment blk;
  7168. FILE *in = NULL, *out = NULL, *err = NULL;
  7169. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7170. pid_t pid = (pid_t)-1;
  7171. if (conn == NULL) {
  7172. return;
  7173. }
  7174. buf = NULL;
  7175. buflen = 16384;
  7176. prepare_cgi_environment(conn, prog, &blk);
  7177. /* CGI must be executed in its own directory. 'dir' must point to the
  7178. * directory containing executable program, 'p' must point to the
  7179. * executable program name relative to 'dir'. */
  7180. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7181. if (truncated) {
  7182. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7183. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7184. goto done;
  7185. }
  7186. if ((p = strrchr(dir, '/')) != NULL) {
  7187. *p++ = '\0';
  7188. } else {
  7189. dir[0] = '.', dir[1] = '\0';
  7190. p = (char *)prog;
  7191. }
  7192. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7193. status = strerror(ERRNO);
  7194. mg_cry(conn,
  7195. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7196. prog,
  7197. status);
  7198. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7199. goto done;
  7200. }
  7201. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7202. if (pid == (pid_t)-1) {
  7203. status = strerror(ERRNO);
  7204. mg_cry(conn,
  7205. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7206. prog,
  7207. status);
  7208. send_http_error(conn,
  7209. 500,
  7210. "Error: Cannot spawn CGI process [%s]: %s",
  7211. prog,
  7212. status);
  7213. goto done;
  7214. }
  7215. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7216. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7217. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7218. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7219. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7220. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7221. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7222. /* Parent closes only one side of the pipes.
  7223. * If we don't mark them as closed, close() attempt before
  7224. * return from this function throws an exception on Windows.
  7225. * Windows does not like when closed descriptor is closed again. */
  7226. (void)close(fdin[0]);
  7227. (void)close(fdout[1]);
  7228. (void)close(fderr[1]);
  7229. fdin[0] = fdout[1] = fderr[1] = -1;
  7230. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7231. status = strerror(ERRNO);
  7232. mg_cry(conn,
  7233. "Error: CGI program \"%s\": Can not open stdin: %s",
  7234. prog,
  7235. status);
  7236. send_http_error(conn,
  7237. 500,
  7238. "Error: CGI can not open fdin\nfopen: %s",
  7239. status);
  7240. goto done;
  7241. }
  7242. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7243. status = strerror(ERRNO);
  7244. mg_cry(conn,
  7245. "Error: CGI program \"%s\": Can not open stdout: %s",
  7246. prog,
  7247. status);
  7248. send_http_error(conn,
  7249. 500,
  7250. "Error: CGI can not open fdout\nfopen: %s",
  7251. status);
  7252. goto done;
  7253. }
  7254. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7255. status = strerror(ERRNO);
  7256. mg_cry(conn,
  7257. "Error: CGI program \"%s\": Can not open stderr: %s",
  7258. prog,
  7259. status);
  7260. send_http_error(conn,
  7261. 500,
  7262. "Error: CGI can not open fdout\nfopen: %s",
  7263. status);
  7264. goto done;
  7265. }
  7266. setbuf(in, NULL);
  7267. setbuf(out, NULL);
  7268. setbuf(err, NULL);
  7269. fout.access.fp = out;
  7270. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7271. /* This is a POST/PUT request, or another request with body data. */
  7272. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7273. /* Error sending the body data */
  7274. mg_cry(conn,
  7275. "Error: CGI program \"%s\": Forward body data failed",
  7276. prog);
  7277. goto done;
  7278. }
  7279. }
  7280. /* Close so child gets an EOF. */
  7281. fclose(in);
  7282. in = NULL;
  7283. fdin[1] = -1;
  7284. /* Now read CGI reply into a buffer. We need to set correct
  7285. * status code, thus we need to see all HTTP headers first.
  7286. * Do not send anything back to client, until we buffer in all
  7287. * HTTP headers. */
  7288. data_len = 0;
  7289. buf = (char *)mg_malloc(buflen);
  7290. if (buf == NULL) {
  7291. send_http_error(conn,
  7292. 500,
  7293. "Error: Not enough memory for CGI buffer (%u bytes)",
  7294. (unsigned int)buflen);
  7295. mg_cry(conn,
  7296. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7297. "bytes)",
  7298. prog,
  7299. (unsigned int)buflen);
  7300. goto done;
  7301. }
  7302. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7303. if (headers_len <= 0) {
  7304. /* Could not parse the CGI response. Check if some error message on
  7305. * stderr. */
  7306. i = pull_all(err, conn, buf, (int)buflen);
  7307. if (i > 0) {
  7308. mg_cry(conn,
  7309. "Error: CGI program \"%s\" sent error "
  7310. "message: [%.*s]",
  7311. prog,
  7312. i,
  7313. buf);
  7314. send_http_error(conn,
  7315. 500,
  7316. "Error: CGI program \"%s\" sent error "
  7317. "message: [%.*s]",
  7318. prog,
  7319. i,
  7320. buf);
  7321. } else {
  7322. mg_cry(conn,
  7323. "Error: CGI program sent malformed or too big "
  7324. "(>%u bytes) HTTP headers: [%.*s]",
  7325. (unsigned)buflen,
  7326. data_len,
  7327. buf);
  7328. send_http_error(conn,
  7329. 500,
  7330. "Error: CGI program sent malformed or too big "
  7331. "(>%u bytes) HTTP headers: [%.*s]",
  7332. (unsigned)buflen,
  7333. data_len,
  7334. buf);
  7335. }
  7336. goto done;
  7337. }
  7338. pbuf = buf;
  7339. buf[headers_len - 1] = '\0';
  7340. parse_http_headers(&pbuf, &ri);
  7341. /* Make up and send the status line */
  7342. status_text = "OK";
  7343. if ((status = get_header(&ri, "Status")) != NULL) {
  7344. conn->status_code = atoi(status);
  7345. status_text = status;
  7346. while (isdigit(*(const unsigned char *)status_text)
  7347. || *status_text == ' ') {
  7348. status_text++;
  7349. }
  7350. } else if (get_header(&ri, "Location") != NULL) {
  7351. conn->status_code = 302;
  7352. } else {
  7353. conn->status_code = 200;
  7354. }
  7355. connection_state = get_header(&ri, "Connection");
  7356. if (!header_has_option(connection_state, "keep-alive")) {
  7357. conn->must_close = 1;
  7358. }
  7359. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7360. /* Send headers */
  7361. for (i = 0; i < ri.num_headers; i++) {
  7362. mg_printf(conn,
  7363. "%s: %s\r\n",
  7364. ri.http_headers[i].name,
  7365. ri.http_headers[i].value);
  7366. }
  7367. mg_write(conn, "\r\n", 2);
  7368. /* Send chunk of data that may have been read after the headers */
  7369. conn->num_bytes_sent +=
  7370. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7371. /* Read the rest of CGI output and send to the client */
  7372. send_file_data(conn, &fout, 0, INT64_MAX);
  7373. done:
  7374. mg_free(blk.var);
  7375. mg_free(blk.buf);
  7376. if (pid != (pid_t)-1) {
  7377. kill(pid, SIGKILL);
  7378. #if !defined(_WIN32)
  7379. {
  7380. int st;
  7381. while (waitpid(pid, &st, 0) != -1)
  7382. ; /* clean zombies */
  7383. }
  7384. #endif
  7385. }
  7386. if (fdin[0] != -1) {
  7387. close(fdin[0]);
  7388. }
  7389. if (fdout[1] != -1) {
  7390. close(fdout[1]);
  7391. }
  7392. if (in != NULL) {
  7393. fclose(in);
  7394. } else if (fdin[1] != -1) {
  7395. close(fdin[1]);
  7396. }
  7397. if (out != NULL) {
  7398. fclose(out);
  7399. } else if (fdout[0] != -1) {
  7400. close(fdout[0]);
  7401. }
  7402. if (err != NULL) {
  7403. fclose(err);
  7404. } else if (fderr[0] != -1) {
  7405. close(fderr[0]);
  7406. }
  7407. if (buf != NULL) {
  7408. mg_free(buf);
  7409. }
  7410. }
  7411. #endif /* !NO_CGI */
  7412. #if !defined(NO_FILES)
  7413. static void
  7414. mkcol(struct mg_connection *conn, const char *path)
  7415. {
  7416. int rc, body_len;
  7417. struct de de;
  7418. char date[64];
  7419. time_t curtime = time(NULL);
  7420. if (conn == NULL) {
  7421. return;
  7422. }
  7423. /* TODO (mid): Check the send_http_error situations in this function */
  7424. memset(&de.file, 0, sizeof(de.file));
  7425. if (!mg_stat(conn, path, &de.file)) {
  7426. mg_cry(conn,
  7427. "%s: mg_stat(%s) failed: %s",
  7428. __func__,
  7429. path,
  7430. strerror(ERRNO));
  7431. }
  7432. if (de.file.last_modified) {
  7433. /* TODO (high): This check does not seem to make any sense ! */
  7434. send_http_error(
  7435. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7436. return;
  7437. }
  7438. body_len = conn->data_len - conn->request_len;
  7439. if (body_len > 0) {
  7440. send_http_error(
  7441. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7442. return;
  7443. }
  7444. rc = mg_mkdir(conn, path, 0755);
  7445. if (rc == 0) {
  7446. conn->status_code = 201;
  7447. gmt_time_string(date, sizeof(date), &curtime);
  7448. mg_printf(conn,
  7449. "HTTP/1.1 %d Created\r\n"
  7450. "Date: %s\r\n",
  7451. conn->status_code,
  7452. date);
  7453. send_static_cache_header(conn);
  7454. mg_printf(conn,
  7455. "Content-Length: 0\r\n"
  7456. "Connection: %s\r\n\r\n",
  7457. suggest_connection_header(conn));
  7458. } else if (rc == -1) {
  7459. if (errno == EEXIST) {
  7460. send_http_error(
  7461. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7462. } else if (errno == EACCES) {
  7463. send_http_error(
  7464. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7465. } else if (errno == ENOENT) {
  7466. send_http_error(
  7467. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7468. } else {
  7469. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7470. }
  7471. }
  7472. }
  7473. static void
  7474. put_file(struct mg_connection *conn, const char *path)
  7475. {
  7476. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7477. const char *range;
  7478. int64_t r1, r2;
  7479. int rc;
  7480. char date[64];
  7481. time_t curtime = time(NULL);
  7482. if (conn == NULL) {
  7483. return;
  7484. }
  7485. if (mg_stat(conn, path, &file.stat)) {
  7486. /* File already exists */
  7487. conn->status_code = 200;
  7488. if (file.stat.is_directory) {
  7489. /* This is an already existing directory,
  7490. * so there is nothing to do for the server. */
  7491. rc = 0;
  7492. } else {
  7493. /* File exists and is not a directory. */
  7494. /* Can it be replaced? */
  7495. if (file.access.membuf != NULL) {
  7496. /* This is an "in-memory" file, that can not be replaced */
  7497. send_http_error(
  7498. conn,
  7499. 405,
  7500. "Error: Put not possible\nReplacing %s is not supported",
  7501. path);
  7502. return;
  7503. }
  7504. /* Check if the server may write this file */
  7505. if (access(path, W_OK) == 0) {
  7506. /* Access granted */
  7507. conn->status_code = 200;
  7508. rc = 1;
  7509. } else {
  7510. send_http_error(
  7511. conn,
  7512. 403,
  7513. "Error: Put not possible\nReplacing %s is not allowed",
  7514. path);
  7515. return;
  7516. }
  7517. }
  7518. } else {
  7519. /* File should be created */
  7520. conn->status_code = 201;
  7521. rc = put_dir(conn, path);
  7522. }
  7523. if (rc == 0) {
  7524. /* put_dir returns 0 if path is a directory */
  7525. gmt_time_string(date, sizeof(date), &curtime);
  7526. mg_printf(conn,
  7527. "HTTP/1.1 %d %s\r\n",
  7528. conn->status_code,
  7529. mg_get_response_code_text(NULL, conn->status_code));
  7530. send_no_cache_header(conn);
  7531. mg_printf(conn,
  7532. "Date: %s\r\n"
  7533. "Content-Length: 0\r\n"
  7534. "Connection: %s\r\n\r\n",
  7535. date,
  7536. suggest_connection_header(conn));
  7537. /* Request to create a directory has been fulfilled successfully.
  7538. * No need to put a file. */
  7539. return;
  7540. }
  7541. if (rc == -1) {
  7542. /* put_dir returns -1 if the path is too long */
  7543. send_http_error(conn,
  7544. 414,
  7545. "Error: Path too long\nput_dir(%s): %s",
  7546. path,
  7547. strerror(ERRNO));
  7548. return;
  7549. }
  7550. if (rc == -2) {
  7551. /* put_dir returns -2 if the directory can not be created */
  7552. send_http_error(conn,
  7553. 500,
  7554. "Error: Can not create directory\nput_dir(%s): %s",
  7555. path,
  7556. strerror(ERRNO));
  7557. return;
  7558. }
  7559. /* A file should be created or overwritten. */
  7560. /* TODO: Test if write or write+read is required. */
  7561. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7562. || file.access.fp == NULL) {
  7563. (void)mg_fclose(&file.access);
  7564. send_http_error(conn,
  7565. 500,
  7566. "Error: Can not create file\nfopen(%s): %s",
  7567. path,
  7568. strerror(ERRNO));
  7569. return;
  7570. }
  7571. fclose_on_exec(&file.access, conn);
  7572. range = mg_get_header(conn, "Content-Range");
  7573. r1 = r2 = 0;
  7574. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7575. conn->status_code = 206; /* Partial content */
  7576. fseeko(file.access.fp, r1, SEEK_SET);
  7577. }
  7578. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7579. /* forward_body_data failed.
  7580. * The error code has already been sent to the client,
  7581. * and conn->status_code is already set. */
  7582. (void)mg_fclose(&file.access);
  7583. return;
  7584. }
  7585. if (mg_fclose(&file.access) != 0) {
  7586. /* fclose failed. This might have different reasons, but a likely
  7587. * one is "no space on disk", http 507. */
  7588. conn->status_code = 507;
  7589. }
  7590. gmt_time_string(date, sizeof(date), &curtime);
  7591. mg_printf(conn,
  7592. "HTTP/1.1 %d %s\r\n",
  7593. conn->status_code,
  7594. mg_get_response_code_text(NULL, conn->status_code));
  7595. send_no_cache_header(conn);
  7596. mg_printf(conn,
  7597. "Date: %s\r\n"
  7598. "Content-Length: 0\r\n"
  7599. "Connection: %s\r\n\r\n",
  7600. date,
  7601. suggest_connection_header(conn));
  7602. }
  7603. static void
  7604. delete_file(struct mg_connection *conn, const char *path)
  7605. {
  7606. struct de de;
  7607. memset(&de.file, 0, sizeof(de.file));
  7608. if (!mg_stat(conn, path, &de.file)) {
  7609. /* mg_stat returns 0 if the file does not exist */
  7610. send_http_error(conn,
  7611. 404,
  7612. "Error: Cannot delete file\nFile %s not found",
  7613. path);
  7614. return;
  7615. }
  7616. #if 0 /* Ignore if a file in memory is inside a folder */
  7617. if (de.access.membuf != NULL) {
  7618. /* the file is cached in memory */
  7619. send_http_error(
  7620. conn,
  7621. 405,
  7622. "Error: Delete not possible\nDeleting %s is not supported",
  7623. path);
  7624. return;
  7625. }
  7626. #endif
  7627. if (de.file.is_directory) {
  7628. if (remove_directory(conn, path)) {
  7629. /* Delete is successful: Return 204 without content. */
  7630. send_http_error(conn, 204, "%s", "");
  7631. } else {
  7632. /* Delete is not successful: Return 500 (Server error). */
  7633. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7634. }
  7635. return;
  7636. }
  7637. /* This is an existing file (not a directory).
  7638. * Check if write permission is granted. */
  7639. if (access(path, W_OK) != 0) {
  7640. /* File is read only */
  7641. send_http_error(
  7642. conn,
  7643. 403,
  7644. "Error: Delete not possible\nDeleting %s is not allowed",
  7645. path);
  7646. return;
  7647. }
  7648. /* Try to delete it. */
  7649. if (mg_remove(conn, path) == 0) {
  7650. /* Delete was successful: Return 204 without content. */
  7651. send_http_error(conn, 204, "%s", "");
  7652. } else {
  7653. /* Delete not successful (file locked). */
  7654. send_http_error(conn,
  7655. 423,
  7656. "Error: Cannot delete file\nremove(%s): %s",
  7657. path,
  7658. strerror(ERRNO));
  7659. }
  7660. }
  7661. #endif /* !NO_FILES */
  7662. static void
  7663. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7664. static void
  7665. do_ssi_include(struct mg_connection *conn,
  7666. const char *ssi,
  7667. char *tag,
  7668. int include_level)
  7669. {
  7670. char file_name[MG_BUF_LEN], path[512], *p;
  7671. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7672. size_t len;
  7673. int truncated = 0;
  7674. if (conn == NULL) {
  7675. return;
  7676. }
  7677. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7678. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7679. * always < MG_BUF_LEN. */
  7680. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7681. /* File name is relative to the webserver root */
  7682. file_name[511] = 0;
  7683. (void)mg_snprintf(conn,
  7684. &truncated,
  7685. path,
  7686. sizeof(path),
  7687. "%s/%s",
  7688. conn->ctx->config[DOCUMENT_ROOT],
  7689. file_name);
  7690. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7691. /* File name is relative to the webserver working directory
  7692. * or it is absolute system path */
  7693. file_name[511] = 0;
  7694. (void)
  7695. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7696. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7697. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7698. /* File name is relative to the currect document */
  7699. file_name[511] = 0;
  7700. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7701. if (!truncated) {
  7702. if ((p = strrchr(path, '/')) != NULL) {
  7703. p[1] = '\0';
  7704. }
  7705. len = strlen(path);
  7706. (void)mg_snprintf(conn,
  7707. &truncated,
  7708. path + len,
  7709. sizeof(path) - len,
  7710. "%s",
  7711. file_name);
  7712. }
  7713. } else {
  7714. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7715. return;
  7716. }
  7717. if (truncated) {
  7718. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7719. return;
  7720. }
  7721. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7722. mg_cry(conn,
  7723. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7724. tag,
  7725. path,
  7726. strerror(ERRNO));
  7727. } else {
  7728. fclose_on_exec(&file.access, conn);
  7729. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7730. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7731. path) > 0) {
  7732. send_ssi_file(conn, path, &file, include_level + 1);
  7733. } else {
  7734. send_file_data(conn, &file, 0, INT64_MAX);
  7735. }
  7736. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7737. }
  7738. }
  7739. #if !defined(NO_POPEN)
  7740. static void
  7741. do_ssi_exec(struct mg_connection *conn, char *tag)
  7742. {
  7743. char cmd[1024] = "";
  7744. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7745. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7746. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7747. } else {
  7748. cmd[1023] = 0;
  7749. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7750. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7751. } else {
  7752. send_file_data(conn, &file, 0, INT64_MAX);
  7753. pclose(file.access.fp);
  7754. }
  7755. }
  7756. }
  7757. #endif /* !NO_POPEN */
  7758. static int
  7759. mg_fgetc(struct mg_file *filep, int offset)
  7760. {
  7761. if (filep == NULL) {
  7762. return EOF;
  7763. }
  7764. if (filep->access.membuf != NULL && offset >= 0
  7765. && ((unsigned int)(offset)) < filep->stat.size) {
  7766. return ((const unsigned char *)filep->access.membuf)[offset];
  7767. } else if (filep->access.fp != NULL) {
  7768. return fgetc(filep->access.fp);
  7769. } else {
  7770. return EOF;
  7771. }
  7772. }
  7773. static void
  7774. send_ssi_file(struct mg_connection *conn,
  7775. const char *path,
  7776. struct mg_file *filep,
  7777. int include_level)
  7778. {
  7779. char buf[MG_BUF_LEN];
  7780. int ch, offset, len, in_ssi_tag;
  7781. if (include_level > 10) {
  7782. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7783. return;
  7784. }
  7785. in_ssi_tag = len = offset = 0;
  7786. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7787. if (in_ssi_tag && ch == '>') {
  7788. in_ssi_tag = 0;
  7789. buf[len++] = (char)ch;
  7790. buf[len] = '\0';
  7791. /* assert(len <= (int) sizeof(buf)); */
  7792. if (len > (int)sizeof(buf)) {
  7793. break;
  7794. }
  7795. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7796. /* Not an SSI tag, pass it */
  7797. (void)mg_write(conn, buf, (size_t)len);
  7798. } else {
  7799. if (!memcmp(buf + 5, "include", 7)) {
  7800. do_ssi_include(conn, path, buf + 12, include_level);
  7801. #if !defined(NO_POPEN)
  7802. } else if (!memcmp(buf + 5, "exec", 4)) {
  7803. do_ssi_exec(conn, buf + 9);
  7804. #endif /* !NO_POPEN */
  7805. } else {
  7806. mg_cry(conn,
  7807. "%s: unknown SSI "
  7808. "command: \"%s\"",
  7809. path,
  7810. buf);
  7811. }
  7812. }
  7813. len = 0;
  7814. } else if (in_ssi_tag) {
  7815. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7816. /* Not an SSI tag */
  7817. in_ssi_tag = 0;
  7818. } else if (len == (int)sizeof(buf) - 2) {
  7819. mg_cry(conn, "%s: SSI tag is too large", path);
  7820. len = 0;
  7821. }
  7822. buf[len++] = (char)(ch & 0xff);
  7823. } else if (ch == '<') {
  7824. in_ssi_tag = 1;
  7825. if (len > 0) {
  7826. mg_write(conn, buf, (size_t)len);
  7827. }
  7828. len = 0;
  7829. buf[len++] = (char)(ch & 0xff);
  7830. } else {
  7831. buf[len++] = (char)(ch & 0xff);
  7832. if (len == (int)sizeof(buf)) {
  7833. mg_write(conn, buf, (size_t)len);
  7834. len = 0;
  7835. }
  7836. }
  7837. }
  7838. /* Send the rest of buffered data */
  7839. if (len > 0) {
  7840. mg_write(conn, buf, (size_t)len);
  7841. }
  7842. }
  7843. static void
  7844. handle_ssi_file_request(struct mg_connection *conn,
  7845. const char *path,
  7846. struct mg_file *filep)
  7847. {
  7848. char date[64];
  7849. time_t curtime = time(NULL);
  7850. const char *cors1, *cors2, *cors3;
  7851. if (conn == NULL || path == NULL || filep == NULL) {
  7852. return;
  7853. }
  7854. if (mg_get_header(conn, "Origin")) {
  7855. /* Cross-origin resource sharing (CORS). */
  7856. cors1 = "Access-Control-Allow-Origin: ";
  7857. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7858. cors3 = "\r\n";
  7859. } else {
  7860. cors1 = cors2 = cors3 = "";
  7861. }
  7862. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7863. /* File exists (precondition for calling this function),
  7864. * but can not be opened by the server. */
  7865. send_http_error(conn,
  7866. 500,
  7867. "Error: Cannot read file\nfopen(%s): %s",
  7868. path,
  7869. strerror(ERRNO));
  7870. } else {
  7871. conn->must_close = 1;
  7872. gmt_time_string(date, sizeof(date), &curtime);
  7873. fclose_on_exec(&filep->access, conn);
  7874. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7875. send_no_cache_header(conn);
  7876. mg_printf(conn,
  7877. "%s%s%s"
  7878. "Date: %s\r\n"
  7879. "Content-Type: text/html\r\n"
  7880. "Connection: %s\r\n\r\n",
  7881. cors1,
  7882. cors2,
  7883. cors3,
  7884. date,
  7885. suggest_connection_header(conn));
  7886. send_ssi_file(conn, path, filep, 0);
  7887. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  7888. }
  7889. }
  7890. #if !defined(NO_FILES)
  7891. static void
  7892. send_options(struct mg_connection *conn)
  7893. {
  7894. char date[64];
  7895. time_t curtime = time(NULL);
  7896. if (!conn) {
  7897. return;
  7898. }
  7899. conn->status_code = 200;
  7900. conn->must_close = 1;
  7901. gmt_time_string(date, sizeof(date), &curtime);
  7902. mg_printf(conn,
  7903. "HTTP/1.1 200 OK\r\n"
  7904. "Date: %s\r\n"
  7905. /* TODO: "Cache-Control" (?) */
  7906. "Connection: %s\r\n"
  7907. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7908. "PROPFIND, MKCOL\r\n"
  7909. "DAV: 1\r\n\r\n",
  7910. date,
  7911. suggest_connection_header(conn));
  7912. }
  7913. /* Writes PROPFIND properties for a collection element */
  7914. static void
  7915. print_props(struct mg_connection *conn,
  7916. const char *uri,
  7917. struct mg_file_stat *filep)
  7918. {
  7919. char mtime[64];
  7920. if (conn == NULL || uri == NULL || filep == NULL) {
  7921. return;
  7922. }
  7923. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7924. conn->num_bytes_sent +=
  7925. mg_printf(conn,
  7926. "<d:response>"
  7927. "<d:href>%s</d:href>"
  7928. "<d:propstat>"
  7929. "<d:prop>"
  7930. "<d:resourcetype>%s</d:resourcetype>"
  7931. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7932. "<d:getlastmodified>%s</d:getlastmodified>"
  7933. "</d:prop>"
  7934. "<d:status>HTTP/1.1 200 OK</d:status>"
  7935. "</d:propstat>"
  7936. "</d:response>\n",
  7937. uri,
  7938. filep->is_directory ? "<d:collection/>" : "",
  7939. filep->size,
  7940. mtime);
  7941. }
  7942. static void
  7943. print_dav_dir_entry(struct de *de, void *data)
  7944. {
  7945. char href[PATH_MAX];
  7946. char href_encoded[PATH_MAX * 3 /* worst case */];
  7947. int truncated;
  7948. struct mg_connection *conn = (struct mg_connection *)data;
  7949. if (!de || !conn) {
  7950. return;
  7951. }
  7952. mg_snprintf(conn,
  7953. &truncated,
  7954. href,
  7955. sizeof(href),
  7956. "%s%s",
  7957. conn->request_info.local_uri,
  7958. de->file_name);
  7959. if (!truncated) {
  7960. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7961. print_props(conn, href_encoded, &de->file);
  7962. }
  7963. }
  7964. static void
  7965. handle_propfind(struct mg_connection *conn,
  7966. const char *path,
  7967. struct mg_file_stat *filep)
  7968. {
  7969. const char *depth = mg_get_header(conn, "Depth");
  7970. char date[64];
  7971. time_t curtime = time(NULL);
  7972. gmt_time_string(date, sizeof(date), &curtime);
  7973. if (!conn || !path || !filep || !conn->ctx) {
  7974. return;
  7975. }
  7976. conn->must_close = 1;
  7977. conn->status_code = 207;
  7978. mg_printf(conn,
  7979. "HTTP/1.1 207 Multi-Status\r\n"
  7980. "Date: %s\r\n",
  7981. date);
  7982. send_static_cache_header(conn);
  7983. mg_printf(conn,
  7984. "Connection: %s\r\n"
  7985. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7986. suggest_connection_header(conn));
  7987. conn->num_bytes_sent +=
  7988. mg_printf(conn,
  7989. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7990. "<d:multistatus xmlns:d='DAV:'>\n");
  7991. /* Print properties for the requested resource itself */
  7992. print_props(conn, conn->request_info.local_uri, filep);
  7993. /* If it is a directory, print directory entries too if Depth is not 0 */
  7994. if (filep && filep->is_directory
  7995. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7996. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7997. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7998. }
  7999. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8000. }
  8001. #endif
  8002. void
  8003. mg_lock_connection(struct mg_connection *conn)
  8004. {
  8005. if (conn) {
  8006. (void)pthread_mutex_lock(&conn->mutex);
  8007. }
  8008. }
  8009. void
  8010. mg_unlock_connection(struct mg_connection *conn)
  8011. {
  8012. if (conn) {
  8013. (void)pthread_mutex_unlock(&conn->mutex);
  8014. }
  8015. }
  8016. void
  8017. mg_lock_context(struct mg_context *ctx)
  8018. {
  8019. if (ctx) {
  8020. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8021. }
  8022. }
  8023. void
  8024. mg_unlock_context(struct mg_context *ctx)
  8025. {
  8026. if (ctx) {
  8027. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8028. }
  8029. }
  8030. #if defined(USE_TIMERS)
  8031. #include "timer.inl"
  8032. #endif /* USE_TIMERS */
  8033. #ifdef USE_LUA
  8034. #include "mod_lua.inl"
  8035. #endif /* USE_LUA */
  8036. #ifdef USE_DUKTAPE
  8037. #include "mod_duktape.inl"
  8038. #endif /* USE_DUKTAPE */
  8039. #if defined(USE_WEBSOCKET)
  8040. #define SHA_API static
  8041. #include "sha1.inl"
  8042. static int
  8043. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8044. {
  8045. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8046. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8047. SHA1_CTX sha_ctx;
  8048. int truncated;
  8049. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8050. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8051. if (truncated) {
  8052. conn->must_close = 1;
  8053. return 0;
  8054. }
  8055. SHA1_Init(&sha_ctx);
  8056. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8057. SHA1_Final(&sha_ctx, (unsigned char *)sha);
  8058. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8059. mg_printf(conn,
  8060. "HTTP/1.1 101 Switching Protocols\r\n"
  8061. "Upgrade: websocket\r\n"
  8062. "Connection: Upgrade\r\n"
  8063. "Sec-WebSocket-Accept: %s\r\n",
  8064. b64_sha);
  8065. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8066. mg_printf(conn,
  8067. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8068. conn->request_info.acceptedWebSocketSubprotocol);
  8069. } else {
  8070. mg_printf(conn, "%s", "\r\n");
  8071. }
  8072. return 1;
  8073. }
  8074. static void
  8075. read_websocket(struct mg_connection *conn,
  8076. mg_websocket_data_handler ws_data_handler,
  8077. void *callback_data)
  8078. {
  8079. /* Pointer to the beginning of the portion of the incoming websocket
  8080. * message queue.
  8081. * The original websocket upgrade request is never removed, so the queue
  8082. * begins after it. */
  8083. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8084. int n, error, exit_by_callback;
  8085. /* body_len is the length of the entire queue in bytes
  8086. * len is the length of the current message
  8087. * data_len is the length of the current message's data payload
  8088. * header_len is the length of the current message's header */
  8089. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8090. /* "The masking key is a 32-bit value chosen at random by the client."
  8091. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8092. */
  8093. unsigned char mask[4];
  8094. /* data points to the place where the message is stored when passed to
  8095. * the
  8096. * websocket_data callback. This is either mem on the stack, or a
  8097. * dynamically allocated buffer if it is too large. */
  8098. unsigned char mem[4096];
  8099. unsigned char *data = mem;
  8100. unsigned char mop; /* mask flag and opcode */
  8101. double timeout = -1.0;
  8102. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8103. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8104. }
  8105. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8106. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8107. }
  8108. mg_set_thread_name("wsock");
  8109. /* Loop continuously, reading messages from the socket, invoking the
  8110. * callback, and waiting repeatedly until an error occurs. */
  8111. while (!conn->ctx->stop_flag) {
  8112. header_len = 0;
  8113. assert(conn->data_len >= conn->request_len);
  8114. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8115. len = buf[1] & 127;
  8116. mask_len = (buf[1] & 128) ? 4 : 0;
  8117. if ((len < 126) && (body_len >= mask_len)) {
  8118. data_len = len;
  8119. header_len = 2 + mask_len;
  8120. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8121. header_len = 4 + mask_len;
  8122. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8123. } else if (body_len >= (10 + mask_len)) {
  8124. header_len = 10 + mask_len;
  8125. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8126. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8127. }
  8128. }
  8129. if (header_len > 0 && body_len >= header_len) {
  8130. /* Allocate space to hold websocket payload */
  8131. data = mem;
  8132. if (data_len > sizeof(mem)) {
  8133. data = (unsigned char *)mg_malloc(data_len);
  8134. if (data == NULL) {
  8135. /* Allocation failed, exit the loop and then close the
  8136. * connection */
  8137. mg_cry(conn, "websocket out of memory; closing connection");
  8138. break;
  8139. }
  8140. }
  8141. /* Copy the mask before we shift the queue and destroy it */
  8142. if (mask_len > 0) {
  8143. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8144. } else {
  8145. memset(mask, 0, sizeof(mask));
  8146. }
  8147. /* Read frame payload from the first message in the queue into
  8148. * data and advance the queue by moving the memory in place. */
  8149. assert(body_len >= header_len);
  8150. if (data_len + header_len > body_len) {
  8151. mop = buf[0]; /* current mask and opcode */
  8152. /* Overflow case */
  8153. len = body_len - header_len;
  8154. memcpy(data, buf + header_len, len);
  8155. error = 0;
  8156. while (len < data_len) {
  8157. n = pull(NULL,
  8158. conn,
  8159. (char *)(data + len),
  8160. (int)(data_len - len),
  8161. timeout);
  8162. if (n <= 0) {
  8163. error = 1;
  8164. break;
  8165. }
  8166. len += (size_t)n;
  8167. }
  8168. if (error) {
  8169. mg_cry(conn, "Websocket pull failed; closing connection");
  8170. break;
  8171. }
  8172. conn->data_len = conn->request_len;
  8173. } else {
  8174. mop = buf[0]; /* current mask and opcode, overwritten by
  8175. * memmove() */
  8176. /* Length of the message being read at the front of the
  8177. * queue */
  8178. len = data_len + header_len;
  8179. /* Copy the data payload into the data pointer for the
  8180. * callback */
  8181. memcpy(data, buf + header_len, data_len);
  8182. /* Move the queue forward len bytes */
  8183. memmove(buf, buf + len, body_len - len);
  8184. /* Mark the queue as advanced */
  8185. conn->data_len -= (int)len;
  8186. }
  8187. /* Apply mask if necessary */
  8188. if (mask_len > 0) {
  8189. for (i = 0; i < data_len; ++i) {
  8190. data[i] ^= mask[i & 3];
  8191. }
  8192. }
  8193. /* Exit the loop if callback signals to exit (server side),
  8194. * or "connection close" opcode received (client side). */
  8195. exit_by_callback = 0;
  8196. if ((ws_data_handler != NULL)
  8197. && !ws_data_handler(
  8198. conn, mop, (char *)data, data_len, callback_data)) {
  8199. exit_by_callback = 1;
  8200. }
  8201. if (data != mem) {
  8202. mg_free(data);
  8203. }
  8204. if (exit_by_callback
  8205. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8206. /* Opcode == 8, connection close */
  8207. break;
  8208. }
  8209. /* Not breaking the loop, process next websocket frame. */
  8210. } else {
  8211. /* Read from the socket into the next available location in the
  8212. * message queue. */
  8213. if ((n = pull(NULL,
  8214. conn,
  8215. conn->buf + conn->data_len,
  8216. conn->buf_size - conn->data_len,
  8217. timeout)) <= 0) {
  8218. /* Error, no bytes read */
  8219. break;
  8220. }
  8221. conn->data_len += n;
  8222. }
  8223. }
  8224. mg_set_thread_name("worker");
  8225. }
  8226. static int
  8227. mg_websocket_write_exec(struct mg_connection *conn,
  8228. int opcode,
  8229. const char *data,
  8230. size_t dataLen,
  8231. uint32_t masking_key)
  8232. {
  8233. unsigned char header[14];
  8234. size_t headerLen = 1;
  8235. int retval = -1;
  8236. #if defined(__GNUC__) || defined(__MINGW32__)
  8237. /* Disable spurious conversion warning for GCC */
  8238. #pragma GCC diagnostic push
  8239. #pragma GCC diagnostic ignored "-Wconversion"
  8240. #endif
  8241. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8242. #if defined(__GNUC__) || defined(__MINGW32__)
  8243. #pragma GCC diagnostic pop
  8244. #endif
  8245. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8246. if (dataLen < 126) {
  8247. /* inline 7-bit length field */
  8248. header[1] = (unsigned char)dataLen;
  8249. headerLen = 2;
  8250. } else if (dataLen <= 0xFFFF) {
  8251. /* 16-bit length field */
  8252. uint16_t len = htons((uint16_t)dataLen);
  8253. header[1] = 126;
  8254. memcpy(header + 2, &len, 2);
  8255. headerLen = 4;
  8256. } else {
  8257. /* 64-bit length field */
  8258. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8259. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8260. header[1] = 127;
  8261. memcpy(header + 2, &len1, 4);
  8262. memcpy(header + 6, &len2, 4);
  8263. headerLen = 10;
  8264. }
  8265. if (masking_key) {
  8266. /* add mask */
  8267. header[1] |= 0x80;
  8268. memcpy(header + headerLen, &masking_key, 4);
  8269. headerLen += 4;
  8270. }
  8271. /* Note that POSIX/Winsock's send() is threadsafe
  8272. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8273. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8274. * push(), although that is only a problem if the packet is large or
  8275. * outgoing buffer is full). */
  8276. (void)mg_lock_connection(conn);
  8277. retval = mg_write(conn, header, headerLen);
  8278. if (dataLen > 0) {
  8279. retval = mg_write(conn, data, dataLen);
  8280. }
  8281. mg_unlock_connection(conn);
  8282. return retval;
  8283. }
  8284. int
  8285. mg_websocket_write(struct mg_connection *conn,
  8286. int opcode,
  8287. const char *data,
  8288. size_t dataLen)
  8289. {
  8290. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8291. }
  8292. static void
  8293. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8294. {
  8295. size_t i = 0;
  8296. i = 0;
  8297. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8298. /* Convert in 32 bit words, if data is 4 byte aligned */
  8299. while (i < (in_len - 3)) {
  8300. *(uint32_t *)(void *)(out + i) =
  8301. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8302. i += 4;
  8303. }
  8304. }
  8305. if (i != in_len) {
  8306. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8307. while (i < in_len) {
  8308. *(uint8_t *)(void *)(out + i) =
  8309. *(uint8_t *)(void *)(in + i)
  8310. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8311. i++;
  8312. }
  8313. }
  8314. }
  8315. int
  8316. mg_websocket_client_write(struct mg_connection *conn,
  8317. int opcode,
  8318. const char *data,
  8319. size_t dataLen)
  8320. {
  8321. int retval = -1;
  8322. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8323. uint32_t masking_key = (uint32_t)get_random();
  8324. if (masked_data == NULL) {
  8325. /* Return -1 in an error case */
  8326. mg_cry(conn,
  8327. "Cannot allocate buffer for masked websocket response: "
  8328. "Out of memory");
  8329. return -1;
  8330. }
  8331. mask_data(data, dataLen, masking_key, masked_data);
  8332. retval = mg_websocket_write_exec(
  8333. conn, opcode, masked_data, dataLen, masking_key);
  8334. mg_free(masked_data);
  8335. return retval;
  8336. }
  8337. static void
  8338. handle_websocket_request(struct mg_connection *conn,
  8339. const char *path,
  8340. int is_callback_resource,
  8341. struct mg_websocket_subprotocols *subprotocols,
  8342. mg_websocket_connect_handler ws_connect_handler,
  8343. mg_websocket_ready_handler ws_ready_handler,
  8344. mg_websocket_data_handler ws_data_handler,
  8345. mg_websocket_close_handler ws_close_handler,
  8346. void *cbData)
  8347. {
  8348. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8349. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8350. int lua_websock = 0;
  8351. #if !defined(USE_LUA)
  8352. (void)path;
  8353. #endif
  8354. /* Step 1: Check websocket protocol version. */
  8355. /* Step 1.1: Check Sec-WebSocket-Key. */
  8356. if (!websock_key) {
  8357. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8358. * requires a Sec-WebSocket-Key header.
  8359. */
  8360. /* It could be the hixie draft version
  8361. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8362. */
  8363. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8364. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8365. char key3[8];
  8366. if ((key1 != NULL) && (key2 != NULL)) {
  8367. /* This version uses 8 byte body data in a GET request */
  8368. conn->content_len = 8;
  8369. if (8 == mg_read(conn, key3, 8)) {
  8370. /* This is the hixie version */
  8371. send_http_error(conn,
  8372. 426,
  8373. "%s",
  8374. "Protocol upgrade to RFC 6455 required");
  8375. return;
  8376. }
  8377. }
  8378. /* This is an unknown version */
  8379. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8380. return;
  8381. }
  8382. /* Step 1.2: Check websocket protocol version. */
  8383. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8384. if (version == NULL || strcmp(version, "13") != 0) {
  8385. /* Reject wrong versions */
  8386. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8387. return;
  8388. }
  8389. /* Step 1.3: Could check for "Host", but we do not really nead this
  8390. * value for anything, so just ignore it. */
  8391. /* Step 2: If a callback is responsible, call it. */
  8392. if (is_callback_resource) {
  8393. /* Step 2.1 check and select subprotocol */
  8394. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8395. if (protocol && subprotocols) {
  8396. int idx;
  8397. unsigned long len;
  8398. const char *sep, *curSubProtocol,
  8399. *acceptedWebSocketSubprotocol = NULL;
  8400. /* look for matching subprotocol */
  8401. do {
  8402. sep = strchr(protocol, ',');
  8403. curSubProtocol = protocol;
  8404. len = sep ? (unsigned long)(sep - protocol)
  8405. : (unsigned long)strlen(protocol);
  8406. while (sep && isspace(*++sep)) {
  8407. ; /* ignore leading whitespaces */
  8408. }
  8409. protocol = sep;
  8410. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8411. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8412. && (strncmp(curSubProtocol,
  8413. subprotocols->subprotocols[idx],
  8414. len) == 0)) {
  8415. acceptedWebSocketSubprotocol =
  8416. subprotocols->subprotocols[idx];
  8417. break;
  8418. }
  8419. }
  8420. } while (sep && !acceptedWebSocketSubprotocol);
  8421. conn->request_info.acceptedWebSocketSubprotocol =
  8422. acceptedWebSocketSubprotocol;
  8423. } else if (protocol) {
  8424. /* keep legacy behavior */
  8425. /* The protocol is a comma seperated list of names. */
  8426. /* The server must only return one value from this list. */
  8427. /* First check if it is a list or just a single value. */
  8428. const char *sep = strrchr(protocol, ',');
  8429. if (sep == NULL) {
  8430. /* Just a single protocol -> accept it. */
  8431. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8432. } else {
  8433. /* Multiple protocols -> accept the last one. */
  8434. /* This is just a quick fix if the client offers multiple
  8435. * protocols. The handler should have a list of accepted
  8436. * protocols on his own
  8437. * and use it to select one protocol among those the client has
  8438. * offered.
  8439. */
  8440. while (isspace(*++sep)) {
  8441. ; /* ignore leading whitespaces */
  8442. }
  8443. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8444. }
  8445. }
  8446. if (ws_connect_handler != NULL
  8447. && ws_connect_handler(conn, cbData) != 0) {
  8448. /* C callback has returned non-zero, do not proceed with
  8449. * handshake.
  8450. */
  8451. /* Note that C callbacks are no longer called when Lua is
  8452. * responsible, so C can no longer filter callbacks for Lua. */
  8453. return;
  8454. }
  8455. }
  8456. #if defined(USE_LUA)
  8457. /* Step 3: No callback. Check if Lua is responsible. */
  8458. else {
  8459. /* Step 3.1: Check if Lua is responsible. */
  8460. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8461. lua_websock =
  8462. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8463. strlen(
  8464. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8465. path);
  8466. }
  8467. if (lua_websock) {
  8468. /* Step 3.2: Lua is responsible: call it. */
  8469. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8470. if (!conn->lua_websocket_state) {
  8471. /* Lua rejected the new client */
  8472. return;
  8473. }
  8474. }
  8475. }
  8476. #endif
  8477. /* Step 4: Check if there is a responsible websocket handler. */
  8478. if (!is_callback_resource && !lua_websock) {
  8479. /* There is no callback, and Lua is not responsible either. */
  8480. /* Reply with a 404 Not Found or with nothing at all?
  8481. * TODO (mid): check the websocket standards, how to reply to
  8482. * requests to invalid websocket addresses. */
  8483. send_http_error(conn, 404, "%s", "Not found");
  8484. return;
  8485. }
  8486. /* Step 5: The websocket connection has been accepted */
  8487. if (!send_websocket_handshake(conn, websock_key)) {
  8488. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8489. return;
  8490. }
  8491. /* Step 6: Call the ready handler */
  8492. if (is_callback_resource) {
  8493. if (ws_ready_handler != NULL) {
  8494. ws_ready_handler(conn, cbData);
  8495. }
  8496. #if defined(USE_LUA)
  8497. } else if (lua_websock) {
  8498. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8499. /* the ready handler returned false */
  8500. return;
  8501. }
  8502. #endif
  8503. }
  8504. /* Step 7: Enter the read loop */
  8505. if (is_callback_resource) {
  8506. read_websocket(conn, ws_data_handler, cbData);
  8507. #if defined(USE_LUA)
  8508. } else if (lua_websock) {
  8509. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8510. #endif
  8511. }
  8512. /* Step 8: Call the close handler */
  8513. if (ws_close_handler) {
  8514. ws_close_handler(conn, cbData);
  8515. }
  8516. }
  8517. static int
  8518. is_websocket_protocol(const struct mg_connection *conn)
  8519. {
  8520. const char *upgrade, *connection;
  8521. /* A websocket protocoll has the following HTTP headers:
  8522. *
  8523. * Connection: Upgrade
  8524. * Upgrade: Websocket
  8525. */
  8526. upgrade = mg_get_header(conn, "Upgrade");
  8527. if (upgrade == NULL) {
  8528. return 0; /* fail early, don't waste time checking other header
  8529. * fields
  8530. */
  8531. }
  8532. if (!mg_strcasestr(upgrade, "websocket")) {
  8533. return 0;
  8534. }
  8535. connection = mg_get_header(conn, "Connection");
  8536. if (connection == NULL) {
  8537. return 0;
  8538. }
  8539. if (!mg_strcasestr(connection, "upgrade")) {
  8540. return 0;
  8541. }
  8542. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8543. * "Sec-WebSocket-Version" are also required.
  8544. * Don't check them here, since even an unsupported websocket protocol
  8545. * request still IS a websocket request (in contrast to a standard HTTP
  8546. * request). It will fail later in handle_websocket_request.
  8547. */
  8548. return 1;
  8549. }
  8550. #endif /* !USE_WEBSOCKET */
  8551. static int
  8552. isbyte(int n)
  8553. {
  8554. return n >= 0 && n <= 255;
  8555. }
  8556. static int
  8557. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8558. {
  8559. int n, a, b, c, d, slash = 32, len = 0;
  8560. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8561. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8562. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8563. && slash < 33) {
  8564. len = n;
  8565. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8566. | (uint32_t)d;
  8567. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8568. }
  8569. return len;
  8570. }
  8571. static int
  8572. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8573. {
  8574. int throttle = 0;
  8575. struct vec vec, val;
  8576. uint32_t net, mask;
  8577. char mult;
  8578. double v;
  8579. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8580. mult = ',';
  8581. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8582. || (v < 0) || ((lowercase(&mult) != 'k')
  8583. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8584. continue;
  8585. }
  8586. v *= (lowercase(&mult) == 'k')
  8587. ? 1024
  8588. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8589. if (vec.len == 1 && vec.ptr[0] == '*') {
  8590. throttle = (int)v;
  8591. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8592. if ((remote_ip & mask) == net) {
  8593. throttle = (int)v;
  8594. }
  8595. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8596. throttle = (int)v;
  8597. }
  8598. }
  8599. return throttle;
  8600. }
  8601. static uint32_t
  8602. get_remote_ip(const struct mg_connection *conn)
  8603. {
  8604. if (!conn) {
  8605. return 0;
  8606. }
  8607. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8608. }
  8609. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8610. #include "handle_form.inl"
  8611. #if defined(MG_LEGACY_INTERFACE)
  8612. /* Implement the deprecated mg_upload function by calling the new
  8613. * mg_handle_form_request function. While mg_upload could only handle
  8614. * HTML forms sent as POST request in multipart/form-data format
  8615. * containing only file input elements, mg_handle_form_request can
  8616. * handle all form input elements and all standard request methods. */
  8617. struct mg_upload_user_data {
  8618. struct mg_connection *conn;
  8619. const char *destination_dir;
  8620. int num_uploaded_files;
  8621. };
  8622. /* Helper function for deprecated mg_upload. */
  8623. static int
  8624. mg_upload_field_found(const char *key,
  8625. const char *filename,
  8626. char *path,
  8627. size_t pathlen,
  8628. void *user_data)
  8629. {
  8630. int truncated = 0;
  8631. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8632. (void)key;
  8633. if (!filename) {
  8634. mg_cry(fud->conn, "%s: No filename set", __func__);
  8635. return FORM_FIELD_STORAGE_ABORT;
  8636. }
  8637. mg_snprintf(fud->conn,
  8638. &truncated,
  8639. path,
  8640. pathlen - 1,
  8641. "%s/%s",
  8642. fud->destination_dir,
  8643. filename);
  8644. if (!truncated) {
  8645. mg_cry(fud->conn, "%s: File path too long", __func__);
  8646. return FORM_FIELD_STORAGE_ABORT;
  8647. }
  8648. return FORM_FIELD_STORAGE_STORE;
  8649. }
  8650. /* Helper function for deprecated mg_upload. */
  8651. static int
  8652. mg_upload_field_get(const char *key,
  8653. const char *value,
  8654. size_t value_size,
  8655. void *user_data)
  8656. {
  8657. /* Function should never be called */
  8658. (void)key;
  8659. (void)value;
  8660. (void)value_size;
  8661. (void)user_data;
  8662. return 0;
  8663. }
  8664. /* Helper function for deprecated mg_upload. */
  8665. static int
  8666. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8667. {
  8668. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8669. (void)file_size;
  8670. fud->num_uploaded_files++;
  8671. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8672. return 0;
  8673. }
  8674. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8675. int
  8676. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8677. {
  8678. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8679. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8680. mg_upload_field_get,
  8681. mg_upload_field_stored,
  8682. 0};
  8683. int ret;
  8684. fdh.user_data = (void *)&fud;
  8685. ret = mg_handle_form_request(conn, &fdh);
  8686. if (ret < 0) {
  8687. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8688. }
  8689. return fud.num_uploaded_files;
  8690. }
  8691. #endif
  8692. static int
  8693. get_first_ssl_listener_index(const struct mg_context *ctx)
  8694. {
  8695. unsigned int i;
  8696. int idx = -1;
  8697. if (ctx) {
  8698. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8699. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8700. }
  8701. }
  8702. return idx;
  8703. }
  8704. static void
  8705. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8706. {
  8707. char host[1025];
  8708. const char *host_header;
  8709. size_t hostlen;
  8710. host_header = mg_get_header(conn, "Host");
  8711. hostlen = sizeof(host);
  8712. if (host_header != NULL) {
  8713. char *pos;
  8714. mg_strlcpy(host, host_header, hostlen);
  8715. host[hostlen - 1] = '\0';
  8716. pos = strchr(host, ':');
  8717. if (pos != NULL) {
  8718. *pos = '\0';
  8719. }
  8720. } else {
  8721. /* Cannot get host from the Host: header.
  8722. * Fallback to our IP address. */
  8723. if (conn) {
  8724. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8725. }
  8726. }
  8727. /* Send host, port, uri and (if it exists) ?query_string */
  8728. if (conn) {
  8729. mg_printf(conn,
  8730. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8731. host,
  8732. #if defined(USE_IPV6)
  8733. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8734. == AF_INET6)
  8735. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8736. .lsa.sin6.sin6_port)
  8737. :
  8738. #endif
  8739. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8740. .lsa.sin.sin_port),
  8741. conn->request_info.local_uri,
  8742. (conn->request_info.query_string == NULL) ? "" : "?",
  8743. (conn->request_info.query_string == NULL)
  8744. ? ""
  8745. : conn->request_info.query_string);
  8746. }
  8747. }
  8748. static void
  8749. mg_set_handler_type(struct mg_context *ctx,
  8750. const char *uri,
  8751. int handler_type,
  8752. int is_delete_request,
  8753. mg_request_handler handler,
  8754. struct mg_websocket_subprotocols *subprotocols,
  8755. mg_websocket_connect_handler connect_handler,
  8756. mg_websocket_ready_handler ready_handler,
  8757. mg_websocket_data_handler data_handler,
  8758. mg_websocket_close_handler close_handler,
  8759. mg_authorization_handler auth_handler,
  8760. void *cbdata)
  8761. {
  8762. struct mg_handler_info *tmp_rh, **lastref;
  8763. size_t urilen = strlen(uri);
  8764. if (handler_type == WEBSOCKET_HANDLER) {
  8765. /* assert(handler == NULL); */
  8766. /* assert(is_delete_request || connect_handler!=NULL ||
  8767. * ready_handler!=NULL || data_handler!=NULL ||
  8768. * close_handler!=NULL);
  8769. */
  8770. /* assert(auth_handler == NULL); */
  8771. if (handler != NULL) {
  8772. return;
  8773. }
  8774. if (!is_delete_request && connect_handler == NULL
  8775. && ready_handler == NULL
  8776. && data_handler == NULL
  8777. && close_handler == NULL) {
  8778. return;
  8779. }
  8780. if (auth_handler != NULL) {
  8781. return;
  8782. }
  8783. } else if (handler_type == REQUEST_HANDLER) {
  8784. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8785. * data_handler==NULL && close_handler==NULL); */
  8786. /* assert(is_delete_request || (handler!=NULL));
  8787. */
  8788. /* assert(auth_handler == NULL); */
  8789. if (connect_handler != NULL || ready_handler != NULL
  8790. || data_handler != NULL
  8791. || close_handler != NULL) {
  8792. return;
  8793. }
  8794. if (!is_delete_request && (handler == NULL)) {
  8795. return;
  8796. }
  8797. if (auth_handler != NULL) {
  8798. return;
  8799. }
  8800. } else { /* AUTH_HANDLER */
  8801. /* assert(handler == NULL); */
  8802. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8803. * data_handler==NULL && close_handler==NULL); */
  8804. /* assert(auth_handler != NULL); */
  8805. if (handler != NULL) {
  8806. return;
  8807. }
  8808. if (connect_handler != NULL || ready_handler != NULL
  8809. || data_handler != NULL
  8810. || close_handler != NULL) {
  8811. return;
  8812. }
  8813. if (!is_delete_request && (auth_handler == NULL)) {
  8814. return;
  8815. }
  8816. }
  8817. if (!ctx) {
  8818. return;
  8819. }
  8820. mg_lock_context(ctx);
  8821. /* first try to find an existing handler */
  8822. lastref = &(ctx->handlers);
  8823. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8824. if (tmp_rh->handler_type == handler_type) {
  8825. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8826. if (!is_delete_request) {
  8827. /* update existing handler */
  8828. if (handler_type == REQUEST_HANDLER) {
  8829. tmp_rh->handler = handler;
  8830. } else if (handler_type == WEBSOCKET_HANDLER) {
  8831. tmp_rh->subprotocols = subprotocols;
  8832. tmp_rh->connect_handler = connect_handler;
  8833. tmp_rh->ready_handler = ready_handler;
  8834. tmp_rh->data_handler = data_handler;
  8835. tmp_rh->close_handler = close_handler;
  8836. } else { /* AUTH_HANDLER */
  8837. tmp_rh->auth_handler = auth_handler;
  8838. }
  8839. tmp_rh->cbdata = cbdata;
  8840. } else {
  8841. /* remove existing handler */
  8842. *lastref = tmp_rh->next;
  8843. mg_free(tmp_rh->uri);
  8844. mg_free(tmp_rh);
  8845. }
  8846. mg_unlock_context(ctx);
  8847. return;
  8848. }
  8849. }
  8850. lastref = &(tmp_rh->next);
  8851. }
  8852. if (is_delete_request) {
  8853. /* no handler to set, this was a remove request to a non-existing
  8854. * handler */
  8855. mg_unlock_context(ctx);
  8856. return;
  8857. }
  8858. tmp_rh =
  8859. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8860. if (tmp_rh == NULL) {
  8861. mg_unlock_context(ctx);
  8862. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8863. return;
  8864. }
  8865. tmp_rh->uri = mg_strdup(uri);
  8866. if (!tmp_rh->uri) {
  8867. mg_unlock_context(ctx);
  8868. mg_free(tmp_rh);
  8869. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8870. return;
  8871. }
  8872. tmp_rh->uri_len = urilen;
  8873. if (handler_type == REQUEST_HANDLER) {
  8874. tmp_rh->handler = handler;
  8875. } else if (handler_type == WEBSOCKET_HANDLER) {
  8876. tmp_rh->subprotocols = subprotocols;
  8877. tmp_rh->connect_handler = connect_handler;
  8878. tmp_rh->ready_handler = ready_handler;
  8879. tmp_rh->data_handler = data_handler;
  8880. tmp_rh->close_handler = close_handler;
  8881. } else { /* AUTH_HANDLER */
  8882. tmp_rh->auth_handler = auth_handler;
  8883. }
  8884. tmp_rh->cbdata = cbdata;
  8885. tmp_rh->handler_type = handler_type;
  8886. tmp_rh->next = NULL;
  8887. *lastref = tmp_rh;
  8888. mg_unlock_context(ctx);
  8889. }
  8890. void
  8891. mg_set_request_handler(struct mg_context *ctx,
  8892. const char *uri,
  8893. mg_request_handler handler,
  8894. void *cbdata)
  8895. {
  8896. mg_set_handler_type(ctx,
  8897. uri,
  8898. REQUEST_HANDLER,
  8899. handler == NULL,
  8900. handler,
  8901. NULL,
  8902. NULL,
  8903. NULL,
  8904. NULL,
  8905. NULL,
  8906. NULL,
  8907. cbdata);
  8908. }
  8909. void
  8910. mg_set_websocket_handler(struct mg_context *ctx,
  8911. const char *uri,
  8912. mg_websocket_connect_handler connect_handler,
  8913. mg_websocket_ready_handler ready_handler,
  8914. mg_websocket_data_handler data_handler,
  8915. mg_websocket_close_handler close_handler,
  8916. void *cbdata)
  8917. {
  8918. mg_set_websocket_handler_with_subprotocols(ctx,
  8919. uri,
  8920. NULL,
  8921. connect_handler,
  8922. ready_handler,
  8923. data_handler,
  8924. close_handler,
  8925. cbdata);
  8926. }
  8927. void
  8928. mg_set_websocket_handler_with_subprotocols(
  8929. struct mg_context *ctx,
  8930. const char *uri,
  8931. struct mg_websocket_subprotocols *subprotocols,
  8932. mg_websocket_connect_handler connect_handler,
  8933. mg_websocket_ready_handler ready_handler,
  8934. mg_websocket_data_handler data_handler,
  8935. mg_websocket_close_handler close_handler,
  8936. void *cbdata)
  8937. {
  8938. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8939. && (data_handler == NULL)
  8940. && (close_handler == NULL);
  8941. mg_set_handler_type(ctx,
  8942. uri,
  8943. WEBSOCKET_HANDLER,
  8944. is_delete_request,
  8945. NULL,
  8946. subprotocols,
  8947. connect_handler,
  8948. ready_handler,
  8949. data_handler,
  8950. close_handler,
  8951. NULL,
  8952. cbdata);
  8953. }
  8954. void
  8955. mg_set_auth_handler(struct mg_context *ctx,
  8956. const char *uri,
  8957. mg_request_handler handler,
  8958. void *cbdata)
  8959. {
  8960. mg_set_handler_type(ctx,
  8961. uri,
  8962. AUTH_HANDLER,
  8963. handler == NULL,
  8964. NULL,
  8965. NULL,
  8966. NULL,
  8967. NULL,
  8968. NULL,
  8969. NULL,
  8970. handler,
  8971. cbdata);
  8972. }
  8973. static int
  8974. get_request_handler(struct mg_connection *conn,
  8975. int handler_type,
  8976. mg_request_handler *handler,
  8977. struct mg_websocket_subprotocols **subprotocols,
  8978. mg_websocket_connect_handler *connect_handler,
  8979. mg_websocket_ready_handler *ready_handler,
  8980. mg_websocket_data_handler *data_handler,
  8981. mg_websocket_close_handler *close_handler,
  8982. mg_authorization_handler *auth_handler,
  8983. void **cbdata)
  8984. {
  8985. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8986. if (request_info) {
  8987. const char *uri = request_info->local_uri;
  8988. size_t urilen = strlen(uri);
  8989. struct mg_handler_info *tmp_rh;
  8990. if (!conn || !conn->ctx) {
  8991. return 0;
  8992. }
  8993. mg_lock_context(conn->ctx);
  8994. /* first try for an exact match */
  8995. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8996. tmp_rh = tmp_rh->next) {
  8997. if (tmp_rh->handler_type == handler_type) {
  8998. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8999. if (handler_type == WEBSOCKET_HANDLER) {
  9000. *subprotocols = tmp_rh->subprotocols;
  9001. *connect_handler = tmp_rh->connect_handler;
  9002. *ready_handler = tmp_rh->ready_handler;
  9003. *data_handler = tmp_rh->data_handler;
  9004. *close_handler = tmp_rh->close_handler;
  9005. } else if (handler_type == REQUEST_HANDLER) {
  9006. *handler = tmp_rh->handler;
  9007. } else { /* AUTH_HANDLER */
  9008. *auth_handler = tmp_rh->auth_handler;
  9009. }
  9010. *cbdata = tmp_rh->cbdata;
  9011. mg_unlock_context(conn->ctx);
  9012. return 1;
  9013. }
  9014. }
  9015. }
  9016. /* next try for a partial match, we will accept uri/something */
  9017. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9018. tmp_rh = tmp_rh->next) {
  9019. if (tmp_rh->handler_type == handler_type) {
  9020. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9021. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9022. if (handler_type == WEBSOCKET_HANDLER) {
  9023. *subprotocols = tmp_rh->subprotocols;
  9024. *connect_handler = tmp_rh->connect_handler;
  9025. *ready_handler = tmp_rh->ready_handler;
  9026. *data_handler = tmp_rh->data_handler;
  9027. *close_handler = tmp_rh->close_handler;
  9028. } else if (handler_type == REQUEST_HANDLER) {
  9029. *handler = tmp_rh->handler;
  9030. } else { /* AUTH_HANDLER */
  9031. *auth_handler = tmp_rh->auth_handler;
  9032. }
  9033. *cbdata = tmp_rh->cbdata;
  9034. mg_unlock_context(conn->ctx);
  9035. return 1;
  9036. }
  9037. }
  9038. }
  9039. /* finally try for pattern match */
  9040. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9041. tmp_rh = tmp_rh->next) {
  9042. if (tmp_rh->handler_type == handler_type) {
  9043. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9044. if (handler_type == WEBSOCKET_HANDLER) {
  9045. *subprotocols = tmp_rh->subprotocols;
  9046. *connect_handler = tmp_rh->connect_handler;
  9047. *ready_handler = tmp_rh->ready_handler;
  9048. *data_handler = tmp_rh->data_handler;
  9049. *close_handler = tmp_rh->close_handler;
  9050. } else if (handler_type == REQUEST_HANDLER) {
  9051. *handler = tmp_rh->handler;
  9052. } else { /* AUTH_HANDLER */
  9053. *auth_handler = tmp_rh->auth_handler;
  9054. }
  9055. *cbdata = tmp_rh->cbdata;
  9056. mg_unlock_context(conn->ctx);
  9057. return 1;
  9058. }
  9059. }
  9060. }
  9061. mg_unlock_context(conn->ctx);
  9062. }
  9063. return 0; /* none found */
  9064. }
  9065. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9066. static int
  9067. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9068. void *cbdata)
  9069. {
  9070. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9071. if (pcallbacks->websocket_connect) {
  9072. return pcallbacks->websocket_connect(conn);
  9073. }
  9074. /* No handler set - assume "OK" */
  9075. return 0;
  9076. }
  9077. static void
  9078. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9079. {
  9080. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9081. if (pcallbacks->websocket_ready) {
  9082. pcallbacks->websocket_ready(conn);
  9083. }
  9084. }
  9085. static int
  9086. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9087. int bits,
  9088. char *data,
  9089. size_t len,
  9090. void *cbdata)
  9091. {
  9092. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9093. if (pcallbacks->websocket_data) {
  9094. return pcallbacks->websocket_data(conn, bits, data, len);
  9095. }
  9096. /* No handler set - assume "OK" */
  9097. return 1;
  9098. }
  9099. #endif
  9100. /* This is the heart of the Civetweb's logic.
  9101. * This function is called when the request is read, parsed and validated,
  9102. * and Civetweb must decide what action to take: serve a file, or
  9103. * a directory, or call embedded function, etcetera. */
  9104. static void
  9105. handle_request(struct mg_connection *conn)
  9106. {
  9107. if (conn) {
  9108. struct mg_request_info *ri = &conn->request_info;
  9109. char path[PATH_MAX];
  9110. int uri_len, ssl_index;
  9111. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9112. is_put_or_delete_request = 0, is_callback_resource = 0;
  9113. int i;
  9114. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9115. mg_request_handler callback_handler = NULL;
  9116. struct mg_websocket_subprotocols *subprotocols;
  9117. mg_websocket_connect_handler ws_connect_handler = NULL;
  9118. mg_websocket_ready_handler ws_ready_handler = NULL;
  9119. mg_websocket_data_handler ws_data_handler = NULL;
  9120. mg_websocket_close_handler ws_close_handler = NULL;
  9121. void *callback_data = NULL;
  9122. mg_authorization_handler auth_handler = NULL;
  9123. void *auth_callback_data = NULL;
  9124. #if !defined(NO_FILES)
  9125. time_t curtime = time(NULL);
  9126. char date[64];
  9127. #endif
  9128. path[0] = 0;
  9129. if (!ri) {
  9130. return;
  9131. }
  9132. /* 1. get the request url */
  9133. /* 1.1. split into url and query string */
  9134. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9135. != NULL) {
  9136. *((char *)conn->request_info.query_string++) = '\0';
  9137. }
  9138. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9139. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9140. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9141. if (ssl_index >= 0) {
  9142. redirect_to_https_port(conn, ssl_index);
  9143. } else {
  9144. /* A http to https forward port has been specified,
  9145. * but no https port to forward to. */
  9146. send_http_error(conn,
  9147. 503,
  9148. "%s",
  9149. "Error: SSL forward not configured properly");
  9150. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9151. }
  9152. return;
  9153. }
  9154. uri_len = (int)strlen(ri->local_uri);
  9155. /* 1.3. decode url (if config says so) */
  9156. if (should_decode_url(conn)) {
  9157. mg_url_decode(
  9158. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9159. }
  9160. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9161. * not possible */
  9162. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9163. /* step 1. completed, the url is known now */
  9164. uri_len = (int)strlen(ri->local_uri);
  9165. DEBUG_TRACE("URL: %s", ri->local_uri);
  9166. /* 3. if this ip has limited speed, set it for this connection */
  9167. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9168. get_remote_ip(conn),
  9169. ri->local_uri);
  9170. /* 4. call a "handle everything" callback, if registered */
  9171. if (conn->ctx->callbacks.begin_request != NULL) {
  9172. /* Note that since V1.7 the "begin_request" function is called
  9173. * before an authorization check. If an authorization check is
  9174. * required, use a request_handler instead. */
  9175. i = conn->ctx->callbacks.begin_request(conn);
  9176. if (i > 0) {
  9177. /* callback already processed the request. Store the
  9178. return value as a status code for the access log. */
  9179. conn->status_code = i;
  9180. discard_unread_request_data(conn);
  9181. return;
  9182. } else if (i == 0) {
  9183. /* civetweb should process the request */
  9184. } else {
  9185. /* unspecified - may change with the next version */
  9186. return;
  9187. }
  9188. }
  9189. /* request not yet handled by a handler or redirect, so the request
  9190. * is processed here */
  9191. /* 5. interpret the url to find out how the request must be handled
  9192. */
  9193. /* 5.1. first test, if the request targets the regular http(s)://
  9194. * protocol namespace or the websocket ws(s):// protocol namespace.
  9195. */
  9196. is_websocket_request = is_websocket_protocol(conn);
  9197. /* 5.2. check if the request will be handled by a callback */
  9198. if (get_request_handler(conn,
  9199. is_websocket_request ? WEBSOCKET_HANDLER
  9200. : REQUEST_HANDLER,
  9201. &callback_handler,
  9202. &subprotocols,
  9203. &ws_connect_handler,
  9204. &ws_ready_handler,
  9205. &ws_data_handler,
  9206. &ws_close_handler,
  9207. NULL,
  9208. &callback_data)) {
  9209. /* 5.2.1. A callback will handle this request. All requests
  9210. * handled
  9211. * by a callback have to be considered as requests to a script
  9212. * resource. */
  9213. is_callback_resource = 1;
  9214. is_script_resource = 1;
  9215. is_put_or_delete_request = is_put_or_delete_method(conn);
  9216. } else {
  9217. no_callback_resource:
  9218. /* 5.2.2. No callback is responsible for this request. The URI
  9219. * addresses a file based resource (static content or Lua/cgi
  9220. * scripts in the file system). */
  9221. is_callback_resource = 0;
  9222. interpret_uri(conn,
  9223. path,
  9224. sizeof(path),
  9225. &file.stat,
  9226. &is_found,
  9227. &is_script_resource,
  9228. &is_websocket_request,
  9229. &is_put_or_delete_request);
  9230. }
  9231. /* 6. authorization check */
  9232. /* 6.1. a custom authorization handler is installed */
  9233. if (get_request_handler(conn,
  9234. AUTH_HANDLER,
  9235. NULL,
  9236. NULL,
  9237. NULL,
  9238. NULL,
  9239. NULL,
  9240. NULL,
  9241. &auth_handler,
  9242. &auth_callback_data)) {
  9243. if (!auth_handler(conn, auth_callback_data)) {
  9244. return;
  9245. }
  9246. } else if (is_put_or_delete_request && !is_script_resource
  9247. && !is_callback_resource) {
  9248. /* 6.2. this request is a PUT/DELETE to a real file */
  9249. /* 6.2.1. thus, the server must have real files */
  9250. #if defined(NO_FILES)
  9251. if (1) {
  9252. #else
  9253. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9254. #endif
  9255. /* This server does not have any real files, thus the
  9256. * PUT/DELETE methods are not valid. */
  9257. send_http_error(conn,
  9258. 405,
  9259. "%s method not allowed",
  9260. conn->request_info.request_method);
  9261. return;
  9262. }
  9263. #if !defined(NO_FILES)
  9264. /* 6.2.2. Check if put authorization for static files is
  9265. * available.
  9266. */
  9267. if (!is_authorized_for_put(conn)) {
  9268. send_authorization_request(conn);
  9269. return;
  9270. }
  9271. #endif
  9272. } else {
  9273. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9274. * or it is a PUT or DELETE request to a resource that does not
  9275. * correspond to a file. Check authorization. */
  9276. if (!check_authorization(conn, path)) {
  9277. send_authorization_request(conn);
  9278. return;
  9279. }
  9280. }
  9281. /* request is authorized or does not need authorization */
  9282. /* 7. check if there are request handlers for this uri */
  9283. if (is_callback_resource) {
  9284. if (!is_websocket_request) {
  9285. i = callback_handler(conn, callback_data);
  9286. if (i > 0) {
  9287. /* Do nothing, callback has served the request. Store
  9288. * the
  9289. * return value as status code for the log and discard
  9290. * all
  9291. * data from the client not used by the callback. */
  9292. conn->status_code = i;
  9293. discard_unread_request_data(conn);
  9294. } else {
  9295. /* TODO (high): what if the handler did NOT handle the
  9296. * request */
  9297. /* The last version did handle this as a file request,
  9298. * but
  9299. * since a file request is not always a script resource,
  9300. * the authorization check might be different */
  9301. interpret_uri(conn,
  9302. path,
  9303. sizeof(path),
  9304. &file.stat,
  9305. &is_found,
  9306. &is_script_resource,
  9307. &is_websocket_request,
  9308. &is_put_or_delete_request);
  9309. callback_handler = NULL;
  9310. /* TODO (very low): goto is deprecated but for the
  9311. * moment,
  9312. * a goto is simpler than some curious loop. */
  9313. /* The situation "callback does not handle the request"
  9314. * needs to be reconsidered anyway. */
  9315. goto no_callback_resource;
  9316. }
  9317. } else {
  9318. #if defined(USE_WEBSOCKET)
  9319. handle_websocket_request(conn,
  9320. path,
  9321. is_callback_resource,
  9322. subprotocols,
  9323. ws_connect_handler,
  9324. ws_ready_handler,
  9325. ws_data_handler,
  9326. ws_close_handler,
  9327. callback_data);
  9328. #endif
  9329. }
  9330. return;
  9331. }
  9332. /* 8. handle websocket requests */
  9333. #if defined(USE_WEBSOCKET)
  9334. if (is_websocket_request) {
  9335. if (is_script_resource) {
  9336. /* Websocket Lua script */
  9337. handle_websocket_request(conn,
  9338. path,
  9339. 0 /* Lua Script */,
  9340. NULL,
  9341. NULL,
  9342. NULL,
  9343. NULL,
  9344. NULL,
  9345. &conn->ctx->callbacks);
  9346. } else {
  9347. #if defined(MG_LEGACY_INTERFACE)
  9348. handle_websocket_request(
  9349. conn,
  9350. path,
  9351. !is_script_resource /* could be deprecated global callback */,
  9352. NULL,
  9353. deprecated_websocket_connect_wrapper,
  9354. deprecated_websocket_ready_wrapper,
  9355. deprecated_websocket_data_wrapper,
  9356. NULL,
  9357. &conn->ctx->callbacks);
  9358. #else
  9359. send_http_error(conn, 404, "%s", "Not found");
  9360. #endif
  9361. }
  9362. return;
  9363. } else
  9364. #endif
  9365. #if defined(NO_FILES)
  9366. /* 9a. In case the server uses only callbacks, this uri is
  9367. * unknown.
  9368. * Then, all request handling ends here. */
  9369. send_http_error(conn, 404, "%s", "Not Found");
  9370. #else
  9371. /* 9b. This request is either for a static file or resource handled
  9372. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9373. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9374. send_http_error(conn, 404, "%s", "Not Found");
  9375. return;
  9376. }
  9377. /* 10. File is handled by a script. */
  9378. if (is_script_resource) {
  9379. handle_file_based_request(conn, path, &file);
  9380. return;
  9381. }
  9382. /* 11. Handle put/delete/mkcol requests */
  9383. if (is_put_or_delete_request) {
  9384. /* 11.1. PUT method */
  9385. if (!strcmp(ri->request_method, "PUT")) {
  9386. put_file(conn, path);
  9387. return;
  9388. }
  9389. /* 11.2. DELETE method */
  9390. if (!strcmp(ri->request_method, "DELETE")) {
  9391. delete_file(conn, path);
  9392. return;
  9393. }
  9394. /* 11.3. MKCOL method */
  9395. if (!strcmp(ri->request_method, "MKCOL")) {
  9396. mkcol(conn, path);
  9397. return;
  9398. }
  9399. /* 11.4. PATCH method
  9400. * This method is not supported for static resources,
  9401. * only for scripts (Lua, CGI) and callbacks. */
  9402. send_http_error(conn,
  9403. 405,
  9404. "%s method not allowed",
  9405. conn->request_info.request_method);
  9406. return;
  9407. }
  9408. /* 11. File does not exist, or it was configured that it should be
  9409. * hidden */
  9410. if (!is_found || (must_hide_file(conn, path))) {
  9411. send_http_error(conn, 404, "%s", "Not found");
  9412. return;
  9413. }
  9414. /* 12. Directory uris should end with a slash */
  9415. if (file.stat.is_directory && (uri_len > 0)
  9416. && (ri->local_uri[uri_len - 1] != '/')) {
  9417. gmt_time_string(date, sizeof(date), &curtime);
  9418. mg_printf(conn,
  9419. "HTTP/1.1 301 Moved Permanently\r\n"
  9420. "Location: %s/\r\n"
  9421. "Date: %s\r\n"
  9422. /* "Cache-Control: private\r\n" (= default) */
  9423. "Content-Length: 0\r\n"
  9424. "Connection: %s\r\n\r\n",
  9425. ri->request_uri,
  9426. date,
  9427. suggest_connection_header(conn));
  9428. return;
  9429. }
  9430. /* 13. Handle other methods than GET/HEAD */
  9431. /* 13.1. Handle PROPFIND */
  9432. if (!strcmp(ri->request_method, "PROPFIND")) {
  9433. handle_propfind(conn, path, &file.stat);
  9434. return;
  9435. }
  9436. /* 13.2. Handle OPTIONS for files */
  9437. if (!strcmp(ri->request_method, "OPTIONS")) {
  9438. /* This standard handler is only used for real files.
  9439. * Scripts should support the OPTIONS method themselves, to allow a
  9440. * maximum flexibility.
  9441. * Lua and CGI scripts may fully support CORS this way (including
  9442. * preflights). */
  9443. send_options(conn);
  9444. return;
  9445. }
  9446. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9447. if (0 != strcmp(ri->request_method, "GET")
  9448. && 0 != strcmp(ri->request_method, "HEAD")) {
  9449. send_http_error(conn,
  9450. 405,
  9451. "%s method not allowed",
  9452. conn->request_info.request_method);
  9453. return;
  9454. }
  9455. /* 14. directories */
  9456. if (file.stat.is_directory) {
  9457. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9458. /* 14.1. use a substitute file */
  9459. /* TODO (high): substitute index may be a script resource.
  9460. * define what should be possible in this case. */
  9461. } else {
  9462. /* 14.2. no substitute file */
  9463. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9464. "yes")) {
  9465. handle_directory_request(conn, path);
  9466. } else {
  9467. send_http_error(conn,
  9468. 403,
  9469. "%s",
  9470. "Error: Directory listing denied");
  9471. }
  9472. return;
  9473. }
  9474. }
  9475. handle_file_based_request(conn, path, &file);
  9476. #endif /* !defined(NO_FILES) */
  9477. #if 0
  9478. /* Perform redirect and auth checks before calling begin_request()
  9479. * handler.
  9480. * Otherwise, begin_request() would need to perform auth checks and
  9481. * redirects. */
  9482. #endif
  9483. }
  9484. return;
  9485. }
  9486. static void
  9487. handle_file_based_request(struct mg_connection *conn,
  9488. const char *path,
  9489. struct mg_file *file)
  9490. {
  9491. if (!conn || !conn->ctx) {
  9492. return;
  9493. }
  9494. if (0) {
  9495. #ifdef USE_LUA
  9496. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9497. strlen(
  9498. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9499. path) > 0) {
  9500. /* Lua server page: an SSI like page containing mostly plain html
  9501. * code
  9502. * plus some tags with server generated contents. */
  9503. handle_lsp_request(conn, path, file, NULL);
  9504. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9505. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9506. path) > 0) {
  9507. /* Lua in-server module script: a CGI like script used to generate
  9508. * the
  9509. * entire reply. */
  9510. mg_exec_lua_script(conn, path, NULL);
  9511. #endif
  9512. #if defined(USE_DUKTAPE)
  9513. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9514. strlen(
  9515. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9516. path) > 0) {
  9517. /* Call duktape to generate the page */
  9518. mg_exec_duktape_script(conn, path);
  9519. #endif
  9520. #if !defined(NO_CGI)
  9521. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9522. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9523. path) > 0) {
  9524. /* CGI scripts may support all HTTP methods */
  9525. handle_cgi_request(conn, path);
  9526. #endif /* !NO_CGI */
  9527. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9528. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9529. path) > 0) {
  9530. handle_ssi_file_request(conn, path, file);
  9531. #if !defined(NO_CACHING)
  9532. } else if ((!conn->in_error_handler)
  9533. && is_not_modified(conn, &file->stat)) {
  9534. /* Send 304 "Not Modified" - this must not send any body data */
  9535. handle_not_modified_static_file_request(conn, file);
  9536. #endif /* !NO_CACHING */
  9537. } else {
  9538. handle_static_file_request(conn, path, file, NULL, NULL);
  9539. }
  9540. }
  9541. static void
  9542. close_all_listening_sockets(struct mg_context *ctx)
  9543. {
  9544. unsigned int i;
  9545. if (!ctx) {
  9546. return;
  9547. }
  9548. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9549. closesocket(ctx->listening_sockets[i].sock);
  9550. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9551. }
  9552. mg_free(ctx->listening_sockets);
  9553. ctx->listening_sockets = NULL;
  9554. mg_free(ctx->listening_socket_fds);
  9555. ctx->listening_socket_fds = NULL;
  9556. }
  9557. /* Valid listening port specification is: [ip_address:]port[s]
  9558. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9559. * Examples for IPv6: [::]:80, [::1]:80,
  9560. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9561. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9562. * In order to bind to both, IPv4 and IPv6, you can either add
  9563. * both ports using 8080,[::]:8080, or the short form +8080.
  9564. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9565. * one only accepting IPv4 the other only IPv6. +8080 creates
  9566. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9567. * environment, they might work differently, or might not work
  9568. * at all - it must be tested what options work best in the
  9569. * relevant network environment.
  9570. */
  9571. static int
  9572. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9573. {
  9574. unsigned int a, b, c, d, port;
  9575. int ch, len;
  9576. #if defined(USE_IPV6)
  9577. char buf[100] = {0};
  9578. #endif
  9579. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9580. * Also, all-zeroes in the socket address means binding to all addresses
  9581. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9582. memset(so, 0, sizeof(*so));
  9583. so->lsa.sin.sin_family = AF_INET;
  9584. *ip_version = 0;
  9585. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9586. == 5) {
  9587. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9588. so->lsa.sin.sin_addr.s_addr =
  9589. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9590. so->lsa.sin.sin_port = htons((uint16_t)port);
  9591. *ip_version = 4;
  9592. #if defined(USE_IPV6)
  9593. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9594. && mg_inet_pton(
  9595. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9596. /* IPv6 address, examples: see above */
  9597. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9598. */
  9599. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9600. *ip_version = 6;
  9601. #endif
  9602. } else if ((vec->ptr[0] == '+')
  9603. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9604. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9605. /* Add 1 to len for the + character we skipped before */
  9606. len++;
  9607. #if defined(USE_IPV6)
  9608. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9609. so->lsa.sin6.sin6_family = AF_INET6;
  9610. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9611. *ip_version = 4 + 6;
  9612. #else
  9613. /* Bind to IPv4 only, since IPv6 is not built in. */
  9614. so->lsa.sin.sin_port = htons((uint16_t)port);
  9615. *ip_version = 4;
  9616. #endif
  9617. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9618. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9619. so->lsa.sin.sin_port = htons((uint16_t)port);
  9620. *ip_version = 4;
  9621. } else {
  9622. /* Parsing failure. Make port invalid. */
  9623. port = 0;
  9624. len = 0;
  9625. }
  9626. /* sscanf and the option splitting code ensure the following condition
  9627. */
  9628. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9629. *ip_version = 0;
  9630. return 0;
  9631. }
  9632. ch = vec->ptr[len]; /* Next character after the port number */
  9633. so->is_ssl = (ch == 's');
  9634. so->ssl_redir = (ch == 'r');
  9635. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9636. if (is_valid_port(port)
  9637. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9638. return 1;
  9639. }
  9640. /* Reset ip_version to 0 of there is an error */
  9641. *ip_version = 0;
  9642. return 0;
  9643. }
  9644. static int
  9645. set_ports_option(struct mg_context *ctx)
  9646. {
  9647. const char *list;
  9648. int on = 1;
  9649. #if defined(USE_IPV6)
  9650. int off = 0;
  9651. #endif
  9652. struct vec vec;
  9653. struct socket so, *ptr;
  9654. struct pollfd *pfd;
  9655. union usa usa;
  9656. socklen_t len;
  9657. int ip_version;
  9658. int portsTotal = 0;
  9659. int portsOk = 0;
  9660. if (!ctx) {
  9661. return 0;
  9662. }
  9663. memset(&so, 0, sizeof(so));
  9664. memset(&usa, 0, sizeof(usa));
  9665. len = sizeof(usa);
  9666. list = ctx->config[LISTENING_PORTS];
  9667. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9668. portsTotal++;
  9669. if (!parse_port_string(&vec, &so, &ip_version)) {
  9670. mg_cry(fc(ctx),
  9671. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9672. (int)vec.len,
  9673. vec.ptr,
  9674. portsTotal,
  9675. "[IP_ADDRESS:]PORT[s|r]");
  9676. continue;
  9677. }
  9678. #if !defined(NO_SSL)
  9679. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9680. mg_cry(fc(ctx),
  9681. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9682. "option set?",
  9683. portsTotal);
  9684. continue;
  9685. }
  9686. #endif
  9687. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9688. == INVALID_SOCKET) {
  9689. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9690. continue;
  9691. }
  9692. #ifdef _WIN32
  9693. /* Windows SO_REUSEADDR lets many procs binds to a
  9694. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9695. * if someone already has the socket -- DTL */
  9696. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9697. * Windows might need a few seconds before
  9698. * the same port can be used again in the
  9699. * same process, so a short Sleep may be
  9700. * required between mg_stop and mg_start.
  9701. */
  9702. if (setsockopt(so.sock,
  9703. SOL_SOCKET,
  9704. SO_EXCLUSIVEADDRUSE,
  9705. (SOCK_OPT_TYPE)&on,
  9706. sizeof(on)) != 0) {
  9707. /* Set reuse option, but don't abort on errors. */
  9708. mg_cry(fc(ctx),
  9709. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9710. portsTotal);
  9711. }
  9712. #else
  9713. if (setsockopt(so.sock,
  9714. SOL_SOCKET,
  9715. SO_REUSEADDR,
  9716. (SOCK_OPT_TYPE)&on,
  9717. sizeof(on)) != 0) {
  9718. /* Set reuse option, but don't abort on errors. */
  9719. mg_cry(fc(ctx),
  9720. "cannot set socket option SO_REUSEADDR (entry %i)",
  9721. portsTotal);
  9722. }
  9723. #endif
  9724. if (ip_version > 4) {
  9725. #if defined(USE_IPV6)
  9726. if (ip_version == 6) {
  9727. if (so.lsa.sa.sa_family == AF_INET6
  9728. && setsockopt(so.sock,
  9729. IPPROTO_IPV6,
  9730. IPV6_V6ONLY,
  9731. (void *)&off,
  9732. sizeof(off)) != 0) {
  9733. /* Set IPv6 only option, but don't abort on errors. */
  9734. mg_cry(fc(ctx),
  9735. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9736. portsTotal);
  9737. }
  9738. }
  9739. #else
  9740. mg_cry(fc(ctx), "IPv6 not available");
  9741. closesocket(so.sock);
  9742. so.sock = INVALID_SOCKET;
  9743. continue;
  9744. #endif
  9745. }
  9746. if (so.lsa.sa.sa_family == AF_INET) {
  9747. len = sizeof(so.lsa.sin);
  9748. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9749. mg_cry(fc(ctx),
  9750. "cannot bind to %.*s: %d (%s)",
  9751. (int)vec.len,
  9752. vec.ptr,
  9753. (int)ERRNO,
  9754. strerror(errno));
  9755. closesocket(so.sock);
  9756. so.sock = INVALID_SOCKET;
  9757. continue;
  9758. }
  9759. }
  9760. #if defined(USE_IPV6)
  9761. else if (so.lsa.sa.sa_family == AF_INET6) {
  9762. len = sizeof(so.lsa.sin6);
  9763. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9764. mg_cry(fc(ctx),
  9765. "cannot bind to IPv6 %.*s: %d (%s)",
  9766. (int)vec.len,
  9767. vec.ptr,
  9768. (int)ERRNO,
  9769. strerror(errno));
  9770. closesocket(so.sock);
  9771. so.sock = INVALID_SOCKET;
  9772. continue;
  9773. }
  9774. }
  9775. #endif
  9776. else {
  9777. mg_cry(fc(ctx),
  9778. "cannot bind: address family not supported (entry %i)",
  9779. portsTotal);
  9780. continue;
  9781. }
  9782. if (listen(so.sock, SOMAXCONN) != 0) {
  9783. mg_cry(fc(ctx),
  9784. "cannot listen to %.*s: %d (%s)",
  9785. (int)vec.len,
  9786. vec.ptr,
  9787. (int)ERRNO,
  9788. strerror(errno));
  9789. closesocket(so.sock);
  9790. so.sock = INVALID_SOCKET;
  9791. continue;
  9792. }
  9793. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9794. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9795. int err = (int)ERRNO;
  9796. mg_cry(fc(ctx),
  9797. "call to getsockname failed %.*s: %d (%s)",
  9798. (int)vec.len,
  9799. vec.ptr,
  9800. err,
  9801. strerror(errno));
  9802. closesocket(so.sock);
  9803. so.sock = INVALID_SOCKET;
  9804. continue;
  9805. }
  9806. /* Update lsa port in case of random free ports */
  9807. #if defined(USE_IPV6)
  9808. if (so.lsa.sa.sa_family == AF_INET6) {
  9809. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9810. } else
  9811. #endif
  9812. {
  9813. so.lsa.sin.sin_port = usa.sin.sin_port;
  9814. }
  9815. if ((ptr = (struct socket *)
  9816. mg_realloc(ctx->listening_sockets,
  9817. (ctx->num_listening_sockets + 1)
  9818. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9819. mg_cry(fc(ctx), "%s", "Out of memory");
  9820. closesocket(so.sock);
  9821. so.sock = INVALID_SOCKET;
  9822. continue;
  9823. }
  9824. if ((pfd = (struct pollfd *)mg_realloc(
  9825. ctx->listening_socket_fds,
  9826. (ctx->num_listening_sockets + 1)
  9827. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9828. mg_cry(fc(ctx), "%s", "Out of memory");
  9829. closesocket(so.sock);
  9830. so.sock = INVALID_SOCKET;
  9831. mg_free(ptr);
  9832. continue;
  9833. }
  9834. set_close_on_exec(so.sock, fc(ctx));
  9835. ctx->listening_sockets = ptr;
  9836. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9837. ctx->listening_socket_fds = pfd;
  9838. ctx->num_listening_sockets++;
  9839. portsOk++;
  9840. }
  9841. if (portsOk != portsTotal) {
  9842. close_all_listening_sockets(ctx);
  9843. portsOk = 0;
  9844. }
  9845. return portsOk;
  9846. }
  9847. static const char *
  9848. header_val(const struct mg_connection *conn, const char *header)
  9849. {
  9850. const char *header_value;
  9851. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9852. return "-";
  9853. } else {
  9854. return header_value;
  9855. }
  9856. }
  9857. static void
  9858. log_access(const struct mg_connection *conn)
  9859. {
  9860. const struct mg_request_info *ri;
  9861. struct mg_file fi;
  9862. char date[64], src_addr[IP_ADDR_STR_LEN];
  9863. struct tm *tm;
  9864. const char *referer;
  9865. const char *user_agent;
  9866. char buf[4096];
  9867. if (!conn || !conn->ctx) {
  9868. return;
  9869. }
  9870. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9871. if (mg_fopen(conn,
  9872. conn->ctx->config[ACCESS_LOG_FILE],
  9873. MG_FOPEN_MODE_APPEND,
  9874. &fi) == 0) {
  9875. fi.access.fp = NULL;
  9876. }
  9877. } else {
  9878. fi.access.fp = NULL;
  9879. }
  9880. /* Log is written to a file and/or a callback. If both are not set,
  9881. * executing the rest of the function is pointless. */
  9882. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9883. return;
  9884. }
  9885. tm = localtime(&conn->conn_birth_time);
  9886. if (tm != NULL) {
  9887. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9888. } else {
  9889. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9890. date[sizeof(date) - 1] = '\0';
  9891. }
  9892. ri = &conn->request_info;
  9893. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9894. referer = header_val(conn, "Referer");
  9895. user_agent = header_val(conn, "User-Agent");
  9896. mg_snprintf(conn,
  9897. NULL, /* Ignore truncation in access log */
  9898. buf,
  9899. sizeof(buf),
  9900. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9901. src_addr,
  9902. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9903. date,
  9904. ri->request_method ? ri->request_method : "-",
  9905. ri->request_uri ? ri->request_uri : "-",
  9906. ri->query_string ? "?" : "",
  9907. ri->query_string ? ri->query_string : "",
  9908. ri->http_version,
  9909. conn->status_code,
  9910. conn->num_bytes_sent,
  9911. referer,
  9912. user_agent);
  9913. if (conn->ctx->callbacks.log_access) {
  9914. conn->ctx->callbacks.log_access(conn, buf);
  9915. }
  9916. if (fi.access.fp) {
  9917. int ok = 1;
  9918. flockfile(fi.access.fp);
  9919. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  9920. ok = 0;
  9921. }
  9922. if (fflush(fi.access.fp) != 0) {
  9923. ok = 0;
  9924. }
  9925. funlockfile(fi.access.fp);
  9926. if (mg_fclose(&fi.access) != 0) {
  9927. ok = 0;
  9928. }
  9929. if (!ok) {
  9930. mg_cry(conn,
  9931. "Error writing log file %s",
  9932. conn->ctx->config[ACCESS_LOG_FILE]);
  9933. }
  9934. }
  9935. }
  9936. /* Verify given socket address against the ACL.
  9937. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9938. */
  9939. static int
  9940. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9941. {
  9942. int allowed, flag;
  9943. uint32_t net, mask;
  9944. struct vec vec;
  9945. if (ctx) {
  9946. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9947. /* If any ACL is set, deny by default */
  9948. allowed = (list == NULL) ? '+' : '-';
  9949. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9950. flag = vec.ptr[0];
  9951. if ((flag != '+' && flag != '-')
  9952. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9953. mg_cry(fc(ctx),
  9954. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9955. __func__);
  9956. return -1;
  9957. }
  9958. if (net == (remote_ip & mask)) {
  9959. allowed = flag;
  9960. }
  9961. }
  9962. return allowed == '+';
  9963. }
  9964. return -1;
  9965. }
  9966. #if !defined(_WIN32)
  9967. static int
  9968. set_uid_option(struct mg_context *ctx)
  9969. {
  9970. struct passwd *pw;
  9971. if (ctx) {
  9972. const char *uid = ctx->config[RUN_AS_USER];
  9973. int success = 0;
  9974. if (uid == NULL) {
  9975. success = 1;
  9976. } else {
  9977. if ((pw = getpwnam(uid)) == NULL) {
  9978. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9979. } else if (setgid(pw->pw_gid) == -1) {
  9980. mg_cry(fc(ctx),
  9981. "%s: setgid(%s): %s",
  9982. __func__,
  9983. uid,
  9984. strerror(errno));
  9985. } else if (setgroups(0, NULL)) {
  9986. mg_cry(fc(ctx),
  9987. "%s: setgroups(): %s",
  9988. __func__,
  9989. strerror(errno));
  9990. } else if (setuid(pw->pw_uid) == -1) {
  9991. mg_cry(fc(ctx),
  9992. "%s: setuid(%s): %s",
  9993. __func__,
  9994. uid,
  9995. strerror(errno));
  9996. } else {
  9997. success = 1;
  9998. }
  9999. }
  10000. return success;
  10001. }
  10002. return 0;
  10003. }
  10004. #endif /* !_WIN32 */
  10005. static void
  10006. tls_dtor(void *key)
  10007. {
  10008. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10009. /* key == pthread_getspecific(sTlsKey); */
  10010. if (tls) {
  10011. if (tls->is_master == 2) {
  10012. tls->is_master = -3; /* Mark memory as dead */
  10013. mg_free(tls);
  10014. }
  10015. }
  10016. pthread_setspecific(sTlsKey, NULL);
  10017. }
  10018. #if !defined(NO_SSL)
  10019. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10020. static const char *ssl_error(void);
  10021. static int
  10022. refresh_trust(struct mg_connection *conn)
  10023. {
  10024. static int reload_lock = 0;
  10025. static long int data_check = 0;
  10026. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10027. struct stat cert_buf;
  10028. long int t;
  10029. char *pem;
  10030. int should_verify_peer;
  10031. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10032. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10033. * refresh_trust still can not work. */
  10034. return 0;
  10035. }
  10036. t = data_check;
  10037. if (stat(pem, &cert_buf) != -1) {
  10038. t = (long int)cert_buf.st_mtime;
  10039. }
  10040. if (data_check != t) {
  10041. data_check = t;
  10042. should_verify_peer =
  10043. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10044. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10045. == 0);
  10046. if (should_verify_peer) {
  10047. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10048. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10049. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10050. ca_file,
  10051. ca_path) != 1) {
  10052. mg_cry(fc(conn->ctx),
  10053. "SSL_CTX_load_verify_locations error: %s "
  10054. "ssl_verify_peer requires setting "
  10055. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10056. "present in "
  10057. "the .conf file?",
  10058. ssl_error());
  10059. return 0;
  10060. }
  10061. }
  10062. if (1 == mg_atomic_inc(p_reload_lock)) {
  10063. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10064. return 0;
  10065. }
  10066. *p_reload_lock = 0;
  10067. }
  10068. }
  10069. /* lock while cert is reloading */
  10070. while (*p_reload_lock) {
  10071. sleep(1);
  10072. }
  10073. return 1;
  10074. }
  10075. static pthread_mutex_t *ssl_mutexes;
  10076. static int
  10077. sslize(struct mg_connection *conn,
  10078. SSL_CTX *s,
  10079. int (*func)(SSL *),
  10080. volatile int *stop_server)
  10081. {
  10082. int ret, err;
  10083. int short_trust;
  10084. unsigned i;
  10085. if (!conn) {
  10086. return 0;
  10087. }
  10088. short_trust =
  10089. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10090. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10091. if (short_trust) {
  10092. int trust_ret = refresh_trust(conn);
  10093. if (!trust_ret) {
  10094. return trust_ret;
  10095. }
  10096. }
  10097. conn->ssl = SSL_new(s);
  10098. if (conn->ssl == NULL) {
  10099. return 0;
  10100. }
  10101. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10102. if (ret != 1) {
  10103. err = SSL_get_error(conn->ssl, ret);
  10104. (void)err; /* TODO: set some error message */
  10105. SSL_free(conn->ssl);
  10106. conn->ssl = NULL;
  10107. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10108. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10109. ERR_remove_state(0);
  10110. return 0;
  10111. }
  10112. /* SSL functions may fail and require to be called again:
  10113. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10114. * Here "func" could be SSL_connect or SSL_accept. */
  10115. for (i = 16; i <= 1024; i *= 2) {
  10116. ret = func(conn->ssl);
  10117. if (ret != 1) {
  10118. err = SSL_get_error(conn->ssl, ret);
  10119. if ((err == SSL_ERROR_WANT_CONNECT)
  10120. || (err == SSL_ERROR_WANT_ACCEPT)
  10121. || (err == SSL_ERROR_WANT_READ)
  10122. || (err == SSL_ERROR_WANT_WRITE)) {
  10123. /* Need to retry the function call "later".
  10124. * See https://linux.die.net/man/3/ssl_get_error
  10125. * This is typical for non-blocking sockets. */
  10126. if (*stop_server) {
  10127. /* Don't wait if the server is going to be stopped. */
  10128. break;
  10129. }
  10130. mg_sleep(i);
  10131. } else if (err == SSL_ERROR_SYSCALL) {
  10132. /* This is an IO error. Look at errno. */
  10133. err = errno;
  10134. /* TODO: set some error message */
  10135. break;
  10136. } else {
  10137. /* This is an SSL specific error */
  10138. /* TODO: set some error message */
  10139. break;
  10140. }
  10141. } else {
  10142. /* success */
  10143. break;
  10144. }
  10145. }
  10146. if (ret != 1) {
  10147. SSL_free(conn->ssl);
  10148. conn->ssl = NULL;
  10149. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10150. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10151. ERR_remove_state(0);
  10152. return 0;
  10153. }
  10154. return 1;
  10155. }
  10156. /* Return OpenSSL error message (from CRYPTO lib) */
  10157. static const char *
  10158. ssl_error(void)
  10159. {
  10160. unsigned long err;
  10161. err = ERR_get_error();
  10162. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10163. }
  10164. static int
  10165. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10166. {
  10167. int i;
  10168. const char hexdigit[] = "0123456789abcdef";
  10169. if (memlen <= 0 || buflen <= 0) {
  10170. return 0;
  10171. }
  10172. if (buflen < (3 * memlen)) {
  10173. return 0;
  10174. }
  10175. for (i = 0; i < memlen; i++) {
  10176. if (i > 0) {
  10177. buf[3 * i - 1] = ' ';
  10178. }
  10179. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10180. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10181. }
  10182. buf[3 * memlen - 1] = 0;
  10183. return 1;
  10184. }
  10185. static void
  10186. ssl_get_client_cert_info(struct mg_connection *conn)
  10187. {
  10188. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10189. if (cert) {
  10190. char str_subject[1024];
  10191. char str_issuer[1024];
  10192. char str_serial[1024];
  10193. char str_finger[1024];
  10194. unsigned char buf[256];
  10195. int len;
  10196. unsigned int ulen;
  10197. /* Handle to algorithm used for fingerprint */
  10198. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10199. /* Get Subject and issuer */
  10200. X509_NAME *subj = X509_get_subject_name(cert);
  10201. X509_NAME *iss = X509_get_issuer_name(cert);
  10202. /* Get serial number */
  10203. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10204. /* Translate subject and issuer to a string */
  10205. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10206. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10207. /* Translate serial number to a hex string */
  10208. len = i2c_ASN1_INTEGER(serial, NULL);
  10209. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  10210. unsigned char *pbuf = buf;
  10211. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  10212. if (!hexdump2string(
  10213. buf, len2, str_serial, (int)sizeof(str_serial))) {
  10214. *str_serial = 0;
  10215. }
  10216. } else {
  10217. *str_serial = 0;
  10218. }
  10219. /* Calculate SHA1 fingerprint and store as a hex string */
  10220. ulen = 0;
  10221. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10222. if (!hexdump2string(
  10223. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10224. *str_finger = 0;
  10225. }
  10226. conn->request_info.client_cert =
  10227. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10228. if (conn->request_info.client_cert) {
  10229. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10230. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10231. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10232. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10233. } else {
  10234. /* TODO: write some OOM message */
  10235. }
  10236. X509_free(cert);
  10237. }
  10238. }
  10239. static void
  10240. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10241. {
  10242. (void)line;
  10243. (void)file;
  10244. if (mode & 1) {
  10245. /* 1 is CRYPTO_LOCK */
  10246. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10247. } else {
  10248. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10249. }
  10250. }
  10251. #if !defined(NO_SSL_DL)
  10252. static void *
  10253. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10254. {
  10255. union {
  10256. void *p;
  10257. void (*fp)(void);
  10258. } u;
  10259. void *dll_handle;
  10260. struct ssl_func *fp;
  10261. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10262. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10263. return NULL;
  10264. }
  10265. for (fp = sw; fp->name != NULL; fp++) {
  10266. #ifdef _WIN32
  10267. /* GetProcAddress() returns pointer to function */
  10268. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10269. #else
  10270. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10271. * pointers to function pointers. We need to use a union to make a
  10272. * cast. */
  10273. u.p = dlsym(dll_handle, fp->name);
  10274. #endif /* _WIN32 */
  10275. if (u.fp == NULL) {
  10276. mg_cry(fc(ctx),
  10277. "%s: %s: cannot find %s",
  10278. __func__,
  10279. dll_name,
  10280. fp->name);
  10281. dlclose(dll_handle);
  10282. return NULL;
  10283. } else {
  10284. fp->ptr = u.fp;
  10285. }
  10286. }
  10287. return dll_handle;
  10288. }
  10289. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10290. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10291. #endif /* NO_SSL_DL */
  10292. #if defined(SSL_ALREADY_INITIALIZED)
  10293. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10294. #else
  10295. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10296. #endif
  10297. static int
  10298. initialize_ssl(struct mg_context *ctx)
  10299. {
  10300. int i;
  10301. size_t size;
  10302. #if !defined(NO_SSL_DL)
  10303. if (!cryptolib_dll_handle) {
  10304. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10305. if (!cryptolib_dll_handle) {
  10306. return 0;
  10307. }
  10308. }
  10309. #endif /* NO_SSL_DL */
  10310. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10311. return 1;
  10312. }
  10313. /* Initialize locking callbacks, needed for thread safety.
  10314. * http://www.openssl.org/support/faq.html#PROG1
  10315. */
  10316. i = CRYPTO_num_locks();
  10317. if (i < 0) {
  10318. i = 0;
  10319. }
  10320. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10321. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10322. mg_cry(fc(ctx),
  10323. "%s: cannot allocate mutexes: %s",
  10324. __func__,
  10325. ssl_error());
  10326. return 0;
  10327. }
  10328. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10329. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10330. }
  10331. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10332. CRYPTO_set_id_callback(&mg_current_thread_id);
  10333. return 1;
  10334. }
  10335. static int
  10336. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10337. {
  10338. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10339. mg_cry(fc(ctx),
  10340. "%s: cannot open certificate file %s: %s",
  10341. __func__,
  10342. pem,
  10343. ssl_error());
  10344. return 0;
  10345. }
  10346. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10347. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10348. mg_cry(fc(ctx),
  10349. "%s: cannot open private key file %s: %s",
  10350. __func__,
  10351. pem,
  10352. ssl_error());
  10353. return 0;
  10354. }
  10355. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10356. mg_cry(fc(ctx),
  10357. "%s: certificate and private key do not match: %s",
  10358. __func__,
  10359. pem);
  10360. return 0;
  10361. }
  10362. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10363. mg_cry(fc(ctx),
  10364. "%s: cannot use certificate chain file %s: %s",
  10365. __func__,
  10366. pem,
  10367. ssl_error());
  10368. return 0;
  10369. }
  10370. return 1;
  10371. }
  10372. static long
  10373. ssl_get_protocol(int version_id)
  10374. {
  10375. long ret = SSL_OP_ALL;
  10376. if (version_id > 0)
  10377. ret |= SSL_OP_NO_SSLv2;
  10378. if (version_id > 1)
  10379. ret |= SSL_OP_NO_SSLv3;
  10380. if (version_id > 2)
  10381. ret |= SSL_OP_NO_TLSv1;
  10382. if (version_id > 3)
  10383. ret |= SSL_OP_NO_TLSv1_1;
  10384. return ret;
  10385. }
  10386. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10387. static int
  10388. set_ssl_option(struct mg_context *ctx)
  10389. {
  10390. const char *pem;
  10391. int callback_ret;
  10392. int should_verify_peer;
  10393. const char *ca_path;
  10394. const char *ca_file;
  10395. int use_default_verify_paths;
  10396. int verify_depth;
  10397. time_t now_rt = time(NULL);
  10398. struct timespec now_mt;
  10399. md5_byte_t ssl_context_id[16];
  10400. md5_state_t md5state;
  10401. int protocol_ver;
  10402. /* If PEM file is not specified and the init_ssl callback
  10403. * is not specified, skip SSL initialization. */
  10404. if (!ctx) {
  10405. return 0;
  10406. }
  10407. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10408. && ctx->callbacks.init_ssl == NULL) {
  10409. return 1;
  10410. }
  10411. if (!initialize_ssl(ctx)) {
  10412. return 0;
  10413. }
  10414. #if !defined(NO_SSL_DL)
  10415. if (!ssllib_dll_handle) {
  10416. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10417. if (!ssllib_dll_handle) {
  10418. return 0;
  10419. }
  10420. }
  10421. #endif /* NO_SSL_DL */
  10422. /* Initialize SSL library */
  10423. SSL_library_init();
  10424. SSL_load_error_strings();
  10425. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10426. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10427. return 0;
  10428. }
  10429. SSL_CTX_clear_options(ctx->ssl_ctx,
  10430. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10431. | SSL_OP_NO_TLSv1_1);
  10432. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10433. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10434. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10435. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10436. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10437. /* If a callback has been specified, call it. */
  10438. callback_ret =
  10439. (ctx->callbacks.init_ssl == NULL)
  10440. ? 0
  10441. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10442. /* If callback returns 0, civetweb sets up the SSL certificate.
  10443. * If it returns 1, civetweb assumes the calback already did this.
  10444. * If it returns -1, initializing ssl fails. */
  10445. if (callback_ret < 0) {
  10446. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10447. return 0;
  10448. }
  10449. if (callback_ret > 0) {
  10450. if (pem != NULL) {
  10451. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10452. }
  10453. return 1;
  10454. }
  10455. /* Use some UID as session context ID. */
  10456. md5_init(&md5state);
  10457. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10458. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10459. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10460. md5_append(&md5state,
  10461. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10462. strlen(ctx->config[LISTENING_PORTS]));
  10463. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10464. md5_finish(&md5state, ssl_context_id);
  10465. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10466. (const unsigned char *)&ssl_context_id,
  10467. sizeof(ssl_context_id));
  10468. if (pem != NULL) {
  10469. if (!ssl_use_pem_file(ctx, pem)) {
  10470. return 0;
  10471. }
  10472. }
  10473. should_verify_peer =
  10474. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10475. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10476. use_default_verify_paths =
  10477. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10478. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10479. if (should_verify_peer) {
  10480. ca_path = ctx->config[SSL_CA_PATH];
  10481. ca_file = ctx->config[SSL_CA_FILE];
  10482. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10483. != 1) {
  10484. mg_cry(fc(ctx),
  10485. "SSL_CTX_load_verify_locations error: %s "
  10486. "ssl_verify_peer requires setting "
  10487. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10488. "present in "
  10489. "the .conf file?",
  10490. ssl_error());
  10491. return 0;
  10492. }
  10493. SSL_CTX_set_verify(ctx->ssl_ctx,
  10494. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10495. NULL);
  10496. if (use_default_verify_paths
  10497. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10498. mg_cry(fc(ctx),
  10499. "SSL_CTX_set_default_verify_paths error: %s",
  10500. ssl_error());
  10501. return 0;
  10502. }
  10503. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10504. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10505. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10506. }
  10507. }
  10508. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10509. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10510. != 1) {
  10511. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10512. }
  10513. }
  10514. return 1;
  10515. }
  10516. static void
  10517. uninitialize_ssl(struct mg_context *ctx)
  10518. {
  10519. int i;
  10520. (void)ctx;
  10521. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10522. /* Shutdown according to
  10523. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10524. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10525. */
  10526. CRYPTO_set_locking_callback(NULL);
  10527. CRYPTO_set_id_callback(NULL);
  10528. ENGINE_cleanup();
  10529. CONF_modules_unload(1);
  10530. ERR_free_strings();
  10531. EVP_cleanup();
  10532. CRYPTO_cleanup_all_ex_data();
  10533. ERR_remove_state(0);
  10534. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10535. pthread_mutex_destroy(&ssl_mutexes[i]);
  10536. }
  10537. mg_free(ssl_mutexes);
  10538. ssl_mutexes = NULL;
  10539. }
  10540. }
  10541. #endif /* !NO_SSL */
  10542. static int
  10543. set_gpass_option(struct mg_context *ctx)
  10544. {
  10545. if (ctx) {
  10546. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10547. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10548. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10549. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10550. return 0;
  10551. }
  10552. return 1;
  10553. }
  10554. return 0;
  10555. }
  10556. static int
  10557. set_acl_option(struct mg_context *ctx)
  10558. {
  10559. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10560. }
  10561. static void
  10562. reset_per_request_attributes(struct mg_connection *conn)
  10563. {
  10564. if (!conn) {
  10565. return;
  10566. }
  10567. conn->path_info = NULL;
  10568. conn->num_bytes_sent = conn->consumed_content = 0;
  10569. conn->status_code = -1;
  10570. conn->is_chunked = 0;
  10571. conn->must_close = conn->request_len = conn->throttle = 0;
  10572. conn->request_info.content_length = -1;
  10573. conn->request_info.remote_user = NULL;
  10574. conn->request_info.request_method = NULL;
  10575. conn->request_info.request_uri = NULL;
  10576. conn->request_info.local_uri = NULL;
  10577. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10578. * local_uri and request_uri */
  10579. conn->request_info.http_version = NULL;
  10580. conn->request_info.num_headers = 0;
  10581. conn->data_len = 0;
  10582. conn->chunk_remainder = 0;
  10583. }
  10584. #if 0
  10585. /* Note: set_sock_timeout is not required for non-blocking sockets.
  10586. * Leave this function here (commented out) for reference until
  10587. * CivetWeb 1.9 is tested, and the tests confirme this function is
  10588. * no longer required.
  10589. */
  10590. static int
  10591. set_sock_timeout(SOCKET sock, int milliseconds)
  10592. {
  10593. int r0 = 0, r1, r2;
  10594. #ifdef _WIN32
  10595. /* Windows specific */
  10596. DWORD tv = (DWORD)milliseconds;
  10597. #else
  10598. /* Linux, ... (not Windows) */
  10599. struct timeval tv;
  10600. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10601. * max. time waiting for the acknowledged of TCP data before the connection
  10602. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10603. * If this option is not set, the default timeout of 20-30 minutes is used.
  10604. */
  10605. /* #define TCP_USER_TIMEOUT (18) */
  10606. #if defined(TCP_USER_TIMEOUT)
  10607. unsigned int uto = (unsigned int)milliseconds;
  10608. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10609. #endif
  10610. memset(&tv, 0, sizeof(tv));
  10611. tv.tv_sec = milliseconds / 1000;
  10612. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10613. #endif /* _WIN32 */
  10614. r1 = setsockopt(
  10615. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10616. r2 = setsockopt(
  10617. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10618. return r0 || r1 || r2;
  10619. }
  10620. #endif
  10621. static int
  10622. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10623. {
  10624. if (setsockopt(sock,
  10625. IPPROTO_TCP,
  10626. TCP_NODELAY,
  10627. (SOCK_OPT_TYPE)&nodelay_on,
  10628. sizeof(nodelay_on)) != 0) {
  10629. /* Error */
  10630. return 1;
  10631. }
  10632. /* OK */
  10633. return 0;
  10634. }
  10635. static void
  10636. close_socket_gracefully(struct mg_connection *conn)
  10637. {
  10638. #if defined(_WIN32)
  10639. char buf[MG_BUF_LEN];
  10640. int n;
  10641. #endif
  10642. struct linger linger;
  10643. int error_code = 0;
  10644. int linger_timeout = -2;
  10645. socklen_t opt_len = sizeof(error_code);
  10646. if (!conn) {
  10647. return;
  10648. }
  10649. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  10650. * "Note that enabling a nonzero timeout on a nonblocking socket
  10651. * is not recommended.", so set it to blocking now */
  10652. set_blocking_mode(conn->client.sock, 1);
  10653. /* Send FIN to the client */
  10654. shutdown(conn->client.sock, SHUTDOWN_WR);
  10655. #if defined(_WIN32)
  10656. /* Read and discard pending incoming data. If we do not do that and
  10657. * close
  10658. * the socket, the data in the send buffer may be discarded. This
  10659. * behaviour is seen on Windows, when client keeps sending data
  10660. * when server decides to close the connection; then when client
  10661. * does recv() it gets no data back. */
  10662. do {
  10663. n = pull(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  10664. } while (n > 0);
  10665. #endif
  10666. if (conn->ctx->config[LINGER_TIMEOUT]) {
  10667. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  10668. }
  10669. /* Set linger option according to configuration */
  10670. if (linger_timeout >= 0) {
  10671. /* Set linger option to avoid socket hanging out after close. This
  10672. * prevent ephemeral port exhaust problem under high QPS. */
  10673. linger.l_onoff = 1;
  10674. #if defined(_MSC_VER)
  10675. #pragma warning(push)
  10676. #pragma warning(disable : 4244)
  10677. #endif
  10678. linger.l_linger = (linger_timeout + 999) / 1000;
  10679. #if defined(_MSC_VER)
  10680. #pragma warning(pop)
  10681. #endif
  10682. } else {
  10683. linger.l_onoff = 0;
  10684. linger.l_linger = 0;
  10685. }
  10686. if (linger_timeout < -1) {
  10687. /* Default: don't configure any linger */
  10688. } else if (getsockopt(conn->client.sock,
  10689. SOL_SOCKET,
  10690. SO_ERROR,
  10691. (char *)&error_code,
  10692. &opt_len) != 0) {
  10693. /* Cannot determine if socket is already closed. This should
  10694. * not occur and never did in a test. Log an error message
  10695. * and continue. */
  10696. mg_cry(conn,
  10697. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10698. __func__,
  10699. strerror(ERRNO));
  10700. } else if (error_code == ECONNRESET) {
  10701. /* Socket already closed by client/peer, close socket without linger */
  10702. } else {
  10703. /* Set linger timeout */
  10704. if (setsockopt(conn->client.sock,
  10705. SOL_SOCKET,
  10706. SO_LINGER,
  10707. (char *)&linger,
  10708. sizeof(linger)) != 0) {
  10709. mg_cry(conn,
  10710. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  10711. __func__,
  10712. linger.l_onoff,
  10713. linger.l_linger,
  10714. strerror(ERRNO));
  10715. }
  10716. }
  10717. /* Now we know that our FIN is ACK-ed, safe to close */
  10718. closesocket(conn->client.sock);
  10719. conn->client.sock = INVALID_SOCKET;
  10720. }
  10721. static void
  10722. close_connection(struct mg_connection *conn)
  10723. {
  10724. if (!conn || !conn->ctx) {
  10725. return;
  10726. }
  10727. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10728. if (conn->lua_websocket_state) {
  10729. lua_websocket_close(conn, conn->lua_websocket_state);
  10730. conn->lua_websocket_state = NULL;
  10731. }
  10732. #endif
  10733. /* call the connection_close callback if assigned */
  10734. if ((conn->ctx->callbacks.connection_close != NULL)
  10735. && (conn->ctx->context_type == 1)) {
  10736. conn->ctx->callbacks.connection_close(conn);
  10737. }
  10738. mg_lock_connection(conn);
  10739. conn->must_close = 1;
  10740. #ifndef NO_SSL
  10741. if (conn->ssl != NULL) {
  10742. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10743. */
  10744. SSL_shutdown(conn->ssl);
  10745. SSL_free(conn->ssl);
  10746. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10747. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10748. ERR_remove_state(0);
  10749. conn->ssl = NULL;
  10750. }
  10751. #endif
  10752. if (conn->client.sock != INVALID_SOCKET) {
  10753. close_socket_gracefully(conn);
  10754. conn->client.sock = INVALID_SOCKET;
  10755. }
  10756. mg_unlock_connection(conn);
  10757. }
  10758. void
  10759. mg_close_connection(struct mg_connection *conn)
  10760. {
  10761. struct mg_context *client_ctx = NULL;
  10762. if (conn == NULL) {
  10763. return;
  10764. }
  10765. #if defined(USE_WEBSOCKET)
  10766. if (conn->ctx->context_type == 2) {
  10767. unsigned int i;
  10768. /* ws/wss client */
  10769. client_ctx = conn->ctx;
  10770. /* client context: loops must end */
  10771. conn->ctx->stop_flag = 1;
  10772. /* We need to get the client thread out of the select/recv call here. */
  10773. /* Since we use a sleep quantum of some seconds to check for recv
  10774. * timeouts, we will just wait a few seconds in mg_join_thread. */
  10775. /* join worker thread */
  10776. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10777. if (client_ctx->worker_threadids[i] != 0) {
  10778. mg_join_thread(client_ctx->worker_threadids[i]);
  10779. }
  10780. }
  10781. }
  10782. #else
  10783. (void)client_ctx;
  10784. #endif
  10785. close_connection(conn);
  10786. #ifndef NO_SSL
  10787. if (conn->client_ssl_ctx != NULL) {
  10788. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10789. }
  10790. #endif
  10791. if (client_ctx != NULL) {
  10792. /* free context */
  10793. mg_free(client_ctx->worker_threadids);
  10794. mg_free(client_ctx);
  10795. (void)pthread_mutex_destroy(&conn->mutex);
  10796. mg_free(conn);
  10797. }
  10798. }
  10799. static struct mg_connection *
  10800. mg_connect_client_impl(const struct mg_client_options *client_options,
  10801. int use_ssl,
  10802. char *ebuf,
  10803. size_t ebuf_len)
  10804. {
  10805. static struct mg_context fake_ctx;
  10806. struct mg_connection *conn = NULL;
  10807. SOCKET sock;
  10808. union usa sa;
  10809. if (!connect_socket(&fake_ctx,
  10810. client_options->host,
  10811. client_options->port,
  10812. use_ssl,
  10813. ebuf,
  10814. ebuf_len,
  10815. &sock,
  10816. &sa)) {
  10817. ;
  10818. } else if ((conn = (struct mg_connection *)
  10819. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10820. mg_snprintf(NULL,
  10821. NULL, /* No truncation check for ebuf */
  10822. ebuf,
  10823. ebuf_len,
  10824. "calloc(): %s",
  10825. strerror(ERRNO));
  10826. closesocket(sock);
  10827. #ifndef NO_SSL
  10828. } else if (use_ssl
  10829. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10830. == NULL) {
  10831. mg_snprintf(NULL,
  10832. NULL, /* No truncation check for ebuf */
  10833. ebuf,
  10834. ebuf_len,
  10835. "SSL_CTX_new error");
  10836. closesocket(sock);
  10837. mg_free(conn);
  10838. conn = NULL;
  10839. #endif /* NO_SSL */
  10840. } else {
  10841. #ifdef USE_IPV6
  10842. socklen_t len = (sa.sa.sa_family == AF_INET)
  10843. ? sizeof(conn->client.rsa.sin)
  10844. : sizeof(conn->client.rsa.sin6);
  10845. struct sockaddr *psa =
  10846. (sa.sa.sa_family == AF_INET)
  10847. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10848. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10849. #else
  10850. socklen_t len = sizeof(conn->client.rsa.sin);
  10851. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10852. #endif
  10853. conn->buf_size = MAX_REQUEST_SIZE;
  10854. conn->buf = (char *)(conn + 1);
  10855. conn->ctx = &fake_ctx;
  10856. conn->client.sock = sock;
  10857. conn->client.lsa = sa;
  10858. if (getsockname(sock, psa, &len) != 0) {
  10859. mg_cry(conn,
  10860. "%s: getsockname() failed: %s",
  10861. __func__,
  10862. strerror(ERRNO));
  10863. }
  10864. conn->client.is_ssl = use_ssl ? 1 : 0;
  10865. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10866. #ifndef NO_SSL
  10867. if (use_ssl) {
  10868. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10869. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10870. * SSL_CTX_set_verify call is needed to switch off server
  10871. * certificate checking, which is off by default in OpenSSL and
  10872. * on in yaSSL. */
  10873. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10874. * SSL_VERIFY_PEER, verify_ssl_server); */
  10875. if (client_options->client_cert) {
  10876. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10877. mg_snprintf(NULL,
  10878. NULL, /* No truncation check for ebuf */
  10879. ebuf,
  10880. ebuf_len,
  10881. "Can not use SSL client certificate");
  10882. SSL_CTX_free(conn->client_ssl_ctx);
  10883. closesocket(sock);
  10884. mg_free(conn);
  10885. conn = NULL;
  10886. }
  10887. }
  10888. if (client_options->server_cert) {
  10889. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10890. client_options->server_cert,
  10891. NULL);
  10892. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10893. } else {
  10894. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10895. }
  10896. if (!sslize(conn,
  10897. conn->client_ssl_ctx,
  10898. SSL_connect,
  10899. &(conn->ctx->stop_flag))) {
  10900. mg_snprintf(NULL,
  10901. NULL, /* No truncation check for ebuf */
  10902. ebuf,
  10903. ebuf_len,
  10904. "SSL connection error");
  10905. SSL_CTX_free(conn->client_ssl_ctx);
  10906. closesocket(sock);
  10907. mg_free(conn);
  10908. conn = NULL;
  10909. }
  10910. }
  10911. #endif
  10912. }
  10913. if (conn) {
  10914. set_blocking_mode(sock, 0);
  10915. }
  10916. return conn;
  10917. }
  10918. CIVETWEB_API struct mg_connection *
  10919. mg_connect_client_secure(const struct mg_client_options *client_options,
  10920. char *error_buffer,
  10921. size_t error_buffer_size)
  10922. {
  10923. return mg_connect_client_impl(client_options,
  10924. 1,
  10925. error_buffer,
  10926. error_buffer_size);
  10927. }
  10928. struct mg_connection *
  10929. mg_connect_client(const char *host,
  10930. int port,
  10931. int use_ssl,
  10932. char *error_buffer,
  10933. size_t error_buffer_size)
  10934. {
  10935. struct mg_client_options opts;
  10936. memset(&opts, 0, sizeof(opts));
  10937. opts.host = host;
  10938. opts.port = port;
  10939. return mg_connect_client_impl(&opts,
  10940. use_ssl,
  10941. error_buffer,
  10942. error_buffer_size);
  10943. }
  10944. static const struct {
  10945. const char *proto;
  10946. size_t proto_len;
  10947. unsigned default_port;
  10948. } abs_uri_protocols[] = {{"http://", 7, 80},
  10949. {"https://", 8, 443},
  10950. {"ws://", 5, 80},
  10951. {"wss://", 6, 443},
  10952. {NULL, 0, 0}};
  10953. /* Check if the uri is valid.
  10954. * return 0 for invalid uri,
  10955. * return 1 for *,
  10956. * return 2 for relative uri,
  10957. * return 3 for absolute uri without port,
  10958. * return 4 for absolute uri with port */
  10959. static int
  10960. get_uri_type(const char *uri)
  10961. {
  10962. int i;
  10963. char *hostend, *portbegin, *portend;
  10964. unsigned long port;
  10965. /* According to the HTTP standard
  10966. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10967. * URI can be an asterisk (*) or should start with slash (relative uri),
  10968. * or it should start with the protocol (absolute uri). */
  10969. if (uri[0] == '*' && uri[1] == '\0') {
  10970. /* asterisk */
  10971. return 1;
  10972. }
  10973. /* Valid URIs according to RFC 3986
  10974. * (https://www.ietf.org/rfc/rfc3986.txt)
  10975. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  10976. * and unreserved characters A-Z a-z 0-9 and -._~
  10977. * and % encoded symbols.
  10978. */
  10979. for (i = 0; uri[i] != 0; i++) {
  10980. if (uri[i] < 33) {
  10981. /* control characters and spaces are invalid */
  10982. return 0;
  10983. }
  10984. if (uri[i] > 126) {
  10985. /* non-ascii characters must be % encoded */
  10986. return 0;
  10987. } else {
  10988. switch (uri[i]) {
  10989. case '"': /* 34 */
  10990. case '<': /* 60 */
  10991. case '>': /* 62 */
  10992. case '\\': /* 92 */
  10993. case '^': /* 94 */
  10994. case '`': /* 96 */
  10995. case '{': /* 123 */
  10996. case '|': /* 124 */
  10997. case '}': /* 125 */
  10998. return 0;
  10999. default:
  11000. /* character is ok */
  11001. break;
  11002. }
  11003. }
  11004. }
  11005. /* A relative uri starts with a / character */
  11006. if (uri[0] == '/') {
  11007. /* relative uri */
  11008. return 2;
  11009. }
  11010. /* It could be an absolute uri: */
  11011. /* This function only checks if the uri is valid, not if it is
  11012. * addressing the current server. So civetweb can also be used
  11013. * as a proxy server. */
  11014. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11015. if (mg_strncasecmp(uri,
  11016. abs_uri_protocols[i].proto,
  11017. abs_uri_protocols[i].proto_len) == 0) {
  11018. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11019. if (!hostend) {
  11020. return 0;
  11021. }
  11022. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11023. if (!portbegin) {
  11024. return 3;
  11025. }
  11026. port = strtoul(portbegin + 1, &portend, 10);
  11027. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11028. return 0;
  11029. }
  11030. return 4;
  11031. }
  11032. }
  11033. return 0;
  11034. }
  11035. /* Return NULL or the relative uri at the current server */
  11036. static const char *
  11037. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11038. {
  11039. const char *server_domain;
  11040. size_t server_domain_len;
  11041. size_t request_domain_len = 0;
  11042. unsigned long port = 0;
  11043. int i;
  11044. const char *hostbegin = NULL;
  11045. const char *hostend = NULL;
  11046. const char *portbegin;
  11047. char *portend;
  11048. /* DNS is case insensitive, so use case insensitive string compare here
  11049. */
  11050. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11051. if (!server_domain) {
  11052. return 0;
  11053. }
  11054. server_domain_len = strlen(server_domain);
  11055. if (!server_domain_len) {
  11056. return 0;
  11057. }
  11058. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11059. if (mg_strncasecmp(uri,
  11060. abs_uri_protocols[i].proto,
  11061. abs_uri_protocols[i].proto_len) == 0) {
  11062. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11063. hostend = strchr(hostbegin, '/');
  11064. if (!hostend) {
  11065. return 0;
  11066. }
  11067. portbegin = strchr(hostbegin, ':');
  11068. if ((!portbegin) || (portbegin > hostend)) {
  11069. port = abs_uri_protocols[i].default_port;
  11070. request_domain_len = (size_t)(hostend - hostbegin);
  11071. } else {
  11072. port = strtoul(portbegin + 1, &portend, 10);
  11073. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11074. return 0;
  11075. }
  11076. request_domain_len = (size_t)(portbegin - hostbegin);
  11077. }
  11078. /* protocol found, port set */
  11079. break;
  11080. }
  11081. }
  11082. if (!port) {
  11083. /* port remains 0 if the protocol is not found */
  11084. return 0;
  11085. }
  11086. /* Check if the request is directed to a different server. */
  11087. /* First check if the port is the same (IPv4 and IPv6). */
  11088. #if defined(USE_IPV6)
  11089. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11090. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11091. /* Request is directed to a different port */
  11092. return 0;
  11093. }
  11094. } else
  11095. #endif
  11096. {
  11097. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11098. /* Request is directed to a different port */
  11099. return 0;
  11100. }
  11101. }
  11102. /* Finally check if the server corresponds to the authentication
  11103. * domain of the server (the server domain).
  11104. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11105. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11106. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11107. * or http://mydomain.com.fake/path/file.ext).
  11108. */
  11109. if ((request_domain_len == server_domain_len)
  11110. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11111. /* Request is directed to this server - full name match. */
  11112. } else {
  11113. if (request_domain_len < (server_domain_len + 2)) {
  11114. /* Request is directed to another server: The server name is longer
  11115. * than
  11116. * the request name. Drop this case here to avoid overflows in the
  11117. * following checks. */
  11118. return 0;
  11119. }
  11120. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11121. /* Request is directed to another server: It could be a substring
  11122. * like notmyserver.com */
  11123. return 0;
  11124. }
  11125. if (0 != memcmp(server_domain,
  11126. hostbegin + request_domain_len - server_domain_len,
  11127. server_domain_len)) {
  11128. /* Request is directed to another server:
  11129. * The server name is different. */
  11130. return 0;
  11131. }
  11132. }
  11133. return hostend;
  11134. }
  11135. static int
  11136. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11137. {
  11138. const char *cl;
  11139. if (ebuf_len > 0) {
  11140. ebuf[0] = '\0';
  11141. }
  11142. *err = 0;
  11143. reset_per_request_attributes(conn);
  11144. if (!conn) {
  11145. mg_snprintf(conn,
  11146. NULL, /* No truncation check for ebuf */
  11147. ebuf,
  11148. ebuf_len,
  11149. "%s",
  11150. "Internal error");
  11151. *err = 500;
  11152. return 0;
  11153. }
  11154. /* Set the time the request was received. This value should be used for
  11155. * timeouts. */
  11156. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11157. conn->request_len =
  11158. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11159. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11160. */
  11161. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11162. mg_snprintf(conn,
  11163. NULL, /* No truncation check for ebuf */
  11164. ebuf,
  11165. ebuf_len,
  11166. "%s",
  11167. "Invalid request size");
  11168. *err = 500;
  11169. return 0;
  11170. }
  11171. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11172. mg_snprintf(conn,
  11173. NULL, /* No truncation check for ebuf */
  11174. ebuf,
  11175. ebuf_len,
  11176. "%s",
  11177. "Request Too Large");
  11178. *err = 413;
  11179. return 0;
  11180. } else if (conn->request_len <= 0) {
  11181. if (conn->data_len > 0) {
  11182. mg_snprintf(conn,
  11183. NULL, /* No truncation check for ebuf */
  11184. ebuf,
  11185. ebuf_len,
  11186. "%s",
  11187. "Client sent malformed request");
  11188. *err = 400;
  11189. } else {
  11190. /* Server did not recv anything -> just close the connection */
  11191. conn->must_close = 1;
  11192. mg_snprintf(conn,
  11193. NULL, /* No truncation check for ebuf */
  11194. ebuf,
  11195. ebuf_len,
  11196. "%s",
  11197. "Client did not send a request");
  11198. *err = 0;
  11199. }
  11200. return 0;
  11201. } else if (parse_http_message(conn->buf,
  11202. conn->buf_size,
  11203. &conn->request_info) <= 0) {
  11204. mg_snprintf(conn,
  11205. NULL, /* No truncation check for ebuf */
  11206. ebuf,
  11207. ebuf_len,
  11208. "%s",
  11209. "Bad Request");
  11210. *err = 400;
  11211. return 0;
  11212. } else {
  11213. /* Message is a valid request or response */
  11214. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11215. /* Request/response has content length set */
  11216. char *endptr = NULL;
  11217. conn->content_len = strtoll(cl, &endptr, 10);
  11218. if (endptr == cl) {
  11219. mg_snprintf(conn,
  11220. NULL, /* No truncation check for ebuf */
  11221. ebuf,
  11222. ebuf_len,
  11223. "%s",
  11224. "Bad Request");
  11225. *err = 411;
  11226. return 0;
  11227. }
  11228. /* Publish the content length back to the request info. */
  11229. conn->request_info.content_length = conn->content_len;
  11230. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11231. != NULL
  11232. && !mg_strcasecmp(cl, "chunked")) {
  11233. conn->is_chunked = 1;
  11234. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11235. || !mg_strcasecmp(conn->request_info.request_method,
  11236. "PUT")) {
  11237. /* POST or PUT request without content length set */
  11238. conn->content_len = -1;
  11239. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11240. "HTTP/",
  11241. 5)) {
  11242. /* Response without content length set */
  11243. conn->content_len = -1;
  11244. } else {
  11245. /* Other request */
  11246. conn->content_len = 0;
  11247. }
  11248. }
  11249. return 1;
  11250. }
  11251. int
  11252. mg_get_response(struct mg_connection *conn,
  11253. char *ebuf,
  11254. size_t ebuf_len,
  11255. int timeout)
  11256. {
  11257. if (conn) {
  11258. /* Implementation of API function for HTTP clients */
  11259. int err, ret;
  11260. struct mg_context *octx = conn->ctx;
  11261. struct mg_context rctx = *(conn->ctx);
  11262. char txt[32]; /* will not overflow */
  11263. if (timeout >= 0) {
  11264. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11265. rctx.config[REQUEST_TIMEOUT] = txt;
  11266. /* Not required for non-blocking sockets.
  11267. set_sock_timeout(conn->client.sock, timeout);
  11268. */
  11269. } else {
  11270. rctx.config[REQUEST_TIMEOUT] = NULL;
  11271. }
  11272. conn->ctx = &rctx;
  11273. ret = getreq(conn, ebuf, ebuf_len, &err);
  11274. conn->ctx = octx;
  11275. /* TODO: 1) uri is deprecated;
  11276. * 2) here, ri.uri is the http response code */
  11277. conn->request_info.uri = conn->request_info.request_uri;
  11278. /* TODO (mid): Define proper return values - maybe return length?
  11279. * For the first test use <0 for error and >0 for OK */
  11280. return (ret == 0) ? -1 : +1;
  11281. }
  11282. return -1;
  11283. }
  11284. struct mg_connection *
  11285. mg_download(const char *host,
  11286. int port,
  11287. int use_ssl,
  11288. char *ebuf,
  11289. size_t ebuf_len,
  11290. const char *fmt,
  11291. ...)
  11292. {
  11293. struct mg_connection *conn;
  11294. va_list ap;
  11295. int i;
  11296. int reqerr;
  11297. va_start(ap, fmt);
  11298. ebuf[0] = '\0';
  11299. /* open a connection */
  11300. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11301. if (conn != NULL) {
  11302. i = mg_vprintf(conn, fmt, ap);
  11303. if (i <= 0) {
  11304. mg_snprintf(conn,
  11305. NULL, /* No truncation check for ebuf */
  11306. ebuf,
  11307. ebuf_len,
  11308. "%s",
  11309. "Error sending request");
  11310. } else {
  11311. getreq(conn, ebuf, ebuf_len, &reqerr);
  11312. /* TODO: 1) uri is deprecated;
  11313. * 2) here, ri.uri is the http response code */
  11314. conn->request_info.uri = conn->request_info.request_uri;
  11315. }
  11316. }
  11317. /* if an error occured, close the connection */
  11318. if (ebuf[0] != '\0' && conn != NULL) {
  11319. mg_close_connection(conn);
  11320. conn = NULL;
  11321. }
  11322. va_end(ap);
  11323. return conn;
  11324. }
  11325. struct websocket_client_thread_data {
  11326. struct mg_connection *conn;
  11327. mg_websocket_data_handler data_handler;
  11328. mg_websocket_close_handler close_handler;
  11329. void *callback_data;
  11330. };
  11331. #if defined(USE_WEBSOCKET)
  11332. #ifdef _WIN32
  11333. static unsigned __stdcall websocket_client_thread(void *data)
  11334. #else
  11335. static void *
  11336. websocket_client_thread(void *data)
  11337. #endif
  11338. {
  11339. struct websocket_client_thread_data *cdata =
  11340. (struct websocket_client_thread_data *)data;
  11341. mg_set_thread_name("ws-clnt");
  11342. if (cdata->conn->ctx) {
  11343. if (cdata->conn->ctx->callbacks.init_thread) {
  11344. /* 3 indicates a websocket client thread */
  11345. /* TODO: check if conn->ctx can be set */
  11346. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11347. }
  11348. }
  11349. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11350. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11351. if (cdata->close_handler != NULL) {
  11352. cdata->close_handler(cdata->conn, cdata->callback_data);
  11353. }
  11354. /* The websocket_client context has only this thread. If it runs out,
  11355. set the stop_flag to 2 (= "stopped"). */
  11356. cdata->conn->ctx->stop_flag = 2;
  11357. mg_free((void *)cdata);
  11358. #ifdef _WIN32
  11359. return 0;
  11360. #else
  11361. return NULL;
  11362. #endif
  11363. }
  11364. #endif
  11365. struct mg_connection *
  11366. mg_connect_websocket_client(const char *host,
  11367. int port,
  11368. int use_ssl,
  11369. char *error_buffer,
  11370. size_t error_buffer_size,
  11371. const char *path,
  11372. const char *origin,
  11373. mg_websocket_data_handler data_func,
  11374. mg_websocket_close_handler close_func,
  11375. void *user_data)
  11376. {
  11377. struct mg_connection *conn = NULL;
  11378. #if defined(USE_WEBSOCKET)
  11379. struct mg_context *newctx = NULL;
  11380. struct websocket_client_thread_data *thread_data;
  11381. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11382. static const char *handshake_req;
  11383. if (origin != NULL) {
  11384. handshake_req = "GET %s HTTP/1.1\r\n"
  11385. "Host: %s\r\n"
  11386. "Upgrade: websocket\r\n"
  11387. "Connection: Upgrade\r\n"
  11388. "Sec-WebSocket-Key: %s\r\n"
  11389. "Sec-WebSocket-Version: 13\r\n"
  11390. "Origin: %s\r\n"
  11391. "\r\n";
  11392. } else {
  11393. handshake_req = "GET %s HTTP/1.1\r\n"
  11394. "Host: %s\r\n"
  11395. "Upgrade: websocket\r\n"
  11396. "Connection: Upgrade\r\n"
  11397. "Sec-WebSocket-Key: %s\r\n"
  11398. "Sec-WebSocket-Version: 13\r\n"
  11399. "\r\n";
  11400. }
  11401. /* Establish the client connection and request upgrade */
  11402. conn = mg_download(host,
  11403. port,
  11404. use_ssl,
  11405. error_buffer,
  11406. error_buffer_size,
  11407. handshake_req,
  11408. path,
  11409. host,
  11410. magic,
  11411. origin);
  11412. /* Connection object will be null if something goes wrong */
  11413. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11414. if (!*error_buffer) {
  11415. /* if there is a connection, but it did not return 101,
  11416. * error_buffer is not yet set */
  11417. mg_snprintf(conn,
  11418. NULL, /* No truncation check for ebuf */
  11419. error_buffer,
  11420. error_buffer_size,
  11421. "Unexpected server reply");
  11422. }
  11423. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11424. if (conn != NULL) {
  11425. mg_free(conn);
  11426. conn = NULL;
  11427. }
  11428. return conn;
  11429. }
  11430. /* For client connections, mg_context is fake. Since we need to set a
  11431. * callback function, we need to create a copy and modify it. */
  11432. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11433. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11434. newctx->user_data = user_data;
  11435. newctx->context_type = 2; /* ws/wss client context type */
  11436. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11437. newctx->worker_threadids =
  11438. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11439. conn->ctx = newctx;
  11440. thread_data = (struct websocket_client_thread_data *)
  11441. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11442. thread_data->conn = conn;
  11443. thread_data->data_handler = data_func;
  11444. thread_data->close_handler = close_func;
  11445. thread_data->callback_data = NULL;
  11446. /* Start a thread to read the websocket client connection
  11447. * This thread will automatically stop when mg_disconnect is
  11448. * called on the client connection */
  11449. if (mg_start_thread_with_id(websocket_client_thread,
  11450. (void *)thread_data,
  11451. newctx->worker_threadids) != 0) {
  11452. mg_free((void *)thread_data);
  11453. mg_free((void *)newctx->worker_threadids);
  11454. mg_free((void *)newctx);
  11455. mg_free((void *)conn);
  11456. conn = NULL;
  11457. DEBUG_TRACE("%s",
  11458. "Websocket client connect thread could not be started\r\n");
  11459. }
  11460. #else
  11461. /* Appease "unused parameter" warnings */
  11462. (void)host;
  11463. (void)port;
  11464. (void)use_ssl;
  11465. (void)error_buffer;
  11466. (void)error_buffer_size;
  11467. (void)path;
  11468. (void)origin;
  11469. (void)user_data;
  11470. (void)data_func;
  11471. (void)close_func;
  11472. #endif
  11473. return conn;
  11474. }
  11475. static void
  11476. process_new_connection(struct mg_connection *conn)
  11477. {
  11478. if (conn && conn->ctx) {
  11479. struct mg_request_info *ri = &conn->request_info;
  11480. int keep_alive_enabled, keep_alive, discard_len;
  11481. char ebuf[100];
  11482. const char *hostend;
  11483. int reqerr, uri_type;
  11484. keep_alive_enabled =
  11485. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11486. /* Important: on new connection, reset the receiving buffer. Credit
  11487. * goes to crule42. */
  11488. conn->data_len = 0;
  11489. conn->handled_requests = 0;
  11490. do {
  11491. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11492. conn->handled_requests + 1);
  11493. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11494. /* The request sent by the client could not be understood by
  11495. * the server, or it was incomplete or a timeout. Send an
  11496. * error message and close the connection. */
  11497. if (reqerr > 0) {
  11498. /*assert(ebuf[0] != '\0');*/
  11499. send_http_error(conn, reqerr, "%s", ebuf);
  11500. }
  11501. } else if (strcmp(ri->http_version, "1.0")
  11502. && strcmp(ri->http_version, "1.1")) {
  11503. mg_snprintf(conn,
  11504. NULL, /* No truncation check for ebuf */
  11505. ebuf,
  11506. sizeof(ebuf),
  11507. "Bad HTTP version: [%s]",
  11508. ri->http_version);
  11509. send_http_error(conn, 505, "%s", ebuf);
  11510. }
  11511. if (ebuf[0] == '\0') {
  11512. uri_type = get_uri_type(conn->request_info.request_uri);
  11513. switch (uri_type) {
  11514. case 1:
  11515. /* Asterisk */
  11516. conn->request_info.local_uri = NULL;
  11517. break;
  11518. case 2:
  11519. /* relative uri */
  11520. conn->request_info.local_uri =
  11521. conn->request_info.request_uri;
  11522. break;
  11523. case 3:
  11524. case 4:
  11525. /* absolute uri (with/without port) */
  11526. hostend = get_rel_url_at_current_server(
  11527. conn->request_info.request_uri, conn);
  11528. if (hostend) {
  11529. conn->request_info.local_uri = hostend;
  11530. } else {
  11531. conn->request_info.local_uri = NULL;
  11532. }
  11533. break;
  11534. default:
  11535. mg_snprintf(conn,
  11536. NULL, /* No truncation check for ebuf */
  11537. ebuf,
  11538. sizeof(ebuf),
  11539. "Invalid URI");
  11540. send_http_error(conn, 400, "%s", ebuf);
  11541. conn->request_info.local_uri = NULL;
  11542. break;
  11543. }
  11544. /* TODO: cleanup uri, local_uri and request_uri */
  11545. conn->request_info.uri = conn->request_info.local_uri;
  11546. }
  11547. DEBUG_TRACE("http: %s, error: %s",
  11548. (ri->http_version ? ri->http_version : "none"),
  11549. (ebuf[0] ? ebuf : "none"));
  11550. if (ebuf[0] == '\0') {
  11551. if (conn->request_info.local_uri) {
  11552. /* handle request to local server */
  11553. handle_request(conn);
  11554. DEBUG_TRACE("%s", "handle_request done");
  11555. if (conn->ctx->callbacks.end_request != NULL) {
  11556. conn->ctx->callbacks.end_request(conn,
  11557. conn->status_code);
  11558. DEBUG_TRACE("%s", "end_request callback done");
  11559. }
  11560. log_access(conn);
  11561. } else {
  11562. /* TODO: handle non-local request (PROXY) */
  11563. conn->must_close = 1;
  11564. }
  11565. } else {
  11566. conn->must_close = 1;
  11567. }
  11568. if (ri->remote_user != NULL) {
  11569. mg_free((void *)ri->remote_user);
  11570. /* Important! When having connections with and without auth
  11571. * would cause double free and then crash */
  11572. ri->remote_user = NULL;
  11573. }
  11574. /* NOTE(lsm): order is important here. should_keep_alive() call
  11575. * is
  11576. * using parsed request, which will be invalid after memmove's
  11577. * below.
  11578. * Therefore, memorize should_keep_alive() result now for later
  11579. * use
  11580. * in loop exit condition. */
  11581. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11582. && (conn->content_len >= 0) && should_keep_alive(conn);
  11583. /* Discard all buffered data for this request */
  11584. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11585. && ((conn->request_len + conn->content_len)
  11586. < (int64_t)conn->data_len))
  11587. ? (int)(conn->request_len + conn->content_len)
  11588. : conn->data_len;
  11589. /*assert(discard_len >= 0);*/
  11590. if (discard_len < 0) {
  11591. DEBUG_TRACE("internal error: discard_len = %li",
  11592. (long int)discard_len);
  11593. break;
  11594. }
  11595. conn->data_len -= discard_len;
  11596. if (conn->data_len > 0) {
  11597. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  11598. memmove(conn->buf,
  11599. conn->buf + discard_len,
  11600. (size_t)conn->data_len);
  11601. }
  11602. /* assert(conn->data_len >= 0); */
  11603. /* assert(conn->data_len <= conn->buf_size); */
  11604. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11605. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  11606. (long int)conn->data_len,
  11607. (long int)conn->buf_size);
  11608. break;
  11609. }
  11610. conn->handled_requests++;
  11611. } while (keep_alive);
  11612. }
  11613. }
  11614. #if defined(ALTERNATIVE_QUEUE)
  11615. static void
  11616. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11617. {
  11618. unsigned int i;
  11619. for (;;) {
  11620. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11621. /* find a free worker slot and signal it */
  11622. if (ctx->client_socks[i].in_use == 0) {
  11623. ctx->client_socks[i] = *sp;
  11624. ctx->client_socks[i].in_use = 1;
  11625. event_signal(ctx->client_wait_events[i]);
  11626. return;
  11627. }
  11628. }
  11629. /* queue is full */
  11630. mg_sleep(1);
  11631. }
  11632. }
  11633. static int
  11634. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11635. {
  11636. DEBUG_TRACE("%s", "going idle");
  11637. ctx->client_socks[thread_index].in_use = 0;
  11638. event_wait(ctx->client_wait_events[thread_index]);
  11639. *sp = ctx->client_socks[thread_index];
  11640. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11641. return !ctx->stop_flag;
  11642. }
  11643. #else /* ALTERNATIVE_QUEUE */
  11644. /* Worker threads take accepted socket from the queue */
  11645. static int
  11646. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11647. {
  11648. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11649. (void)thread_index;
  11650. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11651. DEBUG_TRACE("%s", "going idle");
  11652. /* If the queue is empty, wait. We're idle at this point. */
  11653. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11654. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11655. }
  11656. /* If we're stopping, sq_head may be equal to sq_tail. */
  11657. if (ctx->sq_head > ctx->sq_tail) {
  11658. /* Copy socket from the queue and increment tail */
  11659. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11660. ctx->sq_tail++;
  11661. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11662. /* Wrap pointers if needed */
  11663. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11664. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11665. ctx->sq_head -= QUEUE_SIZE(ctx);
  11666. }
  11667. }
  11668. (void)pthread_cond_signal(&ctx->sq_empty);
  11669. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11670. return !ctx->stop_flag;
  11671. #undef QUEUE_SIZE
  11672. }
  11673. /* Master thread adds accepted socket to a queue */
  11674. static void
  11675. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11676. {
  11677. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11678. if (!ctx) {
  11679. return;
  11680. }
  11681. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11682. /* If the queue is full, wait */
  11683. while (ctx->stop_flag == 0
  11684. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11685. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11686. }
  11687. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11688. /* Copy socket to the queue and increment head */
  11689. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11690. ctx->sq_head++;
  11691. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11692. }
  11693. (void)pthread_cond_signal(&ctx->sq_full);
  11694. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11695. #undef QUEUE_SIZE
  11696. }
  11697. #endif /* ALTERNATIVE_QUEUE */
  11698. struct worker_thread_args {
  11699. struct mg_context *ctx;
  11700. int index;
  11701. };
  11702. static void *
  11703. worker_thread_run(struct worker_thread_args *thread_args)
  11704. {
  11705. struct mg_context *ctx = thread_args->ctx;
  11706. struct mg_connection *conn;
  11707. struct mg_workerTLS tls;
  11708. #if defined(MG_LEGACY_INTERFACE)
  11709. uint32_t addr;
  11710. #endif
  11711. mg_set_thread_name("worker");
  11712. tls.is_master = 0;
  11713. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11714. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11715. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11716. #endif
  11717. if (ctx->callbacks.init_thread) {
  11718. /* call init_thread for a worker thread (type 1) */
  11719. ctx->callbacks.init_thread(ctx, 1);
  11720. }
  11721. conn = &ctx->worker_connections[thread_args->index];
  11722. pthread_setspecific(sTlsKey, &tls);
  11723. conn->buf_size = MAX_REQUEST_SIZE;
  11724. conn->buf = (char *)(conn + 1);
  11725. conn->ctx = ctx;
  11726. conn->thread_index = thread_args->index;
  11727. conn->request_info.user_data = ctx->user_data;
  11728. /* Allocate a mutex for this connection to allow communication both
  11729. * within the request handler and from elsewhere in the application
  11730. */
  11731. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11732. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11733. * signal sq_empty condvar to wake up the master waiting in
  11734. * produce_socket() */
  11735. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11736. conn->conn_birth_time = time(NULL);
  11737. /* Fill in IP, port info early so even if SSL setup below fails,
  11738. * error handler would have the corresponding info.
  11739. * Thanks to Johannes Winkelmann for the patch.
  11740. */
  11741. #if defined(USE_IPV6)
  11742. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11743. conn->request_info.remote_port =
  11744. ntohs(conn->client.rsa.sin6.sin6_port);
  11745. } else
  11746. #endif
  11747. {
  11748. conn->request_info.remote_port =
  11749. ntohs(conn->client.rsa.sin.sin_port);
  11750. }
  11751. sockaddr_to_string(conn->request_info.remote_addr,
  11752. sizeof(conn->request_info.remote_addr),
  11753. &conn->client.rsa);
  11754. DEBUG_TRACE("Start processing connection from %s",
  11755. conn->request_info.remote_addr);
  11756. #if defined(MG_LEGACY_INTERFACE)
  11757. /* This legacy interface only works for the IPv4 case */
  11758. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11759. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11760. #endif
  11761. conn->request_info.is_ssl = conn->client.is_ssl;
  11762. if (conn->client.is_ssl) {
  11763. #ifndef NO_SSL
  11764. /* HTTPS connection */
  11765. if (sslize(conn,
  11766. conn->ctx->ssl_ctx,
  11767. SSL_accept,
  11768. &(conn->ctx->stop_flag))) {
  11769. /* Get SSL client certificate information (if set) */
  11770. ssl_get_client_cert_info(conn);
  11771. /* process HTTPS connection */
  11772. process_new_connection(conn);
  11773. /* Free client certificate info */
  11774. if (conn->request_info.client_cert) {
  11775. mg_free((void *)(conn->request_info.client_cert->subject));
  11776. mg_free((void *)(conn->request_info.client_cert->issuer));
  11777. mg_free((void *)(conn->request_info.client_cert->serial));
  11778. mg_free((void *)(conn->request_info.client_cert->finger));
  11779. conn->request_info.client_cert->subject = 0;
  11780. conn->request_info.client_cert->issuer = 0;
  11781. conn->request_info.client_cert->serial = 0;
  11782. conn->request_info.client_cert->finger = 0;
  11783. mg_free(conn->request_info.client_cert);
  11784. conn->request_info.client_cert = 0;
  11785. }
  11786. }
  11787. #endif
  11788. } else {
  11789. /* process HTTP connection */
  11790. process_new_connection(conn);
  11791. }
  11792. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  11793. conn->request_info.remote_addr,
  11794. difftime(time(NULL), conn->conn_birth_time));
  11795. close_connection(conn);
  11796. DEBUG_TRACE("%s", "Connection closed");
  11797. }
  11798. pthread_setspecific(sTlsKey, NULL);
  11799. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11800. CloseHandle(tls.pthread_cond_helper_mutex);
  11801. #endif
  11802. pthread_mutex_destroy(&conn->mutex);
  11803. DEBUG_TRACE("%s", "exiting");
  11804. return NULL;
  11805. }
  11806. /* Threads have different return types on Windows and Unix. */
  11807. #ifdef _WIN32
  11808. static unsigned __stdcall worker_thread(void *thread_func_param)
  11809. {
  11810. struct worker_thread_args *pwta =
  11811. (struct worker_thread_args *)thread_func_param;
  11812. worker_thread_run(pwta);
  11813. mg_free(thread_func_param);
  11814. return 0;
  11815. }
  11816. #else
  11817. static void *
  11818. worker_thread(void *thread_func_param)
  11819. {
  11820. struct worker_thread_args *pwta =
  11821. (struct worker_thread_args *)thread_func_param;
  11822. worker_thread_run(pwta);
  11823. mg_free(thread_func_param);
  11824. return NULL;
  11825. }
  11826. #endif /* _WIN32 */
  11827. static void
  11828. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11829. {
  11830. struct socket so;
  11831. char src_addr[IP_ADDR_STR_LEN];
  11832. socklen_t len = sizeof(so.rsa);
  11833. int on = 1;
  11834. if (!listener) {
  11835. return;
  11836. }
  11837. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11838. == INVALID_SOCKET) {
  11839. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11840. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11841. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11842. closesocket(so.sock);
  11843. so.sock = INVALID_SOCKET;
  11844. } else {
  11845. /* Put so socket structure into the queue */
  11846. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11847. set_close_on_exec(so.sock, fc(ctx));
  11848. so.is_ssl = listener->is_ssl;
  11849. so.ssl_redir = listener->ssl_redir;
  11850. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11851. mg_cry(fc(ctx),
  11852. "%s: getsockname() failed: %s",
  11853. __func__,
  11854. strerror(ERRNO));
  11855. }
  11856. /* Set TCP keep-alive. This is needed because if HTTP-level
  11857. * keep-alive
  11858. * is enabled, and client resets the connection, server won't get
  11859. * TCP FIN or RST and will keep the connection open forever. With
  11860. * TCP keep-alive, next keep-alive handshake will figure out that
  11861. * the client is down and will close the server end.
  11862. * Thanks to Igor Klopov who suggested the patch. */
  11863. if (setsockopt(so.sock,
  11864. SOL_SOCKET,
  11865. SO_KEEPALIVE,
  11866. (SOCK_OPT_TYPE)&on,
  11867. sizeof(on)) != 0) {
  11868. mg_cry(fc(ctx),
  11869. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11870. __func__,
  11871. strerror(ERRNO));
  11872. }
  11873. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11874. * to effectively fill up the underlying IP packet payload and
  11875. * reduce the overhead of sending lots of small buffers. However
  11876. * this hurts the server's throughput (ie. operations per second)
  11877. * when HTTP 1.1 persistent connections are used and the responses
  11878. * are relatively small (eg. less than 1400 bytes).
  11879. */
  11880. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11881. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11882. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11883. mg_cry(fc(ctx),
  11884. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11885. __func__,
  11886. strerror(ERRNO));
  11887. }
  11888. }
  11889. /* We are using non-blocking sockets. Thus, the
  11890. * set_sock_timeout(so.sock, timeout);
  11891. * call is no longer required. */
  11892. set_blocking_mode(so.sock, 0);
  11893. produce_socket(ctx, &so);
  11894. }
  11895. }
  11896. static void
  11897. master_thread_run(void *thread_func_param)
  11898. {
  11899. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11900. struct mg_workerTLS tls;
  11901. struct pollfd *pfd;
  11902. unsigned int i;
  11903. unsigned int workerthreadcount;
  11904. if (!ctx) {
  11905. return;
  11906. }
  11907. mg_set_thread_name("master");
  11908. /* Increase priority of the master thread */
  11909. #if defined(_WIN32)
  11910. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11911. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11912. int min_prio = sched_get_priority_min(SCHED_RR);
  11913. int max_prio = sched_get_priority_max(SCHED_RR);
  11914. if ((min_prio >= 0) && (max_prio >= 0)
  11915. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11916. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11917. struct sched_param sched_param = {0};
  11918. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11919. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11920. }
  11921. #endif
  11922. /* Initialize thread local storage */
  11923. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11924. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11925. #endif
  11926. tls.is_master = 1;
  11927. pthread_setspecific(sTlsKey, &tls);
  11928. if (ctx->callbacks.init_thread) {
  11929. /* Callback for the master thread (type 0) */
  11930. ctx->callbacks.init_thread(ctx, 0);
  11931. }
  11932. /* Server starts *now* */
  11933. ctx->start_time = time(NULL);
  11934. /* Start the server */
  11935. pfd = ctx->listening_socket_fds;
  11936. while (ctx->stop_flag == 0) {
  11937. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11938. pfd[i].fd = ctx->listening_sockets[i].sock;
  11939. pfd[i].events = POLLIN;
  11940. }
  11941. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11942. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11943. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11944. * successful poll, and POLLIN is defined as
  11945. * (POLLRDNORM | POLLRDBAND)
  11946. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11947. * pfd[i].revents == POLLIN. */
  11948. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11949. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11950. }
  11951. }
  11952. }
  11953. }
  11954. /* Here stop_flag is 1 - Initiate shutdown. */
  11955. DEBUG_TRACE("%s", "stopping workers");
  11956. /* Stop signal received: somebody called mg_stop. Quit. */
  11957. close_all_listening_sockets(ctx);
  11958. /* Wakeup workers that are waiting for connections to handle. */
  11959. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11960. #if defined(ALTERNATIVE_QUEUE)
  11961. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11962. event_signal(ctx->client_wait_events[i]);
  11963. /* Since we know all sockets, we can shutdown the connections. */
  11964. if (ctx->client_socks[i].in_use) {
  11965. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11966. }
  11967. }
  11968. #else
  11969. pthread_cond_broadcast(&ctx->sq_full);
  11970. #endif
  11971. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11972. /* Join all worker threads to avoid leaking threads. */
  11973. workerthreadcount = ctx->cfg_worker_threads;
  11974. for (i = 0; i < workerthreadcount; i++) {
  11975. if (ctx->worker_threadids[i] != 0) {
  11976. mg_join_thread(ctx->worker_threadids[i]);
  11977. }
  11978. }
  11979. #if defined(USE_LUA)
  11980. /* Free Lua state of lua background task */
  11981. if (ctx->lua_background_state) {
  11982. lua_close((lua_State *)ctx->lua_background_state);
  11983. ctx->lua_background_state = 0;
  11984. }
  11985. #endif
  11986. #if !defined(NO_SSL)
  11987. if (ctx->ssl_ctx != NULL) {
  11988. uninitialize_ssl(ctx);
  11989. }
  11990. #endif
  11991. DEBUG_TRACE("%s", "exiting");
  11992. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11993. CloseHandle(tls.pthread_cond_helper_mutex);
  11994. #endif
  11995. pthread_setspecific(sTlsKey, NULL);
  11996. /* Signal mg_stop() that we're done.
  11997. * WARNING: This must be the very last thing this
  11998. * thread does, as ctx becomes invalid after this line. */
  11999. ctx->stop_flag = 2;
  12000. }
  12001. /* Threads have different return types on Windows and Unix. */
  12002. #ifdef _WIN32
  12003. static unsigned __stdcall master_thread(void *thread_func_param)
  12004. {
  12005. master_thread_run(thread_func_param);
  12006. return 0;
  12007. }
  12008. #else
  12009. static void *
  12010. master_thread(void *thread_func_param)
  12011. {
  12012. master_thread_run(thread_func_param);
  12013. return NULL;
  12014. }
  12015. #endif /* _WIN32 */
  12016. static void
  12017. free_context(struct mg_context *ctx)
  12018. {
  12019. int i;
  12020. struct mg_handler_info *tmp_rh;
  12021. if (ctx == NULL) {
  12022. return;
  12023. }
  12024. if (ctx->callbacks.exit_context) {
  12025. ctx->callbacks.exit_context(ctx);
  12026. }
  12027. /* All threads exited, no sync is needed. Destroy thread mutex and
  12028. * condvars
  12029. */
  12030. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12031. #if defined(ALTERNATIVE_QUEUE)
  12032. mg_free(ctx->client_socks);
  12033. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12034. event_destroy(ctx->client_wait_events[i]);
  12035. }
  12036. mg_free(ctx->client_wait_events);
  12037. #else
  12038. (void)pthread_cond_destroy(&ctx->sq_empty);
  12039. (void)pthread_cond_destroy(&ctx->sq_full);
  12040. #endif
  12041. /* Destroy other context global data structures mutex */
  12042. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12043. #if defined(USE_TIMERS)
  12044. timers_exit(ctx);
  12045. #endif
  12046. /* Deallocate config parameters */
  12047. for (i = 0; i < NUM_OPTIONS; i++) {
  12048. if (ctx->config[i] != NULL) {
  12049. #if defined(_MSC_VER)
  12050. #pragma warning(suppress : 6001)
  12051. #endif
  12052. mg_free(ctx->config[i]);
  12053. }
  12054. }
  12055. /* Deallocate request handlers */
  12056. while (ctx->handlers) {
  12057. tmp_rh = ctx->handlers;
  12058. ctx->handlers = tmp_rh->next;
  12059. mg_free(tmp_rh->uri);
  12060. mg_free(tmp_rh);
  12061. }
  12062. #ifndef NO_SSL
  12063. /* Deallocate SSL context */
  12064. if (ctx->ssl_ctx != NULL) {
  12065. SSL_CTX_free(ctx->ssl_ctx);
  12066. }
  12067. #endif /* !NO_SSL */
  12068. /* Deallocate worker thread ID array */
  12069. if (ctx->worker_threadids != NULL) {
  12070. mg_free(ctx->worker_threadids);
  12071. }
  12072. /* Deallocate worker thread ID array */
  12073. if (ctx->worker_connections != NULL) {
  12074. mg_free(ctx->worker_connections);
  12075. }
  12076. /* Deallocate the tls variable */
  12077. if (mg_atomic_dec(&sTlsInit) == 0) {
  12078. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12079. DeleteCriticalSection(&global_log_file_lock);
  12080. #endif /* _WIN32 && !__SYMBIAN32__ */
  12081. #if !defined(_WIN32)
  12082. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12083. #endif
  12084. pthread_key_delete(sTlsKey);
  12085. #if defined(USE_LUA)
  12086. lua_exit_optional_libraries();
  12087. #endif
  12088. }
  12089. /* deallocate system name string */
  12090. mg_free(ctx->systemName);
  12091. /* Deallocate context itself */
  12092. mg_free(ctx);
  12093. }
  12094. void
  12095. mg_stop(struct mg_context *ctx)
  12096. {
  12097. pthread_t mt;
  12098. if (!ctx) {
  12099. return;
  12100. }
  12101. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12102. * two threads is not allowed. */
  12103. mt = ctx->masterthreadid;
  12104. if (mt == 0) {
  12105. return;
  12106. }
  12107. ctx->masterthreadid = 0;
  12108. /* Set stop flag, so all threads know they have to exit. */
  12109. ctx->stop_flag = 1;
  12110. /* Wait until everything has stopped. */
  12111. while (ctx->stop_flag != 2) {
  12112. (void)mg_sleep(10);
  12113. }
  12114. mg_join_thread(mt);
  12115. free_context(ctx);
  12116. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12117. (void)WSACleanup();
  12118. #endif /* _WIN32 && !__SYMBIAN32__ */
  12119. }
  12120. static void
  12121. get_system_name(char **sysName)
  12122. {
  12123. #if defined(_WIN32)
  12124. #if !defined(__SYMBIAN32__)
  12125. #if defined(_WIN32_WCE)
  12126. *sysName = mg_strdup("WinCE");
  12127. #else
  12128. char name[128];
  12129. DWORD dwVersion = 0;
  12130. DWORD dwMajorVersion = 0;
  12131. DWORD dwMinorVersion = 0;
  12132. DWORD dwBuild = 0;
  12133. #ifdef _MSC_VER
  12134. #pragma warning(push)
  12135. /* GetVersion was declared deprecated */
  12136. #pragma warning(disable : 4996)
  12137. #endif
  12138. dwVersion = GetVersion();
  12139. #ifdef _MSC_VER
  12140. #pragma warning(pop)
  12141. #endif
  12142. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12143. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12144. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12145. (void)dwBuild;
  12146. sprintf(name,
  12147. "Windows %u.%u",
  12148. (unsigned)dwMajorVersion,
  12149. (unsigned)dwMinorVersion);
  12150. *sysName = mg_strdup(name);
  12151. #endif
  12152. #else
  12153. *sysName = mg_strdup("Symbian");
  12154. #endif
  12155. #else
  12156. struct utsname name;
  12157. memset(&name, 0, sizeof(name));
  12158. uname(&name);
  12159. *sysName = mg_strdup(name.sysname);
  12160. #endif
  12161. }
  12162. struct mg_context *
  12163. mg_start(const struct mg_callbacks *callbacks,
  12164. void *user_data,
  12165. const char **options)
  12166. {
  12167. struct mg_context *ctx;
  12168. const char *name, *value, *default_value;
  12169. int idx, ok, workerthreadcount;
  12170. unsigned int i;
  12171. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12172. struct mg_workerTLS tls;
  12173. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12174. WSADATA data;
  12175. WSAStartup(MAKEWORD(2, 2), &data);
  12176. #endif /* _WIN32 && !__SYMBIAN32__ */
  12177. /* Allocate context and initialize reasonable general case defaults. */
  12178. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12179. return NULL;
  12180. }
  12181. /* Random number generator will initialize at the first call */
  12182. ctx->auth_nonce_mask =
  12183. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12184. if (mg_atomic_inc(&sTlsInit) == 1) {
  12185. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12186. InitializeCriticalSection(&global_log_file_lock);
  12187. #endif /* _WIN32 && !__SYMBIAN32__ */
  12188. #if !defined(_WIN32)
  12189. pthread_mutexattr_init(&pthread_mutex_attr);
  12190. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12191. #endif
  12192. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12193. /* Fatal error - abort start. However, this situation should
  12194. * never
  12195. * occur in practice. */
  12196. mg_atomic_dec(&sTlsInit);
  12197. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12198. mg_free(ctx);
  12199. return NULL;
  12200. }
  12201. #if defined(USE_LUA)
  12202. lua_init_optional_libraries();
  12203. #endif
  12204. } else {
  12205. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12206. * initialized. */
  12207. mg_sleep(1);
  12208. }
  12209. tls.is_master = -1;
  12210. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12211. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12212. tls.pthread_cond_helper_mutex = NULL;
  12213. #endif
  12214. pthread_setspecific(sTlsKey, &tls);
  12215. /* Dummy use this function - in some #ifdef combinations it's used,
  12216. * while it's not used in others, but GCC seems to stupid to understand
  12217. * #pragma GCC diagnostic ignored "-Wunused-function"
  12218. * in cases the function is unused, and it also complains on
  12219. * __attribute((unused))__ in cases it is used.
  12220. * So dummy use it, to have our peace. */
  12221. (void)mg_current_thread_id();
  12222. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12223. #if !defined(ALTERNATIVE_QUEUE)
  12224. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12225. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12226. #endif
  12227. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12228. if (!ok) {
  12229. /* Fatal error - abort start. However, this situation should never
  12230. * occur in practice. */
  12231. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12232. mg_free(ctx);
  12233. pthread_setspecific(sTlsKey, NULL);
  12234. return NULL;
  12235. }
  12236. if (callbacks) {
  12237. ctx->callbacks = *callbacks;
  12238. exit_callback = callbacks->exit_context;
  12239. ctx->callbacks.exit_context = 0;
  12240. }
  12241. ctx->user_data = user_data;
  12242. ctx->handlers = NULL;
  12243. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12244. ctx->shared_lua_websockets = 0;
  12245. #endif
  12246. while (options && (name = *options++) != NULL) {
  12247. if ((idx = get_option_index(name)) == -1) {
  12248. mg_cry(fc(ctx), "Invalid option: %s", name);
  12249. free_context(ctx);
  12250. pthread_setspecific(sTlsKey, NULL);
  12251. return NULL;
  12252. } else if ((value = *options++) == NULL) {
  12253. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12254. free_context(ctx);
  12255. pthread_setspecific(sTlsKey, NULL);
  12256. return NULL;
  12257. }
  12258. if (ctx->config[idx] != NULL) {
  12259. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12260. mg_free(ctx->config[idx]);
  12261. }
  12262. ctx->config[idx] = mg_strdup(value);
  12263. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12264. }
  12265. /* Set default value if needed */
  12266. for (i = 0; config_options[i].name != NULL; i++) {
  12267. default_value = config_options[i].default_value;
  12268. if (ctx->config[i] == NULL && default_value != NULL) {
  12269. ctx->config[i] = mg_strdup(default_value);
  12270. }
  12271. }
  12272. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12273. if (workerthreadcount > MAX_WORKER_THREADS) {
  12274. mg_cry(fc(ctx), "Too many worker threads");
  12275. free_context(ctx);
  12276. pthread_setspecific(sTlsKey, NULL);
  12277. return NULL;
  12278. }
  12279. if (workerthreadcount <= 0) {
  12280. mg_cry(fc(ctx), "Invalid number of worker threads");
  12281. free_context(ctx);
  12282. pthread_setspecific(sTlsKey, NULL);
  12283. return NULL;
  12284. }
  12285. #if defined(NO_FILES)
  12286. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12287. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12288. free_context(ctx);
  12289. pthread_setspecific(sTlsKey, NULL);
  12290. return NULL;
  12291. }
  12292. #endif
  12293. get_system_name(&ctx->systemName);
  12294. #if defined(USE_LUA)
  12295. /* If a Lua background script has been configured, start it. */
  12296. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  12297. char ebuf[256];
  12298. void *state = (void *)mg_prepare_lua_context_script(
  12299. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  12300. if (!state) {
  12301. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  12302. free_context(ctx);
  12303. pthread_setspecific(sTlsKey, NULL);
  12304. return NULL;
  12305. }
  12306. ctx->lua_background_state = state;
  12307. } else {
  12308. ctx->lua_background_state = 0;
  12309. }
  12310. #endif
  12311. /* NOTE(lsm): order is important here. SSL certificates must
  12312. * be initialized before listening ports. UID must be set last. */
  12313. if (!set_gpass_option(ctx) ||
  12314. #if !defined(NO_SSL)
  12315. !set_ssl_option(ctx) ||
  12316. #endif
  12317. !set_ports_option(ctx) ||
  12318. #if !defined(_WIN32)
  12319. !set_uid_option(ctx) ||
  12320. #endif
  12321. !set_acl_option(ctx)) {
  12322. free_context(ctx);
  12323. pthread_setspecific(sTlsKey, NULL);
  12324. return NULL;
  12325. }
  12326. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12327. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12328. * won't kill the whole process. */
  12329. (void)signal(SIGPIPE, SIG_IGN);
  12330. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12331. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12332. ctx->worker_threadids =
  12333. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12334. if (ctx->worker_threadids == NULL) {
  12335. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12336. free_context(ctx);
  12337. pthread_setspecific(sTlsKey, NULL);
  12338. return NULL;
  12339. }
  12340. ctx->worker_connections =
  12341. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  12342. sizeof(struct mg_connection));
  12343. if (ctx->worker_connections == NULL) {
  12344. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12345. free_context(ctx);
  12346. pthread_setspecific(sTlsKey, NULL);
  12347. return NULL;
  12348. }
  12349. #if defined(ALTERNATIVE_QUEUE)
  12350. ctx->client_wait_events =
  12351. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  12352. if (ctx->client_wait_events == NULL) {
  12353. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12354. mg_free(ctx->worker_threadids);
  12355. free_context(ctx);
  12356. pthread_setspecific(sTlsKey, NULL);
  12357. return NULL;
  12358. }
  12359. ctx->client_socks =
  12360. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12361. if (ctx->client_wait_events == NULL) {
  12362. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12363. mg_free(ctx->client_socks);
  12364. mg_free(ctx->worker_threadids);
  12365. free_context(ctx);
  12366. pthread_setspecific(sTlsKey, NULL);
  12367. return NULL;
  12368. }
  12369. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12370. ctx->client_wait_events[i] = event_create();
  12371. if (ctx->client_wait_events[i] == 0) {
  12372. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12373. /* TODO: clean all and exit */
  12374. }
  12375. }
  12376. #endif
  12377. #if defined(USE_TIMERS)
  12378. if (timers_init(ctx) != 0) {
  12379. mg_cry(fc(ctx), "Error creating timers");
  12380. free_context(ctx);
  12381. pthread_setspecific(sTlsKey, NULL);
  12382. return NULL;
  12383. }
  12384. #endif
  12385. /* Context has been created - init user libraries */
  12386. if (ctx->callbacks.init_context) {
  12387. ctx->callbacks.init_context(ctx);
  12388. }
  12389. ctx->callbacks.exit_context = exit_callback;
  12390. ctx->context_type = 1; /* server context */
  12391. /* Start master (listening) thread */
  12392. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12393. /* Start worker threads */
  12394. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12395. struct worker_thread_args *wta =
  12396. mg_malloc(sizeof(struct worker_thread_args));
  12397. if (wta) {
  12398. wta->ctx = ctx;
  12399. wta->index = (int)i;
  12400. }
  12401. if ((wta == NULL)
  12402. || (mg_start_thread_with_id(worker_thread,
  12403. wta,
  12404. &ctx->worker_threadids[i]) != 0)) {
  12405. /* thread was not created */
  12406. if (wta != NULL) {
  12407. mg_free(wta);
  12408. }
  12409. if (i > 0) {
  12410. mg_cry(fc(ctx),
  12411. "Cannot start worker thread %i: error %ld",
  12412. i + 1,
  12413. (long)ERRNO);
  12414. } else {
  12415. mg_cry(fc(ctx),
  12416. "Cannot create threads: error %ld",
  12417. (long)ERRNO);
  12418. free_context(ctx);
  12419. pthread_setspecific(sTlsKey, NULL);
  12420. return NULL;
  12421. }
  12422. break;
  12423. }
  12424. }
  12425. pthread_setspecific(sTlsKey, NULL);
  12426. return ctx;
  12427. }
  12428. /* Feature check API function */
  12429. unsigned
  12430. mg_check_feature(unsigned feature)
  12431. {
  12432. static const unsigned feature_set = 0
  12433. /* Set bits for available features according to API documentation.
  12434. * This bit mask is created at compile time, according to the active
  12435. * preprocessor defines. It is a single const value at runtime. */
  12436. #if !defined(NO_FILES)
  12437. | 0x0001u
  12438. #endif
  12439. #if !defined(NO_SSL)
  12440. | 0x0002u
  12441. #endif
  12442. #if !defined(NO_CGI)
  12443. | 0x0004u
  12444. #endif
  12445. #if defined(USE_IPV6)
  12446. | 0x0008u
  12447. #endif
  12448. #if defined(USE_WEBSOCKET)
  12449. | 0x0010u
  12450. #endif
  12451. #if defined(USE_LUA)
  12452. | 0x0020u
  12453. #endif
  12454. #if defined(USE_DUKTAPE)
  12455. | 0x0040u
  12456. #endif
  12457. #if !defined(NO_CACHING)
  12458. | 0x0080u
  12459. #endif
  12460. /* Set some extra bits not defined in the API documentation.
  12461. * These bits may change without further notice. */
  12462. #if defined(MG_LEGACY_INTERFACE)
  12463. | 0x8000u
  12464. #endif
  12465. #if defined(MEMORY_DEBUGGING)
  12466. | 0x0100u
  12467. #endif
  12468. #if defined(USE_TIMERS)
  12469. | 0x0200u
  12470. #endif
  12471. #if !defined(NO_NONCE_CHECK)
  12472. | 0x0400u
  12473. #endif
  12474. #if !defined(NO_POPEN)
  12475. | 0x0800u
  12476. #endif
  12477. ;
  12478. return (feature & feature_set);
  12479. }
  12480. /* Get system information. It can be printed or stored by the caller.
  12481. * Return the size of available information. */
  12482. static int
  12483. mg_get_system_info_impl(char *buffer, int buflen)
  12484. {
  12485. char block[256];
  12486. int system_info_length = 0;
  12487. #if defined(_WIN32)
  12488. const char *eol = "\r\n";
  12489. #else
  12490. const char *eol = "\n";
  12491. #endif
  12492. /* Server version */
  12493. {
  12494. const char *version = mg_version();
  12495. mg_snprintf(NULL,
  12496. NULL,
  12497. block,
  12498. sizeof(block),
  12499. "Server Version: %s%s",
  12500. version,
  12501. eol);
  12502. system_info_length += (int)strlen(block);
  12503. if (system_info_length < buflen) {
  12504. strcat(buffer, block);
  12505. }
  12506. }
  12507. /* System info */
  12508. {
  12509. #if defined(_WIN32)
  12510. #if !defined(__SYMBIAN32__)
  12511. DWORD dwVersion = 0;
  12512. DWORD dwMajorVersion = 0;
  12513. DWORD dwMinorVersion = 0;
  12514. SYSTEM_INFO si;
  12515. GetSystemInfo(&si);
  12516. #ifdef _MSC_VER
  12517. #pragma warning(push)
  12518. /* GetVersion was declared deprecated */
  12519. #pragma warning(disable : 4996)
  12520. #endif
  12521. dwVersion = GetVersion();
  12522. #ifdef _MSC_VER
  12523. #pragma warning(pop)
  12524. #endif
  12525. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12526. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12527. mg_snprintf(NULL,
  12528. NULL,
  12529. block,
  12530. sizeof(block),
  12531. "Windows %u.%u%s",
  12532. (unsigned)dwMajorVersion,
  12533. (unsigned)dwMinorVersion,
  12534. eol);
  12535. system_info_length += (int)strlen(block);
  12536. if (system_info_length < buflen) {
  12537. strcat(buffer, block);
  12538. }
  12539. mg_snprintf(NULL,
  12540. NULL,
  12541. block,
  12542. sizeof(block),
  12543. "CPU: type %u, cores %u, mask %x%s",
  12544. (unsigned)si.wProcessorArchitecture,
  12545. (unsigned)si.dwNumberOfProcessors,
  12546. (unsigned)si.dwActiveProcessorMask,
  12547. eol);
  12548. system_info_length += (int)strlen(block);
  12549. if (system_info_length < buflen) {
  12550. strcat(buffer, block);
  12551. }
  12552. #else
  12553. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  12554. system_info_length += (int)strlen(block);
  12555. if (system_info_length < buflen) {
  12556. strcat(buffer, block);
  12557. }
  12558. #endif
  12559. #else
  12560. struct utsname name;
  12561. memset(&name, 0, sizeof(name));
  12562. uname(&name);
  12563. mg_snprintf(NULL,
  12564. NULL,
  12565. block,
  12566. sizeof(block),
  12567. "%s %s (%s) - %s%s",
  12568. name.sysname,
  12569. name.version,
  12570. name.release,
  12571. name.machine,
  12572. eol);
  12573. system_info_length += (int)strlen(block);
  12574. if (system_info_length < buflen) {
  12575. strcat(buffer, block);
  12576. }
  12577. #endif
  12578. }
  12579. /* Features */
  12580. {
  12581. mg_snprintf(NULL,
  12582. NULL,
  12583. block,
  12584. sizeof(block),
  12585. "Features: %X%s%s%s%s%s%s%s%s%s%s",
  12586. mg_check_feature(0xFFFFFFFFu),
  12587. eol,
  12588. mg_check_feature(1) ? " Files" : "",
  12589. mg_check_feature(2) ? " HTTPS" : "",
  12590. mg_check_feature(4) ? " CGI" : "",
  12591. mg_check_feature(8) ? " IPv6" : "",
  12592. mg_check_feature(16) ? " WebSockets" : "",
  12593. mg_check_feature(32) ? " Lua" : "",
  12594. mg_check_feature(64) ? " JavaScript" : "",
  12595. mg_check_feature(128) ? " Cache" : "",
  12596. eol);
  12597. system_info_length += (int)strlen(block);
  12598. if (system_info_length < buflen) {
  12599. strcat(buffer, block);
  12600. }
  12601. #ifdef USE_LUA
  12602. mg_snprintf(NULL,
  12603. NULL,
  12604. block,
  12605. sizeof(block),
  12606. "Lua Version: %u (%s)%s",
  12607. (unsigned)LUA_VERSION_NUM,
  12608. LUA_RELEASE,
  12609. eol);
  12610. system_info_length += (int)strlen(block);
  12611. if (system_info_length < buflen) {
  12612. strcat(buffer, block);
  12613. }
  12614. #endif
  12615. #if defined(USE_DUKTAPE)
  12616. mg_snprintf(NULL,
  12617. NULL,
  12618. block,
  12619. sizeof(block),
  12620. "JavaScript: Duktape %u.%u.%u%s",
  12621. (unsigned)DUK_VERSION / 10000,
  12622. ((unsigned)DUK_VERSION / 100) % 100,
  12623. (unsigned)DUK_VERSION % 10000,
  12624. eol);
  12625. system_info_length += (int)strlen(block);
  12626. if (system_info_length < buflen) {
  12627. strcat(buffer, block);
  12628. }
  12629. #endif
  12630. }
  12631. /* Build date */
  12632. {
  12633. mg_snprintf(
  12634. NULL, NULL, block, sizeof(block), "Build: %s%s", __DATE__, eol);
  12635. system_info_length += (int)strlen(block);
  12636. if (system_info_length < buflen) {
  12637. strcat(buffer, block);
  12638. }
  12639. }
  12640. /* Compiler information */
  12641. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  12642. {
  12643. #if defined(_MSC_VER)
  12644. mg_snprintf(NULL,
  12645. NULL,
  12646. block,
  12647. sizeof(block),
  12648. "MSC: %u (%u)%s",
  12649. (unsigned)_MSC_VER,
  12650. (unsigned)_MSC_FULL_VER,
  12651. eol);
  12652. system_info_length += (int)strlen(block);
  12653. if (system_info_length < buflen) {
  12654. strcat(buffer, block);
  12655. }
  12656. #elif defined(__MINGW64__)
  12657. mg_snprintf(NULL,
  12658. NULL,
  12659. block,
  12660. sizeof(block),
  12661. "MinGW64: %u.%u%s",
  12662. (unsigned)__MINGW64_VERSION_MAJOR,
  12663. (unsigned)__MINGW64_VERSION_MINOR,
  12664. eol);
  12665. system_info_length += (int)strlen(block);
  12666. if (system_info_length < buflen) {
  12667. strcat(buffer, block);
  12668. }
  12669. mg_snprintf(NULL,
  12670. NULL,
  12671. block,
  12672. sizeof(block),
  12673. "MinGW32: %u.%u%s",
  12674. (unsigned)__MINGW32_MAJOR_VERSION,
  12675. (unsigned)__MINGW32_MINOR_VERSION,
  12676. eol);
  12677. system_info_length += (int)strlen(block);
  12678. if (system_info_length < buflen) {
  12679. strcat(buffer, block);
  12680. }
  12681. #elif defined(__MINGW32__)
  12682. mg_snprintf(NULL,
  12683. NULL,
  12684. block,
  12685. sizeof(block),
  12686. "MinGW32: %u.%u%s",
  12687. (unsigned)__MINGW32_MAJOR_VERSION,
  12688. (unsigned)__MINGW32_MINOR_VERSION,
  12689. eol);
  12690. system_info_length += (int)strlen(block);
  12691. if (system_info_length < buflen) {
  12692. strcat(buffer, block);
  12693. }
  12694. #elif defined(__clang__)
  12695. mg_snprintf(NULL,
  12696. NULL,
  12697. block,
  12698. sizeof(block),
  12699. "clang: %u.%u.%u (%s)%s",
  12700. __clang_major__,
  12701. __clang_minor__,
  12702. __clang_patchlevel__,
  12703. __clang_version__,
  12704. eol);
  12705. system_info_length += (int)strlen(block);
  12706. if (system_info_length < buflen) {
  12707. strcat(buffer, block);
  12708. }
  12709. #elif defined(__GNUC__)
  12710. mg_snprintf(NULL,
  12711. NULL,
  12712. block,
  12713. sizeof(block),
  12714. "gcc: %u.%u.%u%s",
  12715. (unsigned)__GNUC__,
  12716. (unsigned)__GNUC_MINOR__,
  12717. (unsigned)__GNUC_PATCHLEVEL__,
  12718. eol);
  12719. system_info_length += (int)strlen(block);
  12720. if (system_info_length < buflen) {
  12721. strcat(buffer, block);
  12722. }
  12723. #elif defined(__INTEL_COMPILER)
  12724. mg_snprintf(NULL,
  12725. NULL,
  12726. block,
  12727. sizeof(block),
  12728. "Intel C/C++: %u%s",
  12729. (unsigned)__INTEL_COMPILER,
  12730. eol);
  12731. system_info_length += (int)strlen(block);
  12732. if (system_info_length < buflen) {
  12733. strcat(buffer, block);
  12734. }
  12735. #elif defined(__BORLANDC__)
  12736. mg_snprintf(NULL,
  12737. NULL,
  12738. block,
  12739. sizeof(block),
  12740. "Borland C: 0x%x%s",
  12741. (unsigned)__BORLANDC__,
  12742. eol);
  12743. system_info_length += (int)strlen(block);
  12744. if (system_info_length < buflen) {
  12745. strcat(buffer, block);
  12746. }
  12747. #elif defined(__SUNPRO_C)
  12748. mg_snprintf(NULL,
  12749. NULL,
  12750. block,
  12751. sizeof(block),
  12752. "Solaris: 0x%x%s",
  12753. (unsigned)__SUNPRO_C,
  12754. eol);
  12755. system_info_length += (int)strlen(block);
  12756. if (system_info_length < buflen) {
  12757. strcat(buffer, block);
  12758. }
  12759. #else
  12760. mg_snprintf(NULL, NULL, block, sizeof(block), "Other compiler%s", eol);
  12761. system_info_length += (int)strlen(block);
  12762. if (system_info_length < buflen) {
  12763. strcat(buffer, block);
  12764. }
  12765. #endif
  12766. }
  12767. /* Determine 32/64 bit data mode.
  12768. * see https://en.wikipedia.org/wiki/64-bit_computing */
  12769. {
  12770. mg_snprintf(NULL,
  12771. NULL,
  12772. block,
  12773. sizeof(block),
  12774. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  12775. "ptr:%u, size:%u, time:%u%s",
  12776. (unsigned)sizeof(short),
  12777. (unsigned)sizeof(int),
  12778. (unsigned)sizeof(long),
  12779. (unsigned)sizeof(long long),
  12780. (unsigned)sizeof(float),
  12781. (unsigned)sizeof(double),
  12782. (unsigned)sizeof(long double),
  12783. (unsigned)sizeof(char),
  12784. (unsigned)sizeof(wchar_t),
  12785. (unsigned)sizeof(void *),
  12786. (unsigned)sizeof(size_t),
  12787. (unsigned)sizeof(time_t),
  12788. eol);
  12789. system_info_length += (int)strlen(block);
  12790. if (system_info_length < buflen) {
  12791. strcat(buffer, block);
  12792. }
  12793. }
  12794. return system_info_length;
  12795. }
  12796. /* Get system information. It can be printed or stored by the caller.
  12797. * Return the size of available information. */
  12798. int
  12799. mg_get_system_info(char *buffer, int buflen)
  12800. {
  12801. if ((buffer == NULL) || (buflen < 1)) {
  12802. return mg_get_system_info_impl(NULL, 0);
  12803. } else {
  12804. /* Reset buffer, so we can always use strcat. */
  12805. buffer[0] = 0;
  12806. return mg_get_system_info_impl(buffer, buflen);
  12807. }
  12808. }
  12809. /* mg_init_library counter */
  12810. static int mg_init_library_called = 0;
  12811. /* Initialize this library. This function does not need to be thread safe. */
  12812. unsigned
  12813. mg_init_library(unsigned features)
  12814. {
  12815. /* Currently we do nothing here. This is planned for Version 1.10.
  12816. * For now, we just add this function, so clients can be changed early. */
  12817. if (mg_init_library_called <= 0) {
  12818. mg_init_library_called = 1;
  12819. return mg_check_feature(features & 0xFFu);
  12820. }
  12821. return 0;
  12822. }
  12823. /* Un-initialize this library. */
  12824. unsigned
  12825. mg_exit_library(void)
  12826. {
  12827. if (mg_init_library_called <= 0) {
  12828. return 0;
  12829. }
  12830. mg_init_library_called--;
  12831. return 1;
  12832. }
  12833. /* End of civetweb.c */