23 #if !defined(_CRT_SECURE_NO_WARNINGS)
24 #define _CRT_SECURE_NO_WARNINGS
28 #define _XOPEN_SOURCE 600
30 #define _LARGEFILE_SOURCE
31 #define __STDC_FORMAT_MACROS
32 #define __STDC_LIMIT_MACROS
35 #if defined (_MSC_VER)
37 #pragma warning (disable : 4306 )
39 #pragma warning (disable : 4127)
41 #pragma warning (disable : 4204)
46 #if defined(WIN32_LEAN_AND_MEAN) && (_MSC_VER <= 1400)
47 #undef WIN32_LEAN_AND_MEAN
50 #if defined USE_IPV6 && defined(_WIN32)
54 #if defined(__SYMBIAN32__)
57 #define PATH_MAX FILENAME_MAX
60 #ifndef IGNORE_UNUSED_RESULT
61 #define IGNORE_UNUSED_RESULT(a) (void)((a) && 1)
65 #include <sys/types.h>
82 #define MAX_WORKER_THREADS 1024
84 #if defined(_WIN32) && !defined(__SYMBIAN32__)
85 #if defined(_MSC_VER) && _MSC_VER <= 1400
87 #define _WIN32_WINNT 0x0400
92 #define PATH_MAX MAX_PATH
97 #define in_port_t u_short
110 #define errno GetLastError()
111 #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
114 #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
115 ((uint64_t)((uint32_t)(hi))) << 32))
116 #define RATE_DIFF 10000000
117 #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
118 #define SYS2UNIX_TIME(lo, hi) \
119 (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
124 #if defined(_MSC_VER) && _MSC_VER < 1300
126 #define STR(x) STRX(x)
127 #define __func__ __FILE__ ":" STR(__LINE__)
128 #define strtoull(x, y, z) (unsigned __int64) _atoi64(x)
129 #define strtoll(x, y, z) _atoi64(x)
131 #define __func__ __FUNCTION__
132 #define strtoull(x, y, z) _strtoui64(x, y, z)
133 #define strtoll(x, y, z) _strtoi64(x, y, z)
136 #define ERRNO GetLastError()
138 #define SSL_LIB "ssleay32.dll"
139 #define CRYPTO_LIB "libeay32.dll"
141 #if !defined(EWOULDBLOCK)
142 #define EWOULDBLOCK WSAEWOULDBLOCK
145 #define INT64_FMT "I64d"
147 #define WINCDECL __cdecl
149 #define snprintf _snprintf
150 #define vsnprintf _vsnprintf
151 #define mg_sleep(x) Sleep(x)
153 #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
155 #define popen(x, y) _popen(x, y)
158 #define pclose(x) _pclose(x)
160 #define close(x) _close(x)
161 #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
163 #define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
164 #define fdopen(x, y) _fdopen((x), (y))
165 #define write(x, y, z) _write((x), (y), (unsigned) z)
166 #define read(x, y, z) _read((x), (y), (unsigned) z)
167 #define flockfile(x) EnterCriticalSection(&global_log_file_lock)
168 #define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
169 #define sleep(x) Sleep((x) * 1000)
170 #define rmdir(x) _rmdir(x)
172 #if !defined(va_copy)
173 #define va_copy(x, y) x = y
177 #define fileno(x) _fileno(x)
180 typedef HANDLE pthread_mutex_t;
181 typedef DWORD pthread_key_t;
182 typedef HANDLE pthread_t;
184 CRITICAL_SECTION threadIdSec;
185 int waitingthreadcount;
186 pthread_t *waitingthreadhdls;
189 typedef DWORD clockid_t;
190 #define CLOCK_MONOTONIC (1)
191 #define CLOCK_REALTIME (2)
200 static int pthread_mutex_lock(pthread_mutex_t *);
201 static int pthread_mutex_unlock(pthread_mutex_t *);
202 static void to_unicode(
const char *path,
wchar_t *wbuf,
size_t wbuf_len);
204 static char *mg_fgets(
char *buf,
size_t size,
struct file *filep,
char **p);
206 #if defined(HAVE_STDINT)
209 typedef unsigned int uint32_t;
210 typedef unsigned short uint16_t;
211 typedef unsigned __int64 uint64_t;
212 typedef __int64 int64_t;
213 #define INT64_MAX 9223372036854775807
218 char d_name[PATH_MAX];
223 WIN32_FIND_DATAW info;
224 struct dirent result;
227 #if !defined(USE_IPV6) && defined(_WIN32)
240 #pragma comment(lib, "Ws2_32.lib")
244 #include <sys/wait.h>
245 #include <sys/socket.h>
246 #include <sys/poll.h>
247 #include <netinet/in.h>
248 #include <arpa/inet.h>
249 #include <sys/time.h>
251 #include <inttypes.h>
257 #if !defined(NO_SSL_DL) && !defined(NO_SSL)
261 #if defined(__MACH__)
262 #define SSL_LIB "libssl.dylib"
263 #define CRYPTO_LIB "libcrypto.dylib"
265 #if !defined(SSL_LIB)
266 #define SSL_LIB "libssl.so"
268 #if !defined(CRYPTO_LIB)
269 #define CRYPTO_LIB "libcrypto.so"
275 #define closesocket(a) close(a)
276 #define mg_mkdir(x, y) mkdir(x, y)
277 #define mg_remove(x) remove(x)
278 #define mg_sleep(x) usleep((x) * 1000)
280 #define INVALID_SOCKET (-1)
281 #define INT64_FMT PRId64
287 #include "civetweb.h"
289 #define PASSWORDS_FILE_NAME ".htpasswd"
290 #define CGI_ENVIRONMENT_SIZE 4096
291 #define MAX_CGI_ENVIR_VARS 64
292 #define MG_BUF_LEN 8192
293 #ifndef MAX_REQUEST_SIZE
294 #define MAX_REQUEST_SIZE 16384
296 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
299 static CRITICAL_SECTION global_log_file_lock;
300 static DWORD pthread_self(
void)
302 return GetCurrentThreadId();
305 int pthread_key_create(pthread_key_t *key,
void (*_must_be_zero)(
void*) )
307 assert(_must_be_zero == NULL);
308 if ((key!=0) && (_must_be_zero == NULL)) {
310 return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
315 int pthread_key_delete(pthread_key_t key)
317 return TlsFree(key) ? 0 : 1;
320 int pthread_setspecific(pthread_key_t key,
void * value)
322 return TlsSetValue(key, value) ? 0 : 1;
325 void *pthread_getspecific(pthread_key_t key)
327 return TlsGetValue(key);
331 #define MD5_STATIC static
336 #define DEBUG_TRACE(x)
339 #define DEBUG_TRACE(x) do { \
341 printf("*** %lu.%p.%s.%d: ", \
342 (unsigned long) time(NULL), (void *) pthread_self(), \
343 __func__, __LINE__); \
347 funlockfile(stdout); \
350 #define DEBUG_TRACE(x)
356 typedef int socklen_t;
358 #define _DARWIN_UNLIMITED_SELECT
360 #define IP_ADDR_STR_LEN 50
362 #if !defined(MSG_NOSIGNAL)
363 #define MSG_NOSIGNAL 0
366 #if !defined(SOMAXCONN)
367 #define SOMAXCONN 100
370 #if !defined(PATH_MAX)
371 #define PATH_MAX 4096
375 #if !defined(MGSQLEN)
379 static const char *http_500_error =
"Internal Server Error";
381 #if defined(NO_SSL_DL)
382 #include <openssl/ssl.h>
383 #include <openssl/err.h>
389 typedef struct ssl_st SSL;
390 typedef struct ssl_method_st SSL_METHOD;
391 typedef struct ssl_ctx_st SSL_CTX;
398 #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
399 #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
400 #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
401 #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
402 #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
403 #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
404 #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
405 #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
406 #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
407 #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
408 #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
409 #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
410 const char *, int)) ssl_sw[11].ptr)
411 #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
412 const char *, int)) ssl_sw[12].ptr)
413 #define SSL_CTX_set_default_passwd_cb \
414 (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
415 #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
416 #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
417 #define SSL_CTX_use_certificate_chain_file \
418 (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
419 #define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
420 #define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)
421 #define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)
422 #define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr)
424 #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
425 #define CRYPTO_set_locking_callback \
426 (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
427 #define CRYPTO_set_id_callback \
428 (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
429 #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
430 #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
436 static struct ssl_func ssl_sw[] = {
438 {
"SSL_accept", NULL},
439 {
"SSL_connect", NULL},
442 {
"SSL_get_error", NULL},
443 {
"SSL_set_fd", NULL},
445 {
"SSL_CTX_new", NULL},
446 {
"SSLv23_server_method", NULL},
447 {
"SSL_library_init", NULL},
448 {
"SSL_CTX_use_PrivateKey_file", NULL},
449 {
"SSL_CTX_use_certificate_file",NULL},
450 {
"SSL_CTX_set_default_passwd_cb",NULL},
451 {
"SSL_CTX_free", NULL},
452 {
"SSL_load_error_strings", NULL},
453 {
"SSL_CTX_use_certificate_chain_file", NULL},
454 {
"SSLv23_client_method", NULL},
455 {
"SSL_pending", NULL},
456 {
"SSL_CTX_set_verify", NULL},
457 {
"SSL_shutdown", NULL},
464 static struct ssl_func crypto_sw[] = {
465 {
"CRYPTO_num_locks", NULL},
466 {
"CRYPTO_set_locking_callback", NULL},
467 {
"CRYPTO_set_id_callback", NULL},
468 {
"ERR_get_error", NULL},
469 {
"ERR_error_string", NULL},
475 static const char *month_names[] = {
476 "Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
477 "Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
484 struct sockaddr_in sin;
485 #if defined(USE_IPV6)
486 struct sockaddr_in6 sin6;
498 time_t modification_time;
506 #define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL, 0}
515 unsigned ssl_redir:1;
521 CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
522 PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
523 ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
524 GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
525 EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
526 NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
529 LUA_SCRIPT_EXTENSIONS, LUA_SERVER_PAGE_EXTENSIONS,
531 #if defined(USE_WEBSOCKET)
534 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
535 LUA_WEBSOCKET_EXTENSIONS,
541 static const char *config_options[] = {
542 "cgi_pattern",
"**.cgi$|**.pl$|**.php$",
543 "cgi_environment", NULL,
544 "put_delete_auth_file", NULL,
545 "cgi_interpreter", NULL,
547 "authentication_domain",
"mydomain.com",
548 "ssi_pattern",
"**.shtml$|**.shtm$",
550 "access_log_file", NULL,
551 "enable_directory_listing",
"yes",
552 "error_log_file", NULL,
553 "global_auth_file", NULL,
556 "index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,index.shtml,index.php",
558 "index.html,index.htm,index.cgi,index.shtml,index.php",
560 "enable_keep_alive",
"no",
561 "access_control_list", NULL,
562 "extra_mime_types", NULL,
563 "listening_ports",
"8080",
564 "document_root", NULL,
565 "ssl_certificate", NULL,
568 "url_rewrite_patterns", NULL,
569 "hide_files_patterns", NULL,
570 "request_timeout_ms",
"30000",
573 "lua_script_pattern",
"**.lua$",
574 "lua_server_page_pattern",
"**.lp$|**.lsp$",
576 #if defined(USE_WEBSOCKET)
577 "websocket_root", NULL,
579 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
580 "lua_websocket_pattern",
"**.lua$",
586 struct mg_request_handler_info {
589 mg_request_handler handler;
591 struct mg_request_handler_info *next;
595 volatile int stop_flag;
596 void *ssllib_dll_handle;
597 void *cryptolib_dll_handle;
599 char *config[NUM_OPTIONS];
600 struct mg_callbacks callbacks;
603 struct socket *listening_sockets;
604 in_port_t *listening_ports;
605 int num_listening_sockets;
607 volatile int num_threads;
608 pthread_mutex_t mutex;
611 struct socket queue[MGSQLEN];
612 volatile int sq_head;
613 volatile int sq_tail;
614 pthread_cond_t sq_full;
615 pthread_cond_t sq_empty;
616 pthread_t masterthreadid;
617 int workerthreadcount;
618 pthread_t *workerthreadids;
621 struct mg_request_handler_info *request_handlers;
624 struct mg_connection {
625 struct mg_request_info request_info;
626 struct mg_context *ctx;
628 SSL_CTX *client_ssl_ctx;
629 struct socket client;
631 int64_t num_bytes_sent;
633 int64_t consumed_content;
643 time_t last_throttle_time;
644 int64_t last_throttle_bytes;
645 pthread_mutex_t mutex;
647 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
648 void * lua_websocket_state;
652 static pthread_key_t sTlsKey;
653 static int sTlsInit = 0;
655 struct mg_workerTLS {
657 #if defined(_WIN32) && !defined(__SYMBIAN32__)
658 HANDLE pthread_cond_helper_mutex;
664 struct mg_connection *conn;
669 #if defined(USE_WEBSOCKET)
670 static int is_websocket_request(
const struct mg_connection *conn);
673 const char **mg_get_valid_option_names(
void)
675 return config_options;
678 static int is_file_in_memory(
struct mg_connection *conn,
const char *path,
682 if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :
683 conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
688 return filep->membuf != NULL;
691 static int is_file_opened(
const struct file *filep)
693 return filep->membuf != NULL || filep->fp != NULL;
696 static int mg_fopen(
struct mg_connection *conn,
const char *path,
697 const char *mode,
struct file *filep)
699 if (!is_file_in_memory(conn, path, filep)) {
701 wchar_t wbuf[PATH_MAX], wmode[20];
702 to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
703 MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
704 filep->fp = _wfopen(wbuf, wmode);
706 filep->fp = fopen(path, mode);
710 return is_file_opened(filep);
713 static void mg_fclose(
struct file *filep)
715 if (filep != NULL && filep->fp != NULL) {
720 static int get_option_index(
const char *name)
724 for (i = 0; config_options[i * 2] != NULL; i++) {
725 if (strcmp(config_options[i * 2], name) == 0) {
732 const char *mg_get_option(
const struct mg_context *ctx,
const char *name)
735 if ((i = get_option_index(name)) == -1) {
737 }
else if (ctx->config[i] == NULL) {
740 return ctx->config[i];
744 size_t mg_get_ports(
const struct mg_context *ctx,
size_t size,
int* ports,
int* ssl)
747 for (i = 0; i < size && i < (size_t)ctx->num_listening_sockets; i++)
749 ssl[i] = ctx->listening_sockets[i].is_ssl;
750 ports[i] = ctx->listening_ports[i];
755 static void sockaddr_to_string(
char *buf,
size_t len,
756 const union usa *usa)
759 #if defined(USE_IPV6)
760 inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
761 (
void *) &usa->sin.sin_addr :
762 (
void *) &usa->sin6.sin6_addr, buf, len);
763 #elif defined(_WIN32)
765 strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
767 inet_ntop(usa->sa.sa_family, (
void *) &usa->sin.sin_addr, buf, len);
772 static void gmt_time_string(
char *buf,
size_t buf_len, time_t *t)
778 strftime(buf, buf_len,
"%a, %d %b %Y %H:%M:%S GMT", tm);
780 strncpy(buf,
"Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
781 buf[buf_len - 1] =
'\0';
786 void mg_cry(
struct mg_connection *conn,
const char *fmt, ...)
788 char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
794 IGNORE_UNUSED_RESULT(vsnprintf(buf,
sizeof(buf), fmt, ap));
800 if (conn->ctx->callbacks.log_message == NULL ||
801 conn->ctx->callbacks.log_message(conn, buf) == 0) {
802 fp = conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
803 fopen(conn->ctx->config[ERROR_LOG_FILE],
"a+");
807 timestamp = time(NULL);
809 sockaddr_to_string(src_addr,
sizeof(src_addr), &conn->client.rsa);
810 fprintf(fp,
"[%010lu] [error] [client %s] ", (
unsigned long) timestamp,
813 if (conn->request_info.request_method != NULL) {
814 fprintf(fp,
"%s %s: ", conn->request_info.request_method,
815 conn->request_info.uri);
818 fprintf(fp,
"%s", buf);
828 static struct mg_connection *fc(
struct mg_context *ctx)
830 static struct mg_connection fake_connection;
831 fake_connection.ctx = ctx;
832 return &fake_connection;
835 const char *mg_version(
void)
837 return CIVETWEB_VERSION;
840 struct mg_request_info *mg_get_request_info(
struct mg_connection *conn)
842 return &conn->request_info;
845 static void mg_strlcpy(
register char *dst,
register const char *src,
size_t n)
847 for (; *src !=
'\0' && n > 1; n--) {
853 static int lowercase(
const char *s)
855 return tolower(* (
const unsigned char *) s);
858 int mg_strncasecmp(
const char *s1,
const char *s2,
size_t len)
864 diff = lowercase(s1++) - lowercase(s2++);
865 }
while (diff == 0 && s1[-1] !=
'\0' && --len > 0);
870 static int mg_strcasecmp(
const char *s1,
const char *s2)
875 diff = lowercase(s1++) - lowercase(s2++);
876 }
while (diff == 0 && s1[-1] !=
'\0');
881 static char * mg_strndup(
const char *ptr,
size_t len)
885 if ((p = (
char *) malloc(len + 1)) != NULL) {
886 mg_strlcpy(p, ptr, len + 1);
892 static char * mg_strdup(
const char *str)
894 return mg_strndup(str, strlen(str));
897 static const char *mg_strcasestr(
const char *big_str,
const char *small_str)
899 int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
901 for (i = 0; i <= big_len - small_len; i++) {
902 if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
914 static int mg_vsnprintf(
struct mg_connection *conn,
char *buf,
size_t buflen,
915 const char *fmt, va_list ap)
922 n = vsnprintf(buf, buflen, fmt, ap);
925 mg_cry(conn,
"vsnprintf error");
927 }
else if (n >= (
int) buflen) {
928 mg_cry(conn,
"truncating vsnprintf buffer: [%.*s]",
929 n > 200 ? 200 : n, buf);
930 n = (int) buflen - 1;
937 static int mg_snprintf(
struct mg_connection *conn,
char *buf,
size_t buflen,
938 PRINTF_FORMAT_STRING(
const char *fmt), ...)
941 static
int mg_snprintf(struct mg_connection *conn,
char *buf,
size_t buflen,
942 const
char *fmt, ...)
948 n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
958 static char *skip_quoted(
char **buf,
const char *delimiters,
959 const char *whitespace,
char quotechar)
961 char *p, *begin_word, *end_word, *end_whitespace;
964 end_word = begin_word + strcspn(begin_word, delimiters);
967 if (end_word > begin_word) {
969 while (*p == quotechar) {
971 if (*end_word ==
'\0') {
975 size_t end_off = strcspn(end_word + 1, delimiters);
976 memmove (p, end_word, end_off + 1);
978 end_word += end_off + 1;
981 for (p++; p < end_word; p++) {
986 if (*end_word ==
'\0') {
989 end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
991 for (p = end_word; p < end_whitespace; p++) {
995 *buf = end_whitespace;
1003 static char *skip(
char **buf,
const char *delimiters)
1005 return skip_quoted(buf, delimiters, delimiters, 0);
1010 static const char *get_header(
const struct mg_request_info *ri,
1015 for (i = 0; i < ri->num_headers; i++)
1016 if (!mg_strcasecmp(name, ri->http_headers[i].name))
1017 return ri->http_headers[i].value;
1022 const char *mg_get_header(
const struct mg_connection *conn,
const char *name)
1024 return get_header(&conn->request_info, name);
1033 static const char *next_option(
const char *list,
struct vec *val,
1036 if (list == NULL || *list ==
'\0') {
1041 if ((list = strchr(val->ptr,
',')) != NULL) {
1043 val->len = list - val->ptr;
1047 list = val->ptr + strlen(val->ptr);
1048 val->len = list - val->ptr;
1051 if (eq_val != NULL) {
1055 eq_val->ptr = (
const char *) memchr(val->ptr,
'=', val->len);
1056 if (eq_val->ptr != NULL) {
1058 eq_val->len = val->ptr + val->len - eq_val->ptr;
1059 val->len = (eq_val->ptr - val->ptr) - 1;
1068 static int match_prefix(
const char *pattern,
int pattern_len,
const char *str)
1073 if ((or_str = (
const char *) memchr(pattern,
'|', pattern_len)) != NULL) {
1074 res = match_prefix(pattern, (
int)(or_str - pattern), str);
1075 return res > 0 ? res :
1076 match_prefix(or_str + 1, (
int)((pattern + pattern_len) - (or_str + 1)), str);
1081 for (; i < pattern_len; i++, j++) {
1082 if (pattern[i] ==
'?' && str[j] !=
'\0') {
1084 }
else if (pattern[i] ==
'$') {
1085 return str[j] ==
'\0' ? j : -1;
1086 }
else if (pattern[i] ==
'*') {
1088 if (pattern[i] ==
'*') {
1090 len = (int) strlen(str + j);
1092 len = (int) strcspn(str + j,
"/");
1094 if (i == pattern_len) {
1098 res = match_prefix(pattern + i, pattern_len - i, str + j + len);
1099 }
while (res == -1 && len-- > 0);
1100 return res == -1 ? -1 : j + res + len;
1101 }
else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
1111 static int should_keep_alive(
const struct mg_connection *conn)
1113 const char *http_version = conn->request_info.http_version;
1114 const char *header = mg_get_header(conn,
"Connection");
1115 if (conn->must_close ||
1116 conn->status_code == 401 ||
1117 mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE],
"yes") != 0 ||
1118 (header != NULL && mg_strcasecmp(header,
"keep-alive") != 0) ||
1119 (header == NULL && http_version && strcmp(http_version,
"1.1"))) {
1125 static const char *suggest_connection_header(
const struct mg_connection *conn)
1127 return should_keep_alive(conn) ?
"keep-alive" :
"close";
1130 static void send_http_error(
struct mg_connection *,
int,
const char *,
1131 PRINTF_FORMAT_STRING(
const char *fmt), ...)
1135 static
void send_http_error(struct mg_connection *conn,
int status,
1136 const
char *reason, const
char *fmt, ...)
1138 char buf[MG_BUF_LEN];
1142 time_t curtime = time(NULL);
1144 conn->status_code = status;
1145 if (conn->ctx->callbacks.http_error == NULL ||
1146 conn->ctx->callbacks.http_error(conn, status)) {
1149 gmt_time_string(date,
sizeof(date), &curtime);
1152 if (status > 199 && status != 204 && status != 304) {
1153 len = mg_snprintf(conn, buf,
sizeof(buf),
"Error %d: %s", status, reason);
1157 len += mg_vsnprintf(conn, buf + len,
sizeof(buf) - len, fmt, ap);
1160 DEBUG_TRACE((
"[%s]", buf));
1162 mg_printf(conn,
"HTTP/1.1 %d %s\r\n"
1163 "Content-Length: %d\r\n"
1165 "Connection: %s\r\n\r\n",
1166 status, reason, len, date,
1167 suggest_connection_header(conn));
1168 conn->num_bytes_sent += mg_printf(conn,
"%s", buf);
1172 #if defined(_WIN32) && !defined(__SYMBIAN32__)
1173 static int pthread_mutex_init(pthread_mutex_t *mutex,
void *unused)
1176 *mutex = CreateMutex(NULL, FALSE, NULL);
1177 return *mutex == NULL ? -1 : 0;
1180 static int pthread_mutex_destroy(pthread_mutex_t *mutex)
1182 return CloseHandle(*mutex) == 0 ? -1 : 0;
1185 static int pthread_mutex_lock(pthread_mutex_t *mutex)
1187 return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
1190 static int pthread_mutex_unlock(pthread_mutex_t *mutex)
1192 return ReleaseMutex(*mutex) == 0 ? -1 : 0;
1195 static int clock_gettime(clockid_t clk_id,
struct timespec *tp)
1201 static double perfcnt_per_sec = 0.0;
1204 if (clk_id == CLOCK_REALTIME) {
1205 GetSystemTimeAsFileTime(&ft);
1206 li.LowPart = ft.dwLowDateTime;
1207 li.HighPart = ft.dwHighDateTime;
1208 li.QuadPart -= 116444736000000000;
1209 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
1210 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
1212 }
else if (clk_id == CLOCK_MONOTONIC) {
1213 if (perfcnt_per_sec==0) {
1214 QueryPerformanceFrequency((LARGE_INTEGER *) &li);
1215 perfcnt_per_sec = 1.0 / li.QuadPart;
1217 if (perfcnt_per_sec!=0) {
1218 QueryPerformanceCounter((LARGE_INTEGER *) &li);
1219 d = li.QuadPart * perfcnt_per_sec;
1220 tp->tv_sec = (time_t)d;
1222 tp->tv_nsec = (long)(d*1.0E9);
1231 static int pthread_cond_init(pthread_cond_t *cv,
const void *unused)
1234 InitializeCriticalSection(&cv->threadIdSec);
1235 cv->waitingthreadcount = 0;
1236 cv->waitingthreadhdls = (pthread_t*) calloc(MAX_WORKER_THREADS,
sizeof(pthread_t));
1237 return (cv->waitingthreadhdls!=NULL) ? 0 : -1;
1240 static int pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mutex,
const struct timespec * abstime)
1242 struct mg_workerTLS * tls = (
struct mg_workerTLS *)TlsGetValue(sTlsKey);
1244 struct timespec tsnow;
1245 int64_t nsnow, nswaitabs, nswaitrel;
1248 EnterCriticalSection(&cv->threadIdSec);
1249 assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
1250 cv->waitingthreadhdls[cv->waitingthreadcount] = tls->pthread_cond_helper_mutex;
1251 cv->waitingthreadcount++;
1252 LeaveCriticalSection(&cv->threadIdSec);
1255 clock_gettime(CLOCK_REALTIME, &tsnow);
1256 nsnow = (((uint64_t)tsnow.tv_sec)<<32) + tsnow.tv_nsec;
1257 nswaitabs = (((uint64_t)abstime->tv_sec)<<32) + abstime->tv_nsec;
1258 nswaitrel = nswaitabs - nsnow;
1259 if (nswaitrel<0) nswaitrel=0;
1260 mswaitrel = (DWORD)(nswaitrel / 1000000);
1262 mswaitrel = INFINITE;
1265 pthread_mutex_unlock(mutex);
1266 ok = (WAIT_OBJECT_0 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
1267 pthread_mutex_lock(mutex);
1272 static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
1274 return pthread_cond_timedwait(cv, mutex, NULL);
1277 static int pthread_cond_signal(pthread_cond_t *cv)
1283 EnterCriticalSection(&cv->threadIdSec);
1284 if (cv->waitingthreadcount) {
1285 wkup = cv->waitingthreadhdls[0];
1286 ok = SetEvent(wkup);
1288 for (i=1; i<cv->waitingthreadcount; i++) {
1289 cv->waitingthreadhdls[i-1] = cv->waitingthreadhdls[i];
1291 cv->waitingthreadcount--;
1295 LeaveCriticalSection(&cv->threadIdSec);
1300 static int pthread_cond_broadcast(pthread_cond_t *cv)
1302 EnterCriticalSection(&cv->threadIdSec);
1303 while (cv->waitingthreadcount) {
1304 pthread_cond_signal(cv);
1306 LeaveCriticalSection(&cv->threadIdSec);
1311 static int pthread_cond_destroy(pthread_cond_t *cv)
1313 EnterCriticalSection(&cv->threadIdSec);
1314 assert(cv->waitingthreadcount==0);
1315 cv->waitingthreadhdls = 0;
1316 free(cv->waitingthreadhdls);
1317 LeaveCriticalSection(&cv->threadIdSec);
1318 DeleteCriticalSection(&cv->threadIdSec);
1324 static void change_slashes_to_backslashes(
char *path)
1328 for (i = 0; path[i] !=
'\0'; i++) {
1332 if (path[i] ==
'\\' && i > 0)
1333 while (path[i + 1] ==
'\\' || path[i + 1] ==
'/')
1334 (void) memmove(path + i + 1,
1335 path + i + 2, strlen(path + i + 1));
1341 static void to_unicode(
const char *path,
wchar_t *wbuf,
size_t wbuf_len)
1343 char buf[PATH_MAX], buf2[PATH_MAX];
1345 mg_strlcpy(buf, path,
sizeof(buf));
1346 change_slashes_to_backslashes(buf);
1350 memset(wbuf, 0, wbuf_len *
sizeof(
wchar_t));
1351 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (
int) wbuf_len);
1352 WideCharToMultiByte(CP_UTF8, 0, wbuf, (
int) wbuf_len, buf2,
sizeof(buf2),
1354 if (strcmp(buf, buf2) != 0) {
1359 #if defined(_WIN32_WCE)
1360 static time_t time(time_t *ptime)
1367 SystemTimeToFileTime(&st, &ft);
1368 t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
1370 if (ptime != NULL) {
1377 static struct tm *localtime(
const time_t *ptime,
struct tm *ptm)
1379 int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
1382 TIME_ZONE_INFORMATION tzinfo;
1388 * (int64_t *) &ft = t;
1389 FileTimeToLocalFileTime(&ft, &lft);
1390 FileTimeToSystemTime(&lft, &st);
1391 ptm->tm_year = st.wYear - 1900;
1392 ptm->tm_mon = st.wMonth - 1;
1393 ptm->tm_wday = st.wDayOfWeek;
1394 ptm->tm_mday = st.wDay;
1395 ptm->tm_hour = st.wHour;
1396 ptm->tm_min = st.wMinute;
1397 ptm->tm_sec = st.wSecond;
1400 GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
1405 static struct tm *gmtime(
const time_t *ptime,
struct tm *ptm)
1408 return localtime(ptime, ptm);
1411 static size_t strftime(
char *dst,
size_t dst_size,
const char *fmt,
1412 const struct tm *tm)
1414 (void) snprintf(dst, dst_size,
"implement strftime() for WinCE");
1423 static int path_cannot_disclose_cgi(
const char *path)
1425 static const char *allowed_last_characters =
"_-";
1426 int last = path[strlen(path) - 1];
1427 return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
1430 static int mg_stat(
struct mg_connection *conn,
const char *path,
1433 wchar_t wbuf[PATH_MAX];
1434 WIN32_FILE_ATTRIBUTE_DATA info;
1436 if (!is_file_in_memory(conn, path, filep)) {
1437 to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
1438 if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
1439 filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
1440 filep->modification_time = SYS2UNIX_TIME(
1441 info.ftLastWriteTime.dwLowDateTime,
1442 info.ftLastWriteTime.dwHighDateTime);
1443 filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
1448 if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
1449 memset(filep, 0,
sizeof(*filep));
1454 return filep->membuf != NULL || filep->modification_time != 0;
1457 static int mg_remove(
const char *path)
1459 wchar_t wbuf[PATH_MAX];
1460 to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
1461 return DeleteFileW(wbuf) ? 0 : -1;
1464 static int mg_mkdir(
const char *path,
int mode)
1467 wchar_t wbuf[PATH_MAX];
1470 mg_strlcpy(buf, path,
sizeof(buf));
1471 change_slashes_to_backslashes(buf);
1473 (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
1475 return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
1479 static DIR * opendir(
const char *name)
1482 wchar_t wpath[PATH_MAX];
1486 SetLastError(ERROR_BAD_ARGUMENTS);
1487 }
else if ((dir = (DIR *) malloc(
sizeof(*dir))) == NULL) {
1488 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1490 to_unicode(name, wpath, ARRAY_SIZE(wpath));
1491 attrs = GetFileAttributesW(wpath);
1492 if (attrs != 0xFFFFFFFF &&
1493 ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
1494 (void) wcscat(wpath, L
"\\*");
1495 dir->handle = FindFirstFileW(wpath, &dir->info);
1496 dir->result.d_name[0] =
'\0';
1506 static int closedir(DIR *dir)
1511 if (dir->handle != INVALID_HANDLE_VALUE)
1512 result = FindClose(dir->handle) ? 0 : -1;
1517 SetLastError(ERROR_BAD_ARGUMENTS);
1523 static struct dirent *readdir(DIR *dir)
1525 struct dirent *result = 0;
1528 if (dir->handle != INVALID_HANDLE_VALUE) {
1529 result = &dir->result;
1530 (void) WideCharToMultiByte(CP_UTF8, 0,
1531 dir->info.cFileName, -1, result->d_name,
1532 sizeof(result->d_name), NULL, NULL);
1534 if (!FindNextFileW(dir->handle, &dir->info)) {
1535 (void) FindClose(dir->handle);
1536 dir->handle = INVALID_HANDLE_VALUE;
1540 SetLastError(ERROR_FILE_NOT_FOUND);
1543 SetLastError(ERROR_BAD_ARGUMENTS);
1550 static int poll(
struct pollfd *pfd,
int n,
int milliseconds)
1557 tv.tv_sec = milliseconds / 1000;
1558 tv.tv_usec = (milliseconds % 1000) * 1000;
1561 for (i = 0; i < n; i++) {
1562 FD_SET((SOCKET) pfd[i].fd, &set);
1565 if (pfd[i].fd > maxfd) {
1570 if ((result = select((
int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
1571 for (i = 0; i < n; i++) {
1572 if (FD_ISSET(pfd[i].fd, &set)) {
1573 pfd[i].revents = POLLIN;
1582 static void set_close_on_exec(SOCKET sock,
struct mg_connection *conn )
1585 (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
1588 int mg_start_thread(mg_thread_func_t f,
void *p)
1590 #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
1592 return (
long)_beginthread((
void (__cdecl *)(
void *)) f, USE_STACK_SIZE, p) == -1L ? -1 : 0;
1594 return (
long)_beginthread((
void (__cdecl *)(
void *)) f, 0, p) == -1L ? -1 : 0;
1600 static int mg_start_thread_with_id(
unsigned (__stdcall *f)(
void *),
void *p,
1601 pthread_t *threadidptr)
1604 HANDLE threadhandle;
1607 uip = _beginthreadex(NULL, 0, (
unsigned (__stdcall *)(
void *)) f, p, 0,
1609 threadhandle = (HANDLE) uip;
1610 if (threadidptr != NULL) {
1611 *threadidptr = threadhandle;
1613 result = (threadhandle == NULL) ? -1 : 0;
1620 static int mg_join_thread(pthread_t threadid)
1626 dwevent = WaitForSingleObject(threadid, INFINITE);
1627 if (dwevent == WAIT_FAILED) {
1630 err = GetLastError();
1631 DEBUG_TRACE((
"WaitForSingleObject() failed, error %d", err));
1633 if (dwevent == WAIT_OBJECT_0) {
1634 CloseHandle(threadid);
1642 static HANDLE dlopen(
const char *dll_name,
int flags)
1644 wchar_t wbuf[PATH_MAX];
1646 to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
1647 return LoadLibraryW(wbuf);
1650 static int dlclose(
void *handle)
1654 if (FreeLibrary((HMODULE) handle) != 0) {
1663 #if !defined(NO_CGI)
1665 static int kill(pid_t pid,
int sig_num)
1667 (void) TerminateProcess(pid, sig_num);
1668 (void) CloseHandle(pid);
1672 static void trim_trailing_whitespaces(
char *s)
1674 char *e = s + strlen(s) - 1;
1675 while (e > s && isspace(* (
unsigned char *) e)) {
1680 static pid_t spawn_process(
struct mg_connection *conn,
const char *prog,
1681 char *envblk,
char *envp[],
int fdin,
1682 int fdout,
const char *dir)
1685 char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
1686 cmdline[PATH_MAX], buf[PATH_MAX];
1687 struct file file = STRUCT_FILE_INITIALIZER;
1689 PROCESS_INFORMATION pi = { 0 };
1693 memset(&si, 0,
sizeof(si));
1697 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1698 si.wShowWindow = SW_HIDE;
1700 me = GetCurrentProcess();
1701 DuplicateHandle(me, (HANDLE) _get_osfhandle(fdin), me,
1702 &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
1703 DuplicateHandle(me, (HANDLE) _get_osfhandle(fdout), me,
1704 &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
1707 interp = conn->ctx->config[CGI_INTERPRETER];
1708 if (interp == NULL) {
1709 buf[0] = buf[1] =
'\0';
1712 snprintf(cmdline,
sizeof(cmdline),
"%s%c%s", dir,
'/', prog);
1713 if (mg_fopen(conn, cmdline,
"r", &file)) {
1714 p = (
char *) file.membuf;
1715 mg_fgets(buf,
sizeof(buf), &file, &p);
1717 buf[
sizeof(buf) - 1] =
'\0';
1720 if (buf[0] ==
'#' && buf[1] ==
'!') {
1721 trim_trailing_whitespaces(buf + 2);
1728 if (interp[0] !=
'\0') {
1729 GetFullPathNameA(interp,
sizeof(full_interp), full_interp, NULL);
1730 interp = full_interp;
1732 GetFullPathNameA(dir,
sizeof(full_dir), full_dir, NULL);
1734 mg_snprintf(conn, cmdline,
sizeof(cmdline),
"%s%s\"%s\\%s\"",
1735 interp, interp[0] ==
'\0' ?
"" :
" ", full_dir, prog);
1737 DEBUG_TRACE((
"Running [%s]", cmdline));
1738 if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
1739 CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
1740 mg_cry(conn,
"%s: CreateProcess(%s): %ld",
1741 __func__, cmdline, ERRNO);
1742 pi.hProcess = (pid_t) -1;
1745 (void) CloseHandle(si.hStdOutput);
1746 (void) CloseHandle(si.hStdInput);
1747 if (pi.hThread != NULL)
1748 (void) CloseHandle(pi.hThread);
1750 return (pid_t) pi.hProcess;
1754 static int set_non_blocking_mode(SOCKET sock)
1756 unsigned long on = 1;
1757 return ioctlsocket(sock, FIONBIO, &on);
1761 static int mg_stat(
struct mg_connection *conn,
const char *path,
1766 if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
1767 filep->size = st.st_size;
1768 filep->modification_time = st.st_mtime;
1769 filep->is_directory = S_ISDIR(st.st_mode);
1771 filep->modification_time = (time_t) 0;
1774 return filep->membuf != NULL || filep->modification_time != (time_t) 0;
1777 static void set_close_on_exec(
int fd,
struct mg_connection *conn )
1779 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
1781 mg_cry(conn,
"%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
1782 __func__, strerror(ERRNO));
1786 int mg_start_thread(mg_thread_func_t func,
void *param)
1788 pthread_t thread_id;
1789 pthread_attr_t attr;
1792 (void) pthread_attr_init(&attr);
1793 (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1795 #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
1798 (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
1801 result = pthread_create(&thread_id, &attr, func, param);
1802 pthread_attr_destroy(&attr);
1809 static int mg_start_thread_with_id(mg_thread_func_t func,
void *param,
1810 pthread_t *threadidptr)
1812 pthread_t thread_id;
1813 pthread_attr_t attr;
1816 (void) pthread_attr_init(&attr);
1818 #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
1821 (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
1824 result = pthread_create(&thread_id, &attr, func, param);
1825 pthread_attr_destroy(&attr);
1826 if (threadidptr != NULL) {
1827 *threadidptr = thread_id;
1834 static int mg_join_thread(pthread_t threadid)
1838 result = pthread_join(threadid, NULL);
1843 static pid_t spawn_process(
struct mg_connection *conn,
const char *prog,
1844 char *envblk,
char *envp[],
int fdin,
1845 int fdout,
const char *dir)
1852 if ((pid = fork()) == -1) {
1854 send_http_error(conn, 500, http_500_error,
"fork(): %s", strerror(ERRNO));
1855 }
else if (pid == 0) {
1857 if (chdir(dir) != 0) {
1858 mg_cry(conn,
"%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
1859 }
else if (dup2(fdin, 0) == -1) {
1860 mg_cry(conn,
"%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
1861 }
else if (dup2(fdout, 1) == -1) {
1862 mg_cry(conn,
"%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
1867 (void) close(fdout);
1874 signal(SIGCHLD, SIG_DFL);
1876 interp = conn->ctx->config[CGI_INTERPRETER];
1877 if (interp == NULL) {
1878 (void) execle(prog, prog, NULL, envp);
1879 mg_cry(conn,
"%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
1881 (void) execle(interp, interp, prog, NULL, envp);
1882 mg_cry(conn,
"%s: execle(%s %s): %s", __func__, interp, prog,
1893 static int set_non_blocking_mode(SOCKET sock)
1897 flags = fcntl(sock, F_GETFL, 0);
1898 (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
1906 static int64_t push(FILE *fp, SOCKET sock, SSL *ssl,
const char *buf,
1914 while (sent < len) {
1917 k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
1921 n = SSL_write(ssl, buf + sent, k);
1925 n = (int) fwrite(buf + sent, 1, (
size_t) k, fp);
1929 n = send(sock, buf + sent, (
size_t) k, MSG_NOSIGNAL);
1943 static int pull(FILE *fp,
struct mg_connection *conn,
char *buf,
int len)
1952 nread = read(fileno(fp), buf, (
size_t) len);
1954 }
else if (conn->ssl != NULL) {
1955 nread = SSL_read(conn->ssl, buf, len);
1958 nread = recv(conn->client.sock, buf, (
size_t) len, 0);
1961 return conn->ctx->stop_flag ? -1 : nread;
1964 static int pull_all(FILE *fp,
struct mg_connection *conn,
char *buf,
int len)
1968 while (len > 0 && conn->ctx->stop_flag == 0) {
1969 n = pull(fp, conn, buf + nread, len);
1973 }
else if (n == 0) {
1976 conn->consumed_content += n;
1985 int mg_read(
struct mg_connection *conn,
void *buf,
size_t len)
1987 int n, buffered_len, nread;
1991 if (conn->consumed_content == 0 && conn->content_len == 0) {
1992 conn->content_len = INT64_MAX;
1993 conn->must_close = 1;
1997 if (conn->consumed_content < conn->content_len) {
1999 int64_t to_read = conn->content_len - conn->consumed_content;
2000 if (to_read < (int64_t) len) {
2001 len = (size_t) to_read;
2005 body = conn->buf + conn->request_len + conn->consumed_content;
2006 buffered_len = (int)(&conn->buf[conn->data_len] - body);
2007 if (buffered_len > 0) {
2008 if (len < (
size_t) buffered_len) {
2009 buffered_len = (int) len;
2011 memcpy(buf, body, (
size_t) buffered_len);
2012 len -= buffered_len;
2013 conn->consumed_content += buffered_len;
2014 nread += buffered_len;
2015 buf = (
char *) buf + buffered_len;
2020 n = pull_all(NULL, conn, (
char *) buf, (
int) len);
2021 nread = n >= 0 ? nread + n : n;
2026 int mg_write(
struct mg_connection *conn,
const void *buf,
size_t len)
2029 int64_t n, total, allowed;
2031 if (conn->throttle > 0) {
2032 if ((now = time(NULL)) != conn->last_throttle_time) {
2033 conn->last_throttle_time = now;
2034 conn->last_throttle_bytes = 0;
2036 allowed = conn->throttle - conn->last_throttle_bytes;
2037 if (allowed > (int64_t) len) {
2040 if ((total = push(NULL, conn->client.sock, conn->ssl, (
const char *) buf,
2041 (int64_t) allowed)) == allowed) {
2042 buf = (
char *) buf + total;
2043 conn->last_throttle_bytes += total;
2044 while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
2045 allowed = conn->throttle > (int64_t) len - total ?
2046 (int64_t) len - total : conn->throttle;
2047 if ((n = push(NULL, conn->client.sock, conn->ssl, (
const char *) buf,
2048 (int64_t) allowed)) != allowed) {
2052 conn->last_throttle_bytes = allowed;
2053 conn->last_throttle_time = time(NULL);
2054 buf = (
char *) buf + n;
2059 total = push(NULL, conn->client.sock, conn->ssl, (
const char *) buf,
2066 static int alloc_vprintf2(
char **buf,
const char *fmt, va_list ap)
2069 int size = MG_BUF_LEN;
2074 if (*buf) free(*buf);
2075 *buf = (
char *)malloc(size *= 4);
2077 va_copy(ap_copy, ap);
2078 len = vsnprintf(*buf, size, fmt, ap_copy);
2088 static int alloc_vprintf(
char **buf,
size_t size,
const char *fmt, va_list ap)
2099 va_copy(ap_copy, ap);
2100 len = vsnprintf(NULL, 0, fmt, ap_copy);
2107 va_copy(ap_copy, ap);
2108 len = alloc_vprintf2(buf, fmt, ap);
2110 }
else if (len > (
int) size &&
2111 (size = len + 1) > 0 &&
2112 (*buf = (
char *) malloc(size)) == NULL) {
2115 va_copy(ap_copy, ap);
2116 IGNORE_UNUSED_RESULT(vsnprintf(*buf, size, fmt, ap_copy));
2123 int mg_vprintf(
struct mg_connection *conn,
const char *fmt, va_list ap);
2125 int mg_vprintf(
struct mg_connection *conn,
const char *fmt, va_list ap)
2127 char mem[MG_BUF_LEN], *buf = mem;
2130 if ((len = alloc_vprintf(&buf,
sizeof(mem), fmt, ap)) > 0) {
2131 len = mg_write(conn, buf, (
size_t) len);
2133 if (buf != mem && buf != NULL) {
2140 int mg_printf(
struct mg_connection *conn,
const char *fmt, ...)
2146 result = mg_vprintf(conn, fmt, ap);
2152 int mg_url_decode(
const char *src,
int src_len,
char *dst,
2153 int dst_len,
int is_form_url_encoded)
2156 #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
2158 for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
2159 if (src[i] ==
'%' && i < src_len - 2 &&
2160 isxdigit(* (
const unsigned char *) (src + i + 1)) &&
2161 isxdigit(* (
const unsigned char *) (src + i + 2))) {
2162 a = tolower(* (
const unsigned char *) (src + i + 1));
2163 b = tolower(* (
const unsigned char *) (src + i + 2));
2164 dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
2166 }
else if (is_form_url_encoded && src[i] ==
'+') {
2175 return i >= src_len ? j : -1;
2178 int mg_get_var(
const char *data,
size_t data_len,
const char *name,
2179 char *dst,
size_t dst_len)
2181 return mg_get_var2(data,data_len,name,dst,dst_len,0);
2184 int mg_get_var2(
const char *data,
size_t data_len,
const char *name,
2185 char *dst,
size_t dst_len,
size_t occurrence)
2187 const char *p, *e, *s;
2191 if (dst == NULL || dst_len == 0) {
2193 }
else if (data == NULL || name == NULL || data_len == 0) {
2197 name_len = strlen(name);
2198 e = data + data_len;
2203 for (p = data; p + name_len < e; p++) {
2204 if ((p == data || p[-1] ==
'&') && p[name_len] ==
'=' &&
2205 !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
2211 s = (
const char *) memchr(p,
'&', (
size_t)(e - p));
2218 len = mg_url_decode(p, (
int)(s - p), dst, (
int)dst_len, 1);
2233 int mg_get_cookie(
const char *cookie_header,
const char *var_name,
2234 char *dst,
size_t dst_size)
2236 const char *s, *p, *end;
2237 int name_len, len = -1;
2239 if (dst == NULL || dst_size == 0) {
2241 }
else if (var_name == NULL || (s = cookie_header) == NULL) {
2245 name_len = (int) strlen(var_name);
2246 end = s + strlen(s);
2249 for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
2250 if (s[name_len] ==
'=') {
2252 if ((p = strchr(s,
' ')) == NULL)
2256 if (*s ==
'"' && p[-1] ==
'"' && p > s + 1) {
2260 if ((
size_t) (p - s) < dst_size) {
2262 mg_strlcpy(dst, s, (
size_t) len + 1);
2273 static void convert_uri_to_file_name(
struct mg_connection *conn,
char *buf,
2274 size_t buf_len,
struct file *filep,
2275 int * is_script_ressource)
2278 const char *rewrite, *uri = conn->request_info.uri,
2279 *root = conn->ctx->config[DOCUMENT_ROOT];
2282 char gz_path[PATH_MAX];
2283 char const* accept_encoding;
2285 *is_script_ressource = 0;
2287 #if defined(USE_WEBSOCKET)
2288 if (is_websocket_request(conn) && conn->ctx->config[WEBSOCKET_ROOT]) {
2289 root = conn->ctx->config[WEBSOCKET_ROOT];
2296 mg_snprintf(conn, buf, buf_len - 1,
"%s%s",
2297 root == NULL ?
"" : root,
2298 root == NULL ?
"" : uri);
2300 rewrite = conn->ctx->config[REWRITE];
2301 while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
2302 if ((match_len = match_prefix(a.ptr, (
int) a.len, uri)) > 0) {
2303 mg_snprintf(conn, buf, buf_len - 1,
"%.*s%s", (
int) b.len, b.ptr,
2309 if (mg_stat(conn, buf, filep))
return;
2317 if ((accept_encoding = mg_get_header(conn,
"Accept-Encoding")) != NULL) {
2318 if (strstr(accept_encoding,
"gzip") != NULL) {
2319 snprintf(gz_path,
sizeof(gz_path),
"%s.gz", buf);
2320 if (mg_stat(conn, gz_path, filep)) {
2328 for (p = buf + strlen(buf); p > buf + 1; p--) {
2331 if ((match_prefix(conn->ctx->config[CGI_EXTENSIONS],
2332 (
int)strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0
2335 match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
2336 (
int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]), buf) > 0
2338 ) && mg_stat(conn, buf, filep)) {
2344 conn->path_info = p + 1;
2345 memmove(p + 2, p + 1, strlen(p + 1) + 1);
2348 *is_script_ressource = 1;
2361 static int get_request_len(
const char *buf,
int buflen)
2366 for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
2368 if (!isprint(* (
const unsigned char *) s) && *s !=
'\r' &&
2369 *s !=
'\n' && * (
const unsigned char *) s < 128) {
2374 }
else if (s[0] ==
'\n' && s[1] ==
'\n') {
2375 len = (int) (s - buf) + 2;
2376 }
else if (s[0] ==
'\n' && &s[1] < e &&
2377 s[1] ==
'\r' && s[2] ==
'\n') {
2378 len = (int) (s - buf) + 3;
2385 static int get_month_index(
const char *s)
2389 for (i = 0; i < ARRAY_SIZE(month_names); i++)
2390 if (!strcmp(s, month_names[i]))
2396 static int num_leap_years(
int year)
2398 return year / 4 - year / 100 + year / 400;
2402 static time_t parse_date_string(
const char *datetime)
2404 static const unsigned short days_before_month[] = {
2405 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
2408 int second, minute, hour, day, month, year, leap_days, days;
2409 time_t result = (time_t) 0;
2411 if (((sscanf(datetime,
"%d/%3s/%d %d:%d:%d",
2412 &day, month_str, &year, &hour, &minute, &second) == 6) ||
2413 (sscanf(datetime,
"%d %3s %d %d:%d:%d",
2414 &day, month_str, &year, &hour, &minute, &second) == 6) ||
2415 (sscanf(datetime,
"%*3s, %d %3s %d %d:%d:%d",
2416 &day, month_str, &year, &hour, &minute, &second) == 6) ||
2417 (sscanf(datetime,
"%d-%3s-%d %d:%d:%d",
2418 &day, month_str, &year, &hour, &minute, &second) == 6)) &&
2420 (month = get_month_index(month_str)) != -1) {
2421 leap_days = num_leap_years(year) - num_leap_years(1970);
2423 days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
2424 result = (time_t) days * 24 * 3600 + (time_t) hour * 3600 +
2425 minute * 60 + second;
2433 static void remove_double_dots_and_double_slashes(
char *s)
2437 while (*s !=
'\0') {
2439 if (s[-1] ==
'/' || s[-1] ==
'\\') {
2441 while (s[0] !=
'\0') {
2442 if (s[0] ==
'/' || s[0] ==
'\\') {
2444 }
else if (s[0] ==
'.' && s[1] ==
'.') {
2455 static const struct {
2456 const char *extension;
2458 const char *mime_type;
2459 } builtin_mime_types[] = {
2462 {
".doc", 4,
"application/msword"},
2463 {
".eps", 4,
"application/postscript"},
2464 {
".exe", 4,
"application/octet-stream"},
2465 {
".js", 3,
"application/javascript"},
2466 {
".json", 5,
"application/json"},
2467 {
".pdf", 4,
"application/pdf"},
2468 {
".ps", 3,
"application/postscript"},
2469 {
".rtf", 4,
"application/rtf"},
2470 {
".xhtml", 6,
"application/xhtml+xml"},
2471 {
".xsl", 4,
"application/xml"},
2472 {
".xslt", 5,
"application/xml"},
2475 {
".mp3", 4,
"audio/mpeg"},
2476 {
".oga", 4,
"audio/ogg"},
2477 {
".ogg", 4,
"audio/ogg"},
2480 {
".gif", 4,
"image/gif"},
2481 {
".ief", 4,
"image/ief"},
2482 {
".jpeg", 5,
"image/jpeg"},
2483 {
".jpg", 4,
"image/jpeg"},
2484 {
".jpm", 4,
"image/jpm"},
2485 {
".jpx", 4,
"image/jpx"},
2486 {
".png", 4,
"image/png"},
2487 {
".svg", 4,
"image/svg+xml"},
2488 {
".tif", 4,
"image/tiff"},
2489 {
".tiff", 5,
"image/tiff"},
2492 {
".wrl", 4,
"model/vrml"},
2495 {
".css", 4,
"text/css"},
2496 {
".csv", 4,
"text/csv"},
2497 {
".htm", 4,
"text/html"},
2498 {
".html", 5,
"text/html"},
2499 {
".sgm", 4,
"text/sgml"},
2500 {
".shtm", 5,
"text/html"},
2501 {
".shtml", 6,
"text/html"},
2502 {
".txt", 4,
"text/plain"},
2503 {
".xml", 4,
"text/xml"},
2506 {
".mov", 4,
"video/quicktime"},
2507 {
".mp4", 4,
"video/mp4"},
2508 {
".mpeg", 5,
"video/mpeg"},
2509 {
".mpg", 4,
"video/mpeg"},
2510 {
".ogv", 4,
"video/ogg"},
2511 {
".qt", 3,
"video/quicktime"},
2516 {
".arj", 4,
"application/x-arj-compressed"},
2517 {
".gz", 3,
"application/x-gunzip"},
2518 {
".rar", 4,
"application/x-arj-compressed"},
2519 {
".swf", 4,
"application/x-shockwave-flash"},
2520 {
".tar", 4,
"application/x-tar"},
2521 {
".tgz", 4,
"application/x-tar-gz"},
2522 {
".torrent", 8,
"application/x-bittorrent"},
2523 {
".ppt", 4,
"application/x-mspowerpoint"},
2524 {
".xls", 4,
"application/x-msexcel"},
2525 {
".zip", 4,
"application/x-zip-compressed"},
2526 {
".aac", 4,
"audio/aac"},
2527 {
".aif", 4,
"audio/x-aif"},
2528 {
".m3u", 4,
"audio/x-mpegurl"},
2529 {
".mid", 4,
"audio/x-midi"},
2530 {
".ra", 3,
"audio/x-pn-realaudio"},
2531 {
".ram", 4,
"audio/x-pn-realaudio"},
2532 {
".wav", 4,
"audio/x-wav"},
2533 {
".bmp", 4,
"image/bmp"},
2534 {
".ico", 4,
"image/x-icon"},
2535 {
".pct", 4,
"image/x-pct"},
2536 {
".pict", 5,
"image/pict"},
2537 {
".rgb", 4,
"image/x-rgb"},
2538 {
".webm", 5,
"video/webm"},
2539 {
".asf", 4,
"video/x-ms-asf"},
2540 {
".avi", 4,
"video/x-msvideo"},
2541 {
".m4v", 4,
"video/x-m4v"},
2545 const char *mg_get_builtin_mime_type(
const char *path)
2550 path_len = strlen(path);
2552 for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
2553 ext = path + (path_len - builtin_mime_types[i].ext_len);
2554 if (path_len > builtin_mime_types[i].ext_len &&
2555 mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
2556 return builtin_mime_types[i].mime_type;
2560 return "text/plain";
2565 static void get_mime_type(
struct mg_context *ctx,
const char *path,
2568 struct vec ext_vec, mime_vec;
2569 const char *list, *ext;
2572 path_len = strlen(path);
2576 list = ctx->config[EXTRA_MIME_TYPES];
2577 while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
2579 ext = path + path_len - ext_vec.len;
2580 if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
2586 vec->ptr = mg_get_builtin_mime_type(path);
2587 vec->len = strlen(vec->ptr);
2592 static void bin2str(
char *to,
const unsigned char *p,
size_t len)
2594 static const char *hex =
"0123456789abcdef";
2596 for (; len--; p++) {
2597 *to++ = hex[p[0] >> 4];
2598 *to++ = hex[p[0] & 0x0f];
2604 char *mg_md5(
char buf[33], ...)
2606 md5_byte_t hash[16];
2614 while ((p = va_arg(ap,
const char *)) != NULL) {
2615 md5_append(&ctx, (
const md5_byte_t *) p, (
int) strlen(p));
2619 md5_finish(&ctx, hash);
2620 bin2str(buf, hash,
sizeof(hash));
2625 static int check_password(
const char *method,
const char *ha1,
const char *uri,
2626 const char *nonce,
const char *nc,
const char *cnonce,
2627 const char *qop,
const char *response)
2629 char ha2[32 + 1], expected_response[32 + 1];
2632 if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
2633 qop == NULL || response == NULL) {
2640 strlen(response) != 32
2646 mg_md5(ha2, method,
":", uri, NULL);
2647 mg_md5(expected_response, ha1,
":", nonce,
":", nc,
2648 ":", cnonce,
":", qop,
":", ha2, NULL);
2650 return mg_strcasecmp(response, expected_response) == 0;
2655 static void open_auth_file(
struct mg_connection *conn,
const char *path,
2658 char name[PATH_MAX];
2659 const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
2660 struct file file = STRUCT_FILE_INITIALIZER;
2662 if (gpass != NULL) {
2664 if (!mg_fopen(conn, gpass,
"r", filep)) {
2666 mg_cry(conn,
"fopen(%s): %s", gpass, strerror(ERRNO));
2673 }
else if (mg_stat(conn, path, &file) && file.is_directory) {
2674 mg_snprintf(conn, name,
sizeof(name),
"%s%c%s",
2675 path,
'/', PASSWORDS_FILE_NAME);
2676 if (!mg_fopen(conn, name,
"r", filep)) {
2678 mg_cry(conn,
"fopen(%s): %s", name, strerror(ERRNO));
2683 for (p = path, e = p + strlen(p) - 1; e > p; e--)
2686 mg_snprintf(conn, name,
sizeof(name),
"%.*s%c%s",
2687 (
int) (e - p), p,
'/', PASSWORDS_FILE_NAME);
2688 if (!mg_fopen(conn, name,
"r", filep)) {
2690 mg_cry(conn,
"fopen(%s): %s", name, strerror(ERRNO));
2698 char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
2702 static int parse_auth_header(
struct mg_connection *conn,
char *buf,
2703 size_t buf_size,
struct ah *ah)
2705 char *name, *value, *s;
2706 const char *auth_header;
2708 (void) memset(ah, 0,
sizeof(*ah));
2709 if ((auth_header = mg_get_header(conn,
"Authorization")) == NULL ||
2710 mg_strncasecmp(auth_header,
"Digest ", 7) != 0) {
2715 (void) mg_strlcpy(buf, auth_header + 7, buf_size);
2721 while (isspace(* (
unsigned char *) s)) {
2724 name = skip_quoted(&s,
"=",
" ", 0);
2728 value = skip_quoted(&s,
"\"",
" ",
'\\');
2733 value = skip_quoted(&s,
", ",
" ", 0);
2736 if (*name ==
'\0') {
2740 if (!strcmp(name,
"username")) {
2742 }
else if (!strcmp(name,
"cnonce")) {
2744 }
else if (!strcmp(name,
"response")) {
2745 ah->response = value;
2746 }
else if (!strcmp(name,
"uri")) {
2748 }
else if (!strcmp(name,
"qop")) {
2750 }
else if (!strcmp(name,
"nc")) {
2752 }
else if (!strcmp(name,
"nonce")) {
2758 if (ah->user != NULL) {
2759 conn->request_info.remote_user = mg_strdup(ah->user);
2767 static char *mg_fgets(
char *buf,
size_t size,
struct file *filep,
char **p)
2773 if (filep->membuf != NULL && *p != NULL) {
2774 memend = (
char *) &filep->membuf[filep->size];
2775 eof = (
char *) memchr(*p,
'\n', memend - *p);
2783 len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);
2784 memcpy(buf, *p, len);
2787 return len ? eof : NULL;
2788 }
else if (filep->fp != NULL) {
2789 return fgets(buf, (
int)size, filep->fp);
2796 static int authorize(
struct mg_connection *conn,
struct file *filep)
2799 char line[256], f_user[256] =
"", ha1[256] =
"", f_domain[256] =
"", buf[MG_BUF_LEN], *p;
2801 if (!parse_auth_header(conn, buf,
sizeof(buf), &ah)) {
2806 p = (
char *) filep->membuf;
2807 while (mg_fgets(line,
sizeof(line), filep, &p) != NULL) {
2808 if (sscanf(line,
"%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
2812 if (!strcmp(ah.user, f_user) &&
2813 !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
2814 return check_password(conn->request_info.request_method, ha1, ah.uri,
2815 ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);
2822 static int check_authorization(
struct mg_connection *conn,
const char *path)
2824 char fname[PATH_MAX];
2825 struct vec uri_vec, filename_vec;
2827 struct file file = STRUCT_FILE_INITIALIZER;
2830 list = conn->ctx->config[PROTECT_URI];
2831 while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
2832 if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
2833 mg_snprintf(conn, fname,
sizeof(fname),
"%.*s",
2834 (
int) filename_vec.len, filename_vec.ptr);
2835 if (!mg_fopen(conn, fname,
"r", &file)) {
2836 mg_cry(conn,
"%s: cannot open %s: %s", __func__, fname, strerror(errno));
2842 if (!is_file_opened(&file)) {
2843 open_auth_file(conn, path, &file);
2846 if (is_file_opened(&file)) {
2847 authorized = authorize(conn, &file);
2854 static void send_authorization_request(
struct mg_connection *conn)
2857 time_t curtime = time(NULL);
2859 conn->status_code = 401;
2860 conn->must_close = 1;
2862 gmt_time_string(date,
sizeof(date), &curtime);
2865 "HTTP/1.1 401 Unauthorized\r\n"
2867 "Connection: %s\r\n"
2868 "Content-Length: 0\r\n"
2869 "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
2870 date, suggest_connection_header(conn),
2871 conn->ctx->config[AUTHENTICATION_DOMAIN],
2872 (
unsigned long) time(NULL));
2875 static int is_authorized_for_put(
struct mg_connection *conn)
2877 struct file file = STRUCT_FILE_INITIALIZER;
2878 const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
2881 if (passfile != NULL && mg_fopen(conn, passfile,
"r", &file)) {
2882 ret = authorize(conn, &file);
2889 int mg_modify_passwords_file(
const char *fname,
const char *domain,
2890 const char *user,
const char *pass)
2893 char line[512], u[512] =
"", d[512] =
"", ha1[33], tmp[PATH_MAX+1];
2900 if (pass != NULL && pass[0] ==
'\0') {
2904 (void) snprintf(tmp,
sizeof(tmp) - 1,
"%s.tmp", fname);
2905 tmp[
sizeof(tmp) - 1] = 0;
2908 if ((fp = fopen(fname,
"a+")) != NULL) {
2913 if ((fp = fopen(fname,
"r")) == NULL) {
2915 }
else if ((fp2 = fopen(tmp,
"w+")) == NULL) {
2921 while (fgets(line,
sizeof(line), fp) != NULL) {
2922 if (sscanf(line,
"%[^:]:%[^:]:%*s", u, d) != 2) {
2926 if (!strcmp(u, user) && !strcmp(d, domain)) {
2929 mg_md5(ha1, user,
":", domain,
":", pass, NULL);
2930 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1);
2933 fprintf(fp2,
"%s", line);
2938 if (!found && pass != NULL) {
2939 mg_md5(ha1, user,
":", domain,
":", pass, NULL);
2940 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1);
2948 IGNORE_UNUSED_RESULT(
remove(fname));
2949 IGNORE_UNUSED_RESULT(rename(tmp, fname));
2954 static SOCKET conn2(
struct mg_context *ctx ,
const char *host,
int port,
2955 int use_ssl,
char *ebuf,
size_t ebuf_len)
2957 struct sockaddr_in sain;
2959 SOCKET sock = INVALID_SOCKET;
2962 snprintf(ebuf, ebuf_len,
"%s",
"NULL host");
2963 }
else if (use_ssl && SSLv23_client_method == NULL) {
2964 snprintf(ebuf, ebuf_len,
"%s",
"SSL is not initialized");
2966 }
else if ((he = gethostbyname(host)) == NULL) {
2967 snprintf(ebuf, ebuf_len,
"gethostbyname(%s): %s", host, strerror(ERRNO));
2968 }
else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
2969 snprintf(ebuf, ebuf_len,
"socket(): %s", strerror(ERRNO));
2971 set_close_on_exec(sock, fc(ctx));
2972 memset(&sain,
'\0',
sizeof(sain));
2973 sain.sin_family = AF_INET;
2974 sain.sin_port = htons((uint16_t) port);
2975 sain.sin_addr = * (
struct in_addr *) he->h_addr_list[0];
2976 if (connect(sock, (
struct sockaddr *) &sain,
sizeof(sain)) != 0) {
2977 snprintf(ebuf, ebuf_len,
"connect(%s:%d): %s",
2978 host, port, strerror(ERRNO));
2980 sock = INVALID_SOCKET;
2986 int mg_url_encode(
const char *src,
char *dst,
size_t dst_len)
2988 static const char *dont_escape =
"._-$,;~()";
2989 static const char *hex =
"0123456789abcdef";
2991 const char *end = dst + dst_len - 1;
2993 for (; *src !=
'\0' && pos < end; src++, pos++) {
2994 if (isalnum(*(
const unsigned char *) src) ||
2995 strchr(dont_escape, * (
const unsigned char *) src) != NULL) {
2997 }
else if (pos + 2 < end) {
2999 pos[1] = hex[(* (
const unsigned char *) src) >> 4];
3000 pos[2] = hex[(* (
const unsigned char *) src) & 0xf];
3008 return (*src ==
'\0') ? (int)(pos - dst) : -1;
3011 static void print_dir_entry(
struct de *de)
3013 char size[64], mod[64], href[PATH_MAX];
3016 if (de->file.is_directory) {
3017 mg_snprintf(de->conn, size,
sizeof(size),
"%s",
"[DIRECTORY]");
3021 if (de->file.size < 1024) {
3022 mg_snprintf(de->conn, size,
sizeof(size),
"%d", (
int) de->file.size);
3023 }
else if (de->file.size < 0x100000) {
3024 mg_snprintf(de->conn, size,
sizeof(size),
3025 "%.1fk", (
double) de->file.size / 1024.0);
3026 }
else if (de->file.size < 0x40000000) {
3027 mg_snprintf(de->conn, size,
sizeof(size),
3028 "%.1fM", (
double) de->file.size / 1048576);
3030 mg_snprintf(de->conn, size,
sizeof(size),
3031 "%.1fG", (
double) de->file.size / 1073741824);
3034 tm = localtime(&de->file.modification_time);
3036 strftime(mod,
sizeof(mod),
"%d-%b-%Y %H:%M", tm);
3038 strncpy(mod,
"01-Jan-1970 00:00",
sizeof(mod));
3039 mod[
sizeof(mod) - 1] =
'\0';
3041 mg_url_encode(de->file_name, href,
sizeof(href));
3042 de->conn->num_bytes_sent += mg_printf(de->conn,
3043 "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
3044 "<td> %s</td><td> %s</td></tr>\n",
3045 de->conn->request_info.uri, href, de->file.is_directory ?
"/" :
"",
3046 de->file_name, de->file.is_directory ?
"/" :
"", mod, size);
3053 static int WINCDECL compare_dir_entries(
const void *p1,
const void *p2)
3055 const struct de *a = (
const struct de *) p1, *b = (
const struct de *) p2;
3056 const char *query_string = a->conn->request_info.query_string;
3059 if (query_string == NULL) {
3060 query_string =
"na";
3063 if (a->file.is_directory && !b->file.is_directory) {
3065 }
else if (!a->file.is_directory && b->file.is_directory) {
3067 }
else if (*query_string ==
'n') {
3068 cmp_result = strcmp(a->file_name, b->file_name);
3069 }
else if (*query_string ==
's') {
3070 cmp_result = a->file.size == b->file.size ? 0 :
3071 a->file.size > b->file.size ? 1 : -1;
3072 }
else if (*query_string ==
'd') {
3073 cmp_result = a->file.modification_time == b->file.modification_time ? 0 :
3074 a->file.modification_time > b->file.modification_time ? 1 : -1;
3077 return query_string[1] ==
'd' ? -cmp_result : cmp_result;
3080 static int must_hide_file(
struct mg_connection *conn,
const char *path)
3082 const char *pw_pattern =
"**" PASSWORDS_FILE_NAME
"$";
3083 const char *pattern = conn->ctx->config[HIDE_FILES];
3084 return match_prefix(pw_pattern, (
int)strlen(pw_pattern), path) > 0 ||
3085 (pattern != NULL && match_prefix(pattern, (
int)strlen(pattern), path) > 0);
3088 static int scan_directory(
struct mg_connection *conn,
const char *dir,
3089 void *data,
void (*cb)(
struct de *,
void *))
3091 char path[PATH_MAX];
3096 if ((dirp = opendir(dir)) == NULL) {
3101 while ((dp = readdir(dirp)) != NULL) {
3103 if (!strcmp(dp->d_name,
".") ||
3104 !strcmp(dp->d_name,
"..") ||
3105 must_hide_file(conn, dp->d_name)) {
3109 mg_snprintf(conn, path,
sizeof(path),
"%s%c%s", dir,
'/', dp->d_name);
3116 memset(&de.file, 0,
sizeof(de.file));
3117 if (!mg_stat(conn, path, &de.file)) {
3118 mg_cry(conn,
"%s: mg_stat(%s) failed: %s",
3119 __func__, path, strerror(ERRNO));
3122 de.file_name = dp->d_name;
3125 (void) closedir(dirp);
3130 static int remove_directory(
struct mg_connection *conn,
const char *dir)
3132 char path[PATH_MAX];
3137 if ((dirp = opendir(dir)) == NULL) {
3142 while ((dp = readdir(dirp)) != NULL) {
3145 if (!strcmp(dp->d_name,
".") ||
3146 !strcmp(dp->d_name,
"..")) {
3150 mg_snprintf(conn, path,
sizeof(path),
"%s%c%s", dir,
'/', dp->d_name);
3157 memset(&de.file, 0,
sizeof(de.file));
3158 if (!mg_stat(conn, path, &de.file)) {
3159 mg_cry(conn,
"%s: mg_stat(%s) failed: %s",
3160 __func__, path, strerror(ERRNO));
3162 if(de.file.modification_time) {
3163 if(de.file.is_directory) {
3164 remove_directory(conn, path);
3171 (void) closedir(dirp);
3173 IGNORE_UNUSED_RESULT(rmdir(dir));
3179 struct dir_scan_data {
3186 static void *realloc2(
void *ptr,
size_t size)
3188 void *new_ptr = realloc(ptr, size);
3189 if (new_ptr == NULL) {
3195 static void dir_scan_callback(
struct de *de,
void *data)
3197 struct dir_scan_data *dsd = (
struct dir_scan_data *) data;
3199 if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
3201 dsd->entries = (
struct de *) realloc2(dsd->entries, dsd->arr_size *
3202 sizeof(dsd->entries[0]));
3204 if (dsd->entries == NULL) {
3206 dsd->num_entries = 0;
3208 dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
3209 dsd->entries[dsd->num_entries].file = de->file;
3210 dsd->entries[dsd->num_entries].conn = de->conn;
3215 static void handle_directory_request(
struct mg_connection *conn,
3218 int i, sort_direction;
3219 struct dir_scan_data data = { NULL, 0, 128 };
3221 time_t curtime = time(NULL);
3223 if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
3224 send_http_error(conn, 500,
"Cannot open directory",
3225 "Error: opendir(%s): %s", dir, strerror(ERRNO));
3229 gmt_time_string(date,
sizeof(date), &curtime);
3231 sort_direction = conn->request_info.query_string != NULL &&
3232 conn->request_info.query_string[1] ==
'd' ?
'a' :
'd';
3234 conn->must_close = 1;
3235 mg_printf(conn,
"HTTP/1.1 200 OK\r\n"
3237 "Connection: close\r\n"
3238 "Content-Type: text/html; charset=utf-8\r\n\r\n",
3241 conn->num_bytes_sent += mg_printf(conn,
3242 "<html><head><title>Index of %s</title>"
3243 "<style>th {text-align: left;}</style></head>"
3244 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
3245 "<tr><th><a href=\"?n%c\">Name</a></th>"
3246 "<th><a href=\"?d%c\">Modified</a></th>"
3247 "<th><a href=\"?s%c\">Size</a></th></tr>"
3248 "<tr><td colspan=\"3\"><hr></td></tr>",
3249 conn->request_info.uri, conn->request_info.uri,
3250 sort_direction, sort_direction, sort_direction);
3253 conn->num_bytes_sent += mg_printf(conn,
3254 "<tr><td><a href=\"%s%s\">%s</a></td>"
3255 "<td> %s</td><td> %s</td></tr>\n",
3256 conn->request_info.uri,
"..",
"Parent directory",
"-",
"-");
3259 if (data.entries != NULL) {
3260 qsort(data.entries, (
size_t) data.num_entries,
3261 sizeof(data.entries[0]), compare_dir_entries);
3262 for (i = 0; i < data.num_entries; i++) {
3263 print_dir_entry(&data.entries[i]);
3264 free(data.entries[i].file_name);
3269 conn->num_bytes_sent += mg_printf(conn,
"%s",
"</table></body></html>");
3270 conn->status_code = 200;
3274 static void send_file_data(
struct mg_connection *conn,
struct file *filep,
3275 int64_t offset, int64_t len)
3277 char buf[MG_BUF_LEN];
3278 int to_read, num_read, num_written;
3281 offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset;
3283 if (len > 0 && filep->membuf != NULL && filep->size > 0) {
3284 if (len > filep->size - offset) {
3285 len = filep->size - offset;
3287 mg_write(conn, filep->membuf + offset, (
size_t) len);
3288 }
else if (len > 0 && filep->fp != NULL) {
3289 if (offset > 0 && fseeko(filep->fp, offset, SEEK_SET) != 0) {
3290 mg_cry(conn,
"%s: fseeko() failed: %s",
3291 __func__, strerror(ERRNO));
3295 to_read =
sizeof(buf);
3296 if ((int64_t) to_read > len) {
3297 to_read = (int) len;
3301 if ((num_read = (
int) fread(buf, 1, (
size_t) to_read, filep->fp)) <= 0) {
3306 if ((num_written = mg_write(conn, buf, (
size_t) num_read)) != num_read) {
3311 conn->num_bytes_sent += num_written;
3317 static int parse_range_header(
const char *header, int64_t *a, int64_t *b)
3319 return sscanf(header,
"bytes=%" INT64_FMT
"-%" INT64_FMT, a, b);
3322 static void construct_etag(
char *buf,
size_t buf_len,
3323 const struct file *filep)
3325 snprintf(buf, buf_len,
"\"%lx.%" INT64_FMT
"\"",
3326 (
unsigned long) filep->modification_time, filep->size);
3329 static void fclose_on_exec(
struct file *filep,
struct mg_connection *conn)
3331 if (filep != NULL && filep->fp != NULL) {
3335 if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
3336 mg_cry(conn,
"%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
3337 __func__, strerror(ERRNO));
3343 static void handle_file_request(
struct mg_connection *conn,
const char *path,
3346 char date[64], lm[64], etag[64], range[64];
3347 const char *msg =
"OK", *hdr;
3348 time_t curtime = time(NULL);
3350 struct vec mime_vec;
3352 char gz_path[PATH_MAX];
3353 char const* encoding =
"";
3355 get_mime_type(conn->ctx, path, &mime_vec);
3357 conn->status_code = 200;
3363 if (filep->gzipped) {
3364 snprintf(gz_path,
sizeof(gz_path),
"%s.gz", path);
3366 encoding =
"Content-Encoding: gzip\r\n";
3369 if (!mg_fopen(conn, path,
"rb", filep)) {
3370 send_http_error(conn, 500, http_500_error,
3371 "fopen(%s): %s", path, strerror(ERRNO));
3375 fclose_on_exec(filep, conn);
3379 hdr = mg_get_header(conn,
"Range");
3380 if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
3381 r1 >= 0 && r2 >= 0) {
3384 if (filep->gzipped) {
3385 send_http_error(conn, 501,
"Not Implemented",
"range requests in gzipped files are not supported");
3389 conn->status_code = 206;
3390 cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;
3391 mg_snprintf(conn, range,
sizeof(range),
3392 "Content-Range: bytes "
3394 INT64_FMT
"/%" INT64_FMT
"\r\n",
3395 r1, r1 + cl - 1, filep->size);
3396 msg =
"Partial Content";
3401 gmt_time_string(date,
sizeof(date), &curtime);
3402 gmt_time_string(lm,
sizeof(lm), &filep->modification_time);
3403 construct_etag(etag,
sizeof(etag), filep);
3405 (void) mg_printf(conn,
3406 "HTTP/1.1 %d %s\r\n"
3408 "Last-Modified: %s\r\n"
3410 "Content-Type: %.*s\r\n"
3411 "Content-Length: %" INT64_FMT
"\r\n"
3412 "Connection: %s\r\n"
3413 "Accept-Ranges: bytes\r\n"
3415 conn->status_code, msg, date, lm, etag, (
int) mime_vec.len,
3416 mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding);
3418 if (strcmp(conn->request_info.request_method,
"HEAD") != 0) {
3419 send_file_data(conn, filep, r1, cl);
3424 void mg_send_file(
struct mg_connection *conn,
const char *path)
3426 struct file file = STRUCT_FILE_INITIALIZER;
3427 if (mg_stat(conn, path, &file)) {
3428 handle_file_request(conn, path, &file);
3430 send_http_error(conn, 404,
"Not Found",
"%s",
"File not found");
3437 static void parse_http_headers(
char **buf,
struct mg_request_info *ri)
3441 for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
3442 ri->http_headers[i].name = skip_quoted(buf,
":",
" ", 0);
3443 ri->http_headers[i].value = skip(buf,
"\r\n");
3444 if (ri->http_headers[i].name[0] ==
'\0')
3446 ri->num_headers = i + 1;
3450 static int is_valid_http_method(
const char *method)
3452 return !strcmp(method,
"GET") || !strcmp(method,
"POST") ||
3453 !strcmp(method,
"HEAD") || !strcmp(method,
"CONNECT") ||
3454 !strcmp(method,
"PUT") || !strcmp(method,
"DELETE") ||
3455 !strcmp(method,
"OPTIONS") || !strcmp(method,
"PROPFIND")
3456 || !strcmp(method,
"MKCOL")
3463 static int parse_http_message(
char *buf,
int len,
struct mg_request_info *ri)
3465 int is_request, request_length = get_request_len(buf, len);
3466 if (request_length > 0) {
3468 ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
3469 ri->num_headers = 0;
3471 buf[request_length - 1] =
'\0';
3474 while (*buf !=
'\0' && isspace(* (
unsigned char *) buf)) {
3477 ri->request_method = skip(&buf,
" ");
3478 ri->uri = skip(&buf,
" ");
3479 ri->http_version = skip(&buf,
"\r\n");
3483 is_request = is_valid_http_method(ri->request_method);
3484 if ((is_request && memcmp(ri->http_version,
"HTTP/", 5) != 0) ||
3485 (!is_request && memcmp(ri->request_method,
"HTTP/", 5) != 0)) {
3486 request_length = -1;
3489 ri->http_version += 5;
3491 parse_http_headers(&buf, ri);
3494 return request_length;
3502 static int read_request(FILE *fp,
struct mg_connection *conn,
3503 char *buf,
int bufsiz,
int *nread)
3505 int request_len, n = 0;
3507 request_len = get_request_len(buf, *nread);
3508 while (conn->ctx->stop_flag == 0 &&
3509 *nread < bufsiz && request_len == 0 &&
3510 (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {
3512 assert(*nread <= bufsiz);
3513 request_len = get_request_len(buf, *nread);
3516 return request_len <= 0 && n <= 0 ? -1 : request_len;
3522 static int substitute_index_file(
struct mg_connection *conn,
char *path,
3523 size_t path_len,
struct file *filep)
3525 const char *list = conn->ctx->config[INDEX_FILES];
3526 struct file file = STRUCT_FILE_INITIALIZER;
3527 struct vec filename_vec;
3528 size_t n = strlen(path);
3534 while (n > 0 && path[n - 1] ==
'/') {
3541 while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
3544 if (filename_vec.len > path_len - (n + 2))
3548 mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
3551 if (mg_stat(conn, path, &file)) {
3568 static int is_not_modified(
const struct mg_connection *conn,
3569 const struct file *filep)
3572 const char *ims = mg_get_header(conn,
"If-Modified-Since");
3573 const char *inm = mg_get_header(conn,
"If-None-Match");
3574 construct_etag(etag,
sizeof(etag), filep);
3575 return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
3576 (ims != NULL && filep->modification_time <= parse_date_string(ims));
3579 static int forward_body_data(
struct mg_connection *conn, FILE *fp,
3580 SOCKET sock, SSL *ssl)
3582 const char *expect, *body;
3583 char buf[MG_BUF_LEN];
3584 int to_read, nread, buffered_len, success = 0;
3586 expect = mg_get_header(conn,
"Expect");
3589 if (conn->content_len == -1) {
3590 send_http_error(conn, 411,
"Length Required",
"%s",
"");
3591 }
else if (expect != NULL && mg_strcasecmp(expect,
"100-continue")) {
3592 send_http_error(conn, 417,
"Expectation Failed",
"%s",
"");
3594 if (expect != NULL) {
3595 (void) mg_printf(conn,
"%s",
"HTTP/1.1 100 Continue\r\n\r\n");
3598 body = conn->buf + conn->request_len + conn->consumed_content;
3599 buffered_len = (int)(&conn->buf[conn->data_len] - body);
3600 assert(buffered_len >= 0);
3601 assert(conn->consumed_content == 0);
3603 if (buffered_len > 0) {
3604 if ((int64_t) buffered_len > conn->content_len) {
3605 buffered_len = (int) conn->content_len;
3607 push(fp, sock, ssl, body, (int64_t) buffered_len);
3608 conn->consumed_content += buffered_len;
3612 while (conn->consumed_content < conn->content_len) {
3613 to_read =
sizeof(buf);
3614 if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
3615 to_read = (int) (conn->content_len - conn->consumed_content);
3617 nread = pull(NULL, conn, buf, to_read);
3618 if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
3621 conn->consumed_content += nread;
3624 if (conn->consumed_content == conn->content_len) {
3625 success = nread >= 0;
3630 send_http_error(conn, 577, http_500_error,
"%s",
"");
3637 #if !defined(NO_CGI)
3646 struct cgi_env_block {
3647 struct mg_connection *conn;
3648 char buf[CGI_ENVIRONMENT_SIZE];
3650 char *vars[MAX_CGI_ENVIR_VARS];
3654 static char *addenv(
struct cgi_env_block *block,
3655 PRINTF_FORMAT_STRING(
const char *fmt), ...)
3660 static
char *addenv(struct cgi_env_block *block, const
char *fmt, ...)
3667 space =
sizeof(block->buf) - block->len - 2;
3671 added = block->buf + block->len;
3675 n = mg_vsnprintf(block->conn, added, (
size_t) space, fmt, ap);
3679 if (n > 0 && n + 1 < space &&
3680 block->nvars < (
int) ARRAY_SIZE(block->vars) - 2) {
3682 block->vars[block->nvars++] = added;
3684 block->len += n + 1;
3686 mg_cry(block->conn,
"%s: CGI env buffer truncated for [%s]", __func__, fmt);
3692 static void prepare_cgi_environment(
struct mg_connection *conn,
3694 struct cgi_env_block *blk)
3696 const char *s, *slash;
3698 char *p, src_addr[IP_ADDR_STR_LEN];
3701 blk->len = blk->nvars = 0;
3703 sockaddr_to_string(src_addr,
sizeof(src_addr), &conn->client.rsa);
3705 addenv(blk,
"SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
3706 addenv(blk,
"SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
3707 addenv(blk,
"DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
3708 addenv(blk,
"SERVER_SOFTWARE=%s/%s",
"Civetweb", mg_version());
3711 addenv(blk,
"%s",
"GATEWAY_INTERFACE=CGI/1.1");
3712 addenv(blk,
"%s",
"SERVER_PROTOCOL=HTTP/1.1");
3713 addenv(blk,
"%s",
"REDIRECT_STATUS=200");
3716 addenv(blk,
"SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
3718 addenv(blk,
"REQUEST_METHOD=%s", conn->request_info.request_method);
3719 addenv(blk,
"REMOTE_ADDR=%s", src_addr);
3720 addenv(blk,
"REMOTE_PORT=%d", conn->request_info.remote_port);
3721 addenv(blk,
"REQUEST_URI=%s", conn->request_info.uri);
3724 assert(conn->request_info.uri[0] ==
'/');
3725 slash = strrchr(conn->request_info.uri,
'/');
3726 if ((s = strrchr(prog,
'/')) == NULL)
3728 addenv(blk,
"SCRIPT_NAME=%.*s%s", (
int) (slash - conn->request_info.uri),
3729 conn->request_info.uri, s);
3731 addenv(blk,
"SCRIPT_FILENAME=%s", prog);
3732 addenv(blk,
"PATH_TRANSLATED=%s", prog);
3733 addenv(blk,
"HTTPS=%s", conn->ssl == NULL ?
"off" :
"on");
3735 if ((s = mg_get_header(conn,
"Content-Type")) != NULL)
3736 addenv(blk,
"CONTENT_TYPE=%s", s);
3738 if (conn->request_info.query_string != NULL)
3739 addenv(blk,
"QUERY_STRING=%s", conn->request_info.query_string);
3741 if ((s = mg_get_header(conn,
"Content-Length")) != NULL)
3742 addenv(blk,
"CONTENT_LENGTH=%s", s);
3744 if ((s = getenv(
"PATH")) != NULL)
3745 addenv(blk,
"PATH=%s", s);
3747 if (conn->path_info != NULL) {
3748 addenv(blk,
"PATH_INFO=%s", conn->path_info);
3752 if ((s = getenv(
"COMSPEC")) != NULL) {
3753 addenv(blk,
"COMSPEC=%s", s);
3755 if ((s = getenv(
"SYSTEMROOT")) != NULL) {
3756 addenv(blk,
"SYSTEMROOT=%s", s);
3758 if ((s = getenv(
"SystemDrive")) != NULL) {
3759 addenv(blk,
"SystemDrive=%s", s);
3761 if ((s = getenv(
"ProgramFiles")) != NULL) {
3762 addenv(blk,
"ProgramFiles=%s", s);
3764 if ((s = getenv(
"ProgramFiles(x86)")) != NULL) {
3765 addenv(blk,
"ProgramFiles(x86)=%s", s);
3768 if ((s = getenv(
"LD_LIBRARY_PATH")) != NULL)
3769 addenv(blk,
"LD_LIBRARY_PATH=%s", s);
3772 if ((s = getenv(
"PERLLIB")) != NULL)
3773 addenv(blk,
"PERLLIB=%s", s);
3775 if (conn->request_info.remote_user != NULL) {
3776 addenv(blk,
"REMOTE_USER=%s", conn->request_info.remote_user);
3777 addenv(blk,
"%s",
"AUTH_TYPE=Digest");
3781 for (i = 0; i < conn->request_info.num_headers; i++) {
3782 p = addenv(blk,
"HTTP_%s=%s",
3783 conn->request_info.http_headers[i].name,
3784 conn->request_info.http_headers[i].value);
3787 for (; *p !=
'=' && *p !=
'\0'; p++) {
3790 *p = (char) toupper(* (
unsigned char *) p);
3795 s = conn->ctx->config[CGI_ENVIRONMENT];
3796 while ((s = next_option(s, &var_vec, NULL)) != NULL) {
3797 addenv(blk,
"%.*s", (
int) var_vec.len, var_vec.ptr);
3800 blk->vars[blk->nvars++] = NULL;
3801 blk->buf[blk->len++] =
'\0';
3803 assert(blk->nvars < (
int) ARRAY_SIZE(blk->vars));
3804 assert(blk->len > 0);
3805 assert(blk->len < (
int)
sizeof(blk->buf));
3808 static void handle_cgi_request(
struct mg_connection *conn,
const char *prog)
3812 int headers_len, data_len, i, fdin[2] = { 0, 0 }, fdout[2] = { 0, 0 };
3813 const char *status, *status_text, *connection_state;
3814 char *pbuf, dir[PATH_MAX], *p;
3815 struct mg_request_info ri;
3816 struct cgi_env_block blk;
3817 FILE *in = NULL, *out = NULL;
3818 struct file fout = STRUCT_FILE_INITIALIZER;
3819 pid_t pid = (pid_t) -1;
3823 prepare_cgi_environment(conn, prog, &blk);
3828 (void) mg_snprintf(conn, dir,
sizeof(dir),
"%s", prog);
3829 if ((p = strrchr(dir,
'/')) != NULL) {
3832 dir[0] =
'.', dir[1] =
'\0';
3836 if (pipe(fdin) != 0 || pipe(fdout) != 0) {
3837 send_http_error(conn, 500, http_500_error,
3838 "Cannot create CGI pipe: %s", strerror(ERRNO));
3842 pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
3843 if (pid == (pid_t) -1) {
3844 send_http_error(conn, 500, http_500_error,
3845 "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
3850 set_close_on_exec(fdin[0], conn);
3851 set_close_on_exec(fdin[1], conn);
3852 set_close_on_exec(fdout[0], conn);
3853 set_close_on_exec(fdout[1], conn);
3859 (void) close(fdin[0]);
3860 (void) close(fdout[1]);
3861 fdin[0] = fdout[1] = -1;
3864 if ((in = fdopen(fdin[1],
"wb")) == NULL ||
3865 (out = fdopen(fdout[0],
"rb")) == NULL) {
3866 send_http_error(conn, 500, http_500_error,
3867 "fopen: %s", strerror(ERRNO));
3876 if (!strcmp(conn->request_info.request_method,
"POST") &&
3877 !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
3891 buf = (
char*)malloc(buflen);
3893 send_http_error(conn, 500, http_500_error,
3894 "Not enough memory for buffer (%u bytes)",
3895 (
unsigned int) buflen);
3898 headers_len = read_request(out, conn, buf, (
int) buflen, &data_len);
3899 if (headers_len <= 0) {
3900 send_http_error(conn, 500, http_500_error,
3901 "CGI program sent malformed or too big (>%u bytes) "
3902 "HTTP headers: [%.*s]",
3903 (
unsigned) buflen, data_len, buf);
3907 buf[headers_len - 1] =
'\0';
3908 parse_http_headers(&pbuf, &ri);
3912 if ((status = get_header(&ri,
"Status")) != NULL) {
3913 conn->status_code = atoi(status);
3914 status_text = status;
3915 while (isdigit(* (
unsigned char *) status_text) || *status_text ==
' ') {
3918 }
else if (get_header(&ri,
"Location") != NULL) {
3919 conn->status_code = 302;
3921 conn->status_code = 200;
3923 connection_state = get_header(&ri,
"Connection");
3924 if (connection_state == NULL ||
3925 mg_strcasecmp(connection_state,
"keep-alive")) {
3926 conn->must_close = 1;
3928 (void) mg_printf(conn,
"HTTP/1.1 %d %s\r\n", conn->status_code,
3932 for (i = 0; i < ri.num_headers; i++) {
3933 mg_printf(conn,
"%s: %s\r\n",
3934 ri.http_headers[i].name, ri.http_headers[i].value);
3936 mg_write(conn,
"\r\n", 2);
3939 conn->num_bytes_sent += mg_write(conn, buf + headers_len,
3940 (
size_t)(data_len - headers_len));
3943 send_file_data(conn, &fout, 0, INT64_MAX);
3946 if (pid != (pid_t) -1) {
3948 #if !defined(_WIN32)
3951 while (waitpid(pid, &st, 0) != -1);
3955 if (fdin[0] != -1) {
3958 if (fdout[1] != -1) {
3964 }
else if (fdin[1] != -1) {
3970 }
else if (fdout[0] != -1) {
3982 static int put_dir(
struct mg_connection *conn,
const char *path)
3986 struct file file = STRUCT_FILE_INITIALIZER;
3989 for (s = p = path + 2; (p = strchr(s,
'/')) != NULL; s = ++p) {
3990 len = (int)(p - path);
3991 if (len >= (
int)
sizeof(buf)) {
3995 memcpy(buf, path, len);
3999 DEBUG_TRACE((
"mkdir(%s)", buf));
4000 if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
4014 static void mkcol(
struct mg_connection *conn,
const char *path)
4019 time_t curtime = time(NULL);
4021 memset(&de.file, 0,
sizeof(de.file));
4022 if (!mg_stat(conn, path, &de.file)) {
4023 mg_cry(conn,
"%s: mg_stat(%s) failed: %s",
4024 __func__, path, strerror(ERRNO));
4027 if(de.file.modification_time) {
4028 send_http_error(conn, 405,
"Method Not Allowed",
4029 "mkcol(%s): %s", path, strerror(ERRNO));
4033 body_len = conn->data_len - conn->request_len;
4035 send_http_error(conn, 415,
"Unsupported media type",
4036 "mkcol(%s): %s", path, strerror(ERRNO));
4040 rc = mg_mkdir(path, 0755);
4043 conn->status_code = 201;
4044 gmt_time_string(date,
sizeof(date), &curtime);
4045 mg_printf(conn,
"HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: 0\r\nConnection: %s\r\n\r\n",
4046 conn->status_code, date, suggest_connection_header(conn));
4047 }
else if (rc == -1) {
4049 send_http_error(conn, 405,
"Method Not Allowed",
4050 "mkcol(%s): %s", path, strerror(ERRNO));
4051 else if(errno == EACCES)
4052 send_http_error(conn, 403,
"Forbidden",
4053 "mkcol(%s): %s", path, strerror(ERRNO));
4054 else if(errno == ENOENT)
4055 send_http_error(conn, 409,
"Conflict",
4056 "mkcol(%s): %s", path, strerror(ERRNO));
4058 send_http_error(conn, 500, http_500_error,
4059 "fopen(%s): %s", path, strerror(ERRNO));
4063 static void put_file(
struct mg_connection *conn,
const char *path)
4065 struct file file = STRUCT_FILE_INITIALIZER;
4070 time_t curtime = time(NULL);
4072 conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;
4074 if ((rc = put_dir(conn, path)) == 0) {
4075 gmt_time_string(date,
sizeof(date), &curtime);
4076 mg_printf(conn,
"HTTP/1.1 %d OK\r\nDate: %s\r\nContent-Length: 0\r\nConnection: %s\r\n\r\n",
4077 conn->status_code, date, suggest_connection_header(conn));
4078 }
else if (rc == -1) {
4079 send_http_error(conn, 500, http_500_error,
4080 "put_dir(%s): %s", path, strerror(ERRNO));
4081 }
else if (!mg_fopen(conn, path,
"wb+", &file) || file.fp == NULL) {
4083 send_http_error(conn, 500, http_500_error,
4084 "fopen(%s): %s", path, strerror(ERRNO));
4086 fclose_on_exec(&file, conn);
4087 range = mg_get_header(conn,
"Content-Range");
4089 if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
4090 conn->status_code = 206;
4091 fseeko(file.fp, r1, SEEK_SET);
4093 if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
4094 conn->status_code = 500;
4096 gmt_time_string(date,
sizeof(date), &curtime);
4097 mg_printf(conn,
"HTTP/1.1 %d OK\r\nDate: %s\r\nContent-Length: 0\r\nConnection: %s\r\n\r\n",
4098 conn->status_code, date, suggest_connection_header(conn));
4103 static void send_ssi_file(
struct mg_connection *,
const char *,
4104 struct file *,
int);
4106 static void do_ssi_include(
struct mg_connection *conn,
const char *ssi,
4107 char *tag,
int include_level)
4109 char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
4110 struct file file = STRUCT_FILE_INITIALIZER;
4115 if (sscanf(tag,
" virtual=\"%[^\"]\"", file_name) == 1) {
4117 (void) mg_snprintf(conn, path,
sizeof(path),
"%s%c%s",
4118 conn->ctx->config[DOCUMENT_ROOT],
'/', file_name);
4119 }
else if (sscanf(tag,
" abspath=\"%[^\"]\"", file_name) == 1) {
4122 (void) mg_snprintf(conn, path,
sizeof(path),
"%s", file_name);
4123 }
else if (sscanf(tag,
" file=\"%[^\"]\"", file_name) == 1 ||
4124 sscanf(tag,
" \"%[^\"]\"", file_name) == 1) {
4126 (void) mg_snprintf(conn, path,
sizeof(path),
"%s", ssi);
4127 if ((p = strrchr(path,
'/')) != NULL) {
4130 (void) mg_snprintf(conn, path + strlen(path),
4131 sizeof(path) - strlen(path),
"%s", file_name);
4133 mg_cry(conn,
"Bad SSI #include: [%s]", tag);
4137 if (!mg_fopen(conn, path,
"rb", &file)) {
4138 mg_cry(conn,
"Cannot open SSI #include: [%s]: fopen(%s): %s",
4139 tag, path, strerror(ERRNO));
4141 fclose_on_exec(&file, conn);
4142 if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
4143 (
int)strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
4144 send_ssi_file(conn, path, &file, include_level + 1);
4146 send_file_data(conn, &file, 0, INT64_MAX);
4152 #if !defined(NO_POPEN)
4153 static void do_ssi_exec(
struct mg_connection *conn,
char *tag)
4155 char cmd[MG_BUF_LEN] =
"";
4156 struct file file = STRUCT_FILE_INITIALIZER;
4158 if (sscanf(tag,
" \"%[^\"]\"", cmd) != 1) {
4159 mg_cry(conn,
"Bad SSI #exec: [%s]", tag);
4160 }
else if ((file.fp = popen(cmd,
"r")) == NULL) {
4161 mg_cry(conn,
"Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
4163 send_file_data(conn, &file, 0, INT64_MAX);
4169 static int mg_fgetc(
struct file *filep,
int offset)
4171 if (filep->membuf != NULL && offset >=0 && offset < filep->size) {
4172 return ((
unsigned char *) filep->membuf)[offset];
4173 }
else if (filep->fp != NULL) {
4174 return fgetc(filep->fp);
4180 static void send_ssi_file(
struct mg_connection *conn,
const char *path,
4181 struct file *filep,
int include_level)
4183 char buf[MG_BUF_LEN];
4184 int ch, offset, len, in_ssi_tag;
4186 if (include_level > 10) {
4187 mg_cry(conn,
"SSI #include level is too deep (%s)", path);
4191 in_ssi_tag = len = offset = 0;
4192 while ((ch = mg_fgetc(filep, offset)) != EOF) {
4193 if (in_ssi_tag && ch ==
'>') {
4195 buf[len++] = (char) ch;
4197 assert(len <= (
int)
sizeof(buf));
4198 if (len < 6 || memcmp(buf,
"<!--#", 5) != 0) {
4200 (void) mg_write(conn, buf, (
size_t) len);
4202 if (!memcmp(buf + 5,
"include", 7)) {
4203 do_ssi_include(conn, path, buf + 12, include_level);
4204 #if !defined(NO_POPEN)
4205 }
else if (!memcmp(buf + 5,
"exec", 4)) {
4206 do_ssi_exec(conn, buf + 9);
4209 mg_cry(conn,
"%s: unknown SSI " "command: \"%s\"", path, buf);
4213 }
else if (in_ssi_tag) {
4214 if (len == 5 && memcmp(buf,
"<!--#", 5) != 0) {
4217 }
else if (len == (
int)
sizeof(buf) - 2) {
4218 mg_cry(conn,
"%s: SSI tag is too large", path);
4221 buf[len++] = ch & 0xff;
4222 }
else if (ch ==
'<') {
4225 mg_write(conn, buf, (
size_t) len);
4228 buf[len++] = ch & 0xff;
4230 buf[len++] = ch & 0xff;
4231 if (len == (
int)
sizeof(buf)) {
4232 mg_write(conn, buf, (
size_t) len);
4240 mg_write(conn, buf, (
size_t) len);
4244 static void handle_ssi_file_request(
struct mg_connection *conn,
4247 struct file file = STRUCT_FILE_INITIALIZER;
4249 time_t curtime = time(NULL);
4251 if (!mg_fopen(conn, path,
"rb", &file)) {
4252 send_http_error(conn, 500, http_500_error,
"fopen(%s): %s", path,
4255 conn->must_close = 1;
4256 gmt_time_string(date,
sizeof(date), &curtime);
4257 fclose_on_exec(&file, conn);
4258 mg_printf(conn,
"HTTP/1.1 200 OK\r\n"
4260 "Content-Type: text/html\r\n"
4261 "Connection: %s\r\n\r\n",
4262 date, suggest_connection_header(conn));
4263 send_ssi_file(conn, path, &file, 0);
4268 static void send_options(
struct mg_connection *conn)
4271 time_t curtime = time(NULL);
4273 conn->status_code = 200;
4274 conn->must_close = 1;
4275 gmt_time_string(date,
sizeof(date), &curtime);
4277 mg_printf(conn,
"HTTP/1.1 200 OK\r\n"
4279 "Connection: %s\r\n"
4280 "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\n"
4282 date, suggest_connection_header(conn));
4286 static void print_props(
struct mg_connection *conn,
const char* uri,
4290 gmt_time_string(mtime,
sizeof(mtime), &filep->modification_time);
4291 conn->num_bytes_sent += mg_printf(conn,
4293 "<d:href>%s</d:href>"
4296 "<d:resourcetype>%s</d:resourcetype>"
4297 "<d:getcontentlength>%" INT64_FMT
"</d:getcontentlength>"
4298 "<d:getlastmodified>%s</d:getlastmodified>"
4300 "<d:status>HTTP/1.1 200 OK</d:status>"
4304 filep->is_directory ?
"<d:collection/>" :
"",
4309 static void print_dav_dir_entry(
struct de *de,
void *data)
4311 char href[PATH_MAX];
4312 char href_encoded[PATH_MAX];
4313 struct mg_connection *conn = (
struct mg_connection *) data;
4314 mg_snprintf(conn, href,
sizeof(href),
"%s%s",
4315 conn->request_info.uri, de->file_name);
4316 mg_url_encode(href, href_encoded, PATH_MAX-1);
4317 print_props(conn, href_encoded, &de->file);
4320 static void handle_propfind(
struct mg_connection *conn,
const char *path,
4323 const char *depth = mg_get_header(conn,
"Depth");
4325 time_t curtime = time(NULL);
4327 gmt_time_string(date,
sizeof(date), &curtime);
4329 conn->must_close = 1;
4330 conn->status_code = 207;
4331 mg_printf(conn,
"HTTP/1.1 207 Multi-Status\r\n"
4333 "Connection: %s\r\n"
4334 "Content-Type: text/xml; charset=utf-8\r\n\r\n",
4335 date, suggest_connection_header(conn));
4337 conn->num_bytes_sent += mg_printf(conn,
4338 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
4339 "<d:multistatus xmlns:d='DAV:'>\n");
4342 print_props(conn, conn->request_info.uri, filep);
4345 if (filep->is_directory &&
4346 !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
"yes") &&
4347 (depth == NULL || strcmp(depth,
"0") != 0)) {
4348 scan_directory(conn, path, conn, &print_dav_dir_entry);
4351 conn->num_bytes_sent += mg_printf(conn,
"%s\n",
"</d:multistatus>");
4354 void mg_lock(
struct mg_connection* conn)
4356 (void) pthread_mutex_lock(&conn->mutex);
4359 void mg_unlock(
struct mg_connection* conn)
4361 (void) pthread_mutex_unlock(&conn->mutex);
4365 #include "mod_lua.inl"
4368 #if defined(USE_WEBSOCKET)
4372 #define SHA1HANDSOFF
4374 #include "solarisfixes.h"
4377 static int is_big_endian(
void)
4379 static const int n = 1;
4380 return ((
char *) &n)[0] == 0;
4383 union char64long16 {
4384 unsigned char c[64];
4388 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
4390 static uint32_t blk0(
union char64long16 *block,
int i)
4393 if (!is_big_endian()) {
4394 block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
4395 (rol(block->l[i], 8) & 0x00FF00FF);
4400 #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
4401 ^block->l[(i+2)&15]^block->l[i&15],1))
4402 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
4403 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
4404 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
4405 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
4406 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
4411 unsigned char buffer[64];
4414 static void SHA1Transform(uint32_t state[5],
const unsigned char buffer[64])
4416 uint32_t a, b, c, d, e;
4417 union char64long16 block[1];
4419 memcpy(block, buffer, 64);
4510 a = b = c = d = e = 0;
4511 memset(block,
'\0',
sizeof(block));
4514 static void SHA1Init(SHA1_CTX* context)
4516 context->state[0] = 0x67452301;
4517 context->state[1] = 0xEFCDAB89;
4518 context->state[2] = 0x98BADCFE;
4519 context->state[3] = 0x10325476;
4520 context->state[4] = 0xC3D2E1F0;
4521 context->count[0] = context->count[1] = 0;
4524 static void SHA1Update(SHA1_CTX* context,
const unsigned char* data,
4529 j = context->count[0];
4530 if ((context->count[0] += len << 3) < j)
4531 context->count[1]++;
4532 context->count[1] += (len>>29);
4534 if ((j + len) > 63) {
4535 memcpy(&context->buffer[j], data, (i = 64-j));
4536 SHA1Transform(context->state, context->buffer);
4537 for ( ; i + 63 < len; i += 64) {
4538 SHA1Transform(context->state, &data[i]);
4542 memcpy(&context->buffer[j], &data[i], len - i);
4545 static void SHA1Final(
unsigned char digest[20], SHA1_CTX* context)
4548 unsigned char finalcount[8], c;
4550 for (i = 0; i < 8; i++) {
4551 finalcount[i] = (
unsigned char)((context->count[(i >= 4 ? 0 : 1)]
4552 >> ((3-(i & 3)) * 8) ) & 255);
4555 SHA1Update(context, &c, 1);
4556 while ((context->count[0] & 504) != 448) {
4558 SHA1Update(context, &c, 1);
4560 SHA1Update(context, finalcount, 8);
4561 for (i = 0; i < 20; i++) {
4562 digest[i] = (
unsigned char)
4563 ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
4565 memset(context,
'\0',
sizeof(*context));
4566 memset(&finalcount,
'\0',
sizeof(finalcount));
4570 static void base64_encode(
const unsigned char *src,
int src_len,
char *dst)
4572 static const char *b64 =
4573 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4576 for (i = j = 0; i < src_len; i += 3) {
4578 b = i + 1 >= src_len ? 0 : src[i + 1];
4579 c = i + 2 >= src_len ? 0 : src[i + 2];
4581 dst[j++] = b64[a >> 2];
4582 dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
4583 if (i + 1 < src_len) {
4584 dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
4586 if (i + 2 < src_len) {
4587 dst[j++] = b64[c & 63];
4590 while (j % 4 != 0) {
4596 static void send_websocket_handshake(
struct mg_connection *conn)
4598 static const char *magic =
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
4599 char buf[100], sha[20], b64_sha[
sizeof(sha) * 2];
4602 mg_snprintf(conn, buf,
sizeof(buf),
"%s%s",
4603 mg_get_header(conn,
"Sec-WebSocket-Key"), magic);
4605 SHA1Update(&sha_ctx, (
unsigned char *) buf, (uint32_t)strlen(buf));
4606 SHA1Final((
unsigned char *) sha, &sha_ctx);
4607 base64_encode((
unsigned char *) sha,
sizeof(sha), b64_sha);
4608 mg_printf(conn,
"%s%s%s",
4609 "HTTP/1.1 101 Switching Protocols\r\n"
4610 "Upgrade: websocket\r\n"
4611 "Connection: Upgrade\r\n"
4612 "Sec-WebSocket-Accept: ", b64_sha,
"\r\n\r\n");
4615 static void read_websocket(
struct mg_connection *conn)
4621 unsigned char *buf = (
unsigned char *) conn->buf + conn->request_len;
4628 size_t i, len, mask_len, data_len, header_len, body_len;
4632 unsigned char mask[4];
4643 assert(conn->content_len == 0);
4646 assert(conn->data_len >= conn->request_len);
4647 if ((body_len = conn->data_len - conn->request_len) >= 2) {
4649 mask_len = buf[1] & 128 ? 4 : 0;
4650 if (len < 126 && body_len >= mask_len) {
4652 header_len = 2 + mask_len;
4653 }
else if (len == 126 && body_len >= 4 + mask_len) {
4654 header_len = 4 + mask_len;
4655 data_len = ((((int) buf[2]) << 8) + buf[3]);
4656 }
else if (body_len >= 10 + mask_len) {
4657 header_len = 10 + mask_len;
4658 data_len = (((uint64_t) ntohl(* (uint32_t *) &buf[2])) << 32) +
4659 ntohl(* (uint32_t *) &buf[6]);
4663 if (header_len > 0) {
4666 if (data_len >
sizeof(mem)) {
4667 data = (
char *)malloc(data_len);
4671 mg_cry(conn,
"websocket malloc() failed; closing connection");
4678 *(uint32_t*)mask = *(uint32_t*)(buf + header_len - mask_len);
4680 *(uint32_t*)mask = 0;
4685 assert(body_len >= header_len);
4686 if (data_len + header_len > body_len) {
4689 len = body_len - header_len;
4690 memcpy(data, buf + header_len, len);
4692 while (len < data_len) {
4693 int n = pull(NULL, conn, data + len, (
int)(data_len - len));
4701 mg_cry(conn,
"Websocket pull failed; closing connection");
4704 conn->data_len = conn->request_len;
4709 len = data_len + header_len;
4713 memcpy(data, buf + header_len, data_len);
4716 memmove(buf, buf + len, body_len - len);
4719 conn->data_len -= (int)len;
4724 for (i = 0; i < data_len; ++i) {
4725 data[i] ^= mask[i & 3];
4731 if ((conn->ctx->callbacks.websocket_data != NULL &&
4733 (conn->lua_websocket_state == NULL) &&
4735 !conn->ctx->callbacks.websocket_data(conn, mop, data, data_len)) ||
4737 (conn->lua_websocket_state &&
4738 !lua_websocket_data(conn, mop, data, data_len)) ||
4740 (buf[0] & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
4751 if ((n = pull(NULL, conn, conn->buf + conn->data_len,
4752 conn->buf_size - conn->data_len)) <= 0) {
4756 conn->data_len += n;
4761 int mg_websocket_write(
struct mg_connection* conn,
int opcode,
const char* data,
size_t dataLen)
4763 unsigned char header[10];
4764 size_t headerLen = 1;
4768 header[0] = 0x80 + (opcode & 0xF);
4771 if (dataLen < 126) {
4773 header[1] = (
unsigned char)dataLen;
4775 }
else if (dataLen <= 0xFFFF) {
4778 *(uint16_t*)(header + 2) = htons((uint16_t)dataLen);
4783 *(uint32_t*)(header + 2) = htonl((uint64_t)dataLen >> 32);
4784 *(uint32_t*)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
4793 (void) mg_lock(conn);
4794 retval = mg_write(conn, header, headerLen);
4795 retval = mg_write(conn, data, dataLen);
4801 static void handle_websocket_request(
struct mg_connection *conn,
const char *path,
int is_script_resource)
4803 const char *version = mg_get_header(conn,
"Sec-WebSocket-Version");
4805 int lua_websock, shared_lua_websock = 0;
4810 if (version == NULL || strcmp(version,
"13") != 0) {
4811 send_http_error(conn, 426,
"Upgrade Required",
"%s",
"Upgrade Required");
4812 }
else if (conn->ctx->callbacks.websocket_connect != NULL &&
4813 conn->ctx->callbacks.websocket_connect(conn) != 0) {
4818 lua_websock = conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS] ?
4819 match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
4820 (
int)strlen(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
4823 if (lua_websock || shared_lua_websock) {
4824 conn->lua_websocket_state = lua_websocket_new(path, conn, !!shared_lua_websock);
4825 if (conn->lua_websocket_state) {
4826 send_websocket_handshake(conn);
4827 if (lua_websocket_ready(conn)) {
4828 read_websocket(conn);
4835 send_websocket_handshake(conn);
4836 if (conn->ctx->callbacks.websocket_ready != NULL) {
4837 conn->ctx->callbacks.websocket_ready(conn);
4839 read_websocket(conn);
4844 static int is_websocket_request(
const struct mg_connection *conn)
4846 const char *host, *upgrade, *connection, *version, *key;
4848 host = mg_get_header(conn,
"Host");
4849 upgrade = mg_get_header(conn,
"Upgrade");
4850 connection = mg_get_header(conn,
"Connection");
4851 key = mg_get_header(conn,
"Sec-WebSocket-Key");
4852 version = mg_get_header(conn,
"Sec-WebSocket-Version");
4854 return host != NULL && upgrade != NULL && connection != NULL &&
4855 key != NULL && version != NULL &&
4856 mg_strcasestr(upgrade,
"websocket") != NULL &&
4857 mg_strcasestr(connection,
"Upgrade") != NULL;
4861 static int isbyte(
int n)
4863 return n >= 0 && n <= 255;
4866 static int parse_net(
const char *spec, uint32_t *net, uint32_t *mask)
4868 int n, a, b, c, d, slash = 32, len = 0;
4870 if ((sscanf(spec,
"%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
4871 sscanf(spec,
"%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
4872 isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
4873 slash >= 0 && slash < 33) {
4875 *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
4876 *mask = slash ? 0xffffffffU << (32 - slash) : 0;
4882 static int set_throttle(
const char *spec, uint32_t remote_ip,
const char *uri)
4885 struct vec vec, val;
4890 while ((spec = next_option(spec, &vec, &val)) != NULL) {
4892 if (sscanf(val.ptr,
"%lf%c", &v, &mult) < 1 || v < 0 ||
4893 (lowercase(&mult) !=
'k' && lowercase(&mult) !=
'm' && mult !=
',')) {
4896 v *= lowercase(&mult) ==
'k' ? 1024 : lowercase(&mult) ==
'm' ? 1048576 : 1;
4897 if (vec.len == 1 && vec.ptr[0] ==
'*') {
4899 }
else if (parse_net(vec.ptr, &net, &mask) > 0) {
4900 if ((remote_ip & mask) == net) {
4903 }
else if (match_prefix(vec.ptr, (
int)vec.len, uri) > 0) {
4911 static uint32_t get_remote_ip(
const struct mg_connection *conn)
4913 return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
4916 int mg_upload(
struct mg_connection *conn,
const char *destination_dir)
4918 const char *content_type_header, *boundary_start;
4919 char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s;
4921 int bl, n, i, j, headers_len, boundary_len, eof,
4922 len = 0, num_uploaded_files = 0;
4940 if ((content_type_header = mg_get_header(conn,
"Content-Type")) == NULL ||
4941 (boundary_start = mg_strcasestr(content_type_header,
4942 "boundary=")) == NULL ||
4943 (sscanf(boundary_start,
"boundary=\"%99[^\"]\"", boundary) == 0 &&
4944 sscanf(boundary_start,
"boundary=%99s", boundary) == 0) ||
4945 boundary[0] ==
'\0') {
4946 return num_uploaded_files;
4949 boundary_len = (int)strlen(boundary);
4950 bl = boundary_len + 4;
4953 assert(len >= 0 && len <= (
int)
sizeof(buf));
4954 while ((n = mg_read(conn, buf + len,
sizeof(buf) - len)) > 0) {
4957 if ((headers_len = get_request_len(buf, len)) <= 0) {
4963 for (i = j = 0; i < headers_len; i++) {
4964 if (buf[i] ==
'\r' && buf[i + 1] ==
'\n') {
4965 buf[i] = buf[i + 1] =
'\0';
4968 IGNORE_UNUSED_RESULT(sscanf(&buf[j],
"Content-Disposition: %*s %*s filename=\"%1023[^\"]",
4975 if (fname[0] ==
'\0') {
4980 assert(len >= headers_len);
4981 memmove(buf, &buf[headers_len], len - headers_len);
4990 if ((s = strrchr(fname,
'/')) == NULL &&
4991 (s = strrchr(fname,
'\\')) == NULL) {
4996 snprintf(path,
sizeof(path),
"%s/%s", destination_dir, s);
4997 if ((fp = fopen(path,
"wb")) == NULL) {
5005 for (i = 0; i < len - bl; i++) {
5006 if (!memcmp(&buf[i],
"\r\n--", 4) &&
5007 !memcmp(&buf[i + 4], boundary, boundary_len)) {
5009 fwrite(buf, 1, i, fp);
5011 memmove(buf, &buf[i + bl], len - (i + bl));
5016 if (!eof && len > bl) {
5017 fwrite(buf, 1, len - bl, fp);
5018 memmove(buf, &buf[len - bl], bl);
5021 }
while (!eof && (n = mg_read(conn, buf + len,
sizeof(buf) - len)) > 0);
5024 num_uploaded_files++;
5025 if (conn->ctx->callbacks.upload != NULL) {
5026 conn->ctx->callbacks.upload(conn, path);
5031 return num_uploaded_files;
5034 static int is_put_or_delete_request(
const struct mg_connection *conn)
5036 const char *s = conn->request_info.request_method;
5037 return s != NULL && (!strcmp(s,
"PUT") ||
5038 !strcmp(s,
"DELETE") ||
5039 !strcmp(s,
"MKCOL"));
5042 static int get_first_ssl_listener_index(
const struct mg_context *ctx)
5045 for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
5046 idx = ctx->listening_sockets[i].is_ssl ? i : -1;
5051 static void redirect_to_https_port(
struct mg_connection *conn,
int ssl_index)
5054 const char *host_header;
5057 host_header = mg_get_header(conn,
"Host");
5058 hostlen =
sizeof(host);
5059 if (host_header != NULL) {
5062 strncpy(host, host_header, hostlen);
5063 host[hostlen - 1] =
'\0';
5064 pos = strchr(host,
':');
5071 sockaddr_to_string(host, hostlen, &conn->client.lsa);
5074 mg_printf(conn,
"HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",
5075 host, (
int) ntohs(conn->ctx->listening_sockets[ssl_index].
5076 lsa.sin.sin_port), conn->request_info.uri);
5080 void mg_set_request_handler(
struct mg_context *ctx,
const char *uri, mg_request_handler handler,
void *cbdata)
5082 struct mg_request_handler_info *tmp_rh, *lastref = 0;
5083 size_t urilen = strlen(uri);
5086 for (tmp_rh = ctx->request_handlers;
5087 tmp_rh != NULL && strcmp(uri, tmp_rh->uri);
5088 lastref = tmp_rh, tmp_rh = tmp_rh->next) {
5090 if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
5093 if (handler != NULL) {
5095 tmp_rh->handler = handler;
5096 tmp_rh->cbdata = cbdata;
5099 if (lastref != NULL)
5100 lastref->next = tmp_rh->next;
5102 ctx->request_handlers = tmp_rh->next;
5110 if (tmp_rh->uri_len < urilen
5111 && uri[tmp_rh->uri_len] ==
'/'
5112 && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
5120 if (handler == NULL) {
5125 tmp_rh = (
struct mg_request_handler_info *)malloc(
sizeof(
struct mg_request_handler_info));
5126 if (tmp_rh == NULL) {
5127 mg_cry(fc(ctx),
"%s",
"Cannot create new request handler struct, OOM");
5130 tmp_rh->uri = mg_strdup(uri);
5131 tmp_rh->uri_len = strlen(uri);
5132 tmp_rh->handler = handler;
5133 tmp_rh->cbdata = cbdata;
5135 if (lastref == NULL) {
5136 tmp_rh->next = ctx->request_handlers;
5137 ctx->request_handlers = tmp_rh;
5139 tmp_rh->next = lastref->next;
5140 lastref->next = tmp_rh;
5145 static int use_request_handler(
struct mg_connection *conn)
5147 struct mg_request_info *request_info = mg_get_request_info(conn);
5148 const char *uri = request_info->uri;
5149 size_t urilen = strlen(uri);
5150 struct mg_request_handler_info *tmp_rh = conn->ctx->request_handlers;
5152 for (; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
5155 if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
5156 return tmp_rh->handler(conn, tmp_rh->cbdata);
5161 if (tmp_rh->uri_len < urilen
5162 && uri[tmp_rh->uri_len] ==
'/'
5163 && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
5165 return tmp_rh->handler(conn, tmp_rh->cbdata);
5169 if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
5170 return tmp_rh->handler(conn, tmp_rh->cbdata);
5182 static void handle_request(
struct mg_connection *conn)
5184 struct mg_request_info *ri = &conn->request_info;
5185 char path[PATH_MAX];
5186 int uri_len, ssl_index, is_script_resource;
5187 struct file file = STRUCT_FILE_INITIALIZER;
5189 time_t curtime = time(NULL);
5191 if ((conn->request_info.query_string = strchr(ri->uri,
'?')) != NULL) {
5192 * ((
char *) conn->request_info.query_string++) =
'\0';
5194 uri_len = (int) strlen(ri->uri);
5195 mg_url_decode(ri->uri, uri_len, (
char *) ri->uri, uri_len + 1, 0);
5196 remove_double_dots_and_double_slashes((
char *) ri->uri);
5198 convert_uri_to_file_name(conn, path,
sizeof(path), &file, &is_script_resource);
5199 conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
5200 get_remote_ip(conn), ri->uri);
5202 DEBUG_TRACE((
"%s", ri->uri));
5206 if (!conn->client.is_ssl && conn->client.ssl_redir &&
5207 (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {
5208 redirect_to_https_port(conn, ssl_index);
5209 }
else if (!is_script_resource && !is_put_or_delete_request(conn) &&
5210 !check_authorization(conn, path)) {
5211 send_authorization_request(conn);
5212 }
else if (conn->ctx->callbacks.begin_request != NULL &&
5213 conn->ctx->callbacks.begin_request(conn)) {
5215 #if defined(USE_WEBSOCKET)
5216 }
else if (is_websocket_request(conn)) {
5217 handle_websocket_request(conn, path, is_script_resource);
5219 }
else if (conn->ctx->request_handlers != NULL &&
5220 use_request_handler(conn)) {
5222 }
else if (!is_script_resource && !strcmp(ri->request_method,
"OPTIONS")) {
5224 }
else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
5225 send_http_error(conn, 404,
"Not Found",
"Not Found");
5226 }
else if (!is_script_resource && is_put_or_delete_request(conn) &&
5227 (is_authorized_for_put(conn) != 1)) {
5228 send_authorization_request(conn);
5229 }
else if (!is_script_resource && !strcmp(ri->request_method,
"PUT")) {
5230 put_file(conn, path);
5231 }
else if (!is_script_resource && !strcmp(ri->request_method,
"MKCOL")) {
5233 }
else if (!is_script_resource && !strcmp(ri->request_method,
"DELETE")) {
5235 memset(&de.file, 0,
sizeof(de.file));
5236 if(!mg_stat(conn, path, &de.file)) {
5237 send_http_error(conn, 404,
"Not Found",
"%s",
"File not found");
5239 if(de.file.modification_time) {
5240 if(de.file.is_directory) {
5241 remove_directory(conn, path);
5242 send_http_error(conn, 204,
"No Content",
"%s",
"");
5243 }
else if (mg_remove(path) == 0) {
5244 send_http_error(conn, 204,
"No Content",
"%s",
"");
5246 send_http_error(conn, 423,
"Locked",
"remove(%s): %s", path,
5250 send_http_error(conn, 500, http_500_error,
"remove(%s): %s", path,
5254 }
else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||
5255 must_hide_file(conn, path)) {
5256 send_http_error(conn, 404,
"Not Found",
"%s",
"File not found");
5257 }
else if (file.is_directory && ri->uri[uri_len - 1] !=
'/') {
5258 gmt_time_string(date,
sizeof(date), &curtime);
5259 mg_printf(conn,
"HTTP/1.1 301 Moved Permanently\r\n"
5262 "Content-Length: 0\r\n"
5263 "Connection: %s\r\n\r\n",
5264 ri->uri, date, suggest_connection_header(conn));
5265 }
else if (!is_script_resource && !strcmp(ri->request_method,
"PROPFIND")) {
5266 handle_propfind(conn, path, &file);
5267 }
else if (file.is_directory &&
5268 !substitute_index_file(conn, path,
sizeof(path), &file)) {
5269 if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
"yes")) {
5270 handle_directory_request(conn, path);
5272 send_http_error(conn, 403,
"Directory Listing Denied",
5273 "Directory listing denied");
5276 }
else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
5277 (
int)strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
5280 handle_lsp_request(conn, path, &file, NULL);
5281 }
else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
5282 (
int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
5285 mg_exec_lua_script(conn, path, NULL);
5287 #if !defined(NO_CGI)
5288 }
else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
5289 (
int)strlen(conn->ctx->config[CGI_EXTENSIONS]),
5300 handle_cgi_request(conn, path);
5302 }
else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
5303 (
int)strlen(conn->ctx->config[SSI_EXTENSIONS]),
5305 handle_ssi_file_request(conn, path);
5306 }
else if (is_not_modified(conn, &file)) {
5307 send_http_error(conn, 304,
"Not Modified",
"%s",
"");
5309 handle_file_request(conn, path, &file);
5313 static void close_all_listening_sockets(
struct mg_context *ctx)
5316 for (i = 0; i < ctx->num_listening_sockets; i++) {
5317 closesocket(ctx->listening_sockets[i].sock);
5319 free(ctx->listening_sockets);
5322 static int is_valid_port(
unsigned int port)
5324 return port < 0xffff;
5330 static int parse_port_string(
const struct vec *vec,
struct socket *so)
5332 unsigned int a, b, c, d, ch, len, port;
5333 #if defined(USE_IPV6)
5340 memset(so, 0,
sizeof(*so));
5341 so->lsa.sin.sin_family = AF_INET;
5343 if (sscanf(vec->ptr,
"%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
5345 so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
5346 so->lsa.sin.sin_port = htons((uint16_t) port);
5347 #if defined(USE_IPV6)
5349 }
else if (sscanf(vec->ptr,
"[%49[^]]]:%d%n", buf, &port, &len) == 2 &&
5350 inet_pton(AF_INET6, buf, &so->lsa.sin6.sin6_addr)) {
5352 so->lsa.sin6.sin6_family = AF_INET6;
5353 so->lsa.sin6.sin6_port = htons((uint16_t) port);
5355 }
else if (sscanf(vec->ptr,
"%u%n", &port, &len) == 1) {
5357 so->lsa.sin.sin_port = htons((uint16_t) port);
5363 so->is_ssl = ch ==
's';
5364 so->ssl_redir = ch ==
'r';
5367 return is_valid_port(port) &&
5368 (ch ==
'\0' || ch ==
's' || ch ==
'r' || ch ==
',');
5371 static int set_ports_option(
struct mg_context *ctx)
5373 const char *list = ctx->config[LISTENING_PORTS];
5374 int on = 1, success = 1;
5375 #if defined(USE_IPV6)
5379 struct socket so, *ptr;
5382 struct sockaddr_in sin;
5385 memset(&sin, 0,
sizeof(sin));
5388 while (success && (list = next_option(list, &vec, NULL)) != NULL) {
5389 if (!parse_port_string(&vec, &so)) {
5390 mg_cry(fc(ctx),
"%s: %.*s: invalid port spec. Expecting list of: %s",
5391 __func__, (
int) vec.len, vec.ptr,
"[IP_ADDRESS:]PORT[s|r]");
5393 }
else if (so.is_ssl && ctx->ssl_ctx == NULL) {
5394 mg_cry(fc(ctx),
"Cannot add SSL socket, is -ssl_certificate option set?");
5396 }
else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
5400 setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,
5401 (
const char *) &on,
sizeof(on)) != 0 ||
5402 #
if defined(USE_IPV6)
5403 (so.lsa.sa.sa_family == AF_INET6 &&
5404 setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (
void *) &off,
5405 sizeof(off)) != 0) ||
5407 bind(so.sock, &so.lsa.sa, so.lsa.sa.sa_family == AF_INET ?
5408 sizeof(so.lsa.sin) :
sizeof(so.lsa)) != 0 ||
5409 listen(so.sock, SOMAXCONN) != 0 ||
5410 getsockname(so.sock, (
struct sockaddr *)&sin, &len) != 0) {
5411 mg_cry(fc(ctx),
"%s: cannot bind to %.*s: %d (%s)", __func__,
5412 (
int) vec.len, vec.ptr, ERRNO, strerror(errno));
5413 if (so.sock != INVALID_SOCKET) {
5414 closesocket(so.sock);
5417 }
else if ((ptr = (
struct socket *) realloc(ctx->listening_sockets,
5418 (ctx->num_listening_sockets + 1) *
5419 sizeof(ctx->listening_sockets[0]))) == NULL) {
5420 closesocket(so.sock);
5422 }
else if ((portPtr = (in_port_t*) realloc(ctx->listening_ports,
5423 (ctx->num_listening_sockets + 1) *
5424 sizeof(ctx->listening_ports[0]))) == NULL) {
5425 closesocket(so.sock);
5429 set_close_on_exec(so.sock, fc(ctx));
5430 ctx->listening_sockets = ptr;
5431 ctx->listening_sockets[ctx->num_listening_sockets] = so;
5432 ctx->listening_ports = portPtr;
5433 ctx->listening_ports[ctx->num_listening_sockets] = ntohs(sin.sin_port);
5434 ctx->num_listening_sockets++;
5439 close_all_listening_sockets(ctx);
5445 static void log_header(
const struct mg_connection *conn,
const char *header,
5448 const char *header_value;
5450 if ((header_value = mg_get_header(conn, header)) == NULL) {
5451 (void) fprintf(fp,
"%s",
" -");
5453 (void) fprintf(fp,
" \"%s\"", header_value);
5457 static void log_access(
const struct mg_connection *conn)
5459 const struct mg_request_info *ri;
5461 char date[64], src_addr[IP_ADDR_STR_LEN];
5464 fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :
5465 fopen(conn->ctx->config[ACCESS_LOG_FILE],
"a+");
5470 tm = localtime(&conn->birth_time);
5472 strftime(date,
sizeof(date),
"%d/%b/%Y:%H:%M:%S %z", tm);
5474 strncpy(date,
"01/Jan/1970:00:00:00 +0000",
sizeof(date));
5475 date[
sizeof(date) - 1] =
'\0';
5478 ri = &conn->request_info;
5481 sockaddr_to_string(src_addr,
sizeof(src_addr), &conn->client.rsa);
5482 fprintf(fp,
"%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
5483 src_addr, ri->remote_user == NULL ?
"-" : ri->remote_user, date,
5484 ri->request_method ? ri->request_method :
"-",
5485 ri->uri ? ri->uri :
"-", ri->http_version,
5486 conn->status_code, conn->num_bytes_sent);
5487 log_header(conn,
"Referer", fp);
5488 log_header(conn,
"User-Agent", fp);
5498 static int check_acl(
struct mg_context *ctx, uint32_t remote_ip)
5503 const char *list = ctx->config[ACCESS_CONTROL_LIST];
5506 allowed = list == NULL ?
'+' :
'-';
5508 while ((list = next_option(list, &vec, NULL)) != NULL) {
5510 if ((flag !=
'+' && flag !=
'-') ||
5511 parse_net(&vec.ptr[1], &net, &mask) == 0) {
5512 mg_cry(fc(ctx),
"%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
5516 if (net == (remote_ip & mask)) {
5521 return allowed ==
'+';
5524 #if !defined(_WIN32)
5525 static int set_uid_option(
struct mg_context *ctx)
5528 const char *uid = ctx->config[RUN_AS_USER];
5534 if ((pw = getpwnam(uid)) == NULL) {
5535 mg_cry(fc(ctx),
"%s: unknown user [%s]", __func__, uid);
5536 }
else if (setgid(pw->pw_gid) == -1) {
5537 mg_cry(fc(ctx),
"%s: setgid(%s): %s", __func__, uid, strerror(errno));
5538 }
else if (setuid(pw->pw_uid) == -1) {
5539 mg_cry(fc(ctx),
"%s: setuid(%s): %s", __func__, uid, strerror(errno));
5549 #if !defined(NO_SSL)
5550 static pthread_mutex_t *ssl_mutexes;
5552 static int sslize(
struct mg_connection *conn, SSL_CTX *s,
int (*func)(SSL *))
5554 return (conn->ssl = SSL_new(s)) != NULL &&
5555 SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
5556 func(conn->ssl) == 1;
5560 static const char *ssl_error(
void)
5563 err = ERR_get_error();
5564 return err == 0 ?
"" : ERR_error_string(err, NULL);
5567 static void ssl_locking_callback(
int mode,
int mutex_num,
const char *file,
5574 (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
5576 (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
5580 static unsigned long ssl_id_callback(
void)
5582 return (
unsigned long) pthread_self();
5585 #if !defined(NO_SSL_DL)
5586 static void *load_dll(
struct mg_context *ctx,
const char *dll_name,
5587 struct ssl_func *sw)
5594 struct ssl_func *fp;
5596 if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
5597 mg_cry(fc(ctx),
"%s: cannot load %s", __func__, dll_name);
5601 for (fp = sw; fp->name != NULL; fp++) {
5604 u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
5609 u.p = dlsym(dll_handle, fp->name);
5612 mg_cry(fc(ctx),
"%s: %s: cannot find %s", __func__, dll_name, fp->name);
5613 dlclose(dll_handle);
5625 static int set_ssl_option(
struct mg_context *ctx)
5632 if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
5633 ctx->callbacks.init_ssl == NULL) {
5637 #if !defined(NO_SSL_DL)
5638 ctx->ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
5639 ctx->cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
5640 if (!ctx->ssllib_dll_handle || !ctx->cryptolib_dll_handle) {
5647 SSL_load_error_strings();
5649 if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
5650 mg_cry(fc(ctx),
"SSL_CTX_new (server) error: %s", ssl_error());
5656 if ((ctx->callbacks.init_ssl == NULL ||
5657 !ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data)) &&
5658 (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||
5659 SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
5660 mg_cry(fc(ctx),
"%s: cannot open %s: %s", __func__, pem, ssl_error());
5665 (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
5670 size =
sizeof(pthread_mutex_t) * CRYPTO_num_locks();
5671 if ((ssl_mutexes = (pthread_mutex_t *) malloc((
size_t)size)) == NULL) {
5672 mg_cry(fc(ctx),
"%s: cannot allocate mutexes: %s", __func__, ssl_error());
5676 for (i = 0; i < CRYPTO_num_locks(); i++) {
5677 pthread_mutex_init(&ssl_mutexes[i], NULL);
5680 CRYPTO_set_locking_callback(&ssl_locking_callback);
5681 CRYPTO_set_id_callback(&ssl_id_callback);
5686 static void uninitialize_ssl(
struct mg_context *ctx)
5689 if (ctx->ssl_ctx != NULL) {
5690 CRYPTO_set_locking_callback(NULL);
5691 for (i = 0; i < CRYPTO_num_locks(); i++) {
5692 pthread_mutex_destroy(&ssl_mutexes[i]);
5694 CRYPTO_set_locking_callback(NULL);
5695 CRYPTO_set_id_callback(NULL);
5700 static int set_gpass_option(
struct mg_context *ctx)
5702 struct file file = STRUCT_FILE_INITIALIZER;
5703 const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
5704 if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
5705 mg_cry(fc(ctx),
"Cannot open %s: %s", path, strerror(ERRNO));
5711 static int set_acl_option(
struct mg_context *ctx)
5713 return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
5716 static void reset_per_request_attributes(
struct mg_connection *conn)
5718 conn->path_info = NULL;
5719 conn->num_bytes_sent = conn->consumed_content = 0;
5720 conn->status_code = -1;
5721 conn->must_close = conn->request_len = conn->throttle = 0;
5724 static void close_socket_gracefully(
struct mg_connection *conn)
5727 char buf[MG_BUF_LEN];
5730 struct linger linger;
5735 linger.l_linger = 1;
5736 if (setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,
5737 (
char *) &linger,
sizeof(linger)) != 0) {
5738 mg_cry(conn,
"%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
5739 __func__, strerror(ERRNO));
5743 shutdown(conn->client.sock, SHUT_WR);
5744 set_non_blocking_mode(conn->client.sock);
5753 n = pull(NULL, conn, buf,
sizeof(buf));
5758 closesocket(conn->client.sock);
5761 static void close_connection(
struct mg_connection *conn)
5763 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
5764 if (conn->lua_websocket_state) {
5765 lua_websocket_close(conn);
5770 if (conn->ctx->callbacks.connection_close != NULL)
5771 conn->ctx->callbacks.connection_close(conn);
5775 conn->must_close = 1;
5778 if (conn->ssl != NULL) {
5780 SSL_shutdown(conn->ssl);
5781 SSL_free(conn->ssl);
5785 if (conn->client.sock != INVALID_SOCKET) {
5786 close_socket_gracefully(conn);
5787 conn->client.sock = INVALID_SOCKET;
5793 void mg_close_connection(
struct mg_connection *conn)
5796 if (conn->client_ssl_ctx != NULL) {
5797 SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);
5800 close_connection(conn);
5801 (void) pthread_mutex_destroy(&conn->mutex);
5805 struct mg_connection *mg_connect(
const char *host,
int port,
int use_ssl,
5806 char *ebuf,
size_t ebuf_len);
5808 struct mg_connection *mg_connect(
const char *host,
int port,
int use_ssl,
5809 char *ebuf,
size_t ebuf_len)
5811 static struct mg_context fake_ctx;
5812 struct mg_connection *conn = NULL;
5815 if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf,
5816 ebuf_len)) == INVALID_SOCKET) {
5817 }
else if ((conn = (
struct mg_connection *)
5818 calloc(1,
sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
5819 snprintf(ebuf, ebuf_len,
"calloc(): %s", strerror(ERRNO));
5822 }
else if (use_ssl && (conn->client_ssl_ctx =
5823 SSL_CTX_new(SSLv23_client_method())) == NULL) {
5824 snprintf(ebuf, ebuf_len,
"SSL_CTX_new error");
5830 socklen_t len =
sizeof(
struct sockaddr);
5831 conn->buf_size = MAX_REQUEST_SIZE;
5832 conn->buf = (
char *) (conn + 1);
5833 conn->ctx = &fake_ctx;
5834 conn->client.sock = sock;
5835 if (getsockname(sock, &conn->client.rsa.sa, &len) != 0) {
5836 mg_cry(conn,
"%s: getsockname() failed: %s",
5837 __func__, strerror(ERRNO));
5839 conn->client.is_ssl = use_ssl;
5840 (void) pthread_mutex_init(&conn->mutex, NULL);
5846 SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
5847 sslize(conn, conn->client_ssl_ctx, SSL_connect);
5855 static int is_valid_uri(
const char *uri)
5860 return uri[0] ==
'/' || (uri[0] ==
'*' && uri[1] ==
'\0');
5863 static int getreq(
struct mg_connection *conn,
char *ebuf,
size_t ebuf_len)
5868 reset_per_request_attributes(conn);
5869 conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
5871 assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
5873 if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
5874 snprintf(ebuf, ebuf_len,
"%s",
"Request Too Large");
5875 }
else if (conn->request_len <= 0) {
5876 snprintf(ebuf, ebuf_len,
"%s",
"Client closed connection");
5877 }
else if (parse_http_message(conn->buf, conn->buf_size,
5878 &conn->request_info) <= 0) {
5879 snprintf(ebuf, ebuf_len,
"Bad request: [%.*s]", conn->data_len, conn->buf);
5882 if ((cl = get_header(&conn->request_info,
"Content-Length")) != NULL) {
5883 conn->content_len = strtoll(cl, NULL, 10);
5884 }
else if (!mg_strcasecmp(conn->request_info.request_method,
"POST") ||
5885 !mg_strcasecmp(conn->request_info.request_method,
"PUT")) {
5886 conn->content_len = -1;
5888 conn->content_len = 0;
5890 conn->birth_time = time(NULL);
5892 return ebuf[0] ==
'\0';
5895 struct mg_connection *mg_download(
const char *host,
int port,
int use_ssl,
5896 char *ebuf,
size_t ebuf_len,
5897 const char *fmt, ...)
5899 struct mg_connection *conn;
5904 if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {
5905 }
else if (mg_vprintf(conn, fmt, ap) <= 0) {
5906 snprintf(ebuf, ebuf_len,
"%s",
"Error sending request");
5908 getreq(conn, ebuf, ebuf_len);
5910 if (ebuf[0] !=
'\0' && conn != NULL) {
5911 mg_close_connection(conn);
5919 static void process_new_connection(
struct mg_connection *conn)
5921 struct mg_request_info *ri = &conn->request_info;
5922 int keep_alive_enabled, keep_alive, discard_len;
5925 keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE],
"yes");
5932 if (!getreq(conn, ebuf,
sizeof(ebuf))) {
5933 send_http_error(conn, 500,
"Server Error",
"%s", ebuf);
5934 conn->must_close = 1;
5935 }
else if (!is_valid_uri(conn->request_info.uri)) {
5936 snprintf(ebuf,
sizeof(ebuf),
"Invalid URI: [%s]", ri->uri);
5937 send_http_error(conn, 400,
"Bad Request",
"%s", ebuf);
5938 }
else if (strcmp(ri->http_version,
"1.0") &&
5939 strcmp(ri->http_version,
"1.1")) {
5940 snprintf(ebuf,
sizeof(ebuf),
"Bad HTTP version: [%s]", ri->http_version);
5941 send_http_error(conn, 505,
"Bad HTTP version",
"%s", ebuf);
5944 if (ebuf[0] ==
'\0') {
5945 handle_request(conn);
5946 if (conn->ctx->callbacks.end_request != NULL) {
5947 conn->ctx->callbacks.end_request(conn, conn->status_code);
5951 if (ri->remote_user != NULL) {
5952 free((
void *) ri->remote_user);
5955 ri->remote_user = NULL;
5962 keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
5963 conn->content_len >= 0 && should_keep_alive(conn);
5966 discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
5967 conn->request_len + conn->content_len < (int64_t) conn->data_len ?
5968 (
int) (conn->request_len + conn->content_len) : conn->data_len;
5969 assert(discard_len >= 0);
5970 memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);
5971 conn->data_len -= discard_len;
5972 assert(conn->data_len >= 0);
5973 assert(conn->data_len <= conn->buf_size);
5974 }
while (keep_alive);
5978 static int consume_socket(
struct mg_context *ctx,
struct socket *sp)
5980 (void) pthread_mutex_lock(&ctx->mutex);
5981 DEBUG_TRACE((
"going idle"));
5984 while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
5985 pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
5989 if (ctx->sq_head > ctx->sq_tail) {
5991 *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
5993 DEBUG_TRACE((
"grabbed socket %d, going busy", sp->sock));
5996 while (ctx->sq_tail > (
int) ARRAY_SIZE(ctx->queue)) {
5997 ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
5998 ctx->sq_head -= ARRAY_SIZE(ctx->queue);
6002 (void) pthread_cond_signal(&ctx->sq_empty);
6003 (void) pthread_mutex_unlock(&ctx->mutex);
6005 return !ctx->stop_flag;
6008 static void *worker_thread_run(
void *thread_func_param)
6010 struct mg_context *ctx = (
struct mg_context *) thread_func_param;
6011 struct mg_connection *conn;
6012 struct mg_workerTLS tls;
6015 #if defined(_WIN32) && !defined(__SYMBIAN32__)
6016 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
6019 conn = (
struct mg_connection *) calloc(1,
sizeof(*conn) + MAX_REQUEST_SIZE);
6021 mg_cry(fc(ctx),
"%s",
"Cannot create new connection struct, OOM");
6023 pthread_setspecific(sTlsKey, &tls);
6024 conn->buf_size = MAX_REQUEST_SIZE;
6025 conn->buf = (
char *) (conn + 1);
6027 conn->request_info.user_data = ctx->user_data;
6030 (void) pthread_mutex_init(&conn->mutex, NULL);
6035 while (consume_socket(ctx, &conn->client)) {
6036 conn->birth_time = time(NULL);
6042 conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
6043 memcpy(&conn->request_info.remote_ip,
6044 &conn->client.rsa.sin.sin_addr.s_addr, 4);
6045 conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
6046 conn->request_info.is_ssl = conn->client.is_ssl;
6048 if (!conn->client.is_ssl
6050 || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
6053 process_new_connection(conn);
6056 close_connection(conn);
6061 (void) pthread_mutex_lock(&ctx->mutex);
6063 (void) pthread_cond_signal(&ctx->cond);
6064 assert(ctx->num_threads >= 0);
6065 (void) pthread_mutex_unlock(&ctx->mutex);
6067 pthread_setspecific(sTlsKey, 0);
6068 #if defined(_WIN32) && !defined(__SYMBIAN32__)
6069 CloseHandle(tls.pthread_cond_helper_mutex);
6073 DEBUG_TRACE((
"exiting"));
6080 static unsigned __stdcall worker_thread(
void *thread_func_param)
6082 worker_thread_run(thread_func_param);
6086 static void *worker_thread(
void *thread_func_param)
6088 worker_thread_run(thread_func_param);
6094 static void produce_socket(
struct mg_context *ctx,
const struct socket *sp)
6096 (void) pthread_mutex_lock(&ctx->mutex);
6099 while (ctx->stop_flag == 0 &&
6100 ctx->sq_head - ctx->sq_tail >= (
int) ARRAY_SIZE(ctx->queue)) {
6101 (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
6104 if (ctx->sq_head - ctx->sq_tail < (
int) ARRAY_SIZE(ctx->queue)) {
6106 ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
6108 DEBUG_TRACE((
"queued socket %d", sp->sock));
6111 (void) pthread_cond_signal(&ctx->sq_full);
6112 (void) pthread_mutex_unlock(&ctx->mutex);
6115 static int set_sock_timeout(SOCKET sock,
int milliseconds)
6118 DWORD t = milliseconds;
6121 t.tv_sec = milliseconds / 1000;
6122 t.tv_usec = (milliseconds * 1000) % 1000000;
6124 return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (
const char *) &t,
sizeof(t)) ||
6125 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (
const char *) &t,
sizeof(t));
6128 static void accept_new_connection(
const struct socket *listener,
6129 struct mg_context *ctx)
6132 char src_addr[IP_ADDR_STR_LEN];
6133 socklen_t len =
sizeof(so.rsa);
6136 if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {
6137 }
else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {
6138 sockaddr_to_string(src_addr,
sizeof(src_addr), &so.rsa);
6139 mg_cry(fc(ctx),
"%s: %s is not allowed to connect", __func__, src_addr);
6140 closesocket(so.sock);
6143 DEBUG_TRACE((
"Accepted socket %d", (
int) so.sock));
6144 set_close_on_exec(so.sock, fc(ctx));
6145 so.is_ssl = listener->is_ssl;
6146 so.ssl_redir = listener->ssl_redir;
6147 if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
6148 mg_cry(fc(ctx),
"%s: getsockname() failed: %s",
6149 __func__, strerror(ERRNO));
6157 if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (
const char *) &on,
6160 "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
6161 __func__, strerror(ERRNO));
6163 set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));
6164 produce_socket(ctx, &so);
6168 static void master_thread_run(
void *thread_func_param)
6170 struct mg_context *ctx = (
struct mg_context *) thread_func_param;
6171 struct mg_workerTLS tls;
6174 int workerthreadcount;
6178 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
6179 #elif defined(USE_MASTER_THREAD_PRIORITY)
6180 int min_prio = sched_get_priority_min(SCHED_RR);
6181 int max_prio = sched_get_priority_max(SCHED_RR);
6182 if ((min_prio >=0) && (max_prio >= 0) &&
6183 ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
6184 ((USE_MASTER_THREAD_PRIORITY) >= min_prio)
6186 struct sched_param sched_param = {0};
6187 sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
6188 pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
6192 #if defined(_WIN32) && !defined(__SYMBIAN32__)
6193 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
6196 pthread_setspecific(sTlsKey, &tls);
6198 pfd = (
struct pollfd *) calloc(ctx->num_listening_sockets,
sizeof(pfd[0]));
6199 while (pfd != NULL && ctx->stop_flag == 0) {
6200 for (i = 0; i < ctx->num_listening_sockets; i++) {
6201 pfd[i].fd = ctx->listening_sockets[i].sock;
6202 pfd[i].events = POLLIN;
6205 if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
6206 for (i = 0; i < ctx->num_listening_sockets; i++) {
6212 if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
6213 accept_new_connection(&ctx->listening_sockets[i], ctx);
6219 DEBUG_TRACE((
"stopping workers"));
6222 close_all_listening_sockets(ctx);
6225 pthread_cond_broadcast(&ctx->sq_full);
6228 (void) pthread_mutex_lock(&ctx->mutex);
6229 while (ctx->num_threads > 0) {
6230 (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
6232 (void) pthread_mutex_unlock(&ctx->mutex);
6235 workerthreadcount = ctx->workerthreadcount;
6236 for (i = 0; i < workerthreadcount; i++) {
6237 mg_join_thread(ctx->workerthreadids[i]);
6241 (void) pthread_mutex_destroy(&ctx->mutex);
6242 (void) pthread_cond_destroy(&ctx->cond);
6243 (void) pthread_cond_destroy(&ctx->sq_empty);
6244 (void) pthread_cond_destroy(&ctx->sq_full);
6246 #if !defined(NO_SSL)
6247 uninitialize_ssl(ctx);
6249 DEBUG_TRACE((
"exiting"));
6251 #if defined(_WIN32) && !defined(__SYMBIAN32__)
6252 CloseHandle(tls.pthread_cond_helper_mutex);
6254 pthread_setspecific(sTlsKey, 0);
6265 static unsigned __stdcall master_thread(
void *thread_func_param)
6267 master_thread_run(thread_func_param);
6271 static void *master_thread(
void *thread_func_param)
6273 master_thread_run(thread_func_param);
6278 static void free_context(
struct mg_context *ctx)
6281 struct mg_request_handler_info *tmp_rh;
6287 for (i = 0; i < NUM_OPTIONS; i++) {
6288 if (ctx->config[i] != NULL)
6290 #pragma warning(suppress: 6001)
6292 free(ctx->config[i]);
6296 while (ctx->request_handlers) {
6297 tmp_rh = ctx->request_handlers;
6298 ctx->request_handlers = tmp_rh->next;
6305 if (ctx->ssl_ctx != NULL) {
6306 SSL_CTX_free(ctx->ssl_ctx);
6308 if (ssl_mutexes != NULL) {
6315 if (ctx->workerthreadids != NULL) {
6316 free(ctx->workerthreadids);
6322 pthread_key_delete(sTlsKey);
6329 void mg_stop(
struct mg_context *ctx)
6334 while (ctx->stop_flag != 2) {
6335 (void) mg_sleep(10);
6337 mg_join_thread(ctx->masterthreadid);
6340 #if defined(_WIN32) && !defined(__SYMBIAN32__)
6341 (void) WSACleanup();
6345 struct mg_context *mg_start(
const struct mg_callbacks *callbacks,
6347 const char **options)
6349 struct mg_context *ctx;
6350 const char *name, *value, *default_value;
6352 int workerthreadcount;
6354 #if defined(_WIN32) && !defined(__SYMBIAN32__)
6356 WSAStartup(MAKEWORD(2,2), &data);
6357 #pragma warning(suppress: 28125)
6358 InitializeCriticalSection(&global_log_file_lock);
6363 assert(
sizeof(config_options)/
sizeof(config_options[0]) == NUM_OPTIONS*2+1);
6367 if ((ctx = (
struct mg_context *) calloc(1,
sizeof(*ctx))) == NULL) {
6372 if (0 != pthread_key_create(&sTlsKey, NULL)) {
6373 mg_cry(fc(ctx),
"Cannot initialize thread local storage");
6380 ctx->callbacks = *callbacks;
6381 ctx->user_data = user_data;
6382 ctx->request_handlers = 0;
6384 while (options && (name = *options++) != NULL) {
6385 if ((i = get_option_index(name)) == -1) {
6386 mg_cry(fc(ctx),
"Invalid option: %s", name);
6389 }
else if ((value = *options++) == NULL) {
6390 mg_cry(fc(ctx),
"%s: option value cannot be NULL", name);
6394 if (ctx->config[i] != NULL) {
6395 mg_cry(fc(ctx),
"warning: %s: duplicate option", name);
6396 free(ctx->config[i]);
6398 ctx->config[i] = mg_strdup(value);
6399 DEBUG_TRACE((
"[%s] -> [%s]", name, value));
6403 for (i = 0; config_options[i * 2] != NULL; i++) {
6404 default_value = config_options[i * 2 + 1];
6405 if (ctx->config[i] == NULL && default_value != NULL) {
6406 ctx->config[i] = mg_strdup(default_value);
6412 if (!set_gpass_option(ctx) ||
6413 #
if !defined(NO_SSL)
6414 !set_ssl_option(ctx) ||
6416 !set_ports_option(ctx) ||
6417 #
if !defined(_WIN32)
6418 !set_uid_option(ctx) ||
6420 !set_acl_option(ctx)) {
6425 #if !defined(_WIN32) && !defined(__SYMBIAN32__)
6428 (void) signal(SIGPIPE, SIG_IGN);
6431 (void) pthread_mutex_init(&ctx->mutex, NULL);
6432 (void) pthread_cond_init(&ctx->cond, NULL);
6433 (void) pthread_cond_init(&ctx->sq_empty, NULL);
6434 (void) pthread_cond_init(&ctx->sq_full, NULL);
6436 workerthreadcount = atoi(ctx->config[NUM_THREADS]);
6438 if (workerthreadcount > MAX_WORKER_THREADS) {
6439 mg_cry(fc(ctx),
"Too many worker threads");
6444 if (workerthreadcount > 0) {
6445 ctx->workerthreadcount = workerthreadcount;
6446 ctx->workerthreadids = (pthread_t*)calloc(workerthreadcount,
sizeof(pthread_t));
6447 if (ctx->workerthreadids == NULL) {
6448 mg_cry(fc(ctx),
"Not enough memory for worker thread ID array");
6455 mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
6458 for (i = 0; i < workerthreadcount; i++) {
6459 (void) pthread_mutex_lock(&ctx->mutex);
6461 (void) pthread_mutex_unlock(&ctx->mutex);
6462 if (mg_start_thread_with_id(worker_thread, ctx,
6463 &ctx->workerthreadids[i]) != 0) {
6464 (void) pthread_mutex_lock(&ctx->mutex);
6466 (void) pthread_mutex_unlock(&ctx->mutex);
6467 mg_cry(fc(ctx),
"Cannot start worker thread: %ld", (
long) ERRNO);