mongoose.c 166 KB

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