source: rtems/cpukit/mghttpd/mongoose.c @ 7093cb5e

4.11 4.11.3
Last change on this file since 7093cb5e was b5d2d4a, checked in by Nick Withers <nick.withers@…>, on 12/03/13 at 23:42:26

Update to Mongoose 3.9 at the last point before the MIT -> GPL license change

[That is, https://github.com/cesanta/mongoose/commit/04fc209644b414d915c446bb1815b55e9fe63acc. See https://groups.google.com/forum/#!topic/mongoose-users/aafbOnHonkI]

The RTEMS patches described in the following emails and made to the previous Mongoose base have been applied:

...as well as a patch very similar to that discussed at http://forums.bannister.org/ubbthreads.php?ubb=showflat&topic=7600&gonew=1 to provide poll() (which might be able to go away soon, with incoming RTEMS poll() support)

mg_connect(), mg_url_encode() and mg_vprintf() were additionally marked "static" to silence warnings.

mongoose.1 appears to have been removed from the upstream distribution.

Note that the API's changed, for example:

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