civetweb.c 278 KB

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