mongoose.c 165 KB

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