mongoose.c 164 KB

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