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,
2033#if !defined(NO_CACHING)
2061#if defined(__linux__)
2071#if defined(USE_WEBSOCKET)
2081#if defined(USE_HTTP2)
2095#if defined(USE_TIMERS)
2103#if defined(USE_TIMERS)
2107#if defined(USE_4_CGI)
2112#if defined(USE_TIMERS)
2120#if defined(USE_TIMERS)
2135 "index.xhtml,index.html,index.htm,"
2136 "index.lp,index.lsp,index.lua,index.cgi,"
2137 "index.shtml,index.php"},
2139 "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
2167#if defined(MG_EXPERIMENTAL_INTERFACES)
2171#if defined(USE_DUKTAPE)
2177#if defined(USE_WEBSOCKET)
2180#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2188#if !defined(NO_CACHING)
2205 "config_options and enum not sync");
2262#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2264 struct mg_shared_lua_websocket_list *shared_lua_websockets;
2275#if defined(STOP_FLAG_NEEDS_LOCK)
2298 sf = mg_atomic_compare_and_swap(
f, *
f,
v);
2305#define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
2306#define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
2307#define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
2330#if defined(USE_SERVER_STATS)
2331 volatile ptrdiff_t active_connections;
2332 volatile ptrdiff_t max_active_connections;
2333 volatile ptrdiff_t total_connections;
2334 volatile ptrdiff_t total_requests;
2335 volatile int64_t total_data_read;
2336 volatile int64_t total_data_written;
2350#if defined(ALTERNATIVE_QUEUE)
2351 struct socket *client_socks;
2352 void **client_wait_events;
2362#if defined(USE_SERVER_STATS)
2370#if defined(USE_SERVER_STATS)
2371 struct mg_memory_stat ctx_memory;
2379#if defined(USE_TIMERS)
2380 struct ttimers *timers;
2385 void *lua_background_state;
2386 pthread_mutex_t lua_bg_mutex;
2387 int lua_bg_log_available;
2410#if defined(USE_SERVER_STATS)
2411static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2413static struct mg_memory_stat *
2417 return &(ctx->ctx_memory);
2419 return &mg_common_memory;
2436#if defined(USE_HTTP2)
2437#if !defined(HTTP2_DYN_TABLE_SIZE)
2438#define HTTP2_DYN_TABLE_SIZE (256)
2441struct mg_http2_connection {
2443 uint32_t dyn_table_size;
2444 struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
2454#if defined(USE_HTTP2)
2455 struct mg_http2_connection http2;
2464#if defined(USE_SERVER_STATS)
2474#if defined(USE_SERVER_STATS)
2475 time_t conn_close_time;
2477 double processing_time;
2503#if defined(USE_WEBSOCKET)
2504 int in_websocket_handling;
2506#if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
2507 && defined(MG_EXPERIMENTAL_INTERFACES)
2509 int websocket_deflate_server_max_windows_bits;
2510 int websocket_deflate_client_max_windows_bits;
2511 int websocket_deflate_server_no_context_takeover;
2512 int websocket_deflate_client_no_context_takeover;
2513 int websocket_deflate_initialized;
2514 int websocket_deflate_flush;
2515 z_stream websocket_deflate_state;
2516 z_stream websocket_inflate_state;
2531#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2532 void *lua_websocket_state;
2548#define mg_cry_internal(conn, fmt, ...) \
2549 mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
2551#define mg_cry_ctx_internal(ctx, fmt, ...) \
2552 mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
2562#if !defined(NO_THREAD_NAME)
2563#if defined(_WIN32) && defined(_MSC_VER)
2567#pragma pack(push, 8)
2568typedef struct tagTHREADNAME_INFO {
2576#elif defined(__linux__)
2578#include <sys/prctl.h>
2579#include <sys/sendfile.h>
2580#if defined(ALTERNATIVE_QUEUE)
2581#include <sys/eventfd.h>
2585#if defined(ALTERNATIVE_QUEUE)
2590 int evhdl = eventfd(0, EFD_CLOEXEC);
2611event_wait(
void *eventhdl)
2620 evhdl = *(
int *)eventhdl;
2622 s = (
int)read(evhdl, &u,
sizeof(u));
2623 if (s !=
sizeof(u)) {
2633event_signal(
void *eventhdl)
2642 evhdl = *(
int *)eventhdl;
2644 s = (
int)write(evhdl, &u,
sizeof(u));
2645 if (s !=
sizeof(u)) {
2654event_destroy(
void *eventhdl)
2662 evhdl = *(
int *)eventhdl;
2674#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2677 pthread_mutex_t mutex;
2686 struct posix_event *ret =
mg_malloc(
sizeof(
struct posix_event));
2691 if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2696 if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2698 pthread_mutex_destroy(&(ret->mutex));
2708event_wait(
void *eventhdl)
2710 struct posix_event *ev = (
struct posix_event *)eventhdl;
2711 pthread_mutex_lock(&(ev->mutex));
2712 while (!ev->signaled) {
2713 pthread_cond_wait(&(ev->cond), &(ev->mutex));
2716 pthread_mutex_unlock(&(ev->mutex));
2722event_signal(
void *eventhdl)
2724 struct posix_event *ev = (
struct posix_event *)eventhdl;
2725 pthread_mutex_lock(&(ev->mutex));
2726 pthread_cond_signal(&(ev->cond));
2728 pthread_mutex_unlock(&(ev->mutex));
2734event_destroy(
void *eventhdl)
2736 struct posix_event *ev = (
struct posix_event *)eventhdl;
2737 pthread_cond_destroy(&(ev->cond));
2738 pthread_mutex_destroy(&(ev->mutex));
2747 char threadName[16 + 1];
2750 NULL, NULL, threadName,
sizeof(threadName),
"civetweb-%s",
name);
2753#if defined(_MSC_VER)
2756 THREADNAME_INFO info;
2757 info.dwType = 0x1000;
2758 info.szName = threadName;
2759 info.dwThreadID = ~0U;
2762 RaiseException(0x406D1388,
2764 sizeof(info) /
sizeof(ULONG_PTR),
2765 (ULONG_PTR *)&info);
2766 } __except (EXCEPTION_EXECUTE_HANDLER) {
2768#elif defined(__MINGW32__)
2771#elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
2772 && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
2774#if defined(__MACH__)
2776 (void)pthread_setname_np(threadName);
2778 (void)pthread_setname_np(pthread_self(), threadName);
2780#elif defined(__linux__)
2786 (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
2805#define MG_FOPEN_MODE_NONE (0)
2808#define MG_FOPEN_MODE_READ (1)
2811#define MG_FOPEN_MODE_WRITE (2)
2814#define MG_FOPEN_MODE_APPEND (4)
2824 return (fileacc->
fp != NULL);
2828#if !defined(NO_FILESYSTEMS)
2838 const uint8_t *
c = (
const uint8_t *)path;
2841 if ((
c == NULL) || (
c[0] == 0)) {
2852 if ((*
c ==
'>') || (*
c ==
'<') || (*
c ==
'|')) {
2856 if ((*
c ==
'*') || (*
c ==
'?')) {
2907 wchar_t wbuf[UTF16_PATH_MAX];
2908 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
2911 filep->
access.
fp = _wfopen(wbuf, L
"rb");
2914 filep->
access.
fp = _wfopen(wbuf, L
"wb");
2917 filep->
access.
fp = _wfopen(wbuf, L
"ab");
2925 filep->
access.
fp = fopen(path,
"r");
2928 filep->
access.
fp = fopen(path,
"w");
2931 filep->
access.
fp = fopen(path,
"a");
2954 if (fileacc != NULL) {
2955 if (fileacc->
fp != NULL) {
2956 ret = fclose(fileacc->
fp);
2959 memset(fileacc, 0,
sizeof(*fileacc));
2969 for (; *
src !=
'\0' &&
n > 1;
n--) {
2979 return tolower((
unsigned char)*s);
2991 }
while (diff == 0 &&
s1[-1] !=
'\0' && --
len > 0);
3005 }
while (diff == 0 &&
s1[-1] !=
'\0');
3042 size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3044 if (big_len >= small_len) {
3045 for (i = 0; i <= (big_len - small_len); i++) {
3075#if defined(__clang__)
3076#pragma clang diagnostic push
3077#pragma clang diagnostic ignored "-Wformat-nonliteral"
3083 ok = (
n >= 0) && ((
size_t)
n < buflen);
3085#if defined(__clang__)
3086#pragma clang diagnostic pop
3098 "truncating vsnprintf buffer: [%.*s]",
3099 (
int)((buflen > 200) ? 200 : (buflen - 1)),
3101 n = (
int)buflen - 1;
3143 }
else if (!ctx || ctx->
dd.
config[i] == NULL) {
3150#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3162 return (ctx == NULL) ? NULL : ctx->
user_data;
3192 if (const_conn != NULL) {
3222 memset(ports, 0,
sizeof(*ports) * (
size_t)
size);
3252#if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
3253#define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
3265 if (
usa->
sa.sa_family == AF_INET) {
3266 getnameinfo(&
usa->
sa,
3274#if defined(USE_IPV6)
3275 else if (
usa->
sa.sa_family == AF_INET6) {
3276 getnameinfo(&
usa->
sa,
3285#if defined(USE_X_DOM_SOCKET)
3286 else if (
usa->
sa.sa_family == AF_UNIX) {
3297 strncpy(
buf, UNIX_DOMAIN_SOCKET_SERVER_NAME,
len);
3309#if !defined(REENTRANT_TIME)
3312 tm = ((t != NULL) ? gmtime(t) : NULL);
3316 struct tm *tm = &_tm;
3321 strftime(buf, buf_len,
"%a, %d %b %Y %H:%M:%S GMT", tm);
3323 mg_strlcpy(buf,
"Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3324 buf[buf_len - 1] =
'\0';
3333 return (
double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3334 + (
double)(ts_now->tv_sec - ts_before->tv_sec);
3338#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3344#include "external_mg_cry_internal_impl.inl"
3345#elif !defined(NO_FILESYSTEMS)
3363#if defined(GCC_DIAGNOSTIC)
3364#pragma GCC diagnostic push
3365#pragma GCC diagnostic ignored "-Wformat-nonliteral"
3370#if defined(GCC_DIAGNOSTIC)
3371#pragma GCC diagnostic pop
3374 buf[
sizeof(buf) - 1] = 0;
3403 timestamp = time(NULL);
3407 "[%010lu] [error] [client %s] ",
3408 (
unsigned long)timestamp,
3430#error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
3477#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3493#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3500 if (strlen(txt) == 3) {
3501 memcpy(tls->txtbuf, txt, 4);
3503 strcpy(tls->txtbuf,
"ERR");
3508 ((
struct mg_connection *)conn)->request_info.local_uri_raw =
3543#if defined(__clang__)
3544#pragma clang diagnostic push
3545#pragma clang diagnostic ignored "-Wunreachable-code"
3556 ? (ri->
is_ssl ?
"wss" :
"ws")
3557 : (ri->
is_ssl ?
"https" :
"http"));
3561#if defined(__clang__)
3562#pragma clang diagnostic pop
3571 const char *define_proto,
3573 const char *define_uri)
3575 if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3584 (define_uri != NULL)
3587 int port = (define_port > 0) ? define_port : ri->
server_port;
3594#if defined(USE_X_DOM_SOCKET)
3605 const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
3621 if ((0 == strcmp(define_proto,
"https"))
3622 || (0 == strcmp(define_proto,
"wss"))) {
3632#if defined(USE_IPV6)
3633 int is_ipv6 = (conn->
client.
lsa.
sa.sa_family == AF_INET6);
3635 int auth_domain_check_enabled =
3640 const char *server_domain =
3647 sprintf(portstr,
":%u", (
unsigned)port);
3652 if (!auth_domain_check_enabled || !server_domain) {
3658 server_domain = server_ip;
3665#
if defined(USE_IPV6)
3668 (is_ipv6 && (server_domain == server_ip)) ?
"[" :
"",
3670 (is_ipv6 && (server_domain == server_ip)) ?
"]" :
"",
3702 const char *delimiters,
3703 const char *whitespace,
3706 char *
p, *begin_word, *end_word, *end_whitespace;
3709 end_word = begin_word + strcspn(begin_word, delimiters);
3712 if (end_word > begin_word) {
3714 while (*
p == quotechar) {
3721 if (*end_word !=
'\0') {
3722 size_t end_off = strcspn(end_word + 1, delimiters);
3723 memmove(
p, end_word, end_off + 1);
3725 end_word += end_off + 1;
3731 for (
p++;
p < end_word;
p++) {
3736 if (*end_word ==
'\0') {
3740#if defined(GCC_DIAGNOSTIC)
3742#pragma GCC diagnostic push
3743#pragma GCC diagnostic ignored "-Wsign-conversion"
3746 end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
3748#if defined(GCC_DIAGNOSTIC)
3749#pragma GCC diagnostic pop
3752 for (
p = end_word;
p < end_whitespace;
p++) {
3756 *buf = end_whitespace;
3768 for (i = 0; i < num_hdr; i++) {
3770 return hdr[i].
value;
3778#if defined(USE_WEBSOCKET)
3785 int output_max_size)
3851 if (val == NULL || list == NULL || *list ==
'\0') {
3857 while (*list ==
' ' || *list ==
'\t')
3861 if ((list = strchr(val->
ptr,
',')) != NULL) {
3863 val->
len = ((size_t)(list - val->
ptr));
3867 list = val->
ptr + strlen(val->
ptr);
3868 val->
len = ((size_t)(list - val->
ptr));
3873 while (end >= 0 && ((val->
ptr[end] ==
' ') || (val->
ptr[end] ==
'\t')))
3875 val->
len = (size_t)(end) + (size_t)(1);
3877 if (val->
len == 0) {
3882 if (eq_val != NULL) {
3886 eq_val->
ptr = (
const char *)memchr(val->
ptr,
'=', val->
len);
3887 if (eq_val->
ptr != NULL) {
3889 eq_val->
len = ((size_t)(val->
ptr - eq_val->
ptr)) + val->
len;
3890 val->
len = ((size_t)(eq_val->
ptr - val->
ptr)) - 1;
3911 while ((header =
next_option(header, &opt_vec, &eq_vec)) != NULL) {
3925 ptrdiff_t i, j,
len, res;
3927 if ((or_str = (
const char *)memchr(pattern,
'|', pattern_len)) != NULL) {
3928 res =
match_prefix(pattern, (
size_t)(or_str - pattern), str);
3929 return (res > 0) ? res
3931 (
size_t)((pattern + pattern_len)
3936 for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
3937 if ((pattern[i] ==
'?') && (str[j] !=
'\0')) {
3939 }
else if (pattern[i] ==
'$') {
3940 return (str[j] ==
'\0') ? j : -1;
3941 }
else if (pattern[i] ==
'*') {
3943 if (pattern[i] ==
'*') {
3945 len = (ptrdiff_t)strlen(str + j);
3947 len = (ptrdiff_t)strcspn(str + j,
"/");
3949 if (i == (ptrdiff_t)pattern_len) {
3954 (pattern_len - (
size_t)i),
3956 }
while (res == -1 &&
len-- > 0);
3957 return (res == -1) ? -1 : j + res +
len;
3962 return (ptrdiff_t)j;
3969 if (pattern == NULL) {
3982 const char *http_version;
4008 if (http_version && (0 == strcmp(http_version,
"1.1"))) {
4021 if (!conn || !conn->
dom_ctx) {
4032 if (!conn || !conn->
dom_ctx) {
4057 "no-cache, no-store, "
4058 "must-revalidate, private, max-age=0",
4072#if !defined(NO_CACHING)
4076 const char *cache_control =
4080 if (cache_control != NULL) {
4107 conn, NULL, val,
sizeof(val),
"max-age=%lu", (
unsigned long)max_age);
4132 (
unsigned long)max_age);
4138 if (header && header[0]) {
4144#if !defined(NO_FILESYSTEMS)
4158 switch (response_code) {
4163 return "Switching Protocols";
4165 return "Processing";
4175 return "Non-Authoritative Information";
4177 return "No Content";
4179 return "Reset Content";
4181 return "Partial Content";
4183 return "Multi-Status";
4186 return "Already Reported";
4193 return "Multiple Choices";
4195 return "Moved Permanently";
4201 return "Not Modified";
4205 return "Temporary Redirect";
4207 return "Permanent Redirect";
4211 return "Bad Request";
4213 return "Unauthorized";
4215 return "Payment Required";
4221 return "Method Not Allowed";
4223 return "Not Acceptable";
4225 return "Proxy Authentication Required";
4227 return "Request Time-out";
4233 return "Length Required";
4235 return "Precondition Failed";
4237 return "Request Entity Too Large";
4239 return "Request-URI Too Large";
4241 return "Unsupported Media Type";
4243 return "Requested range not satisfiable";
4246 return "Expectation Failed";
4249 return "Misdirected Request";
4251 return "Unproccessable entity";
4256 return "Failed Dependency";
4260 return "Upgrade Required";
4263 return "Precondition Required";
4265 return "Too Many Requests";
4268 return "Request Header Fields Too Large";
4271 return "Unavailable For Legal Reasons";
4276 return "Internal Server Error";
4278 return "Not Implemented";
4280 return "Bad Gateway";
4282 return "Service Unavailable";
4284 return "Gateway Time-out";
4286 return "HTTP Version not supported";
4288 return "Variant Also Negotiates";
4290 return "Insufficient Storage";
4293 return "Loop Detected";
4296 return "Not Extended";
4298 return "Network Authentication Required";
4304 return "I am a teapot";
4306 return "Authentication Timeout";
4308 return "Enhance Your Calm";
4310 return "Login Timeout";
4312 return "Bandwidth Limit Exceeded";
4318 "Unknown HTTP response code: %u",
4323 if (response_code >= 100 && response_code < 200) {
4325 return "Information";
4327 if (response_code >= 200 && response_code < 300) {
4331 if (response_code >= 300 && response_code < 400) {
4333 return "Redirection";
4335 if (response_code >= 400 && response_code < 500) {
4337 return "Client Error";
4339 if (response_code >= 500 && response_code < 600) {
4341 return "Server Error";
4360#if !defined(NO_FILESYSTEMS)
4362 int len, i, page_handler_found, scope, truncated;
4363 const char *error_handler = NULL;
4365 const char *error_page_file_ext, *tstr;
4367 int handled_by_callback = 0;
4369 if ((conn == NULL) || (fmt == NULL)) {
4377 has_body = ((status > 199) && (status != 204) && (status != 304));
4385 mg_vsnprintf(conn, NULL, errmsg_buf,
sizeof(errmsg_buf), fmt, ap);
4388 DEBUG_TRACE(
"Error %i - [%s]", status, errmsg_buf);
4398 handled_by_callback =
4404 if (!handled_by_callback) {
4408 "Recursion when handling error %u - fall back to default",
4410#if !defined(NO_FILESYSTEMS)
4415 page_handler_found = 0;
4417 if (error_handler != NULL) {
4418 for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4424 sizeof(path_buf) - 32,
4435 sizeof(path_buf) - 32,
4444 sizeof(path_buf) - 32,
4459 path_buf[
sizeof(path_buf) - 32] = 0;
4460 len = (
int)strlen(path_buf);
4461 if (
len > (
int)
sizeof(path_buf) - 32) {
4462 len = (
int)
sizeof(path_buf) - 32;
4466 tstr = strchr(error_page_file_ext,
'.');
4470 (i < 32) && (tstr[i] != 0) && (tstr[i] !=
',');
4475 path_buf[
len + i - 1] = tstr[i];
4480 path_buf[
len + i - 1] = 0;
4482 if (
mg_stat(conn, path_buf, &error_page_file.
stat)) {
4485 page_handler_found = 1;
4493 tstr = strchr(tstr + i,
'.');
4498 if (page_handler_found) {
4515 "text/plain; charset=utf-8",
4524 mg_printf(conn,
"Error %d: %s\n", status, status_text);
4525 mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4553 long long content_length)
4564 if (content_length < 0) {
4578 (uint64_t)content_length);
4593 const char *target_url,
4607 const char *redirect_text;
4609 size_t content_len = 0;
4610#if defined(MG_SEND_REDIRECT_BODY)
4615 if (redirect_code == 0) {
4616 redirect_code = 307;
4620 if ((redirect_code != 301) && (redirect_code != 302)
4621 && (redirect_code != 303) && (redirect_code != 307)
4622 && (redirect_code != 308)) {
4631 if ((target_url == NULL) || (*target_url == 0)) {
4635#if defined(MG_SEND_REDIRECT_BODY)
4663 "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4667 content_len = strlen(reply);
4673 "HTTP/1.1 %i %s\r\n"
4675 "Content-Length: %u\r\n"
4676 "Connection: %s\r\n\r\n",
4680 (
unsigned int)content_len,
4683#if defined(MG_SEND_REDIRECT_BODY)
4688 ret =
mg_write(conn, reply, content_len);
4693 return (ret > 0) ? ret : -1;
4700#if defined(GCC_DIAGNOSTIC)
4702#pragma GCC diagnostic push
4703#pragma GCC diagnostic ignored "-Wunused-function"
4708pthread_mutex_init(pthread_mutex_t *mutex,
void *unused)
4712 InitializeCriticalSection(&mutex->sec);
4718pthread_mutex_destroy(pthread_mutex_t *mutex)
4720 DeleteCriticalSection(&mutex->sec);
4726pthread_mutex_lock(pthread_mutex_t *mutex)
4728 EnterCriticalSection(&mutex->sec);
4734pthread_mutex_unlock(pthread_mutex_t *mutex)
4736 LeaveCriticalSection(&mutex->sec);
4747 cv->waiting_thread = NULL;
4755 pthread_mutex_t *mutex,
4761 uint64_t nsnow, nswaitabs;
4765 pthread_mutex_lock(&cv->threadIdSec);
4767 ptls = &cv->waiting_thread;
4768 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
4770 tls->next_waiting_thread = NULL;
4772 pthread_mutex_unlock(&cv->threadIdSec);
4777 (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
4778 nswaitrel = nswaitabs - nsnow;
4779 if (nswaitrel < 0) {
4782 mswaitrel = (DWORD)(nswaitrel / 1000000);
4784 mswaitrel = (DWORD)INFINITE;
4787 pthread_mutex_unlock(mutex);
4789 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
4792 pthread_mutex_lock(&cv->threadIdSec);
4793 ptls = &cv->waiting_thread;
4794 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
4796 *ptls = tls->next_waiting_thread;
4801 pthread_mutex_unlock(&cv->threadIdSec);
4803 WaitForSingleObject(tls->pthread_cond_helper_mutex,
4808 pthread_mutex_lock(mutex);
4818 return pthread_cond_timedwait(cv, mutex, NULL);
4829 pthread_mutex_lock(&cv->threadIdSec);
4830 if (cv->waiting_thread) {
4831 wkup = cv->waiting_thread->pthread_cond_helper_mutex;
4832 cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
4834 ok = SetEvent(wkup);
4837 pthread_mutex_unlock(&cv->threadIdSec);
4847 pthread_mutex_lock(&cv->threadIdSec);
4848 while (cv->waiting_thread) {
4849 pthread_cond_signal(cv);
4851 pthread_mutex_unlock(&cv->threadIdSec);
4861 pthread_mutex_lock(&cv->threadIdSec);
4863 pthread_mutex_unlock(&cv->threadIdSec);
4864 pthread_mutex_destroy(&cv->threadIdSec);
4870#if defined(ALTERNATIVE_QUEUE)
4875 return (
void *)CreateEvent(NULL,
FALSE,
FALSE, NULL);
4881event_wait(
void *eventhdl)
4883 int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
4884 return (res == WAIT_OBJECT_0);
4890event_signal(
void *eventhdl)
4892 return (
int)SetEvent((HANDLE)eventhdl);
4898event_destroy(
void *eventhdl)
4900 CloseHandle((HANDLE)eventhdl);
4905#if defined(GCC_DIAGNOSTIC)
4907#pragma GCC diagnostic pop
4913change_slashes_to_backslashes(
char *path)
4917 for (i = 0; path[i] !=
'\0'; i++) {
4918 if (path[i] ==
'/') {
4924 if ((i > 0) && (path[i] ==
'\\')) {
4925 while ((path[i + 1] ==
'\\') || (path[i + 1] ==
'/')) {
4926 (
void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
4934mg_wcscasecmp(
const wchar_t *
s1,
const wchar_t *s2)
4939 diff = ((*
s1 >=
L'A') && (*
s1 <= L
'Z') ? (*
s1 -
L'A' +
L'a') : *
s1)
4940 - ((*s2 >=
L'A') && (*s2 <=
L'Z') ? (*s2 -
L'A' +
L'a') : *s2);
4943 }
while ((diff == 0) && (
s1[-1] != L
'\0'));
4958 wchar_t wbuf2[UTF16_PATH_MAX + 1];
4959 DWORD long_len, err;
4960 int (*fcompare)(
const wchar_t *,
const wchar_t *) = mg_wcscasecmp;
4963 change_slashes_to_backslashes(buf);
4967 memset(wbuf, 0, wbuf_len *
sizeof(
wchar_t));
4968 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (
int)wbuf_len);
4969 WideCharToMultiByte(
4970 CP_UTF8, 0, wbuf, (
int)wbuf_len, buf2,
sizeof(buf2), NULL, NULL);
4971 if (strcmp(buf, buf2) != 0) {
4995 memset(wbuf2, 0,
ARRAY_SIZE(wbuf2) *
sizeof(
wchar_t));
4996 long_len = GetLongPathNameW(wbuf, wbuf2,
ARRAY_SIZE(wbuf2) - 1);
4997 if (long_len == 0) {
4998 err = GetLastError();
4999 if (err == ERROR_FILE_NOT_FOUND) {
5004 if ((long_len >=
ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5011#if !defined(NO_FILESYSTEMS)
5018 wchar_t wbuf[UTF16_PATH_MAX];
5019 WIN32_FILE_ATTRIBUTE_DATA info;
5020 time_t creation_time;
5026 memset(filep, 0,
sizeof(*filep));
5032 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5037 if ((
len > 0) && (path[
len - 1] !=
' ') && (path[
len - 1] !=
'.')
5038 && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
5039 filep->
size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5041 SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5042 info.ftLastWriteTime.dwHighDateTime);
5048 creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5049 info.ftCreationTime.dwHighDateTime);
5054 filep->
is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5066 wchar_t wbuf[UTF16_PATH_MAX];
5067 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5068 return DeleteFileW(wbuf) ? 0 : -1;
5075 wchar_t wbuf[UTF16_PATH_MAX];
5077 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5078 return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5084#if defined(GCC_DIAGNOSTIC)
5086#pragma GCC diagnostic push
5087#pragma GCC diagnostic ignored "-Wunused-function"
5097 wchar_t wpath[UTF16_PATH_MAX];
5101 SetLastError(ERROR_BAD_ARGUMENTS);
5102 }
else if ((dir = (DIR *)
mg_malloc(
sizeof(*dir))) == NULL) {
5103 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5106 attrs = GetFileAttributesW(wpath);
5107 if ((wcslen(wpath) + 2 <
ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5108 && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5109 (
void)wcscat(wpath, L
"\\*");
5110 dir->handle = FindFirstFileW(wpath, &dir->info);
5111 dir->result.d_name[0] =
'\0';
5130 result = FindClose(dir->handle) ? 0 : -1;
5135 SetLastError(ERROR_BAD_ARGUMENTS);
5143static struct dirent *
5146 struct dirent *
result = 0;
5151 (
void)WideCharToMultiByte(CP_UTF8,
5153 dir->info.cFileName,
5160 if (!FindNextFileW(dir->handle, &dir->info)) {
5161 (
void)FindClose(dir->handle);
5166 SetLastError(ERROR_FILE_NOT_FOUND);
5169 SetLastError(ERROR_BAD_ARGUMENTS);
5176#if !defined(HAVE_POLL)
5188poll(
struct mg_pollfd *pfd,
unsigned int n,
int milliseconds)
5198 memset(&tv, 0,
sizeof(tv));
5199 tv.tv_sec = milliseconds / 1000;
5200 tv.tv_usec = (milliseconds % 1000) * 1000;
5205 for (i = 0; i <
n; i++) {
5206 if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
5207 if (pfd[i].events & POLLIN) {
5208 FD_SET(pfd[i].fd, &rset);
5210 if (pfd[i].events & POLLOUT) {
5211 FD_SET(pfd[i].fd, &wset);
5214 FD_SET(pfd[i].fd, &eset);
5218 if (pfd[i].fd > maxfd) {
5223 if ((
result = select((
int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
5224 for (i = 0; i <
n; i++) {
5225 if (FD_ISSET(pfd[i].fd, &rset)) {
5226 pfd[i].revents |= POLLIN;
5228 if (FD_ISSET(pfd[i].fd, &wset)) {
5229 pfd[i].revents |= POLLOUT;
5231 if (FD_ISSET(pfd[i].fd, &eset)) {
5232 pfd[i].revents |= POLLERR;
5249#if defined(GCC_DIAGNOSTIC)
5251#pragma GCC diagnostic pop
5263 (
void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5270#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5274 return ((_beginthread((
void(__cdecl *)(
void *))
f, USE_STACK_SIZE,
p)
5275 == ((uintptr_t)(-1L)))
5280 (_beginthread((
void(__cdecl *)(
void *))
f, 0,
p) == ((uintptr_t)(-1L)))
5291 pthread_t *threadidptr)
5294 HANDLE threadhandle;
5297 uip = _beginthreadex(NULL, 0,
f,
p, 0, NULL);
5298 threadhandle = (HANDLE)uip;
5299 if ((uip != 0) && (threadidptr != NULL)) {
5300 *threadidptr = threadhandle;
5316 dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5317 if (dwevent == WAIT_FAILED) {
5320 if (dwevent == WAIT_OBJECT_0) {
5321 CloseHandle(threadid);
5329#if !defined(NO_SSL_DL) && !defined(NO_SSL)
5333#if defined(GCC_DIAGNOSTIC)
5335#pragma GCC diagnostic push
5336#pragma GCC diagnostic ignored "-Wunused-function"
5342dlopen(
const char *dll_name,
int flags)
5344 wchar_t wbuf[UTF16_PATH_MAX];
5346 path_to_unicode(NULL, dll_name, wbuf,
ARRAY_SIZE(wbuf));
5347 return LoadLibraryW(wbuf);
5353dlclose(
void *handle)
5357 if (FreeLibrary((HMODULE)handle) != 0) {
5367#if defined(GCC_DIAGNOSTIC)
5369#pragma GCC diagnostic pop
5380kill(pid_t pid,
int sig_num)
5382 (
void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5383 (
void)CloseHandle((HANDLE)pid);
5388#if !defined(WNOHANG)
5394waitpid(pid_t pid,
int *status,
int flags)
5396 DWORD timeout = INFINITE;
5401 if ((flags | WNOHANG) == WNOHANG) {
5405 waitres = WaitForSingleObject((HANDLE)pid, timeout);
5406 if (waitres == WAIT_OBJECT_0) {
5409 if (waitres == WAIT_TIMEOUT) {
5417trim_trailing_whitespaces(
char *s)
5419 char *
e = s + strlen(s);
5420 while ((
e > s) && isspace((
unsigned char)
e[-1])) {
5435 unsigned char cgi_config_idx)
5439 char *interp_arg = 0;
5444 PROCESS_INFORMATION pi = {0};
5448 memset(&si, 0,
sizeof(si));
5451 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5452 si.wShowWindow = SW_HIDE;
5454 me = GetCurrentProcess();
5456 (HANDLE)_get_osfhandle(fdin[0]),
5461 DUPLICATE_SAME_ACCESS);
5463 (HANDLE)_get_osfhandle(fdout[1]),
5468 DUPLICATE_SAME_ACCESS);
5470 (HANDLE)_get_osfhandle(fderr[1]),
5475 DUPLICATE_SAME_ACCESS);
5480 SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5481 HANDLE_FLAG_INHERIT,
5483 SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5484 HANDLE_FLAG_INHERIT,
5486 SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5487 HANDLE_FLAG_INHERIT,
5493 if (interp != NULL) {
5501 buf[0] = buf[1] =
'\0';
5505 conn, &truncated, cmdline,
sizeof(cmdline),
"%s/%s", dir, prog);
5508 pi.hProcess = (pid_t)-1;
5518 buf[
sizeof(buf) - 1] =
'\0';
5521 if ((buf[0] ==
'#') && (buf[1] ==
'!')) {
5522 trim_trailing_whitespaces(buf + 2);
5529 GetFullPathNameA(dir,
sizeof(full_dir), full_dir, NULL);
5531 if (interp[0] !=
'\0') {
5533 if ((interp_arg != 0) && (interp_arg[0] != 0)) {
5538 "\"%s\" %s \"%s\\%s\"",
5548 "\"%s\" \"%s\\%s\"",
5565 pi.hProcess = (pid_t)-1;
5570 if (CreateProcessA(NULL,
5575 CREATE_NEW_PROCESS_GROUP,
5582 conn,
"%s: CreateProcess(%s): %ld", __func__, cmdline, (
long)
ERRNO);
5583 pi.hProcess = (pid_t)-1;
5588 (
void)CloseHandle(si.hStdOutput);
5589 (
void)CloseHandle(si.hStdError);
5590 (
void)CloseHandle(si.hStdInput);
5591 if (pi.hThread != NULL) {
5592 (
void)CloseHandle(pi.hThread);
5595 return (pid_t)pi.hProcess;
5603 unsigned long non_blocking = 0;
5604 return ioctlsocket(sock, (
long)FIONBIO, &non_blocking);
5611 unsigned long non_blocking = 1;
5612 return ioctlsocket(sock, (
long)FIONBIO, &non_blocking);
5619#if !defined(NO_FILESYSTEMS)
5629 memset(filep, 0,
sizeof(*filep));
5635 if (0 == stat(path, &st)) {
5636 filep->
size = (uint64_t)(st.st_size);
5652#if defined(__ZEPHYR__)
5657 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5661 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5673 pthread_t thread_id;
5674 pthread_attr_t
attr;
5677 (void)pthread_attr_init(&
attr);
5678 (void)pthread_attr_setdetachstate(&
attr, PTHREAD_CREATE_DETACHED);
5680#if defined(__ZEPHYR__)
5681 pthread_attr_setstack(&
attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
5682#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5685 (void)pthread_attr_setstacksize(&
attr, USE_STACK_SIZE);
5688 result = pthread_create(&thread_id, &
attr, func, param);
5689 pthread_attr_destroy(&
attr);
5699 pthread_t *threadidptr)
5701 pthread_t thread_id;
5702 pthread_attr_t
attr;
5705 (void)pthread_attr_init(&
attr);
5707#if defined(__ZEPHYR__)
5708 pthread_attr_setstack(&
attr,
5709 &civetweb_worker_stacks[zephyr_worker_stack_index++],
5711#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5714 (void)pthread_attr_setstacksize(&
attr, USE_STACK_SIZE);
5717 result = pthread_create(&thread_id, &
attr, func, param);
5718 pthread_attr_destroy(&
attr);
5719 if ((
result == 0) && (threadidptr != NULL)) {
5720 *threadidptr = thread_id;
5732 result = pthread_join(threadid, NULL);
5747 unsigned char cgi_config_idx)
5754 if ((pid = fork()) == -1) {
5757 }
else if (pid != 0) {
5765 if (chdir(dir) != 0) {
5767 conn,
"%s: chdir(%s): %s", __func__, dir, strerror(
ERRNO));
5768 }
else if (dup2(fdin[0], 0) == -1) {
5770 "%s: dup2(%d, 0): %s",
5774 }
else if (dup2(fdout[1], 1) == -1) {
5776 "%s: dup2(%d, 1): %s",
5780 }
else if (dup2(fderr[1], 2) == -1) {
5782 "%s: dup2(%d, 2): %s",
5787 struct sigaction sa;
5792 (void)close(fdin[0]);
5793 (void)close(fdout[1]);
5794 (void)close(fderr[1]);
5797 (void)close(fdin[1]);
5798 (void)close(fdout[0]);
5799 (void)close(fderr[0]);
5806 memset(&sa, 0,
sizeof(sa));
5807 sa.sa_handler = SIG_DFL;
5808 sigaction(SIGCHLD, &sa, NULL);
5811 if (interp == NULL) {
5813 (void)execle(prog, prog, NULL, envp);
5815 "%s: execle(%s): %s",
5821 const char *interp_args =
5825 if ((interp_args != NULL) && (interp_args[0] != 0)) {
5826 (void)execle(interp, interp, interp_args, prog, NULL, envp);
5828 (void)execle(interp, interp, prog, NULL, envp);
5831 "%s: execle(%s %s): %s",
5849 int flags = fcntl(sock, F_GETFL, 0);
5854 if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
5863 int flags = fcntl(sock, F_GETFL, 0);
5868 if (fcntl(sock, F_SETFL, flags & (~(
int)(O_NONBLOCK))) < 0) {
5882 static uint64_t lfsr = 0;
5883 static uint64_t lcg = 0;
5894 | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
5896 lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
5904 return (lfsr ^ lcg ^ now);
5919 int check_pollerr = 0;
5920 if ((
n == 1) && ((pfd[0].events & POLLERR) == 0)) {
5922 pfd[0].events |= POLLERR;
5934 if ((milliseconds >= 0) && (milliseconds < ms_now)) {
5935 ms_now = milliseconds;
5938 result = poll(pfd,
n, ms_now);
5943 && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
5952 if (milliseconds > 0) {
5953 milliseconds -= ms_now;
5956 }
while (milliseconds > 0);
5979 uint64_t start = 0, now = 0, timeout_ns = 0;
5986 typedef size_t len_t;
5992 timeout_ns = (uint64_t)(timeout * 1.0E9);
5999#if defined(NO_SSL) && !defined(USE_MBEDTLS)
6009#if defined(USE_MBEDTLS)