23#if defined(__GNUC__) || defined(__MINGW32__)
25 (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
26#if GCC_VERSION >= 40500
32#if defined(GCC_DIAGNOSTIC)
35#pragma GCC diagnostic ignored "-Wunused-macros"
37#pragma GCC diagnostic ignored "-Wpadded"
44#pragma GCC diagnostic push
45#pragma GCC diagnostic ignored "-Wreserved-id-macro"
49#if !defined(_CRT_SECURE_NO_WARNINGS)
50#define _CRT_SECURE_NO_WARNINGS
52#if !defined(_WIN32_WINNT)
53#define _WIN32_WINNT 0x0502
56#if !defined(_GNU_SOURCE)
59#if defined(__linux__) && !defined(_XOPEN_SOURCE)
60#define _XOPEN_SOURCE 600
62#if defined(__LSB_VERSION__) || defined(__sun)
66#if !defined(_LARGEFILE_SOURCE)
67#define _LARGEFILE_SOURCE
69#if !defined(_FILE_OFFSET_BITS)
70#define _FILE_OFFSET_BITS 64
72#if !defined(__STDC_FORMAT_MACROS)
73#define __STDC_FORMAT_MACROS
75#if !defined(__STDC_LIMIT_MACROS)
76#define __STDC_LIMIT_MACROS
78#if !defined(_DARWIN_UNLIMITED_SELECT)
79#define _DARWIN_UNLIMITED_SELECT
83#define __inline inline
89#pragma GCC diagnostic pop
99#pragma warning(disable : 4306)
101#pragma warning(disable : 4127)
103#pragma warning(disable : 4204)
105#pragma warning(disable : 4820)
107#pragma warning(disable : 4668)
109#pragma warning(disable : 4255)
111#pragma warning(disable : 4711)
118#if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
119#define mg_static_assert _Static_assert
120#elif defined(__cplusplus) && __cplusplus >= 201103L
121#define mg_static_assert static_assert
124#define mg_static_assert(cond, txt) \
125 extern char static_assert_replacement[(cond) ? 1 : -1]
129 "int data type size check");
131 "pointer data type size check");
143#if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
146 "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
148#if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
150#define NO_ALTERNATIVE_QUEUE
153#if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
168#error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
172#if !defined(WIN32_LEAN_AND_MEAN)
173#define WIN32_LEAN_AND_MEAN
176#if defined(__SYMBIAN32__)
181#error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
184#if defined(__ZEPHYR__)
188#include <net/socket.h>
189#include <posix/pthread.h>
190#include <posix/time.h>
198#include <libc_extensions.h>
203#define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
205#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
206#define ZEPHYR_STACK_SIZE USE_STACK_SIZE
208#define ZEPHYR_STACK_SIZE (1024 * 16)
211K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
212K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
216static int zephyr_worker_stack_index;
220#if !defined(CIVETWEB_HEADER_INCLUDED)
226#if !defined(DEBUG_TRACE)
228static void DEBUG_TRACE_FUNC(
const char *func,
233#define DEBUG_TRACE(fmt, ...) \
234 DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
236#define NEED_DEBUG_TRACE_FUNC
237#if !defined(DEBUG_TRACE_STREAM)
238#define DEBUG_TRACE_STREAM stdout
242#define DEBUG_TRACE(fmt, ...) \
249#if !defined(DEBUG_ASSERT)
252#define DEBUG_ASSERT(cond) \
255 DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
260#define DEBUG_ASSERT(cond)
265#if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
266void __cyg_profile_func_enter(
void *this_fn,
void *call_site)
267 __attribute__((no_instrument_function));
269void __cyg_profile_func_exit(
void *this_fn,
void *call_site)
270 __attribute__((no_instrument_function));
273__cyg_profile_func_enter(
void *this_fn,
void *call_site)
275 if ((
void *)this_fn != (
void *)printf) {
276 printf(
"E %p %p\n", this_fn, call_site);
281__cyg_profile_func_exit(
void *this_fn,
void *call_site)
283 if ((
void *)this_fn != (
void *)printf) {
284 printf(
"X %p %p\n", this_fn, call_site);
290#if !defined(IGNORE_UNUSED_RESULT)
291#define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
295#if defined(__GNUC__) || defined(__MINGW32__)
311#pragma GCC diagnostic ignored "-Wunused-function"
313#define FUNCTION_MAY_BE_UNUSED
316#define FUNCTION_MAY_BE_UNUSED
321#if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
327#include <sys/types.h>
331#if defined(__clang__)
335#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
338#if defined(__GNUC__) || defined(__MINGW32__)
357#if defined(__clang__)
358#if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
360#pragma clang diagnostic ignored "-Wno-reserved-id-macro"
361#pragma clang diagnostic ignored "-Wno-keyword-macro"
365#ifndef CLOCK_MONOTONIC
366#define CLOCK_MONOTONIC (1)
368#ifndef CLOCK_REALTIME
369#define CLOCK_REALTIME (2)
372#include <mach/clock.h>
373#include <mach/mach.h>
374#include <mach/mach_time.h>
375#include <sys/errno.h>
380_civet_clock_gettime(
int clk_id,
struct timespec *t)
382 memset(t, 0,
sizeof(*t));
383 if (clk_id == CLOCK_REALTIME) {
385 int rv = gettimeofday(&now, NULL);
389 t->tv_sec = now.tv_sec;
390 t->tv_nsec = now.tv_usec * 1000;
393 }
else if (clk_id == CLOCK_MONOTONIC) {
394 static uint64_t clock_start_time = 0;
395 static mach_timebase_info_data_t timebase_ifo = {0, 0};
397 uint64_t now = mach_absolute_time();
399 if (clock_start_time == 0) {
400 kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
406 clock_start_time = now;
409 now = (uint64_t)((
double)(now - clock_start_time)
410 * (
double)timebase_ifo.numer
411 / (
double)timebase_ifo.denom);
413 t->tv_sec = now / 1000000000;
414 t->tv_nsec = now % 1000000000;
421#if defined(__CLOCK_AVAILABILITY)
426_civet_safe_clock_gettime(
int clk_id,
struct timespec *t)
429 return clock_gettime(clk_id, t);
431 return _civet_clock_gettime(clk_id, t);
433#define clock_gettime _civet_safe_clock_gettime
435#define clock_gettime _civet_clock_gettime
445#define ERROR_TRY_AGAIN(err) \
446 (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
462#if !defined(MAX_WORKER_THREADS)
463#define MAX_WORKER_THREADS (1024 * 64)
470#if !defined(SOCKET_TIMEOUT_QUANTUM)
471#define SOCKET_TIMEOUT_QUANTUM (2000)
475#if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
476#define MG_FILE_COMPRESSION_SIZE_LIMIT (1024)
479#if !defined(PASSWORDS_FILE_NAME)
480#define PASSWORDS_FILE_NAME ".htpasswd"
485#if !defined(CGI_ENVIRONMENT_SIZE)
486#define CGI_ENVIRONMENT_SIZE (4096)
490#if !defined(MAX_CGI_ENVIR_VARS)
491#define MAX_CGI_ENVIR_VARS (256)
495#if !defined(MG_BUF_LEN)
496#define MG_BUF_LEN (1024 * 8)
503#if !defined(ARRAY_SIZE)
504#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
510#if !defined(INT64_MAX)
511#define INT64_MAX (9223372036854775807)
514#define SHUTDOWN_RD (0)
515#define SHUTDOWN_WR (1)
516#define SHUTDOWN_BOTH (2)
519 "worker threads must be a positive number");
522 "size_t data type size check");
540#define UTF8_PATH_MAX (3 * 260)
543#define UTF16_PATH_MAX (260)
545#if !defined(_IN_PORT_T)
546#if !defined(in_port_t)
547#define in_port_t u_short
551#if defined(_WIN32_WCE)
552#error "WinCE support has ended"
560#define MAKEUQUAD(lo, hi) \
561 ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
562#define RATE_DIFF (10000000)
563#define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
564#define SYS2UNIX_TIME(lo, hi) \
565 ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
573#define STR(x) STRX(x)
574#define __func__ __FILE__ ":" STR(__LINE__)
575#define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
576#define strtoll(x, y, z) (_atoi64(x))
578#define __func__ __FUNCTION__
579#define strtoull(x, y, z) (_strtoui64(x, y, z))
580#define strtoll(x, y, z) (_strtoi64(x, y, z))
584#define ERRNO ((int)(GetLastError()))
588#if defined(_WIN64) || defined(__MINGW64__)
591#if defined(OPENSSL_API_3_0)
592#define SSL_LIB "libssl-3-x64.dll"
593#define CRYPTO_LIB "libcrypto-3-x64.dll"
596#if defined(OPENSSL_API_1_1)
597#define SSL_LIB "libssl-1_1-x64.dll"
598#define CRYPTO_LIB "libcrypto-1_1-x64.dll"
601#if defined(OPENSSL_API_1_0)
602#define SSL_LIB "ssleay64.dll"
603#define CRYPTO_LIB "libeay64.dll"
610#if defined(OPENSSL_API_3_0)
611#define SSL_LIB "libssl-3.dll"
612#define CRYPTO_LIB "libcrypto-3.dll"
615#if defined(OPENSSL_API_1_1)
616#define SSL_LIB "libssl-1_1.dll"
617#define CRYPTO_LIB "libcrypto-1_1.dll"
620#if defined(OPENSSL_API_1_0)
621#define SSL_LIB "ssleay32.dll"
622#define CRYPTO_LIB "libeay32.dll"
629#define O_NONBLOCK (0)
634#define INT64_FMT "I64d"
635#define UINT64_FMT "I64u"
637#define WINCDECL __cdecl
638#define vsnprintf_impl _vsnprintf
639#define access _access
640#define mg_sleep(x) (Sleep(x))
642#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
644#define popen(x, y) (_popen(x, y))
647#define pclose(x) (_pclose(x))
649#define close(x) (_close(x))
650#define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
652#define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
653#define fdopen(x, y) (_fdopen((x), (y)))
654#define write(x, y, z) (_write((x), (y), (unsigned)z))
655#define read(x, y, z) (_read((x), (y), (unsigned)z))
656#define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
657#define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
658#define sleep(x) (Sleep((x)*1000))
659#define rmdir(x) (_rmdir(x))
660#if defined(_WIN64) || !defined(__MINGW32__)
662#define timegm(x) (_mkgmtime(x))
664time_t timegm(
struct tm *tm);
670#define fileno(x) (_fileno(x))
674 CRITICAL_SECTION sec;
676typedef DWORD pthread_key_t;
677typedef HANDLE pthread_t;
679 pthread_mutex_t threadIdSec;
683#if !defined(__clockid_t_defined)
684typedef DWORD clockid_t;
686#if !defined(CLOCK_MONOTONIC)
687#define CLOCK_MONOTONIC (1)
689#if !defined(CLOCK_REALTIME)
690#define CLOCK_REALTIME (2)
692#if !defined(CLOCK_THREAD)
693#define CLOCK_THREAD (3)
695#if !defined(CLOCK_PROCESS)
696#define CLOCK_PROCESS (4)
700#if defined(_MSC_VER) && (_MSC_VER >= 1900)
701#define _TIMESPEC_DEFINED
703#if !defined(_TIMESPEC_DEFINED)
710#if !defined(WIN_PTHREADS_TIME_H)
711#define MUST_IMPLEMENT_CLOCK_GETTIME
714#if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
715#define clock_gettime mg_clock_gettime
717clock_gettime(clockid_t clk_id,
struct timespec *tp)
720 ULARGE_INTEGER li, li2;
723 static double perfcnt_per_sec = 0.0;
727 QueryPerformanceFrequency((LARGE_INTEGER *)&li);
728 perfcnt_per_sec = 1.0 / li.QuadPart;
733 memset(tp, 0,
sizeof(*tp));
735 if (clk_id == CLOCK_REALTIME) {
738 GetSystemTimeAsFileTime(&ft);
739 li.LowPart = ft.dwLowDateTime;
740 li.HighPart = ft.dwHighDateTime;
741 li.QuadPart -= 116444736000000000;
742 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
743 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
747 }
else if (clk_id == CLOCK_MONOTONIC) {
750 QueryPerformanceCounter((LARGE_INTEGER *)&li);
751 d = li.QuadPart * perfcnt_per_sec;
752 tp->tv_sec = (time_t)
d;
754 tp->tv_nsec = (long)(
d * 1.0E9);
758 }
else if (clk_id == CLOCK_THREAD) {
761 FILETIME t_create, t_exit, t_kernel, t_user;
762 if (GetThreadTimes(GetCurrentThread(),
767 li.LowPart = t_user.dwLowDateTime;
768 li.HighPart = t_user.dwHighDateTime;
769 li2.LowPart = t_kernel.dwLowDateTime;
770 li2.HighPart = t_kernel.dwHighDateTime;
771 li.QuadPart += li2.QuadPart;
772 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
773 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
778 }
else if (clk_id == CLOCK_PROCESS) {
781 FILETIME t_create, t_exit, t_kernel, t_user;
782 if (GetProcessTimes(GetCurrentProcess(),
787 li.LowPart = t_user.dwLowDateTime;
788 li.HighPart = t_user.dwHighDateTime;
789 li2.LowPart = t_kernel.dwLowDateTime;
790 li2.HighPart = t_kernel.dwHighDateTime;
791 li.QuadPart += li2.QuadPart;
792 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
793 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
813static int pthread_mutex_lock(pthread_mutex_t *);
814static int pthread_mutex_unlock(pthread_mutex_t *);
834 WIN32_FIND_DATAW info;
838#if defined(HAVE_POLL)
839#define mg_pollfd pollfd
850#pragma comment(lib, "Ws2_32.lib")
858#define UTF8_PATH_MAX (PATH_MAX)
863typedef unsigned short int in_port_t;
866#if !defined(__ZEPHYR__)
867#include <arpa/inet.h>
873#include <netinet/in.h>
874#include <netinet/tcp.h>
883#include <sys/socket.h>
885#include <sys/utsname.h>
889#if defined(USE_X_DOM_SOCKET)
894#define vsnprintf_impl vsnprintf
896#if !defined(NO_SSL_DL) && !defined(NO_SSL)
901#define SSL_LIB "libssl.dylib"
902#define CRYPTO_LIB "libcrypto.dylib"
905#define SSL_LIB "libssl.so"
907#if !defined(CRYPTO_LIB)
908#define CRYPTO_LIB "libcrypto.so"
911#if !defined(O_BINARY)
914#define closesocket(a) (close(a))
915#define mg_mkdir(conn, path, mode) (mkdir(path, mode))
916#define mg_remove(conn, x) (remove(x))
917#define mg_sleep(x) (usleep((x)*1000))
918#define mg_opendir(conn, x) (opendir(x))
919#define mg_closedir(x) (closedir(x))
920#define mg_readdir(x) (readdir(x))
922#define INVALID_SOCKET (-1)
923#define INT64_FMT PRId64
924#define UINT64_FMT PRIu64
930#if !defined(CLOCK_MONOTONIC)
931#define CLOCK_MONOTONIC CLOCK_REALTIME
945#define mg_pollfd pollfd
950#if defined(NEED_TIMEGM)
954 return (
y % 4 == 0 &&
y % 100 != 0) ||
y % 400 == 0;
960 return (
y - 1969) / 4 - (
y - 1901) / 100 + (
y - 1601) / 400;
966 static const unsigned short ydays[] = {
967 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
968 int year = tm->tm_year + 1900;
969 int mon = tm->tm_mon;
970 int mday = tm->tm_mday - 1;
971 int hour = tm->tm_hour;
972 int min = tm->tm_min;
973 int sec = tm->tm_sec;
975 if (year < 1970 || mon < 0 || mon > 11 || mday < 0
976 || (mday >= ydays[mon + 1] - ydays[mon]
977 + (mon == 1 && is_leap(year) ? 1 : 0))
978 || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
981 time_t res = year - 1970;
984 res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
985 res += count_leap(year);
1000#define va_copy(x, y) ((x) = (y))
1007#if defined(GCC_DIAGNOSTIC)
1009#pragma GCC diagnostic push
1010#pragma GCC diagnostic ignored "-Wunused-function"
1014static pthread_mutex_t global_log_file_lock;
1020 return GetCurrentThreadId();
1028 void (*_ignored)(
void *)
1035 return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
1043pthread_key_delete(pthread_key_t key)
1045 return TlsFree(key) ? 0 : 1;
1051pthread_setspecific(pthread_key_t key,
void *
value)
1053 return TlsSetValue(key,
value) ? 0 : 1;
1059pthread_getspecific(pthread_key_t key)
1061 return TlsGetValue(key);
1064#if defined(GCC_DIAGNOSTIC)
1066#pragma GCC diagnostic pop
1075#if defined(GCC_DIAGNOSTIC)
1077#pragma GCC diagnostic push
1078#pragma GCC diagnostic ignored "-Wunused-function"
1080#if defined(__clang__)
1082#pragma clang diagnostic push
1083#pragma clang diagnostic ignored "-Wunused-function"
1106mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu,
"Mismatch for atomic types");
1107#elif defined(_WIN32)
1122#if defined(_WIN64) && !defined(NO_ATOMICS)
1123 ret = InterlockedIncrement64(addr);
1124#elif defined(_WIN32) && !defined(NO_ATOMICS)
1125 ret = InterlockedIncrement(addr);
1126#elif defined(__GNUC__) \
1127 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1128 && !defined(NO_ATOMICS)
1129 ret = __sync_add_and_fetch(addr, 1);
1145#if defined(_WIN64) && !defined(NO_ATOMICS)
1146 ret = InterlockedDecrement64(addr);
1147#elif defined(_WIN32) && !defined(NO_ATOMICS)
1148 ret = InterlockedDecrement(addr);
1149#elif defined(__GNUC__) \
1150 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1151 && !defined(NO_ATOMICS)
1152 ret = __sync_sub_and_fetch(addr, 1);
1162#if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
1164mg_atomic_add(
volatile ptrdiff_t *addr, ptrdiff_t
value)
1168#if defined(_WIN64) && !defined(NO_ATOMICS)
1169 ret = InterlockedAdd64(addr,
value);
1170#elif defined(_WIN32) && !defined(NO_ATOMICS)
1171 ret = InterlockedExchangeAdd(addr,
value) +
value;
1172#elif defined(__GNUC__) \
1173 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1174 && !defined(NO_ATOMICS)
1175 ret = __sync_add_and_fetch(addr,
value);
1188mg_atomic_compare_and_swap(
volatile ptrdiff_t *addr,
1194#if defined(_WIN64) && !defined(NO_ATOMICS)
1195 ret = InterlockedCompareExchange64(addr, newval, oldval);
1196#elif defined(_WIN32) && !defined(NO_ATOMICS)
1197 ret = InterlockedCompareExchange(addr, newval, oldval);
1198#elif defined(__GNUC__) \
1199 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1200 && !defined(NO_ATOMICS)
1201 ret = __sync_val_compare_and_swap(addr, oldval, newval);
1205 if ((ret != newval) && (ret == oldval)) {
1215mg_atomic_max(
volatile ptrdiff_t *addr, ptrdiff_t
value)
1217 register ptrdiff_t
tmp = *addr;
1219#if defined(_WIN64) && !defined(NO_ATOMICS)
1220 while (tmp <
value) {
1221 tmp = InterlockedCompareExchange64(addr,
value, tmp);
1223#elif defined(_WIN32) && !defined(NO_ATOMICS)
1224 while (tmp <
value) {
1225 tmp = InterlockedCompareExchange(addr,
value, tmp);
1227#elif defined(__GNUC__) \
1228 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1229 && !defined(NO_ATOMICS)
1230 while (tmp <
value) {
1231 tmp = __sync_val_compare_and_swap(addr, tmp,
value);
1235 if (*addr <
value) {
1244mg_atomic_add64(
volatile int64_t *addr, int64_t
value)
1248#if defined(_WIN64) && !defined(NO_ATOMICS)
1249 ret = InterlockedAdd64(addr,
value);
1250#elif defined(_WIN32) && !defined(NO_ATOMICS)
1251 ret = InterlockedExchangeAdd64(addr,
value) +
value;
1252#elif defined(__GNUC__) \
1253 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1254 && !defined(NO_ATOMICS)
1255 ret = __sync_add_and_fetch(addr,
value);
1267#if defined(GCC_DIAGNOSTIC)
1269#pragma GCC diagnostic pop
1271#if defined(__clang__)
1273#pragma clang diagnostic pop
1277#if defined(USE_SERVER_STATS)
1279struct mg_memory_stat {
1280 volatile ptrdiff_t totalMemUsed;
1281 volatile ptrdiff_t maxMemUsed;
1282 volatile ptrdiff_t blockCount;
1286static struct mg_memory_stat *get_memory_stat(
struct mg_context *ctx);
1290mg_malloc_ex(
size_t size,
1297 struct mg_memory_stat *mstat = get_memory_stat(ctx);
1299#if defined(MEMORY_DEBUGGING)
1300 char mallocStr[256];
1307 ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)
size);
1308 mg_atomic_max(&mstat->maxMemUsed, mmem);
1312 ((uintptr_t *)
data)[1] = (uintptr_t)mstat;
1313 memory = (
void *)(((
char *)
data) + 2 *
sizeof(uintptr_t));
1316#if defined(MEMORY_DEBUGGING)
1318 "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
1320 (
unsigned long)
size,
1321 (
unsigned long)mstat->totalMemUsed,
1322 (
unsigned long)mstat->blockCount,
1333mg_calloc_ex(
size_t count,
1339 void *
data = mg_malloc_ex(
size * count, ctx, file,
line);
1349mg_free_ex(
void *memory,
const char *file,
unsigned line)
1351#if defined(MEMORY_DEBUGGING)
1352 char mallocStr[256];
1359 void *
data = (
void *)(((
char *)memory) - 2 *
sizeof(uintptr_t));
1360 uintptr_t
size = ((uintptr_t *)
data)[0];
1361 struct mg_memory_stat *mstat =
1362 (
struct mg_memory_stat *)(((uintptr_t *)
data)[1]);
1363 mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)
size);
1366#if defined(MEMORY_DEBUGGING)
1368 "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
1370 (
unsigned long)
size,
1371 (
unsigned long)mstat->totalMemUsed,
1372 (
unsigned long)mstat->blockCount,
1383mg_realloc_ex(
void *memory,
1393#if defined(MEMORY_DEBUGGING)
1394 char mallocStr[256];
1403 struct mg_memory_stat *mstat;
1404 data = (
void *)(((
char *)memory) - 2 *
sizeof(uintptr_t));
1405 oldsize = ((uintptr_t *)
data)[0];
1406 mstat = (
struct mg_memory_stat *)((uintptr_t *)
data)[1];
1407 _realloc =
realloc(
data, newsize + 2 *
sizeof(uintptr_t));
1410 mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
1411#if defined(MEMORY_DEBUGGING)
1413 "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
1415 (
unsigned long)oldsize,
1416 (
unsigned long)mstat->totalMemUsed,
1417 (
unsigned long)mstat->blockCount,
1422 mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
1424#if defined(MEMORY_DEBUGGING)
1426 "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
1428 (
unsigned long)newsize,
1429 (
unsigned long)mstat->totalMemUsed,
1430 (
unsigned long)mstat->blockCount,
1435 *(uintptr_t *)
data = newsize;
1436 data = (
void *)(((
char *)
data) + 2 *
sizeof(uintptr_t));
1438#if defined(MEMORY_DEBUGGING)
1445 data = mg_malloc_ex(newsize, ctx, file,
line);
1450 mg_free_ex(memory, file,
line);
1457#define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
1458#define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
1459#define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
1460#define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
1462#define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
1463#define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
1464#define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
1470static __inline
void *
1476static __inline
void *
1482static __inline
void *
1494#define mg_malloc_ctx(a, c) mg_malloc(a)
1495#define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
1496#define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
1497#define mg_free_ctx(a, c) mg_free(a)
1530#if defined(snprintf)
1533#if defined(vsnprintf)
1536#define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
1537#define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
1538#define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
1539#define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
1540#define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
1544#define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
1552#if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
1553 || defined(OPENSSL_API_3_0)
1554static int mg_openssl_initialized = 0;
1556#if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
1557 && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
1558#error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
1560#if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
1561 && defined(OPENSSL_API_3_0)
1562#error "Multiple OPENSSL_API versions defined"
1564#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
1565 || defined(OPENSSL_API_3_0)) \
1566 && defined(USE_MBEDTLS)
1567#error "Multiple SSL libraries defined"
1575#if defined(MG_LEGACY_INTERFACE)
1576#define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
1584 HANDLE pthread_cond_helper_mutex;
1588#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
1594#if defined(GCC_DIAGNOSTIC)
1596#pragma GCC diagnostic push
1597#pragma GCC diagnostic ignored "-Wunused-function"
1599#if defined(__clang__)
1601#pragma clang diagnostic push
1602#pragma clang diagnostic ignored "-Wunused-function"
1621 return GetCurrentThreadId();
1624#if defined(__clang__)
1625#pragma clang diagnostic push
1626#pragma clang diagnostic ignored "-Wunreachable-code"
1634 if (
sizeof(pthread_t) >
sizeof(
unsigned long)) {
1645 pthread_setspecific(
sTlsKey, tls);
1652 unsigned long ret = 0;
1653 pthread_t t = pthread_self();
1654 memcpy(&ret, &t,
sizeof(pthread_t));
1658#if defined(__clang__)
1659#pragma clang diagnostic pop
1670 struct timespec tsnow;
1671 clock_gettime(CLOCK_REALTIME, &tsnow);
1672 return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
1676#if defined(GCC_DIAGNOSTIC)
1678#pragma GCC diagnostic pop
1680#if defined(__clang__)
1682#pragma clang diagnostic pop
1686#if defined(NEED_DEBUG_TRACE_FUNC)
1688DEBUG_TRACE_FUNC(
const char *func,
unsigned line,
const char *fmt, ...)
1691 struct timespec tsnow;
1696 clock_gettime(CLOCK_REALTIME, &tsnow);
1698 flockfile(DEBUG_TRACE_STREAM);
1699 fprintf(DEBUG_TRACE_STREAM,
1700 "*** %lu.%09lu %lu %s:%u: ",
1701 (
unsigned long)tsnow.tv_sec,
1702 (
unsigned long)tsnow.tv_nsec,
1706 va_start(args, fmt);
1707 vfprintf(DEBUG_TRACE_STREAM, fmt, args);
1709 putc(
'\n', DEBUG_TRACE_STREAM);
1710 fflush(DEBUG_TRACE_STREAM);
1711 funlockfile(DEBUG_TRACE_STREAM);
1716#define MD5_STATIC static
1720#if defined(NO_SOCKLEN_T)
1721typedef int socklen_t;
1724#define IP_ADDR_STR_LEN (50)
1726#if !defined(MSG_NOSIGNAL)
1727#define MSG_NOSIGNAL (0)
1732#if defined(USE_MBEDTLS)
1734#include "mod_mbedtls.inl"
1736#elif defined(NO_SSL)
1741#elif defined(NO_SSL_DL)
1743#include <openssl/bn.h>
1744#include <openssl/conf.h>
1745#include <openssl/crypto.h>
1746#include <openssl/dh.h>
1747#include <openssl/err.h>
1748#include <openssl/opensslv.h>
1749#include <openssl/pem.h>
1750#include <openssl/ssl.h>
1751#include <openssl/tls1.h>
1752#include <openssl/x509.h>
1754#if defined(WOLFSSL_VERSION)
1757#include "wolfssl_extras.inl"
1760#if defined(OPENSSL_IS_BORINGSSL)
1771#define CONF_modules_unload(a) ((void)0)
1772#define ENGINE_cleanup() ((void)0)
1776#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
1777#if !defined(OPENSSL_API_3_0)
1778#define OPENSSL_API_3_0
1780#define OPENSSL_REMOVE_THREAD_STATE()
1782#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1783#if !defined(OPENSSL_API_1_1)
1784#define OPENSSL_API_1_1
1786#define OPENSSL_REMOVE_THREAD_STATE()
1788#if !defined(OPENSSL_API_1_0)
1789#define OPENSSL_API_1_0
1791#define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
1805#if !defined(NO_CACHING)
1826#if defined(USE_IPV6)
1827 struct sockaddr_in6 sin6;
1829#if defined(USE_X_DOM_SOCKET)
1830 struct sockaddr_un sun;
1834#if defined(USE_X_DOM_SOCKET)
1835static unsigned short
1838 if (s->
sa.sa_family == AF_INET)
1839 return s->
sin.sin_port;
1840#if defined(USE_IPV6)
1841 if (s->
sa.sa_family == AF_INET6)
1842 return s->sin6.sin6_port;
1847#if defined(USE_IPV6)
1848#define USA_IN_PORT_UNSAFE(s) \
1849 (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
1851#define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
1882#define STRUCT_FILE_INITIALIZER \
1884 {(uint64_t)0, (time_t)0, 0, 0, 0}, \
1920#if defined(__linux__)
1921 ALLOW_SENDFILE_CALL,
1924 CASE_SENSITIVE_FILES,
1930#if defined(USE_WEBSOCKET)
1932 ENABLE_WEBSOCKET_PING_PONG,
1937 LUA_BACKGROUND_SCRIPT,
1938 LUA_BACKGROUND_SCRIPT_PARAMS,
1940#if defined(USE_HTTP2)
1954#if defined(USE_TIMERS)
1962#if defined(USE_TIMERS)
1966#if defined(USE_4_CGI)
1970 CGI3_INTERPRETER_ARGS,
1971#if defined(USE_TIMERS)
1978 CGI4_INTERPRETER_ARGS,
1979#if defined(USE_TIMERS)
2010 LUA_SCRIPT_EXTENSIONS,
2011 LUA_SERVER_PAGE_EXTENSIONS,
2012#if defined(MG_EXPERIMENTAL_INTERFACES)
2016#if defined(USE_DUKTAPE)
2017 DUKTAPE_SCRIPT_EXTENSIONS,
2020#if defined(USE_WEBSOCKET)
2023#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2024 LUA_WEBSOCKET_EXTENSIONS,
2032#if !defined(NO_CACHING)
2060#if defined(__linux__)
2070#if defined(USE_WEBSOCKET)
2080#if defined(USE_HTTP2)
2094#if defined(USE_TIMERS)
2102#if defined(USE_TIMERS)
2106#if defined(USE_4_CGI)
2111#if defined(USE_TIMERS)
2119#if defined(USE_TIMERS)
2134 "index.xhtml,index.html,index.htm,"
2135 "index.lp,index.lsp,index.lua,index.cgi,"
2136 "index.shtml,index.php"},
2138 "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
2166#if defined(MG_EXPERIMENTAL_INTERFACES)
2170#if defined(USE_DUKTAPE)
2176#if defined(USE_WEBSOCKET)
2179#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2187#if !defined(NO_CACHING)
2204 "config_options and enum not sync");
2261#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2263 struct mg_shared_lua_websocket_list *shared_lua_websockets;
2274#if defined(STOP_FLAG_NEEDS_LOCK)
2297 sf = mg_atomic_compare_and_swap(
f, *
f,
v);
2304#define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
2305#define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
2306#define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
2329#if defined(USE_SERVER_STATS)
2330 volatile ptrdiff_t active_connections;
2331 volatile ptrdiff_t max_active_connections;
2332 volatile ptrdiff_t total_connections;
2333 volatile ptrdiff_t total_requests;
2334 volatile int64_t total_data_read;
2335 volatile int64_t total_data_written;
2349#if defined(ALTERNATIVE_QUEUE)
2350 struct socket *client_socks;
2351 void **client_wait_events;
2361#if defined(USE_SERVER_STATS)
2369#if defined(USE_SERVER_STATS)
2370 struct mg_memory_stat ctx_memory;
2378#if defined(USE_TIMERS)
2379 struct ttimers *timers;
2384 void *lua_background_state;
2385 pthread_mutex_t lua_bg_mutex;
2386 int lua_bg_log_available;
2409#if defined(USE_SERVER_STATS)
2410static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2412static struct mg_memory_stat *
2416 return &(ctx->ctx_memory);
2418 return &mg_common_memory;
2435#if defined(USE_HTTP2)
2436#if !defined(HTTP2_DYN_TABLE_SIZE)
2437#define HTTP2_DYN_TABLE_SIZE (256)
2440struct mg_http2_connection {
2442 uint32_t dyn_table_size;
2443 struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
2453#if defined(USE_HTTP2)
2454 struct mg_http2_connection http2;
2463#if defined(USE_SERVER_STATS)
2473#if defined(USE_SERVER_STATS)
2474 time_t conn_close_time;
2476 double processing_time;
2502#if defined(USE_WEBSOCKET)
2503 int in_websocket_handling;
2505#if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
2506 && defined(MG_EXPERIMENTAL_INTERFACES)
2508 int websocket_deflate_server_max_windows_bits;
2509 int websocket_deflate_client_max_windows_bits;
2510 int websocket_deflate_server_no_context_takeover;
2511 int websocket_deflate_client_no_context_takeover;
2512 int websocket_deflate_initialized;
2513 int websocket_deflate_flush;
2514 z_stream websocket_deflate_state;
2515 z_stream websocket_inflate_state;
2530#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2531 void *lua_websocket_state;
2547#define mg_cry_internal(conn, fmt, ...) \
2548 mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
2550#define mg_cry_ctx_internal(ctx, fmt, ...) \
2551 mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
2561#if !defined(NO_THREAD_NAME)
2562#if defined(_WIN32) && defined(_MSC_VER)
2566#pragma pack(push, 8)
2567typedef struct tagTHREADNAME_INFO {
2575#elif defined(__linux__)
2577#include <sys/prctl.h>
2578#include <sys/sendfile.h>
2579#if defined(ALTERNATIVE_QUEUE)
2580#include <sys/eventfd.h>
2584#if defined(ALTERNATIVE_QUEUE)
2589 int evhdl = eventfd(0, EFD_CLOEXEC);
2610event_wait(
void *eventhdl)
2619 evhdl = *(
int *)eventhdl;
2621 s = (
int)read(evhdl, &u,
sizeof(u));
2622 if (s !=
sizeof(u)) {
2632event_signal(
void *eventhdl)
2641 evhdl = *(
int *)eventhdl;
2643 s = (
int)write(evhdl, &u,
sizeof(u));
2644 if (s !=
sizeof(u)) {
2653event_destroy(
void *eventhdl)
2661 evhdl = *(
int *)eventhdl;
2673#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2676 pthread_mutex_t mutex;
2685 struct posix_event *ret =
mg_malloc(
sizeof(
struct posix_event));
2690 if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2695 if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2697 pthread_mutex_destroy(&(ret->mutex));
2707event_wait(
void *eventhdl)
2709 struct posix_event *ev = (
struct posix_event *)eventhdl;
2710 pthread_mutex_lock(&(ev->mutex));
2711 while (!ev->signaled) {
2712 pthread_cond_wait(&(ev->cond), &(ev->mutex));
2715 pthread_mutex_unlock(&(ev->mutex));
2721event_signal(
void *eventhdl)
2723 struct posix_event *ev = (
struct posix_event *)eventhdl;
2724 pthread_mutex_lock(&(ev->mutex));
2725 pthread_cond_signal(&(ev->cond));
2727 pthread_mutex_unlock(&(ev->mutex));
2733event_destroy(
void *eventhdl)
2735 struct posix_event *ev = (
struct posix_event *)eventhdl;
2736 pthread_cond_destroy(&(ev->cond));
2737 pthread_mutex_destroy(&(ev->mutex));
2746 char threadName[16 + 1];
2749 NULL, NULL, threadName,
sizeof(threadName),
"civetweb-%s",
name);
2752#if defined(_MSC_VER)
2755 THREADNAME_INFO info;
2756 info.dwType = 0x1000;
2757 info.szName = threadName;
2758 info.dwThreadID = ~0U;
2761 RaiseException(0x406D1388,
2763 sizeof(info) /
sizeof(ULONG_PTR),
2764 (ULONG_PTR *)&info);
2765 } __except (EXCEPTION_EXECUTE_HANDLER) {
2767#elif defined(__MINGW32__)
2770#elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
2771 && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
2773#if defined(__MACH__)
2775 (void)pthread_setname_np(threadName);
2777 (void)pthread_setname_np(pthread_self(), threadName);
2779#elif defined(__linux__)
2785 (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
2804#define MG_FOPEN_MODE_NONE (0)
2807#define MG_FOPEN_MODE_READ (1)
2810#define MG_FOPEN_MODE_WRITE (2)
2813#define MG_FOPEN_MODE_APPEND (4)
2823 return (fileacc->
fp != NULL);
2827#if !defined(NO_FILESYSTEMS)
2837 const uint8_t *
c = (
const uint8_t *)path;
2840 if ((
c == NULL) || (
c[0] == 0)) {
2851 if ((*
c ==
'>') || (*
c ==
'<') || (*
c ==
'|')) {
2855 if ((*
c ==
'*') || (*
c ==
'?')) {
2906 wchar_t wbuf[UTF16_PATH_MAX];
2907 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
2910 filep->
access.
fp = _wfopen(wbuf, L
"rb");
2913 filep->
access.
fp = _wfopen(wbuf, L
"wb");
2916 filep->
access.
fp = _wfopen(wbuf, L
"ab");
2924 filep->
access.
fp = fopen(path,
"r");
2927 filep->
access.
fp = fopen(path,
"w");
2930 filep->
access.
fp = fopen(path,
"a");
2953 if (fileacc != NULL) {
2954 if (fileacc->
fp != NULL) {
2955 ret = fclose(fileacc->
fp);
2958 memset(fileacc, 0,
sizeof(*fileacc));
2968 for (; *
src !=
'\0' &&
n > 1;
n--) {
2978 return tolower((
unsigned char)*s);
2990 }
while (diff == 0 &&
s1[-1] !=
'\0' && --
len > 0);
3004 }
while (diff == 0 &&
s1[-1] !=
'\0');
3041 size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3043 if (big_len >= small_len) {
3044 for (i = 0; i <= (big_len - small_len); i++) {
3074#if defined(__clang__)
3075#pragma clang diagnostic push
3076#pragma clang diagnostic ignored "-Wformat-nonliteral"
3082 ok = (
n >= 0) && ((
size_t)
n < buflen);
3084#if defined(__clang__)
3085#pragma clang diagnostic pop
3097 "truncating vsnprintf buffer: [%.*s]",
3098 (
int)((buflen > 200) ? 200 : (buflen - 1)),
3100 n = (
int)buflen - 1;
3142 }
else if (!ctx || ctx->
dd.
config[i] == NULL) {
3149#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3161 return (ctx == NULL) ? NULL : ctx->
user_data;
3191 if (const_conn != NULL) {
3221 memset(ports, 0,
sizeof(*ports) * (
size_t)
size);
3251#if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
3252#define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
3264 if (
usa->
sa.sa_family == AF_INET) {
3265 getnameinfo(&
usa->
sa,
3273#if defined(USE_IPV6)
3274 else if (
usa->
sa.sa_family == AF_INET6) {
3275 getnameinfo(&
usa->
sa,
3284#if defined(USE_X_DOM_SOCKET)
3285 else if (
usa->
sa.sa_family == AF_UNIX) {
3296 strncpy(
buf, UNIX_DOMAIN_SOCKET_SERVER_NAME,
len);
3308#if !defined(REENTRANT_TIME)
3311 tm = ((t != NULL) ? gmtime(t) : NULL);
3315 struct tm *tm = &_tm;
3320 strftime(buf, buf_len,
"%a, %d %b %Y %H:%M:%S GMT", tm);
3322 mg_strlcpy(buf,
"Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3323 buf[buf_len - 1] =
'\0';
3332 return (
double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3333 + (
double)(ts_now->tv_sec - ts_before->tv_sec);
3337#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3343#include "external_mg_cry_internal_impl.inl"
3344#elif !defined(NO_FILESYSTEMS)
3362#if defined(GCC_DIAGNOSTIC)
3363#pragma GCC diagnostic push
3364#pragma GCC diagnostic ignored "-Wformat-nonliteral"
3369#if defined(GCC_DIAGNOSTIC)
3370#pragma GCC diagnostic pop
3373 buf[
sizeof(buf) - 1] = 0;
3402 timestamp = time(NULL);
3406 "[%010lu] [error] [client %s] ",
3407 (
unsigned long)timestamp,
3429#error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
3476#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3492#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3499 if (strlen(txt) == 3) {
3500 memcpy(tls->txtbuf, txt, 4);
3502 strcpy(tls->txtbuf,
"ERR");
3507 ((
struct mg_connection *)conn)->request_info.local_uri_raw =
3542#if defined(__clang__)
3543#pragma clang diagnostic push
3544#pragma clang diagnostic ignored "-Wunreachable-code"
3555 ? (ri->
is_ssl ?
"wss" :
"ws")
3556 : (ri->
is_ssl ?
"https" :
"http"));
3560#if defined(__clang__)
3561#pragma clang diagnostic pop
3570 const char *define_proto,
3572 const char *define_uri)
3574 if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3583 (define_uri != NULL)
3586 int port = (define_port > 0) ? define_port : ri->
server_port;
3593#if defined(USE_X_DOM_SOCKET)
3604 const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
3620 if ((0 == strcmp(define_proto,
"https"))
3621 || (0 == strcmp(define_proto,
"wss"))) {
3631#if defined(USE_IPV6)
3632 int is_ipv6 = (conn->
client.
lsa.
sa.sa_family == AF_INET6);
3634 int auth_domain_check_enabled =
3639 const char *server_domain =
3646 sprintf(portstr,
":%u", (
unsigned)port);
3651 if (!auth_domain_check_enabled || !server_domain) {
3657 server_domain = server_ip;
3664#
if defined(USE_IPV6)
3667 (is_ipv6 && (server_domain == server_ip)) ?
"[" :
"",
3669 (is_ipv6 && (server_domain == server_ip)) ?
"]" :
"",
3701 const char *delimiters,
3702 const char *whitespace,
3705 char *
p, *begin_word, *end_word, *end_whitespace;
3708 end_word = begin_word + strcspn(begin_word, delimiters);
3711 if (end_word > begin_word) {
3713 while (*
p == quotechar) {
3720 if (*end_word !=
'\0') {
3721 size_t end_off = strcspn(end_word + 1, delimiters);
3722 memmove(
p, end_word, end_off + 1);
3724 end_word += end_off + 1;
3730 for (
p++;
p < end_word;
p++) {
3735 if (*end_word ==
'\0') {
3739#if defined(GCC_DIAGNOSTIC)
3741#pragma GCC diagnostic push
3742#pragma GCC diagnostic ignored "-Wsign-conversion"
3745 end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
3747#if defined(GCC_DIAGNOSTIC)
3748#pragma GCC diagnostic pop
3751 for (
p = end_word;
p < end_whitespace;
p++) {
3755 *buf = end_whitespace;
3767 for (i = 0; i < num_hdr; i++) {
3769 return hdr[i].
value;
3777#if defined(USE_WEBSOCKET)
3784 int output_max_size)
3850 if (val == NULL || list == NULL || *list ==
'\0') {
3856 while (*list ==
' ' || *list ==
'\t')
3860 if ((list = strchr(val->
ptr,
',')) != NULL) {
3862 val->
len = ((size_t)(list - val->
ptr));
3866 list = val->
ptr + strlen(val->
ptr);
3867 val->
len = ((size_t)(list - val->
ptr));
3872 while (end >= 0 && ((val->
ptr[end] ==
' ') || (val->
ptr[end] ==
'\t')))
3874 val->
len = (size_t)(end) + (size_t)(1);
3876 if (val->
len == 0) {
3881 if (eq_val != NULL) {
3885 eq_val->
ptr = (
const char *)memchr(val->
ptr,
'=', val->
len);
3886 if (eq_val->
ptr != NULL) {
3888 eq_val->
len = ((size_t)(val->
ptr - eq_val->
ptr)) + val->
len;
3889 val->
len = ((size_t)(eq_val->
ptr - val->
ptr)) - 1;
3910 while ((header =
next_option(header, &opt_vec, &eq_vec)) != NULL) {
3924 ptrdiff_t i, j,
len, res;
3926 if ((or_str = (
const char *)memchr(pattern,
'|', pattern_len)) != NULL) {
3927 res =
match_prefix(pattern, (
size_t)(or_str - pattern), str);
3928 return (res > 0) ? res
3930 (
size_t)((pattern + pattern_len)
3935 for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
3936 if ((pattern[i] ==
'?') && (str[j] !=
'\0')) {
3938 }
else if (pattern[i] ==
'$') {
3939 return (str[j] ==
'\0') ? j : -1;
3940 }
else if (pattern[i] ==
'*') {
3942 if (pattern[i] ==
'*') {
3944 len = (ptrdiff_t)strlen(str + j);
3946 len = (ptrdiff_t)strcspn(str + j,
"/");
3948 if (i == (ptrdiff_t)pattern_len) {
3953 (pattern_len - (
size_t)i),
3955 }
while (res == -1 &&
len-- > 0);
3956 return (res == -1) ? -1 : j + res +
len;
3961 return (ptrdiff_t)j;
3968 if (pattern == NULL) {
3981 const char *http_version;
4007 if (http_version && (0 == strcmp(http_version,
"1.1"))) {
4020 if (!conn || !conn->
dom_ctx) {
4031 if (!conn || !conn->
dom_ctx) {
4056 "no-cache, no-store, "
4057 "must-revalidate, private, max-age=0",
4071#if !defined(NO_CACHING)
4075 const char *cache_control =
4079 if (cache_control != NULL) {
4106 conn, NULL, val,
sizeof(val),
"max-age=%lu", (
unsigned long)max_age);
4131 (
unsigned long)max_age);
4137 if (header && header[0]) {
4143#if !defined(NO_FILESYSTEMS)
4157 switch (response_code) {
4162 return "Switching Protocols";
4164 return "Processing";
4174 return "Non-Authoritative Information";
4176 return "No Content";
4178 return "Reset Content";
4180 return "Partial Content";
4182 return "Multi-Status";
4185 return "Already Reported";
4192 return "Multiple Choices";
4194 return "Moved Permanently";
4200 return "Not Modified";
4204 return "Temporary Redirect";
4206 return "Permanent Redirect";
4210 return "Bad Request";
4212 return "Unauthorized";
4214 return "Payment Required";
4220 return "Method Not Allowed";
4222 return "Not Acceptable";
4224 return "Proxy Authentication Required";
4226 return "Request Time-out";
4232 return "Length Required";
4234 return "Precondition Failed";
4236 return "Request Entity Too Large";
4238 return "Request-URI Too Large";
4240 return "Unsupported Media Type";
4242 return "Requested range not satisfiable";
4245 return "Expectation Failed";
4248 return "Misdirected Request";
4250 return "Unproccessable entity";
4255 return "Failed Dependency";
4259 return "Upgrade Required";
4262 return "Precondition Required";
4264 return "Too Many Requests";
4267 return "Request Header Fields Too Large";
4270 return "Unavailable For Legal Reasons";
4275 return "Internal Server Error";
4277 return "Not Implemented";
4279 return "Bad Gateway";
4281 return "Service Unavailable";
4283 return "Gateway Time-out";
4285 return "HTTP Version not supported";
4287 return "Variant Also Negotiates";
4289 return "Insufficient Storage";
4292 return "Loop Detected";
4295 return "Not Extended";
4297 return "Network Authentication Required";
4303 return "I am a teapot";
4305 return "Authentication Timeout";
4307 return "Enhance Your Calm";
4309 return "Login Timeout";
4311 return "Bandwidth Limit Exceeded";
4317 "Unknown HTTP response code: %u",
4322 if (response_code >= 100 && response_code < 200) {
4324 return "Information";
4326 if (response_code >= 200 && response_code < 300) {
4330 if (response_code >= 300 && response_code < 400) {
4332 return "Redirection";
4334 if (response_code >= 400 && response_code < 500) {
4336 return "Client Error";
4338 if (response_code >= 500 && response_code < 600) {
4340 return "Server Error";
4359#if !defined(NO_FILESYSTEMS)
4361 int len, i, page_handler_found, scope, truncated;
4362 const char *error_handler = NULL;
4364 const char *error_page_file_ext, *tstr;
4366 int handled_by_callback = 0;
4368 if ((conn == NULL) || (fmt == NULL)) {
4376 has_body = ((status > 199) && (status != 204) && (status != 304));
4384 mg_vsnprintf(conn, NULL, errmsg_buf,
sizeof(errmsg_buf), fmt, ap);
4387 DEBUG_TRACE(
"Error %i - [%s]", status, errmsg_buf);
4397 handled_by_callback =
4403 if (!handled_by_callback) {
4407 "Recursion when handling error %u - fall back to default",
4409#if !defined(NO_FILESYSTEMS)
4414 page_handler_found = 0;
4416 if (error_handler != NULL) {
4417 for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4423 sizeof(path_buf) - 32,
4434 sizeof(path_buf) - 32,
4443 sizeof(path_buf) - 32,
4458 path_buf[
sizeof(path_buf) - 32] = 0;
4459 len = (
int)strlen(path_buf);
4460 if (
len > (
int)
sizeof(path_buf) - 32) {
4461 len = (
int)
sizeof(path_buf) - 32;
4465 tstr = strchr(error_page_file_ext,
'.');
4469 (i < 32) && (tstr[i] != 0) && (tstr[i] !=
',');
4474 path_buf[
len + i - 1] = tstr[i];
4479 path_buf[
len + i - 1] = 0;
4481 if (
mg_stat(conn, path_buf, &error_page_file.
stat)) {
4484 page_handler_found = 1;
4492 tstr = strchr(tstr + i,
'.');
4497 if (page_handler_found) {
4514 "text/plain; charset=utf-8",
4523 mg_printf(conn,
"Error %d: %s\n", status, status_text);
4524 mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4552 long long content_length)
4563 if (content_length < 0) {
4577 (uint64_t)content_length);
4592 const char *target_url,
4606 const char *redirect_text;
4608 size_t content_len = 0;
4609#if defined(MG_SEND_REDIRECT_BODY)
4614 if (redirect_code == 0) {
4615 redirect_code = 307;
4619 if ((redirect_code != 301) && (redirect_code != 302)
4620 && (redirect_code != 303) && (redirect_code != 307)
4621 && (redirect_code != 308)) {
4630 if ((target_url == NULL) || (*target_url == 0)) {
4634#if defined(MG_SEND_REDIRECT_BODY)
4662 "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4666 content_len = strlen(reply);
4672 "HTTP/1.1 %i %s\r\n"
4674 "Content-Length: %u\r\n"
4675 "Connection: %s\r\n\r\n",
4679 (
unsigned int)content_len,
4682#if defined(MG_SEND_REDIRECT_BODY)
4687 ret =
mg_write(conn, reply, content_len);
4692 return (ret > 0) ? ret : -1;
4699#if defined(GCC_DIAGNOSTIC)
4701#pragma GCC diagnostic push
4702#pragma GCC diagnostic ignored "-Wunused-function"
4707pthread_mutex_init(pthread_mutex_t *mutex,
void *unused)
4711 InitializeCriticalSection(&mutex->sec);
4717pthread_mutex_destroy(pthread_mutex_t *mutex)
4719 DeleteCriticalSection(&mutex->sec);
4725pthread_mutex_lock(pthread_mutex_t *mutex)
4727 EnterCriticalSection(&mutex->sec);
4733pthread_mutex_unlock(pthread_mutex_t *mutex)
4735 LeaveCriticalSection(&mutex->sec);
4746 cv->waiting_thread = NULL;
4754 pthread_mutex_t *mutex,
4760 uint64_t nsnow, nswaitabs;
4764 pthread_mutex_lock(&cv->threadIdSec);
4766 ptls = &cv->waiting_thread;
4767 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
4769 tls->next_waiting_thread = NULL;
4771 pthread_mutex_unlock(&cv->threadIdSec);
4776 (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
4777 nswaitrel = nswaitabs - nsnow;
4778 if (nswaitrel < 0) {
4781 mswaitrel = (DWORD)(nswaitrel / 1000000);
4783 mswaitrel = (DWORD)INFINITE;
4786 pthread_mutex_unlock(mutex);
4788 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
4791 pthread_mutex_lock(&cv->threadIdSec);
4792 ptls = &cv->waiting_thread;
4793 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
4795 *ptls = tls->next_waiting_thread;
4800 pthread_mutex_unlock(&cv->threadIdSec);
4802 WaitForSingleObject(tls->pthread_cond_helper_mutex,
4807 pthread_mutex_lock(mutex);
4817 return pthread_cond_timedwait(cv, mutex, NULL);
4828 pthread_mutex_lock(&cv->threadIdSec);
4829 if (cv->waiting_thread) {
4830 wkup = cv->waiting_thread->pthread_cond_helper_mutex;
4831 cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
4833 ok = SetEvent(wkup);
4836 pthread_mutex_unlock(&cv->threadIdSec);
4846 pthread_mutex_lock(&cv->threadIdSec);
4847 while (cv->waiting_thread) {
4848 pthread_cond_signal(cv);
4850 pthread_mutex_unlock(&cv->threadIdSec);
4860 pthread_mutex_lock(&cv->threadIdSec);
4862 pthread_mutex_unlock(&cv->threadIdSec);
4863 pthread_mutex_destroy(&cv->threadIdSec);
4869#if defined(ALTERNATIVE_QUEUE)
4874 return (
void *)CreateEvent(NULL,
FALSE,
FALSE, NULL);
4880event_wait(
void *eventhdl)
4882 int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
4883 return (res == WAIT_OBJECT_0);
4889event_signal(
void *eventhdl)
4891 return (
int)SetEvent((HANDLE)eventhdl);
4897event_destroy(
void *eventhdl)
4899 CloseHandle((HANDLE)eventhdl);
4904#if defined(GCC_DIAGNOSTIC)
4906#pragma GCC diagnostic pop
4912change_slashes_to_backslashes(
char *path)
4916 for (i = 0; path[i] !=
'\0'; i++) {
4917 if (path[i] ==
'/') {
4923 if ((i > 0) && (path[i] ==
'\\')) {
4924 while ((path[i + 1] ==
'\\') || (path[i + 1] ==
'/')) {
4925 (
void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
4933mg_wcscasecmp(
const wchar_t *
s1,
const wchar_t *s2)
4938 diff = ((*
s1 >=
L'A') && (*
s1 <= L
'Z') ? (*
s1 -
L'A' +
L'a') : *
s1)
4939 - ((*s2 >=
L'A') && (*s2 <=
L'Z') ? (*s2 -
L'A' +
L'a') : *s2);
4942 }
while ((diff == 0) && (
s1[-1] != L
'\0'));
4957 wchar_t wbuf2[UTF16_PATH_MAX + 1];
4958 DWORD long_len, err;
4959 int (*fcompare)(
const wchar_t *,
const wchar_t *) = mg_wcscasecmp;
4962 change_slashes_to_backslashes(buf);
4966 memset(wbuf, 0, wbuf_len *
sizeof(
wchar_t));
4967 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (
int)wbuf_len);
4968 WideCharToMultiByte(
4969 CP_UTF8, 0, wbuf, (
int)wbuf_len, buf2,
sizeof(buf2), NULL, NULL);
4970 if (strcmp(buf, buf2) != 0) {
4994 memset(wbuf2, 0,
ARRAY_SIZE(wbuf2) *
sizeof(
wchar_t));
4995 long_len = GetLongPathNameW(wbuf, wbuf2,
ARRAY_SIZE(wbuf2) - 1);
4996 if (long_len == 0) {
4997 err = GetLastError();
4998 if (err == ERROR_FILE_NOT_FOUND) {
5003 if ((long_len >=
ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5010#if !defined(NO_FILESYSTEMS)
5017 wchar_t wbuf[UTF16_PATH_MAX];
5018 WIN32_FILE_ATTRIBUTE_DATA info;
5019 time_t creation_time;
5025 memset(filep, 0,
sizeof(*filep));
5031 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5036 if ((
len > 0) && (path[
len - 1] !=
' ') && (path[
len - 1] !=
'.')
5037 && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
5038 filep->
size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5040 SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5041 info.ftLastWriteTime.dwHighDateTime);
5047 creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5048 info.ftCreationTime.dwHighDateTime);
5053 filep->
is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5065 wchar_t wbuf[UTF16_PATH_MAX];
5066 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5067 return DeleteFileW(wbuf) ? 0 : -1;
5074 wchar_t wbuf[UTF16_PATH_MAX];
5076 path_to_unicode(conn, path, wbuf,
ARRAY_SIZE(wbuf));
5077 return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5083#if defined(GCC_DIAGNOSTIC)
5085#pragma GCC diagnostic push
5086#pragma GCC diagnostic ignored "-Wunused-function"
5096 wchar_t wpath[UTF16_PATH_MAX];
5100 SetLastError(ERROR_BAD_ARGUMENTS);
5101 }
else if ((dir = (DIR *)
mg_malloc(
sizeof(*dir))) == NULL) {
5102 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5105 attrs = GetFileAttributesW(wpath);
5106 if ((wcslen(wpath) + 2 <
ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5107 && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5108 (
void)wcscat(wpath, L
"\\*");
5109 dir->handle = FindFirstFileW(wpath, &dir->info);
5110 dir->result.d_name[0] =
'\0';
5129 result = FindClose(dir->handle) ? 0 : -1;
5134 SetLastError(ERROR_BAD_ARGUMENTS);
5142static struct dirent *
5145 struct dirent *
result = 0;
5150 (
void)WideCharToMultiByte(CP_UTF8,
5152 dir->info.cFileName,
5159 if (!FindNextFileW(dir->handle, &dir->info)) {
5160 (
void)FindClose(dir->handle);
5165 SetLastError(ERROR_FILE_NOT_FOUND);
5168 SetLastError(ERROR_BAD_ARGUMENTS);
5175#if !defined(HAVE_POLL)
5187poll(
struct mg_pollfd *pfd,
unsigned int n,
int milliseconds)
5197 memset(&tv, 0,
sizeof(tv));
5198 tv.tv_sec = milliseconds / 1000;
5199 tv.tv_usec = (milliseconds % 1000) * 1000;
5204 for (i = 0; i <
n; i++) {
5205 if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
5206 if (pfd[i].events & POLLIN) {
5207 FD_SET(pfd[i].fd, &rset);
5209 if (pfd[i].events & POLLOUT) {
5210 FD_SET(pfd[i].fd, &wset);
5213 FD_SET(pfd[i].fd, &eset);
5217 if (pfd[i].fd > maxfd) {
5222 if ((
result = select((
int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
5223 for (i = 0; i <
n; i++) {
5224 if (FD_ISSET(pfd[i].fd, &rset)) {
5225 pfd[i].revents |= POLLIN;
5227 if (FD_ISSET(pfd[i].fd, &wset)) {
5228 pfd[i].revents |= POLLOUT;
5230 if (FD_ISSET(pfd[i].fd, &eset)) {
5231 pfd[i].revents |= POLLERR;
5248#if defined(GCC_DIAGNOSTIC)
5250#pragma GCC diagnostic pop
5262 (
void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5269#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5273 return ((_beginthread((
void(__cdecl *)(
void *))
f, USE_STACK_SIZE,
p)
5274 == ((uintptr_t)(-1L)))
5279 (_beginthread((
void(__cdecl *)(
void *))
f, 0,
p) == ((uintptr_t)(-1L)))
5290 pthread_t *threadidptr)
5293 HANDLE threadhandle;
5296 uip = _beginthreadex(NULL, 0,
f,
p, 0, NULL);
5297 threadhandle = (HANDLE)uip;
5298 if ((uip != 0) && (threadidptr != NULL)) {
5299 *threadidptr = threadhandle;
5315 dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5316 if (dwevent == WAIT_FAILED) {
5319 if (dwevent == WAIT_OBJECT_0) {
5320 CloseHandle(threadid);
5328#if !defined(NO_SSL_DL) && !defined(NO_SSL)
5332#if defined(GCC_DIAGNOSTIC)
5334#pragma GCC diagnostic push
5335#pragma GCC diagnostic ignored "-Wunused-function"
5341dlopen(
const char *dll_name,
int flags)
5343 wchar_t wbuf[UTF16_PATH_MAX];
5345 path_to_unicode(NULL, dll_name, wbuf,
ARRAY_SIZE(wbuf));
5346 return LoadLibraryW(wbuf);
5352dlclose(
void *handle)
5356 if (FreeLibrary((HMODULE)handle) != 0) {
5366#if defined(GCC_DIAGNOSTIC)
5368#pragma GCC diagnostic pop
5379kill(pid_t pid,
int sig_num)
5381 (
void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5382 (
void)CloseHandle((HANDLE)pid);
5387#if !defined(WNOHANG)
5393waitpid(pid_t pid,
int *status,
int flags)
5395 DWORD timeout = INFINITE;
5400 if ((flags | WNOHANG) == WNOHANG) {
5404 waitres = WaitForSingleObject((HANDLE)pid, timeout);
5405 if (waitres == WAIT_OBJECT_0) {
5408 if (waitres == WAIT_TIMEOUT) {
5416trim_trailing_whitespaces(
char *s)
5418 char *
e = s + strlen(s);
5419 while ((
e > s) && isspace((
unsigned char)
e[-1])) {
5434 unsigned char cgi_config_idx)
5438 char *interp_arg = 0;
5443 PROCESS_INFORMATION pi = {0};
5447 memset(&si, 0,
sizeof(si));
5450 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5451 si.wShowWindow = SW_HIDE;
5453 me = GetCurrentProcess();
5455 (HANDLE)_get_osfhandle(fdin[0]),
5460 DUPLICATE_SAME_ACCESS);
5462 (HANDLE)_get_osfhandle(fdout[1]),
5467 DUPLICATE_SAME_ACCESS);
5469 (HANDLE)_get_osfhandle(fderr[1]),
5474 DUPLICATE_SAME_ACCESS);
5479 SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5480 HANDLE_FLAG_INHERIT,
5482 SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5483 HANDLE_FLAG_INHERIT,
5485 SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5486 HANDLE_FLAG_INHERIT,
5492 if (interp != NULL) {
5500 buf[0] = buf[1] =
'\0';
5504 conn, &truncated, cmdline,
sizeof(cmdline),
"%s/%s", dir, prog);
5507 pi.hProcess = (pid_t)-1;
5517 buf[
sizeof(buf) - 1] =
'\0';
5520 if ((buf[0] ==
'#') && (buf[1] ==
'!')) {
5521 trim_trailing_whitespaces(buf + 2);
5528 GetFullPathNameA(dir,
sizeof(full_dir), full_dir, NULL);
5530 if (interp[0] !=
'\0') {
5532 if ((interp_arg != 0) && (interp_arg[0] != 0)) {
5537 "\"%s\" %s \"%s\\%s\"",
5547 "\"%s\" \"%s\\%s\"",
5564 pi.hProcess = (pid_t)-1;
5569 if (CreateProcessA(NULL,
5574 CREATE_NEW_PROCESS_GROUP,
5581 conn,
"%s: CreateProcess(%s): %ld", __func__, cmdline, (
long)
ERRNO);
5582 pi.hProcess = (pid_t)-1;
5587 (
void)CloseHandle(si.hStdOutput);
5588 (
void)CloseHandle(si.hStdError);
5589 (
void)CloseHandle(si.hStdInput);
5590 if (pi.hThread != NULL) {
5591 (
void)CloseHandle(pi.hThread);
5594 return (pid_t)pi.hProcess;
5602 unsigned long non_blocking = 0;
5603 return ioctlsocket(sock, (
long)FIONBIO, &non_blocking);
5610 unsigned long non_blocking = 1;
5611 return ioctlsocket(sock, (
long)FIONBIO, &non_blocking);
5618#if !defined(NO_FILESYSTEMS)
5628 memset(filep, 0,
sizeof(*filep));
5634 if (0 == stat(path, &st)) {
5635 filep->
size = (uint64_t)(st.st_size);
5651#if defined(__ZEPHYR__)
5656 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5660 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5672 pthread_t thread_id;
5673 pthread_attr_t
attr;
5676 (void)pthread_attr_init(&
attr);
5677 (void)pthread_attr_setdetachstate(&
attr, PTHREAD_CREATE_DETACHED);
5679#if defined(__ZEPHYR__)
5680 pthread_attr_setstack(&
attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
5681#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5684 (void)pthread_attr_setstacksize(&
attr, USE_STACK_SIZE);
5687 result = pthread_create(&thread_id, &
attr, func, param);
5688 pthread_attr_destroy(&
attr);
5698 pthread_t *threadidptr)
5700 pthread_t thread_id;
5701 pthread_attr_t
attr;
5704 (void)pthread_attr_init(&
attr);
5706#if defined(__ZEPHYR__)
5707 pthread_attr_setstack(&
attr,
5708 &civetweb_worker_stacks[zephyr_worker_stack_index++],
5710#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5713 (void)pthread_attr_setstacksize(&
attr, USE_STACK_SIZE);
5716 result = pthread_create(&thread_id, &
attr, func, param);
5717 pthread_attr_destroy(&
attr);
5718 if ((
result == 0) && (threadidptr != NULL)) {
5719 *threadidptr = thread_id;
5731 result = pthread_join(threadid, NULL);
5746 unsigned char cgi_config_idx)
5753 if ((pid = fork()) == -1) {
5756 }
else if (pid != 0) {
5764 if (chdir(dir) != 0) {
5766 conn,
"%s: chdir(%s): %s", __func__, dir, strerror(
ERRNO));
5767 }
else if (dup2(fdin[0], 0) == -1) {
5769 "%s: dup2(%d, 0): %s",
5773 }
else if (dup2(fdout[1], 1) == -1) {
5775 "%s: dup2(%d, 1): %s",
5779 }
else if (dup2(fderr[1], 2) == -1) {
5781 "%s: dup2(%d, 2): %s",
5786 struct sigaction sa;
5791 (void)close(fdin[0]);
5792 (void)close(fdout[1]);
5793 (void)close(fderr[1]);
5796 (void)close(fdin[1]);
5797 (void)close(fdout[0]);
5798 (void)close(fderr[0]);
5805 memset(&sa, 0,
sizeof(sa));
5806 sa.sa_handler = SIG_DFL;
5807 sigaction(SIGCHLD, &sa, NULL);
5810 if (interp == NULL) {
5812 (void)execle(prog, prog, NULL, envp);
5814 "%s: execle(%s): %s",
5820 const char *interp_args =
5824 if ((interp_args != NULL) && (interp_args[0] != 0)) {
5825 (void)execle(interp, interp, interp_args, prog, NULL, envp);
5827 (void)execle(interp, interp, prog, NULL, envp);
5830 "%s: execle(%s %s): %s",
5848 int flags = fcntl(sock, F_GETFL, 0);
5853 if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
5862 int flags = fcntl(sock, F_GETFL, 0);
5867 if (fcntl(sock, F_SETFL, flags & (~(
int)(O_NONBLOCK))) < 0) {
5881 static uint64_t lfsr = 0;
5882 static uint64_t lcg = 0;
5893 | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
5895 lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
5903 return (lfsr ^ lcg ^ now);
5918 int check_pollerr = 0;
5919 if ((
n == 1) && ((pfd[0].events & POLLERR) == 0)) {
5921 pfd[0].events |= POLLERR;
5933 if ((milliseconds >= 0) && (milliseconds < ms_now)) {
5934 ms_now = milliseconds;
5937 result = poll(pfd,
n, ms_now);
5942 && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
5951 if (milliseconds > 0) {
5952 milliseconds -= ms_now;
5955 }
while (milliseconds > 0);
5978 uint64_t start = 0, now = 0, timeout_ns = 0;
5985 typedef size_t len_t;
5991 timeout_ns = (uint64_t)(timeout * 1.0E9);
5998#if defined(NO_SSL) && !defined(USE_MBEDTLS)
6008#if defined(USE_MBEDTLS)
6010 n = mbed_ssl_write(ssl, (
const unsigned char *)buf,
len);
6012 if ((
n == MBEDTLS_ERR_SSL_WANT_READ)
6013 || (
n == MBEDTLS_ERR_SSL_WANT_WRITE)