mongoose.c 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578
  1. // Copyright (c) 2004-2012 Sergey Lyubka
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #if defined(_WIN32)
  21. #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
  22. #else
  23. #ifdef __linux__
  24. #define _XOPEN_SOURCE 600 // For flockfile() on Linux
  25. #endif
  26. #define _LARGEFILE_SOURCE // Enable 64-bit file offsets
  27. #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
  28. #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX
  29. #endif
  30. #ifdef WIN32_LEAN_AND_MEAN
  31. #undef WIN32_LEAN_AND_MEAN // Disable WIN32_LEAN_AND_MEAN, if necessary
  32. #endif
  33. #if defined(__SYMBIAN32__)
  34. #define NO_SSL // SSL is not supported
  35. #define NO_CGI // CGI is not supported
  36. #define PATH_MAX FILENAME_MAX
  37. #endif // __SYMBIAN32__
  38. #ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE
  39. #include <sys/types.h>
  40. #include <sys/stat.h>
  41. #include <errno.h>
  42. #include <signal.h>
  43. #include <fcntl.h>
  44. #endif // !_WIN32_WCE
  45. #include <time.h>
  46. #include <stdlib.h>
  47. #include <stdarg.h>
  48. #include <assert.h>
  49. #include <string.h>
  50. #include <ctype.h>
  51. #include <limits.h>
  52. #include <stddef.h>
  53. #include <stdio.h>
  54. //#include "duma.h"
  55. #if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific
  56. #ifndef __MINGW32__
  57. #define _WIN32_WINNT 0x0400 // To make it link in VS2005
  58. #endif
  59. #include <windows.h>
  60. #ifndef PATH_MAX
  61. #define PATH_MAX MAX_PATH
  62. #endif
  63. #ifndef _WIN32_WCE
  64. #include <process.h>
  65. #include <direct.h>
  66. #include <io.h>
  67. typedef const char *SOCK_OPT_TYPE;
  68. #else // _WIN32_WCE
  69. #include <winsock2.h>
  70. #include <ws2tcpip.h>
  71. typedef const char *SOCK_OPT_TYPE;
  72. #ifdef __GNUC__
  73. #include <malloc.h>
  74. #endif
  75. #define NO_CGI // WinCE has no pipes
  76. typedef long off_t;
  77. #ifndef BUFSIZ
  78. #define BUFSIZ 4096
  79. #endif
  80. #define errno GetLastError()
  81. #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
  82. #endif // _WIN32_WCE
  83. #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
  84. ((uint64_t)((uint32_t)(hi))) << 32))
  85. #define RATE_DIFF 10000000 // 100 nsecs
  86. #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
  87. #define SYS2UNIX_TIME(lo, hi) \
  88. (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
  89. // Visual Studio 6 does not know __func__ or __FUNCTION__
  90. // The rest of MS compilers use __FUNCTION__, not C99 __func__
  91. // Also use _strtoui64 on modern M$ compilers
  92. #if defined(_MSC_VER) && _MSC_VER < 1300
  93. #define STRX(x) #x
  94. #define STR(x) STRX(x)
  95. #define __func__ __FILE__ ":" STR(__LINE__)
  96. #define strtoull(x, y, z) strtoul(x, y, z)
  97. #define strtoll(x, y, z) strtol(x, y, z)
  98. #else
  99. #define __func__ __FUNCTION__
  100. #ifndef __GNUC__
  101. #define strtoull(x, y, z) _strtoui64(x, y, z)
  102. #define strtoll(x, y, z) _strtoi64(x, y, z)
  103. #endif
  104. #endif // _MSC_VER
  105. #define ERRNO GetLastError()
  106. #define NO_SOCKLEN_T
  107. #define SSL_LIB "ssleay32.dll"
  108. #define CRYPTO_LIB "libeay32.dll"
  109. #define DIRSEP '\\'
  110. #define IS_DIRSEP_CHAR(c) ((c) == '/' || (c) == '\\')
  111. #define O_NONBLOCK 0
  112. #if !defined(EWOULDBLOCK)
  113. #define EWOULDBLOCK WSAEWOULDBLOCK
  114. #endif // !EWOULDBLOCK
  115. #define _POSIX_
  116. #define INT64_FMT "I64d"
  117. #define WINCDECL __cdecl
  118. #define SHUT_WR 1
  119. #define snprintf _snprintf
  120. #define vsnprintf _vsnprintf
  121. #define mg_sleep(x) Sleep(x)
  122. #define pipe(x) _pipe(x, BUFSIZ, _O_BINARY)
  123. #ifndef popen
  124. #define popen(x, y) _popen(x, y)
  125. #define pclose(x) _pclose(x)
  126. #endif
  127. #define close(x) _close(x)
  128. #ifdef _WIN32_WCE
  129. #define dlsym(x,y) GetProcAddressA((HINSTANCE) (x), (y))
  130. #else
  131. #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
  132. #endif
  133. #define RTLD_LAZY 0
  134. #ifndef fseeko
  135. //#define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
  136. #define fseeko(x, y, z) fseek((x), (y), (z))
  137. #endif
  138. #define fdopen(x, y) _fdopen((x), (y))
  139. #define write(x, y, z) _write((x), (y), (unsigned) z)
  140. #define read(x, y, z) _read((x), (y), (unsigned) z)
  141. #define flockfile(x) EnterCriticalSection(&global_log_file_lock)
  142. #define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
  143. #if !defined(fileno)
  144. #define fileno(x) _fileno(x)
  145. #endif // !fileno MINGW #defines fileno
  146. typedef HANDLE pthread_mutex_t;
  147. typedef struct {HANDLE signal, broadcast;} pthread_cond_t;
  148. typedef DWORD pthread_t;
  149. #define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.
  150. #ifndef __MINGW32__
  151. struct timespec {
  152. long tv_nsec;
  153. long tv_sec;
  154. };
  155. #endif
  156. static int pthread_mutex_lock(pthread_mutex_t *);
  157. static int pthread_mutex_unlock(pthread_mutex_t *);
  158. static FILE *mg_fopen(const char *path, const char *mode);
  159. #if defined(HAVE_STDINT)
  160. #include <stdint.h>
  161. #else
  162. typedef unsigned int uint32_t;
  163. typedef unsigned short uint16_t;
  164. typedef unsigned __int64 uint64_t;
  165. typedef __int64 int64_t;
  166. #endif // HAVE_STDINT
  167. // POSIX dirent interface
  168. struct dirent {
  169. char d_name[PATH_MAX];
  170. };
  171. typedef struct DIR {
  172. HANDLE handle;
  173. WIN32_FIND_DATAW info;
  174. struct dirent result;
  175. } DIR;
  176. // Mark required libraries
  177. #ifdef _MSC_VER
  178. #pragma comment(lib, "Ws2_32.lib")
  179. #endif
  180. #else // UNIX specific
  181. #include <sys/wait.h>
  182. #include <sys/socket.h>
  183. #include <sys/select.h>
  184. #include <netinet/in.h>
  185. #include <arpa/inet.h>
  186. #include <sys/time.h>
  187. #include <stdint.h>
  188. #include <inttypes.h>
  189. #include <netdb.h>
  190. #include <netinet/tcp.h>
  191. typedef const void *SOCK_OPT_TYPE;
  192. #include <pwd.h>
  193. #include <unistd.h>
  194. #include <dirent.h>
  195. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  196. #include <dlfcn.h>
  197. #endif
  198. #include <pthread.h>
  199. #if defined(__MACH__)
  200. #define SSL_LIB "libssl.dylib"
  201. #define CRYPTO_LIB "libcrypto.dylib"
  202. #else
  203. #if !defined(SSL_LIB)
  204. #define SSL_LIB "libssl.so"
  205. #endif
  206. #if !defined(CRYPTO_LIB)
  207. #define CRYPTO_LIB "libcrypto.so"
  208. #endif
  209. #endif
  210. #define DIRSEP '/'
  211. #define IS_DIRSEP_CHAR(c) ((c) == '/')
  212. #ifndef O_BINARY
  213. #define O_BINARY 0
  214. #endif // O_BINARY
  215. #define closesocket(a) close(a)
  216. #define mg_fopen(x, y) fopen(x, y)
  217. #define mg_mkdir(x, y) mkdir(x, y)
  218. #define mg_remove(x) remove(x)
  219. #define mg_rename(x, y) rename(x, y)
  220. #define mg_sleep(x) usleep((x) * 1000)
  221. #define ERRNO errno
  222. #define INVALID_SOCKET (-1)
  223. #define INT64_FMT PRId64
  224. typedef int SOCKET;
  225. #define WINCDECL
  226. #endif // End of Windows and UNIX specific includes
  227. #ifndef SOCKET_TIMEOUT_QUANTUM
  228. #define SOCKET_TIMEOUT_QUANTUM (10000)
  229. #endif
  230. #ifndef INT64_MAX
  231. #define INT64_MAX 9223372036854775807
  232. #endif
  233. #define ON_MONGOOSE_SRC
  234. #include "mongoose.h"
  235. #define MONGOOSE_VERSION "3.4"
  236. #define PASSWORDS_FILE_NAME ".htpasswd"
  237. #define CGI_ENVIRONMENT_SIZE 4096
  238. #define MAX_CGI_ENVIR_VARS 64
  239. #define MG_BUF_LEN 8192
  240. //#define MAX_REQUEST_SIZE 16384
  241. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  242. #ifdef _WIN32
  243. static CRITICAL_SECTION global_log_file_lock;
  244. static pthread_t pthread_self(void) {
  245. return GetCurrentThreadId();
  246. }
  247. #endif // _WIN32
  248. #ifdef DEBUG_TRACE
  249. #undef DEBUG_TRACE
  250. #define DEBUG_TRACE(x)
  251. #else
  252. #if defined(DEBUG) || defined(MG_DEBUG)
  253. #define DEBUG_TRACE(x) do { \
  254. flockfile(stdout); \
  255. printf("*** %lu.%p.%s.%d: ", \
  256. (unsigned long) time(NULL), (void *) pthread_self(), \
  257. __func__, __LINE__); \
  258. printf x; \
  259. putchar('\n'); \
  260. fflush(stdout); \
  261. funlockfile(stdout); \
  262. } while (0)
  263. #else
  264. #define DEBUG_TRACE(x)
  265. #endif // DEBUG
  266. #endif // DEBUG_TRACE
  267. #if 0
  268. static void *mymg_malloc(size_t size, int line){
  269. void *ptr = malloc(size);
  270. printf("malloc %d : %p\n", line, ptr);
  271. return ptr;
  272. }
  273. static void *mymg_calloc(size_t count, size_t size, int line){
  274. void *ptr = calloc(count, size);
  275. printf("calloc %d : %p\n", line, ptr);
  276. return ptr;
  277. }
  278. static void *mymg_realloc(void *old, size_t size, int line){
  279. void *ptr = realloc(old, size);
  280. printf("realloc %d : %p : %p\n", line, old, ptr);
  281. return ptr;
  282. }
  283. static void *mymg_free(void *ptr, int line){
  284. free(ptr);
  285. printf("free %d : %p\n", line, ptr);
  286. return ptr;
  287. }
  288. # define MG_MALLOC(x) mymg_malloc(x, __LINE__)
  289. # define MG_CALLOC(a,b) mymg_calloc(a,b, __LINE__)
  290. # define MG_REALLOC(x, z) mymg_realloc(x, z, __LINE__)
  291. # define MG_FREE(x) mymg_free(x, __LINE__)
  292. #else
  293. # define MG_MALLOC(x) malloc(x)
  294. # define MG_CALLOC(a,b) calloc(a,b)
  295. # define MG_REALLOC(x, z) realloc(x, z)
  296. # define MG_FREE(x) free(x)
  297. #endif
  298. // Darwin prior to 7.0 and Win32 do not have socklen_t
  299. #ifdef NO_SOCKLEN_T
  300. typedef int socklen_t;
  301. #endif // NO_SOCKLEN_T
  302. #define _DARWIN_UNLIMITED_SELECT
  303. #if !defined(MSG_NOSIGNAL)
  304. #define MSG_NOSIGNAL 0
  305. #endif
  306. #if !defined(SOMAXCONN)
  307. #define SOMAXCONN 100
  308. #endif
  309. #if !defined(PATH_MAX)
  310. #define PATH_MAX 4096
  311. #endif
  312. #ifndef HAS_MG_THREAD_FUNC_DEFINED
  313. typedef void * (*mg_thread_func_t)(void *);
  314. #endif
  315. static const char *http_500_error = "Internal Server Error";
  316. // Snatched from OpenSSL includes. I put the prototypes here to be independent
  317. // from the OpenSSL source installation. Having this, mongoose + SSL can be
  318. // built on any system with binary SSL libraries installed.
  319. typedef struct ssl_st SSL;
  320. typedef struct ssl_method_st SSL_METHOD;
  321. typedef struct ssl_ctx_st SSL_CTX;
  322. #define SSL_ERROR_WANT_READ 2
  323. #define SSL_ERROR_WANT_WRITE 3
  324. #define SSL_FILETYPE_PEM 1
  325. #define CRYPTO_LOCK 1
  326. #if defined(NO_SSL_DL)
  327. extern void SSL_free(SSL *);
  328. extern int SSL_accept(SSL *);
  329. extern int SSL_connect(SSL *);
  330. extern int SSL_read(SSL *, void *, int);
  331. extern int SSL_write(SSL *, const void *, int);
  332. extern int SSL_get_error(const SSL *, int);
  333. extern int SSL_set_fd(SSL *, int);
  334. extern SSL *SSL_new(SSL_CTX *);
  335. extern SSL_CTX *SSL_CTX_new(SSL_METHOD *);
  336. extern SSL_METHOD *SSLv23_server_method(void);
  337. extern SSL_METHOD *SSLv23_client_method(void);
  338. extern int SSL_library_init(void);
  339. extern void SSL_load_error_strings(void);
  340. extern int SSL_CTX_use_PrivateKey_file(SSL_CTX *, const char *, int);
  341. extern int SSL_CTX_use_certificate_file(SSL_CTX *, const char *, int);
  342. extern int SSL_CTX_use_certificate_chain_file(SSL_CTX *, const char *);
  343. extern void SSL_CTX_set_default_passwd_cb(SSL_CTX *, mg_callback_t);
  344. extern void SSL_CTX_free(SSL_CTX *);
  345. extern unsigned long ERR_get_error(void);
  346. extern char *ERR_error_string(unsigned long, char *);
  347. extern int CRYPTO_num_locks(void);
  348. extern void CRYPTO_set_locking_callback(void (*)(int, int, const char *, int));
  349. extern void CRYPTO_set_id_callback(unsigned long (*)(void));
  350. #else
  351. // Dynamically loaded SSL functionality
  352. struct ssl_func {
  353. const char *name; // SSL function name
  354. void (*ptr)(void); // Function pointer
  355. };
  356. #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
  357. #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
  358. #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
  359. #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
  360. #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
  361. #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
  362. #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
  363. #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  364. #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  365. #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  366. #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
  367. #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
  368. const char *, int)) ssl_sw[11].ptr)
  369. #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
  370. const char *, int)) ssl_sw[12].ptr)
  371. #define SSL_CTX_set_default_passwd_cb \
  372. (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
  373. #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
  374. #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
  375. #define SSL_CTX_use_certificate_chain_file \
  376. (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
  377. #define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  378. #define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)
  379. #define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)
  380. #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
  381. #define CRYPTO_set_locking_callback \
  382. (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
  383. #define CRYPTO_set_id_callback \
  384. (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
  385. #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
  386. #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
  387. // set_ssl_option() function updates this array.
  388. // It loads SSL library dynamically and changes NULLs to the actual addresses
  389. // of respective functions. The macros above (like SSL_connect()) are really
  390. // just calling these functions indirectly via the pointer.
  391. static struct ssl_func ssl_sw[] = {
  392. {"SSL_free", NULL},
  393. {"SSL_accept", NULL},
  394. {"SSL_connect", NULL},
  395. {"SSL_read", NULL},
  396. {"SSL_write", NULL},
  397. {"SSL_get_error", NULL},
  398. {"SSL_set_fd", NULL},
  399. {"SSL_new", NULL},
  400. {"SSL_CTX_new", NULL},
  401. {"SSLv23_server_method", NULL},
  402. {"SSL_library_init", NULL},
  403. {"SSL_CTX_use_PrivateKey_file", NULL},
  404. {"SSL_CTX_use_certificate_file",NULL},
  405. {"SSL_CTX_set_default_passwd_cb",NULL},
  406. {"SSL_CTX_free", NULL},
  407. {"SSL_load_error_strings", NULL},
  408. {"SSL_CTX_use_certificate_chain_file", NULL},
  409. {"SSLv23_client_method", NULL},
  410. {"SSL_pending", NULL},
  411. {"SSL_CTX_set_verify", NULL},
  412. {NULL, NULL}
  413. };
  414. // Similar array as ssl_sw. These functions could be located in different lib.
  415. #if !defined(NO_SSL)
  416. static struct ssl_func crypto_sw[] = {
  417. {"CRYPTO_num_locks", NULL},
  418. {"CRYPTO_set_locking_callback", NULL},
  419. {"CRYPTO_set_id_callback", NULL},
  420. {"ERR_get_error", NULL},
  421. {"ERR_error_string", NULL},
  422. {NULL, NULL}
  423. };
  424. #endif // NO_SSL
  425. #endif // NO_SSL_DL
  426. static const char *month_names[] = {
  427. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  428. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  429. };
  430. // Unified socket address. For IPv6 support, add IPv6 address structure
  431. // in the union u.
  432. union usa {
  433. struct sockaddr sa;
  434. struct sockaddr_in sin;
  435. #if defined(USE_IPV6)
  436. struct sockaddr_in6 sin6;
  437. #endif
  438. };
  439. // Describes a string (chunk of memory).
  440. struct vec {
  441. const char *ptr;
  442. size_t len;
  443. };
  444. // Structure used by mg_stat() function. Uses 64 bit file length.
  445. struct mgstat {
  446. int is_directory; // Directory marker
  447. int64_t size; // File size
  448. time_t mtime; // Modification time
  449. };
  450. // Describes listening socket, or socket which was accept()-ed by the master
  451. // thread and queued for future handling by the worker thread.
  452. #define MG_FLAG_IS_SSL 0x0001
  453. #define MG_IS_SSL(flag) (flag & MG_FLAG_IS_SSL)
  454. #define MSG_SET_IS_SSL(flag, b) flag &= (b ? MG_FLAG_IS_SSL : ~MG_FLAG_IS_SSL)
  455. #define MG_FLAG_IS_PROXY 0x0002
  456. #define MG_IS_PROXY(flag) (flag & MG_FLAG_IS_PROXY)
  457. #define MSG_SET_IS_PROXY(flag, b) flag &= (b ? MG_FLAG_IS_PROXY : ~MG_FLAG_IS_PROXY)
  458. #define MG_FLAG_IS_KEEP_ALIVE 0x0004
  459. #define MG_IS_ALIVE(flag) (flag & MG_FLAG_IS_ALIVE)
  460. #define MSG_SET_IS_ALIVE(flag, b) flag &= (b ? MG_FLAG_IS_ALIVE : ~MG_FLAG_IS_ALIVE)
  461. struct socket {
  462. struct socket *next; // Linkage
  463. SOCKET sock; // Listening socket
  464. union usa lsa; // Local socket address
  465. union usa rsa; // Remote socket address
  466. int is_ssl:1; // Is socket SSL-ed
  467. unsigned ssl_redir:1; // Is port supposed to redirect everything to SSL port
  468. int is_proxy:1;
  469. //DAD using bitfield here only need on int and allow more flags
  470. //int connection_count;
  471. };
  472. // NOTE(lsm): this enum shoulds be in sync with the config_options below.
  473. enum {
  474. CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
  475. PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
  476. ACCESS_LOG_FILE, SSL_CHAIN_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
  477. GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
  478. MAX_REQUEST_SIZE,
  479. EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
  480. NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
  481. MAX_THREADS, ENABLE_TCP_NODELAY, NUM_OPTIONS
  482. };
  483. static const char *config_options[] = {
  484. "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$",
  485. "E", "cgi_environment", NULL,
  486. "G", "put_delete_passwords_file", NULL,
  487. "I", "cgi_interpreter", NULL,
  488. "P", "protect_uri", NULL,
  489. "R", "authentication_domain", "mydomain.com",
  490. "S", "ssi_pattern", "**.shtml$|**.shtm$",
  491. "T", "throttle", NULL,
  492. "a", "access_log_file", NULL,
  493. "c", "ssl_chain_file", NULL,
  494. "d", "enable_directory_listing", "yes",
  495. "e", "error_log_file", NULL,
  496. "g", "global_passwords_file", NULL,
  497. "i", "index_files", "index.html,index.htm,index.cgi,index.shtml,index.php",
  498. "k", "enable_keep_alive", "no",
  499. "l", "access_control_list", NULL,
  500. "M", "max_request_size", "16384",
  501. "m", "extra_mime_types", NULL,
  502. "p", "listening_ports", "8080",
  503. "r", "document_root", ".",
  504. "s", "ssl_certificate", NULL,
  505. "t", "num_threads", "10",
  506. "u", "run_as_user", NULL,
  507. "w", "url_rewrite_patterns", NULL,
  508. "x", "hide_files_patterns", NULL,
  509. "to", "request_timeout_ms", "30000",
  510. "MT", "max_threads", NULL,
  511. "nd", "enable_tcp_nodelay", "no",
  512. NULL
  513. };
  514. #define ENTRIES_PER_CONFIG_OPTION 3
  515. struct mg_context {
  516. volatile int stop_flag; // Should we stop event loop
  517. SSL_CTX *ssl_ctx; // SSL context
  518. SSL_CTX *client_ssl_ctx; // Client SSL context
  519. char *config[NUM_OPTIONS]; // Mongoose configuration parameters
  520. mg_callback_t user_callback; // User-defined callback function
  521. void *user_data; // User-defined data
  522. struct socket *listening_sockets;
  523. int num_listening_sockets;
  524. volatile int num_threads; // Number of threads
  525. volatile int idle_threads; // Number of inactive threads
  526. volatile int base_threads; // Number of threads to maintain when idle
  527. volatile int max_threads; // Limit on number of threads
  528. pthread_mutex_t mutex; // Protects (max|num)_threads
  529. pthread_cond_t cond; // Condvar for tracking workers terminations
  530. struct socket queue[20]; // Accepted sockets
  531. //int connection_count;
  532. volatile int sq_head; // Head of the socket queue
  533. volatile int sq_tail; // Tail of the socket queue
  534. pthread_cond_t sq_full; // Signaled when socket is produced
  535. pthread_cond_t sq_empty; // Signaled when socket is consumed
  536. void *master_plugin; // User defined master plugin
  537. pthread_mutex_t master_plugin_mutex; // Protects master_plugin_thread
  538. pthread_cond_t master_plugin_cond; // Condvar for tracking master_plugin_thread
  539. };
  540. struct mg_connection {
  541. struct mg_connection *peer; // Remote target in proxy mode
  542. struct mg_request_info request_info;
  543. struct mg_context *ctx;
  544. SSL *ssl; // SSL descriptor
  545. SSL_CTX *client_ssl_ctx; // SSL context for client connections
  546. struct socket client; // Connected client
  547. time_t birth_time; // Time when request was received
  548. int64_t num_bytes_sent; // Total bytes sent to client
  549. int64_t content_len; // Content-Length header value
  550. int64_t consumed_content; // How many bytes of content have been read
  551. char *buf; // Buffer for received data
  552. char *path_info; // PATH_INFO part of the URL
  553. char *body; // Pointer to not-read yet buffered body data
  554. char *next_request; // Pointer to the buffered next request
  555. int must_close; // 1 if connection must be closed
  556. int buf_size; // Buffer size
  557. int request_len; // Size of the request + headers in a buffer
  558. int data_len; // Total size of data in a buffer
  559. int throttle; // Throttling, bytes/sec. <= 0 means no throttle
  560. time_t last_throttle_time; // Last time throttled data was sent
  561. int64_t last_throttle_bytes;// Bytes sent this second
  562. char *auth_header; // Buffer for the Authorization header (request_info.ah points into it).
  563. void *plugin;
  564. };
  565. const char **mg_get_valid_option_names(void) {
  566. return config_options;
  567. }
  568. static void *call_user(struct mg_connection *conn, enum mg_event event) {
  569. conn->request_info.user_data = conn->ctx->user_data;
  570. return conn->ctx->user_callback == NULL ? NULL :
  571. conn->ctx->user_callback(event, conn, &conn->request_info);
  572. }
  573. void *mg_get_user_data(struct mg_connection *conn) {
  574. return conn != NULL && conn->ctx != NULL ? conn->ctx->user_data : NULL;
  575. }
  576. const char *mg_get_conn_buf(struct mg_connection *conn, int *buf_size){
  577. *buf_size = conn->buf_size;
  578. return conn->buf;
  579. }
  580. const char *mg_get_log_message(const struct mg_connection *conn) {
  581. return conn == NULL ? NULL : conn->request_info.log_message;
  582. }
  583. int mg_get_reply_status_code(const struct mg_connection *conn) {
  584. return conn == NULL ? -1 : conn->request_info.status_code;
  585. }
  586. void *mg_get_ssl_context(const struct mg_connection *conn) {
  587. return conn == NULL || conn->ctx == NULL ? NULL : conn->ctx->ssl_ctx;
  588. }
  589. static int get_option_index(const char *name) {
  590. int i;
  591. for (i = 0; config_options[i] != NULL; i += ENTRIES_PER_CONFIG_OPTION) {
  592. if (strcmp(config_options[i], name) == 0 ||
  593. strcmp(config_options[i + 1], name) == 0) {
  594. return i / ENTRIES_PER_CONFIG_OPTION;
  595. }
  596. }
  597. return -1;
  598. }
  599. const char *mg_get_option(const struct mg_context *ctx, const char *name) {
  600. int i;
  601. if ((i = get_option_index(name)) == -1) {
  602. return NULL;
  603. } else if (ctx->config[i] == NULL) {
  604. return "";
  605. } else {
  606. return ctx->config[i];
  607. }
  608. }
  609. const char *mg_get_document_root(const struct mg_connection *conn) {
  610. return conn->ctx->config[DOCUMENT_ROOT];
  611. }
  612. static void sockaddr_to_string(char *buf, size_t len,
  613. const union usa *usa) {
  614. buf[0] = '\0';
  615. #if defined(USE_IPV6)
  616. inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
  617. (void *) &usa->sin.sin_addr :
  618. (void *) &usa->sin6.sin6_addr, buf, len);
  619. #elif defined(_WIN32)
  620. // Only Windoze Vista (and newer) have inet_ntop()
  621. strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
  622. #else
  623. inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
  624. #endif
  625. }
  626. static void cry(struct mg_connection *conn,
  627. PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
  628. // Print error message to the opened error log stream.
  629. static void cry(struct mg_connection *conn, const char *fmt, ...) {
  630. char buf[MG_BUF_LEN], src_addr[20];
  631. va_list ap;
  632. FILE *fp;
  633. time_t timestamp;
  634. va_start(ap, fmt);
  635. (void) vsnprintf(buf, sizeof(buf), fmt, ap);
  636. va_end(ap);
  637. // Do not lock when getting the callback value, here and below.
  638. // I suppose this is fine, since function cannot disappear in the
  639. // same way string option can.
  640. conn->request_info.log_message = buf;
  641. if (call_user(conn, MG_EVENT_LOG) == NULL) {
  642. fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
  643. mg_fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  644. if (fp != NULL) {
  645. flockfile(fp);
  646. timestamp = time(NULL);
  647. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  648. fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
  649. src_addr);
  650. if (conn->request_info.request_method != NULL) {
  651. fprintf(fp, "%s %s: ", conn->request_info.request_method,
  652. conn->request_info.uri);
  653. }
  654. (void) fprintf(fp, "%s", buf);
  655. fputc('\n', fp);
  656. funlockfile(fp);
  657. if (fp != stderr) {
  658. fclose(fp);
  659. }
  660. }
  661. }
  662. conn->request_info.log_message = NULL;
  663. }
  664. #define MG_SSL_CREATE_CTX_ERROR -100
  665. #define MG_SSL_ALOCATE_MUTEX_ERROR -2000
  666. // Return OpenSSL error message
  667. static const char *ssl_error(int err_code) {
  668. #ifdef USE_AXTLS
  669. extern const char* ssl_get_error(int error_code, char *buf, size_t bufsize);
  670. static char buf[256];
  671. switch(err_code){
  672. case MG_SSL_CREATE_CTX_ERROR:
  673. snprintf(buf, sizeof(buf), "MG_SSL_CREATE_CTX_ERROR");
  674. return buf;
  675. break;
  676. case MG_SSL_ALOCATE_MUTEX_ERROR:
  677. snprintf(buf, sizeof(buf), "MG_SSL_ALOCATE_MUTEX_ERROR");
  678. return buf;
  679. break;
  680. }
  681. return ssl_get_error(err_code, buf, sizeof(buf));
  682. #elif !defined(NO_SSL)
  683. unsigned long err;
  684. err = ERR_get_error();
  685. return err == 0 ? "" : ERR_error_string(err, NULL);
  686. #else
  687. return "";
  688. #endif
  689. }
  690. // Return fake connection structure. Used for logging, if connection
  691. // is not applicable at the moment of logging.
  692. static struct mg_connection *fc(struct mg_context *ctx) {
  693. static struct mg_connection fake_connection;
  694. fake_connection.ctx = ctx;
  695. return &fake_connection;
  696. }
  697. const char *mg_version(void) {
  698. return MONGOOSE_VERSION;
  699. }
  700. const struct mg_request_info *
  701. mg_get_request_info(const struct mg_connection *conn) {
  702. return &conn->request_info;
  703. }
  704. static void mg_strlcpy(register char *dst, register const char *src, size_t n) {
  705. for (; *src != '\0' && n > 1; n--) {
  706. *dst++ = *src++;
  707. }
  708. *dst = '\0';
  709. }
  710. //DAD
  711. //static int lowercase(const char *s) {
  712. // return tolower(* (const unsigned char *) s);
  713. //}
  714. #define lowercase(s) tolower(* (const unsigned char *) s)
  715. int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
  716. int diff = 0;
  717. if (len > 0)
  718. do {
  719. diff = lowercase(s1++) - lowercase(s2++);
  720. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  721. return diff;
  722. }
  723. int mg_strcasecmp(const char *s1, const char *s2) {
  724. int diff;
  725. do {
  726. diff = lowercase(s1++) - lowercase(s2++);
  727. } while (diff == 0 && s1[-1] != '\0');
  728. return diff;
  729. }
  730. char * mg_strndup(const char *ptr, size_t len) {
  731. char *p;
  732. if ((p = (char *) MG_MALLOC(len + 1)) != NULL) {
  733. mg_strlcpy(p, ptr, len + 1);
  734. }
  735. return p;
  736. }
  737. char * mg_strdup(const char *str) {
  738. return mg_strndup(str, strlen(str));
  739. }
  740. static const char *mg_strcasestr(const char *big_str, const char *small_str) {
  741. int i, big_len = strlen(big_str), small_len = strlen(small_str);
  742. for (i = 0; i <= big_len - small_len; i++) {
  743. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  744. return big_str + i;
  745. }
  746. }
  747. return NULL;
  748. }
  749. // Like snprintf(), but never returns negative value, or a value
  750. // that is larger than a supplied buffer.
  751. // Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  752. // in his audit report.
  753. static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
  754. const char *fmt, va_list ap) {
  755. int n;
  756. if (buflen == 0)
  757. return 0;
  758. n = vsnprintf(buf, buflen, fmt, ap);
  759. if (n < 0) {
  760. cry(conn, "vsnprintf error");
  761. n = 0;
  762. } else if (n >= (int) buflen) {
  763. cry(conn, "truncating vsnprintf buffer: [%.*s]",
  764. n > 200 ? 200 : n, buf);
  765. n = (int) buflen - 1;
  766. }
  767. buf[n] = '\0';
  768. return n;
  769. }
  770. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  771. PRINTF_FORMAT_STRING(const char *fmt), ...)
  772. PRINTF_ARGS(4, 5);
  773. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  774. const char *fmt, ...) {
  775. va_list ap;
  776. int n;
  777. va_start(ap, fmt);
  778. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  779. va_end(ap);
  780. return n;
  781. }
  782. // Skip the characters until one of the delimiters characters found.
  783. // 0-terminate resulting word. Skip the delimiter and following whitespaces if any.
  784. // Advance pointer to buffer to the next word. Return found 0-terminated word.
  785. // Delimiters can be quoted with quotechar.
  786. static char *skip_quoted(char **buf, const char *delimiters,
  787. const char *whitespace, char quotechar) {
  788. char *p, *begin_word, *end_word, *end_whitespace;
  789. begin_word = *buf;
  790. end_word = begin_word + strcspn(begin_word, delimiters);
  791. // Check for quotechar
  792. if (end_word > begin_word) {
  793. p = end_word - 1;
  794. while (*p == quotechar) {
  795. // If there is anything beyond end_word, copy it
  796. if (*end_word == '\0') {
  797. *p = '\0';
  798. break;
  799. } else {
  800. size_t end_off = strcspn(end_word + 1, delimiters);
  801. memmove (p, end_word, end_off + 1);
  802. p += end_off; // p must correspond to end_word - 1
  803. end_word += end_off + 1;
  804. }
  805. }
  806. for (p++; p < end_word; p++) {
  807. *p = '\0';
  808. }
  809. }
  810. if (*end_word == '\0') {
  811. *buf = end_word;
  812. } else {
  813. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  814. for (p = end_word; p < end_whitespace; p++) {
  815. *p = '\0';
  816. }
  817. *buf = end_whitespace;
  818. }
  819. return begin_word;
  820. }
  821. // Simplified version of skip_quoted without quote char
  822. // and whitespace == delimiters
  823. static char *skip(char **buf, const char *delimiters) {
  824. return skip_quoted(buf, delimiters, delimiters, 0);
  825. }
  826. // Return HTTP header value, or NULL if not found.
  827. static const char *get_header(const struct mg_request_info *ri,
  828. const char *name) {
  829. int i;
  830. for (i = 0; i < ri->num_headers; i++)
  831. if (!mg_strcasecmp(name, ri->http_headers[i].name))
  832. return ri->http_headers[i].value;
  833. return NULL;
  834. }
  835. const char *mg_get_header(const struct mg_connection *conn, const char *name) {
  836. return get_header(&conn->request_info, name);
  837. }
  838. //int mg_get_connection_count(const struct mg_connection *conn) {
  839. // return conn->client.connection_count;
  840. //}
  841. // A helper function for traversing a comma separated list of values.
  842. // It returns a list pointer shifted to the next value, or NULL if the end
  843. // of the list found.
  844. // Value is stored in val vector. If value has form "x=y", then eq_val
  845. // vector is initialized to point to the "y" part, and val vector length
  846. // is adjusted to point only to "x".
  847. static const char *next_option(const char *list, struct vec *val,
  848. struct vec *eq_val) {
  849. if (list == NULL || *list == '\0') {
  850. // End of the list
  851. list = NULL;
  852. } else {
  853. val->ptr = list;
  854. if ((list = strchr(val->ptr, ',')) != NULL) {
  855. // Comma found. Store length and shift the list ptr
  856. val->len = list - val->ptr;
  857. list++;
  858. } else {
  859. // This value is the last one
  860. list = val->ptr + strlen(val->ptr);
  861. val->len = list - val->ptr;
  862. }
  863. if (eq_val != NULL) {
  864. // Value has form "x=y", adjust pointers and lengths
  865. // so that val points to "x", and eq_val points to "y".
  866. eq_val->len = 0;
  867. eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
  868. if (eq_val->ptr != NULL) {
  869. eq_val->ptr++; // Skip over '=' character
  870. eq_val->len = val->ptr + val->len - eq_val->ptr;
  871. val->len = (eq_val->ptr - val->ptr) - 1;
  872. }
  873. }
  874. }
  875. return list;
  876. }
  877. static int match_prefix(const char *pattern, int pattern_len, const char *str) {
  878. const char *or_str;
  879. int i, j, len, res;
  880. if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
  881. res = match_prefix(pattern, or_str - pattern, str);
  882. return res > 0 ? res :
  883. match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);
  884. }
  885. i = j = 0;
  886. res = -1;
  887. for (; i < pattern_len; i++, j++) {
  888. if (pattern[i] == '?' && str[j] != '\0') {
  889. continue;
  890. } else if (pattern[i] == '$') {
  891. return str[j] == '\0' ? j : -1;
  892. } else if (pattern[i] == '*') {
  893. i++;
  894. if (pattern[i] == '*') {
  895. i++;
  896. len = (int) strlen(str + j);
  897. } else {
  898. len = (int) strcspn(str + j, "/");
  899. }
  900. if (i == pattern_len) {
  901. return j + len;
  902. }
  903. do {
  904. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  905. } while (res == -1 && len-- > 0);
  906. return res == -1 ? -1 : j + res + len;
  907. } else if (pattern[i] != str[j]) {
  908. return -1;
  909. }
  910. }
  911. return j;
  912. }
  913. // HTTP 1.1 assumes keep alive if "Connection:" header is not set
  914. // This function must tolerate situations when connection info is not
  915. // set up, for example if request parsing failed.
  916. static int should_keep_alive(const struct mg_connection *conn) {
  917. const char *http_version = conn->request_info.http_version;
  918. const char *header = mg_get_header(conn, "Connection");
  919. if (conn->must_close ||
  920. conn->request_info.status_code == 401 ||
  921. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  922. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  923. (header == NULL && http_version && strcmp(http_version, "1.1"))) {
  924. return 0;
  925. }
  926. return 1;
  927. }
  928. static const char *suggest_connection_header(const struct mg_connection *conn) {
  929. return should_keep_alive(conn) ? "keep-alive" : "close";
  930. }
  931. static void send_http_error(struct mg_connection *, int, const char *,
  932. PRINTF_FORMAT_STRING(const char *fmt), ...)
  933. PRINTF_ARGS(4, 5);
  934. static void send_http_error(struct mg_connection *conn, int status,
  935. const char *reason, const char *fmt, ...) {
  936. char buf[MG_BUF_LEN];
  937. va_list ap;
  938. int len = 0;
  939. conn->request_info.status_code = status;
  940. if (call_user(conn, MG_HTTP_ERROR) == NULL) {
  941. buf[0] = '\0';
  942. len = 0;
  943. // Errors 1xx, 204 and 304 MUST NOT send a body
  944. if (status > 199 && status != 204 && status != 304) {
  945. len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
  946. buf[len++] = '\n';
  947. va_start(ap, fmt);
  948. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
  949. va_end(ap);
  950. }
  951. DEBUG_TRACE(("[%s]", buf));
  952. mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  953. "Content-Type: text/plain\r\n"
  954. "Content-Length: %d\r\n"
  955. "Connection: %s\r\n\r\n", status, reason, len,
  956. suggest_connection_header(conn));
  957. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  958. }
  959. }
  960. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  961. static int pthread_mutex_init(pthread_mutex_t *mutex, const void *unused) {
  962. unused = NULL;
  963. *mutex = CreateMutex(NULL, FALSE, NULL);
  964. return *mutex == NULL ? -1 : 0;
  965. }
  966. static int pthread_mutex_destroy(pthread_mutex_t *mutex) {
  967. return CloseHandle(*mutex) == 0 ? -1 : 0;
  968. }
  969. static int pthread_mutex_lock(pthread_mutex_t *mutex) {
  970. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  971. }
  972. static int pthread_mutex_trylock(pthread_mutex_t *mutex) {
  973. return WaitForSingleObject(*mutex, 0) == WAIT_OBJECT_0? 0 : -1;
  974. }
  975. static int pthread_mutex_unlock(pthread_mutex_t *mutex) {
  976. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  977. }
  978. static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {
  979. unused = NULL;
  980. cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);
  981. cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);
  982. return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;
  983. }
  984. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {
  985. HANDLE handles[] = {cv->signal, cv->broadcast};
  986. ReleaseMutex(*mutex);
  987. WaitForMultipleObjects(2, handles, FALSE, INFINITE);
  988. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  989. }
  990. static int pthread_cond_signal(pthread_cond_t *cv) {
  991. return SetEvent(cv->signal) == 0 ? -1 : 0;
  992. }
  993. static int pthread_cond_broadcast(pthread_cond_t *cv) {
  994. // Implementation with PulseEvent() has race condition, see
  995. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
  996. return PulseEvent(cv->broadcast) == 0 ? -1 : 0;
  997. }
  998. static int pthread_cond_destroy(pthread_cond_t *cv) {
  999. return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;
  1000. }
  1001. // For Windows, change all slashes to backslashes in path names.
  1002. static void change_slashes_to_backslashes(char *path) {
  1003. int i;
  1004. for (i = 0; path[i] != '\0'; i++) {
  1005. if (path[i] == '/')
  1006. path[i] = '\\';
  1007. // i > 0 check is to preserve UNC paths, like \\server\file.txt
  1008. if (path[i] == '\\' && i > 0)
  1009. while (path[i + 1] == '\\' || path[i + 1] == '/')
  1010. (void) memmove(path + i + 1,
  1011. path + i + 2, strlen(path + i + 1));
  1012. }
  1013. }
  1014. // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  1015. // wbuf and wbuf_len is a target buffer and its length.
  1016. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1017. char buf[PATH_MAX], buf2[PATH_MAX], *p;
  1018. mg_strlcpy(buf, path, sizeof(buf));
  1019. change_slashes_to_backslashes(buf);
  1020. // Point p to the end of the file name
  1021. p = buf + strlen(buf) - 1;
  1022. // Trim trailing backslash character
  1023. while (p > buf && *p == '\\' && p[-1] != ':') {
  1024. *p-- = '\0';
  1025. }
  1026. // Protect from CGI code disclosure.
  1027. // This is very nasty hole. Windows happily opens files with
  1028. // some garbage in the end of file name. So fopen("a.cgi ", "r")
  1029. // actually opens "a.cgi", and does not return an error!
  1030. if (*p == 0x20 || // No space at the end
  1031. (*p == 0x2e && p > buf) || // No '.' but allow '.' as full path
  1032. *p == 0x2b || // No '+'
  1033. (*p & ~0x7f)) { // And generally no non-ASCII chars
  1034. (void) fprintf(stderr, "Rejecting suspicious path: [%s]", buf);
  1035. wbuf[0] = L'\0';
  1036. } else {
  1037. // Convert to Unicode and back. If doubly-converted string does not
  1038. // match the original, something is fishy, reject.
  1039. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1040. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1041. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1042. NULL, NULL);
  1043. if (strcmp(buf, buf2) != 0) {
  1044. wbuf[0] = L'\0';
  1045. }
  1046. }
  1047. }
  1048. #if defined(_WIN32_WCE) && !defined(__GNUC__)
  1049. static time_t time(time_t *ptime) {
  1050. time_t t;
  1051. SYSTEMTIME st;
  1052. FILETIME ft;
  1053. GetSystemTime(&st);
  1054. SystemTimeToFileTime(&st, &ft);
  1055. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  1056. if (ptime != NULL) {
  1057. *ptime = t;
  1058. }
  1059. return t;
  1060. }
  1061. static time_t mktime(struct tm *ptm) {
  1062. SYSTEMTIME st;
  1063. FILETIME ft, lft;
  1064. st.wYear = ptm->tm_year + 1900;
  1065. st.wMonth = ptm->tm_mon + 1;
  1066. st.wDay = ptm->tm_mday;
  1067. st.wHour = ptm->tm_hour;
  1068. st.wMinute = ptm->tm_min;
  1069. st.wSecond = ptm->tm_sec;
  1070. st.wMilliseconds = 0;
  1071. SystemTimeToFileTime(&st, &ft);
  1072. LocalFileTimeToFileTime(&ft, &lft);
  1073. return (time_t) ((MAKEUQUAD(lft.dwLowDateTime, lft.dwHighDateTime) -
  1074. EPOCH_DIFF) / RATE_DIFF);
  1075. }
  1076. static struct tm *localtime(const time_t *ptime, struct tm *ptm) {
  1077. int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
  1078. FILETIME ft, lft;
  1079. SYSTEMTIME st;
  1080. TIME_ZONE_INFORMATION tzinfo;
  1081. if (ptm == NULL) {
  1082. return NULL;
  1083. }
  1084. * (int64_t *) &ft = t;
  1085. FileTimeToLocalFileTime(&ft, &lft);
  1086. FileTimeToSystemTime(&lft, &st);
  1087. ptm->tm_year = st.wYear - 1900;
  1088. ptm->tm_mon = st.wMonth - 1;
  1089. ptm->tm_wday = st.wDayOfWeek;
  1090. ptm->tm_mday = st.wDay;
  1091. ptm->tm_hour = st.wHour;
  1092. ptm->tm_min = st.wMinute;
  1093. ptm->tm_sec = st.wSecond;
  1094. ptm->tm_yday = 0; // hope nobody uses this
  1095. ptm->tm_isdst =
  1096. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  1097. return ptm;
  1098. }
  1099. static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {
  1100. // FIXME(lsm): fix this.
  1101. return localtime(ptime, ptm);
  1102. }
  1103. static size_t strftime(char *dst, size_t dst_size, const char *fmt,
  1104. const struct tm *tm) {
  1105. (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
  1106. return 0;
  1107. }
  1108. #endif
  1109. static int mg_rename(const char* oldname, const char* newname) {
  1110. wchar_t woldbuf[PATH_MAX];
  1111. wchar_t wnewbuf[PATH_MAX];
  1112. to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf));
  1113. to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf));
  1114. return MoveFileW(woldbuf, wnewbuf) ? 0 : -1;
  1115. }
  1116. static FILE *mg_fopen(const char *path, const char *mode) {
  1117. wchar_t wbuf[PATH_MAX], wmode[20];
  1118. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1119. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1120. return _wfopen(wbuf, wmode);
  1121. }
  1122. static int mg_stat(const char *path, struct mgstat *stp) {
  1123. int ok = -1; // Error
  1124. wchar_t wbuf[PATH_MAX];
  1125. WIN32_FILE_ATTRIBUTE_DATA info;
  1126. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1127. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  1128. stp->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  1129. stp->mtime = SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  1130. info.ftLastWriteTime.dwHighDateTime);
  1131. stp->is_directory =
  1132. info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  1133. ok = 0; // Success
  1134. }
  1135. return ok;
  1136. }
  1137. static int mg_remove(const char *path) {
  1138. wchar_t wbuf[PATH_MAX];
  1139. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1140. return DeleteFileW(wbuf) ? 0 : -1;
  1141. }
  1142. static int mg_mkdir(const char *path, int mode) {
  1143. char buf[PATH_MAX];
  1144. wchar_t wbuf[PATH_MAX];
  1145. mode = 0; // Unused
  1146. mg_strlcpy(buf, path, sizeof(buf));
  1147. change_slashes_to_backslashes(buf);
  1148. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, sizeof(wbuf));
  1149. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  1150. }
  1151. // Implementation of POSIX opendir/closedir/readdir for Windows.
  1152. static DIR * opendir(const char *name) {
  1153. DIR *dir = NULL;
  1154. wchar_t wpath[PATH_MAX];
  1155. DWORD attrs;
  1156. if (name == NULL) {
  1157. SetLastError(ERROR_BAD_ARGUMENTS);
  1158. } else if ((dir = (DIR *) MG_MALLOC(sizeof(*dir))) == NULL) {
  1159. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1160. } else {
  1161. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  1162. attrs = GetFileAttributesW(wpath);
  1163. if (attrs != 0xFFFFFFFF &&
  1164. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  1165. (void) wcscat(wpath, L"\\*");
  1166. dir->handle = FindFirstFileW(wpath, &dir->info);
  1167. dir->result.d_name[0] = '\0';
  1168. } else {
  1169. MG_FREE(dir);
  1170. dir = NULL;
  1171. }
  1172. }
  1173. return dir;
  1174. }
  1175. static int closedir(DIR *dir) {
  1176. int result = 0;
  1177. if (dir != NULL) {
  1178. if (dir->handle != INVALID_HANDLE_VALUE)
  1179. result = FindClose(dir->handle) ? 0 : -1;
  1180. MG_FREE(dir);
  1181. } else {
  1182. result = -1;
  1183. SetLastError(ERROR_BAD_ARGUMENTS);
  1184. }
  1185. return result;
  1186. }
  1187. struct dirent * readdir(DIR *dir) {
  1188. struct dirent *result = 0;
  1189. if (dir) {
  1190. if (dir->handle != INVALID_HANDLE_VALUE) {
  1191. result = &dir->result;
  1192. (void) WideCharToMultiByte(CP_UTF8, 0,
  1193. dir->info.cFileName, -1, result->d_name,
  1194. sizeof(result->d_name), NULL, NULL);
  1195. if (!FindNextFileW(dir->handle, &dir->info)) {
  1196. (void) FindClose(dir->handle);
  1197. dir->handle = INVALID_HANDLE_VALUE;
  1198. }
  1199. } else {
  1200. SetLastError(ERROR_FILE_NOT_FOUND);
  1201. }
  1202. } else {
  1203. SetLastError(ERROR_BAD_ARGUMENTS);
  1204. }
  1205. return result;
  1206. }
  1207. #define set_close_on_exec(fd) // No FD_CLOEXEC on Windows
  1208. int mg_start_thread(mg_thread_func_t f, void *p) {
  1209. #ifdef _WIN32_WCE
  1210. HANDLE hThread;
  1211. hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0,
  1212. NULL);
  1213. if (hThread != NULL) {
  1214. (void) CloseHandle(hThread);
  1215. }
  1216. return hThread == NULL ? -1 : 0;
  1217. #else
  1218. return _beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
  1219. #endif
  1220. }
  1221. static HANDLE dlopen(const char *dll_name, int flags) {
  1222. wchar_t wbuf[PATH_MAX];
  1223. flags = 0; // Unused
  1224. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  1225. return LoadLibraryW(wbuf);
  1226. }
  1227. #if !defined(NO_CGI)
  1228. #define SIGKILL 0
  1229. static int kill(pid_t pid, int sig_num) {
  1230. (void) TerminateProcess(pid, sig_num);
  1231. (void) CloseHandle(pid);
  1232. return 0;
  1233. }
  1234. static void trim_trailing_whitespaces(char *s) {
  1235. char *e = s + strlen(s) - 1;
  1236. while (e > s && isspace(* (unsigned char *) e)) {
  1237. *e-- = '\0';
  1238. }
  1239. }
  1240. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1241. char *envblk, char *envp[], int fd_stdin,
  1242. int fd_stdout, const char *dir) {
  1243. HANDLE me;
  1244. char *p, *interp, full_interp[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX];
  1245. FILE *fp;
  1246. STARTUPINFOA si = { sizeof(si) };
  1247. PROCESS_INFORMATION pi = { 0 };
  1248. envp = NULL; // Unused
  1249. // TODO(lsm): redirect CGI errors to the error log file
  1250. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1251. si.wShowWindow = SW_HIDE;
  1252. me = GetCurrentProcess();
  1253. DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,
  1254. &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1255. DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,
  1256. &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1257. // If CGI file is a script, try to read the interpreter line
  1258. interp = conn->ctx->config[CGI_INTERPRETER];
  1259. if (interp == NULL) {
  1260. buf[0] = buf[2] = '\0';
  1261. // Read the first line of the script into the buffer
  1262. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  1263. if ((fp = mg_fopen(cmdline, "r")) != NULL) {
  1264. fgets(buf, sizeof(buf), fp);
  1265. fclose(fp);
  1266. buf[sizeof(buf) - 1] = '\0';
  1267. }
  1268. if (buf[0] == '#' && buf[1] == '!') {
  1269. // Trim whitespace in interpreter name
  1270. for (p = buf + 2; *p != '\0' && isspace(* (unsigned char *) p); )
  1271. p++;
  1272. *p = '\0';
  1273. }
  1274. interp = buf + 2;
  1275. }
  1276. if (interp[0] != '\0') {
  1277. GetFullPathName(interp, sizeof(full_interp), full_interp, NULL);
  1278. interp = full_interp;
  1279. }
  1280. (void) mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s%c%s",
  1281. interp, interp[0] == '\0' ? "" : " ", dir, DIRSEP, prog);
  1282. DEBUG_TRACE(("Running [%s]", cmdline));
  1283. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  1284. CREATE_NEW_PROCESS_GROUP, envblk, dir, &si, &pi) == 0) {
  1285. cry(conn, "%s: CreateProcess(%s): %d",
  1286. __func__, cmdline, (int)ERRNO);
  1287. pi.hProcess = (pid_t) -1;
  1288. }
  1289. // Always close these to prevent handle leakage.
  1290. (void) close(fd_stdin);
  1291. (void) close(fd_stdout);
  1292. (void) CloseHandle(si.hStdOutput);
  1293. (void) CloseHandle(si.hStdInput);
  1294. (void) CloseHandle(pi.hThread);
  1295. return (pid_t) pi.hProcess;
  1296. }
  1297. #endif // !NO_CGI
  1298. static int set_non_blocking_mode(SOCKET sock) {
  1299. unsigned long on = 1;
  1300. return ioctlsocket(sock, FIONBIO, &on);
  1301. }
  1302. #else
  1303. static int mg_stat(const char *path, struct mgstat *stp) {
  1304. struct stat st;
  1305. int ok;
  1306. if (stat(path, &st) == 0) {
  1307. ok = 0;
  1308. stp->size = st.st_size;
  1309. stp->mtime = st.st_mtime;
  1310. stp->is_directory = S_ISDIR(st.st_mode);
  1311. } else {
  1312. ok = -1;
  1313. }
  1314. return ok;
  1315. }
  1316. static void set_close_on_exec(int fd) {
  1317. (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
  1318. }
  1319. int mg_start_thread(mg_thread_func_t func, void *param) {
  1320. pthread_t thread_id;
  1321. pthread_attr_t attr;
  1322. (void) pthread_attr_init(&attr);
  1323. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  1324. // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled
  1325. // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5);
  1326. return pthread_create(&thread_id, &attr, func, param);
  1327. }
  1328. #ifndef NO_CGI
  1329. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1330. char *envblk, char *envp[], int fd_stdin,
  1331. int fd_stdout, const char *dir) {
  1332. pid_t pid;
  1333. const char *interp;
  1334. envblk = NULL; // Unused
  1335. if ((pid = fork()) == -1) {
  1336. // Parent
  1337. send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
  1338. } else if (pid == 0) {
  1339. // Child
  1340. if (chdir(dir) != 0) {
  1341. cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  1342. } else if (dup2(fd_stdin, 0) == -1) {
  1343. cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO));
  1344. } else if (dup2(fd_stdout, 1) == -1) {
  1345. cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO));
  1346. } else {
  1347. (void) dup2(fd_stdout, 2);
  1348. (void) close(fd_stdin);
  1349. (void) close(fd_stdout);
  1350. // After exec, all signal handlers are restored to their default values,
  1351. // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
  1352. // implementation, SIGCHLD's handler will leave unchanged after exec
  1353. // if it was set to be ignored. Restore it to default action.
  1354. signal(SIGCHLD, SIG_DFL);
  1355. interp = conn->ctx->config[CGI_INTERPRETER];
  1356. if (interp == NULL) {
  1357. (void) execle(prog, prog, NULL, envp);
  1358. cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
  1359. } else {
  1360. (void) execle(interp, interp, prog, NULL, envp);
  1361. cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
  1362. strerror(ERRNO));
  1363. }
  1364. }
  1365. exit(EXIT_FAILURE);
  1366. }
  1367. // Parent. Close stdio descriptors
  1368. (void) close(fd_stdin);
  1369. (void) close(fd_stdout);
  1370. return pid;
  1371. }
  1372. #endif // !NO_CGI
  1373. static int set_non_blocking_mode(SOCKET sock) {
  1374. int flags;
  1375. flags = fcntl(sock, F_GETFL, 0);
  1376. (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  1377. return 0;
  1378. }
  1379. #endif // _WIN32
  1380. // Write data to the IO channel - opened file descriptor, socket or SSL
  1381. // descriptor. Return number of bytes written.
  1382. static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
  1383. int64_t len) {
  1384. int64_t sent;
  1385. int n, k;
  1386. sent = 0;
  1387. while (sent < len) {
  1388. // How many bytes we send in this iteration
  1389. k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
  1390. #ifndef NO_SSL
  1391. if (ssl != NULL) {
  1392. n = SSL_write(ssl, buf + sent, k);
  1393. } else
  1394. #endif
  1395. if (fp != NULL) {
  1396. n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
  1397. if (ferror(fp))
  1398. n = -1;
  1399. } else {
  1400. n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
  1401. }
  1402. if (n <= 0)
  1403. break;
  1404. sent += n;
  1405. }
  1406. return sent;
  1407. }
  1408. // This function is needed to prevent Mongoose to be stuck in a blocking
  1409. // socket read when user requested exit. To do that, we sleep in select
  1410. // with a timeout, and when returned, check the context for the stop flag.
  1411. // If it is set, we return 0, and this means that we must not continue
  1412. // reading, must give up and close the connection and exit serving thread.
  1413. static int wait_until_socket_is_readable(struct mg_connection *conn) {
  1414. int result;
  1415. struct timeval tv;
  1416. fd_set set;
  1417. #ifdef _WIN32_WCE
  1418. #define EINTR 4
  1419. #endif
  1420. do {
  1421. tv.tv_sec = 0;
  1422. tv.tv_usec = 300 * 1000;
  1423. FD_ZERO(&set);
  1424. FD_SET(conn->client.sock, &set);
  1425. result = select(conn->client.sock + 1, &set, NULL, NULL, &tv);
  1426. } while ((result == 0 || (result < 0 && ERRNO == EINTR)) &&
  1427. conn->ctx->stop_flag == 0);
  1428. return conn->ctx->stop_flag || result < 0 ? 0 : 1;
  1429. }
  1430. // Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  1431. // Return negative value on error, or number of bytes read on success.
  1432. static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) {
  1433. int nread;
  1434. if (fp != NULL) {
  1435. // Use read() instead of fread(), because if we're reading from the CGI
  1436. // pipe, fread() may block until IO buffer is filled up. We cannot afford
  1437. // to block and must pass all read bytes immediately to the client.
  1438. nread = read(fileno(fp), buf, (size_t) len);
  1439. #ifndef NO_SSL
  1440. } else if (conn->ssl != NULL) {
  1441. nread = SSL_read(conn->ssl, buf, len);
  1442. #endif
  1443. } else {
  1444. nread = recv(conn->client.sock, buf, (size_t) len, 0);
  1445. }
  1446. return conn->ctx->stop_flag ? -1 : nread;
  1447. }
  1448. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len) {
  1449. int n, nread = 0;
  1450. while (len > 0 && conn->ctx->stop_flag == 0) {
  1451. n = pull(fp, conn, buf + nread, len);
  1452. if (n < 0) {
  1453. nread = n; // Propagate the error
  1454. break;
  1455. } else if (n == 0) {
  1456. break; // No more data to read
  1457. } else {
  1458. conn->consumed_content += n;
  1459. nread += n;
  1460. len -= n;
  1461. }
  1462. }
  1463. return nread;
  1464. }
  1465. int mg_read(struct mg_connection *conn, void *buf, size_t len) {
  1466. int n, buffered_len, nread;
  1467. const char *body;
  1468. // If Content-Length is not set, read until socket is closed
  1469. if (conn->consumed_content == 0 && conn->content_len == 0) {
  1470. conn->content_len = INT64_MAX;
  1471. conn->must_close = 1;
  1472. }
  1473. nread = 0;
  1474. if (conn->consumed_content < conn->content_len) {
  1475. // Adjust number of bytes to read.
  1476. int64_t to_read = conn->content_len - conn->consumed_content;
  1477. if (to_read < (int64_t) len) {
  1478. len = (size_t) to_read;
  1479. }
  1480. // Return buffered data
  1481. body = conn->buf + conn->request_len + conn->consumed_content;
  1482. buffered_len = &conn->buf[conn->data_len] - body;
  1483. if (buffered_len > 0) {
  1484. if (len < (size_t) buffered_len) {
  1485. buffered_len = (int) len;
  1486. }
  1487. memcpy(buf, body, (size_t) buffered_len);
  1488. len -= buffered_len;
  1489. conn->consumed_content += buffered_len;
  1490. nread += buffered_len;
  1491. buf = (char *) buf + buffered_len;
  1492. }
  1493. // We have returned all buffered data. Read new data from the remote socket.
  1494. n = pull_all(NULL, conn, (char *) buf, (int) len);
  1495. nread = n >= 0 ? nread + n : n;
  1496. }
  1497. return nread;
  1498. }
  1499. int mg_write(struct mg_connection *conn, const void *buf, size_t len) {
  1500. time_t now;
  1501. int64_t n, total, allowed;
  1502. if (conn->throttle > 0) {
  1503. if ((now = time(NULL)) != conn->last_throttle_time) {
  1504. conn->last_throttle_time = now;
  1505. conn->last_throttle_bytes = 0;
  1506. }
  1507. allowed = conn->throttle - conn->last_throttle_bytes;
  1508. if (allowed > (int64_t) len) {
  1509. allowed = len;
  1510. }
  1511. if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1512. (int64_t) allowed)) == allowed) {
  1513. buf = (char *) buf + total;
  1514. conn->last_throttle_bytes += total;
  1515. while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
  1516. allowed = conn->throttle > (int64_t) len - total ?
  1517. (int64_t) len - total : conn->throttle;
  1518. if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1519. (int64_t) allowed)) != allowed) {
  1520. break;
  1521. }
  1522. mg_sleep(1);
  1523. conn->last_throttle_bytes = allowed;
  1524. conn->last_throttle_time = time(NULL);
  1525. buf = (char *) buf + n;
  1526. total += n;
  1527. }
  1528. }
  1529. } else {
  1530. total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1531. (int64_t) len);
  1532. }
  1533. return (int) total;
  1534. }
  1535. int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  1536. char buf[MG_BUF_LEN];
  1537. int len;
  1538. va_list ap;
  1539. va_start(ap, fmt);
  1540. len = mg_vsnprintf(conn, buf, sizeof(buf), fmt, ap);
  1541. va_end(ap);
  1542. return mg_write(conn, buf, (size_t)len);
  1543. }
  1544. // URL-decode input buffer into destination buffer.
  1545. // 0-terminate the destination buffer. Return the length of decoded data.
  1546. // form-url-encoded data differs from URI encoding in a way that it
  1547. // uses '+' as character for space, see RFC 1866 section 8.2.1
  1548. // http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  1549. size_t mg_url_decode(const char *src, size_t src_len, char *dst,
  1550. size_t dst_len, int is_form_url_encoded) {
  1551. size_t i, j;
  1552. int a, b;
  1553. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  1554. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  1555. if (src[i] == '%' && i < src_len - 2 &&
  1556. isxdigit(* (const unsigned char *) (src + i + 1)) &&
  1557. isxdigit(* (const unsigned char *) (src + i + 2))) {
  1558. a = tolower(* (const unsigned char *) (src + i + 1));
  1559. b = tolower(* (const unsigned char *) (src + i + 2));
  1560. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  1561. i += 2;
  1562. } else if (is_form_url_encoded && src[i] == '+') {
  1563. dst[j] = ' ';
  1564. } else {
  1565. dst[j] = src[i];
  1566. }
  1567. }
  1568. dst[j] = '\0'; // Null-terminate the destination
  1569. return j;
  1570. }
  1571. // Scan given buffer and fetch the value of the given variable.
  1572. // It can be specified in query string, or in the POST data.
  1573. // Return NULL if the variable not found, or allocated 0-terminated value.
  1574. // It is caller's responsibility to free the returned value.
  1575. int mg_find_var(const char *buf, size_t buf_len, const char *name,
  1576. const char **start) {
  1577. const char *p, *e, *s;
  1578. size_t name_len, len;
  1579. name_len = strlen(name);
  1580. e = buf + buf_len;
  1581. len = -1;
  1582. // buf is "var1=val1&var2=val2...". Find variable first
  1583. for (p = buf; p != NULL && p + name_len < e; p++) {
  1584. if ((p == buf || p[-1] == '&') && p[name_len] == '=' &&
  1585. !mg_strncasecmp(name, p, name_len)) {
  1586. // Point p to variable value
  1587. p += name_len + 1;
  1588. // Point s to the end of the value
  1589. s = (const char *) memchr(p, '&', (size_t)(e - p));
  1590. if (s == NULL) {
  1591. s = e;
  1592. }
  1593. assert(s >= p);
  1594. *start = p;
  1595. len = (s - p);
  1596. break;
  1597. }
  1598. }
  1599. return len;
  1600. }
  1601. int mg_get_var(const char *buf, size_t buf_len, const char *name,
  1602. char *dst, size_t dst_len) {
  1603. const char *start;
  1604. int len;
  1605. len = mg_find_var(buf, buf_len, name, &start);
  1606. if( (len > 0) && (len < dst_len) ) {
  1607. len = mg_url_decode(start, len, dst, dst_len, 1);
  1608. } else dst[0] = '\0';
  1609. return len;
  1610. }
  1611. int mg_find_cookie(const struct mg_connection *conn, const char *cookie_name,
  1612. const char **start) {
  1613. const char *s, *p, *end;
  1614. int name_len, len = -1;
  1615. if ((s = mg_get_header(conn, "Cookie")) == NULL) {
  1616. return -1;
  1617. }
  1618. name_len = (int) strlen(cookie_name);
  1619. end = s + strlen(s);
  1620. for (; (s = strstr(s, cookie_name)) != NULL; s += name_len)
  1621. if (s[name_len] == '=') {
  1622. s += name_len + 1;
  1623. if ((p = strchr(s, ' ')) == NULL)
  1624. p = end;
  1625. if (p[-1] == ';')
  1626. p--;
  1627. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  1628. s++;
  1629. p--;
  1630. }
  1631. len = (p - s) + 1;
  1632. *start = s;
  1633. break;
  1634. }
  1635. return len;
  1636. }
  1637. int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name,
  1638. char *dst, size_t dst_size) {
  1639. const char *start;
  1640. int len;
  1641. len = mg_find_cookie(conn, cookie_name, &start);
  1642. if( (len > 0) && (len < dst_size) ) {
  1643. mg_strlcpy(dst, start, (size_t)len);
  1644. dst[len] = '\0';
  1645. } else dst[0] = '\0';
  1646. return len;
  1647. }
  1648. // Mongoose allows to specify multiple directories to serve,
  1649. // like /var/www,/~bob=/home/bob. That means that root directory depends on URI.
  1650. // This function returns root dir for given URI.
  1651. static int get_document_root(const struct mg_connection *conn,
  1652. struct vec *document_root) {
  1653. const char *root, *uri;
  1654. int len_of_matched_uri;
  1655. struct vec uri_vec, path_vec;
  1656. uri = conn->request_info.uri;
  1657. len_of_matched_uri = 0;
  1658. root = next_option(conn->ctx->config[DOCUMENT_ROOT], document_root, NULL);
  1659. while ((root = next_option(root, &uri_vec, &path_vec)) != NULL) {
  1660. if (memcmp(uri, uri_vec.ptr, uri_vec.len) == 0) {
  1661. *document_root = path_vec;
  1662. len_of_matched_uri = uri_vec.len;
  1663. break;
  1664. }
  1665. }
  1666. return len_of_matched_uri;
  1667. }
  1668. static int convert_uri_to_file_name(struct mg_connection *conn, char *buf,
  1669. size_t buf_len, struct mgstat *st) {
  1670. struct vec a, b;
  1671. const char *rewrite, *uri = conn->request_info.uri;
  1672. char *p;
  1673. int match_len, stat_result;
  1674. buf_len--; // This is because memmove() for PATH_INFO may shift part
  1675. // of the path one byte on the right.
  1676. mg_snprintf(conn, buf, buf_len, "%s%s", conn->ctx->config[DOCUMENT_ROOT],
  1677. uri);
  1678. rewrite = conn->ctx->config[REWRITE];
  1679. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  1680. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  1681. mg_snprintf(conn, buf, buf_len, "%.*s%s", (int) b.len, b.ptr,
  1682. uri + match_len);
  1683. break;
  1684. }
  1685. }
  1686. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1687. //change_slashes_to_backslashes(buf);
  1688. #endif // _WIN32
  1689. if ((stat_result = mg_stat(buf, st)) != 0) {
  1690. // Support PATH_INFO for CGI scripts.
  1691. for (p = buf + strlen(buf); p > buf + 1; p--) {
  1692. if (*p == '/') {
  1693. *p = '\0';
  1694. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  1695. strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&
  1696. (stat_result = mg_stat(buf, st)) == 0) {
  1697. // Shift PATH_INFO block one character right, e.g.
  1698. // "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  1699. // conn->path_info is pointing to the local variable "path" declared
  1700. // in handle_request(), so PATH_INFO is not valid after
  1701. // handle_request returns.
  1702. conn->path_info = p + 1;
  1703. memmove(p + 2, p + 1, strlen(p + 1) + 1); // +1 is for trailing \0
  1704. p[1] = '/';
  1705. break;
  1706. } else {
  1707. *p = '/';
  1708. stat_result = -1;
  1709. }
  1710. }
  1711. }
  1712. }
  1713. return stat_result;
  1714. }
  1715. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) {
  1716. return (conn->ssl = SSL_new(s)) != NULL &&
  1717. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  1718. func(conn->ssl) == 1;
  1719. }
  1720. // Check whether full request is buffered. Return:
  1721. // -1 if request is malformed
  1722. // 0 if request is not yet fully buffered
  1723. // >0 actual request length, including last \r\n\r\n
  1724. static int get_request_len(const char *buf, int buflen) {
  1725. const char *s, *e;
  1726. int len = 0;
  1727. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  1728. // Control characters are not allowed but >=128 is.
  1729. if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
  1730. *s != '\n' && * (const unsigned char *) s < 128) {
  1731. len = -1;
  1732. break; // [i_a] abort scan as soon as one malformed character is found;
  1733. // don't let subsequent \r\n\r\n win us over anyhow
  1734. } else if (s[0] == '\n' && s[1] == '\n') {
  1735. len = (int) (s - buf) + 2;
  1736. } else if (s[0] == '\n' && &s[1] < e &&
  1737. s[1] == '\r' && s[2] == '\n') {
  1738. len = (int) (s - buf) + 3;
  1739. }
  1740. return len;
  1741. }
  1742. // Convert month to the month number. Return -1 on error, or month number
  1743. static int get_month_index(const char *s) {
  1744. size_t i;
  1745. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  1746. if (!strcmp(s, month_names[i]))
  1747. return (int) i;
  1748. return -1;
  1749. }
  1750. static int num_leap_years(int year) {
  1751. return year / 4 - year / 100 + year / 400;
  1752. }
  1753. // Parse UTC date-time string, and return the corresponding time_t value.
  1754. static time_t parse_date_string(const char *datetime) {
  1755. static const unsigned short days_before_month[] = {
  1756. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  1757. };
  1758. char month_str[32];
  1759. int second, minute, hour, day, month, year, leap_days, days;
  1760. time_t result = (time_t) 0;
  1761. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
  1762. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1763. (sscanf(datetime, "%d %3s %d %d:%d:%d",
  1764. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1765. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
  1766. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1767. (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
  1768. &day, month_str, &year, &hour, &minute, &second) == 6)) &&
  1769. year > 1970 &&
  1770. (month = get_month_index(month_str)) != -1) {
  1771. leap_days = num_leap_years(year) - num_leap_years(1970);
  1772. year -= 1970;
  1773. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  1774. result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
  1775. }
  1776. return result;
  1777. }
  1778. // Protect against directory disclosure attack by removing '..',
  1779. // excessive '/' and '\' characters
  1780. static void remove_double_dots_and_double_slashes(char *s) {
  1781. char *p = s;
  1782. while (*s != '\0') {
  1783. *p++ = *s++;
  1784. if (IS_DIRSEP_CHAR(s[-1])) {
  1785. // Skip all following slashes and backslashes
  1786. while (IS_DIRSEP_CHAR(s[0])) {
  1787. s++;
  1788. }
  1789. // Skip all double-dots
  1790. while (*s == '.' && s[1] == '.') {
  1791. s += 2;
  1792. }
  1793. }
  1794. }
  1795. *p = '\0';
  1796. }
  1797. static const struct {
  1798. const char *extension;
  1799. size_t ext_len;
  1800. const char *mime_type;
  1801. } builtin_mime_types[] = {
  1802. /* IANA registered MIME types
  1803. * (http://www.iana.org/assignments/media-types)
  1804. * application types */
  1805. {".doc", 4, "application/msword"},
  1806. {".eps", 4, "application/postscript"},
  1807. {".exe", 4, "application/octet-stream"},
  1808. {".js", 3, "application/javascript"},
  1809. {".json", 5, "application/json"},
  1810. {".pdf", 4, "application/pdf"},
  1811. {".ps", 3, "application/postscript"},
  1812. {".rtf", 4, "application/rtf"},
  1813. {".xhtml", 6, "application/xhtml+xml"},
  1814. {".xsl", 4, "application/xml"},
  1815. {".xslt", 5, "application/xml"},
  1816. /* fonts */
  1817. {".ttf", 4, "application/font-sfnt"},
  1818. {".cff", 4, "application/font-sfnt"},
  1819. {".otf", 4, "application/font-sfnt"},
  1820. {".aat", 4, "application/font-sfnt"},
  1821. {".sil", 4, "application/font-sfnt"},
  1822. {".pfr", 4, "application/font-tdpfr"},
  1823. {".woff", 5, "application/font-woff"},
  1824. /* audio */
  1825. {".mp3", 4, "audio/mpeg"},
  1826. {".oga", 4, "audio/ogg"},
  1827. {".ogg", 4, "audio/ogg"},
  1828. /* image */
  1829. {".gif", 4, "image/gif"},
  1830. {".ief", 4, "image/ief"},
  1831. {".jpeg", 5, "image/jpeg"},
  1832. {".jpg", 4, "image/jpeg"},
  1833. {".jpm", 4, "image/jpm"},
  1834. {".jpx", 4, "image/jpx"},
  1835. {".png", 4, "image/png"},
  1836. {".svg", 4, "image/svg+xml"},
  1837. {".tif", 4, "image/tiff"},
  1838. {".tiff", 5, "image/tiff"},
  1839. /* model */
  1840. {".wrl", 4, "model/vrml"},
  1841. /* text */
  1842. {".css", 4, "text/css"},
  1843. {".csv", 4, "text/csv"},
  1844. {".htm", 4, "text/html"},
  1845. {".html", 5, "text/html"},
  1846. {".sgm", 4, "text/sgml"},
  1847. {".shtm", 5, "text/html"},
  1848. {".shtml", 6, "text/html"},
  1849. {".txt", 4, "text/plain"},
  1850. {".xml", 4, "text/xml"},
  1851. /* video */
  1852. {".mov", 4, "video/quicktime"},
  1853. {".mp4", 4, "video/mp4"},
  1854. {".mpeg", 5, "video/mpeg"},
  1855. {".mpg", 4, "video/mpeg"},
  1856. {".ogv", 4, "video/ogg"},
  1857. {".qt", 3, "video/quicktime"},
  1858. /* not registered types
  1859. * (http://reference.sitepoint.com/html/mime-types-full,
  1860. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  1861. {".arj", 4, "application/x-arj-compressed"},
  1862. {".gz", 3, "application/x-gunzip"},
  1863. {".rar", 4, "application/x-arj-compressed"},
  1864. {".swf", 4, "application/x-shockwave-flash"},
  1865. {".tar", 4, "application/x-tar"},
  1866. {".tgz", 4, "application/x-tar-gz"},
  1867. {".torrent", 8, "application/x-bittorrent"},
  1868. {".ppt", 4, "application/x-mspowerpoint"},
  1869. {".xls", 4, "application/x-msexcel"},
  1870. {".zip", 4, "application/x-zip-compressed"},
  1871. {".aac",
  1872. 4,
  1873. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  1874. {".aif", 4, "audio/x-aif"},
  1875. {".m3u", 4, "audio/x-mpegurl"},
  1876. {".mid", 4, "audio/x-midi"},
  1877. {".ra", 3, "audio/x-pn-realaudio"},
  1878. {".ram", 4, "audio/x-pn-realaudio"},
  1879. {".wav", 4, "audio/x-wav"},
  1880. {".bmp", 4, "image/bmp"},
  1881. {".ico", 4, "image/x-icon"},
  1882. {".pct", 4, "image/x-pct"},
  1883. {".pict", 5, "image/pict"},
  1884. {".rgb", 4, "image/x-rgb"},
  1885. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  1886. {".asf", 4, "video/x-ms-asf"},
  1887. {".avi", 4, "video/x-msvideo"},
  1888. {".m4v", 4, "video/x-m4v"},
  1889. {".apk", 4, "application/vnd.android.package-archive"},
  1890. {".manifest", 9, "text/cache-manifest"},
  1891. {NULL, 0, NULL}
  1892. };
  1893. const char *mg_get_builtin_mime_type(const char *path) {
  1894. const char *ext;
  1895. size_t i, path_len;
  1896. path_len = strlen(path);
  1897. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  1898. ext = path + (path_len - builtin_mime_types[i].ext_len);
  1899. if (path_len > builtin_mime_types[i].ext_len &&
  1900. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  1901. return builtin_mime_types[i].mime_type;
  1902. }
  1903. }
  1904. return "text/plain";
  1905. }
  1906. // Look at the "path" extension and figure what mime type it has.
  1907. // Store mime type in the vector.
  1908. static void get_mime_type(struct mg_context *ctx, const char *path,
  1909. struct vec *vec) {
  1910. struct vec ext_vec, mime_vec;
  1911. const char *list, *ext;
  1912. size_t path_len;
  1913. path_len = strlen(path);
  1914. // Scan user-defined mime types first, in case user wants to
  1915. // override default mime types.
  1916. list = ctx->config[EXTRA_MIME_TYPES];
  1917. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  1918. // ext now points to the path suffix
  1919. ext = path + path_len - ext_vec.len;
  1920. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  1921. *vec = mime_vec;
  1922. return;
  1923. }
  1924. }
  1925. vec->ptr = mg_get_builtin_mime_type(path);
  1926. vec->len = strlen(vec->ptr);
  1927. }
  1928. static int is_big_endian(void) {
  1929. static const int n = 1;
  1930. return ((char *) &n)[0] == 0;
  1931. }
  1932. #ifndef HAVE_MD5
  1933. typedef struct MD5Context {
  1934. uint32_t buf[4];
  1935. uint32_t bits[2];
  1936. unsigned char in[64];
  1937. } MD5_CTX;
  1938. static void byteReverse(unsigned char *buf, unsigned longs) {
  1939. uint32_t t;
  1940. // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
  1941. if (is_big_endian()) {
  1942. do {
  1943. t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  1944. ((unsigned) buf[1] << 8 | buf[0]);
  1945. * (uint32_t *) buf = t;
  1946. buf += 4;
  1947. } while (--longs);
  1948. }
  1949. }
  1950. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  1951. #define F2(x, y, z) F1(z, x, y)
  1952. #define F3(x, y, z) (x ^ y ^ z)
  1953. #define F4(x, y, z) (y ^ (x | ~z))
  1954. #define MD5STEP(f, w, x, y, z, data, s) \
  1955. ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
  1956. // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  1957. // initialization constants.
  1958. void MD5Init(MD5_CTX *ctx) {
  1959. ctx->buf[0] = 0x67452301;
  1960. ctx->buf[1] = 0xefcdab89;
  1961. ctx->buf[2] = 0x98badcfe;
  1962. ctx->buf[3] = 0x10325476;
  1963. ctx->bits[0] = 0;
  1964. ctx->bits[1] = 0;
  1965. }
  1966. void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
  1967. register uint32_t a, b, c, d;
  1968. a = buf[0];
  1969. b = buf[1];
  1970. c = buf[2];
  1971. d = buf[3];
  1972. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  1973. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  1974. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  1975. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  1976. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  1977. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  1978. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  1979. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  1980. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  1981. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  1982. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  1983. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  1984. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  1985. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  1986. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  1987. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  1988. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  1989. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  1990. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  1991. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  1992. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  1993. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  1994. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  1995. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  1996. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  1997. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  1998. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  1999. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  2000. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  2001. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  2002. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  2003. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  2004. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  2005. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  2006. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  2007. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  2008. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  2009. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  2010. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  2011. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  2012. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  2013. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  2014. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  2015. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  2016. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  2017. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  2018. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  2019. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  2020. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  2021. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  2022. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  2023. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  2024. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  2025. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  2026. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  2027. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  2028. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  2029. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  2030. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  2031. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  2032. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  2033. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  2034. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  2035. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  2036. buf[0] += a;
  2037. buf[1] += b;
  2038. buf[2] += c;
  2039. buf[3] += d;
  2040. }
  2041. void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
  2042. uint32_t t;
  2043. t = ctx->bits[0];
  2044. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
  2045. ctx->bits[1]++;
  2046. ctx->bits[1] += len >> 29;
  2047. t = (t >> 3) & 0x3f;
  2048. if (t) {
  2049. unsigned char *p = (unsigned char *) ctx->in + t;
  2050. t = 64 - t;
  2051. if (len < t) {
  2052. memcpy(p, buf, len);
  2053. return;
  2054. }
  2055. memcpy(p, buf, t);
  2056. byteReverse(ctx->in, 16);
  2057. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  2058. buf += t;
  2059. len -= t;
  2060. }
  2061. while (len >= 64) {
  2062. memcpy(ctx->in, buf, 64);
  2063. byteReverse(ctx->in, 16);
  2064. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  2065. buf += 64;
  2066. len -= 64;
  2067. }
  2068. memcpy(ctx->in, buf, len);
  2069. }
  2070. void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
  2071. unsigned count;
  2072. unsigned char *p;
  2073. uint32_t *a;
  2074. count = (ctx->bits[0] >> 3) & 0x3F;
  2075. p = ctx->in + count;
  2076. *p++ = 0x80;
  2077. count = 64 - 1 - count;
  2078. if (count < 8) {
  2079. memset(p, 0, count);
  2080. byteReverse(ctx->in, 16);
  2081. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  2082. memset(ctx->in, 0, 56);
  2083. } else {
  2084. memset(p, 0, count - 8);
  2085. }
  2086. byteReverse(ctx->in, 14);
  2087. a = (uint32_t *)ctx->in;
  2088. a[14] = ctx->bits[0];
  2089. a[15] = ctx->bits[1];
  2090. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  2091. byteReverse((unsigned char *) ctx->buf, 4);
  2092. memcpy(digest, ctx->buf, 16);
  2093. memset((char *) ctx, 0, sizeof(*ctx));
  2094. }
  2095. #endif // !HAVE_MD5
  2096. // Stringify binary data. Output buffer must be twice as big as input,
  2097. // because each byte takes 2 bytes in string representation
  2098. void mg_bin2str(char *to, const unsigned char *p, size_t len) {
  2099. static const char *hex = "0123456789abcdef";
  2100. for (; len--; p++) {
  2101. *to++ = hex[p[0] >> 4];
  2102. *to++ = hex[p[0] & 0x0f];
  2103. }
  2104. *to = '\0';
  2105. }
  2106. // Return stringified MD5 hash for list of vectors. Buffer must be 33 bytes.
  2107. void mg_md5(md5_buf_t buf, ...) {
  2108. unsigned char hash[16];
  2109. const char *p;
  2110. va_list ap;
  2111. MD5_CTX ctx;
  2112. MD5Init(&ctx);
  2113. va_start(ap, buf);
  2114. while ((p = va_arg(ap, const char *)) != NULL) {
  2115. MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
  2116. }
  2117. va_end(ap);
  2118. MD5Final(hash, &ctx);
  2119. mg_bin2str(buf, hash, sizeof(hash));
  2120. }
  2121. // Check the user's password, return 1 if OK
  2122. static int check_password(struct mg_connection *conn) {
  2123. char ha2[32 + 1], expected_response[32 + 1];
  2124. struct mg_auth_header *ah = conn->request_info.ah;
  2125. // Some of the parameters may be NULL
  2126. if (conn->request_info.request_method == NULL || ah == NULL ||
  2127. ah->nonce == NULL || ah->nc == NULL ||
  2128. ah->cnonce == NULL || ah->qop == NULL || ah->uri == NULL ||
  2129. ah->response == NULL) {
  2130. return 0;
  2131. }
  2132. // NOTE(lsm): due to a bug in MSIE, we do not compare the URI
  2133. // TODO(lsm): check for authentication timeout
  2134. if (// strcmp(ah->uri, conn->request_info.uri) != 0 ||
  2135. strlen(ah->response) != 32
  2136. // || now - strtoul(ah->nonce, NULL, 10) > 3600
  2137. ) {
  2138. return 0;
  2139. }
  2140. mg_md5(ha2, conn->request_info.request_method, ":", ah->uri, NULL);
  2141. mg_md5(expected_response, ah->ha1, ":", ah->nonce, ":", ah->nc,
  2142. ":", ah->cnonce, ":", ah->qop, ":", ha2, NULL);
  2143. return mg_strcasecmp(ah->response, expected_response) == 0;
  2144. }
  2145. // Use the global passwords file, if specified by auth_gpass option,
  2146. // or search for .htpasswd in the requested directory.
  2147. static FILE *open_auth_file(struct mg_connection *conn, const char *path) {
  2148. struct mg_context *ctx = conn->ctx;
  2149. char name[PATH_MAX];
  2150. const char *p, *e;
  2151. struct mgstat st;
  2152. FILE *fp;
  2153. if (ctx->config[GLOBAL_PASSWORDS_FILE] != NULL) {
  2154. // Use global passwords file
  2155. fp = mg_fopen(ctx->config[GLOBAL_PASSWORDS_FILE], "r");
  2156. if (fp == NULL)
  2157. cry(fc(ctx), "fopen(%s): %s",
  2158. ctx->config[GLOBAL_PASSWORDS_FILE], strerror(ERRNO));
  2159. } else if (!mg_stat(path, &st) && st.is_directory) {
  2160. (void) mg_snprintf(conn, name, sizeof(name), "%s%c%s",
  2161. path, DIRSEP, PASSWORDS_FILE_NAME);
  2162. fp = mg_fopen(name, "r");
  2163. } else {
  2164. // Try to find .htpasswd in requested directory.
  2165. for (p = path, e = p + strlen(p) - 1; e > p; e--)
  2166. if (IS_DIRSEP_CHAR(*e))
  2167. break;
  2168. (void) mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
  2169. (int) (e - p), p, DIRSEP, PASSWORDS_FILE_NAME);
  2170. fp = mg_fopen(name, "r");
  2171. }
  2172. return fp;
  2173. }
  2174. static int parse_auth_header(struct mg_connection *conn) {
  2175. char *name, *value, *s;
  2176. const char *auth_header;
  2177. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  2178. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  2179. return 0;
  2180. }
  2181. // Make modifiable copy of the auth header
  2182. conn->auth_header = mg_strdup(auth_header + 7);
  2183. s = conn->auth_header;
  2184. conn->request_info.ah = (struct mg_auth_header*)MG_CALLOC(1, sizeof(struct mg_auth_header));
  2185. // Parse authorization header
  2186. for (;;) {
  2187. // Gobble initial spaces
  2188. while (isspace(* (unsigned char *) s)) {
  2189. s++;
  2190. }
  2191. name = skip_quoted(&s, "=", " ", 0);
  2192. // Value is either quote-delimited, or ends at first comma or space.
  2193. if (s[0] == '\"') {
  2194. s++;
  2195. value = skip_quoted(&s, "\"", " ", '\\');
  2196. if (s[0] == ',') {
  2197. s++;
  2198. }
  2199. } else {
  2200. value = skip_quoted(&s, ", ", " ", 0); // IE uses commas, FF uses spaces
  2201. }
  2202. if (*name == '\0') {
  2203. break;
  2204. }
  2205. if (!strcmp(name, "username")) {
  2206. conn->request_info.ah->user = value;
  2207. } else if (!strcmp(name, "cnonce")) {
  2208. conn->request_info.ah->cnonce = value;
  2209. } else if (!strcmp(name, "response")) {
  2210. conn->request_info.ah->response = value;
  2211. } else if (!strcmp(name, "uri")) {
  2212. conn->request_info.ah->uri = value;
  2213. } else if (!strcmp(name, "qop")) {
  2214. conn->request_info.ah->qop = value;
  2215. } else if (!strcmp(name, "nc")) {
  2216. conn->request_info.ah->nc = value;
  2217. } else if (!strcmp(name, "nonce")) {
  2218. conn->request_info.ah->nonce = value;
  2219. }
  2220. }
  2221. // CGI needs it as REMOTE_USER
  2222. if (conn->request_info.ah->user != NULL) {
  2223. conn->request_info.remote_user = mg_strdup(conn->request_info.ah->user);
  2224. } else {
  2225. // Can't be valid; clean up
  2226. MG_FREE(conn->request_info.ah);
  2227. conn->request_info.ah = NULL;
  2228. MG_FREE(conn->auth_header);
  2229. conn->auth_header = NULL;
  2230. return 0;
  2231. }
  2232. return 1;
  2233. }
  2234. // Authorize against the opened passwords file. Return 1 if authorized.
  2235. static int authorize(struct mg_connection *conn, FILE *fp) {
  2236. char line[256], f_user[256], ha1[256], f_domain[256];
  2237. if (conn->request_info.ah == NULL)
  2238. return 0;
  2239. // Loop over passwords file
  2240. while (fgets(line, sizeof(line), fp) != NULL) {
  2241. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
  2242. continue;
  2243. }
  2244. if (!strcmp(conn->request_info.ah->user, f_user) &&
  2245. !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain)) {
  2246. conn->request_info.ah->ha1 = mg_strdup(ha1);
  2247. return check_password(conn);
  2248. }
  2249. }
  2250. return 0;
  2251. }
  2252. // Return 1 if request is authorised, 0 otherwise.
  2253. static int check_authorization(struct mg_connection *conn, const char *path) {
  2254. FILE *fp;
  2255. char fname[PATH_MAX];
  2256. struct vec uri_vec, filename_vec;
  2257. const char *list;
  2258. int authorized;
  2259. /* Check for embedded authentication first */
  2260. if (conn->request_info.ah != NULL &&
  2261. conn->request_info.ah->ha1 != NULL) {
  2262. return check_password(conn);
  2263. }
  2264. fp = NULL;
  2265. authorized = 1;
  2266. list = conn->ctx->config[PROTECT_URI];
  2267. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  2268. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  2269. mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  2270. (int) filename_vec.len, filename_vec.ptr);
  2271. if ((fp = mg_fopen(fname, "r")) == NULL) {
  2272. cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
  2273. }
  2274. break;
  2275. }
  2276. }
  2277. if (fp == NULL) {
  2278. fp = open_auth_file(conn, path);
  2279. }
  2280. if (fp != NULL) {
  2281. authorized = authorize(conn, fp);
  2282. (void) fclose(fp);
  2283. }
  2284. return authorized;
  2285. }
  2286. void mg_send_authorization_request(struct mg_connection *conn, const char *nonce) {
  2287. conn->request_info.status_code = 401;
  2288. (void) mg_printf(conn,
  2289. "HTTP/1.1 401 Unauthorized\r\n"
  2290. "Content-Length: 0\r\n"
  2291. "WWW-Authenticate: Digest qop=\"auth\", "
  2292. "realm=\"%s\", nonce=\"",
  2293. conn->ctx->config[AUTHENTICATION_DOMAIN]);
  2294. if (nonce == NULL)
  2295. (void) mg_printf(conn, "%lu", (unsigned long) time(NULL));
  2296. else
  2297. (void) mg_printf(conn, "%s", nonce);
  2298. (void) mg_printf(conn, "\"\r\n\r\n");
  2299. }
  2300. static int is_authorized_for_put(struct mg_connection *conn) {
  2301. FILE *fp;
  2302. int ret = 0;
  2303. /* No need to check for embedded authentication here: we already passed
  2304. * check_authorization() */
  2305. fp = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ? NULL :
  2306. mg_fopen(conn->ctx->config[PUT_DELETE_PASSWORDS_FILE], "r");
  2307. if (fp != NULL) {
  2308. ret = authorize(conn, fp);
  2309. (void) fclose(fp);
  2310. }
  2311. return ret;
  2312. }
  2313. int mg_modify_passwords_file(const char *fname, const char *domain,
  2314. const char *user, const char *pass) {
  2315. int found;
  2316. char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];
  2317. FILE *fp, *fp2;
  2318. found = 0;
  2319. fp = fp2 = NULL;
  2320. // Regard empty password as no password - remove user record.
  2321. if (pass != NULL && pass[0] == '\0') {
  2322. pass = NULL;
  2323. }
  2324. (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
  2325. // Create the file if does not exist
  2326. if ((fp = mg_fopen(fname, "a+")) != NULL) {
  2327. (void) fclose(fp);
  2328. }
  2329. // Open the given file and temporary file
  2330. if ((fp = mg_fopen(fname, "r")) == NULL) {
  2331. return 0;
  2332. } else if ((fp2 = mg_fopen(tmp, "w+")) == NULL) {
  2333. fclose(fp);
  2334. return 0;
  2335. }
  2336. // Copy the stuff to temporary file
  2337. while (fgets(line, sizeof(line), fp) != NULL) {
  2338. if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
  2339. continue;
  2340. }
  2341. if (!strcmp(u, user) && !strcmp(d, domain)) {
  2342. found++;
  2343. if (pass != NULL) {
  2344. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2345. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2346. }
  2347. } else {
  2348. (void) fprintf(fp2, "%s", line);
  2349. }
  2350. }
  2351. // If new user, just add it
  2352. if (!found && pass != NULL) {
  2353. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2354. (void) fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2355. }
  2356. // Close files
  2357. (void) fclose(fp);
  2358. (void) fclose(fp2);
  2359. // Put the temp file in place of real file
  2360. (void) mg_remove(fname);
  2361. (void) mg_rename(tmp, fname);
  2362. return 1;
  2363. }
  2364. struct de {
  2365. struct mg_connection *conn;
  2366. char *file_name;
  2367. struct mgstat st;
  2368. };
  2369. const char * mg_url_encode_to(const char *src, char *dst, size_t dst_len) {
  2370. static const char *dont_escape = "._-$,;~()";
  2371. static const char *hex = "0123456789abcdef";
  2372. const char *end = dst + dst_len - 1;
  2373. for (; *src != '\0' && dst < end; src++, dst++) {
  2374. if (isalnum(*(const unsigned char *) src) ||
  2375. strchr(dont_escape, * (const unsigned char *) src) != NULL) {
  2376. *dst = *src;
  2377. } else if (dst + 2 < end) {
  2378. dst[0] = '%';
  2379. dst[1] = hex[(* (const unsigned char *) src) >> 4];
  2380. dst[2] = hex[(* (const unsigned char *) src) & 0xf];
  2381. dst += 2;
  2382. } else break;
  2383. }
  2384. *dst = '\0';
  2385. return src;
  2386. }
  2387. char * mg_url_encode(const char *src) {
  2388. size_t dst_len = (strlen(src)*2)+1;
  2389. char *dst = (char*)MG_MALLOC(dst_len);
  2390. if(dst){
  2391. const char *done = mg_url_encode_to(src, dst, dst_len);
  2392. while(*done){
  2393. int old_dst_len = dst_len;
  2394. dst_len = dst_len + (dst_len / 2);
  2395. dst = (char*)MG_REALLOC(dst, dst_len);
  2396. if(!dst) break;
  2397. done = mg_url_encode_to(done, dst+strlen(dst), dst_len-old_dst_len);
  2398. }
  2399. }
  2400. return dst;
  2401. }
  2402. static void print_dir_entry(struct de *de) {
  2403. char size[64], mod[64], href[PATH_MAX];
  2404. if (de->st.is_directory) {
  2405. (void) mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  2406. } else {
  2407. // We use (signed) cast below because MSVC 6 compiler cannot
  2408. // convert unsigned __int64 to double. Sigh.
  2409. if (de->st.size < 1024) {
  2410. (void) mg_snprintf(de->conn, size, sizeof(size),
  2411. "%lu", (unsigned long) de->st.size);
  2412. } else if (de->st.size < 1024 * 1024) {
  2413. (void) mg_snprintf(de->conn, size, sizeof(size),
  2414. "%.1fk", (double) de->st.size / 1024.0);
  2415. } else if (de->st.size < 1024 * 1024 * 1024) {
  2416. (void) mg_snprintf(de->conn, size, sizeof(size),
  2417. "%.1fM", (double) de->st.size / 1048576);
  2418. } else {
  2419. (void) mg_snprintf(de->conn, size, sizeof(size),
  2420. "%.1fG", (double) de->st.size / 1073741824);
  2421. }
  2422. }
  2423. (void) strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.mtime));
  2424. mg_url_encode_to(de->file_name, href, sizeof(href));
  2425. de->conn->num_bytes_sent += mg_printf(de->conn,
  2426. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2427. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2428. de->conn->request_info.uri, href, de->st.is_directory ? "/" : "",
  2429. de->file_name, de->st.is_directory ? "/" : "", mod, size);
  2430. }
  2431. // This function is called from send_directory() and used for
  2432. // sorting directory entries by size, or name, or modification time.
  2433. // On windows, __cdecl specification is needed in case if project is built
  2434. // with __stdcall convention. qsort always requires __cdels callback.
  2435. static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {
  2436. const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
  2437. const char *query_string = a->conn->request_info.query_string;
  2438. int cmp_result = 0;
  2439. if (query_string == NULL) {
  2440. query_string = "na";
  2441. }
  2442. if (a->st.is_directory && !b->st.is_directory) {
  2443. return -1; // Always put directories on top
  2444. } else if (!a->st.is_directory && b->st.is_directory) {
  2445. return 1; // Always put directories on top
  2446. } else if (*query_string == 'n') {
  2447. cmp_result = strcmp(a->file_name, b->file_name);
  2448. } else if (*query_string == 's') {
  2449. cmp_result = a->st.size == b->st.size ? 0 :
  2450. a->st.size > b->st.size ? 1 : -1;
  2451. } else if (*query_string == 'd') {
  2452. cmp_result = a->st.mtime == b->st.mtime ? 0 :
  2453. a->st.mtime > b->st.mtime ? 1 : -1;
  2454. }
  2455. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  2456. }
  2457. static int must_hide_file(struct mg_connection *conn, const char *path) {
  2458. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  2459. const char *pattern = conn->ctx->config[HIDE_FILES];
  2460. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  2461. (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0);
  2462. }
  2463. static int scan_directory(struct mg_connection *conn, const char *dir,
  2464. void *data, void (*cb)(struct de *, void *)) {
  2465. char path[PATH_MAX];
  2466. struct dirent *dp;
  2467. DIR *dirp;
  2468. struct de de;
  2469. if ((dirp = opendir(dir)) == NULL) {
  2470. return 0;
  2471. } else {
  2472. de.conn = conn;
  2473. while ((dp = readdir(dirp)) != NULL) {
  2474. // Do not show current dir and hidden files
  2475. if (!strcmp(dp->d_name, ".") ||
  2476. !strcmp(dp->d_name, "..") ||
  2477. must_hide_file(conn, dp->d_name)) {
  2478. continue;
  2479. }
  2480. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, DIRSEP, dp->d_name);
  2481. // If we don't memset stat structure to zero, mtime will have
  2482. // garbage and strftime() will segfault later on in
  2483. // print_dir_entry(). memset is required only if mg_stat()
  2484. // fails. For more details, see
  2485. // http://code.google.com/p/mongoose/issues/detail?id=79
  2486. if (mg_stat(path, &de.st) != 0) {
  2487. memset(&de.st, 0, sizeof(de.st));
  2488. }
  2489. de.file_name = dp->d_name;
  2490. cb(&de, data);
  2491. }
  2492. (void) closedir(dirp);
  2493. }
  2494. return 1;
  2495. }
  2496. struct dir_scan_data {
  2497. struct de *entries;
  2498. int num_entries;
  2499. int arr_size;
  2500. };
  2501. static void dir_scan_callback(struct de *de, void *data) {
  2502. struct dir_scan_data *dsd = (struct dir_scan_data *) data;
  2503. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  2504. dsd->arr_size *= 2;
  2505. dsd->entries = (struct de *) MG_REALLOC(dsd->entries, dsd->arr_size *
  2506. sizeof(dsd->entries[0]));
  2507. }
  2508. if (dsd->entries == NULL) {
  2509. // TODO(lsm): propagate an error to the caller
  2510. dsd->num_entries = 0;
  2511. } else {
  2512. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  2513. dsd->entries[dsd->num_entries].st = de->st;
  2514. dsd->entries[dsd->num_entries].conn = de->conn;
  2515. dsd->num_entries++;
  2516. }
  2517. }
  2518. static void handle_directory_request(struct mg_connection *conn,
  2519. const char *dir) {
  2520. int i, sort_direction;
  2521. struct dir_scan_data data = { NULL, 0, 128 };
  2522. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  2523. send_http_error(conn, 500, "Cannot open directory",
  2524. "Error: opendir(%s): %s", dir, strerror(ERRNO));
  2525. return;
  2526. }
  2527. sort_direction = conn->request_info.query_string != NULL &&
  2528. conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
  2529. conn->must_close = 1;
  2530. mg_printf(conn, "%s",
  2531. "HTTP/1.1 200 OK\r\n"
  2532. "Connection: close\r\n"
  2533. "Content-Type: text/html; charset=utf-8\r\n\r\n");
  2534. conn->num_bytes_sent += mg_printf(conn,
  2535. "<html><head><title>Index of %s</title>"
  2536. "<style>th {text-align: left;}</style></head>"
  2537. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  2538. "<tr><th><a href=\"?n%c\">Name</a></th>"
  2539. "<th><a href=\"?d%c\">Modified</a></th>"
  2540. "<th><a href=\"?s%c\">Size</a></th></tr>"
  2541. "<tr><td colspan=\"3\"><hr></td></tr>",
  2542. conn->request_info.uri, conn->request_info.uri,
  2543. sort_direction, sort_direction, sort_direction);
  2544. // Print first entry - link to a parent directory
  2545. conn->num_bytes_sent += mg_printf(conn,
  2546. "<tr><td><a href=\"%s%s\">%s</a></td>"
  2547. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2548. conn->request_info.uri, "..", "Parent directory", "-", "-");
  2549. // Sort and print directory entries
  2550. qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),
  2551. compare_dir_entries);
  2552. for (i = 0; i < data.num_entries; i++) {
  2553. print_dir_entry(&data.entries[i]);
  2554. MG_FREE(data.entries[i].file_name);
  2555. }
  2556. MG_FREE(data.entries);
  2557. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  2558. conn->request_info.status_code = 200;
  2559. }
  2560. // Send len bytes from the opened file to the client.
  2561. static void send_file_data(struct mg_connection *conn, FILE *fp, size_t len) {
  2562. char buf[MG_BUF_LEN];
  2563. size_t to_read, num_read, num_written;
  2564. while (len > 0) {
  2565. // Calculate how much to read from the file in the buffer
  2566. to_read = sizeof(buf);
  2567. if (to_read > len) {
  2568. to_read = len;
  2569. }
  2570. // Read from file, exit the loop on error
  2571. if ((num_read = fread(buf, 1, to_read, fp)) <= 0) {
  2572. break;
  2573. }
  2574. // Send read bytes to the client, exit the loop on error
  2575. if ((num_written = mg_write(conn, buf, num_read)) != num_read) {
  2576. break;
  2577. }
  2578. // Both read and were successful, adjust counters
  2579. conn->num_bytes_sent += num_written;
  2580. len -= num_written;
  2581. }
  2582. }
  2583. static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
  2584. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  2585. }
  2586. static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  2587. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
  2588. }
  2589. static void construct_etag(char *buf, size_t buf_len,
  2590. const struct mgstat *stp) {
  2591. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  2592. (unsigned long) stp->mtime, stp->size);
  2593. }
  2594. static void handle_file_request(struct mg_connection *conn, const char *path,
  2595. struct mgstat *stp) {
  2596. char date[64], lm[64], etag[64], range[64];
  2597. const char *msg = "OK", *hdr;
  2598. time_t curtime = time(NULL);
  2599. int64_t cl, r1, r2;
  2600. struct vec mime_vec;
  2601. FILE *fp;
  2602. int n;
  2603. get_mime_type(conn->ctx, path, &mime_vec);
  2604. cl = stp->size;
  2605. conn->request_info.status_code = 200;
  2606. range[0] = '\0';
  2607. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2608. send_http_error(conn, 500, http_500_error,
  2609. "fopen(%s): %s", path, strerror(ERRNO));
  2610. return;
  2611. }
  2612. set_close_on_exec(fileno(fp));
  2613. // If Range: header specified, act accordingly
  2614. r1 = r2 = 0;
  2615. hdr = mg_get_header(conn, "Range");
  2616. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) {
  2617. conn->request_info.status_code = 206;
  2618. (void) fseeko(fp, (off_t) r1, SEEK_SET);
  2619. cl = n == 2 ? r2 - r1 + 1: cl - r1;
  2620. (void) mg_snprintf(conn, range, sizeof(range),
  2621. "Content-Range: bytes "
  2622. "%" INT64_FMT "-%"
  2623. INT64_FMT "/%" INT64_FMT "\r\n",
  2624. r1, r1 + cl - 1, stp->size);
  2625. msg = "Partial Content";
  2626. }
  2627. // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  2628. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
  2629. gmt_time_string(date, sizeof(date), &curtime);
  2630. gmt_time_string(lm, sizeof(lm), &stp->mtime);
  2631. construct_etag(etag, sizeof(etag), stp);
  2632. (void) mg_printf(conn,
  2633. "HTTP/1.1 %d %s\r\n"
  2634. "Date: %s\r\n"
  2635. "Last-Modified: %s\r\n"
  2636. "Etag: %s\r\n"
  2637. "Content-Type: %.*s\r\n"
  2638. "Content-Length: %" INT64_FMT "\r\n"
  2639. "Connection: %s\r\n"
  2640. "Accept-Ranges: bytes\r\n"
  2641. "%s\r\n",
  2642. conn->request_info.status_code, msg, date, lm, etag, (int) mime_vec.len,
  2643. mime_vec.ptr, cl, suggest_connection_header(conn), range);
  2644. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  2645. send_file_data(conn, fp, cl);
  2646. }
  2647. (void) fclose(fp);
  2648. }
  2649. void mg_send_file(struct mg_connection *conn, const char *path) {
  2650. struct mgstat st;
  2651. if (mg_stat(path, &st) == 0) {
  2652. handle_file_request(conn, path, &st);
  2653. } else {
  2654. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  2655. }
  2656. }
  2657. // Parse HTTP headers from the given buffer, advance buffer to the point
  2658. // where parsing stopped.
  2659. static void parse_http_headers(char **buf, struct mg_request_info *ri) {
  2660. int i;
  2661. for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
  2662. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  2663. ri->http_headers[i].value = skip(buf, "\r\n");
  2664. if (ri->http_headers[i].name[0] == '\0')
  2665. break;
  2666. ri->num_headers = i + 1;
  2667. }
  2668. }
  2669. static int is_valid_http_method(const char *method) {
  2670. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  2671. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  2672. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  2673. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND");
  2674. }
  2675. // Parse HTTP request, fill in mg_request_info structure.
  2676. // This function modifies the buffer by NUL-terminating
  2677. // HTTP request components, header names and header values.
  2678. static int parse_http_message(char *buf, int len, struct mg_request_info *ri) {
  2679. int request_length = get_request_len(buf, len);
  2680. if (request_length > 0) {
  2681. // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
  2682. ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
  2683. ri->num_headers = 0;
  2684. ri->status_code = -1;
  2685. buf[request_length - 1] = '\0';
  2686. // RFC says that all initial whitespaces should be ingored
  2687. while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
  2688. buf++;
  2689. }
  2690. ri->request_method = skip(&buf, " ");
  2691. ri->uri = skip(&buf, " ");
  2692. ri->http_version = skip(&buf, "\r\n");
  2693. parse_http_headers(&buf, ri);
  2694. }
  2695. return request_length;
  2696. }
  2697. static int parse_http_request(char *buf, int len, struct mg_request_info *ri) {
  2698. int result = parse_http_message(buf, len, ri);
  2699. if (result > 0 &&
  2700. is_valid_http_method(ri->request_method) &&
  2701. !strncmp(ri->http_version, "HTTP/", 5)) {
  2702. ri->http_version += 5; // Skip "HTTP/"
  2703. } else {
  2704. result = -1;
  2705. }
  2706. return result;
  2707. }
  2708. static int parse_http_response(char *buf, int len, struct mg_request_info *ri) {
  2709. int result = parse_http_message(buf, len, ri);
  2710. return result > 0 && !strncmp(ri->request_method, "HTTP/", 5) ? result : -1;
  2711. }
  2712. // Keep reading the input (either opened file descriptor fd, or socket sock,
  2713. // or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  2714. // buffer (which marks the end of HTTP request). Buffer buf may already
  2715. // have some data. The length of the data is stored in nread.
  2716. // Upon every read operation, increase nread by the number of bytes read.
  2717. static int read_request(FILE *fp, struct mg_connection *conn,
  2718. char *buf, int bufsiz, int *nread) {
  2719. int request_len, n = 1;
  2720. request_len = get_request_len(buf, *nread);
  2721. while (*nread < bufsiz && request_len == 0 && n > 0) {
  2722. n = pull(fp, conn, buf + *nread, bufsiz - *nread);
  2723. if (n > 0) {
  2724. *nread += n;
  2725. request_len = get_request_len(buf, *nread);
  2726. }
  2727. }
  2728. if (n < 0) {
  2729. // recv() error -> propagate error; do not process a b0rked-with-very-high-probability request
  2730. return -1;
  2731. }
  2732. return request_len;
  2733. }
  2734. // For given directory path, substitute it to valid index file.
  2735. // Return 0 if index file has been found, -1 if not found.
  2736. // If the file is found, it's stats is returned in stp.
  2737. static int substitute_index_file(struct mg_connection *conn, char *path,
  2738. size_t path_len, struct mgstat *stp) {
  2739. const char *list = conn->ctx->config[INDEX_FILES];
  2740. struct mgstat st;
  2741. struct vec filename_vec;
  2742. size_t n = strlen(path);
  2743. int found = 0;
  2744. // The 'path' given to us points to the directory. Remove all trailing
  2745. // directory separator characters from the end of the path, and
  2746. // then append single directory separator character.
  2747. while (n > 0 && IS_DIRSEP_CHAR(path[n - 1])) {
  2748. n--;
  2749. }
  2750. path[n] = DIRSEP;
  2751. // Traverse index files list. For each entry, append it to the given
  2752. // path and see if the file exists. If it exists, break the loop
  2753. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  2754. // Ignore too long entries that may overflow path buffer
  2755. if (filename_vec.len > path_len - (n + 2))
  2756. continue;
  2757. // Prepare full path to the index file
  2758. (void) mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  2759. // Does it exist?
  2760. if (mg_stat(path, &st) == 0) {
  2761. // Yes it does, break the loop
  2762. *stp = st;
  2763. found = 1;
  2764. break;
  2765. }
  2766. }
  2767. // If no index file exists, restore directory path
  2768. if (!found) {
  2769. path[n] = '\0';
  2770. }
  2771. return found;
  2772. }
  2773. // Return True if we should reply 304 Not Modified.
  2774. static int is_not_modified(const struct mg_connection *conn,
  2775. const struct mgstat *stp) {
  2776. char etag[64];
  2777. const char *ims = mg_get_header(conn, "If-Modified-Since");
  2778. const char *inm = mg_get_header(conn, "If-None-Match");
  2779. construct_etag(etag, sizeof(etag), stp);
  2780. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  2781. (ims != NULL && stp->mtime <= parse_date_string(ims));
  2782. }
  2783. static int forward_body_data(struct mg_connection *conn, FILE *fp,
  2784. SOCKET sock, SSL *ssl) {
  2785. const char *expect;
  2786. char buf[MG_BUF_LEN];
  2787. int to_read, nread, buffered_len, success = 0;
  2788. expect = mg_get_header(conn, "Expect");
  2789. assert(fp != NULL);
  2790. if (conn->content_len == -1) {
  2791. send_http_error(conn, 411, "Length Required", "");
  2792. } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
  2793. send_http_error(conn, 417, "Expectation Failed", "");
  2794. } else {
  2795. if (expect != NULL) {
  2796. (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  2797. }
  2798. buffered_len = conn->next_request - conn->body;
  2799. assert(buffered_len >= 0);
  2800. assert(conn->consumed_content == 0);
  2801. if (buffered_len > 0) {
  2802. if ((int64_t) buffered_len > conn->content_len) {
  2803. buffered_len = (int) conn->content_len;
  2804. }
  2805. push(fp, sock, ssl, conn->body, (int64_t) buffered_len);
  2806. conn->consumed_content += buffered_len;
  2807. conn->body += buffered_len;
  2808. }
  2809. nread = 0;
  2810. while (conn->consumed_content < conn->content_len) {
  2811. to_read = sizeof(buf);
  2812. if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
  2813. to_read = (int) (conn->content_len - conn->consumed_content);
  2814. }
  2815. nread = pull(NULL, conn, buf, to_read);
  2816. if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
  2817. break;
  2818. }
  2819. conn->consumed_content += nread;
  2820. }
  2821. if (conn->consumed_content == conn->content_len) {
  2822. success = nread >= 0;
  2823. }
  2824. // Each error code path in this function must send an error
  2825. if (!success) {
  2826. send_http_error(conn, 577, http_500_error, "");
  2827. }
  2828. }
  2829. return success;
  2830. }
  2831. #if !defined(NO_CGI)
  2832. // This structure helps to create an environment for the spawned CGI program.
  2833. // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  2834. // last element must be NULL.
  2835. // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  2836. // strings must reside in a contiguous buffer. The end of the buffer is
  2837. // marked by two '\0' characters.
  2838. // We satisfy both worlds: we create an envp array (which is vars), all
  2839. // entries are actually pointers inside buf.
  2840. struct cgi_env_block {
  2841. struct mg_connection *conn;
  2842. char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
  2843. int len; // Space taken
  2844. char *vars[MAX_CGI_ENVIR_VARS]; // char **envp
  2845. int nvars; // Number of variables
  2846. };
  2847. static char *addenv(struct cgi_env_block *block,
  2848. PRINTF_FORMAT_STRING(const char *fmt), ...)
  2849. PRINTF_ARGS(2, 3);
  2850. // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  2851. // pointer into the vars array.
  2852. static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
  2853. int n, space;
  2854. char *added;
  2855. va_list ap;
  2856. // Calculate how much space is left in the buffer
  2857. space = sizeof(block->buf) - block->len - 2;
  2858. assert(space >= 0);
  2859. // Make a pointer to the free space int the buffer
  2860. added = block->buf + block->len;
  2861. // Copy VARIABLE=VALUE\0 string into the free space
  2862. va_start(ap, fmt);
  2863. n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
  2864. va_end(ap);
  2865. // Make sure we do not overflow buffer and the envp array
  2866. if (n > 0 && n + 1 < space &&
  2867. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  2868. // Append a pointer to the added string into the envp array
  2869. block->vars[block->nvars++] = added;
  2870. // Bump up used length counter. Include \0 terminator
  2871. block->len += n + 1;
  2872. } else {
  2873. cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
  2874. }
  2875. return added;
  2876. }
  2877. static void prepare_cgi_environment(struct mg_connection *conn,
  2878. const char *prog,
  2879. struct cgi_env_block *blk) {
  2880. const char *s, *slash;
  2881. struct vec var_vec;
  2882. char *p, src_addr[20];
  2883. int i;
  2884. blk->len = blk->nvars = 0;
  2885. blk->conn = conn;
  2886. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2887. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  2888. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  2889. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  2890. // Prepare the environment block
  2891. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  2892. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  2893. addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
  2894. // TODO(lsm): fix this for IPv6 case
  2895. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  2896. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  2897. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  2898. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  2899. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  2900. // SCRIPT_NAME
  2901. assert(conn->request_info.uri[0] == '/');
  2902. slash = strrchr(conn->request_info.uri, '/');
  2903. if ((s = strrchr(prog, '/')) == NULL)
  2904. s = prog;
  2905. addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
  2906. conn->request_info.uri, s);
  2907. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  2908. addenv(blk, "PATH_TRANSLATED=%s", prog);
  2909. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  2910. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  2911. addenv(blk, "CONTENT_TYPE=%s", s);
  2912. if (conn->request_info.query_string != NULL)
  2913. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  2914. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  2915. addenv(blk, "CONTENT_LENGTH=%s", s);
  2916. if ((s = getenv("PATH")) != NULL)
  2917. addenv(blk, "PATH=%s", s);
  2918. if (conn->path_info != NULL) {
  2919. addenv(blk, "PATH_INFO=%s", conn->path_info);
  2920. }
  2921. #if defined(_WIN32)
  2922. if ((s = getenv("COMSPEC")) != NULL) {
  2923. addenv(blk, "COMSPEC=%s", s);
  2924. }
  2925. if ((s = getenv("SYSTEMROOT")) != NULL) {
  2926. addenv(blk, "SYSTEMROOT=%s", s);
  2927. }
  2928. if ((s = getenv("SystemDrive")) != NULL) {
  2929. addenv(blk, "SystemDrive=%s", s);
  2930. }
  2931. #else
  2932. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  2933. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  2934. #endif // _WIN32
  2935. if ((s = getenv("PERLLIB")) != NULL)
  2936. addenv(blk, "PERLLIB=%s", s);
  2937. if (conn->request_info.remote_user != NULL) {
  2938. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  2939. addenv(blk, "%s", "AUTH_TYPE=Digest");
  2940. }
  2941. // Add all headers as HTTP_* variables
  2942. for (i = 0; i < conn->request_info.num_headers; i++) {
  2943. p = addenv(blk, "HTTP_%s=%s",
  2944. conn->request_info.http_headers[i].name,
  2945. conn->request_info.http_headers[i].value);
  2946. // Convert variable name into uppercase, and change - to _
  2947. for (; *p != '=' && *p != '\0'; p++) {
  2948. if (*p == '-')
  2949. *p = '_';
  2950. *p = (char) toupper(* (unsigned char *) p);
  2951. }
  2952. }
  2953. // Add user-specified variables
  2954. s = conn->ctx->config[CGI_ENVIRONMENT];
  2955. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  2956. addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
  2957. }
  2958. blk->vars[blk->nvars++] = NULL;
  2959. blk->buf[blk->len++] = '\0';
  2960. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  2961. assert(blk->len > 0);
  2962. assert(blk->len < (int) sizeof(blk->buf));
  2963. }
  2964. void mg_handle_cgi_request(struct mg_connection *conn, const char *prog) {
  2965. int headers_len, data_len, i, fd_stdin[2], fd_stdout[2];
  2966. const char *status, *status_text;
  2967. char buf[16384], *pbuf, dir[PATH_MAX], *p;
  2968. struct mg_request_info ri;
  2969. struct cgi_env_block blk;
  2970. FILE *in, *out;
  2971. pid_t pid;
  2972. memset(&ri, 0, sizeof(ri));
  2973. prepare_cgi_environment(conn, prog, &blk);
  2974. // CGI must be executed in its own directory. 'dir' must point to the
  2975. // directory containing executable program, 'p' must point to the
  2976. // executable program name relative to 'dir'.
  2977. (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  2978. if ((p = strrchr(dir, DIRSEP)) != NULL) {
  2979. *p++ = '\0';
  2980. } else {
  2981. dir[0] = '.', dir[1] = '\0';
  2982. p = (char *) prog;
  2983. }
  2984. pid = (pid_t) -1;
  2985. fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;
  2986. in = out = NULL;
  2987. if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {
  2988. send_http_error(conn, 500, http_500_error,
  2989. "Cannot create CGI pipe: %s", strerror(ERRNO));
  2990. goto done;
  2991. } else if ((pid = spawn_process(conn, p, blk.buf, blk.vars,
  2992. fd_stdin[0], fd_stdout[1], dir)) == (pid_t) -1) {
  2993. send_http_error(conn, 500, http_500_error,
  2994. "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
  2995. goto done;
  2996. }
  2997. // spawn_process() must close those!
  2998. // If we don't mark them as closed, close() attempt before
  2999. // return from this function throws an exception on Windows.
  3000. // Windows does not like when closed descriptor is closed again.
  3001. fd_stdin[0] = fd_stdout[1] = -1;
  3002. if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||
  3003. (out = fdopen(fd_stdout[0], "rb")) == NULL) {
  3004. send_http_error(conn, 500, http_500_error,
  3005. "fopen: %s", strerror(ERRNO));
  3006. goto done;
  3007. }
  3008. setbuf(in, NULL);
  3009. setbuf(out, NULL);
  3010. // Send POST data to the CGI process if needed
  3011. if (!strcmp(conn->request_info.request_method, "POST") &&
  3012. !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  3013. goto done;
  3014. }
  3015. // Close so child gets an EOF.
  3016. fclose(in);
  3017. in = NULL;
  3018. fd_stdin[1] = -1;
  3019. // Now read CGI reply into a buffer. We need to set correct
  3020. // status code, thus we need to see all HTTP headers first.
  3021. // Do not send anything back to client, until we buffer in all
  3022. // HTTP headers.
  3023. data_len = 0;
  3024. headers_len = read_request(out, fc(conn->ctx), buf, sizeof(buf), &data_len);
  3025. if (headers_len <= 0) {
  3026. send_http_error(conn, 500, http_500_error,
  3027. "CGI program sent malformed or too big (>%u bytes) "
  3028. "HTTP headers: [%.*s]",
  3029. (unsigned) sizeof(buf), data_len, buf);
  3030. goto done;
  3031. }
  3032. pbuf = buf;
  3033. buf[headers_len - 1] = '\0';
  3034. parse_http_headers(&pbuf, &ri);
  3035. // Make up and send the status line
  3036. status_text = "OK";
  3037. if ((status = get_header(&ri, "Status")) != NULL) {
  3038. conn->request_info.status_code = atoi(status);
  3039. status_text = status;
  3040. while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
  3041. status_text++;
  3042. }
  3043. } else if (get_header(&ri, "Location") != NULL) {
  3044. conn->request_info.status_code = 302;
  3045. } else {
  3046. conn->request_info.status_code = 200;
  3047. }
  3048. if (get_header(&ri, "Connection") != NULL &&
  3049. !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) {
  3050. conn->must_close = 1;
  3051. }
  3052. (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->request_info.status_code,
  3053. status_text);
  3054. // Send headers
  3055. for (i = 0; i < ri.num_headers; i++) {
  3056. mg_printf(conn, "%s: %s\r\n",
  3057. ri.http_headers[i].name, ri.http_headers[i].value);
  3058. }
  3059. (void) mg_write(conn, "\r\n", 2);
  3060. // Send chunk of data that may have been read after the headers
  3061. conn->num_bytes_sent += mg_write(conn, buf + headers_len,
  3062. (size_t)(data_len - headers_len));
  3063. // Read the rest of CGI output and send to the client
  3064. send_file_data(conn, out, LONG_MAX);
  3065. done:
  3066. if (pid != (pid_t) -1) {
  3067. kill(pid, SIGKILL);
  3068. }
  3069. if (fd_stdin[0] != -1) {
  3070. (void) close(fd_stdin[0]);
  3071. }
  3072. if (fd_stdout[1] != -1) {
  3073. (void) close(fd_stdout[1]);
  3074. }
  3075. if (in != NULL) {
  3076. (void) fclose(in);
  3077. } else if (fd_stdin[1] != -1) {
  3078. (void) close(fd_stdin[1]);
  3079. }
  3080. if (out != NULL) {
  3081. (void) fclose(out);
  3082. } else if (fd_stdout[0] != -1) {
  3083. (void) close(fd_stdout[0]);
  3084. }
  3085. }
  3086. #endif // !NO_CGI
  3087. // For a given PUT path, create all intermediate subdirectories
  3088. // for given path. Return 0 if the path itself is a directory,
  3089. // or -1 on error, 1 if OK.
  3090. static int put_dir(const char *path) {
  3091. char buf[PATH_MAX];
  3092. const char *s, *p;
  3093. struct mgstat st;
  3094. int len, res = 1;
  3095. for (s = p = path + 2; (p = strchr(s, DIRSEP)) != NULL; s = ++p) {
  3096. len = p - path;
  3097. if (len >= (int) sizeof(buf)) {
  3098. res = -1;
  3099. break;
  3100. }
  3101. memcpy(buf, path, len);
  3102. buf[len] = '\0';
  3103. // Try to create intermediate directory
  3104. DEBUG_TRACE(("mkdir(%s)", buf));
  3105. if (mg_stat(buf, &st) == -1 && mg_mkdir(buf, 0755) != 0) {
  3106. res = -1;
  3107. break;
  3108. }
  3109. // Is path itself a directory?
  3110. if (p[1] == '\0') {
  3111. res = 0;
  3112. }
  3113. }
  3114. return res;
  3115. }
  3116. static void put_file(struct mg_connection *conn, const char *path) {
  3117. struct mgstat st;
  3118. const char *range;
  3119. int64_t r1, r2;
  3120. FILE *fp;
  3121. int rc;
  3122. conn->request_info.status_code = mg_stat(path, &st) == 0 ? 200 : 201;
  3123. if ((rc = put_dir(path)) == 0) {
  3124. mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->request_info.status_code);
  3125. } else if (rc == -1) {
  3126. send_http_error(conn, 500, http_500_error,
  3127. "put_dir(%s): %s", path, strerror(ERRNO));
  3128. } else if ((fp = mg_fopen(path, "wb+")) == NULL) {
  3129. send_http_error(conn, 500, http_500_error,
  3130. "fopen(%s): %s", path, strerror(ERRNO));
  3131. } else {
  3132. set_close_on_exec(fileno(fp));
  3133. range = mg_get_header(conn, "Content-Range");
  3134. r1 = r2 = 0;
  3135. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  3136. conn->request_info.status_code = 206;
  3137. // TODO(lsm): handle seek error
  3138. (void) fseeko(fp, (off_t) r1, SEEK_SET);
  3139. }
  3140. if (forward_body_data(conn, fp, INVALID_SOCKET, NULL))
  3141. (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n",
  3142. conn->request_info.status_code);
  3143. (void) fclose(fp);
  3144. }
  3145. }
  3146. static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
  3147. static void do_ssi_include(struct mg_connection *conn, const char *ssi,
  3148. char *tag, int include_level) {
  3149. char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
  3150. FILE *fp;
  3151. // sscanf() is safe here, since send_ssi_file() also uses buffer
  3152. // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  3153. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  3154. // File name is relative to the webserver root
  3155. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  3156. conn->ctx->config[DOCUMENT_ROOT], DIRSEP, file_name);
  3157. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {
  3158. // File name is relative to the webserver working directory
  3159. // or it is absolute system path
  3160. (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  3161. } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  3162. // File name is relative to the currect document
  3163. (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  3164. if ((p = strrchr(path, DIRSEP)) != NULL) {
  3165. p[1] = '\0';
  3166. }
  3167. (void) mg_snprintf(conn, path + strlen(path),
  3168. sizeof(path) - strlen(path), "%s", file_name);
  3169. } else {
  3170. cry(conn, "Bad SSI #include: [%s]", tag);
  3171. return;
  3172. }
  3173. if ((fp = mg_fopen(path, "rb")) == NULL) {
  3174. cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  3175. tag, path, strerror(ERRNO));
  3176. } else {
  3177. set_close_on_exec(fileno(fp));
  3178. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3179. strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
  3180. send_ssi_file(conn, path, fp, include_level + 1);
  3181. } else {
  3182. send_file_data(conn, fp, LONG_MAX); //INT64_MAX);
  3183. }
  3184. (void) fclose(fp);
  3185. }
  3186. }
  3187. #if !defined(NO_POPEN)
  3188. static void do_ssi_exec(struct mg_connection *conn, char *tag) {
  3189. char cmd[MG_BUF_LEN];
  3190. FILE *fp;
  3191. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  3192. cry(conn, "Bad SSI #exec: [%s]", tag);
  3193. } else if ((fp = popen(cmd, "r")) == NULL) {
  3194. cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  3195. } else {
  3196. send_file_data(conn, fp, LONG_MAX);
  3197. (void) pclose(fp);
  3198. }
  3199. }
  3200. #endif // !NO_POPEN
  3201. static void send_ssi_file(struct mg_connection *conn, const char *path,
  3202. FILE *fp, int include_level) {
  3203. char buf[MG_BUF_LEN];
  3204. int ch, len, in_ssi_tag;
  3205. if (include_level > 10) {
  3206. cry(conn, "SSI #include level is too deep (%s)", path);
  3207. return;
  3208. }
  3209. in_ssi_tag = 0;
  3210. len = 0;
  3211. while ((ch = fgetc(fp)) != EOF) {
  3212. if (in_ssi_tag && ch == '>') {
  3213. in_ssi_tag = 0;
  3214. buf[len++] = (char) ch;
  3215. buf[len] = '\0';
  3216. assert(len <= (int) sizeof(buf));
  3217. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  3218. // Not an SSI tag, pass it
  3219. (void) mg_write(conn, buf, (size_t)len);
  3220. } else {
  3221. if (!memcmp(buf + 5, "include", 7)) {
  3222. do_ssi_include(conn, path, buf + 12, include_level);
  3223. #if !defined(NO_POPEN)
  3224. } else if (!memcmp(buf + 5, "exec", 4)) {
  3225. do_ssi_exec(conn, buf + 9);
  3226. #endif // !NO_POPEN
  3227. } else {
  3228. cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
  3229. }
  3230. }
  3231. len = 0;
  3232. } else if (in_ssi_tag) {
  3233. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  3234. // Not an SSI tag
  3235. in_ssi_tag = 0;
  3236. } else if (len == (int) sizeof(buf) - 2) {
  3237. cry(conn, "%s: SSI tag is too large", path);
  3238. len = 0;
  3239. }
  3240. buf[len++] = ch & 0xff;
  3241. } else if (ch == '<') {
  3242. in_ssi_tag = 1;
  3243. if (len > 0) {
  3244. (void) mg_write(conn, buf, (size_t)len);
  3245. }
  3246. len = 0;
  3247. buf[len++] = ch & 0xff;
  3248. } else {
  3249. buf[len++] = ch & 0xff;
  3250. if (len == (int) sizeof(buf)) {
  3251. (void) mg_write(conn, buf, (size_t)len);
  3252. len = 0;
  3253. }
  3254. }
  3255. }
  3256. // Send the rest of buffered data
  3257. if (len > 0) {
  3258. (void) mg_write(conn, buf, (size_t)len);
  3259. }
  3260. }
  3261. static void handle_ssi_file_request(struct mg_connection *conn,
  3262. const char *path) {
  3263. FILE *fp;
  3264. if ((fp = mg_fopen(path, "rb")) == NULL) {
  3265. send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
  3266. strerror(ERRNO));
  3267. } else {
  3268. conn->must_close = 1;
  3269. set_close_on_exec(fileno(fp));
  3270. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  3271. "Content-Type: text/html\r\nConnection: %s\r\n\r\n",
  3272. suggest_connection_header(conn));
  3273. send_ssi_file(conn, path, fp, 0);
  3274. (void) fclose(fp);
  3275. }
  3276. }
  3277. static void send_options(struct mg_connection *conn) {
  3278. conn->request_info.status_code = 200;
  3279. (void) mg_printf(conn,
  3280. "HTTP/1.1 200 OK\r\n"
  3281. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS\r\n"
  3282. "DAV: 1\r\n\r\n");
  3283. }
  3284. // Writes PROPFIND properties for a collection element
  3285. static void print_props(struct mg_connection *conn, const char* uri,
  3286. struct mgstat* st) {
  3287. char mtime[64];
  3288. gmt_time_string(mtime, sizeof(mtime), &st->mtime);
  3289. conn->num_bytes_sent += mg_printf(conn,
  3290. "<d:response>"
  3291. "<d:href>%s</d:href>"
  3292. "<d:propstat>"
  3293. "<d:prop>"
  3294. "<d:resourcetype>%s</d:resourcetype>"
  3295. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  3296. "<d:getlastmodified>%s</d:getlastmodified>"
  3297. "</d:prop>"
  3298. "<d:status>HTTP/1.1 200 OK</d:status>"
  3299. "</d:propstat>"
  3300. "</d:response>\n",
  3301. uri,
  3302. st->is_directory ? "<d:collection/>" : "",
  3303. st->size,
  3304. mtime);
  3305. }
  3306. static void print_dav_dir_entry(struct de *de, void *data) {
  3307. char href[PATH_MAX];
  3308. struct mg_connection *conn = (struct mg_connection *) data;
  3309. mg_snprintf(conn, href, sizeof(href), "%s%s",
  3310. conn->request_info.uri, de->file_name);
  3311. print_props(conn, href, &de->st);
  3312. }
  3313. static void handle_propfind(struct mg_connection *conn, const char* path,
  3314. struct mgstat* st) {
  3315. const char *depth = mg_get_header(conn, "Depth");
  3316. conn->must_close = 1;
  3317. conn->request_info.status_code = 207;
  3318. mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
  3319. "Connection: close\r\n"
  3320. "Content-Type: text/xml; charset=utf-8\r\n\r\n");
  3321. conn->num_bytes_sent += mg_printf(conn,
  3322. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  3323. "<d:multistatus xmlns:d='DAV:'>\n");
  3324. // Print properties for the requested resource itself
  3325. print_props(conn, conn->request_info.uri, st);
  3326. // If it is a directory, print directory entries too if Depth is not 0
  3327. if (st->is_directory &&
  3328. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  3329. (depth == NULL || strcmp(depth, "0") != 0)) {
  3330. scan_directory(conn, path, conn, &print_dav_dir_entry);
  3331. }
  3332. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  3333. }
  3334. #if defined(USE_WEBSOCKET)
  3335. // START OF SHA-1 code
  3336. // Copyright(c) By Steve Reid <[email protected]>
  3337. #define SHA1HANDSOFF
  3338. #if defined(__sun)
  3339. #include "solarisfixes.h"
  3340. #endif
  3341. union char64long16 { unsigned char c[64]; uint32_t l[16]; };
  3342. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  3343. static uint32_t blk0(union char64long16 *block, int i) {
  3344. // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
  3345. if (!is_big_endian()) {
  3346. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  3347. (rol(block->l[i], 8) & 0x00FF00FF);
  3348. }
  3349. return block->l[i];
  3350. }
  3351. #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
  3352. ^block->l[(i+2)&15]^block->l[i&15],1))
  3353. #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
  3354. #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
  3355. #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
  3356. #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
  3357. #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
  3358. typedef struct {
  3359. uint32_t state[5];
  3360. uint32_t count[2];
  3361. unsigned char buffer[64];
  3362. } SHA1_CTX;
  3363. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
  3364. uint32_t a, b, c, d, e;
  3365. union char64long16 block[1];
  3366. memcpy(block, buffer, 64);
  3367. a = state[0];
  3368. b = state[1];
  3369. c = state[2];
  3370. d = state[3];
  3371. e = state[4];
  3372. R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
  3373. R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
  3374. R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
  3375. R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
  3376. R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
  3377. R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
  3378. R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
  3379. R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
  3380. R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
  3381. R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
  3382. R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
  3383. R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
  3384. R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
  3385. R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
  3386. R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
  3387. R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
  3388. R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
  3389. R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
  3390. R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
  3391. R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
  3392. state[0] += a;
  3393. state[1] += b;
  3394. state[2] += c;
  3395. state[3] += d;
  3396. state[4] += e;
  3397. a = b = c = d = e = 0;
  3398. memset(block, '\0', sizeof(block));
  3399. }
  3400. static void SHA1Init(SHA1_CTX* context) {
  3401. context->state[0] = 0x67452301;
  3402. context->state[1] = 0xEFCDAB89;
  3403. context->state[2] = 0x98BADCFE;
  3404. context->state[3] = 0x10325476;
  3405. context->state[4] = 0xC3D2E1F0;
  3406. context->count[0] = context->count[1] = 0;
  3407. }
  3408. static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
  3409. uint32_t len) {
  3410. uint32_t i, j;
  3411. j = context->count[0];
  3412. if ((context->count[0] += len << 3) < j)
  3413. context->count[1]++;
  3414. context->count[1] += (len>>29);
  3415. j = (j >> 3) & 63;
  3416. if ((j + len) > 63) {
  3417. memcpy(&context->buffer[j], data, (i = 64-j));
  3418. SHA1Transform(context->state, context->buffer);
  3419. for ( ; i + 63 < len; i += 64) {
  3420. SHA1Transform(context->state, &data[i]);
  3421. }
  3422. j = 0;
  3423. }
  3424. else i = 0;
  3425. memcpy(&context->buffer[j], &data[i], len - i);
  3426. }
  3427. static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
  3428. unsigned i;
  3429. unsigned char finalcount[8], c;
  3430. for (i = 0; i < 8; i++) {
  3431. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  3432. >> ((3-(i & 3)) * 8) ) & 255);
  3433. }
  3434. c = 0200;
  3435. SHA1Update(context, &c, 1);
  3436. while ((context->count[0] & 504) != 448) {
  3437. c = 0000;
  3438. SHA1Update(context, &c, 1);
  3439. }
  3440. SHA1Update(context, finalcount, 8);
  3441. for (i = 0; i < 20; i++) {
  3442. digest[i] = (unsigned char)
  3443. ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  3444. }
  3445. memset(context, '\0', sizeof(*context));
  3446. memset(&finalcount, '\0', sizeof(finalcount));
  3447. }
  3448. // END OF SHA1 CODE
  3449. static void base64_encode(const unsigned char *src, int src_len, char *dst) {
  3450. static const char *b64 =
  3451. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3452. int i, j, a, b, c;
  3453. for (i = j = 0; i < src_len; i += 3) {
  3454. a = src[i];
  3455. b = i + 1 >= src_len ? 0 : src[i + 1];
  3456. c = i + 2 >= src_len ? 0 : src[i + 2];
  3457. dst[j++] = b64[a >> 2];
  3458. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3459. if (i + 1 < src_len) {
  3460. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3461. }
  3462. if (i + 2 < src_len) {
  3463. dst[j++] = b64[c & 63];
  3464. }
  3465. }
  3466. while (j % 4 != 0) {
  3467. dst[j++] = '=';
  3468. }
  3469. dst[j++] = '\0';
  3470. }
  3471. static void send_websocket_handshake(struct mg_connection *conn) {
  3472. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3473. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  3474. SHA1_CTX sha_ctx;
  3475. mg_snprintf(conn, buf, sizeof(buf), "%s%s",
  3476. mg_get_header(conn, "Sec-WebSocket-Key"), magic);
  3477. SHA1Init(&sha_ctx);
  3478. SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
  3479. SHA1Final((unsigned char *) sha, &sha_ctx);
  3480. base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  3481. mg_printf(conn, "%s%s%s",
  3482. "HTTP/1.1 101 Switching Protocols\r\n"
  3483. "Upgrade: websocket\r\n"
  3484. "Connection: Upgrade\r\n"
  3485. "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
  3486. }
  3487. static void read_websocket(struct mg_connection *conn) {
  3488. unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;
  3489. int n;
  3490. size_t i, len, mask_len, data_len, header_len, body_len;
  3491. char mem[4 * 1024], *data;
  3492. assert(conn->content_len == 0);
  3493. for (;;) {
  3494. header_len = 0;
  3495. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  3496. len = buf[1] & 127;
  3497. mask_len = buf[1] & 128 ? 4 : 0;
  3498. if (len < 126 && body_len >= mask_len) {
  3499. data_len = len;
  3500. header_len = 2 + mask_len;
  3501. } else if (len == 126 && body_len >= 4 + mask_len) {
  3502. header_len = 4 + mask_len;
  3503. data_len = ((((int) buf[2]) << 8) + buf[3]);
  3504. } else if (body_len >= 10 + mask_len) {
  3505. header_len = 10 + mask_len;
  3506. data_len = (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
  3507. htonl(* (uint32_t *) &buf[6]);
  3508. }
  3509. }
  3510. if (header_len > 0) {
  3511. // Allocate space to hold websocket payload
  3512. data = mem;
  3513. if (data_len > sizeof(mem) && (data = malloc(data_len)) == NULL) {
  3514. // Allocation failed, exit the loop and then close the connection
  3515. // TODO: notify user about the failure
  3516. break;
  3517. }
  3518. // Read frame payload into the allocated buffer.
  3519. assert(body_len >= header_len);
  3520. if (data_len + header_len > body_len) {
  3521. len = body_len - header_len;
  3522. memcpy(data, buf + header_len, len);
  3523. // TODO: handle pull error
  3524. pull(NULL, conn, data + len, data_len - len);
  3525. conn->data_len = 0;
  3526. } else {
  3527. len = data_len + header_len;
  3528. memcpy(data, buf + header_len, data_len);
  3529. memmove(buf, buf + len, body_len - len);
  3530. conn->data_len -= len;
  3531. }
  3532. // Apply mask if necessary
  3533. if (mask_len > 0) {
  3534. for (i = 0; i < data_len; i++) {
  3535. data[i] ^= buf[header_len - mask_len + (i % 4)];
  3536. }
  3537. }
  3538. // Exit the loop if callback signalled to exit,
  3539. // or "connection close" opcode received.
  3540. if ((conn->ctx->callbacks.websocket_data != NULL &&
  3541. !conn->ctx->callbacks.websocket_data(conn, buf[0], data, data_len)) ||
  3542. (buf[0] & 0xf) == 8) { // Opcode == 8, connection close
  3543. break;
  3544. }
  3545. if (data != mem) {
  3546. free(data);
  3547. }
  3548. // Not breaking the loop, process next websocket frame.
  3549. } else {
  3550. // Buffering websocket request
  3551. if ((n = pull(NULL, conn, conn->buf + conn->data_len,
  3552. conn->buf_size - conn->data_len)) <= 0) {
  3553. break;
  3554. }
  3555. conn->data_len += n;
  3556. }
  3557. }
  3558. }
  3559. static void handle_websocket_request(struct mg_connection *conn) {
  3560. if (strcmp(mg_get_header(conn, "Sec-WebSocket-Version"), "13") != 0) {
  3561. send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
  3562. } else if (conn->ctx->callbacks.websocket_connect != NULL &&
  3563. conn->ctx->callbacks.websocket_connect(conn) != 0) {
  3564. // Callback has returned non-zero, do not proceed with handshake
  3565. } else {
  3566. send_websocket_handshake(conn);
  3567. if (conn->ctx->callbacks.websocket_ready != NULL) {
  3568. conn->ctx->callbacks.websocket_ready(conn);
  3569. }
  3570. read_websocket(conn);
  3571. }
  3572. }
  3573. static int is_websocket_request(const struct mg_connection *conn) {
  3574. const char *host, *upgrade, *connection, *version, *key;
  3575. host = mg_get_header(conn, "Host");
  3576. upgrade = mg_get_header(conn, "Upgrade");
  3577. connection = mg_get_header(conn, "Connection");
  3578. key = mg_get_header(conn, "Sec-WebSocket-Key");
  3579. version = mg_get_header(conn, "Sec-WebSocket-Version");
  3580. return host != NULL && upgrade != NULL && connection != NULL &&
  3581. key != NULL && version != NULL &&
  3582. mg_strcasestr(upgrade, "websocket") != NULL &&
  3583. mg_strcasestr(connection, "Upgrade") != NULL;
  3584. }
  3585. #endif // !USE_WEBSOCKET
  3586. static int isbyte(int n) {
  3587. return n >= 0 && n <= 255;
  3588. }
  3589. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  3590. int n, a, b, c, d, slash = 32, len = 0;
  3591. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  3592. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  3593. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
  3594. slash >= 0 && slash < 33) {
  3595. len = n;
  3596. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  3597. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  3598. }
  3599. return len;
  3600. }
  3601. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) {
  3602. int throttle = 0;
  3603. struct vec vec, val;
  3604. uint32_t net, mask;
  3605. char mult;
  3606. double v;
  3607. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  3608. mult = ',';
  3609. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  3610. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
  3611. continue;
  3612. }
  3613. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
  3614. if (vec.len == 1 && vec.ptr[0] == '*') {
  3615. throttle = (int) v;
  3616. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  3617. if ((remote_ip & mask) == net) {
  3618. throttle = (int) v;
  3619. }
  3620. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  3621. throttle = (int) v;
  3622. }
  3623. }
  3624. return throttle;
  3625. }
  3626. static uint32_t get_remote_ip(const struct mg_connection *conn) {
  3627. return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
  3628. }
  3629. // This is the heart of the Mongoose's logic.
  3630. // This function is called when the request is read, parsed and validated,
  3631. // and Mongoose must decide what action to take: serve a file, or
  3632. // a directory, or call embedded function, etcetera.
  3633. static void handle_request(struct mg_connection *conn) {
  3634. struct mg_request_info *ri = &conn->request_info;
  3635. char path[PATH_MAX];
  3636. int stat_result, uri_len;
  3637. struct mgstat st;
  3638. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  3639. *conn->request_info.query_string++ = '\0';
  3640. }
  3641. uri_len = (int) strlen(ri->uri);
  3642. mg_url_decode(ri->uri, (size_t)uri_len, ri->uri, (size_t)(uri_len + 1), 0);
  3643. remove_double_dots_and_double_slashes(ri->uri);
  3644. stat_result = convert_uri_to_file_name(conn, path, sizeof(path), &st);
  3645. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  3646. get_remote_ip(conn), ri->uri);
  3647. DEBUG_TRACE(("%s", ri->uri));
  3648. parse_auth_header(conn);
  3649. if (call_user(conn, MG_AUTHENTICATE) != NULL) {
  3650. // Do nothing, callback has served the request
  3651. } else if (!check_authorization(conn, path)) {
  3652. mg_send_authorization_request(conn, NULL);
  3653. #if defined(USE_WEBSOCKET)
  3654. } else if (is_websocket_request(conn)) {
  3655. handle_websocket_request(conn);
  3656. #endif
  3657. } else if (call_user(conn, MG_NEW_REQUEST) != NULL) {
  3658. // Do nothing, callback has served the request
  3659. } else if (!strcmp(ri->request_method, "OPTIONS")) {
  3660. send_options(conn);
  3661. } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  3662. send_http_error(conn, 404, "Not Found", "Not Found");
  3663. } else if ((!strcmp(ri->request_method, "PUT") ||
  3664. !strcmp(ri->request_method, "DELETE")) &&
  3665. (conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ||
  3666. !is_authorized_for_put(conn))) {
  3667. mg_send_authorization_request(conn, NULL);
  3668. } else if (!strcmp(ri->request_method, "PUT")) {
  3669. put_file(conn, path);
  3670. } else if (!strcmp(ri->request_method, "DELETE")) {
  3671. if (mg_remove(path) == 0) {
  3672. send_http_error(conn, 200, "OK", "");
  3673. } else {
  3674. send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
  3675. strerror(ERRNO));
  3676. }
  3677. } else if (stat_result != 0 || must_hide_file(conn, path)) {
  3678. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  3679. } else if (st.is_directory && ri->uri[uri_len - 1] != '/') {
  3680. (void) mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
  3681. "Location: %s/\r\n\r\n", ri->uri);
  3682. } else if (!strcmp(ri->request_method, "PROPFIND")) {
  3683. handle_propfind(conn, path, &st);
  3684. } else if (st.is_directory &&
  3685. !substitute_index_file(conn, path, sizeof(path), &st)) {
  3686. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
  3687. handle_directory_request(conn, path);
  3688. } else {
  3689. send_http_error(conn, 403, "Directory Listing Denied",
  3690. "Directory listing denied");
  3691. }
  3692. #if !defined(NO_CGI)
  3693. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3694. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3695. path) > 0) {
  3696. if (strcmp(ri->request_method, "POST") &&
  3697. strcmp(ri->request_method, "GET")) {
  3698. send_http_error(conn, 501, "Not Implemented",
  3699. "Method %s is not implemented", ri->request_method);
  3700. } else {
  3701. mg_handle_cgi_request(conn, path);
  3702. }
  3703. #endif // !NO_CGI
  3704. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3705. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  3706. path) > 0) {
  3707. handle_ssi_file_request(conn, path);
  3708. } else if (is_not_modified(conn, &st)) {
  3709. send_http_error(conn, 304, "Not Modified", "");
  3710. } else {
  3711. handle_file_request(conn, path, &st);
  3712. }
  3713. }
  3714. static void close_all_listening_sockets(struct mg_context *ctx) {
  3715. struct socket *sp, *tmp;
  3716. for (sp = ctx->listening_sockets; sp != NULL; sp = tmp) {
  3717. tmp = sp->next;
  3718. (void) closesocket(sp->sock);
  3719. MG_FREE(sp);
  3720. }
  3721. }
  3722. // Valid listening port specification is: [ip_address:]port[s]
  3723. // Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  3724. // TODO(lsm): add parsing of the IPv6 address
  3725. static int parse_port_string(const struct vec *vec, struct socket *so) {
  3726. int a, b, c, d, port, len;
  3727. // MacOS needs that. If we do not zero it, subsequent bind() will fail.
  3728. // Also, all-zeroes in the socket address means binding to all addresses
  3729. // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  3730. memset(so, 0, sizeof(*so));
  3731. if (sscanf(vec->ptr, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &len) == 5) {
  3732. // Bind to a specific IPv4 address
  3733. so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
  3734. } else if (sscanf(vec->ptr, "%d%n", &port, &len) != 1 ||
  3735. len <= 0 ||
  3736. len > (int) vec->len ||
  3737. (vec->ptr[len] && vec->ptr[len] != 's' &&
  3738. vec->ptr[len] != 'r' && vec->ptr[len] != ',')) {
  3739. return 0;
  3740. }
  3741. so->is_ssl = vec->ptr[len] == 's';
  3742. so->ssl_redir = vec->ptr[len] == 'r';
  3743. #if defined(USE_IPV6)
  3744. so->lsa.sin6.sin6_family = AF_INET6;
  3745. so->lsa.sin6.sin6_port = htons((uint16_t) port);
  3746. #else
  3747. so->lsa.sin.sin_family = AF_INET;
  3748. so->lsa.sin.sin_port = htons((uint16_t) port);
  3749. #endif
  3750. return 1;
  3751. }
  3752. static void set_receive_timeout(SOCKET sock) {
  3753. #ifdef SOCKET_RECEIVE_TIMEOUT
  3754. if (SOCKET_RECEIVE_TIMEOUT>0) {
  3755. #ifdef _WIN32
  3756. unsigned long to = SOCKET_RECEIVE_TIMEOUT * 1000;
  3757. unsigned int uto = SOCKET_RECEIVE_TIMEOUT * 1000;
  3758. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&to, sizeof(to));
  3759. /* TCP_USER_TIMEOUT (according to RFC5482) is not (yet?) supported in win32 ?
  3760. setsockopt(sock, IPPROTO_TCP, TCP_USER_TIMEOUT, (const char *)&uto, sizeof(uto));
  3761. */
  3762. #else
  3763. unsigned int uto = SOCKET_RECEIVE_TIMEOUT * 1000;
  3764. struct timeval to;
  3765. to.tv_usec=0;
  3766. to.tv_sec=socketTimeOut;
  3767. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const void *)&to, sizeof(to));
  3768. setsockopt(sock, SOL_TCP, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  3769. #endif
  3770. }
  3771. #endif
  3772. }
  3773. static int set_ports_option(struct mg_context *ctx) {
  3774. const char *list = ctx->config[LISTENING_PORTS];
  3775. int on = 1, success = 1;
  3776. SOCKET sock;
  3777. struct vec vec;
  3778. struct socket so, *listener;
  3779. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  3780. if (!parse_port_string(&vec, &so)) {
  3781. cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
  3782. __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]");
  3783. success = 0;
  3784. } else if (so.is_ssl &&
  3785. (ctx->ssl_ctx == NULL || ctx->config[SSL_CERTIFICATE] == NULL)) {
  3786. cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
  3787. success = 0;
  3788. } else if ((sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  3789. INVALID_SOCKET ||
  3790. #if !defined(_WIN32)
  3791. // On Windows, SO_REUSEADDR is recommended only for
  3792. // broadcast UDP sockets
  3793. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) != 0 ||
  3794. #endif // !_WIN32
  3795. // Set TCP keep-alive. This is needed because if HTTP-level
  3796. // keep-alive is enabled, and client resets the connection,
  3797. // server won't get TCP FIN or RST and will keep the connection
  3798. // open forever. With TCP keep-alive, next keep-alive
  3799. // handshake will figure out that the client is down and
  3800. // will close the server end.
  3801. // Thanks to Igor Klopov who suggested the patch.
  3802. setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on, sizeof(on)) != 0 ||
  3803. bind(sock, &so.lsa.sa, sizeof(so.lsa)) != 0 ||
  3804. listen(sock, SOMAXCONN) != 0) {
  3805. closesocket(sock);
  3806. cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__,
  3807. (int) vec.len, vec.ptr, strerror(ERRNO));
  3808. success = 0;
  3809. } else if ((listener = (struct socket *)
  3810. MG_CALLOC(1, sizeof(*listener))) == NULL) {
  3811. // NOTE(lsm): order is important: call cry before closesocket(),
  3812. // cause closesocket() alters the errno.
  3813. cry(fc(ctx), "%s: %s", __func__, strerror(ERRNO));
  3814. closesocket(sock);
  3815. success = 0;
  3816. } else {
  3817. *listener = so;
  3818. listener->sock = sock;
  3819. set_close_on_exec(listener->sock);
  3820. listener->next = ctx->listening_sockets;
  3821. ctx->listening_sockets = listener;
  3822. //set_receive_timeout(sock); // <bel> set timeouts
  3823. }
  3824. }
  3825. if (!success) {
  3826. close_all_listening_sockets(ctx);
  3827. }
  3828. return success;
  3829. }
  3830. static void log_header(const struct mg_connection *conn, const char *header,
  3831. FILE *fp) {
  3832. const char *header_value;
  3833. if ((header_value = mg_get_header(conn, header)) == NULL) {
  3834. (void) fprintf(fp, "%s", " -");
  3835. } else {
  3836. (void) fprintf(fp, " \"%s\"", header_value);
  3837. }
  3838. }
  3839. static void log_access(const struct mg_connection *conn) {
  3840. const struct mg_request_info *ri;
  3841. FILE *fp;
  3842. char date[64], src_addr[20];
  3843. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :
  3844. mg_fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  3845. if (fp == NULL)
  3846. return;
  3847. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
  3848. localtime(&conn->birth_time));
  3849. ri = &conn->request_info;
  3850. flockfile(fp);
  3851. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3852. fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
  3853. src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
  3854. ri->request_method ? ri->request_method : "-",
  3855. ri->uri ? ri->uri : "-", ri->http_version,
  3856. conn->request_info.status_code, conn->num_bytes_sent);
  3857. log_header(conn, "Referer", fp);
  3858. log_header(conn, "User-Agent", fp);
  3859. fputc('\n', fp);
  3860. fflush(fp);
  3861. funlockfile(fp);
  3862. fclose(fp);
  3863. }
  3864. // Verify given socket address against the ACL.
  3865. // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  3866. static int check_acl(struct mg_context *ctx, uint32_t remote_ip) {
  3867. int allowed, flag;
  3868. uint32_t net, mask;
  3869. struct vec vec;
  3870. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  3871. // If any ACL is set, deny by default
  3872. allowed = list == NULL ? '+' : '-';
  3873. while ((list = next_option(list, &vec, NULL)) != NULL) {
  3874. flag = vec.ptr[0];
  3875. if ((flag != '+' && flag != '-') ||
  3876. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  3877. cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  3878. return -1;
  3879. }
  3880. if (net == (remote_ip & mask)) {
  3881. allowed = flag;
  3882. }
  3883. }
  3884. return allowed == '+';
  3885. }
  3886. static void add_to_set(SOCKET fd, fd_set *set, int *max_fd) {
  3887. FD_SET(fd, set);
  3888. if (fd > (SOCKET) *max_fd) {
  3889. *max_fd = (int) fd;
  3890. }
  3891. }
  3892. #if !defined(_WIN32)
  3893. static int set_uid_option(struct mg_context *ctx) {
  3894. struct passwd *pw;
  3895. const char *uid = ctx->config[RUN_AS_USER];
  3896. int success = 0;
  3897. if (uid == NULL) {
  3898. success = 1;
  3899. } else {
  3900. if ((pw = getpwnam(uid)) == NULL) {
  3901. cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  3902. } else if (setgid(pw->pw_gid) == -1) {
  3903. cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
  3904. } else if (setuid(pw->pw_uid) == -1) {
  3905. cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
  3906. } else {
  3907. success = 1;
  3908. }
  3909. }
  3910. return success;
  3911. }
  3912. #endif // !_WIN32
  3913. #if !defined(NO_SSL)
  3914. static pthread_mutex_t *ssl_mutexes;
  3915. static void ssl_locking_callback(int mode, int mutex_num, const char *file,
  3916. int line) {
  3917. line = 0; // Unused
  3918. file = NULL; // Unused
  3919. if (mode & CRYPTO_LOCK) {
  3920. (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  3921. } else {
  3922. (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  3923. }
  3924. }
  3925. static unsigned long ssl_id_callback(void) {
  3926. return (unsigned long) pthread_self();
  3927. }
  3928. #if !defined(NO_SSL_DL)
  3929. static int load_dll(struct mg_context *ctx, const char *dll_name,
  3930. struct ssl_func *sw) {
  3931. union {void *p; void (*fp)(void);} u;
  3932. void *dll_handle;
  3933. struct ssl_func *fp;
  3934. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  3935. cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  3936. return 0;
  3937. }
  3938. for (fp = sw; fp->name != NULL; fp++) {
  3939. #ifdef _WIN32
  3940. // GetProcAddress() returns pointer to function
  3941. u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
  3942. #else
  3943. // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to
  3944. // function pointers. We need to use a union to make a cast.
  3945. u.p = dlsym(dll_handle, fp->name);
  3946. #endif // _WIN32
  3947. if (u.fp == NULL) {
  3948. cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
  3949. return 0;
  3950. } else {
  3951. fp->ptr = u.fp;
  3952. }
  3953. }
  3954. return 1;
  3955. }
  3956. #endif // NO_SSL_DL
  3957. // Dynamically load SSL library. Set up ctx->ssl_ctx pointer.
  3958. static int set_ssl_option(struct mg_context *ctx) {
  3959. struct mg_request_info request_info;
  3960. SSL_CTX *CTX = 0;
  3961. int i, size;
  3962. int ssl_result;
  3963. const char *pem = ctx->config[SSL_CERTIFICATE];
  3964. const char *chain = ctx->config[SSL_CHAIN_FILE];
  3965. #ifndef USE_AXTLS_ON_MEMORY
  3966. if (pem == NULL) {
  3967. return 1;
  3968. }
  3969. #endif
  3970. #if !defined(NO_SSL_DL)
  3971. if (!load_dll(ctx, SSL_LIB, ssl_sw) ||
  3972. !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {
  3973. return 0;
  3974. }
  3975. #endif // NO_SSL_DL
  3976. // Initialize SSL crap
  3977. SSL_library_init();
  3978. SSL_load_error_strings();
  3979. #ifdef USE_AXTLS
  3980. CTX = 0;
  3981. if (ctx->user_callback != NULL) {
  3982. memset(&request_info, 0, sizeof(request_info));
  3983. request_info.user_data = ctx->user_data;
  3984. request_info.uri = ctx->config[DOCUMENT_ROOT];
  3985. ctx->user_callback(MG_INIT_SSL, (struct mg_connection *) &CTX,
  3986. &request_info);
  3987. }
  3988. if (!CTX) {
  3989. cry(fc(ctx), "SSL_CTX_new error: %s", ssl_error(MG_SSL_CREATE_CTX_ERROR));
  3990. return 0;
  3991. }
  3992. #else
  3993. if ((CTX = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  3994. cry(fc(ctx), "SSL_CTX_new error: %s", ssl_error(MG_SSL_CREATE_CTX_ERROR));
  3995. return 0;
  3996. } else if (ctx->user_callback != NULL) {
  3997. memset(&request_info, 0, sizeof(request_info));
  3998. request_info.user_data = ctx->user_data;
  3999. ctx->user_callback(MG_INIT_SSL, (struct mg_connection *) CTX,
  4000. &request_info);
  4001. }
  4002. #endif
  4003. #ifndef USE_AXTLS_ON_MEMORY
  4004. if (CTX != NULL && (ssl_result = SSL_CTX_use_certificate_file(CTX, pem,
  4005. SSL_FILETYPE_PEM)) == 0) {
  4006. cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error(ssl_result));
  4007. return 0;
  4008. }
  4009. #ifndef USE_AXTLS
  4010. else if (CTX != NULL && (ssl_result = SSL_CTX_use_PrivateKey_file(CTX, pem,
  4011. SSL_FILETYPE_PEM)) == 0) {
  4012. cry(fc(ctx), "%s: cannot open %s: %s", NULL, pem, ssl_error(ssl_result));
  4013. return 0;
  4014. }
  4015. #endif
  4016. if (CTX != NULL && chain != NULL &&
  4017. (ssl_result = SSL_CTX_use_certificate_chain_file(CTX, chain)) == 0) {
  4018. cry(fc(ctx), "%s: cannot open %s: %s", NULL, chain, ssl_error(ssl_result));
  4019. return 0;
  4020. }
  4021. #ifndef USE_AXTLS
  4022. // Initialize locking callbacks, needed for thread safety.
  4023. // http://www.openssl.org/support/faq.html#PROG1
  4024. size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
  4025. if ((ssl_mutexes = (pthread_mutex_t *) MG_MALLOC((size_t)size)) == NULL) {
  4026. cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error(MG_SSL_ALOCATE_MUTEX_ERROR));
  4027. return 0;
  4028. }
  4029. for (i = 0; i < CRYPTO_num_locks(); i++) {
  4030. pthread_mutex_init(&ssl_mutexes[i], NULL);
  4031. }
  4032. CRYPTO_set_locking_callback(&ssl_locking_callback);
  4033. CRYPTO_set_id_callback(&ssl_id_callback);
  4034. #endif
  4035. #endif //USE_AXTLS_ON_MEMORY
  4036. // Done with everything. Save the context.
  4037. ctx->ssl_ctx = CTX;
  4038. return 1;
  4039. }
  4040. static void uninitialize_ssl(struct mg_context *ctx) {
  4041. #if !defined(NO_SSL_DL)
  4042. #if !defined(USE_AXTLS)
  4043. int i;
  4044. if (ctx->ssl_ctx != NULL) {
  4045. CRYPTO_set_locking_callback(NULL);
  4046. for (i = 0; i < CRYPTO_num_locks(); i++) {
  4047. if(ssl_mutexes[i]) {
  4048. pthread_mutex_destroy(&ssl_mutexes[i]);
  4049. }
  4050. }
  4051. CRYPTO_set_locking_callback(NULL);
  4052. CRYPTO_set_id_callback(NULL);
  4053. }
  4054. #endif
  4055. #endif
  4056. }
  4057. #endif // !NO_SSL
  4058. static int set_gpass_option(struct mg_context *ctx) {
  4059. struct mgstat mgstat;
  4060. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  4061. return path == NULL || mg_stat(path, &mgstat) == 0;
  4062. }
  4063. static int set_acl_option(struct mg_context *ctx) {
  4064. return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
  4065. }
  4066. static void reset_per_request_attributes(struct mg_connection *conn) {
  4067. struct mg_request_info *ri = &conn->request_info;
  4068. // Reset request info attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
  4069. if (ri->remote_user != NULL) {
  4070. MG_FREE((void *) ri->remote_user);
  4071. }
  4072. if (ri->ah != NULL) {
  4073. if (ri->ah->ha1 != NULL) {
  4074. MG_FREE((void *) ri->ah->ha1);
  4075. }
  4076. if (ri->ah->expected_response != NULL) {
  4077. MG_FREE((void *) ri->ah->expected_response);
  4078. }
  4079. MG_FREE((void *) ri->ah);
  4080. }
  4081. ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
  4082. ri->ah = NULL;
  4083. ri->num_headers = 0;
  4084. ri->status_code = -1;
  4085. if (conn->auth_header != NULL) {
  4086. MG_FREE((void *) conn->auth_header);
  4087. }
  4088. conn->auth_header = NULL;
  4089. conn->num_bytes_sent = conn->consumed_content = 0;
  4090. conn->content_len = -1;
  4091. conn->request_len = conn->data_len = 0;
  4092. conn->must_close = 0;
  4093. }
  4094. static int
  4095. set_sock_timeout(SOCKET sock, int milliseconds)
  4096. {
  4097. int r1, r2;
  4098. #ifdef _WIN32
  4099. /* Windows specific */
  4100. DWORD tv = (DWORD)milliseconds;
  4101. #else
  4102. /* Linux, ... (not Windows) */
  4103. struct timeval tv;
  4104. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  4105. * max. time waiting for the acknowledged of TCP data before the connection
  4106. * will be forcefully closed and ETIMEDOUT is returned to the application.
  4107. * If this option is not set, the default timeout of 20-30 minutes is used.
  4108. */
  4109. /* #define TCP_USER_TIMEOUT (18) */
  4110. #if defined(TCP_USER_TIMEOUT)
  4111. unsigned int uto = (unsigned int)milliseconds;
  4112. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  4113. #endif
  4114. memset(&tv, 0, sizeof(tv));
  4115. tv.tv_sec = milliseconds / 1000;
  4116. tv.tv_usec = (milliseconds * 1000) % 1000000;
  4117. #endif /* _WIN32 */
  4118. r1 = setsockopt(
  4119. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  4120. r2 = setsockopt(
  4121. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  4122. return r1 || r2;
  4123. }
  4124. static void close_socket_gracefully(struct mg_connection *conn) {
  4125. char buf[MG_BUF_LEN];
  4126. struct linger linger;
  4127. int n, sock = conn->client.sock;
  4128. // Set linger option to avoid socket hanging out after close. This prevent
  4129. // ephemeral port exhaust problem under high QPS.
  4130. linger.l_onoff = 1;
  4131. linger.l_linger = 1;
  4132. setsockopt(sock, SOL_SOCKET, SO_LINGER, (char *) &linger, sizeof(linger));
  4133. // Send FIN to the client
  4134. (void) shutdown(sock, SHUT_WR);
  4135. set_non_blocking_mode(sock);
  4136. #if defined(_WIN32)
  4137. // Read and discard pending incoming data. If we do not do that and close the
  4138. // socket, the data in the send buffer may be discarded. This
  4139. // behaviour is seen on Windows, when client keeps sending data
  4140. // when server decides to close the connection; then when client
  4141. // does recv() it gets no data back.
  4142. do {
  4143. n = pull(NULL, conn, buf, sizeof(buf));
  4144. } while (n > 0);
  4145. #endif
  4146. // Now we know that our FIN is ACK-ed, safe to close
  4147. (void) closesocket(sock);
  4148. }
  4149. static void close_connection(struct mg_connection *conn) {
  4150. if (conn->ssl) {
  4151. SSL_free(conn->ssl);
  4152. conn->ssl = NULL;
  4153. }
  4154. if (conn->client.sock != INVALID_SOCKET) {
  4155. close_socket_gracefully(conn);
  4156. }
  4157. }
  4158. void mg_close_connection(struct mg_connection *conn) {
  4159. close_connection(conn);
  4160. free(conn);
  4161. }
  4162. struct mg_connection *mg_connect(struct mg_context *ctx,
  4163. const char *host, int port, int use_ssl) {
  4164. struct mg_connection *newconn = NULL;
  4165. struct sockaddr_in sin;
  4166. struct hostent *he;
  4167. int sock;
  4168. if (use_ssl && (ctx == NULL || ctx->client_ssl_ctx == NULL)) {
  4169. cry(fc(ctx), "%s: SSL is not initialized", __func__);
  4170. } else if ((he = gethostbyname(host)) == NULL) {
  4171. cry(fc(ctx), "%s: gethostbyname(%s): %s", __func__, host, strerror(ERRNO));
  4172. } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  4173. cry(fc(ctx), "%s: socket: %s", __func__, strerror(ERRNO));
  4174. } else {
  4175. sin.sin_family = AF_INET;
  4176. sin.sin_port = htons((uint16_t) port);
  4177. sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
  4178. if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
  4179. cry(fc(ctx), "%s: connect(%s:%d): %s", __func__, host, port,
  4180. strerror(ERRNO));
  4181. closesocket(sock);
  4182. } else if ((newconn = (struct mg_connection *)
  4183. calloc(1, sizeof(*newconn))) == NULL) {
  4184. cry(fc(ctx), "%s: calloc: %s", __func__, strerror(ERRNO));
  4185. closesocket(sock);
  4186. } else {
  4187. newconn->ctx = ctx;
  4188. newconn->client.sock = sock;
  4189. newconn->client.rsa.sin = sin;
  4190. newconn->client.is_ssl = use_ssl;
  4191. if (use_ssl) {
  4192. sslize(newconn, ctx->client_ssl_ctx, SSL_connect);
  4193. }
  4194. }
  4195. }
  4196. return newconn;
  4197. }
  4198. FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path,
  4199. char *buf, size_t buf_len, struct mg_request_info *ri) {
  4200. struct mg_connection *newconn;
  4201. int n, req_length, data_length, port;
  4202. char host[1025], proto[10], buf2[MG_BUF_LEN];
  4203. FILE *fp = NULL;
  4204. if (sscanf(url, "%9[htps]://%1024[^:]:%d/%n", proto, host, &port, &n) == 3) {
  4205. } else if (sscanf(url, "%9[htps]://%1024[^/]/%n", proto, host, &n) == 2) {
  4206. port = mg_strcasecmp(proto, "https") == 0 ? 443 : 80;
  4207. } else {
  4208. cry(fc(ctx), "%s: invalid URL: [%s]", __func__, url);
  4209. return NULL;
  4210. }
  4211. if ((newconn = mg_connect(ctx, host, port,
  4212. !strcmp(proto, "https"))) == NULL) {
  4213. cry(fc(ctx), "%s: mg_connect(%s): %s", __func__, url, strerror(ERRNO));
  4214. } else {
  4215. mg_printf(newconn, "GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n", url + n, host);
  4216. data_length = 0;
  4217. req_length = read_request(NULL, newconn, buf, buf_len, &data_length);
  4218. if (req_length <= 0) {
  4219. cry(fc(ctx), "%s(%s): invalid HTTP reply", __func__, url);
  4220. } else if (parse_http_response(buf, req_length, ri) <= 0) {
  4221. cry(fc(ctx), "%s(%s): cannot parse HTTP headers", __func__, url);
  4222. } else if ((fp = fopen(path, "w+b")) == NULL) {
  4223. cry(fc(ctx), "%s: fopen(%s): %s", __func__, path, strerror(ERRNO));
  4224. } else {
  4225. // Write chunk of data that may be in the user's buffer
  4226. data_length -= req_length;
  4227. if (data_length > 0 &&
  4228. fwrite(buf + req_length, 1, data_length, fp) != (size_t) data_length) {
  4229. cry(fc(ctx), "%s: fwrite(%s): %s", __func__, path, strerror(ERRNO));
  4230. fclose(fp);
  4231. fp = NULL;
  4232. }
  4233. // Read the rest of the response and write it to the file. Do not use
  4234. // mg_read() cause we didn't set newconn->content_len properly.
  4235. while (fp && (data_length = pull(0, newconn, buf2, sizeof(buf2))) > 0) {
  4236. if (fwrite(buf2, 1, data_length, fp) != (size_t) data_length) {
  4237. cry(fc(ctx), "%s: fwrite(%s): %s", __func__, path, strerror(ERRNO));
  4238. fclose(fp);
  4239. fp = NULL;
  4240. break;
  4241. }
  4242. }
  4243. }
  4244. mg_close_connection(newconn);
  4245. }
  4246. return fp;
  4247. }
  4248. static void discard_current_request_from_buffer(struct mg_connection *conn) {
  4249. //char *buffered;
  4250. int buffered_len, body_len;
  4251. //buffered = conn->buf + conn->request_len;
  4252. buffered_len = conn->data_len - conn->request_len;
  4253. assert(buffered_len >= 0);
  4254. if (conn->content_len <= 0) {
  4255. // Protect from negative Content-Length, too
  4256. body_len = 0;
  4257. } else if (conn->content_len < (int64_t) buffered_len) {
  4258. body_len = (int) conn->content_len;
  4259. } else {
  4260. body_len = buffered_len;
  4261. }
  4262. conn->data_len -= conn->request_len + body_len;
  4263. memmove(conn->buf, conn->buf + conn->request_len + body_len,
  4264. (size_t) conn->data_len);
  4265. }
  4266. static int parse_url(const char *url, char *host, int *port) {
  4267. int len;
  4268. if (sscanf(url, "%*[htps]://%1024[^:]:%d%n", host, port, &len) == 2 ||
  4269. sscanf(url, "%1024[^:]:%d%n", host, port, &len) == 2) {
  4270. } else if (sscanf(url, "%*[htps]://%1024[^/]%n", host, &len) == 1) {
  4271. *port = 80;
  4272. } else {
  4273. sscanf(url, "%1024[^/]%n", host, &len);
  4274. *port = 80;
  4275. }
  4276. DEBUG_TRACE(("Host:%s, port:%d", host, *port));
  4277. return len;
  4278. }
  4279. static void handle_proxy_request(struct mg_connection *conn) {
  4280. struct mg_request_info *ri = &conn->request_info;
  4281. char host[1025], buf[BUFSIZ];
  4282. int port, is_ssl, len, i, n;
  4283. DEBUG_TRACE(("URL: %s", ri->uri));
  4284. if (ri->uri == NULL ||
  4285. ri->uri[0] == '/' ||
  4286. (len = parse_url(ri->uri, host, &port)) == 0) {
  4287. return;
  4288. }
  4289. if (conn->peer == NULL) {
  4290. is_ssl = !strcmp(ri->request_method, "CONNECT");
  4291. if ((conn->peer = mg_connect(conn->ctx, host, port, is_ssl)) == NULL) {
  4292. return;
  4293. }
  4294. conn->peer->client.is_ssl = is_ssl;
  4295. }
  4296. // Forward client's request to the target
  4297. mg_printf(conn->peer, "%s %s HTTP/%s\r\n", ri->request_method, ri->uri + len,
  4298. ri->http_version);
  4299. // And also all headers. TODO(lsm): anonymize!
  4300. for (i = 0; i < ri->num_headers; i++) {
  4301. mg_printf(conn->peer, "%s: %s\r\n", ri->http_headers[i].name,
  4302. ri->http_headers[i].value);
  4303. }
  4304. // End of headers, final newline
  4305. mg_write(conn->peer, "\r\n", 2);
  4306. // Read and forward body data if any
  4307. if (!strcmp(ri->request_method, "POST")) {
  4308. forward_body_data(conn, NULL, conn->peer->client.sock, conn->peer->ssl);
  4309. }
  4310. // Read data from the target and forward it to the client
  4311. while ((n = pull(NULL, conn, buf, sizeof(buf))) > 0) {
  4312. if (mg_write(conn, buf, (size_t)n) != n) {
  4313. break;
  4314. }
  4315. }
  4316. if (!conn->peer->client.is_ssl) {
  4317. close_connection(conn->peer);
  4318. MG_FREE(conn->peer);
  4319. conn->peer = NULL;
  4320. }
  4321. }
  4322. static int is_valid_uri(const char *uri) {
  4323. // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  4324. // URI can be an asterisk (*) or should start with slash.
  4325. return (uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0'));
  4326. }
  4327. static void process_new_connection(struct mg_connection *conn) {
  4328. struct mg_request_info *ri = &conn->request_info;
  4329. int keep_alive_enabled, keep_alive, buffered_len;
  4330. const char *cl;
  4331. keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  4332. do {
  4333. keep_alive = 0;
  4334. reset_per_request_attributes(conn);
  4335. conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
  4336. &conn->data_len);
  4337. assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  4338. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  4339. send_http_error(conn, 413, "Request Too Large", "");
  4340. return;
  4341. } if (conn->request_len <= 0) {
  4342. return; // Remote end closed the connection
  4343. }
  4344. conn->body = conn->next_request = conn->buf + conn->request_len;
  4345. if (parse_http_request(conn->buf, conn->buf_size, ri) <= 0 ||
  4346. !is_valid_uri(ri->uri)) {
  4347. // Do not put garbage in the access log, just send it back to the client
  4348. send_http_error(conn, 400, "Bad Request",
  4349. "Cannot parse HTTP request: [%.*s]", conn->data_len, conn->buf);
  4350. conn->must_close = 1;
  4351. } else if (strcmp(ri->http_version, "1.0") &&
  4352. strcmp(ri->http_version, "1.1")) {
  4353. // Request seems valid, but HTTP version is strange
  4354. send_http_error(conn, 505, "HTTP version not supported", "");
  4355. log_access(conn);
  4356. } else {
  4357. // Request is valid, handle it
  4358. cl = get_header(ri, "Content-Length");
  4359. conn->content_len = cl == NULL ? -1 : strtoll(cl, NULL, 10);
  4360. // Set pointer to the next buffered request
  4361. buffered_len = conn->data_len - conn->request_len;
  4362. assert(buffered_len >= 0);
  4363. if (conn->content_len <= 0) {
  4364. } else if (conn->content_len < (int64_t) buffered_len) {
  4365. conn->next_request += conn->content_len;
  4366. } else {
  4367. conn->next_request += buffered_len;
  4368. }
  4369. conn->birth_time = time(NULL);
  4370. if (conn->client.is_proxy) {
  4371. handle_proxy_request(conn);
  4372. } else {
  4373. handle_request(conn);
  4374. call_user(conn, MG_REQUEST_COMPLETE);
  4375. }
  4376. log_access(conn);
  4377. /* NOTE(lsm): order is important here. should_keep_alive() call
  4378. * is
  4379. * using parsed request, which will be invalid after memmove's
  4380. * below.
  4381. * Therefore, memorize should_keep_alive() result now for later
  4382. * use
  4383. * in loop exit condition. */
  4384. keep_alive = should_keep_alive(conn);
  4385. discard_current_request_from_buffer(conn);
  4386. }
  4387. // conn->peer is not NULL only for SSL-ed proxy connections
  4388. } while (conn->ctx->stop_flag == 0 &&
  4389. (conn->peer || (keep_alive_enabled && keep_alive)));
  4390. }
  4391. // Worker threads take accepted socket from the queue
  4392. static int consume_socket(struct mg_context *ctx, struct socket *sp) {
  4393. (void) pthread_mutex_lock(&ctx->mutex);
  4394. DEBUG_TRACE(("going idle"));
  4395. // If the queue is empty, wait. We're idle at this point.
  4396. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  4397. pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
  4398. }
  4399. // If we're stopping, sq_head may be equal to sq_tail.
  4400. if (ctx->sq_head > ctx->sq_tail) {
  4401. // Copy socket from the queue and increment tail
  4402. *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
  4403. ctx->sq_tail++;
  4404. DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
  4405. // Wrap pointers if needed
  4406. while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
  4407. ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
  4408. ctx->sq_head -= ARRAY_SIZE(ctx->queue);
  4409. }
  4410. }
  4411. (void) pthread_cond_signal(&ctx->sq_empty);
  4412. (void) pthread_mutex_unlock(&ctx->mutex);
  4413. return !ctx->stop_flag;
  4414. }
  4415. void *mg_get_plugin(struct mg_connection *conn){
  4416. return conn->plugin;
  4417. }
  4418. void *mg_lock_master_plugin(struct mg_connection *conn){
  4419. (void) pthread_mutex_lock(&conn->ctx->master_plugin_mutex);
  4420. return conn->ctx->master_plugin;
  4421. }
  4422. void mg_unlock_master_plugin(struct mg_connection *conn){
  4423. (void) pthread_mutex_unlock(&conn->ctx->master_plugin_mutex);
  4424. }
  4425. static void worker_thread(struct mg_context *ctx) {
  4426. struct mg_connection *conn;
  4427. int buf_size = atoi(ctx->config[MAX_REQUEST_SIZE]);
  4428. conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn) + buf_size);
  4429. assert(conn != NULL);
  4430. conn->buf_size = buf_size;
  4431. conn->buf = (char *) (conn + 1);
  4432. conn->ctx = ctx;
  4433. if(ctx->user_callback)
  4434. conn->plugin = ctx->user_callback(MG_NEW_PLUGIN, conn,
  4435. (struct mg_request_info *)ctx);
  4436. // Call consume_socket() even when ctx->stop_flag > 0, to let it signal
  4437. // sq_empty condvar to wake up the master waiting in produce_socket()
  4438. while (consume_socket(ctx, &conn->client)) {
  4439. conn->birth_time = time(NULL);
  4440. conn->ctx = ctx;
  4441. //set_receive_timeout(conn->client.sock); // <bel> set timeouts
  4442. // Fill in IP, port info early so even if SSL setup below fails,
  4443. // error handler would have the corresponding info.
  4444. // Thanks to Johannes Winkelmann for the patch.
  4445. // TODO(lsm): Fix IPv6 case
  4446. conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
  4447. memcpy(&conn->request_info.remote_ip,
  4448. &conn->client.rsa.sin.sin_addr.s_addr, 4);
  4449. conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
  4450. conn->request_info.is_ssl = conn->client.is_ssl;
  4451. if (!conn->client.is_ssl ||
  4452. (conn->client.is_ssl && sslize(conn, conn->ctx->ssl_ctx, SSL_accept))) {
  4453. void *done = 0;
  4454. if(ctx->user_callback){
  4455. done = ctx->user_callback(MG_NEW_CONNECTION, conn,
  4456. (struct mg_request_info *)ctx);
  4457. }
  4458. if(!done) process_new_connection(conn);
  4459. }
  4460. close_connection(conn);
  4461. }
  4462. conn->ctx = ctx;
  4463. if(ctx->user_callback)
  4464. conn->plugin = ctx->user_callback(MG_FREE_PLUGIN, conn,
  4465. (struct mg_request_info *)ctx->user_data);
  4466. MG_FREE(conn);
  4467. // Signal master that we're done with connection and exiting
  4468. (void) pthread_mutex_lock(&ctx->mutex);
  4469. ctx->num_threads--;
  4470. (void) pthread_cond_signal(&ctx->cond);
  4471. assert(ctx->num_threads >= 0);
  4472. (void) pthread_mutex_unlock(&ctx->mutex);
  4473. DEBUG_TRACE(("exiting"));
  4474. }
  4475. // Master thread adds accepted socket to a queue
  4476. static void produce_socket(struct mg_context *ctx, const struct socket *sp) {
  4477. (void) pthread_mutex_lock(&ctx->mutex);
  4478. // If the queue is full, wait
  4479. while (ctx->stop_flag == 0 &&
  4480. ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
  4481. (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
  4482. }
  4483. if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
  4484. // Copy socket to the queue and increment head
  4485. ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
  4486. ctx->sq_head++;
  4487. DEBUG_TRACE(("queued socket %d", sp->sock));
  4488. }
  4489. (void) pthread_cond_signal(&ctx->sq_full);
  4490. (void) pthread_mutex_unlock(&ctx->mutex);
  4491. }
  4492. static void accept_new_connection(const struct socket *listener,
  4493. struct mg_context *ctx) {
  4494. struct socket accepted;
  4495. char src_addr[20];
  4496. socklen_t len;
  4497. int allowed;
  4498. int on = 1;
  4499. int timeout;
  4500. len = sizeof(accepted.rsa);
  4501. accepted.lsa = listener->lsa;
  4502. accepted.sock = accept(listener->sock, &accepted.rsa.sa, &len);
  4503. if (accepted.sock != INVALID_SOCKET) {
  4504. allowed = check_acl(ctx, ntohl(* (uint32_t *) &accepted.rsa.sin.sin_addr));
  4505. if (allowed) {
  4506. // Put accepted socket structure into the queue
  4507. DEBUG_TRACE(("accepted socket %d", accepted.sock));
  4508. accepted.is_ssl = listener->is_ssl;
  4509. accepted.is_proxy = listener->is_proxy;
  4510. //ctx->connection_count++;
  4511. //accepted.connection_count = ctx->connection_count;
  4512. /* Set TCP keep-alive. This is needed because if HTTP-level
  4513. * keep-alive
  4514. * is enabled, and client resets the connection, server won't get
  4515. * TCP FIN or RST and will keep the connection open forever. With
  4516. * TCP
  4517. * keep-alive, next keep-alive handshake will figure out that the
  4518. * client is down and will close the server end.
  4519. * Thanks to Igor Klopov who suggested the patch. */
  4520. if (setsockopt(accepted.sock,
  4521. SOL_SOCKET,
  4522. SO_KEEPALIVE,
  4523. (SOCK_OPT_TYPE)&on,
  4524. sizeof(on)) != 0) {
  4525. cry(fc(ctx),
  4526. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  4527. __func__,
  4528. strerror(ERRNO));
  4529. }
  4530. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  4531. * to effectively fill up the underlying IP packet payload and reduce
  4532. * the overhead of sending lots of small buffers. However this hurts
  4533. * the server's throughput (ie. operations per second) when HTTP 1.1
  4534. * persistent connections are used and the responses are relatively
  4535. * small (eg. less than 1400 bytes).
  4536. */
  4537. if (ctx && mg_strcasecmp(ctx->config[ENABLE_TCP_NODELAY], "yes") == 0) {
  4538. if (setsockopt(accepted.sock,
  4539. IPPROTO_TCP,
  4540. TCP_NODELAY,
  4541. (SOCK_OPT_TYPE)&on,
  4542. sizeof(on)) != 0) {
  4543. cry(fc(ctx),
  4544. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  4545. __func__,
  4546. strerror(ERRNO));
  4547. }
  4548. }
  4549. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  4550. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  4551. } else {
  4552. timeout = -1;
  4553. }
  4554. /* Set socket timeout to the given value, but not more than a
  4555. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  4556. * so the server can exit after that time if requested. */
  4557. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  4558. set_sock_timeout(accepted.sock, timeout);
  4559. } else {
  4560. set_sock_timeout(accepted.sock, SOCKET_TIMEOUT_QUANTUM);
  4561. }
  4562. produce_socket(ctx, &accepted);
  4563. } else {
  4564. sockaddr_to_string(src_addr, sizeof(src_addr), &accepted.rsa);
  4565. cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  4566. (void) closesocket(accepted.sock);
  4567. }
  4568. }
  4569. }
  4570. static void master_thread(struct mg_context *ctx) {
  4571. fd_set read_set;
  4572. struct timeval tv;
  4573. struct socket *sp;
  4574. int max_fd;
  4575. // Increase priority of the master thread
  4576. #if defined(_WIN32)
  4577. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  4578. #endif
  4579. #if defined(ISSUE_317)
  4580. struct sched_param sched_param;
  4581. sched_param.sched_priority = sched_get_priority_max(SCHED_RR);
  4582. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  4583. #endif
  4584. while (ctx->stop_flag == 0) {
  4585. FD_ZERO(&read_set);
  4586. max_fd = -1;
  4587. // Add listening sockets to the read set
  4588. for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
  4589. add_to_set(sp->sock, &read_set, &max_fd);
  4590. }
  4591. tv.tv_sec = 0;
  4592. tv.tv_usec = 200 * 1000;
  4593. if (select(max_fd + 1, &read_set, NULL, NULL, &tv) < 0) {
  4594. #ifdef _WIN32
  4595. // On windows, if read_set and write_set are empty,
  4596. // select() returns "Invalid parameter" error
  4597. // (at least on my Windows XP Pro). So in this case, we sleep here.
  4598. mg_sleep(1000);
  4599. #endif // _WIN32
  4600. } else {
  4601. for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
  4602. if (ctx->stop_flag == 0 && FD_ISSET(sp->sock, &read_set)) {
  4603. accept_new_connection(sp, ctx);
  4604. }
  4605. }
  4606. }
  4607. }
  4608. DEBUG_TRACE(("stopping workers"));
  4609. // Stop signal received: somebody called mg_stop. Quit.
  4610. close_all_listening_sockets(ctx);
  4611. // Wakeup workers that are waiting for connections to handle.
  4612. pthread_cond_broadcast(&ctx->sq_full);
  4613. // Wait until all threads finish
  4614. (void) pthread_mutex_lock(&ctx->mutex);
  4615. while (ctx->num_threads > 0) {
  4616. (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
  4617. }
  4618. (void) pthread_mutex_unlock(&ctx->mutex);
  4619. // All threads exited, no sync is needed. Destroy mutex and condvars
  4620. (void) pthread_mutex_destroy(&ctx->mutex);
  4621. (void) pthread_cond_destroy(&ctx->cond);
  4622. (void) pthread_cond_destroy(&ctx->sq_empty);
  4623. (void) pthread_cond_destroy(&ctx->sq_full);
  4624. (void) pthread_mutex_destroy(&ctx->master_plugin_mutex);
  4625. (void) pthread_cond_destroy(&ctx->master_plugin_cond);
  4626. #if !defined(NO_SSL)
  4627. uninitialize_ssl(ctx);
  4628. #endif
  4629. DEBUG_TRACE(("exiting"));
  4630. // Signal mg_stop() that we're done.
  4631. // WARNING: This must be the very last thing this
  4632. // thread does, as ctx becomes invalid after this line.
  4633. ctx->stop_flag = 2;
  4634. }
  4635. static void free_context(struct mg_context *ctx) {
  4636. int i;
  4637. // Deallocate config parameters
  4638. for (i = 0; i < NUM_OPTIONS; i++) {
  4639. if (ctx->config[i] != NULL)
  4640. MG_FREE(ctx->config[i]);
  4641. }
  4642. // Deallocate SSL context
  4643. if (ctx->ssl_ctx != NULL) {
  4644. SSL_CTX_free(ctx->ssl_ctx);
  4645. }
  4646. if (ctx->client_ssl_ctx != NULL) {
  4647. SSL_CTX_free(ctx->client_ssl_ctx);
  4648. }
  4649. #ifndef NO_SSL
  4650. if (ssl_mutexes != NULL) {
  4651. MG_FREE(ssl_mutexes);
  4652. ssl_mutexes = NULL;
  4653. }
  4654. #endif // !NO_SSL
  4655. // Deallocate context itself
  4656. MG_FREE(ctx);
  4657. }
  4658. void mg_stop(struct mg_context *ctx) {
  4659. ctx->stop_flag = 1;
  4660. // Wait until mg_fini() stops
  4661. while (ctx->stop_flag != 2) {
  4662. (void) mg_sleep(10);
  4663. }
  4664. if(ctx->user_callback)
  4665. ctx->master_plugin = ctx->user_callback(MG_FREE_MASTER_PLUGIN,
  4666. (struct mg_connection *)ctx->master_plugin,
  4667. (struct mg_request_info *)ctx->user_data);
  4668. free_context(ctx);
  4669. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4670. (void) WSACleanup();
  4671. #endif // _WIN32
  4672. }
  4673. struct mg_context *mg_start(mg_callback_t user_callback, void *user_data,
  4674. const char **options) {
  4675. struct mg_context *ctx;
  4676. const char *name, *value, *default_value;
  4677. int i;
  4678. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4679. WSADATA data;
  4680. WSAStartup(MAKEWORD(2,2), &data);
  4681. InitializeCriticalSection(&global_log_file_lock);
  4682. #endif // _WIN32
  4683. // Allocate context and initialize reasonable general case defaults.
  4684. // TODO(lsm): do proper error handling here.
  4685. ctx = (struct mg_context *) MG_CALLOC(1, sizeof(*ctx));
  4686. ctx->user_callback = user_callback;
  4687. ctx->user_data = user_data;
  4688. //ctx->connection_count = 0;
  4689. while (options && (name = *options++) != NULL) {
  4690. if ((i = get_option_index(name)) == -1) {
  4691. cry(fc(ctx), "Invalid option: %s", name);
  4692. free_context(ctx);
  4693. return NULL;
  4694. } else if ((value = *options++) == NULL) {
  4695. cry(fc(ctx), "%s: option value cannot be NULL", name);
  4696. free_context(ctx);
  4697. return NULL;
  4698. }
  4699. if (ctx->config[i] != NULL) {
  4700. cry(fc(ctx), "warning: %s: duplicate option", name);
  4701. }
  4702. ctx->config[i] = mg_strdup(value);
  4703. DEBUG_TRACE(("[%s] -> [%s]", name, value));
  4704. }
  4705. // Set default value if needed
  4706. for (i = 0; config_options[i * ENTRIES_PER_CONFIG_OPTION] != NULL; i++) {
  4707. default_value = config_options[i * ENTRIES_PER_CONFIG_OPTION + 2];
  4708. if (ctx->config[i] == NULL && default_value != NULL) {
  4709. ctx->config[i] = mg_strdup(default_value);
  4710. DEBUG_TRACE(("Setting default: [%s] -> [%s]",
  4711. config_options[i * ENTRIES_PER_CONFIG_OPTION + 1],
  4712. default_value));
  4713. }
  4714. }
  4715. if (ctx->config[MAX_THREADS] == NULL) {
  4716. ctx->config[MAX_THREADS] = mg_strdup(ctx->config[NUM_THREADS]);
  4717. }
  4718. ctx->base_threads = atoi(ctx->config[NUM_THREADS]);
  4719. ctx->max_threads = atoi(ctx->config[MAX_THREADS]);
  4720. // NOTE(lsm): order is important here. SSL certificates must
  4721. // be initialized before listening ports. UID must be set last.
  4722. if (!set_gpass_option(ctx) ||
  4723. #if !defined(NO_SSL)
  4724. !set_ssl_option(ctx) ||
  4725. #endif
  4726. !set_ports_option(ctx) ||
  4727. #if !defined(_WIN32)
  4728. !set_uid_option(ctx) ||
  4729. #endif
  4730. !set_acl_option(ctx)) {
  4731. free_context(ctx);
  4732. return NULL;
  4733. }
  4734. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  4735. // Ignore SIGPIPE signal, so if browser cancels the request, it
  4736. // won't kill the whole process.
  4737. (void) signal(SIGPIPE, SIG_IGN);
  4738. // Also ignoring SIGCHLD to let the OS to reap zombies properly.
  4739. (void) signal(SIGCHLD, SIG_IGN);
  4740. #endif // !_WIN32
  4741. (void) pthread_mutex_init(&ctx->mutex, NULL);
  4742. (void) pthread_cond_init(&ctx->cond, NULL);
  4743. (void) pthread_cond_init(&ctx->sq_empty, NULL);
  4744. (void) pthread_cond_init(&ctx->sq_full, NULL);
  4745. (void) pthread_mutex_init(&ctx->master_plugin_mutex, NULL);
  4746. (void) pthread_cond_init(&ctx->master_plugin_cond, NULL);
  4747. if(ctx->user_callback)
  4748. ctx->master_plugin = ctx->user_callback(MG_NEW_MASTER_PLUGIN,
  4749. (struct mg_connection *)ctx->user_data,
  4750. (struct mg_request_info *)ctx);
  4751. // Start master (listening) thread
  4752. mg_start_thread((mg_thread_func_t) master_thread, ctx);
  4753. // Start worker threads
  4754. for (i = 0; i < ctx->base_threads; i++) {
  4755. if (mg_start_thread((mg_thread_func_t) worker_thread, ctx) != 0) {
  4756. cry(fc(ctx), "Cannot start worker thread: %d", ERRNO);
  4757. } else {
  4758. ctx->num_threads++;
  4759. }
  4760. }
  4761. return ctx;
  4762. }
  4763. mg_thread_t mg_thread_self(void){
  4764. return pthread_self();
  4765. }
  4766. int mg_thread_mutex_init(mg_thread_mutex_t *mutex, const mg_thread_mutexattr_t *attr){
  4767. return pthread_mutex_init(mutex, attr);
  4768. }
  4769. int mg_thread_mutex_destroy(mg_thread_mutex_t *mutex){
  4770. return pthread_mutex_destroy(mutex);
  4771. }
  4772. int mg_thread_mutex_lock(mg_thread_mutex_t *mutex){
  4773. return pthread_mutex_lock(mutex);
  4774. }
  4775. int mg_thread_mutex_trylock(mg_thread_mutex_t *mutex){
  4776. return pthread_mutex_trylock(mutex);
  4777. }
  4778. int mg_thread_mutex_unlock(mg_thread_mutex_t *mutex){
  4779. return pthread_mutex_unlock(mutex);
  4780. }
  4781. int mg_thread_cond_init(mg_thread_cond_t *cv, const mg_thread_condattr_t *attr){
  4782. return pthread_cond_init((pthread_cond_t*)cv, attr);
  4783. }
  4784. int mg_thread_cond_wait(mg_thread_cond_t *cv, mg_thread_mutex_t *mutex){
  4785. return pthread_cond_wait((pthread_cond_t*)cv, mutex);
  4786. }
  4787. int mg_thread_cond_signal(mg_thread_cond_t *cv){
  4788. return pthread_cond_signal((pthread_cond_t*)cv);
  4789. }
  4790. int mg_thread_cond_broadcast(mg_thread_cond_t *cv){
  4791. return pthread_cond_broadcast((pthread_cond_t*)cv);
  4792. }
  4793. int mg_thread_cond_destroy(mg_thread_cond_t *cv){
  4794. return pthread_cond_destroy((pthread_cond_t*)cv);
  4795. }