mongoose.c 117 KB

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