initial check in
authorjwang <jing.j.wang@intel.com>
Mon, 27 May 2013 12:16:27 +0000 (20:16 +0800)
committerjwang <jing.j.wang@intel.com>
Mon, 27 May 2013 12:16:27 +0000 (20:16 +0800)
Makefile [new file with mode: 0644]
VERSION [new file with mode: 0644]
echo.c [new file with mode: 0644]
mongoose.c [new file with mode: 0644]
mongoose.h [new file with mode: 0644]
tinyweb.c [new file with mode: 0644]

diff --git a/Makefile b/Makefile
new file mode 100644 (file)
index 0000000..37e2194
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,14 @@
+CFLAGS=        -W -Wall -I.. -pthread -g
+
+all: echo
+#      $(CC) $(CFLAGS) -DUSE_WEBSOCKET mongoose.c tinyweb.c -ldl -o tinyweb;
+       $(CC) tinyweb.c -ldl -lmongoose -L./ -o tinyweb;
+
+echo: mongoose
+       $(CC) -shared -fPIC -lmongoose -L./ echo.c -o echo.so
+
+mongoose:
+       $(CC) -shared -fPIC $(CFLAGS) -DUSE_WEBSOCKET mongoose.c -ldl -o libmongoose.so;
+
+clean:
+       rm -rf tinyweb *.so
diff --git a/VERSION b/VERSION
new file mode 100644 (file)
index 0000000..e346294
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.22
diff --git a/echo.c b/echo.c
new file mode 100644 (file)
index 0000000..72e4625
--- /dev/null
+++ b/echo.c
@@ -0,0 +1,103 @@
+/*\r
+Copyright (c) 2013 Intel Corporation.\r
+\r
+Redistribution and use in source and binary forms, with or without modification,\r
+are permitted provided that the following conditions are met:\r
+\r
+* Redistributions of works must retain the original copyright notice, this list\r
+  of conditions and the following disclaimer.\r
+* Redistributions in binary form must reproduce the original copyright notice,\r
+  this list of conditions and the following disclaimer in the documentation\r
+  and/or other materials provided with the distribution.\r
+* Neither the name of Intel Corporation nor the names of its contributors\r
+  may be used to endorse or promote products derived from this work without\r
+  specific prior written permission.\r
+\r
+THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"\r
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,\r
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\r
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\r
+OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\r
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+Authors:\r
+        Wang, Jing J <jing.j.wang@intel.com>\r
+\r
+*/\r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include "mongoose.h"\r
+/*\r
+void websocket_ready(struct mg_connection *conn) {\r
+  const char *prot = mg_get_header(conn, "Sec-WebSocket-Protocol");\r
+  char buf[100];\r
+  if (prot){\r
+      char *p = NULL;\r
+      snprintf(buf, sizeof(buf), "%s", prot);\r
+      if ((p = strrchr(buf, ',')) != NULL) {\r
+        *p = '\0';\r
+      } \r
+      mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n", buf);\r
+  }\r
+  mg_printf(conn, "\r\n");\r
+}\r
+*/\r
+\r
+// Arguments:\r
+//   flags: first byte of websocket frame, see websocket RFC,\r
+//          http://tools.ietf.org/html/rfc6455, section 5.2\r
+//   data, data_len: payload data. Mask, if any, is already applied.\r
+int websocket_data(struct mg_connection *conn, int flags,\r
+                                  char *data, size_t data_len) {\r
+  unsigned char reply[4];\r
+  size_t i = 0;\r
+  int offset = 2;\r
+  int ret = 1;\r
+\r
+//  (void) flags;\r
+\r
+  // Truncate echoed message, to simplify output code.\r
+  if (data_len > 65536) {\r
+    data_len = 65536;\r
+  }  \r
+  printf("data_len=%d\n",data_len);\r
+  int opcode = flags & 0x0f;\r
+  if ((opcode == 0x08) || memcmp(data, ".close", 6)==0){\r
+//    printf("close frame");\r
+    reply[0] = 0x88; // close, FIN set\r
+    reply[1] = data_len;\r
+    // Status code\r
+    if (data_len == 0){\r
+      reply[2] = 3;\r
+      reply[3] = 232;\r
+    }else{\r
+      reply[2] = data[0];\r
+      reply[3] = data[1];\r
+    }\r
+    ret = 0;\r
+  } else {\r
+    reply[0] = 0x80|opcode;  // FIN set\r
+    if (data_len <= 125){\r
+      reply[1] = data_len;\r
+    }\r
+    else{\r
+      reply[1] = 126;\r
+      reply[2] = data_len / 256;\r
+      reply[3] = data_len % 256;\r
+      offset = 4;\r
+    }\r
+  }\r
+  // Echo the message back to the client\r
+  mg_write(conn, reply, offset);\r
+  if (data_len > 0)\r
+    mg_write(conn, data, data_len);\r
+  // Returning zero means stoping websocket conversation.\r
+  // Close the conversation if client has sent us "exit" string.\r
+  return ret;\r
+}\r
diff --git a/mongoose.c b/mongoose.c
new file mode 100644 (file)
index 0000000..f1c59d1
--- /dev/null
@@ -0,0 +1,5184 @@
+/*\r
+Copyright (c) 2013 Intel Corporation.\r
+\r
+Redistribution and use in source and binary forms, with or without modification,\r
+are permitted provided that the following conditions are met:\r
+\r
+* Redistributions of works must retain the original copyright notice, this list\r
+  of conditions and the following disclaimer.\r
+* Redistributions in binary form must reproduce the original copyright notice,\r
+  this list of conditions and the following disclaimer in the documentation\r
+  and/or other materials provided with the distribution.\r
+* Neither the name of Intel Corporation nor the names of its contributors\r
+  may be used to endorse or promote products derived from this work without\r
+  specific prior written permission.\r
+\r
+THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"\r
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,\r
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\r
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\r
+OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\r
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+Authors:\r
+        Wang, Jing J <jing.j.wang@intel.com>\r
+\r
+*/\r
+#if defined(_WIN32)\r
+#if !defined(_CRT_SECURE_NO_WARNINGS)\r
+#define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005\r
+#endif\r
+#else\r
+#ifdef __linux__\r
+#define _XOPEN_SOURCE 600     // For flockfile() on Linux\r
+#endif\r
+#define _LARGEFILE_SOURCE     // Enable 64-bit file offsets\r
+#define __STDC_FORMAT_MACROS  // <inttypes.h> wants this for C++\r
+#define __STDC_LIMIT_MACROS   // C++ wants that for INT64_MAX\r
+#endif\r
+\r
+#if defined (_MSC_VER)\r
+// conditional expression is constant: introduced by FD_SET(..)\r
+#pragma warning (disable : 4127)\r
+// non-constant aggregate initializer: issued due to missing C99 support\r
+#pragma warning (disable : 4204)\r
+#endif\r
+\r
+// Disable WIN32_LEAN_AND_MEAN.\r
+// This makes windows.h always include winsock2.h\r
+#ifdef WIN32_LEAN_AND_MEAN\r
+#undef WIN32_LEAN_AND_MEAN\r
+#endif\r
+\r
+#if defined(__SYMBIAN32__)\r
+#define NO_SSL // SSL is not supported\r
+#define NO_CGI // CGI is not supported\r
+#define PATH_MAX FILENAME_MAX\r
+#endif // __SYMBIAN32__\r
+\r
+#ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE\r
+#include <sys/types.h>\r
+#include <sys/stat.h>\r
+#include <errno.h>\r
+#include <signal.h>\r
+#include <fcntl.h>\r
+#endif // !_WIN32_WCE\r
+\r
+#include <time.h>\r
+#include <stdlib.h>\r
+#include <stdarg.h>\r
+#include <assert.h>\r
+#include <string.h>\r
+#include <ctype.h>\r
+#include <limits.h>\r
+#include <stddef.h>\r
+#include <stdio.h>\r
+\r
+#if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific\r
+#undef _WIN32_WINNT\r
+#define _WIN32_WINNT 0x0400 // To make it link in VS2005\r
+#include <windows.h>\r
+\r
+#ifndef PATH_MAX\r
+#define PATH_MAX MAX_PATH\r
+#endif\r
+\r
+#ifndef _WIN32_WCE\r
+#include <process.h>\r
+#include <direct.h>\r
+#include <io.h>\r
+#else // _WIN32_WCE\r
+#define NO_CGI // WinCE has no pipes\r
+\r
+typedef long off_t;\r
+\r
+#define errno   GetLastError()\r
+#define strerror(x)  _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)\r
+#endif // _WIN32_WCE\r
+\r
+#define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \\r
+      ((uint64_t)((uint32_t)(hi))) << 32))\r
+#define RATE_DIFF 10000000 // 100 nsecs\r
+#define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)\r
+#define SYS2UNIX_TIME(lo, hi) \\r
+  (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)\r
+\r
+// Visual Studio 6 does not know __func__ or __FUNCTION__\r
+// The rest of MS compilers use __FUNCTION__, not C99 __func__\r
+// Also use _strtoui64 on modern M$ compilers\r
+#if defined(_MSC_VER) && _MSC_VER < 1300\r
+#define STRX(x) #x\r
+#define STR(x) STRX(x)\r
+#define __func__ __FILE__ ":" STR(__LINE__)\r
+#define strtoull(x, y, z) strtoul(x, y, z)\r
+#define strtoll(x, y, z) strtol(x, y, z)\r
+#else\r
+#define __func__  __FUNCTION__\r
+#define strtoull(x, y, z) _strtoui64(x, y, z)\r
+#define strtoll(x, y, z) _strtoi64(x, y, z)\r
+#endif // _MSC_VER\r
+\r
+#define ERRNO   GetLastError()\r
+#define NO_SOCKLEN_T\r
+#define SSL_LIB   "ssleay32.dll"\r
+#define CRYPTO_LIB  "libeay32.dll"\r
+#define O_NONBLOCK  0\r
+#if !defined(EWOULDBLOCK)\r
+#define EWOULDBLOCK  WSAEWOULDBLOCK\r
+#endif // !EWOULDBLOCK\r
+#define _POSIX_\r
+#define INT64_FMT  "I64d"\r
+\r
+#define WINCDECL __cdecl\r
+#define SHUT_WR 1\r
+#define snprintf _snprintf\r
+#define vsnprintf _vsnprintf\r
+#define mg_sleep(x) Sleep(x)\r
+\r
+#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)\r
+#ifndef popen\r
+#define popen(x, y) _popen(x, y)\r
+#endif\r
+#ifndef pclose\r
+#define pclose(x) _pclose(x)\r
+#endif\r
+#define close(x) _close(x)\r
+#define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))\r
+#define RTLD_LAZY  0\r
+#define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))\r
+#define fdopen(x, y) _fdopen((x), (y))\r
+#define write(x, y, z) _write((x), (y), (unsigned) z)\r
+#define read(x, y, z) _read((x), (y), (unsigned) z)\r
+#define flockfile(x) EnterCriticalSection(&global_log_file_lock)\r
+#define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)\r
+#define sleep(x) Sleep((x) * 1000)\r
+\r
+#if !defined(va_copy)\r
+#define va_copy(x, y) x = y\r
+#endif // !va_copy MINGW #defines va_copy\r
+\r
+#if !defined(fileno)\r
+#define fileno(x) _fileno(x)\r
+#endif // !fileno MINGW #defines fileno\r
+\r
+typedef HANDLE pthread_mutex_t;\r
+typedef struct {HANDLE signal, broadcast;} pthread_cond_t;\r
+typedef DWORD pthread_t;\r
+#define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.\r
+\r
+static int pthread_mutex_lock(pthread_mutex_t *);\r
+static int pthread_mutex_unlock(pthread_mutex_t *);\r
+static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);\r
+struct file;\r
+static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);\r
+\r
+#if defined(HAVE_STDINT)\r
+#include <stdint.h>\r
+#else\r
+typedef unsigned int  uint32_t;\r
+typedef unsigned short  uint16_t;\r
+typedef unsigned __int64 uint64_t;\r
+typedef __int64   int64_t;\r
+#define INT64_MAX  9223372036854775807\r
+#endif // HAVE_STDINT\r
+\r
+// POSIX dirent interface\r
+struct dirent {\r
+  char d_name[PATH_MAX];\r
+};\r
+\r
+typedef struct DIR {\r
+  HANDLE   handle;\r
+  WIN32_FIND_DATAW info;\r
+  struct dirent  result;\r
+} DIR;\r
+\r
+#ifndef HAVE_POLL\r
+struct pollfd {\r
+  int fd;\r
+  short events;\r
+  short revents;\r
+};\r
+#define POLLIN 1\r
+#endif\r
+\r
+\r
+// Mark required libraries\r
+#ifdef _MSC_VER\r
+#pragma comment(lib, "Ws2_32.lib")\r
+#endif\r
+\r
+#else    // UNIX  specific\r
+#include <sys/wait.h>\r
+#include <sys/socket.h>\r
+#include <sys/poll.h>\r
+#include <netinet/in.h>\r
+#include <arpa/inet.h>\r
+#include <sys/time.h>\r
+#include <stdint.h>\r
+#include <inttypes.h>\r
+#include <netdb.h>\r
+\r
+#include <pwd.h>\r
+#include <unistd.h>\r
+#include <dirent.h>\r
+#if !defined(NO_SSL_DL) && !defined(NO_SSL)\r
+#include <dlfcn.h>\r
+#endif\r
+#include <pthread.h>\r
+#if defined(__MACH__)\r
+#define SSL_LIB   "libssl.dylib"\r
+#define CRYPTO_LIB  "libcrypto.dylib"\r
+#else\r
+#if !defined(SSL_LIB)\r
+#define SSL_LIB   "libssl.so"\r
+#endif\r
+#if !defined(CRYPTO_LIB)\r
+#define CRYPTO_LIB  "libcrypto.so"\r
+#endif\r
+#endif\r
+#ifndef O_BINARY\r
+#define O_BINARY  0\r
+#endif // O_BINARY\r
+#define closesocket(a) close(a)\r
+#define mg_mkdir(x, y) mkdir(x, y)\r
+#define mg_remove(x) remove(x)\r
+#define mg_sleep(x) usleep((x) * 1000)\r
+#define ERRNO errno\r
+#define INVALID_SOCKET (-1)\r
+#define INT64_FMT PRId64\r
+typedef int SOCKET;\r
+#define WINCDECL\r
+\r
+#endif // End of Windows and UNIX specific includes\r
+\r
+#include "mongoose.h"\r
+\r
+#define MONGOOSE_VERSION "3.8"\r
+#define PASSWORDS_FILE_NAME ".htpasswd"\r
+#define CGI_ENVIRONMENT_SIZE 4096\r
+#define MAX_CGI_ENVIR_VARS 64\r
+#define MG_BUF_LEN 8192\r
+#define MAX_REQUEST_SIZE 16384\r
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))\r
+\r
+#ifdef _WIN32\r
+static CRITICAL_SECTION global_log_file_lock;\r
+static pthread_t pthread_self(void) {\r
+  return GetCurrentThreadId();\r
+}\r
+#endif // _WIN32\r
+\r
+#ifdef DEBUG_TRACE\r
+#undef DEBUG_TRACE\r
+#define DEBUG_TRACE(x)\r
+#else\r
+#if defined(DEBUG)\r
+#define DEBUG_TRACE(x) do { \\r
+  flockfile(stdout); \\r
+  printf("*** %lu.%p.%s.%d: ", \\r
+         (unsigned long) time(NULL), (void *) pthread_self(), \\r
+         __func__, __LINE__); \\r
+  printf x; \\r
+  putchar('\n'); \\r
+  fflush(stdout); \\r
+  funlockfile(stdout); \\r
+} while (0)\r
+#else\r
+#define DEBUG_TRACE(x)\r
+#endif // DEBUG\r
+#endif // DEBUG_TRACE\r
+\r
+// Darwin prior to 7.0 and Win32 do not have socklen_t\r
+#ifdef NO_SOCKLEN_T\r
+typedef int socklen_t;\r
+#endif // NO_SOCKLEN_T\r
+#define _DARWIN_UNLIMITED_SELECT\r
+\r
+#if !defined(MSG_NOSIGNAL)\r
+#define MSG_NOSIGNAL 0\r
+#endif\r
+\r
+#if !defined(SOMAXCONN)\r
+#define SOMAXCONN 100\r
+#endif\r
+\r
+#if !defined(PATH_MAX)\r
+#define PATH_MAX 4096\r
+#endif\r
+\r
+static const char *http_500_error = "Internal Server Error";\r
+\r
+#if defined(NO_SSL_DL)\r
+#include <openssl/ssl.h>\r
+#else\r
+// SSL loaded dynamically from DLL.\r
+// I put the prototypes here to be independent from OpenSSL source installation.\r
+typedef struct ssl_st SSL;\r
+typedef struct ssl_method_st SSL_METHOD;\r
+typedef struct ssl_ctx_st SSL_CTX;\r
+\r
+struct ssl_func {\r
+  const char *name;   // SSL function name\r
+  void  (*ptr)(void); // Function pointer\r
+};\r
+\r
+#define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)\r
+#define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)\r
+#define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)\r
+#define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)\r
+#define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)\r
+#define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)\r
+#define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)\r
+#define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)\r
+#define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)\r
+#define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)\r
+#define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)\r
+#define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \\r
+        const char *, int)) ssl_sw[11].ptr)\r
+#define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \\r
+        const char *, int)) ssl_sw[12].ptr)\r
+#define SSL_CTX_set_default_passwd_cb \\r
+  (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)\r
+#define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)\r
+#define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)\r
+#define SSL_CTX_use_certificate_chain_file \\r
+  (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)\r
+#define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)\r
+#define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)\r
+#define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)\r
+#define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr)\r
+\r
+#define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)\r
+#define CRYPTO_set_locking_callback \\r
+  (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)\r
+#define CRYPTO_set_id_callback \\r
+  (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)\r
+#define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)\r
+#define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)\r
+\r
+// set_ssl_option() function updates this array.\r
+// It loads SSL library dynamically and changes NULLs to the actual addresses\r
+// of respective functions. The macros above (like SSL_connect()) are really\r
+// just calling these functions indirectly via the pointer.\r
+static struct ssl_func ssl_sw[] = {\r
+  {"SSL_free",   NULL},\r
+  {"SSL_accept",   NULL},\r
+  {"SSL_connect",   NULL},\r
+  {"SSL_read",   NULL},\r
+  {"SSL_write",   NULL},\r
+  {"SSL_get_error",  NULL},\r
+  {"SSL_set_fd",   NULL},\r
+  {"SSL_new",   NULL},\r
+  {"SSL_CTX_new",   NULL},\r
+  {"SSLv23_server_method", NULL},\r
+  {"SSL_library_init",  NULL},\r
+  {"SSL_CTX_use_PrivateKey_file", NULL},\r
+  {"SSL_CTX_use_certificate_file",NULL},\r
+  {"SSL_CTX_set_default_passwd_cb",NULL},\r
+  {"SSL_CTX_free",  NULL},\r
+  {"SSL_load_error_strings", NULL},\r
+  {"SSL_CTX_use_certificate_chain_file", NULL},\r
+  {"SSLv23_client_method", NULL},\r
+  {"SSL_pending", NULL},\r
+  {"SSL_CTX_set_verify", NULL},\r
+  {"SSL_shutdown",   NULL},\r
+  {NULL,    NULL}\r
+};\r
+\r
+// Similar array as ssl_sw. These functions could be located in different lib.\r
+#if !defined(NO_SSL)\r
+static struct ssl_func crypto_sw[] = {\r
+  {"CRYPTO_num_locks",  NULL},\r
+  {"CRYPTO_set_locking_callback", NULL},\r
+  {"CRYPTO_set_id_callback", NULL},\r
+  {"ERR_get_error",  NULL},\r
+  {"ERR_error_string", NULL},\r
+  {NULL,    NULL}\r
+};\r
+#endif // NO_SSL\r
+#endif // NO_SSL_DL\r
+\r
+static const char *month_names[] = {\r
+  "Jan", "Feb", "Mar", "Apr", "May", "Jun",\r
+  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"\r
+};\r
+\r
+// Unified socket address. For IPv6 support, add IPv6 address structure\r
+// in the union u.\r
+union usa {\r
+  struct sockaddr sa;\r
+  struct sockaddr_in sin;\r
+#if defined(USE_IPV6)\r
+  struct sockaddr_in6 sin6;\r
+#endif\r
+};\r
+\r
+// Describes a string (chunk of memory).\r
+struct vec {\r
+  const char *ptr;\r
+  size_t len;\r
+};\r
+\r
+struct file {\r
+  int is_directory;\r
+  time_t modification_time;\r
+  int64_t size;\r
+  FILE *fp;\r
+  const char *membuf;   // Non-NULL if file data is in memory\r
+};\r
+#define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL}\r
+\r
+// Describes listening socket, or socket which was accept()-ed by the master\r
+// thread and queued for future handling by the worker thread.\r
+struct socket {\r
+  SOCKET sock;          // Listening socket\r
+  union usa lsa;        // Local socket address\r
+  union usa rsa;        // Remote socket address\r
+  unsigned is_ssl:1;    // Is port SSL-ed\r
+  unsigned ssl_redir:1; // Is port supposed to redirect everything to SSL port\r
+};\r
+\r
+// NOTE(lsm): this enum shoulds be in sync with the config_options below.\r
+enum {\r
+  CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,\r
+  PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,\r
+  ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,\r
+  GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,\r
+  EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,\r
+  NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,\r
+  NUM_OPTIONS\r
+};\r
+\r
+static const char *config_options[] = {\r
+  "cgi_pattern", "**.cgi$|**.pl$|**.php$",\r
+  "cgi_environment", NULL,\r
+  "put_delete_auth_file", NULL,\r
+  "cgi_interpreter", NULL,\r
+  "protect_uri", NULL,\r
+  "authentication_domain", "mydomain.com",\r
+  "ssi_pattern", "**.shtml$|**.shtm$",\r
+  "throttle", NULL,\r
+  "access_log_file", NULL,\r
+  "enable_directory_listing", "yes",\r
+  "error_log_file", NULL,\r
+  "global_auth_file", NULL,\r
+  "index_files",\r
+    "index.html,index.htm,index.cgi,index.shtml,index.php,index.lp",\r
+  "enable_keep_alive", "no",\r
+  "access_control_list", NULL,\r
+  "extra_mime_types", NULL,\r
+  "listening_ports", "8080",\r
+  "document_root",  ".",\r
+  "ssl_certificate", NULL,\r
+  "num_threads", "50",\r
+  "run_as_user", NULL,\r
+  "url_rewrite_patterns", NULL,\r
+  "hide_files_patterns", NULL,\r
+  "request_timeout_ms", "30000",\r
+  NULL\r
+};\r
+\r
+struct mg_context {\r
+  volatile int stop_flag;         // Should we stop event loop\r
+  SSL_CTX *ssl_ctx;               // SSL context\r
+  char *config[NUM_OPTIONS];      // Mongoose configuration parameters\r
+  struct mg_callbacks callbacks;  // User-defined callback function\r
+  void *user_data;                // User-defined data\r
+\r
+  struct socket *listening_sockets;\r
+  int num_listening_sockets;\r
+\r
+  volatile int num_threads;  // Number of threads\r
+  pthread_mutex_t mutex;     // Protects (max|num)_threads\r
+  pthread_cond_t  cond;      // Condvar for tracking workers terminations\r
+\r
+  struct socket queue[20];   // Accepted sockets\r
+  volatile int sq_head;      // Head of the socket queue\r
+  volatile int sq_tail;      // Tail of the socket queue\r
+  pthread_cond_t sq_full;    // Signaled when socket is produced\r
+  pthread_cond_t sq_empty;   // Signaled when socket is consumed\r
+};\r
+\r
+struct mg_connection {\r
+  struct mg_request_info request_info;\r
+  struct mg_context *ctx;\r
+  SSL *ssl;                   // SSL descriptor\r
+  SSL_CTX *client_ssl_ctx;    // SSL context for client connections\r
+  struct socket client;       // Connected client\r
+  time_t birth_time;          // Time when request was received\r
+  int64_t num_bytes_sent;     // Total bytes sent to client\r
+  int64_t content_len;        // Content-Length header value\r
+  int64_t consumed_content;   // How many bytes of content have been read\r
+  char *buf;                  // Buffer for received data\r
+  char *path_info;            // PATH_INFO part of the URL\r
+  int must_close;             // 1 if connection must be closed\r
+  int buf_size;               // Buffer size\r
+  int request_len;            // Size of the request + headers in a buffer\r
+  int data_len;               // Total size of data in a buffer\r
+  int status_code;            // HTTP reply status code, e.g. 200\r
+  int throttle;               // Throttling, bytes/sec. <= 0 means no throttle\r
+  time_t last_throttle_time;  // Last time throttled data was sent\r
+  int64_t last_throttle_bytes;// Bytes sent this second\r
+};\r
+\r
+// Directory entry\r
+struct de {\r
+  struct mg_connection *conn;\r
+  char *file_name;\r
+  struct file file;\r
+};\r
+\r
+const char **mg_get_valid_option_names(void) {\r
+  return config_options;\r
+}\r
+\r
+static int is_file_in_memory(struct mg_connection *conn, const char *path,\r
+                             struct file *filep) {\r
+  size_t size = 0;\r
+  if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :\r
+       conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {\r
+    // NOTE: override filep->size only on success. Otherwise, it might break\r
+    // constructs like if (!mg_stat() || !mg_fopen()) ...\r
+    filep->size = size;\r
+  }\r
+  return filep->membuf != NULL;\r
+}\r
+\r
+static int is_file_opened(const struct file *filep) {\r
+  return filep->membuf != NULL || filep->fp != NULL;\r
+}\r
+\r
+static int mg_fopen(struct mg_connection *conn, const char *path,\r
+                    const char *mode, struct file *filep) {\r
+  if (!is_file_in_memory(conn, path, filep)) {\r
+#ifdef _WIN32\r
+    wchar_t wbuf[PATH_MAX], wmode[20];\r
+    to_unicode(path, wbuf, ARRAY_SIZE(wbuf));\r
+    MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));\r
+    filep->fp = _wfopen(wbuf, wmode);\r
+#else\r
+    filep->fp = fopen(path, mode);\r
+#endif\r
+  }\r
+\r
+  return is_file_opened(filep);\r
+}\r
+\r
+static void mg_fclose(struct file *filep) {\r
+  if (filep != NULL && filep->fp != NULL) {\r
+    fclose(filep->fp);\r
+  }\r
+}\r
+\r
+static int get_option_index(const char *name) {\r
+  int i;\r
+\r
+  for (i = 0; config_options[i * 2] != NULL; i++) {\r
+    if (strcmp(config_options[i * 2], name) == 0) {\r
+      return i;\r
+    }\r
+  }\r
+  return -1;\r
+}\r
+\r
+const char *mg_get_option(const struct mg_context *ctx, const char *name) {\r
+  int i;\r
+  if ((i = get_option_index(name)) == -1) {\r
+    return NULL;\r
+  } else if (ctx->config[i] == NULL) {\r
+    return "";\r
+  } else {\r
+    return ctx->config[i];\r
+  }\r
+}\r
+\r
+static void sockaddr_to_string(char *buf, size_t len,\r
+                                     const union usa *usa) {\r
+  buf[0] = '\0';\r
+#if defined(USE_IPV6)\r
+  inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?\r
+            (void *) &usa->sin.sin_addr :\r
+            (void *) &usa->sin6.sin6_addr, buf, len);\r
+#elif defined(_WIN32)\r
+  // Only Windoze Vista (and newer) have inet_ntop()\r
+  strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);\r
+#else\r
+  inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);\r
+#endif\r
+}\r
+\r
+static void cry(struct mg_connection *conn,\r
+                PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);\r
+\r
+// Print error message to the opened error log stream.\r
+static void cry(struct mg_connection *conn, const char *fmt, ...) {\r
+  char buf[MG_BUF_LEN], src_addr[20];\r
+  va_list ap;\r
+  FILE *fp;\r
+  time_t timestamp;\r
+\r
+  va_start(ap, fmt);\r
+  (void) vsnprintf(buf, sizeof(buf), fmt, ap);\r
+  va_end(ap);\r
+\r
+  // Do not lock when getting the callback value, here and below.\r
+  // I suppose this is fine, since function cannot disappear in the\r
+  // same way string option can.\r
+  if (conn->ctx->callbacks.log_message == NULL ||\r
+      conn->ctx->callbacks.log_message(conn, buf) == 0) {\r
+    fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :\r
+      fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");\r
+\r
+    if (fp != NULL) {\r
+      flockfile(fp);\r
+      timestamp = time(NULL);\r
+\r
+      sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);\r
+      fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,\r
+              src_addr);\r
+\r
+      if (conn->request_info.request_method != NULL) {\r
+        fprintf(fp, "%s %s: ", conn->request_info.request_method,\r
+                conn->request_info.uri);\r
+      }\r
+\r
+      fprintf(fp, "%s", buf);\r
+      fputc('\n', fp);\r
+      funlockfile(fp);\r
+      fclose(fp);\r
+    }\r
+  }\r
+}\r
+\r
+// Return fake connection structure. Used for logging, if connection\r
+// is not applicable at the moment of logging.\r
+static struct mg_connection *fc(struct mg_context *ctx) {\r
+  static struct mg_connection fake_connection;\r
+  fake_connection.ctx = ctx;\r
+  return &fake_connection;\r
+}\r
+\r
+const char *mg_version(void) {\r
+  return MONGOOSE_VERSION;\r
+}\r
+\r
+struct mg_request_info *mg_get_request_info(struct mg_connection *conn) {\r
+  return &conn->request_info;\r
+}\r
+\r
+static void mg_strlcpy(register char *dst, register const char *src, size_t n) {\r
+  for (; *src != '\0' && n > 1; n--) {\r
+    *dst++ = *src++;\r
+  }\r
+  *dst = '\0';\r
+}\r
+\r
+static int lowercase(const char *s) {\r
+  return tolower(* (const unsigned char *) s);\r
+}\r
+\r
+static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {\r
+  int diff = 0;\r
+\r
+  if (len > 0)\r
+    do {\r
+      diff = lowercase(s1++) - lowercase(s2++);\r
+    } while (diff == 0 && s1[-1] != '\0' && --len > 0);\r
+\r
+  return diff;\r
+}\r
+\r
+static int mg_strcasecmp(const char *s1, const char *s2) {\r
+  int diff;\r
+\r
+  do {\r
+    diff = lowercase(s1++) - lowercase(s2++);\r
+  } while (diff == 0 && s1[-1] != '\0');\r
+\r
+  return diff;\r
+}\r
+\r
+static char * mg_strndup(const char *ptr, size_t len) {\r
+  char *p;\r
+\r
+  if ((p = (char *) malloc(len + 1)) != NULL) {\r
+    mg_strlcpy(p, ptr, len + 1);\r
+  }\r
+\r
+  return p;\r
+}\r
+\r
+static char * mg_strdup(const char *str) {\r
+  return mg_strndup(str, strlen(str));\r
+}\r
+\r
+static const char *mg_strcasestr(const char *big_str, const char *small_str) {\r
+  int i, big_len = strlen(big_str), small_len = strlen(small_str);\r
+\r
+  for (i = 0; i <= big_len - small_len; i++) {\r
+    if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {\r
+      return big_str + i;\r
+    }\r
+  }\r
+\r
+  return NULL;\r
+}\r
+\r
+// Like snprintf(), but never returns negative value, or a value\r
+// that is larger than a supplied buffer.\r
+// Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability\r
+// in his audit report.\r
+static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,\r
+                        const char *fmt, va_list ap) {\r
+  int n;\r
+\r
+  if (buflen == 0)\r
+    return 0;\r
+\r
+  n = vsnprintf(buf, buflen, fmt, ap);\r
+\r
+  if (n < 0) {\r
+    cry(conn, "vsnprintf error");\r
+    n = 0;\r
+  } else if (n >= (int) buflen) {\r
+    cry(conn, "truncating vsnprintf buffer: [%.*s]",\r
+        n > 200 ? 200 : n, buf);\r
+    n = (int) buflen - 1;\r
+  }\r
+  buf[n] = '\0';\r
+\r
+  return n;\r
+}\r
+\r
+static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,\r
+                       PRINTF_FORMAT_STRING(const char *fmt), ...)\r
+  PRINTF_ARGS(4, 5);\r
+\r
+static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,\r
+                       const char *fmt, ...) {\r
+  va_list ap;\r
+  int n;\r
+\r
+  va_start(ap, fmt);\r
+  n = mg_vsnprintf(conn, buf, buflen, fmt, ap);\r
+  va_end(ap);\r
+\r
+  return n;\r
+}\r
+\r
+// Skip the characters until one of the delimiters characters found.\r
+// 0-terminate resulting word. Skip the delimiter and following whitespaces.\r
+// Advance pointer to buffer to the next word. Return found 0-terminated word.\r
+// Delimiters can be quoted with quotechar.\r
+static char *skip_quoted(char **buf, const char *delimiters,\r
+                         const char *whitespace, char quotechar) {\r
+  char *p, *begin_word, *end_word, *end_whitespace;\r
+\r
+  begin_word = *buf;\r
+  end_word = begin_word + strcspn(begin_word, delimiters);\r
+\r
+  // Check for quotechar\r
+  if (end_word > begin_word) {\r
+    p = end_word - 1;\r
+    while (*p == quotechar) {\r
+      // If there is anything beyond end_word, copy it\r
+      if (*end_word == '\0') {\r
+        *p = '\0';\r
+        break;\r
+      } else {\r
+        size_t end_off = strcspn(end_word + 1, delimiters);\r
+        memmove (p, end_word, end_off + 1);\r
+        p += end_off; // p must correspond to end_word - 1\r
+        end_word += end_off + 1;\r
+      }\r
+    }\r
+    for (p++; p < end_word; p++) {\r
+      *p = '\0';\r
+    }\r
+  }\r
+\r
+  if (*end_word == '\0') {\r
+    *buf = end_word;\r
+  } else {\r
+    end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);\r
+\r
+    for (p = end_word; p < end_whitespace; p++) {\r
+      *p = '\0';\r
+    }\r
+\r
+    *buf = end_whitespace;\r
+  }\r
+\r
+  return begin_word;\r
+}\r
+\r
+// Simplified version of skip_quoted without quote char\r
+// and whitespace == delimiters\r
+static char *skip(char **buf, const char *delimiters) {\r
+  return skip_quoted(buf, delimiters, delimiters, 0);\r
+}\r
+\r
+\r
+// Return HTTP header value, or NULL if not found.\r
+static const char *get_header(const struct mg_request_info *ri,\r
+                              const char *name) {\r
+  int i;\r
+\r
+  for (i = 0; i < ri->num_headers; i++)\r
+    if (!mg_strcasecmp(name, ri->http_headers[i].name))\r
+      return ri->http_headers[i].value;\r
+\r
+  return NULL;\r
+}\r
+\r
+const char *mg_get_header(const struct mg_connection *conn, const char *name) {\r
+  return get_header(&conn->request_info, name);\r
+}\r
+\r
+// A helper function for traversing a comma separated list of values.\r
+// It returns a list pointer shifted to the next value, or NULL if the end\r
+// of the list found.\r
+// Value is stored in val vector. If value has form "x=y", then eq_val\r
+// vector is initialized to point to the "y" part, and val vector length\r
+// is adjusted to point only to "x".\r
+static const char *next_option(const char *list, struct vec *val,\r
+                               struct vec *eq_val) {\r
+  if (list == NULL || *list == '\0') {\r
+    // End of the list\r
+    list = NULL;\r
+  } else {\r
+    val->ptr = list;\r
+    if ((list = strchr(val->ptr, ',')) != NULL) {\r
+      // Comma found. Store length and shift the list ptr\r
+      val->len = list - val->ptr;\r
+      list++;\r
+    } else {\r
+      // This value is the last one\r
+      list = val->ptr + strlen(val->ptr);\r
+      val->len = list - val->ptr;\r
+    }\r
+\r
+    if (eq_val != NULL) {\r
+      // Value has form "x=y", adjust pointers and lengths\r
+      // so that val points to "x", and eq_val points to "y".\r
+      eq_val->len = 0;\r
+      eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);\r
+      if (eq_val->ptr != NULL) {\r
+        eq_val->ptr++;  // Skip over '=' character\r
+        eq_val->len = val->ptr + val->len - eq_val->ptr;\r
+        val->len = (eq_val->ptr - val->ptr) - 1;\r
+      }\r
+    }\r
+  }\r
+\r
+  return list;\r
+}\r
+\r
+static int match_prefix(const char *pattern, int pattern_len, const char *str) {\r
+  const char *or_str;\r
+  int i, j, len, res;\r
+\r
+  if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {\r
+    res = match_prefix(pattern, or_str - pattern, str);\r
+    return res > 0 ? res :\r
+        match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);\r
+  }\r
+\r
+  i = j = 0;\r
+  res = -1;\r
+  for (; i < pattern_len; i++, j++) {\r
+    if (pattern[i] == '?' && str[j] != '\0') {\r
+      continue;\r
+    } else if (pattern[i] == '$') {\r
+      return str[j] == '\0' ? j : -1;\r
+    } else if (pattern[i] == '*') {\r
+      i++;\r
+      if (pattern[i] == '*') {\r
+        i++;\r
+        len = (int) strlen(str + j);\r
+      } else {\r
+        len = (int) strcspn(str + j, "/");\r
+      }\r
+      if (i == pattern_len) {\r
+        return j + len;\r
+      }\r
+      do {\r
+        res = match_prefix(pattern + i, pattern_len - i, str + j + len);\r
+      } while (res == -1 && len-- > 0);\r
+      return res == -1 ? -1 : j + res + len;\r
+    } else if (pattern[i] != str[j]) {\r
+      return -1;\r
+    }\r
+  }\r
+  return j;\r
+}\r
+\r
+// HTTP 1.1 assumes keep alive if "Connection:" header is not set\r
+// This function must tolerate situations when connection info is not\r
+// set up, for example if request parsing failed.\r
+static int should_keep_alive(const struct mg_connection *conn) {\r
+  const char *http_version = conn->request_info.http_version;\r
+  const char *header = mg_get_header(conn, "Connection");\r
+  if (conn->must_close ||\r
+      conn->status_code == 401 ||\r
+      mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||\r
+      (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||\r
+      (header == NULL && http_version && strcmp(http_version, "1.1"))) {\r
+    return 0;\r
+  }\r
+  return 1;\r
+}\r
+\r
+static const char *suggest_connection_header(const struct mg_connection *conn) {\r
+  return should_keep_alive(conn) ? "keep-alive" : "close";\r
+}\r
+\r
+static void send_http_error(struct mg_connection *, int, const char *,\r
+                            PRINTF_FORMAT_STRING(const char *fmt), ...)\r
+  PRINTF_ARGS(4, 5);\r
+\r
+\r
+static void send_http_error(struct mg_connection *conn, int status,\r
+                            const char *reason, const char *fmt, ...) {\r
+  char buf[MG_BUF_LEN];\r
+  va_list ap;\r
+  int len = 0;\r
+\r
+  conn->status_code = status;\r
+  if (conn->ctx->callbacks.http_error == NULL ||\r
+      conn->ctx->callbacks.http_error(conn, status)) {\r
+    buf[0] = '\0';\r
+\r
+    // Errors 1xx, 204 and 304 MUST NOT send a body\r
+    if (status > 199 && status != 204 && status != 304) {\r
+      len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);\r
+      buf[len++] = '\n';\r
+\r
+      va_start(ap, fmt);\r
+      len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);\r
+      va_end(ap);\r
+    }\r
+    DEBUG_TRACE(("[%s]", buf));\r
+\r
+    mg_printf(conn, "HTTP/1.1 %d %s\r\n"\r
+              "Content-Length: %d\r\n"\r
+              "Connection: %s\r\n\r\n", status, reason, len,\r
+              suggest_connection_header(conn));\r
+    conn->num_bytes_sent += mg_printf(conn, "%s", buf);\r
+  }\r
+}\r
+\r
+#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
+static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) {\r
+  (void) unused;\r
+  *mutex = CreateMutex(NULL, FALSE, NULL);\r
+  return *mutex == NULL ? -1 : 0;\r
+}\r
+\r
+static int pthread_mutex_destroy(pthread_mutex_t *mutex) {\r
+  return CloseHandle(*mutex) == 0 ? -1 : 0;\r
+}\r
+\r
+static int pthread_mutex_lock(pthread_mutex_t *mutex) {\r
+  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;\r
+}\r
+\r
+static int pthread_mutex_unlock(pthread_mutex_t *mutex) {\r
+  return ReleaseMutex(*mutex) == 0 ? -1 : 0;\r
+}\r
+\r
+static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {\r
+  (void) unused;\r
+  cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);\r
+  cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);\r
+  return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;\r
+}\r
+\r
+static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {\r
+  HANDLE handles[] = {cv->signal, cv->broadcast};\r
+  ReleaseMutex(*mutex);\r
+  WaitForMultipleObjects(2, handles, FALSE, INFINITE);\r
+  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;\r
+}\r
+\r
+static int pthread_cond_signal(pthread_cond_t *cv) {\r
+  return SetEvent(cv->signal) == 0 ? -1 : 0;\r
+}\r
+\r
+static int pthread_cond_broadcast(pthread_cond_t *cv) {\r
+  // Implementation with PulseEvent() has race condition, see\r
+  // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html\r
+  return PulseEvent(cv->broadcast) == 0 ? -1 : 0;\r
+}\r
+\r
+static int pthread_cond_destroy(pthread_cond_t *cv) {\r
+  return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;\r
+}\r
+\r
+// For Windows, change all slashes to backslashes in path names.\r
+static void change_slashes_to_backslashes(char *path) {\r
+  int i;\r
+\r
+  for (i = 0; path[i] != '\0'; i++) {\r
+    if (path[i] == '/')\r
+      path[i] = '\\';\r
+    // i > 0 check is to preserve UNC paths, like \\server\file.txt\r
+    if (path[i] == '\\' && i > 0)\r
+      while (path[i + 1] == '\\' || path[i + 1] == '/')\r
+        (void) memmove(path + i + 1,\r
+            path + i + 2, strlen(path + i + 1));\r
+  }\r
+}\r
+\r
+// Encode 'path' which is assumed UTF-8 string, into UNICODE string.\r
+// wbuf and wbuf_len is a target buffer and its length.\r
+static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {\r
+  char buf[PATH_MAX], buf2[PATH_MAX];\r
+\r
+  mg_strlcpy(buf, path, sizeof(buf));\r
+  change_slashes_to_backslashes(buf);\r
+\r
+  // Convert to Unicode and back. If doubly-converted string does not\r
+  // match the original, something is fishy, reject.\r
+  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));\r
+  MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);\r
+  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),\r
+                      NULL, NULL);\r
+  if (strcmp(buf, buf2) != 0) {\r
+    wbuf[0] = L'\0';\r
+  }\r
+}\r
+\r
+#if defined(_WIN32_WCE)\r
+static time_t time(time_t *ptime) {\r
+  time_t t;\r
+  SYSTEMTIME st;\r
+  FILETIME ft;\r
+\r
+  GetSystemTime(&st);\r
+  SystemTimeToFileTime(&st, &ft);\r
+  t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);\r
+\r
+  if (ptime != NULL) {\r
+    *ptime = t;\r
+  }\r
+\r
+  return t;\r
+}\r
+\r
+static struct tm *localtime(const time_t *ptime, struct tm *ptm) {\r
+  int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;\r
+  FILETIME ft, lft;\r
+  SYSTEMTIME st;\r
+  TIME_ZONE_INFORMATION tzinfo;\r
+\r
+  if (ptm == NULL) {\r
+    return NULL;\r
+  }\r
+\r
+  * (int64_t *) &ft = t;\r
+  FileTimeToLocalFileTime(&ft, &lft);\r
+  FileTimeToSystemTime(&lft, &st);\r
+  ptm->tm_year = st.wYear - 1900;\r
+  ptm->tm_mon = st.wMonth - 1;\r
+  ptm->tm_wday = st.wDayOfWeek;\r
+  ptm->tm_mday = st.wDay;\r
+  ptm->tm_hour = st.wHour;\r
+  ptm->tm_min = st.wMinute;\r
+  ptm->tm_sec = st.wSecond;\r
+  ptm->tm_yday = 0; // hope nobody uses this\r
+  ptm->tm_isdst =\r
+    GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;\r
+\r
+  return ptm;\r
+}\r
+\r
+static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {\r
+  // FIXME(lsm): fix this.\r
+  return localtime(ptime, ptm);\r
+}\r
+\r
+static size_t strftime(char *dst, size_t dst_size, const char *fmt,\r
+                       const struct tm *tm) {\r
+  (void) snprintf(dst, dst_size, "implement strftime() for WinCE");\r
+  return 0;\r
+}\r
+#endif\r
+\r
+// Windows happily opens files with some garbage at the end of file name.\r
+// For example, fopen("a.cgi    ", "r") on Windows successfully opens\r
+// "a.cgi", despite one would expect an error back.\r
+// This function returns non-0 if path ends with some garbage.\r
+static int path_cannot_disclose_cgi(const char *path) {\r
+  static const char *allowed_last_characters = "_-";\r
+  int last = path[strlen(path) - 1];\r
+  return isalnum(last) || strchr(allowed_last_characters, last) != NULL;\r
+}\r
+\r
+static int mg_stat(struct mg_connection *conn, const char *path,\r
+                   struct file *filep) {\r
+  wchar_t wbuf[PATH_MAX];\r
+  WIN32_FILE_ATTRIBUTE_DATA info;\r
+\r
+  if (!is_file_in_memory(conn, path, filep)) {\r
+    to_unicode(path, wbuf, ARRAY_SIZE(wbuf));\r
+    if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {\r
+      filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);\r
+      filep->modification_time = SYS2UNIX_TIME(\r
+          info.ftLastWriteTime.dwLowDateTime,\r
+          info.ftLastWriteTime.dwHighDateTime);\r
+      filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;\r
+      // If file name is fishy, reset the file structure and return error.\r
+      // Note it is important to reset, not just return the error, cause\r
+      // functions like is_file_opened() check the struct.\r
+      if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {\r
+        memset(filep, 0, sizeof(*filep));\r
+      }\r
+    }\r
+  }\r
+\r
+  return filep->membuf != NULL || filep->modification_time != 0;\r
+}\r
+\r
+static int mg_remove(const char *path) {\r
+  wchar_t wbuf[PATH_MAX];\r
+  to_unicode(path, wbuf, ARRAY_SIZE(wbuf));\r
+  return DeleteFileW(wbuf) ? 0 : -1;\r
+}\r
+\r
+static int mg_mkdir(const char *path, int mode) {\r
+  char buf[PATH_MAX];\r
+  wchar_t wbuf[PATH_MAX];\r
+\r
+  (void) mode;\r
+  mg_strlcpy(buf, path, sizeof(buf));\r
+  change_slashes_to_backslashes(buf);\r
+\r
+  (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));\r
+\r
+  return CreateDirectoryW(wbuf, NULL) ? 0 : -1;\r
+}\r
+\r
+// Implementation of POSIX opendir/closedir/readdir for Windows.\r
+static DIR * opendir(const char *name) {\r
+  DIR *dir = NULL;\r
+  wchar_t wpath[PATH_MAX];\r
+  DWORD attrs;\r
+\r
+  if (name == NULL) {\r
+    SetLastError(ERROR_BAD_ARGUMENTS);\r
+  } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {\r
+    SetLastError(ERROR_NOT_ENOUGH_MEMORY);\r
+  } else {\r
+    to_unicode(name, wpath, ARRAY_SIZE(wpath));\r
+    attrs = GetFileAttributesW(wpath);\r
+    if (attrs != 0xFFFFFFFF &&\r
+        ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {\r
+      (void) wcscat(wpath, L"\\*");\r
+      dir->handle = FindFirstFileW(wpath, &dir->info);\r
+      dir->result.d_name[0] = '\0';\r
+    } else {\r
+      free(dir);\r
+      dir = NULL;\r
+    }\r
+  }\r
+\r
+  return dir;\r
+}\r
+\r
+static int closedir(DIR *dir) {\r
+  int result = 0;\r
+\r
+  if (dir != NULL) {\r
+    if (dir->handle != INVALID_HANDLE_VALUE)\r
+      result = FindClose(dir->handle) ? 0 : -1;\r
+\r
+    free(dir);\r
+  } else {\r
+    result = -1;\r
+    SetLastError(ERROR_BAD_ARGUMENTS);\r
+  }\r
+\r
+  return result;\r
+}\r
+\r
+static struct dirent *readdir(DIR *dir) {\r
+  struct dirent *result = 0;\r
+\r
+  if (dir) {\r
+    if (dir->handle != INVALID_HANDLE_VALUE) {\r
+      result = &dir->result;\r
+      (void) WideCharToMultiByte(CP_UTF8, 0,\r
+          dir->info.cFileName, -1, result->d_name,\r
+          sizeof(result->d_name), NULL, NULL);\r
+\r
+      if (!FindNextFileW(dir->handle, &dir->info)) {\r
+        (void) FindClose(dir->handle);\r
+        dir->handle = INVALID_HANDLE_VALUE;\r
+      }\r
+\r
+    } else {\r
+      SetLastError(ERROR_FILE_NOT_FOUND);\r
+    }\r
+  } else {\r
+    SetLastError(ERROR_BAD_ARGUMENTS);\r
+  }\r
+\r
+  return result;\r
+}\r
+\r
+#ifndef HAVE_POLL\r
+static int poll(struct pollfd *pfd, int n, int milliseconds) {\r
+  struct timeval tv;\r
+  fd_set set;\r
+  int i, result, maxfd = 0;\r
+\r
+  tv.tv_sec = milliseconds / 1000;\r
+  tv.tv_usec = (milliseconds % 1000) * 1000;\r
+  FD_ZERO(&set);\r
+\r
+  for (i = 0; i < n; i++) {\r
+    FD_SET((SOCKET) pfd[i].fd, &set);\r
+    pfd[i].revents = 0;\r
+\r
+    if (pfd[i].fd > maxfd) {\r
+        maxfd = pfd[i].fd;\r
+    }\r
+  }\r
+\r
+  if ((result = select(maxfd + 1, &set, NULL, NULL, &tv)) > 0) {\r
+    for (i = 0; i < n; i++) {\r
+      if (FD_ISSET(pfd[i].fd, &set)) {\r
+        pfd[i].revents = POLLIN;\r
+      }\r
+    }\r
+  }\r
+\r
+  return result;\r
+}\r
+#endif // HAVE_POLL\r
+\r
+#define set_close_on_exec(x) // No FD_CLOEXEC on Windows\r
+\r
+int mg_start_thread(mg_thread_func_t f, void *p) {\r
+  return (long)_beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;\r
+}\r
+\r
+static HANDLE dlopen(const char *dll_name, int flags) {\r
+  wchar_t wbuf[PATH_MAX];\r
+  (void) flags;\r
+  to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));\r
+  return LoadLibraryW(wbuf);\r
+}\r
+\r
+#if !defined(NO_CGI)\r
+#define SIGKILL 0\r
+static int kill(pid_t pid, int sig_num) {\r
+  (void) TerminateProcess(pid, sig_num);\r
+  (void) CloseHandle(pid);\r
+  return 0;\r
+}\r
+\r
+static void trim_trailing_whitespaces(char *s) {\r
+  char *e = s + strlen(s) - 1;\r
+  while (e > s && isspace(* (unsigned char *) e)) {\r
+    *e-- = '\0';\r
+  }\r
+}\r
+\r
+static pid_t spawn_process(struct mg_connection *conn, const char *prog,\r
+                           char *envblk, char *envp[], int fd_stdin,\r
+                           int fd_stdout, const char *dir) {\r
+  HANDLE me;\r
+  char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],\r
+       cmdline[PATH_MAX], buf[PATH_MAX];\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  STARTUPINFOA si;\r
+  PROCESS_INFORMATION pi = { 0 };\r
+\r
+  (void) envp;\r
+\r
+  memset(&si, 0, sizeof(si));\r
+  si.cb = sizeof(si);\r
+\r
+  // TODO(lsm): redirect CGI errors to the error log file\r
+  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;\r
+  si.wShowWindow = SW_HIDE;\r
+\r
+  me = GetCurrentProcess();\r
+  DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,\r
+                  &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);\r
+  DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,\r
+                  &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);\r
+\r
+  // If CGI file is a script, try to read the interpreter line\r
+  interp = conn->ctx->config[CGI_INTERPRETER];\r
+  if (interp == NULL) {\r
+    buf[0] = buf[1] = '\0';\r
+\r
+    // Read the first line of the script into the buffer\r
+    snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);\r
+    if (mg_fopen(conn, cmdline, "r", &file)) {\r
+      p = (char *) file.membuf;\r
+      mg_fgets(buf, sizeof(buf), &file, &p);\r
+      mg_fclose(&file);\r
+      buf[sizeof(buf) - 1] = '\0';\r
+    }\r
+\r
+    if (buf[0] == '#' && buf[1] == '!') {\r
+      trim_trailing_whitespaces(buf + 2);\r
+    } else {\r
+      buf[2] = '\0';\r
+    }\r
+    interp = buf + 2;\r
+  }\r
+\r
+  if (interp[0] != '\0') {\r
+    GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);\r
+    interp = full_interp;\r
+  }\r
+  GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);\r
+\r
+  mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s\\%s",\r
+              interp, interp[0] == '\0' ? "" : " ", full_dir, prog);\r
+\r
+  DEBUG_TRACE(("Running [%s]", cmdline));\r
+  if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,\r
+        CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {\r
+    cry(conn, "%s: CreateProcess(%s): %ld",\r
+        __func__, cmdline, ERRNO);\r
+    pi.hProcess = (pid_t) -1;\r
+  }\r
+\r
+  // Always close these to prevent handle leakage.\r
+  (void) close(fd_stdin);\r
+  (void) close(fd_stdout);\r
+\r
+  (void) CloseHandle(si.hStdOutput);\r
+  (void) CloseHandle(si.hStdInput);\r
+  (void) CloseHandle(pi.hThread);\r
+\r
+  return (pid_t) pi.hProcess;\r
+}\r
+#endif // !NO_CGI\r
+\r
+static int set_non_blocking_mode(SOCKET sock) {\r
+  unsigned long on = 1;\r
+  return ioctlsocket(sock, FIONBIO, &on);\r
+}\r
+\r
+#else\r
+static int mg_stat(struct mg_connection *conn, const char *path,\r
+                   struct file *filep) {\r
+  struct stat st;\r
+\r
+  if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {\r
+    filep->size = st.st_size;\r
+    filep->modification_time = st.st_mtime;\r
+    filep->is_directory = S_ISDIR(st.st_mode);\r
+  } else {\r
+    filep->modification_time = (time_t) 0;\r
+  }\r
+\r
+  return filep->membuf != NULL || filep->modification_time != (time_t) 0;\r
+}\r
+\r
+static void set_close_on_exec(int fd) {\r
+  fcntl(fd, F_SETFD, FD_CLOEXEC);\r
+}\r
+\r
+int mg_start_thread(mg_thread_func_t func, void *param) {\r
+  pthread_t thread_id;\r
+  pthread_attr_t attr;\r
+  int result;\r
+\r
+  (void) pthread_attr_init(&attr);\r
+  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);\r
+  // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled\r
+  // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5);\r
+\r
+  result = pthread_create(&thread_id, &attr, func, param);\r
+  pthread_attr_destroy(&attr);\r
+\r
+  return result;\r
+}\r
+\r
+#ifndef NO_CGI\r
+static pid_t spawn_process(struct mg_connection *conn, const char *prog,\r
+                           char *envblk, char *envp[], int fd_stdin,\r
+                           int fd_stdout, const char *dir) {\r
+  pid_t pid;\r
+  const char *interp;\r
+\r
+  (void) envblk;\r
+\r
+  if ((pid = fork()) == -1) {\r
+    // Parent\r
+    send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));\r
+  } else if (pid == 0) {\r
+    // Child\r
+    if (chdir(dir) != 0) {\r
+      cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));\r
+    } else if (dup2(fd_stdin, 0) == -1) {\r
+      cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO));\r
+    } else if (dup2(fd_stdout, 1) == -1) {\r
+      cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO));\r
+    } else {\r
+      (void) dup2(fd_stdout, 2);\r
+      (void) close(fd_stdin);\r
+      (void) close(fd_stdout);\r
+\r
+      // After exec, all signal handlers are restored to their default values,\r
+      // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's\r
+      // implementation, SIGCHLD's handler will leave unchanged after exec\r
+      // if it was set to be ignored. Restore it to default action.\r
+      signal(SIGCHLD, SIG_DFL);\r
+\r
+      interp = conn->ctx->config[CGI_INTERPRETER];\r
+      if (interp == NULL) {\r
+        (void) execle(prog, prog, NULL, envp);\r
+        cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));\r
+      } else {\r
+        (void) execle(interp, interp, prog, NULL, envp);\r
+        cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,\r
+            strerror(ERRNO));\r
+      }\r
+    }\r
+    exit(EXIT_FAILURE);\r
+  }\r
+\r
+  // Parent. Close stdio descriptors\r
+  (void) close(fd_stdin);\r
+  (void) close(fd_stdout);\r
+\r
+  return pid;\r
+}\r
+#endif // !NO_CGI\r
+\r
+static int set_non_blocking_mode(SOCKET sock) {\r
+  int flags;\r
+\r
+  flags = fcntl(sock, F_GETFL, 0);\r
+  (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);\r
+\r
+  return 0;\r
+}\r
+#endif // _WIN32\r
+\r
+// Write data to the IO channel - opened file descriptor, socket or SSL\r
+// descriptor. Return number of bytes written.\r
+static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,\r
+                    int64_t len) {\r
+  int64_t sent;\r
+  int n, k;\r
+\r
+  (void) ssl;  // Get rid of warning\r
+  sent = 0;\r
+  while (sent < len) {\r
+\r
+    // How many bytes we send in this iteration\r
+    k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);\r
+\r
+#ifndef NO_SSL\r
+    if (ssl != NULL) {\r
+      n = SSL_write(ssl, buf + sent, k);\r
+    } else\r
+#endif\r
+      if (fp != NULL) {\r
+      n = (int) fwrite(buf + sent, 1, (size_t) k, fp);\r
+      if (ferror(fp))\r
+        n = -1;\r
+    } else {\r
+      n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);\r
+    }\r
+\r
+    if (n <= 0)\r
+      break;\r
+\r
+    sent += n;\r
+  }\r
+\r
+  return sent;\r
+}\r
+\r
+// Read from IO channel - opened file descriptor, socket, or SSL descriptor.\r
+// Return negative value on error, or number of bytes read on success.\r
+static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) {\r
+  int nread;\r
+\r
+  if (fp != NULL) {\r
+    // Use read() instead of fread(), because if we're reading from the CGI\r
+    // pipe, fread() may block until IO buffer is filled up. We cannot afford\r
+    // to block and must pass all read bytes immediately to the client.\r
+    nread = read(fileno(fp), buf, (size_t) len);\r
+#ifndef NO_SSL\r
+  } else if (conn->ssl != NULL) {\r
+    nread = SSL_read(conn->ssl, buf, len);\r
+#endif\r
+  } else {\r
+    nread = recv(conn->client.sock, buf, (size_t) len, 0);\r
+  }\r
+\r
+  return conn->ctx->stop_flag ? -1 : nread;\r
+}\r
+\r
+static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len) {\r
+  int n, nread = 0;\r
+\r
+  while (len > 0) {\r
+    n = pull(fp, conn, buf + nread, len);\r
+    if (n < 0) {\r
+      nread = n;  // Propagate the error\r
+      break;\r
+    } else if (n == 0) {\r
+      break;  // No more data to read\r
+    } else {\r
+      conn->consumed_content += n;\r
+      nread += n;\r
+      len -= n;\r
+    }\r
+  }\r
+\r
+  return nread;\r
+}\r
+\r
+int mg_read(struct mg_connection *conn, void *buf, size_t len) {\r
+  int n, buffered_len, nread;\r
+  const char *body;\r
+\r
+  nread = 0;\r
+  if (conn->consumed_content < conn->content_len) {\r
+    // Adjust number of bytes to read.\r
+    int64_t to_read = conn->content_len - conn->consumed_content;\r
+    if (to_read < (int64_t) len) {\r
+      len = (size_t) to_read;\r
+    }\r
+\r
+    // Return buffered data\r
+    body = conn->buf + conn->request_len + conn->consumed_content;\r
+    buffered_len = &conn->buf[conn->data_len] - body;\r
+    if (buffered_len > 0) {\r
+      if (len < (size_t) buffered_len) {\r
+        buffered_len = (int) len;\r
+      }\r
+      memcpy(buf, body, (size_t) buffered_len);\r
+      len -= buffered_len;\r
+      conn->consumed_content += buffered_len;\r
+      nread += buffered_len;\r
+      buf = (char *) buf + buffered_len;\r
+    }\r
+\r
+    // We have returned all buffered data. Read new data from the remote socket.\r
+    n = pull_all(NULL, conn, (char *) buf, (int) len);\r
+    nread = n >= 0 ? nread + n : n;\r
+  }\r
+  return nread;\r
+}\r
+\r
+int mg_write(struct mg_connection *conn, const void *buf, size_t len) {\r
+  time_t now;\r
+  int64_t n, total, allowed;\r
+\r
+  if (conn->throttle > 0) {\r
+    if ((now = time(NULL)) != conn->last_throttle_time) {\r
+      conn->last_throttle_time = now;\r
+      conn->last_throttle_bytes = 0;\r
+    }\r
+    allowed = conn->throttle - conn->last_throttle_bytes;\r
+    if (allowed > (int64_t) len) {\r
+      allowed = len;\r
+    }\r
+    if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,\r
+                      (int64_t) allowed)) == allowed) {\r
+      buf = (char *) buf + total;\r
+      conn->last_throttle_bytes += total;\r
+      while (total < (int64_t) len && conn->ctx->stop_flag == 0) {\r
+        allowed = conn->throttle > (int64_t) len - total ?\r
+          (int64_t) len - total : conn->throttle;\r
+        if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,\r
+                      (int64_t) allowed)) != allowed) {\r
+          break;\r
+        }\r
+        sleep(1);\r
+        conn->last_throttle_bytes = allowed;\r
+        conn->last_throttle_time = time(NULL);\r
+        buf = (char *) buf + n;\r
+        total += n;\r
+      }\r
+    }\r
+  } else {\r
+    total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,\r
+                 (int64_t) len);\r
+  }\r
+  return (int) total;\r
+}\r
+\r
+// Print message to buffer. If buffer is large enough to hold the message,\r
+// return buffer. If buffer is to small, allocate large enough buffer on heap,\r
+// and return allocated buffer.\r
+static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) {\r
+  va_list ap_copy;\r
+  int len;\r
+\r
+  // Windows is not standard-compliant, and vsnprintf() returns -1 if\r
+  // buffer is too small. Also, older versions of msvcrt.dll do not have\r
+  // _vscprintf().  However, if size is 0, vsnprintf() behaves correctly.\r
+  // Therefore, we make two passes: on first pass, get required message length.\r
+  // On second pass, actually print the message.\r
+  va_copy(ap_copy, ap);\r
+  len = vsnprintf(NULL, 0, fmt, ap_copy);\r
+\r
+  if (len > (int) size &&\r
+      (size = len + 1) > 0 &&\r
+      (*buf = (char *) malloc(size)) == NULL) {\r
+    len = -1;  // Allocation failed, mark failure\r
+  } else {\r
+    va_copy(ap_copy, ap);\r
+    vsnprintf(*buf, size, fmt, ap_copy);\r
+  }\r
+\r
+  return len;\r
+}\r
+\r
+int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) {\r
+  char mem[MG_BUF_LEN], *buf = mem;\r
+  int len;\r
+\r
+  if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {\r
+    len = mg_write(conn, buf, (size_t) len);\r
+  }\r
+  if (buf != mem && buf != NULL) {\r
+    free(buf);\r
+  }\r
+\r
+  return len;\r
+}\r
+\r
+int mg_printf(struct mg_connection *conn, const char *fmt, ...) {\r
+  va_list ap;\r
+  va_start(ap, fmt);\r
+  return mg_vprintf(conn, fmt, ap);\r
+}\r
+\r
+int mg_url_decode(const char *src, int src_len, char *dst,\r
+                  int dst_len, int is_form_url_encoded) {\r
+  int i, j, a, b;\r
+#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')\r
+\r
+  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {\r
+    if (src[i] == '%' && i < src_len - 2 &&\r
+        isxdigit(* (const unsigned char *) (src + i + 1)) &&\r
+        isxdigit(* (const unsigned char *) (src + i + 2))) {\r
+      a = tolower(* (const unsigned char *) (src + i + 1));\r
+      b = tolower(* (const unsigned char *) (src + i + 2));\r
+      dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));\r
+      i += 2;\r
+    } else if (is_form_url_encoded && src[i] == '+') {\r
+      dst[j] = ' ';\r
+    } else {\r
+      dst[j] = src[i];\r
+    }\r
+  }\r
+\r
+  dst[j] = '\0'; // Null-terminate the destination\r
+\r
+  return i >= src_len ? j : -1;\r
+}\r
+\r
+int mg_get_var(const char *data, size_t data_len, const char *name,\r
+               char *dst, size_t dst_len) {\r
+  const char *p, *e, *s;\r
+  size_t name_len;\r
+  int len;\r
+\r
+  if (dst == NULL || dst_len == 0) {\r
+    len = -2;\r
+  } else if (data == NULL || name == NULL || data_len == 0) {\r
+    len = -1;\r
+    dst[0] = '\0';\r
+  } else {\r
+    name_len = strlen(name);\r
+    e = data + data_len;\r
+    len = -1;\r
+    dst[0] = '\0';\r
+\r
+    // data is "var1=val1&var2=val2...". Find variable first\r
+    for (p = data; p + name_len < e; p++) {\r
+      if ((p == data || p[-1] == '&') && p[name_len] == '=' &&\r
+          !mg_strncasecmp(name, p, name_len)) {\r
+\r
+        // Point p to variable value\r
+        p += name_len + 1;\r
+\r
+        // Point s to the end of the value\r
+        s = (const char *) memchr(p, '&', (size_t)(e - p));\r
+        if (s == NULL) {\r
+          s = e;\r
+        }\r
+        assert(s >= p);\r
+\r
+        // Decode variable into destination buffer\r
+        len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);\r
+\r
+        // Redirect error code from -1 to -2 (destination buffer too small).\r
+        if (len == -1) {\r
+          len = -2;\r
+        }\r
+        break;\r
+      }\r
+    }\r
+  }\r
+\r
+  return len;\r
+}\r
+\r
+int mg_get_cookie(const char *cookie_header, const char *var_name,\r
+                  char *dst, size_t dst_size) {\r
+  const char *s, *p, *end;\r
+  int name_len, len = -1;\r
+\r
+  if (dst == NULL || dst_size == 0) {\r
+    len = -2;\r
+  } else if (var_name == NULL || (s = cookie_header) == NULL) {\r
+    len = -1;\r
+    dst[0] = '\0';\r
+  } else {\r
+    name_len = (int) strlen(var_name);\r
+    end = s + strlen(s);\r
+    dst[0] = '\0';\r
+\r
+    for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {\r
+      if (s[name_len] == '=') {\r
+        s += name_len + 1;\r
+        if ((p = strchr(s, ' ')) == NULL)\r
+          p = end;\r
+        if (p[-1] == ';')\r
+          p--;\r
+        if (*s == '"' && p[-1] == '"' && p > s + 1) {\r
+          s++;\r
+          p--;\r
+        }\r
+        if ((size_t) (p - s) < dst_size) {\r
+          len = p - s;\r
+          mg_strlcpy(dst, s, (size_t) len + 1);\r
+        } else {\r
+          len = -3;\r
+        }\r
+        break;\r
+      }\r
+    }\r
+  }\r
+  return len;\r
+}\r
+\r
+static void convert_uri_to_file_name(struct mg_connection *conn, char *buf,\r
+                                     size_t buf_len, struct file *filep) {\r
+  struct vec a, b;\r
+  const char *rewrite, *uri = conn->request_info.uri;\r
+  char *p;\r
+  int match_len;\r
+\r
+  // Using buf_len - 1 because memmove() for PATH_INFO may shift part\r
+  // of the path one byte on the right.\r
+  mg_snprintf(conn, buf, buf_len - 1, "%s%s", conn->ctx->config[DOCUMENT_ROOT],\r
+              uri);\r
+\r
+  rewrite = conn->ctx->config[REWRITE];\r
+  while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {\r
+    if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {\r
+      mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr,\r
+                  uri + match_len);\r
+      break;\r
+    }\r
+  }\r
+\r
+  if (!mg_stat(conn, buf, filep)) {\r
+    // Support PATH_INFO for CGI scripts.\r
+    for (p = buf + strlen(buf); p > buf + 1; p--) {\r
+      if (*p == '/') {\r
+        *p = '\0';\r
+        if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],\r
+                         strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&\r
+            mg_stat(conn, buf, filep)) {\r
+          // Shift PATH_INFO block one character right, e.g.\r
+          //  "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"\r
+          // conn->path_info is pointing to the local variable "path" declared\r
+          // in handle_request(), so PATH_INFO is not valid after\r
+          // handle_request returns.\r
+          conn->path_info = p + 1;\r
+          memmove(p + 2, p + 1, strlen(p + 1) + 1);  // +1 is for trailing \0\r
+          p[1] = '/';\r
+          break;\r
+        } else {\r
+          *p = '/';\r
+        }\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+// Check whether full request is buffered. Return:\r
+//   -1  if request is malformed\r
+//    0  if request is not yet fully buffered\r
+//   >0  actual request length, including last \r\n\r\n\r
+static int get_request_len(const char *buf, int buflen) {\r
+  const char *s, *e;\r
+  int len = 0;\r
+\r
+  for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)\r
+    // Control characters are not allowed but >=128 is.\r
+    if (!isprint(* (const unsigned char *) s) && *s != '\r' &&\r
+        *s != '\n' && * (const unsigned char *) s < 128) {\r
+      len = -1;\r
+      break;  // [i_a] abort scan as soon as one malformed character is found;\r
+              // don't let subsequent \r\n\r\n win us over anyhow\r
+    } else if (s[0] == '\n' && s[1] == '\n') {\r
+      len = (int) (s - buf) + 2;\r
+    } else if (s[0] == '\n' && &s[1] < e &&\r
+        s[1] == '\r' && s[2] == '\n') {\r
+      len = (int) (s - buf) + 3;\r
+    }\r
+\r
+  return len;\r
+}\r
+\r
+// Convert month to the month number. Return -1 on error, or month number\r
+static int get_month_index(const char *s) {\r
+  size_t i;\r
+\r
+  for (i = 0; i < ARRAY_SIZE(month_names); i++)\r
+    if (!strcmp(s, month_names[i]))\r
+      return (int) i;\r
+\r
+  return -1;\r
+}\r
+\r
+static int num_leap_years(int year) {\r
+  return year / 4 - year / 100 + year / 400;\r
+}\r
+\r
+// Parse UTC date-time string, and return the corresponding time_t value.\r
+static time_t parse_date_string(const char *datetime) {\r
+  static const unsigned short days_before_month[] = {\r
+    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334\r
+  };\r
+  char month_str[32];\r
+  int second, minute, hour, day, month, year, leap_days, days;\r
+  time_t result = (time_t) 0;\r
+\r
+  if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",\r
+               &day, month_str, &year, &hour, &minute, &second) == 6) ||\r
+       (sscanf(datetime, "%d %3s %d %d:%d:%d",\r
+               &day, month_str, &year, &hour, &minute, &second) == 6) ||\r
+       (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",\r
+               &day, month_str, &year, &hour, &minute, &second) == 6) ||\r
+       (sscanf(datetime, "%d-%3s-%d %d:%d:%d",\r
+               &day, month_str, &year, &hour, &minute, &second) == 6)) &&\r
+      year > 1970 &&\r
+      (month = get_month_index(month_str)) != -1) {\r
+    leap_days = num_leap_years(year) - num_leap_years(1970);\r
+    year -= 1970;\r
+    days = year * 365 + days_before_month[month] + (day - 1) + leap_days;\r
+    result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;\r
+  }\r
+\r
+  return result;\r
+}\r
+\r
+// Protect against directory disclosure attack by removing '..',\r
+// excessive '/' and '\' characters\r
+static void remove_double_dots_and_double_slashes(char *s) {\r
+  char *p = s;\r
+\r
+  while (*s != '\0') {\r
+    *p++ = *s++;\r
+    if (s[-1] == '/' || s[-1] == '\\') {\r
+      // Skip all following slashes, backslashes and double-dots\r
+      while (s[0] != '\0') {\r
+        if (s[0] == '/' || s[0] == '\\') {\r
+          s++;\r
+        } else if (s[0] == '.' && s[1] == '.') {\r
+          s += 2;\r
+        } else {\r
+          break;\r
+        }\r
+      }\r
+    }\r
+  }\r
+  *p = '\0';\r
+}\r
+\r
+static const struct {\r
+  const char *extension;\r
+  size_t ext_len;\r
+  const char *mime_type;\r
+} builtin_mime_types[] = {\r
+  {".html", 5, "text/html"},\r
+  {".htm", 4, "text/html"},\r
+  {".shtm", 5, "text/html"},\r
+  {".shtml", 6, "text/html"},\r
+  {".css", 4, "text/css"},\r
+  {".js",  3, "application/x-javascript"},\r
+  {".ico", 4, "image/x-icon"},\r
+  {".gif", 4, "image/gif"},\r
+  {".jpg", 4, "image/jpeg"},\r
+  {".jpeg", 5, "image/jpeg"},\r
+  {".png", 4, "image/png"},\r
+  {".svg", 4, "image/svg+xml"},\r
+  {".txt", 4, "text/plain"},\r
+  {".torrent", 8, "application/x-bittorrent"},\r
+  {".wav", 4, "audio/x-wav"},\r
+  {".mp3", 4, "audio/x-mp3"},\r
+  {".mid", 4, "audio/mid"},\r
+  {".m3u", 4, "audio/x-mpegurl"},\r
+  {".ogg", 4, "audio/ogg"},\r
+  {".ram", 4, "audio/x-pn-realaudio"},\r
+  {".xml", 4, "text/xml"},\r
+  {".json",  5, "text/json"},\r
+  {".xslt", 5, "application/xml"},\r
+  {".xsl", 4, "application/xml"},\r
+  {".ra",  3, "audio/x-pn-realaudio"},\r
+  {".doc", 4, "application/msword"},\r
+  {".exe", 4, "application/octet-stream"},\r
+  {".zip", 4, "application/x-zip-compressed"},\r
+  {".xls", 4, "application/excel"},\r
+  {".tgz", 4, "application/x-tar-gz"},\r
+  {".tar", 4, "application/x-tar"},\r
+  {".gz",  3, "application/x-gunzip"},\r
+  {".arj", 4, "application/x-arj-compressed"},\r
+  {".rar", 4, "application/x-arj-compressed"},\r
+  {".rtf", 4, "application/rtf"},\r
+  {".pdf", 4, "application/pdf"},\r
+  {".swf", 4, "application/x-shockwave-flash"},\r
+  {".mpg", 4, "video/mpeg"},\r
+  {".webm", 5, "video/webm"},\r
+  {".mpeg", 5, "video/mpeg"},\r
+  {".mov", 4, "video/quicktime"},\r
+  {".mp4", 4, "video/mp4"},\r
+  {".m4v", 4, "video/x-m4v"},\r
+  {".asf", 4, "video/x-ms-asf"},\r
+  {".avi", 4, "video/x-msvideo"},\r
+  {".bmp", 4, "image/bmp"},\r
+  {".ttf", 4, "application/x-font-ttf"},\r
+  {NULL,  0, NULL}\r
+};\r
+\r
+const char *mg_get_builtin_mime_type(const char *path) {\r
+  const char *ext;\r
+  size_t i, path_len;\r
+\r
+  path_len = strlen(path);\r
+\r
+  for (i = 0; builtin_mime_types[i].extension != NULL; i++) {\r
+    ext = path + (path_len - builtin_mime_types[i].ext_len);\r
+    if (path_len > builtin_mime_types[i].ext_len &&\r
+        mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {\r
+      return builtin_mime_types[i].mime_type;\r
+    }\r
+  }\r
+\r
+  return "text/plain";\r
+}\r
+\r
+// Look at the "path" extension and figure what mime type it has.\r
+// Store mime type in the vector.\r
+static void get_mime_type(struct mg_context *ctx, const char *path,\r
+                          struct vec *vec) {\r
+  struct vec ext_vec, mime_vec;\r
+  const char *list, *ext;\r
+  size_t path_len;\r
+\r
+  path_len = strlen(path);\r
+\r
+  // Scan user-defined mime types first, in case user wants to\r
+  // override default mime types.\r
+  list = ctx->config[EXTRA_MIME_TYPES];\r
+  while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {\r
+    // ext now points to the path suffix\r
+    ext = path + path_len - ext_vec.len;\r
+    if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {\r
+      *vec = mime_vec;\r
+      return;\r
+    }\r
+  }\r
+\r
+  vec->ptr = mg_get_builtin_mime_type(path);\r
+  vec->len = strlen(vec->ptr);\r
+}\r
+\r
+static int is_big_endian(void) {\r
+  static const int n = 1;\r
+  return ((char *) &n)[0] == 0;\r
+}\r
+\r
+#ifndef HAVE_MD5\r
+typedef struct MD5Context {\r
+  uint32_t buf[4];\r
+  uint32_t bits[2];\r
+  unsigned char in[64];\r
+} MD5_CTX;\r
+\r
+static void byteReverse(unsigned char *buf, unsigned longs) {\r
+  uint32_t t;\r
+\r
+  // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN\r
+  if (is_big_endian()) {\r
+    do {\r
+      t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |\r
+        ((unsigned) buf[1] << 8 | buf[0]);\r
+      * (uint32_t *) buf = t;\r
+      buf += 4;\r
+    } while (--longs);\r
+  }\r
+}\r
+\r
+#define F1(x, y, z) (z ^ (x & (y ^ z)))\r
+#define F2(x, y, z) F1(z, x, y)\r
+#define F3(x, y, z) (x ^ y ^ z)\r
+#define F4(x, y, z) (y ^ (x | ~z))\r
+\r
+#define MD5STEP(f, w, x, y, z, data, s) \\r
+  ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )\r
+\r
+// Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious\r
+// initialization constants.\r
+static void MD5Init(MD5_CTX *ctx) {\r
+  ctx->buf[0] = 0x67452301;\r
+  ctx->buf[1] = 0xefcdab89;\r
+  ctx->buf[2] = 0x98badcfe;\r
+  ctx->buf[3] = 0x10325476;\r
+\r
+  ctx->bits[0] = 0;\r
+  ctx->bits[1] = 0;\r
+}\r
+\r
+static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {\r
+  register uint32_t a, b, c, d;\r
+\r
+  a = buf[0];\r
+  b = buf[1];\r
+  c = buf[2];\r
+  d = buf[3];\r
+\r
+  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);\r
+  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);\r
+  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);\r
+  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);\r
+  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);\r
+  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);\r
+  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);\r
+  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);\r
+  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);\r
+  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);\r
+  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);\r
+  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);\r
+  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);\r
+  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);\r
+  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);\r
+  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);\r
+\r
+  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);\r
+  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);\r
+  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);\r
+  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);\r
+  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);\r
+  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);\r
+  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);\r
+  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);\r
+  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);\r
+  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);\r
+  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);\r
+  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);\r
+  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);\r
+  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);\r
+  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);\r
+  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);\r
+\r
+  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);\r
+  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);\r
+  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);\r
+  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);\r
+  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);\r
+  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);\r
+  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);\r
+  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);\r
+  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);\r
+  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);\r
+  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);\r
+  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);\r
+  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);\r
+  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);\r
+  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);\r
+  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);\r
+\r
+  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);\r
+  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);\r
+  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);\r
+  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);\r
+  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);\r
+  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);\r
+  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);\r
+  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);\r
+  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);\r
+  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);\r
+  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);\r
+  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);\r
+  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);\r
+  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);\r
+  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);\r
+  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);\r
+\r
+  buf[0] += a;\r
+  buf[1] += b;\r
+  buf[2] += c;\r
+  buf[3] += d;\r
+}\r
+\r
+static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {\r
+  uint32_t t;\r
+\r
+  t = ctx->bits[0];\r
+  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)\r
+    ctx->bits[1]++;\r
+  ctx->bits[1] += len >> 29;\r
+\r
+  t = (t >> 3) & 0x3f;\r
+\r
+  if (t) {\r
+    unsigned char *p = (unsigned char *) ctx->in + t;\r
+\r
+    t = 64 - t;\r
+    if (len < t) {\r
+      memcpy(p, buf, len);\r
+      return;\r
+    }\r
+    memcpy(p, buf, t);\r
+    byteReverse(ctx->in, 16);\r
+    MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
+    buf += t;\r
+    len -= t;\r
+  }\r
+\r
+  while (len >= 64) {\r
+    memcpy(ctx->in, buf, 64);\r
+    byteReverse(ctx->in, 16);\r
+    MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
+    buf += 64;\r
+    len -= 64;\r
+  }\r
+\r
+  memcpy(ctx->in, buf, len);\r
+}\r
+\r
+static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {\r
+  unsigned count;\r
+  unsigned char *p;\r
+  uint32_t *a;\r
+\r
+  count = (ctx->bits[0] >> 3) & 0x3F;\r
+\r
+  p = ctx->in + count;\r
+  *p++ = 0x80;\r
+  count = 64 - 1 - count;\r
+  if (count < 8) {\r
+    memset(p, 0, count);\r
+    byteReverse(ctx->in, 16);\r
+    MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
+    memset(ctx->in, 0, 56);\r
+  } else {\r
+    memset(p, 0, count - 8);\r
+  }\r
+  byteReverse(ctx->in, 14);\r
+\r
+  a = (uint32_t *)ctx->in;\r
+  a[14] = ctx->bits[0];\r
+  a[15] = ctx->bits[1];\r
+\r
+  MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
+  byteReverse((unsigned char *) ctx->buf, 4);\r
+  memcpy(digest, ctx->buf, 16);\r
+  memset((char *) ctx, 0, sizeof(*ctx));\r
+}\r
+#endif // !HAVE_MD5\r
+\r
+// Stringify binary data. Output buffer must be twice as big as input,\r
+// because each byte takes 2 bytes in string representation\r
+static void bin2str(char *to, const unsigned char *p, size_t len) {\r
+  static const char *hex = "0123456789abcdef";\r
+\r
+  for (; len--; p++) {\r
+    *to++ = hex[p[0] >> 4];\r
+    *to++ = hex[p[0] & 0x0f];\r
+  }\r
+  *to = '\0';\r
+}\r
+\r
+// Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.\r
+char *mg_md5(char buf[33], ...) {\r
+  unsigned char hash[16];\r
+  const char *p;\r
+  va_list ap;\r
+  MD5_CTX ctx;\r
+\r
+  MD5Init(&ctx);\r
+\r
+  va_start(ap, buf);\r
+  while ((p = va_arg(ap, const char *)) != NULL) {\r
+    MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));\r
+  }\r
+  va_end(ap);\r
+\r
+  MD5Final(hash, &ctx);\r
+  bin2str(buf, hash, sizeof(hash));\r
+  return buf;\r
+}\r
+\r
+// Check the user's password, return 1 if OK\r
+static int check_password(const char *method, const char *ha1, const char *uri,\r
+                          const char *nonce, const char *nc, const char *cnonce,\r
+                          const char *qop, const char *response) {\r
+  char ha2[32 + 1], expected_response[32 + 1];\r
+\r
+  // Some of the parameters may be NULL\r
+  if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||\r
+      qop == NULL || response == NULL) {\r
+    return 0;\r
+  }\r
+\r
+  // NOTE(lsm): due to a bug in MSIE, we do not compare the URI\r
+  // TODO(lsm): check for authentication timeout\r
+  if (// strcmp(dig->uri, c->ouri) != 0 ||\r
+      strlen(response) != 32\r
+      // || now - strtoul(dig->nonce, NULL, 10) > 3600\r
+      ) {\r
+    return 0;\r
+  }\r
+\r
+  mg_md5(ha2, method, ":", uri, NULL);\r
+  mg_md5(expected_response, ha1, ":", nonce, ":", nc,\r
+      ":", cnonce, ":", qop, ":", ha2, NULL);\r
+\r
+  return mg_strcasecmp(response, expected_response) == 0;\r
+}\r
+\r
+// Use the global passwords file, if specified by auth_gpass option,\r
+// or search for .htpasswd in the requested directory.\r
+static void open_auth_file(struct mg_connection *conn, const char *path,\r
+                           struct file *filep) {\r
+  char name[PATH_MAX];\r
+  const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+\r
+  if (gpass != NULL) {\r
+    // Use global passwords file\r
+    if (!mg_fopen(conn, gpass, "r", filep)) {\r
+      cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));\r
+    }\r
+    // Important: using local struct file to test path for is_directory flag.\r
+    // If filep is used, mg_stat() makes it appear as if auth file was opened.\r
+  } else if (mg_stat(conn, path, &file) && file.is_directory) {\r
+    mg_snprintf(conn, name, sizeof(name), "%s%c%s",\r
+                path, '/', PASSWORDS_FILE_NAME);\r
+    mg_fopen(conn, name, "r", filep);\r
+  } else {\r
+     // Try to find .htpasswd in requested directory.\r
+    for (p = path, e = p + strlen(p) - 1; e > p; e--)\r
+      if (e[0] == '/')\r
+        break;\r
+    mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",\r
+                (int) (e - p), p, '/', PASSWORDS_FILE_NAME);\r
+    mg_fopen(conn, name, "r", filep);\r
+  }\r
+}\r
+\r
+// Parsed Authorization header\r
+struct ah {\r
+  char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;\r
+};\r
+\r
+// Return 1 on success. Always initializes the ah structure.\r
+static int parse_auth_header(struct mg_connection *conn, char *buf,\r
+                             size_t buf_size, struct ah *ah) {\r
+  char *name, *value, *s;\r
+  const char *auth_header;\r
+\r
+  (void) memset(ah, 0, sizeof(*ah));\r
+  if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||\r
+      mg_strncasecmp(auth_header, "Digest ", 7) != 0) {\r
+    return 0;\r
+  }\r
+\r
+  // Make modifiable copy of the auth header\r
+  (void) mg_strlcpy(buf, auth_header + 7, buf_size);\r
+  s = buf;\r
+\r
+  // Parse authorization header\r
+  for (;;) {\r
+    // Gobble initial spaces\r
+    while (isspace(* (unsigned char *) s)) {\r
+      s++;\r
+    }\r
+    name = skip_quoted(&s, "=", " ", 0);\r
+    // Value is either quote-delimited, or ends at first comma or space.\r
+    if (s[0] == '\"') {\r
+      s++;\r
+      value = skip_quoted(&s, "\"", " ", '\\');\r
+      if (s[0] == ',') {\r
+        s++;\r
+      }\r
+    } else {\r
+      value = skip_quoted(&s, ", ", " ", 0);  // IE uses commas, FF uses spaces\r
+    }\r
+    if (*name == '\0') {\r
+      break;\r
+    }\r
+\r
+    if (!strcmp(name, "username")) {\r
+      ah->user = value;\r
+    } else if (!strcmp(name, "cnonce")) {\r
+      ah->cnonce = value;\r
+    } else if (!strcmp(name, "response")) {\r
+      ah->response = value;\r
+    } else if (!strcmp(name, "uri")) {\r
+      ah->uri = value;\r
+    } else if (!strcmp(name, "qop")) {\r
+      ah->qop = value;\r
+    } else if (!strcmp(name, "nc")) {\r
+      ah->nc = value;\r
+    } else if (!strcmp(name, "nonce")) {\r
+      ah->nonce = value;\r
+    }\r
+  }\r
+\r
+  // CGI needs it as REMOTE_USER\r
+  if (ah->user != NULL) {\r
+    conn->request_info.remote_user = mg_strdup(ah->user);\r
+  } else {\r
+    return 0;\r
+  }\r
+\r
+  return 1;\r
+}\r
+\r
+static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p) {\r
+  char *eof;\r
+  size_t len;\r
+\r
+  if (filep->membuf != NULL && *p != NULL) {\r
+    eof = memchr(*p, '\n', &filep->membuf[filep->size] - *p);\r
+    len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);\r
+    memcpy(buf, *p, len);\r
+    buf[len] = '\0';\r
+    *p = eof;\r
+    return eof;\r
+  } else if (filep->fp != NULL) {\r
+    return fgets(buf, size, filep->fp);\r
+  } else {\r
+    return NULL;\r
+  }\r
+}\r
+\r
+// Authorize against the opened passwords file. Return 1 if authorized.\r
+static int authorize(struct mg_connection *conn, struct file *filep) {\r
+  struct ah ah;\r
+  char line[256], f_user[256], ha1[256], f_domain[256], buf[MG_BUF_LEN], *p;\r
+\r
+  if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {\r
+    return 0;\r
+  }\r
+\r
+  // Loop over passwords file\r
+  p = (char *) filep->membuf;\r
+  while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {\r
+    if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {\r
+      continue;\r
+    }\r
+\r
+    if (!strcmp(ah.user, f_user) &&\r
+        !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))\r
+      return check_password(conn->request_info.request_method, ha1, ah.uri,\r
+                            ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);\r
+  }\r
+\r
+  return 0;\r
+}\r
+\r
+// Return 1 if request is authorised, 0 otherwise.\r
+static int check_authorization(struct mg_connection *conn, const char *path) {\r
+  char fname[PATH_MAX];\r
+  struct vec uri_vec, filename_vec;\r
+  const char *list;\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  int authorized = 1;\r
+\r
+  list = conn->ctx->config[PROTECT_URI];\r
+  while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {\r
+    if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {\r
+      mg_snprintf(conn, fname, sizeof(fname), "%.*s",\r
+                  (int) filename_vec.len, filename_vec.ptr);\r
+      if (!mg_fopen(conn, fname, "r", &file)) {\r
+        cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));\r
+      }\r
+      break;\r
+    }\r
+  }\r
+\r
+  if (!is_file_opened(&file)) {\r
+    open_auth_file(conn, path, &file);\r
+  }\r
+\r
+  if (is_file_opened(&file)) {\r
+    authorized = authorize(conn, &file);\r
+    mg_fclose(&file);\r
+  }\r
+\r
+  return authorized;\r
+}\r
+\r
+static void send_authorization_request(struct mg_connection *conn) {\r
+  conn->status_code = 401;\r
+  mg_printf(conn,\r
+            "HTTP/1.1 401 Unauthorized\r\n"\r
+            "Content-Length: 0\r\n"\r
+            "WWW-Authenticate: Digest qop=\"auth\", "\r
+            "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",\r
+            conn->ctx->config[AUTHENTICATION_DOMAIN],\r
+            (unsigned long) time(NULL));\r
+}\r
+\r
+static int is_authorized_for_put(struct mg_connection *conn) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];\r
+  int ret = 0;\r
+\r
+  if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {\r
+    ret = authorize(conn, &file);\r
+    mg_fclose(&file);\r
+  }\r
+\r
+  return ret;\r
+}\r
+\r
+int mg_modify_passwords_file(const char *fname, const char *domain,\r
+                             const char *user, const char *pass) {\r
+  int found;\r
+  char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];\r
+  FILE *fp, *fp2;\r
+\r
+  found = 0;\r
+  fp = fp2 = NULL;\r
+\r
+  // Regard empty password as no password - remove user record.\r
+  if (pass != NULL && pass[0] == '\0') {\r
+    pass = NULL;\r
+  }\r
+\r
+  (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);\r
+\r
+  // Create the file if does not exist\r
+  if ((fp = fopen(fname, "a+")) != NULL) {\r
+    (void) fclose(fp);\r
+  }\r
+\r
+  // Open the given file and temporary file\r
+  if ((fp = fopen(fname, "r")) == NULL) {\r
+    return 0;\r
+  } else if ((fp2 = fopen(tmp, "w+")) == NULL) {\r
+    fclose(fp);\r
+    return 0;\r
+  }\r
+\r
+  // Copy the stuff to temporary file\r
+  while (fgets(line, sizeof(line), fp) != NULL) {\r
+    if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {\r
+      continue;\r
+    }\r
+\r
+    if (!strcmp(u, user) && !strcmp(d, domain)) {\r
+      found++;\r
+      if (pass != NULL) {\r
+        mg_md5(ha1, user, ":", domain, ":", pass, NULL);\r
+        fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);\r
+      }\r
+    } else {\r
+      fprintf(fp2, "%s", line);\r
+    }\r
+  }\r
+\r
+  // If new user, just add it\r
+  if (!found && pass != NULL) {\r
+    mg_md5(ha1, user, ":", domain, ":", pass, NULL);\r
+    fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);\r
+  }\r
+\r
+  // Close files\r
+  fclose(fp);\r
+  fclose(fp2);\r
+\r
+  // Put the temp file in place of real file\r
+  remove(fname);\r
+  rename(tmp, fname);\r
+\r
+  return 1;\r
+}\r
+\r
+static int conn2(const char *host, int port, int use_ssl,\r
+                 char *ebuf, size_t ebuf_len) {\r
+  struct sockaddr_in sin;\r
+  struct hostent *he;\r
+  SOCKET sock = INVALID_SOCKET;\r
+\r
+  if (host == NULL) {\r
+    snprintf(ebuf, ebuf_len, "%s", "NULL host");\r
+  } else if (use_ssl && SSLv23_client_method == NULL) {\r
+    snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");\r
+    // TODO(lsm): use something threadsafe instead of gethostbyname()\r
+  } else if ((he = gethostbyname(host)) == NULL) {\r
+    snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO));\r
+  } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {\r
+    snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));\r
+  } else {\r
+    sin.sin_family = AF_INET;\r
+    sin.sin_port = htons((uint16_t) port);\r
+    sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];\r
+    if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {\r
+      snprintf(ebuf, ebuf_len, "connect(%s:%d): %s",\r
+               host, port, strerror(ERRNO));\r
+      closesocket(sock);\r
+      sock = INVALID_SOCKET;\r
+    }\r
+  }\r
+  return sock;\r
+}\r
+\r
+\r
+\r
+void mg_url_encode(const char *src, char *dst, size_t dst_len) {\r
+  static const char *dont_escape = "._-$,;~()";\r
+  static const char *hex = "0123456789abcdef";\r
+  const char *end = dst + dst_len - 1;\r
+\r
+  for (; *src != '\0' && dst < end; src++, dst++) {\r
+    if (isalnum(*(const unsigned char *) src) ||\r
+        strchr(dont_escape, * (const unsigned char *) src) != NULL) {\r
+      *dst = *src;\r
+    } else if (dst + 2 < end) {\r
+      dst[0] = '%';\r
+      dst[1] = hex[(* (const unsigned char *) src) >> 4];\r
+      dst[2] = hex[(* (const unsigned char *) src) & 0xf];\r
+      dst += 2;\r
+    }\r
+  }\r
+\r
+  *dst = '\0';\r
+}\r
+\r
+static void print_dir_entry(struct de *de) {\r
+  char size[64], mod[64], href[PATH_MAX];\r
+\r
+  if (de->file.is_directory) {\r
+    mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");\r
+  } else {\r
+     // We use (signed) cast below because MSVC 6 compiler cannot\r
+     // convert unsigned __int64 to double. Sigh.\r
+    if (de->file.size < 1024) {\r
+      mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size);\r
+    } else if (de->file.size < 0x100000) {\r
+      mg_snprintf(de->conn, size, sizeof(size),\r
+                  "%.1fk", (double) de->file.size / 1024.0);\r
+    } else if (de->file.size < 0x40000000) {\r
+      mg_snprintf(de->conn, size, sizeof(size),\r
+                  "%.1fM", (double) de->file.size / 1048576);\r
+    } else {\r
+      mg_snprintf(de->conn, size, sizeof(size),\r
+                  "%.1fG", (double) de->file.size / 1073741824);\r
+    }\r
+  }\r
+  strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M",\r
+           localtime(&de->file.modification_time));\r
+  mg_url_encode(de->file_name, href, sizeof(href));\r
+  de->conn->num_bytes_sent += mg_printf(de->conn,\r
+      "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"\r
+      "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",\r
+      de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",\r
+      de->file_name, de->file.is_directory ? "/" : "", mod, size);\r
+}\r
+\r
+// This function is called from send_directory() and used for\r
+// sorting directory entries by size, or name, or modification time.\r
+// On windows, __cdecl specification is needed in case if project is built\r
+// with __stdcall convention. qsort always requires __cdels callback.\r
+static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {\r
+  const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;\r
+  const char *query_string = a->conn->request_info.query_string;\r
+  int cmp_result = 0;\r
+\r
+  if (query_string == NULL) {\r
+    query_string = "na";\r
+  }\r
+\r
+  if (a->file.is_directory && !b->file.is_directory) {\r
+    return -1;  // Always put directories on top\r
+  } else if (!a->file.is_directory && b->file.is_directory) {\r
+    return 1;   // Always put directories on top\r
+  } else if (*query_string == 'n') {\r
+    cmp_result = strcmp(a->file_name, b->file_name);\r
+  } else if (*query_string == 's') {\r
+    cmp_result = a->file.size == b->file.size ? 0 :\r
+      a->file.size > b->file.size ? 1 : -1;\r
+  } else if (*query_string == 'd') {\r
+    cmp_result = a->file.modification_time == b->file.modification_time ? 0 :\r
+      a->file.modification_time > b->file.modification_time ? 1 : -1;\r
+  }\r
+\r
+  return query_string[1] == 'd' ? -cmp_result : cmp_result;\r
+}\r
+\r
+static int must_hide_file(struct mg_connection *conn, const char *path) {\r
+  const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";\r
+  const char *pattern = conn->ctx->config[HIDE_FILES];\r
+  return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||\r
+    (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0);\r
+}\r
+\r
+static int scan_directory(struct mg_connection *conn, const char *dir,\r
+                          void *data, void (*cb)(struct de *, void *)) {\r
+  char path[PATH_MAX];\r
+  struct dirent *dp;\r
+  DIR *dirp;\r
+  struct de de;\r
+\r
+  if ((dirp = opendir(dir)) == NULL) {\r
+    return 0;\r
+  } else {\r
+    de.conn = conn;\r
+\r
+    while ((dp = readdir(dirp)) != NULL) {\r
+      // Do not show current dir and hidden files\r
+      if (!strcmp(dp->d_name, ".") ||\r
+          !strcmp(dp->d_name, "..") ||\r
+          must_hide_file(conn, dp->d_name)) {\r
+        continue;\r
+      }\r
+\r
+      mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);\r
+\r
+      // If we don't memset stat structure to zero, mtime will have\r
+      // garbage and strftime() will segfault later on in\r
+      // print_dir_entry(). memset is required only if mg_stat()\r
+      // fails. For more details, see\r
+      // http://code.google.com/p/mongoose/issues/detail?id=79\r
+      memset(&de.file, 0, sizeof(de.file));\r
+      mg_stat(conn, path, &de.file);\r
+\r
+      de.file_name = dp->d_name;\r
+      cb(&de, data);\r
+    }\r
+    (void) closedir(dirp);\r
+  }\r
+  return 1;\r
+}\r
+\r
+struct dir_scan_data {\r
+  struct de *entries;\r
+  int num_entries;\r
+  int arr_size;\r
+};\r
+\r
+// Behaves like realloc(), but frees original pointer on failure\r
+static void *realloc2(void *ptr, size_t size) {\r
+  void *new_ptr = realloc(ptr, size);\r
+  if (new_ptr == NULL) {\r
+    free(ptr);\r
+  }\r
+  return new_ptr;\r
+}\r
+\r
+static void dir_scan_callback(struct de *de, void *data) {\r
+  struct dir_scan_data *dsd = (struct dir_scan_data *) data;\r
+\r
+  if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {\r
+    dsd->arr_size *= 2;\r
+    dsd->entries = (struct de *) realloc2(dsd->entries, dsd->arr_size *\r
+                                          sizeof(dsd->entries[0]));\r
+  }\r
+  if (dsd->entries == NULL) {\r
+    // TODO(lsm): propagate an error to the caller\r
+    dsd->num_entries = 0;\r
+  } else {\r
+    dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);\r
+    dsd->entries[dsd->num_entries].file = de->file;\r
+    dsd->entries[dsd->num_entries].conn = de->conn;\r
+    dsd->num_entries++;\r
+  }\r
+}\r
+\r
+static void handle_directory_request(struct mg_connection *conn,\r
+                                     const char *dir) {\r
+  int i, sort_direction;\r
+  struct dir_scan_data data = { NULL, 0, 128 };\r
+\r
+  if (!scan_directory(conn, dir, &data, dir_scan_callback)) {\r
+    send_http_error(conn, 500, "Cannot open directory",\r
+                    "Error: opendir(%s): %s", dir, strerror(ERRNO));\r
+    return;\r
+  }\r
+\r
+  sort_direction = conn->request_info.query_string != NULL &&\r
+    conn->request_info.query_string[1] == 'd' ? 'a' : 'd';\r
+\r
+  conn->must_close = 1;\r
+  mg_printf(conn, "%s",\r
+            "HTTP/1.1 200 OK\r\n"\r
+            "Connection: close\r\n"\r
+            "Content-Type: text/html; charset=utf-8\r\n\r\n");\r
+\r
+  conn->num_bytes_sent += mg_printf(conn,\r
+      "<html><head><title>Index of %s</title>"\r
+      "<style>th {text-align: left;}</style></head>"\r
+      "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"\r
+      "<tr><th><a href=\"?n%c\">Name</a></th>"\r
+      "<th><a href=\"?d%c\">Modified</a></th>"\r
+      "<th><a href=\"?s%c\">Size</a></th></tr>"\r
+      "<tr><td colspan=\"3\"><hr></td></tr>",\r
+      conn->request_info.uri, conn->request_info.uri,\r
+      sort_direction, sort_direction, sort_direction);\r
+\r
+  // Print first entry - link to a parent directory\r
+  conn->num_bytes_sent += mg_printf(conn,\r
+      "<tr><td><a href=\"%s%s\">%s</a></td>"\r
+      "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",\r
+      conn->request_info.uri, "..", "Parent directory", "-", "-");\r
+\r
+  // Sort and print directory entries\r
+  qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),\r
+        compare_dir_entries);\r
+  for (i = 0; i < data.num_entries; i++) {\r
+    print_dir_entry(&data.entries[i]);\r
+    free(data.entries[i].file_name);\r
+  }\r
+  free(data.entries);\r
+\r
+  conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");\r
+  conn->status_code = 200;\r
+}\r
+\r
+// Send len bytes from the opened file to the client.\r
+static void send_file_data(struct mg_connection *conn, struct file *filep,\r
+                           int64_t offset, int64_t len) {\r
+  char buf[MG_BUF_LEN];\r
+  int to_read, num_read, num_written;\r
+\r
+  // Sanity check the offset\r
+  offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset;\r
+\r
+  if (len > 0 && filep->membuf != NULL && filep->size > 0) {\r
+    if (len > filep->size - offset) {\r
+      len = filep->size - offset;\r
+    }\r
+    mg_write(conn, filep->membuf + offset, (size_t) len);\r
+  } else if (len > 0 && filep->fp != NULL) {\r
+    fseeko(filep->fp, offset, SEEK_SET);\r
+    while (len > 0) {\r
+      // Calculate how much to read from the file in the buffer\r
+      to_read = sizeof(buf);\r
+      if ((int64_t) to_read > len) {\r
+        to_read = (int) len;\r
+      }\r
+\r
+      // Read from file, exit the loop on error\r
+      if ((num_read = fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) {\r
+        break;\r
+      }\r
+\r
+      // Send read bytes to the client, exit the loop on error\r
+      if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) {\r
+        break;\r
+      }\r
+\r
+      // Both read and were successful, adjust counters\r
+      conn->num_bytes_sent += num_written;\r
+      len -= num_written;\r
+    }\r
+  }\r
+}\r
+\r
+static int parse_range_header(const char *header, int64_t *a, int64_t *b) {\r
+  return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);\r
+}\r
+\r
+static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {\r
+  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));\r
+}\r
+\r
+static void construct_etag(char *buf, size_t buf_len,\r
+                           const struct file *filep) {\r
+  snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",\r
+           (unsigned long) filep->modification_time, filep->size);\r
+}\r
+\r
+static void fclose_on_exec(struct file *filep) {\r
+  if (filep != NULL && filep->fp != NULL) {\r
+#ifndef _WIN32\r
+    fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC);\r
+#endif\r
+  }\r
+}\r
+\r
+static void handle_file_request(struct mg_connection *conn, const char *path,\r
+                                struct file *filep) {\r
+  char date[64], lm[64], etag[64], range[64];\r
+  const char *msg = "OK", *hdr;\r
+  time_t curtime = time(NULL);\r
+  int64_t cl, r1, r2;\r
+  struct vec mime_vec;\r
+  int n;\r
+\r
+  get_mime_type(conn->ctx, path, &mime_vec);\r
+  cl = filep->size;\r
+  conn->status_code = 200;\r
+  range[0] = '\0';\r
+\r
+  if (!mg_fopen(conn, path, "rb", filep)) {\r
+    send_http_error(conn, 500, http_500_error,\r
+                    "fopen(%s): %s", path, strerror(ERRNO));\r
+    return;\r
+  }\r
+  fclose_on_exec(filep);\r
+\r
+  // If Range: header specified, act accordingly\r
+  r1 = r2 = 0;\r
+  hdr = mg_get_header(conn, "Range");\r
+  if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&\r
+      r1 >= 0 && r2 >= 0) {\r
+    conn->status_code = 206;\r
+    cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;\r
+    mg_snprintf(conn, range, sizeof(range),\r
+                "Content-Range: bytes "\r
+                "%" INT64_FMT "-%"\r
+                INT64_FMT "/%" INT64_FMT "\r\n",\r
+                r1, r1 + cl - 1, filep->size);\r
+    msg = "Partial Content";\r
+  }\r
+\r
+  // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to\r
+  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3\r
+  gmt_time_string(date, sizeof(date), &curtime);\r
+  gmt_time_string(lm, sizeof(lm), &filep->modification_time);\r
+  construct_etag(etag, sizeof(etag), filep);\r
+\r
+  (void) mg_printf(conn,\r
+      "HTTP/1.1 %d %s\r\n"\r
+      "Date: %s\r\n"\r
+      "Last-Modified: %s\r\n"\r
+      "Etag: %s\r\n"\r
+      "Content-Type: %.*s\r\n"\r
+      "Content-Length: %" INT64_FMT "\r\n"\r
+      "Connection: %s\r\n"\r
+      "Accept-Ranges: bytes\r\n"\r
+      "%s\r\n",\r
+      conn->status_code, msg, date, lm, etag, (int) mime_vec.len,\r
+      mime_vec.ptr, cl, suggest_connection_header(conn), range);\r
+\r
+  if (strcmp(conn->request_info.request_method, "HEAD") != 0) {\r
+    send_file_data(conn, filep, r1, cl);\r
+  }\r
+  mg_fclose(filep);\r
+}\r
+\r
+void mg_send_file(struct mg_connection *conn, const char *path) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  if (mg_stat(conn, path, &file)) {\r
+    handle_file_request(conn, path, &file);\r
+  } else {\r
+    send_http_error(conn, 404, "Not Found", "%s", "File not found");\r
+  }\r
+}\r
+\r
+\r
+// Parse HTTP headers from the given buffer, advance buffer to the point\r
+// where parsing stopped.\r
+static void parse_http_headers(char **buf, struct mg_request_info *ri) {\r
+  int i;\r
+\r
+  for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {\r
+    ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);\r
+    ri->http_headers[i].value = skip(buf, "\r\n");\r
+    if (ri->http_headers[i].name[0] == '\0')\r
+      break;\r
+    ri->num_headers = i + 1;\r
+  }\r
+}\r
+\r
+static int is_valid_http_method(const char *method) {\r
+  return !strcmp(method, "GET") || !strcmp(method, "POST") ||\r
+    !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||\r
+    !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||\r
+    !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND");\r
+}\r
+\r
+// Parse HTTP request, fill in mg_request_info structure.\r
+// This function modifies the buffer by NUL-terminating\r
+// HTTP request components, header names and header values.\r
+static int parse_http_message(char *buf, int len, struct mg_request_info *ri) {\r
+  int is_request, request_length = get_request_len(buf, len);\r
+  if (request_length > 0) {\r
+    // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port\r
+    ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;\r
+    ri->num_headers = 0;\r
+\r
+    buf[request_length - 1] = '\0';\r
+\r
+    // RFC says that all initial whitespaces should be ingored\r
+    while (*buf != '\0' && isspace(* (unsigned char *) buf)) {\r
+      buf++;\r
+    }\r
+    ri->request_method = skip(&buf, " ");\r
+    ri->uri = skip(&buf, " ");\r
+    ri->http_version = skip(&buf, "\r\n");\r
+    if (((is_request = is_valid_http_method(ri->request_method)) &&\r
+         memcmp(ri->http_version, "HTTP/", 5) != 0) ||\r
+        (!is_request && memcmp(ri->request_method, "HTTP/", 5)) != 0) {\r
+      request_length = -1;\r
+    } else {\r
+      if (is_request) {\r
+        ri->http_version += 5;\r
+      }\r
+      parse_http_headers(&buf, ri);\r
+    }\r
+  }\r
+  return request_length;\r
+}\r
+\r
+// Keep reading the input (either opened file descriptor fd, or socket sock,\r
+// or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the\r
+// buffer (which marks the end of HTTP request). Buffer buf may already\r
+// have some data. The length of the data is stored in nread.\r
+// Upon every read operation, increase nread by the number of bytes read.\r
+static int read_request(FILE *fp, struct mg_connection *conn,\r
+                        char *buf, int bufsiz, int *nread) {\r
+  int request_len, n = 0;\r
+\r
+  request_len = get_request_len(buf, *nread);\r
+  while (*nread < bufsiz && request_len == 0 &&\r
+         (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {\r
+    *nread += n;\r
+    assert(*nread <= bufsiz);\r
+    request_len = get_request_len(buf, *nread);\r
+  }\r
+\r
+  return request_len <= 0 && n <= 0 ? -1 : request_len;\r
+}\r
+\r
+// For given directory path, substitute it to valid index file.\r
+// Return 0 if index file has been found, -1 if not found.\r
+// If the file is found, it's stats is returned in stp.\r
+static int substitute_index_file(struct mg_connection *conn, char *path,\r
+                                 size_t path_len, struct file *filep) {\r
+  const char *list = conn->ctx->config[INDEX_FILES];\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  struct vec filename_vec;\r
+  size_t n = strlen(path);\r
+  int found = 0;\r
+\r
+  // The 'path' given to us points to the directory. Remove all trailing\r
+  // directory separator characters from the end of the path, and\r
+  // then append single directory separator character.\r
+  while (n > 0 && path[n - 1] == '/') {\r
+    n--;\r
+  }\r
+  path[n] = '/';\r
+\r
+  // Traverse index files list. For each entry, append it to the given\r
+  // path and see if the file exists. If it exists, break the loop\r
+  while ((list = next_option(list, &filename_vec, NULL)) != NULL) {\r
+\r
+    // Ignore too long entries that may overflow path buffer\r
+    if (filename_vec.len > path_len - (n + 2))\r
+      continue;\r
+\r
+    // Prepare full path to the index file\r
+    mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);\r
+\r
+    // Does it exist?\r
+    if (mg_stat(conn, path, &file)) {\r
+      // Yes it does, break the loop\r
+      *filep = file;\r
+      found = 1;\r
+      break;\r
+    }\r
+  }\r
+\r
+  // If no index file exists, restore directory path\r
+  if (!found) {\r
+    path[n] = '\0';\r
+  }\r
+\r
+  return found;\r
+}\r
+\r
+// Return True if we should reply 304 Not Modified.\r
+static int is_not_modified(const struct mg_connection *conn,\r
+                           const struct file *filep) {\r
+  char etag[64];\r
+  const char *ims = mg_get_header(conn, "If-Modified-Since");\r
+  const char *inm = mg_get_header(conn, "If-None-Match");\r
+  construct_etag(etag, sizeof(etag), filep);\r
+  return (inm != NULL && !mg_strcasecmp(etag, inm)) ||\r
+    (ims != NULL && filep->modification_time <= parse_date_string(ims));\r
+}\r
+\r
+static int forward_body_data(struct mg_connection *conn, FILE *fp,\r
+                             SOCKET sock, SSL *ssl) {\r
+  const char *expect, *body;\r
+  char buf[MG_BUF_LEN];\r
+  int to_read, nread, buffered_len, success = 0;\r
+\r
+  expect = mg_get_header(conn, "Expect");\r
+  assert(fp != NULL);\r
+\r
+  if (conn->content_len == -1) {\r
+    send_http_error(conn, 411, "Length Required", "%s", "");\r
+  } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {\r
+    send_http_error(conn, 417, "Expectation Failed", "%s", "");\r
+  } else {\r
+    if (expect != NULL) {\r
+      (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");\r
+    }\r
+\r
+    body = conn->buf + conn->request_len + conn->consumed_content;\r
+    buffered_len = &conn->buf[conn->data_len] - body;\r
+    assert(buffered_len >= 0);\r
+    assert(conn->consumed_content == 0);\r
+\r
+    if (buffered_len > 0) {\r
+      if ((int64_t) buffered_len > conn->content_len) {\r
+        buffered_len = (int) conn->content_len;\r
+      }\r
+      push(fp, sock, ssl, body, (int64_t) buffered_len);\r
+      conn->consumed_content += buffered_len;\r
+    }\r
+\r
+    nread = 0;\r
+    while (conn->consumed_content < conn->content_len) {\r
+      to_read = sizeof(buf);\r
+      if ((int64_t) to_read > conn->content_len - conn->consumed_content) {\r
+        to_read = (int) (conn->content_len - conn->consumed_content);\r
+      }\r
+      nread = pull(NULL, conn, buf, to_read);\r
+      if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {\r
+        break;\r
+      }\r
+      conn->consumed_content += nread;\r
+    }\r
+\r
+    if (conn->consumed_content == conn->content_len) {\r
+      success = nread >= 0;\r
+    }\r
+\r
+    // Each error code path in this function must send an error\r
+    if (!success) {\r
+      send_http_error(conn, 577, http_500_error, "%s", "");\r
+    }\r
+  }\r
+\r
+  return success;\r
+}\r
+\r
+#if !defined(NO_CGI)\r
+// This structure helps to create an environment for the spawned CGI program.\r
+// Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,\r
+// last element must be NULL.\r
+// However, on Windows there is a requirement that all these VARIABLE=VALUE\0\r
+// strings must reside in a contiguous buffer. The end of the buffer is\r
+// marked by two '\0' characters.\r
+// We satisfy both worlds: we create an envp array (which is vars), all\r
+// entries are actually pointers inside buf.\r
+struct cgi_env_block {\r
+  struct mg_connection *conn;\r
+  char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer\r
+  int len; // Space taken\r
+  char *vars[MAX_CGI_ENVIR_VARS]; // char **envp\r
+  int nvars; // Number of variables\r
+};\r
+\r
+static char *addenv(struct cgi_env_block *block,\r
+                    PRINTF_FORMAT_STRING(const char *fmt), ...)\r
+  PRINTF_ARGS(2, 3);\r
+\r
+// Append VARIABLE=VALUE\0 string to the buffer, and add a respective\r
+// pointer into the vars array.\r
+static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {\r
+  int n, space;\r
+  char *added;\r
+  va_list ap;\r
+\r
+  // Calculate how much space is left in the buffer\r
+  space = sizeof(block->buf) - block->len - 2;\r
+  assert(space >= 0);\r
+\r
+  // Make a pointer to the free space int the buffer\r
+  added = block->buf + block->len;\r
+\r
+  // Copy VARIABLE=VALUE\0 string into the free space\r
+  va_start(ap, fmt);\r
+  n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);\r
+  va_end(ap);\r
+\r
+  // Make sure we do not overflow buffer and the envp array\r
+  if (n > 0 && n + 1 < space &&\r
+      block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {\r
+    // Append a pointer to the added string into the envp array\r
+    block->vars[block->nvars++] = added;\r
+    // Bump up used length counter. Include \0 terminator\r
+    block->len += n + 1;\r
+  } else {\r
+    cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);\r
+  }\r
+\r
+  return added;\r
+}\r
+\r
+static void prepare_cgi_environment(struct mg_connection *conn,\r
+                                    const char *prog,\r
+                                    struct cgi_env_block *blk) {\r
+  const char *s, *slash;\r
+  struct vec var_vec;\r
+  char *p, src_addr[20];\r
+  int  i;\r
+\r
+  blk->len = blk->nvars = 0;\r
+  blk->conn = conn;\r
+  sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);\r
+\r
+  addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);\r
+  addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);\r
+  addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);\r
+\r
+  // Prepare the environment block\r
+  addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");\r
+  addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");\r
+  addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP\r
+\r
+  // TODO(lsm): fix this for IPv6 case\r
+  addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));\r
+\r
+  addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);\r
+  addenv(blk, "REMOTE_ADDR=%s", src_addr);\r
+  addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);\r
+  addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);\r
+\r
+  // SCRIPT_NAME\r
+  assert(conn->request_info.uri[0] == '/');\r
+  slash = strrchr(conn->request_info.uri, '/');\r
+  if ((s = strrchr(prog, '/')) == NULL)\r
+    s = prog;\r
+  addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),\r
+         conn->request_info.uri, s);\r
+\r
+  addenv(blk, "SCRIPT_FILENAME=%s", prog);\r
+  addenv(blk, "PATH_TRANSLATED=%s", prog);\r
+  addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");\r
+\r
+  if ((s = mg_get_header(conn, "Content-Type")) != NULL)\r
+    addenv(blk, "CONTENT_TYPE=%s", s);\r
+\r
+  if (conn->request_info.query_string != NULL)\r
+    addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);\r
+\r
+  if ((s = mg_get_header(conn, "Content-Length")) != NULL)\r
+    addenv(blk, "CONTENT_LENGTH=%s", s);\r
+\r
+  if ((s = getenv("PATH")) != NULL)\r
+    addenv(blk, "PATH=%s", s);\r
+\r
+  if (conn->path_info != NULL) {\r
+    addenv(blk, "PATH_INFO=%s", conn->path_info);\r
+  }\r
+\r
+#if defined(_WIN32)\r
+  if ((s = getenv("COMSPEC")) != NULL) {\r
+    addenv(blk, "COMSPEC=%s", s);\r
+  }\r
+  if ((s = getenv("SYSTEMROOT")) != NULL) {\r
+    addenv(blk, "SYSTEMROOT=%s", s);\r
+  }\r
+  if ((s = getenv("SystemDrive")) != NULL) {\r
+    addenv(blk, "SystemDrive=%s", s);\r
+  }\r
+  if ((s = getenv("ProgramFiles")) != NULL) {\r
+    addenv(blk, "ProgramFiles=%s", s);\r
+  }\r
+  if ((s = getenv("ProgramFiles(x86)")) != NULL) {\r
+    addenv(blk, "ProgramFiles(x86)=%s", s);\r
+  }\r
+#else\r
+  if ((s = getenv("LD_LIBRARY_PATH")) != NULL)\r
+    addenv(blk, "LD_LIBRARY_PATH=%s", s);\r
+#endif // _WIN32\r
+\r
+  if ((s = getenv("PERLLIB")) != NULL)\r
+    addenv(blk, "PERLLIB=%s", s);\r
+\r
+  if (conn->request_info.remote_user != NULL) {\r
+    addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);\r
+    addenv(blk, "%s", "AUTH_TYPE=Digest");\r
+  }\r
+\r
+  // Add all headers as HTTP_* variables\r
+  for (i = 0; i < conn->request_info.num_headers; i++) {\r
+    p = addenv(blk, "HTTP_%s=%s",\r
+        conn->request_info.http_headers[i].name,\r
+        conn->request_info.http_headers[i].value);\r
+\r
+    // Convert variable name into uppercase, and change - to _\r
+    for (; *p != '=' && *p != '\0'; p++) {\r
+      if (*p == '-')\r
+        *p = '_';\r
+      *p = (char) toupper(* (unsigned char *) p);\r
+    }\r
+  }\r
+\r
+  // Add user-specified variables\r
+  s = conn->ctx->config[CGI_ENVIRONMENT];\r
+  while ((s = next_option(s, &var_vec, NULL)) != NULL) {\r
+    addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);\r
+  }\r
+\r
+  blk->vars[blk->nvars++] = NULL;\r
+  blk->buf[blk->len++] = '\0';\r
+\r
+  assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));\r
+  assert(blk->len > 0);\r
+  assert(blk->len < (int) sizeof(blk->buf));\r
+}\r
+\r
+static void handle_cgi_request(struct mg_connection *conn, const char *prog) {\r
+  int headers_len, data_len, i, fd_stdin[2], fd_stdout[2];\r
+  const char *status, *status_text;\r
+  char buf[16384], *pbuf, dir[PATH_MAX], *p;\r
+  struct mg_request_info ri;\r
+  struct cgi_env_block blk;\r
+  FILE *in, *out;\r
+  struct file fout = STRUCT_FILE_INITIALIZER;\r
+  pid_t pid;\r
+\r
+  prepare_cgi_environment(conn, prog, &blk);\r
+\r
+  // CGI must be executed in its own directory. 'dir' must point to the\r
+  // directory containing executable program, 'p' must point to the\r
+  // executable program name relative to 'dir'.\r
+  (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);\r
+  if ((p = strrchr(dir, '/')) != NULL) {\r
+    *p++ = '\0';\r
+  } else {\r
+    dir[0] = '.', dir[1] = '\0';\r
+    p = (char *) prog;\r
+  }\r
+\r
+  pid = (pid_t) -1;\r
+  fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;\r
+  in = out = NULL;\r
+\r
+  if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {\r
+    send_http_error(conn, 500, http_500_error,\r
+        "Cannot create CGI pipe: %s", strerror(ERRNO));\r
+    goto done;\r
+  }\r
+\r
+  pid = spawn_process(conn, p, blk.buf, blk.vars, fd_stdin[0], fd_stdout[1],\r
+                      dir);\r
+  // spawn_process() must close those!\r
+  // If we don't mark them as closed, close() attempt before\r
+  // return from this function throws an exception on Windows.\r
+  // Windows does not like when closed descriptor is closed again.\r
+  fd_stdin[0] = fd_stdout[1] = -1;\r
+\r
+  if (pid == (pid_t) -1) {\r
+    send_http_error(conn, 500, http_500_error,\r
+        "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));\r
+    goto done;\r
+  }\r
+\r
+  if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||\r
+      (out = fdopen(fd_stdout[0], "rb")) == NULL) {\r
+    send_http_error(conn, 500, http_500_error,\r
+        "fopen: %s", strerror(ERRNO));\r
+    goto done;\r
+  }\r
+\r
+  setbuf(in, NULL);\r
+  setbuf(out, NULL);\r
+  fout.fp = out;\r
+\r
+  // Send POST data to the CGI process if needed\r
+  if (!strcmp(conn->request_info.request_method, "POST") &&\r
+      !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {\r
+    goto done;\r
+  }\r
+\r
+  // Close so child gets an EOF.\r
+  fclose(in);\r
+  in = NULL;\r
+  fd_stdin[1] = -1;\r
+\r
+  // Now read CGI reply into a buffer. We need to set correct\r
+  // status code, thus we need to see all HTTP headers first.\r
+  // Do not send anything back to client, until we buffer in all\r
+  // HTTP headers.\r
+  data_len = 0;\r
+  headers_len = read_request(out, conn, buf, sizeof(buf), &data_len);\r
+  if (headers_len <= 0) {\r
+    send_http_error(conn, 500, http_500_error,\r
+                    "CGI program sent malformed or too big (>%u bytes) "\r
+                    "HTTP headers: [%.*s]",\r
+                    (unsigned) sizeof(buf), data_len, buf);\r
+    goto done;\r
+  }\r
+  pbuf = buf;\r
+  buf[headers_len - 1] = '\0';\r
+  parse_http_headers(&pbuf, &ri);\r
+\r
+  // Make up and send the status line\r
+  status_text = "OK";\r
+  if ((status = get_header(&ri, "Status")) != NULL) {\r
+    conn->status_code = atoi(status);\r
+    status_text = status;\r
+    while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {\r
+      status_text++;\r
+    }\r
+  } else if (get_header(&ri, "Location") != NULL) {\r
+    conn->status_code = 302;\r
+  } else {\r
+    conn->status_code = 200;\r
+  }\r
+  if (get_header(&ri, "Connection") != NULL &&\r
+      !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) {\r
+    conn->must_close = 1;\r
+  }\r
+  (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,\r
+                   status_text);\r
+\r
+  // Send headers\r
+  for (i = 0; i < ri.num_headers; i++) {\r
+    mg_printf(conn, "%s: %s\r\n",\r
+              ri.http_headers[i].name, ri.http_headers[i].value);\r
+  }\r
+  mg_write(conn, "\r\n", 2);\r
+\r
+  // Send chunk of data that may have been read after the headers\r
+  conn->num_bytes_sent += mg_write(conn, buf + headers_len,\r
+                                   (size_t)(data_len - headers_len));\r
+\r
+  // Read the rest of CGI output and send to the client\r
+  send_file_data(conn, &fout, 0, INT64_MAX);\r
+\r
+done:\r
+  if (pid != (pid_t) -1) {\r
+    kill(pid, SIGKILL);\r
+  }\r
+  if (fd_stdin[0] != -1) {\r
+    close(fd_stdin[0]);\r
+  }\r
+  if (fd_stdout[1] != -1) {\r
+    close(fd_stdout[1]);\r
+  }\r
+\r
+  if (in != NULL) {\r
+    fclose(in);\r
+  } else if (fd_stdin[1] != -1) {\r
+    close(fd_stdin[1]);\r
+  }\r
+\r
+  if (out != NULL) {\r
+    fclose(out);\r
+  } else if (fd_stdout[0] != -1) {\r
+    close(fd_stdout[0]);\r
+  }\r
+}\r
+#endif // !NO_CGI\r
+\r
+// For a given PUT path, create all intermediate subdirectories\r
+// for given path. Return 0 if the path itself is a directory,\r
+// or -1 on error, 1 if OK.\r
+static int put_dir(struct mg_connection *conn, const char *path) {\r
+  char buf[PATH_MAX];\r
+  const char *s, *p;\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  int len, res = 1;\r
+\r
+  for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {\r
+    len = p - path;\r
+    if (len >= (int) sizeof(buf)) {\r
+      res = -1;\r
+      break;\r
+    }\r
+    memcpy(buf, path, len);\r
+    buf[len] = '\0';\r
+\r
+    // Try to create intermediate directory\r
+    DEBUG_TRACE(("mkdir(%s)", buf));\r
+    if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {\r
+      res = -1;\r
+      break;\r
+    }\r
+\r
+    // Is path itself a directory?\r
+    if (p[1] == '\0') {\r
+      res = 0;\r
+    }\r
+  }\r
+\r
+  return res;\r
+}\r
+\r
+static void put_file(struct mg_connection *conn, const char *path) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  const char *range;\r
+  int64_t r1, r2;\r
+  int rc;\r
+\r
+  conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;\r
+\r
+  if ((rc = put_dir(conn, path)) == 0) {\r
+    mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);\r
+  } else if (rc == -1) {\r
+    send_http_error(conn, 500, http_500_error,\r
+                    "put_dir(%s): %s", path, strerror(ERRNO));\r
+  } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {\r
+    mg_fclose(&file);\r
+    send_http_error(conn, 500, http_500_error,\r
+                    "fopen(%s): %s", path, strerror(ERRNO));\r
+  } else {\r
+    fclose_on_exec(&file);\r
+    range = mg_get_header(conn, "Content-Range");\r
+    r1 = r2 = 0;\r
+    if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {\r
+      conn->status_code = 206;\r
+      fseeko(file.fp, r1, SEEK_SET);\r
+    }\r
+    if (forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {\r
+      mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);\r
+    }\r
+    mg_fclose(&file);\r
+  }\r
+}\r
+\r
+static void send_ssi_file(struct mg_connection *, const char *,\r
+                          struct file *, int);\r
+\r
+static void do_ssi_include(struct mg_connection *conn, const char *ssi,\r
+                           char *tag, int include_level) {\r
+  char file_name[MG_BUF_LEN], path[PATH_MAX], *p;\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+\r
+  // sscanf() is safe here, since send_ssi_file() also uses buffer\r
+  // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.\r
+  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {\r
+    // File name is relative to the webserver root\r
+    (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",\r
+        conn->ctx->config[DOCUMENT_ROOT], '/', file_name);\r
+  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {\r
+    // File name is relative to the webserver working directory\r
+    // or it is absolute system path\r
+    (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);\r
+  } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {\r
+    // File name is relative to the currect document\r
+    (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);\r
+    if ((p = strrchr(path, '/')) != NULL) {\r
+      p[1] = '\0';\r
+    }\r
+    (void) mg_snprintf(conn, path + strlen(path),\r
+        sizeof(path) - strlen(path), "%s", file_name);\r
+  } else {\r
+    cry(conn, "Bad SSI #include: [%s]", tag);\r
+    return;\r
+  }\r
+\r
+  if (!mg_fopen(conn, path, "rb", &file)) {\r
+    cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",\r
+        tag, path, strerror(ERRNO));\r
+  } else {\r
+    fclose_on_exec(&file);\r
+    if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],\r
+                     strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {\r
+      send_ssi_file(conn, path, &file, include_level + 1);\r
+    } else {\r
+      send_file_data(conn, &file, 0, INT64_MAX);\r
+    }\r
+    mg_fclose(&file);\r
+  }\r
+}\r
+\r
+#if !defined(NO_POPEN)\r
+static void do_ssi_exec(struct mg_connection *conn, char *tag) {\r
+  char cmd[MG_BUF_LEN];\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+\r
+  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {\r
+    cry(conn, "Bad SSI #exec: [%s]", tag);\r
+  } else if ((file.fp = popen(cmd, "r")) == NULL) {\r
+    cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));\r
+  } else {\r
+    send_file_data(conn, &file, 0, INT64_MAX);\r
+    pclose(file.fp);\r
+  }\r
+}\r
+#endif // !NO_POPEN\r
+\r
+static int mg_fgetc(struct file *filep, int offset) {\r
+  if (filep->membuf != NULL && offset >=0 && offset < filep->size) {\r
+    return ((unsigned char *) filep->membuf)[offset];\r
+  } else if (filep->fp != NULL) {\r
+    return fgetc(filep->fp);\r
+  } else {\r
+    return EOF;\r
+  }\r
+}\r
+\r
+static void send_ssi_file(struct mg_connection *conn, const char *path,\r
+                          struct file *filep, int include_level) {\r
+  char buf[MG_BUF_LEN];\r
+  int ch, offset, len, in_ssi_tag;\r
+\r
+  if (include_level > 10) {\r
+    cry(conn, "SSI #include level is too deep (%s)", path);\r
+    return;\r
+  }\r
+\r
+  in_ssi_tag = len = offset = 0;\r
+  while ((ch = mg_fgetc(filep, offset)) != EOF) {\r
+    if (in_ssi_tag && ch == '>') {\r
+      in_ssi_tag = 0;\r
+      buf[len++] = (char) ch;\r
+      buf[len] = '\0';\r
+      assert(len <= (int) sizeof(buf));\r
+      if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {\r
+        // Not an SSI tag, pass it\r
+        (void) mg_write(conn, buf, (size_t) len);\r
+      } else {\r
+        if (!memcmp(buf + 5, "include", 7)) {\r
+          do_ssi_include(conn, path, buf + 12, include_level);\r
+#if !defined(NO_POPEN)\r
+        } else if (!memcmp(buf + 5, "exec", 4)) {\r
+          do_ssi_exec(conn, buf + 9);\r
+#endif // !NO_POPEN\r
+        } else {\r
+          cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);\r
+        }\r
+      }\r
+      len = 0;\r
+    } else if (in_ssi_tag) {\r
+      if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {\r
+        // Not an SSI tag\r
+        in_ssi_tag = 0;\r
+      } else if (len == (int) sizeof(buf) - 2) {\r
+        cry(conn, "%s: SSI tag is too large", path);\r
+        len = 0;\r
+      }\r
+      buf[len++] = ch & 0xff;\r
+    } else if (ch == '<') {\r
+      in_ssi_tag = 1;\r
+      if (len > 0) {\r
+        mg_write(conn, buf, (size_t) len);\r
+      }\r
+      len = 0;\r
+      buf[len++] = ch & 0xff;\r
+    } else {\r
+      buf[len++] = ch & 0xff;\r
+      if (len == (int) sizeof(buf)) {\r
+        mg_write(conn, buf, (size_t) len);\r
+        len = 0;\r
+      }\r
+    }\r
+  }\r
+\r
+  // Send the rest of buffered data\r
+  if (len > 0) {\r
+    mg_write(conn, buf, (size_t) len);\r
+  }\r
+}\r
+\r
+static void handle_ssi_file_request(struct mg_connection *conn,\r
+                                    const char *path) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+\r
+  if (!mg_fopen(conn, path, "rb", &file)) {\r
+    send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,\r
+                    strerror(ERRNO));\r
+  } else {\r
+    conn->must_close = 1;\r
+    fclose_on_exec(&file);\r
+    mg_printf(conn, "HTTP/1.1 200 OK\r\n"\r
+              "Content-Type: text/html\r\nConnection: %s\r\n\r\n",\r
+              suggest_connection_header(conn));\r
+    send_ssi_file(conn, path, &file, 0);\r
+    mg_fclose(&file);\r
+  }\r
+}\r
+\r
+static void send_options(struct mg_connection *conn) {\r
+  conn->status_code = 200;\r
+\r
+  mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"\r
+            "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS\r\n"\r
+            "DAV: 1\r\n\r\n");\r
+}\r
+\r
+// Writes PROPFIND properties for a collection element\r
+static void print_props(struct mg_connection *conn, const char* uri,\r
+                        struct file *filep) {\r
+  char mtime[64];\r
+  gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);\r
+  conn->num_bytes_sent += mg_printf(conn,\r
+      "<d:response>"\r
+       "<d:href>%s</d:href>"\r
+       "<d:propstat>"\r
+        "<d:prop>"\r
+         "<d:resourcetype>%s</d:resourcetype>"\r
+         "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"\r
+         "<d:getlastmodified>%s</d:getlastmodified>"\r
+        "</d:prop>"\r
+        "<d:status>HTTP/1.1 200 OK</d:status>"\r
+       "</d:propstat>"\r
+      "</d:response>\n",\r
+      uri,\r
+      filep->is_directory ? "<d:collection/>" : "",\r
+      filep->size,\r
+      mtime);\r
+}\r
+\r
+static void print_dav_dir_entry(struct de *de, void *data) {\r
+  char href[PATH_MAX];\r
+  struct mg_connection *conn = (struct mg_connection *) data;\r
+  mg_snprintf(conn, href, sizeof(href), "%s%s",\r
+              conn->request_info.uri, de->file_name);\r
+  print_props(conn, href, &de->file);\r
+}\r
+\r
+static void handle_propfind(struct mg_connection *conn, const char *path,\r
+                            struct file *filep) {\r
+  const char *depth = mg_get_header(conn, "Depth");\r
+\r
+  conn->must_close = 1;\r
+  conn->status_code = 207;\r
+  mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"\r
+            "Connection: close\r\n"\r
+            "Content-Type: text/xml; charset=utf-8\r\n\r\n");\r
+\r
+  conn->num_bytes_sent += mg_printf(conn,\r
+      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"\r
+      "<d:multistatus xmlns:d='DAV:'>\n");\r
+\r
+  // Print properties for the requested resource itself\r
+  print_props(conn, conn->request_info.uri, filep);\r
+\r
+  // If it is a directory, print directory entries too if Depth is not 0\r
+  if (filep->is_directory &&\r
+      !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&\r
+      (depth == NULL || strcmp(depth, "0") != 0)) {\r
+    scan_directory(conn, path, conn, &print_dav_dir_entry);\r
+  }\r
+\r
+  conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");\r
+}\r
+\r
+#if defined(USE_WEBSOCKET)\r
+\r
+// START OF SHA-1 code\r
+// Copyright(c) By Steve Reid <steve@edmweb.com>\r
+#define SHA1HANDSOFF\r
+#if defined(__sun)\r
+#include "solarisfixes.h"\r
+#endif\r
+\r
+union char64long16 { unsigned char c[64]; uint32_t l[16]; };\r
+\r
+#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))\r
+\r
+static uint32_t blk0(union char64long16 *block, int i) {\r
+  // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN\r
+  if (!is_big_endian()) {\r
+    block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |\r
+      (rol(block->l[i], 8) & 0x00FF00FF);\r
+  }\r
+  return block->l[i];\r
+}\r
+\r
+#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \\r
+    ^block->l[(i+2)&15]^block->l[i&15],1))\r
+#define S0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);\r
+#define S1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);\r
+#define S2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);\r
+#define S3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);\r
+#define S4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);\r
+\r
+typedef struct {\r
+    uint32_t state[5];\r
+    uint32_t count[2];\r
+    unsigned char buffer[64];\r
+} SHA1_CTX;\r
+\r
+static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {\r
+  uint32_t a, b, c, d, e;\r
+  union char64long16 block[1];\r
+\r
+  memcpy(block, buffer, 64);\r
+  a = state[0];\r
+  b = state[1];\r
+  c = state[2];\r
+  d = state[3];\r
+  e = state[4];\r
+  S0(a,b,c,d,e, 0); S0(e,a,b,c,d, 1); S0(d,e,a,b,c, 2); S0(c,d,e,a,b, 3);\r
+  S0(b,c,d,e,a, 4); S0(a,b,c,d,e, 5); S0(e,a,b,c,d, 6); S0(d,e,a,b,c, 7);\r
+  S0(c,d,e,a,b, 8); S0(b,c,d,e,a, 9); S0(a,b,c,d,e,10); S0(e,a,b,c,d,11);\r
+  S0(d,e,a,b,c,12); S0(c,d,e,a,b,13); S0(b,c,d,e,a,14); S0(a,b,c,d,e,15);\r
+  S1(e,a,b,c,d,16); S1(d,e,a,b,c,17); S1(c,d,e,a,b,18); S1(b,c,d,e,a,19);\r
+  S2(a,b,c,d,e,20); S2(e,a,b,c,d,21); S2(d,e,a,b,c,22); S2(c,d,e,a,b,23);\r
+  S2(b,c,d,e,a,24); S2(a,b,c,d,e,25); S2(e,a,b,c,d,26); S2(d,e,a,b,c,27);\r
+  S2(c,d,e,a,b,28); S2(b,c,d,e,a,29); S2(a,b,c,d,e,30); S2(e,a,b,c,d,31);\r
+  S2(d,e,a,b,c,32); S2(c,d,e,a,b,33); S2(b,c,d,e,a,34); S2(a,b,c,d,e,35);\r
+  S2(e,a,b,c,d,36); S2(d,e,a,b,c,37); S2(c,d,e,a,b,38); S2(b,c,d,e,a,39);\r
+  S3(a,b,c,d,e,40); S3(e,a,b,c,d,41); S3(d,e,a,b,c,42); S3(c,d,e,a,b,43);\r
+  S3(b,c,d,e,a,44); S3(a,b,c,d,e,45); S3(e,a,b,c,d,46); S3(d,e,a,b,c,47);\r
+  S3(c,d,e,a,b,48); S3(b,c,d,e,a,49); S3(a,b,c,d,e,50); S3(e,a,b,c,d,51);\r
+  S3(d,e,a,b,c,52); S3(c,d,e,a,b,53); S3(b,c,d,e,a,54); S3(a,b,c,d,e,55);\r
+  S3(e,a,b,c,d,56); S3(d,e,a,b,c,57); S3(c,d,e,a,b,58); S3(b,c,d,e,a,59);\r
+  S4(a,b,c,d,e,60); S4(e,a,b,c,d,61); S4(d,e,a,b,c,62); S4(c,d,e,a,b,63);\r
+  S4(b,c,d,e,a,64); S4(a,b,c,d,e,65); S4(e,a,b,c,d,66); S4(d,e,a,b,c,67);\r
+  S4(c,d,e,a,b,68); S4(b,c,d,e,a,69); S4(a,b,c,d,e,70); S4(e,a,b,c,d,71);\r
+  S4(d,e,a,b,c,72); S4(c,d,e,a,b,73); S4(b,c,d,e,a,74); S4(a,b,c,d,e,75);\r
+  S4(e,a,b,c,d,76); S4(d,e,a,b,c,77); S4(c,d,e,a,b,78); S4(b,c,d,e,a,79);\r
+  state[0] += a;\r
+  state[1] += b;\r
+  state[2] += c;\r
+  state[3] += d;\r
+  state[4] += e;\r
+  a = b = c = d = e = 0;\r
+  memset(block, '\0', sizeof(block));\r
+}\r
+\r
+static void SHA1Init(SHA1_CTX* context) {\r
+  context->state[0] = 0x67452301;\r
+  context->state[1] = 0xEFCDAB89;\r
+  context->state[2] = 0x98BADCFE;\r
+  context->state[3] = 0x10325476;\r
+  context->state[4] = 0xC3D2E1F0;\r
+  context->count[0] = context->count[1] = 0;\r
+}\r
+\r
+static void SHA1Update(SHA1_CTX* context, const unsigned char* data,\r
+                       uint32_t len) {\r
+  uint32_t i, j;\r
+\r
+  j = context->count[0];\r
+  if ((context->count[0] += len << 3) < j)\r
+    context->count[1]++;\r
+  context->count[1] += (len>>29);\r
+  j = (j >> 3) & 63;\r
+  if ((j + len) > 63) {\r
+    memcpy(&context->buffer[j], data, (i = 64-j));\r
+    SHA1Transform(context->state, context->buffer);\r
+    for ( ; i + 63 < len; i += 64) {\r
+      SHA1Transform(context->state, &data[i]);\r
+    }\r
+    j = 0;\r
+  }\r
+  else i = 0;\r
+  memcpy(&context->buffer[j], &data[i], len - i);\r
+}\r
+\r
+static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {\r
+  unsigned i;\r
+  unsigned char finalcount[8], c;\r
+\r
+  for (i = 0; i < 8; i++) {\r
+    finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]\r
+                                     >> ((3-(i & 3)) * 8) ) & 255);\r
+  }\r
+  c = 0200;\r
+  SHA1Update(context, &c, 1);\r
+  while ((context->count[0] & 504) != 448) {\r
+    c = 0000;\r
+    SHA1Update(context, &c, 1);\r
+  }\r
+  SHA1Update(context, finalcount, 8);\r
+  for (i = 0; i < 20; i++) {\r
+    digest[i] = (unsigned char)\r
+      ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);\r
+  }\r
+  memset(context, '\0', sizeof(*context));\r
+  memset(&finalcount, '\0', sizeof(finalcount));\r
+}\r
+// END OF SHA1 CODE\r
+\r
+static void base64_encode(const unsigned char *src, int src_len, char *dst) {\r
+  static const char *b64 =\r
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\r
+  int i, j, a, b, c;\r
+\r
+  for (i = j = 0; i < src_len; i += 3) {\r
+    a = src[i];\r
+    b = i + 1 >= src_len ? 0 : src[i + 1];\r
+    c = i + 2 >= src_len ? 0 : src[i + 2];\r
+\r
+    dst[j++] = b64[a >> 2];\r
+    dst[j++] = b64[((a & 3) << 4) | (b >> 4)];\r
+    if (i + 1 < src_len) {\r
+      dst[j++] = b64[(b & 15) << 2 | (c >> 6)];\r
+    }\r
+    if (i + 2 < src_len) {\r
+      dst[j++] = b64[c & 63];\r
+    }\r
+  }\r
+  while (j % 4 != 0) {\r
+    dst[j++] = '=';\r
+  }\r
+  dst[j++] = '\0';\r
+}\r
+\r
+static void send_websocket_handshake(struct mg_connection *conn) {\r
+  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";\r
+  char buf[100], sha[20], b64_sha[sizeof(sha) * 2];\r
+  SHA1_CTX sha_ctx;\r
+\r
+  mg_snprintf(conn, buf, sizeof(buf), "%s%s",\r
+              mg_get_header(conn, "Sec-WebSocket-Key"), magic);\r
+  SHA1Init(&sha_ctx);\r
+  SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));\r
+  SHA1Final((unsigned char *) sha, &sha_ctx);\r
+  base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);\r
+  mg_printf(conn, "%s%s%s",\r
+            "HTTP/1.1 101 Switching Protocols\r\n"\r
+            "Upgrade: websocket\r\n"\r
+            "Connection: Upgrade\r\n"\r
+//            "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");\r
+            "Sec-WebSocket-Accept: ", b64_sha, "\r\n");\r
+}\r
+\r
+static void read_websocket(struct mg_connection *conn) {\r
+  unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;\r
+  int bits, n, stop = 0;\r
+  size_t i, len, mask_len, data_len, header_len, body_len;\r
+  char mem[4 * 1024], mask[4], *data;\r
+\r
+  assert(conn->content_len == 0);\r
+  while (!stop) {\r
+    header_len = 0;\r
+    if ((body_len = conn->data_len - conn->request_len) >= 2) {\r
+      len = buf[1] & 127;\r
+      mask_len = buf[1] & 128 ? 4 : 0;\r
+      if (len < 126 && body_len >= mask_len) {\r
+        data_len = len;\r
+        header_len = 2 + mask_len;\r
+      } else if (len == 126 && body_len >= 4 + mask_len) {\r
+        header_len = 4 + mask_len;\r
+        data_len = ((((int) buf[2]) << 8) + buf[3]);\r
+      } else if (body_len >= 10 + mask_len) {\r
+        header_len = 10 + mask_len;\r
+        data_len = (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +\r
+          htonl(* (uint32_t *) &buf[6]);\r
+      }\r
+    }\r
+\r
+    // Data layout is as follows:\r
+    //  conn->buf               buf\r
+    //     v                     v              frame1           | frame2\r
+    //     |---------------------|----------------|--------------|-------\r
+    //     |                     |<--header_len-->|<--data_len-->|\r
+    //     |<-conn->request_len->|<-----body_len----------->|\r
+    //     |<-------------------conn->data_len------------->|\r
+\r
+    if (header_len > 0) {\r
+      // Allocate space to hold websocket payload\r
+      data = mem;\r
+      if (data_len > sizeof(mem) && (data = malloc(data_len)) == NULL) {\r
+        // Allocation failed, exit the loop and then close the connection\r
+        // TODO: notify user about the failure\r
+        break;\r
+      }\r
+\r
+      // Save mask and bits, otherwise it may be clobbered by memmove below\r
+      bits = buf[0];\r
+      memcpy(mask, buf + header_len - mask_len, mask_len);\r
+\r
+      // Read frame payload into the allocated buffer.\r
+      assert(body_len >= header_len);\r
+      if (data_len + header_len > body_len) {\r
+        len = body_len - header_len;\r
+        memcpy(data, buf + header_len, len);\r
+        // TODO: handle pull error\r
+        pull_all(NULL, conn, data + len, data_len - len);\r
+        conn->data_len = conn->request_len;\r
+      } else {\r
+        len = data_len + header_len;\r
+        memcpy(data, buf + header_len, data_len);\r
+        memmove(buf, buf + len, body_len - len);\r
+        conn->data_len -= len;\r
+      }\r
+\r
+      // Apply mask if necessary\r
+      if (mask_len > 0) {\r
+        for (i = 0; i < data_len; i++) {\r
+          data[i] ^= mask[i % 4];\r
+        }\r
+      }\r
+\r
+      // Exit the loop if callback signalled to exit,\r
+      // or "connection close" opcode received.\r
+      if ((conn->ctx->callbacks.websocket_data != NULL &&\r
+          !conn->ctx->callbacks.websocket_data(conn, bits, data, data_len)) ||\r
+          (bits & 0xf) == 8) {  // Opcode == 8, connection close\r
+        stop = 1;\r
+      }\r
+\r
+      if (data != mem) {\r
+        free(data);\r
+      }\r
+      // Not breaking the loop, process next websocket frame.\r
+    } else {\r
+      // Buffering websocket request\r
+      if ((n = pull(NULL, conn, conn->buf + conn->data_len,\r
+                    conn->buf_size - conn->data_len)) <= 0) {\r
+        break;\r
+      }\r
+      conn->data_len += n;\r
+    }\r
+  }\r
+}\r
+\r
+static void handle_websocket_request(struct mg_connection *conn) {\r
+  const char *version = mg_get_header(conn, "Sec-WebSocket-Version");\r
+  if (version == NULL || strcmp(version, "13") != 0) {\r
+    send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");\r
+  } else if (conn->ctx->callbacks.websocket_connect != NULL &&\r
+             conn->ctx->callbacks.websocket_connect(conn) != 0) {\r
+    // Callback has returned non-zero, do not proceed with handshake\r
+  } else {\r
+    send_websocket_handshake(conn);\r
+    if (conn->ctx->callbacks.websocket_ready != NULL) {\r
+      conn->ctx->callbacks.websocket_ready(conn);\r
+    } else {\r
+      mg_printf(conn, "\r\n");\r
+    }\r
+    read_websocket(conn);\r
+  }\r
+}\r
+\r
+static int is_websocket_request(const struct mg_connection *conn) {\r
+  const char *host, *upgrade, *connection, *version, *key;\r
+\r
+  host = mg_get_header(conn, "Host");\r
+  upgrade = mg_get_header(conn, "Upgrade");\r
+  connection = mg_get_header(conn, "Connection");\r
+  key = mg_get_header(conn, "Sec-WebSocket-Key");\r
+  version = mg_get_header(conn, "Sec-WebSocket-Version");\r
+\r
+  return host != NULL && upgrade != NULL && connection != NULL &&\r
+    key != NULL && version != NULL &&\r
+    mg_strcasestr(upgrade, "websocket") != NULL &&\r
+    mg_strcasestr(connection, "Upgrade") != NULL;\r
+}\r
+#endif // !USE_WEBSOCKET\r
+\r
+static int isbyte(int n) {\r
+  return n >= 0 && n <= 255;\r
+}\r
+\r
+static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {\r
+  int n, a, b, c, d, slash = 32, len = 0;\r
+\r
+  if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||\r
+      sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&\r
+      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&\r
+      slash >= 0 && slash < 33) {\r
+    len = n;\r
+    *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;\r
+    *mask = slash ? 0xffffffffU << (32 - slash) : 0;\r
+  }\r
+\r
+  return len;\r
+}\r
+\r
+static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) {\r
+  int throttle = 0;\r
+  struct vec vec, val;\r
+  uint32_t net, mask;\r
+  char mult;\r
+  double v;\r
+\r
+  while ((spec = next_option(spec, &vec, &val)) != NULL) {\r
+    mult = ',';\r
+    if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||\r
+        (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {\r
+      continue;\r
+    }\r
+    v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;\r
+    if (vec.len == 1 && vec.ptr[0] == '*') {\r
+      throttle = (int) v;\r
+    } else if (parse_net(vec.ptr, &net, &mask) > 0) {\r
+      if ((remote_ip & mask) == net) {\r
+        throttle = (int) v;\r
+      }\r
+    } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {\r
+      throttle = (int) v;\r
+    }\r
+  }\r
+\r
+  return throttle;\r
+}\r
+\r
+static uint32_t get_remote_ip(const struct mg_connection *conn) {\r
+  return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);\r
+}\r
+\r
+#ifdef USE_LUA\r
+#include "mod_lua.c"\r
+#endif // USE_LUA\r
+\r
+int mg_upload(struct mg_connection *conn, const char *destination_dir) {\r
+  const char *content_type_header, *boundary_start;\r
+  char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s;\r
+  FILE *fp;\r
+  int bl, n, i, j, headers_len, boundary_len, eof,\r
+      len = 0, num_uploaded_files = 0;\r
+\r
+  // Request looks like this:\r
+  //\r
+  // POST /upload HTTP/1.1\r
+  // Host: 127.0.0.1:8080\r
+  // Content-Length: 244894\r
+  // Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr\r
+  //\r
+  // ------WebKitFormBoundaryRVr\r
+  // Content-Disposition: form-data; name="file"; filename="accum.png"\r
+  // Content-Type: image/png\r
+  //\r
+  //  <89>PNG\r
+  //  <PNG DATA>\r
+  // ------WebKitFormBoundaryRVr\r
+\r
+  // Extract boundary string from the Content-Type header\r
+  if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||\r
+      (boundary_start = mg_strcasestr(content_type_header,\r
+                                      "boundary=")) == NULL ||\r
+      (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&\r
+       sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||\r
+      boundary[0] == '\0') {\r
+    return num_uploaded_files;\r
+  }\r
+\r
+  boundary_len = strlen(boundary);\r
+  bl = boundary_len + 4;  // \r\n--<boundary>\r
+  for (;;) {\r
+    // Pull in headers\r
+    assert(len >= 0 && len <= (int) sizeof(buf));\r
+    while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {\r
+      len += n;\r
+    }\r
+    if ((headers_len = get_request_len(buf, len)) <= 0) {\r
+      break;\r
+    }\r
+\r
+    // Fetch file name.\r
+    fname[0] = '\0';\r
+    for (i = j = 0; i < headers_len; i++) {\r
+      if (buf[i] == '\r' && buf[i + 1] == '\n') {\r
+        buf[i] = buf[i + 1] = '\0';\r
+        // TODO(lsm): don't expect filename to be the 3rd field,\r
+        // parse the header properly instead.\r
+        sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",\r
+               fname);\r
+        j = i + 2;\r
+      }\r
+    }\r
+\r
+    // Give up if the headers are not what we expect\r
+    if (fname[0] == '\0') {\r
+      break;\r
+    }\r
+\r
+    // Move data to the beginning of the buffer\r
+    assert(len >= headers_len);\r
+    memmove(buf, &buf[headers_len], len - headers_len);\r
+    len -= headers_len;\r
+\r
+    // We open the file with exclusive lock held. This guarantee us\r
+    // there is no other thread can save into the same file simultaneously.\r
+    fp = NULL;\r
+    // Construct destination file name. Do not allow paths to have slashes.\r
+    if ((s = strrchr(fname, '/')) == NULL) {\r
+      s = fname;\r
+    }\r
+    // Open file in binary mode. TODO: set an exclusive lock.\r
+    snprintf(path, sizeof(path), "%s/%s", destination_dir, s);\r
+    if ((fp = fopen(path, "wb")) == NULL) {\r
+      break;\r
+    }\r
+\r
+    // Read POST data, write into file until boundary is found.\r
+    eof = n = 0;\r
+    do {\r
+      len += n;\r
+      for (i = 0; i < len - bl; i++) {\r
+        if (!memcmp(&buf[i], "\r\n--", 4) &&\r
+            !memcmp(&buf[i + 4], boundary, boundary_len)) {\r
+          // Found boundary, that's the end of file data.\r
+          fwrite(buf, 1, i, fp);\r
+          eof = 1;\r
+          memmove(buf, &buf[i + bl], len - (i + bl));\r
+          len -= i + bl;\r
+          break;\r
+        }\r
+      }\r
+      if (!eof && len > bl) {\r
+        fwrite(buf, 1, len - bl, fp);\r
+        memmove(buf, &buf[len - bl], bl);\r
+        len = bl;\r
+      }\r
+    } while (!eof && (n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);\r
+    fclose(fp);\r
+    if (eof) {\r
+      num_uploaded_files++;\r
+      if (conn->ctx->callbacks.upload != NULL) {\r
+        conn->ctx->callbacks.upload(conn, path);\r
+      }\r
+    }\r
+  }\r
+\r
+  return num_uploaded_files;\r
+}\r
+\r
+static int is_put_or_delete_request(const struct mg_connection *conn) {\r
+  const char *s = conn->request_info.request_method;\r
+  return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE"));\r
+}\r
+\r
+static int get_first_ssl_listener_index(const struct mg_context *ctx) {\r
+  int i, index = -1;\r
+  for (i = 0; index == -1 && i < ctx->num_listening_sockets; i++) {\r
+    index = ctx->listening_sockets[i].is_ssl ? i : -1;\r
+  }\r
+  return index;\r
+}\r
+\r
+static void redirect_to_https_port(struct mg_connection *conn, int ssl_index) {\r
+  char host[1025];\r
+  const char *host_header;\r
+\r
+  if ((host_header = mg_get_header(conn, "Host")) == NULL ||\r
+      sscanf(host_header, "%1024[^:]", host) == 0) {\r
+    // Cannot get host from the Host: header. Fallback to our IP address.\r
+    sockaddr_to_string(host, sizeof(host), &conn->client.lsa);\r
+  }\r
+\r
+  mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",\r
+            host, (int) ntohs(conn->ctx->listening_sockets[ssl_index].\r
+                              lsa.sin.sin_port), conn->request_info.uri);\r
+}\r
+\r
+// This is the heart of the Mongoose's logic.\r
+// This function is called when the request is read, parsed and validated,\r
+// and Mongoose must decide what action to take: serve a file, or\r
+// a directory, or call embedded function, etcetera.\r
+static void handle_request(struct mg_connection *conn) {\r
+  struct mg_request_info *ri = &conn->request_info;\r
+  char path[PATH_MAX];\r
+  int uri_len, ssl_index;\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+\r
+  if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {\r
+    * ((char *) conn->request_info.query_string++) = '\0';\r
+  }\r
+  uri_len = (int) strlen(ri->uri);\r
+  mg_url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0);\r
+  remove_double_dots_and_double_slashes((char *) ri->uri);\r
+  convert_uri_to_file_name(conn, path, sizeof(path), &file);\r
+  conn->throttle = set_throttle(conn->ctx->config[THROTTLE],\r
+                                get_remote_ip(conn), ri->uri);\r
+\r
+  DEBUG_TRACE(("%s", ri->uri));\r
+  // Perform redirect and auth checks before calling begin_request() handler.\r
+  // Otherwise, begin_request() would need to perform auth checks and redirects.\r
+  if (!conn->client.is_ssl && conn->client.ssl_redir &&\r
+      (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {\r
+    redirect_to_https_port(conn, ssl_index);\r
+  } else if (!is_put_or_delete_request(conn) &&\r
+             !check_authorization(conn, path)) {\r
+    send_authorization_request(conn);\r
+  } else if (conn->ctx->callbacks.begin_request != NULL &&\r
+      conn->ctx->callbacks.begin_request(conn)) {\r
+    // Do nothing, callback has served the request\r
+#if defined(USE_WEBSOCKET)\r
+  } else if (is_websocket_request(conn)) {\r
+    handle_websocket_request(conn);\r
+#endif\r
+  } else if (!strcmp(ri->request_method, "OPTIONS")) {\r
+    send_options(conn);\r
+  } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {\r
+    send_http_error(conn, 404, "Not Found", "Not Found");\r
+  } else if (is_put_or_delete_request(conn) &&\r
+             (conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ||\r
+              is_authorized_for_put(conn) != 1)) {\r
+    send_authorization_request(conn);\r
+  } else if (!strcmp(ri->request_method, "PUT")) {\r
+    put_file(conn, path);\r
+  } else if (!strcmp(ri->request_method, "DELETE")) {\r
+    if (mg_remove(path) == 0) {\r
+      send_http_error(conn, 200, "OK", "%s", "");\r
+    } else {\r
+      send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,\r
+                      strerror(ERRNO));\r
+    }\r
+  } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||\r
+             must_hide_file(conn, path)) {\r
+    send_http_error(conn, 404, "Not Found", "%s", "File not found");\r
+  } else if (file.is_directory && ri->uri[uri_len - 1] != '/') {\r
+    mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"\r
+              "Location: %s/\r\n\r\n", ri->uri);\r
+  } else if (!strcmp(ri->request_method, "PROPFIND")) {\r
+    handle_propfind(conn, path, &file);\r
+  } else if (file.is_directory &&\r
+             !substitute_index_file(conn, path, sizeof(path), &file)) {\r
+    if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {\r
+      handle_directory_request(conn, path);\r
+    } else {\r
+      send_http_error(conn, 403, "Directory Listing Denied",\r
+          "Directory listing denied");\r
+    }\r
+#ifdef USE_LUA\r
+  } else if (match_prefix("**.lp$", 6, path) > 0) {\r
+    handle_lsp_request(conn, path, &file, NULL);\r
+#endif\r
+#if !defined(NO_CGI)\r
+  } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],\r
+                          strlen(conn->ctx->config[CGI_EXTENSIONS]),\r
+                          path) > 0) {\r
+    if (strcmp(ri->request_method, "POST") &&\r
+        strcmp(ri->request_method, "HEAD") &&\r
+        strcmp(ri->request_method, "GET")) {\r
+      send_http_error(conn, 501, "Not Implemented",\r
+                      "Method %s is not implemented", ri->request_method);\r
+    } else {\r
+      handle_cgi_request(conn, path);\r
+    }\r
+#endif // !NO_CGI\r
+  } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],\r
+                          strlen(conn->ctx->config[SSI_EXTENSIONS]),\r
+                          path) > 0) {\r
+    handle_ssi_file_request(conn, path);\r
+  } else if (is_not_modified(conn, &file)) {\r
+    send_http_error(conn, 304, "Not Modified", "%s", "");\r
+  } else {\r
+    handle_file_request(conn, path, &file);\r
+  }\r
+}\r
+\r
+static void close_all_listening_sockets(struct mg_context *ctx) {\r
+  int i;\r
+  for (i = 0; i < ctx->num_listening_sockets; i++) {\r
+    closesocket(ctx->listening_sockets[i].sock);\r
+  }\r
+  free(ctx->listening_sockets);\r
+}\r
+\r
+// Valid listening port specification is: [ip_address:]port[s]\r
+// Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s\r
+// TODO(lsm): add parsing of the IPv6 address\r
+static int parse_port_string(const struct vec *vec, struct socket *so) {\r
+  int a, b, c, d, port, len;\r
+\r
+  // MacOS needs that. If we do not zero it, subsequent bind() will fail.\r
+  // Also, all-zeroes in the socket address means binding to all addresses\r
+  // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).\r
+  memset(so, 0, sizeof(*so));\r
+\r
+  if (sscanf(vec->ptr, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &len) == 5) {\r
+    // Bind to a specific IPv4 address\r
+    so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);\r
+  } else if (sscanf(vec->ptr, "%d%n", &port, &len) != 1 ||\r
+             len <= 0 ||\r
+             len > (int) vec->len ||\r
+             (vec->ptr[len] && vec->ptr[len] != 's' &&\r
+              vec->ptr[len] != 'r' && vec->ptr[len] != ',')) {\r
+    return 0;\r
+  }\r
+\r
+  so->is_ssl = vec->ptr[len] == 's';\r
+  so->ssl_redir = vec->ptr[len] == 'r';\r
+#if defined(USE_IPV6)\r
+  so->lsa.sin6.sin6_family = AF_INET6;\r
+  so->lsa.sin6.sin6_port = htons((uint16_t) port);\r
+#else\r
+  so->lsa.sin.sin_family = AF_INET;\r
+  so->lsa.sin.sin_port = htons((uint16_t) port);\r
+#endif\r
+\r
+  return 1;\r
+}\r
+\r
+static int set_ports_option(struct mg_context *ctx) {\r
+  const char *list = ctx->config[LISTENING_PORTS];\r
+  int on = 1, success = 1;\r
+#if defined(USE_IPV6)\r
+  int off = 0;\r
+#endif\r
+  struct vec vec;\r
+  struct socket so, *ptr;\r
+\r
+  while (success && (list = next_option(list, &vec, NULL)) != NULL) {\r
+    if (!parse_port_string(&vec, &so)) {\r
+      cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",\r
+          __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]");\r
+      success = 0;\r
+    } else if (so.is_ssl && ctx->ssl_ctx == NULL) {\r
+      cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");\r
+      success = 0;\r
+    } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==\r
+               INVALID_SOCKET ||\r
+               // On Windows, SO_REUSEADDR is recommended only for\r
+               // broadcast UDP sockets\r
+               setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,\r
+                          (void *) &on, sizeof(on)) != 0 ||\r
+#if defined(USE_IPV6)\r
+               setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &off,\r
+                          sizeof(off)) != 0 ||\r
+#endif\r
+               bind(so.sock, &so.lsa.sa, sizeof(so.lsa)) != 0 ||\r
+               listen(so.sock, SOMAXCONN) != 0) {\r
+      cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__,\r
+          (int) vec.len, vec.ptr, strerror(ERRNO));\r
+      closesocket(so.sock);\r
+      success = 0;\r
+    } else if ((ptr = realloc(ctx->listening_sockets,\r
+                              (ctx->num_listening_sockets + 1) *\r
+                              sizeof(ctx->listening_sockets[0]))) == NULL) {\r
+      closesocket(so.sock);\r
+      success = 0;\r
+    } else {\r
+      set_close_on_exec(so.sock);\r
+      ctx->listening_sockets = ptr;\r
+      ctx->listening_sockets[ctx->num_listening_sockets] = so;\r
+      ctx->num_listening_sockets++;\r
+    }\r
+  }\r
+\r
+  if (!success) {\r
+    close_all_listening_sockets(ctx);\r
+  }\r
+\r
+  return success;\r
+}\r
+\r
+static void log_header(const struct mg_connection *conn, const char *header,\r
+                       FILE *fp) {\r
+  const char *header_value;\r
+\r
+  if ((header_value = mg_get_header(conn, header)) == NULL) {\r
+    (void) fprintf(fp, "%s", " -");\r
+  } else {\r
+    (void) fprintf(fp, " \"%s\"", header_value);\r
+  }\r
+}\r
+\r
+static void log_access(const struct mg_connection *conn) {\r
+  const struct mg_request_info *ri;\r
+  FILE *fp;\r
+  char date[64], src_addr[20];\r
+\r
+  fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ?  NULL :\r
+    fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");\r
+\r
+  if (fp == NULL)\r
+    return;\r
+\r
+  strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",\r
+           localtime(&conn->birth_time));\r
+\r
+  ri = &conn->request_info;\r
+  flockfile(fp);\r
+\r
+  sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);\r
+  fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,\r
+          src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,\r
+          ri->request_method ? ri->request_method : "-",\r
+          ri->uri ? ri->uri : "-", ri->http_version,\r
+          conn->status_code, conn->num_bytes_sent);\r
+  log_header(conn, "Referer", fp);\r
+  log_header(conn, "User-Agent", fp);\r
+  fputc('\n', fp);\r
+  fflush(fp);\r
+\r
+  funlockfile(fp);\r
+  fclose(fp);\r
+}\r
+\r
+// Verify given socket address against the ACL.\r
+// Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.\r
+static int check_acl(struct mg_context *ctx, uint32_t remote_ip) {\r
+  int allowed, flag;\r
+  uint32_t net, mask;\r
+  struct vec vec;\r
+  const char *list = ctx->config[ACCESS_CONTROL_LIST];\r
+\r
+  // If any ACL is set, deny by default\r
+  allowed = list == NULL ? '+' : '-';\r
+\r
+  while ((list = next_option(list, &vec, NULL)) != NULL) {\r
+    flag = vec.ptr[0];\r
+    if ((flag != '+' && flag != '-') ||\r
+        parse_net(&vec.ptr[1], &net, &mask) == 0) {\r
+      cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);\r
+      return -1;\r
+    }\r
+\r
+    if (net == (remote_ip & mask)) {\r
+      allowed = flag;\r
+    }\r
+  }\r
+\r
+  return allowed == '+';\r
+}\r
+\r
+#if !defined(_WIN32)\r
+static int set_uid_option(struct mg_context *ctx) {\r
+  struct passwd *pw;\r
+  const char *uid = ctx->config[RUN_AS_USER];\r
+  int success = 0;\r
+\r
+  if (uid == NULL) {\r
+    success = 1;\r
+  } else {\r
+    if ((pw = getpwnam(uid)) == NULL) {\r
+      cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);\r
+    } else if (setgid(pw->pw_gid) == -1) {\r
+      cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));\r
+    } else if (setuid(pw->pw_uid) == -1) {\r
+      cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));\r
+    } else {\r
+      success = 1;\r
+    }\r
+  }\r
+\r
+  return success;\r
+}\r
+#endif // !_WIN32\r
+\r
+#if !defined(NO_SSL)\r
+static pthread_mutex_t *ssl_mutexes;\r
+\r
+static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) {\r
+  return (conn->ssl = SSL_new(s)) != NULL &&\r
+    SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&\r
+    func(conn->ssl) == 1;\r
+}\r
+\r
+// Return OpenSSL error message\r
+static const char *ssl_error(void) {\r
+  unsigned long err;\r
+  err = ERR_get_error();\r
+  return err == 0 ? "" : ERR_error_string(err, NULL);\r
+}\r
+\r
+static void ssl_locking_callback(int mode, int mutex_num, const char *file,\r
+                                 int line) {\r
+  (void) line;\r
+  (void) file;\r
+\r
+  if (mode & 1) {  // 1 is CRYPTO_LOCK\r
+    (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);\r
+  } else {\r
+    (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);\r
+  }\r
+}\r
+\r
+static unsigned long ssl_id_callback(void) {\r
+  return (unsigned long) pthread_self();\r
+}\r
+\r
+#if !defined(NO_SSL_DL)\r
+static int load_dll(struct mg_context *ctx, const char *dll_name,\r
+                    struct ssl_func *sw) {\r
+  union {void *p; void (*fp)(void);} u;\r
+  void  *dll_handle;\r
+  struct ssl_func *fp;\r
+\r
+  if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {\r
+    cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);\r
+    return 0;\r
+  }\r
+\r
+  for (fp = sw; fp->name != NULL; fp++) {\r
+#ifdef _WIN32\r
+    // GetProcAddress() returns pointer to function\r
+    u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);\r
+#else\r
+    // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to\r
+    // function pointers. We need to use a union to make a cast.\r
+    u.p = dlsym(dll_handle, fp->name);\r
+#endif // _WIN32\r
+    if (u.fp == NULL) {\r
+      cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);\r
+      return 0;\r
+    } else {\r
+      fp->ptr = u.fp;\r
+    }\r
+  }\r
+\r
+  return 1;\r
+}\r
+#endif // NO_SSL_DL\r
+\r
+// Dynamically load SSL library. Set up ctx->ssl_ctx pointer.\r
+static int set_ssl_option(struct mg_context *ctx) {\r
+  int i, size;\r
+  const char *pem;\r
+\r
+  // If PEM file is not specified, skip SSL initialization.\r
+  if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL) {\r
+    return 1;\r
+  }\r
+\r
+#if !defined(NO_SSL_DL)\r
+  if (!load_dll(ctx, SSL_LIB, ssl_sw) ||\r
+      !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {\r
+    return 0;\r
+  }\r
+#endif // NO_SSL_DL\r
+\r
+  // Initialize SSL library\r
+  SSL_library_init();\r
+  SSL_load_error_strings();\r
+\r
+  if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {\r
+    cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());\r
+    return 0;\r
+  }\r
+\r
+  // If user callback returned non-NULL, that means that user callback has\r
+  // set up certificate itself. In this case, skip sertificate setting.\r
+  if ((ctx->callbacks.init_ssl == NULL ||\r
+       !ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data)) &&\r
+      (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||\r
+       SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {\r
+    cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());\r
+    return 0;\r
+  }\r
+\r
+  if (pem != NULL) {\r
+    (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);\r
+  }\r
+\r
+  // Initialize locking callbacks, needed for thread safety.\r
+  // http://www.openssl.org/support/faq.html#PROG1\r
+  size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();\r
+  if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {\r
+    cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());\r
+    return 0;\r
+  }\r
+\r
+  for (i = 0; i < CRYPTO_num_locks(); i++) {\r
+    pthread_mutex_init(&ssl_mutexes[i], NULL);\r
+  }\r
+\r
+  CRYPTO_set_locking_callback(&ssl_locking_callback);\r
+  CRYPTO_set_id_callback(&ssl_id_callback);\r
+\r
+  return 1;\r
+}\r
+\r
+static void uninitialize_ssl(struct mg_context *ctx) {\r
+  int i;\r
+  if (ctx->ssl_ctx != NULL) {\r
+    CRYPTO_set_locking_callback(NULL);\r
+    for (i = 0; i < CRYPTO_num_locks(); i++) {\r
+      pthread_mutex_destroy(&ssl_mutexes[i]);\r
+    }\r
+    CRYPTO_set_locking_callback(NULL);\r
+    CRYPTO_set_id_callback(NULL);\r
+  }\r
+}\r
+#endif // !NO_SSL\r
+\r
+static int set_gpass_option(struct mg_context *ctx) {\r
+  struct file file = STRUCT_FILE_INITIALIZER;\r
+  const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];\r
+  if (path != NULL && !mg_stat(fc(ctx), path, &file)) {\r
+    cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));\r
+    return 0;\r
+  }\r
+  return 1;\r
+}\r
+\r
+static int set_acl_option(struct mg_context *ctx) {\r
+  return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;\r
+}\r
+\r
+static void reset_per_request_attributes(struct mg_connection *conn) {\r
+  conn->path_info = NULL;\r
+  conn->num_bytes_sent = conn->consumed_content = 0;\r
+  conn->status_code = -1;\r
+  conn->must_close = conn->request_len = conn->throttle = 0;\r
+}\r
+\r
+static void close_socket_gracefully(struct mg_connection *conn) {\r
+#if defined(_WIN32)\r
+  char buf[MG_BUF_LEN];\r
+  int n;\r
+#endif\r
+  struct linger linger;\r
+\r
+  // Set linger option to avoid socket hanging out after close. This prevent\r
+  // ephemeral port exhaust problem under high QPS.\r
+  linger.l_onoff = 1;\r
+  linger.l_linger = 1;\r
+  setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,\r
+             (char *) &linger, sizeof(linger));\r
+\r
+  // Send FIN to the client\r
+  shutdown(conn->client.sock, SHUT_WR);\r
+  set_non_blocking_mode(conn->client.sock);\r
+\r
+#if defined(_WIN32)\r
+  // Read and discard pending incoming data. If we do not do that and close the\r
+  // socket, the data in the send buffer may be discarded. This\r
+  // behaviour is seen on Windows, when client keeps sending data\r
+  // when server decides to close the connection; then when client\r
+  // does recv() it gets no data back.\r
+  do {\r
+    n = pull(NULL, conn, buf, sizeof(buf));\r
+  } while (n > 0);\r
+#endif\r
+\r
+  // Now we know that our FIN is ACK-ed, safe to close\r
+  closesocket(conn->client.sock);\r
+}\r
+\r
+static void close_connection(struct mg_connection *conn) {\r
+  conn->must_close = 1;\r
+\r
+#ifndef NO_SSL\r
+  if (conn->ssl != NULL) {\r
+    // Run SSL_shutdown twice to ensure completly close SSL connection\r
+    SSL_shutdown(conn->ssl);\r
+    SSL_shutdown(conn->ssl);\r
+    SSL_free(conn->ssl);\r
+    conn->ssl = NULL;\r
+  }\r
+#endif\r
+  if (conn->client.sock != INVALID_SOCKET) {\r
+    close_socket_gracefully(conn);\r
+    conn->client.sock = INVALID_SOCKET;\r
+  }\r
+}\r
+\r
+void mg_close_connection(struct mg_connection *conn) {\r
+#ifndef NO_SSL\r
+  if (conn->client_ssl_ctx != NULL) {\r
+    SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);\r
+  }\r
+#endif\r
+  close_connection(conn);\r
+  free(conn);\r
+}\r
+\r
+struct mg_connection *mg_connect(const char *host, int port, int use_ssl,\r
+                                 char *ebuf, size_t ebuf_len) {\r
+  static struct mg_context fake_ctx;\r
+  struct mg_connection *conn = NULL;\r
+  SOCKET sock;\r
+\r
+  if ((sock = conn2(host, port, use_ssl, ebuf, ebuf_len)) == INVALID_SOCKET) {\r
+  } else if ((conn = (struct mg_connection *)\r
+              calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {\r
+    snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));\r
+    closesocket(sock);\r
+#ifndef NO_SSL\r
+  } else if (use_ssl && (conn->client_ssl_ctx =\r
+                         SSL_CTX_new(SSLv23_client_method())) == NULL) {\r
+    snprintf(ebuf, ebuf_len, "SSL_CTX_new error");\r
+    closesocket(sock);\r
+    free(conn);\r
+    conn = NULL;\r
+#endif // NO_SSL\r
+  } else {\r
+    socklen_t len;\r
+    conn->buf_size = MAX_REQUEST_SIZE;\r
+    conn->buf = (char *) (conn + 1);\r
+    conn->ctx = &fake_ctx;\r
+    conn->client.sock = sock;\r
+    getsockname(sock, &conn->client.rsa.sa, &len);\r
+    conn->client.is_ssl = use_ssl;\r
+#ifndef NO_SSL\r
+    if (use_ssl) {\r
+      // SSL_CTX_set_verify call is needed to switch off server certificate\r
+      // checking, which is off by default in OpenSSL and on in yaSSL.\r
+      SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);\r
+      sslize(conn, conn->client_ssl_ctx, SSL_connect);\r
+    }\r
+#endif\r
+  }\r
+\r
+  return conn;\r
+}\r
+\r
+static int is_valid_uri(const char *uri) {\r
+  // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2\r
+  // URI can be an asterisk (*) or should start with slash.\r
+  return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');\r
+}\r
+\r
+static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len) {\r
+  const char *cl;\r
+\r
+  ebuf[0] = '\0';\r
+  reset_per_request_attributes(conn);\r
+  conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,\r
+                                   &conn->data_len);\r
+  assert(conn->request_len < 0 || conn->data_len >= conn->request_len);\r
+\r
+  if (conn->request_len == 0 && conn->data_len == conn->buf_size) {\r
+    snprintf(ebuf, ebuf_len, "%s", "Request Too Large");\r
+  } else if (conn->request_len <= 0) {\r
+    snprintf(ebuf, ebuf_len, "%s", "Client closed connection");\r
+  } else if (parse_http_message(conn->buf, conn->buf_size,\r
+                                &conn->request_info) <= 0) {\r
+    snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);\r
+  } else {\r
+    // Request is valid\r
+    if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {\r
+      conn->content_len = strtoll(cl, NULL, 10);\r
+    } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||\r
+               !mg_strcasecmp(conn->request_info.request_method, "PUT")) {\r
+      conn->content_len = -1;\r
+    } else {\r
+      conn->content_len = 0;\r
+    }\r
+    conn->birth_time = time(NULL);\r
+  }\r
+  return ebuf[0] == '\0';\r
+}\r
+\r
+struct mg_connection *mg_download(const char *host, int port, int use_ssl,\r
+                                  char *ebuf, size_t ebuf_len,\r
+                                  const char *fmt, ...) {\r
+  struct mg_connection *conn;\r
+  va_list ap;\r
+\r
+  va_start(ap, fmt);\r
+  ebuf[0] = '\0';\r
+  if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {\r
+  } else if (mg_vprintf(conn, fmt, ap) <= 0) {\r
+    snprintf(ebuf, ebuf_len, "%s", "Error sending request");\r
+  } else {\r
+    getreq(conn, ebuf, ebuf_len);\r
+  }\r
+  if (ebuf[0] != '\0' && conn != NULL) {\r
+    mg_close_connection(conn);\r
+    conn = NULL;\r
+  }\r
+\r
+  return conn;\r
+}\r
+\r
+static void process_new_connection(struct mg_connection *conn) {\r
+  struct mg_request_info *ri = &conn->request_info;\r
+  int keep_alive_enabled, keep_alive, discard_len;\r
+  char ebuf[100];\r
+\r
+  keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");\r
+  keep_alive = 0;\r
+\r
+  // Important: on new connection, reset the receiving buffer. Credit goes\r
+  // to crule42.\r
+  conn->data_len = 0;\r
+  do {\r
+    if (!getreq(conn, ebuf, sizeof(ebuf))) {\r
+      send_http_error(conn, 500, "Server Error", "%s", ebuf);\r
+      conn->must_close = 1;\r
+    } else if (!is_valid_uri(conn->request_info.uri)) {\r
+      snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);\r
+      send_http_error(conn, 400, "Bad Request", "%s", ebuf);\r
+    } else if (strcmp(ri->http_version, "1.0") &&\r
+               strcmp(ri->http_version, "1.1")) {\r
+      snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version);\r
+      send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf);\r
+    }\r
+\r
+    if (ebuf[0] == '\0') {\r
+      handle_request(conn);\r
+      if (conn->ctx->callbacks.end_request != NULL) {\r
+        conn->ctx->callbacks.end_request(conn, conn->status_code);\r
+      }\r
+      log_access(conn);\r
+    }\r
+    if (ri->remote_user != NULL) {\r
+      free((void *) ri->remote_user);\r
+      ri->remote_user = NULL; // when having connections with and without auth would cause double free and then crash\r
+    }\r
+\r
+    // NOTE(lsm): order is important here. should_keep_alive() call\r
+    // is using parsed request, which will be invalid after memmove's below.\r
+    // Therefore, memorize should_keep_alive() result now for later use\r
+    // in loop exit condition.\r
+    keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&\r
+      conn->content_len >= 0 && should_keep_alive(conn);\r
+\r
+    // Discard all buffered data for this request\r
+    discard_len = conn->content_len >= 0 && conn->request_len > 0 &&\r
+      conn->request_len + conn->content_len < (int64_t) conn->data_len ?\r
+      (int) (conn->request_len + conn->content_len) : conn->data_len;\r
+    assert(discard_len >= 0);\r
+    memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);\r
+    conn->data_len -= discard_len;\r
+    assert(conn->data_len >= 0);\r
+    assert(conn->data_len <= conn->buf_size);\r
+  } while (keep_alive);\r
+}\r
+\r
+// Worker threads take accepted socket from the queue\r
+static int consume_socket(struct mg_context *ctx, struct socket *sp) {\r
+  (void) pthread_mutex_lock(&ctx->mutex);\r
+  DEBUG_TRACE(("going idle"));\r
+\r
+  // If the queue is empty, wait. We're idle at this point.\r
+  while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {\r
+    pthread_cond_wait(&ctx->sq_full, &ctx->mutex);\r
+  }\r
+\r
+  // If we're stopping, sq_head may be equal to sq_tail.\r
+  if (ctx->sq_head > ctx->sq_tail) {\r
+    // Copy socket from the queue and increment tail\r
+    *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];\r
+    ctx->sq_tail++;\r
+    DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));\r
+\r
+    // Wrap pointers if needed\r
+    while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {\r
+      ctx->sq_tail -= ARRAY_SIZE(ctx->queue);\r
+      ctx->sq_head -= ARRAY_SIZE(ctx->queue);\r
+    }\r
+  }\r
+\r
+  (void) pthread_cond_signal(&ctx->sq_empty);\r
+  (void) pthread_mutex_unlock(&ctx->mutex);\r
+\r
+  return !ctx->stop_flag;\r
+}\r
+\r
+static void *worker_thread(void *thread_func_param) {\r
+  struct mg_context *ctx = thread_func_param;\r
+  struct mg_connection *conn;\r
+\r
+  conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);\r
+  if (conn == NULL) {\r
+    cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");\r
+  } else {\r
+    conn->buf_size = MAX_REQUEST_SIZE;\r
+    conn->buf = (char *) (conn + 1);\r
+    conn->ctx = ctx;\r
+    conn->request_info.user_data = ctx->user_data;\r
+\r
+    // Call consume_socket() even when ctx->stop_flag > 0, to let it signal\r
+    // sq_empty condvar to wake up the master waiting in produce_socket()\r
+    while (consume_socket(ctx, &conn->client)) {\r
+      conn->birth_time = time(NULL);\r
+\r
+      // Fill in IP, port info early so even if SSL setup below fails,\r
+      // error handler would have the corresponding info.\r
+      // Thanks to Johannes Winkelmann for the patch.\r
+      // TODO(lsm): Fix IPv6 case\r
+      conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);\r
+      memcpy(&conn->request_info.remote_ip,\r
+             &conn->client.rsa.sin.sin_addr.s_addr, 4);\r
+      conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);\r
+      conn->request_info.is_ssl = conn->client.is_ssl;\r
+\r
+      if (!conn->client.is_ssl\r
+#ifndef NO_SSL\r
+          || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)\r
+#endif\r
+         ) {\r
+        process_new_connection(conn);\r
+      }\r
+\r
+      close_connection(conn);\r
+    }\r
+    free(conn);\r
+  }\r
+\r
+  // Signal master that we're done with connection and exiting\r
+  (void) pthread_mutex_lock(&ctx->mutex);\r
+  ctx->num_threads--;\r
+  (void) pthread_cond_signal(&ctx->cond);\r
+  assert(ctx->num_threads >= 0);\r
+  (void) pthread_mutex_unlock(&ctx->mutex);\r
+\r
+  DEBUG_TRACE(("exiting"));\r
+  return NULL;\r
+}\r
+\r
+// Master thread adds accepted socket to a queue\r
+static void produce_socket(struct mg_context *ctx, const struct socket *sp) {\r
+  (void) pthread_mutex_lock(&ctx->mutex);\r
+\r
+  // If the queue is full, wait\r
+  while (ctx->stop_flag == 0 &&\r
+         ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {\r
+    (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);\r
+  }\r
+\r
+  if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {\r
+    // Copy socket to the queue and increment head\r
+    ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;\r
+    ctx->sq_head++;\r
+    DEBUG_TRACE(("queued socket %d", sp->sock));\r
+  }\r
+\r
+  (void) pthread_cond_signal(&ctx->sq_full);\r
+  (void) pthread_mutex_unlock(&ctx->mutex);\r
+}\r
+\r
+static int set_sock_timeout(SOCKET sock, int milliseconds) {\r
+#ifdef _WIN32\r
+  DWORD t = milliseconds;\r
+#else\r
+  struct timeval t;\r
+  t.tv_sec = milliseconds / 1000;\r
+  t.tv_usec = (milliseconds * 1000) % 1000000;\r
+#endif\r
+  return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *) &t, sizeof(t)) ||\r
+    setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *) &t, sizeof(t));\r
+}\r
+\r
+static void accept_new_connection(const struct socket *listener,\r
+                                  struct mg_context *ctx) {\r
+  struct socket so;\r
+  char src_addr[20];\r
+  socklen_t len = sizeof(so.rsa);\r
+  int on = 1;\r
+\r
+  if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {\r
+  } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {\r
+    sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);\r
+    cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);\r
+    closesocket(so.sock);\r
+  } else {\r
+    // Put so socket structure into the queue\r
+    DEBUG_TRACE(("Accepted socket %d", (int) so.sock));\r
+    so.is_ssl = listener->is_ssl;\r
+    so.ssl_redir = listener->ssl_redir;\r
+    getsockname(so.sock, &so.lsa.sa, &len);\r
+    // Set TCP keep-alive. This is needed because if HTTP-level keep-alive\r
+    // is enabled, and client resets the connection, server won't get\r
+    // TCP FIN or RST and will keep the connection open forever. With TCP\r
+    // keep-alive, next keep-alive handshake will figure out that the client\r
+    // is down and will close the server end.\r
+    // Thanks to Igor Klopov who suggested the patch.\r
+    setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on, sizeof(on));\r
+    set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));\r
+    produce_socket(ctx, &so);\r
+  }\r
+}\r
+\r
+static void *master_thread(void *thread_func_param) {\r
+  struct mg_context *ctx = thread_func_param;\r
+  struct pollfd *pfd;\r
+  int i;\r
+\r
+  // Increase priority of the master thread\r
+#if defined(_WIN32)\r
+  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);\r
+#endif\r
+\r
+#if defined(ISSUE_317)\r
+  struct sched_param sched_param;\r
+  sched_param.sched_priority = sched_get_priority_max(SCHED_RR);\r
+  pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);\r
+#endif\r
+\r
+  pfd = calloc(ctx->num_listening_sockets, sizeof(pfd[0]));\r
+  while (pfd != NULL && ctx->stop_flag == 0) {\r
+    for (i = 0; i < ctx->num_listening_sockets; i++) {\r
+      pfd[i].fd = ctx->listening_sockets[i].sock;\r
+      pfd[i].events = POLLIN;\r
+    }\r
+\r
+    if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {\r
+      for (i = 0; i < ctx->num_listening_sockets; i++) {\r
+        // NOTE(lsm): on QNX, poll() returns POLLRDNORM after the\r
+        // successfull poll, and POLLIN is defined as (POLLRDNORM | POLLRDBAND)\r
+        // Therefore, we're checking pfd[i].revents & POLLIN, not\r
+        // pfd[i].revents == POLLIN.\r
+        if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {\r
+          accept_new_connection(&ctx->listening_sockets[i], ctx);\r
+        }\r
+      }\r
+    }\r
+  }\r
+  free(pfd);\r
+  DEBUG_TRACE(("stopping workers"));\r
+\r
+  // Stop signal received: somebody called mg_stop. Quit.\r
+  close_all_listening_sockets(ctx);\r
+\r
+  // Wakeup workers that are waiting for connections to handle.\r
+  pthread_cond_broadcast(&ctx->sq_full);\r
+\r
+  // Wait until all threads finish\r
+  (void) pthread_mutex_lock(&ctx->mutex);\r
+  while (ctx->num_threads > 0) {\r
+    (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);\r
+  }\r
+  (void) pthread_mutex_unlock(&ctx->mutex);\r
+\r
+  // All threads exited, no sync is needed. Destroy mutex and condvars\r
+  (void) pthread_mutex_destroy(&ctx->mutex);\r
+  (void) pthread_cond_destroy(&ctx->cond);\r
+  (void) pthread_cond_destroy(&ctx->sq_empty);\r
+  (void) pthread_cond_destroy(&ctx->sq_full);\r
+\r
+#if !defined(NO_SSL)\r
+  uninitialize_ssl(ctx);\r
+#endif\r
+  DEBUG_TRACE(("exiting"));\r
+\r
+  // Signal mg_stop() that we're done.\r
+  // WARNING: This must be the very last thing this\r
+  // thread does, as ctx becomes invalid after this line.\r
+  ctx->stop_flag = 2;\r
+  return NULL;\r
+}\r
+\r
+static void free_context(struct mg_context *ctx) {\r
+  int i;\r
+\r
+  // Deallocate config parameters\r
+  for (i = 0; i < NUM_OPTIONS; i++) {\r
+    if (ctx->config[i] != NULL)\r
+      free(ctx->config[i]);\r
+  }\r
+\r
+#ifndef NO_SSL\r
+  // Deallocate SSL context\r
+  if (ctx->ssl_ctx != NULL) {\r
+    SSL_CTX_free(ctx->ssl_ctx);\r
+  }\r
+  if (ssl_mutexes != NULL) {\r
+    free(ssl_mutexes);\r
+    ssl_mutexes = NULL;\r
+  }\r
+#endif // !NO_SSL\r
+\r
+  // Deallocate context itself\r
+  free(ctx);\r
+}\r
+\r
+void mg_stop(struct mg_context *ctx) {\r
+  ctx->stop_flag = 1;\r
+\r
+  // Wait until mg_fini() stops\r
+  while (ctx->stop_flag != 2) {\r
+    (void) mg_sleep(10);\r
+  }\r
+  free_context(ctx);\r
+\r
+#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
+  (void) WSACleanup();\r
+#endif // _WIN32\r
+}\r
+\r
+struct mg_context *mg_start(const struct mg_callbacks *callbacks,\r
+                            void *user_data,\r
+                            const char **options) {\r
+  struct mg_context *ctx;\r
+  const char *name, *value, *default_value;\r
+  int i;\r
+\r
+#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
+  WSADATA data;\r
+  WSAStartup(MAKEWORD(2,2), &data);\r
+  InitializeCriticalSection(&global_log_file_lock);\r
+#endif // _WIN32\r
+\r
+  // Allocate context and initialize reasonable general case defaults.\r
+  // TODO(lsm): do proper error handling here.\r
+  if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {\r
+    return NULL;\r
+  }\r
+  ctx->callbacks = *callbacks;\r
+  ctx->user_data = user_data;\r
+\r
+  while (options && (name = *options++) != NULL) {\r
+    if ((i = get_option_index(name)) == -1) {\r
+      cry(fc(ctx), "Invalid option: %s", name);\r
+      free_context(ctx);\r
+      return NULL;\r
+    } else if ((value = *options++) == NULL) {\r
+      cry(fc(ctx), "%s: option value cannot be NULL", name);\r
+      free_context(ctx);\r
+      return NULL;\r
+    }\r
+    if (ctx->config[i] != NULL) {\r
+      cry(fc(ctx), "warning: %s: duplicate option", name);\r
+      free(ctx->config[i]);\r
+    }\r
+    ctx->config[i] = mg_strdup(value);\r
+    DEBUG_TRACE(("[%s] -> [%s]", name, value));\r
+  }\r
+\r
+  // Set default value if needed\r
+  for (i = 0; config_options[i * 2] != NULL; i++) {\r
+    default_value = config_options[i * 2 + 1];\r
+    if (ctx->config[i] == NULL && default_value != NULL) {\r
+      ctx->config[i] = mg_strdup(default_value);\r
+    }\r
+  }\r
+\r
+  // NOTE(lsm): order is important here. SSL certificates must\r
+  // be initialized before listening ports. UID must be set last.\r
+  if (!set_gpass_option(ctx) ||\r
+#if !defined(NO_SSL)\r
+      !set_ssl_option(ctx) ||\r
+#endif\r
+      !set_ports_option(ctx) ||\r
+#if !defined(_WIN32)\r
+      !set_uid_option(ctx) ||\r
+#endif\r
+      !set_acl_option(ctx)) {\r
+    free_context(ctx);\r
+    return NULL;\r
+  }\r
+\r
+#if !defined(_WIN32) && !defined(__SYMBIAN32__)\r
+  // Ignore SIGPIPE signal, so if browser cancels the request, it\r
+  // won't kill the whole process.\r
+  (void) signal(SIGPIPE, SIG_IGN);\r
+  // Also ignoring SIGCHLD to let the OS to reap zombies properly.\r
+  (void) signal(SIGCHLD, SIG_IGN);\r
+#endif // !_WIN32\r
+\r
+  (void) pthread_mutex_init(&ctx->mutex, NULL);\r
+  (void) pthread_cond_init(&ctx->cond, NULL);\r
+  (void) pthread_cond_init(&ctx->sq_empty, NULL);\r
+  (void) pthread_cond_init(&ctx->sq_full, NULL);\r
+\r
+  // Start master (listening) thread\r
+  mg_start_thread(master_thread, ctx);\r
+\r
+  // Start worker threads\r
+  for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) {\r
+    if (mg_start_thread(worker_thread, ctx) != 0) {\r
+      cry(fc(ctx), "Cannot start worker thread: %ld", (long) ERRNO);\r
+    } else {\r
+      ctx->num_threads++;\r
+    }\r
+  }\r
+\r
+  return ctx;\r
+}\r
diff --git a/mongoose.h b/mongoose.h
new file mode 100644 (file)
index 0000000..00c33f1
--- /dev/null
@@ -0,0 +1,361 @@
+/*\r
+Copyright (c) 2013 Intel Corporation.\r
+\r
+Redistribution and use in source and binary forms, with or without modification,\r
+are permitted provided that the following conditions are met:\r
+\r
+* Redistributions of works must retain the original copyright notice, this list\r
+  of conditions and the following disclaimer.\r
+* Redistributions in binary form must reproduce the original copyright notice,\r
+  this list of conditions and the following disclaimer in the documentation\r
+  and/or other materials provided with the distribution.\r
+* Neither the name of Intel Corporation nor the names of its contributors\r
+  may be used to endorse or promote products derived from this work without\r
+  specific prior written permission.\r
+\r
+THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"\r
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,\r
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\r
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\r
+OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\r
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+Authors:\r
+        Wang, Jing J <jing.j.wang@intel.com>\r
+\r
+*/\r
+\r
+#ifndef MONGOOSE_HEADER_INCLUDED\r
+#define  MONGOOSE_HEADER_INCLUDED\r
+\r
+#include <stdio.h>\r
+#include <stddef.h>\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif // __cplusplus\r
+\r
+struct mg_context;     // Handle for the HTTP service itself\r
+struct mg_connection;  // Handle for the individual connection\r
+\r
+\r
+// This structure contains information about the HTTP request.\r
+struct mg_request_info {\r
+  const char *request_method; // "GET", "POST", etc\r
+  const char *uri;            // URL-decoded URI\r
+  const char *http_version;   // E.g. "1.0", "1.1"\r
+  const char *query_string;   // URL part after '?', not including '?', or NULL\r
+  const char *remote_user;    // Authenticated user, or NULL if no auth used\r
+  long remote_ip;             // Client's IP address\r
+  int remote_port;            // Client's port\r
+  int is_ssl;                 // 1 if SSL-ed, 0 if not\r
+  void *user_data;            // User data pointer passed to mg_start()\r
+\r
+  int num_headers;            // Number of HTTP headers\r
+  struct mg_header {\r
+    const char *name;         // HTTP header name\r
+    const char *value;        // HTTP header value\r
+  } http_headers[64];         // Maximum 64 headers\r
+};\r
+\r
+\r
+// This structure needs to be passed to mg_start(), to let mongoose know\r
+// which callbacks to invoke. For detailed description, see\r
+// https://github.com/valenok/mongoose/blob/master/UserManual.md\r
+struct mg_callbacks {\r
+  // Called when mongoose has received new HTTP request.\r
+  // If callback returns non-zero,\r
+  // callback must process the request by sending valid HTTP headers and body,\r
+  // and mongoose will not do any further processing.\r
+  // If callback returns 0, mongoose processes the request itself. In this case,\r
+  // callback must not send any data to the client.\r
+  int  (*begin_request)(struct mg_connection *);\r
+\r
+  // Called when mongoose has finished processing request.\r
+  void (*end_request)(const struct mg_connection *, int reply_status_code);\r
+\r
+  // Called when mongoose is about to log a message. If callback returns\r
+  // non-zero, mongoose does not log anything.\r
+  int  (*log_message)(const struct mg_connection *, const char *message);\r
+\r
+  // Called when mongoose initializes SSL library.\r
+  int  (*init_ssl)(void *ssl_context, void *user_data);\r
+\r
+  // Called when websocket request is received, before websocket handshake.\r
+  // If callback returns 0, mongoose proceeds with handshake, otherwise\r
+  // cinnection is closed immediately.\r
+  int (*websocket_connect)(const struct mg_connection *);\r
+\r
+  // Called when websocket handshake is successfully completed, and\r
+  // connection is ready for data exchange.\r
+  void (*websocket_ready)(struct mg_connection *);\r
+\r
+  // Called when data frame has been received from the client.\r
+  // Parameters:\r
+  //    bits: first byte of the websocket frame, see websocket RFC at\r
+  //          http://tools.ietf.org/html/rfc6455, section 5.2\r
+  //    data, data_len: payload, with mask (if any) already applied.\r
+  // Return value:\r
+  //    0:     keep this websocket connection opened.\r
+  //    non-0: close this websocket connection.\r
+  int  (*websocket_data)(struct mg_connection *, int bits,\r
+                         char *data, size_t data_len);\r
+\r
+  // Called when mongoose tries to open a file. Used to intercept file open\r
+  // calls, and serve file data from memory instead.\r
+  // Parameters:\r
+  //    path:     Full path to the file to open.\r
+  //    data_len: Placeholder for the file size, if file is served from memory.\r
+  // Return value:\r
+  //    NULL: do not serve file from memory, proceed with normal file open.\r
+  //    non-NULL: pointer to the file contents in memory. data_len must be\r
+  //              initilized with the size of the memory block.\r
+  const char * (*open_file)(const struct mg_connection *,\r
+                             const char *path, size_t *data_len);\r
+\r
+  // Called when mongoose is about to serve Lua server page (.lp file), if\r
+  // Lua support is enabled.\r
+  // Parameters:\r
+  //   lua_context: "lua_State *" pointer.\r
+  void (*init_lua)(struct mg_connection *, void *lua_context);\r
+\r
+  // Called when mongoose has uploaded a file to a temporary directory as a\r
+  // result of mg_upload() call.\r
+  // Parameters:\r
+  //    file_file: full path name to the uploaded file.\r
+  void (*upload)(struct mg_connection *, const char *file_name);\r
+\r
+  // Called when mongoose is about to send HTTP error to the client.\r
+  // Implementing this callback allows to create custom error pages.\r
+  // Parameters:\r
+  //   status: HTTP error status code.\r
+  int  (*http_error)(struct mg_connection *, int status);\r
+};\r
+\r
+// Start web server.\r
+//\r
+// Parameters:\r
+//   callbacks: mg_callbacks structure with user-defined callbacks.\r
+//   options: NULL terminated list of option_name, option_value pairs that\r
+//            specify Mongoose configuration parameters.\r
+//\r
+// Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom\r
+//    processing is required for these, signal handlers must be set up\r
+//    after calling mg_start().\r
+//\r
+//\r
+// Example:\r
+//   const char *options[] = {\r
+//     "document_root", "/var/www",\r
+//     "listening_ports", "80,443s",\r
+//     NULL\r
+//   };\r
+//   struct mg_context *ctx = mg_start(&my_func, NULL, options);\r
+//\r
+// Refer to https://github.com/valenok/mongoose/blob/master/UserManual.md\r
+// for the list of valid option and their possible values.\r
+//\r
+// Return:\r
+//   web server context, or NULL on error.\r
+struct mg_context *mg_start(const struct mg_callbacks *callbacks,\r
+                            void *user_data,\r
+                            const char **configuration_options);\r
+\r
+\r
+// Stop the web server.\r
+//\r
+// Must be called last, when an application wants to stop the web server and\r
+// release all associated resources. This function blocks until all Mongoose\r
+// threads are stopped. Context pointer becomes invalid.\r
+void mg_stop(struct mg_context *);\r
+\r
+\r
+// Get the value of particular configuration parameter.\r
+// The value returned is read-only. Mongoose does not allow changing\r
+// configuration at run time.\r
+// If given parameter name is not valid, NULL is returned. For valid\r
+// names, return value is guaranteed to be non-NULL. If parameter is not\r
+// set, zero-length string is returned.\r
+const char *mg_get_option(const struct mg_context *ctx, const char *name);\r
+\r
+\r
+// Return array of strings that represent valid configuration options.\r
+// For each option, a short name, long name, and default value is returned.\r
+// Array is NULL terminated.\r
+const char **mg_get_valid_option_names(void);\r
+\r
+\r
+// Add, edit or delete the entry in the passwords file.\r
+//\r
+// This function allows an application to manipulate .htpasswd files on the\r
+// fly by adding, deleting and changing user records. This is one of the\r
+// several ways of implementing authentication on the server side. For another,\r
+// cookie-based way please refer to the examples/chat.c in the source tree.\r
+//\r
+// If password is not NULL, entry is added (or modified if already exists).\r
+// If password is NULL, entry is deleted.\r
+//\r
+// Return:\r
+//   1 on success, 0 on error.\r
+int mg_modify_passwords_file(const char *passwords_file_name,\r
+                             const char *domain,\r
+                             const char *user,\r
+                             const char *password);\r
+\r
+\r
+// Return information associated with the request.\r
+struct mg_request_info *mg_get_request_info(struct mg_connection *);\r
+\r
+\r
+// Send data to the client.\r
+// Return:\r
+//  0   when the connection has been closed\r
+//  -1  on error\r
+//  >0  number of bytes written on success\r
+int mg_write(struct mg_connection *, const void *buf, size_t len);\r
+\r
+\r
+// Macros for enabling compiler-specific checks for printf-like arguments.\r
+#undef PRINTF_FORMAT_STRING\r
+#if _MSC_VER >= 1400\r
+#include <sal.h>\r
+#if _MSC_VER > 1400\r
+#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s\r
+#else\r
+#define PRINTF_FORMAT_STRING(s) __format_string s\r
+#endif\r
+#else\r
+#define PRINTF_FORMAT_STRING(s) s\r
+#endif\r
+\r
+#ifdef __GNUC__\r
+#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))\r
+#else\r
+#define PRINTF_ARGS(x, y)\r
+#endif\r
+\r
+// Send data to the client using printf() semantics.\r
+//\r
+// Works exactly like mg_write(), but allows to do message formatting.\r
+int mg_printf(struct mg_connection *,\r
+              PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);\r
+\r
+\r
+// Send contents of the entire file together with HTTP headers.\r
+void mg_send_file(struct mg_connection *conn, const char *path);\r
+\r
+\r
+// Read data from the remote end, return number of bytes read.\r
+int mg_read(struct mg_connection *, void *buf, size_t len);\r
+\r
+\r
+// Get the value of particular HTTP header.\r
+//\r
+// This is a helper function. It traverses request_info->http_headers array,\r
+// and if the header is present in the array, returns its value. If it is\r
+// not present, NULL is returned.\r
+const char *mg_get_header(const struct mg_connection *, const char *name);\r
+\r
+\r
+// Get a value of particular form variable.\r
+//\r
+// Parameters:\r
+//   data: pointer to form-uri-encoded buffer. This could be either POST data,\r
+//         or request_info.query_string.\r
+//   data_len: length of the encoded data.\r
+//   var_name: variable name to decode from the buffer\r
+//   dst: destination buffer for the decoded variable\r
+//   dst_len: length of the destination buffer\r
+//\r
+// Return:\r
+//   On success, length of the decoded variable.\r
+//   On error:\r
+//      -1 (variable not found).\r
+//      -2 (destination buffer is NULL, zero length or too small to hold the\r
+//          decoded variable).\r
+//\r
+// Destination buffer is guaranteed to be '\0' - terminated if it is not\r
+// NULL or zero length.\r
+int mg_get_var(const char *data, size_t data_len,\r
+               const char *var_name, char *dst, size_t dst_len);\r
+\r
+// Fetch value of certain cookie variable into the destination buffer.\r
+//\r
+// Destination buffer is guaranteed to be '\0' - terminated. In case of\r
+// failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same\r
+// parameter. This function returns only first occurrence.\r
+//\r
+// Return:\r
+//   On success, value length.\r
+//   On error:\r
+//      -1 (either "Cookie:" header is not present at all or the requested\r
+//          parameter is not found).\r
+//      -2 (destination buffer is NULL, zero length or too small to hold the\r
+//          value).\r
+int mg_get_cookie(const char *cookie, const char *var_name,\r
+                  char *buf, size_t buf_len);\r
+\r
+\r
+// Download data from the remote web server.\r
+//   host: host name to connect to, e.g. "foo.com", or "10.12.40.1".\r
+//   port: port number, e.g. 80.\r
+//   use_ssl: wether to use SSL connection.\r
+//   error_buffer, error_buffer_size: error message placeholder.\r
+//   request_fmt,...: HTTP request.\r
+// Return:\r
+//   On success, valid pointer to the new connection, suitable for mg_read().\r
+//   On error, NULL. error_buffer contains error message.\r
+// Example:\r
+//   char ebuf[100];\r
+//   struct mg_connection *conn;\r
+//   conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),\r
+//                      "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");\r
+struct mg_connection *mg_download(const char *host, int port, int use_ssl,\r
+                                  char *error_buffer, size_t error_buffer_size,\r
+                                  PRINTF_FORMAT_STRING(const char *request_fmt),\r
+                                  ...) PRINTF_ARGS(6, 7);\r
+\r
+\r
+// Close the connection opened by mg_download().\r
+void mg_close_connection(struct mg_connection *conn);\r
+\r
+\r
+// File upload functionality. Each uploaded file gets saved into a temporary\r
+// file and MG_UPLOAD event is sent.\r
+// Return number of uploaded files.\r
+int mg_upload(struct mg_connection *conn, const char *destination_dir);\r
+\r
+\r
+// Convenience function -- create detached thread.\r
+// Return: 0 on success, non-0 on error.\r
+typedef void * (*mg_thread_func_t)(void *);\r
+int mg_start_thread(mg_thread_func_t f, void *p);\r
+\r
+\r
+// Return builtin mime type for the given file name.\r
+// For unrecognized extensions, "text/plain" is returned.\r
+const char *mg_get_builtin_mime_type(const char *file_name);\r
+\r
+\r
+// Return Mongoose version.\r
+const char *mg_version(void);\r
+\r
+\r
+// MD5 hash given strings.\r
+// Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of\r
+// ASCIIz strings. When function returns, buf will contain human-readable\r
+// MD5 hash. Example:\r
+//   char buf[33];\r
+//   mg_md5(buf, "aa", "bb", NULL);\r
+char *mg_md5(char buf[33], ...);\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif // __cplusplus\r
+\r
+#endif // MONGOOSE_HEADER_INCLUDED\r
diff --git a/tinyweb.c b/tinyweb.c
new file mode 100644 (file)
index 0000000..10909b4
--- /dev/null
+++ b/tinyweb.c
@@ -0,0 +1,349 @@
+/*\r
+Copyright (c) 2013 Intel Corporation.\r
+\r
+Redistribution and use in source and binary forms, with or without modification,\r
+are permitted provided that the following conditions are met:\r
+\r
+* Redistributions of works must retain the original copyright notice, this list\r
+  of conditions and the following disclaimer.\r
+* Redistributions in binary form must reproduce the original copyright notice,\r
+  this list of conditions and the following disclaimer in the documentation\r
+  and/or other materials provided with the distribution.\r
+* Neither the name of Intel Corporation nor the names of its contributors\r
+  may be used to endorse or promote products derived from this work without\r
+  specific prior written permission.\r
+\r
+THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"\r
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r
+ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,\r
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\r
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\r
+OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\r
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+Authors:\r
+        Wang, Jing J <jing.j.wang@intel.com>\r
+\r
+*/\r
+\r
+#define _XOPEN_SOURCE 600  // For PATH_MAX on linux\r
+\r
+#include <sys/stat.h>\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <signal.h>\r
+#include <string.h>\r
+#include <errno.h>\r
+#include <limits.h>\r
+#include <stddef.h>\r
+#include <stdarg.h>\r
+#include <ctype.h>\r
+#include <dlfcn.h>\r
+#include "mongoose.h"\r
+\r
+#include <sys/wait.h>\r
+#include <unistd.h>\r
+#include <sys/stat.h>\r
+\r
+#define DIRSEP '/'\r
+#define WINCDECL\r
+\r
+#define MAX_OPTIONS 40\r
+#define MAX_CONF_FILE_LINE_SIZE (8 * 1024)\r
+\r
+static int exit_flag;\r
+static char server_name[40];        // Set by init_server_name()\r
+static char config_file[PATH_MAX];  // Set by process_command_line_arguments()\r
+static struct mg_context *ctx;      // Set by start_server()\r
+\r
+#if !defined(CONFIG_FILE)\r
+#define CONFIG_FILE "mongoose.conf"\r
+#endif /* !CONFIG_FILE */\r
+\r
+static void *get_app(struct mg_connection *conn) {\r
+  char app_name[128];\r
+  const char *uri = mg_get_request_info(conn)->uri;\r
+  if (strcmp(uri, "/") == 0){\r
+    snprintf(app_name, sizeof(app_name), "/usr/lib%secho.so", uri);\r
+  }else{\r
+    snprintf(app_name, sizeof(app_name), "/usr/lib%s.so", uri);\r
+  }\r
+//  printf("app_name=%s\n", app_name);\r
+  void *ws_handle = NULL;\r
+  if ((ws_handle = dlopen(app_name, RTLD_LAZY)) == NULL) {\r
+    fprintf(stderr, "%s: cannot load %s\n", __func__, app_name);\r
+    return NULL;\r
+  }\r
+  return ws_handle;\r
+}\r
+\r
+static void websocket_ready_handler(struct mg_connection *conn){\r
+  const char *prot = mg_get_header(conn, "Sec-WebSocket-Protocol");\r
+  char buf[100];\r
+  if (prot){\r
+      char *p = NULL;\r
+      snprintf(buf, sizeof(buf), "%s", prot);\r
+      if ((p = strrchr(buf, ',')) != NULL) {\r
+        *p = '\0';\r
+      } \r
+      mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n", buf);\r
+  }\r
+  mg_printf(conn, "\r\n");\r
+}\r
+\r
+\r
+// Arguments:\r
+//   flags: first byte of websocket frame, see websocket RFC,\r
+//          http://tools.ietf.org/html/rfc6455, section 5.2\r
+//   data, data_len: payload data. Mask, if any, is already applied.\r
+static int websocket_data_handler(struct mg_connection *conn, int flags,\r
+                                  char *data, size_t data_len){\r
+  void *ws_handle = get_app(conn);\r
+  if (ws_handle == NULL) {\r
+    return 0;\r
+  }\r
+  int (*func)(struct mg_connection *, int, char *, size_t) = dlsym(ws_handle, "websocket_data");\r
+  if (func == NULL){\r
+    dlclose(ws_handle);\r
+    return 0; \r
+  }\r
+  int ret = (*func)(conn, flags, data, data_len);\r
+  dlclose(ws_handle);\r
+  return ret; \r
+}\r
+\r
+static void WINCDECL signal_handler(int sig_num) {\r
+  exit_flag = sig_num;\r
+}\r
+\r
+\r
+static void die(const char *fmt, ...) {\r
+  va_list ap;\r
+  char msg[200];\r
+\r
+  va_start(ap, fmt);\r
+  vsnprintf(msg, sizeof(msg), fmt, ap);\r
+  va_end(ap);\r
+\r
+  fprintf(stderr, "%s\n", msg);\r
+\r
+  exit(EXIT_FAILURE);\r
+}\r
+\r
+static void show_usage_and_exit(void) {\r
+  const char **names;\r
+  int i;\r
+\r
+  fprintf(stderr, "Tinyweb version %s (c) jing wang, built on %s\n",\r
+          mg_version(), __DATE__);\r
+  fprintf(stderr, "Usage:\n");\r
+  fprintf(stderr, "  tinyweb -A <htpasswd_file> <realm> <user> <passwd>\n");\r
+  fprintf(stderr, "  tinyweb [config_file]\n");\r
+  fprintf(stderr, "  tinyweb [-option value ...]\n");\r
+  fprintf(stderr, "\nOPTIONS:\n");\r
+\r
+  names = mg_get_valid_option_names();\r
+  for (i = 0; names[i] != NULL; i += 2) {\r
+    fprintf(stderr, "  -%s %s\n",\r
+            names[i], names[i + 1] == NULL ? "<empty>" : names[i + 1]);\r
+  }\r
+  exit(EXIT_FAILURE);\r
+}\r
+\r
+static void verify_document_root(const char *root) {\r
+  const char *p, *path;\r
+  char buf[PATH_MAX];\r
+  struct stat st;\r
+\r
+  path = root;\r
+  if ((p = strchr(root, ',')) != NULL && (size_t) (p - root) < sizeof(buf)) {\r
+    memcpy(buf, root, p - root);\r
+    buf[p - root] = '\0';\r
+    path = buf;\r
+  }\r
+\r
+  if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) {\r
+    die("Invalid root directory: [%s]: %s", root, strerror(errno));\r
+  }\r
+}\r
+\r
+static char *sdup(const char *str) {\r
+  char *p;\r
+  if ((p = (char *) malloc(strlen(str) + 1)) != NULL) {\r
+    strcpy(p, str);\r
+  }\r
+  return p;\r
+}\r
+\r
+static void set_option(char **options, const char *name, const char *value) {\r
+  int i;\r
+\r
+  if (!strcmp(name, "document_root") || !(strcmp(name, "r"))) {\r
+    verify_document_root(value);\r
+  }\r
+\r
+  for (i = 0; i < MAX_OPTIONS - 3; i++) {\r
+    if (options[i] == NULL) {\r
+      options[i] = sdup(name);\r
+      options[i + 1] = sdup(value);\r
+      options[i + 2] = NULL;\r
+      break;\r
+    }\r
+  }\r
+\r
+  if (i == MAX_OPTIONS - 3) {\r
+    die("%s", "Too many options specified");\r
+  }\r
+}\r
+\r
+static void process_command_line_arguments(char *argv[], char **options) {\r
+  char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;\r
+  FILE *fp = NULL;\r
+  size_t i, cmd_line_opts_start = 1, line_no = 0;\r
+\r
+  options[0] = NULL;\r
+\r
+  // Should we use a config file ?\r
+  if (argv[1] != NULL && argv[1][0] != '-') {\r
+    snprintf(config_file, sizeof(config_file), "%s", argv[1]);\r
+    cmd_line_opts_start = 2;\r
+  } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {\r
+    // No command line flags specified. Look where binary lives\r
+    snprintf(config_file, sizeof(config_file), "%s", CONFIG_FILE);\r
+  } else {\r
+    snprintf(config_file, sizeof(config_file), "%.*s%c%s",\r
+             (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);\r
+  }\r
+\r
+  fp = fopen(config_file, "r");\r
+\r
+  // If config file was set in command line and open failed, die\r
+  if (cmd_line_opts_start == 2 && fp == NULL) {\r
+    die("Cannot open config file %s: %s", config_file, strerror(errno));\r
+  }\r
+\r
+  // Load config file settings first\r
+  if (fp != NULL) {\r
+    fprintf(stderr, "Loading config file %s\n", config_file);\r
+\r
+    // Loop over the lines in config file\r
+    while (fgets(line, sizeof(line), fp) != NULL) {\r
+      line_no++;\r
+\r
+      // Ignore empty lines and comments\r
+      for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++;\r
+      if (line[i] == '#' || line[i] == '\0') {\r
+        continue;\r
+      }\r
+\r
+      if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {\r
+        printf("%s: line %d is invalid, ignoring it:\n %s",\r
+               config_file, (int) line_no, line);\r
+      } else {\r
+        set_option(options, opt, val);\r
+      }\r
+    }\r
+\r
+    (void) fclose(fp);\r
+  }\r
+\r
+  // If we're under MacOS and started by launchd, then the second\r
+  // argument is process serial number, -psn_.....\r
+  // In this case, don't process arguments at all.\r
+  if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {\r
+    // Handle command line flags.\r
+    // They override config file and default settings.\r
+    for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {\r
+      if (argv[i][0] != '-' || argv[i + 1] == NULL) {\r
+        show_usage_and_exit();\r
+      }\r
+      set_option(options, &argv[i][1], argv[i + 1]);\r
+    }\r
+  }\r
+}\r
+\r
+static void init_server_name(void) {\r
+  snprintf(server_name, sizeof(server_name), "Tinyweb server v. %s",\r
+           mg_version());\r
+}\r
+\r
+static int log_message(const struct mg_connection *conn, const char *message) {\r
+  (void) conn;\r
+  printf("%s\n", message);\r
+  return 0;\r
+}\r
+\r
+static void start_server(int argc, char *argv[]) {\r
+  struct mg_callbacks callbacks;\r
+  char *options[MAX_OPTIONS];\r
+  int i;\r
+\r
+  // Edit passwords file if -A option is specified\r
+  if (argc > 1 && !strcmp(argv[1], "-A")) {\r
+    if (argc != 6) {\r
+      show_usage_and_exit();\r
+    }\r
+    exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?\r
+         EXIT_SUCCESS : EXIT_FAILURE);\r
+  }\r
+\r
+  // Show usage if -h or --help options are specified\r
+  if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {\r
+    show_usage_and_exit();\r
+  }\r
+\r
+  /* Update config based on command line arguments */\r
+  process_command_line_arguments(argv, options);\r
+\r
+  /* Setup signal handler: quit on Ctrl-C */\r
+  signal(SIGTERM, signal_handler);\r
+  signal(SIGINT, signal_handler);\r
+\r
+  /* Start Tinyweb server */\r
+  memset(&callbacks, 0, sizeof(callbacks));\r
+  callbacks.websocket_ready = websocket_ready_handler;\r
+  callbacks.websocket_data = websocket_data_handler;\r
+\r
+  callbacks.log_message = &log_message;\r
+  ctx = mg_start(&callbacks, NULL, (const char **) options);\r
+  for (i = 0; options[i] != NULL; i++) {\r
+    free(options[i]);\r
+  }\r
+\r
+  if (ctx == NULL) {\r
+    die("%s", "Failed to start Tinyweb.");\r
+  }\r
+}\r
+\r
+int main(int argc, char *argv[]) {\r
+  init_server_name();\r
+  pid_t pid = 0;\r
+  pid = fork();\r
+  if (pid < 0) {\r
+    fprintf(stderr, "fork failed!\n");\r
+    exit(1);\r
+  }\r
+  if (pid > 0) {\r
+    fprintf(stderr, "Daemonize\n");\r
+    exit(0);\r
+  }\r
+  umask(0);\r
+  setsid();\r
+  start_server(argc, argv);\r
+  printf("%s started on port(s) %s with web root [%s]\n",\r
+         server_name, mg_get_option(ctx, "listening_ports"),\r
+         mg_get_option(ctx, "document_root"));\r
+  while (exit_flag == 0) {\r
+    sleep(1);\r
+  }\r
+  printf("Exiting on signal %d, waiting for all threads to finish...",\r
+         exit_flag);\r
+  fflush(stdout);\r
+  mg_stop(ctx);\r
+  printf("%s", " done.\n");\r
+\r
+  return EXIT_SUCCESS;\r
+}\r