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)