civetweb.c 222 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907
  1. /* Copyright (c) 2013-2014 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #else
  27. #ifdef __linux__
  28. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  29. #endif
  30. #ifndef _LARGEFILE_SOURCE
  31. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  32. #endif
  33. #ifndef _FILE_OFFSET_BITS
  34. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  35. #endif
  36. #ifndef __STDC_FORMAT_MACROS
  37. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  38. #endif
  39. #ifndef __STDC_LIMIT_MACROS
  40. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  41. #endif
  42. #endif
  43. #if defined (_MSC_VER)
  44. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  45. #pragma warning (disable : 4306 )
  46. /* conditional expression is constant: introduced by FD_SET(..) */
  47. #pragma warning (disable : 4127)
  48. /* non-constant aggregate initializer: issued due to missing C99 support */
  49. #pragma warning (disable : 4204)
  50. #endif
  51. /* Disable WIN32_LEAN_AND_MEAN.
  52. This makes windows.h always include winsock2.h */
  53. #if defined(WIN32_LEAN_AND_MEAN)
  54. #undef WIN32_LEAN_AND_MEAN
  55. #endif
  56. #if defined USE_IPV6 && defined(_WIN32)
  57. #include <ws2tcpip.h>
  58. #endif
  59. #if defined(__SYMBIAN32__)
  60. #define NO_SSL /* SSL is not supported */
  61. #define NO_CGI /* CGI is not supported */
  62. #define PATH_MAX FILENAME_MAX
  63. #endif /* __SYMBIAN32__ */
  64. #ifndef IGNORE_UNUSED_RESULT
  65. #define IGNORE_UNUSED_RESULT(a) (void)((a) && 1)
  66. #endif
  67. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  68. #include <sys/types.h>
  69. #include <sys/stat.h>
  70. #include <errno.h>
  71. #include <signal.h>
  72. #include <fcntl.h>
  73. #endif /* !_WIN32_WCE */
  74. #include <time.h>
  75. #include <stdlib.h>
  76. #include <stdarg.h>
  77. #include <assert.h>
  78. #include <string.h>
  79. #include <ctype.h>
  80. #include <limits.h>
  81. #include <stddef.h>
  82. #include <stdio.h>
  83. #ifndef MAX_WORKER_THREADS
  84. #define MAX_WORKER_THREADS 1024
  85. #endif
  86. #if defined(_WIN32) && !defined(__SYMBIAN32__) /* Windows specific */
  87. #if defined(_MSC_VER) && _MSC_VER <= 1400
  88. #undef _WIN32_WINNT
  89. #define _WIN32_WINNT 0x0400 /* To make it link in VS2005 */
  90. #endif
  91. #include <windows.h>
  92. #ifndef PATH_MAX
  93. #define PATH_MAX MAX_PATH
  94. #endif
  95. #ifndef _IN_PORT_T
  96. #ifndef in_port_t
  97. #define in_port_t u_short
  98. #endif
  99. #endif
  100. #ifndef _WIN32_WCE
  101. #include <process.h>
  102. #include <direct.h>
  103. #include <io.h>
  104. #else /* _WIN32_WCE */
  105. #define NO_CGI /* WinCE has no pipes */
  106. typedef long off_t;
  107. #define errno GetLastError()
  108. #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
  109. #endif /* _WIN32_WCE */
  110. #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
  111. ((uint64_t)((uint32_t)(hi))) << 32))
  112. #define RATE_DIFF 10000000 /* 100 nsecs */
  113. #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
  114. #define SYS2UNIX_TIME(lo, hi) \
  115. (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
  116. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  117. The rest of MS compilers use __FUNCTION__, not C99 __func__
  118. Also use _strtoui64 on modern M$ compilers */
  119. #if defined(_MSC_VER) && _MSC_VER < 1300
  120. #define STRX(x) #x
  121. #define STR(x) STRX(x)
  122. #define __func__ __FILE__ ":" STR(__LINE__)
  123. #define strtoull(x, y, z) (unsigned __int64) _atoi64(x)
  124. #define strtoll(x, y, z) _atoi64(x)
  125. #else
  126. #define __func__ __FUNCTION__
  127. #define strtoull(x, y, z) _strtoui64(x, y, z)
  128. #define strtoll(x, y, z) _strtoi64(x, y, z)
  129. #endif /* _MSC_VER */
  130. #define ERRNO GetLastError()
  131. #define NO_SOCKLEN_T
  132. #define SSL_LIB "ssleay32.dll"
  133. #define CRYPTO_LIB "libeay32.dll"
  134. #define O_NONBLOCK 0
  135. #if !defined(EWOULDBLOCK)
  136. #define EWOULDBLOCK WSAEWOULDBLOCK
  137. #endif /* !EWOULDBLOCK */
  138. #define _POSIX_
  139. #define INT64_FMT "I64d"
  140. #define WINCDECL __cdecl
  141. #define SHUT_WR 1
  142. #define snprintf _snprintf
  143. #define vsnprintf _vsnprintf
  144. #define mg_sleep(x) Sleep(x)
  145. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  146. #ifndef popen
  147. #define popen(x, y) _popen(x, y)
  148. #endif
  149. #ifndef pclose
  150. #define pclose(x) _pclose(x)
  151. #endif
  152. #define close(x) _close(x)
  153. #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
  154. #define RTLD_LAZY 0
  155. #define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
  156. #define fdopen(x, y) _fdopen((x), (y))
  157. #define write(x, y, z) _write((x), (y), (unsigned) z)
  158. #define read(x, y, z) _read((x), (y), (unsigned) z)
  159. #define flockfile(x) EnterCriticalSection(&global_log_file_lock)
  160. #define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
  161. #define sleep(x) Sleep((x) * 1000)
  162. #define rmdir(x) _rmdir(x)
  163. #if !defined(va_copy)
  164. #define va_copy(x, y) x = y
  165. #endif /* !va_copy MINGW #defines va_copy */
  166. #if !defined(fileno)
  167. #define fileno(x) _fileno(x)
  168. #endif /* !fileno MINGW #defines fileno */
  169. typedef HANDLE pthread_mutex_t;
  170. typedef DWORD pthread_key_t;
  171. typedef HANDLE pthread_t;
  172. typedef struct {
  173. CRITICAL_SECTION threadIdSec;
  174. int waitingthreadcount; /* The number of threads queued. */
  175. pthread_t *waitingthreadhdls; /* The thread handles. */
  176. } pthread_cond_t;
  177. #ifndef __clockid_t_defined
  178. typedef DWORD clockid_t;
  179. #endif
  180. #ifndef CLOCK_MONOTONIC
  181. #define CLOCK_MONOTONIC (1)
  182. #endif
  183. #ifndef CLOCK_REALTIME
  184. #define CLOCK_REALTIME (2)
  185. #endif
  186. #ifndef _TIMESPEC_DEFINED
  187. struct timespec {
  188. time_t tv_sec; /* seconds */
  189. long tv_nsec; /* nanoseconds */
  190. };
  191. #endif
  192. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  193. static int pthread_mutex_lock(pthread_mutex_t *);
  194. static int pthread_mutex_unlock(pthread_mutex_t *);
  195. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  196. struct file;
  197. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  198. #if defined(HAVE_STDINT)
  199. #include <stdint.h>
  200. #else
  201. typedef unsigned int uint32_t;
  202. typedef unsigned short uint16_t;
  203. typedef unsigned __int64 uint64_t;
  204. typedef __int64 int64_t;
  205. #define INT64_MAX 9223372036854775807
  206. #endif /* HAVE_STDINT */
  207. /* POSIX dirent interface */
  208. struct dirent {
  209. char d_name[PATH_MAX];
  210. };
  211. typedef struct DIR {
  212. HANDLE handle;
  213. WIN32_FIND_DATAW info;
  214. struct dirent result;
  215. } DIR;
  216. #if !defined(USE_IPV6) && defined(_WIN32)
  217. #ifndef HAVE_POLL
  218. struct pollfd {
  219. SOCKET fd;
  220. short events;
  221. short revents;
  222. };
  223. #define POLLIN 1
  224. #endif
  225. #endif
  226. /* Mark required libraries */
  227. #ifdef _MSC_VER
  228. #pragma comment(lib, "Ws2_32.lib")
  229. #endif
  230. #else /* UNIX specific */
  231. #include <sys/wait.h>
  232. #include <sys/socket.h>
  233. #include <sys/poll.h>
  234. #include <netinet/in.h>
  235. #include <arpa/inet.h>
  236. #include <sys/time.h>
  237. #include <sys/utsname.h>
  238. #include <stdint.h>
  239. #include <inttypes.h>
  240. #include <netdb.h>
  241. #if defined(ANDROID)
  242. typedef unsigned short int in_port_t;
  243. #endif
  244. #include <pwd.h>
  245. #include <unistd.h>
  246. #include <dirent.h>
  247. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  248. #include <dlfcn.h>
  249. #endif
  250. #include <pthread.h>
  251. #if defined(__MACH__)
  252. #define SSL_LIB "libssl.dylib"
  253. #define CRYPTO_LIB "libcrypto.dylib"
  254. #else
  255. #if !defined(SSL_LIB)
  256. #define SSL_LIB "libssl.so"
  257. #endif
  258. #if !defined(CRYPTO_LIB)
  259. #define CRYPTO_LIB "libcrypto.so"
  260. #endif
  261. #endif
  262. #ifndef O_BINARY
  263. #define O_BINARY 0
  264. #endif /* O_BINARY */
  265. #define closesocket(a) close(a)
  266. #define mg_mkdir(x, y) mkdir(x, y)
  267. #define mg_remove(x) remove(x)
  268. #define mg_sleep(x) usleep((x) * 1000)
  269. #define ERRNO errno
  270. #define INVALID_SOCKET (-1)
  271. #define INT64_FMT PRId64
  272. typedef int SOCKET;
  273. #define WINCDECL
  274. #endif /* End of Windows and UNIX specific includes */
  275. #ifdef _WIN32
  276. static CRITICAL_SECTION global_log_file_lock;
  277. static DWORD pthread_self(void)
  278. {
  279. return GetCurrentThreadId();
  280. }
  281. int pthread_key_create(pthread_key_t *key, void (*_must_be_zero)(void*) /* destructor function not supported for windows */)
  282. {
  283. assert(_must_be_zero == NULL);
  284. if ((key!=0) && (_must_be_zero == NULL)) {
  285. *key = TlsAlloc();
  286. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  287. }
  288. return -2;
  289. }
  290. int pthread_key_delete(pthread_key_t key)
  291. {
  292. return TlsFree(key) ? 0 : 1;
  293. }
  294. int pthread_setspecific(pthread_key_t key, void * value)
  295. {
  296. return TlsSetValue(key, value) ? 0 : 1;
  297. }
  298. void *pthread_getspecific(pthread_key_t key)
  299. {
  300. return TlsGetValue(key);
  301. }
  302. #endif /* _WIN32 */
  303. #include "civetweb.h"
  304. #define PASSWORDS_FILE_NAME ".htpasswd"
  305. #define CGI_ENVIRONMENT_SIZE 4096
  306. #define MAX_CGI_ENVIR_VARS 64
  307. #define MG_BUF_LEN 8192
  308. #ifndef MAX_REQUEST_SIZE
  309. #define MAX_REQUEST_SIZE 16384
  310. #endif
  311. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  312. #if !defined(DEBUG_TRACE)
  313. #if defined(DEBUG)
  314. static void DEBUG_TRACE_FUNC(const char *func, unsigned line, PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(3, 4);
  315. static void DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...) {
  316. va_list args;
  317. flockfile(stdout);
  318. printf("*** %lu.%p.%s.%d: ",
  319. (unsigned long) time(NULL), (void *) pthread_self(),
  320. func, line);
  321. va_start(args, fmt);
  322. vprintf(fmt, args);
  323. va_end(args);
  324. putchar('\n');
  325. fflush(stdout);
  326. funlockfile(stdout);
  327. }
  328. #define DEBUG_TRACE(fmt, ...) DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  329. #else
  330. #define DEBUG_TRACE(fmt, ...)
  331. #endif /* DEBUG */
  332. #endif /* DEBUG_TRACE */
  333. #if defined(MEMORY_DEBUGGING)
  334. static unsigned long blockCount = 0;
  335. static unsigned long totalMemUsed = 0;
  336. static void * mg_malloc_ex(size_t size, const char * file, unsigned line) {
  337. void * data = malloc(size + sizeof(size_t));
  338. void * memory = 0;
  339. char mallocStr[256];
  340. if (data) {
  341. *(size_t*)data = size;
  342. totalMemUsed += size;
  343. blockCount++;
  344. memory = (void *)(((char*)data)+sizeof(size_t));
  345. }
  346. sprintf(mallocStr, "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n", memory, (unsigned long)size, totalMemUsed, blockCount, file, line);
  347. #if defined(_WIN32)
  348. OutputDebugStringA(mallocStr);
  349. #else
  350. DEBUG_TRACE("%s", mallocStr);
  351. #endif
  352. return memory;
  353. }
  354. static void * mg_calloc_ex(size_t count, size_t size, const char * file, unsigned line) {
  355. void * data = mg_malloc_ex(size*count, file, line);
  356. if (data) memset(data, 0, size);
  357. return data;
  358. }
  359. static void mg_free_ex(void * memory, const char * file, unsigned line) {
  360. char mallocStr[256];
  361. void * data = (void *)(((char*)memory)-sizeof(size_t));
  362. size_t size;
  363. if (memory) {
  364. size = *(size_t*)data;
  365. totalMemUsed -= size;
  366. blockCount--;
  367. sprintf(mallocStr, "MEM: %p %5lu free %7lu %4lu --- %s:%u\n", memory, (unsigned long)size, totalMemUsed, blockCount, file, line);
  368. #if defined(_WIN32)
  369. OutputDebugStringA(mallocStr);
  370. #else
  371. DEBUG_TRACE("%s", mallocStr);
  372. #endif
  373. free(data);
  374. }
  375. }
  376. static void * mg_realloc_ex(void * memory, size_t newsize, const char * file, unsigned line) {
  377. char mallocStr[256];
  378. void * data;
  379. void * _realloc;
  380. size_t oldsize;
  381. if (newsize) {
  382. if (memory) {
  383. data = (void *)(((char*)memory)-sizeof(size_t));
  384. oldsize = *(size_t*)data;
  385. _realloc = realloc(data, newsize+sizeof(size_t));
  386. if (_realloc) {
  387. data = _realloc;
  388. totalMemUsed -= oldsize;
  389. sprintf(mallocStr, "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n", memory, (unsigned long)oldsize, totalMemUsed, blockCount, file, line);
  390. #if defined(_WIN32)
  391. OutputDebugStringA(mallocStr);
  392. #else
  393. DEBUG_TRACE("%s", mallocStr);
  394. #endif
  395. totalMemUsed += newsize;
  396. sprintf(mallocStr, "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n", memory, (unsigned long)newsize, totalMemUsed, blockCount, file, line);
  397. #if defined(_WIN32)
  398. OutputDebugStringA(mallocStr);
  399. #else
  400. DEBUG_TRACE("%s", mallocStr);
  401. #endif
  402. *(size_t*)data = newsize;
  403. data = (void *)(((char*)data)+sizeof(size_t));
  404. } else {
  405. #if defined(_WIN32)
  406. OutputDebugStringA("MEM: realloc failed\n");
  407. #else
  408. DEBUG_TRACE("MEM: realloc failed\n");
  409. #endif
  410. return _realloc;
  411. }
  412. } else {
  413. data = mg_malloc_ex(newsize, file, line);
  414. }
  415. } else {
  416. data = 0;
  417. mg_free_ex(memory, file, line);
  418. }
  419. return data;
  420. }
  421. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  422. #define mg_calloc(a,b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  423. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  424. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  425. #else
  426. static __inline void * mg_malloc(size_t a) {return malloc(a);}
  427. static __inline void * mg_calloc(size_t a, size_t b) {return calloc(a, b);}
  428. static __inline void * mg_realloc(void * a, size_t b) {return realloc(a, b);}
  429. static __inline void mg_free(void * a) {free(a);}
  430. #endif
  431. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  432. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  433. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  434. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  435. #define MD5_STATIC static
  436. #include "md5.inl"
  437. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  438. #ifdef NO_SOCKLEN_T
  439. typedef int socklen_t;
  440. #endif /* NO_SOCKLEN_T */
  441. #define _DARWIN_UNLIMITED_SELECT
  442. #define IP_ADDR_STR_LEN 50 /* IPv6 hex string is 46 chars */
  443. #if !defined(MSG_NOSIGNAL)
  444. #define MSG_NOSIGNAL 0
  445. #endif
  446. #if !defined(SOMAXCONN)
  447. #define SOMAXCONN 100
  448. #endif
  449. #if !defined(PATH_MAX)
  450. #define PATH_MAX 4096
  451. #endif
  452. /* Size of the accepted socket queue */
  453. #if !defined(MGSQLEN)
  454. #define MGSQLEN 20
  455. #endif
  456. static const char *http_500_error = "Internal Server Error";
  457. #if defined(NO_SSL_DL)
  458. #include <openssl/ssl.h>
  459. #include <openssl/err.h>
  460. #else
  461. /* SSL loaded dynamically from DLL.
  462. I put the prototypes here to be independent from OpenSSL source
  463. installation. */
  464. typedef struct ssl_st SSL;
  465. typedef struct ssl_method_st SSL_METHOD;
  466. typedef struct ssl_ctx_st SSL_CTX;
  467. struct ssl_func {
  468. const char *name; /* SSL function name */
  469. void (*ptr)(void); /* Function pointer */
  470. };
  471. #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
  472. #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
  473. #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
  474. #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
  475. #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
  476. #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
  477. #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
  478. #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  479. #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  480. #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  481. #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
  482. #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
  483. const char *, int)) ssl_sw[11].ptr)
  484. #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
  485. const char *, int)) ssl_sw[12].ptr)
  486. #define SSL_CTX_set_default_passwd_cb \
  487. (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
  488. #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
  489. #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
  490. #define SSL_CTX_use_certificate_chain_file \
  491. (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
  492. #define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  493. #define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)
  494. #define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)
  495. #define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr)
  496. #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
  497. #define CRYPTO_set_locking_callback \
  498. (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
  499. #define CRYPTO_set_id_callback \
  500. (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
  501. #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
  502. #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
  503. /* set_ssl_option() function updates this array.
  504. It loads SSL library dynamically and changes NULLs to the actual addresses
  505. of respective functions. The macros above (like SSL_connect()) are really
  506. just calling these functions indirectly via the pointer. */
  507. static struct ssl_func ssl_sw[] = {
  508. {"SSL_free", NULL},
  509. {"SSL_accept", NULL},
  510. {"SSL_connect", NULL},
  511. {"SSL_read", NULL},
  512. {"SSL_write", NULL},
  513. {"SSL_get_error", NULL},
  514. {"SSL_set_fd", NULL},
  515. {"SSL_new", NULL},
  516. {"SSL_CTX_new", NULL},
  517. {"SSLv23_server_method", NULL},
  518. {"SSL_library_init", NULL},
  519. {"SSL_CTX_use_PrivateKey_file", NULL},
  520. {"SSL_CTX_use_certificate_file",NULL},
  521. {"SSL_CTX_set_default_passwd_cb",NULL},
  522. {"SSL_CTX_free", NULL},
  523. {"SSL_load_error_strings", NULL},
  524. {"SSL_CTX_use_certificate_chain_file", NULL},
  525. {"SSLv23_client_method", NULL},
  526. {"SSL_pending", NULL},
  527. {"SSL_CTX_set_verify", NULL},
  528. {"SSL_shutdown", NULL},
  529. {NULL, NULL}
  530. };
  531. /* Similar array as ssl_sw. These functions could be located in different
  532. lib. */
  533. #if !defined(NO_SSL)
  534. static struct ssl_func crypto_sw[] = {
  535. {"CRYPTO_num_locks", NULL},
  536. {"CRYPTO_set_locking_callback", NULL},
  537. {"CRYPTO_set_id_callback", NULL},
  538. {"ERR_get_error", NULL},
  539. {"ERR_error_string", NULL},
  540. {NULL, NULL}
  541. };
  542. #endif /* NO_SSL */
  543. #endif /* NO_SSL_DL */
  544. static const char *month_names[] = {
  545. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  546. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  547. };
  548. /* Unified socket address. For IPv6 support, add IPv6 address structure
  549. in the union u. */
  550. union usa {
  551. struct sockaddr sa;
  552. struct sockaddr_in sin;
  553. #if defined(USE_IPV6)
  554. struct sockaddr_in6 sin6;
  555. #endif
  556. };
  557. /* Describes a string (chunk of memory). */
  558. struct vec {
  559. const char *ptr;
  560. size_t len;
  561. };
  562. struct file {
  563. int is_directory;
  564. time_t modification_time;
  565. int64_t size;
  566. FILE *fp;
  567. const char *membuf; /* Non-NULL if file data is in memory */
  568. /* set to 1 if the content is gzipped
  569. in which case we need a content-encoding: gzip header */
  570. int gzipped;
  571. };
  572. #define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL, 0}
  573. /* Describes listening socket, or socket which was accept()-ed by the master
  574. thread and queued for future handling by the worker thread. */
  575. struct socket {
  576. SOCKET sock; /* Listening socket */
  577. union usa lsa; /* Local socket address */
  578. union usa rsa; /* Remote socket address */
  579. unsigned is_ssl:1; /* Is port SSL-ed */
  580. unsigned ssl_redir:1; /* Is port supposed to redirect everything to SSL
  581. port */
  582. };
  583. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  584. enum {
  585. CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
  586. PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
  587. ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
  588. GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
  589. EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
  590. NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
  591. #if defined(USE_LUA)
  592. LUA_PRELOAD_FILE, LUA_SCRIPT_EXTENSIONS, LUA_SERVER_PAGE_EXTENSIONS,
  593. #endif
  594. #if defined(USE_WEBSOCKET)
  595. WEBSOCKET_ROOT,
  596. #endif
  597. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  598. LUA_WEBSOCKET_EXTENSIONS,
  599. #endif
  600. ACCESS_CONTROL_ALLOW_ORIGIN, ERROR_PAGES,
  601. NUM_OPTIONS
  602. };
  603. /* TODO: replace 12345 by proper config types */
  604. static struct mg_option config_options[] = {
  605. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  606. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  607. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  608. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  609. {"protect_uri", 12345, NULL},
  610. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  611. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  612. {"throttle", 12345, NULL},
  613. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  614. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  615. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  616. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  617. {"index_files", 12345,
  618. #ifdef USE_LUA
  619. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,index.shtml,index.php"},
  620. #else
  621. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  622. #endif
  623. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  624. {"access_control_list", 12345, NULL},
  625. {"extra_mime_types", 12345, NULL},
  626. {"listening_ports", 12345, "8080"},
  627. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  628. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  629. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  630. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  631. {"url_rewrite_patterns", 12345, NULL},
  632. {"hide_files_patterns", 12345, NULL},
  633. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  634. #if defined(USE_LUA)
  635. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  636. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  637. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  638. #endif
  639. #if defined(USE_WEBSOCKET)
  640. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  641. #endif
  642. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  643. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  644. #endif
  645. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  646. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  647. {NULL, CONFIG_TYPE_UNKNOWN, NULL}
  648. };
  649. struct mg_request_handler_info {
  650. char *uri;
  651. size_t uri_len;
  652. mg_request_handler handler;
  653. void *cbdata;
  654. struct mg_request_handler_info *next;
  655. };
  656. struct mg_context {
  657. volatile int stop_flag; /* Should we stop event loop */
  658. void *ssllib_dll_handle; /* Store the ssl library handle. */
  659. void *cryptolib_dll_handle; /* Store the crypto library handle. */
  660. SSL_CTX *ssl_ctx; /* SSL context */
  661. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  662. struct mg_callbacks callbacks; /* User-defined callback function */
  663. void *user_data; /* User-defined data */
  664. struct socket *listening_sockets;
  665. in_port_t *listening_ports;
  666. int num_listening_sockets;
  667. volatile int num_threads; /* Number of threads */
  668. pthread_mutex_t mutex; /* Protects (max|num)_threads */
  669. pthread_cond_t cond; /* Condvar for tracking workers terminations */
  670. struct socket queue[MGSQLEN]; /* Accepted sockets */
  671. volatile int sq_head; /* Head of the socket queue */
  672. volatile int sq_tail; /* Tail of the socket queue */
  673. pthread_cond_t sq_full; /* Signaled when socket is produced */
  674. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  675. pthread_t masterthreadid; /* The master thread ID. */
  676. int workerthreadcount; /* The amount of worker threads. */
  677. pthread_t *workerthreadids;/* The worker thread IDs. */
  678. unsigned long start_time; /* Server start time, used for authentication */
  679. unsigned long nonce_count; /* Used nonces, used for authentication */
  680. char *systemName; /* What operating system is running */
  681. /* linked list of uri handlers */
  682. struct mg_request_handler_info *request_handlers;
  683. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  684. /* linked list of shared lua websockets */
  685. struct mg_shared_lua_websocket *shared_lua_websockets;
  686. #endif
  687. };
  688. struct mg_connection {
  689. struct mg_request_info request_info;
  690. struct mg_context *ctx;
  691. SSL *ssl; /* SSL descriptor */
  692. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  693. struct socket client; /* Connected client */
  694. time_t birth_time; /* Time when request was received */
  695. int64_t num_bytes_sent; /* Total bytes sent to client */
  696. int64_t content_len; /* Content-Length header value */
  697. int64_t consumed_content; /* How many bytes of content have been read */
  698. char *buf; /* Buffer for received data */
  699. char *path_info; /* PATH_INFO part of the URL */
  700. int must_close; /* 1 if connection must be closed */
  701. int in_error_handler; /* 1 if in handler for user defined error pages */
  702. int buf_size; /* Buffer size */
  703. int request_len; /* Size of the request + headers in a buffer */
  704. int data_len; /* Total size of data in a buffer */
  705. int status_code; /* HTTP reply status code, e.g. 200 */
  706. int throttle; /* Throttling, bytes/sec. <= 0 means no
  707. throttle */
  708. time_t last_throttle_time; /* Last time throttled data was sent */
  709. int64_t last_throttle_bytes;/* Bytes sent this second */
  710. pthread_mutex_t mutex; /* Used by mg_lock/mg_unlock to ensure atomic
  711. transmissions for websockets */
  712. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  713. void * lua_websocket_state; /* Lua_State for a websocket connection */
  714. #endif
  715. };
  716. static pthread_key_t sTlsKey; /* Thread local storage index */
  717. static int sTlsInit = 0;
  718. struct mg_workerTLS {
  719. int is_master;
  720. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  721. HANDLE pthread_cond_helper_mutex;
  722. #endif
  723. };
  724. /* Directory entry */
  725. struct de {
  726. struct mg_connection *conn;
  727. char *file_name;
  728. struct file file;
  729. };
  730. #if defined(USE_WEBSOCKET)
  731. static int is_websocket_request(const struct mg_connection *conn);
  732. #endif
  733. #if defined(MG_LEGACY_INTERFACE)
  734. const char **mg_get_valid_option_names(void)
  735. {
  736. static const char * data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  737. int i;
  738. for (i=0; config_options[i].name != NULL; i++) {
  739. data[i * 2] = config_options[i].name;
  740. data[i * 2 + 1] = config_options[i].default_value;
  741. }
  742. return data;
  743. }
  744. #endif
  745. const struct mg_option *mg_get_valid_options(void)
  746. {
  747. return config_options;
  748. }
  749. static int is_file_in_memory(struct mg_connection *conn, const char *path,
  750. struct file *filep)
  751. {
  752. size_t size = 0;
  753. if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :
  754. conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
  755. /* NOTE: override filep->size only on success. Otherwise, it might
  756. break constructs like if (!mg_stat() || !mg_fopen()) ... */
  757. filep->size = size;
  758. }
  759. return filep->membuf != NULL;
  760. }
  761. static int is_file_opened(const struct file *filep)
  762. {
  763. return filep->membuf != NULL || filep->fp != NULL;
  764. }
  765. static int mg_fopen(struct mg_connection *conn, const char *path,
  766. const char *mode, struct file *filep)
  767. {
  768. if (!is_file_in_memory(conn, path, filep)) {
  769. #ifdef _WIN32
  770. wchar_t wbuf[PATH_MAX], wmode[20];
  771. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  772. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  773. filep->fp = _wfopen(wbuf, wmode);
  774. #else
  775. filep->fp = fopen(path, mode);
  776. #endif
  777. }
  778. return is_file_opened(filep);
  779. }
  780. static void mg_fclose(struct file *filep)
  781. {
  782. if (filep != NULL && filep->fp != NULL) {
  783. fclose(filep->fp);
  784. }
  785. }
  786. static void mg_strlcpy(register char *dst, register const char *src, size_t n)
  787. {
  788. for (; *src != '\0' && n > 1; n--) {
  789. *dst++ = *src++;
  790. }
  791. *dst = '\0';
  792. }
  793. static int lowercase(const char *s)
  794. {
  795. return tolower(* (const unsigned char *) s);
  796. }
  797. int mg_strncasecmp(const char *s1, const char *s2, size_t len)
  798. {
  799. int diff = 0;
  800. if (len > 0)
  801. do {
  802. diff = lowercase(s1++) - lowercase(s2++);
  803. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  804. return diff;
  805. }
  806. static int mg_strcasecmp(const char *s1, const char *s2)
  807. {
  808. int diff;
  809. do {
  810. diff = lowercase(s1++) - lowercase(s2++);
  811. } while (diff == 0 && s1[-1] != '\0');
  812. return diff;
  813. }
  814. static char * mg_strndup(const char *ptr, size_t len)
  815. {
  816. char *p;
  817. if ((p = (char *) mg_malloc(len + 1)) != NULL) {
  818. mg_strlcpy(p, ptr, len + 1);
  819. }
  820. return p;
  821. }
  822. static char * mg_strdup(const char *str)
  823. {
  824. return mg_strndup(str, strlen(str));
  825. }
  826. static const char *mg_strcasestr(const char *big_str, const char *small_str)
  827. {
  828. int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
  829. for (i = 0; i <= big_len - small_len; i++) {
  830. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  831. return big_str + i;
  832. }
  833. }
  834. return NULL;
  835. }
  836. /* Like snprintf(), but never returns negative value, or a value
  837. that is larger than a supplied buffer.
  838. Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  839. in his audit report. */
  840. static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
  841. const char *fmt, va_list ap)
  842. {
  843. int n;
  844. if (buflen == 0)
  845. return 0;
  846. n = vsnprintf(buf, buflen, fmt, ap);
  847. if (n < 0) {
  848. mg_cry(conn, "vsnprintf error");
  849. n = 0;
  850. } else if (n >= (int) buflen) {
  851. mg_cry(conn, "truncating vsnprintf buffer: [%.*s]",
  852. n > 200 ? 200 : n, buf);
  853. n = (int) buflen - 1;
  854. }
  855. buf[n] = '\0';
  856. return n;
  857. }
  858. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  859. PRINTF_FORMAT_STRING(const char *fmt), ...)
  860. PRINTF_ARGS(4, 5);
  861. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  862. const char *fmt, ...)
  863. {
  864. va_list ap;
  865. int n;
  866. va_start(ap, fmt);
  867. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  868. va_end(ap);
  869. return n;
  870. }
  871. static int get_option_index(const char *name)
  872. {
  873. int i;
  874. for (i = 0; config_options[i].name != NULL; i++) {
  875. if (strcmp(config_options[i].name, name) == 0) {
  876. return i;
  877. }
  878. }
  879. return -1;
  880. }
  881. const char *mg_get_option(const struct mg_context *ctx, const char *name)
  882. {
  883. int i;
  884. if ((i = get_option_index(name)) == -1) {
  885. return NULL;
  886. } else if (ctx->config[i] == NULL) {
  887. return "";
  888. } else {
  889. return ctx->config[i];
  890. }
  891. }
  892. size_t mg_get_ports(const struct mg_context *ctx, size_t size, int* ports, int* ssl)
  893. {
  894. size_t i;
  895. for (i = 0; i < size && i < (size_t)ctx->num_listening_sockets; i++)
  896. {
  897. ssl[i] = ctx->listening_sockets[i].is_ssl;
  898. ports[i] = ctx->listening_ports[i];
  899. }
  900. return i;
  901. }
  902. static void sockaddr_to_string(char *buf, size_t len,
  903. const union usa *usa)
  904. {
  905. buf[0] = '\0';
  906. #if defined(USE_IPV6)
  907. inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
  908. (void *) &usa->sin.sin_addr :
  909. (void *) &usa->sin6.sin6_addr, buf, len);
  910. #elif defined(_WIN32)
  911. /* Only Windows Vista (and newer) have inet_ntop() */
  912. mg_strlcpy(buf, inet_ntoa(usa->sin.sin_addr), len);
  913. #else
  914. inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
  915. #endif
  916. }
  917. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be included in all responses other than 100, 101, 5xx. */
  918. static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
  919. {
  920. struct tm *tm;
  921. tm = gmtime(t);
  922. if (tm != NULL) {
  923. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  924. } else {
  925. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  926. buf[buf_len - 1] = '\0';
  927. }
  928. }
  929. /* Print error message to the opened error log stream. */
  930. void mg_cry(struct mg_connection *conn, const char *fmt, ...)
  931. {
  932. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  933. va_list ap;
  934. FILE *fp;
  935. time_t timestamp;
  936. va_start(ap, fmt);
  937. IGNORE_UNUSED_RESULT(vsnprintf(buf, sizeof(buf), fmt, ap));
  938. va_end(ap);
  939. /* Do not lock when getting the callback value, here and below.
  940. I suppose this is fine, since function cannot disappear in the
  941. same way string option can. */
  942. if (conn->ctx->callbacks.log_message == NULL ||
  943. conn->ctx->callbacks.log_message(conn, buf) == 0) {
  944. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
  945. fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  946. if (fp != NULL) {
  947. flockfile(fp);
  948. timestamp = time(NULL);
  949. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  950. fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
  951. src_addr);
  952. if (conn->request_info.request_method != NULL) {
  953. fprintf(fp, "%s %s: ", conn->request_info.request_method,
  954. conn->request_info.uri);
  955. }
  956. fprintf(fp, "%s", buf);
  957. fputc('\n', fp);
  958. funlockfile(fp);
  959. fclose(fp);
  960. }
  961. }
  962. }
  963. /* Return fake connection structure. Used for logging, if connection
  964. is not applicable at the moment of logging. */
  965. static struct mg_connection *fc(struct mg_context *ctx)
  966. {
  967. static struct mg_connection fake_connection;
  968. fake_connection.ctx = ctx;
  969. return &fake_connection;
  970. }
  971. const char *mg_version(void)
  972. {
  973. return CIVETWEB_VERSION;
  974. }
  975. struct mg_request_info *mg_get_request_info(struct mg_connection *conn)
  976. {
  977. return &conn->request_info;
  978. }
  979. /* Skip the characters until one of the delimiters characters found.
  980. 0-terminate resulting word. Skip the delimiter and following whitespaces.
  981. Advance pointer to buffer to the next word. Return found 0-terminated word.
  982. Delimiters can be quoted with quotechar. */
  983. static char *skip_quoted(char **buf, const char *delimiters,
  984. const char *whitespace, char quotechar)
  985. {
  986. char *p, *begin_word, *end_word, *end_whitespace;
  987. begin_word = *buf;
  988. end_word = begin_word + strcspn(begin_word, delimiters);
  989. /* Check for quotechar */
  990. if (end_word > begin_word) {
  991. p = end_word - 1;
  992. while (*p == quotechar) {
  993. /* If there is anything beyond end_word, copy it */
  994. if (*end_word == '\0') {
  995. *p = '\0';
  996. break;
  997. } else {
  998. size_t end_off = strcspn(end_word + 1, delimiters);
  999. memmove (p, end_word, end_off + 1);
  1000. p += end_off; /* p must correspond to end_word - 1 */
  1001. end_word += end_off + 1;
  1002. }
  1003. }
  1004. for (p++; p < end_word; p++) {
  1005. *p = '\0';
  1006. }
  1007. }
  1008. if (*end_word == '\0') {
  1009. *buf = end_word;
  1010. } else {
  1011. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1012. for (p = end_word; p < end_whitespace; p++) {
  1013. *p = '\0';
  1014. }
  1015. *buf = end_whitespace;
  1016. }
  1017. return begin_word;
  1018. }
  1019. /* Simplified version of skip_quoted without quote char
  1020. and whitespace == delimiters */
  1021. static char *skip(char **buf, const char *delimiters)
  1022. {
  1023. return skip_quoted(buf, delimiters, delimiters, 0);
  1024. }
  1025. /* Return HTTP header value, or NULL if not found. */
  1026. static const char *get_header(const struct mg_request_info *ri,
  1027. const char *name)
  1028. {
  1029. int i;
  1030. for (i = 0; i < ri->num_headers; i++)
  1031. if (!mg_strcasecmp(name, ri->http_headers[i].name))
  1032. return ri->http_headers[i].value;
  1033. return NULL;
  1034. }
  1035. const char *mg_get_header(const struct mg_connection *conn, const char *name)
  1036. {
  1037. return get_header(&conn->request_info, name);
  1038. }
  1039. /* A helper function for traversing a comma separated list of values.
  1040. It returns a list pointer shifted to the next value, or NULL if the end
  1041. of the list found.
  1042. Value is stored in val vector. If value has form "x=y", then eq_val
  1043. vector is initialized to point to the "y" part, and val vector length
  1044. is adjusted to point only to "x". */
  1045. static const char *next_option(const char *list, struct vec *val,
  1046. struct vec *eq_val)
  1047. {
  1048. if (list == NULL || *list == '\0') {
  1049. /* End of the list */
  1050. list = NULL;
  1051. } else {
  1052. val->ptr = list;
  1053. if ((list = strchr(val->ptr, ',')) != NULL) {
  1054. /* Comma found. Store length and shift the list ptr */
  1055. val->len = list - val->ptr;
  1056. list++;
  1057. } else {
  1058. /* This value is the last one */
  1059. list = val->ptr + strlen(val->ptr);
  1060. val->len = list - val->ptr;
  1061. }
  1062. if (eq_val != NULL) {
  1063. /* Value has form "x=y", adjust pointers and lengths
  1064. so that val points to "x", and eq_val points to "y". */
  1065. eq_val->len = 0;
  1066. eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
  1067. if (eq_val->ptr != NULL) {
  1068. eq_val->ptr++; /* Skip over '=' character */
  1069. eq_val->len = val->ptr + val->len - eq_val->ptr;
  1070. val->len = (eq_val->ptr - val->ptr) - 1;
  1071. }
  1072. }
  1073. }
  1074. return list;
  1075. }
  1076. /* Perform case-insensitive match of string against pattern */
  1077. static int match_prefix(const char *pattern, int pattern_len, const char *str)
  1078. {
  1079. const char *or_str;
  1080. int i, j, len, res;
  1081. if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
  1082. res = match_prefix(pattern, (int)(or_str - pattern), str);
  1083. return res > 0 ? res :
  1084. match_prefix(or_str + 1, (int)((pattern + pattern_len) - (or_str + 1)), str);
  1085. }
  1086. i = j = 0;
  1087. res = -1;
  1088. for (; i < pattern_len; i++, j++) {
  1089. if (pattern[i] == '?' && str[j] != '\0') {
  1090. continue;
  1091. } else if (pattern[i] == '$') {
  1092. return str[j] == '\0' ? j : -1;
  1093. } else if (pattern[i] == '*') {
  1094. i++;
  1095. if (pattern[i] == '*') {
  1096. i++;
  1097. len = (int) strlen(str + j);
  1098. } else {
  1099. len = (int) strcspn(str + j, "/");
  1100. }
  1101. if (i == pattern_len) {
  1102. return j + len;
  1103. }
  1104. do {
  1105. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1106. } while (res == -1 && len-- > 0);
  1107. return res == -1 ? -1 : j + res + len;
  1108. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1109. return -1;
  1110. }
  1111. }
  1112. return j;
  1113. }
  1114. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1115. This function must tolerate situations when connection info is not
  1116. set up, for example if request parsing failed. */
  1117. static int should_keep_alive(const struct mg_connection *conn)
  1118. {
  1119. const char *http_version = conn->request_info.http_version;
  1120. const char *header = mg_get_header(conn, "Connection");
  1121. if (conn->must_close ||
  1122. conn->status_code == 401 ||
  1123. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  1124. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  1125. (header == NULL && http_version && 0!=strcmp(http_version, "1.1"))) {
  1126. return 0;
  1127. }
  1128. return 1;
  1129. }
  1130. static const char *suggest_connection_header(const struct mg_connection *conn)
  1131. {
  1132. return should_keep_alive(conn) ? "keep-alive" : "close";
  1133. }
  1134. static void handle_file_based_request(struct mg_connection *conn, const char *path, struct file *filep);
  1135. static int mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1136. static void send_http_error(struct mg_connection *, int, const char *,
  1137. PRINTF_FORMAT_STRING(const char *fmt), ...)
  1138. PRINTF_ARGS(4, 5);
  1139. static void send_http_error(struct mg_connection *conn, int status,
  1140. const char *reason, const char *fmt, ...)
  1141. {
  1142. char buf[MG_BUF_LEN];
  1143. va_list ap;
  1144. int len = 0, i, page_handler_found, scope;
  1145. char date[64];
  1146. time_t curtime = time(NULL);
  1147. const char *error_handler = NULL;
  1148. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  1149. const char *error_page_file_ext, *tstr;
  1150. conn->status_code = status;
  1151. if (conn->in_error_handler ||
  1152. conn->ctx->callbacks.http_error == NULL ||
  1153. conn->ctx->callbacks.http_error(conn, status)) {
  1154. if (!conn->in_error_handler) {
  1155. /* Send user defined error pages, if defined */
  1156. error_handler = conn->ctx->config[ERROR_PAGES];
  1157. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  1158. page_handler_found = 0;
  1159. if (error_handler != NULL) {
  1160. for (scope=1; (scope<=3) && !page_handler_found; scope++) {
  1161. switch (scope) {
  1162. case 1:
  1163. len = mg_snprintf(conn, buf, sizeof(buf)-32, "%serror%03u.", error_handler, status);
  1164. break;
  1165. case 2:
  1166. len = mg_snprintf(conn, buf, sizeof(buf)-32, "%serror%01uxx.", error_handler, status/100);
  1167. break;
  1168. default:
  1169. len = mg_snprintf(conn, buf, sizeof(buf)-32, "%serror.", error_handler);
  1170. break;
  1171. }
  1172. tstr = strchr(error_page_file_ext, '.');
  1173. while (tstr) {
  1174. for (i=1; i<32 && tstr[i]!=0 && tstr[i]!=','; i++) buf[len+i-1]=tstr[i];
  1175. buf[len+i-1]=0;
  1176. if (mg_stat(conn, buf, &error_page_file)) {
  1177. page_handler_found = 1;
  1178. break;
  1179. }
  1180. tstr = strchr(tstr+i, '.');
  1181. }
  1182. }
  1183. }
  1184. if (page_handler_found) {
  1185. conn->in_error_handler = 1;
  1186. handle_file_based_request(conn, buf, &error_page_file);
  1187. conn->in_error_handler = 0;
  1188. return;
  1189. }
  1190. }
  1191. buf[0] = '\0';
  1192. gmt_time_string(date, sizeof(date), &curtime);
  1193. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  1194. if (status > 199 && status != 204 && status != 304) {
  1195. len = mg_snprintf(conn, buf, sizeof(buf)-1, "Error %d: %s", status, reason);
  1196. buf[len] = '\n';
  1197. len++;
  1198. buf[len] = 0;
  1199. va_start(ap, fmt);
  1200. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
  1201. va_end(ap);
  1202. }
  1203. DEBUG_TRACE("[%s]", buf);
  1204. mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  1205. "Content-Length: %d\r\n"
  1206. "Date: %s\r\n"
  1207. "Connection: %s\r\n\r\n",
  1208. status, reason, len, date,
  1209. suggest_connection_header(conn));
  1210. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  1211. }
  1212. }
  1213. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1214. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  1215. {
  1216. (void) unused;
  1217. *mutex = CreateMutex(NULL, FALSE, NULL);
  1218. return *mutex == NULL ? -1 : 0;
  1219. }
  1220. static int pthread_mutex_destroy(pthread_mutex_t *mutex)
  1221. {
  1222. return CloseHandle(*mutex) == 0 ? -1 : 0;
  1223. }
  1224. static int pthread_mutex_lock(pthread_mutex_t *mutex)
  1225. {
  1226. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  1227. }
  1228. static int pthread_mutex_unlock(pthread_mutex_t *mutex)
  1229. {
  1230. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  1231. }
  1232. #ifndef WIN_PTHREADS_TIME_H
  1233. static int clock_gettime(clockid_t clk_id, struct timespec *tp)
  1234. {
  1235. FILETIME ft;
  1236. ULARGE_INTEGER li;
  1237. BOOL ok = FALSE;
  1238. double d;
  1239. static double perfcnt_per_sec = 0.0;
  1240. if (tp) {
  1241. if (clk_id == CLOCK_REALTIME) {
  1242. GetSystemTimeAsFileTime(&ft);
  1243. li.LowPart = ft.dwLowDateTime;
  1244. li.HighPart = ft.dwHighDateTime;
  1245. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  1246. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  1247. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  1248. ok = TRUE;
  1249. } else if (clk_id == CLOCK_MONOTONIC) {
  1250. if (perfcnt_per_sec == 0.0) {
  1251. QueryPerformanceFrequency((LARGE_INTEGER *) &li);
  1252. perfcnt_per_sec = 1.0 / li.QuadPart;
  1253. }
  1254. if (perfcnt_per_sec != 0.0) {
  1255. QueryPerformanceCounter((LARGE_INTEGER *) &li);
  1256. d = li.QuadPart * perfcnt_per_sec;
  1257. tp->tv_sec = (time_t)d;
  1258. d -= tp->tv_sec;
  1259. tp->tv_nsec = (long)(d*1.0E9);
  1260. ok = TRUE;
  1261. }
  1262. }
  1263. }
  1264. return ok ? 0 : -1;
  1265. }
  1266. #endif
  1267. static int pthread_cond_init(pthread_cond_t *cv, const void *unused)
  1268. {
  1269. (void) unused;
  1270. InitializeCriticalSection(&cv->threadIdSec);
  1271. cv->waitingthreadcount = 0;
  1272. cv->waitingthreadhdls = mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  1273. return (cv->waitingthreadhdls!=NULL) ? 0 : -1;
  1274. }
  1275. static int pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mutex, const struct timespec * abstime)
  1276. {
  1277. struct mg_workerTLS * tls = (struct mg_workerTLS *)TlsGetValue(sTlsKey);
  1278. int ok;
  1279. struct timespec tsnow;
  1280. int64_t nsnow, nswaitabs, nswaitrel;
  1281. DWORD mswaitrel;
  1282. EnterCriticalSection(&cv->threadIdSec);
  1283. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  1284. cv->waitingthreadhdls[cv->waitingthreadcount] = tls->pthread_cond_helper_mutex;
  1285. cv->waitingthreadcount++;
  1286. LeaveCriticalSection(&cv->threadIdSec);
  1287. if (abstime) {
  1288. clock_gettime(CLOCK_REALTIME, &tsnow);
  1289. nsnow = (((uint64_t)tsnow.tv_sec)<<32) + tsnow.tv_nsec;
  1290. nswaitabs = (((uint64_t)abstime->tv_sec)<<32) + abstime->tv_nsec;
  1291. nswaitrel = nswaitabs - nsnow;
  1292. if (nswaitrel<0) nswaitrel=0;
  1293. mswaitrel = (DWORD)(nswaitrel / 1000000);
  1294. } else {
  1295. mswaitrel = INFINITE;
  1296. }
  1297. pthread_mutex_unlock(mutex);
  1298. ok = (WAIT_OBJECT_0 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  1299. pthread_mutex_lock(mutex);
  1300. return ok ? 0 : -1;
  1301. }
  1302. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  1303. {
  1304. return pthread_cond_timedwait(cv, mutex, NULL);
  1305. }
  1306. static int pthread_cond_signal(pthread_cond_t *cv)
  1307. {
  1308. int i;
  1309. HANDLE wkup = NULL;
  1310. BOOL ok = FALSE;
  1311. EnterCriticalSection(&cv->threadIdSec);
  1312. if (cv->waitingthreadcount) {
  1313. wkup = cv->waitingthreadhdls[0];
  1314. ok = SetEvent(wkup);
  1315. for (i=1; i<cv->waitingthreadcount; i++) {
  1316. cv->waitingthreadhdls[i-1] = cv->waitingthreadhdls[i];
  1317. }
  1318. cv->waitingthreadcount--;
  1319. assert(ok);
  1320. }
  1321. LeaveCriticalSection(&cv->threadIdSec);
  1322. return ok ? 0 : 1;
  1323. }
  1324. static int pthread_cond_broadcast(pthread_cond_t *cv)
  1325. {
  1326. EnterCriticalSection(&cv->threadIdSec);
  1327. while (cv->waitingthreadcount) {
  1328. pthread_cond_signal(cv);
  1329. }
  1330. LeaveCriticalSection(&cv->threadIdSec);
  1331. return 0;
  1332. }
  1333. static int pthread_cond_destroy(pthread_cond_t *cv)
  1334. {
  1335. EnterCriticalSection(&cv->threadIdSec);
  1336. assert(cv->waitingthreadcount==0);
  1337. mg_free(cv->waitingthreadhdls);
  1338. cv->waitingthreadhdls = 0;
  1339. LeaveCriticalSection(&cv->threadIdSec);
  1340. DeleteCriticalSection(&cv->threadIdSec);
  1341. return 0;
  1342. }
  1343. /* For Windows, change all slashes to backslashes in path names. */
  1344. static void change_slashes_to_backslashes(char *path)
  1345. {
  1346. int i;
  1347. for (i = 0; path[i] != '\0'; i++) {
  1348. if (path[i] == '/')
  1349. path[i] = '\\';
  1350. /* i > 0 check is to preserve UNC paths, like \\server\file.txt */
  1351. if (path[i] == '\\' && i > 0)
  1352. while (path[i + 1] == '\\' || path[i + 1] == '/')
  1353. (void) memmove(path + i + 1,
  1354. path + i + 2, strlen(path + i + 1));
  1355. }
  1356. }
  1357. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  1358. wbuf and wbuf_len is a target buffer and its length. */
  1359. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  1360. {
  1361. char buf[PATH_MAX], buf2[PATH_MAX];
  1362. mg_strlcpy(buf, path, sizeof(buf));
  1363. change_slashes_to_backslashes(buf);
  1364. /* Convert to Unicode and back. If doubly-converted string does not
  1365. match the original, something is fishy, reject. */
  1366. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1367. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1368. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1369. NULL, NULL);
  1370. if (strcmp(buf, buf2) != 0) {
  1371. wbuf[0] = L'\0';
  1372. }
  1373. }
  1374. #if defined(_WIN32_WCE)
  1375. static time_t time(time_t *ptime)
  1376. {
  1377. time_t t;
  1378. SYSTEMTIME st;
  1379. FILETIME ft;
  1380. GetSystemTime(&st);
  1381. SystemTimeToFileTime(&st, &ft);
  1382. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  1383. if (ptime != NULL) {
  1384. *ptime = t;
  1385. }
  1386. return t;
  1387. }
  1388. static struct tm *localtime(const time_t *ptime, struct tm *ptm)
  1389. {
  1390. int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
  1391. FILETIME ft, lft;
  1392. SYSTEMTIME st;
  1393. TIME_ZONE_INFORMATION tzinfo;
  1394. if (ptm == NULL) {
  1395. return NULL;
  1396. }
  1397. * (int64_t *) &ft = t;
  1398. FileTimeToLocalFileTime(&ft, &lft);
  1399. FileTimeToSystemTime(&lft, &st);
  1400. ptm->tm_year = st.wYear - 1900;
  1401. ptm->tm_mon = st.wMonth - 1;
  1402. ptm->tm_wday = st.wDayOfWeek;
  1403. ptm->tm_mday = st.wDay;
  1404. ptm->tm_hour = st.wHour;
  1405. ptm->tm_min = st.wMinute;
  1406. ptm->tm_sec = st.wSecond;
  1407. ptm->tm_yday = 0; /* hope nobody uses this */
  1408. ptm->tm_isdst =
  1409. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  1410. return ptm;
  1411. }
  1412. static struct tm *gmtime(const time_t *ptime, struct tm *ptm)
  1413. {
  1414. /* FIXME(lsm): fix this. */
  1415. return localtime(ptime, ptm);
  1416. }
  1417. static size_t strftime(char *dst, size_t dst_size, const char *fmt,
  1418. const struct tm *tm)
  1419. {
  1420. (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
  1421. return 0;
  1422. }
  1423. #endif
  1424. /* Windows happily opens files with some garbage at the end of file name.
  1425. For example, fopen("a.cgi ", "r") on Windows successfully opens
  1426. "a.cgi", despite one would expect an error back.
  1427. This function returns non-0 if path ends with some garbage. */
  1428. static int path_cannot_disclose_cgi(const char *path)
  1429. {
  1430. static const char *allowed_last_characters = "_-";
  1431. int last = path[strlen(path) - 1];
  1432. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  1433. }
  1434. static int mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  1435. {
  1436. wchar_t wbuf[PATH_MAX];
  1437. WIN32_FILE_ATTRIBUTE_DATA info;
  1438. if (!is_file_in_memory(conn, path, filep)) {
  1439. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1440. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  1441. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  1442. filep->modification_time = SYS2UNIX_TIME(
  1443. info.ftLastWriteTime.dwLowDateTime,
  1444. info.ftLastWriteTime.dwHighDateTime);
  1445. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  1446. /* If file name is fishy, reset the file structure and return
  1447. error.
  1448. Note it is important to reset, not just return the error, cause
  1449. functions like is_file_opened() check the struct. */
  1450. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  1451. memset(filep, 0, sizeof(*filep));
  1452. }
  1453. }
  1454. }
  1455. return filep->membuf != NULL || filep->modification_time != 0;
  1456. }
  1457. static int mg_remove(const char *path)
  1458. {
  1459. wchar_t wbuf[PATH_MAX];
  1460. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1461. return DeleteFileW(wbuf) ? 0 : -1;
  1462. }
  1463. static int mg_mkdir(const char *path, int mode)
  1464. {
  1465. char buf[PATH_MAX];
  1466. wchar_t wbuf[PATH_MAX];
  1467. (void) mode;
  1468. mg_strlcpy(buf, path, sizeof(buf));
  1469. change_slashes_to_backslashes(buf);
  1470. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  1471. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  1472. }
  1473. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  1474. static DIR * opendir(const char *name)
  1475. {
  1476. DIR *dir = NULL;
  1477. wchar_t wpath[PATH_MAX];
  1478. DWORD attrs;
  1479. if (name == NULL) {
  1480. SetLastError(ERROR_BAD_ARGUMENTS);
  1481. } else if ((dir = (DIR *) mg_malloc(sizeof(*dir))) == NULL) {
  1482. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1483. } else {
  1484. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  1485. attrs = GetFileAttributesW(wpath);
  1486. if (attrs != 0xFFFFFFFF &&
  1487. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  1488. (void) wcscat(wpath, L"\\*");
  1489. dir->handle = FindFirstFileW(wpath, &dir->info);
  1490. dir->result.d_name[0] = '\0';
  1491. } else {
  1492. mg_free(dir);
  1493. dir = NULL;
  1494. }
  1495. }
  1496. return dir;
  1497. }
  1498. static int closedir(DIR *dir)
  1499. {
  1500. int result = 0;
  1501. if (dir != NULL) {
  1502. if (dir->handle != INVALID_HANDLE_VALUE)
  1503. result = FindClose(dir->handle) ? 0 : -1;
  1504. mg_free(dir);
  1505. } else {
  1506. result = -1;
  1507. SetLastError(ERROR_BAD_ARGUMENTS);
  1508. }
  1509. return result;
  1510. }
  1511. static struct dirent *readdir(DIR *dir)
  1512. {
  1513. struct dirent *result = 0;
  1514. if (dir) {
  1515. if (dir->handle != INVALID_HANDLE_VALUE) {
  1516. result = &dir->result;
  1517. (void) WideCharToMultiByte(CP_UTF8, 0,
  1518. dir->info.cFileName, -1, result->d_name,
  1519. sizeof(result->d_name), NULL, NULL);
  1520. if (!FindNextFileW(dir->handle, &dir->info)) {
  1521. (void) FindClose(dir->handle);
  1522. dir->handle = INVALID_HANDLE_VALUE;
  1523. }
  1524. } else {
  1525. SetLastError(ERROR_FILE_NOT_FOUND);
  1526. }
  1527. } else {
  1528. SetLastError(ERROR_BAD_ARGUMENTS);
  1529. }
  1530. return result;
  1531. }
  1532. #ifndef HAVE_POLL
  1533. static int poll(struct pollfd *pfd, int n, int milliseconds)
  1534. {
  1535. struct timeval tv;
  1536. fd_set set;
  1537. int i, result;
  1538. SOCKET maxfd = 0;
  1539. tv.tv_sec = milliseconds / 1000;
  1540. tv.tv_usec = (milliseconds % 1000) * 1000;
  1541. FD_ZERO(&set);
  1542. for (i = 0; i < n; i++) {
  1543. FD_SET((SOCKET) pfd[i].fd, &set);
  1544. pfd[i].revents = 0;
  1545. if (pfd[i].fd > maxfd) {
  1546. maxfd = pfd[i].fd;
  1547. }
  1548. }
  1549. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  1550. for (i = 0; i < n; i++) {
  1551. if (FD_ISSET(pfd[i].fd, &set)) {
  1552. pfd[i].revents = POLLIN;
  1553. }
  1554. }
  1555. }
  1556. return result;
  1557. }
  1558. #endif /* HAVE_POLL */
  1559. static void set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  1560. {
  1561. (void) conn; /* Unused. */
  1562. (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
  1563. }
  1564. int mg_start_thread(mg_thread_func_t f, void *p)
  1565. {
  1566. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  1567. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384 */
  1568. return ((_beginthread((void (__cdecl *)(void *)) f, USE_STACK_SIZE, p) == ((uintptr_t)(-1L))) ? -1 : 0);
  1569. #else
  1570. return ((_beginthread((void (__cdecl *)(void *)) f, 0, p) == ((uintptr_t)(-1L))) ? -1 : 0);
  1571. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  1572. }
  1573. /* Start a thread storing the thread context. */
  1574. static int mg_start_thread_with_id(unsigned (__stdcall *f)(void *), void *p,
  1575. pthread_t *threadidptr)
  1576. {
  1577. uintptr_t uip;
  1578. HANDLE threadhandle;
  1579. int result = -1;
  1580. uip = _beginthreadex(NULL, 0, (unsigned (__stdcall *)(void *)) f, p, 0,
  1581. NULL);
  1582. threadhandle = (HANDLE) uip;
  1583. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  1584. *threadidptr = threadhandle;
  1585. result = 0;
  1586. }
  1587. return result;
  1588. }
  1589. /* Wait for a thread to finish. */
  1590. static int mg_join_thread(pthread_t threadid)
  1591. {
  1592. int result;
  1593. DWORD dwevent;
  1594. result = -1;
  1595. dwevent = WaitForSingleObject(threadid, INFINITE);
  1596. if (dwevent == WAIT_FAILED) {
  1597. int err;
  1598. err = GetLastError();
  1599. DEBUG_TRACE("WaitForSingleObject() failed, error %d", err);
  1600. } else {
  1601. if (dwevent == WAIT_OBJECT_0) {
  1602. CloseHandle(threadid);
  1603. result = 0;
  1604. }
  1605. }
  1606. return result;
  1607. }
  1608. static HANDLE dlopen(const char *dll_name, int flags)
  1609. {
  1610. wchar_t wbuf[PATH_MAX];
  1611. (void) flags;
  1612. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  1613. return LoadLibraryW(wbuf);
  1614. }
  1615. static int dlclose(void *handle)
  1616. {
  1617. int result;
  1618. if (FreeLibrary(handle) != 0) {
  1619. result = 0;
  1620. } else {
  1621. result = -1;
  1622. }
  1623. return result;
  1624. }
  1625. #if !defined(NO_CGI)
  1626. #define SIGKILL 0
  1627. static int kill(pid_t pid, int sig_num)
  1628. {
  1629. (void) TerminateProcess(pid, sig_num);
  1630. (void) CloseHandle(pid);
  1631. return 0;
  1632. }
  1633. static void trim_trailing_whitespaces(char *s)
  1634. {
  1635. char *e = s + strlen(s) - 1;
  1636. while (e > s && isspace(* (unsigned char *) e)) {
  1637. *e-- = '\0';
  1638. }
  1639. }
  1640. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1641. char *envblk, char *envp[], int fdin,
  1642. int fdout, const char *dir)
  1643. {
  1644. HANDLE me;
  1645. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  1646. cmdline[PATH_MAX], buf[PATH_MAX];
  1647. struct file file = STRUCT_FILE_INITIALIZER;
  1648. STARTUPINFOA si;
  1649. PROCESS_INFORMATION pi = { 0 };
  1650. (void) envp;
  1651. memset(&si, 0, sizeof(si));
  1652. si.cb = sizeof(si);
  1653. /* TODO(lsm): redirect CGI errors to the error log file */
  1654. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1655. si.wShowWindow = SW_HIDE;
  1656. me = GetCurrentProcess();
  1657. DuplicateHandle(me, (HANDLE) _get_osfhandle(fdin), me,
  1658. &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1659. DuplicateHandle(me, (HANDLE) _get_osfhandle(fdout), me,
  1660. &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1661. /* If CGI file is a script, try to read the interpreter line */
  1662. interp = conn->ctx->config[CGI_INTERPRETER];
  1663. if (interp == NULL) {
  1664. buf[0] = buf[1] = '\0';
  1665. /* Read the first line of the script into the buffer */
  1666. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  1667. if (mg_fopen(conn, cmdline, "r", &file)) {
  1668. p = (char *) file.membuf;
  1669. mg_fgets(buf, sizeof(buf), &file, &p);
  1670. mg_fclose(&file);
  1671. buf[sizeof(buf) - 1] = '\0';
  1672. }
  1673. if (buf[0] == '#' && buf[1] == '!') {
  1674. trim_trailing_whitespaces(buf + 2);
  1675. } else {
  1676. buf[2] = '\0';
  1677. }
  1678. interp = buf + 2;
  1679. }
  1680. if (interp[0] != '\0') {
  1681. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  1682. interp = full_interp;
  1683. }
  1684. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  1685. mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s\"%s\\%s\"",
  1686. interp, interp[0] == '\0' ? "" : " ", full_dir, prog);
  1687. DEBUG_TRACE("Running [%s]", cmdline);
  1688. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  1689. CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
  1690. mg_cry(conn, "%s: CreateProcess(%s): %ld",
  1691. __func__, cmdline, ERRNO);
  1692. pi.hProcess = (pid_t) -1;
  1693. }
  1694. (void) CloseHandle(si.hStdOutput);
  1695. (void) CloseHandle(si.hStdInput);
  1696. if (pi.hThread != NULL)
  1697. (void) CloseHandle(pi.hThread);
  1698. return (pid_t) pi.hProcess;
  1699. }
  1700. #endif /* !NO_CGI */
  1701. static int set_non_blocking_mode(SOCKET sock)
  1702. {
  1703. unsigned long on = 1;
  1704. return ioctlsocket(sock, FIONBIO, &on);
  1705. }
  1706. #else
  1707. static int mg_stat(struct mg_connection *conn, const char *path,
  1708. struct file *filep)
  1709. {
  1710. struct stat st;
  1711. if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
  1712. filep->size = st.st_size;
  1713. filep->modification_time = st.st_mtime;
  1714. filep->is_directory = S_ISDIR(st.st_mode);
  1715. } else {
  1716. filep->modification_time = (time_t) 0;
  1717. }
  1718. return filep->membuf != NULL || filep->modification_time != (time_t) 0;
  1719. }
  1720. static void set_close_on_exec(int fd, struct mg_connection *conn /* may be null */)
  1721. {
  1722. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  1723. if (conn)
  1724. mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  1725. __func__, strerror(ERRNO));
  1726. }
  1727. }
  1728. int mg_start_thread(mg_thread_func_t func, void *param)
  1729. {
  1730. pthread_t thread_id;
  1731. pthread_attr_t attr;
  1732. int result;
  1733. (void) pthread_attr_init(&attr);
  1734. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  1735. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  1736. /* Compile-time option to control stack size,
  1737. e.g. -DUSE_STACK_SIZE=16384 */
  1738. (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  1739. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  1740. result = pthread_create(&thread_id, &attr, func, param);
  1741. pthread_attr_destroy(&attr);
  1742. return result;
  1743. }
  1744. /* Start a thread storing the thread context. */
  1745. static int mg_start_thread_with_id(mg_thread_func_t func, void *param,
  1746. pthread_t *threadidptr)
  1747. {
  1748. pthread_t thread_id;
  1749. pthread_attr_t attr;
  1750. int result;
  1751. (void) pthread_attr_init(&attr);
  1752. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  1753. /* Compile-time option to control stack size,
  1754. e.g. -DUSE_STACK_SIZE=16384 */
  1755. (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  1756. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  1757. result = pthread_create(&thread_id, &attr, func, param);
  1758. pthread_attr_destroy(&attr);
  1759. if (threadidptr != NULL) {
  1760. *threadidptr = thread_id;
  1761. }
  1762. return result;
  1763. }
  1764. /* Wait for a thread to finish. */
  1765. static int mg_join_thread(pthread_t threadid)
  1766. {
  1767. int result;
  1768. result = pthread_join(threadid, NULL);
  1769. return result;
  1770. }
  1771. #ifndef NO_CGI
  1772. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1773. char *envblk, char *envp[], int fdin,
  1774. int fdout, const char *dir)
  1775. {
  1776. pid_t pid;
  1777. const char *interp;
  1778. (void) envblk;
  1779. if ((pid = fork()) == -1) {
  1780. /* Parent */
  1781. send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
  1782. } else if (pid == 0) {
  1783. /* Child */
  1784. if (chdir(dir) != 0) {
  1785. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  1786. } else if (dup2(fdin, 0) == -1) {
  1787. mg_cry(conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  1788. } else if (dup2(fdout, 1) == -1) {
  1789. mg_cry(conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  1790. } else {
  1791. /* Not redirecting stderr to stdout, to avoid output being littered
  1792. with the error messages. */
  1793. (void) close(fdin);
  1794. (void) close(fdout);
  1795. /* After exec, all signal handlers are restored to their default
  1796. values, with one exception of SIGCHLD. According to
  1797. POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  1798. leave unchanged after exec if it was set to be ignored. Restore
  1799. it to default action. */
  1800. signal(SIGCHLD, SIG_DFL);
  1801. interp = conn->ctx->config[CGI_INTERPRETER];
  1802. if (interp == NULL) {
  1803. (void) execle(prog, prog, NULL, envp);
  1804. mg_cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
  1805. } else {
  1806. (void) execle(interp, interp, prog, NULL, envp);
  1807. mg_cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
  1808. strerror(ERRNO));
  1809. }
  1810. }
  1811. exit(EXIT_FAILURE);
  1812. }
  1813. return pid;
  1814. }
  1815. #endif /* !NO_CGI */
  1816. static int set_non_blocking_mode(SOCKET sock)
  1817. {
  1818. int flags;
  1819. flags = fcntl(sock, F_GETFL, 0);
  1820. (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  1821. return 0;
  1822. }
  1823. #endif /* _WIN32 */
  1824. /* Write data to the IO channel - opened file descriptor, socket or SSL
  1825. descriptor. Return number of bytes written. */
  1826. static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
  1827. int64_t len)
  1828. {
  1829. int64_t sent;
  1830. int n, k;
  1831. (void) ssl; /* Get rid of warning */
  1832. sent = 0;
  1833. while (sent < len) {
  1834. /* How many bytes we send in this iteration */
  1835. k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
  1836. #ifndef NO_SSL
  1837. if (ssl != NULL) {
  1838. n = SSL_write(ssl, buf + sent, k);
  1839. } else
  1840. #endif
  1841. if (fp != NULL) {
  1842. n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
  1843. if (ferror(fp))
  1844. n = -1;
  1845. } else {
  1846. n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
  1847. }
  1848. if (n <= 0)
  1849. break;
  1850. sent += n;
  1851. }
  1852. return sent;
  1853. }
  1854. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  1855. Return negative value on error, or number of bytes read on success. */
  1856. static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len)
  1857. {
  1858. int nread;
  1859. if (fp != NULL) {
  1860. /* Use read() instead of fread(), because if we're reading from the
  1861. CGI pipe, fread() may block until IO buffer is filled up. We cannot
  1862. afford to block and must pass all read bytes immediately to the
  1863. client. */
  1864. nread = read(fileno(fp), buf, (size_t) len);
  1865. #ifndef NO_SSL
  1866. } else if (conn->ssl != NULL) {
  1867. nread = SSL_read(conn->ssl, buf, len);
  1868. #endif
  1869. } else {
  1870. nread = recv(conn->client.sock, buf, (size_t) len, 0);
  1871. }
  1872. return conn->ctx->stop_flag ? -1 : nread;
  1873. }
  1874. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  1875. {
  1876. int n, nread = 0;
  1877. while (len > 0 && conn->ctx->stop_flag == 0) {
  1878. n = pull(fp, conn, buf + nread, len);
  1879. if (n < 0) {
  1880. nread = n; /* Propagate the error */
  1881. break;
  1882. } else if (n == 0) {
  1883. break; /* No more data to read */
  1884. } else {
  1885. conn->consumed_content += n;
  1886. nread += n;
  1887. len -= n;
  1888. }
  1889. }
  1890. return nread;
  1891. }
  1892. int mg_read(struct mg_connection *conn, void *buf, size_t len)
  1893. {
  1894. int64_t n, buffered_len, nread;
  1895. const char *body;
  1896. /* If Content-Length is not set for a PUT or POST request, read until socket is closed */
  1897. if (conn->consumed_content == 0 && conn->content_len == -1) {
  1898. conn->content_len = INT64_MAX;
  1899. conn->must_close = 1;
  1900. }
  1901. nread = 0;
  1902. if (conn->consumed_content < conn->content_len) {
  1903. /* Adjust number of bytes to read. */
  1904. int64_t to_read = conn->content_len - conn->consumed_content;
  1905. if (to_read < (int64_t) len) {
  1906. len = (size_t) to_read;
  1907. }
  1908. /* Return buffered data */
  1909. body = conn->buf + conn->request_len + conn->consumed_content;
  1910. buffered_len = (int64_t)(&conn->buf[conn->data_len] - body);
  1911. if (buffered_len > 0) {
  1912. if (len < (size_t) buffered_len) {
  1913. buffered_len = (int64_t) len;
  1914. }
  1915. memcpy(buf, body, (size_t) buffered_len);
  1916. len -= buffered_len;
  1917. conn->consumed_content += buffered_len;
  1918. nread += buffered_len;
  1919. buf = (char *) buf + buffered_len;
  1920. }
  1921. /* We have returned all buffered data. Read new data from the remote
  1922. socket. */
  1923. n = pull_all(NULL, conn, (char *) buf, (int64_t) len);
  1924. nread = n >= 0 ? nread + n : n;
  1925. }
  1926. return nread;
  1927. }
  1928. int mg_write(struct mg_connection *conn, const void *buf, size_t len)
  1929. {
  1930. time_t now;
  1931. int64_t n, total, allowed;
  1932. if (conn->throttle > 0) {
  1933. if ((now = time(NULL)) != conn->last_throttle_time) {
  1934. conn->last_throttle_time = now;
  1935. conn->last_throttle_bytes = 0;
  1936. }
  1937. allowed = conn->throttle - conn->last_throttle_bytes;
  1938. if (allowed > (int64_t) len) {
  1939. allowed = len;
  1940. }
  1941. if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1942. (int64_t) allowed)) == allowed) {
  1943. buf = (char *) buf + total;
  1944. conn->last_throttle_bytes += total;
  1945. while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
  1946. allowed = conn->throttle > (int64_t) len - total ?
  1947. (int64_t) len - total : conn->throttle;
  1948. if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1949. (int64_t) allowed)) != allowed) {
  1950. break;
  1951. }
  1952. sleep(1);
  1953. conn->last_throttle_bytes = allowed;
  1954. conn->last_throttle_time = time(NULL);
  1955. buf = (char *) buf + n;
  1956. total += n;
  1957. }
  1958. }
  1959. } else {
  1960. total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1961. (int64_t) len);
  1962. }
  1963. return (int) total;
  1964. }
  1965. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  1966. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  1967. {
  1968. va_list ap_copy;
  1969. int size = MG_BUF_LEN;
  1970. int len = -1;
  1971. *buf = NULL;
  1972. while (len == -1) {
  1973. if (*buf) mg_free(*buf);
  1974. *buf = (char *)mg_malloc(size *= 4);
  1975. if (!*buf) break;
  1976. va_copy(ap_copy, ap);
  1977. len = vsnprintf(*buf, size, fmt, ap_copy);
  1978. va_end(ap_copy);
  1979. }
  1980. return len;
  1981. }
  1982. /* Print message to buffer. If buffer is large enough to hold the message,
  1983. return buffer. If buffer is to small, allocate large enough buffer on heap,
  1984. and return allocated buffer. */
  1985. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  1986. {
  1987. va_list ap_copy;
  1988. int len;
  1989. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  1990. buffer is too small. Also, older versions of msvcrt.dll do not have
  1991. _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  1992. Therefore, we make two passes: on first pass, get required message
  1993. length.
  1994. On second pass, actually print the message. */
  1995. va_copy(ap_copy, ap);
  1996. len = vsnprintf(NULL, 0, fmt, ap_copy);
  1997. va_end(ap_copy);
  1998. if (len < 0) {
  1999. /* C runtime is not standard compliant, vsnprintf() returned -1.
  2000. Switch to alternative code path that uses incremental allocations.
  2001. */
  2002. va_copy(ap_copy, ap);
  2003. len = alloc_vprintf2(buf, fmt, ap);
  2004. va_end(ap_copy);
  2005. } else if (len > (int) size &&
  2006. (size = len + 1) > 0 &&
  2007. (*buf = (char *) mg_malloc(size)) == NULL) {
  2008. len = -1; /* Allocation failed, mark failure */
  2009. } else {
  2010. va_copy(ap_copy, ap);
  2011. IGNORE_UNUSED_RESULT(vsnprintf(*buf, size, fmt, ap_copy));
  2012. va_end(ap_copy);
  2013. }
  2014. return len;
  2015. }
  2016. int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap);
  2017. int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  2018. {
  2019. char mem[MG_BUF_LEN], *buf = mem;
  2020. int len;
  2021. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  2022. len = mg_write(conn, buf, (size_t) len);
  2023. }
  2024. if (buf != mem && buf != NULL) {
  2025. mg_free(buf);
  2026. }
  2027. return len;
  2028. }
  2029. int mg_printf(struct mg_connection *conn, const char *fmt, ...)
  2030. {
  2031. va_list ap;
  2032. int result;
  2033. va_start(ap, fmt);
  2034. result = mg_vprintf(conn, fmt, ap);
  2035. va_end(ap);
  2036. return result;
  2037. }
  2038. int mg_url_decode(const char *src, int src_len, char *dst,
  2039. int dst_len, int is_form_url_encoded)
  2040. {
  2041. int i, j, a, b;
  2042. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  2043. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  2044. if (i < src_len - 2 && src[i] == '%' &&
  2045. isxdigit(* (const unsigned char *) (src + i + 1)) &&
  2046. isxdigit(* (const unsigned char *) (src + i + 2))) {
  2047. a = tolower(* (const unsigned char *) (src + i + 1));
  2048. b = tolower(* (const unsigned char *) (src + i + 2));
  2049. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  2050. i += 2;
  2051. } else if (is_form_url_encoded && src[i] == '+') {
  2052. dst[j] = ' ';
  2053. } else {
  2054. dst[j] = src[i];
  2055. }
  2056. }
  2057. dst[j] = '\0'; /* Null-terminate the destination */
  2058. return i >= src_len ? j : -1;
  2059. }
  2060. int mg_get_var(const char *data, size_t data_len, const char *name,
  2061. char *dst, size_t dst_len)
  2062. {
  2063. return mg_get_var2(data,data_len,name,dst,dst_len,0);
  2064. }
  2065. int mg_get_var2(const char *data, size_t data_len, const char *name,
  2066. char *dst, size_t dst_len, size_t occurrence)
  2067. {
  2068. const char *p, *e, *s;
  2069. size_t name_len;
  2070. int len;
  2071. if (dst == NULL || dst_len == 0) {
  2072. len = -2;
  2073. } else if (data == NULL || name == NULL || data_len == 0) {
  2074. len = -1;
  2075. dst[0] = '\0';
  2076. } else {
  2077. name_len = strlen(name);
  2078. e = data + data_len;
  2079. len = -1;
  2080. dst[0] = '\0';
  2081. /* data is "var1=val1&var2=val2...". Find variable first */
  2082. for (p = data; p + name_len < e; p++) {
  2083. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  2084. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  2085. /* Point p to variable value */
  2086. p += name_len + 1;
  2087. /* Point s to the end of the value */
  2088. s = (const char *) memchr(p, '&', (size_t)(e - p));
  2089. if (s == NULL) {
  2090. s = e;
  2091. }
  2092. assert(s >= p);
  2093. /* Decode variable into destination buffer */
  2094. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  2095. /* Redirect error code from -1 to -2 (destination buffer too
  2096. small). */
  2097. if (len == -1) {
  2098. len = -2;
  2099. }
  2100. break;
  2101. }
  2102. }
  2103. }
  2104. return len;
  2105. }
  2106. int mg_get_cookie(const char *cookie_header, const char *var_name,
  2107. char *dst, size_t dst_size)
  2108. {
  2109. const char *s, *p, *end;
  2110. int name_len, len = -1;
  2111. if (dst == NULL || dst_size == 0) {
  2112. len = -2;
  2113. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  2114. len = -1;
  2115. dst[0] = '\0';
  2116. } else {
  2117. name_len = (int) strlen(var_name);
  2118. end = s + strlen(s);
  2119. dst[0] = '\0';
  2120. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  2121. if (s[name_len] == '=') {
  2122. s += name_len + 1;
  2123. if ((p = strchr(s, ' ')) == NULL)
  2124. p = end;
  2125. if (p[-1] == ';')
  2126. p--;
  2127. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  2128. s++;
  2129. p--;
  2130. }
  2131. if ((size_t) (p - s) < dst_size) {
  2132. len = (int)(p - s);
  2133. mg_strlcpy(dst, s, (size_t) len + 1);
  2134. } else {
  2135. len = -3;
  2136. }
  2137. break;
  2138. }
  2139. }
  2140. }
  2141. return len;
  2142. }
  2143. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  2144. static void base64_encode(const unsigned char *src, int src_len, char *dst)
  2145. {
  2146. static const char *b64 =
  2147. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2148. int i, j, a, b, c;
  2149. for (i = j = 0; i < src_len; i += 3) {
  2150. a = src[i];
  2151. b = i + 1 >= src_len ? 0 : src[i + 1];
  2152. c = i + 2 >= src_len ? 0 : src[i + 2];
  2153. dst[j++] = b64[a >> 2];
  2154. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  2155. if (i + 1 < src_len) {
  2156. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  2157. }
  2158. if (i + 2 < src_len) {
  2159. dst[j++] = b64[c & 63];
  2160. }
  2161. }
  2162. while (j % 4 != 0) {
  2163. dst[j++] = '=';
  2164. }
  2165. dst[j++] = '\0';
  2166. }
  2167. static unsigned char b64reverse(char letter) {
  2168. if (letter>='A' && letter<='Z') return letter-'A';
  2169. if (letter>='a' && letter<='z') return letter-'a'+26;
  2170. if (letter>='0' && letter<='9') return letter-'0'+52;
  2171. if (letter=='+') return 62;
  2172. if (letter=='/') return 63;
  2173. if (letter=='=') return 255; /* normal end */
  2174. return 254; /* error */
  2175. }
  2176. static int base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  2177. {
  2178. int i;
  2179. unsigned char a, b, c, d;
  2180. *dst_len = 0;
  2181. for (i = 0; i < src_len; i += 4) {
  2182. a = b64reverse(src[i]);
  2183. if (a>=254) return i;
  2184. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  2185. if (b>=254) return i+1;
  2186. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  2187. if (c==254) return i+2;
  2188. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  2189. if (c==254) return i+3;
  2190. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  2191. if (c!=255) {
  2192. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  2193. if (d!=255) {
  2194. dst[(*dst_len)++] = (c << 6) + d;
  2195. }
  2196. }
  2197. }
  2198. return -1;
  2199. }
  2200. #endif
  2201. static void convert_uri_to_file_name(struct mg_connection *conn, char *buf,
  2202. size_t buf_len, struct file *filep,
  2203. int * is_script_ressource)
  2204. {
  2205. struct vec a, b;
  2206. const char *rewrite, *uri = conn->request_info.uri,
  2207. *root = conn->ctx->config[DOCUMENT_ROOT];
  2208. char *p;
  2209. int match_len;
  2210. char gz_path[PATH_MAX];
  2211. char const* accept_encoding;
  2212. *is_script_ressource = 0;
  2213. #if defined(USE_WEBSOCKET)
  2214. if (is_websocket_request(conn) && conn->ctx->config[WEBSOCKET_ROOT]) {
  2215. root = conn->ctx->config[WEBSOCKET_ROOT];
  2216. }
  2217. #endif
  2218. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  2219. of the path one byte on the right.
  2220. If document_root is NULL, leave the file empty. */
  2221. mg_snprintf(conn, buf, buf_len - 1, "%s%s",
  2222. root == NULL ? "" : root,
  2223. root == NULL ? "" : uri);
  2224. rewrite = conn->ctx->config[REWRITE];
  2225. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  2226. if ((match_len = match_prefix(a.ptr, (int) a.len, uri)) > 0) {
  2227. mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr,
  2228. uri + match_len);
  2229. break;
  2230. }
  2231. }
  2232. if (mg_stat(conn, buf, filep)) return;
  2233. /* if we can't find the actual file, look for the file
  2234. with the same name but a .gz extension. If we find it,
  2235. use that and set the gzipped flag in the file struct
  2236. to indicate that the response need to have the content-
  2237. encoding: gzip header
  2238. we can only do this if the browser declares support */
  2239. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  2240. if (strstr(accept_encoding,"gzip") != NULL) {
  2241. snprintf(gz_path, sizeof(gz_path), "%s.gz", buf);
  2242. if (mg_stat(conn, gz_path, filep)) {
  2243. filep->gzipped = 1;
  2244. return;
  2245. }
  2246. }
  2247. }
  2248. /* Support PATH_INFO for CGI scripts. */
  2249. for (p = buf + strlen(buf); p > buf + 1; p--) {
  2250. if (*p == '/') {
  2251. *p = '\0';
  2252. if ((match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  2253. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0
  2254. #ifdef USE_LUA
  2255. ||
  2256. match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  2257. (int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]), buf) > 0
  2258. #endif
  2259. ) && mg_stat(conn, buf, filep)) {
  2260. /* Shift PATH_INFO block one character right, e.g.
  2261. "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  2262. conn->path_info is pointing to the local variable "path"
  2263. declared in handle_request(), so PATH_INFO is not valid
  2264. after handle_request returns. */
  2265. conn->path_info = p + 1;
  2266. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  2267. trailing \0 */
  2268. p[1] = '/';
  2269. *is_script_ressource = 1;
  2270. break;
  2271. } else {
  2272. *p = '/';
  2273. }
  2274. }
  2275. }
  2276. }
  2277. /* Check whether full request is buffered. Return:
  2278. -1 if request is malformed
  2279. 0 if request is not yet fully buffered
  2280. >0 actual request length, including last \r\n\r\n */
  2281. static int get_request_len(const char *buf, int buflen)
  2282. {
  2283. const char *s, *e;
  2284. int len = 0;
  2285. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  2286. /* Control characters are not allowed but >=128 is. */
  2287. if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
  2288. *s != '\n' && * (const unsigned char *) s < 128) {
  2289. len = -1;
  2290. break; /* [i_a] abort scan as soon as one malformed character is
  2291. found; */
  2292. /* don't let subsequent \r\n\r\n win us over anyhow */
  2293. } else if (s[0] == '\n' && s[1] == '\n') {
  2294. len = (int) (s - buf) + 2;
  2295. } else if (s[0] == '\n' && &s[1] < e &&
  2296. s[1] == '\r' && s[2] == '\n') {
  2297. len = (int) (s - buf) + 3;
  2298. }
  2299. return len;
  2300. }
  2301. /* Convert month to the month number. Return -1 on error, or month number */
  2302. static int get_month_index(const char *s)
  2303. {
  2304. size_t i;
  2305. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  2306. if (!strcmp(s, month_names[i]))
  2307. return (int) i;
  2308. return -1;
  2309. }
  2310. static int num_leap_years(int year)
  2311. {
  2312. return year / 4 - year / 100 + year / 400;
  2313. }
  2314. /* Parse UTC date-time string, and return the corresponding time_t value. */
  2315. static time_t parse_date_string(const char *datetime)
  2316. {
  2317. static const unsigned short days_before_month[] = {
  2318. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  2319. };
  2320. char month_str[32]={0};
  2321. int second, minute, hour, day, month, year, leap_days, days;
  2322. time_t result = (time_t) 0;
  2323. if ((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
  2324. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  2325. (sscanf(datetime, "%d %3s %d %d:%d:%d",
  2326. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  2327. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
  2328. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  2329. (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
  2330. &day, month_str, &year, &hour, &minute, &second) == 6)) {
  2331. month = get_month_index(month_str);
  2332. if ((month >= 0) && (year > 1970)) {
  2333. leap_days = num_leap_years(year) - num_leap_years(1970);
  2334. year -= 1970;
  2335. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  2336. result = (time_t) days * 24 * 3600 + (time_t) hour * 3600 +
  2337. minute * 60 + second;
  2338. }
  2339. }
  2340. return result;
  2341. }
  2342. /* Protect against directory disclosure attack by removing '..',
  2343. excessive '/' and '\' characters */
  2344. static void remove_double_dots_and_double_slashes(char *s)
  2345. {
  2346. char *p = s;
  2347. while (*s != '\0') {
  2348. *p++ = *s++;
  2349. if (s[-1] == '/' || s[-1] == '\\') {
  2350. /* Skip all following slashes, backslashes and double-dots */
  2351. while (s[0] != '\0') {
  2352. if (s[0] == '/' || s[0] == '\\') {
  2353. s++;
  2354. } else if (s[0] == '.' && s[1] == '.') {
  2355. s += 2;
  2356. } else {
  2357. break;
  2358. }
  2359. }
  2360. }
  2361. }
  2362. *p = '\0';
  2363. }
  2364. static const struct {
  2365. const char *extension;
  2366. size_t ext_len;
  2367. const char *mime_type;
  2368. } builtin_mime_types[] = {
  2369. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  2370. application types */
  2371. {".doc", 4, "application/msword"},
  2372. {".eps", 4, "application/postscript"},
  2373. {".exe", 4, "application/octet-stream"},
  2374. {".js", 3, "application/javascript"},
  2375. {".json", 5, "application/json"},
  2376. {".pdf", 4, "application/pdf"},
  2377. {".ps", 3, "application/postscript"},
  2378. {".rtf", 4, "application/rtf"},
  2379. {".xhtml", 6, "application/xhtml+xml"},
  2380. {".xsl", 4, "application/xml"},
  2381. {".xslt", 5, "application/xml"},
  2382. /* audio */
  2383. {".mp3", 4, "audio/mpeg"},
  2384. {".oga", 4, "audio/ogg"},
  2385. {".ogg", 4, "audio/ogg"},
  2386. /* image */
  2387. {".gif", 4, "image/gif"},
  2388. {".ief", 4, "image/ief"},
  2389. {".jpeg", 5, "image/jpeg"},
  2390. {".jpg", 4, "image/jpeg"},
  2391. {".jpm", 4, "image/jpm"},
  2392. {".jpx", 4, "image/jpx"},
  2393. {".png", 4, "image/png"},
  2394. {".svg", 4, "image/svg+xml"},
  2395. {".tif", 4, "image/tiff"},
  2396. {".tiff", 5, "image/tiff"},
  2397. /* model */
  2398. {".wrl", 4, "model/vrml"},
  2399. /* text */
  2400. {".css", 4, "text/css"},
  2401. {".csv", 4, "text/csv"},
  2402. {".htm", 4, "text/html"},
  2403. {".html", 5, "text/html"},
  2404. {".sgm", 4, "text/sgml"},
  2405. {".shtm", 5, "text/html"},
  2406. {".shtml", 6, "text/html"},
  2407. {".txt", 4, "text/plain"},
  2408. {".xml", 4, "text/xml"},
  2409. /* video */
  2410. {".mov", 4, "video/quicktime"},
  2411. {".mp4", 4, "video/mp4"},
  2412. {".mpeg", 5, "video/mpeg"},
  2413. {".mpg", 4, "video/mpeg"},
  2414. {".ogv", 4, "video/ogg"},
  2415. {".qt", 3, "video/quicktime"},
  2416. /* not registered types
  2417. (http://reference.sitepoint.com/html/mime-types-full,
  2418. http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  2419. {".arj", 4, "application/x-arj-compressed"},
  2420. {".gz", 3, "application/x-gunzip"},
  2421. {".rar", 4, "application/x-arj-compressed"},
  2422. {".swf", 4, "application/x-shockwave-flash"},
  2423. {".tar", 4, "application/x-tar"},
  2424. {".tgz", 4, "application/x-tar-gz"},
  2425. {".torrent", 8, "application/x-bittorrent"},
  2426. {".ppt", 4, "application/x-mspowerpoint"},
  2427. {".xls", 4, "application/x-msexcel"},
  2428. {".zip", 4, "application/x-zip-compressed"},
  2429. {".aac", 4, "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  2430. {".aif", 4, "audio/x-aif"},
  2431. {".m3u", 4, "audio/x-mpegurl"},
  2432. {".mid", 4, "audio/x-midi"},
  2433. {".ra", 3, "audio/x-pn-realaudio"},
  2434. {".ram", 4, "audio/x-pn-realaudio"},
  2435. {".wav", 4, "audio/x-wav"},
  2436. {".bmp", 4, "image/bmp"},
  2437. {".ico", 4, "image/x-icon"},
  2438. {".pct", 4, "image/x-pct"},
  2439. {".pict", 5, "image/pict"},
  2440. {".rgb", 4, "image/x-rgb"},
  2441. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  2442. {".asf", 4, "video/x-ms-asf"},
  2443. {".avi", 4, "video/x-msvideo"},
  2444. {".m4v", 4, "video/x-m4v"},
  2445. {NULL, 0, NULL}
  2446. };
  2447. const char *mg_get_builtin_mime_type(const char *path)
  2448. {
  2449. const char *ext;
  2450. size_t i, path_len;
  2451. path_len = strlen(path);
  2452. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  2453. ext = path + (path_len - builtin_mime_types[i].ext_len);
  2454. if (path_len > builtin_mime_types[i].ext_len &&
  2455. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  2456. return builtin_mime_types[i].mime_type;
  2457. }
  2458. }
  2459. return "text/plain";
  2460. }
  2461. /* Look at the "path" extension and figure what mime type it has.
  2462. Store mime type in the vector. */
  2463. static void get_mime_type(struct mg_context *ctx, const char *path,
  2464. struct vec *vec)
  2465. {
  2466. struct vec ext_vec, mime_vec;
  2467. const char *list, *ext;
  2468. size_t path_len;
  2469. path_len = strlen(path);
  2470. /* Scan user-defined mime types first, in case user wants to
  2471. override default mime types. */
  2472. list = ctx->config[EXTRA_MIME_TYPES];
  2473. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  2474. /* ext now points to the path suffix */
  2475. ext = path + path_len - ext_vec.len;
  2476. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  2477. *vec = mime_vec;
  2478. return;
  2479. }
  2480. }
  2481. vec->ptr = mg_get_builtin_mime_type(path);
  2482. vec->len = strlen(vec->ptr);
  2483. }
  2484. /* Stringify binary data. Output buffer must be twice as big as input,
  2485. because each byte takes 2 bytes in string representation */
  2486. static void bin2str(char *to, const unsigned char *p, size_t len)
  2487. {
  2488. static const char *hex = "0123456789abcdef";
  2489. for (; len--; p++) {
  2490. *to++ = hex[p[0] >> 4];
  2491. *to++ = hex[p[0] & 0x0f];
  2492. }
  2493. *to = '\0';
  2494. }
  2495. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  2496. char *mg_md5(char buf[33], ...)
  2497. {
  2498. md5_byte_t hash[16];
  2499. const char *p;
  2500. va_list ap;
  2501. md5_state_t ctx;
  2502. md5_init(&ctx);
  2503. va_start(ap, buf);
  2504. while ((p = va_arg(ap, const char *)) != NULL) {
  2505. md5_append(&ctx, (const md5_byte_t *) p, (int) strlen(p));
  2506. }
  2507. va_end(ap);
  2508. md5_finish(&ctx, hash);
  2509. bin2str(buf, hash, sizeof(hash));
  2510. return buf;
  2511. }
  2512. /* Check the user's password, return 1 if OK */
  2513. static int check_password(const char *method, const char *ha1, const char *uri,
  2514. const char *nonce, const char *nc, const char *cnonce,
  2515. const char *qop, const char *response)
  2516. {
  2517. char ha2[32 + 1], expected_response[32 + 1];
  2518. /* Some of the parameters may be NULL */
  2519. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  2520. qop == NULL || response == NULL) {
  2521. return 0;
  2522. }
  2523. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  2524. /* TODO(lsm): check for authentication timeout */
  2525. if (/* strcmp(dig->uri, c->ouri) != 0 || */
  2526. strlen(response) != 32
  2527. /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
  2528. ) {
  2529. return 0;
  2530. }
  2531. mg_md5(ha2, method, ":", uri, NULL);
  2532. mg_md5(expected_response, ha1, ":", nonce, ":", nc,
  2533. ":", cnonce, ":", qop, ":", ha2, NULL);
  2534. return mg_strcasecmp(response, expected_response) == 0;
  2535. }
  2536. /* Use the global passwords file, if specified by auth_gpass option,
  2537. or search for .htpasswd in the requested directory. */
  2538. static void open_auth_file(struct mg_connection *conn, const char *path,
  2539. struct file *filep)
  2540. {
  2541. char name[PATH_MAX];
  2542. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  2543. struct file file = STRUCT_FILE_INITIALIZER;
  2544. if (gpass != NULL) {
  2545. /* Use global passwords file */
  2546. if (!mg_fopen(conn, gpass, "r", filep)) {
  2547. #ifdef DEBUG
  2548. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  2549. #endif
  2550. }
  2551. /* Important: using local struct file to test path for is_directory
  2552. flag.
  2553. If filep is used, mg_stat() makes it appear as if auth file was
  2554. opened. */
  2555. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  2556. mg_snprintf(conn, name, sizeof(name), "%s%c%s",
  2557. path, '/', PASSWORDS_FILE_NAME);
  2558. if (!mg_fopen(conn, name, "r", filep)) {
  2559. #ifdef DEBUG
  2560. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  2561. #endif
  2562. }
  2563. } else {
  2564. /* Try to find .htpasswd in requested directory. */
  2565. for (p = path, e = p + strlen(p) - 1; e > p; e--)
  2566. if (e[0] == '/')
  2567. break;
  2568. mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
  2569. (int) (e - p), p, '/', PASSWORDS_FILE_NAME);
  2570. if (!mg_fopen(conn, name, "r", filep)) {
  2571. #ifdef DEBUG
  2572. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  2573. #endif
  2574. }
  2575. }
  2576. }
  2577. /* Parsed Authorization header */
  2578. struct ah {
  2579. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  2580. };
  2581. /* Return 1 on success. Always initializes the ah structure. */
  2582. static int parse_auth_header(struct mg_connection *conn, char *buf,
  2583. size_t buf_size, struct ah *ah)
  2584. {
  2585. char *name, *value, *s;
  2586. const char *auth_header;
  2587. unsigned long nonce;
  2588. (void) memset(ah, 0, sizeof(*ah));
  2589. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  2590. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  2591. return 0;
  2592. }
  2593. /* Make modifiable copy of the auth header */
  2594. (void) mg_strlcpy(buf, auth_header + 7, buf_size);
  2595. s = buf;
  2596. /* Parse authorization header */
  2597. for (;;) {
  2598. /* Gobble initial spaces */
  2599. while (isspace(* (unsigned char *) s)) {
  2600. s++;
  2601. }
  2602. name = skip_quoted(&s, "=", " ", 0);
  2603. /* Value is either quote-delimited, or ends at first comma or space. */
  2604. if (s[0] == '\"') {
  2605. s++;
  2606. value = skip_quoted(&s, "\"", " ", '\\');
  2607. if (s[0] == ',') {
  2608. s++;
  2609. }
  2610. } else {
  2611. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  2612. spaces */
  2613. }
  2614. if (*name == '\0') {
  2615. break;
  2616. }
  2617. if (!strcmp(name, "username")) {
  2618. ah->user = value;
  2619. } else if (!strcmp(name, "cnonce")) {
  2620. ah->cnonce = value;
  2621. } else if (!strcmp(name, "response")) {
  2622. ah->response = value;
  2623. } else if (!strcmp(name, "uri")) {
  2624. ah->uri = value;
  2625. } else if (!strcmp(name, "qop")) {
  2626. ah->qop = value;
  2627. } else if (!strcmp(name, "nc")) {
  2628. ah->nc = value;
  2629. } else if (!strcmp(name, "nonce")) {
  2630. ah->nonce = value;
  2631. }
  2632. }
  2633. #ifndef NO_NONCE_CHECK
  2634. /* Convert the nonce from the client to a number and check it. */
  2635. /* Server side nonce check is valuable in all situations but one: if the server restarts frequently,
  2636. but the client should not see that, so the server should accept nonces from previous starts. */
  2637. if (ah->nonce == NULL) {
  2638. return 0;
  2639. }
  2640. nonce = strtoul(ah->nonce, &s, 10);
  2641. if ((s == NULL) || (*s != 0)) {
  2642. return 0;
  2643. }
  2644. nonce ^= (unsigned long)(conn->ctx);
  2645. if (nonce<conn->ctx->start_time) {
  2646. /* nonce is from a previous start of the server and no longer valid (replay attack?) */
  2647. return 0;
  2648. }
  2649. if (nonce>=conn->ctx->start_time+conn->ctx->nonce_count) {
  2650. return 0;
  2651. }
  2652. #endif
  2653. /* CGI needs it as REMOTE_USER */
  2654. if (ah->user != NULL) {
  2655. conn->request_info.remote_user = mg_strdup(ah->user);
  2656. } else {
  2657. return 0;
  2658. }
  2659. return 1;
  2660. }
  2661. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  2662. {
  2663. char *eof;
  2664. size_t len;
  2665. char *memend;
  2666. if (filep->membuf != NULL && *p != NULL) {
  2667. memend = (char *) &filep->membuf[filep->size];
  2668. eof = (char *) memchr(*p, '\n', memend - *p); /* Search for \n from p till the end of stream */
  2669. if (eof != NULL) {
  2670. eof += 1; /* Include \n */
  2671. } else {
  2672. eof = memend; /* Copy remaining data */
  2673. }
  2674. len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);
  2675. memcpy(buf, *p, len);
  2676. buf[len] = '\0';
  2677. *p += len;
  2678. return len ? eof : NULL;
  2679. } else if (filep->fp != NULL) {
  2680. return fgets(buf, (int)size, filep->fp);
  2681. } else {
  2682. return NULL;
  2683. }
  2684. }
  2685. /* Authorize against the opened passwords file. Return 1 if authorized. */
  2686. static int authorize(struct mg_connection *conn, struct file *filep)
  2687. {
  2688. struct ah ah;
  2689. char line[256], f_user[256] = "", ha1[256] = "", f_domain[256] = "", buf[MG_BUF_LEN], *p;
  2690. if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {
  2691. return 0;
  2692. }
  2693. /* Loop over passwords file */
  2694. p = (char *) filep->membuf;
  2695. while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {
  2696. if (sscanf(line, "%255[^:]:%255[^:]:%255s", f_user, f_domain, ha1) != 3) {
  2697. continue;
  2698. }
  2699. f_user[255]=0;
  2700. f_domain[255]=0;
  2701. ha1[255]=0;
  2702. if (!strcmp(ah.user, f_user) &&
  2703. !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
  2704. return check_password(conn->request_info.request_method, ha1, ah.uri,
  2705. ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);
  2706. }
  2707. return 0;
  2708. }
  2709. /* Return 1 if request is authorised, 0 otherwise. */
  2710. static int check_authorization(struct mg_connection *conn, const char *path)
  2711. {
  2712. char fname[PATH_MAX];
  2713. struct vec uri_vec, filename_vec;
  2714. const char *list;
  2715. struct file file = STRUCT_FILE_INITIALIZER;
  2716. int authorized = 1;
  2717. list = conn->ctx->config[PROTECT_URI];
  2718. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  2719. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  2720. mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  2721. (int) filename_vec.len, filename_vec.ptr);
  2722. if (!mg_fopen(conn, fname, "r", &file)) {
  2723. mg_cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
  2724. }
  2725. break;
  2726. }
  2727. }
  2728. if (!is_file_opened(&file)) {
  2729. open_auth_file(conn, path, &file);
  2730. }
  2731. if (is_file_opened(&file)) {
  2732. authorized = authorize(conn, &file);
  2733. mg_fclose(&file);
  2734. }
  2735. return authorized;
  2736. }
  2737. static void send_authorization_request(struct mg_connection *conn)
  2738. {
  2739. char date[64];
  2740. time_t curtime = time(NULL);
  2741. unsigned long nonce = (unsigned long)(conn->ctx->start_time);
  2742. (void)pthread_mutex_lock(&conn->ctx->mutex);
  2743. nonce += conn->ctx->nonce_count;
  2744. ++conn->ctx->nonce_count;
  2745. (void)pthread_mutex_unlock(&conn->ctx->mutex);
  2746. nonce ^= (unsigned long)(conn->ctx);
  2747. conn->status_code = 401;
  2748. conn->must_close = 1;
  2749. gmt_time_string(date, sizeof(date), &curtime);
  2750. mg_printf(conn,
  2751. "HTTP/1.1 401 Unauthorized\r\n"
  2752. "Date: %s\r\n"
  2753. "Connection: %s\r\n"
  2754. "Content-Length: 0\r\n"
  2755. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
  2756. date, suggest_connection_header(conn),
  2757. conn->ctx->config[AUTHENTICATION_DOMAIN],
  2758. nonce);
  2759. }
  2760. static int is_authorized_for_put(struct mg_connection *conn)
  2761. {
  2762. struct file file = STRUCT_FILE_INITIALIZER;
  2763. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  2764. int ret = 0;
  2765. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  2766. ret = authorize(conn, &file);
  2767. mg_fclose(&file);
  2768. }
  2769. return ret;
  2770. }
  2771. int mg_modify_passwords_file(const char *fname, const char *domain,
  2772. const char *user, const char *pass)
  2773. {
  2774. int found, i;
  2775. char line[512], u[512] = "", d[512] ="", ha1[33], tmp[PATH_MAX+8];
  2776. FILE *fp, *fp2;
  2777. found = 0;
  2778. fp = fp2 = NULL;
  2779. /* Regard empty password as no password - remove user record. */
  2780. if (pass != NULL && pass[0] == '\0') {
  2781. pass = NULL;
  2782. }
  2783. /* Other arguments must not be empty */
  2784. if (fname == NULL || domain == NULL || user == NULL) return 0;
  2785. /* Using the given file format, user name and domain must not contain ':' */
  2786. if (strchr(user, ':') != NULL) return 0;
  2787. if (strchr(domain, ':') != NULL) return 0;
  2788. /* Do not allow control characters like newline in user name and domain.
  2789. Do not allow excessively long names either. */
  2790. for (i=0; user[i]!=0 && i<255; i++) {
  2791. if (iscntrl(user[i])) return 0;
  2792. }
  2793. if (user[i]) return 0;
  2794. for (i=0; domain[i]!=0 && i<255; i++) {
  2795. if (iscntrl(domain[i])) return 0;
  2796. }
  2797. if (domain[i]) return 0;
  2798. /* Create a temporary file name */
  2799. (void) snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
  2800. tmp[sizeof(tmp) - 1] = 0;
  2801. /* Create the file if does not exist */
  2802. if ((fp = fopen(fname, "a+")) != NULL) {
  2803. (void) fclose(fp);
  2804. }
  2805. /* Open the given file and temporary file */
  2806. if ((fp = fopen(fname, "r")) == NULL) {
  2807. return 0;
  2808. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  2809. fclose(fp);
  2810. return 0;
  2811. }
  2812. /* Copy the stuff to temporary file */
  2813. while (fgets(line, sizeof(line), fp) != NULL) {
  2814. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  2815. continue;
  2816. }
  2817. u[255]=0;
  2818. d[255]=0;
  2819. if (!strcmp(u, user) && !strcmp(d, domain)) {
  2820. found++;
  2821. if (pass != NULL) {
  2822. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2823. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2824. }
  2825. } else {
  2826. fprintf(fp2, "%s", line);
  2827. }
  2828. }
  2829. /* If new user, just add it */
  2830. if (!found && pass != NULL) {
  2831. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2832. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2833. }
  2834. /* Close files */
  2835. fclose(fp);
  2836. fclose(fp2);
  2837. /* Put the temp file in place of real file */
  2838. IGNORE_UNUSED_RESULT(remove(fname));
  2839. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  2840. return 1;
  2841. }
  2842. static SOCKET conn2(struct mg_context *ctx /* may be null */, const char *host, int port,
  2843. int use_ssl, char *ebuf, size_t ebuf_len)
  2844. {
  2845. struct sockaddr_in sain;
  2846. struct hostent *he;
  2847. SOCKET sock = INVALID_SOCKET;
  2848. if (host == NULL) {
  2849. snprintf(ebuf, ebuf_len, "%s", "NULL host");
  2850. } else if (use_ssl && SSLv23_client_method == NULL) {
  2851. snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
  2852. /* TODO(lsm): use something threadsafe instead of gethostbyname() */
  2853. } else if ((he = gethostbyname(host)) == NULL) {
  2854. snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO));
  2855. } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  2856. snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
  2857. } else {
  2858. set_close_on_exec(sock, fc(ctx));
  2859. memset(&sain, '\0', sizeof(sain));
  2860. sain.sin_family = AF_INET;
  2861. sain.sin_port = htons((uint16_t) port);
  2862. sain.sin_addr = * (struct in_addr *) he->h_addr_list[0];
  2863. if (connect(sock, (struct sockaddr *) &sain, sizeof(sain)) != 0) {
  2864. snprintf(ebuf, ebuf_len, "connect(%s:%d): %s",
  2865. host, port, strerror(ERRNO));
  2866. closesocket(sock);
  2867. sock = INVALID_SOCKET;
  2868. }
  2869. }
  2870. return sock;
  2871. }
  2872. int mg_url_encode(const char *src, char *dst, size_t dst_len)
  2873. {
  2874. static const char *dont_escape = "._-$,;~()";
  2875. static const char *hex = "0123456789abcdef";
  2876. char *pos = dst;
  2877. const char *end = dst + dst_len - 1;
  2878. for (; *src != '\0' && pos < end; src++, pos++) {
  2879. if (isalnum(*(const unsigned char *) src) ||
  2880. strchr(dont_escape, * (const unsigned char *) src) != NULL) {
  2881. *pos = *src;
  2882. } else if (pos + 2 < end) {
  2883. pos[0] = '%';
  2884. pos[1] = hex[(* (const unsigned char *) src) >> 4];
  2885. pos[2] = hex[(* (const unsigned char *) src) & 0xf];
  2886. pos += 2;
  2887. } else {
  2888. return -1;
  2889. }
  2890. }
  2891. *pos = '\0';
  2892. return (*src == '\0') ? (int)(pos - dst) : -1;
  2893. }
  2894. static void print_dir_entry(struct de *de)
  2895. {
  2896. char size[64], mod[64], href[PATH_MAX];
  2897. struct tm *tm;
  2898. if (de->file.is_directory) {
  2899. mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  2900. } else {
  2901. /* We use (signed) cast below because MSVC 6 compiler cannot
  2902. convert unsigned __int64 to double. Sigh. */
  2903. if (de->file.size < 1024) {
  2904. mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size);
  2905. } else if (de->file.size < 0x100000) {
  2906. mg_snprintf(de->conn, size, sizeof(size),
  2907. "%.1fk", (double) de->file.size / 1024.0);
  2908. } else if (de->file.size < 0x40000000) {
  2909. mg_snprintf(de->conn, size, sizeof(size),
  2910. "%.1fM", (double) de->file.size / 1048576);
  2911. } else {
  2912. mg_snprintf(de->conn, size, sizeof(size),
  2913. "%.1fG", (double) de->file.size / 1073741824);
  2914. }
  2915. }
  2916. tm = localtime(&de->file.modification_time);
  2917. if (tm != NULL) {
  2918. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  2919. } else {
  2920. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  2921. mod[sizeof(mod) - 1] = '\0';
  2922. }
  2923. mg_url_encode(de->file_name, href, sizeof(href));
  2924. de->conn->num_bytes_sent += mg_printf(de->conn,
  2925. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2926. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2927. de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",
  2928. de->file_name, de->file.is_directory ? "/" : "", mod, size);
  2929. }
  2930. /* This function is called from send_directory() and used for
  2931. sorting directory entries by size, or name, or modification time.
  2932. On windows, __cdecl specification is needed in case if project is built
  2933. with __stdcall convention. qsort always requires __cdels callback. */
  2934. static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
  2935. {
  2936. const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
  2937. const char *query_string = a->conn->request_info.query_string;
  2938. int cmp_result = 0;
  2939. if (query_string == NULL) {
  2940. query_string = "na";
  2941. }
  2942. if (a->file.is_directory && !b->file.is_directory) {
  2943. return -1; /* Always put directories on top */
  2944. } else if (!a->file.is_directory && b->file.is_directory) {
  2945. return 1; /* Always put directories on top */
  2946. } else if (*query_string == 'n') {
  2947. cmp_result = strcmp(a->file_name, b->file_name);
  2948. } else if (*query_string == 's') {
  2949. cmp_result = a->file.size == b->file.size ? 0 :
  2950. a->file.size > b->file.size ? 1 : -1;
  2951. } else if (*query_string == 'd') {
  2952. cmp_result = a->file.modification_time == b->file.modification_time ? 0 :
  2953. a->file.modification_time > b->file.modification_time ? 1 : -1;
  2954. }
  2955. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  2956. }
  2957. static int must_hide_file(struct mg_connection *conn, const char *path)
  2958. {
  2959. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  2960. const char *pattern = conn->ctx->config[HIDE_FILES];
  2961. return match_prefix(pw_pattern, (int)strlen(pw_pattern), path) > 0 ||
  2962. (pattern != NULL && match_prefix(pattern, (int)strlen(pattern), path) > 0);
  2963. }
  2964. static int scan_directory(struct mg_connection *conn, const char *dir,
  2965. void *data, void (*cb)(struct de *, void *))
  2966. {
  2967. char path[PATH_MAX];
  2968. struct dirent *dp;
  2969. DIR *dirp;
  2970. struct de de;
  2971. if ((dirp = opendir(dir)) == NULL) {
  2972. return 0;
  2973. } else {
  2974. de.conn = conn;
  2975. while ((dp = readdir(dirp)) != NULL) {
  2976. /* Do not show current dir and hidden files */
  2977. if (!strcmp(dp->d_name, ".") ||
  2978. !strcmp(dp->d_name, "..") ||
  2979. must_hide_file(conn, dp->d_name)) {
  2980. continue;
  2981. }
  2982. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2983. /* If we don't memset stat structure to zero, mtime will have
  2984. garbage and strftime() will segfault later on in
  2985. print_dir_entry(). memset is required only if mg_stat()
  2986. fails. For more details, see
  2987. http://code.google.com/p/mongoose/issues/detail?id=79 */
  2988. memset(&de.file, 0, sizeof(de.file));
  2989. if (!mg_stat(conn, path, &de.file)) {
  2990. mg_cry(conn, "%s: mg_stat(%s) failed: %s",
  2991. __func__, path, strerror(ERRNO));
  2992. }
  2993. de.file_name = dp->d_name;
  2994. cb(&de, data);
  2995. }
  2996. (void) closedir(dirp);
  2997. }
  2998. return 1;
  2999. }
  3000. static int remove_directory(struct mg_connection *conn, const char *dir)
  3001. {
  3002. char path[PATH_MAX];
  3003. struct dirent *dp;
  3004. DIR *dirp;
  3005. struct de de;
  3006. if ((dirp = opendir(dir)) == NULL) {
  3007. return 0;
  3008. } else {
  3009. de.conn = conn;
  3010. while ((dp = readdir(dirp)) != NULL) {
  3011. /* Do not show current dir (but show hidden files as they will
  3012. also be removed) */
  3013. if (!strcmp(dp->d_name, ".") ||
  3014. !strcmp(dp->d_name, "..")) {
  3015. continue;
  3016. }
  3017. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  3018. /* If we don't memset stat structure to zero, mtime will have
  3019. garbage and strftime() will segfault later on in
  3020. print_dir_entry(). memset is required only if mg_stat()
  3021. fails. For more details, see
  3022. http://code.google.com/p/mongoose/issues/detail?id=79 */
  3023. memset(&de.file, 0, sizeof(de.file));
  3024. if (!mg_stat(conn, path, &de.file)) {
  3025. mg_cry(conn, "%s: mg_stat(%s) failed: %s",
  3026. __func__, path, strerror(ERRNO));
  3027. }
  3028. if(de.file.modification_time) {
  3029. if(de.file.is_directory) {
  3030. remove_directory(conn, path);
  3031. } else {
  3032. mg_remove(path);
  3033. }
  3034. }
  3035. }
  3036. (void) closedir(dirp);
  3037. IGNORE_UNUSED_RESULT(rmdir(dir));
  3038. }
  3039. return 1;
  3040. }
  3041. struct dir_scan_data {
  3042. struct de *entries;
  3043. int num_entries;
  3044. int arr_size;
  3045. };
  3046. /* Behaves like realloc(), but frees original pointer on failure */
  3047. static void *realloc2(void *ptr, size_t size)
  3048. {
  3049. void *new_ptr = mg_realloc(ptr, size);
  3050. if (new_ptr == NULL) {
  3051. mg_free(ptr);
  3052. }
  3053. return new_ptr;
  3054. }
  3055. static void dir_scan_callback(struct de *de, void *data)
  3056. {
  3057. struct dir_scan_data *dsd = (struct dir_scan_data *) data;
  3058. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  3059. dsd->arr_size *= 2;
  3060. dsd->entries = (struct de *) realloc2(dsd->entries, dsd->arr_size *
  3061. sizeof(dsd->entries[0]));
  3062. }
  3063. if (dsd->entries == NULL) {
  3064. /* TODO(lsm): propagate an error to the caller */
  3065. dsd->num_entries = 0;
  3066. } else {
  3067. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  3068. dsd->entries[dsd->num_entries].file = de->file;
  3069. dsd->entries[dsd->num_entries].conn = de->conn;
  3070. dsd->num_entries++;
  3071. }
  3072. }
  3073. static void handle_directory_request(struct mg_connection *conn,
  3074. const char *dir)
  3075. {
  3076. int i, sort_direction;
  3077. struct dir_scan_data data = { NULL, 0, 128 };
  3078. char date[64];
  3079. time_t curtime = time(NULL);
  3080. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  3081. send_http_error(conn, 500, "Cannot open directory",
  3082. "Error: opendir(%s): %s", dir, strerror(ERRNO));
  3083. return;
  3084. }
  3085. gmt_time_string(date, sizeof(date), &curtime);
  3086. sort_direction = conn->request_info.query_string != NULL &&
  3087. conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
  3088. conn->must_close = 1;
  3089. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  3090. "Date: %s\r\n"
  3091. "Connection: close\r\n"
  3092. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  3093. date);
  3094. conn->num_bytes_sent += mg_printf(conn,
  3095. "<html><head><title>Index of %s</title>"
  3096. "<style>th {text-align: left;}</style></head>"
  3097. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  3098. "<tr><th><a href=\"?n%c\">Name</a></th>"
  3099. "<th><a href=\"?d%c\">Modified</a></th>"
  3100. "<th><a href=\"?s%c\">Size</a></th></tr>"
  3101. "<tr><td colspan=\"3\"><hr></td></tr>",
  3102. conn->request_info.uri, conn->request_info.uri,
  3103. sort_direction, sort_direction, sort_direction);
  3104. /* Print first entry - link to a parent directory */
  3105. conn->num_bytes_sent += mg_printf(conn,
  3106. "<tr><td><a href=\"%s%s\">%s</a></td>"
  3107. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  3108. conn->request_info.uri, "..", "Parent directory", "-", "-");
  3109. /* Sort and print directory entries */
  3110. if (data.entries != NULL) {
  3111. qsort(data.entries, (size_t) data.num_entries,
  3112. sizeof(data.entries[0]), compare_dir_entries);
  3113. for (i = 0; i < data.num_entries; i++) {
  3114. print_dir_entry(&data.entries[i]);
  3115. mg_free(data.entries[i].file_name);
  3116. }
  3117. mg_free(data.entries);
  3118. }
  3119. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  3120. conn->status_code = 200;
  3121. }
  3122. /* Send len bytes from the opened file to the client. */
  3123. static void send_file_data(struct mg_connection *conn, struct file *filep,
  3124. int64_t offset, int64_t len)
  3125. {
  3126. char buf[MG_BUF_LEN];
  3127. int to_read, num_read, num_written;
  3128. /* Sanity check the offset */
  3129. offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset;
  3130. if (len > 0 && filep->membuf != NULL && filep->size > 0) {
  3131. if (len > filep->size - offset) {
  3132. len = filep->size - offset;
  3133. }
  3134. mg_write(conn, filep->membuf + offset, (size_t) len);
  3135. } else if (len > 0 && filep->fp != NULL) {
  3136. if (offset > 0 && fseeko(filep->fp, offset, SEEK_SET) != 0) {
  3137. mg_cry(conn, "%s: fseeko() failed: %s",
  3138. __func__, strerror(ERRNO));
  3139. }
  3140. while (len > 0) {
  3141. /* Calculate how much to read from the file in the buffer */
  3142. to_read = sizeof(buf);
  3143. if ((int64_t) to_read > len) {
  3144. to_read = (int) len;
  3145. }
  3146. /* Read from file, exit the loop on error */
  3147. if ((num_read = (int) fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) {
  3148. break;
  3149. }
  3150. /* Send read bytes to the client, exit the loop on error */
  3151. if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) {
  3152. break;
  3153. }
  3154. /* Both read and were successful, adjust counters */
  3155. conn->num_bytes_sent += num_written;
  3156. len -= num_written;
  3157. }
  3158. }
  3159. }
  3160. static int parse_range_header(const char *header, int64_t *a, int64_t *b)
  3161. {
  3162. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  3163. }
  3164. static void construct_etag(char *buf, size_t buf_len,
  3165. const struct file *filep)
  3166. {
  3167. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  3168. (unsigned long) filep->modification_time, filep->size);
  3169. }
  3170. static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
  3171. {
  3172. if (filep != NULL && filep->fp != NULL) {
  3173. #ifdef _WIN32
  3174. (void) conn; /* Unused. */
  3175. #else
  3176. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  3177. mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3178. __func__, strerror(ERRNO));
  3179. }
  3180. #endif
  3181. }
  3182. }
  3183. static void handle_static_file_request(struct mg_connection *conn, const char *path, struct file *filep)
  3184. {
  3185. char date[64], lm[64], etag[64], range[64];
  3186. const char *msg = "OK", *hdr;
  3187. time_t curtime = time(NULL);
  3188. int64_t cl, r1, r2;
  3189. struct vec mime_vec;
  3190. int n;
  3191. char gz_path[PATH_MAX];
  3192. const char *encoding = "";
  3193. const char *cors1, *cors2, *cors3;
  3194. get_mime_type(conn->ctx, path, &mime_vec);
  3195. cl = filep->size;
  3196. conn->status_code = 200;
  3197. range[0] = '\0';
  3198. /* if this file is in fact a pre-gzipped file, rewrite its filename
  3199. it's important to rewrite the filename after resolving
  3200. the mime type from it, to preserve the actual file's type */
  3201. if (filep->gzipped) {
  3202. snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
  3203. path = gz_path;
  3204. encoding = "Content-Encoding: gzip\r\n";
  3205. }
  3206. if (!mg_fopen(conn, path, "rb", filep)) {
  3207. send_http_error(conn, 500, http_500_error,
  3208. "fopen(%s): %s", path, strerror(ERRNO));
  3209. return;
  3210. }
  3211. fclose_on_exec(filep, conn);
  3212. /* If Range: header specified, act accordingly */
  3213. r1 = r2 = 0;
  3214. hdr = mg_get_header(conn, "Range");
  3215. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
  3216. r1 >= 0 && r2 >= 0) {
  3217. /* actually, range requests don't play well with a pre-gzipped
  3218. file (since the range is specified in the uncompressed space) */
  3219. if (filep->gzipped) {
  3220. send_http_error(conn, 501, "Not Implemented", "range requests in gzipped files are not supported");
  3221. mg_fclose(filep);
  3222. return;
  3223. }
  3224. conn->status_code = 206;
  3225. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;
  3226. mg_snprintf(conn, range, sizeof(range),
  3227. "Content-Range: bytes "
  3228. "%" INT64_FMT "-%"
  3229. INT64_FMT "/%" INT64_FMT "\r\n",
  3230. r1, r1 + cl - 1, filep->size);
  3231. msg = "Partial Content";
  3232. }
  3233. hdr = mg_get_header(conn, "Origin");
  3234. if (hdr) {
  3235. /* Cross-origin resource sharing (CORS), see http://www.html5rocks.com/en/tutorials/cors/,
  3236. http://www.html5rocks.com/static/images/cors_server_flowchart.png - preflight is not supported for files. */
  3237. cors1 = "Access-Control-Allow-Origin: ";
  3238. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3239. cors3 = "\r\n";
  3240. } else {
  3241. cors1 = cors2 = cors3 = "";
  3242. }
  3243. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  3244. http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  3245. gmt_time_string(date, sizeof(date), &curtime);
  3246. gmt_time_string(lm, sizeof(lm), &filep->modification_time);
  3247. construct_etag(etag, sizeof(etag), filep);
  3248. (void) mg_printf(conn,
  3249. "HTTP/1.1 %d %s\r\n"
  3250. "%s%s%s"
  3251. "Date: %s\r\n"
  3252. "Last-Modified: %s\r\n"
  3253. "Etag: %s\r\n"
  3254. "Content-Type: %.*s\r\n"
  3255. "Content-Length: %" INT64_FMT "\r\n"
  3256. "Connection: %s\r\n"
  3257. "Accept-Ranges: bytes\r\n"
  3258. "%s%s\r\n",
  3259. conn->status_code, msg,
  3260. cors1, cors2, cors3,
  3261. date, lm, etag, (int) mime_vec.len,
  3262. mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding);
  3263. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  3264. send_file_data(conn, filep, r1, cl);
  3265. }
  3266. mg_fclose(filep);
  3267. }
  3268. void mg_send_file(struct mg_connection *conn, const char *path)
  3269. {
  3270. struct file file = STRUCT_FILE_INITIALIZER;
  3271. if (mg_stat(conn, path, &file)) {
  3272. handle_static_file_request(conn, path, &file);
  3273. } else {
  3274. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  3275. }
  3276. }
  3277. /* Parse HTTP headers from the given buffer, advance buffer to the point
  3278. where parsing stopped. */
  3279. static void parse_http_headers(char **buf, struct mg_request_info *ri)
  3280. {
  3281. int i;
  3282. for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
  3283. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  3284. ri->http_headers[i].value = skip(buf, "\r\n");
  3285. if (ri->http_headers[i].name[0] == '\0')
  3286. break;
  3287. ri->num_headers = i + 1;
  3288. }
  3289. }
  3290. static int is_valid_http_method(const char *method)
  3291. {
  3292. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  3293. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  3294. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  3295. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND")
  3296. || !strcmp(method, "MKCOL")
  3297. ;
  3298. }
  3299. /* Parse HTTP request, fill in mg_request_info structure.
  3300. This function modifies the buffer by NUL-terminating
  3301. HTTP request components, header names and header values. */
  3302. static int parse_http_message(char *buf, int len, struct mg_request_info *ri)
  3303. {
  3304. int is_request, request_length = get_request_len(buf, len);
  3305. if (request_length > 0) {
  3306. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port */
  3307. ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
  3308. ri->num_headers = 0;
  3309. buf[request_length - 1] = '\0';
  3310. /* RFC says that all initial whitespaces should be ingored */
  3311. while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
  3312. buf++;
  3313. }
  3314. ri->request_method = skip(&buf, " ");
  3315. ri->uri = skip(&buf, " ");
  3316. ri->http_version = skip(&buf, "\r\n");
  3317. /* HTTP message could be either HTTP request or HTTP response, e.g.
  3318. "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  3319. is_request = is_valid_http_method(ri->request_method);
  3320. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  3321. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  3322. request_length = -1;
  3323. } else {
  3324. if (is_request) {
  3325. ri->http_version += 5;
  3326. }
  3327. parse_http_headers(&buf, ri);
  3328. }
  3329. }
  3330. return request_length;
  3331. }
  3332. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  3333. or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  3334. buffer (which marks the end of HTTP request). Buffer buf may already
  3335. have some data. The length of the data is stored in nread.
  3336. Upon every read operation, increase nread by the number of bytes read. */
  3337. static int read_request(FILE *fp, struct mg_connection *conn,
  3338. char *buf, int bufsiz, int *nread)
  3339. {
  3340. int request_len, n = 0;
  3341. request_len = get_request_len(buf, *nread);
  3342. while (conn->ctx->stop_flag == 0 &&
  3343. *nread < bufsiz && request_len == 0 &&
  3344. (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {
  3345. *nread += n;
  3346. assert(*nread <= bufsiz);
  3347. request_len = get_request_len(buf, *nread);
  3348. }
  3349. return request_len <= 0 && n <= 0 ? -1 : request_len;
  3350. }
  3351. /* For given directory path, substitute it to valid index file.
  3352. Return 1 if index file has been found, 0 if not found.
  3353. If the file is found, it's stats is returned in stp. */
  3354. static int substitute_index_file(struct mg_connection *conn, char *path,
  3355. size_t path_len, struct file *filep)
  3356. {
  3357. const char *list = conn->ctx->config[INDEX_FILES];
  3358. struct file file = STRUCT_FILE_INITIALIZER;
  3359. struct vec filename_vec;
  3360. size_t n = strlen(path);
  3361. int found = 0;
  3362. /* The 'path' given to us points to the directory. Remove all trailing
  3363. directory separator characters from the end of the path, and
  3364. then append single directory separator character. */
  3365. while (n > 0 && path[n - 1] == '/') {
  3366. n--;
  3367. }
  3368. path[n] = '/';
  3369. /* Traverse index files list. For each entry, append it to the given
  3370. path and see if the file exists. If it exists, break the loop */
  3371. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  3372. /* Ignore too long entries that may overflow path buffer */
  3373. if (filename_vec.len > path_len - (n + 2))
  3374. continue;
  3375. /* Prepare full path to the index file */
  3376. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  3377. /* Does it exist? */
  3378. if (mg_stat(conn, path, &file)) {
  3379. /* Yes it does, break the loop */
  3380. *filep = file;
  3381. found = 1;
  3382. break;
  3383. }
  3384. }
  3385. /* If no index file exists, restore directory path */
  3386. if (!found) {
  3387. path[n] = '\0';
  3388. }
  3389. return found;
  3390. }
  3391. /* Return True if we should reply 304 Not Modified. */
  3392. static int is_not_modified(const struct mg_connection *conn,
  3393. const struct file *filep)
  3394. {
  3395. char etag[64];
  3396. const char *ims = mg_get_header(conn, "If-Modified-Since");
  3397. const char *inm = mg_get_header(conn, "If-None-Match");
  3398. construct_etag(etag, sizeof(etag), filep);
  3399. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  3400. (ims != NULL && filep->modification_time <= parse_date_string(ims));
  3401. }
  3402. static int forward_body_data(struct mg_connection *conn, FILE *fp,
  3403. SOCKET sock, SSL *ssl)
  3404. {
  3405. const char *expect, *body;
  3406. char buf[MG_BUF_LEN];
  3407. int to_read, nread, buffered_len, success = 0;
  3408. expect = mg_get_header(conn, "Expect");
  3409. assert(fp != NULL);
  3410. if (conn->content_len == -1) {
  3411. send_http_error(conn, 411, "Length Required", "%s", "");
  3412. } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
  3413. send_http_error(conn, 417, "Expectation Failed", "%s", "");
  3414. } else {
  3415. if (expect != NULL) {
  3416. (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  3417. }
  3418. body = conn->buf + conn->request_len + conn->consumed_content;
  3419. buffered_len = (int)(&conn->buf[conn->data_len] - body);
  3420. assert(buffered_len >= 0);
  3421. assert(conn->consumed_content == 0);
  3422. if (buffered_len > 0) {
  3423. if ((int64_t) buffered_len > conn->content_len) {
  3424. buffered_len = (int) conn->content_len;
  3425. }
  3426. push(fp, sock, ssl, body, (int64_t) buffered_len);
  3427. conn->consumed_content += buffered_len;
  3428. }
  3429. nread = 0;
  3430. while (conn->consumed_content < conn->content_len) {
  3431. to_read = sizeof(buf);
  3432. if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
  3433. to_read = (int) (conn->content_len - conn->consumed_content);
  3434. }
  3435. nread = pull(NULL, conn, buf, to_read);
  3436. if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
  3437. break;
  3438. }
  3439. conn->consumed_content += nread;
  3440. }
  3441. if (conn->consumed_content == conn->content_len) {
  3442. success = nread >= 0;
  3443. }
  3444. /* Each error code path in this function must send an error */
  3445. if (!success) {
  3446. send_http_error(conn, 577, http_500_error, "%s", "");
  3447. }
  3448. }
  3449. return success;
  3450. }
  3451. #if !defined(NO_CGI)
  3452. /* This structure helps to create an environment for the spawned CGI program.
  3453. Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  3454. last element must be NULL.
  3455. However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  3456. strings must reside in a contiguous buffer. The end of the buffer is
  3457. marked by two '\0' characters.
  3458. We satisfy both worlds: we create an envp array (which is vars), all
  3459. entries are actually pointers inside buf. */
  3460. struct cgi_env_block {
  3461. struct mg_connection *conn;
  3462. char buf[CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  3463. int len; /* Space taken */
  3464. char *vars[MAX_CGI_ENVIR_VARS]; /* char **envp */
  3465. int nvars; /* Number of variables */
  3466. };
  3467. static char *addenv(struct cgi_env_block *block,
  3468. PRINTF_FORMAT_STRING(const char *fmt), ...)
  3469. PRINTF_ARGS(2, 3);
  3470. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  3471. pointer into the vars array. */
  3472. static char *addenv(struct cgi_env_block *block, const char *fmt, ...)
  3473. {
  3474. int n, space;
  3475. char *added;
  3476. va_list ap;
  3477. /* Calculate how much space is left in the buffer */
  3478. space = sizeof(block->buf) - block->len - 2;
  3479. assert(space >= 0);
  3480. /* Make a pointer to the free space int the buffer */
  3481. added = block->buf + block->len;
  3482. /* Copy VARIABLE=VALUE\0 string into the free space */
  3483. va_start(ap, fmt);
  3484. n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
  3485. va_end(ap);
  3486. /* Make sure we do not overflow buffer and the envp array */
  3487. if (n > 0 && n + 1 < space &&
  3488. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  3489. /* Append a pointer to the added string into the envp array */
  3490. block->vars[block->nvars++] = added;
  3491. /* Bump up used length counter. Include \0 terminator */
  3492. block->len += n + 1;
  3493. } else {
  3494. mg_cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
  3495. }
  3496. return added;
  3497. }
  3498. static void prepare_cgi_environment(struct mg_connection *conn,
  3499. const char *prog,
  3500. struct cgi_env_block *blk)
  3501. {
  3502. const char *s, *slash;
  3503. struct vec var_vec;
  3504. char *p, src_addr[IP_ADDR_STR_LEN];
  3505. int i;
  3506. blk->len = blk->nvars = 0;
  3507. blk->conn = conn;
  3508. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3509. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  3510. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  3511. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  3512. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  3513. /* Prepare the environment block */
  3514. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  3515. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  3516. addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  3517. /* TODO(lsm): fix this for IPv6 case */
  3518. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  3519. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  3520. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  3521. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  3522. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  3523. /* SCRIPT_NAME */
  3524. assert(conn->request_info.uri[0] == '/');
  3525. slash = strrchr(conn->request_info.uri, '/');
  3526. if ((s = strrchr(prog, '/')) == NULL)
  3527. s = prog;
  3528. addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
  3529. conn->request_info.uri, s);
  3530. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  3531. addenv(blk, "PATH_TRANSLATED=%s", prog);
  3532. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  3533. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  3534. addenv(blk, "CONTENT_TYPE=%s", s);
  3535. if (conn->request_info.query_string != NULL)
  3536. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  3537. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  3538. addenv(blk, "CONTENT_LENGTH=%s", s);
  3539. if ((s = getenv("PATH")) != NULL)
  3540. addenv(blk, "PATH=%s", s);
  3541. if (conn->path_info != NULL) {
  3542. addenv(blk, "PATH_INFO=%s", conn->path_info);
  3543. }
  3544. if (conn->status_code > 0) {
  3545. /* CGI error handler should show the status code */
  3546. addenv(blk, "STATUS=%d", conn->status_code);
  3547. }
  3548. #if defined(_WIN32)
  3549. if ((s = getenv("COMSPEC")) != NULL) {
  3550. addenv(blk, "COMSPEC=%s", s);
  3551. }
  3552. if ((s = getenv("SYSTEMROOT")) != NULL) {
  3553. addenv(blk, "SYSTEMROOT=%s", s);
  3554. }
  3555. if ((s = getenv("SystemDrive")) != NULL) {
  3556. addenv(blk, "SystemDrive=%s", s);
  3557. }
  3558. if ((s = getenv("ProgramFiles")) != NULL) {
  3559. addenv(blk, "ProgramFiles=%s", s);
  3560. }
  3561. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  3562. addenv(blk, "ProgramFiles(x86)=%s", s);
  3563. }
  3564. #else
  3565. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  3566. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  3567. #endif /* _WIN32 */
  3568. if ((s = getenv("PERLLIB")) != NULL)
  3569. addenv(blk, "PERLLIB=%s", s);
  3570. if (conn->request_info.remote_user != NULL) {
  3571. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  3572. addenv(blk, "%s", "AUTH_TYPE=Digest");
  3573. }
  3574. /* Add all headers as HTTP_* variables */
  3575. for (i = 0; i < conn->request_info.num_headers; i++) {
  3576. p = addenv(blk, "HTTP_%s=%s",
  3577. conn->request_info.http_headers[i].name,
  3578. conn->request_info.http_headers[i].value);
  3579. /* Convert variable name into uppercase, and change - to _ */
  3580. for (; *p != '=' && *p != '\0'; p++) {
  3581. if (*p == '-')
  3582. *p = '_';
  3583. *p = (char) toupper(* (unsigned char *) p);
  3584. }
  3585. }
  3586. /* Add user-specified variables */
  3587. s = conn->ctx->config[CGI_ENVIRONMENT];
  3588. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  3589. addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
  3590. }
  3591. blk->vars[blk->nvars++] = NULL;
  3592. blk->buf[blk->len++] = '\0';
  3593. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  3594. assert(blk->len > 0);
  3595. assert(blk->len < (int) sizeof(blk->buf));
  3596. }
  3597. static void handle_cgi_request(struct mg_connection *conn, const char *prog)
  3598. {
  3599. char *buf;
  3600. size_t buflen;
  3601. int headers_len, data_len, i, fdin[2] = { 0, 0 }, fdout[2] = { 0, 0 };
  3602. const char *status, *status_text, *connection_state;
  3603. char *pbuf, dir[PATH_MAX], *p;
  3604. struct mg_request_info ri;
  3605. struct cgi_env_block blk;
  3606. FILE *in = NULL, *out = NULL;
  3607. struct file fout = STRUCT_FILE_INITIALIZER;
  3608. pid_t pid = (pid_t) -1;
  3609. buf = NULL;
  3610. buflen = 16384;
  3611. prepare_cgi_environment(conn, prog, &blk);
  3612. /* CGI must be executed in its own directory. 'dir' must point to the
  3613. directory containing executable program, 'p' must point to the
  3614. executable program name relative to 'dir'. */
  3615. (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  3616. if ((p = strrchr(dir, '/')) != NULL) {
  3617. *p++ = '\0';
  3618. } else {
  3619. dir[0] = '.', dir[1] = '\0';
  3620. p = (char *) prog;
  3621. }
  3622. if (pipe(fdin) != 0 || pipe(fdout) != 0) {
  3623. send_http_error(conn, 500, http_500_error,
  3624. "Cannot create CGI pipe: %s", strerror(ERRNO));
  3625. goto done;
  3626. }
  3627. pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
  3628. if (pid == (pid_t) -1) {
  3629. send_http_error(conn, 500, http_500_error,
  3630. "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
  3631. goto done;
  3632. }
  3633. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  3634. set_close_on_exec(fdin[0], conn);
  3635. set_close_on_exec(fdin[1], conn);
  3636. set_close_on_exec(fdout[0], conn);
  3637. set_close_on_exec(fdout[1], conn);
  3638. /* Parent closes only one side of the pipes.
  3639. If we don't mark them as closed, close() attempt before
  3640. return from this function throws an exception on Windows.
  3641. Windows does not like when closed descriptor is closed again. */
  3642. (void) close(fdin[0]);
  3643. (void) close(fdout[1]);
  3644. fdin[0] = fdout[1] = -1;
  3645. if ((in = fdopen(fdin[1], "wb")) == NULL ||
  3646. (out = fdopen(fdout[0], "rb")) == NULL) {
  3647. send_http_error(conn, 500, http_500_error,
  3648. "fopen: %s", strerror(ERRNO));
  3649. goto done;
  3650. }
  3651. setbuf(in, NULL);
  3652. setbuf(out, NULL);
  3653. fout.fp = out;
  3654. /* Send POST data to the CGI process if needed */
  3655. if (!strcmp(conn->request_info.request_method, "POST") &&
  3656. !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  3657. goto done;
  3658. }
  3659. /* Close so child gets an EOF. */
  3660. fclose(in);
  3661. in = NULL;
  3662. fdin[1] = -1;
  3663. /* Now read CGI reply into a buffer. We need to set correct
  3664. status code, thus we need to see all HTTP headers first.
  3665. Do not send anything back to client, until we buffer in all
  3666. HTTP headers. */
  3667. data_len = 0;
  3668. buf = mg_malloc(buflen);
  3669. if (buf == NULL) {
  3670. send_http_error(conn, 500, http_500_error,
  3671. "Not enough memory for buffer (%u bytes)",
  3672. (unsigned int) buflen);
  3673. goto done;
  3674. }
  3675. headers_len = read_request(out, conn, buf, (int) buflen, &data_len);
  3676. if (headers_len <= 0) {
  3677. send_http_error(conn, 500, http_500_error,
  3678. "CGI program sent malformed or too big (>%u bytes) "
  3679. "HTTP headers: [%.*s]",
  3680. (unsigned) buflen, data_len, buf);
  3681. goto done;
  3682. }
  3683. pbuf = buf;
  3684. buf[headers_len - 1] = '\0';
  3685. parse_http_headers(&pbuf, &ri);
  3686. /* Make up and send the status line */
  3687. status_text = "OK";
  3688. if ((status = get_header(&ri, "Status")) != NULL) {
  3689. conn->status_code = atoi(status);
  3690. status_text = status;
  3691. while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
  3692. status_text++;
  3693. }
  3694. } else if (get_header(&ri, "Location") != NULL) {
  3695. conn->status_code = 302;
  3696. } else {
  3697. conn->status_code = 200;
  3698. }
  3699. connection_state = get_header(&ri, "Connection");
  3700. if (connection_state == NULL ||
  3701. mg_strcasecmp(connection_state, "keep-alive")) {
  3702. conn->must_close = 1;
  3703. }
  3704. (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,
  3705. status_text);
  3706. /* Send headers */
  3707. for (i = 0; i < ri.num_headers; i++) {
  3708. mg_printf(conn, "%s: %s\r\n",
  3709. ri.http_headers[i].name, ri.http_headers[i].value);
  3710. }
  3711. mg_write(conn, "\r\n", 2);
  3712. /* Send chunk of data that may have been read after the headers */
  3713. conn->num_bytes_sent += mg_write(conn, buf + headers_len,
  3714. (size_t)(data_len - headers_len));
  3715. /* Read the rest of CGI output and send to the client */
  3716. send_file_data(conn, &fout, 0, INT64_MAX);
  3717. done:
  3718. if (pid != (pid_t) -1) {
  3719. kill(pid, SIGKILL);
  3720. #if !defined(_WIN32)
  3721. {
  3722. int st;
  3723. while (waitpid(pid, &st, 0) != -1); /* clean zombies */
  3724. }
  3725. #endif
  3726. }
  3727. if (fdin[0] != -1) {
  3728. close(fdin[0]);
  3729. }
  3730. if (fdout[1] != -1) {
  3731. close(fdout[1]);
  3732. }
  3733. if (in != NULL) {
  3734. fclose(in);
  3735. } else if (fdin[1] != -1) {
  3736. close(fdin[1]);
  3737. }
  3738. if (out != NULL) {
  3739. fclose(out);
  3740. } else if (fdout[0] != -1) {
  3741. close(fdout[0]);
  3742. }
  3743. if (buf != NULL) {
  3744. mg_free(buf);
  3745. }
  3746. }
  3747. #endif /* !NO_CGI */
  3748. /* For a given PUT path, create all intermediate subdirectories
  3749. for given path. Return 0 if the path itself is a directory,
  3750. or -1 on error, 1 if OK. */
  3751. static int put_dir(struct mg_connection *conn, const char *path)
  3752. {
  3753. char buf[PATH_MAX];
  3754. const char *s, *p;
  3755. struct file file = STRUCT_FILE_INITIALIZER;
  3756. int len, res = 1;
  3757. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  3758. len = (int)(p - path);
  3759. if (len >= (int) sizeof(buf)) {
  3760. res = -1;
  3761. break;
  3762. }
  3763. memcpy(buf, path, len);
  3764. buf[len] = '\0';
  3765. /* Try to create intermediate directory */
  3766. DEBUG_TRACE("mkdir(%s)", buf);
  3767. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  3768. res = -1;
  3769. break;
  3770. }
  3771. /* Is path itself a directory? */
  3772. if (p[1] == '\0') {
  3773. res = 0;
  3774. }
  3775. }
  3776. return res;
  3777. }
  3778. static void mkcol(struct mg_connection *conn, const char *path)
  3779. {
  3780. int rc, body_len;
  3781. struct de de;
  3782. char date[64];
  3783. time_t curtime = time(NULL);
  3784. memset(&de.file, 0, sizeof(de.file));
  3785. if (!mg_stat(conn, path, &de.file)) {
  3786. mg_cry(conn, "%s: mg_stat(%s) failed: %s",
  3787. __func__, path, strerror(ERRNO));
  3788. }
  3789. if(de.file.modification_time) {
  3790. send_http_error(conn, 405, "Method Not Allowed",
  3791. "mkcol(%s): %s", path, strerror(ERRNO));
  3792. return;
  3793. }
  3794. body_len = conn->data_len - conn->request_len;
  3795. if(body_len > 0) {
  3796. send_http_error(conn, 415, "Unsupported media type",
  3797. "mkcol(%s): %s", path, strerror(ERRNO));
  3798. return;
  3799. }
  3800. rc = mg_mkdir(path, 0755);
  3801. if (rc == 0) {
  3802. conn->status_code = 201;
  3803. gmt_time_string(date, sizeof(date), &curtime);
  3804. mg_printf(conn, "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: 0\r\nConnection: %s\r\n\r\n",
  3805. conn->status_code, date, suggest_connection_header(conn));
  3806. } else if (rc == -1) {
  3807. if(errno == EEXIST)
  3808. send_http_error(conn, 405, "Method Not Allowed",
  3809. "mkcol(%s): %s", path, strerror(ERRNO));
  3810. else if(errno == EACCES)
  3811. send_http_error(conn, 403, "Forbidden",
  3812. "mkcol(%s): %s", path, strerror(ERRNO));
  3813. else if(errno == ENOENT)
  3814. send_http_error(conn, 409, "Conflict",
  3815. "mkcol(%s): %s", path, strerror(ERRNO));
  3816. else
  3817. send_http_error(conn, 500, http_500_error,
  3818. "fopen(%s): %s", path, strerror(ERRNO));
  3819. }
  3820. }
  3821. static void put_file(struct mg_connection *conn, const char *path)
  3822. {
  3823. struct file file = STRUCT_FILE_INITIALIZER;
  3824. const char *range;
  3825. int64_t r1, r2;
  3826. int rc;
  3827. char date[64];
  3828. time_t curtime = time(NULL);
  3829. conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;
  3830. if ((rc = put_dir(conn, path)) == 0) {
  3831. gmt_time_string(date, sizeof(date), &curtime);
  3832. mg_printf(conn, "HTTP/1.1 %d OK\r\nDate: %s\r\nContent-Length: 0\r\nConnection: %s\r\n\r\n",
  3833. conn->status_code, date, suggest_connection_header(conn));
  3834. } else if (rc == -1) {
  3835. send_http_error(conn, 500, http_500_error,
  3836. "put_dir(%s): %s", path, strerror(ERRNO));
  3837. } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  3838. mg_fclose(&file);
  3839. send_http_error(conn, 500, http_500_error,
  3840. "fopen(%s): %s", path, strerror(ERRNO));
  3841. } else {
  3842. fclose_on_exec(&file, conn);
  3843. range = mg_get_header(conn, "Content-Range");
  3844. r1 = r2 = 0;
  3845. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  3846. conn->status_code = 206;
  3847. fseeko(file.fp, r1, SEEK_SET);
  3848. }
  3849. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  3850. conn->status_code = 500;
  3851. }
  3852. gmt_time_string(date, sizeof(date), &curtime);
  3853. mg_printf(conn, "HTTP/1.1 %d OK\r\nDate: %s\r\nContent-Length: 0\r\nConnection: %s\r\n\r\n",
  3854. conn->status_code, date, suggest_connection_header(conn));
  3855. mg_fclose(&file);
  3856. }
  3857. }
  3858. static void send_ssi_file(struct mg_connection *, const char *,
  3859. struct file *, int);
  3860. static void do_ssi_include(struct mg_connection *conn, const char *ssi,
  3861. char *tag, int include_level)
  3862. {
  3863. char file_name[MG_BUF_LEN], path[512], *p;
  3864. struct file file = STRUCT_FILE_INITIALIZER;
  3865. size_t len;
  3866. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  3867. of size MG_BUF_LEN to get the tag. So strlen(tag) is
  3868. always < MG_BUF_LEN. */
  3869. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  3870. /* File name is relative to the webserver root */
  3871. file_name[511]=0;
  3872. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  3873. conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
  3874. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  3875. /* File name is relative to the webserver working directory
  3876. or it is absolute system path */
  3877. file_name[511]=0;
  3878. (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  3879. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1 ||
  3880. sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  3881. /* File name is relative to the currect document */
  3882. file_name[511]=0;
  3883. (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  3884. if ((p = strrchr(path, '/')) != NULL) {
  3885. p[1] = '\0';
  3886. }
  3887. len = strlen(path);
  3888. (void) mg_snprintf(conn, path + len, sizeof(path) - len, "%s", file_name);
  3889. } else {
  3890. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  3891. return;
  3892. }
  3893. if (!mg_fopen(conn, path, "rb", &file)) {
  3894. mg_cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  3895. tag, path, strerror(ERRNO));
  3896. } else {
  3897. fclose_on_exec(&file, conn);
  3898. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3899. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
  3900. send_ssi_file(conn, path, &file, include_level + 1);
  3901. } else {
  3902. send_file_data(conn, &file, 0, INT64_MAX);
  3903. }
  3904. mg_fclose(&file);
  3905. }
  3906. }
  3907. #if !defined(NO_POPEN)
  3908. static void do_ssi_exec(struct mg_connection *conn, char *tag)
  3909. {
  3910. char cmd[1024] = "";
  3911. struct file file = STRUCT_FILE_INITIALIZER;
  3912. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  3913. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  3914. } else {
  3915. cmd[1023]=0;
  3916. if ((file.fp = popen(cmd, "r")) == NULL) {
  3917. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  3918. } else {
  3919. send_file_data(conn, &file, 0, INT64_MAX);
  3920. pclose(file.fp);
  3921. }
  3922. }
  3923. }
  3924. #endif /* !NO_POPEN */
  3925. static int mg_fgetc(struct file *filep, int offset)
  3926. {
  3927. if (filep->membuf != NULL && offset >=0 && offset < filep->size) {
  3928. return ((unsigned char *) filep->membuf)[offset];
  3929. } else if (filep->fp != NULL) {
  3930. return fgetc(filep->fp);
  3931. } else {
  3932. return EOF;
  3933. }
  3934. }
  3935. static void send_ssi_file(struct mg_connection *conn, const char *path,
  3936. struct file *filep, int include_level)
  3937. {
  3938. char buf[MG_BUF_LEN];
  3939. int ch, offset, len, in_ssi_tag;
  3940. if (include_level > 10) {
  3941. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  3942. return;
  3943. }
  3944. in_ssi_tag = len = offset = 0;
  3945. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  3946. if (in_ssi_tag && ch == '>') {
  3947. in_ssi_tag = 0;
  3948. buf[len++] = (char) ch;
  3949. buf[len] = '\0';
  3950. assert(len <= (int) sizeof(buf));
  3951. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  3952. /* Not an SSI tag, pass it */
  3953. (void) mg_write(conn, buf, (size_t) len);
  3954. } else {
  3955. if (!memcmp(buf + 5, "include", 7)) {
  3956. do_ssi_include(conn, path, buf + 12, include_level);
  3957. #if !defined(NO_POPEN)
  3958. } else if (!memcmp(buf + 5, "exec", 4)) {
  3959. do_ssi_exec(conn, buf + 9);
  3960. #endif /* !NO_POPEN */
  3961. } else {
  3962. mg_cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
  3963. }
  3964. }
  3965. len = 0;
  3966. } else if (in_ssi_tag) {
  3967. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  3968. /* Not an SSI tag */
  3969. in_ssi_tag = 0;
  3970. } else if (len == (int) sizeof(buf) - 2) {
  3971. mg_cry(conn, "%s: SSI tag is too large", path);
  3972. len = 0;
  3973. }
  3974. buf[len++] = ch & 0xff;
  3975. } else if (ch == '<') {
  3976. in_ssi_tag = 1;
  3977. if (len > 0) {
  3978. mg_write(conn, buf, (size_t) len);
  3979. }
  3980. len = 0;
  3981. buf[len++] = ch & 0xff;
  3982. } else {
  3983. buf[len++] = ch & 0xff;
  3984. if (len == (int) sizeof(buf)) {
  3985. mg_write(conn, buf, (size_t) len);
  3986. len = 0;
  3987. }
  3988. }
  3989. }
  3990. /* Send the rest of buffered data */
  3991. if (len > 0) {
  3992. mg_write(conn, buf, (size_t) len);
  3993. }
  3994. }
  3995. static void handle_ssi_file_request(struct mg_connection *conn,
  3996. const char *path)
  3997. {
  3998. struct file file = STRUCT_FILE_INITIALIZER;
  3999. char date[64];
  4000. time_t curtime = time(NULL);
  4001. const char *cors1, *cors2, *cors3;
  4002. if (mg_get_header(conn, "Origin")) {
  4003. /* Cross-origin resource sharing (CORS). */
  4004. cors1 = "Access-Control-Allow-Origin: ";
  4005. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  4006. cors3 = "\r\n";
  4007. } else {
  4008. cors1 = cors2 = cors3 = "";
  4009. }
  4010. if (!mg_fopen(conn, path, "rb", &file)) {
  4011. send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
  4012. strerror(ERRNO));
  4013. } else {
  4014. conn->must_close = 1;
  4015. gmt_time_string(date, sizeof(date), &curtime);
  4016. fclose_on_exec(&file, conn);
  4017. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  4018. "%s%s%s"
  4019. "Date: %s\r\n"
  4020. "Content-Type: text/html\r\n"
  4021. "Connection: %s\r\n\r\n",
  4022. cors1, cors2, cors3,
  4023. date, suggest_connection_header(conn));
  4024. send_ssi_file(conn, path, &file, 0);
  4025. mg_fclose(&file);
  4026. }
  4027. }
  4028. static void send_options(struct mg_connection *conn)
  4029. {
  4030. char date[64];
  4031. time_t curtime = time(NULL);
  4032. conn->status_code = 200;
  4033. conn->must_close = 1;
  4034. gmt_time_string(date, sizeof(date), &curtime);
  4035. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  4036. "Date: %s\r\n"
  4037. "Connection: %s\r\n"
  4038. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\n"
  4039. "DAV: 1\r\n\r\n",
  4040. date, suggest_connection_header(conn));
  4041. }
  4042. /* Writes PROPFIND properties for a collection element */
  4043. static void print_props(struct mg_connection *conn, const char* uri,
  4044. struct file *filep)
  4045. {
  4046. char mtime[64];
  4047. gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
  4048. conn->num_bytes_sent += mg_printf(conn,
  4049. "<d:response>"
  4050. "<d:href>%s</d:href>"
  4051. "<d:propstat>"
  4052. "<d:prop>"
  4053. "<d:resourcetype>%s</d:resourcetype>"
  4054. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  4055. "<d:getlastmodified>%s</d:getlastmodified>"
  4056. "</d:prop>"
  4057. "<d:status>HTTP/1.1 200 OK</d:status>"
  4058. "</d:propstat>"
  4059. "</d:response>\n",
  4060. uri,
  4061. filep->is_directory ? "<d:collection/>" : "",
  4062. filep->size,
  4063. mtime);
  4064. }
  4065. static void print_dav_dir_entry(struct de *de, void *data)
  4066. {
  4067. char href[PATH_MAX];
  4068. char href_encoded[PATH_MAX];
  4069. struct mg_connection *conn = (struct mg_connection *) data;
  4070. mg_snprintf(conn, href, sizeof(href), "%s%s",
  4071. conn->request_info.uri, de->file_name);
  4072. mg_url_encode(href, href_encoded, PATH_MAX-1);
  4073. print_props(conn, href_encoded, &de->file);
  4074. }
  4075. static void handle_propfind(struct mg_connection *conn, const char *path,
  4076. struct file *filep)
  4077. {
  4078. const char *depth = mg_get_header(conn, "Depth");
  4079. char date[64];
  4080. time_t curtime = time(NULL);
  4081. gmt_time_string(date, sizeof(date), &curtime);
  4082. conn->must_close = 1;
  4083. conn->status_code = 207;
  4084. mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
  4085. "Date: %s\r\n"
  4086. "Connection: %s\r\n"
  4087. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  4088. date, suggest_connection_header(conn));
  4089. conn->num_bytes_sent += mg_printf(conn,
  4090. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  4091. "<d:multistatus xmlns:d='DAV:'>\n");
  4092. /* Print properties for the requested resource itself */
  4093. print_props(conn, conn->request_info.uri, filep);
  4094. /* If it is a directory, print directory entries too if Depth is not 0 */
  4095. if (filep->is_directory &&
  4096. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  4097. (depth == NULL || strcmp(depth, "0") != 0)) {
  4098. scan_directory(conn, path, conn, &print_dav_dir_entry);
  4099. }
  4100. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  4101. }
  4102. void mg_lock(struct mg_connection* conn)
  4103. {
  4104. (void) pthread_mutex_lock(&conn->mutex);
  4105. }
  4106. void mg_unlock(struct mg_connection* conn)
  4107. {
  4108. (void) pthread_mutex_unlock(&conn->mutex);
  4109. }
  4110. #ifdef USE_LUA
  4111. #include "mod_lua.inl"
  4112. #endif /* USE_LUA */
  4113. #if defined(USE_WEBSOCKET)
  4114. /* START OF SHA-1 code
  4115. Copyright(c) By Steve Reid <steve@edmweb.com> */
  4116. #define SHA1HANDSOFF
  4117. #if defined(__sun)
  4118. #include "solarisfixes.h"
  4119. #endif
  4120. static int is_big_endian(void)
  4121. {
  4122. static const int n = 1;
  4123. return ((char *) &n)[0] == 0;
  4124. }
  4125. union char64long16 {
  4126. unsigned char c[64];
  4127. uint32_t l[16];
  4128. };
  4129. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  4130. static uint32_t blk0(union char64long16 *block, int i)
  4131. {
  4132. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  4133. if (!is_big_endian()) {
  4134. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  4135. (rol(block->l[i], 8) & 0x00FF00FF);
  4136. }
  4137. return block->l[i];
  4138. }
  4139. #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
  4140. ^block->l[(i+2)&15]^block->l[i&15],1))
  4141. #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
  4142. #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
  4143. #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
  4144. #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
  4145. #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
  4146. typedef struct {
  4147. uint32_t state[5];
  4148. uint32_t count[2];
  4149. unsigned char buffer[64];
  4150. } SHA1_CTX;
  4151. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  4152. {
  4153. uint32_t a, b, c, d, e;
  4154. union char64long16 block[1];
  4155. memcpy(block, buffer, 64);
  4156. a = state[0];
  4157. b = state[1];
  4158. c = state[2];
  4159. d = state[3];
  4160. e = state[4];
  4161. R0(a,b,c,d,e, 0);
  4162. R0(e,a,b,c,d, 1);
  4163. R0(d,e,a,b,c, 2);
  4164. R0(c,d,e,a,b, 3);
  4165. R0(b,c,d,e,a, 4);
  4166. R0(a,b,c,d,e, 5);
  4167. R0(e,a,b,c,d, 6);
  4168. R0(d,e,a,b,c, 7);
  4169. R0(c,d,e,a,b, 8);
  4170. R0(b,c,d,e,a, 9);
  4171. R0(a,b,c,d,e,10);
  4172. R0(e,a,b,c,d,11);
  4173. R0(d,e,a,b,c,12);
  4174. R0(c,d,e,a,b,13);
  4175. R0(b,c,d,e,a,14);
  4176. R0(a,b,c,d,e,15);
  4177. R1(e,a,b,c,d,16);
  4178. R1(d,e,a,b,c,17);
  4179. R1(c,d,e,a,b,18);
  4180. R1(b,c,d,e,a,19);
  4181. R2(a,b,c,d,e,20);
  4182. R2(e,a,b,c,d,21);
  4183. R2(d,e,a,b,c,22);
  4184. R2(c,d,e,a,b,23);
  4185. R2(b,c,d,e,a,24);
  4186. R2(a,b,c,d,e,25);
  4187. R2(e,a,b,c,d,26);
  4188. R2(d,e,a,b,c,27);
  4189. R2(c,d,e,a,b,28);
  4190. R2(b,c,d,e,a,29);
  4191. R2(a,b,c,d,e,30);
  4192. R2(e,a,b,c,d,31);
  4193. R2(d,e,a,b,c,32);
  4194. R2(c,d,e,a,b,33);
  4195. R2(b,c,d,e,a,34);
  4196. R2(a,b,c,d,e,35);
  4197. R2(e,a,b,c,d,36);
  4198. R2(d,e,a,b,c,37);
  4199. R2(c,d,e,a,b,38);
  4200. R2(b,c,d,e,a,39);
  4201. R3(a,b,c,d,e,40);
  4202. R3(e,a,b,c,d,41);
  4203. R3(d,e,a,b,c,42);
  4204. R3(c,d,e,a,b,43);
  4205. R3(b,c,d,e,a,44);
  4206. R3(a,b,c,d,e,45);
  4207. R3(e,a,b,c,d,46);
  4208. R3(d,e,a,b,c,47);
  4209. R3(c,d,e,a,b,48);
  4210. R3(b,c,d,e,a,49);
  4211. R3(a,b,c,d,e,50);
  4212. R3(e,a,b,c,d,51);
  4213. R3(d,e,a,b,c,52);
  4214. R3(c,d,e,a,b,53);
  4215. R3(b,c,d,e,a,54);
  4216. R3(a,b,c,d,e,55);
  4217. R3(e,a,b,c,d,56);
  4218. R3(d,e,a,b,c,57);
  4219. R3(c,d,e,a,b,58);
  4220. R3(b,c,d,e,a,59);
  4221. R4(a,b,c,d,e,60);
  4222. R4(e,a,b,c,d,61);
  4223. R4(d,e,a,b,c,62);
  4224. R4(c,d,e,a,b,63);
  4225. R4(b,c,d,e,a,64);
  4226. R4(a,b,c,d,e,65);
  4227. R4(e,a,b,c,d,66);
  4228. R4(d,e,a,b,c,67);
  4229. R4(c,d,e,a,b,68);
  4230. R4(b,c,d,e,a,69);
  4231. R4(a,b,c,d,e,70);
  4232. R4(e,a,b,c,d,71);
  4233. R4(d,e,a,b,c,72);
  4234. R4(c,d,e,a,b,73);
  4235. R4(b,c,d,e,a,74);
  4236. R4(a,b,c,d,e,75);
  4237. R4(e,a,b,c,d,76);
  4238. R4(d,e,a,b,c,77);
  4239. R4(c,d,e,a,b,78);
  4240. R4(b,c,d,e,a,79);
  4241. state[0] += a;
  4242. state[1] += b;
  4243. state[2] += c;
  4244. state[3] += d;
  4245. state[4] += e;
  4246. a = b = c = d = e = 0;
  4247. memset(block, '\0', sizeof(block));
  4248. }
  4249. static void SHA1Init(SHA1_CTX* context)
  4250. {
  4251. context->state[0] = 0x67452301;
  4252. context->state[1] = 0xEFCDAB89;
  4253. context->state[2] = 0x98BADCFE;
  4254. context->state[3] = 0x10325476;
  4255. context->state[4] = 0xC3D2E1F0;
  4256. context->count[0] = context->count[1] = 0;
  4257. }
  4258. static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
  4259. uint32_t len)
  4260. {
  4261. uint32_t i, j;
  4262. j = context->count[0];
  4263. if ((context->count[0] += len << 3) < j)
  4264. context->count[1]++;
  4265. context->count[1] += (len>>29);
  4266. j = (j >> 3) & 63;
  4267. if ((j + len) > 63) {
  4268. memcpy(&context->buffer[j], data, (i = 64-j));
  4269. SHA1Transform(context->state, context->buffer);
  4270. for ( ; i + 63 < len; i += 64) {
  4271. SHA1Transform(context->state, &data[i]);
  4272. }
  4273. j = 0;
  4274. } else i = 0;
  4275. memcpy(&context->buffer[j], &data[i], len - i);
  4276. }
  4277. static void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
  4278. {
  4279. unsigned i;
  4280. unsigned char finalcount[8], c;
  4281. for (i = 0; i < 8; i++) {
  4282. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  4283. >> ((3-(i & 3)) * 8) ) & 255);
  4284. }
  4285. c = 0200;
  4286. SHA1Update(context, &c, 1);
  4287. while ((context->count[0] & 504) != 448) {
  4288. c = 0000;
  4289. SHA1Update(context, &c, 1);
  4290. }
  4291. SHA1Update(context, finalcount, 8);
  4292. for (i = 0; i < 20; i++) {
  4293. digest[i] = (unsigned char)
  4294. ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  4295. }
  4296. memset(context, '\0', sizeof(*context));
  4297. memset(&finalcount, '\0', sizeof(finalcount));
  4298. }
  4299. /* END OF SHA1 CODE */
  4300. static void send_websocket_handshake(struct mg_connection *conn)
  4301. {
  4302. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  4303. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  4304. SHA1_CTX sha_ctx;
  4305. mg_snprintf(conn, buf, sizeof(buf), "%s%s",
  4306. mg_get_header(conn, "Sec-WebSocket-Key"), magic);
  4307. SHA1Init(&sha_ctx);
  4308. SHA1Update(&sha_ctx, (unsigned char *) buf, (uint32_t)strlen(buf));
  4309. SHA1Final((unsigned char *) sha, &sha_ctx);
  4310. base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  4311. mg_printf(conn, "%s%s%s",
  4312. "HTTP/1.1 101 Switching Protocols\r\n"
  4313. "Upgrade: websocket\r\n"
  4314. "Connection: Upgrade\r\n"
  4315. "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
  4316. }
  4317. static void read_websocket(struct mg_connection *conn)
  4318. {
  4319. /* Pointer to the beginning of the portion of the incoming websocket
  4320. message queue.
  4321. The original websocket upgrade request is never removed, so the queue
  4322. begins after it. */
  4323. unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;
  4324. int n, error;
  4325. /* body_len is the length of the entire queue in bytes
  4326. len is the length of the current message
  4327. data_len is the length of the current message's data payload
  4328. header_len is the length of the current message's header */
  4329. size_t i, len, mask_len, data_len, header_len, body_len;
  4330. /* "The masking key is a 32-bit value chosen at random by the client."
  4331. http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5 */
  4332. unsigned char mask[4];
  4333. /* data points to the place where the message is stored when passed to the
  4334. websocket_data callback. This is either mem on the stack, or a
  4335. dynamically allocated buffer if it is too large. */
  4336. char mem[4096];
  4337. char *data = mem;
  4338. unsigned char mop; /* mask flag and opcode */
  4339. /* Loop continuously, reading messages from the socket, invoking the
  4340. callback, and waiting repeatedly until an error occurs. */
  4341. assert(conn->content_len == 0);
  4342. for (;;) {
  4343. header_len = 0;
  4344. assert(conn->data_len >= conn->request_len);
  4345. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  4346. len = buf[1] & 127;
  4347. mask_len = buf[1] & 128 ? 4 : 0;
  4348. if (len < 126 && body_len >= mask_len) {
  4349. data_len = len;
  4350. header_len = 2 + mask_len;
  4351. } else if (len == 126 && body_len >= 4 + mask_len) {
  4352. header_len = 4 + mask_len;
  4353. data_len = ((((int) buf[2]) << 8) + buf[3]);
  4354. } else if (body_len >= 10 + mask_len) {
  4355. header_len = 10 + mask_len;
  4356. data_len = (((uint64_t) ntohl(* (uint32_t *) &buf[2])) << 32) +
  4357. ntohl(* (uint32_t *) &buf[6]);
  4358. }
  4359. }
  4360. if (header_len > 0 && body_len >= header_len) {
  4361. /* Allocate space to hold websocket payload */
  4362. data = mem;
  4363. if (data_len > sizeof(mem)) {
  4364. data = (char *)mg_malloc(data_len);
  4365. if (data == NULL) {
  4366. /* Allocation failed, exit the loop and then close the
  4367. connection */
  4368. mg_cry(conn, "websocket out of memory; closing connection");
  4369. break;
  4370. }
  4371. }
  4372. /* Copy the mask before we shift the queue and destroy it */
  4373. if (mask_len > 0) {
  4374. *(uint32_t*)mask = *(uint32_t*)(buf + header_len - mask_len);
  4375. } else {
  4376. *(uint32_t*)mask = 0;
  4377. }
  4378. /* Read frame payload from the first message in the queue into
  4379. data and advance the queue by moving the memory in place. */
  4380. assert(body_len >= header_len);
  4381. if (data_len + header_len > body_len) {
  4382. mop = buf[0]; /* current mask and opcode */
  4383. /* Overflow case */
  4384. len = body_len - header_len;
  4385. memcpy(data, buf + header_len, len);
  4386. error = 0;
  4387. while (len < data_len) {
  4388. int n = pull(NULL, conn, data + len, (int)(data_len - len));
  4389. if (n <= 0) {
  4390. error = 1;
  4391. break;
  4392. }
  4393. len += n;
  4394. }
  4395. if (error) {
  4396. mg_cry(conn, "Websocket pull failed; closing connection");
  4397. break;
  4398. }
  4399. conn->data_len = conn->request_len;
  4400. } else {
  4401. mop = buf[0]; /* current mask and opcode, overwritten by memmove() */
  4402. /* Length of the message being read at the front of the
  4403. queue */
  4404. len = data_len + header_len;
  4405. /* Copy the data payload into the data pointer for the
  4406. callback */
  4407. memcpy(data, buf + header_len, data_len);
  4408. /* Move the queue forward len bytes */
  4409. memmove(buf, buf + len, body_len - len);
  4410. /* Mark the queue as advanced */
  4411. conn->data_len -= (int)len;
  4412. }
  4413. /* Apply mask if necessary */
  4414. if (mask_len > 0) {
  4415. for (i = 0; i < data_len; ++i) {
  4416. data[i] ^= mask[i & 3];
  4417. }
  4418. }
  4419. /* Exit the loop if callback signalled to exit,
  4420. or "connection close" opcode received. */
  4421. if ((conn->ctx->callbacks.websocket_data != NULL &&
  4422. #ifdef USE_LUA
  4423. (conn->lua_websocket_state == NULL) &&
  4424. #endif
  4425. !conn->ctx->callbacks.websocket_data(conn, mop, data, data_len)) ||
  4426. #ifdef USE_LUA
  4427. (conn->lua_websocket_state &&
  4428. !lua_websocket_data(conn, mop, data, data_len)) ||
  4429. #endif
  4430. (buf[0] & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE) { /* Opcode == 8, connection close */
  4431. break;
  4432. }
  4433. if (data != mem) {
  4434. mg_free(data);
  4435. }
  4436. /* Not breaking the loop, process next websocket frame. */
  4437. } else {
  4438. /* Read from the socket into the next available location in the
  4439. message queue. */
  4440. if ((n = pull(NULL, conn, conn->buf + conn->data_len,
  4441. conn->buf_size - conn->data_len)) <= 0) {
  4442. /* Error, no bytes read */
  4443. break;
  4444. }
  4445. conn->data_len += n;
  4446. }
  4447. }
  4448. }
  4449. int mg_websocket_write(struct mg_connection* conn, int opcode, const char* data, size_t dataLen)
  4450. {
  4451. unsigned char header[10];
  4452. size_t headerLen = 1;
  4453. int retval = -1;
  4454. header[0] = 0x80 + (opcode & 0xF);
  4455. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  4456. if (dataLen < 126) {
  4457. /* inline 7-bit length field */
  4458. header[1] = (unsigned char)dataLen;
  4459. headerLen = 2;
  4460. } else if (dataLen <= 0xFFFF) {
  4461. /* 16-bit length field */
  4462. header[1] = 126;
  4463. *(uint16_t*)(header + 2) = htons((uint16_t)dataLen);
  4464. headerLen = 4;
  4465. } else {
  4466. /* 64-bit length field */
  4467. header[1] = 127;
  4468. *(uint32_t*)(header + 2) = htonl((uint64_t)dataLen >> 32);
  4469. *(uint32_t*)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  4470. headerLen = 10;
  4471. }
  4472. /* Note that POSIX/Winsock's send() is threadsafe
  4473. http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  4474. but mongoose's mg_printf/mg_write is not (because of the loop in
  4475. push(), although that is only a problem if the packet is large or
  4476. outgoing buffer is full). */
  4477. (void) mg_lock(conn);
  4478. retval = mg_write(conn, header, headerLen);
  4479. retval = mg_write(conn, data, dataLen);
  4480. mg_unlock(conn);
  4481. return retval;
  4482. }
  4483. static void handle_websocket_request(struct mg_connection *conn, const char *path, int is_script_resource)
  4484. {
  4485. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  4486. #ifdef USE_LUA
  4487. int lua_websock, shared_lua_websock = 0;
  4488. /* TODO: A websocket script may be shared between several clients, allowing them to communicate
  4489. directly instead of writing to a data base and polling the data base. */
  4490. #endif
  4491. if (version == NULL || strcmp(version, "13") != 0) {
  4492. send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
  4493. } else if (conn->ctx->callbacks.websocket_connect != NULL &&
  4494. conn->ctx->callbacks.websocket_connect(conn) != 0) {
  4495. /* C callback has returned non-zero, do not proceed with handshake. */
  4496. /* The C callback is called before Lua and may prevent Lua from handling the websocket. */
  4497. } else {
  4498. #ifdef USE_LUA
  4499. lua_websock = conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS] ?
  4500. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  4501. (int)strlen(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  4502. path) : 0;
  4503. if (lua_websock || shared_lua_websock) {
  4504. /* TODO */ shared_lua_websock = 0;
  4505. conn->lua_websocket_state = lua_websocket_new(path, conn, !!shared_lua_websock);
  4506. if (conn->lua_websocket_state) {
  4507. send_websocket_handshake(conn);
  4508. if (lua_websocket_ready(conn)) {
  4509. read_websocket(conn);
  4510. }
  4511. }
  4512. } else
  4513. #endif
  4514. {
  4515. /* No Lua websock script specified. */
  4516. send_websocket_handshake(conn);
  4517. if (conn->ctx->callbacks.websocket_ready != NULL) {
  4518. conn->ctx->callbacks.websocket_ready(conn);
  4519. }
  4520. read_websocket(conn);
  4521. }
  4522. }
  4523. }
  4524. static int is_websocket_request(const struct mg_connection *conn)
  4525. {
  4526. const char *host, *upgrade, *connection, *version, *key;
  4527. host = mg_get_header(conn, "Host");
  4528. upgrade = mg_get_header(conn, "Upgrade");
  4529. connection = mg_get_header(conn, "Connection");
  4530. key = mg_get_header(conn, "Sec-WebSocket-Key");
  4531. version = mg_get_header(conn, "Sec-WebSocket-Version");
  4532. return host != NULL && upgrade != NULL && connection != NULL &&
  4533. key != NULL && version != NULL &&
  4534. mg_strcasestr(upgrade, "websocket") != NULL &&
  4535. mg_strcasestr(connection, "Upgrade") != NULL;
  4536. }
  4537. #endif /* !USE_WEBSOCKET */
  4538. static int isbyte(int n)
  4539. {
  4540. return n >= 0 && n <= 255;
  4541. }
  4542. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  4543. {
  4544. int n, a, b, c, d, slash = 32, len = 0;
  4545. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  4546. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  4547. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
  4548. slash >= 0 && slash < 33) {
  4549. len = n;
  4550. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  4551. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  4552. }
  4553. return len;
  4554. }
  4555. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  4556. {
  4557. int throttle = 0;
  4558. struct vec vec, val;
  4559. uint32_t net, mask;
  4560. char mult;
  4561. double v;
  4562. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  4563. mult = ',';
  4564. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  4565. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
  4566. continue;
  4567. }
  4568. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
  4569. if (vec.len == 1 && vec.ptr[0] == '*') {
  4570. throttle = (int) v;
  4571. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  4572. if ((remote_ip & mask) == net) {
  4573. throttle = (int) v;
  4574. }
  4575. } else if (match_prefix(vec.ptr, (int)vec.len, uri) > 0) {
  4576. throttle = (int) v;
  4577. }
  4578. }
  4579. return throttle;
  4580. }
  4581. static uint32_t get_remote_ip(const struct mg_connection *conn)
  4582. {
  4583. return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
  4584. }
  4585. int mg_upload(struct mg_connection *conn, const char *destination_dir)
  4586. {
  4587. const char *content_type_header, *boundary_start;
  4588. char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s;
  4589. FILE *fp;
  4590. int bl, n, i, j, headers_len, boundary_len, eof,
  4591. len = 0, num_uploaded_files = 0;
  4592. /* Request looks like this:
  4593. POST /upload HTTP/1.1
  4594. Host: 127.0.0.1:8080
  4595. Content-Length: 244894
  4596. Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  4597. ------WebKitFormBoundaryRVr
  4598. Content-Disposition: form-data; name="file"; filename="accum.png"
  4599. Content-Type: image/png
  4600. <89>PNG
  4601. <PNG DATA>
  4602. ------WebKitFormBoundaryRVr */
  4603. /* Extract boundary string from the Content-Type header */
  4604. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  4605. (boundary_start = mg_strcasestr(content_type_header,
  4606. "boundary=")) == NULL ||
  4607. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  4608. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  4609. boundary[0] == '\0') {
  4610. return num_uploaded_files;
  4611. }
  4612. boundary[99]=0;
  4613. boundary_len = (int)strlen(boundary);
  4614. bl = boundary_len + 4; /* \r\n--<boundary> */
  4615. for (;;) {
  4616. /* Pull in headers */
  4617. assert(len >= 0 && len <= (int) sizeof(buf));
  4618. while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {
  4619. len += n;
  4620. }
  4621. if ((headers_len = get_request_len(buf, len)) <= 0) {
  4622. break;
  4623. }
  4624. /* Fetch file name. */
  4625. fname[0] = '\0';
  4626. for (i = j = 0; i < headers_len; i++) {
  4627. if (buf[i] == '\r' && buf[i + 1] == '\n') {
  4628. buf[i] = buf[i + 1] = '\0';
  4629. /* TODO(lsm): don't expect filename to be the 3rd field,
  4630. parse the header properly instead. */
  4631. IGNORE_UNUSED_RESULT(sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
  4632. fname));
  4633. fname[1023]=0;
  4634. j = i + 2;
  4635. }
  4636. }
  4637. /* Give up if the headers are not what we expect */
  4638. if (fname[0] == '\0') {
  4639. break;
  4640. }
  4641. /* Move data to the beginning of the buffer */
  4642. assert(len >= headers_len);
  4643. memmove(buf, &buf[headers_len], len - headers_len);
  4644. len -= headers_len;
  4645. /* We open the file with exclusive lock held. This guarantee us
  4646. there is no other thread can save into the same file
  4647. simultaneously. */
  4648. fp = NULL;
  4649. /* Construct destination file name. Do not allow paths to have
  4650. slashes. */
  4651. if ((s = strrchr(fname, '/')) == NULL &&
  4652. (s = strrchr(fname, '\\')) == NULL) {
  4653. s = fname;
  4654. }
  4655. /* Open file in binary mode. TODO: set an exclusive lock. */
  4656. snprintf(path, sizeof(path), "%s/%s", destination_dir, s);
  4657. if ((fp = fopen(path, "wb")) == NULL) {
  4658. break;
  4659. }
  4660. /* Read POST data, write into file until boundary is found. */
  4661. eof = n = 0;
  4662. do {
  4663. len += n;
  4664. for (i = 0; i < len - bl; i++) {
  4665. if (!memcmp(&buf[i], "\r\n--", 4) &&
  4666. !memcmp(&buf[i + 4], boundary, boundary_len)) {
  4667. /* Found boundary, that's the end of file data. */
  4668. fwrite(buf, 1, i, fp);
  4669. eof = 1;
  4670. memmove(buf, &buf[i + bl], len - (i + bl));
  4671. len -= i + bl;
  4672. break;
  4673. }
  4674. }
  4675. if (!eof && len > bl) {
  4676. fwrite(buf, 1, len - bl, fp);
  4677. memmove(buf, &buf[len - bl], bl);
  4678. len = bl;
  4679. }
  4680. } while (!eof && (n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);
  4681. fclose(fp);
  4682. if (eof) {
  4683. num_uploaded_files++;
  4684. if (conn->ctx->callbacks.upload != NULL) {
  4685. conn->ctx->callbacks.upload(conn, path);
  4686. }
  4687. }
  4688. }
  4689. return num_uploaded_files;
  4690. }
  4691. static int is_put_or_delete_request(const struct mg_connection *conn)
  4692. {
  4693. const char *s = conn->request_info.request_method;
  4694. return s != NULL && (!strcmp(s, "PUT") ||
  4695. !strcmp(s, "DELETE") ||
  4696. !strcmp(s, "MKCOL"));
  4697. }
  4698. static int get_first_ssl_listener_index(const struct mg_context *ctx)
  4699. {
  4700. int i, idx = -1;
  4701. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  4702. idx = ctx->listening_sockets[i].is_ssl ? i : -1;
  4703. }
  4704. return idx;
  4705. }
  4706. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  4707. {
  4708. char host[1025];
  4709. const char *host_header;
  4710. size_t hostlen;
  4711. host_header = mg_get_header(conn, "Host");
  4712. hostlen = sizeof(host);
  4713. if (host_header != NULL) {
  4714. char *pos;
  4715. mg_strlcpy(host, host_header, hostlen);
  4716. host[hostlen - 1] = '\0';
  4717. pos = strchr(host, ':');
  4718. if (pos != NULL) {
  4719. *pos = '\0';
  4720. }
  4721. } else {
  4722. /* Cannot get host from the Host: header.
  4723. Fallback to our IP address. */
  4724. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  4725. }
  4726. mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",
  4727. host, (int) ntohs(conn->ctx->listening_sockets[ssl_index].
  4728. lsa.sin.sin_port), conn->request_info.uri);
  4729. }
  4730. void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata)
  4731. {
  4732. struct mg_request_handler_info *tmp_rh, *lastref = 0;
  4733. size_t urilen = strlen(uri);
  4734. /* first see it the uri exists */
  4735. for (tmp_rh = ctx->request_handlers;
  4736. tmp_rh != NULL && 0!=strcmp(uri, tmp_rh->uri);
  4737. lastref = tmp_rh, tmp_rh = tmp_rh->next) {
  4738. /* first try for an exact match */
  4739. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
  4740. /* already there... */
  4741. if (handler != NULL) {
  4742. /* change this entry */
  4743. tmp_rh->handler = handler;
  4744. tmp_rh->cbdata = cbdata;
  4745. } else {
  4746. /* remove this entry */
  4747. if (lastref != NULL)
  4748. lastref->next = tmp_rh->next;
  4749. else
  4750. ctx->request_handlers = tmp_rh->next;
  4751. mg_free(tmp_rh->uri);
  4752. mg_free(tmp_rh);
  4753. }
  4754. return;
  4755. }
  4756. /* next try for a partial match, we will accept uri/something */
  4757. if (tmp_rh->uri_len < urilen
  4758. && uri[tmp_rh->uri_len] == '/'
  4759. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  4760. /* if there is a partical match this new entry MUST go BEFORE
  4761. the current position otherwise it will never be matched. */
  4762. break;
  4763. }
  4764. }
  4765. if (handler == NULL) {
  4766. /* no handler to set, this was a remove request */
  4767. return;
  4768. }
  4769. tmp_rh = (struct mg_request_handler_info *)mg_malloc(sizeof(struct mg_request_handler_info));
  4770. if (tmp_rh == NULL) {
  4771. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  4772. return;
  4773. }
  4774. tmp_rh->uri = mg_strdup(uri);
  4775. tmp_rh->uri_len = urilen;
  4776. tmp_rh->handler = handler;
  4777. tmp_rh->cbdata = cbdata;
  4778. if (lastref == NULL) {
  4779. tmp_rh->next = ctx->request_handlers;
  4780. ctx->request_handlers = tmp_rh;
  4781. } else {
  4782. tmp_rh->next = lastref->next;
  4783. lastref->next = tmp_rh;
  4784. }
  4785. }
  4786. static int use_request_handler(struct mg_connection *conn)
  4787. {
  4788. struct mg_request_info *request_info = mg_get_request_info(conn);
  4789. const char *uri = request_info->uri;
  4790. size_t urilen = strlen(uri);
  4791. struct mg_request_handler_info *tmp_rh = conn->ctx->request_handlers;
  4792. for (; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  4793. /* first try for an exact match */
  4794. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
  4795. return tmp_rh->handler(conn, tmp_rh->cbdata);
  4796. }
  4797. /* next try for a partial match */
  4798. /* we will accept uri/something */
  4799. if (tmp_rh->uri_len < urilen
  4800. && uri[tmp_rh->uri_len] == '/'
  4801. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  4802. return tmp_rh->handler(conn, tmp_rh->cbdata);
  4803. }
  4804. /* try for pattern match */
  4805. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  4806. return tmp_rh->handler(conn, tmp_rh->cbdata);
  4807. }
  4808. }
  4809. return 0; /* none found */
  4810. }
  4811. /* This is the heart of the Civetweb's logic.
  4812. This function is called when the request is read, parsed and validated,
  4813. and Civetweb must decide what action to take: serve a file, or
  4814. a directory, or call embedded function, etcetera. */
  4815. static void handle_request(struct mg_connection *conn)
  4816. {
  4817. struct mg_request_info *ri = &conn->request_info;
  4818. char path[PATH_MAX];
  4819. int uri_len, ssl_index, is_script_resource;
  4820. struct file file = STRUCT_FILE_INITIALIZER;
  4821. char date[64];
  4822. time_t curtime = time(NULL);
  4823. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  4824. * ((char *) conn->request_info.query_string++) = '\0';
  4825. }
  4826. uri_len = (int) strlen(ri->uri);
  4827. mg_url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0);
  4828. remove_double_dots_and_double_slashes((char *) ri->uri);
  4829. path[0] = '\0';
  4830. convert_uri_to_file_name(conn, path, sizeof(path), &file, &is_script_resource);
  4831. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  4832. get_remote_ip(conn), ri->uri);
  4833. DEBUG_TRACE("%s", ri->uri);
  4834. /* Perform redirect and auth checks before calling begin_request() handler.
  4835. Otherwise, begin_request() would need to perform auth checks and
  4836. redirects. */
  4837. if (!conn->client.is_ssl && conn->client.ssl_redir &&
  4838. (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {
  4839. redirect_to_https_port(conn, ssl_index);
  4840. } else if (!is_script_resource && !is_put_or_delete_request(conn) &&
  4841. !check_authorization(conn, path)) {
  4842. send_authorization_request(conn);
  4843. } else if (conn->ctx->callbacks.begin_request != NULL &&
  4844. conn->ctx->callbacks.begin_request(conn)) {
  4845. /* Do nothing, callback has served the request */
  4846. #if defined(USE_WEBSOCKET)
  4847. } else if (is_websocket_request(conn)) {
  4848. handle_websocket_request(conn, path, is_script_resource);
  4849. #endif
  4850. } else if (conn->ctx->request_handlers != NULL &&
  4851. use_request_handler(conn)) {
  4852. /* Do nothing, callback has served the request */
  4853. } else if (!is_script_resource && !strcmp(ri->request_method, "OPTIONS")) {
  4854. /* Scripts should support the OPTIONS method themselves, to allow a maximum flexibility.
  4855. Lua and CGI scripts may fully support CORS this way (including preflights). */
  4856. send_options(conn);
  4857. } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  4858. send_http_error(conn, 404, "Not Found", "Not Found");
  4859. } else if (!is_script_resource && is_put_or_delete_request(conn) &&
  4860. (is_authorized_for_put(conn) != 1)) {
  4861. send_authorization_request(conn);
  4862. } else if (!is_script_resource && !strcmp(ri->request_method, "PUT")) {
  4863. put_file(conn, path);
  4864. } else if (!is_script_resource && !strcmp(ri->request_method, "MKCOL")) {
  4865. mkcol(conn, path);
  4866. } else if (!is_script_resource && !strcmp(ri->request_method, "DELETE")) {
  4867. struct de de;
  4868. memset(&de.file, 0, sizeof(de.file));
  4869. if(!mg_stat(conn, path, &de.file)) {
  4870. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  4871. } else {
  4872. if(de.file.modification_time) {
  4873. if(de.file.is_directory) {
  4874. remove_directory(conn, path);
  4875. send_http_error(conn, 204, "No Content", "%s", "");
  4876. } else if (mg_remove(path) == 0) {
  4877. send_http_error(conn, 204, "No Content", "%s", "");
  4878. } else {
  4879. send_http_error(conn, 423, "Locked", "remove(%s): %s", path,
  4880. strerror(ERRNO));
  4881. }
  4882. } else {
  4883. send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
  4884. strerror(ERRNO));
  4885. }
  4886. }
  4887. } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||
  4888. must_hide_file(conn, path)) {
  4889. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  4890. } else if (file.is_directory && ri->uri[uri_len - 1] != '/') {
  4891. gmt_time_string(date, sizeof(date), &curtime);
  4892. mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
  4893. "Location: %s/\r\n"
  4894. "Date: %s\r\n"
  4895. "Content-Length: 0\r\n"
  4896. "Connection: %s\r\n\r\n",
  4897. ri->uri, date, suggest_connection_header(conn));
  4898. } else if (!is_script_resource && !strcmp(ri->request_method, "PROPFIND")) {
  4899. handle_propfind(conn, path, &file);
  4900. } else if (file.is_directory &&
  4901. !substitute_index_file(conn, path, sizeof(path), &file)) {
  4902. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
  4903. handle_directory_request(conn, path);
  4904. } else {
  4905. send_http_error(conn, 403, "Directory Listing Denied",
  4906. "Directory listing denied");
  4907. }
  4908. } else {
  4909. handle_file_based_request(conn, path, &file);
  4910. }
  4911. }
  4912. static void handle_file_based_request(struct mg_connection *conn, const char *path, struct file *file)
  4913. {
  4914. if (0) {
  4915. #ifdef USE_LUA
  4916. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  4917. (int)strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  4918. path) > 0) {
  4919. /* Lua server page: an SSI like page containing mostly plain html code plus some tags with server generated contents. */
  4920. handle_lsp_request(conn, path, file, NULL);
  4921. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4922. (int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4923. path) > 0) {
  4924. /* Lua in-server module script: a CGI like script used to generate the entire reply. */
  4925. mg_exec_lua_script(conn, path, NULL);
  4926. #endif
  4927. #if !defined(NO_CGI)
  4928. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4929. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4930. path) > 0) {
  4931. /* CGI scripts may support all HTTP methods */
  4932. handle_cgi_request(conn, path);
  4933. #endif /* !NO_CGI */
  4934. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  4935. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]),
  4936. path) > 0) {
  4937. handle_ssi_file_request(conn, path);
  4938. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  4939. send_http_error(conn, 304, "Not Modified", "%s", "");
  4940. } else {
  4941. handle_static_file_request(conn, path, file);
  4942. }
  4943. }
  4944. static void close_all_listening_sockets(struct mg_context *ctx)
  4945. {
  4946. int i;
  4947. for (i = 0; i < ctx->num_listening_sockets; i++) {
  4948. closesocket(ctx->listening_sockets[i].sock);
  4949. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  4950. }
  4951. mg_free(ctx->listening_sockets);
  4952. ctx->listening_sockets=0;
  4953. mg_free(ctx->listening_ports);
  4954. ctx->listening_ports=0;
  4955. }
  4956. static int is_valid_port(unsigned int port)
  4957. {
  4958. return port < 0xffff;
  4959. }
  4960. /* Valid listening port specification is: [ip_address:]port[s]
  4961. Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  4962. TODO(lsm): add parsing of the IPv6 address */
  4963. static int parse_port_string(const struct vec *vec, struct socket *so)
  4964. {
  4965. unsigned int a, b, c, d, port;
  4966. int ch, len;
  4967. #if defined(USE_IPV6)
  4968. char buf[100]={0};
  4969. #endif
  4970. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  4971. Also, all-zeroes in the socket address means binding to all addresses
  4972. for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  4973. memset(so, 0, sizeof(*so));
  4974. so->lsa.sin.sin_family = AF_INET;
  4975. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
  4976. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  4977. so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
  4978. so->lsa.sin.sin_port = htons((uint16_t) port);
  4979. #if defined(USE_IPV6)
  4980. } else if (sscanf(vec->ptr, "[%49[^]]]:%d%n", buf, &port, &len) == 2 &&
  4981. inet_pton(AF_INET6, buf, &so->lsa.sin6.sin6_addr)) {
  4982. /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
  4983. so->lsa.sin6.sin6_family = AF_INET6;
  4984. so->lsa.sin6.sin6_port = htons((uint16_t) port);
  4985. #endif
  4986. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  4987. /* If only port is specified, bind to IPv4, INADDR_ANY */
  4988. so->lsa.sin.sin_port = htons((uint16_t) port);
  4989. } else {
  4990. port = len = 0; /* Parsing failure. Make port invalid. */
  4991. }
  4992. assert((len>=0) && ((unsigned)len<=(unsigned)vec->len)); /* sscanf and the option splitting code ensure this condition */
  4993. ch = vec->ptr[len]; /* Next character after the port number */
  4994. so->is_ssl = ch == 's';
  4995. so->ssl_redir = ch == 'r';
  4996. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  4997. return is_valid_port(port) &&
  4998. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  4999. }
  5000. static int set_ports_option(struct mg_context *ctx)
  5001. {
  5002. const char *list = ctx->config[LISTENING_PORTS];
  5003. int on = 1, success = 1;
  5004. #if defined(USE_IPV6)
  5005. int off = 0;
  5006. #endif
  5007. struct vec vec;
  5008. struct socket so, *ptr;
  5009. in_port_t *portPtr;
  5010. union usa usa;
  5011. socklen_t len;
  5012. memset(&usa, 0, sizeof(usa));
  5013. len = sizeof(usa);
  5014. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  5015. if (!parse_port_string(&vec, &so)) {
  5016. mg_cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
  5017. __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|r]");
  5018. success = 0;
  5019. } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
  5020. mg_cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
  5021. success = 0;
  5022. } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  5023. INVALID_SOCKET ||
  5024. /* On Windows, SO_REUSEADDR is recommended only for
  5025. broadcast UDP sockets */
  5026. setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,
  5027. (void *) &on, sizeof(on)) != 0 ||
  5028. #if defined(USE_IPV6)
  5029. (so.lsa.sa.sa_family == AF_INET6 &&
  5030. setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &off,
  5031. sizeof(off)) != 0) ||
  5032. #endif
  5033. bind(so.sock, &so.lsa.sa, so.lsa.sa.sa_family == AF_INET ?
  5034. sizeof(so.lsa.sin) : sizeof(so.lsa)) != 0 ||
  5035. listen(so.sock, SOMAXCONN) != 0 ||
  5036. getsockname(so.sock, &(usa.sa), &len) != 0) {
  5037. mg_cry(fc(ctx), "%s: cannot bind to %.*s: %d (%s)", __func__,
  5038. (int) vec.len, vec.ptr, ERRNO, strerror(errno));
  5039. if (so.sock != INVALID_SOCKET) {
  5040. closesocket(so.sock);
  5041. so.sock = INVALID_SOCKET;
  5042. }
  5043. success = 0;
  5044. } else if ((ptr = (struct socket *) mg_realloc(ctx->listening_sockets,
  5045. (ctx->num_listening_sockets + 1) *
  5046. sizeof(ctx->listening_sockets[0]))) == NULL) {
  5047. closesocket(so.sock);
  5048. so.sock = INVALID_SOCKET;
  5049. success = 0;
  5050. } else if ((portPtr = (in_port_t*) mg_realloc(ctx->listening_ports,
  5051. (ctx->num_listening_sockets + 1) *
  5052. sizeof(ctx->listening_ports[0]))) == NULL) {
  5053. closesocket(so.sock);
  5054. so.sock = INVALID_SOCKET;
  5055. success = 0;
  5056. }
  5057. else {
  5058. set_close_on_exec(so.sock, fc(ctx));
  5059. ctx->listening_sockets = ptr;
  5060. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  5061. ctx->listening_ports = portPtr;
  5062. ctx->listening_ports[ctx->num_listening_sockets] = ntohs(usa.sin.sin_port);
  5063. ctx->num_listening_sockets++;
  5064. }
  5065. }
  5066. if (!success) {
  5067. close_all_listening_sockets(ctx);
  5068. }
  5069. return success;
  5070. }
  5071. static void log_header(const struct mg_connection *conn, const char *header,
  5072. FILE *fp)
  5073. {
  5074. const char *header_value;
  5075. if ((header_value = mg_get_header(conn, header)) == NULL) {
  5076. (void) fprintf(fp, "%s", " -");
  5077. } else {
  5078. (void) fprintf(fp, " \"%s\"", header_value);
  5079. }
  5080. }
  5081. static void log_access(const struct mg_connection *conn)
  5082. {
  5083. const struct mg_request_info *ri;
  5084. FILE *fp;
  5085. char date[64], src_addr[IP_ADDR_STR_LEN];
  5086. struct tm *tm;
  5087. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :
  5088. fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  5089. if (fp == NULL)
  5090. return;
  5091. tm = localtime(&conn->birth_time);
  5092. if (tm != NULL) {
  5093. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  5094. } else {
  5095. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  5096. date[sizeof(date) - 1] = '\0';
  5097. }
  5098. ri = &conn->request_info;
  5099. flockfile(fp);
  5100. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  5101. fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
  5102. src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
  5103. ri->request_method ? ri->request_method : "-",
  5104. ri->uri ? ri->uri : "-", ri->http_version,
  5105. conn->status_code, conn->num_bytes_sent);
  5106. log_header(conn, "Referer", fp);
  5107. log_header(conn, "User-Agent", fp);
  5108. fputc('\n', fp);
  5109. fflush(fp);
  5110. funlockfile(fp);
  5111. fclose(fp);
  5112. }
  5113. /* Verify given socket address against the ACL.
  5114. Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  5115. static int check_acl(struct mg_context *ctx, uint32_t remote_ip)
  5116. {
  5117. int allowed, flag;
  5118. uint32_t net, mask;
  5119. struct vec vec;
  5120. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  5121. /* If any ACL is set, deny by default */
  5122. allowed = list == NULL ? '+' : '-';
  5123. while ((list = next_option(list, &vec, NULL)) != NULL) {
  5124. flag = vec.ptr[0];
  5125. if ((flag != '+' && flag != '-') ||
  5126. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  5127. mg_cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  5128. return -1;
  5129. }
  5130. if (net == (remote_ip & mask)) {
  5131. allowed = flag;
  5132. }
  5133. }
  5134. return allowed == '+';
  5135. }
  5136. #if !defined(_WIN32)
  5137. static int set_uid_option(struct mg_context *ctx)
  5138. {
  5139. struct passwd *pw;
  5140. const char *uid = ctx->config[RUN_AS_USER];
  5141. int success = 0;
  5142. if (uid == NULL) {
  5143. success = 1;
  5144. } else {
  5145. if ((pw = getpwnam(uid)) == NULL) {
  5146. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  5147. } else if (setgid(pw->pw_gid) == -1) {
  5148. mg_cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
  5149. } else if (setuid(pw->pw_uid) == -1) {
  5150. mg_cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
  5151. } else {
  5152. success = 1;
  5153. }
  5154. }
  5155. return success;
  5156. }
  5157. #endif /* !_WIN32 */
  5158. #if !defined(NO_SSL)
  5159. static pthread_mutex_t *ssl_mutexes;
  5160. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  5161. {
  5162. return (conn->ssl = SSL_new(s)) != NULL &&
  5163. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  5164. func(conn->ssl) == 1;
  5165. }
  5166. /* Return OpenSSL error message */
  5167. static const char *ssl_error(void)
  5168. {
  5169. unsigned long err;
  5170. err = ERR_get_error();
  5171. return err == 0 ? "" : ERR_error_string(err, NULL);
  5172. }
  5173. static void ssl_locking_callback(int mode, int mutex_num, const char *file,
  5174. int line)
  5175. {
  5176. (void) line;
  5177. (void) file;
  5178. if (mode & 1) { /* 1 is CRYPTO_LOCK */
  5179. (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  5180. } else {
  5181. (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  5182. }
  5183. }
  5184. static unsigned long ssl_id_callback(void)
  5185. {
  5186. return (unsigned long) pthread_self();
  5187. }
  5188. #if !defined(NO_SSL_DL)
  5189. static void *load_dll(struct mg_context *ctx, const char *dll_name,
  5190. struct ssl_func *sw)
  5191. {
  5192. union {
  5193. void *p;
  5194. void (*fp)(void);
  5195. } u;
  5196. void *dll_handle;
  5197. struct ssl_func *fp;
  5198. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  5199. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  5200. return NULL;
  5201. }
  5202. for (fp = sw; fp->name != NULL; fp++) {
  5203. #ifdef _WIN32
  5204. /* GetProcAddress() returns pointer to function */
  5205. u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
  5206. #else
  5207. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  5208. pointers to function pointers. We need to use a union to make a
  5209. cast. */
  5210. u.p = dlsym(dll_handle, fp->name);
  5211. #endif /* _WIN32 */
  5212. if (u.fp == NULL) {
  5213. mg_cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
  5214. dlclose(dll_handle);
  5215. return NULL;
  5216. } else {
  5217. fp->ptr = u.fp;
  5218. }
  5219. }
  5220. return dll_handle;
  5221. }
  5222. #endif /* NO_SSL_DL */
  5223. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  5224. static int set_ssl_option(struct mg_context *ctx)
  5225. {
  5226. int i, size;
  5227. const char *pem;
  5228. /* If PEM file is not specified and the init_ssl callback
  5229. is not specified, skip SSL initialization. */
  5230. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  5231. ctx->callbacks.init_ssl == NULL) {
  5232. return 1;
  5233. }
  5234. #if !defined(NO_SSL_DL)
  5235. ctx->ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  5236. ctx->cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  5237. if (!ctx->ssllib_dll_handle || !ctx->cryptolib_dll_handle) {
  5238. return 0;
  5239. }
  5240. #endif /* NO_SSL_DL */
  5241. /* Initialize SSL library */
  5242. SSL_library_init();
  5243. SSL_load_error_strings();
  5244. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  5245. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  5246. return 0;
  5247. }
  5248. /* If user callback returned non-NULL, that means that user callback has
  5249. set up certificate itself. In this case, skip sertificate setting. */
  5250. if ((ctx->callbacks.init_ssl == NULL ||
  5251. !ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data)) &&
  5252. (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||
  5253. SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  5254. mg_cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());
  5255. return 0;
  5256. }
  5257. if (pem != NULL) {
  5258. (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  5259. }
  5260. /* Initialize locking callbacks, needed for thread safety.
  5261. http://www.openssl.org/support/faq.html#PROG1 */
  5262. size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
  5263. if ((ssl_mutexes = (pthread_mutex_t *) mg_malloc((size_t)size)) == NULL) {
  5264. mg_cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  5265. return 0;
  5266. }
  5267. for (i = 0; i < CRYPTO_num_locks(); i++) {
  5268. pthread_mutex_init(&ssl_mutexes[i], NULL);
  5269. }
  5270. CRYPTO_set_locking_callback(&ssl_locking_callback);
  5271. CRYPTO_set_id_callback(&ssl_id_callback);
  5272. return 1;
  5273. }
  5274. static void uninitialize_ssl(struct mg_context *ctx)
  5275. {
  5276. int i;
  5277. if (ctx->ssl_ctx != NULL) {
  5278. CRYPTO_set_locking_callback(NULL);
  5279. for (i = 0; i < CRYPTO_num_locks(); i++) {
  5280. pthread_mutex_destroy(&ssl_mutexes[i]);
  5281. }
  5282. CRYPTO_set_locking_callback(NULL);
  5283. CRYPTO_set_id_callback(NULL);
  5284. }
  5285. }
  5286. #endif /* !NO_SSL */
  5287. static int set_gpass_option(struct mg_context *ctx)
  5288. {
  5289. struct file file = STRUCT_FILE_INITIALIZER;
  5290. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  5291. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  5292. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  5293. return 0;
  5294. }
  5295. return 1;
  5296. }
  5297. static int set_acl_option(struct mg_context *ctx)
  5298. {
  5299. return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
  5300. }
  5301. static void reset_per_request_attributes(struct mg_connection *conn)
  5302. {
  5303. conn->path_info = NULL;
  5304. conn->num_bytes_sent = conn->consumed_content = 0;
  5305. conn->status_code = -1;
  5306. conn->must_close = conn->request_len = conn->throttle = 0;
  5307. }
  5308. static void close_socket_gracefully(struct mg_connection *conn)
  5309. {
  5310. #if defined(_WIN32)
  5311. char buf[MG_BUF_LEN];
  5312. int n;
  5313. #endif
  5314. struct linger linger;
  5315. /* Set linger option to avoid socket hanging out after close. This prevent
  5316. ephemeral port exhaust problem under high QPS. */
  5317. linger.l_onoff = 1;
  5318. linger.l_linger = 1;
  5319. if (setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,
  5320. (char *) &linger, sizeof(linger)) != 0) {
  5321. mg_cry(conn, "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  5322. __func__, strerror(ERRNO));
  5323. }
  5324. /* Send FIN to the client */
  5325. shutdown(conn->client.sock, SHUT_WR);
  5326. set_non_blocking_mode(conn->client.sock);
  5327. #if defined(_WIN32)
  5328. /* Read and discard pending incoming data. If we do not do that and close
  5329. the socket, the data in the send buffer may be discarded. This
  5330. behaviour is seen on Windows, when client keeps sending data
  5331. when server decides to close the connection; then when client
  5332. does recv() it gets no data back. */
  5333. do {
  5334. n = pull(NULL, conn, buf, sizeof(buf));
  5335. } while (n > 0);
  5336. #endif
  5337. /* Now we know that our FIN is ACK-ed, safe to close */
  5338. closesocket(conn->client.sock);
  5339. conn->client.sock = INVALID_SOCKET;
  5340. }
  5341. static void close_connection(struct mg_connection *conn)
  5342. {
  5343. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  5344. if (conn->lua_websocket_state) {
  5345. lua_websocket_close(conn);
  5346. }
  5347. #endif
  5348. /* call the connection_close callback if assigned */
  5349. if (conn->ctx->callbacks.connection_close != NULL)
  5350. conn->ctx->callbacks.connection_close(conn);
  5351. mg_lock(conn);
  5352. conn->must_close = 1;
  5353. #ifndef NO_SSL
  5354. if (conn->ssl != NULL) {
  5355. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  5356. SSL_shutdown(conn->ssl);
  5357. SSL_free(conn->ssl);
  5358. conn->ssl = NULL;
  5359. }
  5360. #endif
  5361. if (conn->client.sock != INVALID_SOCKET) {
  5362. close_socket_gracefully(conn);
  5363. conn->client.sock = INVALID_SOCKET;
  5364. }
  5365. mg_unlock(conn);
  5366. }
  5367. void mg_close_connection(struct mg_connection *conn)
  5368. {
  5369. #ifndef NO_SSL
  5370. if (conn->client_ssl_ctx != NULL) {
  5371. SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);
  5372. }
  5373. #endif
  5374. close_connection(conn);
  5375. (void) pthread_mutex_destroy(&conn->mutex);
  5376. mg_free(conn);
  5377. }
  5378. struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
  5379. char *ebuf, size_t ebuf_len)
  5380. {
  5381. static struct mg_context fake_ctx;
  5382. struct mg_connection *conn = NULL;
  5383. SOCKET sock;
  5384. if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf,
  5385. ebuf_len)) == INVALID_SOCKET) {
  5386. } else if ((conn = (struct mg_connection *)
  5387. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  5388. snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
  5389. closesocket(sock);
  5390. sock = INVALID_SOCKET;
  5391. #ifndef NO_SSL
  5392. } else if (use_ssl && (conn->client_ssl_ctx =
  5393. SSL_CTX_new(SSLv23_client_method())) == NULL) {
  5394. snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
  5395. closesocket(sock);
  5396. sock = INVALID_SOCKET;
  5397. mg_free(conn);
  5398. conn = NULL;
  5399. #endif /* NO_SSL */
  5400. } else {
  5401. socklen_t len = sizeof(struct sockaddr);
  5402. conn->buf_size = MAX_REQUEST_SIZE;
  5403. conn->buf = (char *) (conn + 1);
  5404. conn->ctx = &fake_ctx;
  5405. conn->client.sock = sock;
  5406. if (getsockname(sock, &conn->client.rsa.sa, &len) != 0) {
  5407. mg_cry(conn, "%s: getsockname() failed: %s",
  5408. __func__, strerror(ERRNO));
  5409. }
  5410. conn->client.is_ssl = use_ssl;
  5411. (void) pthread_mutex_init(&conn->mutex, NULL);
  5412. #ifndef NO_SSL
  5413. if (use_ssl) {
  5414. /* SSL_CTX_set_verify call is needed to switch off server
  5415. certificate checking, which is off by default in OpenSSL and on
  5416. in yaSSL. */
  5417. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  5418. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  5419. }
  5420. #endif
  5421. }
  5422. return conn;
  5423. }
  5424. static int is_valid_uri(const char *uri)
  5425. {
  5426. /* Conform to
  5427. http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  5428. URI can be an asterisk (*) or should start with slash. */
  5429. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  5430. }
  5431. static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len)
  5432. {
  5433. const char *cl;
  5434. ebuf[0] = '\0';
  5435. reset_per_request_attributes(conn);
  5436. conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
  5437. &conn->data_len);
  5438. assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  5439. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  5440. snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
  5441. } else if (conn->request_len <= 0) {
  5442. snprintf(ebuf, ebuf_len, "%s", "Client closed connection");
  5443. } else if (parse_http_message(conn->buf, conn->buf_size,
  5444. &conn->request_info) <= 0) {
  5445. snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);
  5446. } else {
  5447. /* Message is a valid request or response */
  5448. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  5449. /* Request/response has content length set */
  5450. conn->content_len = strtoll(cl, NULL, 10);
  5451. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  5452. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  5453. /* POST or PUT request without content length set */
  5454. conn->content_len = -1;
  5455. } else if (!mg_strncasecmp(conn->request_info.request_method, "HTTP/", 5)) {
  5456. /* Response without content length set */
  5457. conn->content_len = -1;
  5458. } else {
  5459. /* Other request */
  5460. conn->content_len = 0;
  5461. }
  5462. conn->birth_time = time(NULL);
  5463. }
  5464. return ebuf[0] == '\0';
  5465. }
  5466. struct mg_connection *mg_download(const char *host, int port, int use_ssl,
  5467. char *ebuf, size_t ebuf_len,
  5468. const char *fmt, ...)
  5469. {
  5470. struct mg_connection *conn;
  5471. va_list ap;
  5472. va_start(ap, fmt);
  5473. ebuf[0] = '\0';
  5474. if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {
  5475. } else if (mg_vprintf(conn, fmt, ap) <= 0) {
  5476. snprintf(ebuf, ebuf_len, "%s", "Error sending request");
  5477. } else {
  5478. getreq(conn, ebuf, ebuf_len);
  5479. }
  5480. if (ebuf[0] != '\0' && conn != NULL) {
  5481. mg_close_connection(conn);
  5482. conn = NULL;
  5483. }
  5484. va_end(ap);
  5485. return conn;
  5486. }
  5487. static void process_new_connection(struct mg_connection *conn)
  5488. {
  5489. struct mg_request_info *ri = &conn->request_info;
  5490. int keep_alive_enabled, keep_alive, discard_len;
  5491. char ebuf[100];
  5492. keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  5493. keep_alive = 0;
  5494. /* Important: on new connection, reset the receiving buffer. Credit goes
  5495. to crule42. */
  5496. conn->data_len = 0;
  5497. do {
  5498. if (!getreq(conn, ebuf, sizeof(ebuf))) {
  5499. send_http_error(conn, 500, "Server Error", "%s", ebuf);
  5500. conn->must_close = 1;
  5501. } else if (!is_valid_uri(conn->request_info.uri)) {
  5502. snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
  5503. send_http_error(conn, 400, "Bad Request", "%s", ebuf);
  5504. } else if (strcmp(ri->http_version, "1.0") &&
  5505. strcmp(ri->http_version, "1.1")) {
  5506. snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version);
  5507. send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf);
  5508. }
  5509. if (ebuf[0] == '\0') {
  5510. handle_request(conn);
  5511. if (conn->ctx->callbacks.end_request != NULL) {
  5512. conn->ctx->callbacks.end_request(conn, conn->status_code);
  5513. }
  5514. log_access(conn);
  5515. }
  5516. if (ri->remote_user != NULL) {
  5517. mg_free((void *) ri->remote_user);
  5518. /* Important! When having connections with and without auth
  5519. would cause double free and then crash */
  5520. ri->remote_user = NULL;
  5521. }
  5522. /* NOTE(lsm): order is important here. should_keep_alive() call is
  5523. using parsed request, which will be invalid after memmove's below.
  5524. Therefore, memorize should_keep_alive() result now for later use
  5525. in loop exit condition. */
  5526. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  5527. conn->content_len >= 0 && should_keep_alive(conn);
  5528. /* Discard all buffered data for this request */
  5529. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  5530. conn->request_len + conn->content_len < (int64_t) conn->data_len ?
  5531. (int) (conn->request_len + conn->content_len) : conn->data_len;
  5532. assert(discard_len >= 0);
  5533. memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);
  5534. conn->data_len -= discard_len;
  5535. assert(conn->data_len >= 0);
  5536. assert(conn->data_len <= conn->buf_size);
  5537. } while (keep_alive);
  5538. }
  5539. /* Worker threads take accepted socket from the queue */
  5540. static int consume_socket(struct mg_context *ctx, struct socket *sp)
  5541. {
  5542. (void) pthread_mutex_lock(&ctx->mutex);
  5543. DEBUG_TRACE("going idle");
  5544. /* If the queue is empty, wait. We're idle at this point. */
  5545. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  5546. pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
  5547. }
  5548. /* If we're stopping, sq_head may be equal to sq_tail. */
  5549. if (ctx->sq_head > ctx->sq_tail) {
  5550. /* Copy socket from the queue and increment tail */
  5551. *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
  5552. ctx->sq_tail++;
  5553. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  5554. /* Wrap pointers if needed */
  5555. while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
  5556. ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
  5557. ctx->sq_head -= ARRAY_SIZE(ctx->queue);
  5558. }
  5559. }
  5560. (void) pthread_cond_signal(&ctx->sq_empty);
  5561. (void) pthread_mutex_unlock(&ctx->mutex);
  5562. return !ctx->stop_flag;
  5563. }
  5564. static void *worker_thread_run(void *thread_func_param)
  5565. {
  5566. struct mg_context *ctx = (struct mg_context *) thread_func_param;
  5567. struct mg_connection *conn;
  5568. struct mg_workerTLS tls;
  5569. tls.is_master = 0;
  5570. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5571. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  5572. #endif
  5573. conn = (struct mg_connection *) mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  5574. if (conn == NULL) {
  5575. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  5576. } else {
  5577. pthread_setspecific(sTlsKey, &tls);
  5578. conn->buf_size = MAX_REQUEST_SIZE;
  5579. conn->buf = (char *) (conn + 1);
  5580. conn->ctx = ctx;
  5581. conn->request_info.user_data = ctx->user_data;
  5582. /* Allocate a mutex for this connection to allow communication both
  5583. within the request handler and from elsewhere in the application */
  5584. (void) pthread_mutex_init(&conn->mutex, NULL);
  5585. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  5586. signal sq_empty condvar to wake up the master waiting in
  5587. produce_socket() */
  5588. while (consume_socket(ctx, &conn->client)) {
  5589. conn->birth_time = time(NULL);
  5590. /* Fill in IP, port info early so even if SSL setup below fails,
  5591. error handler would have the corresponding info.
  5592. Thanks to Johannes Winkelmann for the patch.
  5593. TODO(lsm): Fix IPv6 case */
  5594. conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
  5595. memcpy(&conn->request_info.remote_ip,
  5596. &conn->client.rsa.sin.sin_addr.s_addr, 4);
  5597. conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
  5598. conn->request_info.is_ssl = conn->client.is_ssl;
  5599. if (!conn->client.is_ssl
  5600. #ifndef NO_SSL
  5601. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  5602. #endif
  5603. ) {
  5604. process_new_connection(conn);
  5605. }
  5606. close_connection(conn);
  5607. }
  5608. }
  5609. /* Signal master that we're done with connection and exiting */
  5610. (void) pthread_mutex_lock(&ctx->mutex);
  5611. ctx->num_threads--;
  5612. (void) pthread_cond_signal(&ctx->cond);
  5613. assert(ctx->num_threads >= 0);
  5614. (void) pthread_mutex_unlock(&ctx->mutex);
  5615. pthread_setspecific(sTlsKey, 0);
  5616. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5617. CloseHandle(tls.pthread_cond_helper_mutex);
  5618. #endif
  5619. mg_free(conn);
  5620. DEBUG_TRACE("exiting");
  5621. return NULL;
  5622. }
  5623. /* Threads have different return types on Windows and Unix. */
  5624. #ifdef _WIN32
  5625. static unsigned __stdcall worker_thread(void *thread_func_param)
  5626. {
  5627. worker_thread_run(thread_func_param);
  5628. return 0;
  5629. }
  5630. #else
  5631. static void *worker_thread(void *thread_func_param)
  5632. {
  5633. worker_thread_run(thread_func_param);
  5634. return NULL;
  5635. }
  5636. #endif /* _WIN32 */
  5637. /* Master thread adds accepted socket to a queue */
  5638. static void produce_socket(struct mg_context *ctx, const struct socket *sp)
  5639. {
  5640. (void) pthread_mutex_lock(&ctx->mutex);
  5641. /* If the queue is full, wait */
  5642. while (ctx->stop_flag == 0 &&
  5643. ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
  5644. (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
  5645. }
  5646. if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
  5647. /* Copy socket to the queue and increment head */
  5648. ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
  5649. ctx->sq_head++;
  5650. DEBUG_TRACE("queued socket %d", sp->sock);
  5651. }
  5652. (void) pthread_cond_signal(&ctx->sq_full);
  5653. (void) pthread_mutex_unlock(&ctx->mutex);
  5654. }
  5655. static int set_sock_timeout(SOCKET sock, int milliseconds)
  5656. {
  5657. #ifdef _WIN32
  5658. DWORD t = milliseconds;
  5659. #else
  5660. struct timeval t;
  5661. t.tv_sec = milliseconds / 1000;
  5662. t.tv_usec = (milliseconds * 1000) % 1000000;
  5663. #endif
  5664. return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *) &t, sizeof(t)) ||
  5665. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *) &t, sizeof(t));
  5666. }
  5667. static void accept_new_connection(const struct socket *listener,
  5668. struct mg_context *ctx)
  5669. {
  5670. struct socket so;
  5671. char src_addr[IP_ADDR_STR_LEN];
  5672. socklen_t len = sizeof(so.rsa);
  5673. int on = 1;
  5674. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {
  5675. } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {
  5676. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  5677. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  5678. closesocket(so.sock);
  5679. so.sock = INVALID_SOCKET;
  5680. } else {
  5681. /* Put so socket structure into the queue */
  5682. DEBUG_TRACE("Accepted socket %d", (int) so.sock);
  5683. set_close_on_exec(so.sock, fc(ctx));
  5684. so.is_ssl = listener->is_ssl;
  5685. so.ssl_redir = listener->ssl_redir;
  5686. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  5687. mg_cry(fc(ctx), "%s: getsockname() failed: %s",
  5688. __func__, strerror(ERRNO));
  5689. }
  5690. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  5691. is enabled, and client resets the connection, server won't get
  5692. TCP FIN or RST and will keep the connection open forever. With TCP
  5693. keep-alive, next keep-alive handshake will figure out that the
  5694. client is down and will close the server end.
  5695. Thanks to Igor Klopov who suggested the patch. */
  5696. if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
  5697. sizeof(on)) != 0) {
  5698. mg_cry(fc(ctx),
  5699. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  5700. __func__, strerror(ERRNO));
  5701. }
  5702. set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));
  5703. produce_socket(ctx, &so);
  5704. }
  5705. }
  5706. static void master_thread_run(void *thread_func_param)
  5707. {
  5708. struct mg_context *ctx = (struct mg_context *) thread_func_param;
  5709. struct mg_workerTLS tls;
  5710. struct pollfd *pfd;
  5711. int i;
  5712. int workerthreadcount;
  5713. /* Increase priority of the master thread */
  5714. #if defined(_WIN32)
  5715. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  5716. #elif defined(USE_MASTER_THREAD_PRIORITY)
  5717. int min_prio = sched_get_priority_min(SCHED_RR);
  5718. int max_prio = sched_get_priority_max(SCHED_RR);
  5719. if ((min_prio >=0) && (max_prio >= 0) &&
  5720. ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
  5721. ((USE_MASTER_THREAD_PRIORITY) >= min_prio)
  5722. ) {
  5723. struct sched_param sched_param = {0};
  5724. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  5725. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  5726. }
  5727. #endif
  5728. /* Initialize thread local storage */
  5729. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5730. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  5731. #endif
  5732. tls.is_master = 1;
  5733. pthread_setspecific(sTlsKey, &tls);
  5734. /* Server starts *now* */
  5735. ctx->start_time = (unsigned long)time(NULL);
  5736. /* Allocate memory for the listening sockets, and start the server */
  5737. pfd = (struct pollfd *) mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  5738. while (pfd != NULL && ctx->stop_flag == 0) {
  5739. for (i = 0; i < ctx->num_listening_sockets; i++) {
  5740. pfd[i].fd = ctx->listening_sockets[i].sock;
  5741. pfd[i].events = POLLIN;
  5742. }
  5743. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  5744. for (i = 0; i < ctx->num_listening_sockets; i++) {
  5745. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  5746. successful poll, and POLLIN is defined as
  5747. (POLLRDNORM | POLLRDBAND)
  5748. Therefore, we're checking pfd[i].revents & POLLIN, not
  5749. pfd[i].revents == POLLIN. */
  5750. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  5751. accept_new_connection(&ctx->listening_sockets[i], ctx);
  5752. }
  5753. }
  5754. }
  5755. }
  5756. mg_free(pfd);
  5757. DEBUG_TRACE("stopping workers");
  5758. /* Stop signal received: somebody called mg_stop. Quit. */
  5759. close_all_listening_sockets(ctx);
  5760. /* Wakeup workers that are waiting for connections to handle. */
  5761. pthread_cond_broadcast(&ctx->sq_full);
  5762. /* Wait until all threads finish */
  5763. (void) pthread_mutex_lock(&ctx->mutex);
  5764. while (ctx->num_threads > 0) {
  5765. (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
  5766. }
  5767. (void) pthread_mutex_unlock(&ctx->mutex);
  5768. /* Join all worker threads to avoid leaking threads. */
  5769. workerthreadcount = ctx->workerthreadcount;
  5770. for (i = 0; i < workerthreadcount; i++) {
  5771. mg_join_thread(ctx->workerthreadids[i]);
  5772. }
  5773. #if !defined(NO_SSL)
  5774. uninitialize_ssl(ctx);
  5775. #endif
  5776. DEBUG_TRACE("exiting");
  5777. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5778. CloseHandle(tls.pthread_cond_helper_mutex);
  5779. #endif
  5780. pthread_setspecific(sTlsKey, 0);
  5781. /* Signal mg_stop() that we're done.
  5782. WARNING: This must be the very last thing this
  5783. thread does, as ctx becomes invalid after this line. */
  5784. ctx->stop_flag = 2;
  5785. }
  5786. /* Threads have different return types on Windows and Unix. */
  5787. #ifdef _WIN32
  5788. static unsigned __stdcall master_thread(void *thread_func_param)
  5789. {
  5790. master_thread_run(thread_func_param);
  5791. return 0;
  5792. }
  5793. #else
  5794. static void *master_thread(void *thread_func_param)
  5795. {
  5796. master_thread_run(thread_func_param);
  5797. return NULL;
  5798. }
  5799. #endif /* _WIN32 */
  5800. static void free_context(struct mg_context *ctx)
  5801. {
  5802. int i;
  5803. struct mg_request_handler_info *tmp_rh;
  5804. if (ctx == NULL)
  5805. return;
  5806. /* All threads exited, no sync is needed. Destroy mutex and condvars */
  5807. (void) pthread_mutex_destroy(&ctx->mutex);
  5808. (void) pthread_cond_destroy(&ctx->cond);
  5809. (void) pthread_cond_destroy(&ctx->sq_empty);
  5810. (void) pthread_cond_destroy(&ctx->sq_full);
  5811. /* Deallocate config parameters */
  5812. for (i = 0; i < NUM_OPTIONS; i++) {
  5813. if (ctx->config[i] != NULL)
  5814. #ifdef WIN32
  5815. #pragma warning(suppress: 6001)
  5816. #endif
  5817. mg_free(ctx->config[i]);
  5818. }
  5819. /* Deallocate request handlers */
  5820. while (ctx->request_handlers) {
  5821. tmp_rh = ctx->request_handlers;
  5822. ctx->request_handlers = tmp_rh->next;
  5823. mg_free(tmp_rh->uri);
  5824. mg_free(tmp_rh);
  5825. }
  5826. #ifndef NO_SSL
  5827. /* Deallocate SSL context */
  5828. if (ctx->ssl_ctx != NULL) {
  5829. SSL_CTX_free(ctx->ssl_ctx);
  5830. }
  5831. if (ssl_mutexes != NULL) {
  5832. mg_free(ssl_mutexes);
  5833. ssl_mutexes = NULL;
  5834. }
  5835. #endif /* !NO_SSL */
  5836. /* Deallocate worker thread ID array */
  5837. if (ctx->workerthreadids != NULL) {
  5838. mg_free(ctx->workerthreadids);
  5839. }
  5840. /* Deallocate the tls variable */
  5841. sTlsInit--;
  5842. if (sTlsInit==0) {
  5843. pthread_key_delete(sTlsKey);
  5844. }
  5845. /* deallocate system name string */
  5846. mg_free(ctx->systemName);
  5847. /* Deallocate context itself */
  5848. mg_free(ctx);
  5849. }
  5850. void mg_stop(struct mg_context *ctx)
  5851. {
  5852. ctx->stop_flag = 1;
  5853. /* Wait until mg_fini() stops */
  5854. while (ctx->stop_flag != 2) {
  5855. (void) mg_sleep(10);
  5856. }
  5857. mg_join_thread(ctx->masterthreadid);
  5858. free_context(ctx);
  5859. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5860. (void) WSACleanup();
  5861. #endif /* _WIN32 && !__SYMBIAN32__ */
  5862. }
  5863. void get_system_name(char **sysName)
  5864. {
  5865. #if defined(_WIN32)
  5866. #if !defined(__SYMBIAN32__)
  5867. char name[128];
  5868. DWORD dwVersion = 0;
  5869. DWORD dwMajorVersion = 0;
  5870. DWORD dwMinorVersion = 0;
  5871. DWORD dwBuild = 0;
  5872. dwVersion = GetVersion();
  5873. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  5874. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  5875. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  5876. sprintf(name, "Windows %d.%d", dwMajorVersion, dwMinorVersion);
  5877. *sysName = mg_strdup(name);
  5878. #else
  5879. *sysName = mg_strdup("Symbian");
  5880. #endif
  5881. #else
  5882. struct utsname name;
  5883. memset(&name, 0, sizeof(name));
  5884. uname(&name);
  5885. *sysName = mg_strdup(name.sysname);
  5886. #endif
  5887. }
  5888. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  5889. void *user_data,
  5890. const char **options)
  5891. {
  5892. struct mg_context *ctx;
  5893. const char *name, *value, *default_value;
  5894. int i;
  5895. int workerthreadcount;
  5896. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5897. WSADATA data;
  5898. WSAStartup(MAKEWORD(2,2), &data);
  5899. #pragma warning(suppress: 28125)
  5900. InitializeCriticalSection(&global_log_file_lock);
  5901. #endif /* _WIN32 && !__SYMBIAN32__ */
  5902. /* Check if the config_options and the corresponding enum have compatible sizes. */
  5903. /* Could use static_assert, once it is verified that all compilers support this. */
  5904. assert(sizeof(config_options)/sizeof(config_options[0]) == NUM_OPTIONS+1);
  5905. /* Allocate context and initialize reasonable general case defaults.
  5906. TODO(lsm): do proper error handling here. */
  5907. if ((ctx = (struct mg_context *) mg_calloc(1, sizeof(*ctx))) == NULL) {
  5908. return NULL;
  5909. }
  5910. if (sTlsInit==0) {
  5911. if (0 != pthread_key_create(&sTlsKey, NULL)) {
  5912. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  5913. mg_free(ctx);
  5914. return NULL;
  5915. }
  5916. sTlsInit++;
  5917. }
  5918. if (callbacks) {
  5919. ctx->callbacks = *callbacks;
  5920. }
  5921. ctx->user_data = user_data;
  5922. ctx->request_handlers = 0;
  5923. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  5924. ctx->shared_lua_websockets = 0;
  5925. #endif
  5926. while (options && (name = *options++) != NULL) {
  5927. if ((i = get_option_index(name)) == -1) {
  5928. mg_cry(fc(ctx), "Invalid option: %s", name);
  5929. free_context(ctx);
  5930. return NULL;
  5931. } else if ((value = *options++) == NULL) {
  5932. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  5933. free_context(ctx);
  5934. return NULL;
  5935. }
  5936. if (ctx->config[i] != NULL) {
  5937. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  5938. mg_free(ctx->config[i]);
  5939. }
  5940. ctx->config[i] = mg_strdup(value);
  5941. DEBUG_TRACE("[%s] -> [%s]", name, value);
  5942. }
  5943. /* Set default value if needed */
  5944. for (i = 0; config_options[i].name != NULL; i++) {
  5945. default_value = config_options[i].default_value;
  5946. if (ctx->config[i] == NULL && default_value != NULL) {
  5947. ctx->config[i] = mg_strdup(default_value);
  5948. }
  5949. }
  5950. get_system_name(&ctx->systemName);
  5951. /* NOTE(lsm): order is important here. SSL certificates must
  5952. be initialized before listening ports. UID must be set last. */
  5953. if (!set_gpass_option(ctx) ||
  5954. #if !defined(NO_SSL)
  5955. !set_ssl_option(ctx) ||
  5956. #endif
  5957. !set_ports_option(ctx) ||
  5958. #if !defined(_WIN32)
  5959. !set_uid_option(ctx) ||
  5960. #endif
  5961. !set_acl_option(ctx)) {
  5962. free_context(ctx);
  5963. return NULL;
  5964. }
  5965. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  5966. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  5967. won't kill the whole process. */
  5968. (void) signal(SIGPIPE, SIG_IGN);
  5969. #endif /* !_WIN32 && !__SYMBIAN32__ */
  5970. (void) pthread_mutex_init(&ctx->mutex, NULL);
  5971. (void) pthread_cond_init(&ctx->cond, NULL);
  5972. (void) pthread_cond_init(&ctx->sq_empty, NULL);
  5973. (void) pthread_cond_init(&ctx->sq_full, NULL);
  5974. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  5975. if (workerthreadcount > MAX_WORKER_THREADS) {
  5976. mg_cry(fc(ctx), "Too many worker threads");
  5977. free_context(ctx);
  5978. return NULL;
  5979. }
  5980. if (workerthreadcount > 0) {
  5981. ctx->workerthreadcount = workerthreadcount;
  5982. ctx->workerthreadids = mg_calloc(workerthreadcount, sizeof(pthread_t));
  5983. if (ctx->workerthreadids == NULL) {
  5984. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  5985. free_context(ctx);
  5986. return NULL;
  5987. }
  5988. }
  5989. /* Start master (listening) thread */
  5990. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  5991. /* Start worker threads */
  5992. for (i = 0; i < workerthreadcount; i++) {
  5993. (void) pthread_mutex_lock(&ctx->mutex);
  5994. ctx->num_threads++;
  5995. (void) pthread_mutex_unlock(&ctx->mutex);
  5996. if (mg_start_thread_with_id(worker_thread, ctx,
  5997. &ctx->workerthreadids[i]) != 0) {
  5998. (void) pthread_mutex_lock(&ctx->mutex);
  5999. ctx->num_threads--;
  6000. (void) pthread_mutex_unlock(&ctx->mutex);
  6001. mg_cry(fc(ctx), "Cannot start worker thread: %ld", (long) ERRNO);
  6002. }
  6003. }
  6004. return ctx;
  6005. }