mongoose.c 151 KB

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