23#if defined(__GNUC__) || defined(__MINGW32__)
25 (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
26#if GCC_VERSION >= 40500
32#if defined(GCC_DIAGNOSTIC)
35#pragma GCC diagnostic ignored "-Wunused-macros"
37#pragma GCC diagnostic ignored "-Wpadded"
44#pragma GCC diagnostic push
45#pragma GCC diagnostic ignored "-Wreserved-id-macro"
49#if !defined(_CRT_SECURE_NO_WARNINGS)
50#define _CRT_SECURE_NO_WARNINGS
52#if !defined(_WIN32_WINNT)
53#define _WIN32_WINNT 0x0502
56#if !defined(_GNU_SOURCE)
59#if defined(__linux__) && !defined(_XOPEN_SOURCE)
60#define _XOPEN_SOURCE 600
62#if defined(__LSB_VERSION__) || defined(__sun)
66#if !defined(_LARGEFILE_SOURCE)
67#define _LARGEFILE_SOURCE
69#if !defined(_FILE_OFFSET_BITS)
70#define _FILE_OFFSET_BITS 64
72#if !defined(__STDC_FORMAT_MACROS)
73#define __STDC_FORMAT_MACROS
75#if !defined(__STDC_LIMIT_MACROS)
76#define __STDC_LIMIT_MACROS
78#if !defined(_DARWIN_UNLIMITED_SELECT)
79#define _DARWIN_UNLIMITED_SELECT
83#define __inline inline
89#pragma GCC diagnostic pop
99#pragma warning(disable : 4306)
101#pragma warning(disable : 4127)
103#pragma warning(disable : 4204)
105#pragma warning(disable : 4820)
107#pragma warning(disable : 4668)
109#pragma warning(disable : 4255)
111#pragma warning(disable : 4711)
118#if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
119#define mg_static_assert _Static_assert
120#elif defined(__cplusplus) && __cplusplus >= 201103L
121#define mg_static_assert static_assert
124#define mg_static_assert(cond, txt) \
125 extern char static_assert_replacement[(cond) ? 1 : -1]
129 "int data type size check");
131 "pointer data type size check");
143#if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
146 "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
148#if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
150#define NO_ALTERNATIVE_QUEUE
153#if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
168#error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
172#if !defined(WIN32_LEAN_AND_MEAN)
173#define WIN32_LEAN_AND_MEAN
176#if defined(__SYMBIAN32__)
181#error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
184#if defined(__ZEPHYR__)
188#include <net/socket.h>
189#include <posix/pthread.h>
190#include <posix/time.h>
198#include <libc_extensions.h>
203#define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
205#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
206#define ZEPHYR_STACK_SIZE USE_STACK_SIZE
208#define ZEPHYR_STACK_SIZE (1024 * 16)
211K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
212K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
216static int zephyr_worker_stack_index;
220#if !defined(CIVETWEB_HEADER_INCLUDED)
226#if !defined(DEBUG_TRACE)
228static void DEBUG_TRACE_FUNC(
const char *func,
233#define DEBUG_TRACE(fmt, ...) \
234 DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
236#define NEED_DEBUG_TRACE_FUNC
237#if !defined(DEBUG_TRACE_STREAM)
238#define DEBUG_TRACE_STREAM stdout
242#define DEBUG_TRACE(fmt, ...) \
249#if !defined(DEBUG_ASSERT)
252#define DEBUG_ASSERT(cond) \
255 DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
260#define DEBUG_ASSERT(cond)
265#if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
266void __cyg_profile_func_enter(
void *this_fn,
void *call_site)
267 __attribute__((no_instrument_function));
269void __cyg_profile_func_exit(
void *this_fn,
void *call_site)
270 __attribute__((no_instrument_function));
273__cyg_profile_func_enter(
void *this_fn,
void *call_site)
275 if ((
void *)this_fn != (
void *)printf) {
276 printf(
"E %p %p\n", this_fn, call_site);
281__cyg_profile_func_exit(
void *this_fn,
void *call_site)
283 if ((
void *)this_fn != (
void *)printf) {
284 printf(
"X %p %p\n", this_fn, call_site);
290#if !defined(IGNORE_UNUSED_RESULT)
291#define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
295#if defined(__GNUC__) || defined(__MINGW32__)
311#pragma GCC diagnostic ignored "-Wunused-function"
313#define FUNCTION_MAY_BE_UNUSED
316#define FUNCTION_MAY_BE_UNUSED
321#if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
327#include <sys/types.h>
331#if defined(__clang__)
335#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
338#if defined(__GNUC__) || defined(__MINGW32__)
357#if defined(__clang__)
358#if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
360#pragma clang diagnostic ignored "-Wno-reserved-id-macro"
361#pragma clang diagnostic ignored "-Wno-keyword-macro"
365#ifndef CLOCK_MONOTONIC
366#define CLOCK_MONOTONIC (1)
368#ifndef CLOCK_REALTIME
369#define CLOCK_REALTIME (2)
372#include <mach/clock.h>
373#include <mach/mach.h>
374#include <mach/mach_time.h>
375#include <sys/errno.h>
380_civet_clock_gettime(
int clk_id,
struct timespec *t)
382 memset(t, 0,
sizeof(*t));
383 if (clk_id == CLOCK_REALTIME) {
385 int rv = gettimeofday(&now, NULL);
389 t->tv_sec = now.tv_sec;
390 t->tv_nsec = now.tv_usec * 1000;
393 }
else if (clk_id == CLOCK_MONOTONIC) {
394 static uint64_t clock_start_time = 0;
395 static mach_timebase_info_data_t timebase_ifo = {0, 0};
397 uint64_t now = mach_absolute_time();
399 if (clock_start_time == 0) {
400 kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
406 clock_start_time = now;
409 now = (uint64_t)((
double)(now - clock_start_time)
410 * (
double)timebase_ifo.numer
411 / (
double)timebase_ifo.denom);
413 t->tv_sec = now / 1000000000;
414 t->tv_nsec = now % 1000000000;
421#if defined(__CLOCK_AVAILABILITY)
426_civet_safe_clock_gettime(
int clk_id,
struct timespec *t)
429 return clock_gettime(clk_id, t);
431 return _civet_clock_gettime(clk_id, t);
433#define clock_gettime _civet_safe_clock_gettime
435#define clock_gettime _civet_clock_gettime
445#define ERROR_TRY_AGAIN(err) \
446 (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
462#if !defined(MAX_WORKER_THREADS)
463#define MAX_WORKER_THREADS (1024 * 64)
470#if !defined(SOCKET_TIMEOUT_QUANTUM)
471#define SOCKET_TIMEOUT_QUANTUM (2000)
475#if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
476#define MG_FILE_COMPRESSION_SIZE_LIMIT (1024)
479#if !defined(PASSWORDS_FILE_NAME)
480#define PASSWORDS_FILE_NAME ".htpasswd"
485#if !defined(CGI_ENVIRONMENT_SIZE)
486#define CGI_ENVIRONMENT_SIZE (4096)
490#if !defined(MAX_CGI_ENVIR_VARS)
491#define MAX_CGI_ENVIR_VARS (256)
495#if !defined(MG_BUF_LEN)
496#define MG_BUF_LEN (1024 * 8)
503#if !defined(ARRAY_SIZE)
504#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
510#if !defined(INT64_MAX)
511#define INT64_MAX (9223372036854775807)
514#define SHUTDOWN_RD (0)
515#define SHUTDOWN_WR (1)
516#define SHUTDOWN_BOTH (2)
519 "worker threads must be a positive number");
522 "size_t data type size check");
540#define UTF8_PATH_MAX (3 * 260)
543#define UTF16_PATH_MAX (260)
545#if !defined(_IN_PORT_T)
546#if !defined(in_port_t)
547#define in_port_t u_short
551#if defined(_WIN32_WCE)
552#error "WinCE support has ended"
560#define MAKEUQUAD(lo, hi) \
561 ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
562#define RATE_DIFF (10000000)
563#define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
564#define SYS2UNIX_TIME(lo, hi) \
565 ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
573#define STR(x) STRX(x)
574#define __func__ __FILE__ ":" STR(__LINE__)
575#define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
576#define strtoll(x, y, z) (_atoi64(x))
578#define __func__ __FUNCTION__
579#define strtoull(x, y, z) (_strtoui64(x, y, z))
580#define strtoll(x, y, z) (_strtoi64(x, y, z))
584#define ERRNO ((int)(GetLastError()))
588#if defined(_WIN64) || defined(__MINGW64__)
591#if defined(OPENSSL_API_3_0)
592#define SSL_LIB "libssl-3-x64.dll"
593#define CRYPTO_LIB "libcrypto-3-x64.dll"
596#if defined(OPENSSL_API_1_1)
597#define SSL_LIB "libssl-1_1-x64.dll"
598#define CRYPTO_LIB "libcrypto-1_1-x64.dll"
601#if defined(OPENSSL_API_1_0)
602#define SSL_LIB "ssleay64.dll"
603#define CRYPTO_LIB "libeay64.dll"
610#if defined(OPENSSL_API_3_0)
611#define SSL_LIB "libssl-3.dll"
612#define CRYPTO_LIB "libcrypto-3.dll"
615#if defined(OPENSSL_API_1_1)
616#define SSL_LIB "libssl-1_1.dll"
617#define CRYPTO_LIB "libcrypto-1_1.dll"
620#if defined(OPENSSL_API_1_0)
621#define SSL_LIB "ssleay32.dll"
622#define CRYPTO_LIB "libeay32.dll"
629#define O_NONBLOCK (0)
634#define INT64_FMT "I64d"
635#define UINT64_FMT "I64u"
637#define WINCDECL __cdecl
638#define vsnprintf_impl _vsnprintf
639#define access _access
640#define mg_sleep(x) (Sleep(x))
642#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
644#define popen(x, y) (_popen(x, y))
647#define pclose(x) (_pclose(x))
649#define close(x) (_close(x))
650#define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
652#define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
653#define fdopen(x, y) (_fdopen((x), (y)))
654#define write(x, y, z) (_write((x), (y), (unsigned)z))
655#define read(x, y, z) (_read((x), (y), (unsigned)z))
656#define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
657#define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
658#define sleep(x) (Sleep((x)*1000))
659#define rmdir(x) (_rmdir(x))
660#if defined(_WIN64) || !defined(__MINGW32__)
662#define timegm(x) (_mkgmtime(x))
664time_t timegm(
struct tm *tm);
670#define fileno(x) (_fileno(x))
674 CRITICAL_SECTION sec;
676typedef DWORD pthread_key_t;
677typedef HANDLE pthread_t;
679 pthread_mutex_t threadIdSec;
683#if !defined(__clockid_t_defined)
684typedef DWORD clockid_t;
686#if !defined(CLOCK_MONOTONIC)
687#define CLOCK_MONOTONIC (1)
689#if !defined(CLOCK_REALTIME)
690#define CLOCK_REALTIME (2)
692#if !defined(CLOCK_THREAD)
693#define CLOCK_THREAD (3)
695#if !defined(CLOCK_PROCESS)
696#define CLOCK_PROCESS (4)
700#if defined(_MSC_VER) && (_MSC_VER >= 1900)
701#define _TIMESPEC_DEFINED
703#if !defined(_TIMESPEC_DEFINED)
710#if !defined(WIN_PTHREADS_TIME_H)
711#define MUST_IMPLEMENT_CLOCK_GETTIME
714#if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
715#define clock_gettime mg_clock_gettime
717clock_gettime(clockid_t clk_id,
struct timespec *tp)
720 ULARGE_INTEGER li, li2;
723 static double perfcnt_per_sec = 0.0;
727 QueryPerformanceFrequency((LARGE_INTEGER *)&li);
728 perfcnt_per_sec = 1.0 / li.QuadPart;
733 memset(tp, 0,
sizeof(*tp));
735 if (clk_id == CLOCK_REALTIME) {
738 GetSystemTimeAsFileTime(&ft);
739 li.LowPart = ft.dwLowDateTime;
740 li.HighPart = ft.dwHighDateTime;
741 li.QuadPart -= 116444736000000000;
742 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
743 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
747 }
else if (clk_id == CLOCK_MONOTONIC) {
750 QueryPerformanceCounter((LARGE_INTEGER *)&li);
751 d = li.QuadPart * perfcnt_per_sec;
752 tp->tv_sec = (time_t)
d;
754 tp->tv_nsec = (long)(
d * 1.0E9);
758 }
else if (clk_id == CLOCK_THREAD) {
761 FILETIME t_create, t_exit, t_kernel, t_user;
762 if (GetThreadTimes(GetCurrentThread(),
767 li.LowPart = t_user.dwLowDateTime;
768 li.HighPart = t_user.dwHighDateTime;
769 li2.LowPart = t_kernel.dwLowDateTime;
770 li2.HighPart = t_kernel.dwHighDateTime;
771 li.QuadPart += li2.QuadPart;
772 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
773 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
778 }
else if (clk_id == CLOCK_PROCESS) {
781 FILETIME t_create, t_exit, t_kernel, t_user;
782 if (GetProcessTimes(GetCurrentProcess(),
787 li.LowPart = t_user.dwLowDateTime;
788 li.HighPart = t_user.dwHighDateTime;
789 li2.LowPart = t_kernel.dwLowDateTime;
790 li2.HighPart = t_kernel.dwHighDateTime;
791 li.QuadPart += li2.QuadPart;
792 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
793 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
813static int pthread_mutex_lock(pthread_mutex_t *);
814static int pthread_mutex_unlock(pthread_mutex_t *);
834 WIN32_FIND_DATAW info;
838#if defined(HAVE_POLL)
839#define mg_pollfd pollfd
850#pragma comment(lib, "Ws2_32.lib")
858#define UTF8_PATH_MAX (PATH_MAX)
863typedef unsigned short int in_port_t;
866#if !defined(__ZEPHYR__)
867#include <arpa/inet.h>
873#include <netinet/in.h>
874#include <netinet/tcp.h>
883#include <sys/socket.h>
885#include <sys/utsname.h>
889#if defined(USE_X_DOM_SOCKET)
894#define vsnprintf_impl vsnprintf
896#if !defined(NO_SSL_DL) && !defined(NO_SSL)
901#define SSL_LIB "libssl.dylib"
902#define CRYPTO_LIB "libcrypto.dylib"
905#define SSL_LIB "libssl.so"
907#if !defined(CRYPTO_LIB)
908#define CRYPTO_LIB "libcrypto.so"
911#if !defined(O_BINARY)
914#define closesocket(a) (close(a))
915#define mg_mkdir(conn, path, mode) (mkdir(path, mode))
916#define mg_remove(conn, x) (remove(x))
917#define mg_sleep(x) (usleep((x)*1000))
918#define mg_opendir(conn, x) (opendir(x))
919#define mg_closedir(x) (closedir(x))
920#define mg_readdir(x) (readdir(x))
922#define INVALID_SOCKET (-1)
923#define INT64_FMT PRId64
924#define UINT64_FMT PRIu64
930#if !defined(CLOCK_MONOTONIC)
931#define CLOCK_MONOTONIC CLOCK_REALTIME
945#define mg_pollfd pollfd
950#if defined(NEED_TIMEGM)
954 return (
y % 4 == 0 &&
y % 100 != 0) ||
y % 400 == 0;
960 return (
y - 1969) / 4 - (
y - 1901) / 100 + (
y - 1601) / 400;
966 static const unsigned short ydays[] = {
967 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
968 int year = tm->tm_year + 1900;
969 int mon = tm->tm_mon;
970 int mday = tm->tm_mday - 1;
971 int hour = tm->tm_hour;
972 int min = tm->tm_min;
973 int sec = tm->tm_sec;
975 if (year < 1970 || mon < 0 || mon > 11 || mday < 0
976 || (mday >= ydays[mon + 1] - ydays[mon]
977 + (mon == 1 && is_leap(year) ? 1 : 0))
978 || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
981 time_t res = year - 1970;
984 res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
985 res += count_leap(year);
1000#define va_copy(x, y) ((x) = (y))
1007#if defined(GCC_DIAGNOSTIC)
1009#pragma GCC diagnostic push
1010#pragma GCC diagnostic ignored "-Wunused-function"
1014static pthread_mutex_t global_log_file_lock;
1020 return GetCurrentThreadId();
1028 void (*_ignored)(
void *)
1035 return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
1043pthread_key_delete(pthread_key_t key)
1045 return TlsFree(key) ? 0 : 1;
1051pthread_setspecific(pthread_key_t key,
void *
value)
1053 return TlsSetValue(key,
value) ? 0 : 1;
1059pthread_getspecific(pthread_key_t key)
1061 return TlsGetValue(key);
1064#if defined(GCC_DIAGNOSTIC)
1066#pragma GCC diagnostic pop
1075#if defined(GCC_DIAGNOSTIC)
1077#pragma GCC diagnostic push
1078#pragma GCC diagnostic ignored "-Wunused-function"
1080#if defined(__clang__)
1082#pragma clang diagnostic push
1083#pragma clang diagnostic ignored "-Wunused-function"
1106mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu,
"Mismatch for atomic types");
1107#elif defined(_WIN32)
1122#if defined(_WIN64) && !defined(NO_ATOMICS)
1123 ret = InterlockedIncrement64(addr);
1124#elif defined(_WIN32) && !defined(NO_ATOMICS)
1125 ret = InterlockedIncrement(addr);
1126#elif defined(__GNUC__) \
1127 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1128 && !defined(NO_ATOMICS)
1129 ret = __sync_add_and_fetch(addr, 1);
1145#if defined(_WIN64) && !defined(NO_ATOMICS)
1146 ret = InterlockedDecrement64(addr);
1147#elif defined(_WIN32) && !defined(NO_ATOMICS)
1148 ret = InterlockedDecrement(addr);
1149#elif defined(__GNUC__) \
1150 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1151 && !defined(NO_ATOMICS)
1152 ret = __sync_sub_and_fetch(addr, 1);
1162#if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
1164mg_atomic_add(
volatile ptrdiff_t *addr, ptrdiff_t
value)
1168#if defined(_WIN64) && !defined(NO_ATOMICS)
1169 ret = InterlockedAdd64(addr,
value);
1170#elif defined(_WIN32) && !defined(NO_ATOMICS)
1171 ret = InterlockedExchangeAdd(addr,
value) +
value;
1172#elif defined(__GNUC__) \
1173 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1174 && !defined(NO_ATOMICS)
1175 ret = __sync_add_and_fetch(addr,
value);
1188mg_atomic_compare_and_swap(
volatile ptrdiff_t *addr,
1194#if defined(_WIN64) && !defined(NO_ATOMICS)
1195 ret = InterlockedCompareExchange64(addr, newval, oldval);
1196#elif defined(_WIN32) && !defined(NO_ATOMICS)
1197 ret = InterlockedCompareExchange(addr, newval, oldval);
1198#elif defined(__GNUC__) \
1199 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1200 && !defined(NO_ATOMICS)
1201 ret = __sync_val_compare_and_swap(addr, oldval, newval);
1205 if ((ret != newval) && (ret == oldval)) {
1215mg_atomic_max(
volatile ptrdiff_t *addr, ptrdiff_t
value)
1217 register ptrdiff_t
tmp = *addr;
1219#if defined(_WIN64) && !defined(NO_ATOMICS)
1220 while (tmp <
value) {
1221 tmp = InterlockedCompareExchange64(addr,
value, tmp);
1223#elif defined(_WIN32) && !defined(NO_ATOMICS)
1224 while (tmp <
value) {
1225 tmp = InterlockedCompareExchange(addr,
value, tmp);
1227#elif defined(__GNUC__) \
1228 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1229 && !defined(NO_ATOMICS)
1230 while (tmp <
value) {
1231 tmp = __sync_val_compare_and_swap(addr, tmp,
value);
1235 if (*addr <
value) {
1244mg_atomic_add64(
volatile int64_t *addr, int64_t
value)
1248#if defined(_WIN64) && !defined(NO_ATOMICS)
1249 ret = InterlockedAdd64(addr,
value);
1250#elif defined(_WIN32) && !defined(NO_ATOMICS)
1251 ret = InterlockedExchangeAdd64(addr,
value) +
value;
1252#elif defined(__GNUC__) \
1253 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1254 && !defined(NO_ATOMICS)
1255 ret = __sync_add_and_fetch(addr,
value);
1267#if defined(GCC_DIAGNOSTIC)
1269#pragma GCC diagnostic pop
1271#if defined(__clang__)
1273#pragma clang diagnostic pop
1277#if defined(USE_SERVER_STATS)
1279struct mg_memory_stat {
1280 volatile ptrdiff_t totalMemUsed;
1281 volatile ptrdiff_t maxMemUsed;
1282 volatile ptrdiff_t blockCount;
1286static struct mg_memory_stat *get_memory_stat(
struct mg_context *ctx);
1290mg_malloc_ex(
size_t size,
1297 struct mg_memory_stat *mstat = get_memory_stat(ctx);
1299#if defined(MEMORY_DEBUGGING)
1300 char mallocStr[256];
1307 ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)
size);
1308 mg_atomic_max(&mstat->maxMemUsed, mmem);
1312 ((uintptr_t *)
data)[1] = (uintptr_t)mstat;
1313 memory = (
void *)(((
char *)
data) + 2 *
sizeof(uintptr_t));
1316#if defined(MEMORY_DEBUGGING)
1318 "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
1320 (
unsigned long)
size,
1321 (
unsigned long)mstat->totalMemUsed,
1322 (
unsigned long)mstat->blockCount,
1333mg_calloc_ex(
size_t count,
1339 void *
data = mg_malloc_ex(
size * count, ctx, file,
line);
1349mg_free_ex(
void *memory,
const char *file,
unsigned line)
1351#if defined(MEMORY_DEBUGGING)
1352 char mallocStr[256];
1359 void *
data = (
void *)(((
char *)memory) - 2 *
sizeof(uintptr_t));
1360 uintptr_t
size = ((uintptr_t *)
data)[0];
1361 struct mg_memory_stat *mstat =
1362 (
struct mg_memory_stat *)(((uintptr_t *)
data)[1]);
1363 mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)
size);
1366#if defined(MEMORY_DEBUGGING)
1368 "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
1370 (
unsigned long)
size,
1371 (
unsigned long)mstat->totalMemUsed,
1372 (
unsigned long)mstat->blockCount,
1383mg_realloc_ex(
void *memory,
1393#if defined(MEMORY_DEBUGGING)
1394 char mallocStr[256];
1403 struct mg_memory_stat *mstat;
1404 data = (
void *)(((
char *)memory) - 2 *
sizeof(uintptr_t));
1405 oldsize = ((uintptr_t *)
data)[0];
1406 mstat = (
struct mg_memory_stat *)((uintptr_t *)
data)[1];
1407 _realloc =
realloc(
data, newsize + 2 *
sizeof(uintptr_t));
1410 mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
1411#if defined(MEMORY_DEBUGGING)
1413 "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
1415 (
unsigned long)oldsize,
1416 (
unsigned long)mstat->totalMemUsed,
1417 (
unsigned long)mstat->blockCount,
1422 mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
1424#if defined(MEMORY_DEBUGGING)
1426 "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
1428 (
unsigned long)newsize,
1429 (
unsigned long)mstat->totalMemUsed,
1430 (
unsigned long)mstat->blockCount,
1435 *(uintptr_t *)
data = newsize;
1436 data = (
void *)(((
char *)
data) + 2 *
sizeof(uintptr_t));
1438#if defined(MEMORY_DEBUGGING)
1445 data = mg_malloc_ex(newsize, ctx, file,
line);
1450 mg_free_ex(memory, file,
line);
1457#define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
1458#define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
1459#define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
1460#define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
1462#define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
1463#define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
1464#define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
1470static __inline
void *
1476static __inline
void *
1482static __inline
void *
1494#define mg_malloc_ctx(a, c) mg_malloc(a)
1495#define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
1496#define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
1497#define mg_free_ctx(a, c) mg_free(a)
1530#if defined(snprintf)
1533#if defined(vsnprintf)
1536#define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
1537#define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
1538#define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
1539#define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
1540#define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
1544#define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
1552#if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
1553 || defined(OPENSSL_API_3_0)
1554static int mg_openssl_initialized = 0;
1556#if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
1557 && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
1558#error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
1560#if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
1561 && defined(OPENSSL_API_3_0)
1562#error "Multiple OPENSSL_API versions defined"
1564#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
1565 || defined(OPENSSL_API_3_0)) \
1566 && defined(USE_MBEDTLS)
1567#error "Multiple SSL libraries defined"
1575#if defined(MG_LEGACY_INTERFACE)
1576#define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
1584 HANDLE pthread_cond_helper_mutex;
1588#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
1594#if defined(GCC_DIAGNOSTIC)
1596#pragma GCC diagnostic push
1597#pragma GCC diagnostic ignored "-Wunused-function"
1599#if defined(__clang__)
1601#pragma clang diagnostic push
1602#pragma clang diagnostic ignored "-Wunused-function"
1621 return GetCurrentThreadId();
1624#if defined(__clang__)
1625#pragma clang diagnostic push
1626#pragma clang diagnostic ignored "-Wunreachable-code"
1634 if (
sizeof(pthread_t) >
sizeof(
unsigned long)) {
1645 pthread_setspecific(
sTlsKey, tls);
1652 unsigned long ret = 0;
1653 pthread_t t = pthread_self();
1654 memcpy(&ret, &t,
sizeof(pthread_t));
1658#if defined(__clang__)
1659#pragma clang diagnostic pop
1670 struct timespec tsnow;
1671 clock_gettime(CLOCK_REALTIME, &tsnow);
1672 return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
1676#if defined(GCC_DIAGNOSTIC)
1678#pragma GCC diagnostic pop
1680#if defined(__clang__)
1682#pragma clang diagnostic pop
1686#if defined(NEED_DEBUG_TRACE_FUNC)
1688DEBUG_TRACE_FUNC(
const char *func,
unsigned line,
const char *fmt, ...)
1691 struct timespec tsnow;
1696 clock_gettime(CLOCK_REALTIME, &tsnow);
1698 flockfile(DEBUG_TRACE_STREAM);
1699 fprintf(DEBUG_TRACE_STREAM,
1700 "*** %lu.%09lu %lu %s:%u: ",
1701 (
unsigned long)tsnow.tv_sec,
1702 (
unsigned long)tsnow.tv_nsec,
1706 va_start(args, fmt);
1707 vfprintf(DEBUG_TRACE_STREAM, fmt, args);
1709 putc(
'\n', DEBUG_TRACE_STREAM);
1710 fflush(DEBUG_TRACE_STREAM);
1711 funlockfile(DEBUG_TRACE_STREAM);
1716#define MD5_STATIC static
1720#if defined(NO_SOCKLEN_T)
1721typedef int socklen_t;
1724#define IP_ADDR_STR_LEN (50)
1726#if !defined(MSG_NOSIGNAL)
1727#define MSG_NOSIGNAL (0)
1732#if defined(USE_MBEDTLS)
1734#include "mod_mbedtls.inl"
1736#elif defined(NO_SSL)
1741#elif defined(NO_SSL_DL)
1743#include <openssl/bn.h>
1744#include <openssl/conf.h>
1745#include <openssl/crypto.h>
1746#include <openssl/dh.h>
1747#include <openssl/err.h>
1748#include <openssl/opensslv.h>
1749#include <openssl/pem.h>
1750#include <openssl/ssl.h>
1751#include <openssl/tls1.h>
1752#include <openssl/x509.h>
1754#if defined(WOLFSSL_VERSION)
1757#include "wolfssl_extras.inl"
1760#if defined(OPENSSL_IS_BORINGSSL)
1771#define CONF_modules_unload(a) ((void)0)
1772#define ENGINE_cleanup() ((void)0)
1776#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
1777#if !defined(OPENSSL_API_3_0)
1778#define OPENSSL_API_3_0
1780#define OPENSSL_REMOVE_THREAD_STATE()
1782#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1783#if !defined(OPENSSL_API_1_1)
1784#define OPENSSL_API_1_1
1786#define OPENSSL_REMOVE_THREAD_STATE()
1788#if !defined(OPENSSL_API_1_0)
1789#define OPENSSL_API_1_0
1791#define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
1805#if !defined(NO_CACHING)
1826#if defined(USE_IPV6)
1827 struct sockaddr_in6 sin6;
1829#if defined(USE_X_DOM_SOCKET)
1830 struct sockaddr_un sun;
1834#if defined(USE_X_DOM_SOCKET)
1835static unsigned short
1838 if (s->
sa.sa_family == AF_INET)
1839 return s->
sin.sin_port;
1840#if defined(USE_IPV6)
1841 if (s->
sa.sa_family == AF_INET6)
1842 return s->sin6.sin6_port;
1847#if defined(USE_IPV6)
1848#define USA_IN_PORT_UNSAFE(s) \
1849 (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
1851#define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
1882#define STRUCT_FILE_INITIALIZER \
1884 {(uint64_t)0, (time_t)0, 0, 0, 0}, \
1920#if defined(__linux__)
1921 ALLOW_SENDFILE_CALL,
1924 CASE_SENSITIVE_FILES,
1930#if defined(USE_WEBSOCKET)
1932 ENABLE_WEBSOCKET_PING_PONG,
1937 LUA_BACKGROUND_SCRIPT,
1938 LUA_BACKGROUND_SCRIPT_PARAMS,
1940#if defined(USE_HTTP2)
1954#if defined(USE_TIMERS)
1962#if defined(USE_TIMERS)
1966#if defined(USE_4_CGI)
1970 CGI3_INTERPRETER_ARGS,
1971#if defined(USE_TIMERS)
1978 CGI4_INTERPRETER_ARGS,
1979#if defined(USE_TIMERS)
2010 LUA_SCRIPT_EXTENSIONS,
2011 LUA_SERVER_PAGE_EXTENSIONS,
2012#if defined(MG_EXPERIMENTAL_INTERFACES)
2016#if defined(USE_DUKTAPE)
2017 DUKTAPE_SCRIPT_EXTENSIONS,
2020#if defined(USE_WEBSOCKET)
2023#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2024 LUA_WEBSOCKET_EXTENSIONS,
2032#if !defined(NO_CACHING)
2060#if defined(__linux__)
2070#if defined(USE_WEBSOCKET)
2080#if defined(USE_HTTP2)
2094#if defined(USE_TIMERS)
2102#if defined(USE_TIMERS)
2106#if defined(USE_4_CGI)
2111#if defined(USE_TIMERS)
2119#if defined(USE_TIMERS)
2134 "index.xhtml,index.html,index.htm,"
2135 "index.lp,index.lsp,index.lua,index.cgi,"
2136 "index.shtml,index.php"},
2138 "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
2166#if defined(MG_EXPERIMENTAL_INTERFACES)
2170#if defined(USE_DUKTAPE)
2176#if defined(USE_WEBSOCKET)
2179#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2187#if !defined(NO_CACHING)
2204 "config_options and enum not sync");
2261#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2263 struct mg_shared_lua_websocket_list *shared_lua_websockets;
2274#if defined(STOP_FLAG_NEEDS_LOCK)
2297 sf = mg_atomic_compare_and_swap(
f, *
f,
v);
2304#define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
2305#define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
2306#define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
2329#if defined(USE_SERVER_STATS)
2330 volatile ptrdiff_t active_connections;
2331 volatile ptrdiff_t max_active_connections;
2332 volatile ptrdiff_t total_connections;
2333 volatile ptrdiff_t total_requests;
2334 volatile int64_t total_data_read;
2335 volatile int64_t total_data_written;
2349#if defined(ALTERNATIVE_QUEUE)
2350 struct socket *client_socks;
2351 void **client_wait_events;
2361#if defined(USE_SERVER_STATS)
2369#if defined(USE_SERVER_STATS)
2370 struct mg_memory_stat ctx_memory;
2378#if defined(USE_TIMERS)
2379 struct ttimers *timers;
2384 void *lua_background_state;
2385 pthread_mutex_t lua_bg_mutex;
2386 int lua_bg_log_available;
2409#if defined(USE_SERVER_STATS)
2410static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2412static struct mg_memory_stat *
2416 return &(ctx->ctx_memory);
2418 return &mg_common_memory;
2435#if defined(USE_HTTP2)
2436#if !defined(HTTP2_DYN_TABLE_SIZE)
2437#define HTTP2_DYN_TABLE_SIZE (256)
2440struct mg_http2_connection {
2442 uint32_t dyn_table_size;
2443 struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
2453#if defined(USE_HTTP2)
2454 struct mg_http2_connection http2;
2463#if defined(USE_SERVER_STATS)
2473#if defined(USE_SERVER_STATS)
2474 time_t conn_close_time;
2476 double processing_time;
2502#if defined(USE_WEBSOCKET)
2503 int in_websocket_handling;
2505#if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
2506 && defined(MG_EXPERIMENTAL_INTERFACES)
2508 int websocket_deflate_server_max_windows_bits;
2509 int websocket_deflate_client_max_windows_bits;
2510 int websocket_deflate_server_no_context_takeover;
2511 int websocket_deflate_client_no_context_takeover;
2512 int websocket_deflate_initialized;
2513 int websocket_deflate_flush;
2514 z_stream websocket_deflate_state;
2515 z_stream websocket_inflate_state;
2530#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2531 void *lua_websocket_state;
2547#define mg_cry_internal(conn, fmt, ...) \
2548 mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
2550#define mg_cry_ctx_internal(ctx, fmt, ...) \
2551 mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
2561#if !defined(NO_THREAD_NAME)
2562#if defined(_WIN32) && defined(_MSC_VER)
2566#pragma pack(push, 8)
2567typedef struct tagTHREADNAME_INFO {
2575#elif defined(__linux__)
2577#include <sys/prctl.h>
2578#include <sys/sendfile.h>
2579#if defined(ALTERNATIVE_QUEUE)
2580#include <sys/eventfd.h>
2584#if defined(ALTERNATIVE_QUEUE)
2589 int evhdl = eventfd(0, EFD_CLOEXEC);
2610event_wait(
void *eventhdl)
2619 evhdl = *(
int *)eventhdl;
2621 s = (
int)read(evhdl, &u,
sizeof(u));
2622 if (s !=
sizeof(u)) {
2632event_signal(
void *eventhdl)
2641 evhdl = *(
int *)eventhdl;
2643 s = (
int)write(evhdl, &u,
sizeof(u));
2644 if (s !=
sizeof(u)) {
2653event_destroy(
void *eventhdl)
2661 evhdl = *(
int *)eventhdl;
2673#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2676 pthread_mutex_t mutex;
2685 struct posix_event *ret =
mg_malloc(
sizeof(
struct posix_event));
2690 if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2695 if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2697 pthread_mutex_destroy(&(ret->mutex));
2707event_wait(
void *eventhdl)
2709 struct posix_event *ev = (
struct posix_event *)eventhdl;
2710 pthread_mutex_lock(&(ev->mutex));
2711 while (!ev->signaled) {
2712 pthread_cond_wait(&(ev->cond), &(ev->mutex));
2715 pthread_mutex_unlock(&(ev->mutex));
2721event_signal(
void *eventhdl)
2723 struct posix_event *ev = (
struct posix_event *)eventhdl;
2724 pthread_mutex_lock(&(ev->mutex));
2725 pthread_cond_signal(&(ev->cond));
2727 pthread_mutex_unlock(&(ev->mutex));
2733event_destroy(
void *eventhdl)
2735 struct posix_event *ev = (
struct posix_event *)eventhdl;
2736 pthread_cond_destroy(&(ev->cond));
2737 pthread_mutex_destroy(&(ev->mutex));
2746 char threadName[16 + 1];
2749 NULL, NULL, threadName,
sizeof(threadName),
"civetweb-%s",
name);
2752#if defined(_MSC_VER)
2755 THREADNAME_INFO info;
2756 info.dwType = 0x1000;
2757 info.szName = threadName;
2758 info.dwThreadID = ~0U;
2761 RaiseException(0x406D1388,
2763 sizeof(info) /
sizeof(ULONG_PTR),
2764 (ULONG_PTR *)&info);
2765 } __except (EXCEPTION_EXECUTE_HANDLER) {
2767#elif defined(__MINGW32__)
2770#elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
2771 && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
2773#if defined(__MACH__)
2775 (void)pthread_setname_np(threadName);
2777 (void)pthread_setname_np(pthread_self(), threadName);
2779#elif defined(__linux__)
2785 (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
2804#define MG_FOPEN_MODE_NONE (0)
2807#define MG_FOPEN_MODE_READ (1)
2810#define MG_FOPEN_MODE_WRITE (2)
2813#define MG_FOPEN_MODE_APPEND (4)
2823 return (fileacc->
fp != NULL);
2827#if !defined(NO_FILESYSTEMS)
2837 const uint8_t *
c = (
const uint8_t *)path;
2840 if ((
c == NULL) || (
c[0] == 0)) {
2851 if ((*
c ==
'>') || (*
c ==
'<') || (*
c ==
'|')) {
2855 if ((*
c ==
'*') || (*
c ==
'?')) {
2906 wchar_t wbuf[UTF16_PATH_MAX];
2907 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
2910 filep->
access.
fp = _wfopen(wbuf, L
"rb");
2913 filep->
access.
fp = _wfopen(wbuf, L
"wb");
2916 filep->
access.
fp = _wfopen(wbuf, L
"ab");
2924 filep->
access.
fp = fopen(path,
"r");
2927 filep->
access.
fp = fopen(path,
"w");
2930 filep->
access.
fp = fopen(path,
"a");
2953 if (fileacc != NULL) {
2954 if (fileacc->
fp != NULL) {
2955 ret = fclose(fileacc->
fp);
2958 memset(fileacc, 0,
sizeof(*fileacc));
2968 for (; *
src !=
'\0' &&
n > 1;
n--) {
2978 return tolower((
unsigned char)*s);
2990 }
while (diff == 0 &&
s1[-1] !=
'\0' && --
len > 0);
3004 }
while (diff == 0 &&
s1[-1] !=
'\0');
3041 size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3043 if (big_len >= small_len) {
3044 for (i = 0; i <= (big_len - small_len); i++) {
3074#if defined(__clang__)
3075#pragma clang diagnostic push
3076#pragma clang diagnostic ignored "-Wformat-nonliteral"
3082 ok = (
n >= 0) && ((
size_t)
n < buflen);
3084#if defined(__clang__)
3085#pragma clang diagnostic pop
3097 "truncating vsnprintf buffer: [%.*s]",
3098 (
int)((buflen > 200) ? 200 : (buflen - 1)),
3100 n = (
int)buflen - 1;
3142 }
else if (!ctx || ctx->
dd.
config[i] == NULL) {
3149#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3161 return (ctx == NULL) ? NULL : ctx->
user_data;
3191 if (const_conn != NULL) {
3221 memset(ports, 0,
sizeof(*ports) * (
size_t)
size);
3251#if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
3252#define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
3264 if (
usa->
sa.sa_family == AF_INET) {
3265 getnameinfo(&
usa->
sa,
3273#if defined(USE_IPV6)
3274 else if (
usa->
sa.sa_family == AF_INET6) {
3275 getnameinfo(&
usa->
sa,
3284#if defined(USE_X_DOM_SOCKET)
3285 else if (
usa->
sa.sa_family == AF_UNIX) {
3296 strncpy(
buf, UNIX_DOMAIN_SOCKET_SERVER_NAME,
len);
3308#if !defined(REENTRANT_TIME)
3311 tm = ((t != NULL) ? gmtime(t) : NULL);
3315 struct tm *tm = &_tm;
3320 strftime(buf, buf_len,
"%a, %d %b %Y %H:%M:%S GMT", tm);
3322 mg_strlcpy(buf,
"Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3323 buf[buf_len - 1] =
'\0';
3332 return (
double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3333 + (
double)(ts_now->tv_sec - ts_before->tv_sec);
3337#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3343#include "external_mg_cry_internal_impl.inl"
3344#elif !defined(NO_FILESYSTEMS)
3362#if defined(GCC_DIAGNOSTIC)
3363#pragma GCC diagnostic push
3364#pragma GCC diagnostic ignored "-Wformat-nonliteral"
3369#if defined(GCC_DIAGNOSTIC)
3370#pragma GCC diagnostic pop
3373 buf[
sizeof(buf) - 1] = 0;
3402 timestamp = time(NULL);
3406 "[%010lu] [error] [client %s] ",
3407 (
unsigned long)timestamp,
3429#error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
3476#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3492#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3499 if (strlen(txt) == 3) {
3500 memcpy(tls->txtbuf, txt, 4);
3502 strcpy(tls->txtbuf,
"ERR");
3507 ((
struct mg_connection *)conn)->request_info.local_uri_raw =
3542#if defined(__clang__)
3543#pragma clang diagnostic push
3544#pragma clang diagnostic ignored "-Wunreachable-code"
3555 ? (ri->
is_ssl ?
"wss" :
"ws")
3556 : (ri->
is_ssl ?
"https" :
"http"));
3560#if defined(__clang__)
3561#pragma clang diagnostic pop
3570 const char *define_proto,
3572 const char *define_uri)
3574 if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3583 (define_uri != NULL)
3586 int port = (define_port > 0) ? define_port : ri->
server_port;
3593#if defined(USE_X_DOM_SOCKET)
3604 const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
3620 if ((0 == strcmp(define_proto,
"https"))
3621 || (0 == strcmp(define_proto,
"wss"))) {
3631#if defined(USE_IPV6)
3632 int is_ipv6 = (conn->
client.
lsa.
sa.sa_family == AF_INET6);
3634 int auth_domain_check_enabled =
3639 const char *server_domain =
3646 sprintf(portstr,
":%u", (
unsigned)port);
3651 if (!auth_domain_check_enabled || !server_domain) {
3657 server_domain = server_ip;
3664#
if defined(USE_IPV6)
3667 (is_ipv6 && (server_domain == server_ip)) ?
"[" :
"",
3669 (is_ipv6 && (server_domain == server_ip)) ?
"]" :
"",
3701 const char *delimiters,
3702 const char *whitespace,
3705 char *
p, *begin_word, *end_word, *end_whitespace;
3708 end_word = begin_word + strcspn(begin_word, delimiters);
3711 if (end_word > begin_word) {
3713 while (*
p == quotechar) {
3720 if (*end_word !=
'\0') {
3721 size_t end_off = strcspn(end_word + 1, delimiters);
3722 memmove(
p, end_word, end_off + 1);
3724 end_word += end_off + 1;
3730 for (
p++;
p < end_word;
p++) {
3735 if (*end_word ==
'\0') {
3739#if defined(GCC_DIAGNOSTIC)
3741#pragma GCC diagnostic push
3742#pragma GCC diagnostic ignored "-Wsign-conversion"
3745 end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
3747#if defined(GCC_DIAGNOSTIC)
3748#pragma GCC diagnostic pop
3751 for (
p = end_word;
p < end_whitespace;
p++) {
3755 *buf = end_whitespace;
3767 for (i = 0; i < num_hdr; i++) {
3769 return hdr[i].
value;
3777#if defined(USE_WEBSOCKET)
3784 int output_max_size)
3850 if (val == NULL || list == NULL || *list ==
'\0') {
3856 while (*list ==
' ' || *list ==
'\t')
3860 if ((list = strchr(val->
ptr,
',')) != NULL) {
3862 val->
len = ((size_t)(list - val->
ptr));
3866 list = val->
ptr + strlen(val->
ptr);
3867 val->
len = ((size_t)(list - val->
ptr));
3872 while (end >= 0 && ((val->
ptr[end] ==
' ') || (val->
ptr[end] ==
'\t')))
3874 val->
len = (size_t)(end) + (size_t)(1);
3876 if (val->
len == 0) {
3881 if (eq_val != NULL) {
3885 eq_val->
ptr = (
const char *)memchr(val->
ptr,
'=', val->
len);
3886 if (eq_val->
ptr != NULL) {
3888 eq_val->
len = ((size_t)(val->
ptr - eq_val->
ptr)) + val->
len;
3889 val->
len = ((size_t)(eq_val->
ptr - val->
ptr)) - 1;
3910 while ((header =
next_option(header, &opt_vec, &eq_vec)) != NULL) {
3924 ptrdiff_t i, j,
len, res;
3926 if ((or_str = (
const char *)memchr(pattern,
'|', pattern_len)) != NULL) {
3927 res =
match_prefix(pattern, (
size_t)(or_str - pattern), str);
3928 return (res > 0) ? res
3930 (
size_t)((pattern + pattern_len)
3935 for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
3936 if ((pattern[i] ==
'?') && (str[j] !=
'\0')) {
3938 }
else if (pattern[i] ==
'$') {
3939 return (str[j] ==
'\0') ? j : -1;
3940 }
else if (pattern[i] ==
'*') {
3942 if (pattern[i] ==
'*') {
3944 len = (ptrdiff_t)strlen(str + j);
3946 len = (ptrdiff_t)strcspn(str + j,
"/");
3948 if (i == (ptrdiff_t)pattern_len) {
3953 (pattern_len - (
size_t)i),
3955 }
while (res == -1 &&
len-- > 0);
3956 return (res == -1) ? -1 : j + res +
len;
3961 return (ptrdiff_t)j;
3968 if (pattern == NULL) {
3981 const char *http_version;
4007 if (http_version && (0 == strcmp(http_version,
"1.1"))) {
4020 if (!conn || !conn->
dom_ctx) {
4031 if (!conn || !conn->
dom_ctx) {
4056 "no-cache, no-store, "
4057 "must-revalidate, private, max-age=0",
4071#if !defined(NO_CACHING)
4075 const char *cache_control =
4079 if (cache_control != NULL) {
4106 conn, NULL, val,
sizeof(val),
"max-age=%lu", (
unsigned long)max_age);
4131 (
unsigned long)max_age);
4137 if (header && header[0]) {
4143#if !defined(NO_FILESYSTEMS)
4157 switch (response_code) {
4162 return "Switching Protocols";
4164 return "Processing";
4174 return "Non-Authoritative Information";
4176 return "No Content";
4178 return "Reset Content";
4180 return "Partial Content";
4182 return "Multi-Status";
4185 return "Already Reported";
4192 return "Multiple Choices";
4194 return "Moved Permanently";
4200 return "Not Modified";
4204 return "Temporary Redirect";
4206 return "Permanent Redirect";
4210 return "Bad Request";
4212 return "Unauthorized";
4214 return "Payment Required";
4220 return "Method Not Allowed";
4222 return "Not Acceptable";
4224 return "Proxy Authentication Required";
4226 return "Request Time-out";
4232 return "Length Required";
4234 return "Precondition Failed";
4236 return "Request Entity Too Large";
4238 return "Request-URI Too Large";
4240 return "Unsupported Media Type";
4242 return "Requested range not satisfiable";
4245 return "Expectation Failed";
4248 return "Misdirected Request";
4250 return "Unproccessable entity";
4255 return "Failed Dependency";
4259 return "Upgrade Required";
4262 return "Precondition Required";
4264 return "Too Many Requests";
4267 return "Request Header Fields Too Large";
4270 return "Unavailable For Legal Reasons";
4275 return "Internal Server Error";
4277 return "Not Implemented";
4279 return "Bad Gateway";
4281 return "Service Unavailable";
4283 return "Gateway Time-out";
4285 return "HTTP Version not supported";
4287 return "Variant Also Negotiates";
4289 return "Insufficient Storage";
4292 return "Loop Detected";
4295 return "Not Extended";
4297 return "Network Authentication Required";
4303 return "I am a teapot";
4305 return "Authentication Timeout";
4307 return "Enhance Your Calm";
4309 return "Login Timeout";
4311 return "Bandwidth Limit Exceeded";
4317 "Unknown HTTP response code: %u",
4322 if (response_code >= 100 && response_code < 200) {
4324 return "Information";
4326 if (response_code >= 200 && response_code < 300) {
4330 if (response_code >= 300 && response_code < 400) {
4332 return "Redirection";
4334 if (response_code >= 400 && response_code < 500) {
4336 return "Client Error";
4338 if (response_code >= 500 && response_code < 600) {
4340 return "Server Error";
4359#if !defined(NO_FILESYSTEMS)
4361 int len, i, page_handler_found, scope, truncated;
4362 const char *error_handler = NULL;
4364 const char *error_page_file_ext, *tstr;
4366 int handled_by_callback = 0;
4368 if ((conn == NULL) || (fmt == NULL)) {
4376 has_body = ((status > 199) && (status != 204) && (status != 304));
4384 mg_vsnprintf(conn, NULL, errmsg_buf,
sizeof(errmsg_buf), fmt, ap);
4387 DEBUG_TRACE(
"Error %i - [%s]", status, errmsg_buf);
4397 handled_by_callback =
4403 if (!handled_by_callback) {
4407 "Recursion when handling error %u - fall back to default",
4409#if !defined(NO_FILESYSTEMS)
4414 page_handler_found = 0;
4416 if (error_handler != NULL) {
4417 for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4423 sizeof(path_buf) - 32,
4434 sizeof(path_buf) - 32,
4443 sizeof(path_buf) - 32,
4458 path_buf[
sizeof(path_buf) - 32] = 0;
4459 len = (
int)strlen(path_buf);
4460 if (
len > (
int)
sizeof(path_buf) - 32) {
4461 len = (
int)
sizeof(path_buf) - 32;
4465 tstr = strchr(error_page_file_ext,
'.');
4469 (i < 32) && (tstr[i] != 0) && (tstr[i] !=
',');
4474 path_buf[
len + i - 1] = tstr[i];
4479 path_buf[
len + i - 1] = 0;
4481 if (
mg_stat(conn, path_buf, &error_page_file.
stat)) {
4484 page_handler_found = 1;
4492 tstr = strchr(tstr + i,
'.');
4497 if (page_handler_found) {
4514 "text/plain; charset=utf-8",
4523 mg_printf(conn,
"Error %d: %s\n", status, status_text);
4524 mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4552 long long content_length)
4563 if (content_length < 0) {
4577 (uint64_t)content_length);
4592 const char *target_url,
4606 const char *redirect_text;
4608 size_t content_len = 0;
4609#if defined(MG_SEND_REDIRECT_BODY)
4614 if (redirect_code == 0) {
4615 redirect_code = 307;
4619 if ((redirect_code != 301) && (redirect_code != 302)
4620 && (redirect_code != 303) && (redirect_code != 307)
4621 && (redirect_code != 308)) {
4630 if ((target_url == NULL) || (*target_url == 0)) {
4634#if defined(MG_SEND_REDIRECT_BODY)
4662 "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4666 content_len = strlen(reply);
4672 "HTTP/1.1 %i %s\r\n"
4674 "Content-Length: %u\r\n"
4675 "Connection: %s\r\n\r\n",
4679 (
unsigned int)content_len,
4682#if defined(MG_SEND_REDIRECT_BODY)
4687 ret =
mg_write(conn, reply, content_len);
4692 return (ret > 0) ? ret : -1;
4699#if defined(GCC_DIAGNOSTIC)
4701#pragma GCC diagnostic push
4702#pragma GCC diagnostic ignored "-Wunused-function"
4707pthread_mutex_init(pthread_mutex_t *mutex,
void *unused)
4711 InitializeCriticalSection(&mutex->sec);
4717pthread_mutex_destroy(pthread_mutex_t *mutex)
4719 DeleteCriticalSection(&mutex->sec);
4725pthread_mutex_lock(pthread_mutex_t *mutex)
4727 EnterCriticalSection(&mutex->sec);
4733pthread_mutex_unlock(pthread_mutex_t *mutex)
4735 LeaveCriticalSection(&mutex->sec);
4746 cv->waiting_thread = NULL;
4754 pthread_mutex_t *mutex,
4760 uint64_t nsnow, nswaitabs;
4764 pthread_mutex_lock(&cv->threadIdSec);
4766 ptls = &cv->waiting_thread;
4767 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
4769 tls->next_waiting_thread = NULL;
4771 pthread_mutex_unlock(&cv->threadIdSec);
4776 (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
4777 nswaitrel = nswaitabs - nsnow;
4778 if (nswaitrel < 0) {
4781 mswaitrel = (DWORD)(nswaitrel / 1000000);
4783 mswaitrel = (DWORD)INFINITE;
4786 pthread_mutex_unlock(mutex);
4788 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
4791 pthread_mutex_lock(&cv->threadIdSec);
4792 ptls = &cv->waiting_thread;
4793 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
4795 *ptls = tls->next_waiting_thread;
4800 pthread_mutex_unlock(&cv->threadIdSec);
4802 WaitForSingleObject(tls->pthread_cond_helper_mutex,
4807 pthread_mutex_lock(mutex);
4817 return pthread_cond_timedwait(cv, mutex, NULL);
4828 pthread_mutex_lock(&cv->threadIdSec);
4829 if (cv->waiting_thread) {
4830 wkup = cv->waiting_thread->pthread_cond_helper_mutex;
4831 cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
4833 ok = SetEvent(wkup);
4836 pthread_mutex_unlock(&cv->threadIdSec);
4846 pthread_mutex_lock(&cv->threadIdSec);
4847 while (cv->waiting_thread) {
4848 pthread_cond_signal(cv);
4850 pthread_mutex_unlock(&cv->threadIdSec);
4860 pthread_mutex_lock(&cv->threadIdSec);
4862 pthread_mutex_unlock(&cv->threadIdSec);
4863 pthread_mutex_destroy(&cv->threadIdSec);
4869#if defined(ALTERNATIVE_QUEUE)
4874 return (
void *)CreateEvent(NULL,
FALSE,
FALSE, NULL);
4880event_wait(
void *eventhdl)
4882 int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
4883 return (res == WAIT_OBJECT_0);
4889event_signal(
void *eventhdl)
4891 return (
int)SetEvent((HANDLE)eventhdl);
4897event_destroy(
void *eventhdl)
4899 CloseHandle((HANDLE)eventhdl);
4904#if defined(GCC_DIAGNOSTIC)
4906#pragma GCC diagnostic pop
4912change_slashes_to_backslashes(
char *path)
4916 for (i = 0; path[i] !=
'\0'; i++) {
4917 if (path[i] ==
'/') {
4923 if ((i > 0) && (path[i] ==
'\\')) {
4924 while ((path[i + 1] ==
'\\') || (path[i + 1] ==
'/')) {
4925 (
void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
4933mg_wcscasecmp(
const wchar_t *
s1,
const wchar_t *s2)
4938 diff = ((*
s1 >=
L'A') && (*
s1 <= L
'Z') ? (*
s1 -
L'A' +
L'a') : *
s1)
4939 - ((*s2 >=
L'A') && (*s2 <=
L'Z') ? (*s2 -
L'A' +
L'a') : *s2);
4942 }
while ((diff == 0) && (
s1[-1] != L
'\0'));
4957 wchar_t wbuf2[UTF16_PATH_MAX + 1];
4958 DWORD long_len, err;
4959 int (*fcompare)(
const wchar_t *,
const wchar_t *) = mg_wcscasecmp;
4962 change_slashes_to_backslashes(buf);
4966 memset(wbuf, 0, wbuf_len *
sizeof(
wchar_t));
4967 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (
int)wbuf_len);
4968 WideCharToMultiByte(
4969 CP_UTF8, 0, wbuf, (
int)wbuf_len, buf2,
sizeof(buf2), NULL, NULL);
4970 if (strcmp(buf, buf2) != 0) {
4994 memset(wbuf2, 0,
ARRAY_SIZE(wbuf2) *
sizeof(
wchar_t));
4995 long_len = GetLongPathNameW(wbuf, wbuf2,
ARRAY_SIZE(wbuf2) - 1);
4996 if (long_len == 0) {
4997 err = GetLastError();
4998 if (err == ERROR_FILE_NOT_FOUND) {
5003 if ((long_len >=
ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5010#if !defined(NO_FILESYSTEMS)
5017 wchar_t wbuf[UTF16_PATH_MAX];
5018 WIN32_FILE_ATTRIBUTE_DATA info;
5019 time_t creation_time;
5025 memset(filep, 0,
sizeof(*filep));
5031 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5036 if ((
len > 0) && (path[
len - 1] !=
' ') && (path[
len - 1] !=
'.')
5037 && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
5038 filep->
size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5040 SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5041 info.ftLastWriteTime.dwHighDateTime);
5047 creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5048 info.ftCreationTime.dwHighDateTime);
5053 filep->
is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5065 wchar_t wbuf[UTF16_PATH_MAX];
5066 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5067 return DeleteFileW(wbuf) ? 0 : -1;
5074 wchar_t wbuf[UTF16_PATH_MAX];
5076 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5077 return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5083#if defined(GCC_DIAGNOSTIC)
5085#pragma GCC diagnostic push
5086#pragma GCC diagnostic ignored "-Wunused-function"
5096 wchar_t wpath[UTF16_PATH_MAX];
5100 SetLastError(ERROR_BAD_ARGUMENTS);
5101 }
else if ((dir = (DIR *)
mg_malloc(
sizeof(*dir))) == NULL) {
5102 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5105 attrs = GetFileAttributesW(wpath);
5106 if ((wcslen(wpath) + 2 <
ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5107 && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5108 (
void)wcscat(wpath, L
"\\*");
5109 dir->handle = FindFirstFileW(wpath, &dir->info);
5110 dir->result.d_name[0] =
'\0';
5129 result = FindClose(dir->handle) ? 0 : -1;
5134 SetLastError(ERROR_BAD_ARGUMENTS);
5142static struct dirent *
5145 struct dirent *
result = 0;
5150 (
void)WideCharToMultiByte(CP_UTF8,
5152 dir->info.cFileName,
5159 if (!FindNextFileW(dir->handle, &dir->info)) {
5160 (
void)FindClose(dir->handle);
5165 SetLastError(ERROR_FILE_NOT_FOUND);
5168 SetLastError(ERROR_BAD_ARGUMENTS);
5175#if !defined(HAVE_POLL)
5187poll(
struct mg_pollfd *pfd,
unsigned int n,
int milliseconds)
5197 memset(&tv, 0,
sizeof(tv));
5198 tv.tv_sec = milliseconds / 1000;
5199 tv.tv_usec = (milliseconds % 1000) * 1000;
5204 for (i = 0; i <
n; i++) {
5205 if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
5206 if (pfd[i].events & POLLIN) {
5207 FD_SET(pfd[i].fd, &rset);
5209 if (pfd[i].events & POLLOUT) {
5210 FD_SET(pfd[i].fd, &wset);
5213 FD_SET(pfd[i].fd, &eset);
5217 if (pfd[i].fd > maxfd) {
5222 if ((
result = select((
int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
5223 for (i = 0; i <
n; i++) {
5224 if (FD_ISSET(pfd[i].fd, &rset)) {
5225 pfd[i].revents |= POLLIN;
5227 if (FD_ISSET(pfd[i].fd, &wset)) {
5228 pfd[i].revents |= POLLOUT;
5230 if (FD_ISSET(pfd[i].fd, &eset)) {
5231 pfd[i].revents |= POLLERR;
5248#if defined(GCC_DIAGNOSTIC)
5250#pragma GCC diagnostic pop
5262 (
void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5269#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5273 return ((_beginthread((
void(__cdecl *)(
void *))
f, USE_STACK_SIZE,
p)
5274 == ((uintptr_t)(-1L)))
5279 (_beginthread((
void(__cdecl *)(
void *))
f, 0,
p) == ((uintptr_t)(-1L)))
5290 pthread_t *threadidptr)
5293 HANDLE threadhandle;
5296 uip = _beginthreadex(NULL, 0,
f,
p, 0, NULL);
5297 threadhandle = (HANDLE)uip;
5298 if ((uip != 0) && (threadidptr != NULL)) {
5299 *threadidptr = threadhandle;
5315 dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5316 if (dwevent == WAIT_FAILED) {
5319 if (dwevent == WAIT_OBJECT_0) {
5320 CloseHandle(threadid);
5328#if !defined(NO_SSL_DL) && !defined(NO_SSL)
5332#if defined(GCC_DIAGNOSTIC)
5334#pragma GCC diagnostic push
5335#pragma GCC diagnostic ignored "-Wunused-function"
5341dlopen(
const char *dll_name,
int flags)
5343 wchar_t wbuf[UTF16_PATH_MAX];
5345 path_to_unicode(NULL, dll_name, wbuf,
ARRAY_SIZE(wbuf));
5346 return LoadLibraryW(wbuf);
5352dlclose(
void *handle)
5356 if (FreeLibrary((HMODULE)handle) != 0) {
5366#if defined(GCC_DIAGNOSTIC)
5368#pragma GCC diagnostic pop
5379kill(pid_t pid,
int sig_num)
5381 (
void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5382 (
void)CloseHandle((HANDLE)pid);
5387#if !defined(WNOHANG)
5393waitpid(pid_t pid,
int *status,
int flags)
5395 DWORD timeout = INFINITE;
5400 if ((flags | WNOHANG) == WNOHANG) {
5404 waitres = WaitForSingleObject((HANDLE)pid, timeout);
5405 if (waitres == WAIT_OBJECT_0) {
5408 if (waitres == WAIT_TIMEOUT) {
5416trim_trailing_whitespaces(
char *s)
5418 char *
e = s + strlen(s);
5419 while ((
e > s) && isspace((
unsigned char)
e[-1])) {
5434 unsigned char cgi_config_idx)
5438 char *interp_arg = 0;
5443 PROCESS_INFORMATION pi = {0};
5447 memset(&si, 0,
sizeof(si));
5450 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5451 si.wShowWindow = SW_HIDE;
5453 me = GetCurrentProcess();
5455 (HANDLE)_get_osfhandle(fdin[0]),
5460 DUPLICATE_SAME_ACCESS);
5462 (HANDLE)_get_osfhandle(fdout[1]),
5467 DUPLICATE_SAME_ACCESS);
5469 (HANDLE)_get_osfhandle(fderr[1]),
5474 DUPLICATE_SAME_ACCESS);
5479 SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5480 HANDLE_FLAG_INHERIT,
5482 SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5483 HANDLE_FLAG_INHERIT,
5485 SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5486 HANDLE_FLAG_INHERIT,
5492 if (interp != NULL) {
5500 buf[0] = buf[1] =
'\0';
5504 conn, &truncated, cmdline,
sizeof(cmdline),
"%s/%s", dir, prog);
5507 pi.hProcess = (pid_t)-1;
5517 buf[
sizeof(buf) - 1] =
'\0';
5520 if ((buf[0] ==
'#') && (buf[1] ==
'!')) {
5521 trim_trailing_whitespaces(buf + 2);
5528 GetFullPathNameA(dir,
sizeof(full_dir), full_dir, NULL);
5530 if (interp[0] !=
'\0') {
5532 if ((interp_arg != 0) && (interp_arg[0] != 0)) {
5537 "\"%s\" %s \"%s\\%s\"",
5547 "\"%s\" \"%s\\%s\"",
5564 pi.hProcess = (pid_t)-1;
5569 if (CreateProcessA(NULL,
5574 CREATE_NEW_PROCESS_GROUP,
5581 conn,
"%s: CreateProcess(%s): %ld", __func__, cmdline, (
long)
ERRNO);
5582 pi.hProcess = (pid_t)-1;
5587 (
void)CloseHandle(si.hStdOutput);
5588 (
void)CloseHandle(si.hStdError);
5589 (
void)CloseHandle(si.hStdInput);
5590 if (pi.hThread != NULL) {
5591 (
void)CloseHandle(pi.hThread);
5594 return (pid_t)pi.hProcess;
5602 unsigned long non_blocking = 0;
5603 return ioctlsocket(sock, (
long)FIONBIO, &non_blocking);
5610 unsigned long non_blocking = 1;
5611 return ioctlsocket(sock, (
long)FIONBIO, &non_blocking);
5618#if !defined(NO_FILESYSTEMS)
5628 memset(filep, 0,
sizeof(*filep));
5634 if (0 == stat(path, &st)) {
5635 filep->
size = (uint64_t)(st.st_size);
5651#if defined(__ZEPHYR__)
5656 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5660 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5672 pthread_t thread_id;
5673 pthread_attr_t
attr;
5676 (void)pthread_attr_init(&
attr);
5677 (void)pthread_attr_setdetachstate(&
attr, PTHREAD_CREATE_DETACHED);
5679#if defined(__ZEPHYR__)
5680 pthread_attr_setstack(&
attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
5681#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5684 (void)pthread_attr_setstacksize(&
attr, USE_STACK_SIZE);
5687 result = pthread_create(&thread_id, &
attr, func, param);
5688 pthread_attr_destroy(&
attr);
5698 pthread_t *threadidptr)
5700 pthread_t thread_id;
5701 pthread_attr_t
attr;
5704 (void)pthread_attr_init(&
attr);
5706#if defined(__ZEPHYR__)
5707 pthread_attr_setstack(&
attr,
5708 &civetweb_worker_stacks[zephyr_worker_stack_index++],
5710#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5713 (void)pthread_attr_setstacksize(&
attr, USE_STACK_SIZE);
5716 result = pthread_create(&thread_id, &
attr, func, param);
5717 pthread_attr_destroy(&
attr);
5718 if ((
result == 0) && (threadidptr != NULL)) {
5719 *threadidptr = thread_id;
5731 result = pthread_join(threadid, NULL);
5746 unsigned char cgi_config_idx)
5753 if ((pid = fork()) == -1) {
5756 }
else if (pid != 0) {
5764 if (chdir(dir) != 0) {
5766 conn,
"%s: chdir(%s): %s", __func__, dir, strerror(
ERRNO));
5767 }
else if (dup2(fdin[0], 0) == -1) {
5769 "%s: dup2(%d, 0): %s",
5773 }
else if (dup2(fdout[1], 1) == -1) {
5775 "%s: dup2(%d, 1): %s",
5779 }
else if (dup2(fderr[1], 2) == -1) {
5781 "%s: dup2(%d, 2): %s",
5786 struct sigaction sa;
5791 (void)close(fdin[0]);
5792 (void)close(fdout[1]);
5793 (void)close(fderr[1]);
5796 (void)close(fdin[1]);
5797 (void)close(fdout[0]);
5798 (void)close(fderr[0]);
5805 memset(&sa, 0,
sizeof(sa));
5806 sa.sa_handler = SIG_DFL;
5807 sigaction(SIGCHLD, &sa, NULL);
5810 if (interp == NULL) {
5812 (void)execle(prog, prog, NULL, envp);
5814 "%s: execle(%s): %s",
5820 const char *interp_args =
5824 if ((interp_args != NULL) && (interp_args[0] != 0)) {
5825 (void)execle(interp, interp, interp_args, prog, NULL, envp);
5827 (void)execle(interp, interp, prog, NULL, envp);
5830 "%s: execle(%s %s): %s",
5848 int flags = fcntl(sock, F_GETFL, 0);
5853 if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
5862 int flags = fcntl(sock, F_GETFL, 0);
5867 if (fcntl(sock, F_SETFL, flags & (~(
int)(O_NONBLOCK))) < 0) {
5881 static uint64_t lfsr = 0;
5882 static uint64_t lcg = 0;
5893 | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
5895 lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
5903 return (lfsr ^ lcg ^ now);
5918 int check_pollerr = 0;
5919 if ((
n == 1) && ((pfd[0].events & POLLERR) == 0)) {
5921 pfd[0].events |= POLLERR;
5933 if ((milliseconds >= 0) && (milliseconds < ms_now)) {
5934 ms_now = milliseconds;
5937 result = poll(pfd,
n, ms_now);
5942 && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
5951 if (milliseconds > 0) {
5952 milliseconds -= ms_now;
5955 }
while (milliseconds > 0);
5978 uint64_t start = 0, now = 0, timeout_ns = 0;
5985 typedef size_t len_t;
5991 timeout_ns = (uint64_t)(timeout * 1.0E9);
5998#if defined(NO_SSL) && !defined(USE_MBEDTLS)
6008#if defined(USE_MBEDTLS)
6010 n = mbed_ssl_write(ssl, (
const unsigned char *)buf,
len);
6012 if ((
n == MBEDTLS_ERR_SSL_WANT_READ)
6013 || (
n == MBEDTLS_ERR_SSL_WANT_WRITE)
6014 ||
n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6017 fprintf(stderr,
"SSL write failed, error %d\n",
n);
6024#elif !defined(NO_SSL)
6027 n = SSL_write(ssl, buf,
len);
6029 err = SSL_get_error(ssl,
n);
6048 n = (
int)fwrite(buf, 1, (
size_t)
len, fp);
6057 err = (
n < 0) ?
ERRNO : 0;
6059 if (err == WSAEWOULDBLOCK) {
6079 if ((
n > 0) || ((
n == 0) && (
len == 0))) {
6109 pfd[0].events = POLLOUT;
6121 if ((now - start) > timeout_ns) {
6143 double timeout = -1.0;
6144 int n, nwritten = 0;
6153 if (timeout <= 0.0) {
6159 n =
push_inner(ctx, fp, sock, ssl, buf + nwritten,
len, timeout);
6161 if (nwritten == 0) {
6165 }
else if (
n == 0) {
6195 typedef size_t len_t;
6208 nread = (
int)read(fileno(fp), buf, (size_t)
len);
6210 err = (nread < 0) ?
ERRNO : 0;
6211 if ((nread == 0) && (
len > 0)) {
6216#if defined(USE_MBEDTLS)
6217 }
else if (conn->
ssl != NULL) {
6222 to_read = mbedtls_ssl_get_bytes_avail(conn->
ssl);
6234 pfd[0].events = POLLIN;
6240 (
int)(timeout * 1000.0),
6249 nread = mbed_ssl_read(conn->
ssl, (
unsigned char *)buf, to_read);
6251 if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
6252 || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
6253 || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6256 fprintf(stderr,
"SSL read failed, error %d\n", nread);
6263 }
else if (pollres < 0) {
6271#elif !defined(NO_SSL)
6272 }
else if (conn->
ssl != NULL) {
6277 if ((ssl_pending = SSL_pending(conn->
ssl)) > 0) {
6281 if (ssl_pending >
len) {
6287 pfd[0].events = POLLIN;
6290 (
int)(timeout * 1000.0),
6299 SSL_read(conn->
ssl, buf, (ssl_pending > 0) ? ssl_pending :
len);
6301 err = SSL_get_error(conn->
ssl, nread);
6317 }
else if (pollres < 0) {
6331 pfd[0].events = POLLIN;
6334 (
int)(timeout * 1000.0),
6341 err = (nread < 0) ?
ERRNO : 0;
6346 }
else if (pollres < 0) {
6359 if ((nread > 0) || ((nread == 0) && (
len == 0))) {
6367 if (err == WSAEWOULDBLOCK) {
6371 }
else if (err == WSAETIMEDOUT) {
6375 }
else if (err == WSAECONNABORTED) {
6416 double timeout = -1.0;
6417 uint64_t start_time = 0, now = 0, timeout_ns = 0;
6422 if (timeout <= 0.0) {
6427 timeout_ns = (uint64_t)(timeout * 1.0E9);
6436 }
else if (
n == -1) {
6438 if (timeout >= 0.0) {
6440 if ((now - start_time) <= timeout_ns) {
6445 }
else if (
n == 0) {
6462 while (
mg_read(conn, buf,
sizeof(buf)) > 0)
6470 int64_t content_len,
n, buffered_len, nread;
6472 (int64_t)((
len > INT_MAX) ? INT_MAX :
len);
6484 if (content_len < 0) {
6493 if (left_to_read < len64) {
6497 len64 = left_to_read;
6503 if (buffered_len > 0) {
6504 if (len64 < buffered_len) {
6505 buffered_len = len64;
6508 memcpy(buf, body, (
size_t)buffered_len);
6509 len64 -= buffered_len;
6511 nread += buffered_len;
6512 buf = (
char *)buf + buffered_len;
6518 if ((
n =
pull_all(NULL, conn, (
char *)buf, (
int)len64)) >= 0) {
6522 nread = ((nread > 0) ? nread :
n);
6538#if defined(USE_SERVER_STATS)
6539 struct timespec tnow;
6540 conn->conn_state = 4;
6546#if defined(USE_SERVER_STATS)
6547 conn->conn_state = 5;
6549 clock_gettime(CLOCK_MONOTONIC, &tnow);
6553 mg_atomic_add64(&(conn->
phys_ctx->total_data_written),
6567#if defined(USE_HTTP2)
6569#error "HTTP2 requires ALPN, APLN requires SSL/TLS"
6572#include "mod_http2.inl"
6576 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
6577 http2_must_use_http1(conn); \
6589 if (
len > INT_MAX) {
6598 size_t all_read = 0;
6620 all_read += (size_t)read_ret;
6621 len -= (size_t)read_ret;
6629 || (
x[1] !=
'\n')) {
6641 unsigned long chunkSize = 0;
6643 for (i = 0; i < (
sizeof(lenbuf) - 1); i++) {
6648 if ((i > 0) && (lenbuf[i] ==
'\r')
6649 && (lenbuf[i - 1] !=
'\r')) {
6652 if ((i > 1) && (lenbuf[i] ==
'\n')
6653 && (lenbuf[i - 1] ==
'\r')) {
6655 chunkSize = strtoul(lenbuf, &end, 16);
6656 if (chunkSize == 0) {
6662 if (!isxdigit((
unsigned char)lenbuf[i])) {
6668 if ((end == NULL) || (*end !=
'\r')) {
6673 if (chunkSize == 0) {
6677 && (lenbuf[0] ==
'\r') && (lenbuf[1] ==
'\n')) {
6688 return (
int)all_read;
6703 if (
len > INT_MAX) {
6709#if defined(USE_HTTP2)
6711 http2_data_frame_head(conn,
len, 0);
6721 if (allowed > (
int)
len) {
6732 if (
total == allowed) {
6734 buf = (
const char *)buf +
total;
6755 buf = (
const char *)buf +
n;
6778 unsigned int chunk_len)
6786 sprintf(lenbuf,
"%x\r\n", chunk_len);
6787 lenbuf_len = strlen(lenbuf);
6790 ret =
mg_write(conn, lenbuf, lenbuf_len);
6791 if (ret != (
int)lenbuf_len) {
6796 ret =
mg_write(conn, chunk, chunk_len);
6797 if (ret != (
int)chunk_len) {
6812#if defined(GCC_DIAGNOSTIC)
6815#pragma GCC diagnostic push
6816#pragma GCC diagnostic ignored "-Wformat-nonliteral"
6843 (*buf)[
size - 1] = 0;
6857 size_t prealloc_size,
6883 }
else if ((
size_t)(
len) >= prealloc_size) {
6904 *out_buf = prealloc_buf;
6911#if defined(GCC_DIAGNOSTIC)
6913#pragma GCC diagnostic pop
6954 int is_form_url_encoded)
6957#define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
6959 for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
6960 if ((i < src_len - 2) && (
src[i] ==
'%')
6961 && isxdigit((
unsigned char)
src[i + 1])
6962 && isxdigit((
unsigned char)
src[i + 2])) {
6963 a = tolower((
unsigned char)
src[i + 1]);
6964 b = tolower((
unsigned char)
src[i + 2]);
6967 }
else if (is_form_url_encoded && (
src[i] ==
'+')) {
6976 return (i >= src_len) ? j : -1;
6984 int len = (
int)strlen(buf);
7008 const char *
p, *
e, *s;
7012 if ((dst == NULL) || (dst_len == 0)) {
7014 }
else if ((
data == NULL) || (
name == NULL) || (data_len == 0)) {
7018 name_len = strlen(
name);
7019 e =
data + data_len;
7024 for (
p =
data;
p + name_len <
e;
p++) {
7025 if (((
p ==
data) || (
p[-1] ==
'&')) && (
p[name_len] ==
'=')
7031 s = (
const char *)memchr(
p,
'&', (
size_t)(
e -
p));
7061 unsigned num_form_fields)
7072 if ((form_fields == NULL) && (num_form_fields == 0)) {
7088 if ((form_fields == NULL) || ((
int)num_form_fields <= 0)) {
7093 for (i = 0; i < (
int)num_form_fields; i++) {
7095 while ((*
data ==
' ') || (*
data ==
'\t')) {
7107 while ((*
b != 0) && (*
b !=
'&') && (*
b !=
'=')) {
7113 form_fields[num].
value = NULL;
7114 }
else if (*
b ==
'&') {
7116 form_fields[num].
value = NULL;
7129 b = strchr(
data,
'&');
7142 for (i = 0; i < num; i++) {
7143 if (form_fields[i].
name) {
7146 if (form_fields[i].
value) {
7159 const char *var_name,
7163 const char *s, *
p, *end;
7164 int name_len,
len = -1;
7166 if ((dst == NULL) || (dst_size == 0)) {
7171 if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
7175 name_len = (
int)strlen(var_name);
7176 end = s + strlen(s);
7177 for (; (s =
mg_strcasestr(s, var_name)) != NULL; s += name_len) {
7178 if (s[name_len] ==
'=') {
7180 if ((s == cookie_header) || (s[-1] ==
' ')) {
7182 if ((
p = strchr(s,
' ')) == NULL) {
7188 if ((*s ==
'"') && (
p[-1] ==
'"') && (
p > s + 1)) {
7192 if ((
size_t)(
p - s) < dst_size) {
7206#if defined(USE_WEBSOCKET) || defined(USE_LUA)
7208base64_encode(
const unsigned char *
src,
int src_len,
char *dst)
7210 static const char *b64 =
7211 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7214 for (i = j = 0; i < src_len; i += 3) {
7216 b = ((i + 1) >= src_len) ? 0 :
src[i + 1];
7217 c = ((i + 2) >= src_len) ? 0 :
src[i + 2];
7219 dst[j++] = b64[
a >> 2];
7220 dst[j++] = b64[((
a & 3) << 4) | (
b >> 4)];
7221 if (i + 1 < src_len) {
7222 dst[j++] = b64[(
b & 15) << 2 | (
c >> 6)];
7224 if (i + 2 < src_len) {
7225 dst[j++] = b64[
c & 63];
7228 while (j % 4 != 0) {
7238b64reverse(
char letter)
7240 if ((letter >=
'A') && (letter <=
'Z')) {
7241 return letter -
'A';
7243 if ((letter >=
'a') && (letter <=
'z')) {
7244 return letter -
'a' + 26;
7246 if ((letter >=
'0') && (letter <=
'9')) {
7247 return letter -
'0' + 52;
7249 if (letter ==
'+') {
7252 if (letter ==
'/') {
7255 if (letter ==
'=') {
7263base64_decode(
const unsigned char *
src,
int src_len,
char *dst,
size_t *dst_len)
7266 unsigned char a,
b,
c,
d;
7270 for (i = 0; i < src_len; i += 4) {
7271 a = b64reverse(
src[i]);
7276 b = b64reverse(((i + 1) >= src_len) ? 0 :
src[i + 1]);
7281 c = b64reverse(((i + 2) >= src_len) ? 0 :
src[i + 2]);
7286 d = b64reverse(((i + 3) >= src_len) ? 0 :
src[i + 3]);
7291 dst[(*dst_len)++] = (
a << 2) + (
b >> 4);
7293 dst[(*dst_len)++] = (
b << 4) + (
c >> 2);
7295 dst[(*dst_len)++] = (
c << 6) +
d;
7310 && (!strcmp(s,
"PUT") || !strcmp(s,
"DELETE")
7311 || !strcmp(s,
"MKCOL") || !strcmp(s,
"PATCH"));
7317#if !defined(NO_FILES)
7325 unsigned char cgi_config_idx, inc, max;
7335#if defined(USE_DUKTAPE)
7345 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
7395 struct vec filename_vec;
7396 size_t n = strlen(path);
7402 while ((
n > 0) && (path[
n - 1] ==
'/')) {
7409 while ((list =
next_option(list, &filename_vec, NULL)) != NULL) {
7411 if ((filename_vec.
len + 1) > (path_len - (
n + 1))) {
7419 if (
mg_stat(conn, path, filestat)) {
7439 size_t filename_buf_len,
7442 int *is_script_resource,
7443 int *is_websocket_request,
7444 int *is_put_or_delete_request,
7445 int *is_template_text
7448 char const *accept_encoding;
7450#if !defined(NO_FILES)
7453 const char *rewrite;
7455 ptrdiff_t match_len;
7458#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7460 size_t tmp_str_len, sep_pos;
7461 int allow_substitute_script_subresources;
7464 (void)filename_buf_len;
7468 memset(filestat, 0,
sizeof(*filestat));
7471 *is_script_resource = 0;
7472 *is_template_text = 0;
7479#if defined(USE_WEBSOCKET)
7481#if !defined(NO_FILES)
7482 if (*is_websocket_request && conn->
dom_ctx->
config[WEBSOCKET_ROOT]) {
7487 *is_websocket_request = 0;
7492 if ((accept_encoding =
mg_get_header(conn,
"Accept-Encoding")) != NULL) {
7493 if (strstr(accept_encoding,
"gzip") != NULL) {
7498#if !defined(NO_FILES)
7515 conn, &truncated,
filename, filename_buf_len - 1,
"%s%s", root, uri);
7518 goto interpret_cleanup;
7528 filename_buf_len - 1,
7538 goto interpret_cleanup;
7545 int uri_len = (
int)strlen(uri);
7546 int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] ==
'/');
7564 *is_script_resource = (!*is_put_or_delete_request);
7574 *is_template_text = (!*is_put_or_delete_request);
7583 memset(&tmp_filestat, 0,
sizeof(tmp_filestat));
7586 conn,
filename, filename_buf_len, &tmp_filestat)) {
7590 *filestat = tmp_filestat;
7594 *is_script_resource = 1;
7597 *is_template_text = 1;
7600 *is_script_resource = 0;
7619 conn, &truncated, gz_path,
sizeof(gz_path),
"%s.gz",
filename);
7622 goto interpret_cleanup;
7625 if (
mg_stat(conn, gz_path, filestat)) {
7635#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7643 goto interpret_cleanup;
7645 memcpy(tmp_str,
filename, tmp_str_len + 1);
7648 allow_substitute_script_subresources =
7652 sep_pos = tmp_str_len;
7653 while (sep_pos > 0) {
7655 if (tmp_str[sep_pos] ==
'/') {
7656 int is_script = 0, does_exist = 0;
7658 tmp_str[sep_pos] = 0;
7661 does_exist =
mg_stat(conn, tmp_str, filestat);
7664 if (does_exist && is_script) {
7668 strlen(
filename + sep_pos + 1) + 1);
7671 *is_script_resource = 1;
7676 if (allow_substitute_script_subresources) {
7683 size_t script_name_len = strlen(tmp_str);
7687 char *subres_name =
filename + sep_pos;
7688 size_t subres_name_len = strlen(subres_name);
7690 DEBUG_TRACE(
"Substitute script %s serving path %s",
7695 if ((script_name_len + subres_name_len + 2)
7696 >= filename_buf_len) {
7698 goto interpret_cleanup;
7703 memmove(conn->
path_info, subres_name, subres_name_len);
7705 memcpy(
filename, tmp_str, script_name_len + 1);
7707 *is_script_resource = 1;
7720 *is_script_resource = 0;
7727 tmp_str[sep_pos] =
'/';
7737#if !defined(NO_FILES)
7740 memset(filestat, 0,
sizeof(*filestat));
7743 *is_script_resource = 0;
7744 *is_websocket_request = 0;
7745 *is_put_or_delete_request = 0;
7758 for (i = 0; i < buflen; i++) {
7760 const unsigned char c = (
unsigned char)buf[i];
7762 if ((
c < 128) && ((char)
c !=
'\r') && ((char)
c !=
'\n')
7768 if (i < buflen - 1) {
7769 if ((buf[i] ==
'\n') && (buf[i + 1] ==
'\n')) {
7776 if (i < buflen - 3) {
7777 if ((buf[i] ==
'\r') && (buf[i + 1] ==
'\n') && (buf[i + 2] ==
'\r')
7778 && (buf[i + 3] ==
'\n')) {
7789#if !defined(NO_CACHING)
7810 char month_str[32] = {0};
7811 int second, minute, hour, day, month, year;
7812 time_t
result = (time_t)0;
7815 if ((sscanf(datetime,
7816 "%d/%3s/%d %d:%d:%d",
7824 || (sscanf(datetime,
7825 "%d %3s %d %d:%d:%d",
7833 || (sscanf(datetime,
7834 "%*3s, %d %3s %d %d:%d:%d",
7842 || (sscanf(datetime,
7843 "%d-%3s-%d %d:%d:%d",
7852 if ((month >= 0) && (year >= 1970)) {
7853 memset(&tm, 0,
sizeof(tm));
7854 tm.tm_year = year - 1900;
7877 char *out_end = inout;
7910 if (!strncmp(in,
"../", 3)) {
7912 }
else if (!strncmp(in,
"./", 2)) {
7921 else if (!strncmp(in,
"/./", 3)) {
7923 }
else if (!strcmp(in,
"/.")) {
7934 else if (!strncmp(in,
"/../", 4)) {
7936 if (inout != out_end) {
7940 }
while ((inout != out_end) && (*out_end !=
'/'));
7942 }
else if (!strcmp(in,
"/..")) {
7944 if (inout != out_end) {
7948 }
while ((inout != out_end) && (*out_end !=
'/'));
7956 else if (!strcmp(in,
".") || !strcmp(in,
"..")) {
7971 }
while ((*in != 0) && (*in !=
'/'));
7987 out_end = in = inout;
7991 char *in_ahead = in;
7994 }
while (*in_ahead ==
'.');
7995 if (*in_ahead ==
'/') {
7997 if ((out_end != inout) && (out_end[-1] ==
'/')) {
8001 }
else if (*in_ahead == 0) {
8007 }
while (in != in_ahead);
8009 }
else if (*in ==
'/') {
8014 }
while (*in ==
'/');
8024static const struct {
8032 {
".bin", 4,
"application/octet-stream"},
8033 {
".deb", 4,
"application/octet-stream"},
8034 {
".dmg", 4,
"application/octet-stream"},
8035 {
".dll", 4,
"application/octet-stream"},
8036 {
".doc", 4,
"application/msword"},
8037 {
".eps", 4,
"application/postscript"},
8038 {
".exe", 4,
"application/octet-stream"},
8039 {
".iso", 4,
"application/octet-stream"},
8040 {
".js", 3,
"application/javascript"},
8041 {
".json", 5,
"application/json"},
8042 {
".msi", 4,
"application/octet-stream"},
8043 {
".pdf", 4,
"application/pdf"},
8044 {
".ps", 3,
"application/postscript"},
8045 {
".rtf", 4,
"application/rtf"},
8046 {
".xhtml", 6,
"application/xhtml+xml"},
8047 {
".xsl", 4,
"application/xml"},
8048 {
".xslt", 5,
"application/xml"},
8051 {
".ttf", 4,
"application/font-sfnt"},
8052 {
".cff", 4,
"application/font-sfnt"},
8053 {
".otf", 4,
"application/font-sfnt"},
8054 {
".aat", 4,
"application/font-sfnt"},
8055 {
".sil", 4,
"application/font-sfnt"},
8056 {
".pfr", 4,
"application/font-tdpfr"},
8057 {
".woff", 5,
"application/font-woff"},
8058 {
".woff2", 6,
"application/font-woff2"},
8061 {
".mp3", 4,
"audio/mpeg"},
8062 {
".oga", 4,
"audio/ogg"},
8063 {
".ogg", 4,
"audio/ogg"},
8066 {
".gif", 4,
"image/gif"},
8067 {
".ief", 4,
"image/ief"},
8068 {
".jpeg", 5,
"image/jpeg"},
8069 {
".jpg", 4,
"image/jpeg"},
8070 {
".jpm", 4,
"image/jpm"},
8071 {
".jpx", 4,
"image/jpx"},
8072 {
".png", 4,
"image/png"},
8073 {
".svg", 4,
"image/svg+xml"},
8074 {
".tif", 4,
"image/tiff"},
8075 {
".tiff", 5,
"image/tiff"},
8078 {
".wrl", 4,
"model/vrml"},
8081 {
".css", 4,
"text/css"},
8082 {
".csv", 4,
"text/csv"},
8083 {
".htm", 4,
"text/html"},
8084 {
".html", 5,
"text/html"},
8085 {
".sgm", 4,
"text/sgml"},
8086 {
".shtm", 5,
"text/html"},
8087 {
".shtml", 6,
"text/html"},
8088 {
".txt", 4,
"text/plain"},
8089 {
".xml", 4,
"text/xml"},
8092 {
".mov", 4,
"video/quicktime"},
8093 {
".mp4", 4,
"video/mp4"},
8094 {
".mpeg", 5,
"video/mpeg"},
8095 {
".mpg", 4,
"video/mpeg"},
8096 {
".ogv", 4,
"video/ogg"},
8097 {
".qt", 3,
"video/quicktime"},
8102 {
".arj", 4,
"application/x-arj-compressed"},
8103 {
".gz", 3,
"application/x-gunzip"},
8104 {
".rar", 4,
"application/x-arj-compressed"},
8105 {
".swf", 4,
"application/x-shockwave-flash"},
8106 {
".tar", 4,
"application/x-tar"},
8107 {
".tgz", 4,
"application/x-tar-gz"},
8108 {
".torrent", 8,
"application/x-bittorrent"},
8109 {
".ppt", 4,
"application/x-mspowerpoint"},
8110 {
".xls", 4,
"application/x-msexcel"},
8111 {
".zip", 4,
"application/x-zip-compressed"},
8115 {
".flac", 5,
"audio/flac"},
8116 {
".aif", 4,
"audio/x-aif"},
8117 {
".m3u", 4,
"audio/x-mpegurl"},
8118 {
".mid", 4,
"audio/x-midi"},
8119 {
".ra", 3,
"audio/x-pn-realaudio"},
8120 {
".ram", 4,
"audio/x-pn-realaudio"},
8121 {
".wav", 4,
"audio/x-wav"},
8122 {
".bmp", 4,
"image/bmp"},
8123 {
".ico", 4,
"image/x-icon"},
8124 {
".pct", 4,
"image/x-pct"},
8125 {
".pict", 5,
"image/pict"},
8126 {
".rgb", 4,
"image/x-rgb"},
8127 {
".webm", 5,
"video/webm"},
8128 {
".asf", 4,
"video/x-ms-asf"},
8129 {
".avi", 4,
"video/x-msvideo"},
8130 {
".m4v", 4,
"video/x-m4v"},
8140 path_len = strlen(path);
8150 return "text/plain";
8159 struct vec ext_vec, mime_vec;
8160 const char *list, *ext;
8163 path_len = strlen(path);
8165 if ((conn == NULL) || (
vec == NULL)) {
8167 memset(
vec,
'\0',
sizeof(
struct vec));
8175 while ((list =
next_option(list, &ext_vec, &mime_vec)) != NULL) {
8177 ext = path + path_len - ext_vec.
len;
8194 static const char *hex =
"0123456789abcdef";
8196 for (;
len--;
p++) {
8197 *to++ = hex[
p[0] >> 4];
8198 *to++ = hex[
p[0] & 0x0f];
8217 while ((
p = va_arg(ap,
const char *)) != NULL) {
8223 bin2str(buf, hash,
sizeof(hash));
8237 const char *response)
8239 char ha2[32 + 1], expected_response[32 + 1];
8242 if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
8243 || (qop == NULL) || (response == NULL)) {
8248 if (strlen(response) != 32) {
8252 mg_md5(ha2, method,
":", uri, NULL);
8253 mg_md5(expected_response,
8271#if !defined(NO_FILESYSTEMS)
8279 if ((conn != NULL) && (conn->
dom_ctx != NULL)) {
8285 if (gpass != NULL) {
8319 for (
p = path,
e =
p + strlen(
p) - 1;
e >
p;
e--) {
8361 const char *auth_header;
8368 (void)memset(
ah, 0,
sizeof(*
ah));
8369 if (((auth_header =
mg_get_header(conn,
"Authorization")) == NULL)
8375 (void)
mg_strlcpy(buf, auth_header + 7, buf_size);
8381 while (isspace((
unsigned char)*s)) {
8397 if (*
name ==
'\0') {
8401 if (!strcmp(
name,
"username")) {
8403 }
else if (!strcmp(
name,
"cnonce")) {
8405 }
else if (!strcmp(
name,
"response")) {
8407 }
else if (!strcmp(
name,
"uri")) {
8409 }
else if (!strcmp(
name,
"qop")) {
8411 }
else if (!strcmp(
name,
"nc")) {
8413 }
else if (!strcmp(
name,
"nonce")) {
8418#if !defined(NO_NONCE_CHECK)
8424 nonce = strtoull(
ah->
nonce, &s, 10);
8425 if ((s == NULL) || (*s != 0)) {
8487#define INITIAL_DEPTH 9
8488#if INITIAL_DEPTH <= 0
8489#error Bad INITIAL_DEPTH for recursion, set to at least 1
8492#if !defined(NO_FILESYSTEMS)
8509 int is_authorized = 0;
8513 if (!filep || !workdata || (0 == depth)) {
8518 while (
mg_fgets(workdata->
buf,
sizeof(workdata->
buf), filep) != NULL) {
8519 l = strlen(workdata->
buf);
8521 if (isspace((
unsigned char)workdata->
buf[
l - 1])
8522 || iscntrl((
unsigned char)workdata->
buf[
l - 1])) {
8524 workdata->
buf[
l] = 0;
8534 if (workdata->
f_user[0] ==
':') {
8538 if (workdata->
f_user[1] ==
'#') {
8541 }
else if (!strncmp(workdata->
f_user + 1,
"include=", 8)) {
8554 if (is_authorized) {
8555 return is_authorized;
8559 "%s: cannot open authorization file: %s",
8568 "%s: syntax error in authorization file: %s",
8577 "%s: syntax error in authorization file: %s",
8586 if (workdata->
f_ha1 == NULL) {
8588 "%s: syntax error in authorization file: %s",
8593 *(
char *)(workdata->
f_ha1) = 0;
8594 (workdata->
f_ha1)++;
8609 return is_authorized;
8624 memset(&workdata, 0,
sizeof(workdata));
8670#if !defined(NO_FILESYSTEMS)
8672 struct vec uri_vec, filename_vec;
8675 int authorized = 1, truncated;
8677 if (!conn || !conn->
dom_ctx) {
8682 while ((list =
next_option(list, &uri_vec, &filename_vec)) != NULL) {
8689 (
int)filename_vec.
len,
8695 "%s: cannot open %s: %s",
8709 authorized =
authorize(conn, &file, NULL);
8753 "Digest qop=\"auth\", realm=\"%s\", "
8783#if !defined(NO_FILES)
8792 if (passfile != NULL
8813 char line[512], u[512] =
"",
d[512] =
"", ha1buf[33],
8821 if ((pass != NULL) && (pass[0] ==
'\0')) {
8826 if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
8833 if (strchr(user,
':') != NULL) {
8836 if (strchr(domain,
':') != NULL) {
8842 for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
8843 if (iscntrl((
unsigned char)user[i])) {
8850 for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
8851 if (iscntrl((
unsigned char)domain[i])) {
8866 strcat(tmp,
".tmp");
8870 if ((fp = fopen(fname,
"a+")) != NULL) {
8875 if ((fp = fopen(fname,
"r")) == NULL) {
8877 }
else if ((fp2 = fopen(tmp,
"w+")) == NULL) {
8883 while (fgets(
line,
sizeof(
line), fp) != NULL) {
8884 if (sscanf(
line,
"%255[^:]:%255[^:]:%*s", u,
d) != 2) {
8890 if (!strcmp(u, user) && !strcmp(
d, domain)) {
8893 mg_md5(ha1buf, user,
":", domain,
":", pass, NULL);
8894 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1buf);
8895 }
else if (ha1 != NULL) {
8896 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1);
8899 fprintf(fp2,
"%s",
line);
8906 mg_md5(ha1buf, user,
":", domain,
":", pass, NULL);
8907 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1buf);
8908 }
else if (ha1 != NULL) {
8909 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1);
8948 return (port <= 0xffff);
8955 struct addrinfo hints, *res, *ressave;
8959 memset(&hints, 0,
sizeof(
struct addrinfo));
8960 hints.ai_family = af;
8962 hints.ai_flags = AI_NUMERICHOST;
8965 gai_ret = getaddrinfo(
src, NULL, &hints, &res);
8980 if ((dstlen >= (
size_t)res->ai_addrlen)
8981 && (res->ai_addr->sa_family == af)) {
8982 memcpy(dst, res->ai_addr, res->ai_addrlen);
8988 freeaddrinfo(ressave);
9009 memset(sa, 0,
sizeof(*sa));
9025#if defined(USE_X_DOM_SOCKET)
9028 size_t hostlen = strlen(host);
9029 if (hostlen >=
sizeof(sa->sun.sun_path)) {
9035 "host length exceeds limit");
9050#if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
9051#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
9052 if (use_ssl && (TLS_client_method == NULL)) {
9058 "SSL is not initialized");
9062 if (use_ssl && (SSLv23_client_method == NULL)) {
9068 "SSL is not initialized");
9077#if defined(USE_X_DOM_SOCKET)
9079 size_t hostlen = strlen(host);
9082 sa->sun.sun_family = AF_UNIX;
9083 memset(sa->sun.sun_path, 0,
sizeof(sa->sun.sun_path));
9084 memcpy(sa->sun.sun_path, host, hostlen);
9088 sa->
sin.sin_port = htons((uint16_t)port);
9090#if defined(USE_IPV6)
9091 }
else if (
mg_inet_pton(AF_INET6, host, &sa->sin6,
sizeof(sa->sin6), 1)) {
9092 sa->sin6.sin6_port = htons((uint16_t)port);
9094 }
else if (host[0] ==
'[') {
9097 size_t l = strlen(host + 1);
9101 if (
mg_inet_pton(AF_INET6,
h, &sa->sin6,
sizeof(sa->sin6), 0)) {
9102 sa->sin6.sin6_port = htons((uint16_t)port);
9121 *sock =
socket(PF_INET, SOCK_STREAM, 0);
9123#if defined(USE_IPV6)
9124 else if (ip_ver == 6) {
9125 *sock =
socket(PF_INET6, SOCK_STREAM, 0);
9128#if defined(USE_X_DOM_SOCKET)
9129 else if (ip_ver == -99) {
9130 *sock =
socket(AF_UNIX, SOCK_STREAM, 0);
9149 "Cannot set socket to non-blocking: %s",
9160 conn_ret = connect(*sock,
9161 (
struct sockaddr *)((
void *)&sa->
sin),
9164#if defined(USE_IPV6)
9165 else if (ip_ver == 6) {
9167 conn_ret = connect(*sock,
9168 (
struct sockaddr *)((
void *)&sa->sin6),
9172#if defined(USE_X_DOM_SOCKET)
9173 else if (ip_ver == -99) {
9175 conn_ret = connect(*sock,
9176 (
struct sockaddr *)((
void *)&sa->sun),
9181 if (conn_ret != 0) {
9186 if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
9188 if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
9191 void *psockerr = &sockerr;
9195 int len = (
int)
sizeof(sockerr);
9197 socklen_t
len = (socklen_t)
sizeof(sockerr);
9203 int ms_wait = 10000;
9213 pfd[0].events = POLLOUT;
9222 "connect(%s:%d): timeout",
9231 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (
char *)psockerr, &
len);
9233 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &
len);
9236 if ((ret == 0) && (sockerr == 0)) {
9241 if (conn_ret != 0) {
9247 "connect(%s:%d): error %s",
9263 static const char *dont_escape =
"._-$,;~()";
9264 static const char *hex =
"0123456789abcdef";
9266 const char *end = dst + dst_len - 1;
9268 for (; ((*
src !=
'\0') && (pos < end));
src++, pos++) {
9269 if (isalnum((
unsigned char)*
src)
9270 || (strchr(dont_escape, *
src) != NULL)) {
9272 }
else if (pos + 2 < end) {
9274 pos[1] = hex[(
unsigned char)*
src >> 4];
9275 pos[2] = hex[(
unsigned char)*
src & 0xf];
9283 return (*
src ==
'\0') ? (
int)(pos - dst) : -1;
9291 size_t namesize, escsize, i;
9292 char *href, *
esc, *
p;
9293 char size[64], mod[64];
9294#if defined(REENTRANT_TIME)
9296 struct tm *tm = &_tm;
9304 href = (
char *)
mg_malloc(namesize * 3 + escsize);
9312 esc = href + namesize * 3;
9317 }
else if (*
p ==
'<') {
9319 }
else if (*
p ==
'>') {
9369#if defined(REENTRANT_TIME)
9375 strftime(mod,
sizeof(mod),
"%d-%b-%Y %H:%M", tm);
9377 mg_strlcpy(mod,
"01-Jan-1970 00:00",
sizeof(mod));
9378 mod[
sizeof(mod) - 1] =
'\0';
9381 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
9382 "<td> %s</td><td> %s</td></tr>\n",
9402 const struct de *
a = (
const struct de *)p1, *
b = (
const struct de *)p2;
9406 if ((query_string == NULL) || (query_string[0] ==
'\0')) {
9410 if (
a->file.is_directory && !
b->file.is_directory) {
9412 }
else if (!
a->file.is_directory &&
b->file.is_directory) {
9414 }
else if (*query_string ==
'n') {
9415 cmp_result = strcmp(
a->file_name,
b->file_name);
9416 }
else if (*query_string ==
's') {
9417 cmp_result = (
a->file.size ==
b->file.size)
9419 : ((
a->file.size >
b->file.size) ? 1 : -1);
9420 }
else if (*query_string ==
'd') {
9422 (
a->file.last_modified ==
b->file.last_modified)
9424 : ((
a->file.last_modified >
b->file.last_modified) ? 1
9428 return (query_string[1] ==
'd') ? -cmp_result : cmp_result;
9447#if !defined(NO_FILESYSTEMS)
9452 int (*cb)(
struct de *,
void *))
9467 if (!strcmp(dp->d_name,
".") || !strcmp(dp->d_name,
"..")
9473 conn, &truncated, path,
sizeof(path),
"%s/%s", dir, dp->d_name);
9489 "%s: mg_stat(%s) failed: %s",
9507#if !defined(NO_FILES)
9526 if (!strcmp(dp->d_name,
".") || !strcmp(dp->d_name,
"..")) {
9531 conn, &truncated, path,
sizeof(path),
"%s/%s", dir, dp->d_name);
9548 "%s: mg_stat(%s) failed: %s",
9583#if !defined(NO_FILESYSTEMS)
9595 dsd->
arr_size * 2 *
sizeof(entries[0]));
9596 if (entries == NULL) {
9622 char date[64], *
esc, *
p;
9624 time_t curtime = time(NULL);
9633 "Error: Cannot open directory\nopendir(%s): %s",
9643 if (title[strcspn(title,
"&<>")]) {
9647 for (i = 0,
p =
esc; title[i]; i++,
p += strlen(
p)) {
9651 }
else if (*
p ==
'<') {
9653 }
else if (*
p ==
'>') {
9676 "text/html; charset=utf-8",
9684 "<html><head><title>Index of %s</title>"
9685 "<style>th {text-align: left;}</style></head>"
9686 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
9687 "<tr><th><a href=\"?n%c\">Name</a></th>"
9688 "<th><a href=\"?d%c\">Modified</a></th>"
9689 "<th><a href=\"?s%c\">Size</a></th></tr>"
9690 "<tr><td colspan=\"3\"><hr></td></tr>",
9700 "<tr><td><a href=\"%s\">%s</a></td>"
9701 "<td> %s</td><td> %s</td></tr>\n",
9708 if (
data.entries != NULL) {
9711 sizeof(
data.entries[0]),
9713 for (i = 0; i <
data.num_entries; i++) {
9720 mg_printf(conn,
"%s",
"</table></pre></body></html>");
9734 int to_read, num_read, num_written;
9737 if (!filep || !conn) {
9748#if defined(__linux__)
9753 off_t sf_offs = (off_t)
offset;
9755 int sf_file = fileno(filep->
access.
fp);
9762 (size_t)((
len < 0x7FFFF000) ?
len : 0x7FFFF000);
9764 sendfile(conn->
client.
sock, sf_file, &sf_offs, sf_tosend);
9768 }
else if (loop_cnt == 0) {
9774 }
else if (sf_sent == 0) {
9780 }
while ((
len > 0) && (sf_sent >= 0));
9789 offset = (int64_t)sf_offs;
9794 "%s: fseeko() failed: %s",
9801 "Error: Unable to access file at requested position.");
9805 to_read =
sizeof(buf);
9806 if ((int64_t)to_read >
len) {
9812 (
int)fread(buf, 1, (
size_t)to_read, filep->
access.
fp))
9818 if ((num_written =
mg_write(conn, buf, (
size_t)num_read))
9834 return sscanf(header,
9846 if ((filestat != NULL) && (buf != NULL)) {
9861 if (filep != NULL && filep->
fp != NULL) {
9865 if (fcntl(fileno(filep->
fp), F_SETFD, FD_CLOEXEC) != 0) {
9867 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
9876#if defined(USE_ZLIB)
9877#include "mod_zlib.inl"
9881#if !defined(NO_FILESYSTEMS)
9887 const char *additional_headers)
9889 char lm[64], etag[64];
9891 const char *range_hdr;
9893 struct vec mime_vec;
9896 const char *encoding = 0;
9897 const char *origin_hdr;
9898 const char *cors_orig_cfg, *cors_cred_cfg;
9899 const char *cors1, *cors2, *cors3, *cors4;
9900 int is_head_request;
9902#if defined(USE_ZLIB)
9906 int allow_on_the_fly_compression = 1;
9909 if ((conn == NULL) || (conn->
dom_ctx == NULL) || (filep == NULL)) {
9924 "Error: File size is too large to send\n%" INT64_FMT,
9932#if defined(USE_ZLIB)
9937 allow_on_the_fly_compression = 0;
9946 mg_snprintf(conn, &truncated, gz_path,
sizeof(gz_path),
"%s.gz", path);
9951 "Error: Path of zipped file too long (%s)",
9959#if defined(USE_ZLIB)
9961 allow_on_the_fly_compression = 0;
9963 }
else if ((conn->
accept_gzip) && (range_hdr == NULL)
9967 mg_snprintf(conn, &truncated, gz_path,
sizeof(gz_path),
"%s.gz", path);
9969 if (!truncated &&
mg_stat(conn, gz_path, &file_stat)
9972 filep->
stat = file_stat;
9977#if defined(USE_ZLIB)
9979 allow_on_the_fly_compression = 0;
9987 "Error: Cannot open file\nfopen(%s): %s",
9998 if ((range_hdr != NULL)
10008 "Error: Range requests in gzipped files are not supported");
10014 cl = (
n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
10025#if defined(USE_ZLIB)
10027 allow_on_the_fly_compression = 0;
10033#if defined(USE_ZLIB)
10036 allow_on_the_fly_compression = 0;
10043 if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
10049 cors1 =
"Access-Control-Allow-Origin";
10050 cors2 = cors_orig_cfg;
10052 cors1 = cors2 =
"";
10057 if (cors_cred_cfg && *cors_cred_cfg && origin_hdr) {
10058 cors3 =
"Access-Control-Allow-Credentials";
10059 cors4 = cors_cred_cfg;
10061 cors3 = cors4 =
"";
10075 (
int)mime_vec.
len);
10076 if (cors1[0] != 0) {
10079 if (cors3[0] != 0) {
10085#if defined(USE_ZLIB)
10087 if (allow_on_the_fly_compression) {
10116 if (range[0] != 0) {
10122 if ((additional_headers != NULL) && (*additional_headers != 0)) {
10129 if (!is_head_request) {
10130#if defined(USE_ZLIB)
10131 if (allow_on_the_fly_compression) {
10133 send_compressed_data(conn, filep);
10160#if !defined(NO_CACHING)
10167 const char *ims =
mg_get_header(conn,
"If-Modified-Since");
10181 char lm[64], etag[64];
10183 if ((conn == NULL) || (filep == NULL)) {
10203#if !defined(NO_FILESYSTEMS)
10224 const char *additional_headers)
10234#if !defined(NO_CACHING)
10248 "Error: Directory listing denied");
10252 conn, path, &file,
mime_type, additional_headers);
10275 for (s =
p = path + 2; (
p = strchr(s,
'/')) != NULL; s = ++
p) {
10276 len = (size_t)(
p - path);
10277 if (
len >=
sizeof(buf)) {
10282 memcpy(buf, path,
len);
10294 if (
p[1] ==
'\0') {
10309 "%s: Cannot remove invalid file %s",
10344 ret =
mg_read(conn, buf,
sizeof(buf));
10354 ret =
mg_read(conn, buf,
sizeof(buf));
10379 while (isgraph((
unsigned char)**ppw)) {
10386 if ((**ppw !=
'\r') && (**ppw !=
'\n')) {
10391 if (**ppw !=
' ') {
10400 }
while (isspace((
unsigned char)**ppw));
10405 if (!isgraph((
unsigned char)**ppw)) {
10423 int num_headers = 0;
10429 while ((*dp !=
':') && (*dp >= 33) && (*dp <= 126)) {
10438 while (*dp ==
' ') {
10450 hdr[i].name = *buf;
10455 }
while ((*dp ==
' ') || (*dp ==
'\t'));
10461 while ((*dp != 0) && (*dp !=
'\r') && (*dp !=
'\n')) {
10477 num_headers = i + 1;
10484 if ((dp[0] ==
'\r') || (dp[0] ==
'\n')) {
10493 return num_headers;
10510 {
"GET", 0, 1, 1, 1, 1},
10511 {
"POST", 1, 1, 0, 0, 0},
10512 {
"PUT", 1, 0, 0, 1, 0},
10513 {
"DELETE", 0, 0, 0, 1, 0},
10514 {
"HEAD", 0, 0, 1, 1, 1},
10515 {
"OPTIONS", 0, 0, 1, 1, 0},
10516 {
"CONNECT", 1, 1, 0, 0, 0},
10520 {
"PATCH", 1, 0, 0, 0, 0},
10524 {
"PROPFIND", 0, 1, 1, 1, 0},
10530 {
"MKCOL", 0, 0, 0, 1, 0},
10543 {
"LOCK", 1, 1, 0, 0, 0},
10544 {
"UNLOCK", 1, 0, 0, 0, 0},
10545 {
"PROPPATCH", 1, 1, 0, 0, 0},
10557 {
"REPORT", 1, 1, 1, 1, 1},
10564 {NULL, 0, 0, 0, 0, 0}
10579 if (!strcmp(
m->name, method)) {
10607 int request_length;
10619 while ((
len > 0) && isspace((
unsigned char)*buf)) {
10631 if (iscntrl((
unsigned char)*buf)) {
10637 if (request_length <= 0) {
10638 return request_length;
10640 buf[request_length - 1] =
'\0';
10642 if ((*buf == 0) || (*buf ==
'\r') || (*buf ==
'\n')) {
10686 return request_length + init_skip;
10693 int response_length;
10705 while ((
len > 0) && isspace((
unsigned char)*buf)) {
10717 if (iscntrl((
unsigned char)*buf)) {
10723 if (response_length <= 0) {
10724 return response_length;
10726 buf[response_length - 1] =
'\0';
10728 if ((*buf == 0) || (*buf ==
'\r') || (*buf ==
'\n')) {
10734 if (strncmp(buf,
"HTTP/", 5) != 0) {
10739 if (!isgraph((
unsigned char)buf[0])) {
10756 l = strtol(tmp, &tmp2, 10);
10757 if ((
l < 100) || (
l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
10768 while (isprint((
unsigned char)*buf)) {
10771 if ((*buf !=
'\r') && (*buf !=
'\n')) {
10778 }
while (isspace((
unsigned char)*buf));
10788 return response_length + init_skip;
10804 int request_len,
n = 0;
10805 struct timespec last_action_time;
10806 double request_timeout;
10812 memset(&last_action_time, 0,
sizeof(last_action_time));
10833 while (request_len == 0) {
10840 if (*nread >= bufsiz) {
10846 fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
10853 clock_gettime(CLOCK_MONOTONIC, &last_action_time);
10860 if ((request_len == 0) && (request_timeout >= 0)) {
10862 > request_timeout) {
10869 return request_len;
10873#if !defined(NO_CGI) || !defined(NO_FILES)
10877 const char *expect;
10892 if ((expect != NULL) && (
mg_strcasecmp(expect,
"100-continue") != 0)) {
10897 if (expect != NULL) {
10898 (void)
mg_printf(conn,
"%s",
"HTTP/1.1 100 Continue\r\n\r\n");
10912 int nread =
mg_read(conn, buf,
sizeof(buf));
10914 success = (nread == 0);
10936#if defined(USE_TIMERS)
10938#define TIMER_API static
10939#include "timer.inl"
10944#if !defined(NO_CGI)
10977 size_t i,
n, space;
10982 if ((env->varlen - env->varused) < 2) {
10984 "%s: Cannot register CGI variable [%s]",
10991 space = (env->buflen - env->bufused);
11003 "%s: Cannot allocate memory for CGI variable [%s]",
11011 for (i = 0,
n = 0; i < env->varused; i++) {
11012 env->var[i] = added +
n;
11013 n += strlen(added +
n) + 1;
11015 space = (env->buflen - env->bufused);
11019 added = env->buf + env->bufused;
11023 mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
11031 }
while (truncated);
11034 n = strlen(added) + 1;
11038 env->var[env->varused] = added;
11048 unsigned char cgi_config_idx)
11051 struct vec var_vec;
11053 int i, truncated, uri_len;
11055 if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
11063 if (env->
buf == NULL) {
11065 "%s: Not enough memory for environmental buffer",
11073 if (env->
var == NULL) {
11075 "%s: Not enough memory for environmental variables",
11087 addenv(env,
"%s",
"GATEWAY_INTERFACE=CGI/1.1");
11088 addenv(env,
"%s",
"SERVER_PROTOCOL=HTTP/1.1");
11089 addenv(env,
"%s",
"REDIRECT_STATUS=200");
11094 addenv(env,
"REMOTE_ADDR=%s", src_addr);
11111 const char *index_file = strrchr(prog,
'/');
11114 "SCRIPT_NAME=%s%s",
11122 "SCRIPT_NAME=%.*s",
11123 uri_len - (
int)strlen(conn->
path_info),
11127 addenv(env,
"SCRIPT_FILENAME=%s", prog);
11132 "PATH_TRANSLATED=%s%s",
11137 addenv(env,
"HTTPS=%s", (conn->
ssl == NULL) ?
"off" :
"on");
11140 addenv(env,
"CONTENT_TYPE=%s", s);
11146 addenv(env,
"CONTENT_LENGTH=%s", s);
11148 if ((s = getenv(
"PATH")) != NULL) {
11149 addenv(env,
"PATH=%s", s);
11161 if ((s = getenv(
"COMSPEC")) != NULL) {
11162 addenv(env,
"COMSPEC=%s", s);
11164 if ((s = getenv(
"SYSTEMROOT")) != NULL) {
11165 addenv(env,
"SYSTEMROOT=%s", s);
11167 if ((s = getenv(
"SystemDrive")) != NULL) {
11168 addenv(env,
"SystemDrive=%s", s);
11170 if ((s = getenv(
"ProgramFiles")) != NULL) {
11171 addenv(env,
"ProgramFiles=%s", s);
11173 if ((s = getenv(
"ProgramFiles(x86)")) != NULL) {
11174 addenv(env,
"ProgramFiles(x86)=%s", s);
11177 if ((s = getenv(
"LD_LIBRARY_PATH")) != NULL) {
11178 addenv(env,
"LD_LIBRARY_PATH=%s", s);
11182 if ((s = getenv(
"PERLLIB")) != NULL) {
11183 addenv(env,
"PERLLIB=%s", s);
11188 addenv(env,
"%s",
"AUTH_TYPE=Digest");
11197 sizeof(http_var_name),
11203 "%s: HTTP header variable too long [%s]",
11210 for (
p = http_var_name; *
p !=
'\0';
p++) {
11214 *
p = (char)toupper((
unsigned char)*
p);
11225 while ((s =
next_option(s, &var_vec, NULL)) != NULL) {
11253 ret_pid = waitpid(proc->
pid, &status, WNOHANG);
11254 if ((ret_pid != (pid_t)-1) && (status == 0)) {
11257 kill(proc->
pid, SIGABRT);
11260 while (waitpid(proc->
pid, &status, 0) != (pid_t)-1)
11263 DEBUG_TRACE(
"CGI timer: Child process %d already stopped\n", proc->
pid);
11280 unsigned char cgi_config_idx)
11284 int headers_len, data_len, i, truncated;
11285 int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
11286 const char *status, *status_text, *connection_state;
11290 FILE *in = NULL, *out = NULL, *err = NULL;
11292 pid_t pid = (pid_t)-1;
11295#if defined(USE_TIMERS)
11296 double cgi_timeout;
11300 atof(conn->
dom_ctx->
config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
11320 (void)
mg_snprintf(conn, &truncated, dir,
sizeof(dir),
"%s", prog);
11323 mg_cry_internal(conn,
"Error: CGI program \"%s\": Path too long", prog);
11328 if ((
p = strrchr(dir,
'/')) != NULL) {
11336 if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
11337 status = strerror(
ERRNO);
11340 "Error: CGI program \"%s\": Can not create CGI pipes: %s",
11345 "Error: Cannot create CGI pipe: %s",
11352 if (proc == NULL) {
11353 mg_cry_internal(conn,
"Error: CGI program \"%s\": Out or memory", prog);
11360 conn,
p,
blk.buf,
blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
11362 if (
pid == (pid_t)-1) {
11363 status = strerror(
ERRNO);
11366 "Error: CGI program \"%s\": Can not spawn CGI process: %s",
11379#if defined(USE_TIMERS)
11380 if (cgi_timeout > 0.0) {
11398 (void)close(fdin[0]);
11399 (void)close(fdout[1]);
11400 (void)close(fderr[1]);
11401 fdin[0] = fdout[1] = fderr[1] = -1;
11403 if (((in = fdopen(fdin[1],
"wb")) == NULL)
11404 || ((out = fdopen(fdout[0],
"rb")) == NULL)
11405 || ((err = fdopen(fderr[0],
"rb")) == NULL)) {
11406 status = strerror(
ERRNO);
11408 "Error: CGI program \"%s\": Can not open fd: %s",
11413 "Error: CGI can not open fd\nfdopen: %s",
11432 "Error: CGI program \"%s\": Forward body data failed",
11452 "Error: Not enough memory for CGI buffer (%u bytes)",
11453 (
unsigned int)buflen);
11456 "Error: CGI program \"%s\": Not enough memory for buffer (%u "
11459 (
unsigned int)buflen);
11464 headers_len =
read_message(out, conn, buf, (
int)buflen, &data_len);
11465 DEBUG_TRACE(
"CGI: response: %li", (
signed long)headers_len);
11467 if (headers_len <= 0) {
11471 i =
pull_all(err, conn, buf, (
int)buflen);
11476 "Error: CGI program \"%s\" sent error "
11484 "Error: CGI program \"%s\" failed.",
11490 "Error: CGI program sent malformed or too big "
11491 "(>%u bytes) HTTP headers: [%.*s]",
11498 "Error: CGI program sent malformed or too big "
11499 "(>%u bytes) HTTP headers: [%.*s]",
11510 buf[headers_len - 1] =
'\0';
11514 status_text =
"OK";
11518 status_text = status;
11519 while (isdigit((
unsigned char)*status_text) || *status_text ==
' ') {
11551 mg_write(conn, buf + headers_len, (
size_t)(data_len - headers_len));
11562 if (
pid != (pid_t)-1) {
11566 if (fdin[0] != -1) {
11569 if (fdout[1] != -1) {
11572 if (fderr[1] != -1) {
11578 }
else if (fdin[1] != -1) {
11584 }
else if (fdout[0] != -1) {
11590 }
else if (fderr[0] != -1) {
11599#if !defined(NO_FILES)
11606 if (
conn == NULL) {
11616 "%s: mg_stat(%s) failed: %s",
11627 conn, 405,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11632 if (body_len > 0) {
11634 conn, 415,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11652 if (errno == EEXIST) {
11654 conn, 405,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11655 }
else if (errno == EACCES) {
11657 conn, 403,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11658 }
else if (errno == ENOENT) {
11660 conn, 409,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11663 conn, 500,
"fopen(%s): %s", path, strerror(
ERRNO));
11677 if (conn == NULL) {
11695 if (
access(path, W_OK) == 0) {
11702 "Error: Put not possible\nReplacing %s is not allowed",
11734 "Error: Path too long\nput_dir(%s): %s",
11744 "Error: Can not create directory\nput_dir(%s): %s",
11757 "Error: Can not create file\nfopen(%s): %s",
11768 fseeko(file.
access.
fp, r1, SEEK_SET);
11805 "Error: Cannot delete file\nFile %s not found",
11823 if (access(path, W_OK) != 0) {
11828 "Error: Delete not possible\nDeleting %s is not allowed",
11846 "Error: Cannot delete file\nremove(%s): %s",
11854#if !defined(NO_FILESYSTEMS)
11870 if (conn == NULL) {
11877 if (sscanf(tag,
" virtual=\"%511[^\"]\"", file_name) == 1) {
11879 file_name[511] = 0;
11888 }
else if (sscanf(tag,
" abspath=\"%511[^\"]\"", file_name) == 1) {
11891 file_name[511] = 0;
11893 mg_snprintf(conn, &truncated, path,
sizeof(path),
"%s", file_name);
11895 }
else if ((sscanf(tag,
" file=\"%511[^\"]\"", file_name) == 1)
11896 || (sscanf(tag,
" \"%511[^\"]\"", file_name) == 1)) {
11898 file_name[511] = 0;
11899 (void)
mg_snprintf(conn, &truncated, path,
sizeof(path),
"%s", ssi);
11902 if ((
p = strrchr(path,
'/')) != NULL) {
11905 len = strlen(path);
11909 sizeof(path) -
len,
11920 mg_cry_internal(conn,
"SSI #include path length overflow: [%s]", tag);
11926 "Cannot open SSI #include: [%s]: fopen(%s): %s",
11943#if !defined(NO_POPEN)
11947 char cmd[1024] =
"";
11950 if (sscanf(tag,
" \"%1023[^\"]\"", cmd) != 1) {
11954 if ((file.
access.
fp = popen(cmd,
"r")) == NULL) {
11956 "Cannot SSI #exec: [%s]: %s",
11971 if (filep == NULL) {
11990 int ch,
len, in_tag, in_ssi_tag;
11992 if (include_level > 10) {
11997 in_tag = in_ssi_tag =
len = 0;
12000 while ((ch =
mg_fgetc(filep)) != EOF) {
12013 if ((
len > 12) && !memcmp(buf + 5,
"include", 7)) {
12015#if !defined(NO_POPEN)
12016 }
else if ((
len > 9) && !memcmp(buf + 5,
"exec", 4)) {
12027 in_ssi_tag = in_tag = 0;
12039 buf[
len++] = (char)(ch & 0xff);
12041 if ((
len == 5) && !memcmp(buf,
"<!--#", 5)) {
12046 if ((
len + 2) > (
int)
sizeof(buf)) {
12072 buf[
len++] = (char)(ch & 0xff);
12074 if (
len == (
int)
sizeof(buf)) {
12095 time_t curtime = time(NULL);
12096 const char *cors_orig_cfg, *cors_cred_cfg;
12097 const char *cors1, *cors2, *cors3, *cors4;
12099 if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
12104 if (cors_orig_cfg && *cors_orig_cfg &&
mg_get_header(conn,
"Origin")) {
12106 cors1 =
"Access-Control-Allow-Origin";
12107 cors2 = cors_orig_cfg;
12109 cors1 = cors2 =
"";
12113 if (cors_cred_cfg && *cors_cred_cfg &&
mg_get_header(conn,
"Origin")) {
12115 cors3 =
"Access-Control-Allow-Credentials";
12116 cors4 = cors_cred_cfg;
12118 cors3 = cors4 =
"";
12126 "Error: Cannot read file\nfopen(%s): %s",
12157#if !defined(NO_FILES)
12176 "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
12195 size_t href_size, i, j;
12197 char *href, mtime[64];
12199 if ((conn == NULL) || (uri == NULL) || (
name == NULL) || (filep == NULL)) {
12203 href_size = (strlen(uri) + strlen(
name)) * 3 + 1;
12205 if (href == NULL) {
12214 for (i = j = 0; href[i]; j++) {
12215 if (!strncmp(href + i,
"%2f", 3)) {
12219 href[j] = href[i++];
12227 "<d:href>%s</d:href>"
12230 "<d:resourcetype>%s</d:resourcetype>"
12231 "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
12232 "<d:getlastmodified>%s</d:getlastmodified>"
12234 "<d:status>HTTP/1.1 200 OK</d:status>"
12267 time_t curtime = time(NULL);
12271 if (!conn || !path || !filep || !conn->
dom_ctx) {
12286 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12287 "<d:multistatus xmlns:d='DAV:'>\n");
12297 && ((depth == NULL) || (strcmp(depth,
"0") != 0))) {
12301 mg_printf(conn,
"%s\n",
"</d:multistatus>");
12309 (void)pthread_mutex_lock(&conn->
mutex);
12317 (void)pthread_mutex_unlock(&conn->
mutex);
12338#if defined(USE_LUA)
12339#include "mod_lua.inl"
12342#if defined(USE_DUKTAPE)
12343#include "mod_duktape.inl"
12346#if defined(USE_WEBSOCKET)
12348#if !defined(NO_SSL_DL)
12349#if !defined(OPENSSL_API_3_0)
12350#define SHA_API static
12356send_websocket_handshake(
struct mg_connection *conn,
const char *websock_key)
12358 static const char *magic =
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
12359 char buf[100], sha[20], b64_sha[
sizeof(sha) * 2];
12360#if !defined(OPENSSL_API_3_0)
12374#if defined(OPENSSL_API_3_0)
12375 EVP_Digest((
unsigned char *)
buf, (uint32_t)strlen(
buf), (
unsigned char *)sha,
12376 NULL, EVP_get_digestbyname(
"sha1"), NULL);
12382 base64_encode((
unsigned char *)sha,
sizeof(sha), b64_sha);
12384 "HTTP/1.1 101 Switching Protocols\r\n"
12385 "Upgrade: websocket\r\n"
12386 "Connection: Upgrade\r\n"
12387 "Sec-WebSocket-Accept: %s\r\n",
12390#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12392 websocket_deflate_response(conn);
12397 "Sec-WebSocket-Protocol: %s\r\n\r\n",
12407#if !defined(MG_MAX_UNANSWERED_PING)
12413#define MG_MAX_UNANSWERED_PING (5)
12420 void *callback_data)
12427 int n, error, exit_by_callback;
12434 size_t i,
len, mask_len = 0, header_len, body_len;
12440 unsigned char mask[4];
12445 unsigned char mem[4096];
12450 double timeout = -1.0;
12451 int enable_ping_pong = 0;
12452 int ping_count = 0;
12461 timeout = atoi(conn->
dom_ctx->
config[WEBSOCKET_TIMEOUT]) / 1000.0;
12466 if (timeout <= 0.0) {
12471 DEBUG_TRACE(
"Websocket connection %s:%u start data processing loop",
12474 conn->in_websocket_handling = 1;
12485 mask_len = (
buf[1] & 128) ? 4 : 0;
12486 if ((
len < 126) && (body_len >= mask_len)) {
12489 header_len = 2 + mask_len;
12490 }
else if ((
len == 126) && (body_len >= (4 + mask_len))) {
12492 header_len = 4 + mask_len;
12494 }
else if (body_len >= (10 + mask_len)) {
12497 memcpy(&l1, &
buf[2], 4);
12498 memcpy(&l2, &
buf[6], 4);
12499 header_len = 10 + mask_len;
12500 data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
12502 if (
data_len > (uint64_t)0x7FFF0000ul) {
12507 "websocket out of memory; closing connection");
12513 if ((header_len > 0) && (body_len >= header_len)) {
12515 unsigned char *
data = mem;
12517 if ((
size_t)
data_len > (
size_t)
sizeof(mem)) {
12520 if (
data == NULL) {
12526 "websocket out of memory; closing connection");
12532 if (mask_len > 0) {
12533 memcpy(
mask,
buf + header_len - mask_len,
sizeof(
mask));
12541 if (
data_len + (uint64_t)header_len > (uint64_t)body_len) {
12544 len = body_len - header_len;
12556 }
else if (
n > 0) {
12567 "Websocket pull failed; closing connection");
12599 if (mask_len > 0) {
12600 for (i = 0; i < (size_t)
data_len; i++) {
12605 exit_by_callback = 0;
12613 }
else if (enable_ping_pong
12633 if (ws_data_handler != NULL) {
12634#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12637 if (!conn->websocket_deflate_initialized) {
12638 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12639 exit_by_callback = 1;
12641 if (!exit_by_callback) {
12642 size_t inflate_buf_size_old = 0;
12643 size_t inflate_buf_size =
12647 Bytef *inflated = NULL;
12648 Bytef *new_mem = NULL;
12649 conn->websocket_inflate_state.avail_in =
12651 conn->websocket_inflate_state.next_in =
data;
12658 if (inflate_buf_size_old == 0) {
12663 inflate_buf_size *= 2;
12668 if (new_mem == NULL) {
12671 "Out of memory: Cannot allocate "
12672 "inflate buffer of %lu bytes",
12673 (
unsigned long)inflate_buf_size);
12674 exit_by_callback = 1;
12677 inflated = new_mem;
12678 conn->websocket_inflate_state.avail_out =
12679 (uInt)(inflate_buf_size
12680 - inflate_buf_size_old);
12681 conn->websocket_inflate_state.next_out =
12682 inflated + inflate_buf_size_old;
12683 ret = inflate(&conn->websocket_inflate_state,
12685 if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
12686 || ret == Z_MEM_ERROR) {
12689 "ZLIB inflate error: %i %s",
12691 (conn->websocket_inflate_state.msg
12692 ? conn->websocket_inflate_state.msg
12693 :
"<no error message>"));
12694 exit_by_callback = 1;
12697 inflate_buf_size_old = inflate_buf_size;
12699 }
while (conn->websocket_inflate_state.avail_out
12701 inflate_buf_size -=
12702 conn->websocket_inflate_state.avail_out;
12703 if (!ws_data_handler(conn,
12708 exit_by_callback = 1;
12714 if (!ws_data_handler(conn,
12719 exit_by_callback = 1;
12729 if (exit_by_callback) {
12730 DEBUG_TRACE(
"Callback requests to close connection from %s:%u",
12737 DEBUG_TRACE(
"Message requests to close connection from %s:%u",
12766 if (ping_count > MG_MAX_UNANSWERED_PING) {
12768 DEBUG_TRACE(
"Too many (%i) unanswered ping from %s:%u "
12769 "- closing connection",
12775 if (enable_ping_pong) {
12801 conn->in_websocket_handling = 0;
12802 DEBUG_TRACE(
"Websocket connection %s:%u left data processing loop",
12813 uint32_t masking_key)
12815 unsigned char header[14];
12819#if defined(GCC_DIAGNOSTIC)
12821#pragma GCC diagnostic push
12822#pragma GCC diagnostic ignored "-Wconversion"
12838#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12839 size_t deflated_size = 0;
12840 Bytef *deflated = 0;
12842 int use_deflate = dataLen > 100 * 1024 && conn->
accept_gzip;
12845 if (!conn->websocket_deflate_initialized) {
12846 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12851 header[0] = 0xC0u | (
unsigned char)((
unsigned)opcode & 0xf);
12852 conn->websocket_deflate_state.avail_in = (uInt)dataLen;
12853 conn->websocket_deflate_state.next_in = (
unsigned char *)
data;
12854 deflated_size = (Bytef *)compressBound((uLong)dataLen);
12855 deflated =
mg_calloc(deflated_size,
sizeof(Bytef));
12856 if (deflated == NULL) {
12859 "Out of memory: Cannot allocate deflate buffer of %lu bytes",
12860 (
unsigned long)deflated_size);
12864 conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
12865 conn->websocket_deflate_state.next_out = deflated;
12866 deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
12867 dataLen = deflated_size - conn->websocket_deflate_state.avail_out
12871 header[0] = 0x80u | (
unsigned char)((
unsigned)opcode & 0xf);
12873#if defined(GCC_DIAGNOSTIC)
12874#pragma GCC diagnostic pop
12878 if (dataLen < 126) {
12880 header[1] = (
unsigned char)dataLen;
12882 }
else if (dataLen <= 0xFFFF) {
12884 uint16_t
len = htons((uint16_t)dataLen);
12886 memcpy(header + 2, &
len, 2);
12890 uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
12891 uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
12893 memcpy(header + 2, &len1, 4);
12894 memcpy(header + 6, &len2, 4);
12901 memcpy(header + headerLen, &masking_key, 4);
12905 retval =
mg_write(conn, header, headerLen);
12906 if (retval != (
int)headerLen) {
12911#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12913 retval =
mg_write(conn, deflated, dataLen);
12934 return mg_websocket_write_exec(conn, opcode,
data, dataLen, 0);
12939mask_data(
const char *in,
size_t in_len, uint32_t masking_key,
char *out)
12944 if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
12946 while (i < (in_len - 3)) {
12947 *(uint32_t *)(
void *)(
out + i) =
12948 *(uint32_t *)(
void *)(in + i) ^ masking_key;
12954 while (i < in_len) {
12955 *(uint8_t *)(
void *)(
out + i) =
12956 *(uint8_t *)(
void *)(in + i)
12957 ^ *(((uint8_t *)&masking_key) + (i % 4));
12971 char *masked_data =
12973 uint32_t masking_key = 0;
12975 if (masked_data == NULL) {
12979 "Cannot allocate buffer for masked websocket response: "
12987 }
while (masking_key == 0);
12989 mask_data(
data, dataLen, masking_key, masked_data);
12991 retval = mg_websocket_write_exec(
12992 conn, opcode, masked_data, dataLen, masking_key);
13002 int is_callback_resource,
13010 const char *websock_key =
mg_get_header(conn,
"Sec-WebSocket-Key");
13011 const char *version =
mg_get_header(conn,
"Sec-WebSocket-Version");
13012 ptrdiff_t lua_websock = 0;
13014#if !defined(USE_LUA)
13020 if (!websock_key) {
13027 const char *key1 =
mg_get_header(conn,
"Sec-WebSocket-Key1");
13028 const char *key2 =
mg_get_header(conn,
"Sec-WebSocket-Key2");
13031 if ((key1 != NULL) && (key2 != NULL)) {
13034 if (8 ==
mg_read(conn, key3, 8)) {
13039 "Protocol upgrade to RFC 6455 required");
13050 if ((version == NULL) || (strcmp(version,
"13") != 0)) {
13060 if (is_callback_resource) {
13062 const char *protocols[64];
13063 int nbSubprotocolHeader = get_req_headers(&conn->
request_info,
13064 "Sec-WebSocket-Protocol",
13067 if ((nbSubprotocolHeader > 0) && subprotocols) {
13071 const char *
sep, *curSubProtocol,
13072 *acceptedWebSocketSubprotocol = NULL;
13077 const char *protocol = protocols[
cnt];
13080 sep = strchr(protocol,
',');
13081 curSubProtocol = protocol;
13082 len =
sep ? (
unsigned long)(sep - protocol)
13083 : (unsigned long)strlen(protocol);
13084 while (sep && isspace((
unsigned char)*++sep))
13090 && (strncmp(curSubProtocol,
13094 acceptedWebSocketSubprotocol =
13099 }
while (sep && !acceptedWebSocketSubprotocol);
13100 }
while (++cnt < nbSubprotocolHeader
13101 && !acceptedWebSocketSubprotocol);
13104 acceptedWebSocketSubprotocol;
13106 }
else if (nbSubprotocolHeader > 0) {
13108 const char *protocol = protocols[0];
13113 const char *
sep = strrchr(protocol,
',');
13126 while (isspace((
unsigned char)*++sep)) {
13133#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13134 websocket_deflate_negotiate(conn);
13137 if ((ws_connect_handler != NULL)
13138 && (ws_connect_handler(conn, cbData) != 0)) {
13148#if defined(USE_LUA)
13159 conn->lua_websocket_state = lua_websocket_new(path, conn);
13160 if (!conn->lua_websocket_state) {
13169 if (!is_callback_resource && !lua_websock) {
13179 if (!send_websocket_handshake(conn, websock_key)) {
13185 if (is_callback_resource) {
13186 if (ws_ready_handler != NULL) {
13187 ws_ready_handler(conn, cbData);
13189#if defined(USE_LUA)
13190 }
else if (lua_websock) {
13191 if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
13199 if (is_callback_resource) {
13200 read_websocket(conn, ws_data_handler, cbData);
13201#if defined(USE_LUA)
13202 }
else if (lua_websock) {
13203 read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
13207#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13209 if (conn->websocket_deflate_initialized) {
13210 deflateEnd(&conn->websocket_deflate_state);
13211 inflateEnd(&conn->websocket_inflate_state);
13216 if (ws_close_handler) {
13217 ws_close_handler(conn, cbData);
13232 const char *upgrade, *connection;
13241 if (connection == NULL) {
13249 if (upgrade == NULL) {
13284 if (sscanf(
vec->
ptr,
"%u.%u.%u.%u%n", &
a, &
b, &
c, &
d, &
n)
13292 if ((
n > 0) && ((
size_t)
n ==
vec->
len)) {
13293 if ((
a < 256) && (
b < 256) && (
c < 256) && (
d < 256) && (
slash < 33)) {
13295 if (sa->
sa.sa_family == AF_INET) {
13296 uint32_t ip = ntohl(sa->
sin.sin_addr.s_addr);
13297 uint32_t net = ((uint32_t)
a << 24) | ((uint32_t)
b << 16)
13298 | ((uint32_t)
c << 8) | (uint32_t)
d;
13300 return (ip &
mask) == net;
13305#if defined(USE_IPV6)
13310 if (sscanf(
vec->
ptr,
"[%49[^]]]/%u%n", ad, &
slash, &
n) != 2) {
13312 if (sscanf(
vec->
ptr,
"[%49[^]]]%n", ad, &
n) != 1) {
13317 if ((
n <= 0) && no_strict) {
13321 if (((
size_t)(
p -
vec->
ptr) <
sizeof(ad))
13322 && (sscanf(
p,
"/%u%n", &
slash, &
n) == 1)) {
13328 }
else if (
vec->
len <
sizeof(ad)) {
13339 while (isxdigit((
unsigned char)*
p) || (*
p ==
'.') || (*
p ==
':')) {
13340 if (*(
p++) ==
':') {
13344 if ((*
p ==
'\0') && (
c >= 2)) {
13345 struct sockaddr_in6 sin6;
13349 if (sa->
sa.sa_family != AF_INET6) {
13352 if (
mg_inet_pton(AF_INET6, ad, &sin6,
sizeof(sin6), 0)) {
13354 for (i = 0; i < 16; i++) {
13355 uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
13356 uint8_t net = sin6.sin6_addr.s6_addr[i];
13359 if (8 * i + 8 <
slash) {
13361 }
else if (8 * i <
slash) {
13362 mask = (uint8_t)(0xFFu << (8 * i + 8 -
slash));
13364 if ((ip &
mask) != net) {
13392 if ((val.
ptr == NULL)
13393 || (sscanf(val.
ptr,
"%lf%c", &
v, &mult)
13399 && (mult !=
','))) {
13404 : ((
lowercase(&mult) ==
'm') ? 1048576 : 1);
13409 if (matched >= 0) {
13434 for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
13446 const char *host_header =
13452 if (host_header != NULL) {
13457 if (*host_header ==
'[') {
13458 pos = strchr(host_header,
']');
13461 DEBUG_TRACE(
"%s",
"Host name format error '[' without ']'");
13465 host->
ptr = host_header;
13466 host->
len = (size_t)(pos + 1 - host_header);
13469 pos = strchr(host_header,
':');
13471 host->
len = (size_t)(pos - host_header);
13473 host->
len = strlen(host_header);
13475 host->
ptr = host_header;
13495 if ((strlen(sslhost) != host.
len)
13498 DEBUG_TRACE(
"Host mismatch: SNI: %s, HTTPS: %.*s",
13510 size_t domNameLen = strlen(domName);
13511 if ((domNameLen == host.
len)
13529 conn->
ssl ?
"S" :
"",
13547 const char *expect_proto =
13551 int redirect_code = 308;
13558 conn, target_url,
sizeof(target_url), expect_proto, port, NULL)
13562 size_t slen1 = strlen(target_url);
13564 if ((slen1 + slen2 + 2) <
sizeof(target_url)) {
13565 target_url[slen1] =
'?';
13566 memcpy(target_url + slen1 + 1,
13569 target_url[slen1 + slen2 + 1] = 0;
13592 int is_delete_request,
13603 size_t urilen = strlen(
uri);
13634 if (!is_delete_request && (
handler == NULL)) {
13661 if (!phys_ctx || !dom_ctx) {
13671 for (tmp_rh = dom_ctx->
handlers; tmp_rh != NULL;
13672 tmp_rh = tmp_rh->
next) {
13674 && (urilen == tmp_rh->
uri_len) && !strcmp(tmp_rh->
uri,
uri)) {
13675 if (!is_delete_request) {
13712 *lastref = tmp_rh->
next;
13719 lastref = &(tmp_rh->
next);
13721 }
while (tmp_rh != NULL);
13723 if (is_delete_request) {
13734 if (tmp_rh == NULL) {
13738 "Cannot create new request handler struct, OOM");
13742 if (!tmp_rh->
uri) {
13747 "Cannot create new request handler struct, OOM");
13766 tmp_rh->
next = NULL;
13881 if (request_info) {
13882 const char *uri = request_info->
local_uri;
13883 size_t urilen = strlen(uri);
13893 for (step = 0; step < 3; step++) {
13895 tmp_rh = tmp_rh->
next) {
13901 matched = (tmp_rh->
uri_len == urilen)
13902 && (strcmp(tmp_rh->
uri,
uri) == 0);
13903 }
else if (step == 1) {
13931 *handler_info = tmp_rh;
13963#if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
13965experimental_websocket_client_data_wrapper(
struct mg_connection *conn,
13972 if (pcallbacks->websocket_data) {
13973 return pcallbacks->websocket_data(conn, bits,
data,
len);
13981experimental_websocket_client_close_wrapper(
const struct mg_connection *conn,
13998 if (handler_info != NULL) {
14016 int uri_len, ssl_index;
14017 int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
14018 is_put_or_delete_request = 0, is_callback_resource = 0,
14019 is_template_text_file = 0;
14029 void *callback_data = NULL;
14031 void *auth_callback_data = NULL;
14033 time_t curtime = time(NULL);
14052 if (ssl_index >= 0) {
14062 "Error: SSL forward not configured properly");
14065 "Can not redirect to SSL, no SSL port available");
14120 }
else if (i == 0) {
14138 const char *cors_meth_cfg =
14140 const char *cors_orig_cfg =
14142 const char *cors_cred_cfg =
14144 const char *cors_origin =
14148 "Access-Control-Request-Method");
14153 if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
14154 && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
14155 && (cors_origin != NULL) && (cors_acrm != NULL)) {
14158 const char *cors_acrh =
14161 "Access-Control-Request-Headers");
14165 "HTTP/1.1 200 OK\r\n"
14167 "Access-Control-Allow-Origin: %s\r\n"
14168 "Access-Control-Allow-Methods: %s\r\n"
14169 "Content-Length: 0\r\n"
14170 "Connection: %s\r\n",
14173 ((cors_meth_cfg[0] ==
'*') ? cors_acrm : cors_meth_cfg),
14176 if (cors_acrh != NULL) {
14178 const char *cors_hdr_cfg =
14181 if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
14188 "Access-Control-Allow-Headers: %s\r\n",
14189 ((cors_hdr_cfg[0] ==
'*') ? cors_acrh
14193 if (cors_cred_cfg && *cors_cred_cfg) {
14195 "Access-Control-Allow-Credentials: %s\r\n",
14199 mg_printf(conn,
"Access-Control-Max-Age: 60\r\n");
14212#if defined(USE_WEBSOCKET)
14218 if (is_websocket_request) {
14227 &ws_connect_handler,
14237 is_callback_resource = 1;
14238 is_script_resource = 1;
14241 no_callback_resource:
14246 is_callback_resource = 0;
14252 &is_script_resource,
14253 &is_websocket_request,
14254 &is_put_or_delete_request,
14255 &is_template_text_file);
14269 &auth_callback_data,
14271 if (!auth_handler(conn, auth_callback_data)) {
14278 }
else if (is_put_or_delete_request && !is_script_resource
14279 && !is_callback_resource) {
14283#if defined(NO_FILES)
14295 "%s method not allowed",
14300#if !defined(NO_FILES)
14327 if (is_callback_resource) {
14329 if (!is_websocket_request) {
14330 i = callback_handler(conn, callback_data);
14366 &is_script_resource,
14367 &is_websocket_request,
14368 &is_put_or_delete_request,
14369 &is_template_text_file);
14370 callback_handler = NULL;
14381 goto no_callback_resource;
14384#if defined(USE_WEBSOCKET)
14385 handle_websocket_request(conn,
14387 is_callback_resource,
14389 ws_connect_handler,
14400#if defined(USE_WEBSOCKET)
14401 if (is_websocket_request) {
14403 if (is_script_resource) {
14407 handle_websocket_request(conn,
14427#if defined(NO_FILES)
14442 if (is_script_resource) {
14449 if (is_put_or_delete_request) {
14471 "%s method not allowed",
14485 && (ri->
local_uri[uri_len - 1] !=
'/')) {
14494 new_path[
len] =
'/';
14495 new_path[
len + 1] = 0;
14497 new_path[
len + 1] =
'?';
14528 "%s method not allowed",
14545 "Error: Directory listing denied");
14551 if (is_template_text_file) {
14558#if !defined(NO_CACHING)
14573#if !defined(NO_FILESYSTEMS)
14579#if !defined(NO_CGI)
14580 unsigned char cgi_config_idx, inc, max;
14583 if (!conn || !conn->
dom_ctx) {
14587#if defined(USE_LUA)
14594 handle_lsp_request(conn, path, file, NULL);
14607 mg_exec_lua_script(conn, path, NULL);
14616#if defined(USE_DUKTAPE)
14622 mg_exec_duktape_script(conn, path);
14631#if !defined(NO_CGI)
14634 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
14663#if !defined(NO_CACHING)
14686#if defined(USE_X_DOM_SOCKET)
14724 unsigned int a,
b,
c,
d;
14726 unsigned long portUL;
14730#if defined(USE_IPV6)
14731 char buf[100] = {0};
14737 memset(so, 0,
sizeof(*so));
14738 so->
lsa.
sin.sin_family = AF_INET;
14747 "%u.%u.%u.%u:%u%n",
14758 so->
lsa.
sin.sin_addr.s_addr =
14759 htonl((
a << 24) | (
b << 16) | (
c << 8) |
d);
14760 so->
lsa.
sin.sin_port = htons((uint16_t)port);
14763#if defined(USE_IPV6)
14764 }
else if (sscanf(
vec->
ptr,
"[%49[^]]]:%u%n", buf, &port, &
len) == 2
14765 && ((
size_t)len <= vec->
len)
14767 AF_INET6, buf, &so->
lsa.sin6,
sizeof(so->
lsa.sin6), 0)) {
14771 so->
lsa.sin6.sin6_port = htons((uint16_t)port);
14775 }
else if ((
vec->
ptr[0] ==
'+')
14776 && (sscanf(
vec->
ptr + 1,
"%u%n", &port, &
len)
14786#if defined(USE_IPV6)
14788 so->
lsa.sin6.sin6_family = AF_INET6;
14789 so->
lsa.sin6.sin6_port = htons((uint16_t)port);
14790 *ip_version = 4 + 6;
14793 so->
lsa.
sin.sin_port = htons((uint16_t)port);
14798 && (
vec->
ptr != endptr)) {
14800 port = (uint16_t)portUL;
14802 so->
lsa.
sin.sin_port = htons((uint16_t)port);
14805 }
else if ((cb = strchr(
vec->
ptr,
':')) != NULL) {
14815 char hostname[256];
14816 size_t hostnlen = (size_t)(cb -
vec->
ptr);
14818 if ((hostnlen >=
vec->
len) || (hostnlen >=
sizeof(hostname))) {
14827 AF_INET, hostname, &so->
lsa.
sin,
sizeof(so->
lsa.
sin), 1)) {
14828 if (sscanf(cb + 1,
"%u%n", &port, &
len)
14834 so->
lsa.
sin.sin_port = htons((uint16_t)port);
14835 len += (
int)(hostnlen + 1);
14839#if defined(USE_IPV6)
14843 sizeof(so->
lsa.sin6),
14845 if (sscanf(cb + 1,
"%u%n", &port, &
len) == 1) {
14847 so->
lsa.sin6.sin6_port = htons((uint16_t)port);
14848 len += (
int)(hostnlen + 1);
14857#if defined(USE_X_DOM_SOCKET)
14859 }
else if (
vec->
ptr[0] ==
'x') {
14861 if (
vec->
len <
sizeof(so->
lsa.sun.sun_path)) {
14863 so->
lsa.sun.sun_family = AF_UNIX;
14864 memset(so->
lsa.sun.sun_path, 0,
sizeof(so->
lsa.sun.sun_path));
14885 so->
is_ssl = (ch ==
's');
14887 if ((ch ==
'\0') || (ch ==
's') || (ch ==
'r')) {
14938 int portslen = (
int)strlen(ports);
14939 char prevIsNumber = 0;
14941 for (i = 0; i < portslen; i++) {
14942 if (prevIsNumber && (ports[i] ==
's' || ports[i] ==
'r')) {
14945 if (ports[i] >=
'0' && ports[i] <=
'9') {
14961#if defined(USE_IPV6)
14972 int portsTotal = 0;
14975 const char *opt_txt;
14976 long opt_listen_backlog;
14982 memset(&so, 0,
sizeof(so));
14983 memset(&
usa, 0,
sizeof(
usa));
14994 "%.*s: invalid port spec (entry %i). Expecting list of: %s",
14998 "[IP_ADDRESS:]PORT[s|r]");
15002#if !defined(NO_SSL)
15006 "Cannot add SSL socket (entry %i)",
15018 (ip_version == 99) ? ( 0) : ( 6)))
15022 "cannot create socket (entry %i)",
15037 if (setsockopt(so.
sock,
15039 SO_EXCLUSIVEADDRUSE,
15047 "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
15051 if (setsockopt(so.
sock,
15061 "cannot set socket option SO_REUSEADDR (entry %i)",
15066#if defined(USE_X_DOM_SOCKET)
15067 if (ip_version == 99) {
15072 if (ip_version > 4) {
15074#if defined(USE_IPV6)
15075 if (ip_version > 6) {
15076 if (so.
lsa.
sa.sa_family == AF_INET6
15077 && setsockopt(so.
sock,
15086 "cannot set socket option "
15087 "IPV6_V6ONLY=off (entry %i)",
15091 if (so.
lsa.
sa.sa_family == AF_INET6
15092 && setsockopt(so.
sock,
15101 "cannot set socket option "
15102 "IPV6_V6ONLY=on (entry %i)",
15114 if (so.
lsa.
sa.sa_family == AF_INET) {
15119 "cannot bind to %.*s: %d (%s)",
15129#if defined(USE_IPV6)
15130 else if (so.
lsa.
sa.sa_family == AF_INET6) {
15132 len =
sizeof(so.
lsa.sin6);
15135 "cannot bind to IPv6 %.*s: %d (%s)",
15146#if defined(USE_X_DOM_SOCKET)
15147 else if (so.
lsa.
sa.sa_family == AF_UNIX) {
15149 len =
sizeof(so.
lsa.sun);
15152 "cannot bind to unix socket %s: %d (%s)",
15153 so.
lsa.sun.sun_path,
15165 "cannot bind: address family not supported (entry %i)",
15173 opt_listen_backlog = strtol(opt_txt, NULL, 10);
15174 if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
15176 "%s value \"%s\" is invalid",
15184 if (listen(so.
sock, (
int)opt_listen_backlog) != 0) {
15187 "cannot listen to %.*s: %d (%s)",
15198 || (
usa.
sa.sa_family != so.
lsa.
sa.sa_family)) {
15202 "call to getsockname failed %.*s: %d (%s)",
15213#if defined(USE_IPV6)
15214 if (so.
lsa.
sa.sa_family == AF_INET6) {
15215 so.
lsa.sin6.sin6_port =
usa.sin6.sin6_port;
15222 if ((ptr = (
struct socket *)
15257 if (portsOk != portsTotal) {
15269 const char *header_value;
15271 if ((header_value =
mg_get_header(conn, header)) == NULL) {
15274 return header_value;
15279#if defined(MG_EXTERNAL_FUNCTION_log_access)
15280#include "external_log_access.inl"
15281#elif !defined(NO_FILESYSTEMS)
15291 const char *referer;
15292 const char *user_agent;
15294 char log_buf[4096];
15296 if (!conn || !conn->
dom_ctx) {
15303#if defined(USE_LUA)
15304 if (conn->
phys_ctx->lua_bg_log_available) {
15307 lua_State *lstate = (lua_State *)ctx->lua_background_state;
15308 pthread_mutex_lock(&ctx->lua_bg_mutex);
15310 lua_getglobal(lstate,
"log");
15311 prepare_lua_request_info_inner(conn, lstate);
15312 push_lua_response_log_data(conn, lstate);
15314 ret = lua_pcall(lstate, 2, 1, 0);
15316 int t = lua_type(lstate, -1);
15317 if (t == LUA_TBOOLEAN) {
15318 if (lua_toboolean(lstate, -1) == 0) {
15320 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15324 }
else if (t == LUA_TSTRING) {
15326 const char *txt = lua_tolstring(lstate, -1, &
len);
15327 if ((
len == 0) || (*txt == 0)) {
15329 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15333 if (
len >=
sizeof(log_buf)) {
15334 len =
sizeof(log_buf) - 1;
15336 memcpy(log_buf, txt,
len);
15340 lua_cry(conn, ret, lstate,
"lua_background_script",
"log");
15342 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15369 strftime(date,
sizeof(date),
"%d/%b/%Y:%H:%M:%S %z", tm);
15371 mg_strlcpy(date,
"01/Jan/1970:00:00:00 +0000",
sizeof(date));
15372 date[
sizeof(date) - 1] =
'\0';
15379 user_agent =
header_val(conn,
"User-Agent");
15385 "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
15416 if (fprintf(fi.
access.
fp,
"%s\n", log_buf) < 1) {
15428 "Error writing log file %s",
15434#error "Either enable filesystems or provide a custom log_access implementation"
15444 int allowed, flag, matched;
15451 allowed = (list == NULL) ?
'+' :
'-';
15456 if ((
vec.
len > 0) && ((flag ==
'+') || (flag ==
'-'))) {
15463 "%s: subnet must be [+|-]IP-addr[/x]",
15472 return allowed ==
'+';
15478#if !defined(_WIN32) && !defined(__ZEPHYR__)
15486 const uid_t curr_uid = getuid();
15489 const struct passwd *to_pw = NULL;
15491 if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
15495 "%s: unknown user [%s]",
15498 }
else if ((run_as_user == NULL) || (curr_uid == to_pw->
pw_uid)) {
15505 if (setgid(to_pw->
pw_gid) == -1) {
15507 "%s: setgid(%s): %s",
15511 }
else if (setgroups(0, NULL) == -1) {
15513 "%s: setgroups(): %s",
15516 }
else if (setuid(to_pw->
pw_uid) == -1) {
15518 "%s: setuid(%s): %s",
15545 pthread_setspecific(
sTlsKey, NULL);
15549#if defined(USE_MBEDTLS)
15560 dom_ctx = &(phys_ctx->
dd);
15569 if (dom_ctx->
ssl_ctx == NULL) {
15570 fprintf(stderr,
"ssl_ctx malloc failed\n");
15580#elif !defined(NO_SSL)
15585 const char *chain);
15592 struct stat cert_buf;
15596 int should_verify_peer;
15604 if (chain == NULL) {
15612 if (stat(pem, &cert_buf) != -1) {
15613 t = (int64_t)cert_buf.st_mtime;
15620 should_verify_peer = 0;
15624 should_verify_peer = 1;
15628 should_verify_peer = 1;
15632 if (should_verify_peer) {
15642 "SSL_CTX_load_verify_locations error: %s "
15643 "ssl_verify_peer requires setting "
15644 "either ssl_ca_path or ssl_ca_file. Is any of them "
15662#if defined(OPENSSL_API_1_1)
15669 int (*func)(
SSL *),
15674 unsigned timeout = 1024;
15695 if (conn->
ssl == NULL) {
15697 OPENSSL_REMOVE_THREAD_STATE();
15700 SSL_set_app_data(conn->
ssl, (
char *)conn);
15702 ret = SSL_set_fd(conn->ssl, conn->client.sock);
15705 SSL_free(conn->ssl);
15707 OPENSSL_REMOVE_THREAD_STATE();
15711 if (client_options) {
15713 SSL_set_tlsext_host_name(conn->ssl, client_options->
host_name);
15723 timeout = (unsigned)to;
15730 for (i = 0; i <= timeout; i += 50) {
15733 ret = func(conn->ssl);
15735 err = SSL_get_error(conn->ssl, ret);
15753 pfd.fd = conn->client.sock;
15759 mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
15786 SSL_free(conn->ssl);
15788 OPENSSL_REMOVE_THREAD_STATE();
15801 err = ERR_get_error();
15802 return ((err == 0) ?
"" : ERR_error_string(err, NULL));
15810 const char hexdigit[] =
"0123456789abcdef";
15812 if ((memlen <= 0) || (buflen <= 0)) {
15815 if (buflen < (3 * memlen)) {
15819 for (i = 0; i < memlen; i++) {
15821 buf[3 * i - 1] =
' ';
15823 buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
15824 buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
15826 buf[3 * memlen - 1] = 0;
15836 X509 *cert = SSL_get_peer_certificate(conn->
ssl);
15838 char str_buf[1024];
15839 unsigned char buf[256];
15840 char *str_serial = NULL;
15843 unsigned char *tmp_buf;
15844 unsigned char *tmp_p;
15847 const EVP_MD *digest = EVP_get_digestbyname(
"sha1");
15850 X509_NAME *subj = X509_get_subject_name(cert);
15851 X509_NAME *iss = X509_get_issuer_name(cert);
15857 BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
15859 str_serial = BN_bn2hex(serial_bn);
15860 BN_free(serial_bn);
15866 (void)X509_NAME_oneline(subj, str_buf, (
int)
sizeof(str_buf));
15868 (void)X509_NAME_oneline(iss, str_buf, (
int)
sizeof(str_buf));
15876 ilen = i2d_X509(cert, NULL);
15877 tmp_buf = (ilen > 0)
15883 (void)i2d_X509(cert, &tmp_p);
15885 tmp_buf, (
unsigned)ilen, buf, &ulen, digest, NULL)) {
15891 if (!
hexdump2string(buf, (
int)ulen, str_buf, (
int)
sizeof(str_buf))) {
15900 OPENSSL_free(str_serial);
15907#if defined(OPENSSL_API_1_1)
15917 (void)pthread_mutex_lock(&
ssl_mutexes[mutex_num]);
15919 (void)pthread_mutex_unlock(&
ssl_mutexes[mutex_num]);
15925#if !defined(NO_SSL_DL)
15930 const char *dll_name,
15932 int *feature_missing)
15943 if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
15948 "%s: cannot load %s",
15955 for (fp = sw; fp->
name != NULL; fp++) {
15958 u.fp = (void (*)(void))dlsym(dll_handle, fp->
name);
15963 u.p = dlsym(dll_handle, fp->
name);
15969 if (u.fp == NULL) {
15971 if (feature_missing) {
15983 "%s: %s: cannot find %s",
15991 size_t cur_len = strlen(ebuf);
15992 if (!truncated && ((ebuf_len - cur_len) > 3)) {
15996 ebuf_len - cur_len - 3,
16001 strcat(ebuf,
"...");
16010 (void)dlclose(dll_handle);
16024#if defined(SSL_ALREADY_INITIALIZED)
16036#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16041 if (ebuf_len > 0) {
16045#if !defined(NO_SSL_DL)
16055 "%s: error loading library %s",
16068#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16072 num_locks = CRYPTO_num_locks();
16073 if (num_locks < 0) {
16076 size =
sizeof(pthread_mutex_t) * ((
size_t)(num_locks));
16079 if (num_locks == 0) {
16092 "%s: cannot allocate mutexes: %s",
16100 for (i = 0; i < num_locks; i++) {
16106 "%s: error initializing mutex %i of %i",
16121#if !defined(NO_SSL_DL)
16126#if !defined(OPENSSL_API_1_1)
16135#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16136 && !defined(NO_SSL_DL)
16138 OPENSSL_init_ssl(0, NULL);
16144 SSL_library_init();
16145 SSL_load_error_strings();
16158 if (SSL_CTX_use_certificate_file(dom_ctx->
ssl_ctx, pem, 1) == 0) {
16160 "%s: cannot open certificate file %s: %s",
16168 if (SSL_CTX_use_PrivateKey_file(dom_ctx->
ssl_ctx, pem, 1) == 0) {
16170 "%s: cannot open private key file %s: %s",
16177 if (SSL_CTX_check_private_key(dom_ctx->
ssl_ctx) == 0) {
16179 "%s: certificate and private key do not match: %s",
16194 if (SSL_CTX_use_certificate_chain_file(dom_ctx->
ssl_ctx, chain) == 0) {
16196 "%s: cannot use certificate chain file %s: %s",
16207#if defined(OPENSSL_API_1_1)
16208static unsigned long
16211 long unsigned ret = (
long unsigned)
SSL_OP_ALL;
16212 if (version_id > 0)
16214 if (version_id > 1)
16216 if (version_id > 2)
16218 if (version_id > 3)
16220 if (version_id > 4)
16222#if defined(SSL_OP_NO_TLSv1_3)
16223 if (version_id > 5)
16232 unsigned long ret = (
unsigned long)
SSL_OP_ALL;
16233 if (version_id > 0)
16235 if (version_id > 1)
16237 if (version_id > 2)
16239 if (version_id > 3)
16241 if (version_id > 4)
16243#if defined(SSL_OP_NO_TLSv1_3)
16244 if (version_id > 5)
16268 SSL_get_app_data(ssl);
16281#if defined(GCC_DIAGNOSTIC)
16282#pragma GCC diagnostic push
16283#pragma GCC diagnostic ignored "-Wcast-align"
16289#if defined(GCC_DIAGNOSTIC)
16290#pragma GCC diagnostic pop
16298 if ((conn == NULL) || (conn->
phys_ctx == NULL)) {
16310 if ((servername == NULL) || (*servername == 0)) {
16311 DEBUG_TRACE(
"%s",
"SSL connection not supporting SNI");
16318 DEBUG_TRACE(
"TLS connection to host %s", servername);
16346#if defined(USE_ALPN)
16347static const char alpn_proto_list[] =
"\x02h2\x08http/1.1\x08http/1.0";
16348static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
16349 alpn_proto_list + 3 + 8,
16351#if defined(USE_HTTP2)
16352static const char *alpn_proto_order_http2[] = {alpn_proto_list,
16353 alpn_proto_list + 3,
16354 alpn_proto_list + 3 + 8,
16360 const unsigned char **out,
16361 unsigned char *outlen,
16362 const unsigned char *in,
16363 unsigned int inlen,
16367 unsigned int i, j, enable_http2 = 0;
16368 const char **alpn_proto_order = alpn_proto_order_http1;
16381#if defined(USE_HTTP2)
16382 enable_http2 = (0 == strcmp(dom_ctx->
config[ENABLE_HTTP2],
"yes"));
16383 if (enable_http2) {
16384 alpn_proto_order = alpn_proto_order_http2;
16388 for (j = 0; alpn_proto_order[j] != NULL; j++) {
16390 const char *
alpn_proto = alpn_proto_order[j];
16392 for (i = 0; i < inlen; i++) {
16408next_protos_advertised_cb(
SSL *ssl,
16409 const unsigned char **
data,
16414 *
data = (
const unsigned char *)alpn_proto_list;
16415 *
len = (
unsigned int)strlen((
const char *)
data);
16427 unsigned int alpn_len = (
unsigned int)strlen((
char *)alpn_proto_list);
16428 int ret = SSL_CTX_set_alpn_protos(dom_ctx->
ssl_ctx,
16429 (
const unsigned char *)alpn_proto_list,
16433 "SSL_CTX_set_alpn_protos error: %s",
16437 SSL_CTX_set_alpn_select_cb(dom_ctx->
ssl_ctx,
16441 SSL_CTX_set_next_protos_advertised_cb(dom_ctx->
ssl_ctx,
16442 next_protos_advertised_cb,
16458 int should_verify_peer;
16459 int peer_certificate_optional;
16460 const char *ca_path;
16461 const char *ca_file;
16462 int use_default_verify_paths;
16464 struct timespec now_mt;
16468 int ssl_cache_timeout;
16470#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16471 && !defined(NO_SSL_DL)
16472 if ((dom_ctx->
ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
16474 "SSL_CTX_new (server) error: %s",
16479 if ((dom_ctx->
ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
16481 "SSL_CTX_new (server) error: %s",
16487#if defined(SSL_OP_NO_TLSv1_3)
16488 SSL_CTX_clear_options(dom_ctx->
ssl_ctx,
16493 SSL_CTX_clear_options(dom_ctx->
ssl_ctx,
16502 SSL_CTX_set_options(dom_ctx->
ssl_ctx,
16506#if defined(SSL_OP_NO_RENEGOTIATION)
16510#if !defined(NO_SSL_DL)
16511 SSL_CTX_set_ecdh_auto(dom_ctx->
ssl_ctx, 1);
16529 SSL_CTX_set_tlsext_servername_callback(dom_ctx->
ssl_ctx,
16541 if (callback_ret < 0) {
16543 "SSL callback returned error: %i",
16547 if (callback_ret > 0) {
16563 if (callback_ret < 0) {
16565 "Domain SSL callback returned error: %i",
16569 if (callback_ret > 0) {
16577 clock_gettime(CLOCK_MONOTONIC, &now_mt);
16589 SSL_CTX_set_session_id_context(dom_ctx->
ssl_ctx,
16590 (
unsigned char *)ssl_context_id,
16591 sizeof(ssl_context_id));
16601 should_verify_peer = 0;
16602 peer_certificate_optional = 0;
16606 should_verify_peer = 1;
16611 should_verify_peer = 1;
16612 peer_certificate_optional = 1;
16616 use_default_verify_paths =
16621 if (should_verify_peer) {
16624 if (SSL_CTX_load_verify_locations(dom_ctx->
ssl_ctx, ca_file, ca_path)
16627 "SSL_CTX_load_verify_locations error: %s "
16628 "ssl_verify_peer requires setting "
16629 "either ssl_ca_path or ssl_ca_file. "
16630 "Is any of them present in the "
16636 if (peer_certificate_optional) {
16639 SSL_CTX_set_verify(dom_ctx->
ssl_ctx,
16645 if (use_default_verify_paths
16646 && (SSL_CTX_set_default_verify_paths(dom_ctx->
ssl_ctx) != 1)) {
16648 "SSL_CTX_set_default_verify_paths error: %s",
16655 SSL_CTX_set_verify_depth(dom_ctx->
ssl_ctx, verify_depth);
16660 if (SSL_CTX_set_cipher_list(dom_ctx->
ssl_ctx,
16664 "SSL_CTX_set_cipher_list error: %s",
16673 if (ssl_cache_timeout > 0) {
16677 SSL_CTX_set_timeout(dom_ctx->
ssl_ctx, (
long)ssl_cache_timeout);
16680#if defined(USE_ALPN)
16682#if !defined(NO_SSL_DL)
16686 init_alpn(phys_ctx, dom_ctx);
16711 dom_ctx = &(phys_ctx->
dd);
16726 if (callback_ret < 0) {
16729 "external_ssl_ctx callback returned error: %i",
16732 }
else if (callback_ret > 0) {
16753 if (callback_ret < 0) {
16757 "external_ssl_ctx_domain callback returned error: %i",
16760 }
else if (callback_ret > 0) {
16781 "Initializing SSL failed: -%s is not set",
16788 if (chain == NULL) {
16792 if ((chain != NULL) && (*chain == 0)) {
16809#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
16817 CONF_modules_unload(1);
16827 CRYPTO_set_locking_callback(NULL);
16828 CRYPTO_set_id_callback(NULL);
16830 CONF_modules_unload(1);
16831 ERR_free_strings();
16833 CRYPTO_cleanup_all_ex_data();
16834 OPENSSL_REMOVE_THREAD_STATE();
16836 for (i = 0; i < CRYPTO_num_locks(); i++) {
16847#if !defined(NO_FILESYSTEMS)
16862 "Cannot open %s: %s",
16878 memset(&
sa, 0,
sizeof(
sa));
16879#if defined(USE_IPV6)
16880 sa.sin6.sin6_family = AF_INET6;
16882 sa.sin.sin_family = AF_INET;
16924#if defined(USE_SERVER_STATS)
16925 conn->processing_time = 0;
16933 if ((so->
lsa.
sa.sa_family == AF_INET)
16934 || (so->
lsa.
sa.sa_family == AF_INET6)) {
16936 if (setsockopt(so->
sock,
16940 sizeof(nodelay_on))
16951#if !defined(__ZEPHYR__)
16959 struct linger linger;
16960 int error_code = 0;
16961 int linger_timeout = -2;
16962 socklen_t opt_len =
sizeof(error_code);
16985 n =
pull_inner(NULL, conn, buf,
sizeof(buf), 1.0);
16994 if (linger_timeout >= 0) {
16997 linger.l_onoff = 1;
16999#if defined(_MSC_VER)
17000#pragma warning(push)
17001#pragma warning(disable : 4244)
17003#if defined(GCC_DIAGNOSTIC)
17004#pragma GCC diagnostic push
17005#pragma GCC diagnostic ignored "-Wconversion"
17011 linger.l_linger = (linger_timeout + 999) / 1000;
17013#if defined(GCC_DIAGNOSTIC)
17014#pragma GCC diagnostic pop
17016#if defined(_MSC_VER)
17017#pragma warning(pop)
17021 linger.l_onoff = 0;
17022 linger.l_linger = 0;
17025 if (linger_timeout < -1) {
17031 (
char *)&error_code,
17041 "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
17045 }
else if (error_code == WSAECONNRESET) {
17047 }
else if (error_code == ECONNRESET) {
17062 "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
17080#if defined(USE_SERVER_STATS)
17081 conn->conn_state = 6;
17084#if defined(USE_LUA) && defined(USE_WEBSOCKET)
17085 if (conn->lua_websocket_state) {
17086 lua_websocket_close(conn, conn->lua_websocket_state);
17087 conn->lua_websocket_state = NULL;
17109#if defined(USE_SERVER_STATS)
17110 conn->conn_state = 7;
17113#if defined(USE_MBEDTLS)
17114 if (conn->
ssl != NULL) {
17115 mbed_ssl_close(conn->
ssl);
17118#elif !defined(NO_SSL)
17119 if (conn->
ssl != NULL) {
17122 SSL_shutdown(conn->
ssl);
17123 SSL_free(conn->
ssl);
17124 OPENSSL_REMOVE_THREAD_STATE();
17129#if defined(__ZEPHYR__)
17146#if defined(USE_SERVER_STATS)
17147 conn->conn_state = 8;
17155 if ((conn == NULL) || (conn->
phys_ctx == NULL)) {
17159#if defined(USE_WEBSOCKET)
17161 if (conn->in_websocket_handling) {
17189#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
17197#if defined(USE_WEBSOCKET)
17200 (void)pthread_mutex_destroy(&conn->
mutex);
17203 (void)pthread_mutex_destroy(&conn->
mutex);
17208 (void)pthread_mutex_destroy(&conn->
mutex);
17224 struct sockaddr *psa;
17227 unsigned max_req_size =
17231 size_t conn_size = ((
sizeof(
struct mg_connection) + 7) >> 3) << 3;
17232 size_t ctx_size = ((
sizeof(
struct mg_context) + 7) >> 3) << 3;
17236 conn_size + ctx_size + max_req_size);
17238 if (conn == NULL) {
17248#if defined(GCC_DIAGNOSTIC)
17249#pragma GCC diagnostic push
17250#pragma GCC diagnostic ignored "-Wcast-align"
17256#if defined(GCC_DIAGNOSTIC)
17257#pragma GCC diagnostic pop
17260 conn->
buf = (((
char *)conn) + conn_size + ctx_size);
17266 client_options->
host,
17267 client_options->
port,
17279#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
17280#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
17281 && !defined(NO_SSL_DL)
17289 "SSL_CTX_new error: %s",
17297 && (conn->
dom_ctx->
ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
17303 "SSL_CTX_new error: %s",
17313#if defined(USE_IPV6)
17316 psa = (sa.
sa.sa_family == AF_INET)
17318 : (
struct sockaddr *)&(conn->
client.
rsa.sin6);
17327 if (getsockname(sock, psa, &
len) != 0) {
17329 "%s: getsockname() failed: %s",
17340 "Can not create mutex");
17341#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
17350#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
17368 "Can not use SSL client certificate");
17382 "SSL_CTX_load_verify_locations error: %s ",
17394 if (!
sslize(conn, SSL_connect, client_options)) {
17399 "SSL connection error");
17414 char *error_buffer,
17415 size_t error_buffer_size)
17420 error_buffer_size);
17428 char *error_buffer,
17429 size_t error_buffer_size)
17432 memset(&opts, 0,
sizeof(opts));
17438 error_buffer_size);
17442#if defined(MG_EXPERIMENTAL_INTERFACES)
17444mg_connect_client2(
const char *host,
17445 const char *protocol,
17454 if (error != NULL) {
17461 if ((host == NULL) || (protocol == NULL)) {
17468 "Invalid parameters");
17480#if defined(USE_WEBSOCKET)
17494 "Protocol %s not supported",
17503#if defined(USE_WEBSOCKET)
17510 ((error != NULL) ? error->
text : NULL),
17511 ((error != NULL) ? error->text_buffer_size : 0),
17512 (path ? path :
""),
17514 experimental_websocket_client_data_wrapper,
17515 experimental_websocket_client_close_wrapper,
17516 (
void *)init->callbacks);
17522 memset(&opts, 0,
sizeof(opts));
17527 ((error != NULL) ? error->
text : NULL),
17528 ((error != NULL) ? error->text_buffer_size
17534static const struct {
17539 {
"https://", 8, 443},
17541 {
"wss://", 6, 443},
17555 const char *hostend, *portbegin;
17557 unsigned long port;
17563 if ((uri[0] ==
'*') && (uri[1] ==
'\0')) {
17574 for (i = 0; uri[i] != 0; i++) {
17583 if (uri[0] ==
'/') {
17607 port = strtoul(portbegin + 1, &portend, 10);
17608 if ((portend != hostend) || (port <= 0) || !
is_valid_port(port)) {
17624 const char *server_domain;
17625 size_t server_domain_len;
17626 size_t request_domain_len = 0;
17627 unsigned long port = 0;
17628 int i, auth_domain_check_enabled;
17629 const char *hostbegin = NULL;
17630 const char *hostend = NULL;
17631 const char *portbegin;
17634 auth_domain_check_enabled =
17646 hostend = strchr(hostbegin,
'/');
17650 portbegin = strchr(hostbegin,
':');
17651 if ((!portbegin) || (portbegin > hostend)) {
17653 request_domain_len = (size_t)(hostend - hostbegin);
17655 port = strtoul(portbegin + 1, &portend, 10);
17656 if ((portend != hostend) || (port <= 0)
17660 request_domain_len = (size_t)(portbegin - hostbegin);
17687 if (auth_domain_check_enabled) {
17689 server_domain_len = strlen(server_domain);
17690 if ((server_domain_len == 0) || (hostbegin == NULL)) {
17693 if ((request_domain_len == server_domain_len)
17694 && (!memcmp(server_domain, hostbegin, server_domain_len))) {
17697 if (request_domain_len < (server_domain_len + 2)) {
17704 if (hostbegin[request_domain_len - server_domain_len - 1] !=
'.') {
17711 != memcmp(server_domain,
17712 hostbegin + request_domain_len - server_domain_len,
17713 server_domain_len)) {
17728 if (ebuf_len > 0) {
17748 clock_gettime(CLOCK_MONOTONIC, &(conn->
req_time));
17759 "Invalid message size");
17770 "Message too large");
17782 "Malformed message");
17792 "No data received");
17833 "Bad request: Host mismatch");
17841 "Accept-Encoding"))
17843 && strstr(cl,
"gzip")) {
17849 "Transfer-Encoding"))
17869 char *endptr = NULL;
17921 "Transfer-Encoding"))
17940 char *endptr = NULL;
17986 char *save_timeout;
17989 if (ebuf_len > 0) {
17999 "Parameter error");
18009 if (timeout >= 0) {
18010 mg_snprintf(conn, NULL, txt,
sizeof(txt),
"%i", timeout);
18013 new_timeout = NULL;
18026 return (ret == 0) ? -1 : +1;
18044 if (ebuf_len > 0) {
18053 if (conn != NULL) {
18061 "Error sending request");
18073 if ((ebuf[0] !=
'\0') && (conn != NULL)) {
18091#if defined(USE_WEBSOCKET)
18093static unsigned __stdcall websocket_client_thread(
void *
data)
18096websocket_client_thread(
void *
data)
18102 void *user_thread_ptr = NULL;
18104#if !defined(_WIN32) && !defined(__ZEPHYR__)
18105 struct sigaction sa;
18108 memset(&sa, 0,
sizeof(sa));
18109 sa.sa_handler = SIG_IGN;
18110 sigaction(SIGPIPE, &sa, NULL);
18126 DEBUG_TRACE(
"%s",
"Websocket client thread exited\n");
18156 char *error_buffer,
18157 size_t error_buffer_size,
18159 const char *origin,
18160 const char *extensions,
18167#if defined(USE_WEBSOCKET)
18169 static const char *magic =
"x3JJHMbDL1EzLkh9GBhXDw==";
18171 const char *host = client_options->
host;
18174#if defined(__clang__)
18175#pragma clang diagnostic push
18176#pragma clang diagnostic ignored "-Wformat-nonliteral"
18183 error_buffer_size);
18186 if (
conn == NULL) {
18188 if (!error_buffer[0]) {
18194 "Unexpected error");
18199 if (origin != NULL) {
18200 if (extensions != NULL) {
18202 "GET %s HTTP/1.1\r\n"
18204 "Upgrade: websocket\r\n"
18205 "Connection: Upgrade\r\n"
18206 "Sec-WebSocket-Key: %s\r\n"
18207 "Sec-WebSocket-Version: 13\r\n"
18208 "Sec-WebSocket-Extensions: %s\r\n"
18218 "GET %s HTTP/1.1\r\n"
18220 "Upgrade: websocket\r\n"
18221 "Connection: Upgrade\r\n"
18222 "Sec-WebSocket-Key: %s\r\n"
18223 "Sec-WebSocket-Version: 13\r\n"
18233 if (extensions != NULL) {
18235 "GET %s HTTP/1.1\r\n"
18237 "Upgrade: websocket\r\n"
18238 "Connection: Upgrade\r\n"
18239 "Sec-WebSocket-Key: %s\r\n"
18240 "Sec-WebSocket-Version: 13\r\n"
18241 "Sec-WebSocket-Extensions: %s\r\n"
18249 "GET %s HTTP/1.1\r\n"
18251 "Upgrade: websocket\r\n"
18252 "Connection: Upgrade\r\n"
18253 "Sec-WebSocket-Key: %s\r\n"
18254 "Sec-WebSocket-Version: 13\r\n"
18267 "Error sending request");
18280#if defined(__clang__)
18281#pragma clang diagnostic pop
18289 if (!*error_buffer) {
18295 "Unexpected server reply");
18298 DEBUG_TRACE(
"Websocket client connect error: %s\r\n", error_buffer);
18305 if (!thread_data) {
18342 "Websocket client connect thread could not be started\r\n");
18347 (void)client_options;
18349 (void)error_buffer;
18350 (void)error_buffer_size;
18367 char *error_buffer,
18368 size_t error_buffer_size,
18370 const char *origin,
18376 memset(&client_options, 0,
sizeof(client_options));
18396 char *error_buffer,
18397 size_t error_buffer_size,
18399 const char *origin,
18404 if (!client_options) {
18423 char *error_buffer,
18424 size_t error_buffer_size,
18426 const char *origin,
18427 const char *extensions,
18433 memset(&client_options, 0,
sizeof(client_options));
18452 char *error_buffer,
18453 size_t error_buffer_size,
18455 const char *origin,
18456 const char *extensions,
18461 if (!client_options) {
18481 int keep_alive_enabled =
18484 if (!keep_alive_enabled) {
18495#if defined(USE_SERVER_STATS)
18496 conn->conn_state = 2;
18502 void *conn_data = NULL;
18519 int keep_alive, discard_len;
18521 const char *hostend;
18522 int reqerr, uri_type;
18524#if defined(USE_SERVER_STATS)
18526 mg_atomic_add(&(conn->
phys_ctx->total_connections), 1);
18527 mg_atomic_max(&(conn->
phys_ctx->max_active_connections), mcon);
18530 DEBUG_TRACE(
"Start processing connection from %s",
18536 DEBUG_TRACE(
"calling get_request (%i times for this connection)",
18539#if defined(USE_SERVER_STATS)
18540 conn->conn_state = 3;
18543 if (!
get_request(conn, ebuf,
sizeof(ebuf), &reqerr)) {
18559 "Bad HTTP version: [%s]",
18564 if (ebuf[0] ==
'\0') {
18566 switch (uri_type) {
18602 if (ebuf[0] !=
'\0') {
18622 (ebuf[0] ? ebuf :
"none"));
18624 if (ebuf[0] ==
'\0') {
18675 conn->
buf + discard_len,
18684 DEBUG_TRACE(
"internal error: data_len = %li, buf_size = %li",
18690 }
while (keep_alive);
18692 DEBUG_TRACE(
"Done processing connection from %s (%f sec)",
18698#if defined(USE_SERVER_STATS)
18705#if defined(ALTERNATIVE_QUEUE)
18715 if (ctx->client_socks[i].in_use == 2) {
18717 if ((ctx->client_socks[i].in_use == 2) && !ctx->
stop_flag) {
18718 ctx->client_socks[i] = *sp;
18719 ctx->client_socks[i].in_use = 1;
18722 (
void)event_signal(ctx->client_wait_events[i]);
18742 ctx->client_socks[thread_index].in_use = 2;
18745 event_wait(ctx->client_wait_events[thread_index]);
18748 *sp = ctx->client_socks[thread_index];
18774 (void)thread_index;
18800 (void)pthread_cond_signal(&ctx->
sq_empty);
18819 && (queue_filled >= ctx->
sq_size)) {
18821#if defined(USE_SERVER_STATS)
18822 if (queue_filled > ctx->sq_max_fill) {
18823 ctx->sq_max_fill = queue_filled;
18831 if (queue_filled < ctx->sq_size) {
18839#if defined(USE_SERVER_STATS)
18840 if (queue_filled > ctx->sq_max_fill) {
18841 ctx->sq_max_fill = queue_filled;
18845 (void)pthread_cond_signal(&ctx->
sq_full);
18863 tls.pthread_cond_helper_mutex = CreateEvent(NULL,
FALSE,
FALSE, NULL);
18867 pthread_setspecific(
sTlsKey, &tls);
18881 if ((thread_index < 0)
18884 "Internal error: Invalid worker index %i",
18893 if (conn->
buf == NULL) {
18896 "Out of memory: Cannot allocate buffer for worker %i",
18916#if defined(USE_SERVER_STATS)
18917 conn->conn_state = 1;
18928#if defined(USE_SERVER_STATS)
18929 conn->conn_close_time = 0;
18955#if defined(USE_MBEDTLS)
18957 if (mbed_ssl_accept(&(conn->
ssl),
18973#elif !defined(NO_SSL)
18975 if (
sslize(conn, SSL_accept, NULL)) {
18985#if defined(USE_HTTP2)
18987 && (!memcmp(tls.
alpn_proto,
"\x02h2", 3))) {
18995 process_new_http2_connection(conn);
19040#if defined(USE_SERVER_STATS)
19041 conn->conn_close_time = time(NULL);
19051 pthread_setspecific(
sTlsKey, NULL);
19053 CloseHandle(tls.pthread_cond_helper_mutex);
19055 pthread_mutex_destroy(&conn->
mutex);
19068#if defined(USE_SERVER_STATS)
19069 conn->conn_state = 9;
19078static unsigned __stdcall
worker_thread(
void *thread_func_param)
19087#if !defined(__ZEPHYR__)
19088 struct sigaction sa;
19091 memset(&sa, 0,
sizeof(sa));
19092 sa.sa_handler = SIG_IGN;
19093 sigaction(SIGPIPE, &sa, NULL);
19109 socklen_t
len =
sizeof(so.
rsa);
19110#if !defined(__ZEPHYR__)
19113 memset(&so, 0,
sizeof(so));
19120 "%s: %s is not allowed to connect",
19132 "%s: getsockname() failed: %s",
19137#if !defined(__ZEPHYR__)
19138 if ((so.
lsa.
sa.sa_family == AF_INET)
19139 || (so.
lsa.
sa.sa_family == AF_INET6)) {
19147 if (setsockopt(so.
sock,
19155 "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
19174 "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
19197 unsigned int workerthreadcount;
19207 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
19208#elif defined(USE_MASTER_THREAD_PRIORITY)
19209 int min_prio = sched_get_priority_min(SCHED_RR);
19210 int max_prio = sched_get_priority_max(SCHED_RR);
19211 if ((min_prio >= 0) && (max_prio >= 0)
19212 && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
19213 && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
19214 struct sched_param sched_param = {0};
19215 sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
19216 pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
19222 tls.pthread_cond_helper_mutex = CreateEvent(NULL,
FALSE,
FALSE, NULL);
19225 pthread_setspecific(
sTlsKey, &tls);
19235#if defined(USE_LUA)
19236 if (ctx->lua_background_state) {
19237 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19238 pthread_mutex_lock(&ctx->lua_bg_mutex);
19241 lua_getglobal(lstate,
"start");
19242 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19243 int ret = lua_pcall(lstate, 0, 0, 0);
19249 "lua_background_script",
19253 lua_pop(lstate, 1);
19257 lua_getglobal(lstate,
"log");
19258 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19259 ctx->lua_bg_log_available = 1;
19261 lua_pop(lstate, 1);
19263 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19275 pfd[i].events = POLLIN;
19290 && (pfd[i].revents & POLLIN)) {
19304#if defined(ALTERNATIVE_QUEUE)
19306 event_signal(ctx->client_wait_events[i]);
19310 pthread_cond_broadcast(&ctx->
sq_full);
19316 for (i = 0; i < workerthreadcount; i++) {
19322#if defined(USE_LUA)
19324 if (ctx->lua_background_state) {
19325 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19326 ctx->lua_bg_log_available = 0;
19329 pthread_mutex_lock(&ctx->lua_bg_mutex);
19330 lua_getglobal(lstate,
"stop");
19331 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19332 int ret = lua_pcall(lstate, 0, 0, 0);
19338 "lua_background_script",
19344 ctx->lua_background_state = 0;
19345 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19358 CloseHandle(tls.pthread_cond_helper_mutex);
19360 pthread_setspecific(
sTlsKey, NULL);
19371static unsigned __stdcall
master_thread(
void *thread_func_param)
19380#if !defined(__ZEPHYR__)
19381 struct sigaction sa;
19384 memset(&sa, 0,
sizeof(sa));
19385 sa.sa_handler = SIG_IGN;
19386 sigaction(SIGPIPE, &sa, NULL);
19415#if defined(ALTERNATIVE_QUEUE)
19417 if (ctx->client_wait_events != NULL) {
19418 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
19419 event_destroy(ctx->client_wait_events[i]);
19421 mg_free(ctx->client_wait_events);
19424 (void)pthread_cond_destroy(&ctx->
sq_empty);
19425 (void)pthread_cond_destroy(&ctx->
sq_full);
19432#if defined(USE_LUA)
19433 (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
19439#if defined(_MSC_VER)
19440#pragma warning(suppress : 6001)
19454#if defined(USE_MBEDTLS)
19461#elif !defined(NO_SSL)
19464 void *ssl_ctx = (
void *)ctx->
dd.
ssl_ctx;
19470 if (callback_ret == 0) {
19513#if defined(USE_TIMERS)
19526#if defined(USE_LUA)
19540 DWORD dwVersion = 0;
19541 DWORD dwMajorVersion = 0;
19542 DWORD dwMinorVersion = 0;
19544 BOOL wowRet, isWoW =
FALSE;
19546#if defined(_MSC_VER)
19547#pragma warning(push)
19549#pragma warning(disable : 4996)
19551 dwVersion = GetVersion();
19552#if defined(_MSC_VER)
19553#pragma warning(pop)
19556 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
19557 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
19558 dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
19561 wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
19565 (
unsigned)dwMajorVersion,
19566 (
unsigned)dwMinorVersion,
19567 (wowRet ? (isWoW ?
" (WoW64)" :
"") :
" (?)"));
19572#elif defined(__ZEPHYR__)
19575 struct utsname
name;
19589 const char **run_options = options;
19593 while (*run_options) {
19594 if (!strcmp(*run_options, optname)) {
19595 ports_option = run_options[1];
19615 const char *
name, *
value, *default_value;
19616 int idx, ok, workerthreadcount;
19619 void (*exit_callback)(
const struct mg_context *ctx) = 0;
19620 const char **options =
19625 if (error != NULL) {
19645 "Library uninitialized");
19665 (uint64_t)
get_random() ^ (uint64_t)(ptrdiff_t)(options);
19674 tls.pthread_cond_helper_mutex = NULL;
19676 pthread_setspecific(
sTlsKey, &tls);
19679#if !defined(ALTERNATIVE_QUEUE)
19680 ok &= (0 == pthread_cond_init(&ctx->
sq_empty, NULL));
19681 ok &= (0 == pthread_cond_init(&ctx->
sq_full, NULL));
19685#if defined(USE_LUA)
19689 const char *err_msg =
19690 "Cannot initialize thread synchronization objects";
19705 pthread_setspecific(
sTlsKey, NULL);
19709 if ((init != NULL) && (init->
callbacks != NULL)) {
19722#if defined(USE_LUA)
19727 while (options && (
name = *options++) != NULL) {
19735 "Invalid configuration option: %s",
19739 pthread_setspecific(
sTlsKey, NULL);
19741 }
else if ((
value = *options++) == NULL) {
19748 "Invalid configuration option value: %s",
19752 pthread_setspecific(
sTlsKey, NULL);
19755 if (ctx->
dd.
config[idx] != NULL) {
19768 if ((ctx->
dd.
config[i] == NULL) && (default_value != NULL)) {
19784 "Invalid configuration option value: %s",
19788 pthread_setspecific(
sTlsKey, NULL);
19794#if !defined(ALTERNATIVE_QUEUE)
19805 "Invalid configuration option value: %s",
19809 pthread_setspecific(
sTlsKey, NULL);
19814 if (ctx->
squeue == NULL) {
19816 "Out of memory: Cannot allocate %s",
19823 "Out of memory: Cannot allocate %s",
19827 pthread_setspecific(
sTlsKey, NULL);
19837 if (workerthreadcount <= 0) {
19847 "Invalid configuration option value: %s",
19851 pthread_setspecific(
sTlsKey, NULL);
19856#if defined(NO_FILES)
19864 "Invalid configuration option value: %s",
19868 pthread_setspecific(
sTlsKey, NULL);
19875#if defined(USE_LUA)
19877 ctx->lua_bg_log_available = 0;
19878 if (ctx->
dd.
config[LUA_BACKGROUND_SCRIPT] != NULL) {
19880 struct vec opt_vec;
19882 const char *sparams;
19884 memset(ebuf, 0,
sizeof(ebuf));
19885 pthread_mutex_lock(&ctx->lua_bg_mutex);
19888 lua_State *state = mg_lua_context_script_prepare(
19889 ctx->
dd.
config[LUA_BACKGROUND_SCRIPT], ctx, ebuf,
sizeof(ebuf));
19892 "lua_background_script load error: %s",
19899 "Error in script %s: %s",
19903 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19906 pthread_setspecific(
sTlsKey, NULL);
19911 sparams = ctx->
dd.
config[LUA_BACKGROUND_SCRIPT_PARAMS];
19912 if (sparams && sparams[0]) {
19913 lua_getglobal(state,
"mg");
19914 lua_pushstring(state,
"params");
19915 lua_newtable(state);
19917 while ((sparams =
next_option(sparams, &opt_vec, &eq_vec))
19920 state, opt_vec.
ptr, opt_vec.
len, eq_vec.
ptr, eq_vec.
len);
19924 lua_rawset(state, -3);
19929 state = mg_lua_context_script_run(state,
19930 ctx->
dd.
config[LUA_BACKGROUND_SCRIPT],
19936 "lua_background_script start error: %s",
19943 "Error in script %s: %s",
19947 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19950 pthread_setspecific(
sTlsKey, NULL);
19955 ctx->lua_background_state = (
void *)state;
19956 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19959 ctx->lua_background_state = 0;
19964#if !defined(NO_FILESYSTEMS)
19966 const char *err_msg =
"Invalid global password file";
19979 pthread_setspecific(
sTlsKey, NULL);
19984#if defined(USE_MBEDTLS)
19985 if (!mg_sslctx_init(ctx, NULL)) {
19986 const char *err_msg =
"Error initializing SSL context";
19999 pthread_setspecific(
sTlsKey, NULL);
20003#elif !defined(NO_SSL)
20005 const char *err_msg =
"Error initializing SSL context";
20018 pthread_setspecific(
sTlsKey, NULL);
20024 const char *err_msg =
"Failed to setup server ports";
20037 pthread_setspecific(
sTlsKey, NULL);
20042#if !defined(_WIN32) && !defined(__ZEPHYR__)
20044 const char *err_msg =
"Failed to run as configured user";
20057 pthread_setspecific(
sTlsKey, NULL);
20063 const char *err_msg =
"Failed to setup access control list";
20076 pthread_setspecific(
sTlsKey, NULL);
20086 const char *err_msg =
"Not enough memory for worker thread ID array";
20098 pthread_setspecific(
sTlsKey, NULL);
20106 const char *err_msg =
20107 "Not enough memory for worker thread connection array";
20119 pthread_setspecific(
sTlsKey, NULL);
20123#if defined(ALTERNATIVE_QUEUE)
20124 ctx->client_wait_events =
20126 sizeof(ctx->client_wait_events[0]),
20128 if (ctx->client_wait_events == NULL) {
20129 const char *err_msg =
"Not enough memory for worker event array";
20142 pthread_setspecific(
sTlsKey, NULL);
20146 ctx->client_socks =
20148 sizeof(ctx->client_socks[0]),
20150 if (ctx->client_socks == NULL) {
20151 const char *err_msg =
"Not enough memory for worker socket array";
20153 mg_free(ctx->client_wait_events);
20165 pthread_setspecific(
sTlsKey, NULL);
20169 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
20170 ctx->client_wait_events[i] = event_create();
20171 if (ctx->client_wait_events[i] == 0) {
20172 const char *err_msg =
"Error creating worker event %i";
20176 event_destroy(ctx->client_wait_events[i]);
20179 mg_free(ctx->client_wait_events);
20191 pthread_setspecific(
sTlsKey, NULL);
20197#if defined(USE_TIMERS)
20198 if (timers_init(ctx) != 0) {
20199 const char *err_msg =
"Error creating timers";
20211 pthread_setspecific(
sTlsKey, NULL);
20235 long error_no = (long)
ERRNO;
20242 "Cannot start worker thread %i: error %ld",
20255 "Cannot create threads: error %ld",
20264 "Cannot create first worker thread: error %ld",
20268 pthread_setspecific(
sTlsKey, NULL);
20278 pthread_setspecific(
sTlsKey, NULL);
20286 const char **options)
20300 const char **options,
20305 const char *default_value;
20310 if (error != NULL) {
20317 if ((ctx == NULL) || (options == NULL)) {
20324 "Invalid parameters");
20336 "Server already stopped");
20358 while (options && (
name = *options++) != NULL) {
20366 "Invalid option: %s",
20371 }
else if ((
value = *options++) == NULL) {
20378 "Invalid option value: %s",
20384 if (new_dom->
config[idx] != NULL) {
20402 "Mandatory option %s missing",
20412 default_value = ctx->
dd.
config[i];
20413 if ((new_dom->
config[i] == NULL) && (default_value != NULL)) {
20419 new_dom->
next = NULL;
20424#if defined(USE_LUA) && defined(USE_WEBSOCKET)
20425 new_dom->shared_lua_websockets = NULL;
20428#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
20437 "Initializing SSL context failed");
20454 "domain %s already in use",
20461 "Domain %s specified by %s is already in use",
20473 if (dom->
next == NULL) {
20474 dom->
next = new_dom;
20498 static const unsigned feature_set = 0
20502#if !defined(NO_FILES)
20505#if !defined(NO_SSL) || defined(USE_MBEDTLS)
20508#if !defined(NO_CGI)
20511#if defined(USE_IPV6)
20514#if defined(USE_WEBSOCKET)
20517#if defined(USE_LUA)
20520#if defined(USE_DUKTAPE)
20523#if !defined(NO_CACHING)
20526#if defined(USE_SERVER_STATS)
20529#if defined(USE_ZLIB)
20532#if defined(USE_HTTP2)
20535#if defined(USE_X_DOM_SOCKET)
20541#if defined(MG_LEGACY_INTERFACE)
20544#if defined(MG_EXPERIMENTAL_INTERFACES)
20547#if !defined(NO_RESPONSE_BUFFERING)
20550#if defined(MEMORY_DEBUGGING)
20554 return (feature & feature_set);
20561 size_t len = strlen(
src);
20564 if ((
size_t)(end - *dst) >
len) {
20580 char *end, *append_eoobj = NULL, block[256];
20581 size_t system_info_length = 0;
20584 static const char eol[] =
"\r\n", eoobj[] =
"\r\n}\r\n";
20586 static const char eol[] =
"\n", eoobj[] =
"\n}\n";
20589 if ((buffer == NULL) || (buflen < 1)) {
20594 end = buffer + buflen;
20596 if (buflen > (
int)(
sizeof(eoobj) - 1)) {
20598 append_eoobj = buffer;
20600 end -=
sizeof(eoobj) - 1;
20613 "%s\"version\" : \"%s\"",
20622 DWORD dwVersion = 0;
20623 DWORD dwMajorVersion = 0;
20624 DWORD dwMinorVersion = 0;
20627 GetSystemInfo(&si);
20629#if defined(_MSC_VER)
20630#pragma warning(push)
20632#pragma warning(disable : 4996)
20634 dwVersion = GetVersion();
20635#if defined(_MSC_VER)
20636#pragma warning(pop)
20639 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
20640 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
20646 ",%s\"os\" : \"Windows %u.%u\"",
20648 (
unsigned)dwMajorVersion,
20649 (
unsigned)dwMinorVersion);
20656 ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
20658 (
unsigned)si.wProcessorArchitecture,
20659 (
unsigned)si.dwNumberOfProcessors,
20660 (
unsigned)si.dwActiveProcessorMask);
20662#elif defined(__ZEPHYR__)
20667 ",%s\"os\" : \"%s %s\"",
20673 struct utsname
name;
20681 ",%s\"os\" : \"%s %s (%s) - %s\"",
20697 ",%s\"features\" : %lu"
20698 ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
20714#if defined(USE_LUA)
20719 ",%s\"lua_version\" : \"%u (%s)\"",
20721 (
unsigned)LUA_VERSION_NUM,
20725#if defined(USE_DUKTAPE)
20730 ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
20732 (
unsigned)DUK_VERSION / 10000,
20733 ((
unsigned)DUK_VERSION / 100) % 100,
20734 (
unsigned)DUK_VERSION % 100);
20741#if defined(BUILD_DATE)
20742 const char *bd = BUILD_DATE;
20744#if defined(GCC_DIAGNOSTIC)
20745#if GCC_VERSION >= 40900
20746#pragma GCC diagnostic push
20750#pragma GCC diagnostic ignored "-Wdate-time"
20753 const char *bd = __DATE__;
20754#if defined(GCC_DIAGNOSTIC)
20755#if GCC_VERSION >= 40900
20756#pragma GCC diagnostic pop
20762 NULL, NULL, block,
sizeof(block),
",%s\"build\" : \"%s\"", eol, bd);
20771#if defined(_MSC_VER)
20776 ",%s\"compiler\" : \"MSC: %u (%u)\"",
20778 (
unsigned)_MSC_VER,
20779 (
unsigned)_MSC_FULL_VER);
20781#elif defined(__MINGW64__)
20786 ",%s\"compiler\" : \"MinGW64: %u.%u\"",
20788 (
unsigned)__MINGW64_VERSION_MAJOR,
20789 (
unsigned)__MINGW64_VERSION_MINOR);
20795 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20797 (
unsigned)__MINGW32_MAJOR_VERSION,
20798 (
unsigned)__MINGW32_MINOR_VERSION);
20800#elif defined(__MINGW32__)
20805 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20807 (
unsigned)__MINGW32_MAJOR_VERSION,
20808 (
unsigned)__MINGW32_MINOR_VERSION);
20810#elif defined(__clang__)
20815 ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
20819 __clang_patchlevel__,
20820 __clang_version__);
20822#elif defined(__GNUC__)
20827 ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
20829 (
unsigned)__GNUC__,
20830 (
unsigned)__GNUC_MINOR__,
20831 (
unsigned)__GNUC_PATCHLEVEL__);
20833#elif defined(__INTEL_COMPILER)
20838 ",%s\"compiler\" : \"Intel C/C++: %u\"",
20840 (
unsigned)__INTEL_COMPILER);
20842#elif defined(__BORLANDC__)
20847 ",%s\"compiler\" : \"Borland C: 0x%x\"",
20849 (
unsigned)__BORLANDC__);
20851#elif defined(__SUNPRO_C)
20856 ",%s\"compiler\" : \"Solaris: 0x%x\"",
20858 (
unsigned)__SUNPRO_C);
20865 ",%s\"compiler\" : \"other\"",
20878 ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
20880 "ptr:%u, size:%u, time:%u\"",
20882 (
unsigned)
sizeof(
short),
20883 (
unsigned)
sizeof(
int),
20884 (
unsigned)
sizeof(
long),
20885 (
unsigned)
sizeof(
long long),
20886 (
unsigned)
sizeof(
float),
20887 (
unsigned)
sizeof(
double),
20888 (
unsigned)
sizeof(
long double),
20889 (
unsigned)
sizeof(
char),
20890 (
unsigned)
sizeof(
wchar_t),
20891 (
unsigned)
sizeof(
void *),
20892 (
unsigned)
sizeof(
size_t),
20893 (
unsigned)
sizeof(time_t));
20898 if (append_eoobj) {
20899 strcat(append_eoobj, eoobj);
20901 system_info_length +=
sizeof(eoobj) - 1;
20903 return (
int)system_info_length;
20912#if defined(USE_SERVER_STATS)
20913 char *end, *append_eoobj = NULL, block[256];
20914 size_t context_info_length = 0;
20917 static const char eol[] =
"\r\n", eoobj[] =
"\r\n}\r\n";
20919 static const char eol[] =
"\n", eoobj[] =
"\n}\n";
20921 struct mg_memory_stat *ms = get_memory_stat((
struct mg_context *)ctx);
20923 if ((buffer == NULL) || (buflen < 1)) {
20928 end = buffer + buflen;
20930 if (buflen > (
int)(
sizeof(eoobj) - 1)) {
20932 append_eoobj = buffer;
20933 end -=
sizeof(eoobj) - 1;
20940 int blockCount = (
int)ms->blockCount;
20941 int64_t totalMemUsed = ms->totalMemUsed;
20942 int64_t maxMemUsed = ms->maxMemUsed;
20943 if (totalMemUsed > maxMemUsed) {
20944 maxMemUsed = totalMemUsed;
20951 "%s\"memory\" : {%s"
20952 "\"blocks\" : %i,%s"
20970 char start_time_str[64] = {0};
20971 char now_str[64] = {0};
20973 time_t now = time(NULL);
20974 int64_t total_data_read, total_data_written;
20975 int active_connections = (
int)ctx->active_connections;
20976 int max_active_connections = (
int)ctx->max_active_connections;
20977 int total_connections = (
int)ctx->total_connections;
20978 if (active_connections > max_active_connections) {
20979 max_active_connections = active_connections;
20981 if (active_connections > total_connections) {
20982 total_connections = active_connections;
20990 ",%s\"connections\" : {%s"
20991 "\"active\" : %i,%s"
20992 "\"maxActive\" : %i,%s"
20997 active_connections,
20999 max_active_connections,
21006#if !defined(ALTERNATIVE_QUEUE)
21011 ",%s\"queue\" : {%s"
21012 "\"length\" : %i,%s"
21013 "\"filled\" : %i,%s"
21014 "\"maxFilled\" : %i,%s"
21035 ",%s\"requests\" : {%s"
21036 "\"total\" : %lu%s"
21040 (
unsigned long)ctx->total_requests,
21046 mg_atomic_add64((
volatile int64_t *)&ctx->total_data_read, 0);
21047 total_data_written =
21048 mg_atomic_add64((
volatile int64_t *)&ctx->total_data_written, 0);
21053 ",%s\"data\" : {%s"
21061 total_data_written,
21067 sizeof(start_time_str) - 1,
21075 ",%s\"time\" : {%s"
21076 "\"uptime\" : %.0f,%s"
21077 "\"start\" : \"%s\",%s"
21078 "\"now\" : \"%s\"%s"
21082 difftime(now, start_time),
21092 if (append_eoobj) {
21093 strcat(append_eoobj, eoobj);
21095 context_info_length +=
sizeof(eoobj) - 1;
21097 return (
int)context_info_length;
21100 if ((buffer != NULL) && (buflen > 0)) {
21112 if (conn != NULL) {
21118#if defined(MG_EXPERIMENTAL_INTERFACES)
21122mg_get_connection_info(
const struct mg_context *ctx,
21129 char *
end, *append_eoobj = NULL, block[256];
21130 size_t connection_info_length = 0;
21132 const char *state_str =
"unknown";
21135 static const char eol[] =
"\r\n", eoobj[] =
"\r\n}\r\n";
21137 static const char eol[] =
"\n", eoobj[] =
"\n}\n";
21140 if ((buffer == NULL) || (buflen < 1)) {
21145 end = buffer + buflen;
21147 if (buflen > (
int)(
sizeof(eoobj) - 1)) {
21149 append_eoobj = buffer;
21150 end -=
sizeof(eoobj) - 1;
21153 if ((ctx == NULL) || (idx < 0)) {
21168 connection_info_length +=
mg_str_append(&buffer, end,
"{");
21173#if defined(USE_SERVER_STATS)
21174 state = conn->conn_state;
21179 state_str =
"undefined";
21182 state_str =
"not used";
21185 state_str =
"init";
21188 state_str =
"ready";
21191 state_str =
"processing";
21194 state_str =
"processed";
21197 state_str =
"to close";
21200 state_str =
"closing";
21203 state_str =
"closed";
21206 state_str =
"done";
21212 if ((state >= 3) && (state < 9)) {
21217 "%s\"connection\" : {%s"
21219 "\"protocol\" : \"%s\",%s"
21220 "\"addr\" : \"%s\",%s"
21223 "\"handled_requests\" : %u%s"
21237 connection_info_length +=
mg_str_append(&buffer, end, block);
21241 if ((state >= 4) && (state < 6)) {
21246 "%s%s\"request_info\" : {%s"
21247 "\"method\" : \"%s\",%s"
21248 "\"uri\" : \"%s\",%s"
21249 "\"query\" : %s%s%s%s"
21251 (connection_info_length > 1 ?
"," :
""),
21262 connection_info_length +=
mg_str_append(&buffer, end, block);
21266 if ((state >= 2) && (state < 9)) {
21267 char start_time_str[64] = {0};
21268 char close_time_str[64] = {0};
21270 time_t close_time = 0;
21274 sizeof(start_time_str) - 1,
21276#if defined(USE_SERVER_STATS)
21277 close_time = conn->conn_close_time;
21279 if (close_time != 0) {
21280 time_diff = difftime(close_time, start_time);
21282 sizeof(close_time_str) - 1,
21285 time_t now = time(NULL);
21286 time_diff = difftime(now, start_time);
21287 close_time_str[0] = 0;
21294 "%s%s\"time\" : {%s"
21295 "\"uptime\" : %.0f,%s"
21296 "\"start\" : \"%s\",%s"
21297 "\"closed\" : \"%s\"%s"
21299 (connection_info_length > 1 ?
"," :
""),
21308 connection_info_length +=
mg_str_append(&buffer, end, block);
21317 "%s%s\"user\" : {%s"
21318 "\"name\" : \"%s\",%s"
21320 (connection_info_length > 1 ?
"," :
""),
21325 connection_info_length +=
mg_str_append(&buffer, end, block);
21334 "%s%s\"data\" : {%s"
21338 (connection_info_length > 1 ?
"," :
""),
21341 conn->consumed_content,
21343 conn->num_bytes_sent,
21345 connection_info_length +=
mg_str_append(&buffer, end, block);
21353 "%s%s\"state\" : \"%s\"",
21354 (connection_info_length > 1 ?
"," :
""),
21357 connection_info_length +=
mg_str_append(&buffer, end, block);
21360 if (append_eoobj) {
21361 strcat(append_eoobj, eoobj);
21363 connection_info_length +=
sizeof(eoobj) - 1;
21365 return (
int)connection_info_length;
21376 unsigned features_inited = features_to_init;
21389 int file_mutex_init = 1;
21392 int mutexattr_init = 1;
21397 if (key_create == 0) {
21401 if (file_mutex_init == 0) {
21404 failed = wsa = WSAStartup(MAKEWORD(2, 2), &
data);
21408 if (mutexattr_init == 0) {
21410 PTHREAD_MUTEX_RECURSIVE);
21419 (void)WSACleanup();
21421 if (file_mutex_init == 0) {
21422 (void)pthread_mutex_destroy(&global_log_file_lock);
21425 if (mutexattr_init == 0) {
21429 if (key_create == 0) {
21430 (void)pthread_key_delete(
sTlsKey);
21437#if defined(USE_LUA)
21438 lua_init_optional_libraries();
21444#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
21445 || defined(OPENSSL_API_3_0)) \
21446 && !defined(NO_SSL)
21448 if (!mg_openssl_initialized) {
21451 mg_openssl_initialized = 1;
21454 DEBUG_TRACE(
"Initializing SSL failed: %s", ebuf);
21471 return features_inited;
21487#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
21488 if (mg_openssl_initialized) {
21490 mg_openssl_initialized = 0;
21495 (void)WSACleanup();
21496 (void)pthread_mutex_destroy(&global_log_file_lock);
21501 (void)pthread_key_delete(
sTlsKey);
21503#if defined(USE_LUA)
21504 lua_exit_optional_libraries();
static int esc(const char **)
Map escape sequences into their equivalent symbols.
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
static unsigned int total
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t mask
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void on
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t attr
Option_t Option_t TPoint TPoint const char mode
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t src
#define INVALID_HANDLE_VALUE
R__EXTERN C unsigned int sleep(unsigned int seconds)
static void process_new_connection(struct mg_connection *conn)
static int is_authorized_for_put(struct mg_connection *conn)
static int consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
static int parse_http_request(char *buf, int len, struct mg_request_info *ri)
void mg_send_mime_file2(struct mg_connection *conn, const char *path, const char *mime_type, const char *additional_headers)
static pthread_key_t sTlsKey
static int modify_passwords_file(const char *fname, const char *domain, const char *user, const char *pass, const char *ha1)
static void sockaddr_to_string(char *buf, size_t len, const union usa *usa)
static void open_auth_file(struct mg_connection *conn, const char *path, struct mg_file *filep)
int mg_strncasecmp(const char *s1, const char *s2, size_t len)
static int check_authorization(struct mg_connection *conn, const char *path)
#define mg_malloc_ctx(a, c)
static void redirect_to_https_port(struct mg_connection *conn, int port)
static int should_switch_to_protocol(const struct mg_connection *conn)
void mg_unlock_connection(struct mg_connection *conn)
static void mkcol(struct mg_connection *conn, const char *path)
static void remove_bad_file(const struct mg_connection *conn, const char *path)
const struct mg_option * mg_get_valid_options(void)
static int mg_path_suspicious(const struct mg_connection *conn, const char *path)
static int set_non_blocking_mode(SOCKET sock)
static void ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
int mg_send_http_error(struct mg_connection *conn, int status, const char *fmt,...)
static const char * get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
static void mg_cry_internal_impl(const struct mg_connection *conn, const char *func, unsigned line, const char *fmt, va_list ap)
void mg_lock_context(struct mg_context *ctx)
#define MAX_WORKER_THREADS
@ PROTOCOL_TYPE_WEBSOCKET
static void put_file(struct mg_connection *conn, const char *path)
static void do_ssi_exec(struct mg_connection *conn, char *tag)
static void tls_dtor(void *key)
const void * SOCK_OPT_TYPE
static int header_has_option(const char *header, const char *option)
int mg_send_http_redirect(struct mg_connection *conn, const char *target_url, int redirect_code)
int mg_get_cookie(const char *cookie_header, const char *var_name, char *dst, size_t dst_size)
static int ssl_get_client_cert_info(const struct mg_connection *conn, struct mg_client_cert *client_cert)
#define mg_cry_ctx_internal(ctx, fmt,...)
static void mg_snprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, const char *fmt,...)
#define mg_opendir(conn, x)
static char * mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
static int put_dir(struct mg_connection *conn, const char *path)
static void send_static_cache_header(struct mg_connection *conn)
static void handle_cgi_request(struct mg_connection *conn, const char *prog, unsigned char cgi_config_idx)
static ptrdiff_t mg_atomic_dec(volatile ptrdiff_t *addr)
static int print_dav_dir_entry(struct de *de, void *data)
static void delete_file(struct mg_connection *conn, const char *path)
#define mg_calloc_ctx(a, b, c)
struct mg_connection * mg_connect_websocket_client_secure(const struct mg_client_options *client_options, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
int mg_get_server_ports(const struct mg_context *ctx, int size, struct mg_server_port *ports)
static ptrdiff_t mg_atomic_inc(volatile ptrdiff_t *addr)
int mg_printf(struct mg_connection *conn, const char *fmt,...)
static int abort_cgi_process(void *data)
static int should_keep_alive(const struct mg_connection *conn)
static __inline void * mg_malloc(size_t a)
static int mg_fopen(const struct mg_connection *conn, const char *path, int mode, struct mg_file *filep)
void mg_disable_connection_keep_alive(struct mg_connection *conn)
static void mg_global_lock(void)
static void handle_static_file_request(struct mg_connection *conn, const char *path, struct mg_file *filep, const char *mime_type, const char *additional_headers)
static int ssl_use_pem_file(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *pem, const char *chain)
static const char * ssl_error(void)
static int must_hide_file(struct mg_connection *conn, const char *path)
static void log_access(const struct mg_connection *)
struct mg_connection * mg_connect_client_secure(const struct mg_client_options *client_options, char *error_buffer, size_t error_buffer_size)
#define mg_remove(conn, x)
int mg_send_http_ok(struct mg_connection *conn, const char *mime_type, long long content_length)
static void close_all_listening_sockets(struct mg_context *ctx)
void mg_send_file(struct mg_connection *conn, const char *path)
static void send_authorization_request(struct mg_connection *conn, const char *realm)
static pid_t spawn_process(struct mg_connection *conn, const char *prog, char *envblk, char *envp[], int fdin[2], int fdout[2], int fderr[2], const char *dir, unsigned char cgi_config_idx)
static int check_password(const char *method, const char *ha1, const char *uri, const char *nonce, const char *nc, const char *cnonce, const char *qop, const char *response)
static int check_acl(struct mg_context *phys_ctx, const union usa *sa)
static const struct mg_option config_options[]
static const struct mg_http_method_info * get_http_method_info(const char *method)
#define STOP_FLAG_IS_ZERO(f)
const char * mg_get_response_code_text(const struct mg_connection *conn, int response_code)
static int get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
static void mg_cry_internal_wrap(const struct mg_connection *conn, struct mg_context *ctx, const char *func, unsigned line, const char *fmt,...)
static int set_uid_option(struct mg_context *phys_ctx)
static int switch_domain_context(struct mg_connection *conn)
static struct mg_connection * fake_connection(struct mg_connection *fc, struct mg_context *ctx)
static void reset_per_request_attributes(struct mg_connection *conn)
static void handle_file_based_request(struct mg_connection *conn, const char *path, struct mg_file *filep)
#define FUNCTION_MAY_BE_UNUSED
static pthread_mutex_t * ssl_mutexes
static int get_option_index(const char *name)
static char * mg_strdup(const char *str)
static void send_no_cache_header(struct mg_connection *conn)
static void master_thread_run(struct mg_context *ctx)
static int prepare_cgi_environment(struct mg_connection *conn, const char *prog, struct cgi_environment *env, unsigned char cgi_config_idx)
static const char month_names[][4]
const struct mg_response_info * mg_get_response_info(const struct mg_connection *conn)
static __inline void * mg_realloc(void *a, size_t b)
static void accept_new_connection(const struct socket *listener, struct mg_context *ctx)
static volatile ptrdiff_t cryptolib_users
static int get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
static pthread_mutex_t global_lock_mutex
struct mg_context * mg_start2(struct mg_init_data *init, struct mg_error_data *error)
#define CGI_ENVIRONMENT_SIZE
static int parse_http_headers(char **buf, struct mg_header hdr[(64)])
static long ssl_get_protocol(int version_id)
void * mg_get_user_context_data(const struct mg_connection *conn)
static int mg_init_library_called
long long mg_store_body(struct mg_connection *conn, const char *path)
struct mg_connection * mg_download(const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, const char *fmt,...)
#define DEBUG_ASSERT(cond)
static size_t mg_str_append(char **dst, char *end, const char *src)
static int pull_inner(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
int mg_get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int timeout)
#define MG_FILE_COMPRESSION_SIZE_LIMIT
#define USA_IN_PORT_UNSAFE(s)
static struct mg_connection * mg_connect_client_impl(const struct mg_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len)
unsigned mg_check_feature(unsigned feature)
static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
static int mg_send_http_error_impl(struct mg_connection *conn, int status, const char *fmt, va_list args)
struct mg_context * mg_start(const struct mg_callbacks *callbacks, void *user_data, const char **options)
#define MG_FOPEN_MODE_READ
#define STOP_FLAG_ASSIGN(f, v)
static int extention_matches_script(struct mg_connection *conn, const char *filename)
static void get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
void mg_set_websocket_handler(struct mg_context *ctx, const char *uri, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, void *cbdata)
int mg_start_domain(struct mg_context *ctx, const char **options)
static pthread_mutexattr_t pthread_mutex_attr
void mg_unlock_context(struct mg_context *ctx)
static int ssl_servername_callback(SSL *ssl, int *ad, void *arg)
int mg_modify_passwords_file(const char *fname, const char *domain, const char *user, const char *pass)
static char * skip_quoted(char **buf, const char *delimiters, const char *whitespace, char quotechar)
static void fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
int mg_start_thread(mg_thread_func_t func, void *param)
static const char * get_header(const struct mg_header *hdr, int num_hdr, const char *name)
static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
static int init_ssl_ctx_impl(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *pem, const char *chain)
static int connect_socket(struct mg_context *ctx, const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, SOCKET *sock, union usa *sa)
unsigned mg_init_library(unsigned features)
struct mg_connection * mg_connect_client(const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size)
static int forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
static int set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
static int skip_to_end_of_word_and_terminate(char **ppw, int eol)
static int get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
static int set_tcp_nodelay(const struct socket *so, int nodelay_on)
int mg_get_var(const char *data, size_t data_len, const char *name, char *dst, size_t dst_len)
#define ARRAY_SIZE(array)
static int parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
static int get_first_ssl_listener_index(const struct mg_context *ctx)
void mg_send_mime_file(struct mg_connection *conn, const char *path, const char *mime_type)
const char * mg_get_header(const struct mg_connection *conn, const char *name)
#define mg_mkdir(conn, path, mode)
int mg_split_form_urlencoded(char *data, struct mg_header *form_fields, unsigned num_form_fields)
static int hexdump2string(void *mem, int memlen, char *buf, int buflen)
static const struct mg_http_method_info http_methods[]
static int mg_poll(struct pollfd *pfd, unsigned int n, int milliseconds, const stop_flag_t *stop_flag)
static void handle_directory_request(struct mg_connection *conn, const char *dir)
static int set_ports_option(struct mg_context *phys_ctx)
static int read_auth_file(struct mg_file *filep, struct read_auth_file_struct *workdata, int depth)
static int mg_start_thread_with_id(mg_thread_func_t func, void *param, pthread_t *threadidptr)
unsigned mg_exit_library(void)
static void * load_tls_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw, int *feature_missing)
static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
int mg_send_digest_access_authentication_request(struct mg_connection *conn, const char *realm)
static const char * mg_strcasestr(const char *big_str, const char *small_str)
struct mg_connection * mg_connect_websocket_client(const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
static void handle_ssi_file_request(struct mg_connection *conn, const char *path, struct mg_file *filep)
int mg_write(struct mg_connection *conn, const void *buf, size_t len)
static int set_throttle(const char *spec, const union usa *rsa, const char *uri)
static void ssl_info_callback(const SSL *ssl, int what, int ret)
static void bin2str(char *to, const unsigned char *p, size_t len)
const struct mg_request_info * mg_get_request_info(const struct mg_connection *conn)
#define MG_FOPEN_MODE_APPEND
char * mg_md5(char buf[33],...)
#define STOP_FLAG_IS_TWO(f)
static const char * next_option(const char *list, struct vec *val, struct vec *eq_val)
static const char * suggest_connection_header(const struct mg_connection *conn)
static ptrdiff_t match_prefix_strlen(const char *pattern, const char *str)
static int alloc_vprintf(char **out_buf, char *prealloc_buf, size_t prealloc_size, const char *fmt, va_list ap)
static time_t parse_date_string(const char *datetime)
static void do_ssi_include(struct mg_connection *conn, const char *ssi, char *tag, int include_level)
static void uninitialize_openssl(void)
int mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
static int parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
static const struct @143 abs_uri_protocols[]
int mg_modify_passwords_file_ha1(const char *fname, const char *domain, const char *user, const char *ha1)
static void send_options(struct mg_connection *conn)
static int lowercase(const char *s)
static void release_handler_ref(struct mg_connection *conn, struct mg_handler_info *handler_info)
static int parse_range_header(const char *header, int64_t *a, int64_t *b)
static int mg_stat(const struct mg_connection *conn, const char *path, struct mg_file_stat *filep)
static int get_uri_type(const char *uri)
#define DEBUG_TRACE(fmt,...)
static void get_system_name(char **sysName)
int mg_url_encode(const char *src, char *dst, size_t dst_len)
static const char * header_val(const struct mg_connection *conn, const char *header)
#define mg_cry_internal(conn, fmt,...)
static int set_acl_option(struct mg_context *phys_ctx)
static void mg_set_thread_name(const char *name)
static void get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
static int set_blocking_mode(SOCKET sock)
static void send_file_data(struct mg_connection *conn, struct mg_file *filep, int64_t offset, int64_t len)
#define MAX_CGI_ENVIR_VARS
static char * mg_strdup_ctx(const char *str, struct mg_context *ctx)
struct mg_connection * mg_connect_websocket_client_extensions(const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, const char *extensions, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded)
static int parse_auth_header(struct mg_connection *conn, char *buf, size_t buf_size, struct ah *ah)
void mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
int mg_get_var2(const char *data, size_t data_len, const char *name, char *dst, size_t dst_len, size_t occurrence)
static int is_not_modified(const struct mg_connection *conn, const struct mg_file_stat *filestat)
static void worker_thread_run(struct mg_connection *conn)
static void interpret_uri(struct mg_connection *conn, char *filename, size_t filename_buf_len, struct mg_file_stat *filestat, int *is_found, int *is_script_resource, int *is_websocket_request, int *is_put_or_delete_request, int *is_template_text)
static const char * get_proto_name(const struct mg_connection *conn)
static void * master_thread(void *thread_func_param)
static void mg_set_handler_type(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *uri, int handler_type, int is_delete_request, mg_request_handler handler, struct mg_websocket_subprotocols *subprotocols, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, mg_authorization_handler auth_handler, void *cbdata)
static int is_file_opened(const struct mg_file_access *fileacc)
static int get_http_header_len(const char *buf, int buflen)
struct mg_connection * mg_connect_websocket_client_secure_extensions(const struct mg_client_options *client_options, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, const char *extensions, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
void mg_close_connection(struct mg_connection *conn)
static int is_valid_port(unsigned long port)
static void handle_propfind(struct mg_connection *conn, const char *path, struct mg_file_stat *filep)
static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
#define mg_realloc_ctx(a, b, c)
static void send_additional_header(struct mg_connection *conn)
static int push_all(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int len)
static int is_put_or_delete_method(const struct mg_connection *conn)
static int read_message(FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread)
static int print_dir_entry(struct de *de)
#define MG_FOPEN_MODE_WRITE
void * mg_get_user_connection_data(const struct mg_connection *conn)
static int authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
static void send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int)
#define mg_static_assert(cond, txt)
#define SOCKET_TIMEOUT_QUANTUM
static void produce_socket(struct mg_context *ctx, const struct socket *sp)
static ptrdiff_t match_prefix(const char *pattern, size_t pattern_len, const char *str)
int mg_send_chunk(struct mg_connection *conn, const char *chunk, unsigned int chunk_len)
static void remove_dot_segments(char *inout)
static int get_request_handler(struct mg_connection *conn, int handler_type, mg_request_handler *handler, struct mg_websocket_subprotocols **subprotocols, mg_websocket_connect_handler *connect_handler, mg_websocket_ready_handler *ready_handler, mg_websocket_data_handler *data_handler, mg_websocket_close_handler *close_handler, mg_authorization_handler *auth_handler, void **cbdata, struct mg_handler_info **handler_info)
void mg_set_auth_handler(struct mg_context *ctx, const char *uri, mg_authorization_handler handler, void *cbdata)
int mg_start_domain2(struct mg_context *ctx, const char **options, struct mg_error_data *error)
static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
static const struct @142 builtin_mime_types[]
static int extention_matches_template_text(struct mg_connection *conn, const char *filename)
static int is_in_script_path(const struct mg_connection *conn, const char *path)
static int should_decode_query_string(const struct mg_connection *conn)
static double mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
static void free_context(struct mg_context *ctx)
static int sslize(struct mg_connection *conn, int(*func)(SSL *), const struct mg_client_options *client_options)
static void legacy_init(const char **options)
static void construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
int mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
static int refresh_trust(struct mg_connection *conn)
void * mg_get_thread_pointer(const struct mg_connection *conn)
static int compare_dir_entries(const void *p1, const void *p2)
static void mg_vsnprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, const char *fmt, va_list ap)
static int should_decode_url(const struct mg_connection *conn)
static int mg_construct_local_link(const struct mg_connection *conn, char *buf, size_t buflen, const char *define_proto, int define_port, const char *define_uri)
char static_assert_replacement[1]
#define ERROR_TRY_AGAIN(err)
static unsigned long mg_current_thread_id(void)
static void mg_strlcpy(char *dst, const char *src, size_t n)
static int remove_directory(struct mg_connection *conn, const char *dir)
static const char * get_http_version(const struct mg_connection *conn)
static __inline void * mg_calloc(size_t a, size_t b)
static void handle_request(struct mg_connection *)
static int parse_http_response(char *buf, int len, struct mg_response_info *ri)
static void * cryptolib_dll_handle
static uint64_t mg_get_current_time_ns(void)
const char * mg_get_builtin_mime_type(const char *path)
static const char * mg_fgets(char *buf, size_t size, struct mg_file *filep)
int mg_read(struct mg_connection *conn, void *buf, size_t len)
#define IGNORE_UNUSED_RESULT(a)
static void addenv(struct cgi_environment *env, const char *fmt,...)
static void discard_unread_request_data(struct mg_connection *conn)
int mg_strcasecmp(const char *s1, const char *s2)
static int mg_fclose(struct mg_file_access *fileacc)
static struct mg_connection * mg_connect_websocket_client_impl(const struct mg_client_options *client_options, int use_ssl, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, const char *extensions, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata)
static void * worker_thread(void *thread_func_param)
static __inline void mg_free(void *a)
static void handle_request_stat_log(struct mg_connection *conn)
int mg_check_digest_access_authentication(struct mg_connection *conn, const char *realm, const char *filename)
static int mg_join_thread(pthread_t threadid)
static void mg_global_unlock(void)
int mg_get_system_info(char *buffer, int buflen)
static void handle_not_modified_static_file_request(struct mg_connection *conn, struct mg_file *filep)
static int init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
static void close_socket_gracefully(struct mg_connection *conn)
struct mg_context * mg_get_context(const struct mg_connection *conn)
static int is_ssl_port_used(const char *ports)
static void init_connection(struct mg_connection *conn)
static int print_props(struct mg_connection *conn, const char *uri, const char *name, struct mg_file_stat *filep)
static int dir_scan_callback(struct de *de, void *data)
static void set_close_on_exec(int fd, const struct mg_connection *conn, struct mg_context *ctx)
static int get_month_index(const char *s)
void mg_set_websocket_handler_with_subprotocols(struct mg_context *ctx, const char *uri, struct mg_websocket_subprotocols *subprotocols, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, void *cbdata)
static void * ssllib_dll_handle
static int mg_fgetc(struct mg_file *filep)
@ CONNECTION_TYPE_RESPONSE
@ CONNECTION_TYPE_INVALID
@ CONNECTION_TYPE_REQUEST
#define PASSWORDS_FILE_NAME
static void close_connection(struct mg_connection *conn)
@ ENABLE_DIRECTORY_LISTING
@ ACCESS_CONTROL_ALLOW_ORIGIN
@ ALLOW_INDEX_SCRIPT_SUB_RES
@ ACCESS_CONTROL_ALLOW_HEADERS
@ SSL_DEFAULT_VERIFY_PATHS
@ ACCESS_CONTROL_ALLOW_METHODS
@ STATIC_FILE_CACHE_CONTROL
@ PUT_DELETE_PASSWORDS_FILE
@ ENABLE_AUTH_DOMAIN_CHECK
@ ACCESS_CONTROL_ALLOW_CREDENTIALS
static int initialize_openssl(char *ebuf, size_t ebuf_len)
static int substitute_index_file(struct mg_connection *conn, char *path, size_t path_len, struct mg_file_stat *filestat)
void mg_stop(struct mg_context *ctx)
#define STRUCT_FILE_INITIALIZER
static volatile ptrdiff_t thread_idx_max
void * mg_get_user_data(const struct mg_context *ctx)
static int scan_directory(struct mg_connection *conn, const char *dir, void *data, int(*cb)(struct de *, void *))
static int push_inner(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int len, double timeout)
const char * mg_version(void)
static uint64_t get_random(void)
void mg_lock_connection(struct mg_connection *conn)
int mg_send_file_body(struct mg_connection *conn, const char *path)
static int is_valid_http_method(const char *method)
static void url_decode_in_place(char *buf)
int mg_websocket_client_write(struct mg_connection *conn, int opcode, const char *data, size_t data_len)
int mg_response_header_add(struct mg_connection *conn, const char *header, const char *value, int value_len)
void *(* mg_thread_func_t)(void *)
int mg_response_header_send(struct mg_connection *conn)
int mg_websocket_write(struct mg_connection *conn, int opcode, const char *data, size_t data_len)
#define PRINTF_FORMAT_STRING(s)
int(* mg_authorization_handler)(struct mg_connection *conn, void *cbdata)
@ MG_CONFIG_TYPE_DIRECTORY
@ MG_CONFIG_TYPE_EXT_PATTERN
@ MG_CONFIG_TYPE_STRING_MULTILINE
@ MG_CONFIG_TYPE_STRING_LIST
@ MG_CONFIG_TYPE_YES_NO_OPTIONAL
@ MG_FEATURES_X_DOMAIN_SOCKET
@ MG_FEATURES_COMPRESSION
@ MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE
@ MG_WEBSOCKET_OPCODE_PONG
@ MG_WEBSOCKET_OPCODE_PING
void(* mg_websocket_ready_handler)(struct mg_connection *, void *)
int mg_response_header_add_lines(struct mg_connection *conn, const char *http1_headers)
#define PRINTF_ARGS(x, y)
int(* mg_websocket_data_handler)(struct mg_connection *, int, char *, size_t, void *)
int(* mg_request_handler)(struct mg_connection *conn, void *cbdata)
int mg_response_header_start(struct mg_connection *conn, int status)
void(* mg_websocket_close_handler)(const struct mg_connection *, void *)
int(* mg_websocket_connect_handler)(const struct mg_connection *, void *)
MD5_STATIC void md5_finish(md5_state_t *pms, md5_byte_t digest[16])
MD5_STATIC void md5_init(md5_state_t *pms)
MD5_STATIC void md5_append(md5_state_t *pms, const md5_byte_t *data, size_t nbytes)
void(off) SmallVectorTemplateBase< T
RooArgList L(Args_t &&... args)
struct asn1_integer ASN1_INTEGER
#define SSL_OP_CIPHER_SERVER_PREFERENCE
struct ssl_ctx_st SSL_CTX
#define SSL_OP_NO_TLSv1_3
#define SSL_OP_SINGLE_DH_USE
#define SSL_VERIFY_FAIL_IF_NO_PEER_CERT
#define SSL_SESS_CACHE_BOTH
#define SSL_TLSEXT_ERR_OK
#define SSL_TLSEXT_ERR_NOACK
#define OPENSSL_INIT_LOAD_CRYPTO_STRINGS
#define SSL_OP_NO_COMPRESSION
#define SSL_ERROR_SYSCALL
#define SSL_ERROR_WANT_READ
#define SSL_ERROR_WANT_ACCEPT
#define SSL_ERROR_WANT_X509_LOOKUP
#define SSL_CB_HANDSHAKE_START
#define SSL_ERROR_WANT_CONNECT
#define SSL_OP_NO_TLSv1_2
#define SSL_OP_NO_RENEGOTIATION
struct x509_name X509_NAME
#define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
#define TLSEXT_NAMETYPE_host_name
#define SSL_CB_HANDSHAKE_DONE
#define OPENSSL_INIT_LOAD_SSL_STRINGS
#define SSL_OP_NO_TLSv1_1
static int tls_feature_missing[TLS_END_OF_LIST]
#define SSL_ERROR_WANT_WRITE
static void free_buffered_response_header_list(struct mg_connection *conn)
SHA_API void SHA1_Init(SHA_CTX *context)
SHA_API void SHA1_Update(SHA_CTX *context, const uint8_t *data, const uint32_t len)
SHA_API void SHA1_Final(unsigned char *digest, SHA_CTX *context)
struct mg_connection * conn
struct mg_connection * conn
int(* init_ssl)(void *ssl_ctx, void *user_data)
int(* log_message)(const struct mg_connection *, const char *message)
void *(* init_thread)(const struct mg_context *ctx, int thread_type)
void(* end_request)(const struct mg_connection *, int reply_status_code)
int(* init_connection)(const struct mg_connection *conn, void **conn_data)
void(* connection_close)(const struct mg_connection *)
int(* http_error)(struct mg_connection *conn, int status, const char *errmsg)
void(* exit_context)(const struct mg_context *ctx)
int(* init_ssl_domain)(const char *server_domain, void *ssl_ctx, void *user_data)
int(* external_ssl_ctx)(void **ssl_ctx, void *user_data)
void(* exit_thread)(const struct mg_context *ctx, int thread_type, void *thread_pointer)
int(* begin_request)(struct mg_connection *)
int(* log_access)(const struct mg_connection *, const char *message)
void(* init_context)(const struct mg_context *ctx)
void(* connection_closed)(const struct mg_connection *)
int(* external_ssl_ctx_domain)(const char *server_domain, void **ssl_ctx, void *user_data)
time_t last_throttle_time
struct mg_response_info response_info
struct mg_request_info request_info
struct mg_context * phys_ctx
struct mg_domain_context * dom_ctx
pthread_t * worker_threadids
unsigned long starter_thread_idx
struct mg_connection * worker_connections
struct socket * listening_sockets
pthread_mutex_t thread_mutex
struct mg_callbacks callbacks
struct mg_domain_context dd
struct pollfd * listening_socket_fds
unsigned int num_listening_sockets
unsigned int max_request_size
unsigned int cfg_worker_threads
pthread_mutex_t nonce_mutex
char * config[NUM_OPTIONS]
unsigned long nonce_count
int64_t ssl_cert_last_mtime
struct mg_domain_context * next
struct mg_handler_info * handlers
struct mg_file_access access
mg_request_handler handler
mg_authorization_handler auth_handler
mg_websocket_close_handler close_handler
struct mg_handler_info * next
mg_websocket_connect_handler connect_handler
struct mg_websocket_subprotocols * subprotocols
mg_websocket_data_handler data_handler
mg_websocket_ready_handler ready_handler
const struct mg_callbacks * callbacks
const char ** configuration_options
const char * default_value
struct mg_header http_headers[(64)]
const char * local_uri_raw
const char * request_method
struct mg_client_cert * client_cert
const char * query_string
const char * http_version
const char * acceptedWebSocketSubprotocol
struct mg_header http_headers[(64)]
const char * http_version
const char ** subprotocols
struct mg_connection * conn
enum ssl_func_category required
mg_websocket_close_handler close_handler
mg_websocket_data_handler data_handler
struct mg_connection * conn