Advertisement
Guest User

Untitled

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