mongoose.c 127 KB

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