diff --git a/spectrum_manager/src/main.cpp b/spectrum_manager/src/main.cpp index 63503ed1..f950450b 100644 --- a/spectrum_manager/src/main.cpp +++ b/spectrum_manager/src/main.cpp @@ -147,7 +147,6 @@ int main(int argc, char **argv) std::cerr << "Can't set up server handler.\n"; return 1; } - while (1) { sleep(10); } } else { if (command.size() < 2) { diff --git a/spectrum_manager/src/mongoose.c b/spectrum_manager/src/mongoose.c index 8881ecb6..05bdee5c 100644 --- a/spectrum_manager/src/mongoose.c +++ b/spectrum_manager/src/mongoose.c @@ -1,1131 +1,391 @@ -// Copyright (c) 2004-2012 Sergey Lyubka -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#include - -#if defined(_WIN32) -#define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005 -#else -#define _XOPEN_SOURCE 600 // For flockfile() on Linux -#define _LARGEFILE_SOURCE // Enable 64-bit file offsets -#define __STDC_FORMAT_MACROS // wants this for C++ -#define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX -#endif - -#if defined(__SYMBIAN32__) -#define NO_SSL // SSL is not supported -#define NO_CGI // CGI is not supported -#define PATH_MAX FILENAME_MAX -#endif // __SYMBIAN32__ - -#ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE -#include -#include -#include -#include -#include -#endif // !_WIN32_WCE - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific -#define _WIN32_WINNT 0x0400 // To make it link in VS2005 -#include - -#ifndef PATH_MAX -#define PATH_MAX MAX_PATH -#endif - -#ifndef _WIN32_WCE -#include -#include -#include -#else // _WIN32_WCE -#include -#include -#define NO_CGI // WinCE has no pipes - -typedef long off_t; - -#define errno GetLastError() -#define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10) -#endif // _WIN32_WCE - -#define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \ - ((uint64_t)((uint32_t)(hi))) << 32)) -#define RATE_DIFF 10000000 // 100 nsecs -#define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de) -#define SYS2UNIX_TIME(lo, hi) \ - (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF) - -// Visual Studio 6 does not know __func__ or __FUNCTION__ -// The rest of MS compilers use __FUNCTION__, not C99 __func__ -// Also use _strtoui64 on modern M$ compilers -#if defined(_MSC_VER) && _MSC_VER < 1300 -#define STRX(x) #x -#define STR(x) STRX(x) -#define __func__ "line " STR(__LINE__) -#define strtoull(x, y, z) strtoul(x, y, z) -#define strtoll(x, y, z) strtol(x, y, z) -#else -#define __func__ __FUNCTION__ -#define strtoull(x, y, z) _strtoui64(x, y, z) -#define strtoll(x, y, z) _strtoi64(x, y, z) -#endif // _MSC_VER - -#define ERRNO GetLastError() -#define NO_SOCKLEN_T -#define SSL_LIB "ssleay32.dll" -#define CRYPTO_LIB "libeay32.dll" -#define DIRSEP '\\' -#define IS_DIRSEP_CHAR(c) ((c) == '/' || (c) == '\\') -#define O_NONBLOCK 0 -#if !defined(EWOULDBLOCK) -#define EWOULDBLOCK WSAEWOULDBLOCK -#endif // !EWOULDBLOCK -#define _POSIX_ -#define INT64_FMT "I64d" - -#define WINCDECL __cdecl -#define SHUT_WR 1 -#define snprintf _snprintf -#define vsnprintf _vsnprintf -#define mg_sleep(x) Sleep(x) - -#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY) -#define popen(x, y) _popen(x, y) -#define pclose(x) _pclose(x) -#define close(x) _close(x) -#define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y)) -#define RTLD_LAZY 0 -#define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z)) -#define fdopen(x, y) _fdopen((x), (y)) -#define write(x, y, z) _write((x), (y), (unsigned) z) -#define read(x, y, z) _read((x), (y), (unsigned) z) -#define flockfile(x) EnterCriticalSection(&global_log_file_lock) -#define funlockfile(x) LeaveCriticalSection(&global_log_file_lock) - -#if !defined(fileno) -#define fileno(x) _fileno(x) -#endif // !fileno MINGW #defines fileno - -typedef HANDLE pthread_mutex_t; -typedef struct {HANDLE signal, broadcast;} pthread_cond_t; -typedef DWORD pthread_t; -#define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here. - -struct timespec { - long tv_nsec; - long tv_sec; -}; - -static int pthread_mutex_lock(pthread_mutex_t *); -static int pthread_mutex_unlock(pthread_mutex_t *); -static FILE *mg_fopen(const char *path, const char *mode); - -#if defined(HAVE_STDINT) -#include -#else -typedef unsigned int uint32_t; -typedef unsigned short uint16_t; -typedef unsigned __int64 uint64_t; -typedef __int64 int64_t; -#define INT64_MAX 9223372036854775807 -#endif // HAVE_STDINT - -// POSIX dirent interface -struct dirent { - char d_name[PATH_MAX]; -}; - -typedef struct DIR { - HANDLE handle; - WIN32_FIND_DATAW info; - struct dirent result; -} DIR; - -#else // UNIX specific -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#if !defined(NO_SSL_DL) && !defined(NO_SSL) -#include -#endif -#include -#if defined(__MACH__) -#define SSL_LIB "libssl.dylib" -#define CRYPTO_LIB "libcrypto.dylib" -#else -#if !defined(SSL_LIB) -#define SSL_LIB "libssl.so" -#endif -#if !defined(CRYPTO_LIB) -#define CRYPTO_LIB "libcrypto.so" -#endif -#endif -#define DIRSEP '/' -#define IS_DIRSEP_CHAR(c) ((c) == '/') -#ifndef O_BINARY -#define O_BINARY 0 -#endif // O_BINARY -#define closesocket(a) close(a) -#define mg_fopen(x, y) fopen(x, y) -#define mg_mkdir(x, y) mkdir(x, y) -#define mg_remove(x) remove(x) -#define mg_rename(x, y) rename(x, y) -#define mg_sleep(x) usleep((x) * 1000) -#define ERRNO errno -#define INVALID_SOCKET (-1) -#define INT64_FMT PRId64 -typedef int SOCKET; -#define WINCDECL - -#endif // End of Windows and UNIX specific includes - #include "mongoose.h" +#ifdef NS_MODULE_LINES +#line 1 "src/internal.h" +/**/ +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ -#define MONGOOSE_VERSION "3.3" -#define PASSWORDS_FILE_NAME ".htpasswd" -#define CGI_ENVIRONMENT_SIZE 4096 -#define MAX_CGI_ENVIR_VARS 64 -#define MG_BUF_LEN 8192 -#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) +#ifndef MG_INTERNAL_HEADER_INCLUDED +#define MG_INTERNAL_HEADER_INCLUDED + +#ifndef MG_MALLOC +#define MG_MALLOC malloc +#endif + +#ifndef MG_CALLOC +#define MG_CALLOC calloc +#endif + +#ifndef MG_REALLOC +#define MG_REALLOC realloc +#endif + +#ifndef MG_FREE +#define MG_FREE free +#endif + +#ifndef MBUF_REALLOC +#define MBUF_REALLOC MG_REALLOC +#endif + +#ifndef MBUF_FREE +#define MBUF_FREE MG_FREE +#endif + +#define MG_SET_PTRPTR(_ptr, _v) \ + do { \ + if (_ptr) *(_ptr) = _v; \ + } while (0) + +#ifndef MG_INTERNAL +#define MG_INTERNAL static +#endif + +#if !defined(MG_MGR_EV_MGR) +/* + * Switches between different methods of handling sockets. Supported values: + * 0 - select() + * 1 - epoll() (Linux only) + */ +#define MG_MGR_EV_MGR 0 /* select() */ +#endif + +#ifdef PICOTCP +#define NO_LIBC +#define MG_DISABLE_FILESYSTEM +#define MG_DISABLE_POPEN +#define MG_DISABLE_CGI +#define MG_DISABLE_DIRECTORY_LISTING +#define MG_DISABLE_SOCKETPAIR +#define MG_DISABLE_PFS +#endif + +/* Amalgamated: #include "../mongoose.h" */ + +/* internals that need to be accessible in unit tests */ +MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, + int proto, + union socket_address *sa); + +MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, + int *proto, char *host, size_t host_len); +MG_INTERNAL void mg_call(struct mg_connection *nc, + mg_event_handler_t ev_handler, int ev, void *ev_data); +MG_INTERNAL void mg_forward(struct mg_connection *, struct mg_connection *); +MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c); +MG_INTERNAL void mg_remove_conn(struct mg_connection *c); + +#ifndef MG_DISABLE_FILESYSTEM +MG_INTERNAL int find_index_file(char *, size_t, const char *, cs_stat_t *); +#endif #ifdef _WIN32 -static CRITICAL_SECTION global_log_file_lock; -static pthread_t pthread_self(void) { - return GetCurrentThreadId(); -} -#endif // _WIN32 - -#if defined(DEBUG) -#define DEBUG_TRACE(x) do { \ - flockfile(stdout); \ - printf("*** %lu.%p.%s.%d: ", \ - (unsigned long) time(NULL), (void *) pthread_self(), \ - __func__, __LINE__); \ - printf x; \ - putchar('\n'); \ - fflush(stdout); \ - funlockfile(stdout); \ -} while (0) -#else -#define DEBUG_TRACE(x) -#endif // DEBUG - -// Darwin prior to 7.0 and Win32 do not have socklen_t -#ifdef NO_SOCKLEN_T -typedef int socklen_t; -#endif // NO_SOCKLEN_T -#define _DARWIN_UNLIMITED_SELECT - -#if !defined(MSG_NOSIGNAL) -#define MSG_NOSIGNAL 0 +void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len); #endif -#if !defined(SOMAXCONN) -#define SOMAXCONN 100 +/* + * Reassemble the content of the buffer (buf, blen) which should be + * in the HTTP chunked encoding, by collapsing data chunks to the + * beginning of the buffer. + * + * If chunks get reassembled, modify hm->body to point to the reassembled + * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK + * in nc->flags, delete reassembled body from the mbuf. + * + * Return reassembled body size. + */ +MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, + struct http_message *hm, char *buf, + size_t blen); + +#ifndef MG_DISABLE_FILESYSTEM +MG_INTERNAL time_t mg_parse_date_string(const char *datetime); +MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st); #endif -static const char *http_500_error = "Internal Server Error"; +/* Forward declarations for testing. */ +extern void *(*test_malloc)(size_t); +extern void *(*test_calloc)(size_t, size_t); -// Snatched from OpenSSL includes. I put the prototypes here to be independent -// from the OpenSSL source installation. Having this, mongoose + SSL can be -// built on any system with binary SSL libraries installed. -typedef struct ssl_st SSL; -typedef struct ssl_method_st SSL_METHOD; -typedef struct ssl_ctx_st SSL_CTX; - -#define SSL_ERROR_WANT_READ 2 -#define SSL_ERROR_WANT_WRITE 3 -#define SSL_FILETYPE_PEM 1 -#define CRYPTO_LOCK 1 - -#if defined(NO_SSL_DL) -extern void SSL_free(SSL *); -extern int SSL_accept(SSL *); -extern int SSL_connect(SSL *); -extern int SSL_read(SSL *, void *, int); -extern int SSL_write(SSL *, const void *, int); -extern int SSL_get_error(const SSL *, int); -extern int SSL_set_fd(SSL *, int); -extern SSL *SSL_new(SSL_CTX *); -extern SSL_CTX *SSL_CTX_new(SSL_METHOD *); -extern SSL_METHOD *SSLv23_server_method(void); -extern SSL_METHOD *SSLv23_client_method(void); -extern int SSL_library_init(void); -extern void SSL_load_error_strings(void); -extern int SSL_CTX_use_PrivateKey_file(SSL_CTX *, const char *, int); -extern int SSL_CTX_use_certificate_file(SSL_CTX *, const char *, int); -extern int SSL_CTX_use_certificate_chain_file(SSL_CTX *, const char *); -extern void SSL_CTX_set_default_passwd_cb(SSL_CTX *, mg_callback_t); -extern void SSL_CTX_free(SSL_CTX *); -extern unsigned long ERR_get_error(void); -extern char *ERR_error_string(unsigned long, char *); -extern int CRYPTO_num_locks(void); -extern void CRYPTO_set_locking_callback(void (*)(int, int, const char *, int)); -extern void CRYPTO_set_id_callback(unsigned long (*)(void)); -#else -// Dynamically loaded SSL functionality -struct ssl_func { - const char *name; // SSL function name - void (*ptr)(void); // Function pointer -}; - -#define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr) -#define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr) -#define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr) -#define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr) -#define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr) -#define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr) -#define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr) -#define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr) -#define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr) -#define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr) -#define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr) -#define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \ - const char *, int)) ssl_sw[11].ptr) -#define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \ - const char *, int)) ssl_sw[12].ptr) -#define SSL_CTX_set_default_passwd_cb \ - (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr) -#define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr) -#define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr) -#define SSL_CTX_use_certificate_chain_file \ - (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr) -#define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr) - -#define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr) -#define CRYPTO_set_locking_callback \ - (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr) -#define CRYPTO_set_id_callback \ - (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr) -#define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr) -#define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr) - -// set_ssl_option() function updates this array. -// It loads SSL library dynamically and changes NULLs to the actual addresses -// of respective functions. The macros above (like SSL_connect()) are really -// just calling these functions indirectly via the pointer. -static struct ssl_func ssl_sw[] = { - {"SSL_free", NULL}, - {"SSL_accept", NULL}, - {"SSL_connect", NULL}, - {"SSL_read", NULL}, - {"SSL_write", NULL}, - {"SSL_get_error", NULL}, - {"SSL_set_fd", NULL}, - {"SSL_new", NULL}, - {"SSL_CTX_new", NULL}, - {"SSLv23_server_method", NULL}, - {"SSL_library_init", NULL}, - {"SSL_CTX_use_PrivateKey_file", NULL}, - {"SSL_CTX_use_certificate_file",NULL}, - {"SSL_CTX_set_default_passwd_cb",NULL}, - {"SSL_CTX_free", NULL}, - {"SSL_load_error_strings", NULL}, - {"SSL_CTX_use_certificate_chain_file", NULL}, - {"SSLv23_client_method", NULL}, - {NULL, NULL} -}; - -// Similar array as ssl_sw. These functions could be located in different lib. -#if !defined(NO_SSL) -static struct ssl_func crypto_sw[] = { - {"CRYPTO_num_locks", NULL}, - {"CRYPTO_set_locking_callback", NULL}, - {"CRYPTO_set_id_callback", NULL}, - {"ERR_get_error", NULL}, - {"ERR_error_string", NULL}, - {NULL, NULL} -}; -#endif // NO_SSL -#endif // NO_SSL_DL - -static const char *month_names[] = { - "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" -}; - -// Unified socket address. For IPv6 support, add IPv6 address structure -// in the union u. -union usa { - struct sockaddr sa; - struct sockaddr_in sin; -#if defined(USE_IPV6) - struct sockaddr_in6 sin6; +#endif /* MG_INTERNAL_HEADER_INCLUDED */ +#ifdef NS_MODULE_LINES +#line 1 "src/../../common/base64.c" +/**/ #endif -}; +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ -// Describes a string (chunk of memory). -struct vec { - const char *ptr; - size_t len; -}; +#ifndef EXCLUDE_COMMON -// Structure used by mg_stat() function. Uses 64 bit file length. -struct mgstat { - int is_directory; // Directory marker - int64_t size; // File size - time_t mtime; // Modification time -}; +/* Amalgamated: #include "base64.h" */ +#include -// Describes listening socket, or socket which was accept()-ed by the master -// thread and queued for future handling by the worker thread. -struct socket { - struct socket *next; // Linkage - SOCKET sock; // Listening socket - union usa lsa; // Local socket address - union usa rsa; // Remote socket address - int is_ssl; // Is socket SSL-ed -}; +/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */ -// NOTE(lsm): this enum shoulds be in sync with the config_options below. -enum { - CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER, - MAX_REQUEST_SIZE, PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, - ACCESS_LOG_FILE, SSL_CHAIN_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE, - GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST, - EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE, - NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, - NUM_OPTIONS -}; +#define NUM_UPPERCASES ('Z' - 'A' + 1) +#define NUM_LETTERS (NUM_UPPERCASES * 2) +#define NUM_DIGITS ('9' - '0' + 1) -static const char *config_options[] = { - "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$", - "E", "cgi_environment", NULL, - "G", "put_delete_passwords_file", NULL, - "I", "cgi_interpreter", NULL, - "M", "max_request_size", "16384", - "P", "protect_uri", NULL, - "R", "authentication_domain", "mydomain.com", - "S", "ssi_pattern", "**.shtml$|**.shtm$", - "a", "access_log_file", NULL, - "c", "ssl_chain_file", NULL, - "d", "enable_directory_listing", "yes", - "e", "error_log_file", NULL, - "g", "global_passwords_file", NULL, - "i", "index_files", "index.html,index.htm,index.cgi,index.shtml,index.php", - "k", "enable_keep_alive", "no", - "l", "access_control_list", NULL, - "m", "extra_mime_types", NULL, - "p", "listening_ports", "8080", - "r", "document_root", ".", - "s", "ssl_certificate", NULL, - "t", "num_threads", "10", - "u", "run_as_user", NULL, - "w", "url_rewrite_patterns", NULL, - "x", "hide_files_patterns", NULL, - NULL -}; -#define ENTRIES_PER_CONFIG_OPTION 3 - -struct mg_context { - volatile int stop_flag; // Should we stop event loop - SSL_CTX *ssl_ctx; // SSL context - SSL_CTX *client_ssl_ctx; // Client SSL context - char *config[NUM_OPTIONS]; // Mongoose configuration parameters - mg_callback_t user_callback; // User-defined callback function - void *user_data; // User-defined data - - struct socket *listening_sockets; - - volatile int num_threads; // Number of threads - pthread_mutex_t mutex; // Protects (max|num)_threads - pthread_cond_t cond; // Condvar for tracking workers terminations - - struct socket queue[20]; // Accepted sockets - volatile int sq_head; // Head of the socket queue - volatile int sq_tail; // Tail of the socket queue - pthread_cond_t sq_full; // Signaled when socket is produced - pthread_cond_t sq_empty; // Signaled when socket is consumed -}; - -struct mg_connection { - struct mg_request_info request_info; - struct mg_context *ctx; - SSL *ssl; // SSL descriptor - struct socket client; // Connected client - time_t birth_time; // Time when request was received - int64_t num_bytes_sent; // Total bytes sent to client - int64_t content_len; // Content-Length header value - int64_t consumed_content; // How many bytes of content have been read - char *buf; // Buffer for received data - char *path_info; // PATH_INFO part of the URL - char *body; // Pointer to not-read yet buffered body data - char *next_request; // Pointer to the buffered next request - int must_close; // 1 if connection must be closed - int buf_size; // Buffer size - int request_len; // Size of the request + headers in a buffer - int data_len; // Total size of data in a buffer -}; - -const char **mg_get_valid_option_names(void) { - return config_options; +/* + * Emit a base64 code char. + * + * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps + */ +static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) { + if (v < NUM_UPPERCASES) { + ctx->b64_putc(v + 'A', ctx->user_data); + } else if (v < (NUM_LETTERS)) { + ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data); + } else if (v < (NUM_LETTERS + NUM_DIGITS)) { + ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data); + } else { + ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/', + ctx->user_data); + } } -static void *call_user(struct mg_connection *conn, enum mg_event event) { - conn->request_info.user_data = conn->ctx->user_data; - return conn->ctx->user_callback == NULL ? NULL : - conn->ctx->user_callback(event, conn); +static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) { + int a, b, c; + + a = ctx->chunk[0]; + b = ctx->chunk[1]; + c = ctx->chunk[2]; + + cs_base64_emit_code(ctx, a >> 2); + cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4)); + if (ctx->chunk_size > 1) { + cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6)); + } + if (ctx->chunk_size > 2) { + cs_base64_emit_code(ctx, c & 63); + } } -static int get_option_index(const char *name) { - int i; +void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc, + void *user_data) { + ctx->chunk_size = 0; + ctx->b64_putc = b64_putc; + ctx->user_data = user_data; +} - for (i = 0; config_options[i] != NULL; i += ENTRIES_PER_CONFIG_OPTION) { - if (strcmp(config_options[i], name) == 0 || - strcmp(config_options[i + 1], name) == 0) { - return i / ENTRIES_PER_CONFIG_OPTION; +void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) { + const unsigned char *src = (const unsigned char *) str; + size_t i; + for (i = 0; i < len; i++) { + ctx->chunk[ctx->chunk_size++] = src[i]; + if (ctx->chunk_size == 3) { + cs_base64_emit_chunk(ctx); + ctx->chunk_size = 0; } } - return -1; } -const char *mg_get_option(const struct mg_context *ctx, const char *name) { - int i; - if ((i = get_option_index(name)) == -1) { - return NULL; - } else if (ctx->config[i] == NULL) { - return ""; - } else { - return ctx->config[i]; +void cs_base64_finish(struct cs_base64_ctx *ctx) { + if (ctx->chunk_size > 0) { + int i; + memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size); + cs_base64_emit_chunk(ctx); + for (i = 0; i < (3 - ctx->chunk_size); i++) { + ctx->b64_putc('=', ctx->user_data); + } } } -static void sockaddr_to_string(char *buf, size_t len, - const union usa *usa) { - buf[0] = '\0'; -#if defined(USE_IPV6) - inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ? - (void *) &usa->sin.sin_addr : - (void *) &usa->sin6.sin6_addr, buf, len); -#elif defined(_WIN32) - // Only Windoze Vista (and newer) have inet_ntop() - strncpy(buf, inet_ntoa(usa->sin.sin_addr), len); -#else - inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len); -#endif +#define BASE64_ENCODE_BODY \ + static const char *b64 = \ + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \ + int i, j, a, b, c; \ + \ + for (i = j = 0; i < src_len; i += 3) { \ + a = src[i]; \ + b = i + 1 >= src_len ? 0 : src[i + 1]; \ + c = i + 2 >= src_len ? 0 : src[i + 2]; \ + \ + BASE64_OUT(b64[a >> 2]); \ + BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \ + if (i + 1 < src_len) { \ + BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \ + } \ + if (i + 2 < src_len) { \ + BASE64_OUT(b64[c & 63]); \ + } \ + } \ + \ + while (j % 4 != 0) { \ + BASE64_OUT('='); \ + } \ + BASE64_FLUSH() + +#define BASE64_OUT(ch) \ + do { \ + dst[j++] = (ch); \ + } while (0) + +#define BASE64_FLUSH() \ + do { \ + dst[j++] = '\0'; \ + } while (0) + +void cs_base64_encode(const unsigned char *src, int src_len, char *dst) { + BASE64_ENCODE_BODY; } -// Print error message to the opened error log stream. -static void cry(struct mg_connection *conn, const char *fmt, ...) { - char buf[MG_BUF_LEN], src_addr[20]; - va_list ap; - FILE *fp; - time_t timestamp; +#undef BASE64_OUT +#undef BASE64_FLUSH +#define BASE64_OUT(ch) \ + do { \ + fprintf(f, "%c", (ch)); \ + j++; \ + } while (0) + +#define BASE64_FLUSH() + +void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) { + BASE64_ENCODE_BODY; +} + +#undef BASE64_OUT +#undef BASE64_FLUSH + +/* Convert one byte of encoded base64 input stream to 6-bit chunk */ +static unsigned char from_b64(unsigned char ch) { + /* Inverse lookup map */ + static const unsigned char tab[128] = { + 255, 255, 255, 255, + 255, 255, 255, 255, /* 0 */ + 255, 255, 255, 255, + 255, 255, 255, 255, /* 8 */ + 255, 255, 255, 255, + 255, 255, 255, 255, /* 16 */ + 255, 255, 255, 255, + 255, 255, 255, 255, /* 24 */ + 255, 255, 255, 255, + 255, 255, 255, 255, /* 32 */ + 255, 255, 255, 62, + 255, 255, 255, 63, /* 40 */ + 52, 53, 54, 55, + 56, 57, 58, 59, /* 48 */ + 60, 61, 255, 255, + 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */ + 255, 0, 1, 2, + 3, 4, 5, 6, /* 64 */ + 7, 8, 9, 10, + 11, 12, 13, 14, /* 72 */ + 15, 16, 17, 18, + 19, 20, 21, 22, /* 80 */ + 23, 24, 25, 255, + 255, 255, 255, 255, /* 88 */ + 255, 26, 27, 28, + 29, 30, 31, 32, /* 96 */ + 33, 34, 35, 36, + 37, 38, 39, 40, /* 104 */ + 41, 42, 43, 44, + 45, 46, 47, 48, /* 112 */ + 49, 50, 51, 255, + 255, 255, 255, 255, /* 120 */ + }; + return tab[ch & 127]; +} + +int cs_base64_decode(const unsigned char *s, int len, char *dst) { + unsigned char a, b, c, d; + int orig_len = len; + while (len >= 4 && (a = from_b64(s[0])) != 255 && + (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 && + (d = from_b64(s[3])) != 255) { + s += 4; + len -= 4; + if (a == 200 || b == 200) break; /* '=' can't be there */ + *dst++ = a << 2 | b >> 4; + if (c == 200) break; + *dst++ = b << 4 | c >> 2; + if (d == 200) break; + *dst++ = c << 6 | d; + } + *dst = 0; + return orig_len - len; +} + +#endif /* EXCLUDE_COMMON */ +#ifdef NS_MODULE_LINES +#line 1 "src/../../common/cs_dbg.c" +/**/ +#endif +/* Amalgamated: #include "cs_dbg.h" */ + +#include +#include + +enum cs_log_level s_cs_log_level = +#ifdef CS_ENABLE_DEBUG + LL_DEBUG; +#else + LL_ERROR; +#endif + +void cs_log_printf(const char *fmt, ...) { + va_list ap; va_start(ap, fmt); - (void) vsnprintf(buf, sizeof(buf), fmt, ap); + vfprintf(stderr, fmt, ap); va_end(ap); - - // Do not lock when getting the callback value, here and below. - // I suppose this is fine, since function cannot disappear in the - // same way string option can. - conn->request_info.log_message = buf; - if (call_user(conn, MG_EVENT_LOG) == NULL) { - fp = conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL : - mg_fopen(conn->ctx->config[ERROR_LOG_FILE], "a+"); - - if (fp != NULL) { - flockfile(fp); - timestamp = time(NULL); - - sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa); - fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp, - src_addr); - - if (conn->request_info.request_method != NULL) { - fprintf(fp, "%s %s: ", conn->request_info.request_method, - conn->request_info.uri); - } - - (void) fprintf(fp, "%s", buf); - fputc('\n', fp); - funlockfile(fp); - if (fp != stderr) { - fclose(fp); - } - } - } - conn->request_info.log_message = NULL; + fputc('\n', stderr); + fflush(stderr); } -// Return fake connection structure. Used for logging, if connection -// is not applicable at the moment of logging. -static struct mg_connection *fc(struct mg_context *ctx) { - static struct mg_connection fake_connection; - fake_connection.ctx = ctx; - return &fake_connection; -} - -const char *mg_version(void) { - return MONGOOSE_VERSION; -} - -const struct mg_request_info * -mg_get_request_info(const struct mg_connection *conn) { - return &conn->request_info; -} - -static void mg_strlcpy(register char *dst, register const char *src, size_t n) { - for (; *src != '\0' && n > 1; n--) { - *dst++ = *src++; - } - *dst = '\0'; -} - -static int lowercase(const char *s) { - return tolower(* (const unsigned char *) s); -} - -static int mg_strncasecmp(const char *s1, const char *s2, size_t len) { - int diff = 0; - - if (len > 0) - do { - diff = lowercase(s1++) - lowercase(s2++); - } while (diff == 0 && s1[-1] != '\0' && --len > 0); - - return diff; -} - -static int mg_strcasecmp(const char *s1, const char *s2) { - int diff; - - do { - diff = lowercase(s1++) - lowercase(s2++); - } while (diff == 0 && s1[-1] != '\0'); - - return diff; -} - -static char * mg_strndup(const char *ptr, size_t len) { - char *p; - - if ((p = (char *) malloc(len + 1)) != NULL) { - mg_strlcpy(p, ptr, len + 1); - } - - return p; -} - -static char * mg_strdup(const char *str) { - return mg_strndup(str, strlen(str)); -} - -// Like snprintf(), but never returns negative value, or a value -// that is larger than a supplied buffer. -// Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability -// in his audit report. -static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen, - const char *fmt, va_list ap) { - int n; - - if (buflen == 0) - return 0; - - n = vsnprintf(buf, buflen, fmt, ap); - - if (n < 0) { - cry(conn, "vsnprintf error"); - n = 0; - } else if (n >= (int) buflen) { - cry(conn, "truncating vsnprintf buffer: [%.*s]", - n > 200 ? 200 : n, buf); - n = (int) buflen - 1; - } - buf[n] = '\0'; - - return n; -} - -static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen, - const char *fmt, ...) { - va_list ap; - int n; - - va_start(ap, fmt); - n = mg_vsnprintf(conn, buf, buflen, fmt, ap); - va_end(ap); - - return n; -} - -// Skip the characters until one of the delimiters characters found. -// 0-terminate resulting word. Skip the delimiter and following whitespaces if any. -// Advance pointer to buffer to the next word. Return found 0-terminated word. -// Delimiters can be quoted with quotechar. -static char *skip_quoted(char **buf, const char *delimiters, - const char *whitespace, char quotechar) { - char *p, *begin_word, *end_word, *end_whitespace; - - begin_word = *buf; - end_word = begin_word + strcspn(begin_word, delimiters); - - // Check for quotechar - if (end_word > begin_word) { - p = end_word - 1; - while (*p == quotechar) { - // If there is anything beyond end_word, copy it - if (*end_word == '\0') { - *p = '\0'; - break; - } else { - size_t end_off = strcspn(end_word + 1, delimiters); - memmove (p, end_word, end_off + 1); - p += end_off; // p must correspond to end_word - 1 - end_word += end_off + 1; - } - } - for (p++; p < end_word; p++) { - *p = '\0'; - } - } - - if (*end_word == '\0') { - *buf = end_word; - } else { - end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace); - - for (p = end_word; p < end_whitespace; p++) { - *p = '\0'; - } - - *buf = end_whitespace; - } - - return begin_word; -} - -// Simplified version of skip_quoted without quote char -// and whitespace == delimiters -static char *skip(char **buf, const char *delimiters) { - return skip_quoted(buf, delimiters, delimiters, 0); -} - - -// Return HTTP header value, or NULL if not found. -static const char *get_header(const struct mg_request_info *ri, - const char *name) { - int i; - - for (i = 0; i < ri->num_headers; i++) - if (!mg_strcasecmp(name, ri->http_headers[i].name)) - return ri->http_headers[i].value; - - return NULL; -} - -const char *mg_get_header(const struct mg_connection *conn, const char *name) { - return get_header(&conn->request_info, name); -} - -// A helper function for traversing a comma separated list of values. -// It returns a list pointer shifted to the next value, or NULL if the end -// of the list found. -// Value is stored in val vector. If value has form "x=y", then eq_val -// vector is initialized to point to the "y" part, and val vector length -// is adjusted to point only to "x". -static const char *next_option(const char *list, struct vec *val, - struct vec *eq_val) { - if (list == NULL || *list == '\0') { - // End of the list - list = NULL; - } else { - val->ptr = list; - if ((list = strchr(val->ptr, ',')) != NULL) { - // Comma found. Store length and shift the list ptr - val->len = list - val->ptr; - list++; - } else { - // This value is the last one - list = val->ptr + strlen(val->ptr); - val->len = list - val->ptr; - } - - if (eq_val != NULL) { - // Value has form "x=y", adjust pointers and lengths - // so that val points to "x", and eq_val points to "y". - eq_val->len = 0; - eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len); - if (eq_val->ptr != NULL) { - eq_val->ptr++; // Skip over '=' character - eq_val->len = val->ptr + val->len - eq_val->ptr; - val->len = (eq_val->ptr - val->ptr) - 1; - } - } - } - - return list; -} - -static int match_prefix(const char *pattern, int pattern_len, const char *str) { - const char *or_str; - int i, j, len, res; - - if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) { - res = match_prefix(pattern, or_str - pattern, str); - return res > 0 ? res : - match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str); - } - - i = j = 0; - res = -1; - for (; i < pattern_len; i++, j++) { - if (pattern[i] == '?' && str[j] != '\0') { - continue; - } else if (pattern[i] == '$') { - return str[j] == '\0' ? j : -1; - } else if (pattern[i] == '*') { - i++; - if (pattern[i] == '*') { - i++; - len = (int) strlen(str + j); - } else { - len = (int) strcspn(str + j, "/"); - } - if (i == pattern_len) { - return j + len; - } - do { - res = match_prefix(pattern + i, pattern_len - i, str + j + len); - } while (res == -1 && len-- > 0); - return res == -1 ? -1 : j + res + len; - } else if (pattern[i] != str[j]) { - return -1; - } - } - return j; -} - -// HTTP 1.1 assumes keep alive if "Connection:" header is not set -// This function must tolerate situations when connection info is not -// set up, for example if request parsing failed. -static int should_keep_alive(const struct mg_connection *conn) { - const char *http_version = conn->request_info.http_version; - const char *header = mg_get_header(conn, "Connection"); - if (conn->must_close || - conn->request_info.status_code == 401 || - mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 || - (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) || - (header == NULL && http_version && strcmp(http_version, "1.1"))) { - return 0; - } - return 1; -} - -static const char *suggest_connection_header(const struct mg_connection *conn) { - return should_keep_alive(conn) ? "keep-alive" : "close"; -} - -static void send_http_error(struct mg_connection *, int, const char *, - PRINTF_FORMAT_STRING(const char *fmt), ...) - PRINTF_ARGS(4, 5); - - -static void send_http_error(struct mg_connection *conn, int status, - const char *reason, const char *fmt, ...) { - char buf[MG_BUF_LEN]; - va_list ap; - int len; - - conn->request_info.status_code = status; - - if (call_user(conn, MG_HTTP_ERROR) == NULL) { - buf[0] = '\0'; - len = 0; - - // Errors 1xx, 204 and 304 MUST NOT send a body - if (status > 199 && status != 204 && status != 304) { - len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason); - buf[len++] = '\n'; - - va_start(ap, fmt); - len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap); - va_end(ap); - } - DEBUG_TRACE(("[%s]", buf)); - - mg_printf(conn, "HTTP/1.1 %d %s\r\n" - "Content-Type: text/plain\r\n" - "Content-Length: %d\r\n" - "Connection: %s\r\n\r\n", status, reason, len, - suggest_connection_header(conn)); - conn->num_bytes_sent += mg_printf(conn, "%s", buf); - } -} - -#if defined(_WIN32) && !defined(__SYMBIAN32__) -static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) { - unused = NULL; - *mutex = CreateMutex(NULL, FALSE, NULL); - return *mutex == NULL ? -1 : 0; -} - -static int pthread_mutex_destroy(pthread_mutex_t *mutex) { - return CloseHandle(*mutex) == 0 ? -1 : 0; -} - -static int pthread_mutex_lock(pthread_mutex_t *mutex) { - return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1; -} - -static int pthread_mutex_unlock(pthread_mutex_t *mutex) { - return ReleaseMutex(*mutex) == 0 ? -1 : 0; -} - -static int pthread_cond_init(pthread_cond_t *cv, const void *unused) { - unused = NULL; - cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL); - cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL); - return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1; -} - -static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) { - HANDLE handles[] = {cv->signal, cv->broadcast}; - ReleaseMutex(*mutex); - WaitForMultipleObjects(2, handles, FALSE, INFINITE); - return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1; -} - -static int pthread_cond_signal(pthread_cond_t *cv) { - return SetEvent(cv->signal) == 0 ? -1 : 0; -} - -static int pthread_cond_broadcast(pthread_cond_t *cv) { - // Implementation with PulseEvent() has race condition, see - // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html - return PulseEvent(cv->broadcast) == 0 ? -1 : 0; -} - -static int pthread_cond_destroy(pthread_cond_t *cv) { - return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1; -} - -// For Windows, change all slashes to backslashes in path names. -static void change_slashes_to_backslashes(char *path) { - int i; - - for (i = 0; path[i] != '\0'; i++) { - if (path[i] == '/') - path[i] = '\\'; - // i > 0 check is to preserve UNC paths, like \\server\file.txt - if (path[i] == '\\' && i > 0) - while (path[i + 1] == '\\' || path[i + 1] == '/') - (void) memmove(path + i + 1, - path + i + 2, strlen(path + i + 1)); - } -} - -// Encode 'path' which is assumed UTF-8 string, into UNICODE string. -// wbuf and wbuf_len is a target buffer and its length. -static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) { - char buf[PATH_MAX], buf2[PATH_MAX], *p; - - mg_strlcpy(buf, path, sizeof(buf)); - change_slashes_to_backslashes(buf); - - // Point p to the end of the file name - p = buf + strlen(buf) - 1; - - // Trim trailing backslash character - while (p > buf && *p == '\\' && p[-1] != ':') { - *p-- = '\0'; - } - - // Protect from CGI code disclosure. - // This is very nasty hole. Windows happily opens files with - // some garbage in the end of file name. So fopen("a.cgi ", "r") - // actually opens "a.cgi", and does not return an error! - if (*p == 0x20 || // No space at the end - (*p == 0x2e && p > buf) || // No '.' but allow '.' as full path - *p == 0x2b || // No '+' - (*p & ~0x7f)) { // And generally no non-ASCII chars - (void) fprintf(stderr, "Rejecting suspicious path: [%s]", buf); - wbuf[0] = L'\0'; - } else { - // Convert to Unicode and back. If doubly-converted string does not - // match the original, something is fishy, reject. - memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); - MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); - WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), - NULL, NULL); - if (strcmp(buf, buf2) != 0) { - wbuf[0] = L'\0'; - } - } -} - -#if defined(_WIN32_WCE) -static time_t time(time_t *ptime) { - time_t t; - SYSTEMTIME st; - FILETIME ft; - - GetSystemTime(&st); - SystemTimeToFileTime(&st, &ft); - t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime); - - if (ptime != NULL) { - *ptime = t; - } - - return t; -} - -static struct tm *localtime(const time_t *ptime, struct tm *ptm) { - int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF; - FILETIME ft, lft; - SYSTEMTIME st; - TIME_ZONE_INFORMATION tzinfo; - - if (ptm == NULL) { - return NULL; - } - - * (int64_t *) &ft = t; - FileTimeToLocalFileTime(&ft, &lft); - FileTimeToSystemTime(&lft, &st); - ptm->tm_year = st.wYear - 1900; - ptm->tm_mon = st.wMonth - 1; - ptm->tm_wday = st.wDayOfWeek; - ptm->tm_mday = st.wDay; - ptm->tm_hour = st.wHour; - ptm->tm_min = st.wMinute; - ptm->tm_sec = st.wSecond; - ptm->tm_yday = 0; // hope nobody uses this - ptm->tm_isdst = - GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0; - - return ptm; -} - -static struct tm *gmtime(const time_t *ptime, struct tm *ptm) { - // FIXME(lsm): fix this. - return localtime(ptime, ptm); -} - -static size_t strftime(char *dst, size_t dst_size, const char *fmt, - const struct tm *tm) { - (void) snprintf(dst, dst_size, "implement strftime() for WinCE"); - return 0; +void cs_log_set_level(enum cs_log_level level) { + s_cs_log_level = level; } +#ifdef NS_MODULE_LINES +#line 1 "src/../../common/dirent.c" +/**/ +#endif +/* + * Copyright (c) 2015 Cesanta Software Limited + * All rights reserved + */ + +#ifndef EXCLUDE_COMMON + +/* Amalgamated: #include "osdep.h" */ + +/* + * This file contains POSIX opendir/closedir/readdir API implementation + * for systems which do not natively support it (e.g. Windows). + */ + +#ifndef MG_FREE +#define MG_FREE free #endif -static int mg_rename(const char* oldname, const char* newname) { - wchar_t woldbuf[PATH_MAX]; - wchar_t wnewbuf[PATH_MAX]; +#ifndef MG_MALLOC +#define MG_MALLOC malloc +#endif - to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf)); - to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf)); - - return MoveFileW(woldbuf, wnewbuf) ? 0 : -1; -} - - -static FILE *mg_fopen(const char *path, const char *mode) { - wchar_t wbuf[PATH_MAX], wmode[20]; - - to_unicode(path, wbuf, ARRAY_SIZE(wbuf)); - MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode)); - - return _wfopen(wbuf, wmode); -} - -static int mg_stat(const char *path, struct mgstat *stp) { - int ok = -1; // Error - wchar_t wbuf[PATH_MAX]; - WIN32_FILE_ATTRIBUTE_DATA info; - - to_unicode(path, wbuf, ARRAY_SIZE(wbuf)); - - if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) { - stp->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh); - stp->mtime = SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime, - info.ftLastWriteTime.dwHighDateTime); - stp->is_directory = - info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; - ok = 0; // Success - } - - return ok; -} - -static int mg_remove(const char *path) { - wchar_t wbuf[PATH_MAX]; - to_unicode(path, wbuf, ARRAY_SIZE(wbuf)); - return DeleteFileW(wbuf) ? 0 : -1; -} - -static int mg_mkdir(const char *path, int mode) { - char buf[PATH_MAX]; - wchar_t wbuf[PATH_MAX]; - - mode = 0; // Unused - mg_strlcpy(buf, path, sizeof(buf)); - change_slashes_to_backslashes(buf); - - (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, sizeof(wbuf)); - - return CreateDirectoryW(wbuf, NULL) ? 0 : -1; -} - -// Implementation of POSIX opendir/closedir/readdir for Windows. -static DIR * opendir(const char *name) { +#ifdef _WIN32 +DIR *opendir(const char *name) { DIR *dir = NULL; - wchar_t wpath[PATH_MAX]; + wchar_t wpath[MAX_PATH]; DWORD attrs; if (name == NULL) { SetLastError(ERROR_BAD_ARGUMENTS); - } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) { + } else if ((dir = (DIR *) MG_MALLOC(sizeof(*dir))) == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { - to_unicode(name, wpath, ARRAY_SIZE(wpath)); + to_wchar(name, wpath, ARRAY_SIZE(wpath)); attrs = GetFileAttributesW(wpath); - if (attrs != 0xFFFFFFFF && - ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) { + if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) { (void) wcscat(wpath, L"\\*"); dir->handle = FindFirstFileW(wpath, &dir->info); dir->result.d_name[0] = '\0'; } else { - free(dir); + MG_FREE(dir); dir = NULL; } } @@ -1133,14 +393,13 @@ static DIR * opendir(const char *name) { return dir; } -static int closedir(DIR *dir) { +int closedir(DIR *dir) { int result = 0; if (dir != NULL) { if (dir->handle != INVALID_HANDLE_VALUE) result = FindClose(dir->handle) ? 0 : -1; - - free(dir); + MG_FREE(dir); } else { result = -1; SetLastError(ERROR_BAD_ARGUMENTS); @@ -1149,15 +408,15 @@ static int closedir(DIR *dir) { return result; } -static struct dirent *readdir(DIR *dir) { +struct dirent *readdir(DIR *dir) { struct dirent *result = 0; if (dir) { if (dir->handle != INVALID_HANDLE_VALUE) { result = &dir->result; - (void) WideCharToMultiByte(CP_UTF8, 0, - dir->info.cFileName, -1, result->d_name, - sizeof(result->d_name), NULL, NULL); + (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1, + result->d_name, sizeof(result->d_name), NULL, + NULL); if (!FindNextFileW(dir->handle, &dir->info)) { (void) FindClose(dir->handle); @@ -1173,722 +432,550 @@ static struct dirent *readdir(DIR *dir) { return result; } +#endif -#define set_close_on_exec(fd) // No FD_CLOEXEC on Windows +#endif /* EXCLUDE_COMMON */ +#ifdef NS_MODULE_LINES +#line 1 "src/../deps/frozen/frozen.c" +/**/ +#endif +/* + * Copyright (c) 2004-2013 Sergey Lyubka + * Copyright (c) 2013 Cesanta Software Limited + * All rights reserved + * + * This library is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this library under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this library under a commercial + * license, as set out in . + */ -int mg_start_thread(mg_thread_func_t f, void *p) { - return _beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0; +#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005+ */ + +#include +#include +#include +#include +/* Amalgamated: #include "frozen.h" */ + +#ifdef _WIN32 +#define snprintf _snprintf +#endif + +#ifndef FROZEN_REALLOC +#define FROZEN_REALLOC realloc +#endif + +#ifndef FROZEN_FREE +#define FROZEN_FREE free +#endif + +struct frozen { + const char *end; + const char *cur; + struct json_token *tokens; + int max_tokens; + int num_tokens; + int do_realloc; +}; + +static int parse_object(struct frozen *f); +static int parse_value(struct frozen *f); + +#define EXPECT(cond, err_code) do { if (!(cond)) return (err_code); } while (0) +#define TRY(expr) do { int _n = expr; if (_n < 0) return _n; } while (0) +#define END_OF_STRING (-1) + +static int left(const struct frozen *f) { + return f->end - f->cur; } -static HANDLE dlopen(const char *dll_name, int flags) { - wchar_t wbuf[PATH_MAX]; - flags = 0; // Unused - to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf)); - return LoadLibraryW(wbuf); +static int is_space(int ch) { + return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; } -#if !defined(NO_CGI) -#define SIGKILL 0 -static int kill(pid_t pid, int sig_num) { - (void) TerminateProcess(pid, sig_num); - (void) CloseHandle(pid); +static void skip_whitespaces(struct frozen *f) { + while (f->cur < f->end && is_space(*f->cur)) f->cur++; +} + +static int cur(struct frozen *f) { + skip_whitespaces(f); + return f->cur >= f->end ? END_OF_STRING : * (unsigned char *) f->cur; +} + +static int test_and_skip(struct frozen *f, int expected) { + int ch = cur(f); + if (ch == expected) { f->cur++; return 0; } + return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID; +} + +static int is_alpha(int ch) { + return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); +} + +static int is_digit(int ch) { + return ch >= '0' && ch <= '9'; +} + +static int is_hex_digit(int ch) { + return is_digit(ch) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'); +} + +static int get_escape_len(const char *s, int len) { + switch (*s) { + case 'u': + return len < 6 ? JSON_STRING_INCOMPLETE : + is_hex_digit(s[1]) && is_hex_digit(s[2]) && + is_hex_digit(s[3]) && is_hex_digit(s[4]) ? 5 : JSON_STRING_INVALID; + case '"': case '\\': case '/': case 'b': + case 'f': case 'n': case 'r': case 't': + return len < 2 ? JSON_STRING_INCOMPLETE : 1; + default: + return JSON_STRING_INVALID; + } +} + +static int capture_ptr(struct frozen *f, const char *ptr, enum json_type type) { + if (f->do_realloc && f->num_tokens >= f->max_tokens) { + int new_size = f->max_tokens == 0 ? 100 : f->max_tokens * 2; + void *p = FROZEN_REALLOC(f->tokens, new_size * sizeof(f->tokens[0])); + if (p == NULL) return JSON_TOKEN_ARRAY_TOO_SMALL; + f->max_tokens = new_size; + f->tokens = (struct json_token *) p; + } + if (f->tokens == NULL || f->max_tokens == 0) return 0; + if (f->num_tokens >= f->max_tokens) return JSON_TOKEN_ARRAY_TOO_SMALL; + f->tokens[f->num_tokens].ptr = ptr; + f->tokens[f->num_tokens].type = type; + f->num_tokens++; return 0; } -static pid_t spawn_process(struct mg_connection *conn, const char *prog, - char *envblk, char *envp[], int fd_stdin, - int fd_stdout, const char *dir) { - HANDLE me; - char *p, *interp, cmdline[PATH_MAX], buf[PATH_MAX]; - FILE *fp; - STARTUPINFOA si = { sizeof(si) }; - PROCESS_INFORMATION pi = { 0 }; - - envp = NULL; // Unused - - // TODO(lsm): redirect CGI errors to the error log file - si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; - si.wShowWindow = SW_HIDE; - - me = GetCurrentProcess(); - (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me, - &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); - (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me, - &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); - - // If CGI file is a script, try to read the interpreter line - interp = conn->ctx->config[CGI_INTERPRETER]; - if (interp == NULL) { - buf[2] = '\0'; - mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%c%s", dir, DIRSEP, prog); - if ((fp = fopen(cmdline, "r")) != NULL) { - (void) fgets(buf, sizeof(buf), fp); - if (buf[0] != '#' || buf[1] != '!') { - // First line does not start with "#!". Do not set interpreter. - buf[2] = '\0'; - } else { - // Trim whitespace in interpreter name - for (p = &buf[strlen(buf) - 1]; p > buf && isspace(*p); p--) { - *p = '\0'; - } - } - (void) fclose(fp); - } - interp = buf + 2; - } - - (void) mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s%c%s", - interp, interp[0] == '\0' ? "" : " ", dir, DIRSEP, prog); - - DEBUG_TRACE(("Running [%s]", cmdline)); - if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, - CREATE_NEW_PROCESS_GROUP, envblk, dir, &si, &pi) == 0) { - cry(conn, "%s: CreateProcess(%s): %d", - __func__, cmdline, ERRNO); - pi.hProcess = (pid_t) -1; - } - - // Always close these to prevent handle leakage. - (void) close(fd_stdin); - (void) close(fd_stdout); - - (void) CloseHandle(si.hStdOutput); - (void) CloseHandle(si.hStdInput); - (void) CloseHandle(pi.hThread); - - return (pid_t) pi.hProcess; -} -#endif // !NO_CGI - -static int set_non_blocking_mode(SOCKET sock) { - unsigned long on = 1; - return ioctlsocket(sock, FIONBIO, &on); -} - -#else -static int mg_stat(const char *path, struct mgstat *stp) { - struct stat st; - int ok; - - if (stat(path, &st) == 0) { - ok = 0; - stp->size = st.st_size; - stp->mtime = st.st_mtime; - stp->is_directory = S_ISDIR(st.st_mode); - } else { - ok = -1; - } - - return ok; -} - -static void set_close_on_exec(int fd) { - (void) fcntl(fd, F_SETFD, FD_CLOEXEC); -} - -int mg_start_thread(mg_thread_func_t func, void *param) { - pthread_t thread_id; - pthread_attr_t attr; - - (void) pthread_attr_init(&attr); - (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled - // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5); - - return pthread_create(&thread_id, &attr, func, param); -} - -#ifndef NO_CGI -static pid_t spawn_process(struct mg_connection *conn, const char *prog, - char *envblk, char *envp[], int fd_stdin, - int fd_stdout, const char *dir) { - pid_t pid; - const char *interp; - - envblk = NULL; // Unused - - if ((pid = fork()) == -1) { - // Parent - send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO)); - } else if (pid == 0) { - // Child - if (chdir(dir) != 0) { - cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO)); - } else if (dup2(fd_stdin, 0) == -1) { - cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO)); - } else if (dup2(fd_stdout, 1) == -1) { - cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO)); - } else { - (void) dup2(fd_stdout, 2); - (void) close(fd_stdin); - (void) close(fd_stdout); - - interp = conn->ctx->config[CGI_INTERPRETER]; - if (interp == NULL) { - (void) execle(prog, prog, NULL, envp); - cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO)); - } else { - (void) execle(interp, interp, prog, NULL, envp); - cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog, - strerror(ERRNO)); - } - } - exit(EXIT_FAILURE); - } - - // Parent. Close stdio descriptors - (void) close(fd_stdin); - (void) close(fd_stdout); - - return pid; -} -#endif // !NO_CGI - -static int set_non_blocking_mode(SOCKET sock) { - int flags; - - flags = fcntl(sock, F_GETFL, 0); - (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK); - +static int capture_len(struct frozen *f, int token_index, const char *ptr) { + if (f->tokens == 0 || f->max_tokens == 0) return 0; + EXPECT(token_index >= 0 && token_index < f->max_tokens, JSON_STRING_INVALID); + f->tokens[token_index].len = ptr - f->tokens[token_index].ptr; + f->tokens[token_index].num_desc = (f->num_tokens - 1) - token_index; return 0; } -#endif // _WIN32 -// Write data to the IO channel - opened file descriptor, socket or SSL -// descriptor. Return number of bytes written. -static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf, - int64_t len) { - int64_t sent; - int n, k; +/* identifier = letter { letter | digit | '_' } */ +static int parse_identifier(struct frozen *f) { + EXPECT(is_alpha(cur(f)), JSON_STRING_INVALID); + TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING)); + while (f->cur < f->end && + (*f->cur == '_' || is_alpha(*f->cur) || is_digit(*f->cur))) { + f->cur++; + } + capture_len(f, f->num_tokens - 1, f->cur); + return 0; +} - sent = 0; - while (sent < len) { +static int get_utf8_char_len(unsigned char ch) { + if ((ch & 0x80) == 0) return 1; + switch (ch & 0xf0) { + case 0xf0: return 4; + case 0xe0: return 3; + default: return 2; + } +} - // How many bytes we send in this iteration - k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent); - - if (ssl != NULL) { - n = SSL_write(ssl, buf + sent, k); - } else if (fp != NULL) { - n = (int) fwrite(buf + sent, 1, (size_t) k, fp); - if (ferror(fp)) - n = -1; - } else { - n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL); - } - - if (n < 0) +/* string = '"' { quoted_printable_chars } '"' */ +static int parse_string(struct frozen *f) { + int n, ch = 0, len = 0; + TRY(test_and_skip(f, '"')); + TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING)); + for (; f->cur < f->end; f->cur += len) { + ch = * (unsigned char *) f->cur; + len = get_utf8_char_len((unsigned char) ch); + EXPECT(ch >= 32 && len > 0, JSON_STRING_INVALID); /* No control chars */ + EXPECT(len < left(f), JSON_STRING_INCOMPLETE); + if (ch == '\\') { + EXPECT((n = get_escape_len(f->cur + 1, left(f))) > 0, n); + len += n; + } else if (ch == '"') { + capture_len(f, f->num_tokens - 1, f->cur); + f->cur++; break; + }; + } + return ch == '"' ? 0 : JSON_STRING_INCOMPLETE; +} - sent += n; +/* number = [ '-' ] digit+ [ '.' digit+ ] [ ['e'|'E'] ['+'|'-'] digit+ ] */ +static int parse_number(struct frozen *f) { + int ch = cur(f); + TRY(capture_ptr(f, f->cur, JSON_TYPE_NUMBER)); + if (ch == '-') f->cur++; + EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE); + EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID); + while (f->cur < f->end && is_digit(f->cur[0])) f->cur++; + if (f->cur < f->end && f->cur[0] == '.') { + f->cur++; + EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE); + EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID); + while (f->cur < f->end && is_digit(f->cur[0])) f->cur++; + } + if (f->cur < f->end && (f->cur[0] == 'e' || f->cur[0] == 'E')) { + f->cur++; + EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE); + if ((f->cur[0] == '+' || f->cur[0] == '-')) f->cur++; + EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE); + EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID); + while (f->cur < f->end && is_digit(f->cur[0])) f->cur++; + } + capture_len(f, f->num_tokens - 1, f->cur); + return 0; +} + +/* array = '[' [ value { ',' value } ] ']' */ +static int parse_array(struct frozen *f) { + int ind; + TRY(test_and_skip(f, '[')); + TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_ARRAY)); + ind = f->num_tokens - 1; + while (cur(f) != ']') { + TRY(parse_value(f)); + if (cur(f) == ',') f->cur++; + } + TRY(test_and_skip(f, ']')); + capture_len(f, ind, f->cur); + return 0; +} + +static int compare(const char *s, const char *str, int len) { + int i = 0; + while (i < len && s[i] == str[i]) i++; + return i == len ? 1 : 0; +} + +static int expect(struct frozen *f, const char *s, int len, enum json_type t) { + int i, n = left(f); + + TRY(capture_ptr(f, f->cur, t)); + for (i = 0; i < len; i++) { + if (i >= n) return JSON_STRING_INCOMPLETE; + if (f->cur[i] != s[i]) return JSON_STRING_INVALID; + } + f->cur += len; + TRY(capture_len(f, f->num_tokens - 1, f->cur)); + + return 0; +} + +/* value = 'null' | 'true' | 'false' | number | string | array | object */ +static int parse_value(struct frozen *f) { + int ch = cur(f); + + switch (ch) { + case '"': TRY(parse_string(f)); break; + case '{': TRY(parse_object(f)); break; + case '[': TRY(parse_array(f)); break; + case 'n': TRY(expect(f, "null", 4, JSON_TYPE_NULL)); break; + case 't': TRY(expect(f, "true", 4, JSON_TYPE_TRUE)); break; + case 'f': TRY(expect(f, "false", 5, JSON_TYPE_FALSE)); break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + TRY(parse_number(f)); + break; + default: + return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID; } - return sent; + return 0; } -// This function is needed to prevent Mongoose to be stuck in a blocking -// socket read when user requested exit. To do that, we sleep in select -// with a timeout, and when returned, check the context for the stop flag. -// If it is set, we return 0, and this means that we must not continue -// reading, must give up and close the connection and exit serving thread. -static int wait_until_socket_is_readable(struct mg_connection *conn) { - int result; - struct timeval tv; - fd_set set; - - do { - tv.tv_sec = 0; - tv.tv_usec = 300 * 1000; - FD_ZERO(&set); - FD_SET(conn->client.sock, &set); - result = select(conn->client.sock + 1, &set, NULL, NULL, &tv); - } while ((result == 0 || (result < 0 && ERRNO == EINTR)) && - conn->ctx->stop_flag == 0); - - return conn->ctx->stop_flag || result < 0 ? 0 : 1; -} - -// Read from IO channel - opened file descriptor, socket, or SSL descriptor. -// Return negative value on error, or number of bytes read on success. -static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) { - int nread; - - if (fp != NULL) { - // Use read() instead of fread(), because if we're reading from the CGI - // pipe, fread() may block until IO buffer is filled up. We cannot afford - // to block and must pass all read bytes immediately to the client. - nread = read(fileno(fp), buf, (size_t) len); - } else if (!wait_until_socket_is_readable(conn)) { - nread = -1; - } else if (conn->ssl != NULL) { - nread = SSL_read(conn->ssl, buf, len); +/* key = identifier | string */ +static int parse_key(struct frozen *f) { + int ch = cur(f); +#if 0 + printf("%s 1 [%.*s]\n", __func__, (int) (f->end - f->cur), f->cur); +#endif + if (is_alpha(ch)) { + TRY(parse_identifier(f)); + } else if (ch == '"') { + TRY(parse_string(f)); } else { - nread = recv(conn->client.sock, buf, (size_t) len, 0); + return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID; } - - return conn->ctx->stop_flag ? -1 : nread; + return 0; } -int mg_read(struct mg_connection *conn, void *buf, size_t len) { - int n, buffered_len, nread; +/* pair = key ':' value */ +static int parse_pair(struct frozen *f) { + TRY(parse_key(f)); + TRY(test_and_skip(f, ':')); + TRY(parse_value(f)); + return 0; +} - assert(conn->next_request != NULL && - conn->body != NULL && - conn->next_request >= conn->body); - nread = 0; - if (conn->consumed_content < conn->content_len) { +/* object = '{' pair { ',' pair } '}' */ +static int parse_object(struct frozen *f) { + int ind; + TRY(test_and_skip(f, '{')); + TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_OBJECT)); + ind = f->num_tokens - 1; + while (cur(f) != '}') { + TRY(parse_pair(f)); + if (cur(f) == ',') f->cur++; + } + TRY(test_and_skip(f, '}')); + capture_len(f, ind, f->cur); + return 0; +} - // Adjust number of bytes to read. - int64_t to_read = conn->content_len - conn->consumed_content; - if (to_read < (int64_t) len) { - len = (size_t) to_read; - } +static int doit(struct frozen *f) { + if (f->cur == 0 || f->end < f->cur) return JSON_STRING_INVALID; + if (f->end == f->cur) return JSON_STRING_INCOMPLETE; + TRY(parse_object(f)); + TRY(capture_ptr(f, f->cur, JSON_TYPE_EOF)); + capture_len(f, f->num_tokens, f->cur); + return 0; +} - // Return buffered data - buffered_len = conn->next_request - conn->body; - if (buffered_len > 0) { - if (len < (size_t) buffered_len) { - buffered_len = (int) len; +/* json = object */ +int parse_json(const char *s, int s_len, struct json_token *arr, int arr_len) { + struct frozen frozen; + + memset(&frozen, 0, sizeof(frozen)); + frozen.end = s + s_len; + frozen.cur = s; + frozen.tokens = arr; + frozen.max_tokens = arr_len; + + TRY(doit(&frozen)); + + return frozen.cur - s; +} + +struct json_token *parse_json2(const char *s, int s_len) { + struct frozen frozen; + + memset(&frozen, 0, sizeof(frozen)); + frozen.end = s + s_len; + frozen.cur = s; + frozen.do_realloc = 1; + + if (doit(&frozen) < 0) { + FROZEN_FREE((void *) frozen.tokens); + frozen.tokens = NULL; + } + return frozen.tokens; +} + +static int path_part_len(const char *p) { + int i = 0; + while (p[i] != '\0' && p[i] != '[' && p[i] != '.') i++; + return i; +} + +struct json_token *find_json_token(struct json_token *toks, const char *path) { + while (path != 0 && path[0] != '\0') { + int i, ind2 = 0, ind = -1, skip = 2, n = path_part_len(path); + if (path[0] == '[') { + if (toks->type != JSON_TYPE_ARRAY || !is_digit(path[1])) return 0; + for (ind = 0, n = 1; path[n] != ']' && path[n] != '\0'; n++) { + if (!is_digit(path[n])) return 0; + ind *= 10; + ind += path[n] - '0'; } - memcpy(buf, conn->body, (size_t) buffered_len); - len -= buffered_len; - conn->body += buffered_len; - conn->consumed_content += buffered_len; - nread += buffered_len; - buf = (char *) buf + buffered_len; - } - - // We have returned all buffered data. Read new data from the remote socket. - while (len > 0) { - n = pull(NULL, conn, (char *) buf, (int) len); - if (n < 0) { - nread = n; // Propagate the error + if (path[n++] != ']') return 0; + skip = 1; /* In objects, we skip 2 elems while iterating, in arrays 1. */ + } else if (toks->type != JSON_TYPE_OBJECT) return 0; + toks++; + for (i = 0; i < toks[-1].num_desc; i += skip, ind2++) { + /* ind == -1 indicated that we're iterating an array, not object */ + if (ind == -1 && toks[i].type != JSON_TYPE_STRING) return 0; + if (ind2 == ind || + (ind == -1 && toks[i].len == n && compare(path, toks[i].ptr, n))) { + i += skip - 1; break; - } else if (n == 0) { - break; // No more data to read - } else { - buf = (char *) buf + n; - conn->consumed_content += n; - nread += n; - len -= n; + }; + if (toks[i - 1 + skip].type == JSON_TYPE_ARRAY || + toks[i - 1 + skip].type == JSON_TYPE_OBJECT) { + i += toks[i - 1 + skip].num_desc; } } + if (i == toks[-1].num_desc) return 0; + path += n; + if (path[0] == '.') path++; + if (path[0] == '\0') return &toks[i]; + toks += i; } - return nread; + return 0; } -int mg_write(struct mg_connection *conn, const void *buf, size_t len) { - return (int) push(NULL, conn->client.sock, conn->ssl, (const char *) buf, - (int64_t) len); +int json_emit_long(char *buf, int buf_len, long int value) { + char tmp[20]; + int n = snprintf(tmp, sizeof(tmp), "%ld", value); + strncpy(buf, tmp, buf_len > 0 ? buf_len : 0); + return n; } -int mg_printf(struct mg_connection *conn, const char *fmt, ...) { - char mem[MG_BUF_LEN], *buf = mem; +int json_emit_double(char *buf, int buf_len, double value) { + char tmp[20]; + int n = snprintf(tmp, sizeof(tmp), "%g", value); + strncpy(buf, tmp, buf_len > 0 ? buf_len : 0); + return n; +} + +int json_emit_quoted_str(char *s, int s_len, const char *str, int len) { + const char *begin = s, *end = s + s_len, *str_end = str + len; + char ch; + +#define EMIT(x) do { if (s < end) *s = x; s++; } while (0) + + EMIT('"'); + while (str < str_end) { + ch = *str++; + switch (ch) { + case '"': EMIT('\\'); EMIT('"'); break; + case '\\': EMIT('\\'); EMIT('\\'); break; + case '\b': EMIT('\\'); EMIT('b'); break; + case '\f': EMIT('\\'); EMIT('f'); break; + case '\n': EMIT('\\'); EMIT('n'); break; + case '\r': EMIT('\\'); EMIT('r'); break; + case '\t': EMIT('\\'); EMIT('t'); break; + default: EMIT(ch); + } + } + EMIT('"'); + if (s < end) { + *s = '\0'; + } + + return s - begin; +} + +int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len) { + if (buf_len > 0 && len > 0) { + int n = len < buf_len ? len : buf_len; + memcpy(buf, str, n); + if (n < buf_len) { + buf[n] = '\0'; + } + } + return len; +} + +int json_emit_va(char *s, int s_len, const char *fmt, va_list ap) { + const char *end = s + s_len, *str, *orig = s; + size_t len; + + while (*fmt != '\0') { + switch (*fmt) { + case '[': case ']': case '{': case '}': case ',': case ':': + case ' ': case '\r': case '\n': case '\t': + if (s < end) { + *s = *fmt; + } + s++; + break; + case 'i': + s += json_emit_long(s, end - s, va_arg(ap, long)); + break; + case 'f': + s += json_emit_double(s, end - s, va_arg(ap, double)); + break; + case 'v': + str = va_arg(ap, char *); + len = va_arg(ap, size_t); + s += json_emit_quoted_str(s, end - s, str, len); + break; + case 'V': + str = va_arg(ap, char *); + len = va_arg(ap, size_t); + s += json_emit_unquoted_str(s, end - s, str, len); + break; + case 's': + str = va_arg(ap, char *); + s += json_emit_quoted_str(s, end - s, str, strlen(str)); + break; + case 'S': + str = va_arg(ap, char *); + s += json_emit_unquoted_str(s, end - s, str, strlen(str)); + break; + case 'T': + s += json_emit_unquoted_str(s, end - s, "true", 4); + break; + case 'F': + s += json_emit_unquoted_str(s, end - s, "false", 5); + break; + case 'N': + s += json_emit_unquoted_str(s, end - s, "null", 4); + break; + default: + return 0; + } + fmt++; + } + + /* Best-effort to 0-terminate generated string */ + if (s < end) { + *s = '\0'; + } + + return s - orig; +} + +int json_emit(char *buf, int buf_len, const char *fmt, ...) { int len; va_list ap; - // Print in a local buffer first, hoping that it is large enough to - // hold the whole message va_start(ap, fmt); - len = vsnprintf(mem, sizeof(mem), fmt, ap); + len = json_emit_va(buf, buf_len, fmt, ap); va_end(ap); - if (len <= 0) { - // vsnprintf() error, give up - len = -1; - cry(conn, "%s(%s, ...): vsnprintf() error", __func__, fmt); - } else if (len > (int) sizeof(mem) && (buf = malloc(len + 1)) != NULL) { - // Local buffer is not large enough, allocate big buffer on heap - va_start(ap, fmt); - vsnprintf(buf, len + 1, fmt, ap); - va_end(ap); - len = mg_write(conn, buf, (size_t) len); - free(buf); - } else if (len > (int) sizeof(mem)) { - // Failed to allocate large enough buffer, give up - cry(conn, "%s(%s, ...): Can't allocate %d bytes, not printing anything", - __func__, fmt, len); - len = -1; - } else { - // Copy to the local buffer succeeded - len = mg_write(conn, buf, (size_t) len); - } - return len; } +#ifdef NS_MODULE_LINES +#line 1 "src/../../common/md5.c" +/**/ +#endif +/* + * This code implements the MD5 message-digest algorithm. + * The algorithm is due to Ron Rivest. This code was + * written by Colin Plumb in 1993, no copyright is claimed. + * This code is in the public domain; do with it what you wish. + * + * Equivalent code is available from RSA Data Security, Inc. + * This code has been tested against that, and is equivalent, + * except that you don't need to include two pages of legalese + * with every copy. + * + * To compute the message digest of a chunk of bytes, declare an + * MD5Context structure, pass it to MD5Init, call MD5Update as + * needed on buffers full of bytes, and then call MD5Final, which + * will fill a supplied 16-byte array with the digest. + */ -// URL-decode input buffer into destination buffer. -// 0-terminate the destination buffer. Return the length of decoded data. -// form-url-encoded data differs from URI encoding in a way that it -// uses '+' as character for space, see RFC 1866 section 8.2.1 -// http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt -static size_t url_decode(const char *src, size_t src_len, char *dst, - size_t dst_len, int is_form_url_encoded) { - size_t i, j; - int a, b; -#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') +#if !defined(DISABLE_MD5) && !defined(EXCLUDE_COMMON) - for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { - if (src[i] == '%' && - isxdigit(* (const unsigned char *) (src + i + 1)) && - isxdigit(* (const unsigned char *) (src + i + 2))) { - a = tolower(* (const unsigned char *) (src + i + 1)); - b = tolower(* (const unsigned char *) (src + i + 2)); - dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); - i += 2; - } else if (is_form_url_encoded && src[i] == '+') { - dst[j] = ' '; - } else { - dst[j] = src[i]; - } - } +/* Amalgamated: #include "md5.h" */ - dst[j] = '\0'; // Null-terminate the destination - - return j; -} - -// Scan given buffer and fetch the value of the given variable. -// It can be specified in query string, or in the POST data. -// Return -1 if the variable not found, or length of the URL-decoded value -// stored in dst. The dst buffer is guaranteed to be NUL-terminated if it -// is not NULL or zero-length. If dst is NULL or zero-length, then -// -2 is returned. -int mg_get_var(const char *buf, size_t buf_len, const char *name, - char *dst, size_t dst_len) { - const char *p, *e, *s; - size_t name_len; - int len; - - if (dst == NULL || dst_len == 0) { - len = -2; - } else if (buf == NULL || name == NULL || buf_len == 0) { - len = -1; - dst[0] = '\0'; - } else { - name_len = strlen(name); - e = buf + buf_len; - len = -1; - dst[0] = '\0'; - - // buf is "var1=val1&var2=val2...". Find variable first - for (p = buf; p + name_len < e; p++) { - if ((p == buf || p[-1] == '&') && p[name_len] == '=' && - !mg_strncasecmp(name, p, name_len)) { - - // Point p to variable value - p += name_len + 1; - - // Point s to the end of the value - s = (const char *) memchr(p, '&', (size_t)(e - p)); - if (s == NULL) { - s = e; - } - assert(s >= p); - - // Decode variable into destination buffer - if ((size_t) (s - p) < dst_len) { - len = (int) url_decode(p, (size_t)(s - p), dst, dst_len, 1); - } - break; - } - } - } - - return len; -} - -int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name, - char *dst, size_t dst_size) { - const char *s, *p, *end; - int name_len, len = -1; - - dst[0] = '\0'; - if ((s = mg_get_header(conn, "Cookie")) == NULL) { - return -1; - } - - name_len = (int) strlen(cookie_name); - end = s + strlen(s); - - for (; (s = strstr(s, cookie_name)) != NULL; s += name_len) - if (s[name_len] == '=') { - s += name_len + 1; - if ((p = strchr(s, ' ')) == NULL) - p = end; - if (p[-1] == ';') - p--; - if (*s == '"' && p[-1] == '"' && p > s + 1) { - s++; - p--; - } - if ((size_t) (p - s) < dst_size) { - len = p - s; - mg_strlcpy(dst, s, (size_t) len + 1); - } - break; - } - - return len; -} - -static int convert_uri_to_file_name(struct mg_connection *conn, char *buf, - size_t buf_len, struct mgstat *st) { - struct vec a, b; - const char *rewrite, *uri = conn->request_info.uri; - char *p; - int match_len, stat_result; - - buf_len--; // This is because memmove() for PATH_INFO may shift part - // of the path one byte on the right. - mg_snprintf(conn, buf, buf_len, "%s%s", conn->ctx->config[DOCUMENT_ROOT], - uri); - - rewrite = conn->ctx->config[REWRITE]; - while ((rewrite = next_option(rewrite, &a, &b)) != NULL) { - if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) { - mg_snprintf(conn, buf, buf_len, "%.*s%s", b.len, b.ptr, uri + match_len); - break; - } - } - -#if defined(_WIN32) && !defined(__SYMBIAN32__) - //change_slashes_to_backslashes(buf); -#endif // _WIN32 - - if ((stat_result = mg_stat(buf, st)) != 0) { - // Support PATH_INFO for CGI scripts. - for (p = buf + strlen(buf); p > buf + 1; p--) { - if (*p == '/') { - *p = '\0'; - if (match_prefix(conn->ctx->config[CGI_EXTENSIONS], - strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 && - (stat_result = mg_stat(buf, st)) == 0) { - // Shift PATH_INFO block one character right, e.g. - // "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00" - // conn->path_info is pointing to the local variable "path" declared - // in handle_request(), so PATH_INFO is not valid after - // handle_request returns. - conn->path_info = p + 1; - memmove(p + 2, p + 1, strlen(p + 1) + 1); // +1 is for trailing \0 - p[1] = '/'; - break; - } else { - *p = '/'; - stat_result = -1; - } - } - } - } - - return stat_result; -} - -static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) { - return (conn->ssl = SSL_new(s)) != NULL && - SSL_set_fd(conn->ssl, conn->client.sock) == 1 && - func(conn->ssl) == 1; -} - -// Check whether full request is buffered. Return: -// -1 if request is malformed -// 0 if request is not yet fully buffered -// >0 actual request length, including last \r\n\r\n -static int get_request_len(const char *buf, int buflen) { - const char *s, *e; - int len = 0; - - for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++) - // Control characters are not allowed but >=128 is. - if (!isprint(* (const unsigned char *) s) && *s != '\r' && - *s != '\n' && * (const unsigned char *) s < 128) { - len = -1; - break; // [i_a] abort scan as soon as one malformed character is found; don't let subsequent \r\n\r\n win us over anyhow - } else if (s[0] == '\n' && s[1] == '\n') { - len = (int) (s - buf) + 2; - } else if (s[0] == '\n' && &s[1] < e && - s[1] == '\r' && s[2] == '\n') { - len = (int) (s - buf) + 3; - } - - return len; -} - -// Convert month to the month number. Return -1 on error, or month number -static int get_month_index(const char *s) { - size_t i; - - for (i = 0; i < ARRAY_SIZE(month_names); i++) - if (!strcmp(s, month_names[i])) - return (int) i; - - return -1; -} - -// Parse UTC date-time string, and return the corresponding time_t value. -static time_t parse_date_string(const char *datetime) { - static const unsigned short days_before_month[] = { - 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 - }; - char month_str[32]; - int second, minute, hour, day, month, year, leap_days, days; - time_t result = (time_t) 0; - - if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", - &day, month_str, &year, &hour, &minute, &second) == 6) || - (sscanf(datetime, "%d %3s %d %d:%d:%d", - &day, month_str, &year, &hour, &minute, &second) == 6) || - (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", - &day, month_str, &year, &hour, &minute, &second) == 6) || - (sscanf(datetime, "%d-%3s-%d %d:%d:%d", - &day, month_str, &year, &hour, &minute, &second) == 6)) && - year > 1970 && - (month = get_month_index(month_str)) != -1) { - year -= 1970; - leap_days = year / 4 - year / 100 + year / 400; - days = year * 365 + days_before_month[month] + (day - 1) + leap_days; - result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; - } - - return result; -} - -// Protect against directory disclosure attack by removing '..', -// excessive '/' and '\' characters -static void remove_double_dots_and_double_slashes(char *s) { - char *p = s; - - while (*s != '\0') { - *p++ = *s++; - if (IS_DIRSEP_CHAR(s[-1])) { - // Skip all following slashes and backslashes - while (IS_DIRSEP_CHAR(s[0])) { - s++; - } - - // Skip all double-dots - while (*s == '.' && s[1] == '.') { - s += 2; - } - } - } - *p = '\0'; -} - -static const struct { - const char *extension; - size_t ext_len; - const char *mime_type; -} builtin_mime_types[] = { - {".html", 5, "text/html"}, - {".htm", 4, "text/html"}, - {".shtm", 5, "text/html"}, - {".shtml", 6, "text/html"}, - {".css", 4, "text/css"}, - {".js", 3, "application/x-javascript"}, - {".ico", 4, "image/x-icon"}, - {".gif", 4, "image/gif"}, - {".jpg", 4, "image/jpeg"}, - {".jpeg", 5, "image/jpeg"}, - {".png", 4, "image/png"}, - {".svg", 4, "image/svg+xml"}, - {".txt", 4, "text/plain"}, - {".torrent", 8, "application/x-bittorrent"}, - {".wav", 4, "audio/x-wav"}, - {".mp3", 4, "audio/x-mp3"}, - {".mid", 4, "audio/mid"}, - {".m3u", 4, "audio/x-mpegurl"}, - {".ram", 4, "audio/x-pn-realaudio"}, - {".xml", 4, "text/xml"}, - {".json", 5, "text/json"}, - {".xslt", 5, "application/xml"}, - {".ra", 3, "audio/x-pn-realaudio"}, - {".doc", 4, "application/msword"}, - {".exe", 4, "application/octet-stream"}, - {".zip", 4, "application/x-zip-compressed"}, - {".xls", 4, "application/excel"}, - {".tgz", 4, "application/x-tar-gz"}, - {".tar", 4, "application/x-tar"}, - {".gz", 3, "application/x-gunzip"}, - {".arj", 4, "application/x-arj-compressed"}, - {".rar", 4, "application/x-arj-compressed"}, - {".rtf", 4, "application/rtf"}, - {".pdf", 4, "application/pdf"}, - {".swf", 4, "application/x-shockwave-flash"}, - {".mpg", 4, "video/mpeg"}, - {".webm", 5, "video/webm"}, - {".mpeg", 5, "video/mpeg"}, - {".mp4", 4, "video/mp4"}, - {".m4v", 4, "video/x-m4v"}, - {".asf", 4, "video/x-ms-asf"}, - {".avi", 4, "video/x-msvideo"}, - {".bmp", 4, "image/bmp"}, - {NULL, 0, NULL} -}; - -const char *mg_get_builtin_mime_type(const char *path) { - const char *ext; - size_t i, path_len; - - path_len = strlen(path); - - for (i = 0; builtin_mime_types[i].extension != NULL; i++) { - ext = path + (path_len - builtin_mime_types[i].ext_len); - if (path_len > builtin_mime_types[i].ext_len && - mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) { - return builtin_mime_types[i].mime_type; - } - } - - return "text/plain"; -} - -// Look at the "path" extension and figure what mime type it has. -// Store mime type in the vector. -static void get_mime_type(struct mg_context *ctx, const char *path, - struct vec *vec) { - struct vec ext_vec, mime_vec; - const char *list, *ext; - size_t path_len; - - path_len = strlen(path); - - // Scan user-defined mime types first, in case user wants to - // override default mime types. - list = ctx->config[EXTRA_MIME_TYPES]; - while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) { - // ext now points to the path suffix - ext = path + path_len - ext_vec.len; - if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) { - *vec = mime_vec; - return; - } - } - - vec->ptr = mg_get_builtin_mime_type(path); - vec->len = strlen(vec->ptr); -} - -#ifndef HAVE_MD5 -typedef struct MD5Context { - uint32_t buf[4]; - uint32_t bits[2]; - unsigned char in[64]; -} MD5_CTX; - -#if defined(__BYTE_ORDER) && (__BYTE_ORDER == 1234) -#define byteReverse(buf, len) // Do nothing -#else +#ifndef CS_ENABLE_NATIVE_MD5 static void byteReverse(unsigned char *buf, unsigned longs) { - uint32_t t; +/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */ +#if BYTE_ORDER == BIG_ENDIAN do { - t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 | - ((unsigned) buf[1] << 8 | buf[0]); + uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 | + ((unsigned) buf[1] << 8 | buf[0]); *(uint32_t *) buf = t; buf += 4; } while (--longs); -} +#else + (void) buf; + (void) longs; #endif +} #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) @@ -1896,11 +983,13 @@ static void byteReverse(unsigned char *buf, unsigned longs) { #define F4(x, y, z) (y ^ (x | ~z)) #define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) -// Start MD5 accumulation. Set bit count to 0 and buffer to mysterious -// initialization constants. -static void MD5Init(MD5_CTX *ctx) { +/* + * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious + * initialization constants. + */ +void MD5_Init(MD5_CTX *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; @@ -1992,13 +1081,12 @@ static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) { buf[3] += d; } -static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) { +void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len) { uint32_t t; t = ctx->bits[0]; - if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) - ctx->bits[1]++; - ctx->bits[1] += len >> 29; + if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++; + ctx->bits[1] += (uint32_t) len >> 29; t = (t >> 3) & 0x3f; @@ -2028,9 +1116,10 @@ static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) { memcpy(ctx->in, buf, len); } -static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) { +void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) { unsigned count; unsigned char *p; + uint32_t *a; count = (ctx->bits[0] >> 3) & 0x3F; @@ -2047,19 +1136,23 @@ static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) { } byteReverse(ctx->in, 14); - ((uint32_t *) ctx->in)[14] = ctx->bits[0]; - ((uint32_t *) ctx->in)[15] = ctx->bits[1]; + a = (uint32_t *) ctx->in; + a[14] = ctx->bits[0]; + a[15] = ctx->bits[1]; MD5Transform(ctx->buf, (uint32_t *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset((char *) ctx, 0, sizeof(*ctx)); } -#endif // !HAVE_MD5 +#endif /* CS_ENABLE_NATIVE_MD5 */ -// Stringify binary data. Output buffer must be twice as big as input, -// because each byte takes 2 bytes in string representation -static void bin2str(char *to, const unsigned char *p, size_t len) { +/* + * Stringify binary data. Output buffer size must be 2 * size_of_input + 1 + * because each byte of input takes 2 bytes in string representation + * plus 1 byte for the terminating \0 character. + */ +void cs_to_hex(char *to, const unsigned char *p, size_t len) { static const char *hex = "0123456789abcdef"; for (; len--; p++) { @@ -2069,1676 +1162,1565 @@ static void bin2str(char *to, const unsigned char *p, size_t len) { *to = '\0'; } -// Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. -void mg_md5(char buf[33], ...) { +char *cs_md5(char buf[33], ...) { unsigned char hash[16]; - const char *p; + const unsigned char *p; va_list ap; MD5_CTX ctx; - MD5Init(&ctx); + MD5_Init(&ctx); va_start(ap, buf); - while ((p = va_arg(ap, const char *)) != NULL) { - MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p)); + while ((p = va_arg(ap, const unsigned char *) ) != NULL) { + size_t len = va_arg(ap, size_t); + MD5_Update(&ctx, p, len); } va_end(ap); - MD5Final(hash, &ctx); - bin2str(buf, hash, sizeof(hash)); + MD5_Final(hash, &ctx); + cs_to_hex(buf, hash, sizeof(hash)); + + return buf; } -// Check the user's password, return 1 if OK -static int check_password(const char *method, const char *ha1, const char *uri, - const char *nonce, const char *nc, const char *cnonce, - const char *qop, const char *response) { - char ha2[32 + 1], expected_response[32 + 1]; +#endif /* EXCLUDE_COMMON */ +#ifdef NS_MODULE_LINES +#line 1 "src/../../common/mbuf.c" +/**/ +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + */ - // Some of the parameters may be NULL - if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL || - qop == NULL || response == NULL) { - return 0; - } +#ifndef EXCLUDE_COMMON - // NOTE(lsm): due to a bug in MSIE, we do not compare the URI - // TODO(lsm): check for authentication timeout - if (// strcmp(dig->uri, c->ouri) != 0 || - strlen(response) != 32 - // || now - strtoul(dig->nonce, NULL, 10) > 3600 - ) { - return 0; - } +#include +#include +/* Amalgamated: #include "mbuf.h" */ - mg_md5(ha2, method, ":", uri, NULL); - mg_md5(expected_response, ha1, ":", nonce, ":", nc, - ":", cnonce, ":", qop, ":", ha2, NULL); +#ifndef MBUF_REALLOC +#define MBUF_REALLOC realloc +#endif - return mg_strcasecmp(response, expected_response) == 0; +#ifndef MBUF_FREE +#define MBUF_FREE free +#endif + +void mbuf_init(struct mbuf *mbuf, size_t initial_size) { + mbuf->len = mbuf->size = 0; + mbuf->buf = NULL; + mbuf_resize(mbuf, initial_size); } -// Use the global passwords file, if specified by auth_gpass option, -// or search for .htpasswd in the requested directory. -static FILE *open_auth_file(struct mg_connection *conn, const char *path) { - struct mg_context *ctx = conn->ctx; - char name[PATH_MAX]; - const char *p, *e; - struct mgstat st; - FILE *fp; +void mbuf_free(struct mbuf *mbuf) { + if (mbuf->buf != NULL) { + MBUF_FREE(mbuf->buf); + mbuf_init(mbuf, 0); + } +} - if (ctx->config[GLOBAL_PASSWORDS_FILE] != NULL) { - // Use global passwords file - fp = mg_fopen(ctx->config[GLOBAL_PASSWORDS_FILE], "r"); - if (fp == NULL) - cry(fc(ctx), "fopen(%s): %s", - ctx->config[GLOBAL_PASSWORDS_FILE], strerror(ERRNO)); - } else if (!mg_stat(path, &st) && st.is_directory) { - (void) mg_snprintf(conn, name, sizeof(name), "%s%c%s", - path, DIRSEP, PASSWORDS_FILE_NAME); - fp = mg_fopen(name, "r"); +void mbuf_resize(struct mbuf *a, size_t new_size) { + if (new_size > a->size || (new_size < a->size && new_size >= a->len)) { + char *buf = (char *) MBUF_REALLOC(a->buf, new_size); + /* + * In case realloc fails, there's not much we can do, except keep things as + * they are. Note that NULL is a valid return value from realloc when + * size == 0, but that is covered too. + */ + if (buf == NULL && new_size != 0) return; + a->buf = buf; + a->size = new_size; + } +} + +void mbuf_trim(struct mbuf *mbuf) { + mbuf_resize(mbuf, mbuf->len); +} + +size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) { + char *p = NULL; + + assert(a != NULL); + assert(a->len <= a->size); + assert(off <= a->len); + + /* check overflow */ + if (~(size_t) 0 - (size_t) a->buf < len) return 0; + + if (a->len + len <= a->size) { + memmove(a->buf + off + len, a->buf + off, a->len - off); + if (buf != NULL) { + memcpy(a->buf + off, buf, len); + } + a->len += len; + } else if ((p = (char *) MBUF_REALLOC( + a->buf, (a->len + len) * MBUF_SIZE_MULTIPLIER)) != NULL) { + a->buf = p; + memmove(a->buf + off + len, a->buf + off, a->len - off); + if (buf != NULL) { + memcpy(a->buf + off, buf, len); + } + a->len += len; + a->size = a->len * MBUF_SIZE_MULTIPLIER; } else { - // Try to find .htpasswd in requested directory. - for (p = path, e = p + strlen(p) - 1; e > p; e--) - if (IS_DIRSEP_CHAR(*e)) - break; - (void) mg_snprintf(conn, name, sizeof(name), "%.*s%c%s", - (int) (e - p), p, DIRSEP, PASSWORDS_FILE_NAME); - fp = mg_fopen(name, "r"); + len = 0; } - return fp; + return len; } -// Parsed Authorization header -struct ah { - char *user, *uri, *cnonce, *response, *qop, *nc, *nonce; +size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) { + return mbuf_insert(a, a->len, buf, len); +} + +void mbuf_remove(struct mbuf *mb, size_t n) { + if (n > 0 && n <= mb->len) { + memmove(mb->buf, mb->buf + n, mb->len - n); + mb->len -= n; + } +} + +#endif /* EXCLUDE_COMMON */ +#ifdef NS_MODULE_LINES +#line 1 "src/../../common/sha1.c" +/**/ +#endif +/* Copyright(c) By Steve Reid */ +/* 100% Public Domain */ + +#if !defined(DISABLE_SHA1) && !defined(EXCLUDE_COMMON) + +/* Amalgamated: #include "sha1.h" */ + +#define SHA1HANDSOFF +#if defined(__sun) +/* Amalgamated: #include "solarisfixes.h" */ +#endif + +union char64long16 { + unsigned char c[64]; + uint32_t l[16]; }; -// Return 1 on success. Always initializes the ah structure. -static int parse_auth_header(struct mg_connection *conn, char *buf, - size_t buf_size, struct ah *ah) { - char *name, *value, *s; - const char *auth_header; +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) - (void) memset(ah, 0, sizeof(*ah)); - if ((auth_header = mg_get_header(conn, "Authorization")) == NULL || - mg_strncasecmp(auth_header, "Digest ", 7) != 0) { - return 0; +static uint32_t blk0(union char64long16 *block, int i) { +/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */ +#if BYTE_ORDER == LITTLE_ENDIAN + block->l[i] = + (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF); +#endif + return block->l[i]; +} + +/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */ +#undef blk +#undef R0 +#undef R1 +#undef R2 +#undef R3 +#undef R4 + +#define blk(i) \ + (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \ + block->l[(i + 2) & 15] ^ block->l[i & 15], \ + 1)) +#define R0(v, w, x, y, z, i) \ + z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \ + w = rol(w, 30); +#define R1(v, w, x, y, z, i) \ + z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \ + w = rol(w, 30); +#define R2(v, w, x, y, z, i) \ + z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \ + w = rol(w, 30); +#define R3(v, w, x, y, z, i) \ + z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \ + w = rol(w, 30); +#define R4(v, w, x, y, z, i) \ + z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \ + w = rol(w, 30); + +void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) { + uint32_t a, b, c, d, e; + union char64long16 block[1]; + + memcpy(block, buffer, 64); + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + R0(a, b, c, d, e, 0); + R0(e, a, b, c, d, 1); + R0(d, e, a, b, c, 2); + R0(c, d, e, a, b, 3); + R0(b, c, d, e, a, 4); + R0(a, b, c, d, e, 5); + R0(e, a, b, c, d, 6); + R0(d, e, a, b, c, 7); + R0(c, d, e, a, b, 8); + R0(b, c, d, e, a, 9); + R0(a, b, c, d, e, 10); + R0(e, a, b, c, d, 11); + R0(d, e, a, b, c, 12); + R0(c, d, e, a, b, 13); + R0(b, c, d, e, a, 14); + R0(a, b, c, d, e, 15); + R1(e, a, b, c, d, 16); + R1(d, e, a, b, c, 17); + R1(c, d, e, a, b, 18); + R1(b, c, d, e, a, 19); + R2(a, b, c, d, e, 20); + R2(e, a, b, c, d, 21); + R2(d, e, a, b, c, 22); + R2(c, d, e, a, b, 23); + R2(b, c, d, e, a, 24); + R2(a, b, c, d, e, 25); + R2(e, a, b, c, d, 26); + R2(d, e, a, b, c, 27); + R2(c, d, e, a, b, 28); + R2(b, c, d, e, a, 29); + R2(a, b, c, d, e, 30); + R2(e, a, b, c, d, 31); + R2(d, e, a, b, c, 32); + R2(c, d, e, a, b, 33); + R2(b, c, d, e, a, 34); + R2(a, b, c, d, e, 35); + R2(e, a, b, c, d, 36); + R2(d, e, a, b, c, 37); + R2(c, d, e, a, b, 38); + R2(b, c, d, e, a, 39); + R3(a, b, c, d, e, 40); + R3(e, a, b, c, d, 41); + R3(d, e, a, b, c, 42); + R3(c, d, e, a, b, 43); + R3(b, c, d, e, a, 44); + R3(a, b, c, d, e, 45); + R3(e, a, b, c, d, 46); + R3(d, e, a, b, c, 47); + R3(c, d, e, a, b, 48); + R3(b, c, d, e, a, 49); + R3(a, b, c, d, e, 50); + R3(e, a, b, c, d, 51); + R3(d, e, a, b, c, 52); + R3(c, d, e, a, b, 53); + R3(b, c, d, e, a, 54); + R3(a, b, c, d, e, 55); + R3(e, a, b, c, d, 56); + R3(d, e, a, b, c, 57); + R3(c, d, e, a, b, 58); + R3(b, c, d, e, a, 59); + R4(a, b, c, d, e, 60); + R4(e, a, b, c, d, 61); + R4(d, e, a, b, c, 62); + R4(c, d, e, a, b, 63); + R4(b, c, d, e, a, 64); + R4(a, b, c, d, e, 65); + R4(e, a, b, c, d, 66); + R4(d, e, a, b, c, 67); + R4(c, d, e, a, b, 68); + R4(b, c, d, e, a, 69); + R4(a, b, c, d, e, 70); + R4(e, a, b, c, d, 71); + R4(d, e, a, b, c, 72); + R4(c, d, e, a, b, 73); + R4(b, c, d, e, a, 74); + R4(a, b, c, d, e, 75); + R4(e, a, b, c, d, 76); + R4(d, e, a, b, c, 77); + R4(c, d, e, a, b, 78); + R4(b, c, d, e, a, 79); + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + /* Erase working structures. The order of operations is important, + * used to ensure that compiler doesn't optimize those out. */ + memset(block, 0, sizeof(block)); + a = b = c = d = e = 0; + (void) a; + (void) b; + (void) c; + (void) d; + (void) e; +} + +void cs_sha1_init(cs_sha1_ctx *context) { + context->state[0] = 0x67452301; + context->state[1] = 0xEFCDAB89; + context->state[2] = 0x98BADCFE; + context->state[3] = 0x10325476; + context->state[4] = 0xC3D2E1F0; + context->count[0] = context->count[1] = 0; +} + +void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data, + uint32_t len) { + uint32_t i, j; + + j = context->count[0]; + if ((context->count[0] += len << 3) < j) context->count[1]++; + context->count[1] += (len >> 29); + j = (j >> 3) & 63; + if ((j + len) > 63) { + memcpy(&context->buffer[j], data, (i = 64 - j)); + cs_sha1_transform(context->state, context->buffer); + for (; i + 63 < len; i += 64) { + cs_sha1_transform(context->state, &data[i]); + } + j = 0; + } else + i = 0; + memcpy(&context->buffer[j], &data[i], len - i); +} + +void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) { + unsigned i; + unsigned char finalcount[8], c; + + for (i = 0; i < 8; i++) { + finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> + ((3 - (i & 3)) * 8)) & + 255); + } + c = 0200; + cs_sha1_update(context, &c, 1); + while ((context->count[0] & 504) != 448) { + c = 0000; + cs_sha1_update(context, &c, 1); + } + cs_sha1_update(context, finalcount, 8); + for (i = 0; i < 20; i++) { + digest[i] = + (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); + } + memset(context, '\0', sizeof(*context)); + memset(&finalcount, '\0', sizeof(finalcount)); +} + +void cs_hmac_sha1(const unsigned char *key, size_t keylen, + const unsigned char *data, size_t datalen, + unsigned char out[20]) { + cs_sha1_ctx ctx; + unsigned char buf1[64], buf2[64], tmp_key[20], i; + + if (keylen > sizeof(buf1)) { + cs_sha1_init(&ctx); + cs_sha1_update(&ctx, key, keylen); + cs_sha1_final(tmp_key, &ctx); + key = tmp_key; + keylen = sizeof(tmp_key); } - // Make modifiable copy of the auth header - (void) mg_strlcpy(buf, auth_header + 7, buf_size); - s = buf; + memset(buf1, 0, sizeof(buf1)); + memset(buf2, 0, sizeof(buf2)); + memcpy(buf1, key, keylen); + memcpy(buf2, key, keylen); - // Parse authorization header - for (;;) { - // Gobble initial spaces - while (isspace(* (unsigned char *) s)) { - s++; - } - name = skip_quoted(&s, "=", " ", 0); - // Value is either quote-delimited, or ends at first comma or space. - if (s[0] == '\"') { - s++; - value = skip_quoted(&s, "\"", " ", '\\'); - if (s[0] == ',') { - s++; - } + for (i = 0; i < sizeof(buf1); i++) { + buf1[i] ^= 0x36; + buf2[i] ^= 0x5c; + } + + cs_sha1_init(&ctx); + cs_sha1_update(&ctx, buf1, sizeof(buf1)); + cs_sha1_update(&ctx, data, datalen); + cs_sha1_final(out, &ctx); + + cs_sha1_init(&ctx); + cs_sha1_update(&ctx, buf2, sizeof(buf2)); + cs_sha1_update(&ctx, out, 20); + cs_sha1_final(out, &ctx); +} + +#endif /* EXCLUDE_COMMON */ +#ifdef NS_MODULE_LINES +#line 1 "src/../../common/str_util.c" +/**/ +#endif +/* + * Copyright (c) 2015 Cesanta Software Limited + * All rights reserved + */ + +#ifndef EXCLUDE_COMMON + +/* Amalgamated: #include "osdep.h" */ +/* Amalgamated: #include "str_util.h" */ + +#ifdef _MG_PROVIDE_STRNLEN +size_t strnlen(const char *s, size_t maxlen) { + size_t l = 0; + for (; l < maxlen && s[l] != '\0'; l++) { + } + return l; +} +#endif + +#define C_SNPRINTF_APPEND_CHAR(ch) \ + do { \ + if (i < (int) buf_size) buf[i] = ch; \ + i++; \ + } while (0) + +#define C_SNPRINTF_FLAG_ZERO 1 + +#ifdef C_DISABLE_BUILTIN_SNPRINTF +int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { + return vsnprintf(buf, buf_size, fmt, ap); +} +#else +static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags, + int field_width) { + char tmp[40]; + int i = 0, k = 0, neg = 0; + + if (num < 0) { + neg++; + num = -num; + } + + /* Print into temporary buffer - in reverse order */ + do { + int rem = num % base; + if (rem < 10) { + tmp[k++] = '0' + rem; } else { - value = skip_quoted(&s, ", ", " ", 0); // IE uses commas, FF uses spaces - } - if (*name == '\0') { - break; + tmp[k++] = 'a' + (rem - 10); } + num /= base; + } while (num > 0); - if (!strcmp(name, "username")) { - ah->user = value; - } else if (!strcmp(name, "cnonce")) { - ah->cnonce = value; - } else if (!strcmp(name, "response")) { - ah->response = value; - } else if (!strcmp(name, "uri")) { - ah->uri = value; - } else if (!strcmp(name, "qop")) { - ah->qop = value; - } else if (!strcmp(name, "nc")) { - ah->nc = value; - } else if (!strcmp(name, "nonce")) { - ah->nonce = value; + /* Zero padding */ + if (flags && C_SNPRINTF_FLAG_ZERO) { + while (k < field_width && k < (int) sizeof(tmp) - 1) { + tmp[k++] = '0'; } } - // CGI needs it as REMOTE_USER - if (ah->user != NULL) { - conn->request_info.remote_user = mg_strdup(ah->user); - } else { - return 0; + /* And sign */ + if (neg) { + tmp[k++] = '-'; } - return 1; + /* Now output */ + while (--k >= 0) { + C_SNPRINTF_APPEND_CHAR(tmp[k]); + } + + return i; } -// Authorize against the opened passwords file. Return 1 if authorized. -static int authorize(struct mg_connection *conn, FILE *fp) { - struct ah ah; - char line[256], f_user[256], ha1[256], f_domain[256], buf[MG_BUF_LEN]; +int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { + int ch, i = 0, len_mod, flags, precision, field_width; - if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) { - return 0; - } - - // Loop over passwords file - while (fgets(line, sizeof(line), fp) != NULL) { - if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) { - continue; - } - - if (!strcmp(ah.user, f_user) && - !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain)) - return check_password( - conn->request_info.request_method, - ha1, ah.uri, ah.nonce, ah.nc, ah.cnonce, ah.qop, - ah.response); - } - - return 0; -} - -// Return 1 if request is authorised, 0 otherwise. -static int check_authorization(struct mg_connection *conn, const char *path) { - FILE *fp; - char fname[PATH_MAX]; - struct vec uri_vec, filename_vec; - const char *list; - int authorized; - - fp = NULL; - authorized = 1; - - list = conn->ctx->config[PROTECT_URI]; - while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) { - if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) { - (void) mg_snprintf(conn, fname, sizeof(fname), "%.*s", - filename_vec.len, filename_vec.ptr); - if ((fp = mg_fopen(fname, "r")) == NULL) { - cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno)); - } - break; - } - } - - if (fp == NULL) { - fp = open_auth_file(conn, path); - } - - if (fp != NULL) { - authorized = authorize(conn, fp); - (void) fclose(fp); - } - - return authorized; -} - -static void send_authorization_request(struct mg_connection *conn) { - conn->request_info.status_code = 401; - (void) mg_printf(conn, - "HTTP/1.1 401 Unauthorized\r\n" - "Content-Length: 0\r\n" - "WWW-Authenticate: Digest qop=\"auth\", " - "realm=\"%s\", nonce=\"%lu\"\r\n\r\n", - conn->ctx->config[AUTHENTICATION_DOMAIN], - (unsigned long) time(NULL)); -} - -static int is_authorized_for_put(struct mg_connection *conn) { - FILE *fp; - int ret = 0; - - fp = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ? NULL : - mg_fopen(conn->ctx->config[PUT_DELETE_PASSWORDS_FILE], "r"); - - if (fp != NULL) { - ret = authorize(conn, fp); - (void) fclose(fp); - } - - return ret; -} - -int mg_modify_passwords_file(const char *fname, const char *domain, - const char *user, const char *pass) { - int found; - char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX]; - FILE *fp, *fp2; - - found = 0; - fp = fp2 = NULL; - - // Regard empty password as no password - remove user record. - if (pass != NULL && pass[0] == '\0') { - pass = NULL; - } - - (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname); - - // Create the file if does not exist - if ((fp = mg_fopen(fname, "a+")) != NULL) { - (void) fclose(fp); - } - - // Open the given file and temporary file - if ((fp = mg_fopen(fname, "r")) == NULL) { - return 0; - } else if ((fp2 = mg_fopen(tmp, "w+")) == NULL) { - fclose(fp); - return 0; - } - - // Copy the stuff to temporary file - while (fgets(line, sizeof(line), fp) != NULL) { - if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) { - continue; - } - - if (!strcmp(u, user) && !strcmp(d, domain)) { - found++; - if (pass != NULL) { - mg_md5(ha1, user, ":", domain, ":", pass, NULL); - fprintf(fp2, "%s:%s:%s\n", user, domain, ha1); - } + while ((ch = *fmt++) != '\0') { + if (ch != '%') { + C_SNPRINTF_APPEND_CHAR(ch); } else { - (void) fprintf(fp2, "%s", line); - } - } + /* + * Conversion specification: + * zero or more flags (one of: # 0 - + ') + * an optional minimum field width (digits) + * an optional precision (. followed by digits, or *) + * an optional length modifier (one of: hh h l ll L q j z t) + * conversion specifier (one of: d i o u x X e E f F g G a A c s p n) + */ + flags = field_width = precision = len_mod = 0; - // If new user, just add it - if (!found && pass != NULL) { - mg_md5(ha1, user, ":", domain, ":", pass, NULL); - (void) fprintf(fp2, "%s:%s:%s\n", user, domain, ha1); - } - - // Close files - (void) fclose(fp); - (void) fclose(fp2); - - // Put the temp file in place of real file - (void) mg_remove(fname); - (void) mg_rename(tmp, fname); - - return 1; -} - -struct de { - struct mg_connection *conn; - char *file_name; - struct mgstat st; -}; - -static void url_encode(const char *src, char *dst, size_t dst_len) { - static const char *dont_escape = "._-$,;~()"; - static const char *hex = "0123456789abcdef"; - const char *end = dst + dst_len - 1; - - for (; *src != '\0' && dst < end; src++, dst++) { - if (isalnum(*(const unsigned char *) src) || - strchr(dont_escape, * (const unsigned char *) src) != NULL) { - *dst = *src; - } else if (dst + 2 < end) { - dst[0] = '%'; - dst[1] = hex[(* (const unsigned char *) src) >> 4]; - dst[2] = hex[(* (const unsigned char *) src) & 0xf]; - dst += 2; - } - } - - *dst = '\0'; -} - -static void print_dir_entry(struct de *de) { - char size[64], mod[64], href[PATH_MAX]; - - if (de->st.is_directory) { - (void) mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]"); - } else { - // We use (signed) cast below because MSVC 6 compiler cannot - // convert unsigned __int64 to double. Sigh. - if (de->st.size < 1024) { - (void) mg_snprintf(de->conn, size, sizeof(size), - "%lu", (unsigned long) de->st.size); - } else if (de->st.size < 1024 * 1024) { - (void) mg_snprintf(de->conn, size, sizeof(size), - "%.1fk", (double) de->st.size / 1024.0); - } else if (de->st.size < 1024 * 1024 * 1024) { - (void) mg_snprintf(de->conn, size, sizeof(size), - "%.1fM", (double) de->st.size / 1048576); - } else { - (void) mg_snprintf(de->conn, size, sizeof(size), - "%.1fG", (double) de->st.size / 1073741824); - } - } - (void) strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.mtime)); - url_encode(de->file_name, href, sizeof(href)); - de->conn->num_bytes_sent += mg_printf(de->conn, - "%s%s" - " %s  %s\n", - de->conn->request_info.uri, href, de->st.is_directory ? "/" : "", - de->file_name, de->st.is_directory ? "/" : "", mod, size); -} - -// This function is called from send_directory() and used for -// sorting directory entries by size, or name, or modification time. -// On windows, __cdecl specification is needed in case if project is built -// with __stdcall convention. qsort always requires __cdels callback. -static int WINCDECL compare_dir_entries(const void *p1, const void *p2) { - const struct de *a = (const struct de *) p1, *b = (const struct de *) p2; - const char *query_string = a->conn->request_info.query_string; - int cmp_result = 0; - - if (query_string == NULL) { - query_string = "na"; - } - - if (a->st.is_directory && !b->st.is_directory) { - return -1; // Always put directories on top - } else if (!a->st.is_directory && b->st.is_directory) { - return 1; // Always put directories on top - } else if (*query_string == 'n') { - cmp_result = strcmp(a->file_name, b->file_name); - } else if (*query_string == 's') { - cmp_result = a->st.size == b->st.size ? 0 : - a->st.size > b->st.size ? 1 : -1; - } else if (*query_string == 'd') { - cmp_result = a->st.mtime == b->st.mtime ? 0 : - a->st.mtime > b->st.mtime ? 1 : -1; - } - - return query_string[1] == 'd' ? -cmp_result : cmp_result; -} - -static int must_hide_file(struct mg_connection *conn, const char *path) { - const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$"; - const char *pattern = conn->ctx->config[HIDE_FILES]; - return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 || - (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0); -} - -static int scan_directory(struct mg_connection *conn, const char *dir, - void *data, void (*cb)(struct de *, void *)) { - char path[PATH_MAX]; - struct dirent *dp; - DIR *dirp; - struct de de; - - if ((dirp = opendir(dir)) == NULL) { - return 0; - } else { - de.conn = conn; - - while ((dp = readdir(dirp)) != NULL) { - // Do not show current dir and hidden files - if (!strcmp(dp->d_name, ".") || - !strcmp(dp->d_name, "..") || - must_hide_file(conn, dp->d_name)) { - continue; + /* Flags. only zero-pad flag is supported. */ + if (*fmt == '0') { + flags |= C_SNPRINTF_FLAG_ZERO; } - mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, DIRSEP, dp->d_name); - - // If we don't memset stat structure to zero, mtime will have - // garbage and strftime() will segfault later on in - // print_dir_entry(). memset is required only if mg_stat() - // fails. For more details, see - // http://code.google.com/p/mongoose/issues/detail?id=79 - if (mg_stat(path, &de.st) != 0) { - memset(&de.st, 0, sizeof(de.st)); + /* Field width */ + while (*fmt >= '0' && *fmt <= '9') { + field_width *= 10; + field_width += *fmt++ - '0'; + } + /* Dynamic field width */ + if (*fmt == '*') { + field_width = va_arg(ap, int); + fmt++; } - de.file_name = dp->d_name; - cb(&de, data); + /* Precision */ + if (*fmt == '.') { + fmt++; + if (*fmt == '*') { + precision = va_arg(ap, int); + fmt++; + } else { + while (*fmt >= '0' && *fmt <= '9') { + precision *= 10; + precision += *fmt++ - '0'; + } + } + } + + /* Length modifier */ + switch (*fmt) { + case 'h': + case 'l': + case 'L': + case 'I': + case 'q': + case 'j': + case 'z': + case 't': + len_mod = *fmt++; + if (*fmt == 'h') { + len_mod = 'H'; + fmt++; + } + if (*fmt == 'l') { + len_mod = 'q'; + fmt++; + } + break; + } + + ch = *fmt++; + if (ch == 's') { + const char *s = va_arg(ap, const char *); /* Always fetch parameter */ + int j; + int pad = field_width - (precision >= 0 ? strnlen(s, precision) : 0); + for (j = 0; j < pad; j++) { + C_SNPRINTF_APPEND_CHAR(' '); + } + + /* Ignore negative and 0 precisions */ + for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) { + C_SNPRINTF_APPEND_CHAR(s[j]); + } + } else if (ch == 'c') { + ch = va_arg(ap, int); /* Always fetch parameter */ + C_SNPRINTF_APPEND_CHAR(ch); + } else if (ch == 'd' && len_mod == 0) { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags, + field_width); + } else if (ch == 'd' && len_mod == 'l') { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags, + field_width); + } else if ((ch == 'x' || ch == 'u') && len_mod == 0) { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned), + ch == 'x' ? 16 : 10, flags, field_width); + } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') { + i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long), + ch == 'x' ? 16 : 10, flags, field_width); + } else if (ch == 'p') { + unsigned long num = (unsigned long) va_arg(ap, void *); + C_SNPRINTF_APPEND_CHAR('0'); + C_SNPRINTF_APPEND_CHAR('x'); + i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0); + } else { +#ifndef NO_LIBC + /* + * TODO(lsm): abort is not nice in a library, remove it + * Also, ESP8266 SDK doesn't have it + */ + abort(); +#endif + } } - (void) closedir(dirp); } - return 1; + + /* Zero-terminate the result */ + if (buf_size > 0) { + buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0'; + } + + return i; } +#endif -struct dir_scan_data { - struct de *entries; - int num_entries; - int arr_size; -}; - -static void dir_scan_callback(struct de *de, void *data) { - struct dir_scan_data *dsd = (struct dir_scan_data *) data; - - if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) { - dsd->arr_size *= 2; - dsd->entries = (struct de *) realloc(dsd->entries, dsd->arr_size * - sizeof(dsd->entries[0])); - } - if (dsd->entries == NULL) { - // TODO(lsm): propagate an error to the caller - dsd->num_entries = 0; - } else { - dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name); - dsd->entries[dsd->num_entries].st = de->st; - dsd->entries[dsd->num_entries].conn = de->conn; - dsd->num_entries++; - } -} - -static void handle_directory_request(struct mg_connection *conn, - const char *dir) { - int i, sort_direction; - struct dir_scan_data data = { NULL, 0, 128 }; - - if (!scan_directory(conn, dir, &data, dir_scan_callback)) { - send_http_error(conn, 500, "Cannot open directory", - "Error: opendir(%s): %s", dir, strerror(ERRNO)); - return; - } - - sort_direction = conn->request_info.query_string != NULL && - conn->request_info.query_string[1] == 'd' ? 'a' : 'd'; - - conn->must_close = 1; - mg_printf(conn, "%s", - "HTTP/1.1 200 OK\r\n" - "Connection: close\r\n" - "Content-Type: text/html; charset=utf-8\r\n\r\n"); - - conn->num_bytes_sent += mg_printf(conn, - "Index of %s" - "" - "

Index of %s

"
-      ""
-      ""
-      ""
-      "",
-      conn->request_info.uri, conn->request_info.uri,
-      sort_direction, sort_direction, sort_direction);
-
-  // Print first entry - link to a parent directory
-  conn->num_bytes_sent += mg_printf(conn,
-      ""
-      "\n",
-      conn->request_info.uri, "..", "Parent directory", "-", "-");
-
-  // Sort and print directory entries
-  qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),
-        compare_dir_entries);
-  for (i = 0; i < data.num_entries; i++) {
-    print_dir_entry(&data.entries[i]);
-    free(data.entries[i].file_name);
-  }
-  free(data.entries);
-
-  conn->num_bytes_sent += mg_printf(conn, "%s", "
NameModifiedSize

%s %s  %s
"); - conn->request_info.status_code = 200; -} - -// Send len bytes from the opened file to the client. -static void send_file_data(struct mg_connection *conn, FILE *fp, int64_t len) { - char buf[MG_BUF_LEN]; - int to_read, num_read, num_written; - - while (len > 0) { - // Calculate how much to read from the file in the buffer - to_read = sizeof(buf); - if ((int64_t) to_read > len) { - to_read = (int) len; - } - - // Read from file, exit the loop on error - if ((num_read = fread(buf, 1, (size_t)to_read, fp)) <= 0) { - break; - } - - // Send read bytes to the client, exit the loop on error - if ((num_written = mg_write(conn, buf, (size_t)num_read)) != num_read) { - break; - } - - // Both read and were successful, adjust counters - conn->num_bytes_sent += num_written; - len -= num_written; - } -} - -static int parse_range_header(const char *header, int64_t *a, int64_t *b) { - return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); -} - -static void gmt_time_string(char *buf, size_t buf_len, time_t *t) { - strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); -} - -static void construct_etag(char *buf, size_t buf_len, - const struct mgstat *stp) { - snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", - (unsigned long) stp->mtime, stp->size); -} - -static void handle_file_request(struct mg_connection *conn, const char *path, - struct mgstat *stp) { - char date[64], lm[64], etag[64], range[64]; - const char *msg = "OK", *hdr; - time_t curtime = time(NULL); - int64_t cl, r1, r2; - struct vec mime_vec; - FILE *fp; - int n; - - get_mime_type(conn->ctx, path, &mime_vec); - cl = stp->size; - conn->request_info.status_code = 200; - range[0] = '\0'; - - if ((fp = mg_fopen(path, "rb")) == NULL) { - send_http_error(conn, 500, http_500_error, - "fopen(%s): %s", path, strerror(ERRNO)); - return; - } - set_close_on_exec(fileno(fp)); - - // If Range: header specified, act accordingly - r1 = r2 = 0; - hdr = mg_get_header(conn, "Range"); - if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) { - conn->request_info.status_code = 206; - (void) fseeko(fp, r1, SEEK_SET); - cl = n == 2 ? r2 - r1 + 1: cl - r1; - (void) mg_snprintf(conn, range, sizeof(range), - "Content-Range: bytes " - "%" INT64_FMT "-%" - INT64_FMT "/%" INT64_FMT "\r\n", - r1, r1 + cl - 1, stp->size); - msg = "Partial Content"; - } - - // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to - // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 - gmt_time_string(date, sizeof(date), &curtime); - gmt_time_string(lm, sizeof(lm), &stp->mtime); - construct_etag(etag, sizeof(etag), stp); - - (void) mg_printf(conn, - "HTTP/1.1 %d %s\r\n" - "Date: %s\r\n" - "Last-Modified: %s\r\n" - "Etag: %s\r\n" - "Content-Type: %.*s\r\n" - "Content-Length: %" INT64_FMT "\r\n" - "Connection: %s\r\n" - "Accept-Ranges: bytes\r\n" - "%s\r\n", - conn->request_info.status_code, msg, date, lm, etag, (int) mime_vec.len, - mime_vec.ptr, cl, suggest_connection_header(conn), range); - - if (strcmp(conn->request_info.request_method, "HEAD") != 0) { - send_file_data(conn, fp, cl); - } - (void) fclose(fp); -} - -void mg_send_file(struct mg_connection *conn, const char *path) { - struct mgstat st; - if (mg_stat(path, &st) == 0) { - handle_file_request(conn, path, &st); - } else { - send_http_error(conn, 404, "Not Found", "%s", "File not found"); - } -} - - -// Parse HTTP headers from the given buffer, advance buffer to the point -// where parsing stopped. -static void parse_http_headers(char **buf, struct mg_request_info *ri) { - int i; - - for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) { - ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0); - ri->http_headers[i].value = skip(buf, "\r\n"); - if (ri->http_headers[i].name[0] == '\0') - break; - ri->num_headers = i + 1; - } -} - -static int is_valid_http_method(const char *method) { - return !strcmp(method, "GET") || !strcmp(method, "POST") || - !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") || - !strcmp(method, "PUT") || !strcmp(method, "DELETE") || - !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND"); -} - -// Parse HTTP request, fill in mg_request_info structure. -// This function modifies the buffer by NUL-terminating -// HTTP request components, header names and header values. -static int parse_http_message(char *buf, int len, struct mg_request_info *ri) { - int request_length = get_request_len(buf, len); - if (request_length > 0) { - // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port - ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL; - ri->num_headers = 0; - ri->status_code = -1; - - buf[request_length - 1] = '\0'; - - // RFC says that all initial whitespaces should be ingored - while (*buf != '\0' && isspace(* (unsigned char *) buf)) { - buf++; - } - ri->request_method = skip(&buf, " "); - ri->uri = skip(&buf, " "); - ri->http_version = skip(&buf, "\r\n"); - parse_http_headers(&buf, ri); - } - return request_length; -} - -static int parse_http_request(char *buf, int len, struct mg_request_info *ri) { - int result = parse_http_message(buf, len, ri); - if (result > 0 && - is_valid_http_method(ri->request_method) && - !strncmp(ri->http_version, "HTTP/", 5)) { - ri->http_version += 5; // Skip "HTTP/" - } else { - result = -1; - } +int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) { + int result; + va_list ap; + va_start(ap, fmt); + result = c_vsnprintf(buf, buf_size, fmt, ap); + va_end(ap); return result; } -static int parse_http_response(char *buf, int len, struct mg_request_info *ri) { - int result = parse_http_message(buf, len, ri); - return result > 0 && !strncmp(ri->request_method, "HTTP/", 5) ? result : -1; -} - -// Keep reading the input (either opened file descriptor fd, or socket sock, -// or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the -// buffer (which marks the end of HTTP request). Buffer buf may already -// have some data. The length of the data is stored in nread. -// Upon every read operation, increase nread by the number of bytes read. -static int read_request(FILE *fp, struct mg_connection *conn, - char *buf, int bufsiz, int *nread) { - int request_len, n = 1; - - request_len = get_request_len(buf, *nread); - while (*nread < bufsiz && request_len == 0 && n > 0) { - n = pull(fp, conn, buf + *nread, bufsiz - *nread); - if (n > 0) { - *nread += n; - request_len = get_request_len(buf, *nread); - } - } - - if (n < 0) { - // recv() error -> propagate error; do not process a b0rked-with-very-high-probability request - return -1; - } - return request_len; -} - -// For given directory path, substitute it to valid index file. -// Return 0 if index file has been found, -1 if not found. -// If the file is found, it's stats is returned in stp. -static int substitute_index_file(struct mg_connection *conn, char *path, - size_t path_len, struct mgstat *stp) { - const char *list = conn->ctx->config[INDEX_FILES]; - struct mgstat st; - struct vec filename_vec; - size_t n = strlen(path); - int found = 0; - - // The 'path' given to us points to the directory. Remove all trailing - // directory separator characters from the end of the path, and - // then append single directory separator character. - while (n > 0 && IS_DIRSEP_CHAR(path[n - 1])) { - n--; - } - path[n] = DIRSEP; - - // Traverse index files list. For each entry, append it to the given - // path and see if the file exists. If it exists, break the loop - while ((list = next_option(list, &filename_vec, NULL)) != NULL) { - - // Ignore too long entries that may overflow path buffer - if (filename_vec.len > path_len - (n + 2)) - continue; - - // Prepare full path to the index file - (void) mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1); - - // Does it exist? - if (mg_stat(path, &st) == 0) { - // Yes it does, break the loop - *stp = st; - found = 1; - break; - } - } - - // If no index file exists, restore directory path - if (!found) { - path[n] = '\0'; - } - - return found; -} - -// Return True if we should reply 304 Not Modified. -static int is_not_modified(const struct mg_connection *conn, - const struct mgstat *stp) { - char etag[64]; - const char *ims = mg_get_header(conn, "If-Modified-Since"); - const char *inm = mg_get_header(conn, "If-None-Match"); - construct_etag(etag, sizeof(etag), stp); - return (inm != NULL && !mg_strcasecmp(etag, inm)) || - (ims != NULL && stp->mtime <= parse_date_string(ims)); -} - -static int forward_body_data(struct mg_connection *conn, FILE *fp, - SOCKET sock, SSL *ssl) { - const char *expect; - char buf[MG_BUF_LEN]; - int to_read, nread, buffered_len, success = 0; - - expect = mg_get_header(conn, "Expect"); - assert(fp != NULL); - - if (conn->content_len == -1) { - send_http_error(conn, 411, "Length Required", "%s", ""); - } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) { - send_http_error(conn, 417, "Expectation Failed", "%s", ""); - } else { - if (expect != NULL) { - (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n"); - } - - buffered_len = conn->next_request - conn->body; - assert(buffered_len >= 0); - assert(conn->consumed_content == 0); - - if (buffered_len > 0) { - if ((int64_t) buffered_len > conn->content_len) { - buffered_len = (int) conn->content_len; - } - push(fp, sock, ssl, conn->body, (int64_t) buffered_len); - conn->consumed_content += buffered_len; - conn->body += buffered_len; - } - - nread = 0; - while (conn->consumed_content < conn->content_len) { - to_read = sizeof(buf); - if ((int64_t) to_read > conn->content_len - conn->consumed_content) { - to_read = (int) (conn->content_len - conn->consumed_content); - } - nread = pull(NULL, conn, buf, to_read); - if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) { - break; - } - conn->consumed_content += nread; - } - - if (conn->consumed_content == conn->content_len) { - success = nread >= 0; - } - - // Each error code path in this function must send an error - if (!success) { - send_http_error(conn, 577, http_500_error, "%s", ""); - } - } - - return success; -} - -#if !defined(NO_CGI) -// This structure helps to create an environment for the spawned CGI program. -// Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, -// last element must be NULL. -// However, on Windows there is a requirement that all these VARIABLE=VALUE\0 -// strings must reside in a contiguous buffer. The end of the buffer is -// marked by two '\0' characters. -// We satisfy both worlds: we create an envp array (which is vars), all -// entries are actually pointers inside buf. -struct cgi_env_block { - struct mg_connection *conn; - char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer - int len; // Space taken - char *vars[MAX_CGI_ENVIR_VARS]; // char **envp - int nvars; // Number of variables -}; - -static char *addenv(struct cgi_env_block *block, - PRINTF_FORMAT_STRING(const char *fmt), ...) - PRINTF_ARGS(2, 3); - -// Append VARIABLE=VALUE\0 string to the buffer, and add a respective -// pointer into the vars array. -static char *addenv(struct cgi_env_block *block, const char *fmt, ...) { - int n, space; - char *added; - va_list ap; - - // Calculate how much space is left in the buffer - space = sizeof(block->buf) - block->len - 2; - assert(space >= 0); - - // Make a pointer to the free space int the buffer - added = block->buf + block->len; - - // Copy VARIABLE=VALUE\0 string into the free space - va_start(ap, fmt); - n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap); - va_end(ap); - - // Make sure we do not overflow buffer and the envp array - if (n > 0 && n + 1 < space && - block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { - // Append a pointer to the added string into the envp array - block->vars[block->nvars++] = added; - // Bump up used length counter. Include \0 terminator - block->len += n + 1; - } else { - cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt); - } - - return added; -} - -static void prepare_cgi_environment(struct mg_connection *conn, - const char *prog, - struct cgi_env_block *blk) { - const char *s, *slash; - struct vec var_vec; - char *p, src_addr[20]; - int i; - - blk->len = blk->nvars = 0; - blk->conn = conn; - sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa); - - addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]); - addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]); - addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]); - - // Prepare the environment block - addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); - addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); - addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP - - // TODO(lsm): fix this for IPv6 case - addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port)); - - addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method); - addenv(blk, "REMOTE_ADDR=%s", src_addr); - addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port); - addenv(blk, "REQUEST_URI=%s", conn->request_info.uri); - - // SCRIPT_NAME - assert(conn->request_info.uri[0] == '/'); - slash = strrchr(conn->request_info.uri, '/'); - if ((s = strrchr(prog, '/')) == NULL) - s = prog; - addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri), - conn->request_info.uri, s); - - addenv(blk, "SCRIPT_FILENAME=%s", prog); - addenv(blk, "PATH_TRANSLATED=%s", prog); - addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on"); - - if ((s = mg_get_header(conn, "Content-Type")) != NULL) - addenv(blk, "CONTENT_TYPE=%s", s); - - if (conn->request_info.query_string != NULL) - addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string); - - if ((s = mg_get_header(conn, "Content-Length")) != NULL) - addenv(blk, "CONTENT_LENGTH=%s", s); - - if ((s = getenv("PATH")) != NULL) - addenv(blk, "PATH=%s", s); - - if (conn->path_info != NULL) { - addenv(blk, "PATH_INFO=%s", conn->path_info); - } - -#if defined(_WIN32) - if ((s = getenv("COMSPEC")) != NULL) { - addenv(blk, "COMSPEC=%s", s); - } - if ((s = getenv("SYSTEMROOT")) != NULL) { - addenv(blk, "SYSTEMROOT=%s", s); - } - if ((s = getenv("SystemDrive")) != NULL) { - addenv(blk, "SystemDrive=%s", s); - } -#else - if ((s = getenv("LD_LIBRARY_PATH")) != NULL) - addenv(blk, "LD_LIBRARY_PATH=%s", s); -#endif // _WIN32 - - if ((s = getenv("PERLLIB")) != NULL) - addenv(blk, "PERLLIB=%s", s); - - if (conn->request_info.remote_user != NULL) { - addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user); - addenv(blk, "%s", "AUTH_TYPE=Digest"); - } - - // Add all headers as HTTP_* variables - for (i = 0; i < conn->request_info.num_headers; i++) { - p = addenv(blk, "HTTP_%s=%s", - conn->request_info.http_headers[i].name, - conn->request_info.http_headers[i].value); - - // Convert variable name into uppercase, and change - to _ - for (; *p != '=' && *p != '\0'; p++) { - if (*p == '-') - *p = '_'; - *p = (char) toupper(* (unsigned char *) p); - } - } - - // Add user-specified variables - s = conn->ctx->config[CGI_ENVIRONMENT]; - while ((s = next_option(s, &var_vec, NULL)) != NULL) { - addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr); - } - - blk->vars[blk->nvars++] = NULL; - blk->buf[blk->len++] = '\0'; - - assert(blk->nvars < (int) ARRAY_SIZE(blk->vars)); - assert(blk->len > 0); - assert(blk->len < (int) sizeof(blk->buf)); -} - -static void handle_cgi_request(struct mg_connection *conn, const char *prog) { - int headers_len, data_len, i, fd_stdin[2], fd_stdout[2]; - const char *status, *status_text; - char buf[16384], *pbuf, dir[PATH_MAX], *p; - struct mg_request_info ri; - struct cgi_env_block blk; - FILE *in, *out; - pid_t pid; - - prepare_cgi_environment(conn, prog, &blk); - - // CGI must be executed in its own directory. 'dir' must point to the - // directory containing executable program, 'p' must point to the - // executable program name relative to 'dir'. - (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog); - if ((p = strrchr(dir, DIRSEP)) != NULL) { - *p++ = '\0'; - } else { - dir[0] = '.', dir[1] = '\0'; - p = (char *) prog; - } - - pid = (pid_t) -1; - fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1; - in = out = NULL; - - if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) { - send_http_error(conn, 500, http_500_error, - "Cannot create CGI pipe: %s", strerror(ERRNO)); - goto done; - } else if ((pid = spawn_process(conn, p, blk.buf, blk.vars, - fd_stdin[0], fd_stdout[1], dir)) == (pid_t) -1) { - send_http_error(conn, 500, http_500_error, - "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO)); - goto done; - } else if ((in = fdopen(fd_stdin[1], "wb")) == NULL || - (out = fdopen(fd_stdout[0], "rb")) == NULL) { - send_http_error(conn, 500, http_500_error, - "fopen: %s", strerror(ERRNO)); - goto done; - } - - setbuf(in, NULL); - setbuf(out, NULL); - - // spawn_process() must close those! - // If we don't mark them as closed, close() attempt before - // return from this function throws an exception on Windows. - // Windows does not like when closed descriptor is closed again. - fd_stdin[0] = fd_stdout[1] = -1; - - // Send POST data to the CGI process if needed - if (!strcmp(conn->request_info.request_method, "POST") && - !forward_body_data(conn, in, INVALID_SOCKET, NULL)) { - goto done; - } - // Close so child gets an EOF. - fclose(in); - in = NULL; - - // Now read CGI reply into a buffer. We need to set correct - // status code, thus we need to see all HTTP headers first. - // Do not send anything back to client, until we buffer in all - // HTTP headers. - data_len = 0; - headers_len = read_request(out, fc(conn->ctx), buf, sizeof(buf), &data_len); - if (headers_len <= 0) { - send_http_error(conn, 500, http_500_error, - "CGI program sent malformed or too big (>%u bytes) " - "HTTP headers: [%.*s]", - (unsigned) sizeof(buf), data_len, buf); - goto done; - } - pbuf = buf; - buf[headers_len - 1] = '\0'; - parse_http_headers(&pbuf, &ri); - - // Make up and send the status line - status_text = "OK"; - if ((status = get_header(&ri, "Status")) != NULL) { - conn->request_info.status_code = atoi(status); - status_text = status; - while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') { - status_text++; - } - } else if (get_header(&ri, "Location") != NULL) { - conn->request_info.status_code = 302; - } else { - conn->request_info.status_code = 200; - } - if (get_header(&ri, "Connection") != NULL && - !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) { - conn->must_close = 1; - } - (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->request_info.status_code, - status_text); - - // Send headers - for (i = 0; i < ri.num_headers; i++) { - mg_printf(conn, "%s: %s\r\n", - ri.http_headers[i].name, ri.http_headers[i].value); - } - (void) mg_write(conn, "\r\n", 2); - - // Send chunk of data that may have been read after the headers - conn->num_bytes_sent += mg_write(conn, buf + headers_len, - (size_t)(data_len - headers_len)); - - // Read the rest of CGI output and send to the client - send_file_data(conn, out, INT64_MAX); - -done: - if (pid != (pid_t) -1) { - kill(pid, SIGKILL); - } - if (fd_stdin[0] != -1) { - (void) close(fd_stdin[0]); - } - if (fd_stdout[1] != -1) { - (void) close(fd_stdout[1]); - } - - if (in != NULL) { - (void) fclose(in); - } else if (fd_stdin[1] != -1) { - (void) close(fd_stdin[1]); - } - - if (out != NULL) { - (void) fclose(out); - } else if (fd_stdout[0] != -1) { - (void) close(fd_stdout[0]); +#ifdef _WIN32 +void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) { + char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p; + + strncpy(buf, path, sizeof(buf)); + buf[sizeof(buf) - 1] = '\0'; + + /* Trim trailing slashes. Leave backslash for paths like "X:\" */ + p = buf + strlen(buf) - 1; + while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0'; + + /* + * Convert to Unicode and back. If doubly-converted string does not + * match the original, something is fishy, reject. + */ + memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); + MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); + WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), + NULL, NULL); + if (strcmp(buf, buf2) != 0) { + wbuf[0] = L'\0'; } } -#endif // !NO_CGI +#endif /* _WIN32 */ -// For a given PUT path, create all intermediate subdirectories -// for given path. Return 0 if the path itself is a directory, -// or -1 on error, 1 if OK. -static int put_dir(const char *path) { - char buf[PATH_MAX]; - const char *s, *p; - struct mgstat st; - int len, res = 1; +#endif /* EXCLUDE_COMMON */ +#ifdef NS_MODULE_LINES +#line 1 "src/net.c" +/**/ +#endif +/* + * Copyright (c) 2014 Cesanta Software Limited + * All rights reserved + * + * This software is dual-licensed: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. For the terms of this + * license, see . + * + * You are free to use this software under the terms of the GNU General + * Public License, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * Alternatively, you can license this software under a commercial + * license, as set out in . + */ - for (s = p = path + 2; (p = strchr(s, DIRSEP)) != NULL; s = ++p) { - len = p - path; - if (len >= (int) sizeof(buf)) { - res = -1; - break; - } - memcpy(buf, path, len); - buf[len] = '\0'; +/* Amalgamated: #include "internal.h" */ - // Try to create intermediate directory - DEBUG_TRACE(("mkdir(%s)", buf)); - if (mg_stat(buf, &st) == -1 && mg_mkdir(buf, 0755) != 0) { - res = -1; - break; - } - - // Is path itself a directory? - if (p[1] == '\0') { - res = 0; - } - } - - return res; -} - -static void put_file(struct mg_connection *conn, const char *path) { - struct mgstat st; - const char *range; - int64_t r1, r2; - FILE *fp; - int rc; - - conn->request_info.status_code = mg_stat(path, &st) == 0 ? 200 : 201; - - if ((rc = put_dir(path)) == 0) { - mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->request_info.status_code); - } else if (rc == -1) { - send_http_error(conn, 500, http_500_error, - "put_dir(%s): %s", path, strerror(ERRNO)); - } else if ((fp = mg_fopen(path, "wb+")) == NULL) { - send_http_error(conn, 500, http_500_error, - "fopen(%s): %s", path, strerror(ERRNO)); - } else { - set_close_on_exec(fileno(fp)); - range = mg_get_header(conn, "Content-Range"); - r1 = r2 = 0; - if (range != NULL && parse_range_header(range, &r1, &r2) > 0) { - conn->request_info.status_code = 206; - // TODO(lsm): handle seek error - (void) fseeko(fp, r1, SEEK_SET); - } - if (forward_body_data(conn, fp, INVALID_SOCKET, NULL)) - (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", - conn->request_info.status_code); - (void) fclose(fp); - } -} - -static void send_ssi_file(struct mg_connection *, const char *, FILE *, int); - -static void do_ssi_include(struct mg_connection *conn, const char *ssi, - char *tag, int include_level) { - char file_name[MG_BUF_LEN], path[PATH_MAX], *p; - FILE *fp; - - // sscanf() is safe here, since send_ssi_file() also uses buffer - // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN. - if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) { - // File name is relative to the webserver root - (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s", - conn->ctx->config[DOCUMENT_ROOT], DIRSEP, file_name); - } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) { - // File name is relative to the webserver working directory - // or it is absolute system path - (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name); - } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) { - // File name is relative to the currect document - (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi); - if ((p = strrchr(path, DIRSEP)) != NULL) { - p[1] = '\0'; - } - (void) mg_snprintf(conn, path + strlen(path), - sizeof(path) - strlen(path), "%s", file_name); - } else { - cry(conn, "Bad SSI #include: [%s]", tag); - return; - } - - if ((fp = mg_fopen(path, "rb")) == NULL) { - cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s", - tag, path, strerror(ERRNO)); - } else { - set_close_on_exec(fileno(fp)); - if (match_prefix(conn->ctx->config[SSI_EXTENSIONS], - strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) { - send_ssi_file(conn, path, fp, include_level + 1); - } else { - send_file_data(conn, fp, INT64_MAX); - } - (void) fclose(fp); - } -} - -#if !defined(NO_POPEN) -static void do_ssi_exec(struct mg_connection *conn, char *tag) { - char cmd[MG_BUF_LEN]; - FILE *fp; - - if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) { - cry(conn, "Bad SSI #exec: [%s]", tag); - } else if ((fp = popen(cmd, "r")) == NULL) { - cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO)); - } else { - send_file_data(conn, fp, INT64_MAX); - (void) pclose(fp); - } -} -#endif // !NO_POPEN - -static void send_ssi_file(struct mg_connection *conn, const char *path, - FILE *fp, int include_level) { - char buf[MG_BUF_LEN]; - int ch, len, in_ssi_tag; - - if (include_level > 10) { - cry(conn, "SSI #include level is too deep (%s)", path); - return; - } - - in_ssi_tag = 0; - len = 0; - - while ((ch = fgetc(fp)) != EOF) { - if (in_ssi_tag && ch == '>') { - in_ssi_tag = 0; - buf[len++] = (char) ch; - buf[len] = '\0'; - assert(len <= (int) sizeof(buf)); - if (len < 6 || memcmp(buf, " + */ +static void send_ssi_file(struct mg_connection *nc, const char *path, FILE *fp, + int include_level, + const struct mg_serve_http_opts *opts) { + static const struct mg_str btag = MG_STR(" */ + buf[i--] = '\0'; + while (i > 0 && buf[i] == ' ') { + buf[i--] = '\0'; + } + + /* Handle known SSI directives */ + if (memcmp(p, d_include.p, d_include.len) == 0) { + do_ssi_include(nc, path, p + d_include.len + 1, include_level, opts); + } else if (memcmp(p, d_call.p, d_call.len) == 0) { + do_ssi_call(nc, p + d_call.len + 1); +#ifndef MG_DISABLE_POPEN + } else if (memcmp(p, d_exec.p, d_exec.len) == 0) { + do_ssi_exec(nc, p + d_exec.len + 1); +#endif + } else { + /* Silently ignore unknown SSI directive. */ + } + len = 0; + } else if (ch == '<') { + in_ssi_tag = 1; + if (len > 0) { + mg_send(nc, buf, (size_t) len); + } + len = 0; + buf[len++] = ch & 0xff; + } else if (in_ssi_tag) { + if (len == (int) btag.len && memcmp(buf, btag.p, btag.len) != 0) { + /* Not an SSI tag */ + in_ssi_tag = 0; + } else if (len == (int) sizeof(buf) - 2) { + mg_printf(nc, "%s: SSI tag is too large", path); + len = 0; + } + buf[len++] = ch & 0xff; + } else { + buf[len++] = ch & 0xff; + if (len == (int) sizeof(buf)) { + mg_send(nc, buf, (size_t) len); + len = 0; + } + } + } + + /* Send the rest of buffered data */ + if (len > 0) { + mg_send(nc, buf, (size_t) len); + } +} + +static void handle_ssi_request(struct mg_connection *nc, const char *path, + const struct mg_serve_http_opts *opts) { + FILE *fp; + struct mg_str mime_type; + + if ((fp = fopen(path, "rb")) == NULL) { + send_http_error(nc, 404, "Not Found"); + } else { + mg_set_close_on_exec(fileno(fp)); + + mime_type = get_mime_type(path, "text/plain", opts); + mg_send_response_line(nc, 200, opts->extra_headers); + mg_printf(nc, + "Content-Type: %.*s\r\n" + "Connection: close\r\n\r\n", + (int) mime_type.len, mime_type.p); + send_ssi_file(nc, path, fp, 0, opts); + fclose(fp); + nc->flags |= MG_F_SEND_AND_CLOSE; + } +} +#else +static void handle_ssi_request(struct mg_connection *nc, const char *path, + const struct mg_serve_http_opts *opts) { + (void) path; + (void) opts; + send_http_error(nc, 500, "SSI disabled"); +} +#endif /* MG_DISABLE_SSI */ + +static void construct_etag(char *buf, size_t buf_len, const cs_stat_t *st) { + snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime, + (int64_t) st->st_size); +} +static void gmt_time_string(char *buf, size_t buf_len, time_t *t) { + strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); +} + +static int parse_range_header(const struct mg_str *header, int64_t *a, + int64_t *b) { + /* + * There is no snscanf. Headers are not guaranteed to be NUL-terminated, + * so we have this. Ugh. + */ + int result; + char *p = (char *) MG_MALLOC(header->len + 1); + if (p == NULL) return 0; + memcpy(p, header->p, header->len); + p[header->len] = '\0'; + result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); + MG_FREE(p); + return result; +} + +static void mg_send_http_file2(struct mg_connection *nc, const char *path, + cs_stat_t *st, struct http_message *hm, + struct mg_serve_http_opts *opts) { + struct proto_data_http *dp; + struct mg_str mime_type; + + free_http_proto_data(nc); + if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) == NULL) { + send_http_error(nc, 500, "Server Error"); /* LCOV_EXCL_LINE */ + } else if ((dp->fp = fopen(path, "rb")) == NULL) { + MG_FREE(dp); + nc->proto_data = NULL; + send_http_error(nc, 500, "Server Error"); + } else if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), + path) > 0) { + nc->proto_data = (void *) dp; + handle_ssi_request(nc, path, opts); + } else { + char etag[50], current_time[50], last_modified[50], range[50]; + time_t t = time(NULL); + int64_t r1 = 0, r2 = 0, cl = st->st_size; + struct mg_str *range_hdr = mg_get_http_header(hm, "Range"); + int n, status_code = 200; + + /* Handle Range header */ + range[0] = '\0'; + if (range_hdr != NULL && + (n = parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 && + r2 >= 0) { + /* If range is specified like "400-", set second limit to content len */ + if (n == 1) { + r2 = cl - 1; + } + if (r1 > r2 || r2 >= cl) { + status_code = 416; + cl = 0; + snprintf(range, sizeof(range), + "Content-Range: bytes */%" INT64_FMT "\r\n", + (int64_t) st->st_size); + } else { + status_code = 206; + cl = r2 - r1 + 1; + snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT + "-%" INT64_FMT "/%" INT64_FMT "\r\n", + r1, r1 + cl - 1, (int64_t) st->st_size); + fseeko(dp->fp, r1, SEEK_SET); + } + } + + construct_etag(etag, sizeof(etag), st); + gmt_time_string(current_time, sizeof(current_time), &t); + gmt_time_string(last_modified, sizeof(last_modified), &st->st_mtime); + mime_type = get_mime_type(path, "text/plain", opts); + /* + * Content length casted to size_t because: + * 1) that's the maximum buffer size anyway + * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last + * position + * TODO(mkm): fix ESP8266 RTOS SDK + */ + mg_send_response_line(nc, status_code, opts->extra_headers); + mg_printf(nc, + "Date: %s\r\n" + "Last-Modified: %s\r\n" + "Accept-Ranges: bytes\r\n" + "Content-Type: %.*s\r\n" +#ifdef MG_DISABLE_HTTP_KEEP_ALIVE + "Connection: close\r\n" +#endif + "Content-Length: %" SIZE_T_FMT + "\r\n" + "%sEtag: %s\r\n\r\n", + current_time, last_modified, (int) mime_type.len, mime_type.p, + (size_t) cl, range, etag); + + nc->proto_data = (void *) dp; + dp->cl = cl; + dp->type = DATA_FILE; + transfer_file_data(nc); + } +} + +static void remove_double_dots(char *s) { + char *p = s; + + while (*s != '\0') { + *p++ = *s++; + if (s[-1] == '/' || s[-1] == '\\') { + while (s[0] != '\0') { + if (s[0] == '/' || s[0] == '\\') { + s++; + } else if (s[0] == '.' && s[1] == '.') { + s += 2; + } else { break; } } } - mg_close_connection(newconn); + } + *p = '\0'; +} + +#endif + +static int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, + int is_form_url_encoded) { + int i, j, a, b; +#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') + + for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { + if (src[i] == '%') { + if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) && + isxdigit(*(const unsigned char *) (src + i + 2))) { + a = tolower(*(const unsigned char *) (src + i + 1)); + b = tolower(*(const unsigned char *) (src + i + 2)); + dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); + i += 2; + } else { + return -1; + } + } else if (is_form_url_encoded && src[i] == '+') { + dst[j] = ' '; + } else { + dst[j] = src[i]; + } } - return fp; + dst[j] = '\0'; /* Null-terminate the destination */ + + return i >= src_len ? j : -1; } -static int is_valid_uri(const char *uri) { - // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2 - // URI can be an asterisk (*) or should start with slash. - return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0'); +int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, + size_t dst_len) { + const char *p, *e, *s; + size_t name_len; + int len; + + if (dst == NULL || dst_len == 0) { + len = -2; + } else if (buf->p == NULL || name == NULL || buf->len == 0) { + len = -1; + dst[0] = '\0'; + } else { + name_len = strlen(name); + e = buf->p + buf->len; + len = -1; + dst[0] = '\0'; + + for (p = buf->p; p + name_len < e; p++) { + if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' && + !mg_ncasecmp(name, p, name_len)) { + p += name_len + 1; + s = (const char *) memchr(p, '&', (size_t)(e - p)); + if (s == NULL) { + s = e; + } + len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1); + if (len == -1) { + len = -2; + } + break; + } + } + } + + return len; } -static void process_new_connection(struct mg_connection *conn) { - struct mg_request_info *ri = &conn->request_info; - int keep_alive_enabled, buffered_len; - const char *cl; +void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) { + char chunk_size[50]; + int n; - keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes"); + n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len); + mg_send(nc, chunk_size, n); + mg_send(nc, buf, len); + mg_send(nc, "\r\n", 2); +} + +void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) { + char mem[500], *buf = mem; + int len; + va_list ap; + + va_start(ap, fmt); + len = mg_avprintf(&buf, sizeof(mem), fmt, ap); + va_end(ap); + + if (len >= 0) { + mg_send_http_chunk(nc, buf, len); + } + + /* LCOV_EXCL_START */ + if (buf != mem && buf != NULL) { + MG_FREE(buf); + } + /* LCOV_EXCL_STOP */ +} + +void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) { + char mem[500], *buf = mem; + int i, j, len; + va_list ap; + + va_start(ap, fmt); + len = mg_avprintf(&buf, sizeof(mem), fmt, ap); + va_end(ap); + + if (len >= 0) { + for (i = j = 0; i < len; i++) { + if (buf[i] == '<' || buf[i] == '>') { + mg_send(nc, buf + j, i - j); + mg_send(nc, buf[i] == '<' ? "<" : ">", 4); + j = i + 1; + } + } + mg_send(nc, buf + j, i - j); + } + + /* LCOV_EXCL_START */ + if (buf != mem && buf != NULL) { + MG_FREE(buf); + } + /* LCOV_EXCL_STOP */ +} + +int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, + size_t buf_size) { + int ch = ' ', ch1 = ',', len = 0, n = strlen(var_name); + const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL; + + if (buf != NULL && buf_size > 0) buf[0] = '\0'; + if (hdr == NULL) return 0; + + /* Find where variable starts */ + for (s = hdr->p; s != NULL && s + n < end; s++) { + if ((s == hdr->p || s[-1] == ch || s[-1] == ch1) && s[n] == '=' && + !memcmp(s, var_name, n)) + break; + } + + if (s != NULL && &s[n + 1] < end) { + s += n + 1; + if (*s == '"' || *s == '\'') { + ch = ch1 = *s++; + } + p = s; + while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) { + if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++; + buf[len++] = *p++; + } + if (len >= (int) buf_size || (ch != ' ' && *p != ch)) { + len = 0; + } else { + if (len > 0 && s[len - 1] == ',') len--; + if (len > 0 && s[len - 1] == ';') len--; + buf[len] = '\0'; + } + } + + return len; +} + +#ifndef MG_DISABLE_FILESYSTEM +static int is_file_hidden(const char *path, + const struct mg_serve_http_opts *opts) { + const char *p1 = opts->per_directory_auth_file; + const char *p2 = opts->hidden_file_pattern; + + /* Strip directory path from the file name */ + const char *pdir = strrchr(path, DIRSEP); + if (pdir != NULL) { + path = pdir + 1; + } + + return !strcmp(path, ".") || !strcmp(path, "..") || + (p1 != NULL && !strcmp(path, p1)) || + (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0); +} + +#ifndef MG_DISABLE_HTTP_DIGEST_AUTH +static void mkmd5resp(const char *method, size_t method_len, const char *uri, + size_t uri_len, const char *ha1, size_t ha1_len, + const char *nonce, size_t nonce_len, const char *nc, + size_t nc_len, const char *cnonce, size_t cnonce_len, + const char *qop, size_t qop_len, char *resp) { + static const char colon[] = ":"; + static const size_t one = 1; + char ha2[33]; + + cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL); + cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc, + nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len, + colon, one, ha2, sizeof(ha2) - 1, NULL); +} + +int mg_http_create_digest_auth_header(char *buf, size_t buf_len, + const char *method, const char *uri, + const char *auth_domain, const char *user, + const char *passwd) { + static const char colon[] = ":", qop[] = "auth"; + static const size_t one = 1; + char ha1[33], resp[33], cnonce[40]; + + snprintf(cnonce, sizeof(cnonce), "%x", (unsigned int) time(NULL)); + cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain, + (size_t) strlen(auth_domain), colon, one, passwd, + (size_t) strlen(passwd), NULL); + mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1, + cnonce, strlen(cnonce), "1", one, cnonce, strlen(cnonce), qop, + sizeof(qop) - 1, resp); + return snprintf(buf, buf_len, + "Authorization: Digest username=\"%s\"," + "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s," + "nonce=%s,response=%s\r\n", + user, auth_domain, uri, qop, cnonce, cnonce, resp); +} + +/* + * Check for authentication timeout. + * Clients send time stamp encoded in nonce. Make sure it is not too old, + * to prevent replay attacks. + * Assumption: nonce is a hexadecimal number of seconds since 1970. + */ +static int check_nonce(const char *nonce) { + unsigned long now = (unsigned long) time(NULL); + unsigned long val = (unsigned long) strtoul(nonce, NULL, 16); + return 1 || now < val || now - val < 3600; +} + +/* + * Authenticate HTTP request against opened passwords file. + * Returns 1 if authenticated, 0 otherwise. + */ +static int mg_http_check_digest_auth(struct http_message *hm, + const char *auth_domain, FILE *fp) { + struct mg_str *hdr; + char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)]; + char user[50], cnonce[20], response[40], uri[200], qop[20], nc[20], nonce[30]; + char expected_response[33]; + + /* Parse "Authorization:" header, fail fast on parse error */ + if (hm == NULL || fp == NULL || + (hdr = mg_get_http_header(hm, "Authorization")) == NULL || + mg_http_parse_header(hdr, "username", user, sizeof(user)) == 0 || + mg_http_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce)) == 0 || + mg_http_parse_header(hdr, "response", response, sizeof(response)) == 0 || + mg_http_parse_header(hdr, "uri", uri, sizeof(uri)) == 0 || + mg_http_parse_header(hdr, "qop", qop, sizeof(qop)) == 0 || + mg_http_parse_header(hdr, "nc", nc, sizeof(nc)) == 0 || + mg_http_parse_header(hdr, "nonce", nonce, sizeof(nonce)) == 0 || + check_nonce(nonce) == 0) { + return 0; + } + + /* + * Read passwords file line by line. If should have htdigest format, + * i.e. each line should be a colon-separated sequence: + * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD + */ + while (fgets(buf, sizeof(buf), fp) != NULL) { + if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 && + strcmp(user, f_user) == 0 && + /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */ + strcmp(auth_domain, f_domain) == 0) { + /* User and domain matched, check the password */ + mkmd5resp(hm->method.p, hm->method.len, hm->uri.p, hm->uri.len, f_ha1, + strlen(f_ha1), nonce, strlen(nonce), nc, strlen(nc), cnonce, + strlen(cnonce), qop, strlen(qop), expected_response); + return mg_casecmp(response, expected_response) == 0; + } + } + + /* None of the entries in the passwords file matched - return failure */ + return 0; +} + +static int is_authorized(struct http_message *hm, const char *path, + int is_directory, const char *domain, + const char *passwords_file, int is_global_pass_file) { + char buf[MAX_PATH_SIZE]; + const char *p; + FILE *fp; + int authorized = 1; + + if (domain != NULL && passwords_file != NULL) { + if (is_global_pass_file) { + fp = fopen(passwords_file, "r"); + } else if (is_directory) { + snprintf(buf, sizeof(buf), "%s%c%s", path, DIRSEP, passwords_file); + fp = fopen(buf, "r"); + } else { + if ((p = strrchr(path, '/')) == NULL && + (p = strrchr(path, '\\')) == NULL) { + p = path; + } + snprintf(buf, sizeof(buf), "%.*s/%s", (int) (p - path), path, + passwords_file); + fp = fopen(buf, "r"); + } + + if (fp != NULL) { + authorized = mg_http_check_digest_auth(hm, domain, fp); + fclose(fp); + } + } + + return authorized; +} +#else +static int is_authorized(struct http_message *hm, const char *path, + int is_directory, const char *domain, + const char *passwords_file, int is_global_pass_file) { + (void) hm; + (void) path; + (void) is_directory; + (void) domain; + (void) passwords_file; + (void) is_global_pass_file; + return 1; +} +#endif + +#ifndef MG_DISABLE_DIRECTORY_LISTING +static size_t mg_url_encode(const char *src, size_t s_len, char *dst, + size_t dst_len) { + static const char *dont_escape = "._-$,;~()"; + static const char *hex = "0123456789abcdef"; + size_t i = 0, j = 0; + + for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) { + if (isalnum(*(const unsigned char *) (src + i)) || + strchr(dont_escape, *(const unsigned char *) (src + i)) != NULL) { + dst[j] = src[i]; + } else if (j + 3 < dst_len) { + dst[j] = '%'; + dst[j + 1] = hex[(*(const unsigned char *) (src + i)) >> 4]; + dst[j + 2] = hex[(*(const unsigned char *) (src + i)) & 0xf]; + j += 2; + } + } + + dst[j] = '\0'; + return j; +} + +static void escape(const char *src, char *dst, size_t dst_len) { + size_t n = 0; + while (*src != '\0' && n + 5 < dst_len) { + unsigned char ch = *(unsigned char *) src++; + if (ch == '<') { + n += snprintf(dst + n, dst_len - n, "%s", "<"); + } else { + dst[n++] = ch; + } + } + dst[n] = '\0'; +} + +static void print_dir_entry(struct mg_connection *nc, const char *file_name, + cs_stat_t *stp) { + char size[64], mod[64], href[MAX_PATH_SIZE * 3], path[MAX_PATH_SIZE]; + int64_t fsize = stp->st_size; + int is_dir = S_ISDIR(stp->st_mode); + const char *slash = is_dir ? "/" : ""; + + if (is_dir) { + snprintf(size, sizeof(size), "%s", "[DIRECTORY]"); + } else { + /* + * We use (double) cast below because MSVC 6 compiler cannot + * convert unsigned __int64 to double. + */ + if (fsize < 1024) { + snprintf(size, sizeof(size), "%d", (int) fsize); + } else if (fsize < 0x100000) { + snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0); + } else if (fsize < 0x40000000) { + snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576); + } else { + snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824); + } + } + strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime)); + escape(file_name, path, sizeof(path)); + mg_url_encode(file_name, strlen(file_name), href, sizeof(href)); + mg_printf_http_chunk(nc, + "%s%s" + "%s%s\n", + href, slash, path, slash, mod, is_dir ? -1 : fsize, + size); +} + +static void scan_directory(struct mg_connection *nc, const char *dir, + const struct mg_serve_http_opts *opts, + void (*func)(struct mg_connection *, const char *, + cs_stat_t *)) { + char path[MAX_PATH_SIZE]; + cs_stat_t st; + struct dirent *dp; + DIR *dirp; + + if ((dirp = (opendir(dir))) != NULL) { + while ((dp = readdir(dirp)) != NULL) { + /* Do not show current dir and hidden files */ + if (is_file_hidden(dp->d_name, opts)) { + continue; + } + snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name); + if (mg_stat(path, &st) == 0) { + func(nc, dp->d_name, &st); + } + } + closedir(dirp); + } +} + +static void send_directory_listing(struct mg_connection *nc, const char *dir, + struct http_message *hm, + struct mg_serve_http_opts *opts) { + static const char *sort_js_code = + ""; + + mg_send_response_line(nc, 200, opts->extra_headers); + mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked", + "Content-Type", "text/html; charset=utf-8"); + + mg_printf_http_chunk( + nc, + "Index of %.*s%s%s" + "" + "

Index of %.*s

"
+      ""
+      "",
+      (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
+      (int) hm->uri.len, hm->uri.p);
+  scan_directory(nc, dir, opts, print_dir_entry);
+  mg_printf_http_chunk(nc, "%s", "");
+  mg_send_http_chunk(nc, "", 0);
+  /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
+  nc->flags |= MG_F_SEND_AND_CLOSE;
+}
+#endif /* MG_DISABLE_DIRECTORY_LISTING */
+
+#ifndef MG_DISABLE_DAV
+static void print_props(struct mg_connection *nc, const char *name,
+                        cs_stat_t *stp) {
+  char mtime[64], buf[MAX_PATH_SIZE * 3];
+  time_t t = stp->st_mtime; /* store in local variable for NDK compile */
+  gmt_time_string(mtime, sizeof(mtime), &t);
+  mg_url_encode(name, strlen(name), buf, sizeof(buf));
+  mg_printf(nc,
+            ""
+            "%s"
+            ""
+            ""
+            "%s"
+            "%" INT64_FMT
+            ""
+            "%s"
+            ""
+            "HTTP/1.1 200 OK"
+            ""
+            "\n",
+            buf, S_ISDIR(stp->st_mode) ? "" : "",
+            (int64_t) stp->st_size, mtime);
+}
+
+static void handle_propfind(struct mg_connection *nc, const char *path,
+                            cs_stat_t *stp, struct http_message *hm,
+                            struct mg_serve_http_opts *opts) {
+  static const char header[] =
+      "HTTP/1.1 207 Multi-Status\r\n"
+      "Connection: close\r\n"
+      "Content-Type: text/xml; charset=utf-8\r\n\r\n"
+      ""
+      "\n";
+  static const char footer[] = "\n";
+  const struct mg_str *depth = mg_get_http_header(hm, "Depth");
+
+  /* Print properties for the requested resource itself */
+  if (S_ISDIR(stp->st_mode) &&
+      strcmp(opts->enable_directory_listing, "yes") != 0) {
+    mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
+  } else {
+    char uri[MAX_PATH_SIZE];
+    mg_send(nc, header, sizeof(header) - 1);
+    snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
+    print_props(nc, uri, stp);
+    if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
+      scan_directory(nc, path, opts, print_props);
+    }
+    mg_send(nc, footer, sizeof(footer) - 1);
+    nc->flags |= MG_F_SEND_AND_CLOSE;
+  }
+}
+
+static void handle_mkcol(struct mg_connection *nc, const char *path,
+                         struct http_message *hm) {
+  int status_code = 500;
+  if (mg_get_http_header(hm, "Content-Length") != NULL) {
+    status_code = 415;
+  } else if (!mg_mkdir(path, 0755)) {
+    status_code = 201;
+  } else if (errno == EEXIST) {
+    status_code = 405;
+  } else if (errno == EACCES) {
+    status_code = 403;
+  } else if (errno == ENOENT) {
+    status_code = 409;
+  }
+  send_http_error(nc, status_code, NULL);
+}
+
+static int remove_directory(const char *dir) {
+  char path[MAX_PATH_SIZE];
+  struct dirent *dp;
+  cs_stat_t st;
+  DIR *dirp;
+
+  if ((dirp = opendir(dir)) == NULL) return 0;
+
+  while ((dp = readdir(dirp)) != NULL) {
+    if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
+    snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
+    mg_stat(path, &st);
+    if (S_ISDIR(st.st_mode)) {
+      remove_directory(path);
+    } else {
+      remove(path);
+    }
+  }
+  closedir(dirp);
+  rmdir(dir);
+
+  return 1;
+}
+
+static void handle_delete(struct mg_connection *nc, const char *path) {
+  cs_stat_t st;
+  if (mg_stat(path, &st) != 0) {
+    send_http_error(nc, 404, NULL);
+  } else if (S_ISDIR(st.st_mode)) {
+    remove_directory(path);
+    send_http_error(nc, 204, NULL);
+  } else if (remove(path) == 0) {
+    send_http_error(nc, 204, NULL);
+  } else {
+    send_http_error(nc, 423, NULL);
+  }
+}
+
+/* Return -1 on error, 1 on success. */
+static int create_itermediate_directories(const char *path) {
+  const char *s = path;
+
+  /* Create intermediate directories if they do not exist */
+  while (*s) {
+    if (*s == '/') {
+      char buf[MAX_PATH_SIZE];
+      cs_stat_t st;
+      snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
+      buf[sizeof(buf) - 1] = '\0';
+      if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
+        return -1;
+      }
+    }
+    s++;
+  }
+
+  return 1;
+}
+
+static void handle_put(struct mg_connection *nc, const char *path,
+                       struct http_message *hm) {
+  cs_stat_t st;
+  const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
+  int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
+  struct proto_data_http *dp = (struct proto_data_http *) nc->proto_data;
+
+  free_http_proto_data(nc);
+  if ((rc = create_itermediate_directories(path)) == 0) {
+    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
+  } else if (rc == -1) {
+    send_http_error(nc, 500, NULL);
+  } else if (cl_hdr == NULL) {
+    send_http_error(nc, 411, NULL);
+  } else if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) ==
+             NULL) {
+    send_http_error(nc, 500, NULL); /* LCOV_EXCL_LINE */
+  } else if ((dp->fp = fopen(path, "w+b")) == NULL) {
+    send_http_error(nc, 500, NULL);
+    free_http_proto_data(nc);
+  } else {
+    const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
+    int64_t r1 = 0, r2 = 0;
+    dp->type = DATA_PUT;
+    mg_set_close_on_exec(fileno(dp->fp));
+    dp->cl = to64(cl_hdr->p);
+    if (range_hdr != NULL && parse_range_header(range_hdr, &r1, &r2) > 0) {
+      status_code = 206;
+      fseeko(dp->fp, r1, SEEK_SET);
+      dp->cl = r2 > r1 ? r2 - r1 + 1 : dp->cl - r1;
+    }
+    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
+    nc->proto_data = dp;
+    /* Remove HTTP request from the mbuf, leave only payload */
+    mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
+    transfer_file_data(nc);
+  }
+}
+#endif /* MG_DISABLE_DAV */
+
+static int is_dav_request(const struct mg_str *s) {
+  return !mg_vcmp(s, "PUT") || !mg_vcmp(s, "DELETE") || !mg_vcmp(s, "MKCOL") ||
+         !mg_vcmp(s, "PROPFIND");
+}
+
+/*
+ * Given a directory path, find one of the files specified in the
+ * comma-separated list of index files `list`.
+ * First found index file wins. If an index file is found, then gets
+ * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
+ * If index file is not found, then `path` and `stp` remain unchanged.
+ */
+MG_INTERNAL int find_index_file(char *path, size_t path_len, const char *list,
+                                cs_stat_t *stp) {
+  cs_stat_t st;
+  size_t n = strlen(path);
+  struct mg_str vec;
+  int found = 0;
+
+  /* The 'path' given to us points to the directory. Remove all trailing */
+  /* directory separator characters from the end of the path, and */
+  /* then append single directory separator character. */
+  while (n > 0 && (path[n - 1] == '/' || path[n - 1] == '\\')) {
+    n--;
+  }
+
+  /* Traverse index files list. For each entry, append it to the given */
+  /* path and see if the file exists. If it exists, break the loop */
+  while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
+    /* Prepare full path to the index file */
+    snprintf(path + n, path_len - n, "/%.*s", (int) vec.len, vec.p);
+    path[path_len - 1] = '\0';
+
+    /* Does it exist? */
+    if (!mg_stat(path, &st)) {
+      /* Yes it does, break the loop */
+      *stp = st;
+      found = 1;
+      break;
+    }
+  }
+
+  /* If no index file exists, restore directory path, keep trailing slash. */
+  if (!found) {
+    path[n] = '\0';
+    strncat(path + n, "/", path_len - n);
+  }
+
+  return found;
+}
+
+static int send_port_based_redirect(struct mg_connection *c,
+                                    struct http_message *hm,
+                                    const struct mg_serve_http_opts *opts) {
+  const char *rewrites = opts->url_rewrites;
+  struct mg_str a, b;
+  char local_port[20] = {'%'};
+
+#ifndef MG_ESP8266
+  mg_sock_to_str(c->sock, local_port + 1, sizeof(local_port) - 1,
+                 MG_SOCK_STRINGIFY_PORT);
+#else
+  /* TODO(lsm): remove when mg_sock_to_str() is implemented in LWIP codepath */
+  snprintf(local_port, sizeof(local_port), "%s", "%0");
+#endif
+
+  while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
+    if (mg_vcmp(&a, local_port) == 0) {
+      mg_send_response_line(c, 301, NULL);
+      mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
+                (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
+                hm->uri.p);
+      return 1;
+    }
+  }
+
+  return 0;
+}
+
+static void uri_to_path(struct http_message *hm, char *buf, size_t buf_len,
+                        const struct mg_serve_http_opts *opts) {
+  char uri[MG_MAX_PATH];
+  struct mg_str a, b, *host_hdr = mg_get_http_header(hm, "Host");
+  const char *rewrites = opts->url_rewrites;
+
+  mg_url_decode(hm->uri.p, hm->uri.len, uri, sizeof(uri), 0);
+  remove_double_dots(uri);
+  snprintf(buf, buf_len, "%s%s", opts->document_root, uri);
+
+#ifndef MG_DISABLE_DAV
+  if (is_dav_request(&hm->method) && opts->dav_document_root != NULL) {
+    snprintf(buf, buf_len, "%s%s", opts->dav_document_root, uri);
+  }
+#endif
+
+  /* Handle URL rewrites */
+  while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
+    if (a.len > 1 && a.p[0] == '@' && host_hdr != NULL &&
+        host_hdr->len == a.len - 1 &&
+        mg_ncasecmp(a.p + 1, host_hdr->p, a.len - 1) == 0) {
+      /* This is a virtual host rewrite: @domain.name=document_root_dir */
+      snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.p, uri);
+      break;
+    } else {
+      /* This is a usual rewrite, URI=directory */
+      int match_len = mg_match_prefix(a.p, a.len, uri);
+      if (match_len > 0) {
+        snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.p, uri + match_len);
+        break;
+      }
+    }
+  }
+}
+
+#ifndef MG_DISABLE_CGI
+#ifdef _WIN32
+struct threadparam {
+  sock_t s;
+  HANDLE hPipe;
+};
+
+static int wait_until_ready(sock_t sock, int for_read) {
+  fd_set set;
+  FD_ZERO(&set);
+  FD_SET(sock, &set);
+  return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
+}
+
+static void *push_to_stdin(void *arg) {
+  struct threadparam *tp = (struct threadparam *) arg;
+  int n, sent, stop = 0;
+  DWORD k;
+  char buf[BUFSIZ];
+
+  while (!stop && wait_until_ready(tp->s, 1) &&
+         (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
+    if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
+    for (sent = 0; !stop && sent < n; sent += k) {
+      if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
+    }
+  }
+  DBG(("%s", "FORWARED EVERYTHING TO CGI"));
+  CloseHandle(tp->hPipe);
+  MG_FREE(tp);
+  _endthread();
+  return NULL;
+}
+
+static void *pull_from_stdout(void *arg) {
+  struct threadparam *tp = (struct threadparam *) arg;
+  int k = 0, stop = 0;
+  DWORD n, sent;
+  char buf[BUFSIZ];
+
+  while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
+    for (sent = 0; !stop && sent < n; sent += k) {
+      if (wait_until_ready(tp->s, 0) &&
+          (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
+        stop = 1;
+    }
+  }
+  DBG(("%s", "EOF FROM CGI"));
+  CloseHandle(tp->hPipe);
+  shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
+  closesocket(tp->s);
+  MG_FREE(tp);
+  _endthread();
+  return NULL;
+}
+
+static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
+                               void *(*func)(void *)) {
+  struct threadparam *tp = (struct threadparam *) MG_MALLOC(sizeof(*tp));
+  if (tp != NULL) {
+    tp->s = sock;
+    tp->hPipe = hPipe;
+    mg_start_thread(func, tp);
+  }
+}
+
+static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
+  wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
+  to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
+  GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
+  WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
+}
+
+static pid_t start_process(const char *interp, const char *cmd, const char *env,
+                           const char *envp[], const char *dir, sock_t sock) {
+  STARTUPINFOW si;
+  PROCESS_INFORMATION pi;
+  HANDLE a[2], b[2], me = GetCurrentProcess();
+  wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
+  char buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
+      buf4[MAX_PATH_SIZE], cmdline[MAX_PATH_SIZE];
+  DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
+  FILE *fp;
+
+  memset(&si, 0, sizeof(si));
+  memset(&pi, 0, sizeof(pi));
+
+  si.cb = sizeof(si);
+  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
+  si.wShowWindow = SW_HIDE;
+  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
+
+  CreatePipe(&a[0], &a[1], NULL, 0);
+  CreatePipe(&b[0], &b[1], NULL, 0);
+  DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
+  DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
+
+  if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
+    buf[0] = buf[1] = '\0';
+    fgets(buf, sizeof(buf), fp);
+    buf[sizeof(buf) - 1] = '\0';
+    if (buf[0] == '#' && buf[1] == '!') {
+      interp = buf + 2;
+      /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
+      while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
+        interp++;
+      }
+    }
+    fclose(fp);
+  }
+
+  snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
+  abs_path(buf, buf2, ARRAY_SIZE(buf2));
+
+  abs_path(dir, buf5, ARRAY_SIZE(buf5));
+  to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
+
+  if (interp != NULL) {
+    abs_path(interp, buf4, ARRAY_SIZE(buf4));
+    snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
+  } else {
+    snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
+  }
+  to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
+
+#if 0
+  printf("[%ls] [%ls]\n", full_dir, wcmd);
+#endif
+
+  if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
+                     (void *) env, full_dir, &si, &pi) != 0) {
+    spawn_stdio_thread(sock, a[1], push_to_stdin);
+    spawn_stdio_thread(sock, b[0], pull_from_stdout);
+  } else {
+    CloseHandle(a[1]);
+    CloseHandle(b[0]);
+    closesocket(sock);
+  }
+  DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
+
+  /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
+  CloseHandle(si.hStdOutput);
+  CloseHandle(si.hStdInput);
+  /* TODO(lsm): check if we need close process and thread handles too */
+  /* CloseHandle(pi.hThread); */
+  /* CloseHandle(pi.hProcess); */
+
+  return pi.hProcess;
+}
+#else
+static pid_t start_process(const char *interp, const char *cmd, const char *env,
+                           const char *envp[], const char *dir, sock_t sock) {
+  char buf[500];
+  pid_t pid = fork();
+  (void) env;
+
+  if (pid == 0) {
+    /*
+     * In Linux `chdir` declared with `warn_unused_result` attribute
+     * To shutup compiler we have yo use result in some way
+     */
+    int tmp = chdir(dir);
+    (void) tmp;
+    (void) dup2(sock, 0);
+    (void) dup2(sock, 1);
+    closesocket(sock);
+
+    /*
+     * After exec, all signal handlers are restored to their default values,
+     * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
+     * implementation, SIGCHLD's handler will leave unchanged after exec
+     * if it was set to be ignored. Restore it to default action.
+     */
+    signal(SIGCHLD, SIG_DFL);
+
+    if (interp == NULL) {
+      execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
+    } else {
+      execle(interp, interp, cmd, (char *) 0, envp);
+    }
+    snprintf(buf, sizeof(buf),
+             "Status: 500\r\n\r\n"
+             "500 Server Error: %s%s%s: %s",
+             interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
+             strerror(errno));
+    send(1, buf, strlen(buf), 0);
+    exit(EXIT_FAILURE); /* exec call failed */
+  }
+
+  return pid;
+}
+#endif /* _WIN32 */
+
+/*
+ * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
+ * pointer into the vars array.
+ */
+static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
+  int n, space;
+  char *added = block->buf + block->len;
+  va_list ap;
+
+  /* Calculate how much space is left in the buffer */
+  space = sizeof(block->buf) - (block->len + 2);
+  if (space > 0) {
+    /* Copy VARIABLE=VALUE\0 string into the free space */
+    va_start(ap, fmt);
+    n = vsnprintf(added, (size_t) space, fmt, ap);
+    va_end(ap);
+
+    /* Make sure we do not overflow buffer and the envp array */
+    if (n > 0 && n + 1 < space &&
+        block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
+      /* Append a pointer to the added string into the envp array */
+      block->vars[block->nvars++] = added;
+      /* Bump up used length counter. Include \0 terminator */
+      block->len += n + 1;
+    }
+  }
+
+  return added;
+}
+
+static void addenv2(struct cgi_env_block *blk, const char *name) {
+  const char *s;
+  if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
+}
+
+static void prepare_cgi_environment(struct mg_connection *nc, const char *prog,
+                                    const struct http_message *hm,
+                                    const struct mg_serve_http_opts *opts,
+                                    struct cgi_env_block *blk) {
+  const char *s, *slash;
+  struct mg_str *h;
+  char *p;
+  size_t i;
+
+  blk->len = blk->nvars = 0;
+  blk->nc = nc;
+
+  if ((s = getenv("SERVER_NAME")) != NULL) {
+    addenv(blk, "SERVER_NAME=%s", s);
+  } else {
+    char buf[100];
+    mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
+    addenv(blk, "SERVER_NAME=%s", buf);
+  }
+  addenv(blk, "SERVER_ROOT=%s", opts->document_root);
+  addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
+  addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
+
+  /* Prepare the environment block */
+  addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
+  addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
+  addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
+
+  /* TODO(lsm): fix this for IPv6 case */
+  /*addenv(blk, "SERVER_PORT=%d", ri->remote_port); */
+
+  addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
+#if 0
+  addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
+  addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
+#endif
+  addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
+         hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
+         hm->query_string.p);
+
+/* SCRIPT_NAME */
+#if 0
+  if (nc->path_info != NULL) {
+    addenv(blk, "SCRIPT_NAME=%.*s",
+           (int) (strlen(ri->uri) - strlen(nc->path_info)), ri->uri);
+    addenv(blk, "PATH_INFO=%s", nc->path_info);
+  } else {
+#endif
+  s = strrchr(prog, '/');
+  slash = hm->uri.p + hm->uri.len;
+  while (slash > hm->uri.p && *slash != '/') {
+    slash--;
+  }
+  addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - hm->uri.p), hm->uri.p,
+         s == NULL ? prog : s);
+#if 0
+  }
+#endif
+
+  addenv(blk, "SCRIPT_FILENAME=%s", prog);
+  addenv(blk, "PATH_TRANSLATED=%s", prog);
+  addenv(blk, "HTTPS=%s", nc->ssl != NULL ? "on" : "off");
+
+  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
+      NULL) {
+    addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
+  }
+
+  if (hm->query_string.len > 0) {
+    addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
+           hm->query_string.p);
+  }
+
+  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
+      NULL) {
+    addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
+  }
+
+  addenv2(blk, "PATH");
+  addenv2(blk, "TMP");
+  addenv2(blk, "TEMP");
+  addenv2(blk, "TMPDIR");
+  addenv2(blk, "PERLLIB");
+  addenv2(blk, MG_ENV_EXPORT_TO_CGI);
+
+#if defined(_WIN32)
+  addenv2(blk, "COMSPEC");
+  addenv2(blk, "SYSTEMROOT");
+  addenv2(blk, "SystemDrive");
+  addenv2(blk, "ProgramFiles");
+  addenv2(blk, "ProgramFiles(x86)");
+  addenv2(blk, "CommonProgramFiles(x86)");
+#else
+  addenv2(blk, "LD_LIBRARY_PATH");
+#endif /* _WIN32 */
+
+  /* Add all headers as HTTP_* variables */
+  for (i = 0; hm->header_names[i].len > 0; i++) {
+    p = addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
+               hm->header_names[i].p, (int) hm->header_values[i].len,
+               hm->header_values[i].p);
+
+    /* Convert variable name into uppercase, and change - to _ */
+    for (; *p != '=' && *p != '\0'; p++) {
+      if (*p == '-') *p = '_';
+      *p = (char) toupper(*(unsigned char *) p);
+    }
+  }
+
+  blk->vars[blk->nvars++] = NULL;
+  blk->buf[blk->len++] = '\0';
+}
+
+static void cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
+                           void *ev_data) {
+  struct mg_connection *nc = (struct mg_connection *) cgi_nc->user_data;
+  (void) ev_data;
+
+  if (nc == NULL) return;
+
+  switch (ev) {
+    case MG_EV_RECV:
+      /*
+       * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
+       * It outputs headers, then body. Headers might include "Status"
+       * header, which changes CODE, and it might include "Location" header
+       * which changes CODE to 302.
+       *
+       * Therefore we do not send the output from the CGI script to the user
+       * until all CGI headers are received.
+       *
+       * Here we parse the output from the CGI script, and if all headers has
+       * been received, send appropriate reply line, and forward all
+       * received headers to the client.
+       */
+      if (nc->flags & MG_F_USER_1) {
+        struct mbuf *io = &cgi_nc->recv_mbuf;
+        int len = get_request_len(io->buf, io->len);
+
+        if (len == 0) break;
+        if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
+          cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
+          send_http_error(nc, 500, "Bad headers");
+        } else {
+          struct http_message hm;
+          struct mg_str *h;
+          parse_http_headers(io->buf, io->buf + io->len, io->len, &hm);
+          /*printf("=== %d [%.*s]\n", k, k, io->buf);*/
+          if (mg_get_http_header(&hm, "Location") != NULL) {
+            mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
+          } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
+            mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
+          } else {
+            mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
+          }
+        }
+        nc->flags &= ~MG_F_USER_1;
+      }
+      if (!(nc->flags & MG_F_USER_1)) {
+        mg_forward(cgi_nc, nc);
+      }
+      break;
+    case MG_EV_CLOSE:
+      free_http_proto_data(cgi_nc);
+      nc->flags |= MG_F_SEND_AND_CLOSE;
+      nc->user_data = NULL;
+      break;
+  }
+}
+
+static void handle_cgi(struct mg_connection *nc, const char *prog,
+                       const struct http_message *hm,
+                       const struct mg_serve_http_opts *opts) {
+  struct proto_data_http *dp;
+  struct cgi_env_block blk;
+  char dir[MAX_PATH_SIZE];
+  const char *p;
+  sock_t fds[2];
+
+  prepare_cgi_environment(nc, prog, hm, opts, &blk);
+  /*
+   * CGI must be executed in its own directory. 'dir' must point to the
+   * directory containing executable program, 'p' must point to the
+   * executable program name relative to 'dir'.
+   */
+  if ((p = strrchr(prog, '/')) == NULL) {
+    snprintf(dir, sizeof(dir), "%s", ".");
+  } else {
+    snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
+    prog = p + 1;
+  }
+
+  /*
+   * Try to create socketpair in a loop until success. mg_socketpair()
+   * can be interrupted by a signal and fail.
+   * TODO(lsm): use sigaction to restart interrupted syscall
+   */
+  do {
+    mg_socketpair(fds, SOCK_STREAM);
+  } while (fds[0] == INVALID_SOCKET);
+
+  free_http_proto_data(nc);
+  if ((dp = (struct proto_data_http *) MG_CALLOC(1, sizeof(*dp))) == NULL) {
+    send_http_error(nc, 500, "OOM"); /* LCOV_EXCL_LINE */
+  } else if (start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
+                           fds[1]) != 0) {
+    size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
+    dp->type = DATA_CGI;
+    dp->cgi_nc = mg_add_sock(nc->mgr, fds[0], cgi_ev_handler);
+    dp->cgi_nc->user_data = nc;
+    dp->cgi_nc->proto_data = dp;
+    nc->flags |= MG_F_USER_1;
+    /* Push POST data to the CGI */
+    if (n > 0 && n < nc->recv_mbuf.len) {
+      mg_send(dp->cgi_nc, hm->body.p, n);
+    }
+    mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
+  } else {
+    closesocket(fds[0]);
+    send_http_error(nc, 500, "CGI failure");
+  }
+
+#ifndef _WIN32
+  closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
+#endif
+}
+#endif
+
+static int mg_get_month_index(const char *s) {
+  static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
+                                      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
+  size_t i;
+
+  for (i = 0; i < ARRAY_SIZE(month_names); i++)
+    if (!strcmp(s, month_names[i])) return (int) i;
+
+  return -1;
+}
+
+static int mg_num_leap_years(int year) {
+  return year / 4 - year / 100 + year / 400;
+}
+
+/* Parse UTC date-time string, and return the corresponding time_t value. */
+MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
+  static const unsigned short days_before_month[] = {
+      0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
+  char month_str[32];
+  int second, minute, hour, day, month, year, leap_days, days;
+  time_t result = (time_t) 0;
+
+  if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
+               &minute, &second) == 6) ||
+       (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
+               &minute, &second) == 6) ||
+       (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
+               &hour, &minute, &second) == 6) ||
+       (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
+               &minute, &second) == 6)) &&
+      year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
+    leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
+    year -= 1970;
+    days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
+    result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
+  }
+
+  return result;
+}
+
+MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
+  struct mg_str *hdr;
+  if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
+    char etag[64];
+    construct_etag(etag, sizeof(etag), st);
+    return mg_vcasecmp(hdr, etag) == 0;
+  } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
+    return st->st_mtime <= mg_parse_date_string(hdr->p);
+  } else {
+    return 0;
+  }
+}
+
+static void mg_send_digest_auth_request(struct mg_connection *c,
+                                        const char *domain) {
+  mg_printf(c,
+            "HTTP/1.1 401 Unauthorized\r\n"
+            "WWW-Authenticate: Digest qop=\"auth\", "
+            "realm=\"%s\", nonce=\"%lu\"\r\n"
+            "Content-Length: 0\r\n\r\n",
+            domain, (unsigned long) time(NULL));
+}
+
+void mg_send_http_file(struct mg_connection *nc, char *path,
+                       size_t path_buf_len, struct http_message *hm,
+                       struct mg_serve_http_opts *opts) {
+  int stat_result, is_directory, is_dav = is_dav_request(&hm->method);
+  uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
+  cs_stat_t st;
+
+  DBG(("serving [%s]", path));
+  stat_result = mg_stat(path, &st);
+  is_directory = !stat_result && S_ISDIR(st.st_mode);
+
+  if (mg_check_ip_acl(opts->ip_acl, remote_ip) != 1) {
+    /* Not allowed to connect */
+    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
+  } else if (is_dav && opts->dav_document_root == NULL) {
+    send_http_error(nc, 501, NULL);
+  } else if (!is_authorized(hm, path, is_directory, opts->auth_domain,
+                            opts->global_auth_file, 1) ||
+             !is_authorized(hm, path, is_directory, opts->auth_domain,
+                            opts->per_directory_auth_file, 0)) {
+    mg_send_digest_auth_request(nc, opts->auth_domain);
+  } else if ((stat_result != 0 || is_file_hidden(path, opts)) && !is_dav) {
+    mg_printf(nc, "%s", "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
+  } else if (is_directory && path[strlen(path) - 1] != '/' && !is_dav) {
+    mg_printf(nc,
+              "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
+              "Content-Length: 0\r\n\r\n",
+              (int) hm->uri.len, hm->uri.p);
+#ifndef MG_DISABLE_DAV
+  } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
+    handle_propfind(nc, path, &st, hm, opts);
+#ifndef MG_DISABLE_DAV_AUTH
+  } else if (is_dav &&
+             (opts->dav_auth_file == NULL ||
+              !is_authorized(hm, path, is_directory, opts->auth_domain,
+                             opts->dav_auth_file, 1))) {
+    mg_send_digest_auth_request(nc, opts->auth_domain);
+#endif
+  } else if (!mg_vcmp(&hm->method, "MKCOL")) {
+    handle_mkcol(nc, path, hm);
+  } else if (!mg_vcmp(&hm->method, "DELETE")) {
+    handle_delete(nc, path);
+  } else if (!mg_vcmp(&hm->method, "PUT")) {
+    handle_put(nc, path, hm);
+#endif
+  } else if (S_ISDIR(st.st_mode) &&
+             !find_index_file(path, path_buf_len, opts->index_files, &st)) {
+    if (strcmp(opts->enable_directory_listing, "yes") == 0) {
+#ifndef MG_DISABLE_DIRECTORY_LISTING
+      send_directory_listing(nc, path, hm, opts);
+#else
+      send_http_error(nc, 501, NULL);
+#endif
+    } else {
+      send_http_error(nc, 403, NULL);
+    }
+  } else if (mg_match_prefix(opts->cgi_file_pattern,
+                             strlen(opts->cgi_file_pattern), path) > 0) {
+#if !defined(MG_DISABLE_CGI)
+    handle_cgi(nc, path, hm, opts);
+#else
+    send_http_error(nc, 501, NULL);
+#endif /* MG_DISABLE_CGI */
+  } else if (mg_is_not_modified(hm, &st)) {
+    send_http_error(nc, 304, "Not Modified");
+  } else {
+    mg_send_http_file2(nc, path, &st, hm, opts);
+  }
+}
+
+void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
+                   struct mg_serve_http_opts opts) {
+  char path[MG_MAX_PATH];
+  struct mg_str *hdr;
+
+  if (send_port_based_redirect(nc, hm, &opts)) {
+    return;
+  }
+
+  if (opts.document_root == NULL) {
+    opts.document_root = ".";
+  }
+  if (opts.per_directory_auth_file == NULL) {
+    opts.per_directory_auth_file = ".htpasswd";
+  }
+  if (opts.enable_directory_listing == NULL) {
+    opts.enable_directory_listing = "yes";
+  }
+  if (opts.cgi_file_pattern == NULL) {
+    opts.cgi_file_pattern = "**.cgi$|**.php$";
+  }
+  if (opts.ssi_pattern == NULL) {
+    opts.ssi_pattern = "**.shtml$|**.shtm$";
+  }
+  if (opts.index_files == NULL) {
+    opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
+  }
+
+  uri_to_path(hm, path, sizeof(path), &opts);
+  mg_send_http_file(nc, path, sizeof(path), hm, &opts);
+
+  /* Close connection for non-keep-alive requests */
+  if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
+      ((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
+       mg_vcmp(hdr, "keep-alive") != 0)) {
+#if 0
+    nc->flags |= MG_F_SEND_AND_CLOSE;
+#endif
+  }
+}
+
+#endif /* MG_DISABLE_FILESYSTEM */
+
+struct mg_connection *mg_connect_http(struct mg_mgr *mgr,
+                                      mg_event_handler_t ev_handler,
+                                      const char *url,
+                                      const char *extra_headers,
+                                      const char *post_data) {
+  struct mg_connection *nc = NULL;
+  char *addr = NULL;
+  const char *path = NULL;
+  int use_ssl = 0, addr_len = 0, port_i = -1;
+
+  if (memcmp(url, "http://", 7) == 0) {
+    url += 7;
+  } else if (memcmp(url, "https://", 8) == 0) {
+    url += 8;
+    use_ssl = 1;
+#ifndef MG_ENABLE_SSL
+    return NULL; /* SSL is not enabled, cannot do HTTPS URLs */
+#endif
+  }
+
+  while (*url != '\0') {
+    addr = (char *) MG_REALLOC(addr, addr_len + 5 /* space for port too. */);
+    if (addr == NULL) {
+      DBG(("OOM"));
+      return NULL;
+    }
+    if (*url == '/') {
+      url++;
+      break;
+    }
+    if (*url == ':') port_i = addr_len;
+    addr[addr_len++] = *url;
+    addr[addr_len] = '\0';
+    url++;
+  }
+  if (addr_len == 0) goto cleanup;
+  if (port_i < 0) {
+    port_i = addr_len;
+    strcpy(addr + port_i, use_ssl ? ":443" : ":80");
+  } else {
+    port_i = -1;
+  }
+
+  if (path == NULL) path = url;
+
+  DBG(("%s %s", addr, path));
+  if ((nc = mg_connect(mgr, addr, ev_handler)) != NULL) {
+    mg_set_protocol_http_websocket(nc);
+
+    if (use_ssl) {
+#ifdef MG_ENABLE_SSL
+      mg_set_ssl(nc, NULL, NULL);
+#endif
+    }
+
+    /* If the port was addred by us, restore the original host. */
+    if (port_i >= 0) addr[port_i] = '\0';
+    mg_printf(nc, "%s /%s HTTP/1.1\r\nHost: %s\r\nContent-Length: %" SIZE_T_FMT
+                  "\r\n%s\r\n%s",
+              post_data == NULL ? "GET" : "POST", path, addr,
+              post_data == NULL ? 0 : strlen(post_data),
+              extra_headers == NULL ? "" : extra_headers,
+              post_data == NULL ? "" : post_data);
+  }
+
+cleanup:
+  MG_FREE(addr);
+  return nc;
+}
+
+static size_t get_line_len(const char *buf, size_t buf_len) {
+  size_t len = 0;
+  while (len < buf_len && buf[len] != '\n') len++;
+  return buf[len] == '\n' ? len + 1 : 0;
+}
+
+size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
+                          size_t var_name_len, char *file_name,
+                          size_t file_name_len, const char **data,
+                          size_t *data_len) {
+  static const char cd[] = "Content-Disposition: ";
+  size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
+
+  if (buf == NULL || buf_len <= 0) return 0;
+  if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
+  if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
+
+  /* Get boundary length */
+  bl = get_line_len(buf, buf_len);
+
+  /* Loop through headers, fetch variable name and file name */
+  var_name[0] = file_name[0] = '\0';
+  for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
+    if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
+      struct mg_str header;
+      header.p = buf + n + cdl;
+      header.len = ll - (cdl + 2);
+      mg_http_parse_header(&header, "name", var_name, var_name_len);
+      mg_http_parse_header(&header, "filename", file_name, file_name_len);
+    }
+  }
+
+  /* Scan through the body, search for terminating boundary */
+  for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
+    if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
+      if (data_len != NULL) *data_len = (pos - 2) - hl;
+      if (data != NULL) *data = buf + hl;
+      return pos;
+    }
+  }
+
+  return 0;
+}
+
+#endif /* MG_DISABLE_HTTP */
+#ifdef NS_MODULE_LINES
+#line 1 "src/util.c"
+/**/
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/* Amalgamated: #include "internal.h" */
+
+const char *mg_skip(const char *s, const char *end, const char *delims,
+                    struct mg_str *v) {
+  v->p = s;
+  while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
+  v->len = s - v->p;
+  while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
+  return s;
+}
+
+static int lowercase(const char *s) {
+  return tolower(*(const unsigned char *) s);
+}
+
+int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
+  int diff = 0;
+
+  if (len > 0) do {
+      diff = lowercase(s1++) - lowercase(s2++);
+    } while (diff == 0 && s1[-1] != '\0' && --len > 0);
+
+  return diff;
+}
+
+int mg_casecmp(const char *s1, const char *s2) {
+  return mg_ncasecmp(s1, s2, (size_t) ~0);
+}
+
+int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
+  size_t n2 = strlen(str2), n1 = str1->len;
+  int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
+  if (r == 0) {
+    return n1 - n2;
+  }
+  return r;
+}
+
+int mg_vcmp(const struct mg_str *str1, const char *str2) {
+  size_t n2 = strlen(str2), n1 = str1->len;
+  int r = memcmp(str1->p, str2, (n1 < n2) ? n1 : n2);
+  if (r == 0) {
+    return n1 - n2;
+  }
+  return r;
+}
+
+#ifndef MG_DISABLE_FILESYSTEM
+int mg_stat(const char *path, cs_stat_t *st) {
+#ifdef _WIN32
+  wchar_t wpath[MAX_PATH_SIZE];
+  to_wchar(path, wpath, ARRAY_SIZE(wpath));
+  DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
+  return _wstati64(wpath, (struct _stati64 *) st);
+#else
+  return stat(path, st);
+#endif
+}
+
+FILE *mg_fopen(const char *path, const char *mode) {
+#ifdef _WIN32
+  wchar_t wpath[MAX_PATH_SIZE], wmode[10];
+  to_wchar(path, wpath, ARRAY_SIZE(wpath));
+  to_wchar(mode, wmode, ARRAY_SIZE(wmode));
+  return _wfopen(wpath, wmode);
+#else
+  return fopen(path, mode);
+#endif
+}
+
+int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
+#ifdef _WIN32
+  wchar_t wpath[MAX_PATH_SIZE];
+  to_wchar(path, wpath, ARRAY_SIZE(wpath));
+  return _wopen(wpath, flag, mode);
+#else
+  return open(path, flag, mode); /* LCOV_EXCL_LINE */
+#endif
+}
+#endif
+
+void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
+  cs_base64_encode(src, src_len, dst);
+}
+
+int mg_base64_decode(const unsigned char *s, int len, char *dst) {
+  return cs_base64_decode(s, len, dst);
+}
+
+#ifdef MG_ENABLE_THREADS
+void *mg_start_thread(void *(*f)(void *), void *p) {
+#ifdef _WIN32
+  return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
+#else
+  pthread_t thread_id = (pthread_t) 0;
+  pthread_attr_t attr;
+
+  (void) pthread_attr_init(&attr);
+  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
+
+#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
+  (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
+#endif
+
+  pthread_create(&thread_id, &attr, f, p);
+  pthread_attr_destroy(&attr);
+
+  return (void *) thread_id;
+#endif
+}
+#endif /* MG_ENABLE_THREADS */
+
+/* Set close-on-exec bit for a given socket. */
+void mg_set_close_on_exec(sock_t sock) {
+#ifdef _WIN32
+  (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
+#else
+  fcntl(sock, F_SETFD, FD_CLOEXEC);
+#endif
+}
+
+void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
+                         int flags) {
+  int is_v6;
+  if (buf == NULL || len <= 0) return;
+  buf[0] = '\0';
+#if defined(MG_ENABLE_IPV6)
+  is_v6 = sa->sa.sa_family == AF_INET6;
+#else
+  is_v6 = 0;
+#endif
+  if (flags & MG_SOCK_STRINGIFY_IP) {
+#if defined(MG_ENABLE_IPV6)
+    const void *addr = NULL;
+    char *start = buf;
+    socklen_t capacity = len;
+    if (!is_v6) {
+      addr = &sa->sin.sin_addr;
+    } else {
+      addr = (void *) &sa->sin6.sin6_addr;
+      if (flags & MG_SOCK_STRINGIFY_PORT) {
+        *buf = '[';
+        start++;
+        capacity--;
+      }
+    }
+    if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
+      *buf = '\0';
+    }
+#elif defined(_WIN32) || defined(MG_ESP8266)
+    /* Only Windoze Vista (and newer) have inet_ntop() */
+    strncpy(buf, inet_ntoa(sa->sin.sin_addr), len);
+#else
+    inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len);
+#endif
+  }
+  if (flags & MG_SOCK_STRINGIFY_PORT) {
+    int port = ntohs(sa->sin.sin_port);
+    if (flags & MG_SOCK_STRINGIFY_IP) {
+      snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s:%d",
+               (is_v6 ? "]" : ""), port);
+    } else {
+      snprintf(buf, len, "%d", port);
+    }
+  }
+}
+
+void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
+                         int flags) {
+  union socket_address sa;
+  memset(&sa, 0, sizeof(sa));
+  mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
+  mg_sock_addr_to_str(&sa, buf, len, flags);
+}
+
+#ifndef MG_DISABLE_HEXDUMP
+int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
+  const unsigned char *p = (const unsigned char *) buf;
+  char ascii[17] = "";
+  int i, idx, n = 0;
+
+  for (i = 0; i < len; i++) {
+    idx = i % 16;
+    if (idx == 0) {
+      if (i > 0) n += snprintf(dst + n, dst_len - n, "  %s\n", ascii);
+      n += snprintf(dst + n, dst_len - n, "%04x ", i);
+    }
+    n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
+    ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
+    ascii[idx + 1] = '\0';
+  }
+
+  while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", "   ");
+  n += snprintf(dst + n, dst_len - n, "  %s\n\n", ascii);
+
+  return n;
+}
+#endif
+
+int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
+  va_list ap_copy;
+  int len;
+
+  va_copy(ap_copy, ap);
+  len = vsnprintf(*buf, size, fmt, ap_copy);
+  va_end(ap_copy);
+
+  if (len < 0) {
+    /* eCos and Windows are not standard-compliant and return -1 when
+     * the buffer is too small. Keep allocating larger buffers until we
+     * succeed or out of memory. */
+    *buf = NULL; /* LCOV_EXCL_START */
+    while (len < 0) {
+      MG_FREE(*buf);
+      size *= 2;
+      if ((*buf = (char *) MG_MALLOC(size)) == NULL) break;
+      va_copy(ap_copy, ap);
+      len = vsnprintf(*buf, size, fmt, ap_copy);
+      va_end(ap_copy);
+    }
+    /* LCOV_EXCL_STOP */
+  } else if (len >= (int) size) {
+    /* Standard-compliant code path. Allocate a buffer that is large enough. */
+    if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
+      len = -1; /* LCOV_EXCL_LINE */
+    } else {    /* LCOV_EXCL_LINE */
+      va_copy(ap_copy, ap);
+      len = vsnprintf(*buf, len + 1, fmt, ap_copy);
+      va_end(ap_copy);
+    }
+  }
+
+  return len;
+}
+
+#if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP)
+void mg_hexdump_connection(struct mg_connection *nc, const char *path,
+                           const void *buf, int num_bytes, int ev) {
+  FILE *fp = NULL;
+  char *hexbuf, src[60], dst[60];
+  int buf_size = num_bytes * 5 + 100;
+
+  if (strcmp(path, "-") == 0) {
+    fp = stdout;
+  } else if (strcmp(path, "--") == 0) {
+    fp = stderr;
+#ifndef MG_DISABLE_FILESYSTEM
+  } else {
+    fp = fopen(path, "a");
+#endif
+  }
+  if (fp == NULL) return;
+
+  mg_conn_addr_to_str(nc, src, sizeof(src),
+                      MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
+  mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
+                                                MG_SOCK_STRINGIFY_PORT |
+                                                MG_SOCK_STRINGIFY_REMOTE);
+  fprintf(
+      fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL), nc, src,
+      ev == MG_EV_RECV ? "<-" : ev == MG_EV_SEND
+                                    ? "->"
+                                    : ev == MG_EV_ACCEPT
+                                          ? "" : "XX",
+      dst, num_bytes);
+  if (num_bytes > 0 && (hexbuf = (char *) MG_MALLOC(buf_size)) != NULL) {
+    mg_hexdump(buf, num_bytes, hexbuf, buf_size);
+    fprintf(fp, "%s", hexbuf);
+    MG_FREE(hexbuf);
+  }
+  if (fp != stdin && fp != stdout) fclose(fp);
+}
+#endif
+
+int mg_is_big_endian(void) {
+  static const int n = 1;
+  /* TODO(mkm) use compiletime check with 4-byte char literal */
+  return ((char *) &n)[0] == 0;
+}
+
+const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
+                                     struct mg_str *eq_val) {
+  if (list == NULL || *list == '\0') {
+    /* End of the list */
+    list = NULL;
+  } else {
+    val->p = list;
+    if ((list = strchr(val->p, ',')) != NULL) {
+      /* Comma found. Store length and shift the list ptr */
+      val->len = list - val->p;
+      list++;
+    } else {
+      /* This value is the last one */
+      list = val->p + strlen(val->p);
+      val->len = list - val->p;
+    }
+
+    if (eq_val != NULL) {
+      /* Value has form "x=y", adjust pointers and lengths */
+      /* so that val points to "x", and eq_val points to "y". */
+      eq_val->len = 0;
+      eq_val->p = (const char *) memchr(val->p, '=', val->len);
+      if (eq_val->p != NULL) {
+        eq_val->p++; /* Skip over '=' character */
+        eq_val->len = val->p + val->len - eq_val->p;
+        val->len = (eq_val->p - val->p) - 1;
+      }
+    }
+  }
+
+  return list;
+}
+
+int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
+  const char *or_str;
+  int len, res, i = 0, j = 0;
+
+  if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
+    res = mg_match_prefix(pattern, or_str - pattern, str);
+    return res > 0 ? res : mg_match_prefix(
+                               or_str + 1,
+                               (pattern + pattern_len) - (or_str + 1), str);
+  }
+
+  for (; i < pattern_len; i++, j++) {
+    if (pattern[i] == '?' && str[j] != '\0') {
+      continue;
+    } else if (pattern[i] == '$') {
+      return str[j] == '\0' ? j : -1;
+    } else if (pattern[i] == '*') {
+      i++;
+      if (pattern[i] == '*') {
+        i++;
+        len = (int) strlen(str + j);
+      } else {
+        len = (int) strcspn(str + j, "/");
+      }
+      if (i == pattern_len) {
+        return j + len;
+      }
+      do {
+        res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len);
+      } while (res == -1 && len-- > 0);
+      return res == -1 ? -1 : j + res + len;
+    } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
+      return -1;
+    }
+  }
+  return j;
+}
+#ifdef NS_MODULE_LINES
+#line 1 "src/json-rpc.c"
+/**/
+#endif
+/* Copyright (c) 2014 Cesanta Software Limited */
+/* All rights reserved */
+
+#ifndef MG_DISABLE_JSON_RPC
+
+/* Amalgamated: #include "internal.h" */
+
+int mg_rpc_create_reply(char *buf, int len, const struct mg_rpc_request *req,
+                        const char *result_fmt, ...) {
+  static const struct json_token null_tok = {"null", 4, 0, JSON_TYPE_NULL};
+  const struct json_token *id = req->id == NULL ? &null_tok : req->id;
+  va_list ap;
+  int n = 0;
+
+  n += json_emit(buf + n, len - n, "{s:s,s:", "jsonrpc", "2.0", "id");
+  if (id->type == JSON_TYPE_STRING) {
+    n += json_emit_quoted_str(buf + n, len - n, id->ptr, id->len);
+  } else {
+    n += json_emit_unquoted_str(buf + n, len - n, id->ptr, id->len);
+  }
+  n += json_emit(buf + n, len - n, ",s:", "result");
+
+  va_start(ap, result_fmt);
+  n += json_emit_va(buf + n, len - n, result_fmt, ap);
+  va_end(ap);
+
+  n += json_emit(buf + n, len - n, "}");
+
+  return n;
+}
+
+int mg_rpc_create_request(char *buf, int len, const char *method,
+                          const char *id, const char *params_fmt, ...) {
+  va_list ap;
+  int n = 0;
+
+  n += json_emit(buf + n, len - n, "{s:s,s:s,s:s,s:", "jsonrpc", "2.0", "id",
+                 id, "method", method, "params");
+  va_start(ap, params_fmt);
+  n += json_emit_va(buf + n, len - n, params_fmt, ap);
+  va_end(ap);
+
+  n += json_emit(buf + n, len - n, "}");
+
+  return n;
+}
+
+int mg_rpc_create_error(char *buf, int len, struct mg_rpc_request *req,
+                        int code, const char *message, const char *fmt, ...) {
+  va_list ap;
+  int n = 0;
+
+  n += json_emit(buf + n, len - n, "{s:s,s:V,s:{s:i,s:s,s:", "jsonrpc", "2.0",
+                 "id", req->id == NULL ? "null" : req->id->ptr,
+                 req->id == NULL ? 4 : req->id->len, "error", "code", code,
+                 "message", message, "data");
+  va_start(ap, fmt);
+  n += json_emit_va(buf + n, len - n, fmt, ap);
+  va_end(ap);
+
+  n += json_emit(buf + n, len - n, "}}");
+
+  return n;
+}
+
+int mg_rpc_create_std_error(char *buf, int len, struct mg_rpc_request *req,
+                            int code) {
+  const char *message = NULL;
+
+  switch (code) {
+    case JSON_RPC_PARSE_ERROR:
+      message = "parse error";
+      break;
+    case JSON_RPC_INVALID_REQUEST_ERROR:
+      message = "invalid request";
+      break;
+    case JSON_RPC_METHOD_NOT_FOUND_ERROR:
+      message = "method not found";
+      break;
+    case JSON_RPC_INVALID_PARAMS_ERROR:
+      message = "invalid parameters";
+      break;
+    case JSON_RPC_SERVER_ERROR:
+      message = "server error";
+      break;
+    default:
+      message = "unspecified error";
+      break;
+  }
+
+  return mg_rpc_create_error(buf, len, req, code, message, "N");
+}
+
+int mg_rpc_dispatch(const char *buf, int len, char *dst, int dst_len,
+                    const char **methods, mg_rpc_handler_t *handlers) {
+  struct json_token tokens[200];
+  struct mg_rpc_request req;
+  int i, n;
+
+  memset(&req, 0, sizeof(req));
+  n = parse_json(buf, len, tokens, sizeof(tokens) / sizeof(tokens[0]));
+  if (n <= 0) {
+    int err_code = (n == JSON_STRING_INVALID) ? JSON_RPC_PARSE_ERROR
+                                              : JSON_RPC_SERVER_ERROR;
+    return mg_rpc_create_std_error(dst, dst_len, &req, err_code);
+  }
+
+  req.message = tokens;
+  req.id = find_json_token(tokens, "id");
+  req.method = find_json_token(tokens, "method");
+  req.params = find_json_token(tokens, "params");
+
+  if (req.id == NULL || req.method == NULL) {
+    return mg_rpc_create_std_error(dst, dst_len, &req,
+                                   JSON_RPC_INVALID_REQUEST_ERROR);
+  }
+
+  for (i = 0; methods[i] != NULL; i++) {
+    int mlen = strlen(methods[i]);
+    if (mlen == req.method->len &&
+        memcmp(methods[i], req.method->ptr, mlen) == 0)
+      break;
+  }
+
+  if (methods[i] == NULL) {
+    return mg_rpc_create_std_error(dst, dst_len, &req,
+                                   JSON_RPC_METHOD_NOT_FOUND_ERROR);
+  }
+
+  return handlers[i](dst, dst_len, &req);
+}
+
+int mg_rpc_parse_reply(const char *buf, int len, struct json_token *toks,
+                       int max_toks, struct mg_rpc_reply *rep,
+                       struct mg_rpc_error *er) {
+  int n = parse_json(buf, len, toks, max_toks);
+
+  memset(rep, 0, sizeof(*rep));
+  memset(er, 0, sizeof(*er));
+
+  if (n > 0) {
+    if ((rep->result = find_json_token(toks, "result")) != NULL) {
+      rep->message = toks;
+      rep->id = find_json_token(toks, "id");
+    } else {
+      er->message = toks;
+      er->id = find_json_token(toks, "id");
+      er->error_code = find_json_token(toks, "error.code");
+      er->error_message = find_json_token(toks, "error.message");
+      er->error_data = find_json_token(toks, "error.data");
+    }
+  }
+  return n;
+}
+
+#endif /* MG_DISABLE_JSON_RPC */
+#ifdef NS_MODULE_LINES
+#line 1 "src/mqtt.c"
+/**/
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#ifndef MG_DISABLE_MQTT
+
+/* Amalgamated: #include "internal.h" */
+
+static int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
+  uint8_t header;
+  int cmd;
+  size_t len = 0;
+  int var_len = 0;
+  char *vlen = &io->buf[1];
+
+  if (io->len < 2) return -1;
+
+  header = io->buf[0];
+  cmd = header >> 4;
+
+  /* decode mqtt variable length */
+  do {
+    len += (*vlen & 127) << 7 * (vlen - &io->buf[1]);
+  } while ((*vlen++ & 128) != 0 && ((size_t)(vlen - io->buf) <= io->len));
+
+  if (io->len < (size_t)(len - 1)) return -1;
+
+  mbuf_remove(io, 1 + (vlen - &io->buf[1]));
+  mm->cmd = cmd;
+  mm->qos = MG_MQTT_GET_QOS(header);
+
+  switch (cmd) {
+    case MG_MQTT_CMD_CONNECT:
+      /* TODO(mkm): parse keepalive and will */
+      break;
+    case MG_MQTT_CMD_CONNACK:
+      mm->connack_ret_code = io->buf[1];
+      var_len = 2;
+      break;
+    case MG_MQTT_CMD_PUBACK:
+    case MG_MQTT_CMD_PUBREC:
+    case MG_MQTT_CMD_PUBREL:
+    case MG_MQTT_CMD_PUBCOMP:
+    case MG_MQTT_CMD_SUBACK:
+      mm->message_id = ntohs(*(uint16_t *) io->buf);
+      var_len = 2;
+      break;
+    case MG_MQTT_CMD_PUBLISH: {
+      uint16_t topic_len = ntohs(*(uint16_t *) io->buf);
+      mm->topic = (char *) MG_MALLOC(topic_len + 1);
+      mm->topic[topic_len] = 0;
+      strncpy(mm->topic, io->buf + 2, topic_len);
+      var_len = topic_len + 2;
+
+      if (MG_MQTT_GET_QOS(header) > 0) {
+        mm->message_id = ntohs(*(uint16_t *) io->buf);
+        var_len += 2;
+      }
+    } break;
+    case MG_MQTT_CMD_SUBSCRIBE:
+      /*
+       * topic expressions are left in the payload and can be parsed with
+       * `mg_mqtt_next_subscribe_topic`
+       */
+      mm->message_id = ntohs(*(uint16_t *) io->buf);
+      var_len = 2;
+      break;
+    default:
+      printf("TODO: UNHANDLED COMMAND %d\n", cmd);
+      break;
+  }
+
+  mbuf_remove(io, var_len);
+  return len - var_len;
+}
+
+static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data) {
+  int len;
+  struct mbuf *io = &nc->recv_mbuf;
+  struct mg_mqtt_message mm;
+  memset(&mm, 0, sizeof(mm));
+
+  nc->handler(nc, ev, ev_data);
+
+  switch (ev) {
+    case MG_EV_RECV:
+      len = parse_mqtt(io, &mm);
+      if (len == -1) break; /* not fully buffered */
+      mm.payload.p = io->buf;
+      mm.payload.len = len;
+
+      nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm);
+
+      if (mm.topic) {
+        MG_FREE(mm.topic);
+      }
+      mbuf_remove(io, mm.payload.len);
+      break;
+  }
+}
+
+void mg_set_protocol_mqtt(struct mg_connection *nc) {
+  nc->proto_handler = mqtt_handler;
+}
+
+void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
+  static struct mg_send_mqtt_handshake_opts opts;
+  mg_send_mqtt_handshake_opt(nc, client_id, opts);
+}
+
+void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
+                                struct mg_send_mqtt_handshake_opts opts) {
+  uint8_t header = MG_MQTT_CMD_CONNECT << 4;
+  uint8_t rem_len;
+  uint16_t keep_alive;
+  uint16_t client_id_len;
+
+  /*
+   * 9: version_header(len, magic_string, version_number), 1: flags, 2:
+   * keep-alive timer,
+   * 2: client_identifier_len, n: client_id
+   */
+  rem_len = 9 + 1 + 2 + 2 + strlen(client_id);
+
+  mg_send(nc, &header, 1);
+  mg_send(nc, &rem_len, 1);
+  mg_send(nc, "\00\06MQIsdp\03", 9);
+  mg_send(nc, &opts.flags, 1);
+
+  if (opts.keep_alive == 0) {
+    opts.keep_alive = 60;
+  }
+  keep_alive = htons(opts.keep_alive);
+  mg_send(nc, &keep_alive, 2);
+
+  client_id_len = htons(strlen(client_id));
+  mg_send(nc, &client_id_len, 2);
+  mg_send(nc, client_id, strlen(client_id));
+}
+
+static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd,
+                                   uint8_t flags, size_t len) {
+  size_t off = nc->send_mbuf.len - len;
+  uint8_t header = cmd << 4 | (uint8_t) flags;
+
+  uint8_t buf[1 + sizeof(size_t)];
+  uint8_t *vlen = &buf[1];
+
+  assert(nc->send_mbuf.len >= len);
+
+  buf[0] = header;
+
+  /* mqtt variable length encoding */
+  do {
+    *vlen = len % 0x80;
+    len /= 0x80;
+    if (len > 0) *vlen |= 0x80;
+    vlen++;
+  } while (len > 0);
+
+  mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
+}
+
+void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
+                     uint16_t message_id, int flags, const void *data,
+                     size_t len) {
+  size_t old_len = nc->send_mbuf.len;
+
+  uint16_t topic_len = htons(strlen(topic));
+  uint16_t message_id_net = htons(message_id);
+
+  mg_send(nc, &topic_len, 2);
+  mg_send(nc, topic, strlen(topic));
+  if (MG_MQTT_GET_QOS(flags) > 0) {
+    mg_send(nc, &message_id_net, 2);
+  }
+  mg_send(nc, data, len);
+
+  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags,
+                         nc->send_mbuf.len - old_len);
+}
+
+void mg_mqtt_subscribe(struct mg_connection *nc,
+                       const struct mg_mqtt_topic_expression *topics,
+                       size_t topics_len, uint16_t message_id) {
+  size_t old_len = nc->send_mbuf.len;
+
+  uint16_t message_id_n = htons(message_id);
+  size_t i;
+
+  mg_send(nc, (char *) &message_id_n, 2);
+  for (i = 0; i < topics_len; i++) {
+    uint16_t topic_len_n = htons(strlen(topics[i].topic));
+    mg_send(nc, &topic_len_n, 2);
+    mg_send(nc, topics[i].topic, strlen(topics[i].topic));
+    mg_send(nc, &topics[i].qos, 1);
+  }
+
+  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1),
+                         nc->send_mbuf.len - old_len);
+}
+
+int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
+                                 struct mg_str *topic, uint8_t *qos, int pos) {
+  unsigned char *buf = (unsigned char *) msg->payload.p + pos;
+  if ((size_t) pos >= msg->payload.len) {
+    return -1;
+  }
+
+  topic->len = buf[0] << 8 | buf[1];
+  topic->p = (char *) buf + 2;
+  *qos = buf[2 + topic->len];
+  return pos + 2 + topic->len + 1;
+}
+
+void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
+                         size_t topics_len, uint16_t message_id) {
+  size_t old_len = nc->send_mbuf.len;
+
+  uint16_t message_id_n = htons(message_id);
+  size_t i;
+
+  mg_send(nc, (char *) &message_id_n, 2);
+  for (i = 0; i < topics_len; i++) {
+    uint16_t topic_len_n = htons(strlen(topics[i]));
+    mg_send(nc, &topic_len_n, 2);
+    mg_send(nc, topics[i], strlen(topics[i]));
+  }
+
+  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1),
+                         nc->send_mbuf.len - old_len);
+}
+
+void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
+  uint8_t unused = 0;
+  mg_send(nc, &unused, 1);
+  mg_send(nc, &return_code, 1);
+  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
+}
+
+/*
+ * Sends a command which contains only a `message_id` and a QoS level of 1.
+ *
+ * Helper function.
+ */
+static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
+                                       uint16_t message_id) {
+  uint16_t message_id_net = htons(message_id);
+  mg_send(nc, &message_id_net, 2);
+  mg_mqtt_prepend_header(nc, cmd, MG_MQTT_QOS(1), 2);
+}
+
+void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
+  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
+}
+
+void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
+  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
+}
+
+void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
+  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
+}
+
+void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
+  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
+}
+
+void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
+                    uint16_t message_id) {
+  size_t i;
+  uint16_t message_id_net = htons(message_id);
+  mg_send(nc, &message_id_net, 2);
+  for (i = 0; i < qoss_len; i++) {
+    mg_send(nc, &qoss[i], 1);
+  }
+  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
+}
+
+void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
+  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
+}
+
+void mg_mqtt_ping(struct mg_connection *nc) {
+  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
+}
+
+void mg_mqtt_pong(struct mg_connection *nc) {
+  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
+}
+
+void mg_mqtt_disconnect(struct mg_connection *nc) {
+  mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
+}
+
+#endif /* MG_DISABLE_MQTT */
+#ifdef NS_MODULE_LINES
+#line 1 "src/mqtt-broker.c"
+/**/
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/* Amalgamated: #include "internal.h" */
+
+#ifdef MG_ENABLE_MQTT_BROKER
+
+static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
+                                 struct mg_mqtt_session *s,
+                                 struct mg_connection *nc) {
+  s->brk = brk;
+  s->subscriptions = NULL;
+  s->num_subscriptions = 0;
+  s->nc = nc;
+}
+
+static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
+  s->next = s->brk->sessions;
+  s->brk->sessions = s;
+  s->prev = NULL;
+  if (s->next != NULL) s->next->prev = s;
+}
+
+static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
+  if (s->prev == NULL) s->brk->sessions = s->next;
+  if (s->prev) s->prev->next = s->next;
+  if (s->next) s->next->prev = s->prev;
+}
+
+static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
+  size_t i;
+  for (i = 0; i < s->num_subscriptions; i++) {
+    MG_FREE((void *) s->subscriptions[i].topic);
+  }
+  MG_FREE(s->subscriptions);
+  MG_FREE(s);
+}
+
+static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
+  mg_mqtt_remove_session(s);
+  mg_mqtt_destroy_session(s);
+}
+
+void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
+  brk->sessions = NULL;
+  brk->user_data = user_data;
+}
+
+static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
+                                          struct mg_connection *nc) {
+  struct mg_mqtt_session *s = (struct mg_mqtt_session *) malloc(sizeof *s);
+  if (s == NULL) {
+    /* LCOV_EXCL_START */
+    mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
+    return;
+    /* LCOV_EXCL_STOP */
+  }
+
+  /* TODO(mkm): check header (magic and version) */
+
+  mg_mqtt_session_init(brk, s, nc);
+  s->user_data = nc->user_data;
+  nc->user_data = s;
+  mg_mqtt_add_session(s);
+
+  mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
+}
+
+static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
+                                            struct mg_mqtt_message *msg) {
+  struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->user_data;
+  uint8_t qoss[512];
+  size_t qoss_len = 0;
+  struct mg_str topic;
+  uint8_t qos;
+  int pos;
+  struct mg_mqtt_topic_expression *te;
+
+  for (pos = 0;
+       (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
+    qoss[qoss_len++] = qos;
+  }
+
+  ss->subscriptions = (struct mg_mqtt_topic_expression *) realloc(
+      ss->subscriptions, sizeof(*ss->subscriptions) * qoss_len);
+  for (pos = 0;
+       (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
+       ss->num_subscriptions++) {
+    te = &ss->subscriptions[ss->num_subscriptions];
+    te->topic = (char *) malloc(topic.len + 1);
+    te->qos = qos;
+    strncpy((char *) te->topic, topic.p, topic.len + 1);
+  }
+
+  mg_mqtt_suback(nc, qoss, qoss_len, msg->message_id);
+}
+
+/*
+ * Matches a topic against a topic expression
+ *
+ * See http://goo.gl/iWk21X
+ *
+ * Returns 1 if it matches; 0 otherwise.
+ */
+static int mg_mqtt_match_topic_expression(const char *exp, const char *topic) {
+  /* TODO(mkm): implement real matching */
+  int len = strlen(exp);
+  if (strchr(exp, '#')) {
+    len -= 2;
+  }
+  return strncmp(exp, topic, len) == 0;
+}
+
+static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
+                                          struct mg_mqtt_message *msg) {
+  struct mg_mqtt_session *s;
+  size_t i;
+
+  for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
+    for (i = 0; i < s->num_subscriptions; i++) {
+      if (mg_mqtt_match_topic_expression(s->subscriptions[i].topic,
+                                         msg->topic)) {
+        mg_mqtt_publish(s->nc, msg->topic, 0, 0, msg->payload.p,
+                        msg->payload.len);
+        break;
+      }
+    }
+  }
+}
+
+void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
+  struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
+  struct mg_mqtt_broker *brk;
+
+  if (nc->listener) {
+    brk = (struct mg_mqtt_broker *) nc->listener->user_data;
+  } else {
+    brk = (struct mg_mqtt_broker *) nc->user_data;
+  }
+
+  switch (ev) {
+    case MG_EV_ACCEPT:
+      mg_set_protocol_mqtt(nc);
+      break;
+    case MG_EV_MQTT_CONNECT:
+      mg_mqtt_broker_handle_connect(brk, nc);
+      break;
+    case MG_EV_MQTT_SUBSCRIBE:
+      mg_mqtt_broker_handle_subscribe(nc, msg);
+      break;
+    case MG_EV_MQTT_PUBLISH:
+      mg_mqtt_broker_handle_publish(brk, msg);
+      break;
+    case MG_EV_CLOSE:
+      if (nc->listener) {
+        mg_mqtt_close_session((struct mg_mqtt_session *) nc->user_data);
+      }
+      break;
+  }
+}
+
+struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
+                                     struct mg_mqtt_session *s) {
+  return s == NULL ? brk->sessions : s->next;
+}
+
+#endif /* MG_ENABLE_MQTT_BROKER */
+#ifdef NS_MODULE_LINES
+#line 1 "src/dns.c"
+/**/
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#ifndef MG_DISABLE_DNS
+
+/* Amalgamated: #include "internal.h" */
+
+static int mg_dns_tid = 0xa0;
+
+struct mg_dns_header {
+  uint16_t transaction_id;
+  uint16_t flags;
+  uint16_t num_questions;
+  uint16_t num_answers;
+  uint16_t num_authority_prs;
+  uint16_t num_other_prs;
+};
+
+struct mg_dns_resource_record *mg_dns_next_record(
+    struct mg_dns_message *msg, int query,
+    struct mg_dns_resource_record *prev) {
+  struct mg_dns_resource_record *rr;
+
+  for (rr = (prev == NULL ? msg->answers : prev + 1);
+       rr - msg->answers < msg->num_answers; rr++) {
+    if (rr->rtype == query) {
+      return rr;
+    }
+  }
+  return NULL;
+}
+
+int mg_dns_parse_record_data(struct mg_dns_message *msg,
+                             struct mg_dns_resource_record *rr, void *data,
+                             size_t data_len) {
+  switch (rr->rtype) {
+    case MG_DNS_A_RECORD:
+      if (data_len < sizeof(struct in_addr)) {
+        return -1;
+      }
+      if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
+        return -1;
+      }
+      memcpy(data, rr->rdata.p, data_len);
+      return 0;
+#ifdef MG_ENABLE_IPV6
+    case MG_DNS_AAAA_RECORD:
+      if (data_len < sizeof(struct in6_addr)) {
+        return -1; /* LCOV_EXCL_LINE */
+      }
+      memcpy(data, rr->rdata.p, data_len);
+      return 0;
+#endif
+    case MG_DNS_CNAME_RECORD:
+      mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
+      return 0;
+  }
+
+  return -1;
+}
+
+int mg_dns_insert_header(struct mbuf *io, size_t pos,
+                         struct mg_dns_message *msg) {
+  struct mg_dns_header header;
+
+  memset(&header, 0, sizeof(header));
+  header.transaction_id = msg->transaction_id;
+  header.flags = htons(msg->flags);
+  header.num_questions = htons(msg->num_questions);
+  header.num_answers = htons(msg->num_answers);
+
+  return mbuf_insert(io, pos, &header, sizeof(header));
+}
+
+int mg_dns_copy_body(struct mbuf *io, struct mg_dns_message *msg) {
+  return mbuf_append(io, msg->pkt.p + sizeof(struct mg_dns_header),
+                     msg->pkt.len - sizeof(struct mg_dns_header));
+}
+
+static int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
+  const char *s;
+  unsigned char n;
+  size_t pos = io->len;
 
   do {
-    reset_per_request_attributes(conn);
-    conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
-                                     &conn->data_len);
-    assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
-    if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
-      send_http_error(conn, 413, "Request Too Large", "%s", "");
-      return;
-    } if (conn->request_len <= 0) {
-      return;  // Remote end closed the connection
+    if ((s = strchr(name, '.')) == NULL) {
+      s = name + len;
     }
-    conn->body = conn->next_request = conn->buf + conn->request_len;
 
-    if (parse_http_request(conn->buf, conn->buf_size, ri) <= 0 ||
-        !is_valid_uri(ri->uri)) {
-      // Do not put garbage in the access log, just send it back to the client
-      send_http_error(conn, 400, "Bad Request",
-          "Cannot parse HTTP request: [%.*s]", conn->data_len, conn->buf);
-      conn->must_close = 1;
-    } else if (strcmp(ri->http_version, "1.0") &&
-               strcmp(ri->http_version, "1.1")) {
-      // Request seems valid, but HTTP version is strange
-      send_http_error(conn, 505, "HTTP version not supported", "%s", "");
-      log_access(conn);
-    } else {
-      // Request is valid, handle it
-      cl = get_header(ri, "Content-Length");
-      conn->content_len = cl == NULL ? -1 : strtoll(cl, NULL, 10);
+    if (s - name > 127) {
+      return -1; /* TODO(mkm) cover */
+    }
+    n = s - name;           /* chunk length */
+    mbuf_append(io, &n, 1); /* send length */
+    mbuf_append(io, name, n);
 
-      // Set pointer to the next buffered request
-      buffered_len = conn->data_len - conn->request_len;
-      assert(buffered_len >= 0);
-      if (conn->content_len <= 0) {
-      } else if (conn->content_len < (int64_t) buffered_len) {
-        conn->next_request += conn->content_len;
-      } else {
-        conn->next_request += buffered_len;
+    if (*s == '.') {
+      n++;
+    }
+
+    name += n;
+    len -= n;
+  } while (*s != '\0');
+  mbuf_append(io, "\0", 1); /* Mark end of host name */
+
+  return io->len - pos;
+}
+
+int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
+                         const char *name, size_t nlen, const void *rdata,
+                         size_t rlen) {
+  size_t pos = io->len;
+  uint16_t u16;
+  uint32_t u32;
+
+  if (rr->kind == MG_DNS_INVALID_RECORD) {
+    return -1; /* LCOV_EXCL_LINE */
+  }
+
+  if (mg_dns_encode_name(io, name, nlen) == -1) {
+    return -1;
+  }
+
+  u16 = htons(rr->rtype);
+  mbuf_append(io, &u16, 2);
+  u16 = htons(rr->rclass);
+  mbuf_append(io, &u16, 2);
+
+  if (rr->kind == MG_DNS_ANSWER) {
+    u32 = htonl(rr->ttl);
+    mbuf_append(io, &u32, 4);
+
+    if (rr->rtype == MG_DNS_CNAME_RECORD) {
+      int clen;
+      /* fill size after encoding */
+      size_t off = io->len;
+      mbuf_append(io, &u16, 2);
+      if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
+        return -1;
       }
-
-      conn->birth_time = time(NULL);
-      handle_request(conn);
-      call_user(conn, MG_REQUEST_COMPLETE);
-      log_access(conn);
-    }
-    if (ri->remote_user != NULL) {
-      free((void *) ri->remote_user);
-    }
-
-    // Discard all buffered data for this request
-    assert(conn->next_request >= conn->buf);
-    assert(conn->data_len >= conn->next_request - conn->buf);
-    conn->data_len -= conn->next_request - conn->buf;
-    memmove(conn->buf, conn->next_request, (size_t) conn->data_len);
-  } while (conn->ctx->stop_flag == 0 &&
-           keep_alive_enabled &&
-           should_keep_alive(conn));
-}
-
-// Worker threads take accepted socket from the queue
-static int consume_socket(struct mg_context *ctx, struct socket *sp) {
-  (void) pthread_mutex_lock(&ctx->mutex);
-  DEBUG_TRACE(("going idle"));
-
-  // If the queue is empty, wait. We're idle at this point.
-  while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
-    pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
-  }
-
-  // If we're stopping, sq_head may be equal to sq_tail.
-  if (ctx->sq_head > ctx->sq_tail) {
-    // Copy socket from the queue and increment tail
-    *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
-    ctx->sq_tail++;
-    DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
-
-    // Wrap pointers if needed
-    while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
-      ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
-      ctx->sq_head -= ARRAY_SIZE(ctx->queue);
+      u16 = clen;
+      io->buf[off] = u16 >> 8;
+      io->buf[off + 1] = u16 & 0xff;
+    } else {
+      u16 = htons(rlen);
+      mbuf_append(io, &u16, 2);
+      mbuf_append(io, rdata, rlen);
     }
   }
 
-  (void) pthread_cond_signal(&ctx->sq_empty);
-  (void) pthread_mutex_unlock(&ctx->mutex);
-
-  return !ctx->stop_flag;
+  return io->len - pos;
 }
 
-static void worker_thread(struct mg_context *ctx) {
-  struct mg_connection *conn;
-  int buf_size = atoi(ctx->config[MAX_REQUEST_SIZE]);
+void mg_send_dns_query(struct mg_connection *nc, const char *name,
+                       int query_type) {
+  struct mg_dns_message *msg =
+      (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
+  struct mbuf pkt;
+  struct mg_dns_resource_record *rr = &msg->questions[0];
 
-  conn = (struct mg_connection *) calloc(1, sizeof(*conn) + buf_size);
-  if (conn == NULL) {
-    cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
-  } else {
-    conn->buf_size = buf_size;
-    conn->buf = (char *) (conn + 1);
+  DBG(("%s %d", name, query_type));
 
-    // Call consume_socket() even when ctx->stop_flag > 0, to let it signal
-    // sq_empty condvar to wake up the master waiting in produce_socket()
-    while (consume_socket(ctx, &conn->client)) {
-      conn->birth_time = time(NULL);
-      conn->ctx = ctx;
+  mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
 
-      // Fill in IP, port info early so even if SSL setup below fails,
-      // error handler would have the corresponding info.
-      // Thanks to Johannes Winkelmann for the patch.
-      // TODO(lsm): Fix IPv6 case
-      conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
-      memcpy(&conn->request_info.remote_ip,
-             &conn->client.rsa.sin.sin_addr.s_addr, 4);
-      conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
-      conn->request_info.is_ssl = conn->client.is_ssl;
+  msg->transaction_id = ++mg_dns_tid;
+  msg->flags = 0x100;
+  msg->num_questions = 1;
 
-      if (!conn->client.is_ssl ||
-          (conn->client.is_ssl &&
-           sslize(conn, conn->ctx->ssl_ctx, SSL_accept))) {
-        process_new_connection(conn);
+  mg_dns_insert_header(&pkt, 0, msg);
+
+  rr->rtype = query_type;
+  rr->rclass = 1; /* Class: inet */
+  rr->kind = MG_DNS_QUESTION;
+
+  if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
+    /* TODO(mkm): return an error code */
+    goto cleanup; /* LCOV_EXCL_LINE */
+  }
+
+  /* TCP DNS requires messages to be prefixed with len */
+  if (!(nc->flags & MG_F_UDP)) {
+    uint16_t len = htons(pkt.len);
+    mbuf_insert(&pkt, 0, &len, 2);
+  }
+
+  mg_send(nc, pkt.buf, pkt.len);
+  mbuf_free(&pkt);
+
+cleanup:
+  MG_FREE(msg);
+}
+
+static unsigned char *mg_parse_dns_resource_record(
+    unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
+    int reply) {
+  unsigned char *name = data;
+  int chunk_len, data_len;
+
+  while (data < end && (chunk_len = *data)) {
+    if (((unsigned char *) data)[0] & 0xc0) {
+      data += 1;
+      break;
+    }
+    data += chunk_len + 1;
+  }
+
+  rr->name.p = (char *) name;
+  rr->name.len = data - name + 1;
+
+  data++;
+  if (data > end - 4) {
+    return data;
+  }
+
+  rr->rtype = data[0] << 8 | data[1];
+  data += 2;
+
+  rr->rclass = data[0] << 8 | data[1];
+  data += 2;
+
+  rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
+  if (reply) {
+    if (data >= end - 6) {
+      return data;
+    }
+
+    rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
+              data[2] << 8 | data[3];
+    data += 4;
+
+    data_len = *data << 8 | *(data + 1);
+    data += 2;
+
+    rr->rdata.p = (char *) data;
+    rr->rdata.len = data_len;
+    data += data_len;
+  }
+  return data;
+}
+
+int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
+  struct mg_dns_header *header = (struct mg_dns_header *) buf;
+  unsigned char *data = (unsigned char *) buf + sizeof(*header);
+  unsigned char *end = (unsigned char *) buf + len;
+  int i;
+  msg->pkt.p = buf;
+  msg->pkt.len = len;
+
+  if (len < (int) sizeof(*header)) {
+    return -1; /* LCOV_EXCL_LINE */
+  }
+
+  msg->transaction_id = header->transaction_id;
+  msg->flags = ntohs(header->flags);
+  msg->num_questions = ntohs(header->num_questions);
+  msg->num_answers = ntohs(header->num_answers);
+
+  for (i = 0; i < msg->num_questions && i < (int) ARRAY_SIZE(msg->questions);
+       i++) {
+    data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
+  }
+
+  for (i = 0; i < msg->num_answers && i < (int) ARRAY_SIZE(msg->answers); i++) {
+    data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
+  }
+
+  return 0;
+}
+
+size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
+                              char *dst, int dst_len) {
+  int chunk_len;
+  char *old_dst = dst;
+  const unsigned char *data = (unsigned char *) name->p;
+  const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
+
+  if (data >= end) {
+    return 0;
+  }
+
+  while ((chunk_len = *data++)) {
+    int leeway = dst_len - (dst - old_dst);
+    if (data >= end) {
+      return 0;
+    }
+
+    if (chunk_len & 0xc0) {
+      uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
+      if (off >= msg->pkt.len) {
+        return 0;
       }
-
-      close_connection(conn);
+      data = (unsigned char *) msg->pkt.p + off;
+      continue;
     }
-    free(conn);
-  }
-
-  // Signal master that we're done with connection and exiting
-  (void) pthread_mutex_lock(&ctx->mutex);
-  ctx->num_threads--;
-  (void) pthread_cond_signal(&ctx->cond);
-  assert(ctx->num_threads >= 0);
-  (void) pthread_mutex_unlock(&ctx->mutex);
-
-  DEBUG_TRACE(("exiting"));
-}
-
-// Master thread adds accepted socket to a queue
-static void produce_socket(struct mg_context *ctx, const struct socket *sp) {
-  (void) pthread_mutex_lock(&ctx->mutex);
-
-  // If the queue is full, wait
-  while (ctx->stop_flag == 0 &&
-         ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
-    (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
-  }
-
-  if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
-    // Copy socket to the queue and increment head
-    ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
-    ctx->sq_head++;
-    DEBUG_TRACE(("queued socket %d", sp->sock));
-  }
-
-  (void) pthread_cond_signal(&ctx->sq_full);
-  (void) pthread_mutex_unlock(&ctx->mutex);
-}
-
-static void accept_new_connection(const struct socket *listener,
-                                  struct mg_context *ctx) {
-  struct socket accepted;
-  char src_addr[20];
-  socklen_t len;
-  int allowed;
-
-  len = sizeof(accepted.rsa);
-  accepted.lsa = listener->lsa;
-  accepted.sock = accept(listener->sock, &accepted.rsa.sa, &len);
-  if (accepted.sock != INVALID_SOCKET) {
-    allowed = check_acl(ctx, &accepted.rsa);
-    if (allowed) {
-      // Put accepted socket structure into the queue
-      DEBUG_TRACE(("accepted socket %d", accepted.sock));
-      accepted.is_ssl = listener->is_ssl;
-      produce_socket(ctx, &accepted);
-    } else {
-      sockaddr_to_string(src_addr, sizeof(src_addr), &accepted.rsa);
-      cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
-      (void) closesocket(accepted.sock);
-    }
-  }
-}
-
-static void master_thread(struct mg_context *ctx) {
-  fd_set read_set;
-  struct timeval tv;
-  struct socket *sp;
-  int max_fd;
-
-  // Increase priority of the master thread
-#if defined(_WIN32)
-  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
-#endif
-
-#if defined(ISSUE_317)
-  struct sched_param sched_param;
-  sched_param.sched_priority = sched_get_priority_max(SCHED_RR);
-  pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
-#endif
-
-  while (ctx->stop_flag == 0) {
-    FD_ZERO(&read_set);
-    max_fd = -1;
-
-    // Add listening sockets to the read set
-    for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
-      add_to_set(sp->sock, &read_set, &max_fd);
+    if (chunk_len > leeway) {
+      chunk_len = leeway;
     }
 
-    tv.tv_sec = 0;
-    tv.tv_usec = 200 * 1000;
+    if (data + chunk_len >= end) {
+      return 0;
+    }
 
-    if (select(max_fd + 1, &read_set, NULL, NULL, &tv) < 0) {
-#ifdef _WIN32
-      // On windows, if read_set and write_set are empty,
-      // select() returns "Invalid parameter" error
-      // (at least on my Windows XP Pro). So in this case, we sleep here.
-      mg_sleep(1000);
-#endif // _WIN32
-    } else {
-      for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
-        if (ctx->stop_flag == 0 && FD_ISSET(sp->sock, &read_set)) {
-          accept_new_connection(sp, ctx);
+    memcpy(dst, data, chunk_len);
+    data += chunk_len;
+    dst += chunk_len;
+    leeway -= chunk_len;
+    if (leeway == 0) {
+      return dst - old_dst;
+    }
+    *dst++ = '.';
+  }
+
+  if (dst != old_dst) {
+    *--dst = 0;
+  }
+  return dst - old_dst;
+}
+
+static void dns_handler(struct mg_connection *nc, int ev, void *ev_data) {
+  struct mbuf *io = &nc->recv_mbuf;
+  struct mg_dns_message msg;
+
+  /* Pass low-level events to the user handler */
+  nc->handler(nc, ev, ev_data);
+
+  switch (ev) {
+    case MG_EV_RECV:
+      if (!(nc->flags & MG_F_UDP)) {
+        mbuf_remove(&nc->recv_mbuf, 2);
+      }
+      if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
+        /* reply + recursion allowed + format error */
+        memset(&msg, 0, sizeof(msg));
+        msg.flags = 0x8081;
+        mg_dns_insert_header(io, 0, &msg);
+        if (!(nc->flags & MG_F_UDP)) {
+          uint16_t len = htons(io->len);
+          mbuf_insert(io, 0, &len, 2);
         }
+        mg_send(nc, io->buf, io->len);
+      } else {
+        /* Call user handler with parsed message */
+        nc->handler(nc, MG_DNS_MESSAGE, &msg);
+      }
+      mbuf_remove(io, io->len);
+      break;
+  }
+}
+
+void mg_set_protocol_dns(struct mg_connection *nc) {
+  nc->proto_handler = dns_handler;
+}
+
+#endif /* MG_DISABLE_DNS */
+#ifdef NS_MODULE_LINES
+#line 1 "src/dns-server.c"
+/**/
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#ifdef MG_ENABLE_DNS_SERVER
+
+/* Amalgamated: #include "internal.h" */
+
+struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
+                                        struct mg_dns_message *msg) {
+  struct mg_dns_reply rep;
+  rep.msg = msg;
+  rep.io = io;
+  rep.start = io->len;
+
+  /* reply + recursion allowed */
+  msg->flags |= 0x8080;
+  mg_dns_copy_body(io, msg);
+
+  msg->num_answers = 0;
+  return rep;
+}
+
+void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
+  size_t sent = r->io->len - r->start;
+  mg_dns_insert_header(r->io, r->start, r->msg);
+  if (!(nc->flags & MG_F_UDP)) {
+    uint16_t len = htons(sent);
+    mbuf_insert(r->io, r->start, &len, 2);
+  }
+
+  if (&nc->send_mbuf != r->io) {
+    mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
+    r->io->len = r->start;
+  }
+}
+
+int mg_dns_reply_record(struct mg_dns_reply *reply,
+                        struct mg_dns_resource_record *question,
+                        const char *name, int rtype, int ttl, const void *rdata,
+                        size_t rdata_len) {
+  struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
+  char rname[512];
+  struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
+  if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
+    return -1; /* LCOV_EXCL_LINE */
+  }
+
+  if (name == NULL) {
+    name = rname;
+    rname[511] = 0;
+    mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
+  }
+
+  *ans = *question;
+  ans->kind = MG_DNS_ANSWER;
+  ans->rtype = rtype;
+  ans->ttl = ttl;
+
+  if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
+                           rdata_len) == -1) {
+    return -1; /* LCOV_EXCL_LINE */
+  };
+
+  msg->num_answers++;
+  return 0;
+}
+
+#endif /* MG_ENABLE_DNS_SERVER */
+#ifdef NS_MODULE_LINES
+#line 1 "src/resolv.c"
+/**/
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#ifndef MG_DISABLE_RESOLVER
+
+/* Amalgamated: #include "internal.h" */
+
+#ifndef MG_DEFAULT_NAMESERVER
+#define MG_DEFAULT_NAMESERVER "8.8.8.8"
+#endif
+
+static const char *mg_default_dns_server = "udp://" MG_DEFAULT_NAMESERVER ":53";
+
+MG_INTERNAL char mg_dns_server[256];
+
+struct mg_resolve_async_request {
+  char name[1024];
+  int query;
+  mg_resolve_callback_t callback;
+  void *data;
+  time_t timeout;
+  int max_retries;
+
+  /* state */
+  time_t last_time;
+  int retries;
+};
+
+/*
+ * Find what nameserver to use.
+ *
+ * Return 0 if OK, -1 if error
+ */
+static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
+  int ret = -1;
+
+#ifdef _WIN32
+  int i;
+  LONG err;
+  HKEY hKey, hSub;
+  char subkey[512], value[128],
+      *key = "SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
+
+  if ((err = RegOpenKey(HKEY_LOCAL_MACHINE, key, &hKey)) != ERROR_SUCCESS) {
+    fprintf(stderr, "cannot open reg key %s: %d\n", key, err);
+    ret = -1;
+  } else {
+    for (ret = -1, i = 0;
+         RegEnumKey(hKey, i, subkey, sizeof(subkey)) == ERROR_SUCCESS; i++) {
+      DWORD type, len = sizeof(value);
+      if (RegOpenKey(hKey, subkey, &hSub) == ERROR_SUCCESS &&
+          (RegQueryValueEx(hSub, "NameServer", 0, &type, (void *) value,
+                           &len) == ERROR_SUCCESS ||
+           RegQueryValueEx(hSub, "DhcpNameServer", 0, &type, (void *) value,
+                           &len) == ERROR_SUCCESS)) {
+        /*
+         * See https://github.com/cesanta/mongoose/issues/176
+         * The value taken from the registry can be empty, a single
+         * IP address, or multiple IP addresses separated by comma.
+         * If it's empty, check the next interface.
+         * If it's multiple IP addresses, take the first one.
+         */
+        char *comma = strchr(value, ',');
+        if (value[0] == '\0') {
+          continue;
+        }
+        if (comma != NULL) {
+          *comma = '\0';
+        }
+        snprintf(name, name_len, "udp://%s:53", value);
+        ret = 0;
+        RegCloseKey(hSub);
+        break;
+      }
+    }
+    RegCloseKey(hKey);
+  }
+#elif !defined(MG_DISABLE_FILESYSTEM)
+  FILE *fp;
+  char line[512];
+
+  if ((fp = fopen("/etc/resolv.conf", "r")) == NULL) {
+    ret = -1;
+  } else {
+    /* Try to figure out what nameserver to use */
+    for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
+      char buf[256];
+      if (sscanf(line, "nameserver %255[^\n\t #]s", buf) == 1) {
+        snprintf(name, name_len, "udp://%s:53", buf);
+        ret = 0;
+        break;
+      }
+    }
+    (void) fclose(fp);
+  }
+#else
+  snprintf(name, name_len, "%s", mg_default_dns_server);
+#endif /* _WIN32 */
+
+  return ret;
+}
+
+int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
+#ifndef MG_DISABLE_FILESYSTEM
+  /* TODO(mkm) cache /etc/hosts */
+  FILE *fp;
+  char line[1024];
+  char *p;
+  char alias[256];
+  unsigned int a, b, c, d;
+  int len = 0;
+
+  if ((fp = fopen("/etc/hosts", "r")) == NULL) {
+    return -1;
+  }
+
+  for (; fgets(line, sizeof(line), fp) != NULL;) {
+    if (line[0] == '#') continue;
+
+    if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
+      /* TODO(mkm): handle ipv6 */
+      continue;
+    }
+    for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
+      if (strcmp(alias, name) == 0) {
+        usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
+        fclose(fp);
+        return 0;
       }
     }
   }
-  DEBUG_TRACE(("stopping workers"));
 
-  // Stop signal received: somebody called mg_stop. Quit.
-  close_all_listening_sockets(ctx);
-
-  // Wakeup workers that are waiting for connections to handle.
-  pthread_cond_broadcast(&ctx->sq_full);
-
-  // Wait until all threads finish
-  (void) pthread_mutex_lock(&ctx->mutex);
-  while (ctx->num_threads > 0) {
-    (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
-  }
-  (void) pthread_mutex_unlock(&ctx->mutex);
-
-  // All threads exited, no sync is needed. Destroy mutex and condvars
-  (void) pthread_mutex_destroy(&ctx->mutex);
-  (void) pthread_cond_destroy(&ctx->cond);
-  (void) pthread_cond_destroy(&ctx->sq_empty);
-  (void) pthread_cond_destroy(&ctx->sq_full);
-
-#if !defined(NO_SSL)
-  uninitialize_ssl(ctx);
+  fclose(fp);
 #endif
-  DEBUG_TRACE(("exiting"));
 
-  // Signal mg_stop() that we're done.
-  // WARNING: This must be the very last thing this
-  // thread does, as ctx becomes invalid after this line.
-  ctx->stop_flag = 2;
+  return -1;
 }
 
-static void free_context(struct mg_context *ctx) {
-  int i;
+static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data) {
+  time_t now = time(NULL);
+  struct mg_resolve_async_request *req;
+  struct mg_dns_message *msg;
 
-  // Deallocate config parameters
-  for (i = 0; i < NUM_OPTIONS; i++) {
-    if (ctx->config[i] != NULL)
-      free(ctx->config[i]);
-  }
+  DBG(("ev=%d", ev));
 
-  // Deallocate SSL context
-  if (ctx->ssl_ctx != NULL) {
-    SSL_CTX_free(ctx->ssl_ctx);
-  }
-  if (ctx->client_ssl_ctx != NULL) {
-    SSL_CTX_free(ctx->client_ssl_ctx);
-  }
-#ifndef NO_SSL
-  if (ssl_mutexes != NULL) {
-    free(ssl_mutexes);
-  }
-#endif // !NO_SSL
+  req = (struct mg_resolve_async_request *) nc->user_data;
 
-  // Deallocate context itself
-  free(ctx);
+  switch (ev) {
+    case MG_EV_CONNECT:
+    case MG_EV_POLL:
+      if (req->retries > req->max_retries) {
+        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
+        break;
+      }
+      if (now - req->last_time >= req->timeout) {
+        mg_send_dns_query(nc, req->name, req->query);
+        req->last_time = now;
+        req->retries++;
+      }
+      break;
+    case MG_EV_RECV:
+      msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
+      if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
+          msg->num_answers > 0) {
+        req->callback(msg, req->data);
+        nc->user_data = NULL;
+        MG_FREE(req);
+      }
+      MG_FREE(msg);
+      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
+      break;
+    case MG_EV_SEND:
+      /*
+       * If a send error occurs, prevent closing of the connection by the core.
+       * We will retry after timeout.
+       */
+      nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
+      mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
+      break;
+    case MG_EV_CLOSE:
+      /* If we got here with request still not done, fire an error callback. */
+      if (req != NULL) {
+        req->callback(NULL, req->data);
+        nc->user_data = NULL;
+        MG_FREE(req);
+      }
+      break;
+  }
 }
 
-void mg_stop(struct mg_context *ctx) {
-  ctx->stop_flag = 1;
-
-  // Wait until mg_fini() stops
-  while (ctx->stop_flag != 2) {
-    (void) mg_sleep(10);
-  }
-  free_context(ctx);
-
-#if defined(_WIN32) && !defined(__SYMBIAN32__)
-  (void) WSACleanup();
-#endif // _WIN32
+int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
+                     mg_resolve_callback_t cb, void *data) {
+  struct mg_resolve_async_opts opts;
+  memset(&opts, 0, sizeof(opts));
+  return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
 }
 
-struct mg_context *mg_start(mg_callback_t user_callback, void *user_data,
-                            const char **options) {
-  struct mg_context *ctx;
-  const char *name, *value, *default_value;
-  int i;
+int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
+                         mg_resolve_callback_t cb, void *data,
+                         struct mg_resolve_async_opts opts) {
+  struct mg_resolve_async_request *req;
+  struct mg_connection *dns_nc;
+  const char *nameserver = opts.nameserver_url;
 
-#if defined(_WIN32) && !defined(__SYMBIAN32__)
-  WSADATA data;
-  WSAStartup(MAKEWORD(2,2), &data);
-  InitializeCriticalSection(&global_log_file_lock);
-#endif // _WIN32
+  DBG(("%s %d", name, query));
 
-  // Allocate context and initialize reasonable general case defaults.
-  // TODO(lsm): do proper error handling here.
-  if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
-    return NULL;
-  }
-  ctx->user_callback = user_callback;
-  ctx->user_data = user_data;
-
-  while (options && (name = *options++) != NULL) {
-    if ((i = get_option_index(name)) == -1) {
-      cry(fc(ctx), "Invalid option: %s", name);
-      free_context(ctx);
-      return NULL;
-    } else if ((value = *options++) == NULL) {
-      cry(fc(ctx), "%s: option value cannot be NULL", name);
-      free_context(ctx);
-      return NULL;
-    }
-    if (ctx->config[i] != NULL) {
-      cry(fc(ctx), "warning: %s: duplicate option", name);
-    }
-    ctx->config[i] = mg_strdup(value);
-    DEBUG_TRACE(("[%s] -> [%s]", name, value));
+  /* resolve with DNS */
+  req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
+  if (req == NULL) {
+    return -1;
   }
 
-  // Set default value if needed
-  for (i = 0; config_options[i * ENTRIES_PER_CONFIG_OPTION] != NULL; i++) {
-    default_value = config_options[i * ENTRIES_PER_CONFIG_OPTION + 2];
-    if (ctx->config[i] == NULL && default_value != NULL) {
-      ctx->config[i] = mg_strdup(default_value);
-      DEBUG_TRACE(("Setting default: [%s] -> [%s]",
-                   config_options[i * ENTRIES_PER_CONFIG_OPTION + 1],
-                   default_value));
-    }
+  strncpy(req->name, name, sizeof(req->name));
+  req->query = query;
+  req->callback = cb;
+  req->data = data;
+  /* TODO(mkm): parse defaults out of resolve.conf */
+  req->max_retries = opts.max_retries ? opts.max_retries : 2;
+  req->timeout = opts.timeout ? opts.timeout : 5;
+
+  /* Lazily initialize dns server */
+  if (nameserver == NULL && mg_dns_server[0] == '\0' &&
+      mg_get_ip_address_of_nameserver(mg_dns_server, sizeof(mg_dns_server)) ==
+          -1) {
+    strncpy(mg_dns_server, mg_default_dns_server, sizeof(mg_dns_server));
   }
 
-  // NOTE(lsm): order is important here. SSL certificates must
-  // be initialized before listening ports. UID must be set last.
-  if (!set_gpass_option(ctx) ||
-#if !defined(NO_SSL)
-      !set_ssl_option(ctx) ||
+  if (nameserver == NULL) {
+    nameserver = mg_dns_server;
+  }
+
+  dns_nc = mg_connect(mgr, nameserver, mg_resolve_async_eh);
+  if (dns_nc == NULL) {
+    free(req);
+    return -1;
+  }
+  dns_nc->user_data = req;
+
+  return 0;
+}
+
+#endif /* MG_DISABLE_RESOLVE */
+#ifdef NS_MODULE_LINES
+#line 1 "src/coap.c"
+/**/
 #endif
-      !set_ports_option(ctx) ||
-#if !defined(_WIN32)
-      !set_uid_option(ctx) ||
-#endif
-      !set_acl_option(ctx)) {
-    free_context(ctx);
-    return NULL;
+/*
+ * Copyright (c) 2015 Cesanta Software Limited
+ * All rights reserved
+ * This software is dual-licensed: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. For the terms of this
+ * license, see .
+ *
+ * You are free to use this software under the terms of the GNU General
+ * Public License, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the GNU General Public License for more details.
+ *
+ * Alternatively, you can license this software under a commercial
+ * license, as set out in .
+ */
+
+/* Amalgamated: #include "internal.h" */
+
+#ifdef MG_ENABLE_COAP
+
+void mg_coap_free_options(struct mg_coap_message *cm) {
+  while (cm->options != NULL) {
+    struct mg_coap_option *next = cm->options->next;
+    MG_FREE(cm->options);
+    cm->options = next;
   }
+}
 
-#if !defined(_WIN32) && !defined(__SYMBIAN32__)
-  // Ignore SIGPIPE signal, so if browser cancels the request, it
-  // won't kill the whole process.
-  (void) signal(SIGPIPE, SIG_IGN);
-  // Also ignoring SIGCHLD to let the OS to reap zombies properly.
-  (void) signal(SIGCHLD, SIG_IGN);
-#endif // !_WIN32
+struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
+                                          uint32_t number, char *value,
+                                          size_t len) {
+  struct mg_coap_option *new_option =
+      (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
 
-  (void) pthread_mutex_init(&ctx->mutex, NULL);
-  (void) pthread_cond_init(&ctx->cond, NULL);
-  (void) pthread_cond_init(&ctx->sq_empty, NULL);
-  (void) pthread_cond_init(&ctx->sq_full, NULL);
+  new_option->number = number;
+  new_option->value.p = value;
+  new_option->value.len = len;
 
-  // Start master (listening) thread
-  mg_start_thread((mg_thread_func_t) master_thread, ctx);
-
-  // Start worker threads
-  for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) {
-    if (mg_start_thread((mg_thread_func_t) worker_thread, ctx) != 0) {
-      cry(fc(ctx), "Cannot start worker thread: %d", ERRNO);
+  if (cm->options == NULL) {
+    cm->options = cm->optiomg_tail = new_option;
+  } else {
+    /*
+     * A very simple attention to help clients to compose options:
+     * CoAP wants to see options ASC ordered.
+     * Could be change by using sort in coap_compose
+     */
+    if (cm->optiomg_tail->number <= new_option->number) {
+      /* if option is already ordered just add it */
+      cm->optiomg_tail = cm->optiomg_tail->next = new_option;
     } else {
-      ctx->num_threads++;
+      /* looking for appropriate position */
+      struct mg_coap_option *current_opt = cm->options;
+      struct mg_coap_option *prev_opt = 0;
+
+      while (current_opt != NULL) {
+        if (current_opt->number > new_option->number) {
+          break;
+        }
+        prev_opt = current_opt;
+        current_opt = current_opt->next;
+      }
+
+      if (prev_opt != NULL) {
+        prev_opt->next = new_option;
+        new_option->next = current_opt;
+      } else {
+        /* insert new_option to the beginning */
+        new_option->next = cm->options;
+        cm->options = new_option;
+      }
     }
   }
 
-  return ctx;
+  return new_option;
 }
+
+/*
+ * Fills CoAP header in mg_coap_message.
+ *
+ * Helper function.
+ */
+static char *coap_parse_header(char *ptr, struct mbuf *io,
+                               struct mg_coap_message *cm) {
+  if (io->len < sizeof(uint32_t)) {
+    cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
+    return NULL;
+  }
+
+  /*
+   * Version (Ver):  2-bit unsigned integer.  Indicates the CoAP version
+   * number.  Implementations of this specification MUST set this field
+   * to 1 (01 binary).  Other values are reserved for future versions.
+   * Messages with unknown version numbers MUST be silently ignored.
+   */
+  if (((uint8_t) *ptr >> 6) != 1) {
+    cm->flags |= MG_COAP_IGNORE;
+    return NULL;
+  }
+
+  /*
+   * Type (T):  2-bit unsigned integer.  Indicates if this message is of
+   * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
+   * Reset (3).
+   */
+  cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
+  cm->flags |= MG_COAP_MSG_TYPE_FIELD;
+
+  /*
+   * Token Length (TKL):  4-bit unsigned integer.  Indicates the length of
+   * the variable-length Token field (0-8 bytes).  Lengths 9-15 are
+   * reserved, MUST NOT be sent, and MUST be processed as a message
+   * format error.
+   */
+  cm->token.len = *ptr & 0x0F;
+  if (cm->token.len > 8) {
+    cm->flags |= MG_COAP_FORMAT_ERROR;
+    return NULL;
+  }
+
+  ptr++;
+
+  /*
+   * Code:  8-bit unsigned integer, split into a 3-bit class (most
+   * significant bits) and a 5-bit detail (least significant bits)
+   */
+  cm->code_class = (uint8_t) *ptr >> 5;
+  cm->code_detail = *ptr & 0x1F;
+  cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
+
+  ptr++;
+
+  /* Message ID:  16-bit unsigned integer in network byte order. */
+  cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
+  cm->flags |= MG_COAP_MSG_ID_FIELD;
+
+  ptr += 2;
+
+  return ptr;
+}
+
+/*
+ * Fills token information in mg_coap_message.
+ *
+ * Helper function.
+ */
+static char *coap_get_token(char *ptr, struct mbuf *io,
+                            struct mg_coap_message *cm) {
+  if (cm->token.len != 0) {
+    if (ptr + cm->token.len > io->buf + io->len) {
+      cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
+      return NULL;
+    } else {
+      cm->token.p = ptr;
+      ptr += cm->token.len;
+      cm->flags |= MG_COAP_TOKEN_FIELD;
+    }
+  }
+
+  return ptr;
+}
+
+/*
+ * Returns Option Delta or Length.
+ *
+ * Helper function.
+ */
+static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
+  int ret = 0;
+
+  if (*opt_info == 13) {
+    /*
+     * 13:  An 8-bit unsigned integer follows the initial byte and
+     * indicates the Option Delta/Length minus 13.
+     */
+    if (ptr < io->buf + io->len) {
+      *opt_info = (uint8_t) *ptr + 13;
+      ret = sizeof(uint8_t);
+    } else {
+      ret = -1; /* LCOV_EXCL_LINE */
+    }
+  } else if (*opt_info == 14) {
+    /*
+     * 14:  A 16-bit unsigned integer in network byte order follows the
+     * initial byte and indicates the Option Delta/Length minus 269.
+     */
+    if (ptr + sizeof(uint8_t) < io->buf + io->len) {
+      *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
+      ret = sizeof(uint16_t);
+    } else {
+      ret = -1; /* LCOV_EXCL_LINE */
+    }
+  }
+
+  return ret;
+}
+
+/*
+ * Fills options in mg_coap_message.
+ *
+ * Helper function.
+ *
+ * General options format:
+ * +---------------+---------------+
+ * | Option Delta  | Option Length |  1 byte
+ * +---------------+---------------+
+ * \    Option Delta (extended)    \  0-2 bytes
+ * +-------------------------------+
+ * / Option Length  (extended)     \  0-2 bytes
+ * +-------------------------------+
+ * \         Option Value          \  0 or more bytes
+ * +-------------------------------+
+ */
+static char *coap_get_options(char *ptr, struct mbuf *io,
+                              struct mg_coap_message *cm) {
+  uint16_t prev_opt = 0;
+
+  if (ptr == io->buf + io->len) {
+    /* end of packet, ok */
+    return NULL;
+  }
+
+  /* 0xFF is payload marker */
+  while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
+    uint16_t option_delta, option_lenght;
+    int optinfo_len;
+
+    /* Option Delta:  4-bit unsigned integer */
+    option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
+    /* Option Length:  4-bit unsigned integer */
+    option_lenght = *ptr & 0x0F;
+
+    if (option_delta == 15 || option_lenght == 15) {
+      /*
+       * 15:  Reserved for future use.  If the field is set to this value,
+       * it MUST be processed as a message format error
+       */
+      cm->flags |= MG_COAP_FORMAT_ERROR;
+      break;
+    }
+
+    ptr++;
+
+    /* check for extended option delta */
+    optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
+    if (optinfo_len == -1) {
+      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
+      break;                                /* LCOV_EXCL_LINE */
+    }
+
+    ptr += optinfo_len;
+
+    /* check or extended option lenght */
+    optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
+    if (optinfo_len == -1) {
+      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
+      break;                                /* LCOV_EXCL_LINE */
+    }
+
+    ptr += optinfo_len;
+
+    /*
+     * Instead of specifying the Option Number directly, the instances MUST
+     * appear in order of their Option Numbers and a delta encoding is used
+     * between them.
+     */
+    option_delta += prev_opt;
+
+    mg_coap_add_option(cm, option_delta, ptr, option_lenght);
+
+    prev_opt = option_delta;
+
+    if (ptr + option_lenght > io->buf + io->len) {
+      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
+      break;                                /* LCOV_EXCL_LINE */
+    }
+
+    ptr += option_lenght;
+  }
+
+  if ((cm->flags & MG_COAP_ERROR) != 0) {
+    mg_coap_free_options(cm);
+    return NULL;
+  }
+
+  cm->flags |= MG_COAP_OPTIOMG_FIELD;
+
+  if (ptr == io->buf + io->len) {
+    /* end of packet, ok */
+    return NULL;
+  }
+
+  ptr++;
+
+  return ptr;
+}
+
+uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
+  char *ptr;
+
+  memset(cm, 0, sizeof(*cm));
+
+  if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
+    return cm->flags;
+  }
+
+  if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
+    return cm->flags;
+  }
+
+  if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
+    return cm->flags;
+  }
+
+  /* the rest is payload */
+  cm->payload.len = io->len - (ptr - io->buf);
+  if (cm->payload.len != 0) {
+    cm->payload.p = ptr;
+    cm->flags |= MG_COAP_PAYLOAD_FIELD;
+  }
+
+  return cm->flags;
+}
+
+/*
+ * Calculates extended size of given Opt Number/Length in coap message.
+ *
+ * Helper function.
+ */
+static size_t coap_get_ext_opt_size(uint32_t value) {
+  int ret = 0;
+
+  if (value >= 13 && value <= 0xFF + 13) {
+    ret = sizeof(uint8_t);
+  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
+    ret = sizeof(uint16_t);
+  }
+
+  return ret;
+}
+
+/*
+ * Splits given Opt Number/Length into base and ext values.
+ *
+ * Helper function.
+ */
+static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
+  int ret = 0;
+
+  if (value < 13) {
+    *base = value;
+  } else if (value >= 13 && value <= 0xFF + 13) {
+    *base = 13;
+    *ext = value - 13;
+    ret = sizeof(uint8_t);
+  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
+    *base = 14;
+    *ext = value - 269;
+    ret = sizeof(uint16_t);
+  }
+
+  return ret;
+}
+
+/*
+ * Puts uint16_t (in network order) into given char stream.
+ *
+ * Helper function.
+ */
+static char *coap_add_uint16(char *ptr, uint16_t val) {
+  *ptr = val >> 8;
+  ptr++;
+  *ptr = val & 0x00FF;
+  ptr++;
+  return ptr;
+}
+
+/*
+ * Puts extended value of Opt Number/Length into given char stream.
+ *
+ * Helper function.
+ */
+static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
+  if (len == sizeof(uint8_t)) {
+    *ptr = val;
+    ptr++;
+  } else if (len == sizeof(uint16_t)) {
+    ptr = coap_add_uint16(ptr, val);
+  }
+
+  return ptr;
+}
+
+/*
+ * Verifies given mg_coap_message and calculates message size for it.
+ *
+ * Helper function.
+ */
+static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
+                                           size_t *len) {
+  struct mg_coap_option *opt;
+  uint32_t prev_opt_number;
+
+  *len = 4; /* header */
+  if (cm->msg_type > MG_COAP_MSG_MAX) {
+    return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
+  }
+  if (cm->token.len > 8) {
+    return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
+  }
+  if (cm->code_class > 7) {
+    return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
+  }
+  if (cm->code_detail > 31) {
+    return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
+  }
+
+  *len += cm->token.len;
+  if (cm->payload.len != 0) {
+    *len += cm->payload.len + 1; /* ... + 1; add payload marker */
+  }
+
+  opt = cm->options;
+  prev_opt_number = 0;
+  while (opt != NULL) {
+    *len += 1; /* basic delta/length */
+    *len += coap_get_ext_opt_size(opt->number);
+    *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
+    /*
+     * Current implementation performs check if
+     * option_number > previous option_number and produces an error
+     * TODO(alashkin): write design doc with limitations
+     * May be resorting is more suitable solution.
+     */
+    if ((opt->next != NULL && opt->number > opt->next->number) ||
+        opt->value.len > 0xFFFF + 269 ||
+        opt->number - prev_opt_number > 0xFFFF + 269) {
+      return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
+    }
+    *len += opt->value.len;
+    opt = opt->next;
+  }
+
+  return 0;
+}
+
+uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
+  struct mg_coap_option *opt;
+  uint32_t res, prev_opt_number;
+  size_t prev_io_len, packet_size;
+  char *ptr;
+
+  res = coap_calculate_packet_size(cm, &packet_size);
+  if (res != 0) {
+    return res;
+  }
+
+  /* saving previous lenght to handle non-empty mbuf */
+  prev_io_len = io->len;
+  mbuf_append(io, NULL, packet_size);
+  ptr = io->buf + prev_io_len;
+
+  /*
+   * since cm is verified, it is possible to use bits shift operator
+   * without additional zeroing of unused bits
+   */
+
+  /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
+  *ptr = (1 << 6) | (cm->msg_type << 4) | (cm->token.len);
+  ptr++;
+
+  /* code class: 3 bits, code detail: 5 bits */
+  *ptr = (cm->code_class << 5) | (cm->code_detail);
+  ptr++;
+
+  ptr = coap_add_uint16(ptr, cm->msg_id);
+
+  if (cm->token.len != 0) {
+    memcpy(ptr, cm->token.p, cm->token.len);
+    ptr += cm->token.len;
+  }
+
+  opt = cm->options;
+  prev_opt_number = 0;
+  while (opt != NULL) {
+    uint8_t delta_base = 0, length_base = 0;
+    uint16_t delta_ext, length_ext;
+
+    size_t opt_delta_len =
+        coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
+    size_t opt_lenght_len =
+        coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
+
+    *ptr = (delta_base << 4) | length_base;
+    ptr++;
+
+    ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
+    ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
+
+    if (opt->value.len != 0) {
+      memcpy(ptr, opt->value.p, opt->value.len);
+      ptr += opt->value.len;
+    }
+
+    prev_opt_number = opt->number;
+    opt = opt->next;
+  }
+
+  if (cm->payload.len != 0) {
+    *ptr = 0xFF;
+    ptr++;
+    memcpy(ptr, cm->payload.p, cm->payload.len);
+  }
+
+  return 0;
+}
+
+uint32_t mg_coap_send_message(struct mg_connection *nc,
+                              struct mg_coap_message *cm) {
+  struct mbuf packet_out;
+  uint32_t compose_res;
+
+  mbuf_init(&packet_out, 0);
+  compose_res = mg_coap_compose(cm, &packet_out);
+  if (compose_res != 0) {
+    return compose_res; /* LCOV_EXCL_LINE */
+  }
+
+  mg_send(nc, packet_out.buf, (int) packet_out.len);
+  mbuf_free(&packet_out);
+
+  return 0;
+}
+
+uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
+  struct mg_coap_message cm;
+  memset(&cm, 0, sizeof(cm));
+  cm.msg_type = MG_COAP_MSG_ACK;
+  cm.msg_id = msg_id;
+
+  return mg_coap_send_message(nc, &cm);
+}
+
+static void coap_handler(struct mg_connection *nc, int ev, void *ev_data) {
+  struct mbuf *io = &nc->recv_mbuf;
+  struct mg_coap_message cm;
+  uint32_t parse_res;
+
+  memset(&cm, 0, sizeof(cm));
+
+  nc->handler(nc, ev, ev_data);
+
+  switch (ev) {
+    case MG_EV_RECV:
+      parse_res = mg_coap_parse(io, &cm);
+      if ((parse_res & MG_COAP_IGNORE) == 0) {
+        if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
+          /*
+           * Since we support UDP only
+           * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
+           */
+          cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
+        }                                   /* LCOV_EXCL_LINE */
+        nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, &cm);
+      }
+
+      mg_coap_free_options(&cm);
+      mbuf_remove(io, io->len);
+      break;
+  }
+}
+/*
+ * Attach built-in CoAP event handler to the given connection.
+ *
+ * The user-defined event handler will receive following extra events:
+ *
+ * - MG_EV_COAP_CON
+ * - MG_EV_COAP_NOC
+ * - MG_EV_COAP_ACK
+ * - MG_EV_COAP_RST
+ */
+int mg_set_protocol_coap(struct mg_connection *nc) {
+  /* supports UDP only */
+  if ((nc->flags & MG_F_UDP) == 0) {
+    return -1;
+  }
+
+  nc->proto_handler = coap_handler;
+
+  return 0;
+}
+
+#endif /* MG_DISABLE_COAP */
diff --git a/spectrum_manager/src/mongoose.h b/spectrum_manager/src/mongoose.h
index 06336d3f..e5ce1800 100644
--- a/spectrum_manager/src/mongoose.h
+++ b/spectrum_manager/src/mongoose.h
@@ -1,301 +1,2750 @@
-// Copyright (c) 2004-2012 Sergey Lyubka
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
+#ifdef __AVR__
+#include "avrsupport.h"
+#endif
+/*
+ * Copyright (c) 2004-2013 Sergey Lyubka
+ * Copyright (c) 2013-2015 Cesanta Software Limited
+ * All rights reserved
+ *
+ * This software is dual-licensed: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. For the terms of this
+ * license, see .
+ *
+ * You are free to use this software under the terms of the GNU General
+ * Public License, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the GNU General Public License for more details.
+ *
+ * Alternatively, you can license this software under a commercial
+ * license, as set out in .
+ */
 
-#ifndef MONGOOSE_HEADER_INCLUDED
-#define  MONGOOSE_HEADER_INCLUDED
+#define MG_VERSION "6.1"
 
-#include 
+/* Local tweaks, applied before any of Mongoose's own headers. */
+#ifdef MG_LOCALS
+#include 
+#endif
+
+#if defined(MG_ENABLE_DEBUG) && !defined(CS_ENABLE_DEBUG)
+#define CS_ENABLE_DEBUG
+#endif
+/*
+ * Copyright (c) 2015 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#ifndef OSDEP_HEADER_INCLUDED
+#define OSDEP_HEADER_INCLUDED
+
+#if !defined(MG_DISABLE_FILESYSTEM) && defined(AVR_NOFS)
+#define MG_DISABLE_FILESYSTEM
+#endif
+
+#undef UNICODE                /* Use ANSI WinAPI functions */
+#undef _UNICODE               /* Use multibyte encoding on Windows */
+#define _MBCS                 /* Use multibyte encoding on Windows */
+#define _INTEGRAL_MAX_BITS 64 /* Enable _stati64() on Windows */
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005+ */
+#endif
+#undef WIN32_LEAN_AND_MEAN /* Let windows.h always include winsock2.h */
+#undef _XOPEN_SOURCE
+#define _XOPEN_SOURCE 600    /* For flockfile() on Linux */
+#define __STDC_FORMAT_MACROS /*  wants this for C++ */
+#define __STDC_LIMIT_MACROS  /* C++ wants that for INT64_MAX */
+#ifndef _LARGEFILE_SOURCE
+#define _LARGEFILE_SOURCE /* Enable fseeko() and ftello() functions */
+#endif
+#define _FILE_OFFSET_BITS 64 /* Enable 64-bit file offsets */
+
+#if !(defined(AVR_LIBC) || defined(PICOTCP))
+#include 
+#include 
+#include 
+#include 
+#include 
+#endif
+
+#ifndef BYTE_ORDER
+#define LITTLE_ENDIAN 0x41424344
+#define BIG_ENDIAN 0x44434241
+#define PDP_ENDIAN 0x42414443
+/* TODO(lsm): fix for big-endian machines. 'ABCD' is not portable */
+/*#define BYTE_ORDER 'ABCD'*/
+#define BYTE_ORDER LITTLE_ENDIAN
+#endif
+
+/*
+ * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
+ * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
+ * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)
+ * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)
+ * MSVC++ 9.0  _MSC_VER == 1500 (Visual Studio 2008)
+ * MSVC++ 8.0  _MSC_VER == 1400 (Visual Studio 2005)
+ * MSVC++ 7.1  _MSC_VER == 1310 (Visual Studio 2003)
+ * MSVC++ 7.0  _MSC_VER == 1300
+ * MSVC++ 6.0  _MSC_VER == 1200
+ * MSVC++ 5.0  _MSC_VER == 1100
+ */
+#ifdef _MSC_VER
+#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */
+#pragma warning(disable : 4204) /* missing c99 support */
+#endif
+
+#ifdef PICOTCP
+#define time(x) PICO_TIME()
+#ifndef SOMAXCONN
+#define SOMAXCONN (16)
+#endif
+#ifdef _POSIX_VERSION
+#define signal(...)
+#endif
+#endif
+
+#include 
+#include 
+#include 
+#include 
 #include 
+#include 
+#include 
+#include 
+
+#ifndef va_copy
+#ifdef __va_copy
+#define va_copy __va_copy
+#else
+#define va_copy(x, y) (x) = (y)
+#endif
+#endif
+
+#ifdef _WIN32
+#define random() rand()
+#ifdef _MSC_VER
+#pragma comment(lib, "ws2_32.lib") /* Linking with winsock library */
+#endif
+#include 
+#include 
+#ifndef EINPROGRESS
+#define EINPROGRESS WSAEINPROGRESS
+#endif
+#ifndef EWOULDBLOCK
+#define EWOULDBLOCK WSAEWOULDBLOCK
+#endif
+#ifndef __func__
+#define STRX(x) #x
+#define STR(x) STRX(x)
+#define __func__ __FILE__ ":" STR(__LINE__)
+#endif
+#define snprintf _snprintf
+#define fileno _fileno
+#define vsnprintf _vsnprintf
+#define sleep(x) Sleep((x) *1000)
+#define to64(x) _atoi64(x)
+#define popen(x, y) _popen((x), (y))
+#define pclose(x) _pclose(x)
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+#define fseeko(x, y, z) _fseeki64((x), (y), (z))
+#else
+#define fseeko(x, y, z) fseek((x), (y), (z))
+#endif
+#define random() rand()
+typedef int socklen_t;
+typedef signed char int8_t;
+typedef unsigned char uint8_t;
+typedef int int32_t;
+typedef unsigned int uint32_t;
+typedef short int16_t;
+typedef unsigned short uint16_t;
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+typedef SOCKET sock_t;
+typedef uint32_t in_addr_t;
+#ifndef UINT16_MAX
+#define UINT16_MAX 65535
+#endif
+#ifndef UINT32_MAX
+#define UINT32_MAX 4294967295
+#endif
+#ifndef pid_t
+#define pid_t HANDLE
+#endif
+#define INT64_FMT "I64d"
+#define SIZE_T_FMT "Iu"
+#ifdef __MINGW32__
+typedef struct stat cs_stat_t;
+#else
+typedef struct _stati64 cs_stat_t;
+#endif
+#ifndef S_ISDIR
+#define S_ISDIR(x) ((x) &_S_IFDIR)
+#endif
+#define DIRSEP '\\'
+
+/* POSIX opendir/closedir/readdir API for Windows. */
+struct dirent {
+  char d_name[MAX_PATH];
+};
+
+typedef struct DIR {
+  HANDLE handle;
+  WIN32_FIND_DATAW info;
+  struct dirent result;
+} DIR;
+
+DIR *opendir(const char *name);
+int closedir(DIR *dir);
+struct dirent *readdir(DIR *dir);
+
+#elif /* not _WIN32 */ defined(MG_CC3200)
+
+#include 
+#include 
+#include 
+#include 
+
+#elif /* not CC3200 */ defined(MG_LWIP)
+
+#include 
+#include 
+#include 
+
+#if defined(MG_ESP8266) && defined(RTOS_SDK)
+#include 
+#define random() os_random()
+#endif
+
+/* TODO(alashkin): check if zero is OK */
+#define SOMAXCONN 0
+#include 
+
+#elif /* not ESP8266 RTOS */ !defined(NO_LIBC) && !defined(NO_BSD_SOCKETS)
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include  /* For inet_pton() when MG_ENABLE_IPV6 is defined */
+#include 
+#include 
+#include 
+#endif
+
+#ifndef LWIP_PROVIDE_ERRNO
+#include 
+#endif
+
+#ifndef _WIN32
+#include 
+#include 
+
+#ifndef AVR_LIBC
+#ifndef MG_ESP8266
+#define closesocket(x) close(x)
+#endif
+#ifndef __cdecl
+#define __cdecl
+#endif
+
+#define INVALID_SOCKET (-1)
+#define INT64_FMT PRId64
+#if defined(ESP8266) || defined(MG_ESP8266) || defined(MG_CC3200)
+#define SIZE_T_FMT "u"
+#else
+#define SIZE_T_FMT "zu"
+#endif
+#define to64(x) strtoll(x, NULL, 10)
+typedef int sock_t;
+typedef struct stat cs_stat_t;
+#define DIRSEP '/'
+#endif /* !AVR_LIBC */
+
+#ifdef __APPLE__
+int64_t strtoll(const char *str, char **endptr, int base);
+#endif
+#endif /* !_WIN32 */
+
+#ifndef ARRAY_SIZE
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
+#endif
+
+#endif /* OSDEP_HEADER_INCLUDED */
+#ifndef _CS_DBG_H_
+#define _CS_DBG_H_
+
+enum cs_log_level {
+  LL_NONE = -1,
+  LL_ERROR = 0,
+  LL_WARN = 1,
+  LL_INFO = 2,
+  LL_DEBUG = 3,
+  LL_VERBOSE_DEBUG = 4,
+
+  _LL_MIN = -2,
+  _LL_MAX = 5,
+};
+
+#ifndef CS_NDEBUG
+
+extern enum cs_log_level s_cs_log_level;
+void cs_log_set_level(enum cs_log_level level);
+
+void cs_log_printf(const char *fmt, ...);
+
+#define LOG(l, x)                        \
+  if (s_cs_log_level >= l) {             \
+    fprintf(stderr, "%-20s ", __func__); \
+    cs_log_printf x;                     \
+  }
+
+#define DBG(x)                              \
+  if (s_cs_log_level >= LL_VERBOSE_DEBUG) { \
+    fprintf(stderr, "%-20s ", __func__);    \
+    cs_log_printf x;                        \
+  }
+
+#else /* NDEBUG */
+
+#define cs_log_set_level(l)
+
+#define LOG(l, x)
+#define DBG(x)
+
+#endif
+
+#endif /* _CS_DBG_H_ */
+/*
+ * Copyright (c) 2015 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/*
+ * === Memory Buffers
+ *
+ * Mbufs are mutable/growing memory buffers, like C++ strings.
+ * Mbuf can append data to the end of a buffer, or insert data into arbitrary
+ * position in the middle of a buffer. The buffer grows automatically when
+ * needed.
+ */
+
+#ifndef MBUF_H_INCLUDED
+#define MBUF_H_INCLUDED
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#include 
+
+#ifndef MBUF_SIZE_MULTIPLIER
+#define MBUF_SIZE_MULTIPLIER 1.5
+#endif
+
+/* Memory buffer descriptor */
+struct mbuf {
+  char *buf;   /* Buffer pointer */
+  size_t len;  /* Data length. Data is located between offset 0 and len. */
+  size_t size; /* Buffer size allocated by realloc(1). Must be >= len */
+};
+
+/*
+ * Initialize an Mbuf.
+ * `initial_capacity` specifies the initial capacity of the mbuf.
+ */
+void mbuf_init(struct mbuf *, size_t initial_capacity);
+
+/* Free the space allocated for the mbuffer and resets the mbuf structure. */
+void mbuf_free(struct mbuf *);
+
+/*
+ * Appends data to the Mbuf.
+ *
+ * Return the number of bytes appended, or 0 if out of memory.
+ */
+size_t mbuf_append(struct mbuf *, const void *data, size_t data_size);
+
+/*
+ * Insert data at a specified offset in the Mbuf.
+ *
+ * Existing data will be shifted forwards and the buffer will
+ * be grown if necessary.
+ * Return the number of bytes inserted.
+ */
+size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t);
+
+/* Remove `data_size` bytes from the beginning of the buffer. */
+void mbuf_remove(struct mbuf *, size_t data_size);
+
+/*
+ * Resize an Mbuf.
+ *
+ * If `new_size` is smaller than buffer's `len`, the
+ * resize is not performed.
+ */
+void mbuf_resize(struct mbuf *, size_t new_size);
+
+/* Shrink an Mbuf by resizing its `size` to `len`. */
+void mbuf_trim(struct mbuf *);
+
+#if defined(__cplusplus)
+}
+#endif /* __cplusplus */
+
+#endif /* MBUF_H_INCLUDED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if !defined(MG_SHA1_HEADER_INCLUDED) && !defined(DISABLE_SHA1)
+#define MG_SHA1_HEADER_INCLUDED
+
 
 #ifdef __cplusplus
 extern "C" {
-#endif // __cplusplus
+#endif /* __cplusplus */
 
-struct mg_context;     // Handle for the HTTP service itself
-struct mg_connection;  // Handle for the individual connection
+typedef struct {
+  uint32_t state[5];
+  uint32_t count[2];
+  unsigned char buffer[64];
+} cs_sha1_ctx;
 
+void cs_sha1_init(cs_sha1_ctx *);
+void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len);
+void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *);
+void cs_hmac_sha1(const unsigned char *key, size_t key_len,
+                  const unsigned char *text, size_t text_len,
+                  unsigned char out[20]);
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* MG_SHA1_HEADER_INCLUDED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
 
-// This structure contains information about the HTTP request.
-struct mg_request_info {
-  void *user_data;       // User-defined pointer passed to mg_start()
-  char *request_method;  // "GET", "POST", etc
-  char *uri;             // URL-decoded URI
-  char *http_version;    // E.g. "1.0", "1.1"
-  char *query_string;    // URL part after '?' (not including '?') or NULL
-  char *remote_user;     // Authenticated user, or NULL if no auth used
-  char *log_message;     // Mongoose error log message, MG_EVENT_LOG only
-  long remote_ip;        // Client's IP address
-  int remote_port;       // Client's port
-  int status_code;       // HTTP reply status code, e.g. 200
-  int is_ssl;            // 1 if SSL-ed, 0 if not
-  int num_headers;       // Number of headers
-  struct mg_header {
-    char *name;          // HTTP header name
-    char *value;         // HTTP header value
-  } http_headers[64];    // Maximum 64 headers
-};
-
-// Various events on which user-defined function is called by Mongoose.
-enum mg_event {
-  MG_NEW_REQUEST,       // New HTTP request has arrived from the client
-  MG_REQUEST_COMPLETE,  // Mongoose has finished handling the request
-  MG_HTTP_ERROR,        // HTTP error must be returned to the client
-  MG_EVENT_LOG,         // Mongoose logs an event, request_info.log_message
-  MG_INIT_SSL           // Mongoose initializes SSL. Instead of mg_connection *,
-                        // SSL context is passed to the callback function.
-};
-
-// Prototype for the user-defined function. Mongoose calls this function
-// on every MG_* event.
-//
-// Parameters:
-//   event: which event has been triggered.
-//   conn: opaque connection handler. Could be used to read, write data to the
-//         client, etc. See functions below that have "mg_connection *" arg.
-//
-// Return:
-//   If handler returns non-NULL, that means that handler has processed the
-//   request by sending appropriate HTTP reply to the client. Mongoose treats
-//   the request as served.
-//   If handler returns NULL, that means that handler has not processed
-//   the request. Handler must not send any data to the client in this case.
-//   Mongoose proceeds with request handling as if nothing happened.
-typedef void * (*mg_callback_t)(enum mg_event event,
-                                struct mg_connection *conn);
-
-
-// Start web server.
-//
-// Parameters:
-//   callback: user defined event handling function or NULL.
-//   options: NULL terminated list of option_name, option_value pairs that
-//            specify Mongoose configuration parameters.
-//
-// Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
-//    processing is required for these, signal handlers must be set up
-//    after calling mg_start().
-//
-//
-// Example:
-//   const char *options[] = {
-//     "document_root", "/var/www",
-//     "listening_ports", "80,443s",
-//     NULL
-//   };
-//   struct mg_context *ctx = mg_start(&my_func, NULL, options);
-//
-// Please refer to http://code.google.com/p/mongoose/wiki/MongooseManual
-// for the list of valid option and their possible values.
-//
-// Return:
-//   web server context, or NULL on error.
-struct mg_context *mg_start(mg_callback_t callback, void *user_data,
-                            const char **options);
-
-
-// Stop the web server.
-//
-// Must be called last, when an application wants to stop the web server and
-// release all associated resources. This function blocks until all Mongoose
-// threads are stopped. Context pointer becomes invalid.
-void mg_stop(struct mg_context *);
-
-
-// Get the value of particular configuration parameter.
-// The value returned is read-only. Mongoose does not allow changing
-// configuration at run time.
-// If given parameter name is not valid, NULL is returned. For valid
-// names, return value is guaranteed to be non-NULL. If parameter is not
-// set, zero-length string is returned.
-const char *mg_get_option(const struct mg_context *ctx, const char *name);
-
-
-// Return array of strings that represent valid configuration options.
-// For each option, a short name, long name, and default value is returned.
-// Array is NULL terminated.
-const char **mg_get_valid_option_names(void);
-
-
-// Add, edit or delete the entry in the passwords file.
-//
-// This function allows an application to manipulate .htpasswd files on the
-// fly by adding, deleting and changing user records. This is one of the
-// several ways of implementing authentication on the server side. For another,
-// cookie-based way please refer to the examples/chat.c in the source tree.
-//
-// If password is not NULL, entry is added (or modified if already exists).
-// If password is NULL, entry is deleted.
-//
-// Return:
-//   1 on success, 0 on error.
-int mg_modify_passwords_file(const char *passwords_file_name,
-                             const char *domain,
-                             const char *user,
-                             const char *password);
-
-
-// Return mg_request_info structure associated with the request.
-// Always succeeds.
-const struct mg_request_info *mg_get_request_info(const struct mg_connection *);
-
-
-// Send data to the client.
-// Return:
-//  0   when the connection has been closed
-//  -1  on error
-//  number of bytes written on success
-int mg_write(struct mg_connection *, const void *buf, size_t len);
-
-
-// Send data to the browser using printf() semantics.
-//
-// Works exactly like mg_write(), but allows to do message formatting.
-// Below are the macros for enabling compiler-specific checks for
-// printf-like arguments.
-
-#undef PRINTF_FORMAT_STRING
-#if _MSC_VER >= 1400
-#include 
-#if _MSC_VER > 1400
-#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
-#else
-#define PRINTF_FORMAT_STRING(s) __format_string s
-#endif
-#else
-#define PRINTF_FORMAT_STRING(s) s
-#endif
-
-#ifdef __GNUC__
-#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
-#else
-#define PRINTF_ARGS(x, y)
-#endif
-
-int mg_printf(struct mg_connection *,
-              PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
-
-
-// Send contents of the entire file together with HTTP headers.
-void mg_send_file(struct mg_connection *conn, const char *path);
-
-
-// Read data from the remote end, return number of bytes read.
-int mg_read(struct mg_connection *, void *buf, size_t len);
-
-
-// Get the value of particular HTTP header.
-//
-// This is a helper function. It traverses request_info->http_headers array,
-// and if the header is present in the array, returns its value. If it is
-// not present, NULL is returned.
-const char *mg_get_header(const struct mg_connection *, const char *name);
-
-
-// Get a value of particular form variable.
-//
-// Parameters:
-//   data: pointer to form-uri-encoded buffer. This could be either POST data,
-//         or request_info.query_string.
-//   data_len: length of the encoded data.
-//   var_name: variable name to decode from the buffer
-//   buf: destination buffer for the decoded variable
-//   buf_len: length of the destination buffer
-//
-// Return:
-//   On success, length of the decoded variable.
-//   On error:
-//      -1 (variable not found, or destination buffer is too small).
-//      -2 (destination buffer is NULL or zero length).
-//
-// Destination buffer is guaranteed to be '\0' - terminated if it is not
-// NULL or zero length. In case of failure, dst[0] == '\0'.
-int mg_get_var(const char *data, size_t data_len,
-               const char *var_name, char *buf, size_t buf_len);
-
-// Fetch value of certain cookie variable into the destination buffer.
-//
-// Destination buffer is guaranteed to be '\0' - terminated. In case of
-// failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
-// parameter. This function returns only first occurrence.
-//
-// Return:
-//   On success, value length.
-//   On error, -1 (either "Cookie:" header is not present at all, or the
-//   requested parameter is not found, or destination buffer is too small
-//   to hold the value).
-int mg_get_cookie(const struct mg_connection *,
-                  const char *cookie_name, char *buf, size_t buf_len);
-
-
-// Connect to the remote web server.
-// Return:
-//   On success, valid pointer to the new connection
-//   On error, NULL
-struct mg_connection *mg_connect(struct mg_context *ctx,
-                                 const char *host, int port, int use_ssl);
-
-
-// Close the connection opened by mg_connect().
-void mg_close_connection(struct mg_connection *conn);
-
-
-// Download given URL to a given file.
-//   url: URL to download
-//   path: file name where to save the data
-//   request_info: pointer to a structure that will hold parsed reply headers
-//   buf, bul_len: a buffer for the reply headers
-// Return:
-//   On error, NULL
-//   On success, opened file stream to the downloaded contents. The stream
-//   is positioned to the end of the file. It is the user's responsibility
-//   to fclose() the opened file stream.
-FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path,
-               char *buf, size_t buf_len, struct mg_request_info *request_info);
-
-
-// Convenience function -- create detached thread.
-// Return: 0 on success, non-0 on error.
-typedef void * (*mg_thread_func_t)(void *);
-int mg_start_thread(mg_thread_func_t f, void *p);
-
-
-// Return builtin mime type for the given file name.
-// For unrecognized extensions, "text/plain" is returned.
-const char *mg_get_builtin_mime_type(const char *file_name);
-
-
-// Return Mongoose version.
-const char *mg_version(void);
-
-
-// MD5 hash given strings.
-// Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
-// ASCIIz strings. When function returns, buf will contain human-readable
-// MD5 hash. Example:
-//   char buf[33];
-//   mg_md5(buf, "aa", "bb", NULL);
-void mg_md5(char buf[33], ...);
+#ifndef MD5_HEADER_DEFINED
+#define MD5_HEADER_DEFINED
 
 
 #ifdef __cplusplus
-}
-#endif // __cplusplus
+extern "C" {
+#endif /* __cplusplus */
 
-#endif // MONGOOSE_HEADER_INCLUDED
+typedef struct MD5Context {
+  uint32_t buf[4];
+  uint32_t bits[2];
+  unsigned char in[64];
+} MD5_CTX;
+
+void MD5_Init(MD5_CTX *c);
+void MD5_Update(MD5_CTX *c, const unsigned char *data, size_t len);
+void MD5_Final(unsigned char *md, MD5_CTX *c);
+
+/*
+ * Return stringified MD5 hash for NULL terminated list of strings.
+ * Example:
+ *
+ *    char buf[33];
+ *    cs_md5(buf, "foo", "bar", NULL);
+ */
+char *cs_md5(char buf[33], ...);
+
+/*
+ * Stringify binary data. Output buffer size must be 2 * size_of_input + 1
+ * because each byte of input takes 2 bytes in string representation
+ * plus 1 byte for the terminating \0 character.
+ */
+void cs_to_hex(char *to, const unsigned char *p, size_t len);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if !defined(BASE64_H_INCLUDED) && !defined(DISABLE_BASE64)
+#define BASE64_H_INCLUDED
+
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void (*cs_base64_putc_t)(char, void *);
+
+struct cs_base64_ctx {
+  /* cannot call it putc because it's a macro on some environments */
+  cs_base64_putc_t b64_putc;
+  unsigned char chunk[3];
+  int chunk_size;
+  void *user_data;
+};
+
+void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc,
+                    void *user_data);
+void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len);
+void cs_base64_finish(struct cs_base64_ctx *ctx);
+
+void cs_base64_encode(const unsigned char *src, int src_len, char *dst);
+void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len);
+int cs_base64_decode(const unsigned char *s, int len, char *dst);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
+/*
+ * Copyright (c) 2015 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#ifndef STR_UTIL_H
+#define STR_UTIL_H
+
+#include 
+#include 
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int c_snprintf(char *buf, size_t buf_size, const char *format, ...);
+int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap);
+
+#if (!(defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 700) &&           \
+     !(defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200809L) &&   \
+     !(defined(__DARWIN_C_LEVEL) && __DARWIN_C_LEVEL >= 200809L) && \
+     !defined(RTOS_SDK)) ||                                         \
+    defined(_WIN32)
+#define _MG_PROVIDE_STRNLEN
+size_t strnlen(const char *s, size_t maxlen);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif
+/*
+ * Copyright (c) 2004-2013 Sergey Lyubka 
+ * Copyright (c) 2013 Cesanta Software Limited
+ * All rights reserved
+ *
+ * This library is dual-licensed: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. For the terms of this
+ * license, see .
+ *
+ * You are free to use this library under the terms of the GNU General
+ * Public License, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the GNU General Public License for more details.
+ *
+ * Alternatively, you can license this library under a commercial
+ * license, as set out in .
+ */
+
+#ifndef FROZEN_HEADER_INCLUDED
+#define FROZEN_HEADER_INCLUDED
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include 
+
+enum json_type {
+  JSON_TYPE_EOF     = 0,      /* End of parsed tokens marker */
+  JSON_TYPE_STRING  = 1,
+  JSON_TYPE_NUMBER  = 2,
+  JSON_TYPE_OBJECT  = 3,
+  JSON_TYPE_TRUE    = 4,
+  JSON_TYPE_FALSE   = 5,
+  JSON_TYPE_NULL    = 6,
+  JSON_TYPE_ARRAY   = 7
+};
+
+struct json_token {
+  const char *ptr;      /* Points to the beginning of the token */
+  int len;              /* Token length */
+  int num_desc;         /* For arrays and object, total number of descendants */
+  enum json_type type;  /* Type of the token, possible values above */
+};
+
+/* Error codes */
+#define JSON_STRING_INVALID           -1
+#define JSON_STRING_INCOMPLETE        -2
+#define JSON_TOKEN_ARRAY_TOO_SMALL    -3
+
+int parse_json(const char *json_string, int json_string_length,
+               struct json_token *tokens_array, int size_of_tokens_array);
+struct json_token *parse_json2(const char *json_string, int string_length);
+struct json_token *find_json_token(struct json_token *toks, const char *path);
+
+int json_emit_long(char *buf, int buf_len, long value);
+int json_emit_double(char *buf, int buf_len, double value);
+int json_emit_quoted_str(char *buf, int buf_len, const char *str, int len);
+int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len);
+int json_emit(char *buf, int buf_len, const char *fmt, ...);
+int json_emit_va(char *buf, int buf_len, const char *fmt, va_list);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* FROZEN_HEADER_INCLUDED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ * This software is dual-licensed: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. For the terms of this
+ * license, see .
+ *
+ * You are free to use this software under the terms of the GNU General
+ * Public License, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the GNU General Public License for more details.
+ *
+ * Alternatively, you can license this software under a commercial
+ * license, as set out in .
+ */
+
+/*
+ * === Core: TCP/UDP/SSL
+ *
+ * NOTE: Mongoose manager is single threaded. It does not protect
+ * its data structures by mutexes, therefore all functions that are dealing
+ * with particular event manager should be called from the same thread,
+ * with exception of `mg_broadcast()` function. It is fine to have different
+ * event managers handled by different threads.
+ */
+
+#ifndef MG_NET_HEADER_INCLUDED
+#define MG_NET_HEADER_INCLUDED
+
+#ifdef MG_ENABLE_JAVASCRIPT
+#define EXCLUDE_COMMON
+#include 
+#endif
+
+
+#ifdef MG_ENABLE_SSL
+#ifdef __APPLE__
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+#include 
+#else
+typedef void *SSL;
+typedef void *SSL_CTX;
+#endif
+
+#ifdef MG_USE_READ_WRITE
+#define MG_RECV_FUNC(s, b, l, f) read(s, b, l)
+#define MG_SEND_FUNC(s, b, l, f) write(s, b, l)
+#else
+#define MG_RECV_FUNC(s, b, l, f) recv(s, b, l, f)
+#define MG_SEND_FUNC(s, b, l, f) send(s, b, l, f)
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+union socket_address {
+  struct sockaddr sa;
+  struct sockaddr_in sin;
+#ifdef MG_ENABLE_IPV6
+  struct sockaddr_in6 sin6;
+#else
+  struct sockaddr sin6;
+#endif
+};
+
+/* Describes chunk of memory */
+struct mg_str {
+  const char *p; /* Memory chunk pointer */
+  size_t len;    /* Memory chunk length */
+};
+
+#define MG_STR(str_literal) \
+  { str_literal, sizeof(str_literal) - 1 }
+
+/*
+ * Callback function (event handler) prototype, must be defined by user.
+ * Mongoose calls event handler, passing events defined below.
+ */
+struct mg_connection;
+typedef void (*mg_event_handler_t)(struct mg_connection *, int ev, void *);
+
+/* Events. Meaning of event parameter (evp) is given in the comment. */
+#define MG_EV_POLL 0    /* Sent to each connection on each mg_mgr_poll() call */
+#define MG_EV_ACCEPT 1  /* New connection accepted. union socket_address * */
+#define MG_EV_CONNECT 2 /* connect() succeeded or failed. int *  */
+#define MG_EV_RECV 3    /* Data has benn received. int *num_bytes */
+#define MG_EV_SEND 4    /* Data has been written to a socket. int *num_bytes */
+#define MG_EV_CLOSE 5   /* Connection is closed. NULL */
+
+/*
+ * Mongoose event manager.
+ */
+struct mg_mgr {
+  struct mg_connection *active_connections;
+  const char *hexdump_file; /* Debug hexdump file path */
+  sock_t ctl[2];            /* Socketpair for mg_wakeup() */
+  void *user_data;          /* User data */
+  void *mgr_data;           /* Implementation-specific event manager's data. */
+#ifdef MG_ENABLE_JAVASCRIPT
+  struct v7 *v7;
+#endif
+};
+
+/*
+ * Mongoose connection.
+ */
+struct mg_connection {
+  struct mg_connection *next, *prev; /* mg_mgr::active_connections linkage */
+  struct mg_connection *listener;    /* Set only for accept()-ed connections */
+  struct mg_mgr *mgr;                /* Pointer to containing manager */
+
+  sock_t sock; /* Socket to the remote peer */
+  int err;
+  union socket_address sa; /* Remote peer address */
+  size_t recv_mbuf_limit;  /* Max size of recv buffer */
+  struct mbuf recv_mbuf;   /* Received data */
+  struct mbuf send_mbuf;   /* Data scheduled for sending */
+  SSL *ssl;
+  SSL_CTX *ssl_ctx;
+  time_t last_io_time;              /* Timestamp of the last socket IO */
+  mg_event_handler_t proto_handler; /* Protocol-specific event handler */
+  void *proto_data;                 /* Protocol-specific data */
+  mg_event_handler_t handler;       /* Event handler function */
+  void *user_data;                  /* User-specific data */
+  void *priv_1;                     /* Used by mg_enable_multithreading() */
+  void *priv_2;                     /* Used by mg_enable_multithreading() */
+  void *mgr_data; /* Implementation-specific event manager's data. */
+
+  unsigned long flags;
+/* Flags set by Mongoose */
+#define MG_F_LISTENING (1 << 0)          /* This connection is listening */
+#define MG_F_UDP (1 << 1)                /* This connection is UDP */
+#define MG_F_RESOLVING (1 << 2)          /* Waiting for async resolver */
+#define MG_F_CONNECTING (1 << 3)         /* connect() call in progress */
+#define MG_F_SSL_HANDSHAKE_DONE (1 << 4) /* SSL specific */
+#define MG_F_WANT_READ (1 << 5)          /* SSL specific */
+#define MG_F_WANT_WRITE (1 << 6)         /* SSL specific */
+#define MG_F_IS_WEBSOCKET (1 << 7)       /* Websocket specific */
+
+/* Flags that are settable by user */
+#define MG_F_SEND_AND_CLOSE (1 << 10)      /* Push remaining data and close  */
+#define MG_F_CLOSE_IMMEDIATELY (1 << 11)   /* Disconnect */
+#define MG_F_WEBSOCKET_NO_DEFRAG (1 << 12) /* Websocket specific */
+#define MG_F_DELETE_CHUNK (1 << 13)        /* HTTP specific */
+
+#define MG_F_USER_1 (1 << 20) /* Flags left for application */
+#define MG_F_USER_2 (1 << 21)
+#define MG_F_USER_3 (1 << 22)
+#define MG_F_USER_4 (1 << 23)
+#define MG_F_USER_5 (1 << 24)
+#define MG_F_USER_6 (1 << 25)
+};
+
+/*
+ * Initialize Mongoose manager. Side effect: ignores SIGPIPE signal.
+ * `mgr->user_data` field will be initialized with `user_data` parameter.
+ * That is an arbitrary pointer, where user code can associate some data
+ * with the particular Mongoose manager. For example, a C++ wrapper class
+ * could be written, in which case `user_data` can hold a pointer to the
+ * class instance.
+ */
+void mg_mgr_init(struct mg_mgr *mgr, void *user_data);
+
+/*
+ * De-initializes Mongoose manager.
+ *
+ * Close and deallocate all active connections.
+ */
+void mg_mgr_free(struct mg_mgr *);
+
+/*
+ * This function performs the actual IO, and must be called in a loop
+ * (an event loop). Returns the current timestamp.
+ * `milli` is the maximum number of milliseconds to sleep.
+ * `mg_mgr_poll()` checks all connection for IO readiness. If at least one
+ * of the connections is IO-ready, `mg_mgr_poll()` triggers respective
+ * event handlers and returns.
+ */
+time_t mg_mgr_poll(struct mg_mgr *, int milli);
+
+#ifndef MG_DISABLE_SOCKETPAIR
+/*
+ * Pass a message of a given length to all connections.
+ *
+ * Must be called from a thread that does NOT call `mg_mgr_poll()`.
+ * Note that `mg_broadcast()` is the only function
+ * that can be, and must be, called from a different (non-IO) thread.
+ *
+ * `func` callback function will be called by the IO thread for each
+ * connection. When called, event would be `MG_EV_POLL`, and message will
+ * be passed as `ev_data` pointer. Maximum message size is capped
+ * by `MG_CTL_MSG_MESSAGE_SIZE` which is set to 8192 bytes.
+ */
+void mg_broadcast(struct mg_mgr *, mg_event_handler_t func, void *, size_t);
+#endif
+
+/*
+ * Iterate over all active connections.
+ *
+ * Returns next connection from the list
+ * of active connections, or `NULL` if there is no more connections. Below
+ * is the iteration idiom:
+ *
+ * [source,c]
+ * ----
+ * for (c = mg_next(srv, NULL); c != NULL; c = mg_next(srv, c)) {
+ *   // Do something with connection `c`
+ * }
+ * ----
+ */
+struct mg_connection *mg_next(struct mg_mgr *, struct mg_connection *);
+
+/*
+ * Optional parameters to mg_add_sock_opt()
+ * `flags` is an initial `struct mg_connection::flags` bitmask to set,
+ * see `MG_F_*` flags definitions.
+ */
+struct mg_add_sock_opts {
+  void *user_data;           /* Initial value for connection's user_data */
+  unsigned int flags;        /* Initial connection flags */
+  const char **error_string; /* Placeholder for the error string */
+};
+
+/*
+ * Create a connection, associate it with the given socket and event handler,
+ * and add it to the manager.
+ *
+ * For more options see the `mg_add_sock_opt` variant.
+ */
+struct mg_connection *mg_add_sock(struct mg_mgr *, sock_t, mg_event_handler_t);
+
+/*
+ * Create a connection, associate it with the given socket and event handler,
+ * and add to the manager.
+ *
+ * See the `mg_add_sock_opts` structure for a description of the options.
+ */
+struct mg_connection *mg_add_sock_opt(struct mg_mgr *, sock_t,
+                                      mg_event_handler_t,
+                                      struct mg_add_sock_opts);
+
+/*
+ * Optional parameters to mg_bind_opt()
+ * `flags` is an initial `struct mg_connection::flags` bitmask to set,
+ * see `MG_F_*` flags definitions.
+ */
+struct mg_bind_opts {
+  void *user_data;           /* Initial value for connection's user_data */
+  unsigned int flags;        /* Extra connection flags */
+  const char **error_string; /* Placeholder for the error string */
+};
+
+/*
+ * Create listening connection.
+ *
+ * See `mg_bind_opt` for full documentation.
+ */
+struct mg_connection *mg_bind(struct mg_mgr *, const char *,
+                              mg_event_handler_t);
+/*
+ * Create listening connection.
+ *
+ * `address` parameter tells which address to bind to. It's format is the same
+ * as for the `mg_connect()` call, where `HOST` part is optional. `address`
+ * can be just a port number, e.g. `:8000`. To bind to a specific interface,
+ * an IP address can be specified, e.g. `1.2.3.4:8000`. By default, a TCP
+ * connection is created. To create UDP connection, prepend `udp://` prefix,
+ * e.g. `udp://:8000`. To summarize, `address` paramer has following format:
+ * `[PROTO://][IP_ADDRESS]:PORT`, where `PROTO` could be `tcp` or `udp`.
+ *
+ * See the `mg_bind_opts` structure for a description of the optional
+ * parameters.
+ *
+ * Return a new listening connection, or `NULL` on error.
+ * NOTE: Connection remains owned by the manager, do not free().
+ */
+struct mg_connection *mg_bind_opt(struct mg_mgr *, const char *,
+                                  mg_event_handler_t, struct mg_bind_opts);
+
+/* Optional parameters to mg_connect_opt() */
+struct mg_connect_opts {
+  void *user_data;           /* Initial value for connection's user_data */
+  unsigned int flags;        /* Extra connection flags */
+  const char **error_string; /* Placeholder for the error string */
+};
+
+/*
+ * Connect to a remote host.
+ *
+ * See `mg_connect_opt()` for full documentation.
+ */
+struct mg_connection *mg_connect(struct mg_mgr *, const char *,
+                                 mg_event_handler_t);
+
+/*
+ * Connect to a remote host.
+ *
+ * `address` format is `[PROTO://]HOST:PORT`. `PROTO` could be `tcp` or `udp`.
+ * `HOST` could be an IP address,
+ * IPv6 address (if Mongoose is compiled with `-DMG_ENABLE_IPV6`), or a host
+ * name. If `HOST` is a name, Mongoose will resolve it asynchronously. Examples
+ * of valid addresses: `google.com:80`, `udp://1.2.3.4:53`, `10.0.0.1:443`,
+ * `[::1]:80`
+ *
+ * See the `mg_connect_opts` structure for a description of the optional
+ * parameters.
+ *
+ * Returns a new outbound connection, or `NULL` on error.
+ *
+ * NOTE: Connection remains owned by the manager, do not free().
+ *
+ * NOTE: To enable IPv6 addresses, `-DMG_ENABLE_IPV6` should be specified
+ * in the compilation flags.
+ *
+ * NOTE: New connection will receive `MG_EV_CONNECT` as it's first event
+ * which will report connect success status.
+ * If asynchronous resolution fail, or `connect()` syscall fail for whatever
+ * reason (e.g. with `ECONNREFUSED` or `ENETUNREACH`), then `MG_EV_CONNECT`
+ * event report failure. Code example below:
+ *
+ * [source,c]
+ * ----
+ * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
+ *   int connect_status;
+ *
+ *   switch (ev) {
+ *     case MG_EV_CONNECT:
+ *       connect_status = * (int *) ev_data;
+ *       if (connect_status == 0) {
+ *         // Success
+ *       } else  {
+ *         // Error
+ *         printf("connect() error: %s\n", strerror(connect_status));
+ *       }
+ *       break;
+ *     ...
+ *   }
+ * }
+ *
+ *   ...
+ *   mg_connect(mgr, "my_site.com:80", ev_handler);
+ * ----
+ */
+struct mg_connection *mg_connect_opt(struct mg_mgr *, const char *,
+                                     mg_event_handler_t,
+                                     struct mg_connect_opts);
+
+/*
+ * Enable SSL for a given connection.
+ * `cert` is a server certificate file name for a listening connection,
+ * or a client certificate file name for an outgoing connection.
+ * Certificate files must be in PEM format. Server certificate file
+ * must contain a certificate, concatenated with a private key, optionally
+ * concatenated with parameters.
+ * `ca_cert` is a CA certificate, or NULL if peer verification is not
+ * required.
+ * Return: NULL on success, or error message on error.
+ */
+const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
+                       const char *ca_cert);
+
+/*
+ * Send data to the connection.
+ *
+ * Note that sending functions do not actually push data to the socket.
+ * They just append data to the output buffer. MG_EV_SEND will be delivered when
+ * the data has actually been pushed out.
+ */
+void mg_send(struct mg_connection *, const void *buf, int len);
+
+/* Enables format string warnings for mg_printf */
+#if defined(__GNUC__)
+__attribute__((format(printf, 2, 3)))
+#endif
+/* don't separate from mg_printf declaration */
+
+/*
+ * Send `printf`-style formatted data to the connection.
+ *
+ * See `mg_send` for more details on send semantics.
+ */
+int mg_printf(struct mg_connection *, const char *fmt, ...);
+
+/* Same as `mg_printf()`, but takes `va_list ap` as an argument. */
+int mg_vprintf(struct mg_connection *, const char *fmt, va_list ap);
+
+/*
+ * Create a socket pair.
+ * `sock_type` can be either `SOCK_STREAM` or `SOCK_DGRAM`.
+ * Return 0 on failure, 1 on success.
+ */
+int mg_socketpair(sock_t[2], int sock_type);
+
+/*
+ * Convert domain name into IP address.
+ *
+ * This is a utility function. If compilation flags have
+ * `-DMG_ENABLE_GETADDRINFO`, then `getaddrinfo()` call is used for name
+ * resolution. Otherwise, `gethostbyname()` is used.
+ *
+ * CAUTION: this function can block.
+ * Return 1 on success, 0 on failure.
+ */
+#ifndef MG_DISABLE_SYNC_RESOLVER
+int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len);
+#endif
+
+/*
+ * Verify given IP address against the ACL.
+ *
+ * `remote_ip` - an IPv4 address to check, in host byte order
+ * `acl` - a comma separated list of IP subnets: `x.x.x.x/x` or `x.x.x.x`.
+ * Each subnet is
+ * prepended by either a - or a + sign. A plus sign means allow, where a
+ * minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`,
+ * this means to deny only that single IP address.
+ * Subnet masks may vary from 0 to 32, inclusive. The default setting
+ * is to allow all accesses. On each request the full list is traversed,
+ * and the last match wins. Example:
+ *
+ * `-0.0.0.0/0,+192.168/16` - deny all acccesses, only allow 192.168/16 subnet
+ *
+ * To learn more about subnet masks, see the
+ * link:https://en.wikipedia.org/wiki/Subnetwork[Wikipedia page on Subnetwork]
+ *
+ * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
+ */
+int mg_check_ip_acl(const char *acl, uint32_t remote_ip);
+
+/*
+ * Enable multi-threaded handling for the given listening connection `nc`.
+ * For each accepted connection, Mongoose will create a separate thread
+ * and run event handler in that thread. Thus, if an event hanler is doing
+ * a blocking call or some long computation, that will not slow down
+ * other connections.
+ */
+void mg_enable_multithreading(struct mg_connection *nc);
+
+#ifdef MG_ENABLE_JAVASCRIPT
+/*
+ * Enable server-side JavaScript scripting.
+ * Requires `-DMG_ENABLE_JAVASCRIPT` compilation flag, and V7 engine sources.
+ * v7 instance must not be destroyed during manager's lifetime.
+ * Return V7 error.
+ */
+enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
+                                 const char *init_js_file_name);
+#endif
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* MG_NET_HEADER_INCLUDED */
+#ifndef MG_NET_IF_HEADER_INCLUDED
+#define MG_NET_IF_HEADER_INCLUDED
+
+/*
+ * Internal async networking core interface.
+ * Consists of calls made by the core, which should not block,
+ * and callbacks back into the core ("..._cb").
+ * Callbacks may (will) cause methods to be invoked from within,
+ * but methods are not allowed to invoke callbacks inline.
+ *
+ * Implementation must ensure that only one callback is invoked at any time.
+ */
+
+/* Request that a TCP connection is made to the specified address. */
+void mg_if_connect_tcp(struct mg_connection *nc,
+                       const union socket_address *sa);
+/* Open a UDP socket. Doesn't actually connect anything. */
+void mg_if_connect_udp(struct mg_connection *nc);
+/* Callback invoked by connect methods. err = 0 -> ok, != 0 -> error. */
+void mg_if_connect_cb(struct mg_connection *nc, int err);
+
+/* Set up a listening TCP socket on a given address. rv = 0 -> ok. */
+int mg_if_listen_tcp(struct mg_connection *nc, union socket_address *sa);
+/* Deliver a new TCP connection. Returns NULL in case on error (unable to
+ * create connection, in which case interface state should be discarded. */
+struct mg_connection *mg_if_accept_tcp_cb(struct mg_connection *lc,
+                                          union socket_address *sa,
+                                          size_t sa_len);
+
+/* Request that a "listening" UDP socket be created. */
+int mg_if_listen_udp(struct mg_connection *nc, union socket_address *sa);
+
+/* Send functions for TCP and UDP. Sent data is copied before return. */
+void mg_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len);
+void mg_if_udp_send(struct mg_connection *nc, const void *buf, size_t len);
+/* Callback that reports that data has been put on the wire. */
+void mg_if_sent_cb(struct mg_connection *nc, int num_sent);
+
+/*
+ * Receive callback.
+ * buf must be heap-allocated and ownership is transferred to the core.
+ * Core will acknowledge consumption by calling mg_if_recved.
+ * No more than one chunk of data can be unacknowledged at any time.
+ */
+void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len);
+void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
+                       union socket_address *sa, size_t sa_len);
+void mg_if_recved(struct mg_connection *nc, size_t len);
+
+/* Deliver a POLL event to the connection. */
+void mg_if_poll(struct mg_connection *nc, time_t now);
+
+/* Perform interface-related cleanup on connection before destruction. */
+void mg_if_destroy_conn(struct mg_connection *nc);
+
+void mg_close_conn(struct mg_connection *nc);
+
+/* Put connection's address into *sa, local (remote = 0) or remote. */
+void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
+                         union socket_address *sa);
+
+#endif /* MG_NET_IF_HEADER_INCLUDED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/*
+ * === Utilities
+ */
+
+#ifndef MG_UTIL_HEADER_DEFINED
+#define MG_UTIL_HEADER_DEFINED
+
+#include 
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#ifndef MAX_PATH_SIZE
+#define MAX_PATH_SIZE 500
+#endif
+
+/*
+ * Fetch substring from input string `s`, `end` into `v`.
+ * Skips initial delimiter characters. Records first non-delimiter character
+ * as the beginning of substring `v`. Then scans the rest of the string
+ * until a delimiter character or end-of-string is found.
+ * `delimiters` is a 0-terminated string containing delimiter characters.
+ * Either one of `delimiters` or `end_string` terminates the search.
+ * Return an `s` pointer, advanced forward where parsing stopped.
+ */
+const char *mg_skip(const char *s, const char *end_string,
+                    const char *delimiters, struct mg_str *v);
+
+/*
+ * Cross-platform version of `strncasecmp()`.
+ */
+int mg_ncasecmp(const char *s1, const char *s2, size_t len);
+
+/*
+ * Cross-platform version of `strcasecmp()`.
+ */
+int mg_casecmp(const char *s1, const char *s2);
+
+/*
+ * Cross-platform version of `strcmp()` where where first string is
+ * specified by `struct mg_str`.
+ */
+int mg_vcmp(const struct mg_str *str2, const char *str1);
+
+/*
+ * Cross-platform version of `strncasecmp()` where first string is
+ * specified by `struct mg_str`.
+ */
+int mg_vcasecmp(const struct mg_str *str2, const char *str1);
+
+/*
+ * Decode base64-encoded string `s`, `len` into the destination `dst`.
+ * Destination has to have enough space to hold decoded buffer.
+ * Decoding stops either when all string has been decoded, or invalid
+ * character appeared.
+ * Destination is '\0'-terminated.
+ * Return number of decoded characters. On success, that should be equal to
+ * `len`. On error (invalid character) the return value is smaller then `len`.
+ */
+int mg_base64_decode(const unsigned char *s, int len, char *dst);
+
+/*
+ * Base64-encode chunk of memory `src`, `src_len` into the destination `dst`.
+ * Destination has to have enough space to hold encoded buffer.
+ * Destination is '\0'-terminated.
+ */
+void mg_base64_encode(const unsigned char *src, int src_len, char *dst);
+
+#ifndef MG_DISABLE_FILESYSTEM
+/*
+ * Perform a 64-bit `stat()` call against given file.
+ *
+ * `path` should be UTF8 encoded.
+ *
+ * Return value is the same as for `stat()` syscall.
+ */
+int mg_stat(const char *path, cs_stat_t *st);
+
+/*
+ * Open the given file and return a file stream.
+ *
+ * `path` and `mode` should be UTF8 encoded.
+ *
+ * Return value is the same as for the `fopen()` call.
+ */
+FILE *mg_fopen(const char *path, const char *mode);
+
+/*
+ * Open the given file and return a file stream.
+ *
+ * `path` should be UTF8 encoded.
+ *
+ * Return value is the same as for the `open()` syscall.
+ */
+int mg_open(const char *path, int flag, int mode);
+#endif /* MG_DISABLE_FILESYSTEM */
+
+#ifdef _WIN32
+#define MG_ENABLE_THREADS
+#endif
+
+#ifdef MG_ENABLE_THREADS
+/*
+ * Start a new detached thread.
+ * Arguments and semantic is the same as pthead's `pthread_create()`.
+ * `thread_func` is a thread function, `thread_func_param` is a parameter
+ * that is passed to the thread function.
+ */
+void *mg_start_thread(void *(*thread_func)(void *), void *thread_func_param);
+#endif
+
+void mg_set_close_on_exec(sock_t);
+
+#define MG_SOCK_STRINGIFY_IP 1
+#define MG_SOCK_STRINGIFY_PORT 2
+#define MG_SOCK_STRINGIFY_REMOTE 4
+/*
+ * Convert connection's local or remote address into string.
+ *
+ * The `flags` parameter is a bit mask that controls the behavior,
+ * see `MG_SOCK_STRINGIFY_*` definitions.
+ *
+ * - MG_SOCK_STRINGIFY_IP - print IP address
+ * - MG_SOCK_STRINGIFY_PORT - print port number
+ * - MG_SOCK_STRINGIFY_REMOTE - print remote peer's IP/port, not local address
+ *
+ * If both port number and IP address are printed, they are separated by `:`.
+ * If compiled with `-DMG_ENABLE_IPV6`, IPv6 addresses are supported.
+ */
+void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
+                         int flags);
+#ifndef MG_DISABLE_SOCKET_IF /* Legacy interface. */
+void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
+#endif
+
+/*
+ * Convert socket's address into string.
+ *
+ * `flags` is MG_SOCK_STRINGIFY_IP and/or MG_SOCK_STRINGIFY_PORT.
+ */
+void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
+                         int flags);
+
+/*
+ * Generates human-readable hexdump of memory chunk.
+ *
+ * Takes a memory buffer `buf` of length `len` and creates a hex dump of that
+ * buffer in `dst`. Generated output is a-la hexdump(1).
+ * Return length of generated string, excluding terminating `\0`. If returned
+ * length is bigger than `dst_len`, overflow bytes are discarded.
+ */
+int mg_hexdump(const void *buf, int len, char *dst, int dst_len);
+
+/*
+ * Generates human-readable hexdump of the data sent or received by connection.
+ * `path` is a file name where hexdump should be written. `num_bytes` is
+ * a number of bytes sent/received. `ev` is one of the `MG_*` events sent to
+ * an event handler. This function is supposed to be called from the
+ * event handler.
+ */
+void mg_hexdump_connection(struct mg_connection *nc, const char *path,
+                           const void *buf, int num_bytes, int ev);
+/*
+ * Print message to buffer. If buffer is large enough to hold the message,
+ * return buffer. If buffer is to small, allocate large enough buffer on heap,
+ * and return allocated buffer.
+ * This is a supposed use case:
+ *
+ *    char buf[5], *p = buf;
+ *    p = mg_avprintf(&p, sizeof(buf), "%s", "hi there");
+ *    use_p_somehow(p);
+ *    if (p != buf) {
+ *      free(p);
+ *    }
+ *
+ * The purpose of this is to avoid malloc-ing if generated strings are small.
+ */
+int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
+
+/*
+ * Return true if target platform is big endian.
+ */
+int mg_is_big_endian(void);
+
+/*
+ * A helper function for traversing a comma separated list of values.
+ * It returns a list pointer shifted to the next value, or NULL if the end
+ * of the list found.
+ * Value is stored in val vector. If value has form "x=y", then eq_val
+ * vector is initialized to point to the "y" part, and val vector length
+ * is adjusted to point only to "x".
+ * If list is just a comma separated list of entries, like "aa,bb,cc" then
+ * `eq_val` will contain zero-length string.
+ *
+ * The purpose of this function is to parse comma separated string without
+ * any copying/memory allocation.
+ */
+const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
+                                     struct mg_str *eq_val);
+
+/*
+ * Match 0-terminated string against a glob pattern.
+ * Match is case-insensitive. Return number of bytes matched, or -1 if no match.
+ */
+int mg_match_prefix(const char *pattern, int pattern_len, const char *str);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* MG_UTIL_HEADER_DEFINED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/*
+ * === HTTP + Websocket
+ */
+
+#ifndef MG_HTTP_HEADER_DEFINED
+#define MG_HTTP_HEADER_DEFINED
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#ifndef MG_MAX_HTTP_HEADERS
+#define MG_MAX_HTTP_HEADERS 40
+#endif
+
+#ifndef MG_MAX_HTTP_REQUEST_SIZE
+#define MG_MAX_HTTP_REQUEST_SIZE 8192
+#endif
+
+#ifndef MG_MAX_PATH
+#ifdef PATH_MAX
+#define MG_MAX_PATH PATH_MAX
+#else
+#define MG_MAX_PATH 1024
+#endif
+#endif
+
+#ifndef MG_MAX_HTTP_SEND_IOBUF
+#define MG_MAX_HTTP_SEND_IOBUF 4096
+#endif
+
+#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
+#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
+#endif
+
+#ifndef MG_CGI_ENVIRONMENT_SIZE
+#define MG_CGI_ENVIRONMENT_SIZE 8192
+#endif
+
+#ifndef MG_MAX_CGI_ENVIR_VARS
+#define MG_MAX_CGI_ENVIR_VARS 64
+#endif
+
+#ifndef MG_ENV_EXPORT_TO_CGI
+#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
+#endif
+
+/* HTTP message */
+struct http_message {
+  struct mg_str message; /* Whole message: request line + headers + body */
+
+  /* HTTP Request line (or HTTP response line) */
+  struct mg_str method; /* "GET" */
+  struct mg_str uri;    /* "/my_file.html" */
+  struct mg_str proto;  /* "HTTP/1.1" -- for both request and response */
+
+  /* For responses, code and response status message are set */
+  int resp_code;
+  struct mg_str resp_status_msg;
+
+  /*
+   * Query-string part of the URI. For example, for HTTP request
+   *    GET /foo/bar?param1=val1¶m2=val2
+   *    |    uri    |     query_string     |
+   *
+   * Note that question mark character doesn't belong neither to the uri,
+   * nor to the query_string
+   */
+  struct mg_str query_string;
+
+  /* Headers */
+  struct mg_str header_names[MG_MAX_HTTP_HEADERS];
+  struct mg_str header_values[MG_MAX_HTTP_HEADERS];
+
+  /* Message body */
+  struct mg_str body; /* Zero-length for requests with no body */
+};
+
+struct websocket_message {
+  unsigned char *data;
+  size_t size;
+  unsigned char flags;
+};
+
+/* HTTP and websocket events. void *ev_data is described in a comment. */
+#define MG_EV_HTTP_REQUEST 100 /* struct http_message * */
+#define MG_EV_HTTP_REPLY 101   /* struct http_message * */
+#define MG_EV_HTTP_CHUNK 102   /* struct http_message * */
+#define MG_EV_SSI_CALL 105     /* char * */
+
+#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* NULL */
+#define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112    /* NULL */
+#define MG_EV_WEBSOCKET_FRAME 113             /* struct websocket_message * */
+#define MG_EV_WEBSOCKET_CONTROL_FRAME 114     /* struct websocket_message * */
+
+/*
+ * Attach built-in HTTP event handler to the given connection.
+ * User-defined event handler will receive following extra events:
+ *
+ * - MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request is passed
+ *as
+ *   `struct http_message` through the handler's `void *ev_data` pointer.
+ * - MG_EV_HTTP_REPLY: HTTP reply has arrived. Parsed HTTP reply is passed as
+ *   `struct http_message` through the handler's `void *ev_data` pointer.
+ * - MG_EV_HTTP_CHUNK: HTTP chunked-encoding chunk has arrived.
+ *   Parsed HTTP reply is passed as `struct http_message` through the
+ *   handler's `void *ev_data` pointer. `http_message::body` would contain
+ *   incomplete, reassembled HTTP body.
+ *   It will grow with every new chunk arrived, and
+ *   potentially can consume a lot of memory. An event handler may process
+ *   the body as chunks are coming, and signal Mongoose to delete processed
+ *   body by setting `MG_F_DELETE_CHUNK` in `mg_connection::flags`. When
+ *   the last zero chunk is received,
+ *   Mongoose sends `MG_EV_HTTP_REPLY` event with
+ *   full reassembled body (if handler did not signal to delete chunks) or
+ *   with empty body (if handler did signal to delete chunks).
+ * - MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received websocket handshake
+ *   request. `ev_data` contains parsed HTTP request.
+ * - MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed Websocket handshake.
+ *   `ev_data` is `NULL`.
+ * - MG_EV_WEBSOCKET_FRAME: new websocket frame has arrived. `ev_data` is
+ *   `struct websocket_message *`
+ */
+void mg_set_protocol_http_websocket(struct mg_connection *nc);
+
+/*
+ * Send websocket handshake to the server.
+ *
+ * `nc` must be a valid connection, connected to a server. `uri` is an URI
+ * to fetch, extra_headers` is extra HTTP headers to send or `NULL`.
+ *
+ * This function is intended to be used by websocket client.
+ */
+void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
+                                 const char *extra_headers);
+
+/*
+ * Send websocket frame to the remote end.
+ *
+ * `op_and_flags` specifies frame's type, one of:
+ *
+ * - WEBSOCKET_OP_CONTINUE
+ * - WEBSOCKET_OP_TEXT
+ * - WEBSOCKET_OP_BINARY
+ * - WEBSOCKET_OP_CLOSE
+ * - WEBSOCKET_OP_PING
+ * - WEBSOCKET_OP_PONG
+ *
+ * Orred with one of the flags:
+ *
+ * - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent.
+ *
+ * `data` and `data_len` contain frame data.
+ */
+void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags,
+                             const void *data, size_t data_len);
+
+/*
+ * Send multiple websocket frames.
+ *
+ * Like `mg_send_websocket_frame()`, but composes a frame from multiple buffers.
+ */
+void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags,
+                              const struct mg_str *strings, int num_strings);
+
+/*
+ * Send websocket frame to the remote end.
+ *
+ * Like `mg_send_websocket_frame()`, but allows to create formatted message
+ * with `printf()`-like semantics.
+ */
+void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags,
+                               const char *fmt, ...);
+
+/*
+ * Send buffer `buf` of size `len` to the client using chunked HTTP encoding.
+ * This function first sends buffer size as hex number + newline, then
+ * buffer itself, then newline. For example,
+ *   `mg_send_http_chunk(nc, "foo", 3)` whill append `3\r\nfoo\r\n` string to
+ * the `nc->send_mbuf` output IO buffer.
+ *
+ * NOTE: HTTP header "Transfer-Encoding: chunked" should be sent prior to
+ * using this function.
+ *
+ * NOTE: do not forget to send empty chunk at the end of the response,
+ * to tell the client that everything was sent. Example:
+ *
+ * ```
+ *   mg_printf_http_chunk(nc, "%s", "my response!");
+ *   mg_send_http_chunk(nc, "", 0); // Tell the client we're finished
+ * ```
+ */
+void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len);
+
+/*
+ * Send printf-formatted HTTP chunk.
+ * Functionality is similar to `mg_send_http_chunk()`.
+ */
+void mg_printf_http_chunk(struct mg_connection *, const char *, ...);
+
+/*
+ * Send response status line.
+ * If `extra_headers` is not NULL, then `extra_headers` are also sent
+ * after the reponse line. `extra_headers` must NOT end end with new line.
+ * Example:
+ *
+ *      mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *");
+ *
+ * Will result in:
+ *
+ *      HTTP/1.1 200 OK\r\n
+ *      Access-Control-Allow-Origin: *\r\n
+ */
+void mg_send_response_line(struct mg_connection *c, int status_code,
+                           const char *extra_headers);
+
+/*
+ * Send response line and headers.
+ * This function sends response line with the `status_code`, and automatically
+ * sends one header: either "Content-Length", or "Transfer-Encoding".
+ * If `content_length` is negative, then "Transfer-Encoding: chunked" header
+ * is sent, otherwise, "Content-Length" header is sent.
+ *
+ * NOTE: If `Transfer-Encoding` is `chunked`, then message body must be sent
+ * using `mg_send_http_chunk()` or `mg_printf_http_chunk()` functions.
+ * Otherwise, `mg_send()` or `mg_printf()` must be used.
+ * Extra headers could be set through `extra_headers` - and note `extra_headers`
+ * must NOT be terminated by a new line.
+ */
+void mg_send_head(struct mg_connection *n, int status_code,
+                  int64_t content_length, const char *extra_headers);
+
+/*
+ * Send printf-formatted HTTP chunk, escaping HTML tags.
+ */
+void mg_printf_html_escape(struct mg_connection *, const char *, ...);
+
+/* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */
+#define WEBSOCKET_OP_CONTINUE 0
+#define WEBSOCKET_OP_TEXT 1
+#define WEBSOCKET_OP_BINARY 2
+#define WEBSOCKET_OP_CLOSE 8
+#define WEBSOCKET_OP_PING 9
+#define WEBSOCKET_OP_PONG 10
+
+/*
+ * If set causes the FIN flag to not be set on outbound
+ * frames. This enables sending multiple fragments of a single
+ * logical message.
+ *
+ * The WebSocket protocol mandates that if the FIN flag of a data
+ * frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE.
+ * The last frame must have the FIN bit set.
+ *
+ * Note that mongoose will automatically defragment incoming messages,
+ * so this flag is used only on outbound messages.
+ */
+#define WEBSOCKET_DONT_FIN 0x100
+
+/*
+ * Parse a HTTP message.
+ *
+ * `is_req` should be set to 1 if parsing request, 0 if reply.
+ *
+ * Return number of bytes parsed. If HTTP message is
+ * incomplete, `0` is returned. On parse error, negative number is returned.
+ */
+int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req);
+
+/*
+ * Search and return header `name` in parsed HTTP message `hm`.
+ * If header is not found, NULL is returned. Example:
+ *
+ *     struct mg_str *host_hdr = mg_get_http_header(hm, "Host");
+ */
+struct mg_str *mg_get_http_header(struct http_message *hm, const char *name);
+
+/*
+ * Parse HTTP header `hdr`. Find variable `var_name` and store it's value
+ * in the buffer `buf`, `buf_size`. Return 0 if variable not found, non-zero
+ * otherwise.
+ *
+ * This function is supposed to parse
+ * cookies, authentication headers, etcetera. Example (error handling omitted):
+ *
+ *     char user[20];
+ *     struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
+ *     mg_http_parse_header(hdr, "username", user, sizeof(user));
+ *
+ * Return length of the variable's value. If buffer is not large enough,
+ * or variable not found, 0 is returned.
+ */
+int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
+                         size_t buf_size);
+
+/*
+ * Parse buffer `buf`, `buf_len` that contains multipart form data chunks.
+ * Store chunk name in a `var_name`, `var_name_len` buffer.
+ * If a chunk is an uploaded file, then `file_name`, `file_name_len` is
+ * filled with an uploaded file name. `chunk`, `chunk_len`
+ * points to the chunk data.
+ *
+ * Return: number of bytes to skip to the next chunk, or 0 if there are
+ *         no more chunks.
+ *
+ * Usage example:
+ *
+ *    static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
+ *      switch(ev) {
+ *        case MG_EV_HTTP_REQUEST: {
+ *          struct http_message *hm = (struct http_message *) ev_data;
+ *          char var_name[100], file_name[100];
+ *          const char *chunk;
+ *          size_t chunk_len, n1, n2;
+ *
+ *          n1 = n2 = 0;
+ *          while ((n2 = mg_parse_multipart(hm->body.p + n1,
+ *                                          hm->body.len - n1,
+ *                                          var_name, sizeof(var_name),
+ *                                          file_name, sizeof(file_name),
+ *                                          &chunk, &chunk_len)) > 0) {
+ *            printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n",
+ *                   var_name, file_name, (int) chunk_len,
+ *                   (int) chunk_len, chunk);
+ *            n1 += n2;
+ *          }
+ *        }
+ *        break;
+ *
+ */
+size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
+                          size_t var_name_len, char *file_name,
+                          size_t file_name_len, const char **chunk,
+                          size_t *chunk_len);
+
+/*
+ * Fetch an HTTP form variable.
+ *
+ * Fetch a variable `name` from a `buf` into a buffer specified by
+ * `dst`, `dst_len`. Destination is always zero-terminated. Return length
+ * of a fetched variable. If not found, 0 is returned. `buf` must be
+ * valid url-encoded buffer. If destination is too small, `-1` is returned.
+ */
+int mg_get_http_var(const struct mg_str *, const char *, char *dst, size_t);
+
+/* Create Digest authentication header for client request. */
+int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
+                                      const char *method, const char *uri,
+                                      const char *auth_domain, const char *user,
+                                      const char *passwd);
+/*
+ * Helper function that creates outbound HTTP connection.
+ *
+ * `url` is a URL to fetch. It must be properly URL-encoded, e.g. have
+ * no spaces, etc. By default, `mg_connect_http()` sends Connection and
+ * Host headers. `extra_headers` is an extra HTTP headers to send, e.g.
+ * `"User-Agent: my-app\r\n"`.
+ * If `post_data` is NULL, then GET request is created. Otherwise, POST request
+ * is created with the specified POST data. Examples:
+ *
+ * [source,c]
+ * ----
+ *   nc1 = mg_connect_http(mgr, ev_handler_1, "http://www.google.com", NULL,
+ *                         NULL);
+ *   nc2 = mg_connect_http(mgr, ev_handler_1, "https://github.com", NULL, NULL);
+ *   nc3 = mg_connect_http(mgr, ev_handler_1, "my_server:8000/form_submit/",
+ *                         NULL, "var_1=value_1&var_2=value_2");
+ * ----
+ */
+struct mg_connection *mg_connect_http(struct mg_mgr *,
+                                      mg_event_handler_t event_handler,
+                                      const char *url,
+                                      const char *extra_headers,
+                                      const char *post_data);
+
+/*
+ * This structure defines how `mg_serve_http()` works.
+ * Best practice is to set only required settings, and leave the rest as NULL.
+ */
+struct mg_serve_http_opts {
+  /* Path to web root directory */
+  const char *document_root;
+
+  /* List of index files. Default is "" */
+  const char *index_files;
+
+  /* Path to a HTTP requests log file. Leave as NULL to disable access log. */
+  const char *access_log_file;
+
+  /*
+   * Leave as NULL to disable authentication.
+   * To enable directory protection with authentication, set this to ".htpasswd"
+   * Then, creating ".htpasswd" file in any directory automatically protects
+   * it with digest authentication.
+   * Use `mongoose` web server binary, or `htdigest` Apache utility to
+   * create/manipulate passwords file.
+   * Make sure `auth_domain` is set to a valid domain name.
+   */
+  const char *per_directory_auth_file;
+
+  /* Authorization domain (domain name of this web server) */
+  const char *auth_domain;
+
+  /*
+   * Leave as NULL to disable authentication.
+   * Normally, only selected directories in the document root are protected.
+   * If absolutely every access to the web server needs to be authenticated,
+   * regardless of the URI, set this option to the path to the passwords file.
+   * Format of that file is the same as ".htpasswd" file. Make sure that file
+   * is located outside document root to prevent people fetching it.
+   */
+  const char *global_auth_file;
+
+  /* Set to "no" to disable directory listing. Enabled by default. */
+  const char *enable_directory_listing;
+
+  /* SSI files pattern. If not set, "**.shtml$|**.shtm$" is used. */
+  const char *ssi_pattern;
+
+  /* IP ACL. By default, NULL, meaning all IPs are allowed to connect */
+  const char *ip_acl;
+
+  /* URL rewrites.
+   *
+   * Comma-separated list of `uri_pattern=file_or_directory_path` rewrites.
+   * When HTTP request is received, Mongoose constructs a file name from the
+   * requested URI by combining `document_root` and the URI. However, if the
+   * rewrite option is used and `uri_pattern` matches requested URI, then
+   * `document_root` is ignored. Instead, `file_or_directory_path` is used,
+   * which should be a full path name or a path relative to the web server's
+   * current working directory. Note that `uri_pattern`, as all Mongoose
+   * patterns, is a prefix pattern.
+   *
+   * If uri_pattern starts with `@` symbol, then Mongoose compares it with the
+   * HOST header of the request. If they are equal, Mongoose sets document root
+   * to `file_or_directory_path`, implementing virtual hosts support.
+   * Example: `@foo.com=/document/root/for/foo.com`
+   *
+   * If `uri_pattern` starts with `%` symbol, then Mongoose compares it with
+   * the listening port. If they match, then Mongoose issues a 301 redirect.
+   * For example, to redirect all HTTP requests to the
+   * HTTPS port, do `%80=https://my.site.com`. Note that the request URI is
+   * automatically appended to the redirect location.
+   */
+  const char *url_rewrites;
+
+  /* DAV document root. If NULL, DAV requests are going to fail. */
+  const char *dav_document_root;
+
+  /* DAV passwords file. If NULL, DAV requests are going to fail. */
+  const char *dav_auth_file;
+
+  /* Glob pattern for the files to hide. */
+  const char *hidden_file_pattern;
+
+  /* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */
+  const char *cgi_file_pattern;
+
+  /* If not NULL, ignore CGI script hashbang and use this interpreter */
+  const char *cgi_interpreter;
+
+  /*
+   * Comma-separated list of Content-Type overrides for path suffixes, e.g.
+   * ".txt=text/plain; charset=utf-8,.c=text/plain"
+   */
+  const char *custom_mime_types;
+
+  /*
+   * Extra HTTP headers to add to each server response.
+   * Example: to enable CORS, set this to "Access-Control-Allow-Origin: *".
+   */
+  const char *extra_headers;
+};
+
+/*
+ * Serve given HTTP request according to the `options`.
+ *
+ * Example code snippet:
+ *
+ * [source,c]
+ * .web_server.c
+ * ----
+ * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
+ *   struct http_message *hm = (struct http_message *) ev_data;
+ *   struct mg_serve_http_opts opts = { .document_root = "/var/www" };  // C99
+ *
+ *   switch (ev) {
+ *     case MG_EV_HTTP_REQUEST:
+ *       mg_serve_http(nc, hm, opts);
+ *       break;
+ *     default:
+ *       break;
+ *   }
+ * }
+ * ----
+ */
+void mg_serve_http(struct mg_connection *, struct http_message *,
+                   struct mg_serve_http_opts);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* MG_HTTP_HEADER_DEFINED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/*
+ * === JSON-RPC
+ */
+
+#ifndef MG_JSON_RPC_HEADER_DEFINED
+#define MG_JSON_RPC_HEADER_DEFINED
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* JSON-RPC request */
+struct mg_rpc_request {
+  struct json_token *message; /* Whole RPC message */
+  struct json_token *id;      /* Message ID */
+  struct json_token *method;  /* Method name */
+  struct json_token *params;  /* Method params */
+};
+
+/* JSON-RPC response */
+struct mg_rpc_reply {
+  struct json_token *message; /* Whole RPC message */
+  struct json_token *id;      /* Message ID */
+  struct json_token *result;  /* Remote call result */
+};
+
+/* JSON-RPC error */
+struct mg_rpc_error {
+  struct json_token *message;       /* Whole RPC message */
+  struct json_token *id;            /* Message ID */
+  struct json_token *error_code;    /* error.code */
+  struct json_token *error_message; /* error.message */
+  struct json_token *error_data;    /* error.data, can be NULL */
+};
+
+/*
+ * Parse JSON-RPC reply contained in `buf`, `len` into JSON tokens array
+ * `toks`, `max_toks`. If buffer contains valid reply, `reply` structure is
+ * populated. The result of RPC call is located in `reply.result`. On error,
+ * `error` structure is populated. Returns: the result of calling
+ * `parse_json(buf, len, toks, max_toks)`:
+ *
+ * On success, an offset inside `json_string` is returned
+ * where parsing has finished. On failure, a negative number is
+ * returned, one of:
+ *
+ *  - #define JSON_STRING_INVALID           -1
+ *  - #define JSON_STRING_INCOMPLETE        -2
+ *  - #define JSON_TOKEN_ARRAY_TOO_SMALL    -3
+ */
+int mg_rpc_parse_reply(const char *buf, int len, struct json_token *toks,
+                       int max_toks, struct mg_rpc_reply *,
+                       struct mg_rpc_error *);
+
+/*
+ * Create JSON-RPC request in a given buffer.
+ *
+ * Return length of the request, which
+ * can be larger then `len` that indicates an overflow.
+ * `params_fmt` format string should conform to `json_emit()` API,
+ * see https://github.com/cesanta/frozen
+ */
+int mg_rpc_create_request(char *buf, int len, const char *method,
+                          const char *id, const char *params_fmt, ...);
+
+/*
+ * Create JSON-RPC reply in a given buffer.
+ *
+ * Return length of the reply, which
+ * can be larger then `len` that indicates an overflow.
+ * `result_fmt` format string should conform to `json_emit()` API,
+ * see https://github.com/cesanta/frozen
+ */
+int mg_rpc_create_reply(char *buf, int len, const struct mg_rpc_request *req,
+                        const char *result_fmt, ...);
+
+/*
+ * Create JSON-RPC error reply in a given buffer.
+ *
+ * Return length of the error, which
+ * can be larger then `len` that indicates an overflow.
+ * `fmt` format string should conform to `json_emit()` API,
+ * see https://github.com/cesanta/frozen
+ */
+int mg_rpc_create_error(char *buf, int len, struct mg_rpc_request *req,
+                        int code, const char *message, const char *fmt, ...);
+
+/* JSON-RPC standard error codes */
+#define JSON_RPC_PARSE_ERROR (-32700)
+#define JSON_RPC_INVALID_REQUEST_ERROR (-32600)
+#define JSON_RPC_METHOD_NOT_FOUND_ERROR (-32601)
+#define JSON_RPC_INVALID_PARAMS_ERROR (-32602)
+#define JSON_RPC_INTERNAL_ERROR (-32603)
+#define JSON_RPC_SERVER_ERROR (-32000)
+
+/*
+ * Create JSON-RPC error in a given buffer.
+ *
+ * Return length of the error, which
+ * can be larger then `len` that indicates an overflow. See
+ * JSON_RPC_*_ERROR definitions for standard error values:
+ *
+ * - #define JSON_RPC_PARSE_ERROR (-32700)
+ * - #define JSON_RPC_INVALID_REQUEST_ERROR (-32600)
+ * - #define JSON_RPC_METHOD_NOT_FOUND_ERROR (-32601)
+ * - #define JSON_RPC_INVALID_PARAMS_ERROR (-32602)
+ * - #define JSON_RPC_INTERNAL_ERROR (-32603)
+ * - #define JSON_RPC_SERVER_ERROR (-32000)
+ */
+int mg_rpc_create_std_error(char *, int, struct mg_rpc_request *, int code);
+
+typedef int (*mg_rpc_handler_t)(char *buf, int len, struct mg_rpc_request *);
+
+/*
+ * Dispatches a JSON-RPC request.
+ *
+ * Parses JSON-RPC request contained in `buf`, `len`.
+ * Then, dispatches the request to the correct handler method.
+ * Valid method names should be specified in NULL
+ * terminated array `methods`, and corresponding handlers in `handlers`.
+ * Result is put in `dst`, `dst_len`. Return: length of the result, which
+ * can be larger then `dst_len` that indicates an overflow.
+ * Overflown bytes are not written to the buffer.
+ * If method is not found, an error is automatically generated.
+ */
+int mg_rpc_dispatch(const char *buf, int, char *dst, int dst_len,
+                    const char **methods, mg_rpc_handler_t *handlers);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* MG_JSON_RPC_HEADER_DEFINED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ * This software is dual-licensed: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. For the terms of this
+ * license, see .
+ *
+ * You are free to use this software under the terms of the GNU General
+ * Public License, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the GNU General Public License for more details.
+ *
+ * Alternatively, you can license this software under a commercial
+ * license, as set out in .
+ */
+
+/*
+ * === MQTT
+ */
+
+#ifndef MG_MQTT_HEADER_INCLUDED
+#define MG_MQTT_HEADER_INCLUDED
+
+
+struct mg_mqtt_message {
+  int cmd;
+  struct mg_str payload;
+  int qos;
+  uint8_t connack_ret_code; /* connack */
+  uint16_t message_id;      /* puback */
+  char *topic;
+};
+
+struct mg_mqtt_topic_expression {
+  const char *topic;
+  uint8_t qos;
+};
+
+struct mg_send_mqtt_handshake_opts {
+  unsigned char flags; /* connection flags */
+  uint16_t keep_alive;
+  const char *will_topic;
+  const char *will_message;
+  const char *user_name;
+  const char *password;
+};
+
+/* Message types */
+#define MG_MQTT_CMD_CONNECT 1
+#define MG_MQTT_CMD_CONNACK 2
+#define MG_MQTT_CMD_PUBLISH 3
+#define MG_MQTT_CMD_PUBACK 4
+#define MG_MQTT_CMD_PUBREC 5
+#define MG_MQTT_CMD_PUBREL 6
+#define MG_MQTT_CMD_PUBCOMP 7
+#define MG_MQTT_CMD_SUBSCRIBE 8
+#define MG_MQTT_CMD_SUBACK 9
+#define MG_MQTT_CMD_UNSUBSCRIBE 10
+#define MG_MQTT_CMD_UNSUBACK 11
+#define MG_MQTT_CMD_PINGREQ 12
+#define MG_MQTT_CMD_PINGRESP 13
+#define MG_MQTT_CMD_DISCONNECT 14
+
+/* MQTT event types */
+#define MG_MQTT_EVENT_BASE 200
+#define MG_EV_MQTT_CONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNECT)
+#define MG_EV_MQTT_CONNACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNACK)
+#define MG_EV_MQTT_PUBLISH (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBLISH)
+#define MG_EV_MQTT_PUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBACK)
+#define MG_EV_MQTT_PUBREC (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREC)
+#define MG_EV_MQTT_PUBREL (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREL)
+#define MG_EV_MQTT_PUBCOMP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBCOMP)
+#define MG_EV_MQTT_SUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBSCRIBE)
+#define MG_EV_MQTT_SUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBACK)
+#define MG_EV_MQTT_UNSUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBSCRIBE)
+#define MG_EV_MQTT_UNSUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBACK)
+#define MG_EV_MQTT_PINGREQ (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGREQ)
+#define MG_EV_MQTT_PINGRESP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGRESP)
+#define MG_EV_MQTT_DISCONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_DISCONNECT)
+
+/* Message flags */
+#define MG_MQTT_RETAIN 0x1
+#define MG_MQTT_DUP 0x4
+#define MG_MQTT_QOS(qos) ((qos) << 1)
+#define MG_MQTT_GET_QOS(flags) (((flags) &0x6) >> 1)
+#define MG_MQTT_SET_QOS(flags, qos) (flags) = ((flags) & ~0x6) | ((qos) << 1)
+
+/* Connection flags */
+#define MG_MQTT_CLEAN_SESSION 0x02
+#define MG_MQTT_HAS_WILL 0x04
+#define MG_MQTT_WILL_RETAIN 0x20
+#define MG_MQTT_HAS_PASSWORD 0x40
+#define MG_MQTT_HAS_USER_NAME 0x80
+#define MG_MQTT_GET_WILL_QOS(flags) (((flags) &0x18) >> 3)
+#define MG_MQTT_SET_WILL_QOS(flags, qos) \
+  (flags) = ((flags) & ~0x18) | ((qos) << 3)
+
+/* CONNACK return codes */
+#define MG_EV_MQTT_CONNACK_ACCEPTED 0
+#define MG_EV_MQTT_CONNACK_UNACCEPTABLE_VERSION 1
+#define MG_EV_MQTT_CONNACK_IDENTIFIER_REJECTED 2
+#define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE 3
+#define MG_EV_MQTT_CONNACK_BAD_AUTH 4
+#define MG_EV_MQTT_CONNACK_NOT_AUTHORIZED 5
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/*
+ * Attach built-in MQTT event handler to the given connection.
+ *
+ * The user-defined event handler will receive following extra events:
+ *
+ * - MG_EV_MQTT_CONNACK
+ * - MG_EV_MQTT_PUBLISH
+ * - MG_EV_MQTT_PUBACK
+ * - MG_EV_MQTT_PUBREC
+ * - MG_EV_MQTT_PUBREL
+ * - MG_EV_MQTT_PUBCOMP
+ * - MG_EV_MQTT_SUBACK
+ */
+void mg_set_protocol_mqtt(struct mg_connection *);
+
+/* Send MQTT handshake. */
+void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id);
+
+/* Send MQTT handshake with optional parameters. */
+void mg_send_mqtt_handshake_opt(struct mg_connection *, const char *client_id,
+                                struct mg_send_mqtt_handshake_opts);
+
+/* Publish a message to a given topic. */
+void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
+                     uint16_t message_id, int flags, const void *data,
+                     size_t len);
+
+/* Subscribe to a bunch of topics. */
+void mg_mqtt_subscribe(struct mg_connection *nc,
+                       const struct mg_mqtt_topic_expression *topics,
+                       size_t topics_len, uint16_t message_id);
+
+/* Unsubscribe from a bunch of topics. */
+void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
+                         size_t topics_len, uint16_t message_id);
+
+/* Send a DISCONNECT command. */
+void mg_mqtt_disconnect(struct mg_connection *nc);
+
+/* Send a CONNACK command with a given `return_code`. */
+void mg_mqtt_connack(struct mg_connection *, uint8_t);
+
+/* Send a PUBACK command with a given `message_id`. */
+void mg_mqtt_puback(struct mg_connection *, uint16_t);
+
+/* Send a PUBREC command with a given `message_id`. */
+void mg_mqtt_pubrec(struct mg_connection *, uint16_t);
+
+/* Send a PUBREL command with a given `message_id`. */
+void mg_mqtt_pubrel(struct mg_connection *, uint16_t);
+
+/* Send a PUBCOMP command with a given `message_id`. */
+void mg_mqtt_pubcomp(struct mg_connection *, uint16_t);
+
+/*
+ * Send a SUBACK command with a given `message_id`
+ * and a sequence of granted QoSs.
+ */
+void mg_mqtt_suback(struct mg_connection *, uint8_t *, size_t, uint16_t);
+
+/* Send a UNSUBACK command with a given `message_id`. */
+void mg_mqtt_unsuback(struct mg_connection *, uint16_t);
+
+/* Send a PINGREQ command. */
+void mg_mqtt_ping(struct mg_connection *);
+
+/* Send a PINGRESP command. */
+void mg_mqtt_pong(struct mg_connection *);
+
+/*
+ * Extract the next topic expression from a SUBSCRIBE command payload.
+ *
+ * Topic expression name will point to a string in the payload buffer.
+ * Return the pos of the next topic expression or -1 when the list
+ * of topics is exhausted.
+ */
+int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *, struct mg_str *,
+                                 uint8_t *, int);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* MG_MQTT_HEADER_INCLUDED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ * This software is dual-licensed: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. For the terms of this
+ * license, see .
+ *
+ * You are free to use this software under the terms of the GNU General
+ * Public License, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the GNU General Public License for more details.
+ *
+ * Alternatively, you can license this software under a commercial
+ * license, as set out in .
+ */
+
+/*
+ * === MQTT Broker
+ */
+
+#ifndef MG_MQTT_BROKER_HEADER_INCLUDED
+#define MG_MQTT_BROKER_HEADER_INCLUDED
+
+#ifdef MG_ENABLE_MQTT_BROKER
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#define MG_MQTT_MAX_SESSION_SUBSCRIPTIONS 512;
+
+struct mg_mqtt_broker;
+
+/* MQTT session (Broker side). */
+struct mg_mqtt_session {
+  struct mg_mqtt_broker *brk;          /* Broker */
+  struct mg_mqtt_session *next, *prev; /* mg_mqtt_broker::sessions linkage */
+  struct mg_connection *nc;            /* Connection with the client */
+  size_t num_subscriptions;            /* Size of `subscriptions` array */
+  struct mg_mqtt_topic_expression *subscriptions;
+  void *user_data; /* User data */
+};
+
+/* MQTT broker. */
+struct mg_mqtt_broker {
+  struct mg_mqtt_session *sessions; /* Session list */
+  void *user_data;                  /* User data */
+};
+
+/* Initialize a MQTT broker. */
+void mg_mqtt_broker_init(struct mg_mqtt_broker *, void *);
+
+/*
+ * Process a MQTT broker message.
+ *
+ * Listening connection expects a pointer to an initialized `mg_mqtt_broker`
+ * structure in the `user_data` field.
+ *
+ * Basic usage:
+ *
+ * [source,c]
+ * -----
+ * mg_mqtt_broker_init(&brk, NULL);
+ *
+ * if ((nc = mg_bind(&mgr, address, mg_mqtt_broker)) == NULL) {
+ *   // fail;
+ * }
+ * nc->user_data = &brk;
+ * -----
+ *
+ * New incoming connections will receive a `mg_mqtt_session` structure
+ * in the connection `user_data`. The original `user_data` will be stored
+ * in the `user_data` field of the session structure. This allows the user
+ * handler to store user data before `mg_mqtt_broker` creates the session.
+ *
+ * Since only the MG_EV_ACCEPT message is processed by the listening socket,
+ * for most events the `user_data` will thus point to a `mg_mqtt_session`.
+ */
+void mg_mqtt_broker(struct mg_connection *, int, void *);
+
+/*
+ * Iterate over all mqtt sessions connections. Example:
+ *
+ *    struct mg_mqtt_session *s;
+ *    for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
+ *       // Do something
+ *    }
+ */
+struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *,
+                                     struct mg_mqtt_session *);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* MG_ENABLE_MQTT_BROKER */
+#endif /* MG_MQTT_HEADER_INCLUDED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/*
+ * === DNS
+ */
+
+#ifndef MG_DNS_HEADER_DEFINED
+#define MG_DNS_HEADER_DEFINED
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#define MG_DNS_A_RECORD 0x01     /* Lookup IP address */
+#define MG_DNS_CNAME_RECORD 0x05 /* Lookup CNAME */
+#define MG_DNS_AAAA_RECORD 0x1c  /* Lookup IPv6 address */
+#define MG_DNS_MX_RECORD 0x0f    /* Lookup mail server for domain */
+
+#define MG_MAX_DNS_QUESTIONS 32
+#define MG_MAX_DNS_ANSWERS 32
+
+#define MG_DNS_MESSAGE 100 /* High-level DNS message event */
+
+enum mg_dns_resource_record_kind {
+  MG_DNS_INVALID_RECORD = 0,
+  MG_DNS_QUESTION,
+  MG_DNS_ANSWER
+};
+
+/* DNS resource record. */
+struct mg_dns_resource_record {
+  struct mg_str name; /* buffer with compressed name */
+  int rtype;
+  int rclass;
+  int ttl;
+  enum mg_dns_resource_record_kind kind;
+  struct mg_str rdata; /* protocol data (can be a compressed name) */
+};
+
+/* DNS message (request and response). */
+struct mg_dns_message {
+  struct mg_str pkt; /* packet body */
+  uint16_t flags;
+  uint16_t transaction_id;
+  int num_questions;
+  int num_answers;
+  struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS];
+  struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS];
+};
+
+struct mg_dns_resource_record *mg_dns_next_record(
+    struct mg_dns_message *, int, struct mg_dns_resource_record *);
+
+/*
+ * Parse the record data from a DNS resource record.
+ *
+ *  - A:     struct in_addr *ina
+ *  - AAAA:  struct in6_addr *ina
+ *  - CNAME: char buffer
+ *
+ * Returns -1 on error.
+ *
+ * TODO(mkm): MX
+ */
+int mg_dns_parse_record_data(struct mg_dns_message *,
+                             struct mg_dns_resource_record *, void *, size_t);
+
+/*
+ * Send a DNS query to the remote end.
+ */
+void mg_send_dns_query(struct mg_connection *, const char *, int);
+
+/*
+ * Insert a DNS header to an IO buffer.
+ *
+ * Return number of bytes inserted.
+ */
+int mg_dns_insert_header(struct mbuf *, size_t, struct mg_dns_message *);
+
+/*
+ * Append already encoded body from an existing message.
+ *
+ * This is useful when generating a DNS reply message which includes
+ * all question records.
+ *
+ * Return number of appened bytes.
+ */
+int mg_dns_copy_body(struct mbuf *, struct mg_dns_message *);
+
+/*
+ * Encode and append a DNS resource record to an IO buffer.
+ *
+ * The record metadata is taken from the `rr` parameter, while the name and data
+ * are taken from the parameters, encoded in the appropriate format depending on
+ * record type, and stored in the IO buffer. The encoded values might contain
+ * offsets within the IO buffer. It's thus important that the IO buffer doesn't
+ * get trimmed while a sequence of records are encoded while preparing a DNS
+ *reply.
+ *
+ * This function doesn't update the `name` and `rdata` pointers in the `rr`
+ *struct
+ * because they might be invalidated as soon as the IO buffer grows again.
+ *
+ * Return the number of bytes appened or -1 in case of error.
+ */
+int mg_dns_encode_record(struct mbuf *, struct mg_dns_resource_record *,
+                         const char *, size_t, const void *, size_t);
+
+/* Low-level: parses a DNS response. */
+int mg_parse_dns(const char *, int, struct mg_dns_message *);
+
+/*
+ * Uncompress a DNS compressed name.
+ *
+ * The containing dns message is required because the compressed encoding
+ * and reference suffixes present elsewhere in the packet.
+ *
+ * If name is less than `dst_len` characters long, the remainder
+ * of `dst` is terminated with `\0' characters. Otherwise, `dst` is not
+ *terminated.
+ *
+ * If `dst_len` is 0 `dst` can be NULL.
+ * Return the uncompressed name length.
+ */
+size_t mg_dns_uncompress_name(struct mg_dns_message *, struct mg_str *, char *,
+                              int);
+
+/*
+ * Attach built-in DNS event handler to the given listening connection.
+ *
+ * DNS event handler parses incoming UDP packets, treating them as DNS
+ * requests. If incoming packet gets successfully parsed by the DNS event
+ * handler, a user event handler will receive `MG_DNS_REQUEST` event, with
+ * `ev_data` pointing to the parsed `struct mg_dns_message`.
+ *
+ * See
+ * https://github.com/cesanta/mongoose/tree/master/examples/captive_dns_server[captive_dns_server]
+ * example on how to handle DNS request and send DNS reply.
+ */
+void mg_set_protocol_dns(struct mg_connection *);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* MG_HTTP_HEADER_DEFINED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/*
+ * === DNS server
+ *
+ * Disabled by default; enable with `-DMG_ENABLE_DNS_SERVER`.
+ */
+
+#ifndef MG_DNS_SERVER_HEADER_DEFINED
+#define MG_DNS_SERVER_HEADER_DEFINED
+
+#ifdef MG_ENABLE_DNS_SERVER
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#define MG_DNS_SERVER_DEFAULT_TTL 3600
+
+struct mg_dns_reply {
+  struct mg_dns_message *msg;
+  struct mbuf *io;
+  size_t start;
+};
+
+/*
+ * Create a DNS reply.
+ *
+ * The reply will be based on an existing query message `msg`.
+ * The query body will be appended to the output buffer.
+ * "reply + recursion allowed" will be added to the message flags and
+ * message's num_answers will be set to 0.
+ *
+ * Answer records can be appended with `mg_dns_send_reply` or by lower
+ * level function defined in the DNS API.
+ *
+ * In order to send the reply use `mg_dns_send_reply`.
+ * It's possible to use a connection's send buffer as reply buffers,
+ * and it will work for both UDP and TCP connections.
+ *
+ * Example:
+ *
+ * [source,c]
+ * -----
+ * reply = mg_dns_create_reply(&nc->send_mbuf, msg);
+ * for (i = 0; i < msg->num_questions; i++) {
+ *   rr = &msg->questions[i];
+ *   if (rr->rtype == MG_DNS_A_RECORD) {
+ *     mg_dns_reply_record(&reply, rr, 3600, &dummy_ip_addr, 4);
+ *   }
+ * }
+ * mg_dns_send_reply(nc, &reply);
+ * -----
+ */
+struct mg_dns_reply mg_dns_create_reply(struct mbuf *, struct mg_dns_message *);
+
+/*
+ * Append a DNS reply record to the IO buffer and to the DNS message.
+ *
+ * The message num_answers field will be incremented. It's caller's duty
+ * to ensure num_answers is propertly initialized.
+ *
+ * Returns -1 on error.
+ */
+int mg_dns_reply_record(struct mg_dns_reply *, struct mg_dns_resource_record *,
+                        const char *, int, int, const void *, size_t);
+
+/*
+ * Send a DNS reply through a connection.
+ *
+ * The DNS data is stored in an IO buffer pointed by reply structure in `r`.
+ * This function mutates the content of that buffer in order to ensure that
+ * the DNS header reflects size and flags of the mssage, that might have been
+ * updated either with `mg_dns_reply_record` or by direct manipulation of
+ * `r->message`.
+ *
+ * Once sent, the IO buffer will be trimmed unless the reply IO buffer
+ * is the connection's send buffer and the connection is not in UDP mode.
+ */
+void mg_dns_send_reply(struct mg_connection *, struct mg_dns_reply *);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* MG_ENABLE_DNS_SERVER */
+#endif /* MG_HTTP_HEADER_DEFINED */
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/*
+ * === Asynchronouns DNS resolver
+ */
+
+#ifndef MG_RESOLV_HEADER_DEFINED
+#define MG_RESOLV_HEADER_DEFINED
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+typedef void (*mg_resolve_callback_t)(struct mg_dns_message *, void *);
+
+/* Options for `mg_resolve_async_opt`. */
+struct mg_resolve_async_opts {
+  const char *nameserver_url;
+  int max_retries;    /* defaults to 2 if zero */
+  int timeout;        /* in seconds; defaults to 5 if zero */
+  int accept_literal; /* pseudo-resolve literal ipv4 and ipv6 addrs */
+  int only_literal;   /* only resolves literal addrs; sync cb invocation */
+};
+
+/* See `mg_resolve_async_opt()` */
+int mg_resolve_async(struct mg_mgr *, const char *, int, mg_resolve_callback_t,
+                     void *data);
+
+/*
+ * Resolved a DNS name asynchronously.
+ *
+ * Upon successful resolution, the user callback will be invoked
+ * with the full DNS response message and a pointer to the user's
+ * context `data`.
+ *
+ * In case of timeout while performing the resolution the callback
+ * will receive a NULL `msg`.
+ *
+ * The DNS answers can be extracted with `mg_next_record` and
+ * `mg_dns_parse_record_data`:
+ *
+ * [source,c]
+ * ----
+ * struct in_addr ina;
+ * struct mg_dns_resource_record *rr = mg_next_record(msg, MG_DNS_A_RECORD,
+ *   NULL);
+ * mg_dns_parse_record_data(msg, rr, &ina, sizeof(ina));
+ * ----
+ */
+int mg_resolve_async_opt(struct mg_mgr *, const char *, int,
+                         mg_resolve_callback_t, void *data,
+                         struct mg_resolve_async_opts opts);
+
+/*
+ * Resolve a name from `/etc/hosts`.
+ *
+ * Returns 0 on success, -1 on failure.
+ */
+int mg_resolve_from_hosts_file(const char *host, union socket_address *usa);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* MG_RESOLV_HEADER_DEFINED */
+/*
+ * Copyright (c) 2015 Cesanta Software Limited
+ * All rights reserved
+ * This software is dual-licensed: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. For the terms of this
+ * license, see .
+ *
+ * You are free to use this software under the terms of the GNU General
+ * Public License, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the GNU General Public License for more details.
+ *
+ * Alternatively, you can license this software under a commercial
+ * license, as set out in .
+ */
+
+/*
+ * === CoAP
+ *
+ * CoAP message format:
+ *
+ *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
+ *    |Ver| T | TKL | Code | Message ID | Token (if any, TKL bytes) ...
+ *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
+ *    | Options (if any) ...            |1 1 1 1 1 1 1 1| Payload (if any) ...
+ *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
+ */
+
+#ifndef MG_COAP_HEADER_INCLUDED
+#define MG_COAP_HEADER_INCLUDED
+
+#ifdef MG_ENABLE_COAP
+
+#define MG_COAP_MSG_TYPE_FIELD 0x2
+#define MG_COAP_CODE_CLASS_FIELD 0x4
+#define MG_COAP_CODE_DETAIL_FIELD 0x8
+#define MG_COAP_MSG_ID_FIELD 0x10
+#define MG_COAP_TOKEN_FIELD 0x20
+#define MG_COAP_OPTIOMG_FIELD 0x40
+#define MG_COAP_PAYLOAD_FIELD 0x80
+
+#define MG_COAP_ERROR 0x10000
+#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)
+#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)
+#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)
+#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)
+
+#define MG_COAP_MSG_CON 0
+#define MG_COAP_MSG_NOC 1
+#define MG_COAP_MSG_ACK 2
+#define MG_COAP_MSG_RST 3
+#define MG_COAP_MSG_MAX 3
+
+#define MG_COAP_CODECLASS_REQUEST 0
+#define MG_COAP_CODECLASS_RESP_OK 2
+#define MG_COAP_CODECLASS_CLIENT_ERR 4
+#define MG_COAP_CODECLASS_SRV_ERR 5
+
+#define MG_COAP_EVENT_BASE 300
+#define MG_EV_COAP_CON (MG_COAP_EVENT_BASE + MG_COAP_MSG_CON)
+#define MG_EV_COAP_NOC (MG_COAP_EVENT_BASE + MG_COAP_MSG_NOC)
+#define MG_EV_COAP_ACK (MG_COAP_EVENT_BASE + MG_COAP_MSG_ACK)
+#define MG_EV_COAP_RST (MG_COAP_EVENT_BASE + MG_COAP_MSG_RST)
+
+/*
+ * CoAP options.
+ * Use mg_coap_add_option and mg_coap_free_options
+ * for creation and destruction.
+ */
+struct mg_coap_option {
+  struct mg_coap_option *next;
+  uint32_t number;
+  struct mg_str value;
+};
+
+/* CoAP message. See RFC 7252 for details. */
+struct mg_coap_message {
+  uint32_t flags;
+  uint8_t msg_type;
+  uint8_t code_class;
+  uint8_t code_detail;
+  uint16_t msg_id;
+  struct mg_str token;
+  struct mg_coap_option *options;
+  struct mg_str payload;
+  struct mg_coap_option *optiomg_tail;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* Set CoAP protocol handler - trigger CoAP specific events */
+int mg_set_protocol_coap(struct mg_connection *nc);
+
+/*
+ * Add new option to mg_coap_message structure.
+ * Returns pointer to the newly created option.
+ */
+struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
+                                          uint32_t number, char *value,
+                                          size_t len);
+
+/*
+ * Free the memory allocated for options,
+ * if cm paramater doesn't contain any option does nothing.
+ */
+void mg_coap_free_options(struct mg_coap_message *cm);
+
+/*
+ * Compose CoAP message from `mg_coap_message`
+ * and send it into `nc` connection.
+ * Return 0 on success. On error, it is a bitmask:
+ *
+ * - #define MG_COAP_ERROR 0x10000
+ * - #define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)
+ * - #define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)
+ * - #define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)
+ * - #define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)
+ */
+uint32_t mg_coap_send_message(struct mg_connection *nc,
+                              struct mg_coap_message *cm);
+
+/*
+ * Compose CoAP acknowledgement from `mg_coap_message`
+ * and send it into `nc` connection.
+ * Return value: see `mg_coap_send_message()`
+ */
+uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id);
+
+/*
+ * Parse COAP message and fills mg_coap_message and returns cm->flags.
+ * This is a helper function.
+ *
+ * NOTE: usually CoAP work over UDP, so lack of data means format error,
+ * but in theory it is possible to use CoAP over TCP (according to RFC)
+ *
+ * The caller have to check results and treat COAP_NOT_ENOUGH_DATA according to
+ * underlying protocol:
+ *
+ * - in case of UDP COAP_NOT_ENOUGH_DATA means COAP_FORMAT_ERROR,
+ * - in case of TCP client can try to receive more data
+ *
+ * Return value: see `mg_coap_send_message()`
+ */
+uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm);
+
+/*
+ * Composes CoAP message from mg_coap_message structure.
+ * This is a helper function.
+ * Return value: see `mg_coap_send_message()`
+ */
+uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* MG_ENABLE_COAP */
+
+#endif /* MG_COAP_HEADER_INCLUDED */
diff --git a/spectrum_manager/src/server.cpp b/spectrum_manager/src/server.cpp
index 510fb3a4..39b7c1e2 100644
--- a/spectrum_manager/src/server.cpp
+++ b/spectrum_manager/src/server.cpp
@@ -122,10 +122,9 @@ padding-left: 15px;\
 }
 
 
-static void get_qsvar(const struct mg_request_info *request_info,
+static void get_qsvar(const struct http_message *hm,
                       const char *name, char *dst, size_t dst_len) {
-  const char *qs = request_info->query_string;
-  mg_get_var(qs, strlen(qs == NULL ? "" : qs), name, dst, dst_len);
+	mg_get_http_var(&hm->query_string, name, dst, dst_len);
 }
 
 static void my_strlcpy(char *dst, const char *src, size_t len) {
@@ -138,7 +137,11 @@ static void my_strlcpy(char *dst, const char *src, size_t len) {
 // This is why all communication must be SSL-ed.
 static void generate_session_id(char *buf, const char *random,
                                 const char *user) {
-  mg_md5(buf, random, user, NULL);
+  cs_md5(buf, random, strlen(random), user, strlen(user), NULL);
+}
+
+static void _event_handler(struct mg_connection *nc, int ev, void *p) {
+	static_cast(nc->mgr->user_data)->event_handler(nc, ev, p);
 }
 
 Server::Server(ManagerConfig *config) {
@@ -146,30 +149,19 @@ Server::Server(ManagerConfig *config) {
 	m_config = config;
 	m_user = CONFIG_STRING(m_config, "service.admin_username");
 	m_password = CONFIG_STRING(m_config, "service.admin_password");
+
+	mg_mgr_init(&m_mgr, this);
+	m_nc = mg_bind(&m_mgr, std::string(":" + boost::lexical_cast(CONFIG_INT(m_config, "service.port"))).c_str(), &_event_handler);
+	mg_set_protocol_http_websocket(m_nc);
 }
 
 Server::~Server() {
-	if (ctx) {
-		mg_stop(ctx);
-	}
-}
-
-
-static void *_event_handler(enum mg_event event, struct mg_connection *conn) {
-	const struct mg_request_info *request_info = mg_get_request_info(conn);
-	return static_cast(request_info->user_data)->event_handler(event, conn);
+	mg_mgr_free(&m_mgr);
 }
 
 bool Server::start() {
-	const char *options[] = {
-		"listening_ports", boost::lexical_cast(CONFIG_INT(m_config, "service.port")).c_str(),
-		"num_threads", "1",
-		NULL
-	};
-
-	// Setup and start Mongoose
-	if ((ctx = mg_start(&_event_handler, this, options)) == NULL) {
-		return false;
+	for (;;) {
+		mg_mgr_poll(&m_mgr, 1000);
 	}
 
 	return true;
@@ -193,10 +185,12 @@ Server::session *Server::new_session(const char *user) {
 }
 
 // Get session object for the connection. Caller must hold the lock.
-Server::session *Server::get_session(const struct mg_connection *conn) {
+Server::session *Server::get_session(struct http_message *hm) {
 	time_t now = time(NULL);
-	char session_id[33];
-	mg_get_cookie(conn, "session", session_id, sizeof(session_id));
+	char session_id[255];
+	struct mg_str *hdr = mg_get_http_header(hm, "Cookie");
+	int len = mg_http_parse_header(hdr, "session", session_id, sizeof(session_id));
+	session_id[len] = 0;
 
 	if (sessions.find(session_id) == sessions.end()) {
 		return NULL;
@@ -209,13 +203,13 @@ Server::session *Server::get_session(const struct mg_connection *conn) {
 	return NULL;
 }
 
-void Server::authorize(struct mg_connection *conn, const struct mg_request_info *request_info) {
+void Server::authorize(struct mg_connection *conn, struct http_message *hm) {
 	char user[255], password[255];
 	Server::session *session;
 
 	// Fetch user name and password.
-	get_qsvar(request_info, "user", user, sizeof(user));
-	get_qsvar(request_info, "password", password, sizeof(password));
+	get_qsvar(hm, "user", user, sizeof(user));
+	get_qsvar(hm, "password", password, sizeof(password));
 
 	if (check_password(user, password) && (session = new_session(user)) != NULL) {
 		std::cout << "User authorized\n";
@@ -238,27 +232,27 @@ void Server::authorize(struct mg_connection *conn, const struct mg_request_info
 			session->session_id, session->user);
 	} else {
 		// Authentication failure, redirect to login.
-		redirect_to(conn, request_info, "/login");
+		redirect_to(conn, hm, "/login");
 	}
 }
 
-bool Server::is_authorized(const struct mg_connection *conn, const struct mg_request_info *request_info) {
+bool Server::is_authorized(const struct mg_connection *conn, struct http_message *hm) {
 	Server::session *session;
 	char valid_id[33];
 	bool authorized = false;
 
 	// Always authorize accesses to login page and to authorize URI
-	if (!strcmp(request_info->uri, "/login") ||
-		!strcmp(request_info->uri, "/authorize")) {
+	if (!mg_vcmp(&hm->uri, "/login") ||
+		!mg_vcmp(&hm->uri, "/authorize")) {
 		return true;
 	}
 
 // 	pthread_rwlock_rdlock(&rwlock);
-	if ((session = get_session(conn)) != NULL) {
+	if ((session = get_session(hm)) != NULL) {
 		generate_session_id(valid_id, session->random, session->user);
 		if (strcmp(valid_id, session->session_id) == 0) {
-		session->expire = time(0) + SESSION_TTL;
-		authorized = true;
+			session->expire = time(0) + SESSION_TTL;
+			authorized = true;
 		}
 	}
 // 	pthread_rwlock_unlock(&rwlock);
@@ -266,14 +260,13 @@ bool Server::is_authorized(const struct mg_connection *conn, const struct mg_req
 	return authorized;
 }
 
-void Server::redirect_to(struct mg_connection *conn, const struct mg_request_info *request_info, const char *where) {
+void Server::redirect_to(struct mg_connection *conn, struct http_message *hm, const char *where) {
 	mg_printf(conn, "HTTP/1.1 302 Found\r\n"
-		"Set-Cookie: original_url=%s\r\n"
-		"Location: %s\r\n\r\n",
-		request_info->uri, where);
+		"Set-Cookie: original_url=/\r\n"
+		"Location: %s\r\n\r\n", where);
 }
 
-void Server::print_html(struct mg_connection *conn, const struct mg_request_info *request_info, const std::string &html) {
+void Server::print_html(struct mg_connection *conn, struct http_message *hm, const std::string &html) {
 	mg_printf(conn,
 			"HTTP/1.1 200 OK\r\n"
 			"Content-Type: text/html\r\n"
@@ -283,7 +276,7 @@ void Server::print_html(struct mg_connection *conn, const struct mg_request_info
 			(int) html.size(), html.c_str());
 }
 
-void Server::serve_login(struct mg_connection *conn, const struct mg_request_info *request_info) {
+void Server::serve_login(struct mg_connection *conn, struct http_message *hm) {
 	std::string html= "\
  \
@@ -305,13 +298,13 @@ void Server::serve_login(struct mg_connection *conn, const struct mg_request_inf
   \
 ";
 
-	print_html(conn, request_info, html);
+	print_html(conn, hm, html);
 }
 
-void Server::serve_onlineusers(struct mg_connection *conn, const struct mg_request_info *request_info) {
+void Server::serve_onlineusers(struct mg_connection *conn, struct http_message *hm) {
 	std::string html = get_header();
 	char jid[255];
-	get_qsvar(request_info, "jid", jid, sizeof(jid));
+	get_qsvar(hm, "jid", jid, sizeof(jid));
 
 	html += std::string("

") + jid + " online users

Name" + "Modified" + "Size

"; @@ -334,15 +327,15 @@ void Server::serve_onlineusers(struct mg_connection *conn, const struct mg_reque html += "
JIDCommand
Back to main page"; html += ""; - print_html(conn, request_info, html); + print_html(conn, hm, html); } -void Server::serve_cmd(struct mg_connection *conn, const struct mg_request_info *request_info) { +void Server::serve_cmd(struct mg_connection *conn, struct http_message *hm) { std::string html = get_header(); char jid[255]; - get_qsvar(request_info, "jid", jid, sizeof(jid)); + get_qsvar(hm, "jid", jid, sizeof(jid)); char cmd[4096]; - get_qsvar(request_info, "cmd", cmd, sizeof(cmd)); + get_qsvar(hm, "cmd", cmd, sizeof(cmd)); html += std::string("

") + jid + " command result

"; @@ -360,33 +353,33 @@ void Server::serve_cmd(struct mg_connection *conn, const struct mg_request_info html += "Back to main page"; html += ""; - print_html(conn, request_info, html); + print_html(conn, hm, html); } -void Server::serve_start(struct mg_connection *conn, const struct mg_request_info *request_info) { +void Server::serve_start(struct mg_connection *conn, struct http_message *hm) { std::string html= get_header() ; char jid[255]; - get_qsvar(request_info, "jid", jid, sizeof(jid)); + get_qsvar(hm, "jid", jid, sizeof(jid)); start_instances(m_config, jid); html += "" + get_response() + "
Back to main page"; html += ""; - print_html(conn, request_info, html); + print_html(conn, hm, html); } -void Server::serve_stop(struct mg_connection *conn, const struct mg_request_info *request_info) { +void Server::serve_stop(struct mg_connection *conn, struct http_message *hm) { std::string html= get_header(); char jid[255]; - get_qsvar(request_info, "jid", jid, sizeof(jid)); + get_qsvar(hm, "jid", jid, sizeof(jid)); stop_instances(m_config, jid); html += "" + get_response() + "
Back to main page"; html += ""; - print_html(conn, request_info, html); + print_html(conn, hm, html); } -void Server::serve_root(struct mg_connection *conn, const struct mg_request_info *request_info) { +void Server::serve_root(struct mg_connection *conn, struct http_message *hm) { std::vector list = show_list(m_config, false); std::string html= get_header() + "

List of instances

"; @@ -419,45 +412,34 @@ void Server::serve_root(struct mg_connection *conn, const struct mg_request_info } html += "
JIDStatusCommandRun command
"; - print_html(conn, request_info, html); + print_html(conn, hm, html); } -void *Server::event_handler(enum mg_event event, struct mg_connection *conn) { - const struct mg_request_info *request_info = mg_get_request_info(conn); - void *processed = (void *) 0x1; +void Server::event_handler(struct mg_connection *conn, int ev, void *p) { + struct http_message *hm = (struct http_message *) p; - if (event == MG_NEW_REQUEST) { - if (!is_authorized(conn, request_info)) { - redirect_to(conn, request_info, "/login"); - } else if (strcmp(request_info->uri, "/authorize") == 0) { - authorize(conn, request_info); - } else if (strcmp(request_info->uri, "/login") == 0) { - serve_login(conn, request_info); - } else if (strcmp(request_info->uri, "/") == 0) { - serve_root(conn, request_info); - } else if (strcmp(request_info->uri, "/onlineusers") == 0) { - serve_onlineusers(conn, request_info); - } else if (strcmp(request_info->uri, "/cmd") == 0) { - serve_cmd(conn, request_info); - } else if (strcmp(request_info->uri, "/start") == 0) { - serve_start(conn, request_info); - } else if (strcmp(request_info->uri, "/stop") == 0) { - serve_stop(conn, request_info); - } else { - // No suitable handler found, mark as not processed. Mongoose will - // try to serve the request. - processed = NULL; - } + if (ev != MG_EV_HTTP_REQUEST) { + return; } - else if (event == MG_EVENT_LOG) { - // Called by Mongoose's cry() - std::cerr << "Mongoose error: " << request_info->log_message << "\n"; - } - else { - processed = NULL; + if (!is_authorized(conn, hm)) { + redirect_to(conn, hm, "/login"); + } else if (mg_vcmp(&hm->uri, "/authorize") == 0) { + authorize(conn, hm); + } else if (mg_vcmp(&hm->uri, "/login") == 0) { + serve_login(conn, hm); + } else if (mg_vcmp(&hm->uri, "/") == 0) { + serve_root(conn, hm); + } else if (mg_vcmp(&hm->uri, "/onlineusers") == 0) { + serve_onlineusers(conn, hm); + } else if (mg_vcmp(&hm->uri, "/cmd") == 0) { + serve_cmd(conn, hm); + } else if (mg_vcmp(&hm->uri, "/start") == 0) { + serve_start(conn, hm); + } else if (mg_vcmp(&hm->uri, "/stop") == 0) { + serve_stop(conn, hm); } - return processed; + conn->flags |= MG_F_SEND_AND_CLOSE; } diff --git a/spectrum_manager/src/server.h b/spectrum_manager/src/server.h index 4d202040..ecd52fa5 100644 --- a/spectrum_manager/src/server.h +++ b/spectrum_manager/src/server.h @@ -48,30 +48,32 @@ class Server { bool start(); - void *event_handler(enum mg_event event, struct mg_connection *conn); + void event_handler(struct mg_connection *nc, int ev, void *p); private: - void serve_login(struct mg_connection *conn, const struct mg_request_info *request_info); - void serve_root(struct mg_connection *conn, const struct mg_request_info *request_info); - void serve_start(struct mg_connection *conn, const struct mg_request_info *request_info); - void serve_stop(struct mg_connection *conn, const struct mg_request_info *request_info); - void serve_onlineusers(struct mg_connection *conn, const struct mg_request_info *request_info); - void serve_cmd(struct mg_connection *conn, const struct mg_request_info *request_info); - void print_html(struct mg_connection *conn, const struct mg_request_info *request_info, const std::string &html); + void serve_login(struct mg_connection *conn, struct http_message *hm); + void serve_root(struct mg_connection *conn, struct http_message *hm); + void serve_start(struct mg_connection *conn, struct http_message *hm); + void serve_stop(struct mg_connection *conn, struct http_message *hm); + void serve_onlineusers(struct mg_connection *conn, struct http_message *hm); + void serve_cmd(struct mg_connection *conn, struct http_message *hm); + void print_html(struct mg_connection *conn, struct http_message *hm, const std::string &html); private: bool check_password(const char *user, const char *password); session *new_session(const char *user); - session *get_session(const struct mg_connection *conn); + session *get_session(struct http_message *hm); - void authorize(struct mg_connection *conn, const struct mg_request_info *request_info); + void authorize(struct mg_connection *conn, struct http_message *hm); - bool is_authorized(const struct mg_connection *conn, const struct mg_request_info *request_info); + bool is_authorized(const struct mg_connection *conn, struct http_message *hm); - void redirect_to(struct mg_connection *conn, const struct mg_request_info *request_info, const char *where); + void redirect_to(struct mg_connection *conn, struct http_message *hm, const char *where); private: - struct mg_context *ctx; + struct mg_mgr m_mgr; + struct mg_connection *m_nc; + std::map sessions; std::string m_user; std::string m_password;