PageRenderTime 42ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/rsync/mongoose.c

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