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,
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)
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/engine.h>
1748#include <openssl/err.h>
1749#include <openssl/opensslv.h>
1750#include <openssl/pem.h>
1751#include <openssl/ssl.h>
1752#include <openssl/tls1.h>
1753#include <openssl/x509.h>
1755#if defined(WOLFSSL_VERSION)
1758#include "wolfssl_extras.inl"
1761#if defined(OPENSSL_IS_BORINGSSL)
1772#define CONF_modules_unload(a) ((void)0)
1773#define ENGINE_cleanup() ((void)0)
1777#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
1778#if !defined(OPENSSL_API_3_0)
1779#define OPENSSL_API_3_0
1781#define OPENSSL_REMOVE_THREAD_STATE()
1783#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1784#if !defined(OPENSSL_API_1_1)
1785#define OPENSSL_API_1_1
1787#define OPENSSL_REMOVE_THREAD_STATE()
1789#if !defined(OPENSSL_API_1_0)
1790#define OPENSSL_API_1_0
1792#define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
1806#if !defined(NO_CACHING)
1827#if defined(USE_IPV6)
1828 struct sockaddr_in6 sin6;
1830#if defined(USE_X_DOM_SOCKET)
1831 struct sockaddr_un sun;
1835#if defined(USE_X_DOM_SOCKET)
1836static unsigned short
1839 if (s->
sa.sa_family == AF_INET)
1840 return s->
sin.sin_port;
1841#if defined(USE_IPV6)
1842 if (s->
sa.sa_family == AF_INET6)
1843 return s->sin6.sin6_port;
1848#if defined(USE_IPV6)
1849#define USA_IN_PORT_UNSAFE(s) \
1850 (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
1852#define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
1883#define STRUCT_FILE_INITIALIZER \
1885 {(uint64_t)0, (time_t)0, 0, 0, 0}, \
1921#if defined(__linux__)
1922 ALLOW_SENDFILE_CALL,
1925 CASE_SENSITIVE_FILES,
1931#if defined(USE_WEBSOCKET)
1933 ENABLE_WEBSOCKET_PING_PONG,
1938 LUA_BACKGROUND_SCRIPT,
1939 LUA_BACKGROUND_SCRIPT_PARAMS,
1941#if defined(USE_HTTP2)
1955#if defined(USE_TIMERS)
1963#if defined(USE_TIMERS)
1967#if defined(USE_4_CGI)
1971 CGI3_INTERPRETER_ARGS,
1972#if defined(USE_TIMERS)
1979 CGI4_INTERPRETER_ARGS,
1980#if defined(USE_TIMERS)
2011 LUA_SCRIPT_EXTENSIONS,
2012 LUA_SERVER_PAGE_EXTENSIONS,
2013#if defined(MG_EXPERIMENTAL_INTERFACES)
2017#if defined(USE_DUKTAPE)
2018 DUKTAPE_SCRIPT_EXTENSIONS,
2021#if defined(USE_WEBSOCKET)
2024#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2025 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)
2186#if !defined(NO_CACHING)
2203 "config_options and enum not sync");
2260#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2262 struct mg_shared_lua_websocket_list *shared_lua_websockets;
2273#if defined(STOP_FLAG_NEEDS_LOCK)
2296 sf = mg_atomic_compare_and_swap(
f, *
f,
v);
2303#define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
2304#define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
2305#define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
2328#if defined(USE_SERVER_STATS)
2329 volatile ptrdiff_t active_connections;
2330 volatile ptrdiff_t max_active_connections;
2331 volatile ptrdiff_t total_connections;
2332 volatile ptrdiff_t total_requests;
2333 volatile int64_t total_data_read;
2334 volatile int64_t total_data_written;
2348#if defined(ALTERNATIVE_QUEUE)
2349 struct socket *client_socks;
2350 void **client_wait_events;
2360#if defined(USE_SERVER_STATS)
2368#if defined(USE_SERVER_STATS)
2369 struct mg_memory_stat ctx_memory;
2377#if defined(USE_TIMERS)
2378 struct ttimers *timers;
2383 void *lua_background_state;
2384 pthread_mutex_t lua_bg_mutex;
2385 int lua_bg_log_available;
2408#if defined(USE_SERVER_STATS)
2409static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2411static struct mg_memory_stat *
2415 return &(ctx->ctx_memory);
2417 return &mg_common_memory;
2434#if defined(USE_HTTP2)
2435#if !defined(HTTP2_DYN_TABLE_SIZE)
2436#define HTTP2_DYN_TABLE_SIZE (256)
2439struct mg_http2_connection {
2441 uint32_t dyn_table_size;
2442 struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
2452#if defined(USE_HTTP2)
2453 struct mg_http2_connection http2;
2462#if defined(USE_SERVER_STATS)
2472#if defined(USE_SERVER_STATS)
2473 time_t conn_close_time;
2475 double processing_time;
2501#if defined(USE_WEBSOCKET)
2502 int in_websocket_handling;
2504#if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
2505 && defined(MG_EXPERIMENTAL_INTERFACES)
2507 int websocket_deflate_server_max_windows_bits;
2508 int websocket_deflate_client_max_windows_bits;
2509 int websocket_deflate_server_no_context_takeover;
2510 int websocket_deflate_client_no_context_takeover;
2511 int websocket_deflate_initialized;
2512 int websocket_deflate_flush;
2513 z_stream websocket_deflate_state;
2514 z_stream websocket_inflate_state;
2529#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2530 void *lua_websocket_state;
2546#define mg_cry_internal(conn, fmt, ...) \
2547 mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
2549#define mg_cry_ctx_internal(ctx, fmt, ...) \
2550 mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
2560#if !defined(NO_THREAD_NAME)
2561#if defined(_WIN32) && defined(_MSC_VER)
2565#pragma pack(push, 8)
2566typedef struct tagTHREADNAME_INFO {
2574#elif defined(__linux__)
2576#include <sys/prctl.h>
2577#include <sys/sendfile.h>
2578#if defined(ALTERNATIVE_QUEUE)
2579#include <sys/eventfd.h>
2583#if defined(ALTERNATIVE_QUEUE)
2588 int evhdl = eventfd(0, EFD_CLOEXEC);
2609event_wait(
void *eventhdl)
2618 evhdl = *(
int *)eventhdl;
2620 s = (
int)read(evhdl, &u,
sizeof(u));
2621 if (s !=
sizeof(u)) {
2631event_signal(
void *eventhdl)
2640 evhdl = *(
int *)eventhdl;
2642 s = (
int)write(evhdl, &u,
sizeof(u));
2643 if (s !=
sizeof(u)) {
2652event_destroy(
void *eventhdl)
2660 evhdl = *(
int *)eventhdl;
2672#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2675 pthread_mutex_t mutex;
2684 struct posix_event *ret =
mg_malloc(
sizeof(
struct posix_event));
2689 if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2694 if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2696 pthread_mutex_destroy(&(ret->mutex));
2706event_wait(
void *eventhdl)
2708 struct posix_event *ev = (
struct posix_event *)eventhdl;
2709 pthread_mutex_lock(&(ev->mutex));
2710 while (!ev->signaled) {
2711 pthread_cond_wait(&(ev->cond), &(ev->mutex));
2714 pthread_mutex_unlock(&(ev->mutex));
2720event_signal(
void *eventhdl)
2722 struct posix_event *ev = (
struct posix_event *)eventhdl;
2723 pthread_mutex_lock(&(ev->mutex));
2724 pthread_cond_signal(&(ev->cond));
2726 pthread_mutex_unlock(&(ev->mutex));
2732event_destroy(
void *eventhdl)
2734 struct posix_event *ev = (
struct posix_event *)eventhdl;
2735 pthread_cond_destroy(&(ev->cond));
2736 pthread_mutex_destroy(&(ev->mutex));
2745 char threadName[16 + 1];
2748 NULL, NULL, threadName,
sizeof(threadName),
"civetweb-%s",
name);
2751#if defined(_MSC_VER)
2754 THREADNAME_INFO info;
2755 info.dwType = 0x1000;
2756 info.szName = threadName;
2757 info.dwThreadID = ~0U;
2760 RaiseException(0x406D1388,
2762 sizeof(info) /
sizeof(ULONG_PTR),
2763 (ULONG_PTR *)&info);
2764 } __except (EXCEPTION_EXECUTE_HANDLER) {
2766#elif defined(__MINGW32__)
2769#elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
2770 && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
2772#if defined(__MACH__)
2774 (void)pthread_setname_np(threadName);
2776 (void)pthread_setname_np(pthread_self(), threadName);
2778#elif defined(__linux__)
2784 (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
2803#define MG_FOPEN_MODE_NONE (0)
2806#define MG_FOPEN_MODE_READ (1)
2809#define MG_FOPEN_MODE_WRITE (2)
2812#define MG_FOPEN_MODE_APPEND (4)
2822 return (fileacc->
fp != NULL);
2826#if !defined(NO_FILESYSTEMS)
2836 const uint8_t *
c = (
const uint8_t *)path;
2839 if ((
c == NULL) || (
c[0] == 0)) {
2850 if ((*
c ==
'>') || (*
c ==
'<') || (*
c ==
'|')) {
2854 if ((*
c ==
'*') || (*
c ==
'?')) {
2905 wchar_t wbuf[UTF16_PATH_MAX];
2906 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
2909 filep->
access.
fp = _wfopen(wbuf, L
"rb");
2912 filep->
access.
fp = _wfopen(wbuf, L
"wb");
2915 filep->
access.
fp = _wfopen(wbuf, L
"ab");
2923 filep->
access.
fp = fopen(path,
"r");
2926 filep->
access.
fp = fopen(path,
"w");
2929 filep->
access.
fp = fopen(path,
"a");
2952 if (fileacc != NULL) {
2953 if (fileacc->
fp != NULL) {
2954 ret = fclose(fileacc->
fp);
2957 memset(fileacc, 0,
sizeof(*fileacc));
2967 for (; *
src !=
'\0' &&
n > 1;
n--) {
2977 return tolower((
unsigned char)*s);
2989 }
while (diff == 0 &&
s1[-1] !=
'\0' && --
len > 0);
3003 }
while (diff == 0 &&
s1[-1] !=
'\0');
3040 size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3042 if (big_len >= small_len) {
3043 for (i = 0; i <= (big_len - small_len); i++) {
3073#if defined(__clang__)
3074#pragma clang diagnostic push
3075#pragma clang diagnostic ignored "-Wformat-nonliteral"
3081 ok = (
n >= 0) && ((
size_t)
n < buflen);
3083#if defined(__clang__)
3084#pragma clang diagnostic pop
3096 "truncating vsnprintf buffer: [%.*s]",
3097 (
int)((buflen > 200) ? 200 : (buflen - 1)),
3099 n = (
int)buflen - 1;
3141 }
else if (!ctx || ctx->
dd.
config[i] == NULL) {
3148#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3160 return (ctx == NULL) ? NULL : ctx->
user_data;
3190 if (const_conn != NULL) {
3220 memset(ports, 0,
sizeof(*ports) * (
size_t)
size);
3250#if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
3251#define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
3263 if (
usa->
sa.sa_family == AF_INET) {
3264 getnameinfo(&
usa->
sa,
3272#if defined(USE_IPV6)
3273 else if (
usa->
sa.sa_family == AF_INET6) {
3274 getnameinfo(&
usa->
sa,
3283#if defined(USE_X_DOM_SOCKET)
3284 else if (
usa->
sa.sa_family == AF_UNIX) {
3295 strncpy(
buf, UNIX_DOMAIN_SOCKET_SERVER_NAME,
len);
3307#if !defined(REENTRANT_TIME)
3310 tm = ((t != NULL) ? gmtime(t) : NULL);
3314 struct tm *tm = &_tm;
3319 strftime(buf, buf_len,
"%a, %d %b %Y %H:%M:%S GMT", tm);
3321 mg_strlcpy(buf,
"Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3322 buf[buf_len - 1] =
'\0';
3331 return (
double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3332 + (
double)(ts_now->tv_sec - ts_before->tv_sec);
3336#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3342#include "external_mg_cry_internal_impl.inl"
3343#elif !defined(NO_FILESYSTEMS)
3361#if defined(GCC_DIAGNOSTIC)
3362#pragma GCC diagnostic push
3363#pragma GCC diagnostic ignored "-Wformat-nonliteral"
3368#if defined(GCC_DIAGNOSTIC)
3369#pragma GCC diagnostic pop
3372 buf[
sizeof(buf) - 1] = 0;
3401 timestamp = time(NULL);
3405 "[%010lu] [error] [client %s] ",
3406 (
unsigned long)timestamp,
3428#error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
3475#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3491#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3498 if (strlen(txt) == 3) {
3499 memcpy(tls->txtbuf, txt, 4);
3501 strcpy(tls->txtbuf,
"ERR");
3506 ((
struct mg_connection *)conn)->request_info.local_uri_raw =
3541#if defined(__clang__)
3542#pragma clang diagnostic push
3543#pragma clang diagnostic ignored "-Wunreachable-code"
3554 ? (ri->
is_ssl ?
"wss" :
"ws")
3555 : (ri->
is_ssl ?
"https" :
"http"));
3559#if defined(__clang__)
3560#pragma clang diagnostic pop
3569 const char *define_proto,
3571 const char *define_uri)
3573 if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3582 (define_uri != NULL)
3585 int port = (define_port > 0) ? define_port : ri->
server_port;
3592#if defined(USE_X_DOM_SOCKET)
3603 const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
3619 if ((0 == strcmp(define_proto,
"https"))
3620 || (0 == strcmp(define_proto,
"wss"))) {
3630#if defined(USE_IPV6)
3631 int is_ipv6 = (conn->
client.
lsa.
sa.sa_family == AF_INET6);
3633 int auth_domain_check_enabled =
3638 const char *server_domain =
3645 sprintf(portstr,
":%u", (
unsigned)port);
3650 if (!auth_domain_check_enabled || !server_domain) {
3656 server_domain = server_ip;
3663#
if defined(USE_IPV6)
3666 (is_ipv6 && (server_domain == server_ip)) ?
"[" :
"",
3668 (is_ipv6 && (server_domain == server_ip)) ?
"]" :
"",
3700 const char *delimiters,
3701 const char *whitespace,
3704 char *
p, *begin_word, *end_word, *end_whitespace;
3707 end_word = begin_word + strcspn(begin_word, delimiters);
3710 if (end_word > begin_word) {
3712 while (*
p == quotechar) {
3719 if (*end_word !=
'\0') {
3720 size_t end_off = strcspn(end_word + 1, delimiters);
3721 memmove(
p, end_word, end_off + 1);
3723 end_word += end_off + 1;
3729 for (
p++;
p < end_word;
p++) {
3734 if (*end_word ==
'\0') {
3738#if defined(GCC_DIAGNOSTIC)
3740#pragma GCC diagnostic push
3741#pragma GCC diagnostic ignored "-Wsign-conversion"
3744 end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
3746#if defined(GCC_DIAGNOSTIC)
3747#pragma GCC diagnostic pop
3750 for (
p = end_word;
p < end_whitespace;
p++) {
3754 *buf = end_whitespace;
3766 for (i = 0; i < num_hdr; i++) {
3768 return hdr[i].
value;
3776#if defined(USE_WEBSOCKET)
3783 int output_max_size)
3849 if (val == NULL || list == NULL || *list ==
'\0') {
3855 while (*list ==
' ' || *list ==
'\t')
3859 if ((list = strchr(val->
ptr,
',')) != NULL) {
3861 val->
len = ((size_t)(list - val->
ptr));
3865 list = val->
ptr + strlen(val->
ptr);
3866 val->
len = ((size_t)(list - val->
ptr));
3871 while (end >= 0 && ((val->
ptr[end] ==
' ') || (val->
ptr[end] ==
'\t')))
3873 val->
len = (size_t)(end) + (size_t)(1);
3875 if (val->
len == 0) {
3880 if (eq_val != NULL) {
3884 eq_val->
ptr = (
const char *)memchr(val->
ptr,
'=', val->
len);
3885 if (eq_val->
ptr != NULL) {
3887 eq_val->
len = ((size_t)(val->
ptr - eq_val->
ptr)) + val->
len;
3888 val->
len = ((size_t)(eq_val->
ptr - val->
ptr)) - 1;
3909 while ((header =
next_option(header, &opt_vec, &eq_vec)) != NULL) {
3923 ptrdiff_t i, j,
len, res;
3925 if ((or_str = (
const char *)memchr(pattern,
'|', pattern_len)) != NULL) {
3926 res =
match_prefix(pattern, (
size_t)(or_str - pattern), str);
3927 return (res > 0) ? res
3929 (
size_t)((pattern + pattern_len)
3934 for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
3935 if ((pattern[i] ==
'?') && (str[j] !=
'\0')) {
3937 }
else if (pattern[i] ==
'$') {
3938 return (str[j] ==
'\0') ? j : -1;
3939 }
else if (pattern[i] ==
'*') {
3941 if (pattern[i] ==
'*') {
3943 len = (ptrdiff_t)strlen(str + j);
3945 len = (ptrdiff_t)strcspn(str + j,
"/");
3947 if (i == (ptrdiff_t)pattern_len) {
3952 (pattern_len - (
size_t)i),
3954 }
while (res == -1 &&
len-- > 0);
3955 return (res == -1) ? -1 : j + res +
len;
3960 return (ptrdiff_t)j;
3967 if (pattern == NULL) {
3980 const char *http_version;
4006 if (http_version && (0 == strcmp(http_version,
"1.1"))) {
4019 if (!conn || !conn->
dom_ctx) {
4030 if (!conn || !conn->
dom_ctx) {
4055 "no-cache, no-store, "
4056 "must-revalidate, private, max-age=0",
4070#if !defined(NO_CACHING)
4074 const char *cache_control =
4078 if (cache_control != NULL) {
4105 conn, NULL, val,
sizeof(val),
"max-age=%lu", (
unsigned long)max_age);
4130 (
unsigned long)max_age);
4136 if (header && header[0]) {
4142#if !defined(NO_FILESYSTEMS)
4156 switch (response_code) {
4161 return "Switching Protocols";
4163 return "Processing";
4173 return "Non-Authoritative Information";
4175 return "No Content";
4177 return "Reset Content";
4179 return "Partial Content";
4181 return "Multi-Status";
4184 return "Already Reported";
4191 return "Multiple Choices";
4193 return "Moved Permanently";
4199 return "Not Modified";
4203 return "Temporary Redirect";
4205 return "Permanent Redirect";
4209 return "Bad Request";
4211 return "Unauthorized";
4213 return "Payment Required";
4219 return "Method Not Allowed";
4221 return "Not Acceptable";
4223 return "Proxy Authentication Required";
4225 return "Request Time-out";
4231 return "Length Required";
4233 return "Precondition Failed";
4235 return "Request Entity Too Large";
4237 return "Request-URI Too Large";
4239 return "Unsupported Media Type";
4241 return "Requested range not satisfiable";
4244 return "Expectation Failed";
4247 return "Misdirected Request";
4249 return "Unproccessable entity";
4254 return "Failed Dependency";
4258 return "Upgrade Required";
4261 return "Precondition Required";
4263 return "Too Many Requests";
4266 return "Request Header Fields Too Large";
4269 return "Unavailable For Legal Reasons";
4274 return "Internal Server Error";
4276 return "Not Implemented";
4278 return "Bad Gateway";
4280 return "Service Unavailable";
4282 return "Gateway Time-out";
4284 return "HTTP Version not supported";
4286 return "Variant Also Negotiates";
4288 return "Insufficient Storage";
4291 return "Loop Detected";
4294 return "Not Extended";
4296 return "Network Authentication Required";
4302 return "I am a teapot";
4304 return "Authentication Timeout";
4306 return "Enhance Your Calm";
4308 return "Login Timeout";
4310 return "Bandwidth Limit Exceeded";
4316 "Unknown HTTP response code: %u",
4321 if (response_code >= 100 && response_code < 200) {
4323 return "Information";
4325 if (response_code >= 200 && response_code < 300) {
4329 if (response_code >= 300 && response_code < 400) {
4331 return "Redirection";
4333 if (response_code >= 400 && response_code < 500) {
4335 return "Client Error";
4337 if (response_code >= 500 && response_code < 600) {
4339 return "Server Error";
4358#if !defined(NO_FILESYSTEMS)
4360 int len, i, page_handler_found, scope, truncated;
4361 const char *error_handler = NULL;
4363 const char *error_page_file_ext, *tstr;
4365 int handled_by_callback = 0;
4367 if ((conn == NULL) || (fmt == NULL)) {
4375 has_body = ((status > 199) && (status != 204) && (status != 304));
4383 mg_vsnprintf(conn, NULL, errmsg_buf,
sizeof(errmsg_buf), fmt, ap);
4386 DEBUG_TRACE(
"Error %i - [%s]", status, errmsg_buf);
4396 handled_by_callback =
4402 if (!handled_by_callback) {
4406 "Recursion when handling error %u - fall back to default",
4408#if !defined(NO_FILESYSTEMS)
4413 page_handler_found = 0;
4415 if (error_handler != NULL) {
4416 for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4422 sizeof(path_buf) - 32,
4433 sizeof(path_buf) - 32,
4442 sizeof(path_buf) - 32,
4457 path_buf[
sizeof(path_buf) - 32] = 0;
4458 len = (
int)strlen(path_buf);
4459 if (
len > (
int)
sizeof(path_buf) - 32) {
4460 len = (
int)
sizeof(path_buf) - 32;
4464 tstr = strchr(error_page_file_ext,
'.');
4468 (i < 32) && (tstr[i] != 0) && (tstr[i] !=
',');
4473 path_buf[
len + i - 1] = tstr[i];
4478 path_buf[
len + i - 1] = 0;
4480 if (
mg_stat(conn, path_buf, &error_page_file.
stat)) {
4483 page_handler_found = 1;
4491 tstr = strchr(tstr + i,
'.');
4496 if (page_handler_found) {
4513 "text/plain; charset=utf-8",
4522 mg_printf(conn,
"Error %d: %s\n", status, status_text);
4523 mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4551 long long content_length)
4562 if (content_length < 0) {
4576 (uint64_t)content_length);
4591 const char *target_url,
4605 const char *redirect_text;
4607 size_t content_len = 0;
4608#if defined(MG_SEND_REDIRECT_BODY)
4613 if (redirect_code == 0) {
4614 redirect_code = 307;
4618 if ((redirect_code != 301) && (redirect_code != 302)
4619 && (redirect_code != 303) && (redirect_code != 307)
4620 && (redirect_code != 308)) {
4629 if ((target_url == NULL) || (*target_url == 0)) {
4633#if defined(MG_SEND_REDIRECT_BODY)
4661 "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4665 content_len = strlen(reply);
4671 "HTTP/1.1 %i %s\r\n"
4673 "Content-Length: %u\r\n"
4674 "Connection: %s\r\n\r\n",
4678 (
unsigned int)content_len,
4681#if defined(MG_SEND_REDIRECT_BODY)
4686 ret =
mg_write(conn, reply, content_len);
4691 return (ret > 0) ? ret : -1;
4698#if defined(GCC_DIAGNOSTIC)
4700#pragma GCC diagnostic push
4701#pragma GCC diagnostic ignored "-Wunused-function"
4706pthread_mutex_init(pthread_mutex_t *mutex,
void *unused)
4710 InitializeCriticalSection(&mutex->sec);
4716pthread_mutex_destroy(pthread_mutex_t *mutex)
4718 DeleteCriticalSection(&mutex->sec);
4724pthread_mutex_lock(pthread_mutex_t *mutex)
4726 EnterCriticalSection(&mutex->sec);
4732pthread_mutex_unlock(pthread_mutex_t *mutex)
4734 LeaveCriticalSection(&mutex->sec);
4745 cv->waiting_thread = NULL;
4753 pthread_mutex_t *mutex,
4759 uint64_t nsnow, nswaitabs;
4763 pthread_mutex_lock(&cv->threadIdSec);
4765 ptls = &cv->waiting_thread;
4766 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
4768 tls->next_waiting_thread = NULL;
4770 pthread_mutex_unlock(&cv->threadIdSec);
4775 (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
4776 nswaitrel = nswaitabs - nsnow;
4777 if (nswaitrel < 0) {
4780 mswaitrel = (DWORD)(nswaitrel / 1000000);
4782 mswaitrel = (DWORD)INFINITE;
4785 pthread_mutex_unlock(mutex);
4787 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
4790 pthread_mutex_lock(&cv->threadIdSec);
4791 ptls = &cv->waiting_thread;
4792 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
4794 *ptls = tls->next_waiting_thread;
4799 pthread_mutex_unlock(&cv->threadIdSec);
4801 WaitForSingleObject(tls->pthread_cond_helper_mutex,
4806 pthread_mutex_lock(mutex);
4816 return pthread_cond_timedwait(cv, mutex, NULL);
4827 pthread_mutex_lock(&cv->threadIdSec);
4828 if (cv->waiting_thread) {
4829 wkup = cv->waiting_thread->pthread_cond_helper_mutex;
4830 cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
4832 ok = SetEvent(wkup);
4835 pthread_mutex_unlock(&cv->threadIdSec);
4845 pthread_mutex_lock(&cv->threadIdSec);
4846 while (cv->waiting_thread) {
4847 pthread_cond_signal(cv);
4849 pthread_mutex_unlock(&cv->threadIdSec);
4859 pthread_mutex_lock(&cv->threadIdSec);
4861 pthread_mutex_unlock(&cv->threadIdSec);
4862 pthread_mutex_destroy(&cv->threadIdSec);
4868#if defined(ALTERNATIVE_QUEUE)
4873 return (
void *)CreateEvent(NULL,
FALSE,
FALSE, NULL);
4879event_wait(
void *eventhdl)
4881 int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
4882 return (res == WAIT_OBJECT_0);
4888event_signal(
void *eventhdl)
4890 return (
int)SetEvent((HANDLE)eventhdl);
4896event_destroy(
void *eventhdl)
4898 CloseHandle((HANDLE)eventhdl);
4903#if defined(GCC_DIAGNOSTIC)
4905#pragma GCC diagnostic pop
4911change_slashes_to_backslashes(
char *path)
4915 for (i = 0; path[i] !=
'\0'; i++) {
4916 if (path[i] ==
'/') {
4922 if ((i > 0) && (path[i] ==
'\\')) {
4923 while ((path[i + 1] ==
'\\') || (path[i + 1] ==
'/')) {
4924 (
void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
4932mg_wcscasecmp(
const wchar_t *
s1,
const wchar_t *s2)
4937 diff = ((*
s1 >=
L'A') && (*
s1 <= L
'Z') ? (*
s1 -
L'A' +
L'a') : *
s1)
4938 - ((*s2 >=
L'A') && (*s2 <=
L'Z') ? (*s2 -
L'A' +
L'a') : *s2);
4941 }
while ((diff == 0) && (
s1[-1] != L
'\0'));
4956 wchar_t wbuf2[UTF16_PATH_MAX + 1];
4957 DWORD long_len, err;
4958 int (*fcompare)(
const wchar_t *,
const wchar_t *) = mg_wcscasecmp;
4961 change_slashes_to_backslashes(buf);
4965 memset(wbuf, 0, wbuf_len *
sizeof(
wchar_t));
4966 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (
int)wbuf_len);
4967 WideCharToMultiByte(
4968 CP_UTF8, 0, wbuf, (
int)wbuf_len, buf2,
sizeof(buf2), NULL, NULL);
4969 if (strcmp(buf, buf2) != 0) {
4993 memset(wbuf2, 0,
ARRAY_SIZE(wbuf2) *
sizeof(
wchar_t));
4994 long_len = GetLongPathNameW(wbuf, wbuf2,
ARRAY_SIZE(wbuf2) - 1);
4995 if (long_len == 0) {
4996 err = GetLastError();
4997 if (err == ERROR_FILE_NOT_FOUND) {
5002 if ((long_len >=
ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5009#if !defined(NO_FILESYSTEMS)
5016 wchar_t wbuf[UTF16_PATH_MAX];
5017 WIN32_FILE_ATTRIBUTE_DATA info;
5018 time_t creation_time;
5024 memset(filep, 0,
sizeof(*filep));
5030 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5035 if ((
len > 0) && (path[
len - 1] !=
' ') && (path[
len - 1] !=
'.')
5036 && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
5037 filep->
size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5039 SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5040 info.ftLastWriteTime.dwHighDateTime);
5046 creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5047 info.ftCreationTime.dwHighDateTime);
5052 filep->
is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5064 wchar_t wbuf[UTF16_PATH_MAX];
5065 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5066 return DeleteFileW(wbuf) ? 0 : -1;
5073 wchar_t wbuf[UTF16_PATH_MAX];
5075 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5076 return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5082#if defined(GCC_DIAGNOSTIC)
5084#pragma GCC diagnostic push
5085#pragma GCC diagnostic ignored "-Wunused-function"
5095 wchar_t wpath[UTF16_PATH_MAX];
5099 SetLastError(ERROR_BAD_ARGUMENTS);
5100 }
else if ((dir = (DIR *)
mg_malloc(
sizeof(*dir))) == NULL) {
5101 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5104 attrs = GetFileAttributesW(wpath);
5105 if ((wcslen(wpath) + 2 <
ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5106 && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5107 (
void)wcscat(wpath, L
"\\*");
5108 dir->handle = FindFirstFileW(wpath, &dir->info);
5109 dir->result.d_name[0] =
'\0';
5128 result = FindClose(dir->handle) ? 0 : -1;
5133 SetLastError(ERROR_BAD_ARGUMENTS);
5141static struct dirent *
5144 struct dirent *
result = 0;
5149 (
void)WideCharToMultiByte(CP_UTF8,
5151 dir->info.cFileName,
5158 if (!FindNextFileW(dir->handle, &dir->info)) {
5159 (
void)FindClose(dir->handle);
5164 SetLastError(ERROR_FILE_NOT_FOUND);
5167 SetLastError(ERROR_BAD_ARGUMENTS);
5174#if !defined(HAVE_POLL)
5186poll(
struct mg_pollfd *pfd,
unsigned int n,
int milliseconds)
5196 memset(&tv, 0,
sizeof(tv));
5197 tv.tv_sec = milliseconds / 1000;
5198 tv.tv_usec = (milliseconds % 1000) * 1000;
5203 for (i = 0; i <
n; i++) {
5204 if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
5205 if (pfd[i].events & POLLIN) {
5206 FD_SET(pfd[i].fd, &rset);
5208 if (pfd[i].events & POLLOUT) {
5209 FD_SET(pfd[i].fd, &wset);
5212 FD_SET(pfd[i].fd, &eset);
5216 if (pfd[i].fd > maxfd) {
5221 if ((
result = select((
int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
5222 for (i = 0; i <
n; i++) {
5223 if (FD_ISSET(pfd[i].fd, &rset)) {
5224 pfd[i].revents |= POLLIN;
5226 if (FD_ISSET(pfd[i].fd, &wset)) {
5227 pfd[i].revents |= POLLOUT;
5229 if (FD_ISSET(pfd[i].fd, &eset)) {
5230 pfd[i].revents |= POLLERR;
5247#if defined(GCC_DIAGNOSTIC)
5249#pragma GCC diagnostic pop
5261 (
void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5268#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5272 return ((_beginthread((
void(__cdecl *)(
void *))
f, USE_STACK_SIZE,
p)
5273 == ((uintptr_t)(-1L)))
5278 (_beginthread((
void(__cdecl *)(
void *))
f, 0,
p) == ((uintptr_t)(-1L)))
5289 pthread_t *threadidptr)
5292 HANDLE threadhandle;
5295 uip = _beginthreadex(NULL, 0,
f,
p, 0, NULL);
5296 threadhandle = (HANDLE)uip;
5297 if ((uip != 0) && (threadidptr != NULL)) {
5298 *threadidptr = threadhandle;
5314 dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5315 if (dwevent == WAIT_FAILED) {
5318 if (dwevent == WAIT_OBJECT_0) {
5319 CloseHandle(threadid);
5327#if !defined(NO_SSL_DL) && !defined(NO_SSL)
5331#if defined(GCC_DIAGNOSTIC)
5333#pragma GCC diagnostic push
5334#pragma GCC diagnostic ignored "-Wunused-function"
5340dlopen(
const char *dll_name,
int flags)
5342 wchar_t wbuf[UTF16_PATH_MAX];
5344 path_to_unicode(NULL, dll_name, wbuf,
ARRAY_SIZE(wbuf));
5345 return LoadLibraryW(wbuf);
5351dlclose(
void *handle)
5355 if (FreeLibrary((HMODULE)handle) != 0) {
5365#if defined(GCC_DIAGNOSTIC)
5367#pragma GCC diagnostic pop
5378kill(pid_t pid,
int sig_num)
5380 (
void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5381 (
void)CloseHandle((HANDLE)pid);
5386#if !defined(WNOHANG)
5392waitpid(pid_t pid,
int *status,
int flags)
5394 DWORD timeout = INFINITE;
5399 if ((flags | WNOHANG) == WNOHANG) {
5403 waitres = WaitForSingleObject((HANDLE)pid, timeout);
5404 if (waitres == WAIT_OBJECT_0) {
5407 if (waitres == WAIT_TIMEOUT) {
5415trim_trailing_whitespaces(
char *s)
5417 char *
e = s + strlen(s);
5418 while ((
e > s) && isspace((
unsigned char)
e[-1])) {
5433 unsigned char cgi_config_idx)
5437 char *interp_arg = 0;
5442 PROCESS_INFORMATION pi = {0};
5446 memset(&si, 0,
sizeof(si));
5449 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5450 si.wShowWindow = SW_HIDE;
5452 me = GetCurrentProcess();
5454 (HANDLE)_get_osfhandle(fdin[0]),
5459 DUPLICATE_SAME_ACCESS);
5461 (HANDLE)_get_osfhandle(fdout[1]),
5466 DUPLICATE_SAME_ACCESS);
5468 (HANDLE)_get_osfhandle(fderr[1]),
5473 DUPLICATE_SAME_ACCESS);
5478 SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5479 HANDLE_FLAG_INHERIT,
5481 SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5482 HANDLE_FLAG_INHERIT,
5484 SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5485 HANDLE_FLAG_INHERIT,
5491 if (interp != NULL) {
5499 buf[0] = buf[1] =
'\0';
5503 conn, &truncated, cmdline,
sizeof(cmdline),
"%s/%s", dir, prog);
5506 pi.hProcess = (pid_t)-1;
5516 buf[
sizeof(buf) - 1] =
'\0';
5519 if ((buf[0] ==
'#') && (buf[1] ==
'!')) {
5520 trim_trailing_whitespaces(buf + 2);
5527 GetFullPathNameA(dir,
sizeof(full_dir), full_dir, NULL);
5529 if (interp[0] !=
'\0') {
5531 if ((interp_arg != 0) && (interp_arg[0] != 0)) {
5536 "\"%s\" %s \"%s\\%s\"",
5546 "\"%s\" \"%s\\%s\"",
5563 pi.hProcess = (pid_t)-1;
5568 if (CreateProcessA(NULL,
5573 CREATE_NEW_PROCESS_GROUP,
5580 conn,
"%s: CreateProcess(%s): %ld", __func__, cmdline, (
long)
ERRNO);
5581 pi.hProcess = (pid_t)-1;
5586 (
void)CloseHandle(si.hStdOutput);
5587 (
void)CloseHandle(si.hStdError);
5588 (
void)CloseHandle(si.hStdInput);
5589 if (pi.hThread != NULL) {
5590 (
void)CloseHandle(pi.hThread);
5593 return (pid_t)pi.hProcess;
5601 unsigned long non_blocking = 0;
5602 return ioctlsocket(sock, (
long)FIONBIO, &non_blocking);
5609 unsigned long non_blocking = 1;
5610 return ioctlsocket(sock, (
long)FIONBIO, &non_blocking);
5617#if !defined(NO_FILESYSTEMS)
5627 memset(filep, 0,
sizeof(*filep));
5633 if (0 == stat(path, &st)) {
5634 filep->
size = (uint64_t)(st.st_size);
5650#if defined(__ZEPHYR__)
5655 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5659 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5671 pthread_t thread_id;
5672 pthread_attr_t
attr;
5675 (void)pthread_attr_init(&
attr);
5676 (void)pthread_attr_setdetachstate(&
attr, PTHREAD_CREATE_DETACHED);
5678#if defined(__ZEPHYR__)
5679 pthread_attr_setstack(&
attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
5680#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5683 (void)pthread_attr_setstacksize(&
attr, USE_STACK_SIZE);
5686 result = pthread_create(&thread_id, &
attr, func, param);
5687 pthread_attr_destroy(&
attr);
5697 pthread_t *threadidptr)
5699 pthread_t thread_id;
5700 pthread_attr_t
attr;
5703 (void)pthread_attr_init(&
attr);
5705#if defined(__ZEPHYR__)
5706 pthread_attr_setstack(&
attr,
5707 &civetweb_worker_stacks[zephyr_worker_stack_index++],
5709#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5712 (void)pthread_attr_setstacksize(&
attr, USE_STACK_SIZE);
5715 result = pthread_create(&thread_id, &
attr, func, param);
5716 pthread_attr_destroy(&
attr);
5717 if ((
result == 0) && (threadidptr != NULL)) {
5718 *threadidptr = thread_id;
5730 result = pthread_join(threadid, NULL);
5745 unsigned char cgi_config_idx)
5752 if ((pid = fork()) == -1) {
5755 }
else if (pid != 0) {
5763 if (chdir(dir) != 0) {
5765 conn,
"%s: chdir(%s): %s", __func__, dir, strerror(
ERRNO));
5766 }
else if (dup2(fdin[0], 0) == -1) {
5768 "%s: dup2(%d, 0): %s",
5772 }
else if (dup2(fdout[1], 1) == -1) {
5774 "%s: dup2(%d, 1): %s",
5778 }
else if (dup2(fderr[1], 2) == -1) {
5780 "%s: dup2(%d, 2): %s",
5785 struct sigaction sa;
5790 (void)close(fdin[0]);
5791 (void)close(fdout[1]);
5792 (void)close(fderr[1]);
5795 (void)close(fdin[1]);
5796 (void)close(fdout[0]);
5797 (void)close(fderr[0]);
5804 memset(&sa, 0,
sizeof(sa));
5805 sa.sa_handler = SIG_DFL;
5806 sigaction(SIGCHLD, &sa, NULL);
5809 if (interp == NULL) {
5811 (void)execle(prog, prog, NULL, envp);
5813 "%s: execle(%s): %s",
5819 const char *interp_args =
5823 if ((interp_args != NULL) && (interp_args[0] != 0)) {
5824 (void)execle(interp, interp, interp_args, prog, NULL, envp);
5826 (void)execle(interp, interp, prog, NULL, envp);
5829 "%s: execle(%s %s): %s",
5847 int flags = fcntl(sock, F_GETFL, 0);
5852 if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
5861 int flags = fcntl(sock, F_GETFL, 0);
5866 if (fcntl(sock, F_SETFL, flags & (~(
int)(O_NONBLOCK))) < 0) {
5880 static uint64_t lfsr = 0;
5881 static uint64_t lcg = 0;
5892 | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
5894 lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
5902 return (lfsr ^ lcg ^ now);
5917 int check_pollerr = 0;
5918 if ((
n == 1) && ((pfd[0].events & POLLERR) == 0)) {
5920 pfd[0].events |= POLLERR;
5932 if ((milliseconds >= 0) && (milliseconds < ms_now)) {
5933 ms_now = milliseconds;
5936 result = poll(pfd,
n, ms_now);
5941 && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
5950 if (milliseconds > 0) {
5951 milliseconds -= ms_now;
5954 }
while (milliseconds > 0);
5977 uint64_t start = 0, now = 0, timeout_ns = 0;
5984 typedef size_t len_t;
5990 timeout_ns = (uint64_t)(timeout * 1.0E9);
5997#if defined(NO_SSL) && !defined(USE_MBEDTLS)
6007#if defined(USE_MBEDTLS)
6009 n = mbed_ssl_write(ssl, (
const unsigned char *)buf,
len);
6011 if ((
n == MBEDTLS_ERR_SSL_WANT_READ)
6012 || (
n == MBEDTLS_ERR_SSL_WANT_WRITE)
6013 ||
n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6016 fprintf(stderr,
"SSL write failed, error %d\n",
n);
6023#elif !defined(NO_SSL)
6026 n = SSL_write(ssl, buf,
len);
6028 err = SSL_get_error(ssl,
n);
6047 n = (
int)fwrite(buf, 1, (
size_t)
len, fp);
6056 err = (
n < 0) ?
ERRNO : 0;
6058 if (err == WSAEWOULDBLOCK) {
6078 if ((
n > 0) || ((
n == 0) && (
len == 0))) {
6108 pfd[0].events = POLLOUT;
6120 if ((now - start) > timeout_ns) {
6142 double timeout = -1.0;
6143 int n, nwritten = 0;
6152 if (timeout <= 0.0) {
6158 n =
push_inner(ctx, fp, sock, ssl, buf + nwritten,
len, timeout);
6160 if (nwritten == 0) {
6164 }
else if (
n == 0) {
6194 typedef size_t len_t;
6207 nread = (
int)read(fileno(fp), buf, (size_t)
len);
6209 err = (nread < 0) ?
ERRNO : 0;
6210 if ((nread == 0) && (
len > 0)) {
6215#if defined(USE_MBEDTLS)
6216 }
else if (conn->
ssl != NULL) {
6221 to_read = mbedtls_ssl_get_bytes_avail(conn->
ssl);
6233 pfd[0].events = POLLIN;
6239 (
int)(timeout * 1000.0),
6248 nread = mbed_ssl_read(conn->
ssl, (
unsigned char *)buf, to_read);
6250 if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
6251 || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
6252 || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6255 fprintf(stderr,
"SSL read failed, error %d\n", nread);
6262 }
else if (pollres < 0) {
6270#elif !defined(NO_SSL)
6271 }
else if (conn->
ssl != NULL) {
6276 if ((ssl_pending = SSL_pending(conn->
ssl)) > 0) {
6280 if (ssl_pending >
len) {
6286 pfd[0].events = POLLIN;
6289 (
int)(timeout * 1000.0),
6298 SSL_read(conn->
ssl, buf, (ssl_pending > 0) ? ssl_pending :
len);
6300 err = SSL_get_error(conn->
ssl, nread);
6316 }
else if (pollres < 0) {
6330 pfd[0].events = POLLIN;
6333 (
int)(timeout * 1000.0),
6340 err = (nread < 0) ?
ERRNO : 0;
6345 }
else if (pollres < 0) {
6358 if ((nread > 0) || ((nread == 0) && (
len == 0))) {
6366 if (err == WSAEWOULDBLOCK) {
6370 }
else if (err == WSAETIMEDOUT) {
6374 }
else if (err == WSAECONNABORTED) {
6415 double timeout = -1.0;
6416 uint64_t start_time = 0, now = 0, timeout_ns = 0;
6421 if (timeout <= 0.0) {
6426 timeout_ns = (uint64_t)(timeout * 1.0E9);
6435 }
else if (
n == -1) {
6437 if (timeout >= 0.0) {
6439 if ((now - start_time) <= timeout_ns) {
6444 }
else if (
n == 0) {
6461 while (
mg_read(conn, buf,
sizeof(buf)) > 0)
6469 int64_t content_len,
n, buffered_len, nread;
6471 (int64_t)((
len > INT_MAX) ? INT_MAX :
len);
6483 if (content_len < 0) {
6492 if (left_to_read < len64) {
6496 len64 = left_to_read;
6502 if (buffered_len > 0) {
6503 if (len64 < buffered_len) {
6504 buffered_len = len64;
6507 memcpy(buf, body, (
size_t)buffered_len);
6508 len64 -= buffered_len;
6510 nread += buffered_len;
6511 buf = (
char *)buf + buffered_len;
6517 if ((
n =
pull_all(NULL, conn, (
char *)buf, (
int)len64)) >= 0) {
6521 nread = ((nread > 0) ? nread :
n);
6537#if defined(USE_SERVER_STATS)
6538 struct timespec tnow;
6539 conn->conn_state = 4;
6545#if defined(USE_SERVER_STATS)
6546 conn->conn_state = 5;
6548 clock_gettime(CLOCK_MONOTONIC, &tnow);
6552 mg_atomic_add64(&(conn->
phys_ctx->total_data_written),
6566#if defined(USE_HTTP2)
6568#error "HTTP2 requires ALPN, APLN requires SSL/TLS"
6571#include "mod_http2.inl"
6575 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
6576 http2_must_use_http1(conn); \
6588 if (
len > INT_MAX) {
6597 size_t all_read = 0;
6619 all_read += (size_t)read_ret;
6620 len -= (size_t)read_ret;
6628 || (
x[1] !=
'\n')) {
6640 unsigned long chunkSize = 0;
6642 for (i = 0; i < (
sizeof(lenbuf) - 1); i++) {
6647 if ((i > 0) && (lenbuf[i] ==
'\r')
6648 && (lenbuf[i - 1] !=
'\r')) {
6651 if ((i > 1) && (lenbuf[i] ==
'\n')
6652 && (lenbuf[i - 1] ==
'\r')) {
6654 chunkSize = strtoul(lenbuf, &end, 16);
6655 if (chunkSize == 0) {
6661 if (!isxdigit((
unsigned char)lenbuf[i])) {
6667 if ((end == NULL) || (*end !=
'\r')) {
6672 if (chunkSize == 0) {
6676 && (lenbuf[0] ==
'\r') && (lenbuf[1] ==
'\n')) {
6687 return (
int)all_read;
6702 if (
len > INT_MAX) {
6708#if defined(USE_HTTP2)
6710 http2_data_frame_head(conn,
len, 0);
6720 if (allowed > (
int)
len) {
6731 if (
total == allowed) {
6733 buf = (
const char *)buf +
total;
6754 buf = (
const char *)buf +
n;
6777 unsigned int chunk_len)
6785 sprintf(lenbuf,
"%x\r\n", chunk_len);
6786 lenbuf_len = strlen(lenbuf);
6789 ret =
mg_write(conn, lenbuf, lenbuf_len);
6790 if (ret != (
int)lenbuf_len) {
6795 ret =
mg_write(conn, chunk, chunk_len);
6796 if (ret != (
int)chunk_len) {
6811#if defined(GCC_DIAGNOSTIC)
6814#pragma GCC diagnostic push
6815#pragma GCC diagnostic ignored "-Wformat-nonliteral"
6842 (*buf)[
size - 1] = 0;
6856 size_t prealloc_size,
6882 }
else if ((
size_t)(
len) >= prealloc_size) {
6903 *out_buf = prealloc_buf;
6910#if defined(GCC_DIAGNOSTIC)
6912#pragma GCC diagnostic pop
6953 int is_form_url_encoded)
6956#define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
6958 for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
6959 if ((i < src_len - 2) && (
src[i] ==
'%')
6960 && isxdigit((
unsigned char)
src[i + 1])
6961 && isxdigit((
unsigned char)
src[i + 2])) {
6962 a = tolower((
unsigned char)
src[i + 1]);
6963 b = tolower((
unsigned char)
src[i + 2]);
6966 }
else if (is_form_url_encoded && (
src[i] ==
'+')) {
6975 return (i >= src_len) ? j : -1;
6983 int len = (
int)strlen(buf);
7007 const char *
p, *
e, *s;
7011 if ((dst == NULL) || (dst_len == 0)) {
7013 }
else if ((
data == NULL) || (
name == NULL) || (data_len == 0)) {
7017 name_len = strlen(
name);
7018 e =
data + data_len;
7023 for (
p =
data;
p + name_len <
e;
p++) {
7024 if (((
p ==
data) || (
p[-1] ==
'&')) && (
p[name_len] ==
'=')
7030 s = (
const char *)memchr(
p,
'&', (
size_t)(
e -
p));
7060 unsigned num_form_fields)
7071 if ((form_fields == NULL) && (num_form_fields == 0)) {
7087 if ((form_fields == NULL) || ((
int)num_form_fields <= 0)) {
7092 for (i = 0; i < (
int)num_form_fields; i++) {
7094 while ((*
data ==
' ') || (*
data ==
'\t')) {
7106 while ((*
b != 0) && (*
b !=
'&') && (*
b !=
'=')) {
7112 form_fields[num].
value = NULL;
7113 }
else if (*
b ==
'&') {
7115 form_fields[num].
value = NULL;
7128 b = strchr(
data,
'&');
7141 for (i = 0; i < num; i++) {
7142 if (form_fields[i].
name) {
7145 if (form_fields[i].
value) {
7158 const char *var_name,
7162 const char *s, *
p, *end;
7163 int name_len,
len = -1;
7165 if ((dst == NULL) || (dst_size == 0)) {
7170 if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
7174 name_len = (
int)strlen(var_name);
7175 end = s + strlen(s);
7176 for (; (s =
mg_strcasestr(s, var_name)) != NULL; s += name_len) {
7177 if (s[name_len] ==
'=') {
7179 if ((s == cookie_header) || (s[-1] ==
' ')) {
7181 if ((
p = strchr(s,
' ')) == NULL) {
7187 if ((*s ==
'"') && (
p[-1] ==
'"') && (
p > s + 1)) {
7191 if ((
size_t)(
p - s) < dst_size) {
7205#if defined(USE_WEBSOCKET) || defined(USE_LUA)
7207base64_encode(
const unsigned char *
src,
int src_len,
char *dst)
7209 static const char *b64 =
7210 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7213 for (i = j = 0; i < src_len; i += 3) {
7215 b = ((i + 1) >= src_len) ? 0 :
src[i + 1];
7216 c = ((i + 2) >= src_len) ? 0 :
src[i + 2];
7218 dst[j++] = b64[
a >> 2];
7219 dst[j++] = b64[((
a & 3) << 4) | (
b >> 4)];
7220 if (i + 1 < src_len) {
7221 dst[j++] = b64[(
b & 15) << 2 | (
c >> 6)];
7223 if (i + 2 < src_len) {
7224 dst[j++] = b64[
c & 63];
7227 while (j % 4 != 0) {
7237b64reverse(
char letter)
7239 if ((letter >=
'A') && (letter <=
'Z')) {
7240 return letter -
'A';
7242 if ((letter >=
'a') && (letter <=
'z')) {
7243 return letter -
'a' + 26;
7245 if ((letter >=
'0') && (letter <=
'9')) {
7246 return letter -
'0' + 52;
7248 if (letter ==
'+') {
7251 if (letter ==
'/') {
7254 if (letter ==
'=') {
7262base64_decode(
const unsigned char *
src,
int src_len,
char *dst,
size_t *dst_len)
7265 unsigned char a,
b,
c,
d;
7269 for (i = 0; i < src_len; i += 4) {
7270 a = b64reverse(
src[i]);
7275 b = b64reverse(((i + 1) >= src_len) ? 0 :
src[i + 1]);
7280 c = b64reverse(((i + 2) >= src_len) ? 0 :
src[i + 2]);
7285 d = b64reverse(((i + 3) >= src_len) ? 0 :
src[i + 3]);
7290 dst[(*dst_len)++] = (
a << 2) + (
b >> 4);
7292 dst[(*dst_len)++] = (
b << 4) + (
c >> 2);
7294 dst[(*dst_len)++] = (
c << 6) +
d;
7309 && (!strcmp(s,
"PUT") || !strcmp(s,
"DELETE")
7310 || !strcmp(s,
"MKCOL") || !strcmp(s,
"PATCH"));
7316#if !defined(NO_FILES)
7324 unsigned char cgi_config_idx, inc, max;
7334#if defined(USE_DUKTAPE)
7344 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
7394 struct vec filename_vec;
7395 size_t n = strlen(path);
7401 while ((
n > 0) && (path[
n - 1] ==
'/')) {
7408 while ((list =
next_option(list, &filename_vec, NULL)) != NULL) {
7410 if ((filename_vec.
len + 1) > (path_len - (
n + 1))) {
7418 if (
mg_stat(conn, path, filestat)) {
7438 size_t filename_buf_len,
7441 int *is_script_resource,
7442 int *is_websocket_request,
7443 int *is_put_or_delete_request,
7444 int *is_template_text
7447 char const *accept_encoding;
7449#if !defined(NO_FILES)
7452 const char *rewrite;
7454 ptrdiff_t match_len;
7457#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7459 size_t tmp_str_len, sep_pos;
7460 int allow_substitute_script_subresources;
7463 (void)filename_buf_len;
7467 memset(filestat, 0,
sizeof(*filestat));
7470 *is_script_resource = 0;
7471 *is_template_text = 0;
7478#if defined(USE_WEBSOCKET)
7480#if !defined(NO_FILES)
7481 if (*is_websocket_request && conn->
dom_ctx->
config[WEBSOCKET_ROOT]) {
7486 *is_websocket_request = 0;
7491 if ((accept_encoding =
mg_get_header(conn,
"Accept-Encoding")) != NULL) {
7492 if (strstr(accept_encoding,
"gzip") != NULL) {
7497#if !defined(NO_FILES)
7514 conn, &truncated,
filename, filename_buf_len - 1,
"%s%s", root, uri);
7517 goto interpret_cleanup;
7527 filename_buf_len - 1,
7537 goto interpret_cleanup;
7544 int uri_len = (
int)strlen(uri);
7545 int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] ==
'/');
7563 *is_script_resource = (!*is_put_or_delete_request);
7573 *is_template_text = (!*is_put_or_delete_request);
7582 memset(&tmp_filestat, 0,
sizeof(tmp_filestat));
7585 conn,
filename, filename_buf_len, &tmp_filestat)) {
7589 *filestat = tmp_filestat;
7593 *is_script_resource = 1;
7596 *is_template_text = 1;
7599 *is_script_resource = 0;
7618 conn, &truncated, gz_path,
sizeof(gz_path),
"%s.gz",
filename);
7621 goto interpret_cleanup;
7624 if (
mg_stat(conn, gz_path, filestat)) {
7634#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7642 goto interpret_cleanup;
7644 memcpy(tmp_str,
filename, tmp_str_len + 1);
7647 allow_substitute_script_subresources =
7651 sep_pos = tmp_str_len;
7652 while (sep_pos > 0) {
7654 if (tmp_str[sep_pos] ==
'/') {
7655 int is_script = 0, does_exist = 0;
7657 tmp_str[sep_pos] = 0;
7660 does_exist =
mg_stat(conn, tmp_str, filestat);
7663 if (does_exist && is_script) {
7667 strlen(
filename + sep_pos + 1) + 1);
7670 *is_script_resource = 1;
7675 if (allow_substitute_script_subresources) {
7682 size_t script_name_len = strlen(tmp_str);
7686 char *subres_name =
filename + sep_pos;
7687 size_t subres_name_len = strlen(subres_name);
7689 DEBUG_TRACE(
"Substitute script %s serving path %s",
7694 if ((script_name_len + subres_name_len + 2)
7695 >= filename_buf_len) {
7697 goto interpret_cleanup;
7702 memmove(conn->
path_info, subres_name, subres_name_len);
7704 memcpy(
filename, tmp_str, script_name_len + 1);
7706 *is_script_resource = 1;
7719 *is_script_resource = 0;
7726 tmp_str[sep_pos] =
'/';
7736#if !defined(NO_FILES)
7739 memset(filestat, 0,
sizeof(*filestat));
7742 *is_script_resource = 0;
7743 *is_websocket_request = 0;
7744 *is_put_or_delete_request = 0;
7757 for (i = 0; i < buflen; i++) {
7759 const unsigned char c = (
unsigned char)buf[i];
7761 if ((
c < 128) && ((char)
c !=
'\r') && ((char)
c !=
'\n')
7767 if (i < buflen - 1) {
7768 if ((buf[i] ==
'\n') && (buf[i + 1] ==
'\n')) {
7775 if (i < buflen - 3) {
7776 if ((buf[i] ==
'\r') && (buf[i + 1] ==
'\n') && (buf[i + 2] ==
'\r')
7777 && (buf[i + 3] ==
'\n')) {
7788#if !defined(NO_CACHING)
7809 char month_str[32] = {0};
7810 int second, minute, hour, day, month, year;
7811 time_t
result = (time_t)0;
7814 if ((sscanf(datetime,
7815 "%d/%3s/%d %d:%d:%d",
7823 || (sscanf(datetime,
7824 "%d %3s %d %d:%d:%d",
7832 || (sscanf(datetime,
7833 "%*3s, %d %3s %d %d:%d:%d",
7841 || (sscanf(datetime,
7842 "%d-%3s-%d %d:%d:%d",
7851 if ((month >= 0) && (year >= 1970)) {
7852 memset(&tm, 0,
sizeof(tm));
7853 tm.tm_year = year - 1900;
7876 char *out_end = inout;
7909 if (!strncmp(in,
"../", 3)) {
7911 }
else if (!strncmp(in,
"./", 2)) {
7920 else if (!strncmp(in,
"/./", 3)) {
7922 }
else if (!strcmp(in,
"/.")) {
7933 else if (!strncmp(in,
"/../", 4)) {
7935 if (inout != out_end) {
7939 }
while ((inout != out_end) && (*out_end !=
'/'));
7941 }
else if (!strcmp(in,
"/..")) {
7943 if (inout != out_end) {
7947 }
while ((inout != out_end) && (*out_end !=
'/'));
7955 else if (!strcmp(in,
".") || !strcmp(in,
"..")) {
7970 }
while ((*in != 0) && (*in !=
'/'));
7986 out_end = in = inout;
7990 char *in_ahead = in;
7993 }
while (*in_ahead ==
'.');
7994 if (*in_ahead ==
'/') {
7996 if ((out_end != inout) && (out_end[-1] ==
'/')) {
8000 }
else if (*in_ahead == 0) {
8006 }
while (in != in_ahead);
8008 }
else if (*in ==
'/') {
8013 }
while (*in ==
'/');
8023static const struct {
8031 {
".bin", 4,
"application/octet-stream"},
8032 {
".deb", 4,
"application/octet-stream"},
8033 {
".dmg", 4,
"application/octet-stream"},
8034 {
".dll", 4,
"application/octet-stream"},
8035 {
".doc", 4,
"application/msword"},
8036 {
".eps", 4,
"application/postscript"},
8037 {
".exe", 4,
"application/octet-stream"},
8038 {
".iso", 4,
"application/octet-stream"},
8039 {
".js", 3,
"application/javascript"},
8040 {
".json", 5,
"application/json"},
8041 {
".msi", 4,
"application/octet-stream"},
8042 {
".pdf", 4,
"application/pdf"},
8043 {
".ps", 3,
"application/postscript"},
8044 {
".rtf", 4,
"application/rtf"},
8045 {
".xhtml", 6,
"application/xhtml+xml"},
8046 {
".xsl", 4,
"application/xml"},
8047 {
".xslt", 5,
"application/xml"},
8050 {
".ttf", 4,
"application/font-sfnt"},
8051 {
".cff", 4,
"application/font-sfnt"},
8052 {
".otf", 4,
"application/font-sfnt"},
8053 {
".aat", 4,
"application/font-sfnt"},
8054 {
".sil", 4,
"application/font-sfnt"},
8055 {
".pfr", 4,
"application/font-tdpfr"},
8056 {
".woff", 5,
"application/font-woff"},
8057 {
".woff2", 6,
"application/font-woff2"},
8060 {
".mp3", 4,
"audio/mpeg"},
8061 {
".oga", 4,
"audio/ogg"},
8062 {
".ogg", 4,
"audio/ogg"},
8065 {
".gif", 4,
"image/gif"},
8066 {
".ief", 4,
"image/ief"},
8067 {
".jpeg", 5,
"image/jpeg"},
8068 {
".jpg", 4,
"image/jpeg"},
8069 {
".jpm", 4,
"image/jpm"},
8070 {
".jpx", 4,
"image/jpx"},
8071 {
".png", 4,
"image/png"},
8072 {
".svg", 4,
"image/svg+xml"},
8073 {
".tif", 4,
"image/tiff"},
8074 {
".tiff", 5,
"image/tiff"},
8077 {
".wrl", 4,
"model/vrml"},
8080 {
".css", 4,
"text/css"},
8081 {
".csv", 4,
"text/csv"},
8082 {
".htm", 4,
"text/html"},
8083 {
".html", 5,
"text/html"},
8084 {
".sgm", 4,
"text/sgml"},
8085 {
".shtm", 5,
"text/html"},
8086 {
".shtml", 6,
"text/html"},
8087 {
".txt", 4,
"text/plain"},
8088 {
".xml", 4,
"text/xml"},
8091 {
".mov", 4,
"video/quicktime"},
8092 {
".mp4", 4,
"video/mp4"},
8093 {
".mpeg", 5,
"video/mpeg"},
8094 {
".mpg", 4,
"video/mpeg"},
8095 {
".ogv", 4,
"video/ogg"},
8096 {
".qt", 3,
"video/quicktime"},
8101 {
".arj", 4,
"application/x-arj-compressed"},
8102 {
".gz", 3,
"application/x-gunzip"},
8103 {
".rar", 4,
"application/x-arj-compressed"},
8104 {
".swf", 4,
"application/x-shockwave-flash"},
8105 {
".tar", 4,
"application/x-tar"},
8106 {
".tgz", 4,
"application/x-tar-gz"},
8107 {
".torrent", 8,
"application/x-bittorrent"},
8108 {
".ppt", 4,
"application/x-mspowerpoint"},
8109 {
".xls", 4,
"application/x-msexcel"},
8110 {
".zip", 4,
"application/x-zip-compressed"},
8114 {
".flac", 5,
"audio/flac"},
8115 {
".aif", 4,
"audio/x-aif"},
8116 {
".m3u", 4,
"audio/x-mpegurl"},
8117 {
".mid", 4,
"audio/x-midi"},
8118 {
".ra", 3,
"audio/x-pn-realaudio"},
8119 {
".ram", 4,
"audio/x-pn-realaudio"},
8120 {
".wav", 4,
"audio/x-wav"},
8121 {
".bmp", 4,
"image/bmp"},
8122 {
".ico", 4,
"image/x-icon"},
8123 {
".pct", 4,
"image/x-pct"},
8124 {
".pict", 5,
"image/pict"},
8125 {
".rgb", 4,
"image/x-rgb"},
8126 {
".webm", 5,
"video/webm"},
8127 {
".asf", 4,
"video/x-ms-asf"},
8128 {
".avi", 4,
"video/x-msvideo"},
8129 {
".m4v", 4,
"video/x-m4v"},
8139 path_len = strlen(path);
8149 return "text/plain";
8158 struct vec ext_vec, mime_vec;
8159 const char *list, *ext;
8162 path_len = strlen(path);
8164 if ((conn == NULL) || (
vec == NULL)) {
8166 memset(
vec,
'\0',
sizeof(
struct vec));
8174 while ((list =
next_option(list, &ext_vec, &mime_vec)) != NULL) {
8176 ext = path + path_len - ext_vec.
len;
8193 static const char *hex =
"0123456789abcdef";
8195 for (;
len--;
p++) {
8196 *to++ = hex[
p[0] >> 4];
8197 *to++ = hex[
p[0] & 0x0f];
8216 while ((
p = va_arg(ap,
const char *)) != NULL) {
8222 bin2str(buf, hash,
sizeof(hash));
8236 const char *response)
8238 char ha2[32 + 1], expected_response[32 + 1];
8241 if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
8242 || (qop == NULL) || (response == NULL)) {
8247 if (strlen(response) != 32) {
8251 mg_md5(ha2, method,
":", uri, NULL);
8252 mg_md5(expected_response,
8270#if !defined(NO_FILESYSTEMS)
8278 if ((conn != NULL) && (conn->
dom_ctx != NULL)) {
8284 if (gpass != NULL) {
8318 for (
p = path,
e =
p + strlen(
p) - 1;
e >
p;
e--) {
8360 const char *auth_header;
8367 (void)memset(
ah, 0,
sizeof(*
ah));
8368 if (((auth_header =
mg_get_header(conn,
"Authorization")) == NULL)
8374 (void)
mg_strlcpy(buf, auth_header + 7, buf_size);
8380 while (isspace((
unsigned char)*s)) {
8396 if (*
name ==
'\0') {
8400 if (!strcmp(
name,
"username")) {
8402 }
else if (!strcmp(
name,
"cnonce")) {
8404 }
else if (!strcmp(
name,
"response")) {
8406 }
else if (!strcmp(
name,
"uri")) {
8408 }
else if (!strcmp(
name,
"qop")) {
8410 }
else if (!strcmp(
name,
"nc")) {
8412 }
else if (!strcmp(
name,
"nonce")) {
8417#if !defined(NO_NONCE_CHECK)
8423 nonce = strtoull(
ah->
nonce, &s, 10);
8424 if ((s == NULL) || (*s != 0)) {
8486#define INITIAL_DEPTH 9
8487#if INITIAL_DEPTH <= 0
8488#error Bad INITIAL_DEPTH for recursion, set to at least 1
8491#if !defined(NO_FILESYSTEMS)
8508 int is_authorized = 0;
8512 if (!filep || !workdata || (0 == depth)) {
8517 while (
mg_fgets(workdata->
buf,
sizeof(workdata->
buf), filep) != NULL) {
8518 l = strlen(workdata->
buf);
8520 if (isspace((
unsigned char)workdata->
buf[
l - 1])
8521 || iscntrl((
unsigned char)workdata->
buf[
l - 1])) {
8523 workdata->
buf[
l] = 0;
8533 if (workdata->
f_user[0] ==
':') {
8537 if (workdata->
f_user[1] ==
'#') {
8540 }
else if (!strncmp(workdata->
f_user + 1,
"include=", 8)) {
8553 if (is_authorized) {
8554 return is_authorized;
8558 "%s: cannot open authorization file: %s",
8567 "%s: syntax error in authorization file: %s",
8576 "%s: syntax error in authorization file: %s",
8585 if (workdata->
f_ha1 == NULL) {
8587 "%s: syntax error in authorization file: %s",
8592 *(
char *)(workdata->
f_ha1) = 0;
8593 (workdata->
f_ha1)++;
8608 return is_authorized;
8623 memset(&workdata, 0,
sizeof(workdata));
8669#if !defined(NO_FILESYSTEMS)
8671 struct vec uri_vec, filename_vec;
8674 int authorized = 1, truncated;
8676 if (!conn || !conn->
dom_ctx) {
8681 while ((list =
next_option(list, &uri_vec, &filename_vec)) != NULL) {
8688 (
int)filename_vec.
len,
8694 "%s: cannot open %s: %s",
8752 "Digest qop=\"auth\", realm=\"%s\", "
8782#if !defined(NO_FILES)
8791 if (passfile != NULL
8812 char line[512], u[512] =
"",
d[512] =
"", ha1buf[33],
8820 if ((pass != NULL) && (pass[0] ==
'\0')) {
8825 if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
8832 if (strchr(user,
':') != NULL) {
8835 if (strchr(domain,
':') != NULL) {
8841 for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
8842 if (iscntrl((
unsigned char)user[i])) {
8849 for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
8850 if (iscntrl((
unsigned char)domain[i])) {
8865 strcat(tmp,
".tmp");
8869 if ((fp = fopen(fname,
"a+")) != NULL) {
8874 if ((fp = fopen(fname,
"r")) == NULL) {
8876 }
else if ((fp2 = fopen(tmp,
"w+")) == NULL) {
8882 while (fgets(
line,
sizeof(
line), fp) != NULL) {
8883 if (sscanf(
line,
"%255[^:]:%255[^:]:%*s", u,
d) != 2) {
8889 if (!strcmp(u, user) && !strcmp(
d, domain)) {
8892 mg_md5(ha1buf, user,
":", domain,
":", pass, NULL);
8893 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1buf);
8894 }
else if (ha1 != NULL) {
8895 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1);
8898 fprintf(fp2,
"%s",
line);
8905 mg_md5(ha1buf, user,
":", domain,
":", pass, NULL);
8906 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1buf);
8907 }
else if (ha1 != NULL) {
8908 fprintf(fp2,
"%s:%s:%s\n", user, domain, ha1);
8947 return (port <= 0xffff);
8954 struct addrinfo hints, *res, *ressave;
8958 memset(&hints, 0,
sizeof(
struct addrinfo));
8959 hints.ai_family = af;
8961 hints.ai_flags = AI_NUMERICHOST;
8964 gai_ret = getaddrinfo(
src, NULL, &hints, &res);
8979 if ((dstlen >= (
size_t)res->ai_addrlen)
8980 && (res->ai_addr->sa_family == af)) {
8981 memcpy(dst, res->ai_addr, res->ai_addrlen);
8987 freeaddrinfo(ressave);
9008 memset(sa, 0,
sizeof(*sa));
9024#if defined(USE_X_DOM_SOCKET)
9027 size_t hostlen = strlen(host);
9028 if (hostlen >=
sizeof(sa->sun.sun_path)) {
9034 "host length exceeds limit");
9049#if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
9050#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
9051 if (use_ssl && (TLS_client_method == NULL)) {
9057 "SSL is not initialized");
9061 if (use_ssl && (SSLv23_client_method == NULL)) {
9067 "SSL is not initialized");
9076#if defined(USE_X_DOM_SOCKET)
9078 size_t hostlen = strlen(host);
9081 sa->sun.sun_family = AF_UNIX;
9082 memset(sa->sun.sun_path, 0,
sizeof(sa->sun.sun_path));
9083 memcpy(sa->sun.sun_path, host, hostlen);
9087 sa->
sin.sin_port = htons((uint16_t)port);
9089#if defined(USE_IPV6)
9090 }
else if (
mg_inet_pton(AF_INET6, host, &sa->sin6,
sizeof(sa->sin6), 1)) {
9091 sa->sin6.sin6_port = htons((uint16_t)port);
9093 }
else if (host[0] ==
'[') {
9096 size_t l = strlen(host + 1);
9100 if (
mg_inet_pton(AF_INET6,
h, &sa->sin6,
sizeof(sa->sin6), 0)) {
9101 sa->sin6.sin6_port = htons((uint16_t)port);
9120 *sock =
socket(PF_INET, SOCK_STREAM, 0);
9122#if defined(USE_IPV6)
9123 else if (ip_ver == 6) {
9124 *sock =
socket(PF_INET6, SOCK_STREAM, 0);
9127#if defined(USE_X_DOM_SOCKET)
9128 else if (ip_ver == -99) {
9129 *sock =
socket(AF_UNIX, SOCK_STREAM, 0);
9148 "Cannot set socket to non-blocking: %s",
9159 conn_ret = connect(*sock,
9160 (
struct sockaddr *)((
void *)&sa->
sin),
9163#if defined(USE_IPV6)
9164 else if (ip_ver == 6) {
9166 conn_ret = connect(*sock,
9167 (
struct sockaddr *)((
void *)&sa->sin6),
9171#if defined(USE_X_DOM_SOCKET)
9172 else if (ip_ver == -99) {
9174 conn_ret = connect(*sock,
9175 (
struct sockaddr *)((
void *)&sa->sun),
9180 if (conn_ret != 0) {
9185 if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
9187 if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
9190 void *psockerr = &sockerr;
9194 int len = (
int)
sizeof(sockerr);
9196 socklen_t
len = (socklen_t)
sizeof(sockerr);
9202 int ms_wait = 10000;
9212 pfd[0].events = POLLOUT;
9221 "connect(%s:%d): timeout",
9230 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (
char *)psockerr, &
len);
9232 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &
len);
9235 if ((ret == 0) && (sockerr == 0)) {
9240 if (conn_ret != 0) {
9246 "connect(%s:%d): error %s",
9262 static const char *dont_escape =
"._-$,;~()";
9263 static const char *hex =
"0123456789abcdef";
9265 const char *end = dst + dst_len - 1;
9267 for (; ((*
src !=
'\0') && (pos < end));
src++, pos++) {
9268 if (isalnum((
unsigned char)*
src)
9269 || (strchr(dont_escape, *
src) != NULL)) {
9271 }
else if (pos + 2 < end) {
9273 pos[1] = hex[(
unsigned char)*
src >> 4];
9274 pos[2] = hex[(
unsigned char)*
src & 0xf];
9282 return (*
src ==
'\0') ? (
int)(pos - dst) : -1;
9290 size_t namesize, escsize, i;
9291 char *href, *
esc, *
p;
9292 char size[64], mod[64];
9293#if defined(REENTRANT_TIME)
9295 struct tm *tm = &_tm;
9303 href = (
char *)
mg_malloc(namesize * 3 + escsize);
9311 esc = href + namesize * 3;
9316 }
else if (*
p ==
'<') {
9318 }
else if (*
p ==
'>') {
9368#if defined(REENTRANT_TIME)
9374 strftime(mod,
sizeof(mod),
"%d-%b-%Y %H:%M", tm);
9376 mg_strlcpy(mod,
"01-Jan-1970 00:00",
sizeof(mod));
9377 mod[
sizeof(mod) - 1] =
'\0';
9380 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
9381 "<td> %s</td><td> %s</td></tr>\n",
9401 const struct de *
a = (
const struct de *)p1, *
b = (
const struct de *)p2;
9405 if ((query_string == NULL) || (query_string[0] ==
'\0')) {
9409 if (
a->file.is_directory && !
b->file.is_directory) {
9411 }
else if (!
a->file.is_directory &&
b->file.is_directory) {
9413 }
else if (*query_string ==
'n') {
9414 cmp_result = strcmp(
a->file_name,
b->file_name);
9415 }
else if (*query_string ==
's') {
9416 cmp_result = (
a->file.size ==
b->file.size)
9418 : ((
a->file.size >
b->file.size) ? 1 : -1);
9419 }
else if (*query_string ==
'd') {
9421 (
a->file.last_modified ==
b->file.last_modified)
9423 : ((
a->file.last_modified >
b->file.last_modified) ? 1
9427 return (query_string[1] ==
'd') ? -cmp_result : cmp_result;
9446#if !defined(NO_FILESYSTEMS)
9451 int (*cb)(
struct de *,
void *))
9466 if (!strcmp(dp->d_name,
".") || !strcmp(dp->d_name,
"..")
9472 conn, &truncated, path,
sizeof(path),
"%s/%s", dir, dp->d_name);
9488 "%s: mg_stat(%s) failed: %s",
9506#if !defined(NO_FILES)
9525 if (!strcmp(dp->d_name,
".") || !strcmp(dp->d_name,
"..")) {
9530 conn, &truncated, path,
sizeof(path),
"%s/%s", dir, dp->d_name);
9547 "%s: mg_stat(%s) failed: %s",
9582#if !defined(NO_FILESYSTEMS)
9594 dsd->
arr_size * 2 *
sizeof(entries[0]));
9595 if (entries == NULL) {
9621 char date[64], *
esc, *
p;
9623 time_t curtime = time(NULL);
9632 "Error: Cannot open directory\nopendir(%s): %s",
9642 if (title[strcspn(title,
"&<>")]) {
9646 for (i = 0,
p =
esc; title[i]; i++,
p += strlen(
p)) {
9650 }
else if (*
p ==
'<') {
9652 }
else if (*
p ==
'>') {
9675 "text/html; charset=utf-8",
9683 "<html><head><title>Index of %s</title>"
9684 "<style>th {text-align: left;}</style></head>"
9685 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
9686 "<tr><th><a href=\"?n%c\">Name</a></th>"
9687 "<th><a href=\"?d%c\">Modified</a></th>"
9688 "<th><a href=\"?s%c\">Size</a></th></tr>"
9689 "<tr><td colspan=\"3\"><hr></td></tr>",
9699 "<tr><td><a href=\"%s\">%s</a></td>"
9700 "<td> %s</td><td> %s</td></tr>\n",
9707 if (
data.entries != NULL) {
9710 sizeof(
data.entries[0]),
9712 for (i = 0; i <
data.num_entries; i++) {
9719 mg_printf(conn,
"%s",
"</table></pre></body></html>");
9733 int to_read, num_read, num_written;
9736 if (!filep || !conn) {
9747#if defined(__linux__)
9752 off_t sf_offs = (off_t)
offset;
9754 int sf_file = fileno(filep->
access.
fp);
9761 (size_t)((
len < 0x7FFFF000) ?
len : 0x7FFFF000);
9763 sendfile(conn->
client.
sock, sf_file, &sf_offs, sf_tosend);
9767 }
else if (loop_cnt == 0) {
9773 }
else if (sf_sent == 0) {
9779 }
while ((
len > 0) && (sf_sent >= 0));
9788 offset = (int64_t)sf_offs;
9793 "%s: fseeko() failed: %s",
9800 "Error: Unable to access file at requested position.");
9804 to_read =
sizeof(buf);
9805 if ((int64_t)to_read >
len) {
9811 (
int)fread(buf, 1, (
size_t)to_read, filep->
access.
fp))
9817 if ((num_written =
mg_write(conn, buf, (
size_t)num_read))
9833 return sscanf(header,
9845 if ((filestat != NULL) && (buf != NULL)) {
9860 if (filep != NULL && filep->
fp != NULL) {
9864 if (fcntl(fileno(filep->
fp), F_SETFD, FD_CLOEXEC) != 0) {
9866 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
9875#if defined(USE_ZLIB)
9876#include "mod_zlib.inl"
9880#if !defined(NO_FILESYSTEMS)
9886 const char *additional_headers)
9888 char lm[64], etag[64];
9890 const char *range_hdr;
9892 struct vec mime_vec;
9895 const char *encoding = 0;
9896 const char *origin_hdr;
9897 const char *cors_orig_cfg;
9898 const char *cors1, *cors2;
9899 int is_head_request;
9901#if defined(USE_ZLIB)
9905 int allow_on_the_fly_compression = 1;
9908 if ((conn == NULL) || (conn->
dom_ctx == NULL) || (filep == NULL)) {
9923 "Error: File size is too large to send\n%" INT64_FMT,
9931#if defined(USE_ZLIB)
9936 allow_on_the_fly_compression = 0;
9945 mg_snprintf(conn, &truncated, gz_path,
sizeof(gz_path),
"%s.gz", path);
9950 "Error: Path of zipped file too long (%s)",
9958#if defined(USE_ZLIB)
9960 allow_on_the_fly_compression = 0;
9962 }
else if ((conn->
accept_gzip) && (range_hdr == NULL)
9966 mg_snprintf(conn, &truncated, gz_path,
sizeof(gz_path),
"%s.gz", path);
9968 if (!truncated &&
mg_stat(conn, gz_path, &file_stat)
9971 filep->
stat = file_stat;
9976#if defined(USE_ZLIB)
9978 allow_on_the_fly_compression = 0;
9986 "Error: Cannot open file\nfopen(%s): %s",
9997 if ((range_hdr != NULL)
10007 "Error: Range requests in gzipped files are not supported");
10013 cl = (
n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
10024#if defined(USE_ZLIB)
10026 allow_on_the_fly_compression = 0;
10032#if defined(USE_ZLIB)
10035 allow_on_the_fly_compression = 0;
10042 if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
10048 cors1 =
"Access-Control-Allow-Origin";
10049 cors2 = cors_orig_cfg;
10051 cors1 = cors2 =
"";
10065 (
int)mime_vec.
len);
10066 if (cors1[0] != 0) {
10072#if defined(USE_ZLIB)
10074 if (allow_on_the_fly_compression) {
10103 if (range[0] != 0) {
10109 if ((additional_headers != NULL) && (*additional_headers != 0)) {
10116 if (!is_head_request) {
10117#if defined(USE_ZLIB)
10118 if (allow_on_the_fly_compression) {
10120 send_compressed_data(conn, filep);
10147#if !defined(NO_CACHING)
10154 const char *ims =
mg_get_header(conn,
"If-Modified-Since");
10168 char lm[64], etag[64];
10170 if ((conn == NULL) || (filep == NULL)) {
10190#if !defined(NO_FILESYSTEMS)
10211 const char *additional_headers)
10221#if !defined(NO_CACHING)
10227 if (
file.stat.is_directory) {
10235 "Error: Directory listing denied");
10262 for (s =
p = path + 2; (
p = strchr(s,
'/')) != NULL; s = ++
p) {
10263 len = (size_t)(
p - path);
10264 if (
len >=
sizeof(buf)) {
10269 memcpy(buf, path,
len);
10281 if (
p[1] ==
'\0') {
10296 "%s: Cannot remove invalid file %s",
10331 ret =
mg_read(conn, buf,
sizeof(buf));
10341 ret =
mg_read(conn, buf,
sizeof(buf));
10366 while (isgraph((
unsigned char)**ppw)) {
10373 if ((**ppw !=
'\r') && (**ppw !=
'\n')) {
10378 if (**ppw !=
' ') {
10387 }
while (isspace((
unsigned char)**ppw));
10392 if (!isgraph((
unsigned char)**ppw)) {
10410 int num_headers = 0;
10416 while ((*dp !=
':') && (*dp >= 33) && (*dp <= 126)) {
10425 while (*dp ==
' ') {
10437 hdr[i].name = *buf;
10442 }
while ((*dp ==
' ') || (*dp ==
'\t'));
10448 while ((*dp != 0) && (*dp !=
'\r') && (*dp !=
'\n')) {
10464 num_headers = i + 1;
10471 if ((dp[0] ==
'\r') || (dp[0] ==
'\n')) {
10480 return num_headers;
10497 {
"GET", 0, 1, 1, 1, 1},
10498 {
"POST", 1, 1, 0, 0, 0},
10499 {
"PUT", 1, 0, 0, 1, 0},
10500 {
"DELETE", 0, 0, 0, 1, 0},
10501 {
"HEAD", 0, 0, 1, 1, 1},
10502 {
"OPTIONS", 0, 0, 1, 1, 0},
10503 {
"CONNECT", 1, 1, 0, 0, 0},
10507 {
"PATCH", 1, 0, 0, 0, 0},
10511 {
"PROPFIND", 0, 1, 1, 1, 0},
10517 {
"MKCOL", 0, 0, 0, 1, 0},
10530 {
"LOCK", 1, 1, 0, 0, 0},
10531 {
"UNLOCK", 1, 0, 0, 0, 0},
10532 {
"PROPPATCH", 1, 1, 0, 0, 0},
10544 {
"REPORT", 1, 1, 1, 1, 1},
10551 {NULL, 0, 0, 0, 0, 0}
10566 if (!strcmp(
m->name, method)) {
10594 int request_length;
10606 while ((
len > 0) && isspace((
unsigned char)*buf)) {
10618 if (iscntrl((
unsigned char)*buf)) {
10624 if (request_length <= 0) {
10625 return request_length;
10627 buf[request_length - 1] =
'\0';
10629 if ((*buf == 0) || (*buf ==
'\r') || (*buf ==
'\n')) {
10673 return request_length + init_skip;
10680 int response_length;
10692 while ((
len > 0) && isspace((
unsigned char)*buf)) {
10704 if (iscntrl((
unsigned char)*buf)) {
10710 if (response_length <= 0) {
10711 return response_length;
10713 buf[response_length - 1] =
'\0';
10715 if ((*buf == 0) || (*buf ==
'\r') || (*buf ==
'\n')) {
10721 if (strncmp(buf,
"HTTP/", 5) != 0) {
10726 if (!isgraph((
unsigned char)buf[0])) {
10743 l = strtol(tmp, &tmp2, 10);
10744 if ((
l < 100) || (
l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
10755 while (isprint((
unsigned char)*buf)) {
10758 if ((*buf !=
'\r') && (*buf !=
'\n')) {
10765 }
while (isspace((
unsigned char)*buf));
10775 return response_length + init_skip;
10791 int request_len,
n = 0;
10792 struct timespec last_action_time;
10793 double request_timeout;
10799 memset(&last_action_time, 0,
sizeof(last_action_time));
10820 while (request_len == 0) {
10827 if (*nread >= bufsiz) {
10833 fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
10840 clock_gettime(CLOCK_MONOTONIC, &last_action_time);
10847 if ((request_len == 0) && (request_timeout >= 0)) {
10849 > request_timeout) {
10856 return request_len;
10860#if !defined(NO_CGI) || !defined(NO_FILES)
10864 const char *expect;
10879 if ((expect != NULL) && (
mg_strcasecmp(expect,
"100-continue") != 0)) {
10884 if (expect != NULL) {
10885 (void)
mg_printf(conn,
"%s",
"HTTP/1.1 100 Continue\r\n\r\n");
10899 int nread =
mg_read(conn, buf,
sizeof(buf));
10901 success = (nread == 0);
10923#if defined(USE_TIMERS)
10925#define TIMER_API static
10926#include "timer.inl"
10931#if !defined(NO_CGI)
10964 size_t i,
n, space;
10969 if ((env->varlen - env->varused) < 2) {
10971 "%s: Cannot register CGI variable [%s]",
10978 space = (env->buflen - env->bufused);
10990 "%s: Cannot allocate memory for CGI variable [%s]",
10998 for (i = 0,
n = 0; i < env->varused; i++) {
10999 env->var[i] = added +
n;
11000 n += strlen(added +
n) + 1;
11002 space = (env->buflen - env->bufused);
11006 added = env->buf + env->bufused;
11010 mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
11018 }
while (truncated);
11021 n = strlen(added) + 1;
11025 env->var[env->varused] = added;
11035 unsigned char cgi_config_idx)
11038 struct vec var_vec;
11040 int i, truncated, uri_len;
11042 if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
11050 if (env->
buf == NULL) {
11052 "%s: Not enough memory for environmental buffer",
11060 if (env->
var == NULL) {
11062 "%s: Not enough memory for environmental variables",
11074 addenv(env,
"%s",
"GATEWAY_INTERFACE=CGI/1.1");
11075 addenv(env,
"%s",
"SERVER_PROTOCOL=HTTP/1.1");
11076 addenv(env,
"%s",
"REDIRECT_STATUS=200");
11081 addenv(env,
"REMOTE_ADDR=%s", src_addr);
11098 const char *index_file = strrchr(prog,
'/');
11101 "SCRIPT_NAME=%s%s",
11109 "SCRIPT_NAME=%.*s",
11110 uri_len - (
int)strlen(conn->
path_info),
11114 addenv(env,
"SCRIPT_FILENAME=%s", prog);
11119 "PATH_TRANSLATED=%s%s",
11124 addenv(env,
"HTTPS=%s", (conn->
ssl == NULL) ?
"off" :
"on");
11127 addenv(env,
"CONTENT_TYPE=%s", s);
11133 addenv(env,
"CONTENT_LENGTH=%s", s);
11135 if ((s = getenv(
"PATH")) != NULL) {
11136 addenv(env,
"PATH=%s", s);
11148 if ((s = getenv(
"COMSPEC")) != NULL) {
11149 addenv(env,
"COMSPEC=%s", s);
11151 if ((s = getenv(
"SYSTEMROOT")) != NULL) {
11152 addenv(env,
"SYSTEMROOT=%s", s);
11154 if ((s = getenv(
"SystemDrive")) != NULL) {
11155 addenv(env,
"SystemDrive=%s", s);
11157 if ((s = getenv(
"ProgramFiles")) != NULL) {
11158 addenv(env,
"ProgramFiles=%s", s);
11160 if ((s = getenv(
"ProgramFiles(x86)")) != NULL) {
11161 addenv(env,
"ProgramFiles(x86)=%s", s);
11164 if ((s = getenv(
"LD_LIBRARY_PATH")) != NULL) {
11165 addenv(env,
"LD_LIBRARY_PATH=%s", s);
11169 if ((s = getenv(
"PERLLIB")) != NULL) {
11170 addenv(env,
"PERLLIB=%s", s);
11175 addenv(env,
"%s",
"AUTH_TYPE=Digest");
11184 sizeof(http_var_name),
11190 "%s: HTTP header variable too long [%s]",
11197 for (
p = http_var_name; *
p !=
'\0';
p++) {
11201 *
p = (char)toupper((
unsigned char)*
p);
11212 while ((s =
next_option(s, &var_vec, NULL)) != NULL) {
11240 ret_pid = waitpid(proc->
pid, &status, WNOHANG);
11241 if ((ret_pid != (pid_t)-1) && (status == 0)) {
11244 kill(proc->
pid, SIGABRT);
11247 while (waitpid(proc->
pid, &status, 0) != (pid_t)-1)
11250 DEBUG_TRACE(
"CGI timer: Child process %d already stopped\n", proc->
pid);
11267 unsigned char cgi_config_idx)
11271 int headers_len, data_len, i, truncated;
11272 int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
11273 const char *status, *status_text, *connection_state;
11277 FILE *in = NULL, *out = NULL, *err = NULL;
11279 pid_t pid = (pid_t)-1;
11282#if defined(USE_TIMERS)
11283 double cgi_timeout;
11287 atof(conn->
dom_ctx->
config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
11307 (void)
mg_snprintf(conn, &truncated, dir,
sizeof(dir),
"%s", prog);
11310 mg_cry_internal(conn,
"Error: CGI program \"%s\": Path too long", prog);
11315 if ((
p = strrchr(dir,
'/')) != NULL) {
11323 if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
11324 status = strerror(
ERRNO);
11327 "Error: CGI program \"%s\": Can not create CGI pipes: %s",
11332 "Error: Cannot create CGI pipe: %s",
11339 if (proc == NULL) {
11340 mg_cry_internal(conn,
"Error: CGI program \"%s\": Out or memory", prog);
11347 conn,
p,
blk.buf,
blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
11349 if (
pid == (pid_t)-1) {
11350 status = strerror(
ERRNO);
11353 "Error: CGI program \"%s\": Can not spawn CGI process: %s",
11366#if defined(USE_TIMERS)
11367 if (cgi_timeout > 0.0) {
11385 (void)close(fdin[0]);
11386 (void)close(fdout[1]);
11387 (void)close(fderr[1]);
11388 fdin[0] = fdout[1] = fderr[1] = -1;
11390 if (((in = fdopen(fdin[1],
"wb")) == NULL)
11391 || ((out = fdopen(fdout[0],
"rb")) == NULL)
11392 || ((err = fdopen(fderr[0],
"rb")) == NULL)) {
11393 status = strerror(
ERRNO);
11395 "Error: CGI program \"%s\": Can not open fd: %s",
11400 "Error: CGI can not open fd\nfdopen: %s",
11419 "Error: CGI program \"%s\": Forward body data failed",
11439 "Error: Not enough memory for CGI buffer (%u bytes)",
11440 (
unsigned int)buflen);
11443 "Error: CGI program \"%s\": Not enough memory for buffer (%u "
11446 (
unsigned int)buflen);
11451 headers_len =
read_message(out, conn, buf, (
int)buflen, &data_len);
11452 DEBUG_TRACE(
"CGI: response: %li", (
signed long)headers_len);
11454 if (headers_len <= 0) {
11458 i =
pull_all(err, conn, buf, (
int)buflen);
11463 "Error: CGI program \"%s\" sent error "
11471 "Error: CGI program \"%s\" failed.",
11477 "Error: CGI program sent malformed or too big "
11478 "(>%u bytes) HTTP headers: [%.*s]",
11485 "Error: CGI program sent malformed or too big "
11486 "(>%u bytes) HTTP headers: [%.*s]",
11497 buf[headers_len - 1] =
'\0';
11501 status_text =
"OK";
11505 status_text = status;
11506 while (isdigit((
unsigned char)*status_text) || *status_text ==
' ') {
11538 mg_write(conn, buf + headers_len, (
size_t)(data_len - headers_len));
11549 if (
pid != (pid_t)-1) {
11553 if (fdin[0] != -1) {
11556 if (fdout[1] != -1) {
11559 if (fderr[1] != -1) {
11565 }
else if (fdin[1] != -1) {
11571 }
else if (fdout[0] != -1) {
11577 }
else if (fderr[0] != -1) {
11586#if !defined(NO_FILES)
11593 if (
conn == NULL) {
11603 "%s: mg_stat(%s) failed: %s",
11614 conn, 405,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11619 if (body_len > 0) {
11621 conn, 415,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11639 if (errno == EEXIST) {
11641 conn, 405,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11642 }
else if (errno == EACCES) {
11644 conn, 403,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11645 }
else if (errno == ENOENT) {
11647 conn, 409,
"Error: mkcol(%s): %s", path, strerror(
ERRNO));
11650 conn, 500,
"fopen(%s): %s", path, strerror(
ERRNO));
11664 if (conn == NULL) {
11672 if (
file.stat.is_directory) {
11682 if (
access(path, W_OK) == 0) {
11689 "Error: Put not possible\nReplacing %s is not allowed",
11721 "Error: Path too long\nput_dir(%s): %s",
11731 "Error: Can not create directory\nput_dir(%s): %s",
11740 ||
file.access.fp == NULL) {
11744 "Error: Can not create file\nfopen(%s): %s",
11755 fseeko(
file.access.fp, r1, SEEK_SET);
11792 "Error: Cannot delete file\nFile %s not found",
11810 if (access(path, W_OK) != 0) {
11815 "Error: Delete not possible\nDeleting %s is not allowed",
11833 "Error: Cannot delete file\nremove(%s): %s",
11841#if !defined(NO_FILESYSTEMS)
11857 if (conn == NULL) {
11864 if (sscanf(tag,
" virtual=\"%511[^\"]\"", file_name) == 1) {
11866 file_name[511] = 0;
11875 }
else if (sscanf(tag,
" abspath=\"%511[^\"]\"", file_name) == 1) {
11878 file_name[511] = 0;
11880 mg_snprintf(conn, &truncated, path,
sizeof(path),
"%s", file_name);
11882 }
else if ((sscanf(tag,
" file=\"%511[^\"]\"", file_name) == 1)
11883 || (sscanf(tag,
" \"%511[^\"]\"", file_name) == 1)) {
11885 file_name[511] = 0;
11886 (void)
mg_snprintf(conn, &truncated, path,
sizeof(path),
"%s", ssi);
11889 if ((
p = strrchr(path,
'/')) != NULL) {
11892 len = strlen(path);
11896 sizeof(path) -
len,
11907 mg_cry_internal(conn,
"SSI #include path length overflow: [%s]", tag);
11913 "Cannot open SSI #include: [%s]: fopen(%s): %s",
11930#if !defined(NO_POPEN)
11934 char cmd[1024] =
"";
11937 if (sscanf(tag,
" \"%1023[^\"]\"", cmd) != 1) {
11941 if ((
file.access.fp = popen(cmd,
"r")) == NULL) {
11943 "Cannot SSI #exec: [%s]: %s",
11948 pclose(
file.access.fp);
11958 if (filep == NULL) {
11977 int ch,
len, in_tag, in_ssi_tag;
11979 if (include_level > 10) {
11984 in_tag = in_ssi_tag =
len = 0;
11987 while ((ch =
mg_fgetc(filep)) != EOF) {
12000 if ((
len > 12) && !memcmp(buf + 5,
"include", 7)) {
12002#if !defined(NO_POPEN)
12003 }
else if ((
len > 9) && !memcmp(buf + 5,
"exec", 4)) {
12014 in_ssi_tag = in_tag = 0;
12026 buf[
len++] = (char)(ch & 0xff);
12028 if ((
len == 5) && !memcmp(buf,
"<!--#", 5)) {
12033 if ((
len + 2) > (
int)
sizeof(buf)) {
12059 buf[
len++] = (char)(ch & 0xff);
12061 if (
len == (
int)
sizeof(buf)) {
12082 time_t curtime = time(NULL);
12083 const char *cors_orig_cfg;
12084 const char *cors1, *cors2;
12086 if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
12091 if (cors_orig_cfg && *cors_orig_cfg &&
mg_get_header(conn,
"Origin")) {
12093 cors1 =
"Access-Control-Allow-Origin";
12094 cors2 = cors_orig_cfg;
12096 cors1 = cors2 =
"";
12104 "Error: Cannot read file\nfopen(%s): %s",
12132#if !defined(NO_FILES)
12151 "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
12170 size_t href_size, i, j;
12172 char *href, mtime[64];
12174 if ((conn == NULL) || (uri == NULL) || (
name == NULL) || (filep == NULL)) {
12178 href_size = (strlen(uri) + strlen(
name)) * 3 + 1;
12180 if (href == NULL) {
12189 for (i = j = 0; href[i]; j++) {
12190 if (!strncmp(href + i,
"%2f", 3)) {
12194 href[j] = href[i++];
12202 "<d:href>%s</d:href>"
12205 "<d:resourcetype>%s</d:resourcetype>"
12206 "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
12207 "<d:getlastmodified>%s</d:getlastmodified>"
12209 "<d:status>HTTP/1.1 200 OK</d:status>"
12242 time_t curtime = time(NULL);
12246 if (!conn || !path || !filep || !conn->
dom_ctx) {
12261 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12262 "<d:multistatus xmlns:d='DAV:'>\n");
12272 && ((depth == NULL) || (strcmp(depth,
"0") != 0))) {
12276 mg_printf(conn,
"%s\n",
"</d:multistatus>");
12284 (void)pthread_mutex_lock(&conn->
mutex);
12292 (void)pthread_mutex_unlock(&conn->
mutex);
12313#if defined(USE_LUA)
12314#include "mod_lua.inl"
12317#if defined(USE_DUKTAPE)
12318#include "mod_duktape.inl"
12321#if defined(USE_WEBSOCKET)
12323#if !defined(NO_SSL_DL)
12324#if !defined(OPENSSL_API_3_0)
12325#define SHA_API static
12331send_websocket_handshake(
struct mg_connection *conn,
const char *websock_key)
12333 static const char *magic =
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
12334 char buf[100], sha[20], b64_sha[
sizeof(sha) * 2];
12335#if !defined(OPENSSL_API_3_0)
12349#if defined(OPENSSL_API_3_0)
12350 EVP_Digest((
unsigned char *)
buf, (uint32_t)strlen(
buf), (
unsigned char *)sha,
12351 NULL, EVP_get_digestbyname(
"sha1"), NULL);
12357 base64_encode((
unsigned char *)sha,
sizeof(sha), b64_sha);
12359 "HTTP/1.1 101 Switching Protocols\r\n"
12360 "Upgrade: websocket\r\n"
12361 "Connection: Upgrade\r\n"
12362 "Sec-WebSocket-Accept: %s\r\n",
12365#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12367 websocket_deflate_response(conn);
12372 "Sec-WebSocket-Protocol: %s\r\n\r\n",
12382#if !defined(MG_MAX_UNANSWERED_PING)
12388#define MG_MAX_UNANSWERED_PING (5)
12395 void *callback_data)
12402 int n, error, exit_by_callback;
12409 size_t i,
len, mask_len = 0, header_len, body_len;
12415 unsigned char mask[4];
12420 unsigned char mem[4096];
12425 double timeout = -1.0;
12426 int enable_ping_pong = 0;
12427 int ping_count = 0;
12436 timeout = atoi(conn->
dom_ctx->
config[WEBSOCKET_TIMEOUT]) / 1000.0;
12441 if (timeout <= 0.0) {
12446 DEBUG_TRACE(
"Websocket connection %s:%u start data processing loop",
12449 conn->in_websocket_handling = 1;
12460 mask_len = (
buf[1] & 128) ? 4 : 0;
12461 if ((
len < 126) && (body_len >= mask_len)) {
12464 header_len = 2 + mask_len;
12465 }
else if ((
len == 126) && (body_len >= (4 + mask_len))) {
12467 header_len = 4 + mask_len;
12469 }
else if (body_len >= (10 + mask_len)) {
12472 memcpy(&l1, &
buf[2], 4);
12473 memcpy(&l2, &
buf[6], 4);
12474 header_len = 10 + mask_len;
12475 data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
12477 if (
data_len > (uint64_t)0x7FFF0000ul) {
12482 "websocket out of memory; closing connection");
12488 if ((header_len > 0) && (body_len >= header_len)) {
12490 unsigned char *
data = mem;
12492 if ((
size_t)
data_len > (
size_t)
sizeof(mem)) {
12495 if (
data == NULL) {
12501 "websocket out of memory; closing connection");
12507 if (mask_len > 0) {
12508 memcpy(
mask,
buf + header_len - mask_len,
sizeof(
mask));
12516 if (
data_len + (uint64_t)header_len > (uint64_t)body_len) {
12519 len = body_len - header_len;
12531 }
else if (
n > 0) {
12542 "Websocket pull failed; closing connection");
12574 if (mask_len > 0) {
12575 for (i = 0; i < (size_t)
data_len; i++) {
12580 exit_by_callback = 0;
12588 }
else if (enable_ping_pong
12608 if (ws_data_handler != NULL) {
12609#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12612 if (!conn->websocket_deflate_initialized) {
12613 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12614 exit_by_callback = 1;
12616 if (!exit_by_callback) {
12617 size_t inflate_buf_size_old = 0;
12618 size_t inflate_buf_size =
12622 Bytef *inflated = NULL;
12623 Bytef *new_mem = NULL;
12624 conn->websocket_inflate_state.avail_in =
12626 conn->websocket_inflate_state.next_in =
data;
12633 if (inflate_buf_size_old == 0) {
12638 inflate_buf_size *= 2;
12643 if (new_mem == NULL) {
12646 "Out of memory: Cannot allocate "
12647 "inflate buffer of %lu bytes",
12648 (
unsigned long)inflate_buf_size);
12649 exit_by_callback = 1;
12652 inflated = new_mem;
12653 conn->websocket_inflate_state.avail_out =
12654 (uInt)(inflate_buf_size
12655 - inflate_buf_size_old);
12656 conn->websocket_inflate_state.next_out =
12657 inflated + inflate_buf_size_old;
12658 ret = inflate(&conn->websocket_inflate_state,
12660 if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
12661 || ret == Z_MEM_ERROR) {
12664 "ZLIB inflate error: %i %s",
12666 (conn->websocket_inflate_state.msg
12667 ? conn->websocket_inflate_state.msg
12668 :
"<no error message>"));
12669 exit_by_callback = 1;
12672 inflate_buf_size_old = inflate_buf_size;
12674 }
while (conn->websocket_inflate_state.avail_out
12676 inflate_buf_size -=
12677 conn->websocket_inflate_state.avail_out;
12678 if (!ws_data_handler(conn,
12683 exit_by_callback = 1;
12689 if (!ws_data_handler(conn,
12694 exit_by_callback = 1;
12704 if (exit_by_callback) {
12705 DEBUG_TRACE(
"Callback requests to close connection from %s:%u",
12712 DEBUG_TRACE(
"Message requests to close connection from %s:%u",
12741 if (ping_count > MG_MAX_UNANSWERED_PING) {
12743 DEBUG_TRACE(
"Too many (%i) unanswered ping from %s:%u "
12744 "- closing connection",
12750 if (enable_ping_pong) {
12776 conn->in_websocket_handling = 0;
12777 DEBUG_TRACE(
"Websocket connection %s:%u left data processing loop",
12788 uint32_t masking_key)
12790 unsigned char header[14];
12794#if defined(GCC_DIAGNOSTIC)
12796#pragma GCC diagnostic push
12797#pragma GCC diagnostic ignored "-Wconversion"
12813#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12814 size_t deflated_size = 0;
12815 Bytef *deflated = 0;
12817 int use_deflate = dataLen > 100 * 1024 && conn->
accept_gzip;
12820 if (!conn->websocket_deflate_initialized) {
12821 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12826 header[0] = 0xC0u | (
unsigned char)((
unsigned)opcode & 0xf);
12827 conn->websocket_deflate_state.avail_in = (uInt)dataLen;
12828 conn->websocket_deflate_state.next_in = (
unsigned char *)
data;
12829 deflated_size = (Bytef *)compressBound((uLong)dataLen);
12830 deflated =
mg_calloc(deflated_size,
sizeof(Bytef));
12831 if (deflated == NULL) {
12834 "Out of memory: Cannot allocate deflate buffer of %lu bytes",
12835 (
unsigned long)deflated_size);
12839 conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
12840 conn->websocket_deflate_state.next_out = deflated;
12841 deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
12842 dataLen = deflated_size - conn->websocket_deflate_state.avail_out
12846 header[0] = 0x80u | (
unsigned char)((
unsigned)opcode & 0xf);
12848#if defined(GCC_DIAGNOSTIC)
12849#pragma GCC diagnostic pop
12853 if (dataLen < 126) {
12855 header[1] = (
unsigned char)dataLen;
12857 }
else if (dataLen <= 0xFFFF) {
12859 uint16_t
len = htons((uint16_t)dataLen);
12861 memcpy(header + 2, &
len, 2);
12865 uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
12866 uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
12868 memcpy(header + 2, &len1, 4);
12869 memcpy(header + 6, &len2, 4);
12876 memcpy(header + headerLen, &masking_key, 4);
12880 retval =
mg_write(conn, header, headerLen);
12881 if (retval != (
int)headerLen) {
12886#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12888 retval =
mg_write(conn, deflated, dataLen);
12909 return mg_websocket_write_exec(conn, opcode,
data, dataLen, 0);
12914mask_data(
const char *in,
size_t in_len, uint32_t masking_key,
char *out)
12919 if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
12921 while (i < (in_len - 3)) {
12922 *(uint32_t *)(
void *)(out + i) =
12923 *(uint32_t *)(
void *)(in + i) ^ masking_key;
12929 while (i < in_len) {
12930 *(uint8_t *)(
void *)(out + i) =
12931 *(uint8_t *)(
void *)(in + i)
12932 ^ *(((uint8_t *)&masking_key) + (i % 4));
12946 char *masked_data =
12948 uint32_t masking_key = 0;
12950 if (masked_data == NULL) {
12954 "Cannot allocate buffer for masked websocket response: "
12962 }
while (masking_key == 0);
12964 mask_data(
data, dataLen, masking_key, masked_data);
12966 retval = mg_websocket_write_exec(
12967 conn, opcode, masked_data, dataLen, masking_key);
12977 int is_callback_resource,
12985 const char *websock_key =
mg_get_header(conn,
"Sec-WebSocket-Key");
12986 const char *version =
mg_get_header(conn,
"Sec-WebSocket-Version");
12987 ptrdiff_t lua_websock = 0;
12989#if !defined(USE_LUA)
12995 if (!websock_key) {
13002 const char *key1 =
mg_get_header(conn,
"Sec-WebSocket-Key1");
13003 const char *key2 =
mg_get_header(conn,
"Sec-WebSocket-Key2");
13006 if ((key1 != NULL) && (key2 != NULL)) {
13009 if (8 ==
mg_read(conn, key3, 8)) {
13014 "Protocol upgrade to RFC 6455 required");
13025 if ((version == NULL) || (strcmp(version,
"13") != 0)) {
13035 if (is_callback_resource) {
13037 const char *protocols[64];
13038 int nbSubprotocolHeader = get_req_headers(&conn->
request_info,
13039 "Sec-WebSocket-Protocol",
13042 if ((nbSubprotocolHeader > 0) && subprotocols) {
13046 const char *
sep, *curSubProtocol,
13047 *acceptedWebSocketSubprotocol = NULL;
13052 const char *protocol = protocols[
cnt];
13055 sep = strchr(protocol,
',');
13056 curSubProtocol = protocol;
13057 len =
sep ? (
unsigned long)(sep - protocol)
13058 : (unsigned long)strlen(protocol);
13059 while (sep && isspace((
unsigned char)*++sep))
13065 && (strncmp(curSubProtocol,
13069 acceptedWebSocketSubprotocol =
13074 }
while (sep && !acceptedWebSocketSubprotocol);
13075 }
while (++cnt < nbSubprotocolHeader
13076 && !acceptedWebSocketSubprotocol);
13079 acceptedWebSocketSubprotocol;
13081 }
else if (nbSubprotocolHeader > 0) {
13083 const char *protocol = protocols[0];
13088 const char *
sep = strrchr(protocol,
',');
13101 while (isspace((
unsigned char)*++sep)) {
13108#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13109 websocket_deflate_negotiate(conn);
13112 if ((ws_connect_handler != NULL)
13113 && (ws_connect_handler(conn, cbData) != 0)) {
13123#if defined(USE_LUA)
13134 conn->lua_websocket_state = lua_websocket_new(path, conn);
13135 if (!conn->lua_websocket_state) {
13144 if (!is_callback_resource && !lua_websock) {
13154 if (!send_websocket_handshake(conn, websock_key)) {
13160 if (is_callback_resource) {
13161 if (ws_ready_handler != NULL) {
13162 ws_ready_handler(conn, cbData);
13164#if defined(USE_LUA)
13165 }
else if (lua_websock) {
13166 if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
13174 if (is_callback_resource) {
13175 read_websocket(conn, ws_data_handler, cbData);
13176#if defined(USE_LUA)
13177 }
else if (lua_websock) {
13178 read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
13182#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13184 if (conn->websocket_deflate_initialized) {
13185 deflateEnd(&conn->websocket_deflate_state);
13186 inflateEnd(&conn->websocket_inflate_state);
13191 if (ws_close_handler) {
13192 ws_close_handler(conn, cbData);
13207 const char *upgrade, *connection;
13216 if (connection == NULL) {
13224 if (upgrade == NULL) {
13259 if (sscanf(
vec->
ptr,
"%u.%u.%u.%u%n", &
a, &
b, &
c, &
d, &
n)
13267 if ((
n > 0) && ((
size_t)
n ==
vec->
len)) {
13268 if ((
a < 256) && (
b < 256) && (
c < 256) && (
d < 256) && (
slash < 33)) {
13270 if (sa->
sa.sa_family == AF_INET) {
13271 uint32_t ip = ntohl(sa->
sin.sin_addr.s_addr);
13272 uint32_t net = ((uint32_t)
a << 24) | ((uint32_t)
b << 16)
13273 | ((uint32_t)
c << 8) | (uint32_t)
d;
13275 return (ip &
mask) == net;
13280#if defined(USE_IPV6)
13285 if (sscanf(
vec->
ptr,
"[%49[^]]]/%u%n", ad, &
slash, &
n) != 2) {
13287 if (sscanf(
vec->
ptr,
"[%49[^]]]%n", ad, &
n) != 1) {
13292 if ((
n <= 0) && no_strict) {
13296 if (((
size_t)(
p -
vec->
ptr) <
sizeof(ad))
13297 && (sscanf(
p,
"/%u%n", &
slash, &
n) == 1)) {
13303 }
else if (
vec->
len <
sizeof(ad)) {
13314 while (isxdigit((
unsigned char)*
p) || (*
p ==
'.') || (*
p ==
':')) {
13315 if (*(
p++) ==
':') {
13319 if ((*
p ==
'\0') && (
c >= 2)) {
13320 struct sockaddr_in6 sin6;
13324 if (sa->
sa.sa_family != AF_INET6) {
13327 if (
mg_inet_pton(AF_INET6, ad, &sin6,
sizeof(sin6), 0)) {
13329 for (i = 0; i < 16; i++) {
13330 uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
13331 uint8_t net = sin6.sin6_addr.s6_addr[i];
13334 if (8 * i + 8 <
slash) {
13336 }
else if (8 * i <
slash) {
13337 mask = (uint8_t)(0xFFu << (8 * i + 8 -
slash));
13339 if ((ip &
mask) != net) {
13367 if ((val.
ptr == NULL)
13368 || (sscanf(val.
ptr,
"%lf%c", &
v, &mult)
13374 && (mult !=
','))) {
13379 : ((
lowercase(&mult) ==
'm') ? 1048576 : 1);
13384 if (matched >= 0) {
13409 for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
13421 const char *host_header =
13427 if (host_header != NULL) {
13432 if (*host_header ==
'[') {
13433 pos = strchr(host_header,
']');
13436 DEBUG_TRACE(
"%s",
"Host name format error '[' without ']'");
13440 host->
ptr = host_header;
13441 host->
len = (size_t)(pos + 1 - host_header);
13444 pos = strchr(host_header,
':');
13446 host->
len = (size_t)(pos - host_header);
13448 host->
len = strlen(host_header);
13450 host->
ptr = host_header;
13470 if ((strlen(sslhost) != host.
len)
13473 DEBUG_TRACE(
"Host mismatch: SNI: %s, HTTPS: %.*s",
13485 size_t domNameLen = strlen(domName);
13486 if ((domNameLen == host.
len)
13504 conn->
ssl ?
"S" :
"",
13522 const char *expect_proto =
13526 int redirect_code = 308;
13533 conn, target_url,
sizeof(target_url), expect_proto, port, NULL)
13537 size_t slen1 = strlen(target_url);
13539 if ((slen1 + slen2 + 2) <
sizeof(target_url)) {
13540 target_url[slen1] =
'?';
13541 memcpy(target_url + slen1 + 1,
13544 target_url[slen1 + slen2 + 1] = 0;
13567 int is_delete_request,
13578 size_t urilen = strlen(
uri);
13609 if (!is_delete_request && (
handler == NULL)) {
13636 if (!phys_ctx || !dom_ctx) {
13646 for (tmp_rh = dom_ctx->
handlers; tmp_rh != NULL;
13647 tmp_rh = tmp_rh->
next) {
13649 && (urilen == tmp_rh->
uri_len) && !strcmp(tmp_rh->
uri,
uri)) {
13650 if (!is_delete_request) {
13687 *lastref = tmp_rh->
next;
13694 lastref = &(tmp_rh->
next);
13696 }
while (tmp_rh != NULL);
13698 if (is_delete_request) {
13709 if (tmp_rh == NULL) {
13713 "Cannot create new request handler struct, OOM");
13717 if (!tmp_rh->
uri) {
13722 "Cannot create new request handler struct, OOM");
13741 tmp_rh->
next = NULL;
13856 if (request_info) {
13857 const char *uri = request_info->
local_uri;
13858 size_t urilen = strlen(uri);
13868 for (step = 0; step < 3; step++) {
13870 tmp_rh = tmp_rh->
next) {
13876 matched = (tmp_rh->
uri_len == urilen)
13877 && (strcmp(tmp_rh->
uri,
uri) == 0);
13878 }
else if (step == 1) {
13906 *handler_info = tmp_rh;
13938#if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
13940experimental_websocket_client_data_wrapper(
struct mg_connection *conn,
13947 if (pcallbacks->websocket_data) {
13948 return pcallbacks->websocket_data(conn, bits,
data,
len);
13956experimental_websocket_client_close_wrapper(
const struct mg_connection *conn,
13973 if (handler_info != NULL) {
13991 int uri_len, ssl_index;
13992 int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
13993 is_put_or_delete_request = 0, is_callback_resource = 0,
13994 is_template_text_file = 0;
14004 void *callback_data = NULL;
14006 void *auth_callback_data = NULL;
14008 time_t curtime = time(NULL);
14027 if (ssl_index >= 0) {
14037 "Error: SSL forward not configured properly");
14040 "Can not redirect to SSL, no SSL port available");
14095 }
else if (i == 0) {
14113 const char *cors_meth_cfg =
14115 const char *cors_orig_cfg =
14117 const char *cors_origin =
14121 "Access-Control-Request-Method");
14126 if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
14127 && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
14128 && (cors_origin != NULL) && (cors_acrm != NULL)) {
14131 const char *cors_acrh =
14134 "Access-Control-Request-Headers");
14138 "HTTP/1.1 200 OK\r\n"
14140 "Access-Control-Allow-Origin: %s\r\n"
14141 "Access-Control-Allow-Methods: %s\r\n"
14142 "Content-Length: 0\r\n"
14143 "Connection: %s\r\n",
14146 ((cors_meth_cfg[0] ==
'*') ? cors_acrm : cors_meth_cfg),
14149 if (cors_acrh != NULL) {
14151 const char *cors_hdr_cfg =
14154 if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
14161 "Access-Control-Allow-Headers: %s\r\n",
14162 ((cors_hdr_cfg[0] ==
'*') ? cors_acrh
14166 mg_printf(conn,
"Access-Control-Max-Age: 60\r\n");
14179#if defined(USE_WEBSOCKET)
14185 if (is_websocket_request) {
14194 &ws_connect_handler,
14204 is_callback_resource = 1;
14205 is_script_resource = 1;
14208 no_callback_resource:
14213 is_callback_resource = 0;
14219 &is_script_resource,
14220 &is_websocket_request,
14221 &is_put_or_delete_request,
14222 &is_template_text_file);
14236 &auth_callback_data,
14238 if (!auth_handler(conn, auth_callback_data)) {
14245 }
else if (is_put_or_delete_request && !is_script_resource
14246 && !is_callback_resource) {
14250#if defined(NO_FILES)
14262 "%s method not allowed",
14267#if !defined(NO_FILES)
14294 if (is_callback_resource) {
14296 if (!is_websocket_request) {
14297 i = callback_handler(conn, callback_data);
14333 &is_script_resource,
14334 &is_websocket_request,
14335 &is_put_or_delete_request,
14336 &is_template_text_file);
14337 callback_handler = NULL;
14348 goto no_callback_resource;
14351#if defined(USE_WEBSOCKET)
14352 handle_websocket_request(conn,
14354 is_callback_resource,
14356 ws_connect_handler,
14367#if defined(USE_WEBSOCKET)
14368 if (is_websocket_request) {
14370 if (is_script_resource) {
14374 handle_websocket_request(conn,
14394#if defined(NO_FILES)
14409 if (is_script_resource) {
14416 if (is_put_or_delete_request) {
14438 "%s method not allowed",
14451 if (
file.stat.is_directory && (uri_len > 0)
14452 && (ri->
local_uri[uri_len - 1] !=
'/')) {
14461 new_path[
len] =
'/';
14462 new_path[
len + 1] = 0;
14464 new_path[
len + 1] =
'?';
14495 "%s method not allowed",
14501 if (
file.stat.is_directory) {
14512 "Error: Directory listing denied");
14518 if (is_template_text_file) {
14525#if !defined(NO_CACHING)
14540#if !defined(NO_FILESYSTEMS)
14546#if !defined(NO_CGI)
14547 unsigned char cgi_config_idx, inc, max;
14550 if (!conn || !conn->
dom_ctx) {
14554#if defined(USE_LUA)
14561 handle_lsp_request(conn, path,
file, NULL);
14574 mg_exec_lua_script(conn, path, NULL);
14583#if defined(USE_DUKTAPE)
14589 mg_exec_duktape_script(conn, path);
14598#if !defined(NO_CGI)
14601 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
14630#if !defined(NO_CACHING)
14653#if defined(USE_X_DOM_SOCKET)
14691 unsigned int a,
b,
c,
d;
14693 unsigned long portUL;
14697#if defined(USE_IPV6)
14698 char buf[100] = {0};
14704 memset(so, 0,
sizeof(*so));
14705 so->
lsa.
sin.sin_family = AF_INET;
14714 "%u.%u.%u.%u:%u%n",
14725 so->
lsa.
sin.sin_addr.s_addr =
14726 htonl((
a << 24) | (
b << 16) | (
c << 8) |
d);
14727 so->
lsa.
sin.sin_port = htons((uint16_t)port);
14730#if defined(USE_IPV6)
14731 }
else if (sscanf(
vec->
ptr,
"[%49[^]]]:%u%n", buf, &port, &
len) == 2
14732 && ((
size_t)len <= vec->
len)
14734 AF_INET6, buf, &so->
lsa.sin6,
sizeof(so->
lsa.sin6), 0)) {
14738 so->
lsa.sin6.sin6_port = htons((uint16_t)port);
14742 }
else if ((
vec->
ptr[0] ==
'+')
14743 && (sscanf(
vec->
ptr + 1,
"%u%n", &port, &
len)
14753#if defined(USE_IPV6)
14755 so->
lsa.sin6.sin6_family = AF_INET6;
14756 so->
lsa.sin6.sin6_port = htons((uint16_t)port);
14757 *ip_version = 4 + 6;
14760 so->
lsa.
sin.sin_port = htons((uint16_t)port);
14765 && (
vec->
ptr != endptr)) {
14767 port = (uint16_t)portUL;
14769 so->
lsa.
sin.sin_port = htons((uint16_t)port);
14772 }
else if ((cb = strchr(
vec->
ptr,
':')) != NULL) {
14782 char hostname[256];
14783 size_t hostnlen = (size_t)(cb -
vec->
ptr);
14785 if ((hostnlen >=
vec->
len) || (hostnlen >=
sizeof(hostname))) {
14794 AF_INET, hostname, &so->
lsa.
sin,
sizeof(so->
lsa.
sin), 1)) {
14795 if (sscanf(cb + 1,
"%u%n", &port, &
len)
14801 so->
lsa.
sin.sin_port = htons((uint16_t)port);
14802 len += (
int)(hostnlen + 1);
14806#if defined(USE_IPV6)
14810 sizeof(so->
lsa.sin6),
14812 if (sscanf(cb + 1,
"%u%n", &port, &
len) == 1) {
14814 so->
lsa.sin6.sin6_port = htons((uint16_t)port);
14815 len += (
int)(hostnlen + 1);
14824#if defined(USE_X_DOM_SOCKET)
14826 }
else if (
vec->
ptr[0] ==
'x') {
14828 if (
vec->
len <
sizeof(so->
lsa.sun.sun_path)) {
14830 so->
lsa.sun.sun_family = AF_UNIX;
14831 memset(so->
lsa.sun.sun_path, 0,
sizeof(so->
lsa.sun.sun_path));
14852 so->
is_ssl = (ch ==
's');
14854 if ((ch ==
'\0') || (ch ==
's') || (ch ==
'r')) {
14905 int portslen = (
int)strlen(ports);
14906 char prevIsNumber = 0;
14908 for (i = 0; i < portslen; i++) {
14909 if (prevIsNumber && (ports[i] ==
's' || ports[i] ==
'r')) {
14912 if (ports[i] >=
'0' && ports[i] <=
'9') {
14928#if defined(USE_IPV6)
14939 int portsTotal = 0;
14942 const char *opt_txt;
14943 long opt_listen_backlog;
14949 memset(&so, 0,
sizeof(so));
14950 memset(&
usa, 0,
sizeof(
usa));
14961 "%.*s: invalid port spec (entry %i). Expecting list of: %s",
14965 "[IP_ADDRESS:]PORT[s|r]");
14969#if !defined(NO_SSL)
14973 "Cannot add SSL socket (entry %i)",
14985 (ip_version == 99) ? ( 0) : ( 6)))
14989 "cannot create socket (entry %i)",
15004 if (setsockopt(so.
sock,
15006 SO_EXCLUSIVEADDRUSE,
15014 "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
15018 if (setsockopt(so.
sock,
15028 "cannot set socket option SO_REUSEADDR (entry %i)",
15033#if defined(USE_X_DOM_SOCKET)
15034 if (ip_version == 99) {
15039 if (ip_version > 4) {
15041#if defined(USE_IPV6)
15042 if (ip_version > 6) {
15043 if (so.
lsa.
sa.sa_family == AF_INET6
15044 && setsockopt(so.
sock,
15053 "cannot set socket option "
15054 "IPV6_V6ONLY=off (entry %i)",
15058 if (so.
lsa.
sa.sa_family == AF_INET6
15059 && setsockopt(so.
sock,
15068 "cannot set socket option "
15069 "IPV6_V6ONLY=on (entry %i)",
15081 if (so.
lsa.
sa.sa_family == AF_INET) {
15086 "cannot bind to %.*s: %d (%s)",
15096#if defined(USE_IPV6)
15097 else if (so.
lsa.
sa.sa_family == AF_INET6) {
15099 len =
sizeof(so.
lsa.sin6);
15102 "cannot bind to IPv6 %.*s: %d (%s)",
15113#if defined(USE_X_DOM_SOCKET)
15114 else if (so.
lsa.
sa.sa_family == AF_UNIX) {
15116 len =
sizeof(so.
lsa.sun);
15119 "cannot bind to unix socket %s: %d (%s)",
15120 so.
lsa.sun.sun_path,
15132 "cannot bind: address family not supported (entry %i)",
15140 opt_listen_backlog = strtol(opt_txt, NULL, 10);
15141 if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
15143 "%s value \"%s\" is invalid",
15151 if (listen(so.
sock, (
int)opt_listen_backlog) != 0) {
15154 "cannot listen to %.*s: %d (%s)",
15165 || (
usa.
sa.sa_family != so.
lsa.
sa.sa_family)) {
15169 "call to getsockname failed %.*s: %d (%s)",
15180#if defined(USE_IPV6)
15181 if (so.
lsa.
sa.sa_family == AF_INET6) {
15182 so.
lsa.sin6.sin6_port =
usa.sin6.sin6_port;
15189 if ((ptr = (
struct socket *)
15224 if (portsOk != portsTotal) {
15236 const char *header_value;
15238 if ((header_value =
mg_get_header(conn, header)) == NULL) {
15241 return header_value;
15246#if defined(MG_EXTERNAL_FUNCTION_log_access)
15247#include "external_log_access.inl"
15248#elif !defined(NO_FILESYSTEMS)
15258 const char *referer;
15259 const char *user_agent;
15261 char log_buf[4096];
15263 if (!conn || !conn->
dom_ctx) {
15270#if defined(USE_LUA)
15271 if (conn->
phys_ctx->lua_bg_log_available) {
15274 lua_State *lstate = (lua_State *)ctx->lua_background_state;
15275 pthread_mutex_lock(&ctx->lua_bg_mutex);
15277 lua_getglobal(lstate,
"log");
15278 prepare_lua_request_info_inner(conn, lstate);
15279 push_lua_response_log_data(conn, lstate);
15281 ret = lua_pcall(lstate, 2, 1, 0);
15283 int t = lua_type(lstate, -1);
15284 if (t == LUA_TBOOLEAN) {
15285 if (lua_toboolean(lstate, -1) == 0) {
15287 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15291 }
else if (t == LUA_TSTRING) {
15293 const char *txt = lua_tolstring(lstate, -1, &
len);
15294 if ((
len == 0) || (*txt == 0)) {
15296 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15300 if (
len >=
sizeof(log_buf)) {
15301 len =
sizeof(log_buf) - 1;
15303 memcpy(log_buf, txt,
len);
15307 lua_cry(conn, ret, lstate,
"lua_background_script",
"log");
15309 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15336 strftime(date,
sizeof(date),
"%d/%b/%Y:%H:%M:%S %z", tm);
15338 mg_strlcpy(date,
"01/Jan/1970:00:00:00 +0000",
sizeof(date));
15339 date[
sizeof(date) - 1] =
'\0';
15346 user_agent =
header_val(conn,
"User-Agent");
15352 "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
15383 if (fprintf(fi.
access.
fp,
"%s\n", log_buf) < 1) {
15395 "Error writing log file %s",
15401#error "Either enable filesystems or provide a custom log_access implementation"
15411 int allowed, flag, matched;
15418 allowed = (list == NULL) ?
'+' :
'-';
15423 if ((
vec.
len > 0) && ((flag ==
'+') || (flag ==
'-'))) {
15430 "%s: subnet must be [+|-]IP-addr[/x]",
15439 return allowed ==
'+';
15445#if !defined(_WIN32) && !defined(__ZEPHYR__)
15453 const uid_t curr_uid = getuid();
15456 const struct passwd *to_pw = NULL;
15458 if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
15462 "%s: unknown user [%s]",
15465 }
else if ((run_as_user == NULL) || (curr_uid == to_pw->
pw_uid)) {
15472 if (setgid(to_pw->
pw_gid) == -1) {
15474 "%s: setgid(%s): %s",
15478 }
else if (setgroups(0, NULL) == -1) {
15480 "%s: setgroups(): %s",
15483 }
else if (setuid(to_pw->
pw_uid) == -1) {
15485 "%s: setuid(%s): %s",
15512 pthread_setspecific(
sTlsKey, NULL);
15516#if defined(USE_MBEDTLS)
15527 dom_ctx = &(phys_ctx->
dd);
15536 if (dom_ctx->
ssl_ctx == NULL) {
15537 fprintf(stderr,
"ssl_ctx malloc failed\n");
15547#elif !defined(NO_SSL)
15552 const char *chain);
15559 struct stat cert_buf;
15563 int should_verify_peer;
15571 if (chain == NULL) {
15579 if (stat(pem, &cert_buf) != -1) {
15580 t = (int64_t)cert_buf.st_mtime;
15587 should_verify_peer = 0;
15591 should_verify_peer = 1;
15595 should_verify_peer = 1;
15599 if (should_verify_peer) {
15609 "SSL_CTX_load_verify_locations error: %s "
15610 "ssl_verify_peer requires setting "
15611 "either ssl_ca_path or ssl_ca_file. Is any of them "
15629#if defined(OPENSSL_API_1_1)
15636 int (*func)(
SSL *),
15641 unsigned timeout = 1024;
15662 if (conn->
ssl == NULL) {
15664 OPENSSL_REMOVE_THREAD_STATE();
15667 SSL_set_app_data(conn->
ssl, (
char *)conn);
15669 ret = SSL_set_fd(conn->ssl, conn->client.sock);
15672 SSL_free(conn->ssl);
15674 OPENSSL_REMOVE_THREAD_STATE();
15678 if (client_options) {
15680 SSL_set_tlsext_host_name(conn->ssl, client_options->
host_name);
15690 timeout = (unsigned)to;
15697 for (i = 0; i <= timeout; i += 50) {
15700 ret = func(conn->ssl);
15702 err = SSL_get_error(conn->ssl, ret);
15720 pfd.fd = conn->client.sock;
15726 mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
15753 SSL_free(conn->ssl);
15755 OPENSSL_REMOVE_THREAD_STATE();
15768 err = ERR_get_error();
15769 return ((err == 0) ?
"" : ERR_error_string(err, NULL));
15777 const char hexdigit[] =
"0123456789abcdef";
15779 if ((memlen <= 0) || (buflen <= 0)) {
15782 if (buflen < (3 * memlen)) {
15786 for (i = 0; i < memlen; i++) {
15788 buf[3 * i - 1] =
' ';
15790 buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
15791 buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
15793 buf[3 * memlen - 1] = 0;
15803 X509 *cert = SSL_get_peer_certificate(conn->
ssl);
15805 char str_buf[1024];
15806 unsigned char buf[256];
15807 char *str_serial = NULL;
15810 unsigned char *tmp_buf;
15811 unsigned char *tmp_p;
15814 const EVP_MD *digest = EVP_get_digestbyname(
"sha1");
15817 X509_NAME *subj = X509_get_subject_name(cert);
15818 X509_NAME *iss = X509_get_issuer_name(cert);
15824 BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
15826 str_serial = BN_bn2hex(serial_bn);
15827 BN_free(serial_bn);
15833 (void)X509_NAME_oneline(subj, str_buf, (
int)
sizeof(str_buf));
15835 (void)X509_NAME_oneline(iss, str_buf, (
int)
sizeof(str_buf));
15843 ilen = i2d_X509(cert, NULL);
15844 tmp_buf = (ilen > 0)
15850 (void)i2d_X509(cert, &tmp_p);
15852 tmp_buf, (
unsigned)ilen, buf, &ulen, digest, NULL)) {
15858 if (!
hexdump2string(buf, (
int)ulen, str_buf, (
int)
sizeof(str_buf))) {
15867 OPENSSL_free(str_serial);
15874#if defined(OPENSSL_API_1_1)
15884 (void)pthread_mutex_lock(&
ssl_mutexes[mutex_num]);
15886 (void)pthread_mutex_unlock(&
ssl_mutexes[mutex_num]);
15892#if !defined(NO_SSL_DL)
15897 const char *dll_name,
15899 int *feature_missing)
15910 if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
15915 "%s: cannot load %s",
15922 for (fp = sw; fp->
name != NULL; fp++) {
15925 u.fp = (void (*)(void))dlsym(dll_handle, fp->
name);
15930 u.p = dlsym(dll_handle, fp->
name);
15936 if (u.fp == NULL) {
15938 if (feature_missing) {
15950 "%s: %s: cannot find %s",
15958 size_t cur_len = strlen(ebuf);
15959 if (!truncated && ((ebuf_len - cur_len) > 3)) {
15963 ebuf_len - cur_len - 3,
15968 strcat(ebuf,
"...");
15977 (void)dlclose(dll_handle);
15991#if defined(SSL_ALREADY_INITIALIZED)
16003#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16008 if (ebuf_len > 0) {
16012#if !defined(NO_SSL_DL)
16022 "%s: error loading library %s",
16035#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16039 num_locks = CRYPTO_num_locks();
16040 if (num_locks < 0) {
16043 size =
sizeof(pthread_mutex_t) * ((
size_t)(num_locks));
16046 if (num_locks == 0) {
16059 "%s: cannot allocate mutexes: %s",
16067 for (i = 0; i < num_locks; i++) {
16073 "%s: error initializing mutex %i of %i",
16088#if !defined(NO_SSL_DL)
16093#if !defined(OPENSSL_API_1_1)
16102#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16103 && !defined(NO_SSL_DL)
16105 OPENSSL_init_ssl(0, NULL);
16111 SSL_library_init();
16112 SSL_load_error_strings();
16125 if (SSL_CTX_use_certificate_file(dom_ctx->
ssl_ctx, pem, 1) == 0) {
16127 "%s: cannot open certificate file %s: %s",
16135 if (SSL_CTX_use_PrivateKey_file(dom_ctx->
ssl_ctx, pem, 1) == 0) {
16137 "%s: cannot open private key file %s: %s",
16144 if (SSL_CTX_check_private_key(dom_ctx->
ssl_ctx) == 0) {
16146 "%s: certificate and private key do not match: %s",
16161 if (SSL_CTX_use_certificate_chain_file(dom_ctx->
ssl_ctx, chain) == 0) {
16163 "%s: cannot use certificate chain file %s: %s",
16174#if defined(OPENSSL_API_1_1)
16175static unsigned long
16178 long unsigned ret = (
long unsigned)
SSL_OP_ALL;
16179 if (version_id > 0)
16181 if (version_id > 1)
16183 if (version_id > 2)
16185 if (version_id > 3)
16187 if (version_id > 4)
16189#if defined(SSL_OP_NO_TLSv1_3)
16190 if (version_id > 5)
16199 unsigned long ret = (
unsigned long)
SSL_OP_ALL;
16200 if (version_id > 0)
16202 if (version_id > 1)
16204 if (version_id > 2)
16206 if (version_id > 3)
16208 if (version_id > 4)
16210#if defined(SSL_OP_NO_TLSv1_3)
16211 if (version_id > 5)
16235 SSL_get_app_data(ssl);
16248#if defined(GCC_DIAGNOSTIC)
16249#pragma GCC diagnostic push
16250#pragma GCC diagnostic ignored "-Wcast-align"
16256#if defined(GCC_DIAGNOSTIC)
16257#pragma GCC diagnostic pop
16265 if ((conn == NULL) || (conn->
phys_ctx == NULL)) {
16277 if ((servername == NULL) || (*servername == 0)) {
16278 DEBUG_TRACE(
"%s",
"SSL connection not supporting SNI");
16285 DEBUG_TRACE(
"TLS connection to host %s", servername);
16313#if defined(USE_ALPN)
16314static const char alpn_proto_list[] =
"\x02h2\x08http/1.1\x08http/1.0";
16315static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
16316 alpn_proto_list + 3 + 8,
16318#if defined(USE_HTTP2)
16319static const char *alpn_proto_order_http2[] = {alpn_proto_list,
16320 alpn_proto_list + 3,
16321 alpn_proto_list + 3 + 8,
16327 const unsigned char **out,
16328 unsigned char *outlen,
16329 const unsigned char *in,
16330 unsigned int inlen,
16334 unsigned int i, j, enable_http2 = 0;
16335 const char **alpn_proto_order = alpn_proto_order_http1;
16348#if defined(USE_HTTP2)
16349 enable_http2 = (0 == strcmp(dom_ctx->
config[ENABLE_HTTP2],
"yes"));
16350 if (enable_http2) {
16351 alpn_proto_order = alpn_proto_order_http2;
16355 for (j = 0; alpn_proto_order[j] != NULL; j++) {
16357 const char *
alpn_proto = alpn_proto_order[j];
16359 for (i = 0; i < inlen; i++) {
16375next_protos_advertised_cb(
SSL *ssl,
16376 const unsigned char **
data,
16381 *
data = (
const unsigned char *)alpn_proto_list;
16382 *
len = (
unsigned int)strlen((
const char *)
data);
16394 unsigned int alpn_len = (
unsigned int)strlen((
char *)alpn_proto_list);
16395 int ret = SSL_CTX_set_alpn_protos(dom_ctx->
ssl_ctx,
16396 (
const unsigned char *)alpn_proto_list,
16400 "SSL_CTX_set_alpn_protos error: %s",
16404 SSL_CTX_set_alpn_select_cb(dom_ctx->
ssl_ctx,
16408 SSL_CTX_set_next_protos_advertised_cb(dom_ctx->
ssl_ctx,
16409 next_protos_advertised_cb,
16425 int should_verify_peer;
16426 int peer_certificate_optional;
16427 const char *ca_path;
16428 const char *ca_file;
16429 int use_default_verify_paths;
16431 struct timespec now_mt;
16435 int ssl_cache_timeout;
16437#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16438 && !defined(NO_SSL_DL)
16439 if ((dom_ctx->
ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
16441 "SSL_CTX_new (server) error: %s",
16446 if ((dom_ctx->
ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
16448 "SSL_CTX_new (server) error: %s",
16454#if defined(SSL_OP_NO_TLSv1_3)
16455 SSL_CTX_clear_options(dom_ctx->
ssl_ctx,
16460 SSL_CTX_clear_options(dom_ctx->
ssl_ctx,
16469 SSL_CTX_set_options(dom_ctx->
ssl_ctx,
16473#if defined(SSL_OP_NO_RENEGOTIATION)
16477#if !defined(NO_SSL_DL)
16478 SSL_CTX_set_ecdh_auto(dom_ctx->
ssl_ctx, 1);
16496 SSL_CTX_set_tlsext_servername_callback(dom_ctx->
ssl_ctx,
16508 if (callback_ret < 0) {
16510 "SSL callback returned error: %i",
16514 if (callback_ret > 0) {
16530 if (callback_ret < 0) {
16532 "Domain SSL callback returned error: %i",
16536 if (callback_ret > 0) {
16544 clock_gettime(CLOCK_MONOTONIC, &now_mt);
16556 SSL_CTX_set_session_id_context(dom_ctx->
ssl_ctx,
16557 (
unsigned char *)ssl_context_id,
16558 sizeof(ssl_context_id));
16568 should_verify_peer = 0;
16569 peer_certificate_optional = 0;
16573 should_verify_peer = 1;
16578 should_verify_peer = 1;
16579 peer_certificate_optional = 1;
16583 use_default_verify_paths =
16588 if (should_verify_peer) {
16591 if (SSL_CTX_load_verify_locations(dom_ctx->
ssl_ctx, ca_file, ca_path)
16594 "SSL_CTX_load_verify_locations error: %s "
16595 "ssl_verify_peer requires setting "
16596 "either ssl_ca_path or ssl_ca_file. "
16597 "Is any of them present in the "
16603 if (peer_certificate_optional) {
16606 SSL_CTX_set_verify(dom_ctx->
ssl_ctx,
16612 if (use_default_verify_paths
16613 && (SSL_CTX_set_default_verify_paths(dom_ctx->
ssl_ctx) != 1)) {
16615 "SSL_CTX_set_default_verify_paths error: %s",
16622 SSL_CTX_set_verify_depth(dom_ctx->
ssl_ctx, verify_depth);
16627 if (SSL_CTX_set_cipher_list(dom_ctx->
ssl_ctx,
16631 "SSL_CTX_set_cipher_list error: %s",
16640 if (ssl_cache_timeout > 0) {
16644 SSL_CTX_set_timeout(dom_ctx->
ssl_ctx, (
long)ssl_cache_timeout);
16647#if defined(USE_ALPN)
16649#if !defined(NO_SSL_DL)
16653 init_alpn(phys_ctx, dom_ctx);
16678 dom_ctx = &(phys_ctx->
dd);
16693 if (callback_ret < 0) {
16696 "external_ssl_ctx callback returned error: %i",
16699 }
else if (callback_ret > 0) {
16720 if (callback_ret < 0) {
16724 "external_ssl_ctx_domain callback returned error: %i",
16727 }
else if (callback_ret > 0) {
16748 "Initializing SSL failed: -%s is not set",
16755 if (chain == NULL) {
16759 if ((chain != NULL) && (*chain == 0)) {
16776#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
16784 CONF_modules_unload(1);
16794 CRYPTO_set_locking_callback(NULL);
16795 CRYPTO_set_id_callback(NULL);
16797 CONF_modules_unload(1);
16798 ERR_free_strings();
16800 CRYPTO_cleanup_all_ex_data();
16801 OPENSSL_REMOVE_THREAD_STATE();
16803 for (i = 0; i < CRYPTO_num_locks(); i++) {
16814#if !defined(NO_FILESYSTEMS)
16829 "Cannot open %s: %s",
16845 memset(&
sa, 0,
sizeof(
sa));
16846#if defined(USE_IPV6)
16847 sa.sin6.sin6_family = AF_INET6;
16849 sa.sin.sin_family = AF_INET;
16891#if defined(USE_SERVER_STATS)
16892 conn->processing_time = 0;
16900 if ((so->
lsa.
sa.sa_family == AF_INET)
16901 || (so->
lsa.
sa.sa_family == AF_INET6)) {
16903 if (setsockopt(so->
sock,
16907 sizeof(nodelay_on))
16918#if !defined(__ZEPHYR__)
16926 struct linger linger;
16927 int error_code = 0;
16928 int linger_timeout = -2;
16929 socklen_t opt_len =
sizeof(error_code);
16952 n =
pull_inner(NULL, conn, buf,
sizeof(buf), 1.0);
16961 if (linger_timeout >= 0) {
16964 linger.l_onoff = 1;
16966#if defined(_MSC_VER)
16967#pragma warning(push)
16968#pragma warning(disable : 4244)
16970#if defined(GCC_DIAGNOSTIC)
16971#pragma GCC diagnostic push
16972#pragma GCC diagnostic ignored "-Wconversion"
16978 linger.l_linger = (linger_timeout + 999) / 1000;
16980#if defined(GCC_DIAGNOSTIC)
16981#pragma GCC diagnostic pop
16983#if defined(_MSC_VER)
16984#pragma warning(pop)
16988 linger.l_onoff = 0;
16989 linger.l_linger = 0;
16992 if (linger_timeout < -1) {
16998 (
char *)&error_code,
17008 "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
17012 }
else if (error_code == WSAECONNRESET) {
17014 }
else if (error_code == ECONNRESET) {
17029 "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
17047#if defined(USE_SERVER_STATS)
17048 conn->conn_state = 6;
17051#if defined(USE_LUA) && defined(USE_WEBSOCKET)
17052 if (conn->lua_websocket_state) {
17053 lua_websocket_close(conn, conn->lua_websocket_state);
17054 conn->lua_websocket_state = NULL;
17076#if defined(USE_SERVER_STATS)
17077 conn->conn_state = 7;
17080#if defined(USE_MBEDTLS)
17081 if (conn->
ssl != NULL) {
17082 mbed_ssl_close(conn->
ssl);
17085#elif !defined(NO_SSL)
17086 if (conn->
ssl != NULL) {
17089 SSL_shutdown(conn->
ssl);
17090 SSL_free(conn->
ssl);
17091 OPENSSL_REMOVE_THREAD_STATE();
17096#if defined(__ZEPHYR__)
17113#if defined(USE_SERVER_STATS)
17114 conn->conn_state = 8;
17122 if ((conn == NULL) || (conn->
phys_ctx == NULL)) {
17126#if defined(USE_WEBSOCKET)
17128 if (conn->in_websocket_handling) {
17156#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
17164#if defined(USE_WEBSOCKET)
17167 (void)pthread_mutex_destroy(&conn->
mutex);
17170 (void)pthread_mutex_destroy(&conn->
mutex);
17175 (void)pthread_mutex_destroy(&conn->
mutex);
17191 struct sockaddr *psa;
17194 unsigned max_req_size =
17198 size_t conn_size = ((
sizeof(
struct mg_connection) + 7) >> 3) << 3;
17199 size_t ctx_size = ((
sizeof(
struct mg_context) + 7) >> 3) << 3;
17203 conn_size + ctx_size + max_req_size);
17205 if (conn == NULL) {
17215#if defined(GCC_DIAGNOSTIC)
17216#pragma GCC diagnostic push
17217#pragma GCC diagnostic ignored "-Wcast-align"
17223#if defined(GCC_DIAGNOSTIC)
17224#pragma GCC diagnostic pop
17227 conn->
buf = (((
char *)conn) + conn_size + ctx_size);
17233 client_options->
host,
17234 client_options->
port,
17246#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
17247#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
17248 && !defined(NO_SSL_DL)
17256 "SSL_CTX_new error: %s",
17264 && (conn->
dom_ctx->
ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
17270 "SSL_CTX_new error: %s",
17280#if defined(USE_IPV6)
17283 psa = (sa.
sa.sa_family == AF_INET)
17285 : (
struct sockaddr *)&(conn->
client.
rsa.sin6);
17294 if (getsockname(sock, psa, &
len) != 0) {
17296 "%s: getsockname() failed: %s",
17307 "Can not create mutex");
17308#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
17317#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
17335 "Can not use SSL client certificate");
17349 "SSL_CTX_load_verify_locations error: %s ",
17361 if (!
sslize(conn, SSL_connect, client_options)) {
17366 "SSL connection error");
17381 char *error_buffer,
17382 size_t error_buffer_size)
17387 error_buffer_size);
17395 char *error_buffer,
17396 size_t error_buffer_size)
17399 memset(&opts, 0,
sizeof(opts));
17405 error_buffer_size);
17409#if defined(MG_EXPERIMENTAL_INTERFACES)
17411mg_connect_client2(
const char *host,
17412 const char *protocol,
17421 if (error != NULL) {
17428 if ((host == NULL) || (protocol == NULL)) {
17435 "Invalid parameters");
17447#if defined(USE_WEBSOCKET)
17461 "Protocol %s not supported",
17470#if defined(USE_WEBSOCKET)
17477 ((error != NULL) ? error->
text : NULL),
17478 ((error != NULL) ? error->text_buffer_size : 0),
17479 (path ? path :
""),
17481 experimental_websocket_client_data_wrapper,
17482 experimental_websocket_client_close_wrapper,
17489 memset(&opts, 0,
sizeof(opts));
17494 ((error != NULL) ? error->
text : NULL),
17495 ((error != NULL) ? error->text_buffer_size
17501static const struct {
17506 {
"https://", 8, 443},
17508 {
"wss://", 6, 443},
17522 const char *hostend, *portbegin;
17524 unsigned long port;
17530 if ((uri[0] ==
'*') && (uri[1] ==
'\0')) {
17541 for (i = 0; uri[i] != 0; i++) {
17550 if (uri[0] ==
'/') {
17574 port = strtoul(portbegin + 1, &portend, 10);
17575 if ((portend != hostend) || (port <= 0) || !
is_valid_port(port)) {
17591 const char *server_domain;
17592 size_t server_domain_len;
17593 size_t request_domain_len = 0;
17594 unsigned long port = 0;
17595 int i, auth_domain_check_enabled;
17596 const char *hostbegin = NULL;
17597 const char *hostend = NULL;
17598 const char *portbegin;
17601 auth_domain_check_enabled =
17613 hostend = strchr(hostbegin,
'/');
17617 portbegin = strchr(hostbegin,
':');
17618 if ((!portbegin) || (portbegin > hostend)) {
17620 request_domain_len = (size_t)(hostend - hostbegin);
17622 port = strtoul(portbegin + 1, &portend, 10);
17623 if ((portend != hostend) || (port <= 0)
17627 request_domain_len = (size_t)(portbegin - hostbegin);
17654 if (auth_domain_check_enabled) {
17656 server_domain_len = strlen(server_domain);
17657 if ((server_domain_len == 0) || (hostbegin == NULL)) {
17660 if ((request_domain_len == server_domain_len)
17661 && (!memcmp(server_domain, hostbegin, server_domain_len))) {
17664 if (request_domain_len < (server_domain_len + 2)) {
17671 if (hostbegin[request_domain_len - server_domain_len - 1] !=
'.') {
17678 != memcmp(server_domain,
17679 hostbegin + request_domain_len - server_domain_len,
17680 server_domain_len)) {
17695 if (ebuf_len > 0) {
17715 clock_gettime(CLOCK_MONOTONIC, &(conn->
req_time));
17726 "Invalid message size");
17737 "Message too large");
17749 "Malformed message");
17759 "No data received");
17800 "Bad request: Host mismatch");
17808 "Accept-Encoding"))
17810 && strstr(cl,
"gzip")) {
17816 "Transfer-Encoding"))
17836 char *endptr = NULL;
17888 "Transfer-Encoding"))
17907 char *endptr = NULL;
17953 char *save_timeout;
17956 if (ebuf_len > 0) {
17966 "Parameter error");
17976 if (timeout >= 0) {
17977 mg_snprintf(conn, NULL, txt,
sizeof(txt),
"%i", timeout);
17980 new_timeout = NULL;
17993 return (ret == 0) ? -1 : +1;
18011 if (ebuf_len > 0) {
18020 if (conn != NULL) {
18028 "Error sending request");
18040 if ((ebuf[0] !=
'\0') && (conn != NULL)) {
18058#if defined(USE_WEBSOCKET)
18060static unsigned __stdcall websocket_client_thread(
void *
data)
18063websocket_client_thread(
void *
data)
18069 void *user_thread_ptr = NULL;
18071#if !defined(_WIN32) && !defined(__ZEPHYR__)
18072 struct sigaction sa;
18075 memset(&sa, 0,
sizeof(sa));
18076 sa.sa_handler = SIG_IGN;
18077 sigaction(SIGPIPE, &sa, NULL);
18093 DEBUG_TRACE(
"%s",
"Websocket client thread exited\n");
18123 char *error_buffer,
18124 size_t error_buffer_size,
18126 const char *origin,
18127 const char *extensions,
18134#if defined(USE_WEBSOCKET)
18136 static const char *magic =
"x3JJHMbDL1EzLkh9GBhXDw==";
18138 const char *host = client_options->
host;
18141#if defined(__clang__)
18142#pragma clang diagnostic push
18143#pragma clang diagnostic ignored "-Wformat-nonliteral"
18150 error_buffer_size);
18153 if (
conn == NULL) {
18155 if (!error_buffer[0]) {
18161 "Unexpected error");
18166 if (origin != NULL) {
18167 if (extensions != NULL) {
18169 "GET %s HTTP/1.1\r\n"
18171 "Upgrade: websocket\r\n"
18172 "Connection: Upgrade\r\n"
18173 "Sec-WebSocket-Key: %s\r\n"
18174 "Sec-WebSocket-Version: 13\r\n"
18175 "Sec-WebSocket-Extensions: %s\r\n"
18185 "GET %s HTTP/1.1\r\n"
18187 "Upgrade: websocket\r\n"
18188 "Connection: Upgrade\r\n"
18189 "Sec-WebSocket-Key: %s\r\n"
18190 "Sec-WebSocket-Version: 13\r\n"
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"
18216 "GET %s HTTP/1.1\r\n"
18218 "Upgrade: websocket\r\n"
18219 "Connection: Upgrade\r\n"
18220 "Sec-WebSocket-Key: %s\r\n"
18221 "Sec-WebSocket-Version: 13\r\n"
18234 "Error sending request");
18247#if defined(__clang__)
18248#pragma clang diagnostic pop
18256 if (!*error_buffer) {
18262 "Unexpected server reply");
18265 DEBUG_TRACE(
"Websocket client connect error: %s\r\n", error_buffer);
18272 if (!thread_data) {
18309 "Websocket client connect thread could not be started\r\n");
18314 (void)client_options;
18316 (void)error_buffer;
18317 (void)error_buffer_size;
18334 char *error_buffer,
18335 size_t error_buffer_size,
18337 const char *origin,
18343 memset(&client_options, 0,
sizeof(client_options));
18363 char *error_buffer,
18364 size_t error_buffer_size,
18366 const char *origin,
18371 if (!client_options) {
18390 char *error_buffer,
18391 size_t error_buffer_size,
18393 const char *origin,
18394 const char *extensions,
18400 memset(&client_options, 0,
sizeof(client_options));
18419 char *error_buffer,
18420 size_t error_buffer_size,
18422 const char *origin,
18423 const char *extensions,
18428 if (!client_options) {
18448 int keep_alive_enabled =
18451 if (!keep_alive_enabled) {
18462#if defined(USE_SERVER_STATS)
18463 conn->conn_state = 2;
18469 void *conn_data = NULL;
18486 int keep_alive, discard_len;
18488 const char *hostend;
18489 int reqerr, uri_type;
18491#if defined(USE_SERVER_STATS)
18493 mg_atomic_add(&(conn->
phys_ctx->total_connections), 1);
18494 mg_atomic_max(&(conn->
phys_ctx->max_active_connections), mcon);
18497 DEBUG_TRACE(
"Start processing connection from %s",
18503 DEBUG_TRACE(
"calling get_request (%i times for this connection)",
18506#if defined(USE_SERVER_STATS)
18507 conn->conn_state = 3;
18510 if (!
get_request(conn, ebuf,
sizeof(ebuf), &reqerr)) {
18526 "Bad HTTP version: [%s]",
18531 if (ebuf[0] ==
'\0') {
18533 switch (uri_type) {
18569 if (ebuf[0] !=
'\0') {
18589 (ebuf[0] ? ebuf :
"none"));
18591 if (ebuf[0] ==
'\0') {
18642 conn->
buf + discard_len,
18651 DEBUG_TRACE(
"internal error: data_len = %li, buf_size = %li",
18657 }
while (keep_alive);
18659 DEBUG_TRACE(
"Done processing connection from %s (%f sec)",
18665#if defined(USE_SERVER_STATS)
18672#if defined(ALTERNATIVE_QUEUE)
18682 if (ctx->client_socks[i].in_use == 2) {
18684 if ((ctx->client_socks[i].in_use == 2) && !ctx->
stop_flag) {
18685 ctx->client_socks[i] = *sp;
18686 ctx->client_socks[i].in_use = 1;
18689 (
void)event_signal(ctx->client_wait_events[i]);
18709 ctx->client_socks[thread_index].in_use = 2;
18712 event_wait(ctx->client_wait_events[thread_index]);
18715 *sp = ctx->client_socks[thread_index];
18741 (void)thread_index;
18767 (void)pthread_cond_signal(&ctx->
sq_empty);
18786 && (queue_filled >= ctx->
sq_size)) {
18788#if defined(USE_SERVER_STATS)
18789 if (queue_filled > ctx->sq_max_fill) {
18790 ctx->sq_max_fill = queue_filled;
18798 if (queue_filled < ctx->sq_size) {
18806#if defined(USE_SERVER_STATS)
18807 if (queue_filled > ctx->sq_max_fill) {
18808 ctx->sq_max_fill = queue_filled;
18812 (void)pthread_cond_signal(&ctx->
sq_full);
18830 tls.pthread_cond_helper_mutex = CreateEvent(NULL,
FALSE,
FALSE, NULL);
18834 pthread_setspecific(
sTlsKey, &tls);
18848 if ((thread_index < 0)
18851 "Internal error: Invalid worker index %i",
18860 if (conn->
buf == NULL) {
18863 "Out of memory: Cannot allocate buffer for worker %i",
18883#if defined(USE_SERVER_STATS)
18884 conn->conn_state = 1;
18895#if defined(USE_SERVER_STATS)
18896 conn->conn_close_time = 0;
18922#if defined(USE_MBEDTLS)
18924 if (mbed_ssl_accept(&(conn->
ssl),
18940#elif !defined(NO_SSL)
18942 if (
sslize(conn, SSL_accept, NULL)) {
18952#if defined(USE_HTTP2)
18954 && (!memcmp(tls.
alpn_proto,
"\x02h2", 3))) {
18962 process_new_http2_connection(conn);
19007#if defined(USE_SERVER_STATS)
19008 conn->conn_close_time = time(NULL);
19018 pthread_setspecific(
sTlsKey, NULL);
19020 CloseHandle(tls.pthread_cond_helper_mutex);
19022 pthread_mutex_destroy(&conn->
mutex);
19035#if defined(USE_SERVER_STATS)
19036 conn->conn_state = 9;
19045static unsigned __stdcall
worker_thread(
void *thread_func_param)
19054#if !defined(__ZEPHYR__)
19055 struct sigaction sa;
19058 memset(&sa, 0,
sizeof(sa));
19059 sa.sa_handler = SIG_IGN;
19060 sigaction(SIGPIPE, &sa, NULL);
19076 socklen_t
len =
sizeof(so.
rsa);
19077#if !defined(__ZEPHYR__)
19080 memset(&so, 0,
sizeof(so));
19087 "%s: %s is not allowed to connect",
19099 "%s: getsockname() failed: %s",
19104#if !defined(__ZEPHYR__)
19105 if ((so.
lsa.
sa.sa_family == AF_INET)
19106 || (so.
lsa.
sa.sa_family == AF_INET6)) {
19114 if (setsockopt(so.
sock,
19122 "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
19141 "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
19164 unsigned int workerthreadcount;
19174 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
19175#elif defined(USE_MASTER_THREAD_PRIORITY)
19176 int min_prio = sched_get_priority_min(SCHED_RR);
19177 int max_prio = sched_get_priority_max(SCHED_RR);
19178 if ((min_prio >= 0) && (max_prio >= 0)
19179 && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
19180 && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
19181 struct sched_param sched_param = {0};
19182 sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
19183 pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
19189 tls.pthread_cond_helper_mutex = CreateEvent(NULL,
FALSE,
FALSE, NULL);
19192 pthread_setspecific(
sTlsKey, &tls);
19202#if defined(USE_LUA)
19203 if (ctx->lua_background_state) {
19204 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19205 pthread_mutex_lock(&ctx->lua_bg_mutex);
19208 lua_getglobal(lstate,
"start");
19209 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19210 int ret = lua_pcall(lstate, 0, 0, 0);
19216 "lua_background_script",
19220 lua_pop(lstate, 1);
19224 lua_getglobal(lstate,
"log");
19225 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19226 ctx->lua_bg_log_available = 1;
19228 lua_pop(lstate, 1);
19230 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19242 pfd[i].events = POLLIN;
19257 && (pfd[i].revents & POLLIN)) {
19271#if defined(ALTERNATIVE_QUEUE)
19273 event_signal(ctx->client_wait_events[i]);
19277 pthread_cond_broadcast(&ctx->
sq_full);
19283 for (i = 0; i < workerthreadcount; i++) {
19289#if defined(USE_LUA)
19291 if (ctx->lua_background_state) {
19292 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19293 ctx->lua_bg_log_available = 0;
19296 pthread_mutex_lock(&ctx->lua_bg_mutex);
19297 lua_getglobal(lstate,
"stop");
19298 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19299 int ret = lua_pcall(lstate, 0, 0, 0);
19305 "lua_background_script",
19311 ctx->lua_background_state = 0;
19312 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19325 CloseHandle(tls.pthread_cond_helper_mutex);
19327 pthread_setspecific(
sTlsKey, NULL);
19338static unsigned __stdcall
master_thread(
void *thread_func_param)
19347#if !defined(__ZEPHYR__)
19348 struct sigaction sa;
19351 memset(&sa, 0,
sizeof(sa));
19352 sa.sa_handler = SIG_IGN;
19353 sigaction(SIGPIPE, &sa, NULL);
19382#if defined(ALTERNATIVE_QUEUE)
19384 if (ctx->client_wait_events != NULL) {
19385 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
19386 event_destroy(ctx->client_wait_events[i]);
19388 mg_free(ctx->client_wait_events);
19391 (void)pthread_cond_destroy(&ctx->
sq_empty);
19392 (void)pthread_cond_destroy(&ctx->
sq_full);
19399#if defined(USE_LUA)
19400 (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
19406#if defined(_MSC_VER)
19407#pragma warning(suppress : 6001)
19421#if defined(USE_MBEDTLS)
19428#elif !defined(NO_SSL)
19431 void *ssl_ctx = (
void *)ctx->
dd.
ssl_ctx;
19437 if (callback_ret == 0) {
19480#if defined(USE_TIMERS)
19493#if defined(USE_LUA)
19507 DWORD dwVersion = 0;
19508 DWORD dwMajorVersion = 0;
19509 DWORD dwMinorVersion = 0;
19511 BOOL wowRet, isWoW =
FALSE;
19513#if defined(_MSC_VER)
19514#pragma warning(push)
19516#pragma warning(disable : 4996)
19518 dwVersion = GetVersion();
19519#if defined(_MSC_VER)
19520#pragma warning(pop)
19523 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
19524 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
19525 dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
19528 wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
19532 (
unsigned)dwMajorVersion,
19533 (
unsigned)dwMinorVersion,
19534 (wowRet ? (isWoW ?
" (WoW64)" :
"") :
" (?)"));
19539#elif defined(__ZEPHYR__)
19542 struct utsname
name;
19556 const char **run_options = options;
19560 while (*run_options) {
19561 if (!strcmp(*run_options, optname)) {
19562 ports_option = run_options[1];
19582 const char *
name, *
value, *default_value;
19583 int idx, ok, workerthreadcount;
19586 void (*exit_callback)(
const struct mg_context *ctx) = 0;
19587 const char **options =
19588 ((init != NULL) ? (init->configuration_options) : (NULL));
19592 if (error != NULL) {
19612 "Library uninitialized");
19632 (uint64_t)
get_random() ^ (uint64_t)(ptrdiff_t)(options);
19641 tls.pthread_cond_helper_mutex = NULL;
19643 pthread_setspecific(
sTlsKey, &tls);
19646#if !defined(ALTERNATIVE_QUEUE)
19647 ok &= (0 == pthread_cond_init(&ctx->
sq_empty, NULL));
19648 ok &= (0 == pthread_cond_init(&ctx->
sq_full, NULL));
19652#if defined(USE_LUA)
19656 const char *err_msg =
19657 "Cannot initialize thread synchronization objects";
19672 pthread_setspecific(
sTlsKey, NULL);
19676 if ((init != NULL) && (init->callbacks != NULL)) {
19679 exit_callback = init->callbacks->exit_context;
19685 ctx->
user_data = ((init != NULL) ? (init->user_data) : (NULL));
19689#if defined(USE_LUA)
19694 while (options && (
name = *options++) != NULL) {
19702 "Invalid configuration option: %s",
19706 pthread_setspecific(
sTlsKey, NULL);
19708 }
else if ((
value = *options++) == NULL) {
19715 "Invalid configuration option value: %s",
19719 pthread_setspecific(
sTlsKey, NULL);
19722 if (ctx->
dd.
config[idx] != NULL) {
19735 if ((ctx->
dd.
config[i] == NULL) && (default_value != NULL)) {
19751 "Invalid configuration option value: %s",
19755 pthread_setspecific(
sTlsKey, NULL);
19761#if !defined(ALTERNATIVE_QUEUE)
19772 "Invalid configuration option value: %s",
19776 pthread_setspecific(
sTlsKey, NULL);
19781 if (ctx->
squeue == NULL) {
19783 "Out of memory: Cannot allocate %s",
19790 "Out of memory: Cannot allocate %s",
19794 pthread_setspecific(
sTlsKey, NULL);
19804 if (workerthreadcount <= 0) {
19814 "Invalid configuration option value: %s",
19818 pthread_setspecific(
sTlsKey, NULL);
19823#if defined(NO_FILES)
19831 "Invalid configuration option value: %s",
19835 pthread_setspecific(
sTlsKey, NULL);
19842#if defined(USE_LUA)
19844 ctx->lua_bg_log_available = 0;
19845 if (ctx->
dd.
config[LUA_BACKGROUND_SCRIPT] != NULL) {
19847 struct vec opt_vec;
19849 const char *sparams;
19851 memset(ebuf, 0,
sizeof(ebuf));
19852 pthread_mutex_lock(&ctx->lua_bg_mutex);
19855 lua_State *state = mg_lua_context_script_prepare(
19856 ctx->
dd.
config[LUA_BACKGROUND_SCRIPT], ctx, ebuf,
sizeof(ebuf));
19859 "lua_background_script load error: %s",
19866 "Error in script %s: %s",
19870 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19873 pthread_setspecific(
sTlsKey, NULL);
19878 sparams = ctx->
dd.
config[LUA_BACKGROUND_SCRIPT_PARAMS];
19879 if (sparams && sparams[0]) {
19880 lua_getglobal(state,
"mg");
19881 lua_pushstring(state,
"params");
19882 lua_newtable(state);
19884 while ((sparams =
next_option(sparams, &opt_vec, &eq_vec))
19887 state, opt_vec.
ptr, opt_vec.
len, eq_vec.
ptr, eq_vec.
len);
19891 lua_rawset(state, -3);
19896 state = mg_lua_context_script_run(state,
19897 ctx->
dd.
config[LUA_BACKGROUND_SCRIPT],
19903 "lua_background_script start error: %s",
19910 "Error in script %s: %s",
19914 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19917 pthread_setspecific(
sTlsKey, NULL);
19922 ctx->lua_background_state = (
void *)state;
19923 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19926 ctx->lua_background_state = 0;
19931#if !defined(NO_FILESYSTEMS)
19933 const char *err_msg =
"Invalid global password file";
19946 pthread_setspecific(
sTlsKey, NULL);
19951#if defined(USE_MBEDTLS)
19952 if (!mg_sslctx_init(ctx, NULL)) {
19953 const char *err_msg =
"Error initializing SSL context";
19966 pthread_setspecific(
sTlsKey, NULL);
19970#elif !defined(NO_SSL)
19972 const char *err_msg =
"Error initializing SSL context";
19985 pthread_setspecific(
sTlsKey, NULL);
19991 const char *err_msg =
"Failed to setup server ports";
20004 pthread_setspecific(
sTlsKey, NULL);
20009#if !defined(_WIN32) && !defined(__ZEPHYR__)
20011 const char *err_msg =
"Failed to run as configured user";
20024 pthread_setspecific(
sTlsKey, NULL);
20030 const char *err_msg =
"Failed to setup access control list";
20043 pthread_setspecific(
sTlsKey, NULL);
20053 const char *err_msg =
"Not enough memory for worker thread ID array";
20065 pthread_setspecific(
sTlsKey, NULL);
20073 const char *err_msg =
20074 "Not enough memory for worker thread connection array";
20086 pthread_setspecific(
sTlsKey, NULL);
20090#if defined(ALTERNATIVE_QUEUE)
20091 ctx->client_wait_events =
20093 sizeof(ctx->client_wait_events[0]),
20095 if (ctx->client_wait_events == NULL) {
20096 const char *err_msg =
"Not enough memory for worker event array";
20109 pthread_setspecific(
sTlsKey, NULL);
20113 ctx->client_socks =
20115 sizeof(ctx->client_socks[0]),
20117 if (ctx->client_socks == NULL) {
20118 const char *err_msg =
"Not enough memory for worker socket array";
20120 mg_free(ctx->client_wait_events);
20132 pthread_setspecific(
sTlsKey, NULL);
20136 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
20137 ctx->client_wait_events[i] = event_create();
20138 if (ctx->client_wait_events[i] == 0) {
20139 const char *err_msg =
"Error creating worker event %i";
20143 event_destroy(ctx->client_wait_events[i]);
20146 mg_free(ctx->client_wait_events);
20158 pthread_setspecific(
sTlsKey, NULL);
20164#if defined(USE_TIMERS)
20165 if (timers_init(ctx) != 0) {
20166 const char *err_msg =
"Error creating timers";
20178 pthread_setspecific(
sTlsKey, NULL);
20202 long error_no = (long)
ERRNO;
20209 "Cannot start worker thread %i: error %ld",
20222 "Cannot create threads: error %ld",
20231 "Cannot create first worker thread: error %ld",
20235 pthread_setspecific(
sTlsKey, NULL);
20245 pthread_setspecific(
sTlsKey, NULL);
20253 const char **options)
20258 init.configuration_options = options;
20267 const char **options,
20272 const char *default_value;
20277 if (error != NULL) {
20284 if ((ctx == NULL) || (options == NULL)) {
20291 "Invalid parameters");
20303 "Server already stopped");
20325 while (options && (
name = *options++) != NULL) {
20333 "Invalid option: %s",
20338 }
else if ((
value = *options++) == NULL) {
20345 "Invalid option value: %s",
20351 if (new_dom->
config[idx] != NULL) {
20369 "Mandatory option %s missing",
20379 default_value = ctx->
dd.
config[i];
20380 if ((new_dom->
config[i] == NULL) && (default_value != NULL)) {
20386 new_dom->
next = NULL;
20391#if defined(USE_LUA) && defined(USE_WEBSOCKET)
20392 new_dom->shared_lua_websockets = NULL;
20395#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
20404 "Initializing SSL context failed");
20421 "domain %s already in use",
20428 "Domain %s specified by %s is already in use",
20440 if (dom->
next == NULL) {
20441 dom->
next = new_dom;
20465 static const unsigned feature_set = 0
20469#if !defined(NO_FILES)
20472#if !defined(NO_SSL) || defined(USE_MBEDTLS)
20475#if !defined(NO_CGI)
20478#if defined(USE_IPV6)
20481#if defined(USE_WEBSOCKET)
20484#if defined(USE_LUA)
20487#if defined(USE_DUKTAPE)
20490#if !defined(NO_CACHING)
20493#if defined(USE_SERVER_STATS)
20496#if defined(USE_ZLIB)
20499#if defined(USE_HTTP2)
20502#if defined(USE_X_DOM_SOCKET)
20508#if defined(MG_LEGACY_INTERFACE)
20511#if defined(MG_EXPERIMENTAL_INTERFACES)
20514#if !defined(NO_RESPONSE_BUFFERING)
20517#if defined(MEMORY_DEBUGGING)
20521 return (feature & feature_set);
20528 size_t len = strlen(
src);
20531 if ((
size_t)(end - *dst) >
len) {
20547 char *end, *append_eoobj = NULL, block[256];
20548 size_t system_info_length = 0;
20551 static const char eol[] =
"\r\n", eoobj[] =
"\r\n}\r\n";
20553 static const char eol[] =
"\n", eoobj[] =
"\n}\n";
20556 if ((buffer == NULL) || (buflen < 1)) {
20561 end = buffer + buflen;
20563 if (buflen > (
int)(
sizeof(eoobj) - 1)) {
20565 append_eoobj = buffer;
20567 end -=
sizeof(eoobj) - 1;
20580 "%s\"version\" : \"%s\"",
20589 DWORD dwVersion = 0;
20590 DWORD dwMajorVersion = 0;
20591 DWORD dwMinorVersion = 0;
20594 GetSystemInfo(&si);
20596#if defined(_MSC_VER)
20597#pragma warning(push)
20599#pragma warning(disable : 4996)
20601 dwVersion = GetVersion();
20602#if defined(_MSC_VER)
20603#pragma warning(pop)
20606 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
20607 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
20613 ",%s\"os\" : \"Windows %u.%u\"",
20615 (
unsigned)dwMajorVersion,
20616 (
unsigned)dwMinorVersion);
20623 ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
20625 (
unsigned)si.wProcessorArchitecture,
20626 (
unsigned)si.dwNumberOfProcessors,
20627 (
unsigned)si.dwActiveProcessorMask);
20629#elif defined(__ZEPHYR__)
20634 ",%s\"os\" : \"%s %s\"",
20640 struct utsname
name;
20648 ",%s\"os\" : \"%s %s (%s) - %s\"",
20664 ",%s\"features\" : %lu"
20665 ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
20681#if defined(USE_LUA)
20686 ",%s\"lua_version\" : \"%u (%s)\"",
20688 (
unsigned)LUA_VERSION_NUM,
20692#if defined(USE_DUKTAPE)
20697 ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
20699 (
unsigned)DUK_VERSION / 10000,
20700 ((
unsigned)DUK_VERSION / 100) % 100,
20701 (
unsigned)DUK_VERSION % 100);
20708#if defined(BUILD_DATE)
20709 const char *bd = BUILD_DATE;
20711#if defined(GCC_DIAGNOSTIC)
20712#if GCC_VERSION >= 40900
20713#pragma GCC diagnostic push
20717#pragma GCC diagnostic ignored "-Wdate-time"
20720 const char *bd = __DATE__;
20721#if defined(GCC_DIAGNOSTIC)
20722#if GCC_VERSION >= 40900
20723#pragma GCC diagnostic pop
20729 NULL, NULL, block,
sizeof(block),
",%s\"build\" : \"%s\"", eol, bd);
20738#if defined(_MSC_VER)
20743 ",%s\"compiler\" : \"MSC: %u (%u)\"",
20745 (
unsigned)_MSC_VER,
20746 (
unsigned)_MSC_FULL_VER);
20748#elif defined(__MINGW64__)
20753 ",%s\"compiler\" : \"MinGW64: %u.%u\"",
20755 (
unsigned)__MINGW64_VERSION_MAJOR,
20756 (
unsigned)__MINGW64_VERSION_MINOR);
20762 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20764 (
unsigned)__MINGW32_MAJOR_VERSION,
20765 (
unsigned)__MINGW32_MINOR_VERSION);
20767#elif defined(__MINGW32__)
20772 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20774 (
unsigned)__MINGW32_MAJOR_VERSION,
20775 (
unsigned)__MINGW32_MINOR_VERSION);
20777#elif defined(__clang__)
20782 ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
20786 __clang_patchlevel__,
20787 __clang_version__);
20789#elif defined(__GNUC__)
20794 ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
20796 (
unsigned)__GNUC__,
20797 (
unsigned)__GNUC_MINOR__,
20798 (
unsigned)__GNUC_PATCHLEVEL__);
20800#elif defined(__INTEL_COMPILER)
20805 ",%s\"compiler\" : \"Intel C/C++: %u\"",
20807 (
unsigned)__INTEL_COMPILER);
20809#elif defined(__BORLANDC__)
20814 ",%s\"compiler\" : \"Borland C: 0x%x\"",
20816 (
unsigned)__BORLANDC__);
20818#elif defined(__SUNPRO_C)
20823 ",%s\"compiler\" : \"Solaris: 0x%x\"",
20825 (
unsigned)__SUNPRO_C);
20832 ",%s\"compiler\" : \"other\"",
20845 ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
20847 "ptr:%u, size:%u, time:%u\"",
20849 (
unsigned)
sizeof(
short),
20850 (
unsigned)
sizeof(
int),
20851 (
unsigned)
sizeof(
long),
20852 (
unsigned)
sizeof(
long long),
20853 (
unsigned)
sizeof(
float),
20854 (
unsigned)
sizeof(
double),
20855 (
unsigned)
sizeof(
long double),
20856 (
unsigned)
sizeof(
char),
20857 (
unsigned)
sizeof(
wchar_t),
20858 (
unsigned)
sizeof(
void *),
20859 (
unsigned)
sizeof(
size_t),
20860 (
unsigned)
sizeof(time_t));
20865 if (append_eoobj) {
20866 strcat(append_eoobj, eoobj);
20868 system_info_length +=
sizeof(eoobj) - 1;
20870 return (
int)system_info_length;
20879#if defined(USE_SERVER_STATS)
20880 char *end, *append_eoobj = NULL, block[256];
20881 size_t context_info_length = 0;
20884 static const char eol[] =
"\r\n", eoobj[] =
"\r\n}\r\n";
20886 static const char eol[] =
"\n", eoobj[] =
"\n}\n";
20888 struct mg_memory_stat *ms = get_memory_stat((
struct mg_context *)ctx);
20890 if ((buffer == NULL) || (buflen < 1)) {
20895 end = buffer + buflen;
20897 if (buflen > (
int)(
sizeof(eoobj) - 1)) {
20899 append_eoobj = buffer;
20900 end -=
sizeof(eoobj) - 1;
20907 int blockCount = (
int)ms->blockCount;
20908 int64_t totalMemUsed = ms->totalMemUsed;
20909 int64_t maxMemUsed = ms->maxMemUsed;
20910 if (totalMemUsed > maxMemUsed) {
20911 maxMemUsed = totalMemUsed;
20918 "%s\"memory\" : {%s"
20919 "\"blocks\" : %i,%s"
20937 char start_time_str[64] = {0};
20938 char now_str[64] = {0};
20940 time_t now = time(NULL);
20941 int64_t total_data_read, total_data_written;
20942 int active_connections = (
int)ctx->active_connections;
20943 int max_active_connections = (
int)ctx->max_active_connections;
20944 int total_connections = (
int)ctx->total_connections;
20945 if (active_connections > max_active_connections) {
20946 max_active_connections = active_connections;
20948 if (active_connections > total_connections) {
20949 total_connections = active_connections;
20957 ",%s\"connections\" : {%s"
20958 "\"active\" : %i,%s"
20959 "\"maxActive\" : %i,%s"
20964 active_connections,
20966 max_active_connections,
20973#if !defined(ALTERNATIVE_QUEUE)
20978 ",%s\"queue\" : {%s"
20979 "\"length\" : %i,%s"
20980 "\"filled\" : %i,%s"
20981 "\"maxFilled\" : %i,%s"
21002 ",%s\"requests\" : {%s"
21003 "\"total\" : %lu%s"
21007 (
unsigned long)ctx->total_requests,
21013 mg_atomic_add64((
volatile int64_t *)&ctx->total_data_read, 0);
21014 total_data_written =
21015 mg_atomic_add64((
volatile int64_t *)&ctx->total_data_written, 0);
21020 ",%s\"data\" : {%s"
21028 total_data_written,
21034 sizeof(start_time_str) - 1,
21042 ",%s\"time\" : {%s"
21043 "\"uptime\" : %.0f,%s"
21044 "\"start\" : \"%s\",%s"
21045 "\"now\" : \"%s\"%s"
21049 difftime(now, start_time),
21059 if (append_eoobj) {
21060 strcat(append_eoobj, eoobj);
21062 context_info_length +=
sizeof(eoobj) - 1;
21064 return (
int)context_info_length;
21067 if ((buffer != NULL) && (buflen > 0)) {
21079 if (conn != NULL) {
21085#if defined(MG_EXPERIMENTAL_INTERFACES)
21089mg_get_connection_info(
const struct mg_context *ctx,
21096 char *end, *append_eoobj = NULL, block[256];
21097 size_t connection_info_length = 0;
21099 const char *state_str =
"unknown";
21102 static const char eol[] =
"\r\n", eoobj[] =
"\r\n}\r\n";
21104 static const char eol[] =
"\n", eoobj[] =
"\n}\n";
21107 if ((buffer == NULL) || (buflen < 1)) {
21112 end = buffer + buflen;
21114 if (buflen > (
int)(
sizeof(eoobj) - 1)) {
21116 append_eoobj = buffer;
21117 end -=
sizeof(eoobj) - 1;
21120 if ((ctx == NULL) || (idx < 0)) {
21135 connection_info_length +=
mg_str_append(&buffer, end,
"{");
21140#if defined(USE_SERVER_STATS)
21141 state = conn->conn_state;
21146 state_str =
"undefined";
21149 state_str =
"not used";
21152 state_str =
"init";
21155 state_str =
"ready";
21158 state_str =
"processing";
21161 state_str =
"processed";
21164 state_str =
"to close";
21167 state_str =
"closing";
21170 state_str =
"closed";
21173 state_str =
"done";
21179 if ((state >= 3) && (state < 9)) {
21184 "%s\"connection\" : {%s"
21186 "\"protocol\" : \"%s\",%s"
21187 "\"addr\" : \"%s\",%s"
21190 "\"handled_requests\" : %u%s"
21204 connection_info_length +=
mg_str_append(&buffer, end, block);
21208 if ((state >= 4) && (state < 6)) {
21213 "%s%s\"request_info\" : {%s"
21214 "\"method\" : \"%s\",%s"
21215 "\"uri\" : \"%s\",%s"
21216 "\"query\" : %s%s%s%s"
21218 (connection_info_length > 1 ?
"," :
""),
21229 connection_info_length +=
mg_str_append(&buffer, end, block);
21233 if ((state >= 2) && (state < 9)) {
21234 char start_time_str[64] = {0};
21235 char close_time_str[64] = {0};
21237 time_t close_time = 0;
21241 sizeof(start_time_str) - 1,
21243#if defined(USE_SERVER_STATS)
21244 close_time = conn->conn_close_time;
21246 if (close_time != 0) {
21247 time_diff = difftime(close_time, start_time);
21249 sizeof(close_time_str) - 1,
21252 time_t now = time(NULL);
21253 time_diff = difftime(now, start_time);
21254 close_time_str[0] = 0;
21261 "%s%s\"time\" : {%s"
21262 "\"uptime\" : %.0f,%s"
21263 "\"start\" : \"%s\",%s"
21264 "\"closed\" : \"%s\"%s"
21266 (connection_info_length > 1 ?
"," :
""),
21275 connection_info_length +=
mg_str_append(&buffer, end, block);
21284 "%s%s\"user\" : {%s"
21285 "\"name\" : \"%s\",%s"
21287 (connection_info_length > 1 ?
"," :
""),
21292 connection_info_length +=
mg_str_append(&buffer, end, block);
21301 "%s%s\"data\" : {%s"
21305 (connection_info_length > 1 ?
"," :
""),
21308 conn->consumed_content,
21310 conn->num_bytes_sent,
21312 connection_info_length +=
mg_str_append(&buffer, end, block);
21320 "%s%s\"state\" : \"%s\"",
21321 (connection_info_length > 1 ?
"," :
""),
21324 connection_info_length +=
mg_str_append(&buffer, end, block);
21327 if (append_eoobj) {
21328 strcat(append_eoobj, eoobj);
21330 connection_info_length +=
sizeof(eoobj) - 1;
21332 return (
int)connection_info_length;
21343 unsigned features_inited = features_to_init;
21356 int file_mutex_init = 1;
21359 int mutexattr_init = 1;
21364 if (key_create == 0) {
21368 if (file_mutex_init == 0) {
21371 failed = wsa = WSAStartup(MAKEWORD(2, 2), &
data);
21375 if (mutexattr_init == 0) {
21377 PTHREAD_MUTEX_RECURSIVE);
21386 (void)WSACleanup();
21388 if (file_mutex_init == 0) {
21389 (void)pthread_mutex_destroy(&global_log_file_lock);
21392 if (mutexattr_init == 0) {
21396 if (key_create == 0) {
21397 (void)pthread_key_delete(
sTlsKey);
21404#if defined(USE_LUA)
21405 lua_init_optional_libraries();
21411#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
21412 || defined(OPENSSL_API_3_0)) \
21413 && !defined(NO_SSL)
21415 if (!mg_openssl_initialized) {
21418 mg_openssl_initialized = 1;
21421 DEBUG_TRACE(
"Initializing SSL failed: %s", ebuf);
21438 return features_inited;
21454#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
21455 if (mg_openssl_initialized) {
21457 mg_openssl_initialized = 0;
21462 (void)WSACleanup();
21463 (void)pthread_mutex_destroy(&global_log_file_lock);
21468 (void)pthread_key_delete(
sTlsKey);
21470#if defined(USE_LUA)
21471 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)
@ CONNECTION_TYPE_RESPONSE
@ CONNECTION_TYPE_INVALID
@ CONNECTION_TYPE_REQUEST
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)
static const struct @145 abs_uri_protocols[]
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
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,...)
@ 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
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)
@ PROTOCOL_TYPE_WEBSOCKET
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)
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 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)
static const struct @144 builtin_mime_types[]
#define PASSWORDS_FILE_NAME
static void close_connection(struct mg_connection *conn)
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_FEATURES_X_DOMAIN_SOCKET
@ MG_FEATURES_COMPRESSION
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)
@ 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_WEBSOCKET_OPCODE_CONNECTION_CLOSE
@ MG_WEBSOCKET_OPCODE_PONG
@ MG_WEBSOCKET_OPCODE_PING
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
void init()
Inspect hardware capabilities, and load the optimal library for RooFit computations.
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 * 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