mongoose.c 116 KB

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