+++ /dev/null
-// Copyright (c) 2004-2011 Sergey Lyubka\r
-//\r
-// Permission is hereby granted, free of charge, to any person obtaining a copy\r
-// of this software and associated documentation files (the "Software"), to deal\r
-// in the Software without restriction, including without limitation the rights\r
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
-// copies of the Software, and to permit persons to whom the Software is\r
-// furnished to do so, subject to the following conditions:\r
-//\r
-// The above copyright notice and this permission notice shall be included in\r
-// all copies or substantial portions of the Software.\r
-//\r
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
-// THE SOFTWARE.\r
-\r
-#if defined(_WIN32)\r
-#define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005\r
-#else\r
-#define _XOPEN_SOURCE 600 // For flockfile() on Linux\r
-#define _LARGEFILE_SOURCE // Enable 64-bit file offsets\r
-#define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++\r
-#define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX\r
-#endif\r
-\r
-#if defined(__SYMBIAN32__)\r
-#define NO_SSL // SSL is not supported\r
-#define NO_CGI // CGI is not supported\r
-#define PATH_MAX FILENAME_MAX\r
-#endif // __SYMBIAN32__\r
-\r
-#ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE\r
-#include <sys/types.h>\r
-#include <sys/stat.h>\r
-#include <errno.h>\r
-#include <signal.h>\r
-#include <fcntl.h>\r
-#endif // !_WIN32_WCE\r
-\r
-#include <time.h>\r
-#include <stdlib.h>\r
-#include <stdarg.h>\r
-#include <assert.h>\r
-#include <string.h>\r
-#include <ctype.h>\r
-#include <limits.h>\r
-#include <stddef.h>\r
-#include <stdio.h>\r
-\r
-#if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific\r
-#define _WIN32_WINNT 0x0400 // To make it link in VS2005\r
-#include <windows.h>\r
-\r
-#ifndef PATH_MAX\r
-#define PATH_MAX MAX_PATH\r
-#endif\r
-\r
-#ifndef _WIN32_WCE\r
-#include <process.h>\r
-#include <direct.h>\r
-#include <io.h>\r
-#else // _WIN32_WCE\r
-#include <winsock2.h>\r
-#include <ws2tcpip.h>\r
-#define NO_CGI // WinCE has no pipes\r
-\r
-typedef long off_t;\r
-#define BUFSIZ 4096\r
-\r
-#define errno GetLastError()\r
-#define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)\r
-#endif // _WIN32_WCE\r
-\r
-#define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \\r
- ((uint64_t)((uint32_t)(hi))) << 32))\r
-#define RATE_DIFF 10000000 // 100 nsecs\r
-#define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)\r
-#define SYS2UNIX_TIME(lo, hi) \\r
- (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)\r
-\r
-// Visual Studio 6 does not know __func__ or __FUNCTION__\r
-// The rest of MS compilers use __FUNCTION__, not C99 __func__\r
-// Also use _strtoui64 on modern M$ compilers\r
-#if defined(_MSC_VER) && _MSC_VER < 1300\r
-#define STRX(x) #x\r
-#define STR(x) STRX(x)\r
-#define __func__ "line " STR(__LINE__)\r
-#define strtoull(x, y, z) strtoul(x, y, z)\r
-#define strtoll(x, y, z) strtol(x, y, z)\r
-#else\r
-#define __func__ __FUNCTION__\r
-#define strtoull(x, y, z) _strtoui64(x, y, z)\r
-#define strtoll(x, y, z) _strtoi64(x, y, z)\r
-#endif // _MSC_VER\r
-\r
-#define ERRNO GetLastError()\r
-#define NO_SOCKLEN_T\r
-#define SSL_LIB "ssleay32.dll"\r
-#define CRYPTO_LIB "libeay32.dll"\r
-#define DIRSEP '\\'\r
-#define IS_DIRSEP_CHAR(c) ((c) == '/' || (c) == '\\')\r
-#define O_NONBLOCK 0\r
-#if !defined(EWOULDBLOCK)\r
-#define EWOULDBLOCK WSAEWOULDBLOCK\r
-#endif // !EWOULDBLOCK\r
-#define _POSIX_\r
-#define INT64_FMT "I64d"\r
-\r
-#define WINCDECL __cdecl\r
-#define SHUT_WR 1\r
-#define snprintf _snprintf\r
-#define vsnprintf _vsnprintf\r
-#define mg_sleep(x) Sleep(x)\r
-\r
-#define pipe(x) _pipe(x, BUFSIZ, _O_BINARY)\r
-#define popen(x, y) _popen(x, y)\r
-#define pclose(x) _pclose(x)\r
-#define close(x) _close(x)\r
-#define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))\r
-#define RTLD_LAZY 0\r
-#define fseeko(x, y, z) fseek((x), (y), (z))\r
-#define fdopen(x, y) _fdopen((x), (y))\r
-#define write(x, y, z) _write((x), (y), (unsigned) z)\r
-#define read(x, y, z) _read((x), (y), (unsigned) z)\r
-#define flockfile(x) EnterCriticalSection(&global_log_file_lock)\r
-#define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)\r
-\r
-#if !defined(fileno)\r
-#define fileno(x) _fileno(x)\r
-#endif // !fileno MINGW #defines fileno\r
-\r
-typedef HANDLE pthread_mutex_t;\r
-typedef struct {HANDLE signal, broadcast;} pthread_cond_t;\r
-typedef DWORD pthread_t;\r
-#define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.\r
-\r
-struct timespec {\r
- long tv_nsec;\r
- long tv_sec;\r
-};\r
-\r
-static int pthread_mutex_lock(pthread_mutex_t *);\r
-static int pthread_mutex_unlock(pthread_mutex_t *);\r
-static FILE *mg_fopen(const char *path, const char *mode);\r
-\r
-#if defined(HAVE_STDINT)\r
-#include <stdint.h>\r
-#else\r
-typedef unsigned int uint32_t;\r
-typedef unsigned short uint16_t;\r
-typedef unsigned __int64 uint64_t;\r
-typedef __int64 int64_t;\r
-#define INT64_MAX 9223372036854775807\r
-#endif // HAVE_STDINT\r
-\r
-// POSIX dirent interface\r
-struct dirent {\r
- char d_name[PATH_MAX];\r
-};\r
-\r
-typedef struct DIR {\r
- HANDLE handle;\r
- WIN32_FIND_DATAW info;\r
- struct dirent result;\r
-} DIR;\r
-\r
-#else // UNIX specific\r
-#include <sys/wait.h>\r
-#include <sys/socket.h>\r
-#include <sys/select.h>\r
-#include <netinet/in.h>\r
-#include <arpa/inet.h>\r
-#include <sys/time.h>\r
-#include <stdint.h>\r
-#include <inttypes.h>\r
-#include <netdb.h>\r
-\r
-#include <pwd.h>\r
-#include <unistd.h>\r
-#include <dirent.h>\r
-#if !defined(NO_SSL_DL) && !defined(NO_SSL)\r
-#include <dlfcn.h>\r
-#endif\r
-#include <pthread.h>\r
-#if defined(__MACH__)\r
-#define SSL_LIB "libssl.dylib"\r
-#define CRYPTO_LIB "libcrypto.dylib"\r
-#else\r
-#if !defined(SSL_LIB)\r
-#define SSL_LIB "libssl.so"\r
-#endif\r
-#if !defined(CRYPTO_LIB)\r
-#define CRYPTO_LIB "libcrypto.so"\r
-#endif\r
-#endif\r
-#define DIRSEP '/'\r
-#define IS_DIRSEP_CHAR(c) ((c) == '/')\r
-#ifndef O_BINARY\r
-#define O_BINARY 0\r
-#endif // O_BINARY\r
-#define closesocket(a) close(a)\r
-#define mg_fopen(x, y) fopen(x, y)\r
-#define mg_mkdir(x, y) mkdir(x, y)\r
-#define mg_remove(x) remove(x)\r
-#define mg_rename(x, y) rename(x, y)\r
-#define mg_sleep(x) usleep((x) * 1000)\r
-#define ERRNO errno\r
-#define INVALID_SOCKET (-1)\r
-#define INT64_FMT PRId64\r
-typedef int SOCKET;\r
-#define WINCDECL\r
-\r
-#endif // End of Windows and UNIX specific includes\r
-\r
-#include "mongoose.h"\r
-\r
-#define MONGOOSE_VERSION "3.2"\r
-#define PASSWORDS_FILE_NAME ".htpasswd"\r
-#define CGI_ENVIRONMENT_SIZE 4096\r
-#define MAX_CGI_ENVIR_VARS 64\r
-#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))\r
-\r
-#ifdef _WIN32\r
-static CRITICAL_SECTION global_log_file_lock;\r
-static pthread_t pthread_self(void) {\r
- return GetCurrentThreadId();\r
-}\r
-#endif // _WIN32\r
-\r
-#if defined(DEBUG)\r
-#define DEBUG_TRACE(x) do { \\r
- flockfile(stdout); \\r
- printf("*** %lu.%p.%s.%d: ", \\r
- (unsigned long) time(NULL), (void *) pthread_self(), \\r
- __func__, __LINE__); \\r
- printf x; \\r
- putchar('\n'); \\r
- fflush(stdout); \\r
- funlockfile(stdout); \\r
-} while (0)\r
-#else\r
-#define DEBUG_TRACE(x)\r
-#endif // DEBUG\r
-\r
-// Darwin prior to 7.0 and Win32 do not have socklen_t\r
-#ifdef NO_SOCKLEN_T\r
-typedef int socklen_t;\r
-#endif // NO_SOCKLEN_T\r
-\r
-#if !defined(MSG_NOSIGNAL)\r
-#define MSG_NOSIGNAL 0\r
-#endif\r
-\r
-typedef void * (*mg_thread_func_t)(void *);\r
-\r
-static const char *http_500_error = "Internal Server Error";\r
-\r
-// Snatched from OpenSSL includes. I put the prototypes here to be independent\r
-// from the OpenSSL source installation. Having this, mongoose + SSL can be\r
-// built on any system with binary SSL libraries installed.\r
-typedef struct ssl_st SSL;\r
-typedef struct ssl_method_st SSL_METHOD;\r
-typedef struct ssl_ctx_st SSL_CTX;\r
-\r
-#define SSL_ERROR_WANT_READ 2\r
-#define SSL_ERROR_WANT_WRITE 3\r
-#define SSL_FILETYPE_PEM 1\r
-#define CRYPTO_LOCK 1\r
-\r
-#if defined(NO_SSL_DL)\r
-extern void SSL_free(SSL *);\r
-extern int SSL_accept(SSL *);\r
-extern int SSL_connect(SSL *);\r
-extern int SSL_read(SSL *, void *, int);\r
-extern int SSL_write(SSL *, const void *, int);\r
-extern int SSL_get_error(const SSL *, int);\r
-extern int SSL_set_fd(SSL *, int);\r
-extern SSL *SSL_new(SSL_CTX *);\r
-extern SSL_CTX *SSL_CTX_new(SSL_METHOD *);\r
-extern SSL_METHOD *SSLv23_server_method(void);\r
-extern int SSL_library_init(void);\r
-extern void SSL_load_error_strings(void);\r
-extern int SSL_CTX_use_PrivateKey_file(SSL_CTX *, const char *, int);\r
-extern int SSL_CTX_use_certificate_file(SSL_CTX *, const char *, int);\r
-extern int SSL_CTX_use_certificate_chain_file(SSL_CTX *, const char *);\r
-extern void SSL_CTX_set_default_passwd_cb(SSL_CTX *, mg_callback_t);\r
-extern void SSL_CTX_free(SSL_CTX *);\r
-extern unsigned long ERR_get_error(void);\r
-extern char *ERR_error_string(unsigned long, char *);\r
-extern int CRYPTO_num_locks(void);\r
-extern void CRYPTO_set_locking_callback(void (*)(int, int, const char *, int));\r
-extern void CRYPTO_set_id_callback(unsigned long (*)(void));\r
-#else\r
-// Dynamically loaded SSL functionality\r
-struct ssl_func {\r
- const char *name; // SSL function name\r
- void (*ptr)(void); // Function pointer\r
-};\r
-\r
-#define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)\r
-#define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)\r
-#define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)\r
-#define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)\r
-#define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)\r
-#define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)\r
-#define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)\r
-#define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)\r
-#define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)\r
-#define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)\r
-#define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)\r
-#define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \\r
- const char *, int)) ssl_sw[11].ptr)\r
-#define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \\r
- const char *, int)) ssl_sw[12].ptr)\r
-#define SSL_CTX_set_default_passwd_cb \\r
- (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)\r
-#define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)\r
-#define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)\r
-#define SSL_CTX_use_certificate_chain_file \\r
- (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)\r
-\r
-#define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)\r
-#define CRYPTO_set_locking_callback \\r
- (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)\r
-#define CRYPTO_set_id_callback \\r
- (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)\r
-#define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)\r
-#define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)\r
-\r
-// set_ssl_option() function updates this array.\r
-// It loads SSL library dynamically and changes NULLs to the actual addresses\r
-// of respective functions. The macros above (like SSL_connect()) are really\r
-// just calling these functions indirectly via the pointer.\r
-static struct ssl_func ssl_sw[] = {\r
- {"SSL_free", NULL},\r
- {"SSL_accept", NULL},\r
- {"SSL_connect", NULL},\r
- {"SSL_read", NULL},\r
- {"SSL_write", NULL},\r
- {"SSL_get_error", NULL},\r
- {"SSL_set_fd", NULL},\r
- {"SSL_new", NULL},\r
- {"SSL_CTX_new", NULL},\r
- {"SSLv23_server_method", NULL},\r
- {"SSL_library_init", NULL},\r
- {"SSL_CTX_use_PrivateKey_file", NULL},\r
- {"SSL_CTX_use_certificate_file",NULL},\r
- {"SSL_CTX_set_default_passwd_cb",NULL},\r
- {"SSL_CTX_free", NULL},\r
- {"SSL_load_error_strings", NULL},\r
- {"SSL_CTX_use_certificate_chain_file", NULL},\r
- {NULL, NULL}\r
-};\r
-\r
-// Similar array as ssl_sw. These functions could be located in different lib.\r
-static struct ssl_func crypto_sw[] = {\r
- {"CRYPTO_num_locks", NULL},\r
- {"CRYPTO_set_locking_callback", NULL},\r
- {"CRYPTO_set_id_callback", NULL},\r
- {"ERR_get_error", NULL},\r
- {"ERR_error_string", NULL},\r
- {NULL, NULL}\r
-};\r
-#endif // NO_SSL_DL\r
-\r
-static const char *month_names[] = {\r
- "Jan", "Feb", "Mar", "Apr", "May", "Jun",\r
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"\r
-};\r
-\r
-// Unified socket address. For IPv6 support, add IPv6 address structure\r
-// in the union u.\r
-union usa {\r
- struct sockaddr sa;\r
- struct sockaddr_in sin;\r
-#if defined(USE_IPV6)\r
- struct sockaddr_in6 sin6;\r
-#endif\r
-};\r
-\r
-// Describes a string (chunk of memory).\r
-struct vec {\r
- const char *ptr;\r
- size_t len;\r
-};\r
-\r
-// Structure used by mg_stat() function. Uses 64 bit file length.\r
-struct mgstat {\r
- int is_directory; // Directory marker\r
- int64_t size; // File size\r
- time_t mtime; // Modification time\r
-};\r
-\r
-// Describes listening socket, or socket which was accept()-ed by the master\r
-// thread and queued for future handling by the worker thread.\r
-struct socket {\r
- struct socket *next; // Linkage\r
- SOCKET sock; // Listening socket\r
- union usa lsa; // Local socket address\r
- union usa rsa; // Remote socket address\r
- int is_ssl; // Is socket SSL-ed\r
-};\r
-\r
-enum {\r
- CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,\r
- PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, ACCESS_LOG_FILE,\r
- SSL_CHAIN_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,\r
- GLOBAL_PASSWORDS_FILE, INDEX_FILES,\r
- ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST, MAX_REQUEST_SIZE,\r
- EXTRA_MIME_TYPES, LISTENING_PORTS,\r
- DOCUMENT_ROOT, SSL_CERTIFICATE, NUM_THREADS, RUN_AS_USER, REWRITE,\r
- NUM_OPTIONS\r
-};\r
-\r
-static const char *config_options[] = {\r
- "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$",\r
- "E", "cgi_environment", NULL,\r
- "G", "put_delete_passwords_file", NULL,\r
- "I", "cgi_interpreter", NULL,\r
- "P", "protect_uri", NULL,\r
- "R", "authentication_domain", "mydomain.com",\r
- "S", "ssi_pattern", "**.shtml$|**.shtm$",\r
- "a", "access_log_file", NULL,\r
- "c", "ssl_chain_file", NULL,\r
- "d", "enable_directory_listing", "yes",\r
- "e", "error_log_file", NULL,\r
- "g", "global_passwords_file", NULL,\r
- "i", "index_files", "index.html,index.htm,index.cgi",\r
- "k", "enable_keep_alive", "no",\r
- "l", "access_control_list", NULL,\r
- "M", "max_request_size", "16384",\r
- "m", "extra_mime_types", NULL,\r
- "p", "listening_ports", "8080",\r
- "r", "document_root", ".",\r
- "s", "ssl_certificate", NULL,\r
- "t", "num_threads", "10",\r
- "u", "run_as_user", NULL,\r
- "w", "url_rewrite_patterns", NULL,\r
- NULL\r
-};\r
-#define ENTRIES_PER_CONFIG_OPTION 3\r
-\r
-struct mg_context {\r
- volatile int stop_flag; // Should we stop event loop\r
- SSL_CTX *ssl_ctx; // SSL context\r
- char *config[NUM_OPTIONS]; // Mongoose configuration parameters\r
- mg_callback_t user_callback; // User-defined callback function\r
- void *user_data; // User-defined data\r
-\r
- struct socket *listening_sockets;\r
-\r
- volatile int num_threads; // Number of threads\r
- pthread_mutex_t mutex; // Protects (max|num)_threads\r
- pthread_cond_t cond; // Condvar for tracking workers terminations\r
-\r
- struct socket queue[20]; // Accepted sockets\r
- volatile int sq_head; // Head of the socket queue\r
- volatile int sq_tail; // Tail of the socket queue\r
- pthread_cond_t sq_full; // Singaled when socket is produced\r
- pthread_cond_t sq_empty; // Signaled when socket is consumed\r
-};\r
-\r
-struct mg_connection {\r
- struct mg_request_info request_info;\r
- struct mg_context *ctx;\r
- SSL *ssl; // SSL descriptor\r
- struct socket client; // Connected client\r
- time_t birth_time; // Time connection was accepted\r
- int64_t num_bytes_sent; // Total bytes sent to client\r
- int64_t content_len; // Content-Length header value\r
- int64_t consumed_content; // How many bytes of content is already read\r
- char *buf; // Buffer for received data\r
- char *path_info; // PATH_INFO part of the URL\r
- int must_close; // 1 if connection must be closed\r
- int buf_size; // Buffer size\r
- int request_len; // Size of the request + headers in a buffer\r
- int data_len; // Total size of data in a buffer\r
-};\r
-\r
-const char **mg_get_valid_option_names(void) {\r
- return config_options;\r
-}\r
-\r
-static void *call_user(struct mg_connection *conn, enum mg_event event) {\r
- conn->request_info.user_data = conn->ctx->user_data;\r
- return conn->ctx->user_callback == NULL ? NULL :\r
- conn->ctx->user_callback(event, conn, &conn->request_info);\r
-}\r
-\r
-static int get_option_index(const char *name) {\r
- int i;\r
-\r
- for (i = 0; config_options[i] != NULL; i += ENTRIES_PER_CONFIG_OPTION) {\r
- if (strcmp(config_options[i], name) == 0 ||\r
- strcmp(config_options[i + 1], name) == 0) {\r
- return i / ENTRIES_PER_CONFIG_OPTION;\r
- }\r
- }\r
- return -1;\r
-}\r
-\r
-const char *mg_get_option(const struct mg_context *ctx, const char *name) {\r
- int i;\r
- if ((i = get_option_index(name)) == -1) {\r
- return NULL;\r
- } else if (ctx->config[i] == NULL) {\r
- return "";\r
- } else {\r
- return ctx->config[i];\r
- }\r
-}\r
-\r
-static void sockaddr_to_string(char *buf, size_t len,\r
- const union usa *usa) {\r
- buf[0] = '\0';\r
-#if defined(USE_IPV6)\r
- inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?\r
- (void *) &usa->sin.sin_addr :\r
- (void *) &usa->sin6.sin6_addr, buf, len);\r
-#elif defined(_WIN32)\r
- // Only Windoze Vista (and newer) have inet_ntop()\r
- strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);\r
-#else\r
- inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);\r
-#endif\r
-}\r
-\r
-// Print error message to the opened error log stream.\r
-static void cry(struct mg_connection *conn, const char *fmt, ...) {\r
- char buf[BUFSIZ], src_addr[20];\r
- va_list ap;\r
- FILE *fp;\r
- time_t timestamp;\r
-\r
- va_start(ap, fmt);\r
- (void) vsnprintf(buf, sizeof(buf), fmt, ap);\r
- va_end(ap);\r
-\r
- // Do not lock when getting the callback value, here and below.\r
- // I suppose this is fine, since function cannot disappear in the\r
- // same way string option can.\r
- conn->request_info.log_message = buf;\r
- if (call_user(conn, MG_EVENT_LOG) == NULL) {\r
- fp = conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :\r
- mg_fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");\r
-\r
- if (fp != NULL) {\r
- flockfile(fp);\r
- timestamp = time(NULL);\r
-\r
- sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);\r
- fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,\r
- src_addr);\r
-\r
- if (conn->request_info.request_method != NULL) {\r
- fprintf(fp, "%s %s: ", conn->request_info.request_method,\r
- conn->request_info.uri);\r
- }\r
-\r
- (void) fprintf(fp, "%s", buf);\r
- fputc('\n', fp);\r
- funlockfile(fp);\r
- if (fp != stderr) {\r
- fclose(fp);\r
- }\r
- }\r
- }\r
- conn->request_info.log_message = NULL;\r
-}\r
-\r
-// Return OpenSSL error message\r
-static const char *ssl_error(void) {\r
- unsigned long err;\r
- err = ERR_get_error();\r
- return err == 0 ? "" : ERR_error_string(err, NULL);\r
-}\r
-\r
-// Return fake connection structure. Used for logging, if connection\r
-// is not applicable at the moment of logging.\r
-static struct mg_connection *fc(struct mg_context *ctx) {\r
- static struct mg_connection fake_connection;\r
- fake_connection.ctx = ctx;\r
- return &fake_connection;\r
-}\r
-\r
-const char *mg_version(void) {\r
- return MONGOOSE_VERSION;\r
-}\r
-\r
-static void mg_strlcpy(register char *dst, register const char *src, size_t n) {\r
- for (; *src != '\0' && n > 1; n--) {\r
- *dst++ = *src++;\r
- }\r
- *dst = '\0';\r
-}\r
-\r
-static int lowercase(const char *s) {\r
- return tolower(* (const unsigned char *) s);\r
-}\r
-\r
-static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {\r
- int diff = 0;\r
-\r
- if (len > 0)\r
- do {\r
- diff = lowercase(s1++) - lowercase(s2++);\r
- } while (diff == 0 && s1[-1] != '\0' && --len > 0);\r
-\r
- return diff;\r
-}\r
-\r
-static int mg_strcasecmp(const char *s1, const char *s2) {\r
- int diff;\r
-\r
- do {\r
- diff = lowercase(s1++) - lowercase(s2++);\r
- } while (diff == 0 && s1[-1] != '\0');\r
-\r
- return diff;\r
-}\r
-\r
-static char * mg_strndup(const char *ptr, size_t len) {\r
- char *p;\r
-\r
- if ((p = (char *) malloc(len + 1)) != NULL) {\r
- mg_strlcpy(p, ptr, len + 1);\r
- }\r
-\r
- return p;\r
-}\r
-\r
-static char * mg_strdup(const char *str) {\r
- return mg_strndup(str, strlen(str));\r
-}\r
-\r
-// Like snprintf(), but never returns negative value, or the value\r
-// that is larger than a supplied buffer.\r
-// Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability\r
-// in his audit report.\r
-static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,\r
- const char *fmt, va_list ap) {\r
- int n;\r
-\r
- if (buflen == 0)\r
- return 0;\r
-\r
- n = vsnprintf(buf, buflen, fmt, ap);\r
-\r
- if (n < 0) {\r
- cry(conn, "vsnprintf error");\r
- n = 0;\r
- } else if (n >= (int) buflen) {\r
- cry(conn, "truncating vsnprintf buffer: [%.*s]",\r
- n > 200 ? 200 : n, buf);\r
- n = (int) buflen - 1;\r
- }\r
- buf[n] = '\0';\r
-\r
- return n;\r
-}\r
-\r
-static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,\r
- const char *fmt, ...) {\r
- va_list ap;\r
- int n;\r
-\r
- va_start(ap, fmt);\r
- n = mg_vsnprintf(conn, buf, buflen, fmt, ap);\r
- va_end(ap);\r
-\r
- return n;\r
-}\r
-\r
-// Skip the characters until one of the delimiters characters found.\r
-// 0-terminate resulting word. Skip the delimiter and following whitespaces if any.\r
-// Advance pointer to buffer to the next word. Return found 0-terminated word.\r
-// Delimiters can be quoted with quotechar.\r
-static char *skip_quoted(char **buf, const char *delimiters, const char *whitespace, char quotechar) {\r
- char *p, *begin_word, *end_word, *end_whitespace;\r
-\r
- begin_word = *buf;\r
- end_word = begin_word + strcspn(begin_word, delimiters);\r
-\r
- // Check for quotechar\r
- if (end_word > begin_word) {\r
- p = end_word - 1;\r
- while (*p == quotechar) {\r
- // If there is anything beyond end_word, copy it\r
- if (*end_word == '\0') {\r
- *p = '\0';\r
- break;\r
- } else {\r
- size_t end_off = strcspn(end_word + 1, delimiters);\r
- memmove (p, end_word, end_off + 1);\r
- p += end_off; // p must correspond to end_word - 1\r
- end_word += end_off + 1;\r
- }\r
- }\r
- for (p++; p < end_word; p++) {\r
- *p = '\0';\r
- }\r
- }\r
-\r
- if (*end_word == '\0') {\r
- *buf = end_word;\r
- } else {\r
- end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);\r
-\r
- for (p = end_word; p < end_whitespace; p++) {\r
- *p = '\0';\r
- }\r
-\r
- *buf = end_whitespace;\r
- }\r
-\r
- return begin_word;\r
-}\r
-\r
-// Simplified version of skip_quoted without quote char\r
-// and whitespace == delimiters\r
-static char *skip(char **buf, const char *delimiters) {\r
- return skip_quoted(buf, delimiters, delimiters, 0);\r
-}\r
-\r
-\r
-// Return HTTP header value, or NULL if not found.\r
-static const char *get_header(const struct mg_request_info *ri,\r
- const char *name) {\r
- int i;\r
-\r
- for (i = 0; i < ri->num_headers; i++)\r
- if (!mg_strcasecmp(name, ri->http_headers[i].name))\r
- return ri->http_headers[i].value;\r
-\r
- return NULL;\r
-}\r
-\r
-const char *mg_get_header(const struct mg_connection *conn, const char *name) {\r
- return get_header(&conn->request_info, name);\r
-}\r
-\r
-// A helper function for traversing comma separated list of values.\r
-// It returns a list pointer shifted to the next value, of NULL if the end\r
-// of the list found.\r
-// Value is stored in val vector. If value has form "x=y", then eq_val\r
-// vector is initialized to point to the "y" part, and val vector length\r
-// is adjusted to point only to "x".\r
-static const char *next_option(const char *list, struct vec *val,\r
- struct vec *eq_val) {\r
- if (list == NULL || *list == '\0') {\r
- // End of the list\r
- list = NULL;\r
- } else {\r
- val->ptr = list;\r
- if ((list = strchr(val->ptr, ',')) != NULL) {\r
- // Comma found. Store length and shift the list ptr\r
- val->len = list - val->ptr;\r
- list++;\r
- } else {\r
- // This value is the last one\r
- list = val->ptr + strlen(val->ptr);\r
- val->len = list - val->ptr;\r
- }\r
-\r
- if (eq_val != NULL) {\r
- // Value has form "x=y", adjust pointers and lengths\r
- // so that val points to "x", and eq_val points to "y".\r
- eq_val->len = 0;\r
- eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);\r
- if (eq_val->ptr != NULL) {\r
- eq_val->ptr++; // Skip over '=' character\r
- eq_val->len = val->ptr + val->len - eq_val->ptr;\r
- val->len = (eq_val->ptr - val->ptr) - 1;\r
- }\r
- }\r
- }\r
-\r
- return list;\r
-}\r
-\r
-static int match_prefix(const char *pattern, int pattern_len, const char *str) {\r
- const char *or_str;\r
- int i, j, len, res;\r
-\r
- if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {\r
- res = match_prefix(pattern, or_str - pattern, str);\r
- return res > 0 ? res :\r
- match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);\r
- }\r
-\r
- i = j = 0;\r
- res = -1;\r
- for (; i < pattern_len; i++, j++) {\r
- if (pattern[i] == '?' && str[j] != '\0') {\r
- continue;\r
- } else if (pattern[i] == '$') {\r
- return str[j] == '\0' ? j : -1;\r
- } else if (pattern[i] == '*') {\r
- i++;\r
- if (pattern[i] == '*') {\r
- i++;\r
- len = strlen(str + j);\r
- } else {\r
- len = strcspn(str + j, "/");\r
- }\r
- if (i == pattern_len) {\r
- return j + len;\r
- }\r
- do {\r
- res = match_prefix(pattern + i, pattern_len - i, str + j + len);\r
- } while (res == -1 && len-- > 0);\r
- return res == -1 ? -1 : j + res + len;\r
- } else if (pattern[i] != str[j]) {\r
- return -1;\r
- }\r
- }\r
- return j;\r
-}\r
-\r
-// HTTP 1.1 assumes keep alive if "Connection:" header is not set\r
-// This function must tolerate situations when connection info is not\r
-// set up, for example if request parsing failed.\r
-static int should_keep_alive(const struct mg_connection *conn) {\r
- const char *http_version = conn->request_info.http_version;\r
- const char *header = mg_get_header(conn, "Connection");\r
- return (!conn->must_close &&\r
- !conn->request_info.status_code != 401 &&\r
- !mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") &&\r
- (header == NULL && http_version && !strcmp(http_version, "1.1"))) ||\r
- (header != NULL && !mg_strcasecmp(header, "keep-alive"));\r
-}\r
-\r
-static const char *suggest_connection_header(const struct mg_connection *conn) {\r
- return should_keep_alive(conn) ? "keep-alive" : "close";\r
-}\r
-\r
-static void send_http_error(struct mg_connection *conn, int status,\r
- const char *reason, const char *fmt, ...) {\r
- char buf[BUFSIZ];\r
- va_list ap;\r
- int len;\r
-\r
- conn->request_info.status_code = status;\r
-\r
- if (call_user(conn, MG_HTTP_ERROR) == NULL) {\r
- buf[0] = '\0';\r
- len = 0;\r
-\r
- // Errors 1xx, 204 and 304 MUST NOT send a body\r
- if (status > 199 && status != 204 && status != 304) {\r
- len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);\r
- cry(conn, "%s", buf);\r
- buf[len++] = '\n';\r
-\r
- va_start(ap, fmt);\r
- len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);\r
- va_end(ap);\r
- }\r
- DEBUG_TRACE(("[%s]", buf));\r
-\r
- mg_printf(conn, "HTTP/1.1 %d %s\r\n"\r
- "Content-Type: text/plain\r\n"\r
- "Content-Length: %d\r\n"\r
- "Connection: %s\r\n\r\n", status, reason, len,\r
- suggest_connection_header(conn));\r
- conn->num_bytes_sent += mg_printf(conn, "%s", buf);\r
- }\r
-}\r
-\r
-#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
-static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) {\r
- unused = NULL;\r
- *mutex = CreateMutex(NULL, FALSE, NULL);\r
- return *mutex == NULL ? -1 : 0;\r
-}\r
-\r
-static int pthread_mutex_destroy(pthread_mutex_t *mutex) {\r
- return CloseHandle(*mutex) == 0 ? -1 : 0;\r
-}\r
-\r
-static int pthread_mutex_lock(pthread_mutex_t *mutex) {\r
- return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;\r
-}\r
-\r
-static int pthread_mutex_unlock(pthread_mutex_t *mutex) {\r
- return ReleaseMutex(*mutex) == 0 ? -1 : 0;\r
-}\r
-\r
-static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {\r
- unused = NULL;\r
- cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);\r
- cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);\r
- return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;\r
-}\r
-\r
-static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {\r
- HANDLE handles[] = {cv->signal, cv->broadcast};\r
- ReleaseMutex(*mutex);\r
- WaitForMultipleObjects(2, handles, FALSE, INFINITE);\r
- return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;\r
-}\r
-\r
-static int pthread_cond_signal(pthread_cond_t *cv) {\r
- return SetEvent(cv->signal) == 0 ? -1 : 0;\r
-}\r
-\r
-static int pthread_cond_broadcast(pthread_cond_t *cv) {\r
- // Implementation with PulseEvent() has race condition, see\r
- // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html\r
- return PulseEvent(cv->broadcast) == 0 ? -1 : 0;\r
-}\r
-\r
-static int pthread_cond_destroy(pthread_cond_t *cv) {\r
- return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;\r
-}\r
-\r
-// For Windows, change all slashes to backslashes in path names.\r
-static void change_slashes_to_backslashes(char *path) {\r
- int i;\r
-\r
- for (i = 0; path[i] != '\0'; i++) {\r
- if (path[i] == '/')\r
- path[i] = '\\';\r
- // i > 0 check is to preserve UNC paths, like \\server\file.txt\r
- if (path[i] == '\\' && i > 0)\r
- while (path[i + 1] == '\\' || path[i + 1] == '/')\r
- (void) memmove(path + i + 1,\r
- path + i + 2, strlen(path + i + 1));\r
- }\r
-}\r
-\r
-// Encode 'path' which is assumed UTF-8 string, into UNICODE string.\r
-// wbuf and wbuf_len is a target buffer and its length.\r
-static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {\r
- char buf[PATH_MAX], buf2[PATH_MAX], *p;\r
-\r
- mg_strlcpy(buf, path, sizeof(buf));\r
- change_slashes_to_backslashes(buf);\r
-\r
- // Point p to the end of the file name\r
- p = buf + strlen(buf) - 1;\r
-\r
- // Trim trailing backslash character\r
- while (p > buf && *p == '\\' && p[-1] != ':') {\r
- *p-- = '\0';\r
- }\r
-\r
- // Protect from CGI code disclosure.\r
- // This is very nasty hole. Windows happily opens files with\r
- // some garbage in the end of file name. So fopen("a.cgi ", "r")\r
- // actually opens "a.cgi", and does not return an error!\r
- if (*p == 0x20 || // No space at the end\r
- (*p == 0x2e && p > buf) || // No '.' but allow '.' as full path\r
- *p == 0x2b || // No '+'\r
- (*p & ~0x7f)) { // And generally no non-ascii chars\r
- (void) fprintf(stderr, "Rejecting suspicious path: [%s]", buf);\r
- wbuf[0] = L'\0';\r
- } else {\r
- // Convert to Unicode and back. If doubly-converted string does not\r
- // match the original, something is fishy, reject.\r
- memset(wbuf, 0, wbuf_len * sizeof(wchar_t));\r
- MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);\r
- WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),\r
- NULL, NULL);\r
- if (strcmp(buf, buf2) != 0) {\r
- wbuf[0] = L'\0';\r
- }\r
- }\r
-}\r
-\r
-#if defined(_WIN32_WCE)\r
-static time_t time(time_t *ptime) {\r
- time_t t;\r
- SYSTEMTIME st;\r
- FILETIME ft;\r
-\r
- GetSystemTime(&st);\r
- SystemTimeToFileTime(&st, &ft);\r
- t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);\r
-\r
- if (ptime != NULL) {\r
- *ptime = t;\r
- }\r
-\r
- return t;\r
-}\r
-\r
-static struct tm *localtime(const time_t *ptime, struct tm *ptm) {\r
- int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;\r
- FILETIME ft, lft;\r
- SYSTEMTIME st;\r
- TIME_ZONE_INFORMATION tzinfo;\r
-\r
- if (ptm == NULL) {\r
- return NULL;\r
- }\r
-\r
- * (int64_t *) &ft = t;\r
- FileTimeToLocalFileTime(&ft, &lft);\r
- FileTimeToSystemTime(&lft, &st);\r
- ptm->tm_year = st.wYear - 1900;\r
- ptm->tm_mon = st.wMonth - 1;\r
- ptm->tm_wday = st.wDayOfWeek;\r
- ptm->tm_mday = st.wDay;\r
- ptm->tm_hour = st.wHour;\r
- ptm->tm_min = st.wMinute;\r
- ptm->tm_sec = st.wSecond;\r
- ptm->tm_yday = 0; // hope nobody uses this\r
- ptm->tm_isdst =\r
- GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;\r
-\r
- return ptm;\r
-}\r
-\r
-static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {\r
- // FIXME(lsm): fix this.\r
- return localtime(ptime, ptm);\r
-}\r
-\r
-static size_t strftime(char *dst, size_t dst_size, const char *fmt,\r
- const struct tm *tm) {\r
- (void) snprintf(dst, dst_size, "implement strftime() for WinCE");\r
- return 0;\r
-}\r
-#endif\r
-\r
-static int mg_rename(const char* oldname, const char* newname) {\r
- wchar_t woldbuf[PATH_MAX];\r
- wchar_t wnewbuf[PATH_MAX];\r
-\r
- to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf));\r
- to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf));\r
-\r
- return MoveFileW(woldbuf, wnewbuf) ? 0 : -1;\r
-}\r
-\r
-\r
-static FILE *mg_fopen(const char *path, const char *mode) {\r
- wchar_t wbuf[PATH_MAX], wmode[20];\r
-\r
- to_unicode(path, wbuf, ARRAY_SIZE(wbuf));\r
- MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));\r
-\r
- return _wfopen(wbuf, wmode);\r
-}\r
-\r
-static int mg_stat(const char *path, struct mgstat *stp) {\r
- int ok = -1; // Error\r
- wchar_t wbuf[PATH_MAX];\r
- WIN32_FILE_ATTRIBUTE_DATA info;\r
-\r
- to_unicode(path, wbuf, ARRAY_SIZE(wbuf));\r
-\r
- if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {\r
- stp->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);\r
- stp->mtime = SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,\r
- info.ftLastWriteTime.dwHighDateTime);\r
- stp->is_directory =\r
- info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;\r
- ok = 0; // Success\r
- }\r
-\r
- return ok;\r
-}\r
-\r
-static int mg_remove(const char *path) {\r
- wchar_t wbuf[PATH_MAX];\r
- to_unicode(path, wbuf, ARRAY_SIZE(wbuf));\r
- return DeleteFileW(wbuf) ? 0 : -1;\r
-}\r
-\r
-static int mg_mkdir(const char *path, int mode) {\r
- char buf[PATH_MAX];\r
- wchar_t wbuf[PATH_MAX];\r
-\r
- mode = 0; // Unused\r
- mg_strlcpy(buf, path, sizeof(buf));\r
- change_slashes_to_backslashes(buf);\r
-\r
- (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, sizeof(wbuf));\r
-\r
- return CreateDirectoryW(wbuf, NULL) ? 0 : -1;\r
-}\r
-\r
-// Implementation of POSIX opendir/closedir/readdir for Windows.\r
-static DIR * opendir(const char *name) {\r
- DIR *dir = NULL;\r
- wchar_t wpath[PATH_MAX];\r
- DWORD attrs;\r
-\r
- if (name == NULL) {\r
- SetLastError(ERROR_BAD_ARGUMENTS);\r
- } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {\r
- SetLastError(ERROR_NOT_ENOUGH_MEMORY);\r
- } else {\r
- to_unicode(name, wpath, ARRAY_SIZE(wpath));\r
- attrs = GetFileAttributesW(wpath);\r
- if (attrs != 0xFFFFFFFF &&\r
- ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {\r
- (void) wcscat(wpath, L"\\*");\r
- dir->handle = FindFirstFileW(wpath, &dir->info);\r
- dir->result.d_name[0] = '\0';\r
- } else {\r
- free(dir);\r
- dir = NULL;\r
- }\r
- }\r
-\r
- return dir;\r
-}\r
-\r
-static int closedir(DIR *dir) {\r
- int result = 0;\r
-\r
- if (dir != NULL) {\r
- if (dir->handle != INVALID_HANDLE_VALUE)\r
- result = FindClose(dir->handle) ? 0 : -1;\r
-\r
- free(dir);\r
- } else {\r
- result = -1;\r
- SetLastError(ERROR_BAD_ARGUMENTS);\r
- }\r
-\r
- return result;\r
-}\r
-\r
-struct dirent * readdir(DIR *dir) {\r
- struct dirent *result = 0;\r
-\r
- if (dir) {\r
- if (dir->handle != INVALID_HANDLE_VALUE) {\r
- result = &dir->result;\r
- (void) WideCharToMultiByte(CP_UTF8, 0,\r
- dir->info.cFileName, -1, result->d_name,\r
- sizeof(result->d_name), NULL, NULL);\r
-\r
- if (!FindNextFileW(dir->handle, &dir->info)) {\r
- (void) FindClose(dir->handle);\r
- dir->handle = INVALID_HANDLE_VALUE;\r
- }\r
-\r
- } else {\r
- SetLastError(ERROR_FILE_NOT_FOUND);\r
- }\r
- } else {\r
- SetLastError(ERROR_BAD_ARGUMENTS);\r
- }\r
-\r
- return result;\r
-}\r
-\r
-#define set_close_on_exec(fd) // No FD_CLOEXEC on Windows\r
-\r
-static int start_thread(struct mg_context *ctx, mg_thread_func_t f, void *p) {\r
- return _beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;\r
-}\r
-\r
-static HANDLE dlopen(const char *dll_name, int flags) {\r
- wchar_t wbuf[PATH_MAX];\r
- flags = 0; // Unused\r
- to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));\r
- return LoadLibraryW(wbuf);\r
-}\r
-\r
-#if !defined(NO_CGI)\r
-#define SIGKILL 0\r
-static int kill(pid_t pid, int sig_num) {\r
- (void) TerminateProcess(pid, sig_num);\r
- (void) CloseHandle(pid);\r
- return 0;\r
-}\r
-\r
-static pid_t spawn_process(struct mg_connection *conn, const char *prog,\r
- char *envblk, char *envp[], int fd_stdin,\r
- int fd_stdout, const char *dir) {\r
- HANDLE me;\r
- char *p, *interp, cmdline[PATH_MAX], buf[PATH_MAX];\r
- FILE *fp;\r
- STARTUPINFOA si = { sizeof(si) };\r
- PROCESS_INFORMATION pi = { 0 };\r
-\r
- envp = NULL; // Unused\r
-\r
- // TODO(lsm): redirect CGI errors to the error log file\r
- si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;\r
- si.wShowWindow = SW_HIDE;\r
-\r
- me = GetCurrentProcess();\r
- (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,\r
- &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);\r
- (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,\r
- &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);\r
-\r
- // If CGI file is a script, try to read the interpreter line\r
- interp = conn->ctx->config[CGI_INTERPRETER];\r
- if (interp == NULL) {\r
- buf[2] = '\0';\r
- mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%c%s", dir, DIRSEP, prog);\r
- if ((fp = fopen(cmdline, "r")) != NULL) {\r
- (void) fgets(buf, sizeof(buf), fp);\r
- if (buf[0] != '#' || buf[1] != '!') {\r
- // First line does not start with "#!". Do not set interpreter.\r
- buf[2] = '\0';\r
- } else {\r
- // Trim whitespaces in interpreter name\r
- for (p = &buf[strlen(buf) - 1]; p > buf && isspace(*p); p--) {\r
- *p = '\0';\r
- }\r
- }\r
- (void) fclose(fp);\r
- }\r
- interp = buf + 2;\r
- }\r
-\r
- (void) mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s%c%s",\r
- interp, interp[0] == '\0' ? "" : " ", dir, DIRSEP, prog);\r
-\r
- DEBUG_TRACE(("Running [%s]", cmdline));\r
- if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,\r
- CREATE_NEW_PROCESS_GROUP, envblk, dir, &si, &pi) == 0) {\r
- cry(conn, "%s: CreateProcess(%s): %d",\r
- __func__, cmdline, ERRNO);\r
- pi.hProcess = (pid_t) -1;\r
- } else {\r
- (void) close(fd_stdin);\r
- (void) close(fd_stdout);\r
- }\r
-\r
- (void) CloseHandle(si.hStdOutput);\r
- (void) CloseHandle(si.hStdInput);\r
- (void) CloseHandle(pi.hThread);\r
-\r
- return (pid_t) pi.hProcess;\r
-}\r
-#endif // !NO_CGI\r
-\r
-static int set_non_blocking_mode(SOCKET sock) {\r
- unsigned long on = 1;\r
- return ioctlsocket(sock, FIONBIO, &on);\r
-}\r
-\r
-#else\r
-static int mg_stat(const char *path, struct mgstat *stp) {\r
- struct stat st;\r
- int ok;\r
-\r
- if (stat(path, &st) == 0) {\r
- ok = 0;\r
- stp->size = st.st_size;\r
- stp->mtime = st.st_mtime;\r
- stp->is_directory = S_ISDIR(st.st_mode);\r
- } else {\r
- ok = -1;\r
- }\r
-\r
- return ok;\r
-}\r
-\r
-static void set_close_on_exec(int fd) {\r
- (void) fcntl(fd, F_SETFD, FD_CLOEXEC);\r
-}\r
-\r
-static int start_thread(struct mg_context *ctx, mg_thread_func_t func,\r
- void *param) {\r
- pthread_t thread_id;\r
- pthread_attr_t attr;\r
- int retval;\r
-\r
- (void) pthread_attr_init(&attr);\r
- (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);\r
- // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled\r
- // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5);\r
-\r
- if ((retval = pthread_create(&thread_id, &attr, func, param)) != 0) {\r
- cry(fc(ctx), "%s: %s", __func__, strerror(retval));\r
- }\r
-\r
- return retval;\r
-}\r
-\r
-#ifndef NO_CGI\r
-static pid_t spawn_process(struct mg_connection *conn, const char *prog,\r
- char *envblk, char *envp[], int fd_stdin,\r
- int fd_stdout, const char *dir) {\r
- pid_t pid;\r
- const char *interp;\r
-\r
- envblk = NULL; // Unused\r
-\r
- if ((pid = fork()) == -1) {\r
- // Parent\r
- send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));\r
- } else if (pid == 0) {\r
- // Child\r
- if (chdir(dir) != 0) {\r
- cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));\r
- } else if (dup2(fd_stdin, 0) == -1) {\r
- cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO));\r
- } else if (dup2(fd_stdout, 1) == -1) {\r
- cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO));\r
- } else {\r
- (void) dup2(fd_stdout, 2);\r
- (void) close(fd_stdin);\r
- (void) close(fd_stdout);\r
-\r
- // Execute CGI program. No need to lock: new process\r
- interp = conn->ctx->config[CGI_INTERPRETER];\r
- if (interp == NULL) {\r
- (void) execle(prog, prog, NULL, envp);\r
- cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));\r
- } else {\r
- (void) execle(interp, interp, prog, NULL, envp);\r
- cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,\r
- strerror(ERRNO));\r
- }\r
- }\r
- exit(EXIT_FAILURE);\r
- } else {\r
- // Parent. Close stdio descriptors\r
- (void) close(fd_stdin);\r
- (void) close(fd_stdout);\r
- }\r
-\r
- return pid;\r
-}\r
-#endif // !NO_CGI\r
-\r
-static int set_non_blocking_mode(SOCKET sock) {\r
- int flags;\r
-\r
- flags = fcntl(sock, F_GETFL, 0);\r
- (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);\r
-\r
- return 0;\r
-}\r
-#endif // _WIN32\r
-\r
-// Write data to the IO channel - opened file descriptor, socket or SSL\r
-// descriptor. Return number of bytes written.\r
-static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,\r
- int64_t len) {\r
- int64_t sent;\r
- int n, k;\r
-\r
- sent = 0;\r
- while (sent < len) {\r
-\r
- // How many bytes we send in this iteration\r
- k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);\r
-\r
- if (ssl != NULL) {\r
- n = SSL_write(ssl, buf + sent, k);\r
- } else if (fp != NULL) {\r
- n = fwrite(buf + sent, 1, (size_t) k, fp);\r
- if (ferror(fp))\r
- n = -1;\r
- } else {\r
- n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);\r
- }\r
-\r
- if (n < 0)\r
- break;\r
-\r
- sent += n;\r
- }\r
-\r
- return sent;\r
-}\r
-\r
-// Read from IO channel - opened file descriptor, socket, or SSL descriptor.\r
-// Return number of bytes read.\r
-static int pull(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int len) {\r
- int nread;\r
-\r
- if (ssl != NULL) {\r
- nread = SSL_read(ssl, buf, len);\r
- } else if (fp != NULL) {\r
- // Use read() instead of fread(), because if we're reading from the CGI\r
- // pipe, fread() may block until IO buffer is filled up. We cannot afford\r
- // to block and must pass all read bytes immediately to the client.\r
- nread = read(fileno(fp), buf, (size_t) len);\r
- if (ferror(fp))\r
- nread = -1;\r
- } else {\r
- nread = recv(sock, buf, (size_t) len, 0);\r
- }\r
-\r
- return nread;\r
-}\r
-\r
-int mg_read(struct mg_connection *conn, void *buf, size_t len) {\r
- int n, buffered_len, nread;\r
- const char *buffered;\r
-\r
- assert((conn->content_len == -1 && conn->consumed_content == 0) ||\r
- conn->consumed_content <= conn->content_len);\r
- DEBUG_TRACE(("%p %zu %lld %lld", buf, len,\r
- conn->content_len, conn->consumed_content));\r
- nread = 0;\r
- if (conn->consumed_content < conn->content_len) {\r
-\r
- // Adjust number of bytes to read.\r
- int64_t to_read = conn->content_len - conn->consumed_content;\r
- if (to_read < (int64_t) len) {\r
- len = (int) to_read;\r
- }\r
-\r
- // How many bytes of data we have buffered in the request buffer?\r
- buffered = conn->buf + conn->request_len + conn->consumed_content;\r
- buffered_len = conn->data_len - conn->request_len;\r
- assert(buffered_len >= 0);\r
-\r
- // Return buffered data back if we haven't done that yet.\r
- if (conn->consumed_content < (int64_t) buffered_len) {\r
- buffered_len -= (int) conn->consumed_content;\r
- if (len < (size_t) buffered_len) {\r
- buffered_len = len;\r
- }\r
- memcpy(buf, buffered, (size_t)buffered_len);\r
- len -= buffered_len;\r
- buf = (char *) buf + buffered_len;\r
- conn->consumed_content += buffered_len;\r
- nread = buffered_len;\r
- }\r
-\r
- // We have returned all buffered data. Read new data from the remote socket.\r
- while (len > 0) {\r
- n = pull(NULL, conn->client.sock, conn->ssl, (char *) buf, (int) len);\r
- if (n <= 0) {\r
- break;\r
- }\r
- buf = (char *) buf + n;\r
- conn->consumed_content += n;\r
- nread += n;\r
- len -= n;\r
- }\r
- }\r
- return nread;\r
-}\r
-\r
-int mg_write(struct mg_connection *conn, const void *buf, size_t len) {\r
- return (int) push(NULL, conn->client.sock, conn->ssl, (const char *) buf,\r
- (int64_t) len);\r
-}\r
-\r
-int mg_printf(struct mg_connection *conn, const char *fmt, ...) {\r
- char buf[BUFSIZ];\r
- int len;\r
- va_list ap;\r
-\r
- va_start(ap, fmt);\r
- len = mg_vsnprintf(conn, buf, sizeof(buf), fmt, ap);\r
- va_end(ap);\r
-\r
- return mg_write(conn, buf, (size_t)len);\r
-}\r
-\r
-// URL-decode input buffer into destination buffer.\r
-// 0-terminate the destination buffer. Return the length of decoded data.\r
-// form-url-encoded data differs from URI encoding in a way that it\r
-// uses '+' as character for space, see RFC 1866 section 8.2.1\r
-// http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt\r
-static size_t url_decode(const char *src, size_t src_len, char *dst,\r
- size_t dst_len, int is_form_url_encoded) {\r
- size_t i, j;\r
- int a, b;\r
-#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')\r
-\r
- for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {\r
- if (src[i] == '%' &&\r
- isxdigit(* (const unsigned char *) (src + i + 1)) &&\r
- isxdigit(* (const unsigned char *) (src + i + 2))) {\r
- a = tolower(* (const unsigned char *) (src + i + 1));\r
- b = tolower(* (const unsigned char *) (src + i + 2));\r
- dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));\r
- i += 2;\r
- } else if (is_form_url_encoded && src[i] == '+') {\r
- dst[j] = ' ';\r
- } else {\r
- dst[j] = src[i];\r
- }\r
- }\r
-\r
- dst[j] = '\0'; // Null-terminate the destination\r
-\r
- return j;\r
-}\r
-\r
-// Scan given buffer and fetch the value of the given variable.\r
-// It can be specified in query string, or in the POST data.\r
-// Return NULL if the variable not found, or allocated 0-terminated value.\r
-// It is caller's responsibility to free the returned value.\r
-int mg_get_var(const char *buf, size_t buf_len, const char *name,\r
- char *dst, size_t dst_len) {\r
- const char *p, *e, *s;\r
- size_t name_len, len;\r
-\r
- name_len = strlen(name);\r
- e = buf + buf_len;\r
- len = -1;\r
- dst[0] = '\0';\r
-\r
- // buf is "var1=val1&var2=val2...". Find variable first\r
- for (p = buf; p != NULL && p + name_len < e; p++) {\r
- if ((p == buf || p[-1] == '&') && p[name_len] == '=' &&\r
- !mg_strncasecmp(name, p, name_len)) {\r
-\r
- // Point p to variable value\r
- p += name_len + 1;\r
-\r
- // Point s to the end of the value\r
- s = (const char *) memchr(p, '&', (size_t)(e - p));\r
- if (s == NULL) {\r
- s = e;\r
- }\r
- assert(s >= p);\r
-\r
- // Decode variable into destination buffer\r
- if ((size_t) (s - p) < dst_len) {\r
- len = url_decode(p, (size_t)(s - p), dst, dst_len, 1);\r
- }\r
- break;\r
- }\r
- }\r
-\r
- return len;\r
-}\r
-\r
-int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name,\r
- char *dst, size_t dst_size) {\r
- const char *s, *p, *end;\r
- int name_len, len = -1;\r
-\r
- dst[0] = '\0';\r
- if ((s = mg_get_header(conn, "Cookie")) == NULL) {\r
- return 0;\r
- }\r
-\r
- name_len = strlen(cookie_name);\r
- end = s + strlen(s);\r
-\r
- for (; (s = strstr(s, cookie_name)) != NULL; s += name_len)\r
- if (s[name_len] == '=') {\r
- s += name_len + 1;\r
- if ((p = strchr(s, ' ')) == NULL)\r
- p = end;\r
- if (p[-1] == ';')\r
- p--;\r
- if (*s == '"' && p[-1] == '"' && p > s + 1) {\r
- s++;\r
- p--;\r
- }\r
- if ((size_t) (p - s) < dst_size) {\r
- len = (p - s) + 1;\r
- mg_strlcpy(dst, s, (size_t)len);\r
- }\r
- break;\r
- }\r
-\r
- return len;\r
-}\r
-\r
-static int convert_uri_to_file_name(struct mg_connection *conn, char *buf,\r
- size_t buf_len, struct mgstat *st) {\r
- struct vec a, b;\r
- const char *rewrite, *uri = conn->request_info.uri;\r
- char *p;\r
- int match_len, stat_result;\r
-\r
- buf_len--; // This is because memmove() for PATH_INFO may shift part\r
- // of the path one byte on the right.\r
- mg_snprintf(conn, buf, buf_len, "%s%s", conn->ctx->config[DOCUMENT_ROOT],\r
- uri);\r
-\r
- rewrite = conn->ctx->config[REWRITE];\r
- while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {\r
- if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {\r
- mg_snprintf(conn, buf, buf_len, "%.*s%s", b.len, b.ptr, uri + match_len);\r
- break;\r
- }\r
- }\r
-\r
-#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
- //change_slashes_to_backslashes(buf);\r
-#endif // _WIN32\r
-\r
- if ((stat_result = mg_stat(buf, st)) != 0) {\r
- // Support PATH_INFO for CGI scripts.\r
- for (p = buf + strlen(buf); p > buf + 1; p--) {\r
- if (*p == '/') {\r
- *p = '\0';\r
- if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],\r
- strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&\r
- (stat_result = mg_stat(buf, st)) == 0) {\r
- // Shift PATH_INFO block one character right, e.g.\r
- // "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"\r
- // conn->path_info is pointing to the local variable "path" declared\r
- // in handle_request(), so PATH_INFO not valid after\r
- // handle_request returns.\r
- conn->path_info = p + 1;\r
- memmove(p + 2, p + 1, strlen(p + 1) + 1); // +1 is for trailing \0\r
- p[1] = '/';\r
- break;\r
- } else {\r
- *p = '/';\r
- stat_result = -1;\r
- }\r
- }\r
- }\r
- }\r
-\r
- return stat_result;\r
-}\r
-\r
-static int sslize(struct mg_connection *conn, int (*func)(SSL *)) {\r
- return (conn->ssl = SSL_new(conn->ctx->ssl_ctx)) != NULL &&\r
- SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&\r
- func(conn->ssl) == 1;\r
-}\r
-\r
-// Check whether full request is buffered. Return:\r
-// -1 if request is malformed\r
-// 0 if request is not yet fully buffered\r
-// >0 actual request length, including last \r\n\r\n\r
-static int get_request_len(const char *buf, int buflen) {\r
- const char *s, *e;\r
- int len = 0;\r
-\r
- DEBUG_TRACE(("buf: %p, len: %d", buf, buflen));\r
- for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)\r
- // Control characters are not allowed but >=128 is.\r
- if (!isprint(* (const unsigned char *) s) && *s != '\r' &&\r
- *s != '\n' && * (const unsigned char *) s < 128) {\r
- len = -1;\r
- } else if (s[0] == '\n' && s[1] == '\n') {\r
- len = (int) (s - buf) + 2;\r
- } else if (s[0] == '\n' && &s[1] < e &&\r
- s[1] == '\r' && s[2] == '\n') {\r
- len = (int) (s - buf) + 3;\r
- }\r
-\r
- return len;\r
-}\r
-\r
-// Convert month to the month number. Return -1 on error, or month number\r
-static int get_month_index(const char *s) {\r
- size_t i;\r
-\r
- for (i = 0; i < ARRAY_SIZE(month_names); i++)\r
- if (!strcmp(s, month_names[i]))\r
- return (int) i;\r
-\r
- return -1;\r
-}\r
-\r
-// Parse UTC date-time string, and return the corresponding time_t value.\r
-static time_t parse_date_string(const char *datetime) {\r
- static const unsigned short days_before_month[] = {\r
- 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334\r
- };\r
- char month_str[32];\r
- int second, minute, hour, day, month, year, leap_days, days;\r
- time_t result = (time_t) 0;\r
-\r
- if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",\r
- &day, month_str, &year, &hour, &minute, &second) == 6) ||\r
- (sscanf(datetime, "%d %3s %d %d:%d:%d",\r
- &day, month_str, &year, &hour, &minute, &second) == 6) ||\r
- (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",\r
- &day, month_str, &year, &hour, &minute, &second) == 6) ||\r
- (sscanf(datetime, "%d-%3s-%d %d:%d:%d",\r
- &day, month_str, &year, &hour, &minute, &second) == 6)) &&\r
- year > 1970 &&\r
- (month = get_month_index(month_str)) != -1) {\r
- year -= 1970;\r
- leap_days = year / 4 - year / 100 + year / 400;\r
- days = year * 365 + days_before_month[month] + (day - 1) + leap_days;\r
- result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;\r
- }\r
-\r
- return result;\r
-}\r
-\r
-// Protect against directory disclosure attack by removing '..',\r
-// excessive '/' and '\' characters\r
-static void remove_double_dots_and_double_slashes(char *s) {\r
- char *p = s;\r
-\r
- while (*s != '\0') {\r
- *p++ = *s++;\r
- if (IS_DIRSEP_CHAR(s[-1])) {\r
- // Skip all following slashes and backslashes\r
- while (IS_DIRSEP_CHAR(s[0])) {\r
- s++;\r
- }\r
-\r
- // Skip all double-dots\r
- while (*s == '.' && s[1] == '.') {\r
- s += 2;\r
- }\r
- }\r
- }\r
- *p = '\0';\r
-}\r
-\r
-static const struct {\r
- const char *extension;\r
- size_t ext_len;\r
- const char *mime_type;\r
- size_t mime_type_len;\r
-} builtin_mime_types[] = {\r
- {".html", 5, "text/html", 9},\r
- {".htm", 4, "text/html", 9},\r
- {".shtm", 5, "text/html", 9},\r
- {".shtml", 6, "text/html", 9},\r
- {".css", 4, "text/css", 8},\r
- {".js", 3, "application/x-javascript", 24},\r
- {".ico", 4, "image/x-icon", 12},\r
- {".gif", 4, "image/gif", 9},\r
- {".jpg", 4, "image/jpeg", 10},\r
- {".jpeg", 5, "image/jpeg", 10},\r
- {".png", 4, "image/png", 9},\r
- {".svg", 4, "image/svg+xml", 13},\r
- {".torrent", 8, "application/x-bittorrent", 24},\r
- {".wav", 4, "audio/x-wav", 11},\r
- {".mp3", 4, "audio/x-mp3", 11},\r
- {".mid", 4, "audio/mid", 9},\r
- {".m3u", 4, "audio/x-mpegurl", 15},\r
- {".ram", 4, "audio/x-pn-realaudio", 20},\r
- {".xml", 4, "text/xml", 8},\r
- {".xslt", 5, "application/xml", 15},\r
- {".ra", 3, "audio/x-pn-realaudio", 20},\r
- {".doc", 4, "application/msword", 19},\r
- {".exe", 4, "application/octet-stream", 24},\r
- {".zip", 4, "application/x-zip-compressed", 28},\r
- {".xls", 4, "application/excel", 17},\r
- {".tgz", 4, "application/x-tar-gz", 20},\r
- {".tar", 4, "application/x-tar", 17},\r
- {".gz", 3, "application/x-gunzip", 20},\r
- {".arj", 4, "application/x-arj-compressed", 28},\r
- {".rar", 4, "application/x-arj-compressed", 28},\r
- {".rtf", 4, "application/rtf", 15},\r
- {".pdf", 4, "application/pdf", 15},\r
- {".swf", 4, "application/x-shockwave-flash",29},\r
- {".mpg", 4, "video/mpeg", 10},\r
- {".mpeg", 5, "video/mpeg", 10},\r
- {".mp4", 4, "video/mp4", 9},\r
- {".m4v", 4, "video/x-m4v", 11},\r
- {".asf", 4, "video/x-ms-asf", 14},\r
- {".avi", 4, "video/x-msvideo", 15},\r
- {".bmp", 4, "image/bmp", 9},\r
- {NULL, 0, NULL, 0}\r
-};\r
-\r
-// Look at the "path" extension and figure what mime type it has.\r
-// Store mime type in the vector.\r
-static void get_mime_type(struct mg_context *ctx, const char *path,\r
- struct vec *vec) {\r
- struct vec ext_vec, mime_vec;\r
- const char *list, *ext;\r
- size_t i, path_len;\r
-\r
- path_len = strlen(path);\r
-\r
- // Scan user-defined mime types first, in case user wants to\r
- // override default mime types.\r
- list = ctx->config[EXTRA_MIME_TYPES];\r
- while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {\r
- // ext now points to the path suffix\r
- ext = path + path_len - ext_vec.len;\r
- if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {\r
- *vec = mime_vec;\r
- return;\r
- }\r
- }\r
-\r
- // Now scan built-in mime types\r
- for (i = 0; builtin_mime_types[i].extension != NULL; i++) {\r
- ext = path + (path_len - builtin_mime_types[i].ext_len);\r
- if (path_len > builtin_mime_types[i].ext_len &&\r
- mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {\r
- vec->ptr = builtin_mime_types[i].mime_type;\r
- vec->len = builtin_mime_types[i].mime_type_len;\r
- return;\r
- }\r
- }\r
-\r
- // Nothing found. Fall back to "text/plain"\r
- vec->ptr = "text/plain";\r
- vec->len = 10;\r
-}\r
-\r
-#ifndef HAVE_MD5\r
-typedef struct MD5Context {\r
- uint32_t buf[4];\r
- uint32_t bits[2];\r
- unsigned char in[64];\r
-} MD5_CTX;\r
-\r
-#if defined(__BYTE_ORDER) && (__BYTE_ORDER == 1234)\r
-#define byteReverse(buf, len) // Do nothing\r
-#else\r
-static void byteReverse(unsigned char *buf, unsigned longs) {\r
- uint32_t t;\r
- do {\r
- t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |\r
- ((unsigned) buf[1] << 8 | buf[0]);\r
- *(uint32_t *) buf = t;\r
- buf += 4;\r
- } while (--longs);\r
-}\r
-#endif\r
-\r
-#define F1(x, y, z) (z ^ (x & (y ^ z)))\r
-#define F2(x, y, z) F1(z, x, y)\r
-#define F3(x, y, z) (x ^ y ^ z)\r
-#define F4(x, y, z) (y ^ (x | ~z))\r
-\r
-#define MD5STEP(f, w, x, y, z, data, s) \\r
- ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )\r
-\r
-// Start MD5 accumulation. Set bit count to 0 and buffer to mysterious\r
-// initialization constants.\r
-static void MD5Init(MD5_CTX *ctx) {\r
- ctx->buf[0] = 0x67452301;\r
- ctx->buf[1] = 0xefcdab89;\r
- ctx->buf[2] = 0x98badcfe;\r
- ctx->buf[3] = 0x10325476;\r
-\r
- ctx->bits[0] = 0;\r
- ctx->bits[1] = 0;\r
-}\r
-\r
-static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {\r
- register uint32_t a, b, c, d;\r
-\r
- a = buf[0];\r
- b = buf[1];\r
- c = buf[2];\r
- d = buf[3];\r
-\r
- MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);\r
- MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);\r
- MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);\r
- MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);\r
- MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);\r
- MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);\r
- MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);\r
- MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);\r
- MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);\r
- MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);\r
- MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);\r
- MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);\r
- MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);\r
- MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);\r
- MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);\r
- MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);\r
-\r
- MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);\r
- MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);\r
- MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);\r
- MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);\r
- MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);\r
- MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);\r
- MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);\r
- MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);\r
- MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);\r
- MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);\r
- MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);\r
- MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);\r
- MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);\r
- MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);\r
- MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);\r
- MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);\r
-\r
- MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);\r
- MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);\r
- MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);\r
- MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);\r
- MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);\r
- MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);\r
- MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);\r
- MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);\r
- MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);\r
- MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);\r
- MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);\r
- MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);\r
- MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);\r
- MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);\r
- MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);\r
- MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);\r
-\r
- MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);\r
- MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);\r
- MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);\r
- MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);\r
- MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);\r
- MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);\r
- MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);\r
- MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);\r
- MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);\r
- MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);\r
- MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);\r
- MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);\r
- MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);\r
- MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);\r
- MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);\r
- MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);\r
-\r
- buf[0] += a;\r
- buf[1] += b;\r
- buf[2] += c;\r
- buf[3] += d;\r
-}\r
-\r
-static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {\r
- uint32_t t;\r
-\r
- t = ctx->bits[0];\r
- if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)\r
- ctx->bits[1]++;\r
- ctx->bits[1] += len >> 29;\r
-\r
- t = (t >> 3) & 0x3f;\r
-\r
- if (t) {\r
- unsigned char *p = (unsigned char *) ctx->in + t;\r
-\r
- t = 64 - t;\r
- if (len < t) {\r
- memcpy(p, buf, len);\r
- return;\r
- }\r
- memcpy(p, buf, t);\r
- byteReverse(ctx->in, 16);\r
- MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
- buf += t;\r
- len -= t;\r
- }\r
-\r
- while (len >= 64) {\r
- memcpy(ctx->in, buf, 64);\r
- byteReverse(ctx->in, 16);\r
- MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
- buf += 64;\r
- len -= 64;\r
- }\r
-\r
- memcpy(ctx->in, buf, len);\r
-}\r
-\r
-static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {\r
- unsigned count;\r
- unsigned char *p;\r
-\r
- count = (ctx->bits[0] >> 3) & 0x3F;\r
-\r
- p = ctx->in + count;\r
- *p++ = 0x80;\r
- count = 64 - 1 - count;\r
- if (count < 8) {\r
- memset(p, 0, count);\r
- byteReverse(ctx->in, 16);\r
- MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
- memset(ctx->in, 0, 56);\r
- } else {\r
- memset(p, 0, count - 8);\r
- }\r
- byteReverse(ctx->in, 14);\r
-\r
- ((uint32_t *) ctx->in)[14] = ctx->bits[0];\r
- ((uint32_t *) ctx->in)[15] = ctx->bits[1];\r
-\r
- MD5Transform(ctx->buf, (uint32_t *) ctx->in);\r
- byteReverse((unsigned char *) ctx->buf, 4);\r
- memcpy(digest, ctx->buf, 16);\r
- memset((char *) ctx, 0, sizeof(*ctx));\r
-}\r
-#endif // !HAVE_MD5\r
-\r
-// Stringify binary data. Output buffer must be twice as big as input,\r
-// because each byte takes 2 bytes in string representation\r
-static void bin2str(char *to, const unsigned char *p, size_t len) {\r
- static const char *hex = "0123456789abcdef";\r
-\r
- for (; len--; p++) {\r
- *to++ = hex[p[0] >> 4];\r
- *to++ = hex[p[0] & 0x0f];\r
- }\r
- *to = '\0';\r
-}\r
-\r
-// Return stringified MD5 hash for list of vectors. Buffer must be 33 bytes.\r
-void mg_md5(char *buf, ...) {\r
- unsigned char hash[16];\r
- const char *p;\r
- va_list ap;\r
- MD5_CTX ctx;\r
-\r
- MD5Init(&ctx);\r
-\r
- va_start(ap, buf);\r
- while ((p = va_arg(ap, const char *)) != NULL) {\r
- MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));\r
- }\r
- va_end(ap);\r
-\r
- MD5Final(hash, &ctx);\r
- bin2str(buf, hash, sizeof(hash));\r
-}\r
-\r
-// Check the user's password, return 1 if OK\r
-static int check_password(const char *method, const char *ha1, const char *uri,\r
- const char *nonce, const char *nc, const char *cnonce,\r
- const char *qop, const char *response) {\r
- char ha2[32 + 1], expected_response[32 + 1];\r
-\r
- // Some of the parameters may be NULL\r
- if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||\r
- qop == NULL || response == NULL) {\r
- return 0;\r
- }\r
-\r
- // NOTE(lsm): due to a bug in MSIE, we do not compare the URI\r
- // TODO(lsm): check for authentication timeout\r
- if (// strcmp(dig->uri, c->ouri) != 0 ||\r
- strlen(response) != 32\r
- // || now - strtoul(dig->nonce, NULL, 10) > 3600\r
- ) {\r
- return 0;\r
- }\r
-\r
- mg_md5(ha2, method, ":", uri, NULL);\r
- mg_md5(expected_response, ha1, ":", nonce, ":", nc,\r
- ":", cnonce, ":", qop, ":", ha2, NULL);\r
-\r
- return mg_strcasecmp(response, expected_response) == 0;\r
-}\r
-\r
-// Use the global passwords file, if specified by auth_gpass option,\r
-// or search for .htpasswd in the requested directory.\r
-static FILE *open_auth_file(struct mg_connection *conn, const char *path) {\r
- struct mg_context *ctx = conn->ctx;\r
- char name[PATH_MAX];\r
- const char *p, *e;\r
- struct mgstat st;\r
- FILE *fp;\r
-\r
- if (ctx->config[GLOBAL_PASSWORDS_FILE] != NULL) {\r
- // Use global passwords file\r
- fp = mg_fopen(ctx->config[GLOBAL_PASSWORDS_FILE], "r");\r
- if (fp == NULL)\r
- cry(fc(ctx), "fopen(%s): %s",\r
- ctx->config[GLOBAL_PASSWORDS_FILE], strerror(ERRNO));\r
- } else if (!mg_stat(path, &st) && st.is_directory) {\r
- (void) mg_snprintf(conn, name, sizeof(name), "%s%c%s",\r
- path, DIRSEP, PASSWORDS_FILE_NAME);\r
- fp = mg_fopen(name, "r");\r
- } else {\r
- // Try to find .htpasswd in requested directory.\r
- for (p = path, e = p + strlen(p) - 1; e > p; e--)\r
- if (IS_DIRSEP_CHAR(*e))\r
- break;\r
- (void) mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",\r
- (int) (e - p), p, DIRSEP, PASSWORDS_FILE_NAME);\r
- fp = mg_fopen(name, "r");\r
- }\r
-\r
- return fp;\r
-}\r
-\r
-// Parsed Authorization header\r
-struct ah {\r
- char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;\r
-};\r
-\r
-static int parse_auth_header(struct mg_connection *conn, char *buf,\r
- size_t buf_size, struct ah *ah) {\r
- char *name, *value, *s;\r
- const char *auth_header;\r
-\r
- if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||\r
- mg_strncasecmp(auth_header, "Digest ", 7) != 0) {\r
- return 0;\r
- }\r
-\r
- // Make modifiable copy of the auth header\r
- (void) mg_strlcpy(buf, auth_header + 7, buf_size);\r
-\r
- s = buf;\r
- (void) memset(ah, 0, sizeof(*ah));\r
-\r
- // Parse authorization header\r
- for (;;) {\r
- // Gobble initial spaces\r
- while (isspace(* (unsigned char *) s)) {\r
- s++;\r
- }\r
- name = skip_quoted(&s, "=", " ", 0);\r
- // Value is either quote-delimited, or ends at first comma or space.\r
- if (s[0] == '\"') {\r
- s++;\r
- value = skip_quoted(&s, "\"", " ", '\\');\r
- if (s[0] == ',') {\r
- s++;\r
- }\r
- } else {\r
- value = skip_quoted(&s, ", ", " ", 0); // IE uses commas, FF uses spaces\r
- }\r
- if (*name == '\0') {\r
- break;\r
- }\r
-\r
- if (!strcmp(name, "username")) {\r
- ah->user = value;\r
- } else if (!strcmp(name, "cnonce")) {\r
- ah->cnonce = value;\r
- } else if (!strcmp(name, "response")) {\r
- ah->response = value;\r
- } else if (!strcmp(name, "uri")) {\r
- ah->uri = value;\r
- } else if (!strcmp(name, "qop")) {\r
- ah->qop = value;\r
- } else if (!strcmp(name, "nc")) {\r
- ah->nc = value;\r
- } else if (!strcmp(name, "nonce")) {\r
- ah->nonce = value;\r
- }\r
- }\r
-\r
- // CGI needs it as REMOTE_USER\r
- if (ah->user != NULL) {\r
- conn->request_info.remote_user = mg_strdup(ah->user);\r
- } else {\r
- return 0;\r
- }\r
-\r
- return 1;\r
-}\r
-\r
-// Authorize against the opened passwords file. Return 1 if authorized.\r
-static int authorize(struct mg_connection *conn, FILE *fp) {\r
- struct ah ah;\r
- char line[256], f_user[256], ha1[256], f_domain[256], buf[BUFSIZ];\r
-\r
- if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {\r
- return 0;\r
- }\r
-\r
- // Loop over passwords file\r
- while (fgets(line, sizeof(line), fp) != NULL) {\r
- if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {\r
- continue;\r
- }\r
-\r
- if (!strcmp(ah.user, f_user) &&\r
- !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))\r
- return check_password(\r
- conn->request_info.request_method,\r
- ha1, ah.uri, ah.nonce, ah.nc, ah.cnonce, ah.qop,\r
- ah.response);\r
- }\r
-\r
- return 0;\r
-}\r
-\r
-// Return 1 if request is authorised, 0 otherwise.\r
-static int check_authorization(struct mg_connection *conn, const char *path) {\r
- FILE *fp;\r
- char fname[PATH_MAX];\r
- struct vec uri_vec, filename_vec;\r
- const char *list;\r
- int authorized;\r
-\r
- fp = NULL;\r
- authorized = 1;\r
-\r
- list = conn->ctx->config[PROTECT_URI];\r
- while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {\r
- if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {\r
- (void) mg_snprintf(conn, fname, sizeof(fname), "%.*s",\r
- filename_vec.len, filename_vec.ptr);\r
- if ((fp = mg_fopen(fname, "r")) == NULL) {\r
- cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));\r
- }\r
- break;\r
- }\r
- }\r
-\r
- if (fp == NULL) {\r
- fp = open_auth_file(conn, path);\r
- }\r
-\r
- if (fp != NULL) {\r
- authorized = authorize(conn, fp);\r
- (void) fclose(fp);\r
- }\r
-\r
- return authorized;\r
-}\r
-\r
-static void send_authorization_request(struct mg_connection *conn) {\r
- conn->request_info.status_code = 401;\r
- (void) mg_printf(conn,\r
- "HTTP/1.1 401 Unauthorized\r\n"\r
- "Content-Length: 0\r\n"\r
- "WWW-Authenticate: Digest qop=\"auth\", "\r
- "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",\r
- conn->ctx->config[AUTHENTICATION_DOMAIN],\r
- (unsigned long) time(NULL));\r
-}\r
-\r
-static int is_authorized_for_put(struct mg_connection *conn) {\r
- FILE *fp;\r
- int ret = 0;\r
-\r
- fp = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ? NULL :\r
- mg_fopen(conn->ctx->config[PUT_DELETE_PASSWORDS_FILE], "r");\r
-\r
- if (fp != NULL) {\r
- ret = authorize(conn, fp);\r
- (void) fclose(fp);\r
- }\r
-\r
- return ret;\r
-}\r
-\r
-int mg_modify_passwords_file(const char *fname, const char *domain,\r
- const char *user, const char *pass) {\r
- int found;\r
- char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];\r
- FILE *fp, *fp2;\r
-\r
- found = 0;\r
- fp = fp2 = NULL;\r
-\r
- // Regard empty password as no password - remove user record.\r
- if (pass != NULL && pass[0] == '\0') {\r
- pass = NULL;\r
- }\r
-\r
- (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);\r
-\r
- // Create the file if does not exist\r
- if ((fp = mg_fopen(fname, "a+")) != NULL) {\r
- (void) fclose(fp);\r
- }\r
-\r
- // Open the given file and temporary file\r
- if ((fp = mg_fopen(fname, "r")) == NULL) {\r
- return 0;\r
- } else if ((fp2 = mg_fopen(tmp, "w+")) == NULL) {\r
- fclose(fp);\r
- return 0;\r
- }\r
-\r
- // Copy the stuff to temporary file\r
- while (fgets(line, sizeof(line), fp) != NULL) {\r
- if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {\r
- continue;\r
- }\r
-\r
- if (!strcmp(u, user) && !strcmp(d, domain)) {\r
- found++;\r
- if (pass != NULL) {\r
- mg_md5(ha1, user, ":", domain, ":", pass, NULL);\r
- fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);\r
- }\r
- } else {\r
- (void) fprintf(fp2, "%s", line);\r
- }\r
- }\r
-\r
- // If new user, just add it\r
- if (!found && pass != NULL) {\r
- mg_md5(ha1, user, ":", domain, ":", pass, NULL);\r
- (void) fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);\r
- }\r
-\r
- // Close files\r
- (void) fclose(fp);\r
- (void) fclose(fp2);\r
-\r
- // Put the temp file in place of real file\r
- (void) mg_remove(fname);\r
- (void) mg_rename(tmp, fname);\r
-\r
- return 1;\r
-}\r
-\r
-struct de {\r
- struct mg_connection *conn;\r
- char *file_name;\r
- struct mgstat st;\r
-};\r
-\r
-static void url_encode(const char *src, char *dst, size_t dst_len) {\r
- static const char *dont_escape = "._-$,;~()";\r
- static const char *hex = "0123456789abcdef";\r
- const char *end = dst + dst_len - 1;\r
-\r
- for (; *src != '\0' && dst < end; src++, dst++) {\r
- if (isalnum(*(const unsigned char *) src) ||\r
- strchr(dont_escape, * (const unsigned char *) src) != NULL) {\r
- *dst = *src;\r
- } else if (dst + 2 < end) {\r
- dst[0] = '%';\r
- dst[1] = hex[(* (const unsigned char *) src) >> 4];\r
- dst[2] = hex[(* (const unsigned char *) src) & 0xf];\r
- dst += 2;\r
- }\r
- }\r
-\r
- *dst = '\0';\r
-}\r
-\r
-static void print_dir_entry(struct de *de) {\r
- char size[64], mod[64], href[PATH_MAX];\r
-\r
- if (de->st.is_directory) {\r
- (void) mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");\r
- } else {\r
- // We use (signed) cast below because MSVC 6 compiler cannot\r
- // convert unsigned __int64 to double. Sigh.\r
- if (de->st.size < 1024) {\r
- (void) mg_snprintf(de->conn, size, sizeof(size),\r
- "%lu", (unsigned long) de->st.size);\r
- } else if (de->st.size < 1024 * 1024) {\r
- (void) mg_snprintf(de->conn, size, sizeof(size),\r
- "%.1fk", (double) de->st.size / 1024.0);\r
- } else if (de->st.size < 1024 * 1024 * 1024) {\r
- (void) mg_snprintf(de->conn, size, sizeof(size),\r
- "%.1fM", (double) de->st.size / 1048576);\r
- } else {\r
- (void) mg_snprintf(de->conn, size, sizeof(size),\r
- "%.1fG", (double) de->st.size / 1073741824);\r
- }\r
- }\r
- (void) strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.mtime));\r
- url_encode(de->file_name, href, sizeof(href));\r
- de->conn->num_bytes_sent += mg_printf(de->conn,\r
- "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"\r
- "<td> %s</td><td> %s</td></tr>\n",\r
- de->conn->request_info.uri, href, de->st.is_directory ? "/" : "",\r
- de->file_name, de->st.is_directory ? "/" : "", mod, size);\r
-}\r
-\r
-// This function is called from send_directory() and used for\r
-// sorting directory entries by size, or name, or modification time.\r
-// On windows, __cdecl specification is needed in case if project is built\r
-// with __stdcall convention. qsort always requires __cdels callback.\r
-static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {\r
- const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;\r
- const char *query_string = a->conn->request_info.query_string;\r
- int cmp_result = 0;\r
-\r
- if (query_string == NULL) {\r
- query_string = "na";\r
- }\r
-\r
- if (a->st.is_directory && !b->st.is_directory) {\r
- return -1; // Always put directories on top\r
- } else if (!a->st.is_directory && b->st.is_directory) {\r
- return 1; // Always put directories on top\r
- } else if (*query_string == 'n') {\r
- cmp_result = strcmp(a->file_name, b->file_name);\r
- } else if (*query_string == 's') {\r
- cmp_result = a->st.size == b->st.size ? 0 :\r
- a->st.size > b->st.size ? 1 : -1;\r
- } else if (*query_string == 'd') {\r
- cmp_result = a->st.mtime == b->st.mtime ? 0 :\r
- a->st.mtime > b->st.mtime ? 1 : -1;\r
- }\r
-\r
- return query_string[1] == 'd' ? -cmp_result : cmp_result;\r
-}\r
-\r
-static int scan_directory(struct mg_connection *conn, const char *dir,\r
- void *data, void (*cb)(struct de *, void *)) {\r
- char path[PATH_MAX];\r
- struct dirent *dp;\r
- DIR *dirp;\r
- struct de de;\r
-\r
- if ((dirp = opendir(dir)) == NULL) {\r
- return 0;\r
- } else {\r
- de.conn = conn;\r
-\r
- while ((dp = readdir(dirp)) != NULL) {\r
- // Do not show current dir and passwords file\r
- if (!strcmp(dp->d_name, ".") ||\r
- !strcmp(dp->d_name, "..") ||\r
- !strcmp(dp->d_name, PASSWORDS_FILE_NAME))\r
- continue;\r
-\r
- mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, DIRSEP, dp->d_name);\r
-\r
- // If we don't memset stat structure to zero, mtime will have\r
- // garbage and strftime() will segfault later on in\r
- // print_dir_entry(). memset is required only if mg_stat()\r
- // fails. For more details, see\r
- // http://code.google.com/p/mongoose/issues/detail?id=79\r
- if (mg_stat(path, &de.st) != 0) {\r
- memset(&de.st, 0, sizeof(de.st));\r
- }\r
- de.file_name = dp->d_name;\r
-\r
- cb(&de, data);\r
- }\r
- (void) closedir(dirp);\r
- }\r
- return 1;\r
-}\r
-\r
-struct dir_scan_data {\r
- struct de *entries;\r
- int num_entries;\r
- int arr_size;\r
-};\r
-\r
-static void dir_scan_callback(struct de *de, void *data) {\r
- struct dir_scan_data *dsd = (struct dir_scan_data *) data;\r
-\r
- if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {\r
- dsd->arr_size *= 2;\r
- dsd->entries = (struct de *) realloc(dsd->entries, dsd->arr_size *\r
- sizeof(dsd->entries[0]));\r
- }\r
- if (dsd->entries == NULL) {\r
- // TODO(lsm): propagate an error to the caller\r
- dsd->num_entries = 0;\r
- } else {\r
- dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);\r
- dsd->entries[dsd->num_entries].st = de->st;\r
- dsd->entries[dsd->num_entries].conn = de->conn;\r
- dsd->num_entries++;\r
- }\r
-}\r
-\r
-static void handle_directory_request(struct mg_connection *conn,\r
- const char *dir) {\r
- int i, sort_direction;\r
- struct dir_scan_data data = { NULL, 0, 128 };\r
-\r
- if (!scan_directory(conn, dir, &data, dir_scan_callback)) {\r
- send_http_error(conn, 500, "Cannot open directory",\r
- "Error: opendir(%s): %s", dir, strerror(ERRNO));\r
- return;\r
- }\r
-\r
- sort_direction = conn->request_info.query_string != NULL &&\r
- conn->request_info.query_string[1] == 'd' ? 'a' : 'd';\r
-\r
- conn->must_close = 1;\r
- mg_printf(conn, "%s",\r
- "HTTP/1.1 200 OK\r\n"\r
- "Connection: close\r\n"\r
- "Content-Type: text/html; charset=utf-8\r\n\r\n");\r
-\r
- conn->num_bytes_sent += mg_printf(conn,\r
- "<html><head><title>Index of %s</title>"\r
- "<style>th {text-align: left;}</style></head>"\r
- "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"\r
- "<tr><th><a href=\"?n%c\">Name</a></th>"\r
- "<th><a href=\"?d%c\">Modified</a></th>"\r
- "<th><a href=\"?s%c\">Size</a></th></tr>"\r
- "<tr><td colspan=\"3\"><hr></td></tr>",\r
- conn->request_info.uri, conn->request_info.uri,\r
- sort_direction, sort_direction, sort_direction);\r
-\r
- // Print first entry - link to a parent directory\r
- conn->num_bytes_sent += mg_printf(conn,\r
- "<tr><td><a href=\"%s%s\">%s</a></td>"\r
- "<td> %s</td><td> %s</td></tr>\n",\r
- conn->request_info.uri, "..", "Parent directory", "-", "-");\r
-\r
- // Sort and print directory entries\r
- qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),\r
- compare_dir_entries);\r
- for (i = 0; i < data.num_entries; i++) {\r
- print_dir_entry(&data.entries[i]);\r
- free(data.entries[i].file_name);\r
- }\r
- free(data.entries);\r
-\r
- conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");\r
- conn->request_info.status_code = 200;\r
-}\r
-\r
-// Send len bytes from the opened file to the client.\r
-static void send_file_data(struct mg_connection *conn, FILE *fp, int64_t len) {\r
- char buf[BUFSIZ];\r
- int to_read, num_read, num_written;\r
-\r
- while (len > 0) {\r
- // Calculate how much to read from the file in the buffer\r
- to_read = sizeof(buf);\r
- if ((int64_t) to_read > len)\r
- to_read = (int) len;\r
-\r
- // Read from file, exit the loop on error\r
- if ((num_read = fread(buf, 1, (size_t)to_read, fp)) == 0)\r
- break;\r
-\r
- // Send read bytes to the client, exit the loop on error\r
- if ((num_written = mg_write(conn, buf, (size_t)num_read)) != num_read)\r
- break;\r
-\r
- // Both read and were successful, adjust counters\r
- conn->num_bytes_sent += num_written;\r
- len -= num_written;\r
- }\r
-}\r
-\r
-static int parse_range_header(const char *header, int64_t *a, int64_t *b) {\r
- return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);\r
-}\r
-\r
-static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {\r
- strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));\r
-}\r
-\r
-static void handle_file_request(struct mg_connection *conn, const char *path,\r
- struct mgstat *stp) {\r
- char date[64], lm[64], etag[64], range[64];\r
- const char *msg = "OK", *hdr;\r
- time_t curtime = time(NULL);\r
- int64_t cl, r1, r2;\r
- struct vec mime_vec;\r
- FILE *fp;\r
- int n;\r
-\r
- get_mime_type(conn->ctx, path, &mime_vec);\r
- cl = stp->size;\r
- conn->request_info.status_code = 200;\r
- range[0] = '\0';\r
-\r
- if ((fp = mg_fopen(path, "rb")) == NULL) {\r
- send_http_error(conn, 500, http_500_error,\r
- "fopen(%s): %s", path, strerror(ERRNO));\r
- return;\r
- }\r
- set_close_on_exec(fileno(fp));\r
-\r
- // If Range: header specified, act accordingly\r
- r1 = r2 = 0;\r
- hdr = mg_get_header(conn, "Range");\r
- if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) {\r
- conn->request_info.status_code = 206;\r
- (void) fseeko(fp, (off_t) r1, SEEK_SET);\r
- cl = n == 2 ? r2 - r1 + 1: cl - r1;\r
- (void) mg_snprintf(conn, range, sizeof(range),\r
- "Content-Range: bytes "\r
- "%" INT64_FMT "-%"\r
- INT64_FMT "/%" INT64_FMT "\r\n",\r
- r1, r1 + cl - 1, stp->size);\r
- msg = "Partial Content";\r
- }\r
-\r
- // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to\r
- // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3\r
- gmt_time_string(date, sizeof(date), &curtime);\r
- gmt_time_string(lm, sizeof(lm), &stp->mtime);\r
- (void) mg_snprintf(conn, etag, sizeof(etag), "%lx.%lx",\r
- (unsigned long) stp->mtime, (unsigned long) stp->size);\r
-\r
- (void) mg_printf(conn,\r
- "HTTP/1.1 %d %s\r\n"\r
- "Date: %s\r\n"\r
- "Last-Modified: %s\r\n"\r
- "Etag: \"%s\"\r\n"\r
- "Content-Type: %.*s\r\n"\r
- "Content-Length: %" INT64_FMT "\r\n"\r
- "Connection: %s\r\n"\r
- "Accept-Ranges: bytes\r\n"\r
- "%s\r\n",\r
- conn->request_info.status_code, msg, date, lm, etag, (int) mime_vec.len,\r
- mime_vec.ptr, cl, suggest_connection_header(conn), range);\r
-\r
- if (strcmp(conn->request_info.request_method, "HEAD") != 0) {\r
- send_file_data(conn, fp, cl);\r
- }\r
- (void) fclose(fp);\r
-}\r
-\r
-void mg_send_file(struct mg_connection *conn, const char *path) {\r
- struct mgstat st;\r
- if (mg_stat(path, &st) == 0) {\r
- handle_file_request(conn, path, &st);\r
- } else {\r
- send_http_error(conn, 404, "Not Found", "%s", "File not found");\r
- }\r
-}\r
-\r
-\r
-// Parse HTTP headers from the given buffer, advance buffer to the point\r
-// where parsing stopped.\r
-static void parse_http_headers(char **buf, struct mg_request_info *ri) {\r
- int i;\r
-\r
- for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {\r
- ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);\r
- ri->http_headers[i].value = skip(buf, "\r\n");\r
- if (ri->http_headers[i].name[0] == '\0')\r
- break;\r
- ri->num_headers = i + 1;\r
- }\r
-}\r
-\r
-static int is_valid_http_method(const char *method) {\r
- return !strcmp(method, "GET") || !strcmp(method, "POST") ||\r
- !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||\r
- !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||\r
- !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND");\r
-}\r
-\r
-// Parse HTTP request, fill in mg_request_info structure.\r
-static int parse_http_request(char *buf, struct mg_request_info *ri) {\r
- int status = 0;\r
-\r
- // RFC says that all initial whitespaces should be ingored\r
- while (*buf != '\0' && isspace(* (unsigned char *) buf)) {\r
- buf++;\r
- }\r
-\r
- ri->request_method = skip(&buf, " ");\r
- ri->uri = skip(&buf, " ");\r
- ri->http_version = skip(&buf, "\r\n");\r
-\r
- if (is_valid_http_method(ri->request_method) &&\r
- strncmp(ri->http_version, "HTTP/", 5) == 0) {\r
- ri->http_version += 5; // Skip "HTTP/"\r
- parse_http_headers(&buf, ri);\r
- status = 1;\r
- }\r
-\r
- return status;\r
-}\r
-\r
-// Keep reading the input (either opened file descriptor fd, or socket sock,\r
-// or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the\r
-// buffer (which marks the end of HTTP request). Buffer buf may already\r
-// have some data. The length of the data is stored in nread.\r
-// Upon every read operation, increase nread by the number of bytes read.\r
-static int read_request(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int bufsiz,\r
- int *nread) {\r
- int n, request_len;\r
-\r
- request_len = 0;\r
- while (*nread < bufsiz && request_len == 0) {\r
- n = pull(fp, sock, ssl, buf + *nread, bufsiz - *nread);\r
- if (n <= 0) {\r
- break;\r
- } else {\r
- *nread += n;\r
- request_len = get_request_len(buf, *nread);\r
- }\r
- }\r
-\r
- return request_len;\r
-}\r
-\r
-// For given directory path, substitute it to valid index file.\r
-// Return 0 if index file has been found, -1 if not found.\r
-// If the file is found, it's stats is returned in stp.\r
-static int substitute_index_file(struct mg_connection *conn, char *path,\r
- size_t path_len, struct mgstat *stp) {\r
- const char *list = conn->ctx->config[INDEX_FILES];\r
- struct mgstat st;\r
- struct vec filename_vec;\r
- size_t n = strlen(path);\r
- int found = 0;\r
-\r
- // The 'path' given to us points to the directory. Remove all trailing\r
- // directory separator characters from the end of the path, and\r
- // then append single directory separator character.\r
- while (n > 0 && IS_DIRSEP_CHAR(path[n - 1])) {\r
- n--;\r
- }\r
- path[n] = DIRSEP;\r
-\r
- // Traverse index files list. For each entry, append it to the given\r
- // path and see if the file exists. If it exists, break the loop\r
- while ((list = next_option(list, &filename_vec, NULL)) != NULL) {\r
-\r
- // Ignore too long entries that may overflow path buffer\r
- if (filename_vec.len > path_len - (n + 2))\r
- continue;\r
-\r
- // Prepare full path to the index file\r
- (void) mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);\r
-\r
- // Does it exist?\r
- if (mg_stat(path, &st) == 0) {\r
- // Yes it does, break the loop\r
- *stp = st;\r
- found = 1;\r
- break;\r
- }\r
- }\r
-\r
- // If no index file exists, restore directory path\r
- if (!found) {\r
- path[n] = '\0';\r
- }\r
-\r
- return found;\r
-}\r
-\r
-// Return True if we should reply 304 Not Modified.\r
-static int is_not_modified(const struct mg_connection *conn,\r
- const struct mgstat *stp) {\r
- const char *ims = mg_get_header(conn, "If-Modified-Since");\r
- return ims != NULL && stp->mtime <= parse_date_string(ims);\r
-}\r
-\r
-static int forward_body_data(struct mg_connection *conn, FILE *fp,\r
- SOCKET sock, SSL *ssl) {\r
- const char *expect, *buffered;\r
- char buf[BUFSIZ];\r
- int to_read, nread, buffered_len, success = 0;\r
-\r
- expect = mg_get_header(conn, "Expect");\r
- assert(fp != NULL);\r
-\r
- if (conn->content_len == -1) {\r
- send_http_error(conn, 411, "Length Required", "");\r
- } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {\r
- send_http_error(conn, 417, "Expectation Failed", "");\r
- } else {\r
- if (expect != NULL) {\r
- (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");\r
- }\r
-\r
- buffered = conn->buf + conn->request_len;\r
- buffered_len = conn->data_len - conn->request_len;\r
- assert(buffered_len >= 0);\r
- assert(conn->consumed_content == 0);\r
-\r
- if (buffered_len > 0) {\r
- if ((int64_t) buffered_len > conn->content_len) {\r
- buffered_len = (int) conn->content_len;\r
- }\r
- push(fp, sock, ssl, buffered, (int64_t) buffered_len);\r
- conn->consumed_content += buffered_len;\r
- }\r
-\r
- while (conn->consumed_content < conn->content_len) {\r
- to_read = sizeof(buf);\r
- if ((int64_t) to_read > conn->content_len - conn->consumed_content) {\r
- to_read = (int) (conn->content_len - conn->consumed_content);\r
- }\r
- nread = pull(NULL, conn->client.sock, conn->ssl, buf, to_read);\r
- if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {\r
- break;\r
- }\r
- conn->consumed_content += nread;\r
- }\r
-\r
- if (conn->consumed_content == conn->content_len) {\r
- success = 1;\r
- }\r
-\r
- // Each error code path in this function must send an error\r
- if (!success) {\r
- send_http_error(conn, 577, http_500_error, "");\r
- }\r
- }\r
-\r
- return success;\r
-}\r
-\r
-#if !defined(NO_CGI)\r
-// This structure helps to create an environment for the spawned CGI program.\r
-// Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,\r
-// last element must be NULL.\r
-// However, on Windows there is a requirement that all these VARIABLE=VALUE\0\r
-// strings must reside in a contiguous buffer. The end of the buffer is\r
-// marked by two '\0' characters.\r
-// We satisfy both worlds: we create an envp array (which is vars), all\r
-// entries are actually pointers inside buf.\r
-struct cgi_env_block {\r
- struct mg_connection *conn;\r
- char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer\r
- int len; // Space taken\r
- char *vars[MAX_CGI_ENVIR_VARS]; // char **envp\r
- int nvars; // Number of variables\r
-};\r
-\r
-// Append VARIABLE=VALUE\0 string to the buffer, and add a respective\r
-// pointer into the vars array.\r
-static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {\r
- int n, space;\r
- char *added;\r
- va_list ap;\r
-\r
- // Calculate how much space is left in the buffer\r
- space = sizeof(block->buf) - block->len - 2;\r
- assert(space >= 0);\r
-\r
- // Make a pointer to the free space int the buffer\r
- added = block->buf + block->len;\r
-\r
- // Copy VARIABLE=VALUE\0 string into the free space\r
- va_start(ap, fmt);\r
- n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);\r
- va_end(ap);\r
-\r
- // Make sure we do not overflow buffer and the envp array\r
- if (n > 0 && n < space &&\r
- block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {\r
- // Append a pointer to the added string into the envp array\r
- block->vars[block->nvars++] = block->buf + block->len;\r
- // Bump up used length counter. Include \0 terminator\r
- block->len += n + 1;\r
- }\r
-\r
- return added;\r
-}\r
-\r
-static void prepare_cgi_environment(struct mg_connection *conn,\r
- const char *prog,\r
- struct cgi_env_block *blk) {\r
- const char *s, *slash;\r
- struct vec var_vec;\r
- char *p, src_addr[20];\r
- int i;\r
-\r
- blk->len = blk->nvars = 0;\r
- blk->conn = conn;\r
- sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);\r
-\r
- addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);\r
- addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);\r
- addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);\r
-\r
- // Prepare the environment block\r
- addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");\r
- addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");\r
- addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP\r
-\r
- // TODO(lsm): fix this for IPv6 case\r
- addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));\r
-\r
- addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);\r
- addenv(blk, "REMOTE_ADDR=%s", src_addr);\r
- addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);\r
- addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);\r
-\r
- // SCRIPT_NAME\r
- assert(conn->request_info.uri[0] == '/');\r
- slash = strrchr(conn->request_info.uri, '/');\r
- if ((s = strrchr(prog, '/')) == NULL)\r
- s = prog;\r
- addenv(blk, "SCRIPT_NAME=%.*s%s", slash - conn->request_info.uri,\r
- conn->request_info.uri, s);\r
-\r
- addenv(blk, "SCRIPT_FILENAME=%s", prog);\r
- addenv(blk, "PATH_TRANSLATED=%s", prog);\r
- addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");\r
-\r
- if ((s = mg_get_header(conn, "Content-Type")) != NULL)\r
- addenv(blk, "CONTENT_TYPE=%s", s);\r
-\r
- if (conn->request_info.query_string != NULL)\r
- addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);\r
-\r
- if ((s = mg_get_header(conn, "Content-Length")) != NULL)\r
- addenv(blk, "CONTENT_LENGTH=%s", s);\r
-\r
- if ((s = getenv("PATH")) != NULL)\r
- addenv(blk, "PATH=%s", s);\r
-\r
- if (conn->path_info != NULL) {\r
- addenv(blk, "PATH_INFO=%s", conn->path_info);\r
- }\r
-\r
-#if defined(_WIN32)\r
- if ((s = getenv("COMSPEC")) != NULL) {\r
- addenv(blk, "COMSPEC=%s", s);\r
- }\r
- if ((s = getenv("SYSTEMROOT")) != NULL) {\r
- addenv(blk, "SYSTEMROOT=%s", s);\r
- }\r
- if ((s = getenv("SystemDrive")) != NULL) {\r
- addenv(blk, "SystemDrive=%s", s);\r
- }\r
-#else\r
- if ((s = getenv("LD_LIBRARY_PATH")) != NULL)\r
- addenv(blk, "LD_LIBRARY_PATH=%s", s);\r
-#endif // _WIN32\r
-\r
- if ((s = getenv("PERLLIB")) != NULL)\r
- addenv(blk, "PERLLIB=%s", s);\r
-\r
- if (conn->request_info.remote_user != NULL) {\r
- addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);\r
- addenv(blk, "%s", "AUTH_TYPE=Digest");\r
- }\r
-\r
- // Add all headers as HTTP_* variables\r
- for (i = 0; i < conn->request_info.num_headers; i++) {\r
- p = addenv(blk, "HTTP_%s=%s",\r
- conn->request_info.http_headers[i].name,\r
- conn->request_info.http_headers[i].value);\r
-\r
- // Convert variable name into uppercase, and change - to _\r
- for (; *p != '=' && *p != '\0'; p++) {\r
- if (*p == '-')\r
- *p = '_';\r
- *p = (char) toupper(* (unsigned char *) p);\r
- }\r
- }\r
-\r
- // Add user-specified variables\r
- s = conn->ctx->config[CGI_ENVIRONMENT];\r
- while ((s = next_option(s, &var_vec, NULL)) != NULL) {\r
- addenv(blk, "%.*s", var_vec.len, var_vec.ptr);\r
- }\r
-\r
- blk->vars[blk->nvars++] = NULL;\r
- blk->buf[blk->len++] = '\0';\r
-\r
- assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));\r
- assert(blk->len > 0);\r
- assert(blk->len < (int) sizeof(blk->buf));\r
-}\r
-\r
-static void handle_cgi_request(struct mg_connection *conn, const char *prog) {\r
- int headers_len, data_len, i, fd_stdin[2], fd_stdout[2];\r
- const char *status, *status_text;\r
- char buf[BUFSIZ], *pbuf, dir[PATH_MAX], *p;\r
- struct mg_request_info ri;\r
- struct cgi_env_block blk;\r
- FILE *in, *out;\r
- pid_t pid;\r
-\r
- prepare_cgi_environment(conn, prog, &blk);\r
-\r
- // CGI must be executed in its own directory. 'dir' must point to the\r
- // directory containing executable program, 'p' must point to the\r
- // executable program name relative to 'dir'.\r
- (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);\r
- if ((p = strrchr(dir, DIRSEP)) != NULL) {\r
- *p++ = '\0';\r
- } else {\r
- dir[0] = '.', dir[1] = '\0';\r
- p = (char *) prog;\r
- }\r
-\r
- pid = (pid_t) -1;\r
- fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;\r
- in = out = NULL;\r
-\r
- if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {\r
- send_http_error(conn, 500, http_500_error,\r
- "Cannot create CGI pipe: %s", strerror(ERRNO));\r
- goto done;\r
- } else if ((pid = spawn_process(conn, p, blk.buf, blk.vars,\r
- fd_stdin[0], fd_stdout[1], dir)) == (pid_t) -1) {\r
- goto done;\r
- } else if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||\r
- (out = fdopen(fd_stdout[0], "rb")) == NULL) {\r
- send_http_error(conn, 500, http_500_error,\r
- "fopen: %s", strerror(ERRNO));\r
- goto done;\r
- }\r
-\r
- setbuf(in, NULL);\r
- setbuf(out, NULL);\r
-\r
- // spawn_process() must close those!\r
- // If we don't mark them as closed, close() attempt before\r
- // return from this function throws an exception on Windows.\r
- // Windows does not like when closed descriptor is closed again.\r
- fd_stdin[0] = fd_stdout[1] = -1;\r
-\r
- // Send POST data to the CGI process if needed\r
- if (!strcmp(conn->request_info.request_method, "POST") &&\r
- !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {\r
- goto done;\r
- }\r
-\r
- // Now read CGI reply into a buffer. We need to set correct\r
- // status code, thus we need to see all HTTP headers first.\r
- // Do not send anything back to client, until we buffer in all\r
- // HTTP headers.\r
- data_len = 0;\r
- headers_len = read_request(out, INVALID_SOCKET, NULL,\r
- buf, sizeof(buf), &data_len);\r
- if (headers_len <= 0) {\r
- send_http_error(conn, 500, http_500_error,\r
- "CGI program sent malformed HTTP headers: [%.*s]",\r
- data_len, buf);\r
- goto done;\r
- }\r
- pbuf = buf;\r
- buf[headers_len - 1] = '\0';\r
- parse_http_headers(&pbuf, &ri);\r
-\r
- // Make up and send the status line\r
- status_text = "OK";\r
- if ((status = get_header(&ri, "Status")) != NULL) {\r
- conn->request_info.status_code = atoi(status);\r
- status_text = status;\r
- while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {\r
- status_text++;\r
- }\r
- } else if (get_header(&ri, "Location") != NULL) {\r
- conn->request_info.status_code = 302;\r
- } else {\r
- conn->request_info.status_code = 200;\r
- }\r
- if (get_header(&ri, "Connection") != NULL &&\r
- !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) {\r
- conn->must_close = 1;\r
- }\r
- (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->request_info.status_code,\r
- status_text);\r
-\r
- // Send headers\r
- for (i = 0; i < ri.num_headers; i++) {\r
- mg_printf(conn, "%s: %s\r\n",\r
- ri.http_headers[i].name, ri.http_headers[i].value);\r
- }\r
- (void) mg_write(conn, "\r\n", 2);\r
-\r
- // Send chunk of data that may be read after the headers\r
- conn->num_bytes_sent += mg_write(conn, buf + headers_len,\r
- (size_t)(data_len - headers_len));\r
-\r
- // Read the rest of CGI output and send to the client\r
- send_file_data(conn, out, INT64_MAX);\r
-\r
-done:\r
- if (pid != (pid_t) -1) {\r
- kill(pid, SIGKILL);\r
- }\r
- if (fd_stdin[0] != -1) {\r
- (void) close(fd_stdin[0]);\r
- }\r
- if (fd_stdout[1] != -1) {\r
- (void) close(fd_stdout[1]);\r
- }\r
-\r
- if (in != NULL) {\r
- (void) fclose(in);\r
- } else if (fd_stdin[1] != -1) {\r
- (void) close(fd_stdin[1]);\r
- }\r
-\r
- if (out != NULL) {\r
- (void) fclose(out);\r
- } else if (fd_stdout[0] != -1) {\r
- (void) close(fd_stdout[0]);\r
- }\r
-}\r
-#endif // !NO_CGI\r
-\r
-// For a given PUT path, create all intermediate subdirectories\r
-// for given path. Return 0 if the path itself is a directory,\r
-// or -1 on error, 1 if OK.\r
-static int put_dir(const char *path) {\r
- char buf[PATH_MAX];\r
- const char *s, *p;\r
- struct mgstat st;\r
- int len, res = 1;\r
-\r
- for (s = p = path + 2; (p = strchr(s, DIRSEP)) != NULL; s = ++p) {\r
- len = p - path;\r
- if (len >= (int) sizeof(buf)) {\r
- res = -1;\r
- break;\r
- }\r
- memcpy(buf, path, len);\r
- buf[len] = '\0';\r
-\r
- // Try to create intermediate directory\r
- DEBUG_TRACE(("mkdir(%s)", buf));\r
- if (mg_stat(buf, &st) == -1 && mg_mkdir(buf, 0755) != 0) {\r
- res = -1;\r
- break;\r
- }\r
-\r
- // Is path itself a directory?\r
- if (p[1] == '\0') {\r
- res = 0;\r
- }\r
- }\r
-\r
- return res;\r
-}\r
-\r
-static void put_file(struct mg_connection *conn, const char *path) {\r
- struct mgstat st;\r
- const char *range;\r
- int64_t r1, r2;\r
- FILE *fp;\r
- int rc;\r
-\r
- conn->request_info.status_code = mg_stat(path, &st) == 0 ? 200 : 201;\r
-\r
- if ((rc = put_dir(path)) == 0) {\r
- mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->request_info.status_code);\r
- } else if (rc == -1) {\r
- send_http_error(conn, 500, http_500_error,\r
- "put_dir(%s): %s", path, strerror(ERRNO));\r
- } else if ((fp = mg_fopen(path, "wb+")) == NULL) {\r
- send_http_error(conn, 500, http_500_error,\r
- "fopen(%s): %s", path, strerror(ERRNO));\r
- } else {\r
- set_close_on_exec(fileno(fp));\r
- range = mg_get_header(conn, "Content-Range");\r
- r1 = r2 = 0;\r
- if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {\r
- conn->request_info.status_code = 206;\r
- // TODO(lsm): handle seek error\r
- (void) fseeko(fp, (off_t) r1, SEEK_SET);\r
- }\r
- if (forward_body_data(conn, fp, INVALID_SOCKET, NULL))\r
- (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n",\r
- conn->request_info.status_code);\r
- (void) fclose(fp);\r
- }\r
-}\r
-\r
-static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);\r
-\r
-static void do_ssi_include(struct mg_connection *conn, const char *ssi,\r
- char *tag, int include_level) {\r
- char file_name[BUFSIZ], path[PATH_MAX], *p;\r
- FILE *fp;\r
-\r
- // sscanf() is safe here, since send_ssi_file() also uses buffer\r
- // of size BUFSIZ to get the tag. So strlen(tag) is always < BUFSIZ.\r
- if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {\r
- // File name is relative to the webserver root\r
- (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",\r
- conn->ctx->config[DOCUMENT_ROOT], DIRSEP, file_name);\r
- } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {\r
- // File name is relative to the webserver working directory\r
- // or it is absolute system path\r
- (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);\r
- } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {\r
- // File name is relative to the currect document\r
- (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);\r
- if ((p = strrchr(path, DIRSEP)) != NULL) {\r
- p[1] = '\0';\r
- }\r
- (void) mg_snprintf(conn, path + strlen(path),\r
- sizeof(path) - strlen(path), "%s", file_name);\r
- } else {\r
- cry(conn, "Bad SSI #include: [%s]", tag);\r
- return;\r
- }\r
-\r
- if ((fp = mg_fopen(path, "rb")) == NULL) {\r
- cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",\r
- tag, path, strerror(ERRNO));\r
- } else {\r
- set_close_on_exec(fileno(fp));\r
- if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],\r
- strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {\r
- send_ssi_file(conn, path, fp, include_level + 1);\r
- } else {\r
- send_file_data(conn, fp, INT64_MAX);\r
- }\r
- (void) fclose(fp);\r
- }\r
-}\r
-\r
-#if !defined(NO_POPEN)\r
-static void do_ssi_exec(struct mg_connection *conn, char *tag) {\r
- char cmd[BUFSIZ];\r
- FILE *fp;\r
-\r
- if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {\r
- cry(conn, "Bad SSI #exec: [%s]", tag);\r
- } else if ((fp = popen(cmd, "r")) == NULL) {\r
- cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));\r
- } else {\r
- send_file_data(conn, fp, INT64_MAX);\r
- (void) pclose(fp);\r
- }\r
-}\r
-#endif // !NO_POPEN\r
-\r
-static void send_ssi_file(struct mg_connection *conn, const char *path,\r
- FILE *fp, int include_level) {\r
- char buf[BUFSIZ];\r
- int ch, len, in_ssi_tag;\r
-\r
- if (include_level > 10) {\r
- cry(conn, "SSI #include level is too deep (%s)", path);\r
- return;\r
- }\r
-\r
- in_ssi_tag = 0;\r
- len = 0;\r
-\r
- while ((ch = fgetc(fp)) != EOF) {\r
- if (in_ssi_tag && ch == '>') {\r
- in_ssi_tag = 0;\r
- buf[len++] = (char) ch;\r
- buf[len] = '\0';\r
- assert(len <= (int) sizeof(buf));\r
- if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {\r
- // Not an SSI tag, pass it\r
- (void) mg_write(conn, buf, (size_t)len);\r
- } else {\r
- if (!memcmp(buf + 5, "include", 7)) {\r
- do_ssi_include(conn, path, buf + 12, include_level);\r
-#if !defined(NO_POPEN)\r
- } else if (!memcmp(buf + 5, "exec", 4)) {\r
- do_ssi_exec(conn, buf + 9);\r
-#endif // !NO_POPEN\r
- } else {\r
- cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);\r
- }\r
- }\r
- len = 0;\r
- } else if (in_ssi_tag) {\r
- if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {\r
- // Not an SSI tag\r
- in_ssi_tag = 0;\r
- } else if (len == (int) sizeof(buf) - 2) {\r
- cry(conn, "%s: SSI tag is too large", path);\r
- len = 0;\r
- }\r
- buf[len++] = ch & 0xff;\r
- } else if (ch == '<') {\r
- in_ssi_tag = 1;\r
- if (len > 0) {\r
- (void) mg_write(conn, buf, (size_t)len);\r
- }\r
- len = 0;\r
- buf[len++] = ch & 0xff;\r
- } else {\r
- buf[len++] = ch & 0xff;\r
- if (len == (int) sizeof(buf)) {\r
- (void) mg_write(conn, buf, (size_t)len);\r
- len = 0;\r
- }\r
- }\r
- }\r
-\r
- // Send the rest of buffered data\r
- if (len > 0) {\r
- (void) mg_write(conn, buf, (size_t)len);\r
- }\r
-}\r
-\r
-static void handle_ssi_file_request(struct mg_connection *conn,\r
- const char *path) {\r
- FILE *fp;\r
-\r
- if ((fp = mg_fopen(path, "rb")) == NULL) {\r
- send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,\r
- strerror(ERRNO));\r
- } else {\r
- conn->must_close = 1;\r
- set_close_on_exec(fileno(fp));\r
- mg_printf(conn, "HTTP/1.1 200 OK\r\n"\r
- "Content-Type: text/html\r\nConnection: %s\r\n\r\n",\r
- suggest_connection_header(conn));\r
- send_ssi_file(conn, path, fp, 0);\r
- (void) fclose(fp);\r
- }\r
-}\r
-\r
-static void send_options(struct mg_connection *conn) {\r
- conn->request_info.status_code = 200;\r
-\r
- (void) mg_printf(conn,\r
- "HTTP/1.1 200 OK\r\n"\r
- "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS\r\n"\r
- "DAV: 1\r\n\r\n");\r
-}\r
-\r
-// Writes PROPFIND properties for a collection element\r
-static void print_props(struct mg_connection *conn, const char* uri,\r
- struct mgstat* st) {\r
- char mtime[64];\r
- gmt_time_string(mtime, sizeof(mtime), &st->mtime);\r
- conn->num_bytes_sent += mg_printf(conn,\r
- "<d:response>"\r
- "<d:href>%s</d:href>"\r
- "<d:propstat>"\r
- "<d:prop>"\r
- "<d:resourcetype>%s</d:resourcetype>"\r
- "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"\r
- "<d:getlastmodified>%s</d:getlastmodified>"\r
- "</d:prop>"\r
- "<d:status>HTTP/1.1 200 OK</d:status>"\r
- "</d:propstat>"\r
- "</d:response>\n",\r
- uri,\r
- st->is_directory ? "<d:collection/>" : "",\r
- st->size,\r
- mtime);\r
-}\r
-\r
-static void print_dav_dir_entry(struct de *de, void *data) {\r
- char href[PATH_MAX];\r
- struct mg_connection *conn = (struct mg_connection *) data;\r
- mg_snprintf(conn, href, sizeof(href), "%s%s",\r
- conn->request_info.uri, de->file_name);\r
- print_props(conn, href, &de->st);\r
-}\r
-\r
-static void handle_propfind(struct mg_connection *conn, const char* path,\r
- struct mgstat* st) {\r
- const char *depth = mg_get_header(conn, "Depth");\r
-\r
- conn->must_close = 1;\r
- conn->request_info.status_code = 207;\r
- mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"\r
- "Connection: close\r\n"\r
- "Content-Type: text/xml; charset=utf-8\r\n\r\n");\r
-\r
- conn->num_bytes_sent += mg_printf(conn,\r
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>"\r
- "<d:multistatus xmlns:d='DAV:'>\n");\r
-\r
- // Print properties for the requested resource itself\r
- print_props(conn, conn->request_info.uri, st);\r
-\r
- // If it is a directory, print directory entries too if Depth is not 0\r
- if (st->is_directory &&\r
- !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&\r
- (depth == NULL || strcmp(depth, "0") != 0)) {\r
- scan_directory(conn, path, conn, &print_dav_dir_entry);\r
- }\r
-\r
- conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");\r
-}\r
-\r
-// This is the heart of the Mongoose's logic.\r
-// This function is called when the request is read, parsed and validated,\r
-// and Mongoose must decide what action to take: serve a file, or\r
-// a directory, or call embedded function, etcetera.\r
-static void handle_request(struct mg_connection *conn) {\r
- struct mg_request_info *ri = &conn->request_info;\r
- char path[PATH_MAX];\r
- int stat_result, uri_len;\r
- struct mgstat st;\r
-\r
- if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {\r
- * conn->request_info.query_string++ = '\0';\r
- }\r
- uri_len = strlen(ri->uri);\r
- url_decode(ri->uri, (size_t)uri_len, ri->uri, (size_t)(uri_len + 1), 0);\r
- remove_double_dots_and_double_slashes(ri->uri);\r
- stat_result = convert_uri_to_file_name(conn, path, sizeof(path), &st);\r
-\r
- DEBUG_TRACE(("%s", ri->uri));\r
- if (!check_authorization(conn, path)) {\r
- send_authorization_request(conn);\r
- } else if (call_user(conn, MG_NEW_REQUEST) != NULL) {\r
- // Do nothing, callback has served the request\r
- } else if (!strcmp(ri->request_method, "OPTIONS")) {\r
- send_options(conn);\r
- } else if (strstr(path, PASSWORDS_FILE_NAME)) {\r
- // Do not allow to view passwords files\r
- send_http_error(conn, 403, "Forbidden", "Access Forbidden");\r
- } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {\r
- send_http_error(conn, 404, "Not Found", "Not Found");\r
- } else if ((!strcmp(ri->request_method, "PUT") ||\r
- !strcmp(ri->request_method, "DELETE")) &&\r
- (conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ||\r
- !is_authorized_for_put(conn))) {\r
- send_authorization_request(conn);\r
- } else if (!strcmp(ri->request_method, "PUT")) {\r
- put_file(conn, path);\r
- } else if (!strcmp(ri->request_method, "DELETE")) {\r
- if (mg_remove(path) == 0) {\r
- send_http_error(conn, 200, "OK", "");\r
- } else {\r
- send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,\r
- strerror(ERRNO));\r
- }\r
- } else if (stat_result != 0) {\r
- send_http_error(conn, 404, "Not Found", "%s", "File not found");\r
- } else if (st.is_directory && ri->uri[uri_len - 1] != '/') {\r
- (void) mg_printf(conn,\r
- "HTTP/1.1 301 Moved Permanently\r\n"\r
- "Location: %s/\r\n\r\n", ri->uri);\r
- } else if (!strcmp(ri->request_method, "PROPFIND")) {\r
- handle_propfind(conn, path, &st);\r
- } else if (st.is_directory &&\r
- !substitute_index_file(conn, path, sizeof(path), &st)) {\r
- if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {\r
- handle_directory_request(conn, path);\r
- } else {\r
- send_http_error(conn, 403, "Directory Listing Denied",\r
- "Directory listing denied");\r
- }\r
-#if !defined(NO_CGI)\r
- } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],\r
- strlen(conn->ctx->config[CGI_EXTENSIONS]),\r
- path) > 0) {\r
- if (strcmp(ri->request_method, "POST") &&\r
- strcmp(ri->request_method, "GET")) {\r
- send_http_error(conn, 501, "Not Implemented",\r
- "Method %s is not implemented", ri->request_method);\r
- } else {\r
- handle_cgi_request(conn, path);\r
- }\r
-#endif // !NO_CGI\r
- } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],\r
- strlen(conn->ctx->config[SSI_EXTENSIONS]),\r
- path) > 0) {\r
- handle_ssi_file_request(conn, path);\r
- } else if (is_not_modified(conn, &st)) {\r
- send_http_error(conn, 304, "Not Modified", "");\r
- } else {\r
- handle_file_request(conn, path, &st);\r
- }\r
-}\r
-\r
-static void close_all_listening_sockets(struct mg_context *ctx) {\r
- struct socket *sp, *tmp;\r
- for (sp = ctx->listening_sockets; sp != NULL; sp = tmp) {\r
- tmp = sp->next;\r
- (void) closesocket(sp->sock);\r
- free(sp);\r
- }\r
-}\r
-\r
-// Valid listening port specification is: [ip_address:]port[s]\r
-// Examples: 80, 443s, 127.0.0.1:3128,1.2.3.4:8080s\r
-// TODO(lsm): add parsing of the IPv6 address\r
-static int parse_port_string(const struct vec *vec, struct socket *so) {\r
- int a, b, c, d, port, len;\r
-\r
- // MacOS needs that. If we do not zero it, subsequent bind() will fail.\r
- // Also, all-zeroes in the socket address means binding to all addresses\r
- // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).\r
- memset(so, 0, sizeof(*so));\r
-\r
- if (sscanf(vec->ptr, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &len) == 5) {\r
- // Bind to a specific IPv4 address\r
- so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);\r
- } else if (sscanf(vec->ptr, "%d%n", &port, &len) != 1 ||\r
- len <= 0 ||\r
- len > (int) vec->len ||\r
- (vec->ptr[len] && vec->ptr[len] != 's' && vec->ptr[len] != ',')) {\r
- return 0;\r
- }\r
-\r
- so->is_ssl = vec->ptr[len] == 's';\r
-#if defined(USE_IPV6)\r
- so->lsa.sin6.sin6_family = AF_INET6;\r
- so->lsa.sin6.sin6_port = htons((uint16_t) port);\r
-#else\r
- so->lsa.sin.sin_family = AF_INET;\r
- so->lsa.sin.sin_port = htons((uint16_t) port);\r
-#endif\r
-\r
- return 1;\r
-}\r
-\r
-static int set_ports_option(struct mg_context *ctx) {\r
- const char *list = ctx->config[LISTENING_PORTS];\r
- int on = 1, success = 1;\r
- SOCKET sock;\r
- struct vec vec;\r
- struct socket so, *listener;\r
-\r
- while (success && (list = next_option(list, &vec, NULL)) != NULL) {\r
- if (!parse_port_string(&vec, &so)) {\r
- cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",\r
- __func__, vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]");\r
- success = 0;\r
- } else if (so.is_ssl && ctx->ssl_ctx == NULL) {\r
- cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");\r
- success = 0;\r
- } else if ((sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==\r
- INVALID_SOCKET ||\r
-#if !defined(_WIN32)\r
- // On Windows, SO_REUSEADDR is recommended only for\r
- // broadcast UDP sockets\r
- setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,\r
- sizeof(on)) != 0 ||\r
-#endif // !_WIN32\r
- // Set TCP keep-alive. This is needed because if HTTP-level\r
- // keep-alive is enabled, and client resets the connection,\r
- // server won't get TCP FIN or RST and will keep the connection\r
- // open forever. With TCP keep-alive, next keep-alive\r
- // handshake will figure out that the client is down and\r
- // will close the server end.\r
- // Thanks to Igor Klopov who suggested the patch.\r
- setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,\r
- sizeof(on)) != 0 ||\r
- bind(sock, &so.lsa.sa, sizeof(so.lsa)) != 0 ||\r
- listen(sock, 100) != 0) {\r
- closesocket(sock);\r
- cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__,\r
- vec.len, vec.ptr, strerror(ERRNO));\r
- success = 0;\r
- } else if ((listener = (struct socket *)\r
- calloc(1, sizeof(*listener))) == NULL) {\r
- closesocket(sock);\r
- cry(fc(ctx), "%s: %s", __func__, strerror(ERRNO));\r
- success = 0;\r
- } else {\r
- *listener = so;\r
- listener->sock = sock;\r
- set_close_on_exec(listener->sock);\r
- listener->next = ctx->listening_sockets;\r
- ctx->listening_sockets = listener;\r
- }\r
- }\r
-\r
- if (!success) {\r
- close_all_listening_sockets(ctx);\r
- }\r
-\r
- return success;\r
-}\r
-\r
-static void log_header(const struct mg_connection *conn, const char *header,\r
- FILE *fp) {\r
- const char *header_value;\r
-\r
- if ((header_value = mg_get_header(conn, header)) == NULL) {\r
- (void) fprintf(fp, "%s", " -");\r
- } else {\r
- (void) fprintf(fp, " \"%s\"", header_value);\r
- }\r
-}\r
-\r
-static void log_access(const struct mg_connection *conn) {\r
- const struct mg_request_info *ri;\r
- FILE *fp;\r
- char date[64], src_addr[20];\r
-\r
- fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :\r
- mg_fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");\r
-\r
- if (fp == NULL)\r
- return;\r
-\r
- strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",\r
- localtime(&conn->birth_time));\r
-\r
- ri = &conn->request_info;\r
- flockfile(fp);\r
-\r
- sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);\r
- fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,\r
- src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,\r
- ri->request_method ? ri->request_method : "-",\r
- ri->uri ? ri->uri : "-", ri->http_version,\r
- conn->request_info.status_code, conn->num_bytes_sent);\r
- log_header(conn, "Referer", fp);\r
- log_header(conn, "User-Agent", fp);\r
- fputc('\n', fp);\r
- fflush(fp);\r
-\r
- funlockfile(fp);\r
- fclose(fp);\r
-}\r
-\r
-static int isbyte(int n) {\r
- return n >= 0 && n <= 255;\r
-}\r
-\r
-// Verify given socket address against the ACL.\r
-// Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.\r
-static int check_acl(struct mg_context *ctx, const union usa *usa) {\r
- int a, b, c, d, n, mask, allowed;\r
- char flag;\r
- uint32_t acl_subnet, acl_mask, remote_ip;\r
- struct vec vec;\r
- const char *list = ctx->config[ACCESS_CONTROL_LIST];\r
-\r
- if (list == NULL) {\r
- return 1;\r
- }\r
-\r
- (void) memcpy(&remote_ip, &usa->sin.sin_addr, sizeof(remote_ip));\r
-\r
- // If any ACL is set, deny by default\r
- allowed = '-';\r
-\r
- while ((list = next_option(list, &vec, NULL)) != NULL) {\r
- mask = 32;\r
-\r
- if (sscanf(vec.ptr, "%c%d.%d.%d.%d%n", &flag, &a, &b, &c, &d, &n) != 5) {\r
- cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);\r
- return -1;\r
- } else if (flag != '+' && flag != '-') {\r
- cry(fc(ctx), "%s: flag must be + or -: [%s]", __func__, vec.ptr);\r
- return -1;\r
- } else if (!isbyte(a)||!isbyte(b)||!isbyte(c)||!isbyte(d)) {\r
- cry(fc(ctx), "%s: bad ip address: [%s]", __func__, vec.ptr);\r
- return -1;\r
- } else if (sscanf(vec.ptr + n, "/%d", &mask) == 0) {\r
- // Do nothing, no mask specified\r
- } else if (mask < 0 || mask > 32) {\r
- cry(fc(ctx), "%s: bad subnet mask: %d [%s]", __func__, n, vec.ptr);\r
- return -1;\r
- }\r
-\r
- acl_subnet = (a << 24) | (b << 16) | (c << 8) | d;\r
- acl_mask = mask ? 0xffffffffU << (32 - mask) : 0;\r
-\r
- if (acl_subnet == (ntohl(remote_ip) & acl_mask)) {\r
- allowed = flag;\r
- }\r
- }\r
-\r
- return allowed == '+';\r
-}\r
-\r
-static void add_to_set(SOCKET fd, fd_set *set, int *max_fd) {\r
- FD_SET(fd, set);\r
- if (fd > (SOCKET) *max_fd) {\r
- *max_fd = (int) fd;\r
- }\r
-}\r
-\r
-#if !defined(_WIN32)\r
-static int set_uid_option(struct mg_context *ctx) {\r
- struct passwd *pw;\r
- const char *uid = ctx->config[RUN_AS_USER];\r
- int success = 0;\r
-\r
- if (uid == NULL) {\r
- success = 1;\r
- } else {\r
- if ((pw = getpwnam(uid)) == NULL) {\r
- cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);\r
- } else if (setgid(pw->pw_gid) == -1) {\r
- cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));\r
- } else if (setuid(pw->pw_uid) == -1) {\r
- cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));\r
- } else {\r
- success = 1;\r
- }\r
- }\r
-\r
- return success;\r
-}\r
-#endif // !_WIN32\r
-\r
-#if !defined(NO_SSL)\r
-static pthread_mutex_t *ssl_mutexes;\r
-\r
-static void ssl_locking_callback(int mode, int mutex_num, const char *file,\r
- int line) {\r
- line = 0; // Unused\r
- file = NULL; // Unused\r
-\r
- if (mode & CRYPTO_LOCK) {\r
- (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);\r
- } else {\r
- (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);\r
- }\r
-}\r
-\r
-static unsigned long ssl_id_callback(void) {\r
- return (unsigned long) pthread_self();\r
-}\r
-\r
-#if !defined(NO_SSL_DL)\r
-static int load_dll(struct mg_context *ctx, const char *dll_name,\r
- struct ssl_func *sw) {\r
- union {void *p; void (*fp)(void);} u;\r
- void *dll_handle;\r
- struct ssl_func *fp;\r
-\r
- if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {\r
- cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);\r
- return 0;\r
- }\r
-\r
- for (fp = sw; fp->name != NULL; fp++) {\r
-#ifdef _WIN32\r
- // GetProcAddress() returns pointer to function\r
- u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);\r
-#else\r
- // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to\r
- // function pointers. We need to use a union to make a cast.\r
- u.p = dlsym(dll_handle, fp->name);\r
-#endif // _WIN32\r
- if (u.fp == NULL) {\r
- cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);\r
- return 0;\r
- } else {\r
- fp->ptr = u.fp;\r
- }\r
- }\r
-\r
- return 1;\r
-}\r
-#endif // NO_SSL_DL\r
-\r
-// Dynamically load SSL library. Set up ctx->ssl_ctx pointer.\r
-static int set_ssl_option(struct mg_context *ctx) {\r
- struct mg_request_info request_info;\r
- SSL_CTX *CTX;\r
- int i, size;\r
- const char *pem = ctx->config[SSL_CERTIFICATE];\r
- const char *chain = ctx->config[SSL_CHAIN_FILE];\r
-\r
- if (pem == NULL) {\r
- return 1;\r
- }\r
-\r
-#if !defined(NO_SSL_DL)\r
- if (!load_dll(ctx, SSL_LIB, ssl_sw) ||\r
- !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {\r
- return 0;\r
- }\r
-#endif // NO_SSL_DL\r
-\r
- // Initialize SSL crap\r
- SSL_library_init();\r
- SSL_load_error_strings();\r
-\r
- if ((CTX = SSL_CTX_new(SSLv23_server_method())) == NULL) {\r
- cry(fc(ctx), "SSL_CTX_new error: %s", ssl_error());\r
- } else if (ctx->user_callback != NULL) {\r
- memset(&request_info, 0, sizeof(request_info));\r
- request_info.user_data = ctx->user_data;\r
- ctx->user_callback(MG_INIT_SSL, (struct mg_connection *) CTX,\r
- &request_info);\r
- }\r
-\r
- if (CTX != NULL && SSL_CTX_use_certificate_file(CTX, pem,\r
- SSL_FILETYPE_PEM) == 0) {\r
- cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());\r
- return 0;\r
- } else if (CTX != NULL && SSL_CTX_use_PrivateKey_file(CTX, pem,\r
- SSL_FILETYPE_PEM) == 0) {\r
- cry(fc(ctx), "%s: cannot open %s: %s", NULL, pem, ssl_error());\r
- return 0;\r
- }\r
-\r
- if (CTX != NULL && chain != NULL &&\r
- SSL_CTX_use_certificate_chain_file(CTX, chain) == 0) {\r
- cry(fc(ctx), "%s: cannot open %s: %s", NULL, chain, ssl_error());\r
- return 0;\r
- }\r
-\r
- // Initialize locking callbacks, needed for thread safety.\r
- // http://www.openssl.org/support/faq.html#PROG1\r
- size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();\r
- if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {\r
- cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());\r
- return 0;\r
- }\r
-\r
- for (i = 0; i < CRYPTO_num_locks(); i++) {\r
- pthread_mutex_init(&ssl_mutexes[i], NULL);\r
- }\r
-\r
- CRYPTO_set_locking_callback(&ssl_locking_callback);\r
- CRYPTO_set_id_callback(&ssl_id_callback);\r
-\r
- // Done with everything. Save the context.\r
- ctx->ssl_ctx = CTX;\r
-\r
- return 1;\r
-}\r
-\r
-static void uninitialize_ssl(struct mg_context *ctx) {\r
- int i;\r
- if (ctx->ssl_ctx != NULL) {\r
- CRYPTO_set_locking_callback(NULL);\r
- for (i = 0; i < CRYPTO_num_locks(); i++) {\r
- pthread_mutex_destroy(&ssl_mutexes[i]);\r
- }\r
- CRYPTO_set_locking_callback(NULL);\r
- CRYPTO_set_id_callback(NULL);\r
- }\r
-}\r
-#endif // !NO_SSL\r
-\r
-static int set_gpass_option(struct mg_context *ctx) {\r
- struct mgstat mgstat;\r
- const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];\r
- return path == NULL || mg_stat(path, &mgstat) == 0;\r
-}\r
-\r
-static int set_acl_option(struct mg_context *ctx) {\r
- union usa fake;\r
- return check_acl(ctx, &fake) != -1;\r
-}\r
-\r
-static void reset_per_request_attributes(struct mg_connection *conn) {\r
- struct mg_request_info *ri = &conn->request_info;\r
-\r
- // Reset request info attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port\r
- ri->remote_user = ri->request_method = ri->uri = ri->http_version =\r
- conn->path_info = NULL;\r
- ri->num_headers = 0;\r
- ri->status_code = -1;\r
-\r
- conn->num_bytes_sent = conn->consumed_content = 0;\r
- conn->content_len = -1;\r
- conn->request_len = conn->data_len = 0;\r
- conn->must_close = 0;\r
-}\r
-\r
-static void close_socket_gracefully(SOCKET sock) {\r
- char buf[BUFSIZ];\r
- struct linger linger;\r
- int n;\r
-\r
- // Set linger option to avoid socket hanging out after close. This prevent\r
- // ephemeral port exhaust problem under high QPS.\r
- linger.l_onoff = 1;\r
- linger.l_linger = 1;\r
- setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));\r
-\r
- // Send FIN to the client\r
- (void) shutdown(sock, SHUT_WR);\r
- set_non_blocking_mode(sock);\r
-\r
- // Read and discard pending data. If we do not do that and close the\r
- // socket, the data in the send buffer may be discarded. This\r
- // behaviour is seen on Windows, when client keeps sending data\r
- // when server decide to close the connection; then when client\r
- // does recv() it gets no data back.\r
- do {\r
- n = pull(NULL, sock, NULL, buf, sizeof(buf));\r
- } while (n > 0);\r
-\r
- // Now we know that our FIN is ACK-ed, safe to close\r
- (void) closesocket(sock);\r
-}\r
-\r
-static void close_connection(struct mg_connection *conn) {\r
- if (conn->ssl) {\r
- SSL_free(conn->ssl);\r
- conn->ssl = NULL;\r
- }\r
-\r
- if (conn->client.sock != INVALID_SOCKET) {\r
- close_socket_gracefully(conn->client.sock);\r
- }\r
-}\r
-\r
-static void discard_current_request_from_buffer(struct mg_connection *conn) {\r
- char *buffered;\r
- int buffered_len, body_len;\r
-\r
- buffered = conn->buf + conn->request_len;\r
- buffered_len = conn->data_len - conn->request_len;\r
- assert(buffered_len >= 0);\r
-\r
- if (conn->content_len == -1) {\r
- body_len = 0;\r
- } else if (conn->content_len < (int64_t) buffered_len) {\r
- body_len = (int) conn->content_len;\r
- } else {\r
- body_len = buffered_len;\r
- }\r
-\r
- conn->data_len -= conn->request_len + body_len;\r
- memmove(conn->buf, conn->buf + conn->request_len + body_len,\r
- (size_t) conn->data_len);\r
-}\r
-\r
-static int is_valid_uri(const char *uri) {\r
- // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2\r
- // URI can be an asterisk (*) or should start with slash.\r
- return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');\r
-}\r
-\r
-static void process_new_connection(struct mg_connection *conn) {\r
- struct mg_request_info *ri = &conn->request_info;\r
- int keep_alive_enabled;\r
- const char *cl;\r
-\r
- keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");\r
-\r
- do {\r
- reset_per_request_attributes(conn);\r
-\r
- // If next request is not pipelined, read it in\r
- if ((conn->request_len = get_request_len(conn->buf, conn->data_len)) == 0) {\r
- conn->request_len = read_request(NULL, conn->client.sock, conn->ssl,\r
- conn->buf, conn->buf_size, &conn->data_len);\r
- }\r
- assert(conn->data_len >= conn->request_len);\r
- if (conn->request_len == 0 && conn->data_len == conn->buf_size) {\r
- send_http_error(conn, 413, "Request Too Large", "");\r
- return;\r
- } if (conn->request_len <= 0) {\r
- return; // Remote end closed the connection\r
- }\r
-\r
- // Nul-terminate the request cause parse_http_request() uses sscanf\r
- conn->buf[conn->request_len - 1] = '\0';\r
- if (!parse_http_request(conn->buf, ri) || !is_valid_uri(ri->uri)) {\r
- // Do not put garbage in the access log, just send it back to the client\r
- send_http_error(conn, 400, "Bad Request",\r
- "Cannot parse HTTP request: [%.*s]", conn->data_len, conn->buf);\r
- } else if (strcmp(ri->http_version, "1.0") &&\r
- strcmp(ri->http_version, "1.1")) {\r
- // Request seems valid, but HTTP version is strange\r
- send_http_error(conn, 505, "HTTP version not supported", "");\r
- log_access(conn);\r
- } else {\r
- // Request is valid, handle it\r
- cl = get_header(ri, "Content-Length");\r
- conn->content_len = cl == NULL ? -1 : strtoll(cl, NULL, 10);\r
- conn->birth_time = time(NULL);\r
- handle_request(conn);\r
- call_user(conn, MG_REQUEST_COMPLETE);\r
- log_access(conn);\r
- discard_current_request_from_buffer(conn);\r
- }\r
- if (ri->remote_user != NULL) {\r
- free((void *) ri->remote_user);\r
- }\r
- } while (conn->ctx->stop_flag == 0 &&\r
- keep_alive_enabled &&\r
- should_keep_alive(conn));\r
-}\r
-\r
-// Worker threads take accepted socket from the queue\r
-static int consume_socket(struct mg_context *ctx, struct socket *sp) {\r
- (void) pthread_mutex_lock(&ctx->mutex);\r
- DEBUG_TRACE(("going idle"));\r
-\r
- // If the queue is empty, wait. We're idle at this point.\r
- while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {\r
- pthread_cond_wait(&ctx->sq_full, &ctx->mutex);\r
- }\r
-\r
- // If we're stopping, sq_head may be equal to sq_tail.\r
- if (ctx->sq_head > ctx->sq_tail) {\r
- // Copy socket from the queue and increment tail\r
- *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];\r
- ctx->sq_tail++;\r
- DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));\r
-\r
- // Wrap pointers if needed\r
- while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {\r
- ctx->sq_tail -= ARRAY_SIZE(ctx->queue);\r
- ctx->sq_head -= ARRAY_SIZE(ctx->queue);\r
- }\r
- }\r
-\r
- (void) pthread_cond_signal(&ctx->sq_empty);\r
- (void) pthread_mutex_unlock(&ctx->mutex);\r
-\r
- return !ctx->stop_flag;\r
-}\r
-\r
-static void worker_thread(struct mg_context *ctx) {\r
- struct mg_connection *conn;\r
- int buf_size = atoi(ctx->config[MAX_REQUEST_SIZE]);\r
-\r
- conn = (struct mg_connection *) calloc(1, sizeof(*conn) + buf_size);\r
- if (conn == NULL) {\r
- cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");\r
- return;\r
- }\r
- conn->buf_size = buf_size;\r
- conn->buf = (char *) (conn + 1);\r
-\r
- // Call consume_socket() even when ctx->stop_flag > 0, to let it signal\r
- // sq_empty condvar to wake up the master waiting in produce_socket()\r
- while (consume_socket(ctx, &conn->client)) {\r
- conn->birth_time = time(NULL);\r
- conn->ctx = ctx;\r
-\r
- // Fill in IP, port info early so even if SSL setup below fails,\r
- // error handler would have the corresponding info.\r
- // Thanks to Johannes Winkelmann for the patch.\r
- // TODO(lsm): Fix IPv6 case\r
- conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);\r
- memcpy(&conn->request_info.remote_ip,\r
- &conn->client.rsa.sin.sin_addr.s_addr, 4);\r
- conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);\r
- conn->request_info.is_ssl = conn->client.is_ssl;\r
-\r
- if (!conn->client.is_ssl ||\r
- (conn->client.is_ssl && sslize(conn, SSL_accept))) {\r
- process_new_connection(conn);\r
- }\r
-\r
- close_connection(conn);\r
- }\r
- free(conn);\r
-\r
- // Signal master that we're done with connection and exiting\r
- (void) pthread_mutex_lock(&ctx->mutex);\r
- ctx->num_threads--;\r
- (void) pthread_cond_signal(&ctx->cond);\r
- assert(ctx->num_threads >= 0);\r
- (void) pthread_mutex_unlock(&ctx->mutex);\r
-\r
- DEBUG_TRACE(("exiting"));\r
-}\r
-\r
-// Master thread adds accepted socket to a queue\r
-static void produce_socket(struct mg_context *ctx, const struct socket *sp) {\r
- (void) pthread_mutex_lock(&ctx->mutex);\r
-\r
- // If the queue is full, wait\r
- while (ctx->stop_flag == 0 &&\r
- ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {\r
- (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);\r
- }\r
-\r
- if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {\r
- // Copy socket to the queue and increment head\r
- ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;\r
- ctx->sq_head++;\r
- DEBUG_TRACE(("queued socket %d", sp->sock));\r
- }\r
-\r
- (void) pthread_cond_signal(&ctx->sq_full);\r
- (void) pthread_mutex_unlock(&ctx->mutex);\r
-}\r
-\r
-static void accept_new_connection(const struct socket *listener,\r
- struct mg_context *ctx) {\r
- struct socket accepted;\r
- char src_addr[20];\r
- socklen_t len;\r
- int allowed;\r
-\r
- len = sizeof(accepted.rsa);\r
- accepted.lsa = listener->lsa;\r
- accepted.sock = accept(listener->sock, &accepted.rsa.sa, &len);\r
- if (accepted.sock != INVALID_SOCKET) {\r
- allowed = check_acl(ctx, &accepted.rsa);\r
- if (allowed) {\r
- // Put accepted socket structure into the queue\r
- DEBUG_TRACE(("accepted socket %d", accepted.sock));\r
- accepted.is_ssl = listener->is_ssl;\r
- produce_socket(ctx, &accepted);\r
- } else {\r
- sockaddr_to_string(src_addr, sizeof(src_addr), &accepted.rsa);\r
- cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);\r
- (void) closesocket(accepted.sock);\r
- }\r
- }\r
-}\r
-\r
-static void master_thread(struct mg_context *ctx) {\r
- fd_set read_set;\r
- struct timeval tv;\r
- struct socket *sp;\r
- int max_fd;\r
-\r
- // Increase priority of the master thread\r
-#if defined(_WIN32)\r
- SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);\r
-#endif\r
- \r
-#if defined(ISSUE_317)\r
- struct sched_param sched_param;\r
- sched_param.sched_priority = sched_get_priority_max(SCHED_RR);\r
- pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);\r
-#endif\r
-\r
- while (ctx->stop_flag == 0) {\r
- FD_ZERO(&read_set);\r
- max_fd = -1;\r
-\r
- // Add listening sockets to the read set\r
- for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {\r
- add_to_set(sp->sock, &read_set, &max_fd);\r
- }\r
-\r
- tv.tv_sec = 0;\r
- tv.tv_usec = 200 * 1000;\r
-\r
- if (select(max_fd + 1, &read_set, NULL, NULL, &tv) < 0) {\r
-#ifdef _WIN32\r
- // On windows, if read_set and write_set are empty,\r
- // select() returns "Invalid parameter" error\r
- // (at least on my Windows XP Pro). So in this case, we sleep here.\r
- mg_sleep(1000);\r
-#endif // _WIN32\r
- } else {\r
- for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {\r
- if (ctx->stop_flag == 0 && FD_ISSET(sp->sock, &read_set)) {\r
- accept_new_connection(sp, ctx);\r
- }\r
- }\r
- }\r
- }\r
- DEBUG_TRACE(("stopping workers"));\r
-\r
- // Stop signal received: somebody called mg_stop. Quit.\r
- close_all_listening_sockets(ctx);\r
-\r
- // Wakeup workers that are waiting for connections to handle.\r
- pthread_cond_broadcast(&ctx->sq_full);\r
-\r
- // Wait until all threads finish\r
- (void) pthread_mutex_lock(&ctx->mutex);\r
- while (ctx->num_threads > 0) {\r
- (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);\r
- }\r
- (void) pthread_mutex_unlock(&ctx->mutex);\r
-\r
- // All threads exited, no sync is needed. Destroy mutex and condvars\r
- (void) pthread_mutex_destroy(&ctx->mutex);\r
- (void) pthread_cond_destroy(&ctx->cond);\r
- (void) pthread_cond_destroy(&ctx->sq_empty);\r
- (void) pthread_cond_destroy(&ctx->sq_full);\r
-\r
-#if !defined(NO_SSL)\r
- uninitialize_ssl(ctx);\r
-#endif\r
-\r
- // Signal mg_stop() that we're done\r
- ctx->stop_flag = 2;\r
-\r
- DEBUG_TRACE(("exiting"));\r
-}\r
-\r
-static void free_context(struct mg_context *ctx) {\r
- int i;\r
-\r
- // Deallocate config parameters\r
- for (i = 0; i < NUM_OPTIONS; i++) {\r
- if (ctx->config[i] != NULL)\r
- free(ctx->config[i]);\r
- }\r
-\r
- // Deallocate SSL context\r
- if (ctx->ssl_ctx != NULL) {\r
- SSL_CTX_free(ctx->ssl_ctx);\r
- }\r
-#ifndef NO_SSL\r
- if (ssl_mutexes != NULL) {\r
- free(ssl_mutexes);\r
- }\r
-#endif // !NO_SSL\r
-\r
- // Deallocate context itself\r
- free(ctx);\r
-}\r
-\r
-void mg_stop(struct mg_context *ctx) {\r
- ctx->stop_flag = 1;\r
-\r
- // Wait until mg_fini() stops\r
- while (ctx->stop_flag != 2) {\r
- mg_sleep(10);\r
- }\r
- free_context(ctx);\r
-\r
-#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
- (void) WSACleanup();\r
-#endif // _WIN32\r
-}\r
-\r
-struct mg_context *mg_start(mg_callback_t user_callback, void *user_data,\r
- const char **options) {\r
- struct mg_context *ctx;\r
- const char *name, *value, *default_value;\r
- int i;\r
-\r
-#if defined(_WIN32) && !defined(__SYMBIAN32__)\r
- WSADATA data;\r
- WSAStartup(MAKEWORD(2,2), &data);\r
- InitializeCriticalSection(&global_log_file_lock);\r
-#endif // _WIN32\r
-\r
- // Allocate context and initialize reasonable general case defaults.\r
- // TODO(lsm): do proper error handling here.\r
- ctx = (struct mg_context *) calloc(1, sizeof(*ctx));\r
- ctx->user_callback = user_callback;\r
- ctx->user_data = user_data;\r
-\r
- while (options && (name = *options++) != NULL) {\r
- if ((i = get_option_index(name)) == -1) {\r
- cry(fc(ctx), "Invalid option: %s", name);\r
- free_context(ctx);\r
- return NULL;\r
- } else if ((value = *options++) == NULL) {\r
- cry(fc(ctx), "%s: option value cannot be NULL", name);\r
- free_context(ctx);\r
- return NULL;\r
- }\r
- if (ctx->config[i] != NULL) {\r
- cry(fc(ctx), "%s: duplicate option", name);\r
- }\r
- ctx->config[i] = mg_strdup(value);\r
- DEBUG_TRACE(("[%s] -> [%s]", name, value));\r
- }\r
-\r
- // Set default value if needed\r
- for (i = 0; config_options[i * ENTRIES_PER_CONFIG_OPTION] != NULL; i++) {\r
- default_value = config_options[i * ENTRIES_PER_CONFIG_OPTION + 2];\r
- if (ctx->config[i] == NULL && default_value != NULL) {\r
- ctx->config[i] = mg_strdup(default_value);\r
- DEBUG_TRACE(("Setting default: [%s] -> [%s]",\r
- config_options[i * ENTRIES_PER_CONFIG_OPTION + 1],\r
- default_value));\r
- }\r
- }\r
-\r
- // NOTE(lsm): order is important here. SSL certificates must\r
- // be initialized before listening ports. UID must be set last.\r
- if (!set_gpass_option(ctx) ||\r
-#if !defined(NO_SSL)\r
- !set_ssl_option(ctx) ||\r
-#endif\r
- !set_ports_option(ctx) ||\r
-#if !defined(_WIN32)\r
- !set_uid_option(ctx) ||\r
-#endif\r
- !set_acl_option(ctx)) {\r
- free_context(ctx);\r
- return NULL;\r
- }\r
-\r
-#if !defined(_WIN32) && !defined(__SYMBIAN32__)\r
- // Ignore SIGPIPE signal, so if browser cancels the request, it\r
- // won't kill the whole process.\r
- (void) signal(SIGPIPE, SIG_IGN);\r
- // Also ignoring SIGCHLD to let the OS to reap zombies properly.\r
- (void) signal(SIGCHLD, SIG_IGN);\r
-#endif // !_WIN32\r
-\r
- (void) pthread_mutex_init(&ctx->mutex, NULL);\r
- (void) pthread_cond_init(&ctx->cond, NULL);\r
- (void) pthread_cond_init(&ctx->sq_empty, NULL);\r
- (void) pthread_cond_init(&ctx->sq_full, NULL);\r
-\r
- // Start master (listening) thread\r
- start_thread(ctx, (mg_thread_func_t) master_thread, ctx);\r
-\r
- // Start worker threads\r
- for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) {\r
- if (start_thread(ctx, (mg_thread_func_t) worker_thread, ctx) != 0) {\r
- cry(fc(ctx), "Cannot start worker thread: %d", ERRNO);\r
- } else {\r
- ctx->num_threads++;\r
- }\r
- }\r
-\r
- return ctx;\r
-}\r