mongoose.c 133 KB

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