Path: blob/trunk/third_party/cpp/civetweb/civetweb.c
2868 views
/* Copyright (c) 2013-2018 the Civetweb developers1* Copyright (c) 2004-2013 Sergey Lyubka2*3* Permission is hereby granted, free of charge, to any person obtaining a copy4* of this software and associated documentation files (the "Software"), to deal5* in the Software without restriction, including without limitation the rights6* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7* copies of the Software, and to permit persons to whom the Software is8* furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice shall be included in11* all copies or substantial portions of the Software.12*13* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN19* THE SOFTWARE.20*/2122#if defined(__GNUC__) || defined(__MINGW32__)23#define GCC_VERSION \24(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)25#if GCC_VERSION >= 4050026/* gcc diagnostic pragmas available */27#define GCC_DIAGNOSTIC28#endif29#endif3031#if defined(GCC_DIAGNOSTIC)32/* Disable unused macros warnings - not all defines are required33* for all systems and all compilers. */34#pragma GCC diagnostic ignored "-Wunused-macros"35/* A padding warning is just plain useless */36#pragma GCC diagnostic ignored "-Wpadded"37#endif3839#if defined(__clang__) /* GCC does not (yet) support this pragma */40/* We must set some flags for the headers we include. These flags41* are reserved ids according to C99, so we need to disable a42* warning for that. */43#pragma GCC diagnostic push44#pragma GCC diagnostic ignored "-Wreserved-id-macro"45#endif4647#if defined(_WIN32)48#if !defined(_CRT_SECURE_NO_WARNINGS)49#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */50#endif51#if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */52#define _WIN32_WINNT 0x050153#endif54#else55#if !defined(_GNU_SOURCE)56#define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */57#endif58#if defined(__linux__) && !defined(_XOPEN_SOURCE)59#define _XOPEN_SOURCE 600 /* For flockfile() on Linux */60#endif61#if !defined(_LARGEFILE_SOURCE)62#define _LARGEFILE_SOURCE /* For fseeko(), ftello() */63#endif64#if !defined(_FILE_OFFSET_BITS)65#define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */66#endif67#if !defined(__STDC_FORMAT_MACROS)68#define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */69#endif70#if !defined(__STDC_LIMIT_MACROS)71#define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */72#endif73#if !defined(_DARWIN_UNLIMITED_SELECT)74#define _DARWIN_UNLIMITED_SELECT75#endif76#if defined(__sun)77#define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */78#define __inline inline /* not recognized on older compiler versions */79#endif80#endif8182#if defined(__clang__)83/* Enable reserved-id-macro warning again. */84#pragma GCC diagnostic pop85#endif868788#if defined(USE_LUA)89#define USE_TIMERS90#endif9192#if defined(_MSC_VER)93/* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */94#pragma warning(disable : 4306)95/* conditional expression is constant: introduced by FD_SET(..) */96#pragma warning(disable : 4127)97/* non-constant aggregate initializer: issued due to missing C99 support */98#pragma warning(disable : 4204)99/* padding added after data member */100#pragma warning(disable : 4820)101/* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */102#pragma warning(disable : 4668)103/* no function prototype given: converting '()' to '(void)' */104#pragma warning(disable : 4255)105/* function has been selected for automatic inline expansion */106#pragma warning(disable : 4711)107#endif108109110/* This code uses static_assert to check some conditions.111* Unfortunately some compilers still do not support it, so we have a112* replacement function here. */113#if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L114#define mg_static_assert _Static_assert115#elif defined(__cplusplus) && __cplusplus >= 201103L116#define mg_static_assert static_assert117#else118char static_assert_replacement[1];119#define mg_static_assert(cond, txt) \120extern char static_assert_replacement[(cond) ? 1 : -1]121#endif122123mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,124"int data type size check");125mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,126"pointer data type size check");127mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");128129130/* Alternative queue is well tested and should be the new default */131#if defined(NO_ALTERNATIVE_QUEUE)132#if defined(ALTERNATIVE_QUEUE)133#error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"134#endif135#else136#define ALTERNATIVE_QUEUE137#endif138139140/* DTL -- including winsock2.h works better if lean and mean */141#if !defined(WIN32_LEAN_AND_MEAN)142#define WIN32_LEAN_AND_MEAN143#endif144145#if defined(__SYMBIAN32__)146/* According to https://en.wikipedia.org/wiki/Symbian#History,147* Symbian is no longer maintained since 2014-01-01.148* Recent versions of CivetWeb are no longer tested for Symbian.149* It makes no sense, to support an abandoned operating system.150*/151#error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."152#define NO_SSL /* SSL is not supported */153#define NO_CGI /* CGI is not supported */154#define PATH_MAX FILENAME_MAX155#endif /* __SYMBIAN32__ */156157158#if !defined(CIVETWEB_HEADER_INCLUDED)159/* Include the header file here, so the CivetWeb interface is defined for the160* entire implementation, including the following forward definitions. */161#include "civetweb.h"162#endif163164#if !defined(DEBUG_TRACE)165#if defined(DEBUG)166static void DEBUG_TRACE_FUNC(const char *func,167unsigned line,168PRINTF_FORMAT_STRING(const char *fmt),169...) PRINTF_ARGS(3, 4);170171#define DEBUG_TRACE(fmt, ...) \172DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)173174#define NEED_DEBUG_TRACE_FUNC175176#else177#define DEBUG_TRACE(fmt, ...) \178do { \179} while (0)180#endif /* DEBUG */181#endif /* DEBUG_TRACE */182183184#if !defined(DEBUG_ASSERT)185#if defined(DEBUG)186#define DEBUG_ASSERT(cond) \187do { \188if (!(cond)) { \189DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \190exit(2); /* Exit with error */ \191} \192} while (0)193#else194#define DEBUG_ASSERT(cond)195#endif /* DEBUG */196#endif197198199#if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)200void __cyg_profile_func_enter(void *this_fn, void *call_site)201__attribute__((no_instrument_function));202203void __cyg_profile_func_exit(void *this_fn, void *call_site)204__attribute__((no_instrument_function));205206void207__cyg_profile_func_enter(void *this_fn, void *call_site)208{209if ((void *)this_fn != (void *)printf) {210printf("E %p %p\n", this_fn, call_site);211}212}213214void215__cyg_profile_func_exit(void *this_fn, void *call_site)216{217if ((void *)this_fn != (void *)printf) {218printf("X %p %p\n", this_fn, call_site);219}220}221#endif222223224#if !defined(IGNORE_UNUSED_RESULT)225#define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))226#endif227228229#if defined(__GNUC__) || defined(__MINGW32__)230231/* GCC unused function attribute seems fundamentally broken.232* Several attempts to tell the compiler "THIS FUNCTION MAY BE USED233* OR UNUSED" for individual functions failed.234* Either the compiler creates an "unused-function" warning if a235* function is not marked with __attribute__((unused)).236* On the other hand, if the function is marked with this attribute,237* but is used, the compiler raises a completely idiotic238* "used-but-marked-unused" warning - and239* #pragma GCC diagnostic ignored "-Wused-but-marked-unused"240* raises error: unknown option after "#pragma GCC diagnostic".241* Disable this warning completely, until the GCC guys sober up242* again.243*/244245#pragma GCC diagnostic ignored "-Wunused-function"246247#define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */248249#else250#define FUNCTION_MAY_BE_UNUSED251#endif252253254/* Some ANSI #includes are not available on Windows CE */255#if !defined(_WIN32_WCE)256#include <errno.h>257#include <fcntl.h>258#include <signal.h>259#include <sys/stat.h>260#include <sys/types.h>261#endif /* !_WIN32_WCE */262263264#if defined(__clang__)265/* When using -Weverything, clang does not accept it's own headers266* in a release build configuration. Disable what is too much in267* -Weverything. */268#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"269#endif270271#if defined(__GNUC__) || defined(__MINGW32__)272/* Who on earth came to the conclusion, using __DATE__ should rise273* an "expansion of date or time macro is not reproducible"274* warning. That's exactly what was intended by using this macro.275* Just disable this nonsense warning. */276277/* And disabling them does not work either:278* #pragma clang diagnostic ignored "-Wno-error=date-time"279* #pragma clang diagnostic ignored "-Wdate-time"280* So we just have to disable ALL warnings for some lines281* of code.282* This seems to be a known GCC bug, not resolved since 2012:283* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431284*/285#endif286287288#if defined(__MACH__) /* Apple OSX section */289290#if defined(__clang__)291#if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))292/* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */293#pragma clang diagnostic ignored "-Wno-reserved-id-macro"294#pragma clang diagnostic ignored "-Wno-keyword-macro"295#endif296#endif297298#define CLOCK_MONOTONIC (1)299#define CLOCK_REALTIME (2)300301#include <mach/clock.h>302#include <mach/mach.h>303#include <mach/mach_time.h>304#include <sys/errno.h>305#include <sys/time.h>306307/* clock_gettime is not implemented on OSX prior to 10.12 */308static int309_civet_clock_gettime(int clk_id, struct timespec *t)310{311memset(t, 0, sizeof(*t));312if (clk_id == CLOCK_REALTIME) {313struct timeval now;314int rv = gettimeofday(&now, NULL);315if (rv) {316return rv;317}318t->tv_sec = now.tv_sec;319t->tv_nsec = now.tv_usec * 1000;320return 0;321322} else if (clk_id == CLOCK_MONOTONIC) {323static uint64_t clock_start_time = 0;324static mach_timebase_info_data_t timebase_ifo = {0, 0};325326uint64_t now = mach_absolute_time();327328if (clock_start_time == 0) {329kern_return_t mach_status = mach_timebase_info(&timebase_ifo);330DEBUG_ASSERT(mach_status == KERN_SUCCESS);331332/* appease "unused variable" warning for release builds */333(void)mach_status;334335clock_start_time = now;336}337338now = (uint64_t)((double)(now - clock_start_time)339* (double)timebase_ifo.numer340/ (double)timebase_ifo.denom);341342t->tv_sec = now / 1000000000;343t->tv_nsec = now % 1000000000;344return 0;345}346return -1; /* EINVAL - Clock ID is unknown */347}348349/* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */350#if defined(__CLOCK_AVAILABILITY)351/* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be352* declared but it may be NULL at runtime. So we need to check before using353* it. */354static int355_civet_safe_clock_gettime(int clk_id, struct timespec *t)356{357if (clock_gettime) {358return clock_gettime(clk_id, t);359}360return _civet_clock_gettime(clk_id, t);361}362#define clock_gettime _civet_safe_clock_gettime363#else364#define clock_gettime _civet_clock_gettime365#endif366367#endif368369370#include <ctype.h>371#include <limits.h>372#include <stdarg.h>373#include <stddef.h>374#include <stdint.h>375#include <stdio.h>376#include <stdlib.h>377#include <string.h>378#include <time.h>379380/********************************************************************/381/* CivetWeb configuration defines */382/********************************************************************/383384/* Maximum number of threads that can be configured.385* The number of threads actually created depends on the "num_threads"386* configuration parameter, but this is the upper limit. */387#if !defined(MAX_WORKER_THREADS)388#define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */389#endif390391/* Timeout interval for select/poll calls.392* The timeouts depend on "*_timeout_ms" configuration values, but long393* timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.394* This reduces the time required to stop the server. */395#if !defined(SOCKET_TIMEOUT_QUANTUM)396#define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */397#endif398399/* Do not try to compress files smaller than this limit. */400#if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)401#define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */402#endif403404#if !defined(PASSWORDS_FILE_NAME)405#define PASSWORDS_FILE_NAME ".htpasswd"406#endif407408/* Initial buffer size for all CGI environment variables. In case there is409* not enough space, another block is allocated. */410#if !defined(CGI_ENVIRONMENT_SIZE)411#define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */412#endif413414/* Maximum number of environment variables. */415#if !defined(MAX_CGI_ENVIR_VARS)416#define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */417#endif418419/* General purpose buffer size. */420#if !defined(MG_BUF_LEN) /* in bytes */421#define MG_BUF_LEN (1024 * 8)422#endif423424/* Size of the accepted socket queue (in case the old queue implementation425* is used). */426#if !defined(MGSQLEN)427#define MGSQLEN (20) /* count */428#endif429430431/********************************************************************/432433/* Helper makros */434#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))435436/* Standard defines */437#if !defined(INT64_MAX)438#define INT64_MAX (9223372036854775807)439#endif440441#define SHUTDOWN_RD (0)442#define SHUTDOWN_WR (1)443#define SHUTDOWN_BOTH (2)444445mg_static_assert(MAX_WORKER_THREADS >= 1,446"worker threads must be a positive number");447448mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,449"size_t data type size check");450451#if defined(_WIN32) /* WINDOWS include block */452#include <windows.h>453#include <winsock2.h> /* DTL add for SO_EXCLUSIVE */454#include <ws2tcpip.h>455456typedef const char *SOCK_OPT_TYPE;457458#if !defined(PATH_MAX)459#define W_PATH_MAX (MAX_PATH)460/* at most three UTF-8 chars per wchar_t */461#define PATH_MAX (W_PATH_MAX * 3)462#else463#define W_PATH_MAX ((PATH_MAX + 2) / 3)464#endif465466mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");467468#if !defined(_IN_PORT_T)469#if !defined(in_port_t)470#define in_port_t u_short471#endif472#endif473474#if !defined(_WIN32_WCE)475#include <direct.h>476#include <io.h>477#include <process.h>478#else /* _WIN32_WCE */479#define NO_CGI /* WinCE has no pipes */480#define NO_POPEN /* WinCE has no popen */481482typedef long off_t;483484#define errno ((int)(GetLastError()))485#define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))486#endif /* _WIN32_WCE */487488#define MAKEUQUAD(lo, hi) \489((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))490#define RATE_DIFF (10000000) /* 100 nsecs */491#define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))492#define SYS2UNIX_TIME(lo, hi) \493((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))494495/* Visual Studio 6 does not know __func__ or __FUNCTION__496* The rest of MS compilers use __FUNCTION__, not C99 __func__497* Also use _strtoui64 on modern M$ compilers */498#if defined(_MSC_VER)499#if (_MSC_VER < 1300)500#define STRX(x) #x501#define STR(x) STRX(x)502#define __func__ __FILE__ ":" STR(__LINE__)503#define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))504#define strtoll(x, y, z) (_atoi64(x))505#else506#define __func__ __FUNCTION__507#define strtoull(x, y, z) (_strtoui64(x, y, z))508#define strtoll(x, y, z) (_strtoi64(x, y, z))509#endif510#endif /* _MSC_VER */511512#define ERRNO ((int)(GetLastError()))513#define NO_SOCKLEN_T514515#if defined(_WIN64) || defined(__MINGW64__)516#if !defined(SSL_LIB)517#define SSL_LIB "ssleay64.dll"518#endif519#if !defined(CRYPTO_LIB)520#define CRYPTO_LIB "libeay64.dll"521#endif522#else523#if !defined(SSL_LIB)524#define SSL_LIB "ssleay32.dll"525#endif526#if !defined(CRYPTO_LIB)527#define CRYPTO_LIB "libeay32.dll"528#endif529#endif530531#define O_NONBLOCK (0)532#if !defined(W_OK)533#define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */534#endif535#if !defined(EWOULDBLOCK)536#define EWOULDBLOCK WSAEWOULDBLOCK537#endif /* !EWOULDBLOCK */538#define _POSIX_539#define INT64_FMT "I64d"540#define UINT64_FMT "I64u"541542#define WINCDECL __cdecl543#define vsnprintf_impl _vsnprintf544#define access _access545#define mg_sleep(x) (Sleep(x))546547#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)548#if !defined(popen)549#define popen(x, y) (_popen(x, y))550#endif551#if !defined(pclose)552#define pclose(x) (_pclose(x))553#endif554#define close(x) (_close(x))555#define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))556#define RTLD_LAZY (0)557#define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)558#define fdopen(x, y) (_fdopen((x), (y)))559#define write(x, y, z) (_write((x), (y), (unsigned)z))560#define read(x, y, z) (_read((x), (y), (unsigned)z))561#define flockfile(x) (EnterCriticalSection(&global_log_file_lock))562#define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))563#define sleep(x) (Sleep((x)*1000))564#define rmdir(x) (_rmdir(x))565#if defined(_WIN64) || !defined(__MINGW32__)566/* Only MinGW 32 bit is missing this function */567#define timegm(x) (_mkgmtime(x))568#else569time_t timegm(struct tm *tm);570#define NEED_TIMEGM571#endif572573574#if !defined(fileno)575#define fileno(x) (_fileno(x))576#endif /* !fileno MINGW #defines fileno */577578typedef HANDLE pthread_mutex_t;579typedef DWORD pthread_key_t;580typedef HANDLE pthread_t;581typedef struct {582CRITICAL_SECTION threadIdSec;583struct mg_workerTLS *waiting_thread; /* The chain of threads */584} pthread_cond_t;585586#if !defined(__clockid_t_defined)587typedef DWORD clockid_t;588#endif589#if !defined(CLOCK_MONOTONIC)590#define CLOCK_MONOTONIC (1)591#endif592#if !defined(CLOCK_REALTIME)593#define CLOCK_REALTIME (2)594#endif595#if !defined(CLOCK_THREAD)596#define CLOCK_THREAD (3)597#endif598#if !defined(CLOCK_PROCESS)599#define CLOCK_PROCESS (4)600#endif601602603#if defined(_MSC_VER) && (_MSC_VER >= 1900)604#define _TIMESPEC_DEFINED605#endif606#if !defined(_TIMESPEC_DEFINED)607struct timespec {608time_t tv_sec; /* seconds */609long tv_nsec; /* nanoseconds */610};611#endif612613#if !defined(WIN_PTHREADS_TIME_H)614#define MUST_IMPLEMENT_CLOCK_GETTIME615#endif616617#if defined(MUST_IMPLEMENT_CLOCK_GETTIME)618#define clock_gettime mg_clock_gettime619static int620clock_gettime(clockid_t clk_id, struct timespec *tp)621{622FILETIME ft;623ULARGE_INTEGER li, li2;624BOOL ok = FALSE;625double d;626static double perfcnt_per_sec = 0.0;627static BOOL initialized = FALSE;628629if (!initialized) {630QueryPerformanceFrequency((LARGE_INTEGER *)&li);631perfcnt_per_sec = 1.0 / li.QuadPart;632initialized = TRUE;633}634635if (tp) {636memset(tp, 0, sizeof(*tp));637638if (clk_id == CLOCK_REALTIME) {639640/* BEGIN: CLOCK_REALTIME = wall clock (date and time) */641GetSystemTimeAsFileTime(&ft);642li.LowPart = ft.dwLowDateTime;643li.HighPart = ft.dwHighDateTime;644li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */645tp->tv_sec = (time_t)(li.QuadPart / 10000000);646tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;647ok = TRUE;648/* END: CLOCK_REALTIME */649650} else if (clk_id == CLOCK_MONOTONIC) {651652/* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */653QueryPerformanceCounter((LARGE_INTEGER *)&li);654d = li.QuadPart * perfcnt_per_sec;655tp->tv_sec = (time_t)d;656d -= (double)tp->tv_sec;657tp->tv_nsec = (long)(d * 1.0E9);658ok = TRUE;659/* END: CLOCK_MONOTONIC */660661} else if (clk_id == CLOCK_THREAD) {662663/* BEGIN: CLOCK_THREAD = CPU usage of thread */664FILETIME t_create, t_exit, t_kernel, t_user;665if (GetThreadTimes(GetCurrentThread(),666&t_create,667&t_exit,668&t_kernel,669&t_user)) {670li.LowPart = t_user.dwLowDateTime;671li.HighPart = t_user.dwHighDateTime;672li2.LowPart = t_kernel.dwLowDateTime;673li2.HighPart = t_kernel.dwHighDateTime;674li.QuadPart += li2.QuadPart;675tp->tv_sec = (time_t)(li.QuadPart / 10000000);676tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;677ok = TRUE;678}679/* END: CLOCK_THREAD */680681} else if (clk_id == CLOCK_PROCESS) {682683/* BEGIN: CLOCK_PROCESS = CPU usage of process */684FILETIME t_create, t_exit, t_kernel, t_user;685if (GetProcessTimes(GetCurrentProcess(),686&t_create,687&t_exit,688&t_kernel,689&t_user)) {690li.LowPart = t_user.dwLowDateTime;691li.HighPart = t_user.dwHighDateTime;692li2.LowPart = t_kernel.dwLowDateTime;693li2.HighPart = t_kernel.dwHighDateTime;694li.QuadPart += li2.QuadPart;695tp->tv_sec = (time_t)(li.QuadPart / 10000000);696tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;697ok = TRUE;698}699/* END: CLOCK_PROCESS */700701} else {702703/* BEGIN: unknown clock */704/* ok = FALSE; already set by init */705/* END: unknown clock */706}707}708709return ok ? 0 : -1;710}711#endif712713714#define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */715716static int pthread_mutex_lock(pthread_mutex_t *);717static int pthread_mutex_unlock(pthread_mutex_t *);718static void path_to_unicode(const struct mg_connection *conn,719const char *path,720wchar_t *wbuf,721size_t wbuf_len);722723/* All file operations need to be rewritten to solve #246. */724725struct mg_file;726727static const char *728mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);729730731/* POSIX dirent interface */732struct dirent {733char d_name[PATH_MAX];734};735736typedef struct DIR {737HANDLE handle;738WIN32_FIND_DATAW info;739struct dirent result;740} DIR;741742#if defined(_WIN32)743#if !defined(HAVE_POLL)744struct pollfd {745SOCKET fd;746short events;747short revents;748};749#endif750#endif751752/* Mark required libraries */753#if defined(_MSC_VER)754#pragma comment(lib, "Ws2_32.lib")755#endif756757#else /* defined(_WIN32) - WINDOWS vs UNIX include block */758759#include <arpa/inet.h>760#include <inttypes.h>761#include <netdb.h>762#include <netinet/in.h>763#include <netinet/tcp.h>764#include <stdint.h>765#include <sys/poll.h>766#include <sys/socket.h>767#include <sys/time.h>768#include <sys/utsname.h>769#include <sys/wait.h>770typedef const void *SOCK_OPT_TYPE;771772#if defined(ANDROID)773typedef unsigned short int in_port_t;774#endif775776#include <dirent.h>777#include <grp.h>778#include <pwd.h>779#include <unistd.h>780#define vsnprintf_impl vsnprintf781782#if !defined(NO_SSL_DL) && !defined(NO_SSL)783#include <dlfcn.h>784#endif785#include <pthread.h>786#if defined(__MACH__)787#define SSL_LIB "libssl.dylib"788#define CRYPTO_LIB "libcrypto.dylib"789#else790#if !defined(SSL_LIB)791#define SSL_LIB "libssl.so"792#endif793#if !defined(CRYPTO_LIB)794#define CRYPTO_LIB "libcrypto.so"795#endif796#endif797#if !defined(O_BINARY)798#define O_BINARY (0)799#endif /* O_BINARY */800#define closesocket(a) (close(a))801#define mg_mkdir(conn, path, mode) (mkdir(path, mode))802#define mg_remove(conn, x) (remove(x))803#define mg_sleep(x) (usleep((x)*1000))804#define mg_opendir(conn, x) (opendir(x))805#define mg_closedir(x) (closedir(x))806#define mg_readdir(x) (readdir(x))807#define ERRNO (errno)808#define INVALID_SOCKET (-1)809#define INT64_FMT PRId64810#define UINT64_FMT PRIu64811typedef int SOCKET;812#define WINCDECL813814#if defined(__hpux)815/* HPUX 11 does not have monotonic, fall back to realtime */816#if !defined(CLOCK_MONOTONIC)817#define CLOCK_MONOTONIC CLOCK_REALTIME818#endif819820/* HPUX defines socklen_t incorrectly as size_t which is 64bit on821* Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED822* the prototypes use int* rather than socklen_t* which matches the823* actual library expectation. When called with the wrong size arg824* accept() returns a zero client inet addr and check_acl() always825* fails. Since socklen_t is widely used below, just force replace826* their typedef with int. - DTL827*/828#define socklen_t int829#endif /* hpux */830831#endif /* defined(_WIN32) - WINDOWS vs UNIX include block */832833/* Maximum queue length for pending connections. This value is passed as834* parameter to the "listen" socket call. */835#if !defined(SOMAXCONN)836/* This symbol may be defined in winsock2.h so this must after that include */837#define SOMAXCONN (100) /* in pending connections (count) */838#endif839840/* In case our C library is missing "timegm", provide an implementation */841#if defined(NEED_TIMEGM)842static inline int843is_leap(int y)844{845return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;846}847848static inline int849count_leap(int y)850{851return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;852}853854time_t855timegm(struct tm *tm)856{857static const unsigned short ydays[] = {8580, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};859int year = tm->tm_year + 1900;860int mon = tm->tm_mon;861int mday = tm->tm_mday - 1;862int hour = tm->tm_hour;863int min = tm->tm_min;864int sec = tm->tm_sec;865866if (year < 1970 || mon < 0 || mon > 11 || mday < 0867|| (mday >= ydays[mon + 1] - ydays[mon]868+ (mon == 1 && is_leap(year) ? 1 : 0))869|| hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)870return -1;871872time_t res = year - 1970;873res *= 365;874res += mday;875res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);876res += count_leap(year);877878res *= 24;879res += hour;880res *= 60;881res += min;882res *= 60;883res += sec;884return res;885}886#endif /* NEED_TIMEGM */887888889/* va_copy should always be a macro, C99 and C++11 - DTL */890#if !defined(va_copy)891#define va_copy(x, y) ((x) = (y))892#endif893894895#if defined(_WIN32)896/* Create substitutes for POSIX functions in Win32. */897898#if defined(GCC_DIAGNOSTIC)899/* Show no warning in case system functions are not used. */900#pragma GCC diagnostic push901#pragma GCC diagnostic ignored "-Wunused-function"902#endif903904905static CRITICAL_SECTION global_log_file_lock;906907FUNCTION_MAY_BE_UNUSED908static DWORD909pthread_self(void)910{911return GetCurrentThreadId();912}913914915FUNCTION_MAY_BE_UNUSED916static int917pthread_key_create(918pthread_key_t *key,919void (*_ignored)(void *) /* destructor not supported for Windows */920)921{922(void)_ignored;923924if ((key != 0)) {925*key = TlsAlloc();926return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;927}928return -2;929}930931932FUNCTION_MAY_BE_UNUSED933static int934pthread_key_delete(pthread_key_t key)935{936return TlsFree(key) ? 0 : 1;937}938939940FUNCTION_MAY_BE_UNUSED941static int942pthread_setspecific(pthread_key_t key, void *value)943{944return TlsSetValue(key, value) ? 0 : 1;945}946947948FUNCTION_MAY_BE_UNUSED949static void *950pthread_getspecific(pthread_key_t key)951{952return TlsGetValue(key);953}954955#if defined(GCC_DIAGNOSTIC)956/* Enable unused function warning again */957#pragma GCC diagnostic pop958#endif959960static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;961#else962static pthread_mutexattr_t pthread_mutex_attr;963#endif /* _WIN32 */964965966#if defined(_WIN32_WCE)967/* Create substitutes for POSIX functions in Win32. */968969#if defined(GCC_DIAGNOSTIC)970/* Show no warning in case system functions are not used. */971#pragma GCC diagnostic push972#pragma GCC diagnostic ignored "-Wunused-function"973#endif974975976FUNCTION_MAY_BE_UNUSED977static time_t978time(time_t *ptime)979{980time_t t;981SYSTEMTIME st;982FILETIME ft;983984GetSystemTime(&st);985SystemTimeToFileTime(&st, &ft);986t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);987988if (ptime != NULL) {989*ptime = t;990}991992return t;993}994995996FUNCTION_MAY_BE_UNUSED997static struct tm *998localtime_s(const time_t *ptime, struct tm *ptm)999{1000int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;1001FILETIME ft, lft;1002SYSTEMTIME st;1003TIME_ZONE_INFORMATION tzinfo;10041005if (ptm == NULL) {1006return NULL;1007}10081009*(int64_t *)&ft = t;1010FileTimeToLocalFileTime(&ft, &lft);1011FileTimeToSystemTime(&lft, &st);1012ptm->tm_year = st.wYear - 1900;1013ptm->tm_mon = st.wMonth - 1;1014ptm->tm_wday = st.wDayOfWeek;1015ptm->tm_mday = st.wDay;1016ptm->tm_hour = st.wHour;1017ptm->tm_min = st.wMinute;1018ptm->tm_sec = st.wSecond;1019ptm->tm_yday = 0; /* hope nobody uses this */1020ptm->tm_isdst =1021(GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;10221023return ptm;1024}102510261027FUNCTION_MAY_BE_UNUSED1028static struct tm *1029gmtime_s(const time_t *ptime, struct tm *ptm)1030{1031/* FIXME(lsm): fix this. */1032return localtime_s(ptime, ptm);1033}103410351036static int mg_atomic_inc(volatile int *addr);1037static struct tm tm_array[MAX_WORKER_THREADS];1038static int tm_index = 0;103910401041FUNCTION_MAY_BE_UNUSED1042static struct tm *1043localtime(const time_t *ptime)1044{1045int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));1046return localtime_s(ptime, tm_array + i);1047}104810491050FUNCTION_MAY_BE_UNUSED1051static struct tm *1052gmtime(const time_t *ptime)1053{1054int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);1055return gmtime_s(ptime, tm_array + i);1056}105710581059FUNCTION_MAY_BE_UNUSED1060static size_t1061strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)1062{1063/* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()1064* for WinCE"); */1065return 0;1066}10671068#define _beginthreadex(psec, stack, func, prm, flags, ptid) \1069(uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)10701071#define remove(f) mg_remove(NULL, f)107210731074FUNCTION_MAY_BE_UNUSED1075static int1076rename(const char *a, const char *b)1077{1078wchar_t wa[W_PATH_MAX];1079wchar_t wb[W_PATH_MAX];1080path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));1081path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));10821083return MoveFileW(wa, wb) ? 0 : -1;1084}108510861087struct stat {1088int64_t st_size;1089time_t st_mtime;1090};109110921093FUNCTION_MAY_BE_UNUSED1094static int1095stat(const char *name, struct stat *st)1096{1097wchar_t wbuf[W_PATH_MAX];1098WIN32_FILE_ATTRIBUTE_DATA attr;1099time_t creation_time, write_time;11001101path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));1102memset(&attr, 0, sizeof(attr));11031104GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);1105st->st_size =1106(((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;11071108write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,1109attr.ftLastWriteTime.dwHighDateTime);1110creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,1111attr.ftCreationTime.dwHighDateTime);11121113if (creation_time > write_time) {1114st->st_mtime = creation_time;1115} else {1116st->st_mtime = write_time;1117}1118return 0;1119}11201121#define access(x, a) 1 /* not required anyway */11221123/* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */1124/* Values from errno.h in Windows SDK (Visual Studio). */1125#define EEXIST 171126#define EACCES 131127#define ENOENT 211281129#if defined(GCC_DIAGNOSTIC)1130/* Enable unused function warning again */1131#pragma GCC diagnostic pop1132#endif11331134#endif /* defined(_WIN32_WCE) */113511361137#if defined(GCC_DIAGNOSTIC)1138/* Show no warning in case system functions are not used. */1139#pragma GCC diagnostic push1140#pragma GCC diagnostic ignored "-Wunused-function"1141#endif /* defined(GCC_DIAGNOSTIC) */1142#if defined(__clang__)1143/* Show no warning in case system functions are not used. */1144#pragma clang diagnostic push1145#pragma clang diagnostic ignored "-Wunused-function"1146#endif11471148static pthread_mutex_t global_lock_mutex;114911501151#if defined(_WIN32)1152/* Forward declaration for Windows */1153FUNCTION_MAY_BE_UNUSED1154static int pthread_mutex_lock(pthread_mutex_t *mutex);11551156FUNCTION_MAY_BE_UNUSED1157static int pthread_mutex_unlock(pthread_mutex_t *mutex);1158#endif115911601161FUNCTION_MAY_BE_UNUSED1162static void1163mg_global_lock(void)1164{1165(void)pthread_mutex_lock(&global_lock_mutex);1166}116711681169FUNCTION_MAY_BE_UNUSED1170static void1171mg_global_unlock(void)1172{1173(void)pthread_mutex_unlock(&global_lock_mutex);1174}117511761177FUNCTION_MAY_BE_UNUSED1178static int1179mg_atomic_inc(volatile int *addr)1180{1181int ret;1182#if defined(_WIN32) && !defined(NO_ATOMICS)1183/* Depending on the SDK, this function uses either1184* (volatile unsigned int *) or (volatile LONG *),1185* so whatever you use, the other SDK is likely to raise a warning. */1186ret = InterlockedIncrement((volatile long *)addr);1187#elif defined(__GNUC__) \1188&& ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \1189&& !defined(NO_ATOMICS)1190ret = __sync_add_and_fetch(addr, 1);1191#else1192mg_global_lock();1193ret = (++(*addr));1194mg_global_unlock();1195#endif1196return ret;1197}119811991200FUNCTION_MAY_BE_UNUSED1201static int1202mg_atomic_dec(volatile int *addr)1203{1204int ret;1205#if defined(_WIN32) && !defined(NO_ATOMICS)1206/* Depending on the SDK, this function uses either1207* (volatile unsigned int *) or (volatile LONG *),1208* so whatever you use, the other SDK is likely to raise a warning. */1209ret = InterlockedDecrement((volatile long *)addr);1210#elif defined(__GNUC__) \1211&& ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \1212&& !defined(NO_ATOMICS)1213ret = __sync_sub_and_fetch(addr, 1);1214#else1215mg_global_lock();1216ret = (--(*addr));1217mg_global_unlock();1218#endif1219return ret;1220}122112221223#if defined(USE_SERVER_STATS)1224static int64_t1225mg_atomic_add(volatile int64_t *addr, int64_t value)1226{1227int64_t ret;1228#if defined(_WIN64) && !defined(NO_ATOMICS)1229ret = InterlockedAdd64(addr, value);1230#elif defined(__GNUC__) \1231&& ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \1232&& !defined(NO_ATOMICS)1233ret = __sync_add_and_fetch(addr, value);1234#else1235mg_global_lock();1236*addr += value;1237ret = (*addr);1238mg_global_unlock();1239#endif1240return ret;1241}1242#endif124312441245#if defined(GCC_DIAGNOSTIC)1246/* Show no warning in case system functions are not used. */1247#pragma GCC diagnostic pop1248#endif /* defined(GCC_DIAGNOSTIC) */1249#if defined(__clang__)1250/* Show no warning in case system functions are not used. */1251#pragma clang diagnostic pop1252#endif125312541255#if defined(USE_SERVER_STATS)12561257struct mg_memory_stat {1258volatile int64_t totalMemUsed;1259volatile int64_t maxMemUsed;1260volatile int blockCount;1261};126212631264static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);126512661267static void *1268mg_malloc_ex(size_t size,1269struct mg_context *ctx,1270const char *file,1271unsigned line)1272{1273void *data = malloc(size + 2 * sizeof(uintptr_t));1274void *memory = 0;1275struct mg_memory_stat *mstat = get_memory_stat(ctx);12761277#if defined(MEMORY_DEBUGGING)1278char mallocStr[256];1279#else1280(void)file;1281(void)line;1282#endif12831284if (data) {1285int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);1286if (mmem > mstat->maxMemUsed) {1287/* could use atomic compare exchange, but this1288* seems overkill for statistics data */1289mstat->maxMemUsed = mmem;1290}12911292mg_atomic_inc(&mstat->blockCount);1293((uintptr_t *)data)[0] = size;1294((uintptr_t *)data)[1] = (uintptr_t)mstat;1295memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));1296}12971298#if defined(MEMORY_DEBUGGING)1299sprintf(mallocStr,1300"MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",1301memory,1302(unsigned long)size,1303(unsigned long)mstat->totalMemUsed,1304(unsigned long)mstat->blockCount,1305file,1306line);1307#if defined(_WIN32)1308OutputDebugStringA(mallocStr);1309#else1310DEBUG_TRACE("%s", mallocStr);1311#endif1312#endif13131314return memory;1315}131613171318static void *1319mg_calloc_ex(size_t count,1320size_t size,1321struct mg_context *ctx,1322const char *file,1323unsigned line)1324{1325void *data = mg_malloc_ex(size * count, ctx, file, line);13261327if (data) {1328memset(data, 0, size * count);1329}1330return data;1331}133213331334static void1335mg_free_ex(void *memory, const char *file, unsigned line)1336{1337void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));133813391340#if defined(MEMORY_DEBUGGING)1341char mallocStr[256];1342#else1343(void)file;1344(void)line;1345#endif13461347if (memory) {1348uintptr_t size = ((uintptr_t *)data)[0];1349struct mg_memory_stat *mstat =1350(struct mg_memory_stat *)(((uintptr_t *)data)[1]);1351mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);1352mg_atomic_dec(&mstat->blockCount);1353#if defined(MEMORY_DEBUGGING)1354sprintf(mallocStr,1355"MEM: %p %5lu free %7lu %4lu --- %s:%u\n",1356memory,1357(unsigned long)size,1358(unsigned long)mstat->totalMemUsed,1359(unsigned long)mstat->blockCount,1360file,1361line);1362#if defined(_WIN32)1363OutputDebugStringA(mallocStr);1364#else1365DEBUG_TRACE("%s", mallocStr);1366#endif1367#endif1368free(data);1369}1370}137113721373static void *1374mg_realloc_ex(void *memory,1375size_t newsize,1376struct mg_context *ctx,1377const char *file,1378unsigned line)1379{1380void *data;1381void *_realloc;1382uintptr_t oldsize;13831384#if defined(MEMORY_DEBUGGING)1385char mallocStr[256];1386#else1387(void)file;1388(void)line;1389#endif13901391if (newsize) {1392if (memory) {1393/* Reallocate existing block */1394struct mg_memory_stat *mstat;1395data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));1396oldsize = ((uintptr_t *)data)[0];1397mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];1398_realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));1399if (_realloc) {1400data = _realloc;1401mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);1402#if defined(MEMORY_DEBUGGING)1403sprintf(mallocStr,1404"MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",1405memory,1406(unsigned long)oldsize,1407(unsigned long)mstat->totalMemUsed,1408(unsigned long)mstat->blockCount,1409file,1410line);1411#if defined(_WIN32)1412OutputDebugStringA(mallocStr);1413#else1414DEBUG_TRACE("%s", mallocStr);1415#endif1416#endif1417mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);1418#if defined(MEMORY_DEBUGGING)1419sprintf(mallocStr,1420"MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",1421memory,1422(unsigned long)newsize,1423(unsigned long)mstat->totalMemUsed,1424(unsigned long)mstat->blockCount,1425file,1426line);1427#if defined(_WIN32)1428OutputDebugStringA(mallocStr);1429#else1430DEBUG_TRACE("%s", mallocStr);1431#endif1432#endif1433*(uintptr_t *)data = newsize;1434data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));1435} else {1436#if defined(MEMORY_DEBUGGING)1437#if defined(_WIN32)1438OutputDebugStringA("MEM: realloc failed\n");1439#else1440DEBUG_TRACE("%s", "MEM: realloc failed\n");1441#endif1442#endif1443return _realloc;1444}1445} else {1446/* Allocate new block */1447data = mg_malloc_ex(newsize, ctx, file, line);1448}1449} else {1450/* Free existing block */1451data = 0;1452mg_free_ex(memory, file, line);1453}14541455return data;1456}14571458#define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)1459#define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)1460#define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)1461#define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)14621463#define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)1464#define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)1465#define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)14661467#else /* USE_SERVER_STATS */14681469static __inline void *1470mg_malloc(size_t a)1471{1472return malloc(a);1473}14741475static __inline void *1476mg_calloc(size_t a, size_t b)1477{1478return calloc(a, b);1479}14801481static __inline void *1482mg_realloc(void *a, size_t b)1483{1484return realloc(a, b);1485}14861487static __inline void1488mg_free(void *a)1489{1490free(a);1491}14921493#define mg_malloc_ctx(a, c) mg_malloc(a)1494#define mg_calloc_ctx(a, b, c) mg_calloc(a, b)1495#define mg_realloc_ctx(a, b, c) mg_realloc(a, b)1496#define mg_free_ctx(a, c) mg_free(a)14971498#endif /* USE_SERVER_STATS */149915001501static void mg_vsnprintf(const struct mg_connection *conn,1502int *truncated,1503char *buf,1504size_t buflen,1505const char *fmt,1506va_list ap);15071508static void mg_snprintf(const struct mg_connection *conn,1509int *truncated,1510char *buf,1511size_t buflen,1512PRINTF_FORMAT_STRING(const char *fmt),1513...) PRINTF_ARGS(5, 6);15141515/* This following lines are just meant as a reminder to use the mg-functions1516* for memory management */1517#if defined(malloc)1518#undef malloc1519#endif1520#if defined(calloc)1521#undef calloc1522#endif1523#if defined(realloc)1524#undef realloc1525#endif1526#if defined(free)1527#undef free1528#endif1529#if defined(snprintf)1530#undef snprintf1531#endif1532#if defined(vsnprintf)1533#undef vsnprintf1534#endif1535#define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc1536#define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc1537#define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc1538#define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free1539#define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf1540#if defined(_WIN32)1541/* vsnprintf must not be used in any system,1542* but this define only works well for Windows. */1543#define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf1544#endif154515461547/* mg_init_library counter */1548static int mg_init_library_called = 0;15491550#if !defined(NO_SSL)1551static int mg_ssl_initialized = 0;1552#endif15531554static pthread_key_t sTlsKey; /* Thread local storage index */1555static int thread_idx_max = 0;15561557#if defined(MG_LEGACY_INTERFACE)1558#define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE1559#endif15601561struct mg_workerTLS {1562int is_master;1563unsigned long thread_idx;1564#if defined(_WIN32)1565HANDLE pthread_cond_helper_mutex;1566struct mg_workerTLS *next_waiting_thread;1567#endif1568#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)1569char txtbuf[4];1570#endif1571};157215731574#if defined(GCC_DIAGNOSTIC)1575/* Show no warning in case system functions are not used. */1576#pragma GCC diagnostic push1577#pragma GCC diagnostic ignored "-Wunused-function"1578#endif /* defined(GCC_DIAGNOSTIC) */1579#if defined(__clang__)1580/* Show no warning in case system functions are not used. */1581#pragma clang diagnostic push1582#pragma clang diagnostic ignored "-Wunused-function"1583#endif158415851586/* Get a unique thread ID as unsigned long, independent from the data type1587* of thread IDs defined by the operating system API.1588* If two calls to mg_current_thread_id return the same value, they calls1589* are done from the same thread. If they return different values, they are1590* done from different threads. (Provided this function is used in the same1591* process context and threads are not repeatedly created and deleted, but1592* CivetWeb does not do that).1593* This function must match the signature required for SSL id callbacks:1594* CRYPTO_set_id_callback1595*/1596FUNCTION_MAY_BE_UNUSED1597static unsigned long1598mg_current_thread_id(void)1599{1600#if defined(_WIN32)1601return GetCurrentThreadId();1602#else16031604#if defined(__clang__)1605#pragma clang diagnostic push1606#pragma clang diagnostic ignored "-Wunreachable-code"1607/* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"1608* or not, so one of the two conditions will be unreachable by construction.1609* Unfortunately the C standard does not define a way to check this at1610* compile time, since the #if preprocessor conditions can not use the sizeof1611* operator as an argument. */1612#endif16131614if (sizeof(pthread_t) > sizeof(unsigned long)) {1615/* This is the problematic case for CRYPTO_set_id_callback:1616* The OS pthread_t can not be cast to unsigned long. */1617struct mg_workerTLS *tls =1618(struct mg_workerTLS *)pthread_getspecific(sTlsKey);1619if (tls == NULL) {1620/* SSL called from an unknown thread: Create some thread index.1621*/1622tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));1623tls->is_master = -2; /* -2 means "3rd party thread" */1624tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);1625pthread_setspecific(sTlsKey, tls);1626}1627return tls->thread_idx;1628} else {1629/* pthread_t may be any data type, so a simple cast to unsigned long1630* can rise a warning/error, depending on the platform.1631* Here memcpy is used as an anything-to-anything cast. */1632unsigned long ret = 0;1633pthread_t t = pthread_self();1634memcpy(&ret, &t, sizeof(pthread_t));1635return ret;1636}16371638#if defined(__clang__)1639#pragma clang diagnostic pop1640#endif16411642#endif1643}164416451646FUNCTION_MAY_BE_UNUSED1647static uint64_t1648mg_get_current_time_ns(void)1649{1650struct timespec tsnow;1651clock_gettime(CLOCK_REALTIME, &tsnow);1652return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;1653}165416551656#if defined(GCC_DIAGNOSTIC)1657/* Show no warning in case system functions are not used. */1658#pragma GCC diagnostic pop1659#endif /* defined(GCC_DIAGNOSTIC) */1660#if defined(__clang__)1661/* Show no warning in case system functions are not used. */1662#pragma clang diagnostic pop1663#endif166416651666#if defined(NEED_DEBUG_TRACE_FUNC)1667static void1668DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)1669{1670va_list args;1671uint64_t nsnow;1672static uint64_t nslast;1673struct timespec tsnow;16741675/* Get some operating system independent thread id */1676unsigned long thread_id = mg_current_thread_id();16771678clock_gettime(CLOCK_REALTIME, &tsnow);1679nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)1680+ ((uint64_t)tsnow.tv_nsec);16811682if (!nslast) {1683nslast = nsnow;1684}16851686flockfile(stdout);1687printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",1688(unsigned long)tsnow.tv_sec,1689(unsigned long)tsnow.tv_nsec,1690nsnow - nslast,1691thread_id,1692func,1693line);1694va_start(args, fmt);1695vprintf(fmt, args);1696va_end(args);1697putchar('\n');1698fflush(stdout);1699funlockfile(stdout);1700nslast = nsnow;1701}1702#endif /* NEED_DEBUG_TRACE_FUNC */170317041705#define MD5_STATIC static1706#include "md5.inl"17071708/* Darwin prior to 7.0 and Win32 do not have socklen_t */1709#if defined(NO_SOCKLEN_T)1710typedef int socklen_t;1711#endif /* NO_SOCKLEN_T */17121713#define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */17141715#if !defined(MSG_NOSIGNAL)1716#define MSG_NOSIGNAL (0)1717#endif171817191720#if defined(NO_SSL)1721typedef struct SSL SSL; /* dummy for SSL argument to push/pull */1722typedef struct SSL_CTX SSL_CTX;1723#else1724#if defined(NO_SSL_DL)1725#include <openssl/bn.h>1726#include <openssl/conf.h>1727#include <openssl/crypto.h>1728#include <openssl/dh.h>1729#include <openssl/engine.h>1730#include <openssl/err.h>1731#include <openssl/opensslv.h>1732#include <openssl/pem.h>1733#include <openssl/ssl.h>1734#include <openssl/x509.h>17351736#if defined(WOLFSSL_VERSION)1737/* Additional defines for WolfSSL, see1738* https://github.com/civetweb/civetweb/issues/583 */1739#include "wolfssl_extras.inl"1740#endif17411742#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)1743/* If OpenSSL headers are included, automatically select the API version */1744#if !defined(OPENSSL_API_1_1)1745#define OPENSSL_API_1_11746#endif1747#endif174817491750#else17511752/* SSL loaded dynamically from DLL.1753* I put the prototypes here to be independent from OpenSSL source1754* installation. */17551756typedef struct ssl_st SSL;1757typedef struct ssl_method_st SSL_METHOD;1758typedef struct ssl_ctx_st SSL_CTX;1759typedef struct x509_store_ctx_st X509_STORE_CTX;1760typedef struct x509_name X509_NAME;1761typedef struct asn1_integer ASN1_INTEGER;1762typedef struct bignum BIGNUM;1763typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;1764typedef struct evp_md EVP_MD;1765typedef struct x509 X509;176617671768#define SSL_CTRL_OPTIONS (32)1769#define SSL_CTRL_CLEAR_OPTIONS (77)1770#define SSL_CTRL_SET_ECDH_AUTO (94)17711772#define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L1773#define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L1774#define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L17751776#define SSL_VERIFY_NONE (0)1777#define SSL_VERIFY_PEER (1)1778#define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)1779#define SSL_VERIFY_CLIENT_ONCE (4)1780#define SSL_OP_ALL ((long)(0x80000BFFUL))1781#define SSL_OP_NO_SSLv2 (0x01000000L)1782#define SSL_OP_NO_SSLv3 (0x02000000L)1783#define SSL_OP_NO_TLSv1 (0x04000000L)1784#define SSL_OP_NO_TLSv1_2 (0x08000000L)1785#define SSL_OP_NO_TLSv1_1 (0x10000000L)1786#define SSL_OP_SINGLE_DH_USE (0x00100000L)1787#define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)1788#define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)1789#define SSL_OP_NO_COMPRESSION (0x00020000L)17901791#define SSL_CB_HANDSHAKE_START (0x10)1792#define SSL_CB_HANDSHAKE_DONE (0x20)17931794#define SSL_ERROR_NONE (0)1795#define SSL_ERROR_SSL (1)1796#define SSL_ERROR_WANT_READ (2)1797#define SSL_ERROR_WANT_WRITE (3)1798#define SSL_ERROR_WANT_X509_LOOKUP (4)1799#define SSL_ERROR_SYSCALL (5) /* see errno */1800#define SSL_ERROR_ZERO_RETURN (6)1801#define SSL_ERROR_WANT_CONNECT (7)1802#define SSL_ERROR_WANT_ACCEPT (8)18031804#define TLSEXT_TYPE_server_name (0)1805#define TLSEXT_NAMETYPE_host_name (0)1806#define SSL_TLSEXT_ERR_OK (0)1807#define SSL_TLSEXT_ERR_ALERT_WARNING (1)1808#define SSL_TLSEXT_ERR_ALERT_FATAL (2)1809#define SSL_TLSEXT_ERR_NOACK (3)18101811struct ssl_func {1812const char *name; /* SSL function name */1813void (*ptr)(void); /* Function pointer */1814};181518161817#if defined(OPENSSL_API_1_1)18181819#define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)1820#define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)1821#define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)1822#define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)1823#define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)1824#define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)1825#define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)1826#define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)1827#define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)1828#define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)1829#define OPENSSL_init_ssl \1830(*(int (*)(uint64_t opts, \1831const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \1832.ptr)1833#define SSL_CTX_use_PrivateKey_file \1834(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)1835#define SSL_CTX_use_certificate_file \1836(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)1837#define SSL_CTX_set_default_passwd_cb \1838(*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)1839#define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)1840#define SSL_CTX_use_certificate_chain_file \1841(*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)1842#define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)1843#define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)1844#define SSL_CTX_set_verify \1845(*(void (*)(SSL_CTX *, \1846int, \1847int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \1848.ptr)1849#define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)1850#define SSL_CTX_load_verify_locations \1851(*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)1852#define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)1853#define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)1854#define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)1855#define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)1856#define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)1857#define SSL_CIPHER_get_name \1858(*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)1859#define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)1860#define SSL_CTX_set_session_id_context \1861(*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)1862#define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)1863#define SSL_CTX_set_cipher_list \1864(*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)1865#define SSL_CTX_set_options \1866(*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)1867#define SSL_CTX_set_info_callback \1868(*(void (*)(SSL_CTX * ctx, void (*callback)(SSL * s, int, int))) \1869ssl_sw[32] \1870.ptr)1871#define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)1872#define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)1873#define SSL_CTX_callback_ctrl \1874(*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)1875#define SSL_get_servername \1876(*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)1877#define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)18781879#define SSL_CTX_clear_options(ctx, op) \1880SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)1881#define SSL_CTX_set_ecdh_auto(ctx, onoff) \1882SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)18831884#define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 531885#define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 541886#define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \1887SSL_CTX_callback_ctrl(ctx, \1888SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \1889(void (*)(void))cb)1890#define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \1891SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)18921893#define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)1894#define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)18951896#define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))1897#define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))18981899#define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)1900#define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)1901#define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)1902#define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)1903#define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)1904#define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)1905#define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[6].ptr)1906#define X509_NAME_oneline \1907(*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)1908#define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[8].ptr)1909#define EVP_get_digestbyname \1910(*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)1911#define EVP_Digest \1912(*(int (*)( \1913const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \1914crypto_sw[10] \1915.ptr)1916#define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)1917#define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)1918#define ASN1_INTEGER_to_BN \1919(*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[13].ptr)1920#define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)1921#define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)19221923#define OPENSSL_free(a) CRYPTO_free(a)192419251926/* init_ssl_ctx() function updates this array.1927* It loads SSL library dynamically and changes NULLs to the actual addresses1928* of respective functions. The macros above (like SSL_connect()) are really1929* just calling these functions indirectly via the pointer. */1930static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},1931{"SSL_accept", NULL},1932{"SSL_connect", NULL},1933{"SSL_read", NULL},1934{"SSL_write", NULL},1935{"SSL_get_error", NULL},1936{"SSL_set_fd", NULL},1937{"SSL_new", NULL},1938{"SSL_CTX_new", NULL},1939{"TLS_server_method", NULL},1940{"OPENSSL_init_ssl", NULL},1941{"SSL_CTX_use_PrivateKey_file", NULL},1942{"SSL_CTX_use_certificate_file", NULL},1943{"SSL_CTX_set_default_passwd_cb", NULL},1944{"SSL_CTX_free", NULL},1945{"SSL_CTX_use_certificate_chain_file", NULL},1946{"TLS_client_method", NULL},1947{"SSL_pending", NULL},1948{"SSL_CTX_set_verify", NULL},1949{"SSL_shutdown", NULL},1950{"SSL_CTX_load_verify_locations", NULL},1951{"SSL_CTX_set_default_verify_paths", NULL},1952{"SSL_CTX_set_verify_depth", NULL},1953{"SSL_get_peer_certificate", NULL},1954{"SSL_get_version", NULL},1955{"SSL_get_current_cipher", NULL},1956{"SSL_CIPHER_get_name", NULL},1957{"SSL_CTX_check_private_key", NULL},1958{"SSL_CTX_set_session_id_context", NULL},1959{"SSL_CTX_ctrl", NULL},1960{"SSL_CTX_set_cipher_list", NULL},1961{"SSL_CTX_set_options", NULL},1962{"SSL_CTX_set_info_callback", NULL},1963{"SSL_get_ex_data", NULL},1964{"SSL_set_ex_data", NULL},1965{"SSL_CTX_callback_ctrl", NULL},1966{"SSL_get_servername", NULL},1967{"SSL_set_SSL_CTX", NULL},1968{NULL, NULL}};196919701971/* Similar array as ssl_sw. These functions could be located in different1972* lib. */1973static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},1974{"ERR_error_string", NULL},1975{"ERR_remove_state", NULL},1976{"CONF_modules_unload", NULL},1977{"X509_free", NULL},1978{"X509_get_subject_name", NULL},1979{"X509_get_issuer_name", NULL},1980{"X509_NAME_oneline", NULL},1981{"X509_get_serialNumber", NULL},1982{"EVP_get_digestbyname", NULL},1983{"EVP_Digest", NULL},1984{"i2d_X509", NULL},1985{"BN_bn2hex", NULL},1986{"ASN1_INTEGER_to_BN", NULL},1987{"BN_free", NULL},1988{"CRYPTO_free", NULL},1989{NULL, NULL}};1990#else19911992#define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)1993#define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)1994#define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)1995#define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)1996#define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)1997#define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)1998#define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)1999#define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)2000#define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)2001#define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)2002#define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)2003#define SSL_CTX_use_PrivateKey_file \2004(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)2005#define SSL_CTX_use_certificate_file \2006(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)2007#define SSL_CTX_set_default_passwd_cb \2008(*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)2009#define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)2010#define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)2011#define SSL_CTX_use_certificate_chain_file \2012(*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)2013#define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)2014#define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)2015#define SSL_CTX_set_verify \2016(*(void (*)(SSL_CTX *, \2017int, \2018int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \2019.ptr)2020#define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)2021#define SSL_CTX_load_verify_locations \2022(*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)2023#define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)2024#define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)2025#define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)2026#define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)2027#define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)2028#define SSL_CIPHER_get_name \2029(*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)2030#define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)2031#define SSL_CTX_set_session_id_context \2032(*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)2033#define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)2034#define SSL_CTX_set_cipher_list \2035(*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)2036#define SSL_CTX_set_info_callback \2037(*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int))) ssl_sw[32].ptr)2038#define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)2039#define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)2040#define SSL_CTX_callback_ctrl \2041(*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)2042#define SSL_get_servername \2043(*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)2044#define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)20452046#define SSL_CTX_set_options(ctx, op) \2047SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)2048#define SSL_CTX_clear_options(ctx, op) \2049SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)2050#define SSL_CTX_set_ecdh_auto(ctx, onoff) \2051SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)20522053#define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 532054#define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 542055#define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \2056SSL_CTX_callback_ctrl(ctx, \2057SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \2058(void (*)(void))cb)2059#define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \2060SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)20612062#define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)2063#define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)20642065#define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))2066#define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))20672068#define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)2069#define CRYPTO_set_locking_callback \2070(*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)2071#define CRYPTO_set_id_callback \2072(*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)2073#define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)2074#define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)2075#define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)2076#define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)2077#define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)2078#define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)2079#define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)2080#define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)2081#define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)2082#define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)2083#define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)2084#define X509_NAME_oneline \2085(*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)2086#define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)2087#define i2c_ASN1_INTEGER \2088(*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)2089#define EVP_get_digestbyname \2090(*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)2091#define EVP_Digest \2092(*(int (*)( \2093const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \2094crypto_sw[18] \2095.ptr)2096#define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)2097#define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)2098#define ASN1_INTEGER_to_BN \2099(*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)2100#define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)2101#define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)21022103#define OPENSSL_free(a) CRYPTO_free(a)21042105/* init_ssl_ctx() function updates this array.2106* It loads SSL library dynamically and changes NULLs to the actual addresses2107* of respective functions. The macros above (like SSL_connect()) are really2108* just calling these functions indirectly via the pointer. */2109static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},2110{"SSL_accept", NULL},2111{"SSL_connect", NULL},2112{"SSL_read", NULL},2113{"SSL_write", NULL},2114{"SSL_get_error", NULL},2115{"SSL_set_fd", NULL},2116{"SSL_new", NULL},2117{"SSL_CTX_new", NULL},2118{"SSLv23_server_method", NULL},2119{"SSL_library_init", NULL},2120{"SSL_CTX_use_PrivateKey_file", NULL},2121{"SSL_CTX_use_certificate_file", NULL},2122{"SSL_CTX_set_default_passwd_cb", NULL},2123{"SSL_CTX_free", NULL},2124{"SSL_load_error_strings", NULL},2125{"SSL_CTX_use_certificate_chain_file", NULL},2126{"SSLv23_client_method", NULL},2127{"SSL_pending", NULL},2128{"SSL_CTX_set_verify", NULL},2129{"SSL_shutdown", NULL},2130{"SSL_CTX_load_verify_locations", NULL},2131{"SSL_CTX_set_default_verify_paths", NULL},2132{"SSL_CTX_set_verify_depth", NULL},2133{"SSL_get_peer_certificate", NULL},2134{"SSL_get_version", NULL},2135{"SSL_get_current_cipher", NULL},2136{"SSL_CIPHER_get_name", NULL},2137{"SSL_CTX_check_private_key", NULL},2138{"SSL_CTX_set_session_id_context", NULL},2139{"SSL_CTX_ctrl", NULL},2140{"SSL_CTX_set_cipher_list", NULL},2141{"SSL_CTX_set_info_callback", NULL},2142{"SSL_get_ex_data", NULL},2143{"SSL_set_ex_data", NULL},2144{"SSL_CTX_callback_ctrl", NULL},2145{"SSL_get_servername", NULL},2146{"SSL_set_SSL_CTX", NULL},2147{NULL, NULL}};214821492150/* Similar array as ssl_sw. These functions could be located in different2151* lib. */2152static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},2153{"CRYPTO_set_locking_callback", NULL},2154{"CRYPTO_set_id_callback", NULL},2155{"ERR_get_error", NULL},2156{"ERR_error_string", NULL},2157{"ERR_remove_state", NULL},2158{"ERR_free_strings", NULL},2159{"ENGINE_cleanup", NULL},2160{"CONF_modules_unload", NULL},2161{"CRYPTO_cleanup_all_ex_data", NULL},2162{"EVP_cleanup", NULL},2163{"X509_free", NULL},2164{"X509_get_subject_name", NULL},2165{"X509_get_issuer_name", NULL},2166{"X509_NAME_oneline", NULL},2167{"X509_get_serialNumber", NULL},2168{"i2c_ASN1_INTEGER", NULL},2169{"EVP_get_digestbyname", NULL},2170{"EVP_Digest", NULL},2171{"i2d_X509", NULL},2172{"BN_bn2hex", NULL},2173{"ASN1_INTEGER_to_BN", NULL},2174{"BN_free", NULL},2175{"CRYPTO_free", NULL},2176{NULL, NULL}};2177#endif /* OPENSSL_API_1_1 */2178#endif /* NO_SSL_DL */2179#endif /* NO_SSL */218021812182#if !defined(NO_CACHING)2183static const char *month_names[] = {"Jan",2184"Feb",2185"Mar",2186"Apr",2187"May",2188"Jun",2189"Jul",2190"Aug",2191"Sep",2192"Oct",2193"Nov",2194"Dec"};2195#endif /* !NO_CACHING */21962197/* Unified socket address. For IPv6 support, add IPv6 address structure in2198* the2199* union u. */2200union usa {2201struct sockaddr sa;2202struct sockaddr_in sin;2203#if defined(USE_IPV6)2204struct sockaddr_in6 sin6;2205#endif2206};22072208/* Describes a string (chunk of memory). */2209struct vec {2210const char *ptr;2211size_t len;2212};22132214struct mg_file_stat {2215/* File properties filled by mg_stat: */2216uint64_t size;2217time_t last_modified;2218int is_directory; /* Set to 1 if mg_stat is called for a directory */2219int is_gzipped; /* Set to 1 if the content is gzipped, in which2220* case we need a "Content-Eencoding: gzip" header */2221int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */2222};22232224struct mg_file_in_memory {2225char *p;2226uint32_t pos;2227char mode;2228};22292230struct mg_file_access {2231/* File properties filled by mg_fopen: */2232FILE *fp;2233#if defined(MG_USE_OPEN_FILE)2234/* TODO (low): Remove obsolete "file in memory" implementation.2235* In an "early 2017" discussion at Google groups2236* https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI2237* we decided to get rid of this feature (after some fade-out2238* phase). */2239const char *membuf;2240#endif2241};22422243struct mg_file {2244struct mg_file_stat stat;2245struct mg_file_access access;2246};22472248#if defined(MG_USE_OPEN_FILE)22492250#define STRUCT_FILE_INITIALIZER \2251{ \2252{(uint64_t)0, (time_t)0, 0, 0, 0}, \2253{ \2254(FILE *)NULL, (const char *)NULL \2255} \2256}22572258#else22592260#define STRUCT_FILE_INITIALIZER \2261{ \2262{(uint64_t)0, (time_t)0, 0, 0, 0}, \2263{ \2264(FILE *)NULL \2265} \2266}22672268#endif226922702271/* Describes listening socket, or socket which was accept()-ed by the master2272* thread and queued for future handling by the worker thread. */2273struct socket {2274SOCKET sock; /* Listening socket */2275union usa lsa; /* Local socket address */2276union usa rsa; /* Remote socket address */2277unsigned char is_ssl; /* Is port SSL-ed */2278unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL2279* port */2280unsigned char in_use; /* Is valid */2281};228222832284/* Enum const for all options must be in sync with2285* static struct mg_option config_options[]2286* This is tested in the unit test (test/private.c)2287* "Private Config Options"2288*/2289enum {2290/* Once for each server */2291LISTENING_PORTS,2292NUM_THREADS,2293RUN_AS_USER,2294CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the2295* socket option typedef TCP_NODELAY. */2296MAX_REQUEST_SIZE,2297LINGER_TIMEOUT,2298#if defined(__linux__)2299ALLOW_SENDFILE_CALL,2300#endif2301#if defined(_WIN32)2302CASE_SENSITIVE_FILES,2303#endif2304THROTTLE,2305ACCESS_LOG_FILE,2306ERROR_LOG_FILE,2307ENABLE_KEEP_ALIVE,2308REQUEST_TIMEOUT,2309KEEP_ALIVE_TIMEOUT,2310#if defined(USE_WEBSOCKET)2311WEBSOCKET_TIMEOUT,2312ENABLE_WEBSOCKET_PING_PONG,2313#endif2314DECODE_URL,2315#if defined(USE_LUA)2316LUA_BACKGROUND_SCRIPT,2317LUA_BACKGROUND_SCRIPT_PARAMS,2318#endif2319#if defined(USE_TIMERS)2320CGI_TIMEOUT,2321#endif23222323/* Once for each domain */2324DOCUMENT_ROOT,2325CGI_EXTENSIONS,2326CGI_ENVIRONMENT,2327PUT_DELETE_PASSWORDS_FILE,2328CGI_INTERPRETER,2329PROTECT_URI,2330AUTHENTICATION_DOMAIN,2331ENABLE_AUTH_DOMAIN_CHECK,2332SSI_EXTENSIONS,2333ENABLE_DIRECTORY_LISTING,2334GLOBAL_PASSWORDS_FILE,2335INDEX_FILES,2336ACCESS_CONTROL_LIST,2337EXTRA_MIME_TYPES,2338SSL_CERTIFICATE,2339SSL_CERTIFICATE_CHAIN,2340URL_REWRITE_PATTERN,2341HIDE_FILES,2342SSL_DO_VERIFY_PEER,2343SSL_CA_PATH,2344SSL_CA_FILE,2345SSL_VERIFY_DEPTH,2346SSL_DEFAULT_VERIFY_PATHS,2347SSL_CIPHER_LIST,2348SSL_PROTOCOL_VERSION,2349SSL_SHORT_TRUST,23502351#if defined(USE_LUA)2352LUA_PRELOAD_FILE,2353LUA_SCRIPT_EXTENSIONS,2354LUA_SERVER_PAGE_EXTENSIONS,2355#if defined(MG_EXPERIMENTAL_INTERFACES)2356LUA_DEBUG_PARAMS,2357#endif2358#endif2359#if defined(USE_DUKTAPE)2360DUKTAPE_SCRIPT_EXTENSIONS,2361#endif23622363#if defined(USE_WEBSOCKET)2364WEBSOCKET_ROOT,2365#endif2366#if defined(USE_LUA) && defined(USE_WEBSOCKET)2367LUA_WEBSOCKET_EXTENSIONS,2368#endif23692370ACCESS_CONTROL_ALLOW_ORIGIN,2371ACCESS_CONTROL_ALLOW_METHODS,2372ACCESS_CONTROL_ALLOW_HEADERS,2373ERROR_PAGES,2374#if !defined(NO_CACHING)2375STATIC_FILE_MAX_AGE,2376#endif2377#if !defined(NO_SSL)2378STRICT_HTTPS_MAX_AGE,2379#endif2380ADDITIONAL_HEADER,2381ALLOW_INDEX_SCRIPT_SUB_RES,23822383NUM_OPTIONS2384};238523862387/* Config option name, config types, default value.2388* Must be in the same order as the enum const above.2389*/2390static const struct mg_option config_options[] = {23912392/* Once for each server */2393{"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},2394{"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},2395{"run_as_user", MG_CONFIG_TYPE_STRING, NULL},2396{"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},2397{"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},2398{"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},2399#if defined(__linux__)2400{"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},2401#endif2402#if defined(_WIN32)2403{"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},2404#endif2405{"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},2406{"access_log_file", MG_CONFIG_TYPE_FILE, NULL},2407{"error_log_file", MG_CONFIG_TYPE_FILE, NULL},2408{"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},2409{"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},2410{"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},2411#if defined(USE_WEBSOCKET)2412{"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},2413{"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},2414#endif2415{"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},2416#if defined(USE_LUA)2417{"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},2418{"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},2419#endif2420#if defined(USE_TIMERS)2421{"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},2422#endif24232424/* Once for each domain */2425{"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},2426{"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},2427{"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},2428{"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},2429{"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},2430{"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},2431{"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},2432{"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},2433{"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},2434{"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},2435{"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},2436{"index_files",2437MG_CONFIG_TYPE_STRING_LIST,2438#if defined(USE_LUA)2439"index.xhtml,index.html,index.htm,"2440"index.lp,index.lsp,index.lua,index.cgi,"2441"index.shtml,index.php"},2442#else2443"index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},2444#endif2445{"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},2446{"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},2447{"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},2448{"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},2449{"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},2450{"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},24512452{"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},24532454{"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},2455{"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},2456{"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},2457{"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},2458{"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},2459{"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},2460{"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},24612462#if defined(USE_LUA)2463{"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},2464{"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},2465{"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},2466#if defined(MG_EXPERIMENTAL_INTERFACES)2467{"lua_debug", MG_CONFIG_TYPE_STRING, NULL},2468#endif2469#endif2470#if defined(USE_DUKTAPE)2471/* The support for duktape is still in alpha version state.2472* The name of this config option might change. */2473{"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},2474#endif24752476#if defined(USE_WEBSOCKET)2477{"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},2478#endif2479#if defined(USE_LUA) && defined(USE_WEBSOCKET)2480{"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},2481#endif2482{"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},2483{"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},2484{"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},2485{"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},2486#if !defined(NO_CACHING)2487{"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},2488#endif2489#if !defined(NO_SSL)2490{"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},2491#endif2492{"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},2493{"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},24942495{NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};249624972498/* Check if the config_options and the corresponding enum have compatible2499* sizes. */2500mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))2501== (NUM_OPTIONS + 1),2502"config_options and enum not sync");250325042505enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };250625072508struct mg_handler_info {2509/* Name/Pattern of the URI. */2510char *uri;2511size_t uri_len;25122513/* handler type */2514int handler_type;25152516/* Handler for http/https or authorization requests. */2517mg_request_handler handler;2518unsigned int refcount;2519pthread_mutex_t refcount_mutex; /* Protects refcount */2520pthread_cond_t2521refcount_cond; /* Signaled when handler refcount is decremented */25222523/* Handler for ws/wss (websocket) requests. */2524mg_websocket_connect_handler connect_handler;2525mg_websocket_ready_handler ready_handler;2526mg_websocket_data_handler data_handler;2527mg_websocket_close_handler close_handler;25282529/* accepted subprotocols for ws/wss requests. */2530struct mg_websocket_subprotocols *subprotocols;25312532/* Handler for authorization requests */2533mg_authorization_handler auth_handler;25342535/* User supplied argument for the handler function. */2536void *cbdata;25372538/* next handler in a linked list */2539struct mg_handler_info *next;2540};254125422543enum {2544CONTEXT_INVALID,2545CONTEXT_SERVER,2546CONTEXT_HTTP_CLIENT,2547CONTEXT_WS_CLIENT2548};254925502551struct mg_domain_context {2552SSL_CTX *ssl_ctx; /* SSL context */2553char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */2554struct mg_handler_info *handlers; /* linked list of uri handlers */25552556/* Server nonce */2557uint64_t auth_nonce_mask; /* Mask for all nonce values */2558unsigned long nonce_count; /* Used nonces, used for authentication */25592560#if defined(USE_LUA) && defined(USE_WEBSOCKET)2561/* linked list of shared lua websockets */2562struct mg_shared_lua_websocket_list *shared_lua_websockets;2563#endif25642565/* Linked list of domains */2566struct mg_domain_context *next;2567};256825692570struct mg_context {25712572/* Part 1 - Physical context:2573* This holds threads, ports, timeouts, ...2574* set for the entire server, independent from the2575* addressed hostname.2576*/25772578/* Connection related */2579int context_type; /* See CONTEXT_* above */25802581struct socket *listening_sockets;2582struct pollfd *listening_socket_fds;2583unsigned int num_listening_sockets;25842585struct mg_connection *worker_connections; /* The connection struct, pre-2586* allocated for each worker */25872588#if defined(USE_SERVER_STATS)2589int active_connections;2590int max_connections;2591int64_t total_connections;2592int64_t total_requests;2593int64_t total_data_read;2594int64_t total_data_written;2595#endif25962597/* Thread related */2598volatile int stop_flag; /* Should we stop event loop */2599pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */26002601pthread_t masterthreadid; /* The master thread ID */2602unsigned int2603cfg_worker_threads; /* The number of configured worker threads. */2604pthread_t *worker_threadids; /* The worker thread IDs */26052606/* Connection to thread dispatching */2607#if defined(ALTERNATIVE_QUEUE)2608struct socket *client_socks;2609void **client_wait_events;2610#else2611struct socket queue[MGSQLEN]; /* Accepted sockets */2612volatile int sq_head; /* Head of the socket queue */2613volatile int sq_tail; /* Tail of the socket queue */2614pthread_cond_t sq_full; /* Signaled when socket is produced */2615pthread_cond_t sq_empty; /* Signaled when socket is consumed */2616#endif26172618/* Memory related */2619unsigned int max_request_size; /* The max request size */26202621#if defined(USE_SERVER_STATS)2622struct mg_memory_stat ctx_memory;2623#endif26242625/* Operating system related */2626char *systemName; /* What operating system is running */2627time_t start_time; /* Server start time, used for authentication2628* and for diagnstics. */26292630#if defined(USE_TIMERS)2631struct ttimers *timers;2632#endif26332634/* Lua specific: Background operations and shared websockets */2635#if defined(USE_LUA)2636void *lua_background_state;2637#endif26382639/* Server nonce */2640pthread_mutex_t nonce_mutex; /* Protects nonce_count */26412642/* Server callbacks */2643struct mg_callbacks callbacks; /* User-defined callback function */2644void *user_data; /* User-defined data */26452646/* Part 2 - Logical domain:2647* This holds hostname, TLS certificate, document root, ...2648* set for a domain hosted at the server.2649* There may be multiple domains hosted at one physical server.2650* The default domain "dd" is the first element of a list of2651* domains.2652*/2653struct mg_domain_context dd; /* default domain */2654};265526562657#if defined(USE_SERVER_STATS)2658static struct mg_memory_stat mg_common_memory = {0, 0, 0};26592660static struct mg_memory_stat *2661get_memory_stat(struct mg_context *ctx)2662{2663if (ctx) {2664return &(ctx->ctx_memory);2665}2666return &mg_common_memory;2667}2668#endif26692670enum {2671CONNECTION_TYPE_INVALID,2672CONNECTION_TYPE_REQUEST,2673CONNECTION_TYPE_RESPONSE2674};26752676struct mg_connection {2677int connection_type; /* see CONNECTION_TYPE_* above */26782679struct mg_request_info request_info;2680struct mg_response_info response_info;26812682struct mg_context *phys_ctx;2683struct mg_domain_context *dom_ctx;26842685#if defined(USE_SERVER_STATS)2686int conn_state; /* 0 = undef, numerical value may change in different2687* versions. For the current definition, see2688* mg_get_connection_info_impl */2689#endif26902691const char *host; /* Host (HTTP/1.1 header or SNI) */2692SSL *ssl; /* SSL descriptor */2693SSL_CTX *client_ssl_ctx; /* SSL context for client connections */2694struct socket client; /* Connected client */2695time_t conn_birth_time; /* Time (wall clock) when connection was2696* established */2697struct timespec req_time; /* Time (since system start) when the request2698* was received */2699int64_t num_bytes_sent; /* Total bytes sent to client */2700int64_t content_len; /* Content-Length header value */2701int64_t consumed_content; /* How many bytes of content have been read */2702int is_chunked; /* Transfer-Encoding is chunked:2703* 0 = not chunked,2704* 1 = chunked, do data read yet,2705* 2 = chunked, some data read,2706* 3 = chunked, all data read2707*/2708size_t chunk_remainder; /* Unread data from the last chunk */2709char *buf; /* Buffer for received data */2710char *path_info; /* PATH_INFO part of the URL */27112712int must_close; /* 1 if connection must be closed */2713int accept_gzip; /* 1 if gzip encoding is accepted */2714int in_error_handler; /* 1 if in handler for user defined error2715* pages */2716#if defined(USE_WEBSOCKET)2717int in_websocket_handling; /* 1 if in read_websocket */2718#endif2719int handled_requests; /* Number of requests handled by this connection2720*/2721int buf_size; /* Buffer size */2722int request_len; /* Size of the request + headers in a buffer */2723int data_len; /* Total size of data in a buffer */2724int status_code; /* HTTP reply status code, e.g. 200 */2725int throttle; /* Throttling, bytes/sec. <= 0 means no2726* throttle */27272728time_t last_throttle_time; /* Last time throttled data was sent */2729int64_t last_throttle_bytes; /* Bytes sent this second */2730pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure2731* atomic transmissions for websockets */2732#if defined(USE_LUA) && defined(USE_WEBSOCKET)2733void *lua_websocket_state; /* Lua_State for a websocket connection */2734#endif27352736int thread_index; /* Thread index within ctx */2737};273827392740/* Directory entry */2741struct de {2742struct mg_connection *conn;2743char *file_name;2744struct mg_file_stat file;2745};274627472748#if defined(USE_WEBSOCKET)2749static int is_websocket_protocol(const struct mg_connection *conn);2750#else2751#define is_websocket_protocol(conn) (0)2752#endif275327542755#define mg_cry_internal(conn, fmt, ...) \2756mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)27572758static void mg_cry_internal_wrap(const struct mg_connection *conn,2759const char *func,2760unsigned line,2761const char *fmt,2762...) PRINTF_ARGS(4, 5);276327642765#if !defined(NO_THREAD_NAME)2766#if defined(_WIN32) && defined(_MSC_VER)2767/* Set the thread name for debugging purposes in Visual Studio2768* http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx2769*/2770#pragma pack(push, 8)2771typedef struct tagTHREADNAME_INFO {2772DWORD dwType; /* Must be 0x1000. */2773LPCSTR szName; /* Pointer to name (in user addr space). */2774DWORD dwThreadID; /* Thread ID (-1=caller thread). */2775DWORD dwFlags; /* Reserved for future use, must be zero. */2776} THREADNAME_INFO;2777#pragma pack(pop)27782779#elif defined(__linux__)27802781#include <sys/prctl.h>2782#include <sys/sendfile.h>2783#if defined(ALTERNATIVE_QUEUE)2784#include <sys/eventfd.h>2785#endif /* ALTERNATIVE_QUEUE */278627872788#if defined(ALTERNATIVE_QUEUE)27892790static void *2791event_create(void)2792{2793int evhdl = eventfd(0, EFD_CLOEXEC);2794int *ret;27952796if (evhdl == -1) {2797/* Linux uses -1 on error, Windows NULL. */2798/* However, Linux does not return 0 on success either. */2799return 0;2800}28012802ret = (int *)mg_malloc(sizeof(int));2803if (ret) {2804*ret = evhdl;2805} else {2806(void)close(evhdl);2807}28082809return (void *)ret;2810}281128122813static int2814event_wait(void *eventhdl)2815{2816uint64_t u;2817int evhdl, s;28182819if (!eventhdl) {2820/* error */2821return 0;2822}2823evhdl = *(int *)eventhdl;28242825s = (int)read(evhdl, &u, sizeof(u));2826if (s != sizeof(u)) {2827/* error */2828return 0;2829}2830(void)u; /* the value is not required */2831return 1;2832}283328342835static int2836event_signal(void *eventhdl)2837{2838uint64_t u = 1;2839int evhdl, s;28402841if (!eventhdl) {2842/* error */2843return 0;2844}2845evhdl = *(int *)eventhdl;28462847s = (int)write(evhdl, &u, sizeof(u));2848if (s != sizeof(u)) {2849/* error */2850return 0;2851}2852return 1;2853}285428552856static void2857event_destroy(void *eventhdl)2858{2859int evhdl;28602861if (!eventhdl) {2862/* error */2863return;2864}2865evhdl = *(int *)eventhdl;28662867close(evhdl);2868mg_free(eventhdl);2869}287028712872#endif28732874#endif287528762877#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)28782879struct posix_event {2880pthread_mutex_t mutex;2881pthread_cond_t cond;2882};288328842885static void *2886event_create(void)2887{2888struct posix_event *ret = mg_malloc(sizeof(struct posix_event));2889if (ret == 0) {2890/* out of memory */2891return 0;2892}2893if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {2894/* pthread mutex not available */2895mg_free(ret);2896return 0;2897}2898if (0 != pthread_cond_init(&(ret->cond), NULL)) {2899/* pthread cond not available */2900pthread_mutex_destroy(&(ret->mutex));2901mg_free(ret);2902return 0;2903}2904return (void *)ret;2905}290629072908static int2909event_wait(void *eventhdl)2910{2911struct posix_event *ev = (struct posix_event *)eventhdl;2912pthread_mutex_lock(&(ev->mutex));2913pthread_cond_wait(&(ev->cond), &(ev->mutex));2914pthread_mutex_unlock(&(ev->mutex));2915return 1;2916}291729182919static int2920event_signal(void *eventhdl)2921{2922struct posix_event *ev = (struct posix_event *)eventhdl;2923pthread_mutex_lock(&(ev->mutex));2924pthread_cond_signal(&(ev->cond));2925pthread_mutex_unlock(&(ev->mutex));2926return 1;2927}292829292930static void2931event_destroy(void *eventhdl)2932{2933struct posix_event *ev = (struct posix_event *)eventhdl;2934pthread_cond_destroy(&(ev->cond));2935pthread_mutex_destroy(&(ev->mutex));2936mg_free(ev);2937}2938#endif293929402941static void2942mg_set_thread_name(const char *name)2943{2944char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */29452946mg_snprintf(2947NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);29482949#if defined(_WIN32)2950#if defined(_MSC_VER)2951/* Windows and Visual Studio Compiler */2952__try {2953THREADNAME_INFO info;2954info.dwType = 0x1000;2955info.szName = threadName;2956info.dwThreadID = ~0U;2957info.dwFlags = 0;29582959RaiseException(0x406D1388,29600,2961sizeof(info) / sizeof(ULONG_PTR),2962(ULONG_PTR *)&info);2963} __except (EXCEPTION_EXECUTE_HANDLER) {2964}2965#elif defined(__MINGW32__)2966/* No option known to set thread name for MinGW */2967#endif2968#elif defined(_GNU_SOURCE) && defined(__GLIBC__) \2969&& ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))2970/* pthread_setname_np first appeared in glibc in version 2.12*/2971#if defined(__MACH__)2972/* OS X only current thread name can be changed */2973(void)pthread_setname_np(threadName);2974#else2975(void)pthread_setname_np(pthread_self(), threadName);2976#endif2977#elif defined(__linux__)2978/* on linux we can use the old prctl function */2979(void)prctl(PR_SET_NAME, threadName, 0, 0, 0);2980#endif2981}2982#else /* !defined(NO_THREAD_NAME) */2983void2984mg_set_thread_name(const char *threadName)2985{2986}2987#endif298829892990#if defined(MG_LEGACY_INTERFACE)2991const char **2992mg_get_valid_option_names(void)2993{2994/* This function is deprecated. Use mg_get_valid_options instead. */2995static const char2996*data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};2997int i;29982999for (i = 0; config_options[i].name != NULL; i++) {3000data[i * 2] = config_options[i].name;3001data[i * 2 + 1] = config_options[i].default_value;3002}30033004return data;3005}3006#endif300730083009const struct mg_option *3010mg_get_valid_options(void)3011{3012return config_options;3013}301430153016/* Do not open file (used in is_file_in_memory) */3017#define MG_FOPEN_MODE_NONE (0)30183019/* Open file for read only access */3020#define MG_FOPEN_MODE_READ (1)30213022/* Open file for writing, create and overwrite */3023#define MG_FOPEN_MODE_WRITE (2)30243025/* Open file for writing, create and append */3026#define MG_FOPEN_MODE_APPEND (4)302730283029/* If a file is in memory, set all "stat" members and the membuf pointer of3030* output filep and return 1, otherwise return 0 and don't modify anything.3031*/3032static int3033open_file_in_memory(const struct mg_connection *conn,3034const char *path,3035struct mg_file *filep,3036int mode)3037{3038#if defined(MG_USE_OPEN_FILE)30393040size_t size = 0;3041const char *buf = NULL;3042if (!conn) {3043return 0;3044}30453046if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {3047return 0;3048}30493050if (conn->phys_ctx->callbacks.open_file) {3051buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);3052if (buf != NULL) {3053if (filep == NULL) {3054/* This is a file in memory, but we cannot store the3055* properties3056* now.3057* Called from "is_file_in_memory" function. */3058return 1;3059}30603061/* NOTE: override filep->size only on success. Otherwise, it3062* might3063* break constructs like if (!mg_stat() || !mg_fopen()) ... */3064filep->access.membuf = buf;3065filep->access.fp = NULL;30663067/* Size was set by the callback */3068filep->stat.size = size;30693070/* Assume the data may change during runtime by setting3071* last_modified = now */3072filep->stat.last_modified = time(NULL);30733074filep->stat.is_directory = 0;3075filep->stat.is_gzipped = 0;3076}3077}30783079return (buf != NULL);30803081#else3082(void)conn;3083(void)path;3084(void)filep;3085(void)mode;30863087return 0;30883089#endif3090}309130923093static int3094is_file_in_memory(const struct mg_connection *conn, const char *path)3095{3096return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);3097}309830993100static int3101is_file_opened(const struct mg_file_access *fileacc)3102{3103if (!fileacc) {3104return 0;3105}31063107#if defined(MG_USE_OPEN_FILE)3108return (fileacc->membuf != NULL) || (fileacc->fp != NULL);3109#else3110return (fileacc->fp != NULL);3111#endif3112}311331143115static int mg_stat(const struct mg_connection *conn,3116const char *path,3117struct mg_file_stat *filep);311831193120/* mg_fopen will open a file either in memory or on the disk.3121* The input parameter path is a string in UTF-8 encoding.3122* The input parameter mode is MG_FOPEN_MODE_*3123* On success, either fp or membuf will be set in the output3124* struct file. All status members will also be set.3125* The function returns 1 on success, 0 on error. */3126static int3127mg_fopen(const struct mg_connection *conn,3128const char *path,3129int mode,3130struct mg_file *filep)3131{3132int found;31333134if (!filep) {3135return 0;3136}3137filep->access.fp = NULL;3138#if defined(MG_USE_OPEN_FILE)3139filep->access.membuf = NULL;3140#endif31413142if (!is_file_in_memory(conn, path)) {31433144/* filep is initialized in mg_stat: all fields with memset to,3145* some fields like size and modification date with values */3146found = mg_stat(conn, path, &(filep->stat));31473148if ((mode == MG_FOPEN_MODE_READ) && (!found)) {3149/* file does not exist and will not be created */3150return 0;3151}31523153#if defined(_WIN32)3154{3155wchar_t wbuf[W_PATH_MAX];3156path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));3157switch (mode) {3158case MG_FOPEN_MODE_READ:3159filep->access.fp = _wfopen(wbuf, L"rb");3160break;3161case MG_FOPEN_MODE_WRITE:3162filep->access.fp = _wfopen(wbuf, L"wb");3163break;3164case MG_FOPEN_MODE_APPEND:3165filep->access.fp = _wfopen(wbuf, L"ab");3166break;3167}3168}3169#else3170/* Linux et al already use unicode. No need to convert. */3171switch (mode) {3172case MG_FOPEN_MODE_READ:3173filep->access.fp = fopen(path, "r");3174break;3175case MG_FOPEN_MODE_WRITE:3176filep->access.fp = fopen(path, "w");3177break;3178case MG_FOPEN_MODE_APPEND:3179filep->access.fp = fopen(path, "a");3180break;3181}31823183#endif3184if (!found) {3185/* File did not exist before fopen was called.3186* Maybe it has been created now. Get stat info3187* like creation time now. */3188found = mg_stat(conn, path, &(filep->stat));3189(void)found;3190}31913192/* file is on disk */3193return (filep->access.fp != NULL);31943195} else {3196#if defined(MG_USE_OPEN_FILE)3197/* is_file_in_memory returned true */3198if (open_file_in_memory(conn, path, filep, mode)) {3199/* file is in memory */3200return (filep->access.membuf != NULL);3201}3202#endif3203}32043205/* Open failed */3206return 0;3207}320832093210/* return 0 on success, just like fclose */3211static int3212mg_fclose(struct mg_file_access *fileacc)3213{3214int ret = -1;3215if (fileacc != NULL) {3216if (fileacc->fp != NULL) {3217ret = fclose(fileacc->fp);3218#if defined(MG_USE_OPEN_FILE)3219} else if (fileacc->membuf != NULL) {3220ret = 0;3221#endif3222}3223/* reset all members of fileacc */3224memset(fileacc, 0, sizeof(*fileacc));3225}3226return ret;3227}322832293230static void3231mg_strlcpy(register char *dst, register const char *src, size_t n)3232{3233for (; *src != '\0' && n > 1; n--) {3234*dst++ = *src++;3235}3236*dst = '\0';3237}323832393240static int3241lowercase(const char *s)3242{3243return tolower(*(const unsigned char *)s);3244}324532463247int3248mg_strncasecmp(const char *s1, const char *s2, size_t len)3249{3250int diff = 0;32513252if (len > 0) {3253do {3254diff = lowercase(s1++) - lowercase(s2++);3255} while (diff == 0 && s1[-1] != '\0' && --len > 0);3256}32573258return diff;3259}326032613262int3263mg_strcasecmp(const char *s1, const char *s2)3264{3265int diff;32663267do {3268diff = lowercase(s1++) - lowercase(s2++);3269} while (diff == 0 && s1[-1] != '\0');32703271return diff;3272}327332743275static char *3276mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)3277{3278char *p;3279(void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not3280* defined */32813282if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {3283mg_strlcpy(p, ptr, len + 1);3284}32853286return p;3287}328832893290static char *3291mg_strdup_ctx(const char *str, struct mg_context *ctx)3292{3293return mg_strndup_ctx(str, strlen(str), ctx);3294}32953296static char *3297mg_strdup(const char *str)3298{3299return mg_strndup_ctx(str, strlen(str), NULL);3300}330133023303static const char *3304mg_strcasestr(const char *big_str, const char *small_str)3305{3306size_t i, big_len = strlen(big_str), small_len = strlen(small_str);33073308if (big_len >= small_len) {3309for (i = 0; i <= (big_len - small_len); i++) {3310if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {3311return big_str + i;3312}3313}3314}33153316return NULL;3317}331833193320/* Return null terminated string of given maximum length.3321* Report errors if length is exceeded. */3322static void3323mg_vsnprintf(const struct mg_connection *conn,3324int *truncated,3325char *buf,3326size_t buflen,3327const char *fmt,3328va_list ap)3329{3330int n, ok;33313332if (buflen == 0) {3333if (truncated) {3334*truncated = 1;3335}3336return;3337}33383339#if defined(__clang__)3340#pragma clang diagnostic push3341#pragma clang diagnostic ignored "-Wformat-nonliteral"3342/* Using fmt as a non-literal is intended here, since it is mostly called3343* indirectly by mg_snprintf */3344#endif33453346n = (int)vsnprintf_impl(buf, buflen, fmt, ap);3347ok = (n >= 0) && ((size_t)n < buflen);33483349#if defined(__clang__)3350#pragma clang diagnostic pop3351#endif33523353if (ok) {3354if (truncated) {3355*truncated = 0;3356}3357} else {3358if (truncated) {3359*truncated = 1;3360}3361mg_cry_internal(conn,3362"truncating vsnprintf buffer: [%.*s]",3363(int)((buflen > 200) ? 200 : (buflen - 1)),3364buf);3365n = (int)buflen - 1;3366}3367buf[n] = '\0';3368}336933703371static void3372mg_snprintf(const struct mg_connection *conn,3373int *truncated,3374char *buf,3375size_t buflen,3376const char *fmt,3377...)3378{3379va_list ap;33803381va_start(ap, fmt);3382mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);3383va_end(ap);3384}338533863387static int3388get_option_index(const char *name)3389{3390int i;33913392for (i = 0; config_options[i].name != NULL; i++) {3393if (strcmp(config_options[i].name, name) == 0) {3394return i;3395}3396}3397return -1;3398}339934003401const char *3402mg_get_option(const struct mg_context *ctx, const char *name)3403{3404int i;3405if ((i = get_option_index(name)) == -1) {3406return NULL;3407} else if (!ctx || ctx->dd.config[i] == NULL) {3408return "";3409} else {3410return ctx->dd.config[i];3411}3412}34133414#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly34153416struct mg_context *3417mg_get_context(const struct mg_connection *conn)3418{3419return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);3420}342134223423void *3424mg_get_user_data(const struct mg_context *ctx)3425{3426return (ctx == NULL) ? NULL : ctx->user_data;3427}342834293430void3431mg_set_user_connection_data(struct mg_connection *conn, void *data)3432{3433if (conn != NULL) {3434conn->request_info.conn_data = data;3435}3436}343734383439void *3440mg_get_user_connection_data(const struct mg_connection *conn)3441{3442if (conn != NULL) {3443return conn->request_info.conn_data;3444}3445return NULL;3446}344734483449#if defined(MG_LEGACY_INTERFACE)3450/* Deprecated: Use mg_get_server_ports instead. */3451size_t3452mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)3453{3454size_t i;3455if (!ctx) {3456return 0;3457}3458for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {3459ssl[i] = ctx->listening_sockets[i].is_ssl;3460ports[i] =3461#if defined(USE_IPV6)3462(ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)3463? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)3464:3465#endif3466ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);3467}3468return i;3469}3470#endif347134723473int3474mg_get_server_ports(const struct mg_context *ctx,3475int size,3476struct mg_server_ports *ports)3477{3478int i, cnt = 0;34793480if (size <= 0) {3481return -1;3482}3483memset(ports, 0, sizeof(*ports) * (size_t)size);3484if (!ctx) {3485return -1;3486}3487if (!ctx->listening_sockets) {3488return -1;3489}34903491for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {34923493ports[cnt].port =3494#if defined(USE_IPV6)3495(ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)3496? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)3497:3498#endif3499ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);3500ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;3501ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;35023503if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {3504/* IPv4 */3505ports[cnt].protocol = 1;3506cnt++;3507} else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {3508/* IPv6 */3509ports[cnt].protocol = 3;3510cnt++;3511}3512}35133514return cnt;3515}351635173518static void3519sockaddr_to_string(char *buf, size_t len, const union usa *usa)3520{3521buf[0] = '\0';35223523if (!usa) {3524return;3525}35263527if (usa->sa.sa_family == AF_INET) {3528getnameinfo(&usa->sa,3529sizeof(usa->sin),3530buf,3531(unsigned)len,3532NULL,35330,3534NI_NUMERICHOST);3535}3536#if defined(USE_IPV6)3537else if (usa->sa.sa_family == AF_INET6) {3538getnameinfo(&usa->sa,3539sizeof(usa->sin6),3540buf,3541(unsigned)len,3542NULL,35430,3544NI_NUMERICHOST);3545}3546#endif3547}354835493550/* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be3551* included in all responses other than 100, 101, 5xx. */3552static void3553gmt_time_string(char *buf, size_t buf_len, time_t *t)3554{3555#if !defined(REENTRANT_TIME)3556struct tm *tm;35573558tm = ((t != NULL) ? gmtime(t) : NULL);3559if (tm != NULL) {3560#else3561struct tm _tm;3562struct tm *tm = &_tm;35633564if (t != NULL) {3565gmtime_r(t, tm);3566#endif3567strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);3568} else {3569mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);3570buf[buf_len - 1] = '\0';3571}3572}357335743575/* difftime for struct timespec. Return value is in seconds. */3576static double3577mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)3578{3579return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-93580+ (double)(ts_now->tv_sec - ts_before->tv_sec);3581}358235833584#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)3585static void mg_cry_internal_impl(const struct mg_connection *conn,3586const char *func,3587unsigned line,3588const char *fmt,3589va_list ap);3590#include "external_mg_cry_internal_impl.inl"3591#else35923593/* Print error message to the opened error log stream. */3594static void3595mg_cry_internal_impl(const struct mg_connection *conn,3596const char *func,3597unsigned line,3598const char *fmt,3599va_list ap)3600{3601char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];3602struct mg_file fi;3603time_t timestamp;36043605/* Unused, in the RELEASE build */3606(void)func;3607(void)line;36083609#if defined(GCC_DIAGNOSTIC)3610#pragma GCC diagnostic push3611#pragma GCC diagnostic ignored "-Wformat-nonliteral"3612#endif36133614IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));36153616#if defined(GCC_DIAGNOSTIC)3617#pragma GCC diagnostic pop3618#endif36193620buf[sizeof(buf) - 1] = 0;36213622DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);36233624if (!conn) {3625puts(buf);3626return;3627}36283629/* Do not lock when getting the callback value, here and below.3630* I suppose this is fine, since function cannot disappear in the3631* same way string option can. */3632if ((conn->phys_ctx->callbacks.log_message == NULL)3633|| (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {36343635if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {3636if (mg_fopen(conn,3637conn->dom_ctx->config[ERROR_LOG_FILE],3638MG_FOPEN_MODE_APPEND,3639&fi)3640== 0) {3641fi.access.fp = NULL;3642}3643} else {3644fi.access.fp = NULL;3645}36463647if (fi.access.fp != NULL) {3648flockfile(fi.access.fp);3649timestamp = time(NULL);36503651sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);3652fprintf(fi.access.fp,3653"[%010lu] [error] [client %s] ",3654(unsigned long)timestamp,3655src_addr);36563657if (conn->request_info.request_method != NULL) {3658fprintf(fi.access.fp,3659"%s %s: ",3660conn->request_info.request_method,3661conn->request_info.request_uri3662? conn->request_info.request_uri3663: "");3664}36653666fprintf(fi.access.fp, "%s", buf);3667fputc('\n', fi.access.fp);3668fflush(fi.access.fp);3669funlockfile(fi.access.fp);3670(void)mg_fclose(&fi.access); /* Ignore errors. We can't call3671* mg_cry here anyway ;-) */3672}3673}3674}36753676#endif /* Externally provided function */367736783679static void3680mg_cry_internal_wrap(const struct mg_connection *conn,3681const char *func,3682unsigned line,3683const char *fmt,3684...)3685{3686va_list ap;3687va_start(ap, fmt);3688mg_cry_internal_impl(conn, func, line, fmt, ap);3689va_end(ap);3690}369136923693void3694mg_cry(const struct mg_connection *conn, const char *fmt, ...)3695{3696va_list ap;3697va_start(ap, fmt);3698mg_cry_internal_impl(conn, "user", 0, fmt, ap);3699va_end(ap);3700}370137023703#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal370437053706/* Return fake connection structure. Used for logging, if connection3707* is not applicable at the moment of logging. */3708static struct mg_connection *3709fc(struct mg_context *ctx)3710{3711static struct mg_connection fake_connection;3712fake_connection.phys_ctx = ctx;3713fake_connection.dom_ctx = &(ctx->dd);3714return &fake_connection;3715}371637173718const char *3719mg_version(void)3720{3721return CIVETWEB_VERSION;3722}372337243725const struct mg_request_info *3726mg_get_request_info(const struct mg_connection *conn)3727{3728if (!conn) {3729return NULL;3730}3731#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)3732if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {3733char txt[16];3734struct mg_workerTLS *tls =3735(struct mg_workerTLS *)pthread_getspecific(sTlsKey);37363737sprintf(txt, "%03i", conn->response_info.status_code);3738if (strlen(txt) == 3) {3739memcpy(tls->txtbuf, txt, 4);3740} else {3741strcpy(tls->txtbuf, "ERR");3742}37433744((struct mg_connection *)conn)->request_info.local_uri =3745((struct mg_connection *)conn)->request_info.request_uri =3746tls->txtbuf; /* use thread safe buffer */37473748((struct mg_connection *)conn)->request_info.num_headers =3749conn->response_info.num_headers;3750memcpy(((struct mg_connection *)conn)->request_info.http_headers,3751conn->response_info.http_headers,3752sizeof(conn->response_info.http_headers));3753} else3754#endif3755if (conn->connection_type != CONNECTION_TYPE_REQUEST) {3756return NULL;3757}3758return &conn->request_info;3759}376037613762const struct mg_response_info *3763mg_get_response_info(const struct mg_connection *conn)3764{3765if (!conn) {3766return NULL;3767}3768if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {3769return NULL;3770}3771return &conn->response_info;3772}377337743775static const char *3776get_proto_name(const struct mg_connection *conn)3777{3778#if defined(__clang__)3779#pragma clang diagnostic push3780#pragma clang diagnostic ignored "-Wunreachable-code"3781/* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be3782* not supported. Clang raises an "unreachable code" warning for parts of ?:3783* unreachable, but splitting into four different #ifdef clauses here is more3784* complicated.3785*/3786#endif37873788const struct mg_request_info *ri = &conn->request_info;37893790const char *proto =3791(is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")3792: (ri->is_ssl ? "https" : "http"));37933794return proto;37953796#if defined(__clang__)3797#pragma clang diagnostic pop3798#endif3799}380038013802int3803mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)3804{3805if ((buflen < 1) || (buf == 0) || (conn == 0)) {3806return -1;3807} else {38083809int truncated = 0;3810const struct mg_request_info *ri = &conn->request_info;38113812const char *proto = get_proto_name(conn);38133814if (ri->local_uri == NULL) {3815return -1;3816}38173818if ((ri->request_uri != NULL)3819&& (0 != strcmp(ri->local_uri, ri->request_uri))) {3820/* The request uri is different from the local uri.3821* This is usually if an absolute URI, including server3822* name has been provided. */3823mg_snprintf(conn,3824&truncated,3825buf,3826buflen,3827"%s://%s",3828proto,3829ri->request_uri);3830if (truncated) {3831return -1;3832}3833return 0;38343835} else {38363837/* The common case is a relative URI, so we have to3838* construct an absolute URI from server name and port */38393840#if defined(USE_IPV6)3841int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);3842int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)3843: htons(conn->client.lsa.sin.sin_port);3844#else3845int port = htons(conn->client.lsa.sin.sin_port);3846#endif3847int def_port = ri->is_ssl ? 443 : 80;3848int auth_domain_check_enabled =3849conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]3850&& (!mg_strcasecmp(3851conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));3852const char *server_domain =3853conn->dom_ctx->config[AUTHENTICATION_DOMAIN];38543855char portstr[16];3856char server_ip[48];38573858if (port != def_port) {3859sprintf(portstr, ":%u", (unsigned)port);3860} else {3861portstr[0] = 0;3862}38633864if (!auth_domain_check_enabled || !server_domain) {38653866sockaddr_to_string(server_ip,3867sizeof(server_ip),3868&conn->client.lsa);38693870server_domain = server_ip;3871}38723873mg_snprintf(conn,3874&truncated,3875buf,3876buflen,3877"%s://%s%s%s",3878proto,3879server_domain,3880portstr,3881ri->local_uri);3882if (truncated) {3883return -1;3884}3885return 0;3886}3887}3888}38893890/* Skip the characters until one of the delimiters characters found.3891* 0-terminate resulting word. Skip the delimiter and following whitespaces.3892* Advance pointer to buffer to the next word. Return found 0-terminated3893* word.3894* Delimiters can be quoted with quotechar. */3895static char *3896skip_quoted(char **buf,3897const char *delimiters,3898const char *whitespace,3899char quotechar)3900{3901char *p, *begin_word, *end_word, *end_whitespace;39023903begin_word = *buf;3904end_word = begin_word + strcspn(begin_word, delimiters);39053906/* Check for quotechar */3907if (end_word > begin_word) {3908p = end_word - 1;3909while (*p == quotechar) {3910/* While the delimiter is quoted, look for the next delimiter.3911*/3912/* This happens, e.g., in calls from parse_auth_header,3913* if the user name contains a " character. */39143915/* If there is anything beyond end_word, copy it. */3916if (*end_word != '\0') {3917size_t end_off = strcspn(end_word + 1, delimiters);3918memmove(p, end_word, end_off + 1);3919p += end_off; /* p must correspond to end_word - 1 */3920end_word += end_off + 1;3921} else {3922*p = '\0';3923break;3924}3925}3926for (p++; p < end_word; p++) {3927*p = '\0';3928}3929}39303931if (*end_word == '\0') {3932*buf = end_word;3933} else {39343935#if defined(GCC_DIAGNOSTIC)3936/* Disable spurious conversion warning for GCC */3937#pragma GCC diagnostic push3938#pragma GCC diagnostic ignored "-Wsign-conversion"3939#endif /* defined(GCC_DIAGNOSTIC) */39403941end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;39423943#if defined(GCC_DIAGNOSTIC)3944#pragma GCC diagnostic pop3945#endif /* defined(GCC_DIAGNOSTIC) */39463947for (p = end_word; p < end_whitespace; p++) {3948*p = '\0';3949}39503951*buf = end_whitespace;3952}39533954return begin_word;3955}395639573958/* Return HTTP header value, or NULL if not found. */3959static const char *3960get_header(const struct mg_header *hdr, int num_hdr, const char *name)3961{3962int i;3963for (i = 0; i < num_hdr; i++) {3964if (!mg_strcasecmp(name, hdr[i].name)) {3965return hdr[i].value;3966}3967}39683969return NULL;3970}397139723973#if defined(USE_WEBSOCKET)3974/* Retrieve requested HTTP header multiple values, and return the number of3975* found occurrences */3976static int3977get_req_headers(const struct mg_request_info *ri,3978const char *name,3979const char **output,3980int output_max_size)3981{3982int i;3983int cnt = 0;3984if (ri) {3985for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {3986if (!mg_strcasecmp(name, ri->http_headers[i].name)) {3987output[cnt++] = ri->http_headers[i].value;3988}3989}3990}3991return cnt;3992}3993#endif399439953996const char *3997mg_get_header(const struct mg_connection *conn, const char *name)3998{3999if (!conn) {4000return NULL;4001}40024003if (conn->connection_type == CONNECTION_TYPE_REQUEST) {4004return get_header(conn->request_info.http_headers,4005conn->request_info.num_headers,4006name);4007}4008if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {4009return get_header(conn->response_info.http_headers,4010conn->response_info.num_headers,4011name);4012}4013return NULL;4014}401540164017static const char *4018get_http_version(const struct mg_connection *conn)4019{4020if (!conn) {4021return NULL;4022}40234024if (conn->connection_type == CONNECTION_TYPE_REQUEST) {4025return conn->request_info.http_version;4026}4027if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {4028return conn->response_info.http_version;4029}4030return NULL;4031}403240334034/* A helper function for traversing a comma separated list of values.4035* It returns a list pointer shifted to the next value, or NULL if the end4036* of the list found.4037* Value is stored in val vector. If value has form "x=y", then eq_val4038* vector is initialized to point to the "y" part, and val vector length4039* is adjusted to point only to "x". */4040static const char *4041next_option(const char *list, struct vec *val, struct vec *eq_val)4042{4043int end;40444045reparse:4046if (val == NULL || list == NULL || *list == '\0') {4047/* End of the list */4048return NULL;4049}40504051/* Skip over leading LWS */4052while (*list == ' ' || *list == '\t')4053list++;40544055val->ptr = list;4056if ((list = strchr(val->ptr, ',')) != NULL) {4057/* Comma found. Store length and shift the list ptr */4058val->len = ((size_t)(list - val->ptr));4059list++;4060} else {4061/* This value is the last one */4062list = val->ptr + strlen(val->ptr);4063val->len = ((size_t)(list - val->ptr));4064}40654066/* Adjust length for trailing LWS */4067end = (int)val->len - 1;4068while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))4069end--;4070val->len = (size_t)(end + 1);40714072if (val->len == 0) {4073/* Ignore any empty entries. */4074goto reparse;4075}40764077if (eq_val != NULL) {4078/* Value has form "x=y", adjust pointers and lengths4079* so that val points to "x", and eq_val points to "y". */4080eq_val->len = 0;4081eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);4082if (eq_val->ptr != NULL) {4083eq_val->ptr++; /* Skip over '=' character */4084eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;4085val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;4086}4087}40884089return list;4090}409140924093/* A helper function for checking if a comma separated list of values4094* contains4095* the given option (case insensitvely).4096* 'header' can be NULL, in which case false is returned. */4097static int4098header_has_option(const char *header, const char *option)4099{4100struct vec opt_vec;4101struct vec eq_vec;41024103DEBUG_ASSERT(option != NULL);4104DEBUG_ASSERT(option[0] != '\0');41054106while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {4107if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)4108return 1;4109}41104111return 0;4112}411341144115/* Perform case-insensitive match of string against pattern */4116static ptrdiff_t4117match_prefix(const char *pattern, size_t pattern_len, const char *str)4118{4119const char *or_str;4120ptrdiff_t i, j, len, res;41214122if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {4123res = match_prefix(pattern, (size_t)(or_str - pattern), str);4124return (res > 0) ? res4125: match_prefix(or_str + 1,4126(size_t)((pattern + pattern_len)4127- (or_str + 1)),4128str);4129}41304131for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {4132if ((pattern[i] == '?') && (str[j] != '\0')) {4133continue;4134} else if (pattern[i] == '$') {4135return (str[j] == '\0') ? j : -1;4136} else if (pattern[i] == '*') {4137i++;4138if (pattern[i] == '*') {4139i++;4140len = strlen(str + j);4141} else {4142len = strcspn(str + j, "/");4143}4144if (i == (ptrdiff_t)pattern_len) {4145return j + len;4146}4147do {4148res = match_prefix(pattern + i, pattern_len - i, str + j + len);4149} while (res == -1 && len-- > 0);4150return (res == -1) ? -1 : j + res + len;4151} else if (lowercase(&pattern[i]) != lowercase(&str[j])) {4152return -1;4153}4154}4155return (ptrdiff_t)j;4156}415741584159/* HTTP 1.1 assumes keep alive if "Connection:" header is not set4160* This function must tolerate situations when connection info is not4161* set up, for example if request parsing failed. */4162static int4163should_keep_alive(const struct mg_connection *conn)4164{4165const char *http_version;4166const char *header;41674168/* First satisfy needs of the server */4169if ((conn == NULL) || conn->must_close) {4170/* Close, if civetweb framework needs to close */4171return 0;4172}41734174if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {4175/* Close, if keep alive is not enabled */4176return 0;4177}41784179/* Check explicit wish of the client */4180header = mg_get_header(conn, "Connection");4181if (header) {4182/* If there is a connection header from the client, obey */4183if (header_has_option(header, "keep-alive")) {4184return 1;4185}4186return 0;4187}41884189/* Use default of the standard */4190http_version = get_http_version(conn);4191if (http_version && (0 == strcmp(http_version, "1.1"))) {4192/* HTTP 1.1 default is keep alive */4193return 1;4194}41954196/* HTTP 1.0 (and earlier) default is to close the connection */4197return 0;4198}419942004201static int4202should_decode_url(const struct mg_connection *conn)4203{4204if (!conn || !conn->dom_ctx) {4205return 0;4206}42074208return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);4209}421042114212static const char *4213suggest_connection_header(const struct mg_connection *conn)4214{4215return should_keep_alive(conn) ? "keep-alive" : "close";4216}421742184219static int4220send_no_cache_header(struct mg_connection *conn)4221{4222/* Send all current and obsolete cache opt-out directives. */4223return mg_printf(conn,4224"Cache-Control: no-cache, no-store, "4225"must-revalidate, private, max-age=0\r\n"4226"Pragma: no-cache\r\n"4227"Expires: 0\r\n");4228}422942304231static int4232send_static_cache_header(struct mg_connection *conn)4233{4234#if !defined(NO_CACHING)4235/* Read the server config to check how long a file may be cached.4236* The configuration is in seconds. */4237int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);4238if (max_age <= 0) {4239/* 0 means "do not cache". All values <0 are reserved4240* and may be used differently in the future. */4241/* If a file should not be cached, do not only send4242* max-age=0, but also pragmas and Expires headers. */4243return send_no_cache_header(conn);4244}42454246/* Use "Cache-Control: max-age" instead of "Expires" header.4247* Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */4248/* See also https://www.mnot.net/cache_docs/ */4249/* According to RFC 2616, Section 14.21, caching times should not exceed4250* one year. A year with 365 days corresponds to 31536000 seconds, a4251* leap4252* year to 31622400 seconds. For the moment, we just send whatever has4253* been configured, still the behavior for >1 year should be considered4254* as undefined. */4255return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);4256#else /* NO_CACHING */4257return send_no_cache_header(conn);4258#endif /* !NO_CACHING */4259}426042614262static int4263send_additional_header(struct mg_connection *conn)4264{4265int i = 0;4266const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];42674268#if !defined(NO_SSL)4269if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {4270int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);4271if (max_age >= 0) {4272i += mg_printf(conn,4273"Strict-Transport-Security: max-age=%u\r\n",4274(unsigned)max_age);4275}4276}4277#endif42784279if (header && header[0]) {4280i += mg_printf(conn, "%s\r\n", header);4281}42824283return i;4284}428542864287static void handle_file_based_request(struct mg_connection *conn,4288const char *path,4289struct mg_file *filep);429042914292const char *4293mg_get_response_code_text(const struct mg_connection *conn, int response_code)4294{4295/* See IANA HTTP status code assignment:4296* http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml4297*/42984299switch (response_code) {4300/* RFC2616 Section 10.1 - Informational 1xx */4301case 100:4302return "Continue"; /* RFC2616 Section 10.1.1 */4303case 101:4304return "Switching Protocols"; /* RFC2616 Section 10.1.2 */4305case 102:4306return "Processing"; /* RFC2518 Section 10.1 */43074308/* RFC2616 Section 10.2 - Successful 2xx */4309case 200:4310return "OK"; /* RFC2616 Section 10.2.1 */4311case 201:4312return "Created"; /* RFC2616 Section 10.2.2 */4313case 202:4314return "Accepted"; /* RFC2616 Section 10.2.3 */4315case 203:4316return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */4317case 204:4318return "No Content"; /* RFC2616 Section 10.2.5 */4319case 205:4320return "Reset Content"; /* RFC2616 Section 10.2.6 */4321case 206:4322return "Partial Content"; /* RFC2616 Section 10.2.7 */4323case 207:4324return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.14325*/4326case 208:4327return "Already Reported"; /* RFC5842 Section 7.1 */43284329case 226:4330return "IM used"; /* RFC3229 Section 10.4.1 */43314332/* RFC2616 Section 10.3 - Redirection 3xx */4333case 300:4334return "Multiple Choices"; /* RFC2616 Section 10.3.1 */4335case 301:4336return "Moved Permanently"; /* RFC2616 Section 10.3.2 */4337case 302:4338return "Found"; /* RFC2616 Section 10.3.3 */4339case 303:4340return "See Other"; /* RFC2616 Section 10.3.4 */4341case 304:4342return "Not Modified"; /* RFC2616 Section 10.3.5 */4343case 305:4344return "Use Proxy"; /* RFC2616 Section 10.3.6 */4345case 307:4346return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */4347case 308:4348return "Permanent Redirect"; /* RFC7238 Section 3 */43494350/* RFC2616 Section 10.4 - Client Error 4xx */4351case 400:4352return "Bad Request"; /* RFC2616 Section 10.4.1 */4353case 401:4354return "Unauthorized"; /* RFC2616 Section 10.4.2 */4355case 402:4356return "Payment Required"; /* RFC2616 Section 10.4.3 */4357case 403:4358return "Forbidden"; /* RFC2616 Section 10.4.4 */4359case 404:4360return "Not Found"; /* RFC2616 Section 10.4.5 */4361case 405:4362return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */4363case 406:4364return "Not Acceptable"; /* RFC2616 Section 10.4.7 */4365case 407:4366return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */4367case 408:4368return "Request Time-out"; /* RFC2616 Section 10.4.9 */4369case 409:4370return "Conflict"; /* RFC2616 Section 10.4.10 */4371case 410:4372return "Gone"; /* RFC2616 Section 10.4.11 */4373case 411:4374return "Length Required"; /* RFC2616 Section 10.4.12 */4375case 412:4376return "Precondition Failed"; /* RFC2616 Section 10.4.13 */4377case 413:4378return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */4379case 414:4380return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */4381case 415:4382return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */4383case 416:4384return "Requested range not satisfiable"; /* RFC2616 Section 10.4.174385*/4386case 417:4387return "Expectation Failed"; /* RFC2616 Section 10.4.18 */43884389case 421:4390return "Misdirected Request"; /* RFC7540 Section 9.1.2 */4391case 422:4392return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC49184393* Section 11.2 */4394case 423:4395return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */4396case 424:4397return "Failed Dependency"; /* RFC2518 Section 10.5, RFC49184398* Section 11.4 */43994400case 426:4401return "Upgrade Required"; /* RFC 2817 Section 4 */44024403case 428:4404return "Precondition Required"; /* RFC 6585, Section 3 */4405case 429:4406return "Too Many Requests"; /* RFC 6585, Section 4 */44074408case 431:4409return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */44104411case 451:4412return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,4413* Section 3 */44144415/* RFC2616 Section 10.5 - Server Error 5xx */4416case 500:4417return "Internal Server Error"; /* RFC2616 Section 10.5.1 */4418case 501:4419return "Not Implemented"; /* RFC2616 Section 10.5.2 */4420case 502:4421return "Bad Gateway"; /* RFC2616 Section 10.5.3 */4422case 503:4423return "Service Unavailable"; /* RFC2616 Section 10.5.4 */4424case 504:4425return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */4426case 505:4427return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */4428case 506:4429return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */4430case 507:4431return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC49184432* Section 11.5 */4433case 508:4434return "Loop Detected"; /* RFC5842 Section 7.1 */44354436case 510:4437return "Not Extended"; /* RFC 2774, Section 7 */4438case 511:4439return "Network Authentication Required"; /* RFC 6585, Section 6 */44404441/* Other status codes, not shown in the IANA HTTP status code4442* assignment.4443* E.g., "de facto" standards due to common use, ... */4444case 418:4445return "I am a teapot"; /* RFC2324 Section 2.3.2 */4446case 419:4447return "Authentication Timeout"; /* common use */4448case 420:4449return "Enhance Your Calm"; /* common use */4450case 440:4451return "Login Timeout"; /* common use */4452case 509:4453return "Bandwidth Limit Exceeded"; /* common use */44544455default:4456/* This error code is unknown. This should not happen. */4457if (conn) {4458mg_cry_internal(conn,4459"Unknown HTTP response code: %u",4460response_code);4461}44624463/* Return at least a category according to RFC 2616 Section 10. */4464if (response_code >= 100 && response_code < 200) {4465/* Unknown informational status code */4466return "Information";4467}4468if (response_code >= 200 && response_code < 300) {4469/* Unknown success code */4470return "Success";4471}4472if (response_code >= 300 && response_code < 400) {4473/* Unknown redirection code */4474return "Redirection";4475}4476if (response_code >= 400 && response_code < 500) {4477/* Unknown request error code */4478return "Client Error";4479}4480if (response_code >= 500 && response_code < 600) {4481/* Unknown server error code */4482return "Server Error";4483}44844485/* Response code not even within reasonable range */4486return "";4487}4488}448944904491static int4492mg_send_http_error_impl(struct mg_connection *conn,4493int status,4494const char *fmt,4495va_list args)4496{4497char errmsg_buf[MG_BUF_LEN];4498char path_buf[PATH_MAX];4499va_list ap;4500int len, i, page_handler_found, scope, truncated, has_body;4501char date[64];4502time_t curtime = time(NULL);4503const char *error_handler = NULL;4504struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;4505const char *error_page_file_ext, *tstr;4506int handled_by_callback = 0;45074508const char *status_text = mg_get_response_code_text(conn, status);45094510if ((conn == NULL) || (fmt == NULL)) {4511return -2;4512}45134514/* Set status (for log) */4515conn->status_code = status;45164517/* Errors 1xx, 204 and 304 MUST NOT send a body */4518has_body = ((status > 199) && (status != 204) && (status != 304));45194520/* Prepare message in buf, if required */4521if (has_body4522|| (!conn->in_error_handler4523&& (conn->phys_ctx->callbacks.http_error != NULL))) {4524/* Store error message in errmsg_buf */4525va_copy(ap, args);4526mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);4527va_end(ap);4528/* In a debug build, print all html errors */4529DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);4530}45314532/* If there is a http_error callback, call it.4533* But don't do it recursively, if callback calls mg_send_http_error again.4534*/4535if (!conn->in_error_handler4536&& (conn->phys_ctx->callbacks.http_error != NULL)) {4537/* Mark in_error_handler to avoid recursion and call user callback. */4538conn->in_error_handler = 1;4539handled_by_callback =4540(conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)4541== 0);4542conn->in_error_handler = 0;4543}45444545if (!handled_by_callback) {4546/* Check for recursion */4547if (conn->in_error_handler) {4548DEBUG_TRACE(4549"Recursion when handling error %u - fall back to default",4550status);4551} else {4552/* Send user defined error pages, if defined */4553error_handler = conn->dom_ctx->config[ERROR_PAGES];4554error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];4555page_handler_found = 0;45564557if (error_handler != NULL) {4558for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {4559switch (scope) {4560case 1: /* Handler for specific error, e.g. 404 error */4561mg_snprintf(conn,4562&truncated,4563path_buf,4564sizeof(path_buf) - 32,4565"%serror%03u.",4566error_handler,4567status);4568break;4569case 2: /* Handler for error group, e.g., 5xx error4570* handler4571* for all server errors (500-599) */4572mg_snprintf(conn,4573&truncated,4574path_buf,4575sizeof(path_buf) - 32,4576"%serror%01uxx.",4577error_handler,4578status / 100);4579break;4580default: /* Handler for all errors */4581mg_snprintf(conn,4582&truncated,4583path_buf,4584sizeof(path_buf) - 32,4585"%serror.",4586error_handler);4587break;4588}45894590/* String truncation in buf may only occur if4591* error_handler is too long. This string is4592* from the config, not from a client. */4593(void)truncated;45944595len = (int)strlen(path_buf);45964597tstr = strchr(error_page_file_ext, '.');45984599while (tstr) {4600for (i = 1;4601(i < 32) && (tstr[i] != 0) && (tstr[i] != ',');4602i++) {4603/* buffer overrun is not possible here, since4604* (i < 32) && (len < sizeof(path_buf) - 32)4605* ==> (i + len) < sizeof(path_buf) */4606path_buf[len + i - 1] = tstr[i];4607}4608/* buffer overrun is not possible here, since4609* (i <= 32) && (len < sizeof(path_buf) - 32)4610* ==> (i + len) <= sizeof(path_buf) */4611path_buf[len + i - 1] = 0;46124613if (mg_stat(conn, path_buf, &error_page_file.stat)) {4614DEBUG_TRACE("Check error page %s - found",4615path_buf);4616page_handler_found = 1;4617break;4618}4619DEBUG_TRACE("Check error page %s - not found",4620path_buf);46214622tstr = strchr(tstr + i, '.');4623}4624}4625}46264627if (page_handler_found) {4628conn->in_error_handler = 1;4629handle_file_based_request(conn, path_buf, &error_page_file);4630conn->in_error_handler = 0;4631return 0;4632}4633}46344635/* No custom error page. Send default error page. */4636gmt_time_string(date, sizeof(date), &curtime);46374638conn->must_close = 1;4639mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);4640send_no_cache_header(conn);4641send_additional_header(conn);4642if (has_body) {4643mg_printf(conn,4644"%s",4645"Content-Type: text/plain; charset=utf-8\r\n");4646}4647mg_printf(conn,4648"Date: %s\r\n"4649"Connection: close\r\n\r\n",4650date);46514652/* HTTP responses 1xx, 204 and 304 MUST NOT send a body */4653if (has_body) {4654/* For other errors, send a generic error message. */4655mg_printf(conn, "Error %d: %s\n", status, status_text);4656mg_write(conn, errmsg_buf, strlen(errmsg_buf));46574658} else {4659/* No body allowed. Close the connection. */4660DEBUG_TRACE("Error %i", status);4661}4662}4663return 0;4664}466546664667int4668mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)4669{4670va_list ap;4671int ret;46724673va_start(ap, fmt);4674ret = mg_send_http_error_impl(conn, status, fmt, ap);4675va_end(ap);46764677return ret;4678}467946804681int4682mg_send_http_ok(struct mg_connection *conn,4683const char *mime_type,4684long long content_length)4685{4686char date[64];4687time_t curtime = time(NULL);46884689if ((mime_type == NULL) || (*mime_type == 0)) {4690/* Parameter error */4691return -2;4692}46934694gmt_time_string(date, sizeof(date), &curtime);46954696mg_printf(conn,4697"HTTP/1.1 200 OK\r\n"4698"Content-Type: %s\r\n"4699"Date: %s\r\n"4700"Connection: %s\r\n",4701mime_type,4702date,4703suggest_connection_header(conn));47044705send_no_cache_header(conn);4706send_additional_header(conn);4707if (content_length < 0) {4708mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");4709} else {4710mg_printf(conn,4711"Content-Length: %" UINT64_FMT "\r\n\r\n",4712(uint64_t)content_length);4713}47144715return 0;4716}471747184719int4720mg_send_http_redirect(struct mg_connection *conn,4721const char *target_url,4722int redirect_code)4723{4724/* Send a 30x redirect response.4725*4726* Redirect types (status codes):4727*4728* Status | Perm/Temp | Method | Version4729* 301 | permanent | POST->GET undefined | HTTP/1.04730* 302 | temporary | POST->GET undefined | HTTP/1.04731* 303 | temporary | always use GET | HTTP/1.14732* 307 | temporary | always keep method | HTTP/1.14733* 308 | permanent | always keep method | HTTP/1.14734*/4735const char *redirect_text;4736int ret;4737size_t content_len = 0;4738char reply[MG_BUF_LEN];47394740/* In case redirect_code=0, use 307. */4741if (redirect_code == 0) {4742redirect_code = 307;4743}47444745/* In case redirect_code is none of the above, return error. */4746if ((redirect_code != 301) && (redirect_code != 302)4747&& (redirect_code != 303) && (redirect_code != 307)4748&& (redirect_code != 308)) {4749/* Parameter error */4750return -2;4751}47524753/* Get proper text for response code */4754redirect_text = mg_get_response_code_text(conn, redirect_code);47554756/* If target_url is not defined, redirect to "/". */4757if ((target_url == NULL) || (*target_url == 0)) {4758target_url = "/";4759}47604761#if defined(MG_SEND_REDIRECT_BODY)4762/* TODO: condition name? */47634764/* Prepare a response body with a hyperlink.4765*4766* According to RFC2616 (and RFC1945 before):4767* Unless the request method was HEAD, the entity of the4768* response SHOULD contain a short hypertext note with a hyperlink to4769* the new URI(s).4770*4771* However, this response body is not useful in M2M communication.4772* Probably the original reason in the RFC was, clients not supporting4773* a 30x HTTP redirect could still show the HTML page and let the user4774* press the link. Since current browsers support 30x HTTP, the additional4775* HTML body does not seem to make sense anymore.4776*4777* The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),4778* but it only notes:4779* The server's response payload usually contains a short4780* hypertext note with a hyperlink to the new URI(s).4781*4782* Deactivated by default. If you need the 30x body, set the define.4783*/4784mg_snprintf(4785conn,4786NULL /* ignore truncation */,4787reply,4788sizeof(reply),4789"<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",4790redirect_text,4791target_url,4792target_url);4793content_len = strlen(reply);4794#else4795reply[0] = 0;4796#endif47974798/* Do not send any additional header. For all other options,4799* including caching, there are suitable defaults. */4800ret = mg_printf(conn,4801"HTTP/1.1 %i %s\r\n"4802"Location: %s\r\n"4803"Content-Length: %u\r\n"4804"Connection: %s\r\n\r\n",4805redirect_code,4806redirect_text,4807target_url,4808(unsigned int)content_len,4809suggest_connection_header(conn));48104811/* Send response body */4812if (ret > 0) {4813/* ... unless it is a HEAD request */4814if (0 != strcmp(conn->request_info.request_method, "HEAD")) {4815ret = mg_write(conn, reply, content_len);4816}4817}48184819return (ret > 0) ? ret : -1;4820}482148224823#if defined(_WIN32)4824/* Create substitutes for POSIX functions in Win32. */48254826#if defined(GCC_DIAGNOSTIC)4827/* Show no warning in case system functions are not used. */4828#pragma GCC diagnostic push4829#pragma GCC diagnostic ignored "-Wunused-function"4830#endif483148324833FUNCTION_MAY_BE_UNUSED4834static int4835pthread_mutex_init(pthread_mutex_t *mutex, void *unused)4836{4837(void)unused;4838*mutex = CreateMutex(NULL, FALSE, NULL);4839return (*mutex == NULL) ? -1 : 0;4840}48414842FUNCTION_MAY_BE_UNUSED4843static int4844pthread_mutex_destroy(pthread_mutex_t *mutex)4845{4846return (CloseHandle(*mutex) == 0) ? -1 : 0;4847}484848494850FUNCTION_MAY_BE_UNUSED4851static int4852pthread_mutex_lock(pthread_mutex_t *mutex)4853{4854return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 04855: -1;4856}485748584859#if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)4860FUNCTION_MAY_BE_UNUSED4861static int4862pthread_mutex_trylock(pthread_mutex_t *mutex)4863{4864switch (WaitForSingleObject(*mutex, 0)) {4865case WAIT_OBJECT_0:4866return 0;4867case WAIT_TIMEOUT:4868return -2; /* EBUSY */4869}4870return -1;4871}4872#endif487348744875FUNCTION_MAY_BE_UNUSED4876static int4877pthread_mutex_unlock(pthread_mutex_t *mutex)4878{4879return (ReleaseMutex(*mutex) == 0) ? -1 : 0;4880}488148824883FUNCTION_MAY_BE_UNUSED4884static int4885pthread_cond_init(pthread_cond_t *cv, const void *unused)4886{4887(void)unused;4888InitializeCriticalSection(&cv->threadIdSec);4889cv->waiting_thread = NULL;4890return 0;4891}489248934894FUNCTION_MAY_BE_UNUSED4895static int4896pthread_cond_timedwait(pthread_cond_t *cv,4897pthread_mutex_t *mutex,4898FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)4899{4900struct mg_workerTLS **ptls,4901*tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);4902int ok;4903int64_t nsnow, nswaitabs, nswaitrel;4904DWORD mswaitrel;49054906EnterCriticalSection(&cv->threadIdSec);4907/* Add this thread to cv's waiting list */4908ptls = &cv->waiting_thread;4909for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)4910;4911tls->next_waiting_thread = NULL;4912*ptls = tls;4913LeaveCriticalSection(&cv->threadIdSec);49144915if (abstime) {4916nsnow = mg_get_current_time_ns();4917nswaitabs =4918(((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;4919nswaitrel = nswaitabs - nsnow;4920if (nswaitrel < 0) {4921nswaitrel = 0;4922}4923mswaitrel = (DWORD)(nswaitrel / 1000000);4924} else {4925mswaitrel = (DWORD)INFINITE;4926}49274928pthread_mutex_unlock(mutex);4929ok = (WAIT_OBJECT_04930== WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));4931if (!ok) {4932ok = 1;4933EnterCriticalSection(&cv->threadIdSec);4934ptls = &cv->waiting_thread;4935for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {4936if (*ptls == tls) {4937*ptls = tls->next_waiting_thread;4938ok = 0;4939break;4940}4941}4942LeaveCriticalSection(&cv->threadIdSec);4943if (ok) {4944WaitForSingleObject(tls->pthread_cond_helper_mutex,4945(DWORD)INFINITE);4946}4947}4948/* This thread has been removed from cv's waiting list */4949pthread_mutex_lock(mutex);49504951return ok ? 0 : -1;4952}495349544955FUNCTION_MAY_BE_UNUSED4956static int4957pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)4958{4959return pthread_cond_timedwait(cv, mutex, NULL);4960}496149624963FUNCTION_MAY_BE_UNUSED4964static int4965pthread_cond_signal(pthread_cond_t *cv)4966{4967HANDLE wkup = NULL;4968BOOL ok = FALSE;49694970EnterCriticalSection(&cv->threadIdSec);4971if (cv->waiting_thread) {4972wkup = cv->waiting_thread->pthread_cond_helper_mutex;4973cv->waiting_thread = cv->waiting_thread->next_waiting_thread;49744975ok = SetEvent(wkup);4976DEBUG_ASSERT(ok);4977}4978LeaveCriticalSection(&cv->threadIdSec);49794980return ok ? 0 : 1;4981}498249834984FUNCTION_MAY_BE_UNUSED4985static int4986pthread_cond_broadcast(pthread_cond_t *cv)4987{4988EnterCriticalSection(&cv->threadIdSec);4989while (cv->waiting_thread) {4990pthread_cond_signal(cv);4991}4992LeaveCriticalSection(&cv->threadIdSec);49934994return 0;4995}499649974998FUNCTION_MAY_BE_UNUSED4999static int5000pthread_cond_destroy(pthread_cond_t *cv)5001{5002EnterCriticalSection(&cv->threadIdSec);5003DEBUG_ASSERT(cv->waiting_thread == NULL);5004LeaveCriticalSection(&cv->threadIdSec);5005DeleteCriticalSection(&cv->threadIdSec);50065007return 0;5008}500950105011#if defined(ALTERNATIVE_QUEUE)5012FUNCTION_MAY_BE_UNUSED5013static void *5014event_create(void)5015{5016return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);5017}501850195020FUNCTION_MAY_BE_UNUSED5021static int5022event_wait(void *eventhdl)5023{5024int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);5025return (res == WAIT_OBJECT_0);5026}502750285029FUNCTION_MAY_BE_UNUSED5030static int5031event_signal(void *eventhdl)5032{5033return (int)SetEvent((HANDLE)eventhdl);5034}503550365037FUNCTION_MAY_BE_UNUSED5038static void5039event_destroy(void *eventhdl)5040{5041CloseHandle((HANDLE)eventhdl);5042}5043#endif504450455046#if defined(GCC_DIAGNOSTIC)5047/* Enable unused function warning again */5048#pragma GCC diagnostic pop5049#endif505050515052/* For Windows, change all slashes to backslashes in path names. */5053static void5054change_slashes_to_backslashes(char *path)5055{5056int i;50575058for (i = 0; path[i] != '\0'; i++) {5059if (path[i] == '/') {5060path[i] = '\\';5061}50625063/* remove double backslash (check i > 0 to preserve UNC paths,5064* like \\server\file.txt) */5065if ((path[i] == '\\') && (i > 0)) {5066while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {5067(void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));5068}5069}5070}5071}507250735074static int5075mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)5076{5077int diff;50785079do {5080diff = tolower(*s1) - tolower(*s2);5081s1++;5082s2++;5083} while ((diff == 0) && (s1[-1] != '\0'));50845085return diff;5086}508750885089/* Encode 'path' which is assumed UTF-8 string, into UNICODE string.5090* wbuf and wbuf_len is a target buffer and its length. */5091static void5092path_to_unicode(const struct mg_connection *conn,5093const char *path,5094wchar_t *wbuf,5095size_t wbuf_len)5096{5097char buf[PATH_MAX], buf2[PATH_MAX];5098wchar_t wbuf2[W_PATH_MAX + 1];5099DWORD long_len, err;5100int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;51015102mg_strlcpy(buf, path, sizeof(buf));5103change_slashes_to_backslashes(buf);51045105/* Convert to Unicode and back. If doubly-converted string does not5106* match the original, something is fishy, reject. */5107memset(wbuf, 0, wbuf_len * sizeof(wchar_t));5108MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);5109WideCharToMultiByte(5110CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);5111if (strcmp(buf, buf2) != 0) {5112wbuf[0] = L'\0';5113}51145115/* Windows file systems are not case sensitive, but you can still use5116* uppercase and lowercase letters (on all modern file systems).5117* The server can check if the URI uses the same upper/lowercase5118* letters an the file system, effectively making Windows servers5119* case sensitive (like Linux servers are). It is still not possible5120* to use two files with the same name in different cases on Windows5121* (like /a and /A) - this would be possible in Linux.5122* As a default, Windows is not case sensitive, but the case sensitive5123* file name check can be activated by an additional configuration. */5124if (conn) {5125if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]5126&& !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],5127"yes")) {5128/* Use case sensitive compare function */5129fcompare = wcscmp;5130}5131}5132(void)conn; /* conn is currently unused */51335134#if !defined(_WIN32_WCE)5135/* Only accept a full file path, not a Windows short (8.3) path. */5136memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));5137long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);5138if (long_len == 0) {5139err = GetLastError();5140if (err == ERROR_FILE_NOT_FOUND) {5141/* File does not exist. This is not always a problem here. */5142return;5143}5144}5145if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {5146/* Short name is used. */5147wbuf[0] = L'\0';5148}5149#else5150(void)long_len;5151(void)wbuf2;5152(void)err;51535154if (strchr(path, '~')) {5155wbuf[0] = L'\0';5156}5157#endif5158}515951605161/* Windows happily opens files with some garbage at the end of file name.5162* For example, fopen("a.cgi ", "r") on Windows successfully opens5163* "a.cgi", despite one would expect an error back.5164* This function returns non-0 if path ends with some garbage. */5165static int5166path_cannot_disclose_cgi(const char *path)5167{5168static const char *allowed_last_characters = "_-";5169int last = path[strlen(path) - 1];5170return isalnum(last) || strchr(allowed_last_characters, last) != NULL;5171}517251735174static int5175mg_stat(const struct mg_connection *conn,5176const char *path,5177struct mg_file_stat *filep)5178{5179wchar_t wbuf[W_PATH_MAX];5180WIN32_FILE_ATTRIBUTE_DATA info;5181time_t creation_time;51825183if (!filep) {5184return 0;5185}5186memset(filep, 0, sizeof(*filep));51875188if (conn && is_file_in_memory(conn, path)) {5189/* filep->is_directory = 0; filep->gzipped = 0; .. already done by5190* memset */51915192/* Quick fix (for 1.9.x): */5193/* mg_stat must fill all fields, also for files in memory */5194struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;5195open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);5196filep->size = tmp_file.stat.size;5197filep->location = 2;5198/* TODO: for 1.10: restructure how files in memory are handled */51995200/* The "file in memory" feature is a candidate for deletion.5201* Please join the discussion at5202* https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI5203*/52045205filep->last_modified = time(NULL); /* TODO */5206/* last_modified = now ... assumes the file may change during5207* runtime,5208* so every mg_fopen call may return different data */5209/* last_modified = conn->phys_ctx.start_time;5210* May be used it the data does not change during runtime. This5211* allows5212* browser caching. Since we do not know, we have to assume the file5213* in memory may change. */5214return 1;5215}52165217path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));5218if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {5219filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);5220filep->last_modified =5221SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,5222info.ftLastWriteTime.dwHighDateTime);52235224/* On Windows, the file creation time can be higher than the5225* modification time, e.g. when a file is copied.5226* Since the Last-Modified timestamp is used for caching5227* it should be based on the most recent timestamp. */5228creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,5229info.ftCreationTime.dwHighDateTime);5230if (creation_time > filep->last_modified) {5231filep->last_modified = creation_time;5232}52335234filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;5235/* If file name is fishy, reset the file structure and return5236* error.5237* Note it is important to reset, not just return the error, cause5238* functions like is_file_opened() check the struct. */5239if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {5240memset(filep, 0, sizeof(*filep));5241return 0;5242}52435244return 1;5245}52465247return 0;5248}524952505251static int5252mg_remove(const struct mg_connection *conn, const char *path)5253{5254wchar_t wbuf[W_PATH_MAX];5255path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));5256return DeleteFileW(wbuf) ? 0 : -1;5257}525852595260static int5261mg_mkdir(const struct mg_connection *conn, const char *path, int mode)5262{5263wchar_t wbuf[W_PATH_MAX];5264(void)mode;5265path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));5266return CreateDirectoryW(wbuf, NULL) ? 0 : -1;5267}526852695270/* Create substitutes for POSIX functions in Win32. */52715272#if defined(GCC_DIAGNOSTIC)5273/* Show no warning in case system functions are not used. */5274#pragma GCC diagnostic push5275#pragma GCC diagnostic ignored "-Wunused-function"5276#endif527752785279/* Implementation of POSIX opendir/closedir/readdir for Windows. */5280FUNCTION_MAY_BE_UNUSED5281static DIR *5282mg_opendir(const struct mg_connection *conn, const char *name)5283{5284DIR *dir = NULL;5285wchar_t wpath[W_PATH_MAX];5286DWORD attrs;52875288if (name == NULL) {5289SetLastError(ERROR_BAD_ARGUMENTS);5290} else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {5291SetLastError(ERROR_NOT_ENOUGH_MEMORY);5292} else {5293path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));5294attrs = GetFileAttributesW(wpath);5295if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)5296&& ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {5297(void)wcscat(wpath, L"\\*");5298dir->handle = FindFirstFileW(wpath, &dir->info);5299dir->result.d_name[0] = '\0';5300} else {5301mg_free(dir);5302dir = NULL;5303}5304}53055306return dir;5307}530853095310FUNCTION_MAY_BE_UNUSED5311static int5312mg_closedir(DIR *dir)5313{5314int result = 0;53155316if (dir != NULL) {5317if (dir->handle != INVALID_HANDLE_VALUE)5318result = FindClose(dir->handle) ? 0 : -1;53195320mg_free(dir);5321} else {5322result = -1;5323SetLastError(ERROR_BAD_ARGUMENTS);5324}53255326return result;5327}532853295330FUNCTION_MAY_BE_UNUSED5331static struct dirent *5332mg_readdir(DIR *dir)5333{5334struct dirent *result = 0;53355336if (dir) {5337if (dir->handle != INVALID_HANDLE_VALUE) {5338result = &dir->result;5339(void)WideCharToMultiByte(CP_UTF8,53400,5341dir->info.cFileName,5342-1,5343result->d_name,5344sizeof(result->d_name),5345NULL,5346NULL);53475348if (!FindNextFileW(dir->handle, &dir->info)) {5349(void)FindClose(dir->handle);5350dir->handle = INVALID_HANDLE_VALUE;5351}53525353} else {5354SetLastError(ERROR_FILE_NOT_FOUND);5355}5356} else {5357SetLastError(ERROR_BAD_ARGUMENTS);5358}53595360return result;5361}536253635364#if !defined(HAVE_POLL)5365#define POLLIN (1) /* Data ready - read will not block. */5366#define POLLPRI (2) /* Priority data ready. */5367#define POLLOUT (4) /* Send queue not full - write will not block. */53685369FUNCTION_MAY_BE_UNUSED5370static int5371poll(struct pollfd *pfd, unsigned int n, int milliseconds)5372{5373struct timeval tv;5374fd_set rset;5375fd_set wset;5376unsigned int i;5377int result;5378SOCKET maxfd = 0;53795380memset(&tv, 0, sizeof(tv));5381tv.tv_sec = milliseconds / 1000;5382tv.tv_usec = (milliseconds % 1000) * 1000;5383FD_ZERO(&rset);5384FD_ZERO(&wset);53855386for (i = 0; i < n; i++) {5387if (pfd[i].events & POLLIN) {5388FD_SET((SOCKET)pfd[i].fd, &rset);5389} else if (pfd[i].events & POLLOUT) {5390FD_SET((SOCKET)pfd[i].fd, &wset);5391}5392pfd[i].revents = 0;53935394if (pfd[i].fd > maxfd) {5395maxfd = pfd[i].fd;5396}5397}53985399if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {5400for (i = 0; i < n; i++) {5401if (FD_ISSET(pfd[i].fd, &rset)) {5402pfd[i].revents |= POLLIN;5403}5404if (FD_ISSET(pfd[i].fd, &wset)) {5405pfd[i].revents |= POLLOUT;5406}5407}5408}54095410/* We should subtract the time used in select from remaining5411* "milliseconds", in particular if called from mg_poll with a5412* timeout quantum.5413* Unfortunately, the remaining time is not stored in "tv" in all5414* implementations, so the result in "tv" must be considered undefined.5415* See http://man7.org/linux/man-pages/man2/select.2.html */54165417return result;5418}5419#endif /* HAVE_POLL */542054215422#if defined(GCC_DIAGNOSTIC)5423/* Enable unused function warning again */5424#pragma GCC diagnostic pop5425#endif542654275428static void5429set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)5430{5431(void)conn; /* Unused. */5432#if defined(_WIN32_WCE)5433(void)sock;5434#else5435(void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);5436#endif5437}543854395440int5441mg_start_thread(mg_thread_func_t f, void *p)5442{5443#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)5444/* Compile-time option to control stack size, e.g.5445* -DUSE_STACK_SIZE=163845446*/5447return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)5448== ((uintptr_t)(-1L)))5449? -15450: 0);5451#else5452return (5453(_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))5454? -15455: 0);5456#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */5457}545854595460/* Start a thread storing the thread context. */5461static int5462mg_start_thread_with_id(unsigned(__stdcall *f)(void *),5463void *p,5464pthread_t *threadidptr)5465{5466uintptr_t uip;5467HANDLE threadhandle;5468int result = -1;54695470uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);5471threadhandle = (HANDLE)uip;5472if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {5473*threadidptr = threadhandle;5474result = 0;5475}54765477return result;5478}547954805481/* Wait for a thread to finish. */5482static int5483mg_join_thread(pthread_t threadid)5484{5485int result;5486DWORD dwevent;54875488result = -1;5489dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);5490if (dwevent == WAIT_FAILED) {5491DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);5492} else {5493if (dwevent == WAIT_OBJECT_0) {5494CloseHandle(threadid);5495result = 0;5496}5497}54985499return result;5500}55015502#if !defined(NO_SSL_DL) && !defined(NO_SSL)5503/* If SSL is loaded dynamically, dlopen/dlclose is required. */5504/* Create substitutes for POSIX functions in Win32. */55055506#if defined(GCC_DIAGNOSTIC)5507/* Show no warning in case system functions are not used. */5508#pragma GCC diagnostic push5509#pragma GCC diagnostic ignored "-Wunused-function"5510#endif551155125513FUNCTION_MAY_BE_UNUSED5514static HANDLE5515dlopen(const char *dll_name, int flags)5516{5517wchar_t wbuf[W_PATH_MAX];5518(void)flags;5519path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));5520return LoadLibraryW(wbuf);5521}552255235524FUNCTION_MAY_BE_UNUSED5525static int5526dlclose(void *handle)5527{5528int result;55295530if (FreeLibrary((HMODULE)handle) != 0) {5531result = 0;5532} else {5533result = -1;5534}55355536return result;5537}553855395540#if defined(GCC_DIAGNOSTIC)5541/* Enable unused function warning again */5542#pragma GCC diagnostic pop5543#endif55445545#endif554655475548#if !defined(NO_CGI)5549#define SIGKILL (0)555055515552static int5553kill(pid_t pid, int sig_num)5554{5555(void)TerminateProcess((HANDLE)pid, (UINT)sig_num);5556(void)CloseHandle((HANDLE)pid);5557return 0;5558}555955605561#if !defined(WNOHANG)5562#define WNOHANG (1)5563#endif556455655566static pid_t5567waitpid(pid_t pid, int *status, int flags)5568{5569DWORD timeout = INFINITE;5570DWORD waitres;55715572(void)status; /* Currently not used by any client here */55735574if ((flags | WNOHANG) == WNOHANG) {5575timeout = 0;5576}55775578waitres = WaitForSingleObject((HANDLE)pid, timeout);5579if (waitres == WAIT_OBJECT_0) {5580return pid;5581}5582if (waitres == WAIT_TIMEOUT) {5583return 0;5584}5585return (pid_t)-1;5586}558755885589static void5590trim_trailing_whitespaces(char *s)5591{5592char *e = s + strlen(s) - 1;5593while ((e > s) && isspace(*(unsigned char *)e)) {5594*e-- = '\0';5595}5596}559755985599static pid_t5600spawn_process(struct mg_connection *conn,5601const char *prog,5602char *envblk,5603char *envp[],5604int fdin[2],5605int fdout[2],5606int fderr[2],5607const char *dir)5608{5609HANDLE me;5610char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],5611cmdline[PATH_MAX], buf[PATH_MAX];5612int truncated;5613struct mg_file file = STRUCT_FILE_INITIALIZER;5614STARTUPINFOA si;5615PROCESS_INFORMATION pi = {0};56165617(void)envp;56185619memset(&si, 0, sizeof(si));5620si.cb = sizeof(si);56215622si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;5623si.wShowWindow = SW_HIDE;56245625me = GetCurrentProcess();5626DuplicateHandle(me,5627(HANDLE)_get_osfhandle(fdin[0]),5628me,5629&si.hStdInput,56300,5631TRUE,5632DUPLICATE_SAME_ACCESS);5633DuplicateHandle(me,5634(HANDLE)_get_osfhandle(fdout[1]),5635me,5636&si.hStdOutput,56370,5638TRUE,5639DUPLICATE_SAME_ACCESS);5640DuplicateHandle(me,5641(HANDLE)_get_osfhandle(fderr[1]),5642me,5643&si.hStdError,56440,5645TRUE,5646DUPLICATE_SAME_ACCESS);56475648/* Mark handles that should not be inherited. See5649* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx5650*/5651SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),5652HANDLE_FLAG_INHERIT,56530);5654SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),5655HANDLE_FLAG_INHERIT,56560);5657SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),5658HANDLE_FLAG_INHERIT,56590);56605661/* If CGI file is a script, try to read the interpreter line */5662interp = conn->dom_ctx->config[CGI_INTERPRETER];5663if (interp == NULL) {5664buf[0] = buf[1] = '\0';56655666/* Read the first line of the script into the buffer */5667mg_snprintf(5668conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);56695670if (truncated) {5671pi.hProcess = (pid_t)-1;5672goto spawn_cleanup;5673}56745675if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {5676#if defined(MG_USE_OPEN_FILE)5677p = (char *)file.access.membuf;5678#else5679p = (char *)NULL;5680#endif5681mg_fgets(buf, sizeof(buf), &file, &p);5682(void)mg_fclose(&file.access); /* ignore error on read only file */5683buf[sizeof(buf) - 1] = '\0';5684}56855686if ((buf[0] == '#') && (buf[1] == '!')) {5687trim_trailing_whitespaces(buf + 2);5688} else {5689buf[2] = '\0';5690}5691interp = buf + 2;5692}56935694if (interp[0] != '\0') {5695GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);5696interp = full_interp;5697}5698GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);56995700if (interp[0] != '\0') {5701mg_snprintf(conn,5702&truncated,5703cmdline,5704sizeof(cmdline),5705"\"%s\" \"%s\\%s\"",5706interp,5707full_dir,5708prog);5709} else {5710mg_snprintf(conn,5711&truncated,5712cmdline,5713sizeof(cmdline),5714"\"%s\\%s\"",5715full_dir,5716prog);5717}57185719if (truncated) {5720pi.hProcess = (pid_t)-1;5721goto spawn_cleanup;5722}57235724DEBUG_TRACE("Running [%s]", cmdline);5725if (CreateProcessA(NULL,5726cmdline,5727NULL,5728NULL,5729TRUE,5730CREATE_NEW_PROCESS_GROUP,5731envblk,5732NULL,5733&si,5734&pi)5735== 0) {5736mg_cry_internal(5737conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);5738pi.hProcess = (pid_t)-1;5739/* goto spawn_cleanup; */5740}57415742spawn_cleanup:5743(void)CloseHandle(si.hStdOutput);5744(void)CloseHandle(si.hStdError);5745(void)CloseHandle(si.hStdInput);5746if (pi.hThread != NULL) {5747(void)CloseHandle(pi.hThread);5748}57495750return (pid_t)pi.hProcess;5751}5752#endif /* !NO_CGI */575357545755static int5756set_blocking_mode(SOCKET sock)5757{5758unsigned long non_blocking = 0;5759return ioctlsocket(sock, (long)FIONBIO, &non_blocking);5760}57615762static int5763set_non_blocking_mode(SOCKET sock)5764{5765unsigned long non_blocking = 1;5766return ioctlsocket(sock, (long)FIONBIO, &non_blocking);5767}57685769#else57705771static int5772mg_stat(const struct mg_connection *conn,5773const char *path,5774struct mg_file_stat *filep)5775{5776struct stat st;5777if (!filep) {5778return 0;5779}5780memset(filep, 0, sizeof(*filep));57815782if (conn && is_file_in_memory(conn, path)) {57835784/* Quick fix (for 1.9.x): */5785/* mg_stat must fill all fields, also for files in memory */5786struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;5787open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);5788filep->size = tmp_file.stat.size;5789filep->last_modified = time(NULL);5790filep->location = 2;5791/* TODO: remove legacy "files in memory" feature */57925793return 1;5794}57955796if (0 == stat(path, &st)) {5797filep->size = (uint64_t)(st.st_size);5798filep->last_modified = st.st_mtime;5799filep->is_directory = S_ISDIR(st.st_mode);5800return 1;5801}58025803return 0;5804}580558065807static void5808set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)5809{5810if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {5811if (conn) {5812mg_cry_internal(conn,5813"%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",5814__func__,5815strerror(ERRNO));5816}5817}5818}581958205821int5822mg_start_thread(mg_thread_func_t func, void *param)5823{5824pthread_t thread_id;5825pthread_attr_t attr;5826int result;58275828(void)pthread_attr_init(&attr);5829(void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);58305831#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)5832/* Compile-time option to control stack size,5833* e.g. -DUSE_STACK_SIZE=16384 */5834(void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);5835#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */58365837result = pthread_create(&thread_id, &attr, func, param);5838pthread_attr_destroy(&attr);58395840return result;5841}584258435844/* Start a thread storing the thread context. */5845static int5846mg_start_thread_with_id(mg_thread_func_t func,5847void *param,5848pthread_t *threadidptr)5849{5850pthread_t thread_id;5851pthread_attr_t attr;5852int result;58535854(void)pthread_attr_init(&attr);58555856#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)5857/* Compile-time option to control stack size,5858* e.g. -DUSE_STACK_SIZE=16384 */5859(void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);5860#endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */58615862result = pthread_create(&thread_id, &attr, func, param);5863pthread_attr_destroy(&attr);5864if ((result == 0) && (threadidptr != NULL)) {5865*threadidptr = thread_id;5866}5867return result;5868}586958705871/* Wait for a thread to finish. */5872static int5873mg_join_thread(pthread_t threadid)5874{5875int result;58765877result = pthread_join(threadid, NULL);5878return result;5879}588058815882#if !defined(NO_CGI)5883static pid_t5884spawn_process(struct mg_connection *conn,5885const char *prog,5886char *envblk,5887char *envp[],5888int fdin[2],5889int fdout[2],5890int fderr[2],5891const char *dir)5892{5893pid_t pid;5894const char *interp;58955896(void)envblk;58975898if (conn == NULL) {5899return 0;5900}59015902if ((pid = fork()) == -1) {5903/* Parent */5904mg_send_http_error(conn,5905500,5906"Error: Creating CGI process\nfork(): %s",5907strerror(ERRNO));5908} else if (pid == 0) {5909/* Child */5910if (chdir(dir) != 0) {5911mg_cry_internal(5912conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));5913} else if (dup2(fdin[0], 0) == -1) {5914mg_cry_internal(conn,5915"%s: dup2(%d, 0): %s",5916__func__,5917fdin[0],5918strerror(ERRNO));5919} else if (dup2(fdout[1], 1) == -1) {5920mg_cry_internal(conn,5921"%s: dup2(%d, 1): %s",5922__func__,5923fdout[1],5924strerror(ERRNO));5925} else if (dup2(fderr[1], 2) == -1) {5926mg_cry_internal(conn,5927"%s: dup2(%d, 2): %s",5928__func__,5929fderr[1],5930strerror(ERRNO));5931} else {5932/* Keep stderr and stdout in two different pipes.5933* Stdout will be sent back to the client,5934* stderr should go into a server error log. */5935(void)close(fdin[0]);5936(void)close(fdout[1]);5937(void)close(fderr[1]);59385939/* Close write end fdin and read end fdout and fderr */5940(void)close(fdin[1]);5941(void)close(fdout[0]);5942(void)close(fderr[0]);59435944/* After exec, all signal handlers are restored to their default5945* values, with one exception of SIGCHLD. According to5946* POSIX.1-2001 and Linux's implementation, SIGCHLD's handler5947* will leave unchanged after exec if it was set to be ignored.5948* Restore it to default action. */5949signal(SIGCHLD, SIG_DFL);59505951interp = conn->dom_ctx->config[CGI_INTERPRETER];5952if (interp == NULL) {5953(void)execle(prog, prog, NULL, envp);5954mg_cry_internal(conn,5955"%s: execle(%s): %s",5956__func__,5957prog,5958strerror(ERRNO));5959} else {5960(void)execle(interp, interp, prog, NULL, envp);5961mg_cry_internal(conn,5962"%s: execle(%s %s): %s",5963__func__,5964interp,5965prog,5966strerror(ERRNO));5967}5968}5969exit(EXIT_FAILURE);5970}59715972return pid;5973}5974#endif /* !NO_CGI */597559765977static int5978set_non_blocking_mode(SOCKET sock)5979{5980int flags = fcntl(sock, F_GETFL, 0);5981if (flags < 0) {5982return -1;5983}59845985if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {5986return -1;5987}5988return 0;5989}59905991static int5992set_blocking_mode(SOCKET sock)5993{5994int flags = fcntl(sock, F_GETFL, 0);5995if (flags < 0) {5996return -1;5997}59985999if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {6000return -1;6001}6002return 0;6003}6004#endif /* _WIN32 / else */60056006/* End of initial operating system specific define block. */600760086009/* Get a random number (independent of C rand function) */6010static uint64_t6011get_random(void)6012{6013static uint64_t lfsr = 0; /* Linear feedback shift register */6014static uint64_t lcg = 0; /* Linear congruential generator */6015uint64_t now = mg_get_current_time_ns();60166017if (lfsr == 0) {6018/* lfsr will be only 0 if has not been initialized,6019* so this code is called only once. */6020lfsr = mg_get_current_time_ns();6021lcg = mg_get_current_time_ns();6022} else {6023/* Get the next step of both random number generators. */6024lfsr = (lfsr >> 1)6025| ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)6026<< 63);6027lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;6028}60296030/* Combining two pseudo-random number generators and a high resolution6031* part6032* of the current server time will make it hard (impossible?) to guess6033* the6034* next number. */6035return (lfsr ^ lcg ^ now);6036}603760386039static int6040mg_poll(struct pollfd *pfd,6041unsigned int n,6042int milliseconds,6043volatile int *stop_server)6044{6045/* Call poll, but only for a maximum time of a few seconds.6046* This will allow to stop the server after some seconds, instead6047* of having to wait for a long socket timeout. */6048int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */60496050do {6051int result;60526053if (*stop_server) {6054/* Shut down signal */6055return -2;6056}60576058if ((milliseconds >= 0) && (milliseconds < ms_now)) {6059ms_now = milliseconds;6060}60616062result = poll(pfd, n, ms_now);6063if (result != 0) {6064/* Poll returned either success (1) or error (-1).6065* Forward both to the caller. */6066return result;6067}60686069/* Poll returned timeout (0). */6070if (milliseconds > 0) {6071milliseconds -= ms_now;6072}60736074} while (milliseconds != 0);60756076/* timeout: return 0 */6077return 0;6078}607960806081/* Write data to the IO channel - opened file descriptor, socket or SSL6082* descriptor.6083* Return value:6084* >=0 .. number of bytes successfully written6085* -1 .. timeout6086* -2 .. error6087*/6088static int6089push_inner(struct mg_context *ctx,6090FILE *fp,6091SOCKET sock,6092SSL *ssl,6093const char *buf,6094int len,6095double timeout)6096{6097uint64_t start = 0, now = 0, timeout_ns = 0;6098int n, err;6099unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */61006101#if defined(_WIN32)6102typedef int len_t;6103#else6104typedef size_t len_t;6105#endif61066107if (timeout > 0) {6108now = mg_get_current_time_ns();6109start = now;6110timeout_ns = (uint64_t)(timeout * 1.0E9);6111}61126113if (ctx == NULL) {6114return -2;6115}61166117#if defined(NO_SSL)6118if (ssl) {6119return -2;6120}6121#endif61226123/* Try to read until it succeeds, fails, times out, or the server6124* shuts down. */6125for (;;) {61266127#if !defined(NO_SSL)6128if (ssl != NULL) {6129n = SSL_write(ssl, buf, len);6130if (n <= 0) {6131err = SSL_get_error(ssl, n);6132if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {6133err = ERRNO;6134} else if ((err == SSL_ERROR_WANT_READ)6135|| (err == SSL_ERROR_WANT_WRITE)) {6136n = 0;6137} else {6138DEBUG_TRACE("SSL_write() failed, error %d", err);6139return -2;6140}6141} else {6142err = 0;6143}6144} else6145#endif6146if (fp != NULL) {6147n = (int)fwrite(buf, 1, (size_t)len, fp);6148if (ferror(fp)) {6149n = -1;6150err = ERRNO;6151} else {6152err = 0;6153}6154} else {6155n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);6156err = (n < 0) ? ERRNO : 0;6157#if defined(_WIN32)6158if (err == WSAEWOULDBLOCK) {6159err = 0;6160n = 0;6161}6162#else6163if (err == EWOULDBLOCK) {6164err = 0;6165n = 0;6166}6167#endif6168if (n < 0) {6169/* shutdown of the socket at client side */6170return -2;6171}6172}61736174if (ctx->stop_flag) {6175return -2;6176}61776178if ((n > 0) || ((n == 0) && (len == 0))) {6179/* some data has been read, or no data was requested */6180return n;6181}6182if (n < 0) {6183/* socket error - check errno */6184DEBUG_TRACE("send() failed, error %d", err);61856186/* TODO (mid): error handling depending on the error code.6187* These codes are different between Windows and Linux.6188* Currently there is no problem with failing send calls,6189* if there is a reproducible situation, it should be6190* investigated in detail.6191*/6192return -2;6193}61946195/* Only in case n=0 (timeout), repeat calling the write function */61966197/* If send failed, wait before retry */6198if (fp != NULL) {6199/* For files, just wait a fixed time.6200* Maybe it helps, maybe not. */6201mg_sleep(5);6202} else {6203/* For sockets, wait for the socket using poll */6204struct pollfd pfd[1];6205int pollres;62066207pfd[0].fd = sock;6208pfd[0].events = POLLOUT;6209pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));6210if (ctx->stop_flag) {6211return -2;6212}6213if (pollres > 0) {6214continue;6215}6216}62176218if (timeout > 0) {6219now = mg_get_current_time_ns();6220if ((now - start) > timeout_ns) {6221/* Timeout */6222break;6223}6224}6225}62266227(void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not6228used */62296230return -1;6231}623262336234static int64_t6235push_all(struct mg_context *ctx,6236FILE *fp,6237SOCKET sock,6238SSL *ssl,6239const char *buf,6240int64_t len)6241{6242double timeout = -1.0;6243int64_t n, nwritten = 0;62446245if (ctx == NULL) {6246return -1;6247}62486249if (ctx->dd.config[REQUEST_TIMEOUT]) {6250timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;6251}62526253while ((len > 0) && (ctx->stop_flag == 0)) {6254n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);6255if (n < 0) {6256if (nwritten == 0) {6257nwritten = n; /* Propagate the error */6258}6259break;6260} else if (n == 0) {6261break; /* No more data to write */6262} else {6263nwritten += n;6264len -= n;6265}6266}62676268return nwritten;6269}627062716272/* Read from IO channel - opened file descriptor, socket, or SSL descriptor.6273* Return value:6274* >=0 .. number of bytes successfully read6275* -1 .. timeout6276* -2 .. error6277*/6278static int6279pull_inner(FILE *fp,6280struct mg_connection *conn,6281char *buf,6282int len,6283double timeout)6284{6285int nread, err = 0;62866287#if defined(_WIN32)6288typedef int len_t;6289#else6290typedef size_t len_t;6291#endif6292#if !defined(NO_SSL)6293int ssl_pending;6294#endif62956296/* We need an additional wait loop around this, because in some cases6297* with TLSwe may get data from the socket but not from SSL_read.6298* In this case we need to repeat at least once.6299*/63006301if (fp != NULL) {6302#if !defined(_WIN32_WCE)6303/* Use read() instead of fread(), because if we're reading from the6304* CGI pipe, fread() may block until IO buffer is filled up. We6305* cannot afford to block and must pass all read bytes immediately6306* to the client. */6307nread = (int)read(fileno(fp), buf, (size_t)len);6308#else6309/* WinCE does not support CGI pipes */6310nread = (int)fread(buf, 1, (size_t)len, fp);6311#endif6312err = (nread < 0) ? ERRNO : 0;6313if ((nread == 0) && (len > 0)) {6314/* Should get data, but got EOL */6315return -2;6316}63176318#if !defined(NO_SSL)6319} else if ((conn->ssl != NULL)6320&& ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {6321/* We already know there is no more data buffered in conn->buf6322* but there is more available in the SSL layer. So don't poll6323* conn->client.sock yet. */6324if (ssl_pending > len) {6325ssl_pending = len;6326}6327nread = SSL_read(conn->ssl, buf, ssl_pending);6328if (nread <= 0) {6329err = SSL_get_error(conn->ssl, nread);6330if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {6331err = ERRNO;6332} else if ((err == SSL_ERROR_WANT_READ)6333|| (err == SSL_ERROR_WANT_WRITE)) {6334nread = 0;6335} else {6336DEBUG_TRACE("SSL_read() failed, error %d", err);6337return -1;6338}6339} else {6340err = 0;6341}63426343} else if (conn->ssl != NULL) {63446345struct pollfd pfd[1];6346int pollres;63476348pfd[0].fd = conn->client.sock;6349pfd[0].events = POLLIN;6350pollres = mg_poll(pfd,63511,6352(int)(timeout * 1000.0),6353&(conn->phys_ctx->stop_flag));6354if (conn->phys_ctx->stop_flag) {6355return -2;6356}6357if (pollres > 0) {6358nread = SSL_read(conn->ssl, buf, len);6359if (nread <= 0) {6360err = SSL_get_error(conn->ssl, nread);6361if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {6362err = ERRNO;6363} else if ((err == SSL_ERROR_WANT_READ)6364|| (err == SSL_ERROR_WANT_WRITE)) {6365nread = 0;6366} else {6367DEBUG_TRACE("SSL_read() failed, error %d", err);6368return -2;6369}6370} else {6371err = 0;6372}63736374} else if (pollres < 0) {6375/* Error */6376return -2;6377} else {6378/* pollres = 0 means timeout */6379nread = 0;6380}6381#endif63826383} else {6384struct pollfd pfd[1];6385int pollres;63866387pfd[0].fd = conn->client.sock;6388pfd[0].events = POLLIN;6389pollres = mg_poll(pfd,63901,6391(int)(timeout * 1000.0),6392&(conn->phys_ctx->stop_flag));6393if (conn->phys_ctx->stop_flag) {6394return -2;6395}6396if (pollres > 0) {6397nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);6398err = (nread < 0) ? ERRNO : 0;6399if (nread <= 0) {6400/* shutdown of the socket at client side */6401return -2;6402}6403} else if (pollres < 0) {6404/* error callint poll */6405return -2;6406} else {6407/* pollres = 0 means timeout */6408nread = 0;6409}6410}64116412if (conn->phys_ctx->stop_flag) {6413return -2;6414}64156416if ((nread > 0) || ((nread == 0) && (len == 0))) {6417/* some data has been read, or no data was requested */6418return nread;6419}64206421if (nread < 0) {6422/* socket error - check errno */6423#if defined(_WIN32)6424if (err == WSAEWOULDBLOCK) {6425/* TODO (low): check if this is still required */6426/* standard case if called from close_socket_gracefully */6427return -2;6428} else if (err == WSAETIMEDOUT) {6429/* TODO (low): check if this is still required */6430/* timeout is handled by the while loop */6431return 0;6432} else if (err == WSAECONNABORTED) {6433/* See https://www.chilkatsoft.com/p/p_299.asp */6434return -2;6435} else {6436DEBUG_TRACE("recv() failed, error %d", err);6437return -2;6438}6439#else6440/* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,6441* if the timeout is reached and if the socket was set to non-6442* blocking in close_socket_gracefully, so we can not distinguish6443* here. We have to wait for the timeout in both cases for now.6444*/6445if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {6446/* TODO (low): check if this is still required */6447/* EAGAIN/EWOULDBLOCK:6448* standard case if called from close_socket_gracefully6449* => should return -1 */6450/* or timeout occurred6451* => the code must stay in the while loop */64526453/* EINTR can be generated on a socket with a timeout set even6454* when SA_RESTART is effective for all relevant signals6455* (see signal(7)).6456* => stay in the while loop */6457} else {6458DEBUG_TRACE("recv() failed, error %d", err);6459return -2;6460}6461#endif6462}64636464/* Timeout occurred, but no data available. */6465return -1;6466}646764686469static int6470pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)6471{6472int n, nread = 0;6473double timeout = -1.0;6474uint64_t start_time = 0, now = 0, timeout_ns = 0;64756476if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {6477timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;6478}6479if (timeout >= 0.0) {6480start_time = mg_get_current_time_ns();6481timeout_ns = (uint64_t)(timeout * 1.0E9);6482}64836484while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {6485n = pull_inner(fp, conn, buf + nread, len, timeout);6486if (n == -2) {6487if (nread == 0) {6488nread = -1; /* Propagate the error */6489}6490break;6491} else if (n == -1) {6492/* timeout */6493if (timeout >= 0.0) {6494now = mg_get_current_time_ns();6495if ((now - start_time) <= timeout_ns) {6496continue;6497}6498}6499break;6500} else if (n == 0) {6501break; /* No more data to read */6502} else {6503conn->consumed_content += n;6504nread += n;6505len -= n;6506}6507}65086509return nread;6510}651165126513static void6514discard_unread_request_data(struct mg_connection *conn)6515{6516char buf[MG_BUF_LEN];6517size_t to_read;6518int nread;65196520if (conn == NULL) {6521return;6522}65236524to_read = sizeof(buf);65256526if (conn->is_chunked) {6527/* Chunked encoding: 3=chunk read completely6528* completely */6529while (conn->is_chunked != 3) {6530nread = mg_read(conn, buf, to_read);6531if (nread <= 0) {6532break;6533}6534}65356536} else {6537/* Not chunked: content length is known */6538while (conn->consumed_content < conn->content_len) {6539if (to_read6540> (size_t)(conn->content_len - conn->consumed_content)) {6541to_read = (size_t)(conn->content_len - conn->consumed_content);6542}65436544nread = mg_read(conn, buf, to_read);6545if (nread <= 0) {6546break;6547}6548}6549}6550}655165526553static int6554mg_read_inner(struct mg_connection *conn, void *buf, size_t len)6555{6556int64_t n, buffered_len, nread;6557int64_t len64 =6558(int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is6559* int, we may not read more6560* bytes */6561const char *body;65626563if (conn == NULL) {6564return 0;6565}65666567/* If Content-Length is not set for a request with body data6568* (e.g., a PUT or POST request), we do not know in advance6569* how much data should be read. */6570if (conn->consumed_content == 0) {6571if (conn->is_chunked == 1) {6572conn->content_len = len64;6573conn->is_chunked = 2;6574} else if (conn->content_len == -1) {6575/* The body data is completed when the connection6576* is closed. */6577conn->content_len = INT64_MAX;6578conn->must_close = 1;6579}6580}65816582nread = 0;6583if (conn->consumed_content < conn->content_len) {6584/* Adjust number of bytes to read. */6585int64_t left_to_read = conn->content_len - conn->consumed_content;6586if (left_to_read < len64) {6587/* Do not read more than the total content length of the6588* request.6589*/6590len64 = left_to_read;6591}65926593/* Return buffered data */6594buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len6595- conn->consumed_content;6596if (buffered_len > 0) {6597if (len64 < buffered_len) {6598buffered_len = len64;6599}6600body = conn->buf + conn->request_len + conn->consumed_content;6601memcpy(buf, body, (size_t)buffered_len);6602len64 -= buffered_len;6603conn->consumed_content += buffered_len;6604nread += buffered_len;6605buf = (char *)buf + buffered_len;6606}66076608/* We have returned all buffered data. Read new data from the remote6609* socket.6610*/6611if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {6612nread += n;6613} else {6614nread = ((nread > 0) ? nread : n);6615}6616}6617return (int)nread;6618}661966206621static char6622mg_getc(struct mg_connection *conn)6623{6624char c;6625if (conn == NULL) {6626return 0;6627}6628if (mg_read_inner(conn, &c, 1) <= 0) {6629return (char)0;6630}6631return c;6632}663366346635int6636mg_read(struct mg_connection *conn, void *buf, size_t len)6637{6638if (len > INT_MAX) {6639len = INT_MAX;6640}66416642if (conn == NULL) {6643return 0;6644}66456646if (conn->is_chunked) {6647size_t all_read = 0;66486649while (len > 0) {6650if (conn->is_chunked == 3) {6651/* No more data left to read */6652return 0;6653}66546655if (conn->chunk_remainder) {6656/* copy from the remainder of the last received chunk */6657long read_ret;6658size_t read_now =6659((conn->chunk_remainder > len) ? (len)6660: (conn->chunk_remainder));66616662conn->content_len += (int)read_now;6663read_ret =6664mg_read_inner(conn, (char *)buf + all_read, read_now);66656666if (read_ret < 1) {6667/* read error */6668return -1;6669}66706671all_read += (size_t)read_ret;6672conn->chunk_remainder -= (size_t)read_ret;6673len -= (size_t)read_ret;66746675if (conn->chunk_remainder == 0) {6676/* Add data bytes in the current chunk have been read,6677* so we are expecting \r\n now. */6678char x1, x2;6679conn->content_len += 2;6680x1 = mg_getc(conn);6681x2 = mg_getc(conn);6682if ((x1 != '\r') || (x2 != '\n')) {6683/* Protocol violation */6684return -1;6685}6686}66876688} else {6689/* fetch a new chunk */6690int i = 0;6691char lenbuf[64];6692char *end = 0;6693unsigned long chunkSize = 0;66946695for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {6696conn->content_len++;6697lenbuf[i] = mg_getc(conn);6698if ((i > 0) && (lenbuf[i] == '\r')6699&& (lenbuf[i - 1] != '\r')) {6700continue;6701}6702if ((i > 1) && (lenbuf[i] == '\n')6703&& (lenbuf[i - 1] == '\r')) {6704lenbuf[i + 1] = 0;6705chunkSize = strtoul(lenbuf, &end, 16);6706if (chunkSize == 0) {6707/* regular end of content */6708conn->is_chunked = 3;6709}6710break;6711}6712if (!isxdigit(lenbuf[i])) {6713/* illegal character for chunk length */6714return -1;6715}6716}6717if ((end == NULL) || (*end != '\r')) {6718/* chunksize not set correctly */6719return -1;6720}6721if (chunkSize == 0) {6722break;6723}67246725conn->chunk_remainder = chunkSize;6726}6727}67286729return (int)all_read;6730}6731return mg_read_inner(conn, buf, len);6732}673367346735int6736mg_write(struct mg_connection *conn, const void *buf, size_t len)6737{6738time_t now;6739int64_t n, total, allowed;67406741if (conn == NULL) {6742return 0;6743}67446745if (conn->throttle > 0) {6746if ((now = time(NULL)) != conn->last_throttle_time) {6747conn->last_throttle_time = now;6748conn->last_throttle_bytes = 0;6749}6750allowed = conn->throttle - conn->last_throttle_bytes;6751if (allowed > (int64_t)len) {6752allowed = (int64_t)len;6753}6754if ((total = push_all(conn->phys_ctx,6755NULL,6756conn->client.sock,6757conn->ssl,6758(const char *)buf,6759(int64_t)allowed))6760== allowed) {6761buf = (const char *)buf + total;6762conn->last_throttle_bytes += total;6763while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {6764allowed = (conn->throttle > ((int64_t)len - total))6765? (int64_t)len - total6766: conn->throttle;6767if ((n = push_all(conn->phys_ctx,6768NULL,6769conn->client.sock,6770conn->ssl,6771(const char *)buf,6772(int64_t)allowed))6773!= allowed) {6774break;6775}6776sleep(1);6777conn->last_throttle_bytes = allowed;6778conn->last_throttle_time = time(NULL);6779buf = (const char *)buf + n;6780total += n;6781}6782}6783} else {6784total = push_all(conn->phys_ctx,6785NULL,6786conn->client.sock,6787conn->ssl,6788(const char *)buf,6789(int64_t)len);6790}6791if (total > 0) {6792conn->num_bytes_sent += total;6793}6794return (int)total;6795}679667976798/* Send a chunk, if "Transfer-Encoding: chunked" is used */6799int6800mg_send_chunk(struct mg_connection *conn,6801const char *chunk,6802unsigned int chunk_len)6803{6804char lenbuf[16];6805size_t lenbuf_len;6806int ret;6807int t;68086809/* First store the length information in a text buffer. */6810sprintf(lenbuf, "%x\r\n", chunk_len);6811lenbuf_len = strlen(lenbuf);68126813/* Then send length information, chunk and terminating \r\n. */6814ret = mg_write(conn, lenbuf, lenbuf_len);6815if (ret != (int)lenbuf_len) {6816return -1;6817}6818t = ret;68196820ret = mg_write(conn, chunk, chunk_len);6821if (ret != (int)chunk_len) {6822return -1;6823}6824t += ret;68256826ret = mg_write(conn, "\r\n", 2);6827if (ret != 2) {6828return -1;6829}6830t += ret;68316832return t;6833}683468356836#if defined(GCC_DIAGNOSTIC)6837/* This block forwards format strings to printf implementations,6838* so we need to disable the format-nonliteral warning. */6839#pragma GCC diagnostic push6840#pragma GCC diagnostic ignored "-Wformat-nonliteral"6841#endif684268436844/* Alternative alloc_vprintf() for non-compliant C runtimes */6845static int6846alloc_vprintf2(char **buf, const char *fmt, va_list ap)6847{6848va_list ap_copy;6849size_t size = MG_BUF_LEN / 4;6850int len = -1;68516852*buf = NULL;6853while (len < 0) {6854if (*buf) {6855mg_free(*buf);6856}68576858size *= 4;6859*buf = (char *)mg_malloc(size);6860if (!*buf) {6861break;6862}68636864va_copy(ap_copy, ap);6865len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);6866va_end(ap_copy);6867(*buf)[size - 1] = 0;6868}68696870return len;6871}687268736874/* Print message to buffer. If buffer is large enough to hold the message,6875* return buffer. If buffer is to small, allocate large enough buffer on6876* heap,6877* and return allocated buffer. */6878static int6879alloc_vprintf(char **out_buf,6880char *prealloc_buf,6881size_t prealloc_size,6882const char *fmt,6883va_list ap)6884{6885va_list ap_copy;6886int len;68876888/* Windows is not standard-compliant, and vsnprintf() returns -1 if6889* buffer is too small. Also, older versions of msvcrt.dll do not have6890* _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.6891* Therefore, we make two passes: on first pass, get required message6892* length.6893* On second pass, actually print the message. */6894va_copy(ap_copy, ap);6895len = vsnprintf_impl(NULL, 0, fmt, ap_copy);6896va_end(ap_copy);68976898if (len < 0) {6899/* C runtime is not standard compliant, vsnprintf() returned -1.6900* Switch to alternative code path that uses incremental6901* allocations.6902*/6903va_copy(ap_copy, ap);6904len = alloc_vprintf2(out_buf, fmt, ap_copy);6905va_end(ap_copy);69066907} else if ((size_t)(len) >= prealloc_size) {6908/* The pre-allocated buffer not large enough. */6909/* Allocate a new buffer. */6910*out_buf = (char *)mg_malloc((size_t)(len) + 1);6911if (!*out_buf) {6912/* Allocation failed. Return -1 as "out of memory" error. */6913return -1;6914}6915/* Buffer allocation successful. Store the string there. */6916va_copy(ap_copy, ap);6917IGNORE_UNUSED_RESULT(6918vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));6919va_end(ap_copy);69206921} else {6922/* The pre-allocated buffer is large enough.6923* Use it to store the string and return the address. */6924va_copy(ap_copy, ap);6925IGNORE_UNUSED_RESULT(6926vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));6927va_end(ap_copy);6928*out_buf = prealloc_buf;6929}69306931return len;6932}693369346935#if defined(GCC_DIAGNOSTIC)6936/* Enable format-nonliteral warning again. */6937#pragma GCC diagnostic pop6938#endif693969406941static int6942mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)6943{6944char mem[MG_BUF_LEN];6945char *buf = NULL;6946int len;69476948if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {6949len = mg_write(conn, buf, (size_t)len);6950}6951if ((buf != mem) && (buf != NULL)) {6952mg_free(buf);6953}69546955return len;6956}695769586959int6960mg_printf(struct mg_connection *conn, const char *fmt, ...)6961{6962va_list ap;6963int result;69646965va_start(ap, fmt);6966result = mg_vprintf(conn, fmt, ap);6967va_end(ap);69686969return result;6970}697169726973int6974mg_url_decode(const char *src,6975int src_len,6976char *dst,6977int dst_len,6978int is_form_url_encoded)6979{6980int i, j, a, b;6981#define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))69826983for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {6984if ((i < src_len - 2) && (src[i] == '%')6985&& isxdigit(*(const unsigned char *)(src + i + 1))6986&& isxdigit(*(const unsigned char *)(src + i + 2))) {6987a = tolower(*(const unsigned char *)(src + i + 1));6988b = tolower(*(const unsigned char *)(src + i + 2));6989dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));6990i += 2;6991} else if (is_form_url_encoded && (src[i] == '+')) {6992dst[j] = ' ';6993} else {6994dst[j] = src[i];6995}6996}69976998dst[j] = '\0'; /* Null-terminate the destination */69997000return (i >= src_len) ? j : -1;7001}700270037004int7005mg_get_var(const char *data,7006size_t data_len,7007const char *name,7008char *dst,7009size_t dst_len)7010{7011return mg_get_var2(data, data_len, name, dst, dst_len, 0);7012}701370147015int7016mg_get_var2(const char *data,7017size_t data_len,7018const char *name,7019char *dst,7020size_t dst_len,7021size_t occurrence)7022{7023const char *p, *e, *s;7024size_t name_len;7025int len;70267027if ((dst == NULL) || (dst_len == 0)) {7028len = -2;7029} else if ((data == NULL) || (name == NULL) || (data_len == 0)) {7030len = -1;7031dst[0] = '\0';7032} else {7033name_len = strlen(name);7034e = data + data_len;7035len = -1;7036dst[0] = '\0';70377038/* data is "var1=val1&var2=val2...". Find variable first */7039for (p = data; p + name_len < e; p++) {7040if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')7041&& !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {7042/* Point p to variable value */7043p += name_len + 1;70447045/* Point s to the end of the value */7046s = (const char *)memchr(p, '&', (size_t)(e - p));7047if (s == NULL) {7048s = e;7049}7050DEBUG_ASSERT(s >= p);7051if (s < p) {7052return -3;7053}70547055/* Decode variable into destination buffer */7056len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);70577058/* Redirect error code from -1 to -2 (destination buffer too7059* small). */7060if (len == -1) {7061len = -2;7062}7063break;7064}7065}7066}70677068return len;7069}707070717072/* HCP24: some changes to compare hole var_name */7073int7074mg_get_cookie(const char *cookie_header,7075const char *var_name,7076char *dst,7077size_t dst_size)7078{7079const char *s, *p, *end;7080int name_len, len = -1;70817082if ((dst == NULL) || (dst_size == 0)) {7083return -2;7084}70857086dst[0] = '\0';7087if ((var_name == NULL) || ((s = cookie_header) == NULL)) {7088return -1;7089}70907091name_len = (int)strlen(var_name);7092end = s + strlen(s);7093for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {7094if (s[name_len] == '=') {7095/* HCP24: now check is it a substring or a full cookie name */7096if ((s == cookie_header) || (s[-1] == ' ')) {7097s += name_len + 1;7098if ((p = strchr(s, ' ')) == NULL) {7099p = end;7100}7101if (p[-1] == ';') {7102p--;7103}7104if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {7105s++;7106p--;7107}7108if ((size_t)(p - s) < dst_size) {7109len = (int)(p - s);7110mg_strlcpy(dst, s, (size_t)len + 1);7111} else {7112len = -3;7113}7114break;7115}7116}7117}7118return len;7119}712071217122#if defined(USE_WEBSOCKET) || defined(USE_LUA)7123static void7124base64_encode(const unsigned char *src, int src_len, char *dst)7125{7126static const char *b64 =7127"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";7128int i, j, a, b, c;71297130for (i = j = 0; i < src_len; i += 3) {7131a = src[i];7132b = ((i + 1) >= src_len) ? 0 : src[i + 1];7133c = ((i + 2) >= src_len) ? 0 : src[i + 2];71347135dst[j++] = b64[a >> 2];7136dst[j++] = b64[((a & 3) << 4) | (b >> 4)];7137if (i + 1 < src_len) {7138dst[j++] = b64[(b & 15) << 2 | (c >> 6)];7139}7140if (i + 2 < src_len) {7141dst[j++] = b64[c & 63];7142}7143}7144while (j % 4 != 0) {7145dst[j++] = '=';7146}7147dst[j++] = '\0';7148}7149#endif715071517152#if defined(USE_LUA)7153static unsigned char7154b64reverse(char letter)7155{7156if ((letter >= 'A') && (letter <= 'Z')) {7157return letter - 'A';7158}7159if ((letter >= 'a') && (letter <= 'z')) {7160return letter - 'a' + 26;7161}7162if ((letter >= '0') && (letter <= '9')) {7163return letter - '0' + 52;7164}7165if (letter == '+') {7166return 62;7167}7168if (letter == '/') {7169return 63;7170}7171if (letter == '=') {7172return 255; /* normal end */7173}7174return 254; /* error */7175}717671777178static int7179base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)7180{7181int i;7182unsigned char a, b, c, d;71837184*dst_len = 0;71857186for (i = 0; i < src_len; i += 4) {7187a = b64reverse(src[i]);7188if (a >= 254) {7189return i;7190}71917192b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);7193if (b >= 254) {7194return i + 1;7195}71967197c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);7198if (c == 254) {7199return i + 2;7200}72017202d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);7203if (d == 254) {7204return i + 3;7205}72067207dst[(*dst_len)++] = (a << 2) + (b >> 4);7208if (c != 255) {7209dst[(*dst_len)++] = (b << 4) + (c >> 2);7210if (d != 255) {7211dst[(*dst_len)++] = (c << 6) + d;7212}7213}7214}7215return -1;7216}7217#endif721872197220static int7221is_put_or_delete_method(const struct mg_connection *conn)7222{7223if (conn) {7224const char *s = conn->request_info.request_method;7225return (s != NULL)7226&& (!strcmp(s, "PUT") || !strcmp(s, "DELETE")7227|| !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));7228}7229return 0;7230}723172327233#if !defined(NO_FILES)7234static int7235extention_matches_script(7236struct mg_connection *conn, /* in: request (must be valid) */7237const char *filename /* in: filename (must be valid) */7238)7239{7240#if !defined(NO_CGI)7241if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],7242strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),7243filename)7244> 0) {7245return 1;7246}7247#endif7248#if defined(USE_LUA)7249if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],7250strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),7251filename)7252> 0) {7253return 1;7254}7255#endif7256#if defined(USE_DUKTAPE)7257if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],7258strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),7259filename)7260> 0) {7261return 1;7262}7263#endif7264/* filename and conn could be unused, if all preocessor conditions7265* are false (no script language supported). */7266(void)filename;7267(void)conn;72687269return 0;7270}727172727273/* For given directory path, substitute it to valid index file.7274* Return 1 if index file has been found, 0 if not found.7275* If the file is found, it's stats is returned in stp. */7276static int7277substitute_index_file(struct mg_connection *conn,7278char *path,7279size_t path_len,7280struct mg_file_stat *filestat)7281{7282const char *list = conn->dom_ctx->config[INDEX_FILES];7283struct vec filename_vec;7284size_t n = strlen(path);7285int found = 0;72867287/* The 'path' given to us points to the directory. Remove all trailing7288* directory separator characters from the end of the path, and7289* then append single directory separator character. */7290while ((n > 0) && (path[n - 1] == '/')) {7291n--;7292}7293path[n] = '/';72947295/* Traverse index files list. For each entry, append it to the given7296* path and see if the file exists. If it exists, break the loop */7297while ((list = next_option(list, &filename_vec, NULL)) != NULL) {7298/* Ignore too long entries that may overflow path buffer */7299if ((filename_vec.len + 1) > (path_len - (n + 1))) {7300continue;7301}73027303/* Prepare full path to the index file */7304mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);73057306/* Does it exist? */7307if (mg_stat(conn, path, filestat)) {7308/* Yes it does, break the loop */7309found = 1;7310break;7311}7312}73137314/* If no index file exists, restore directory path */7315if (!found) {7316path[n] = '\0';7317}73187319return found;7320}7321#endif732273237324static void7325interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */7326char *filename, /* out: filename */7327size_t filename_buf_len, /* in: size of filename buffer */7328struct mg_file_stat *filestat, /* out: file status structure */7329int *is_found, /* out: file found (directly) */7330int *is_script_resource, /* out: handled by a script? */7331int *is_websocket_request, /* out: websocket connetion? */7332int *is_put_or_delete_request /* out: put/delete a file? */7333)7334{7335char const *accept_encoding;73367337#if !defined(NO_FILES)7338const char *uri = conn->request_info.local_uri;7339const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];7340const char *rewrite;7341struct vec a, b;7342ptrdiff_t match_len;7343char gz_path[PATH_MAX];7344int truncated;7345#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)7346char *tmp_str;7347size_t tmp_str_len, sep_pos;7348int allow_substitute_script_subresources;7349#endif7350#else7351(void)filename_buf_len; /* unused if NO_FILES is defined */7352#endif73537354/* Step 1: Set all initially unknown outputs to zero */7355memset(filestat, 0, sizeof(*filestat));7356*filename = 0;7357*is_found = 0;7358*is_script_resource = 0;73597360/* Step 2: Check if the request attempts to modify the file system */7361*is_put_or_delete_request = is_put_or_delete_method(conn);73627363/* Step 3: Check if it is a websocket request, and modify the document7364* root if required */7365#if defined(USE_WEBSOCKET)7366*is_websocket_request = is_websocket_protocol(conn);7367#if !defined(NO_FILES)7368if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {7369root = conn->dom_ctx->config[WEBSOCKET_ROOT];7370}7371#endif /* !NO_FILES */7372#else /* USE_WEBSOCKET */7373*is_websocket_request = 0;7374#endif /* USE_WEBSOCKET */73757376/* Step 4: Check if gzip encoded response is allowed */7377conn->accept_gzip = 0;7378if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {7379if (strstr(accept_encoding, "gzip") != NULL) {7380conn->accept_gzip = 1;7381}7382}73837384#if !defined(NO_FILES)7385/* Step 5: If there is no root directory, don't look for files. */7386/* Note that root == NULL is a regular use case here. This occurs,7387* if all requests are handled by callbacks, so the WEBSOCKET_ROOT7388* config is not required. */7389if (root == NULL) {7390/* all file related outputs have already been set to 0, just return7391*/7392return;7393}73947395/* Step 6: Determine the local file path from the root path and the7396* request uri. */7397/* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift7398* part of the path one byte on the right. */7399mg_snprintf(7400conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);74017402if (truncated) {7403goto interpret_cleanup;7404}74057406/* Step 7: URI rewriting */7407rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];7408while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {7409if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {7410mg_snprintf(conn,7411&truncated,7412filename,7413filename_buf_len - 1,7414"%.*s%s",7415(int)b.len,7416b.ptr,7417uri + match_len);7418break;7419}7420}74217422if (truncated) {7423goto interpret_cleanup;7424}74257426/* Step 8: Check if the file exists at the server */7427/* Local file path and name, corresponding to requested URI7428* is now stored in "filename" variable. */7429if (mg_stat(conn, filename, filestat)) {7430int uri_len = (int)strlen(uri);7431int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');74327433/* 8.1: File exists. */7434*is_found = 1;74357436/* 8.2: Check if it is a script type. */7437if (extention_matches_script(conn, filename)) {7438/* The request addresses a CGI resource, Lua script or7439* server-side javascript.7440* The URI corresponds to the script itself (like7441* /path/script.cgi), and there is no additional resource7442* path (like /path/script.cgi/something).7443* Requests that modify (replace or delete) a resource, like7444* PUT and DELETE requests, should replace/delete the script7445* file.7446* Requests that read or write from/to a resource, like GET and7447* POST requests, should call the script and return the7448* generated response. */7449*is_script_resource = (!*is_put_or_delete_request);7450}74517452/* 8.3: If the request target is a directory, there could be7453* a substitute file (index.html, index.cgi, ...). */7454if (filestat->is_directory && is_uri_end_slash) {7455/* Use a local copy here, since substitute_index_file will7456* change the content of the file status */7457struct mg_file_stat tmp_filestat;7458memset(&tmp_filestat, 0, sizeof(tmp_filestat));74597460if (substitute_index_file(7461conn, filename, filename_buf_len, &tmp_filestat)) {74627463/* Substitute file found. Copy stat to the output, then7464* check if the file is a script file */7465*filestat = tmp_filestat;74667467if (extention_matches_script(conn, filename)) {7468/* Substitute file is a script file */7469*is_script_resource = 1;7470} else {7471/* Substitute file is a regular file */7472*is_script_resource = 0;7473*is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);7474}7475}7476/* If there is no substitute file, the server could return7477* a directory listing in a later step */7478}7479return;7480}74817482/* Step 9: Check for zipped files: */7483/* If we can't find the actual file, look for the file7484* with the same name but a .gz extension. If we find it,7485* use that and set the gzipped flag in the file struct7486* to indicate that the response need to have the content-7487* encoding: gzip header.7488* We can only do this if the browser declares support. */7489if (conn->accept_gzip) {7490mg_snprintf(7491conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);74927493if (truncated) {7494goto interpret_cleanup;7495}74967497if (mg_stat(conn, gz_path, filestat)) {7498if (filestat) {7499filestat->is_gzipped = 1;7500*is_found = 1;7501}7502/* Currently gz files can not be scripts. */7503return;7504}7505}75067507#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)7508/* Step 10: Script resources may handle sub-resources */7509/* Support PATH_INFO for CGI scripts. */7510tmp_str_len = strlen(filename);7511tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);7512if (!tmp_str) {7513/* Out of memory */7514goto interpret_cleanup;7515}7516memcpy(tmp_str, filename, tmp_str_len + 1);75177518/* Check config, if index scripts may have sub-resources */7519allow_substitute_script_subresources =7520!mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],7521"yes");75227523sep_pos = tmp_str_len;7524while (sep_pos > 0) {7525sep_pos--;7526if (tmp_str[sep_pos] == '/') {7527int is_script = 0, does_exist = 0;75287529tmp_str[sep_pos] = 0;7530if (tmp_str[0]) {7531is_script = extention_matches_script(conn, tmp_str);7532does_exist = mg_stat(conn, tmp_str, filestat);7533}75347535if (does_exist && is_script) {7536filename[sep_pos] = 0;7537memmove(filename + sep_pos + 2,7538filename + sep_pos + 1,7539strlen(filename + sep_pos + 1) + 1);7540conn->path_info = filename + sep_pos + 1;7541filename[sep_pos + 1] = '/';7542*is_script_resource = 1;7543*is_found = 1;7544break;7545}75467547if (allow_substitute_script_subresources) {7548if (substitute_index_file(7549conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {75507551/* some intermediate directory has an index file */7552if (extention_matches_script(conn, tmp_str)) {75537554char *tmp_str2;75557556DEBUG_TRACE("Substitute script %s serving path %s",7557tmp_str,7558filename);75597560/* this index file is a script */7561tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,7562conn->phys_ctx);7563mg_snprintf(conn,7564&truncated,7565filename,7566filename_buf_len,7567"%s//%s",7568tmp_str,7569tmp_str2);7570mg_free(tmp_str2);75717572if (truncated) {7573mg_free(tmp_str);7574goto interpret_cleanup;7575}7576sep_pos = strlen(tmp_str);7577filename[sep_pos] = 0;7578conn->path_info = filename + sep_pos + 1;7579*is_script_resource = 1;7580*is_found = 1;7581break;75827583} else {75847585DEBUG_TRACE("Substitute file %s serving path %s",7586tmp_str,7587filename);75887589/* non-script files will not have sub-resources */7590filename[sep_pos] = 0;7591conn->path_info = 0;7592*is_script_resource = 0;7593*is_found = 0;7594break;7595}7596}7597}75987599tmp_str[sep_pos] = '/';7600}7601}76027603mg_free(tmp_str);76047605#endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */7606#endif /* !defined(NO_FILES) */7607return;76087609#if !defined(NO_FILES)7610/* Reset all outputs */7611interpret_cleanup:7612memset(filestat, 0, sizeof(*filestat));7613*filename = 0;7614*is_found = 0;7615*is_script_resource = 0;7616*is_websocket_request = 0;7617*is_put_or_delete_request = 0;7618#endif /* !defined(NO_FILES) */7619}762076217622/* Check whether full request is buffered. Return:7623* -1 if request or response is malformed7624* 0 if request or response is not yet fully buffered7625* >0 actual request length, including last \r\n\r\n */7626static int7627get_http_header_len(const char *buf, int buflen)7628{7629int i;7630for (i = 0; i < buflen; i++) {7631/* Do an unsigned comparison in some conditions below */7632const unsigned char c = ((const unsigned char *)buf)[i];76337634if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')7635&& !isprint(c)) {7636/* abort scan as soon as one malformed character is found */7637return -1;7638}76397640if (i < buflen - 1) {7641if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {7642/* Two newline, no carriage return - not standard compliant,7643* but7644* it7645* should be accepted */7646return i + 2;7647}7648}76497650if (i < buflen - 3) {7651if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')7652&& (buf[i + 3] == '\n')) {7653/* Two \r\n - standard compliant */7654return i + 4;7655}7656}7657}76587659return 0;7660}766176627663#if !defined(NO_CACHING)7664/* Convert month to the month number. Return -1 on error, or month number */7665static int7666get_month_index(const char *s)7667{7668size_t i;76697670for (i = 0; i < ARRAY_SIZE(month_names); i++) {7671if (!strcmp(s, month_names[i])) {7672return (int)i;7673}7674}76757676return -1;7677}767876797680/* Parse UTC date-time string, and return the corresponding time_t value. */7681static time_t7682parse_date_string(const char *datetime)7683{7684char month_str[32] = {0};7685int second, minute, hour, day, month, year;7686time_t result = (time_t)0;7687struct tm tm;76887689if ((sscanf(datetime,7690"%d/%3s/%d %d:%d:%d",7691&day,7692month_str,7693&year,7694&hour,7695&minute,7696&second)7697== 6)7698|| (sscanf(datetime,7699"%d %3s %d %d:%d:%d",7700&day,7701month_str,7702&year,7703&hour,7704&minute,7705&second)7706== 6)7707|| (sscanf(datetime,7708"%*3s, %d %3s %d %d:%d:%d",7709&day,7710month_str,7711&year,7712&hour,7713&minute,7714&second)7715== 6)7716|| (sscanf(datetime,7717"%d-%3s-%d %d:%d:%d",7718&day,7719month_str,7720&year,7721&hour,7722&minute,7723&second)7724== 6)) {7725month = get_month_index(month_str);7726if ((month >= 0) && (year >= 1970)) {7727memset(&tm, 0, sizeof(tm));7728tm.tm_year = year - 1900;7729tm.tm_mon = month;7730tm.tm_mday = day;7731tm.tm_hour = hour;7732tm.tm_min = minute;7733tm.tm_sec = second;7734result = timegm(&tm);7735}7736}77377738return result;7739}7740#endif /* !NO_CACHING */774177427743/* Protect against directory disclosure attack by removing '..',7744* excessive '/' and '\' characters */7745static void7746remove_double_dots_and_double_slashes(char *s)7747{7748char *p = s;77497750while ((s[0] == '.') && (s[1] == '.')) {7751s++;7752}77537754while (*s != '\0') {7755*p++ = *s++;7756if ((s[-1] == '/') || (s[-1] == '\\')) {7757/* Skip all following slashes, backslashes and double-dots */7758while (s[0] != '\0') {7759if ((s[0] == '/') || (s[0] == '\\')) {7760s++;7761} else if ((s[0] == '.') && (s[1] == '.')) {7762s += 2;7763} else {7764break;7765}7766}7767}7768}7769*p = '\0';7770}777177727773static const struct {7774const char *extension;7775size_t ext_len;7776const char *mime_type;7777} builtin_mime_types[] = {7778/* IANA registered MIME types7779* (http://www.iana.org/assignments/media-types)7780* application types */7781{".doc", 4, "application/msword"},7782{".eps", 4, "application/postscript"},7783{".exe", 4, "application/octet-stream"},7784{".js", 3, "application/javascript"},7785{".json", 5, "application/json"},7786{".pdf", 4, "application/pdf"},7787{".ps", 3, "application/postscript"},7788{".rtf", 4, "application/rtf"},7789{".xhtml", 6, "application/xhtml+xml"},7790{".xsl", 4, "application/xml"},7791{".xslt", 5, "application/xml"},77927793/* fonts */7794{".ttf", 4, "application/font-sfnt"},7795{".cff", 4, "application/font-sfnt"},7796{".otf", 4, "application/font-sfnt"},7797{".aat", 4, "application/font-sfnt"},7798{".sil", 4, "application/font-sfnt"},7799{".pfr", 4, "application/font-tdpfr"},7800{".woff", 5, "application/font-woff"},78017802/* audio */7803{".mp3", 4, "audio/mpeg"},7804{".oga", 4, "audio/ogg"},7805{".ogg", 4, "audio/ogg"},78067807/* image */7808{".gif", 4, "image/gif"},7809{".ief", 4, "image/ief"},7810{".jpeg", 5, "image/jpeg"},7811{".jpg", 4, "image/jpeg"},7812{".jpm", 4, "image/jpm"},7813{".jpx", 4, "image/jpx"},7814{".png", 4, "image/png"},7815{".svg", 4, "image/svg+xml"},7816{".tif", 4, "image/tiff"},7817{".tiff", 5, "image/tiff"},78187819/* model */7820{".wrl", 4, "model/vrml"},78217822/* text */7823{".css", 4, "text/css"},7824{".csv", 4, "text/csv"},7825{".htm", 4, "text/html"},7826{".html", 5, "text/html"},7827{".sgm", 4, "text/sgml"},7828{".shtm", 5, "text/html"},7829{".shtml", 6, "text/html"},7830{".txt", 4, "text/plain"},7831{".xml", 4, "text/xml"},78327833/* video */7834{".mov", 4, "video/quicktime"},7835{".mp4", 4, "video/mp4"},7836{".mpeg", 5, "video/mpeg"},7837{".mpg", 4, "video/mpeg"},7838{".ogv", 4, "video/ogg"},7839{".qt", 3, "video/quicktime"},78407841/* not registered types7842* (http://reference.sitepoint.com/html/mime-types-full,7843* http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */7844{".arj", 4, "application/x-arj-compressed"},7845{".gz", 3, "application/x-gunzip"},7846{".rar", 4, "application/x-arj-compressed"},7847{".swf", 4, "application/x-shockwave-flash"},7848{".tar", 4, "application/x-tar"},7849{".tgz", 4, "application/x-tar-gz"},7850{".torrent", 8, "application/x-bittorrent"},7851{".ppt", 4, "application/x-mspowerpoint"},7852{".xls", 4, "application/x-msexcel"},7853{".zip", 4, "application/x-zip-compressed"},7854{".aac",78554,7856"audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */7857{".aif", 4, "audio/x-aif"},7858{".m3u", 4, "audio/x-mpegurl"},7859{".mid", 4, "audio/x-midi"},7860{".ra", 3, "audio/x-pn-realaudio"},7861{".ram", 4, "audio/x-pn-realaudio"},7862{".wav", 4, "audio/x-wav"},7863{".bmp", 4, "image/bmp"},7864{".ico", 4, "image/x-icon"},7865{".pct", 4, "image/x-pct"},7866{".pict", 5, "image/pict"},7867{".rgb", 4, "image/x-rgb"},7868{".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */7869{".asf", 4, "video/x-ms-asf"},7870{".avi", 4, "video/x-msvideo"},7871{".m4v", 4, "video/x-m4v"},7872{NULL, 0, NULL}};787378747875const char *7876mg_get_builtin_mime_type(const char *path)7877{7878const char *ext;7879size_t i, path_len;78807881path_len = strlen(path);78827883for (i = 0; builtin_mime_types[i].extension != NULL; i++) {7884ext = path + (path_len - builtin_mime_types[i].ext_len);7885if ((path_len > builtin_mime_types[i].ext_len)7886&& (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {7887return builtin_mime_types[i].mime_type;7888}7889}78907891return "text/plain";7892}789378947895/* Look at the "path" extension and figure what mime type it has.7896* Store mime type in the vector. */7897static void7898get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)7899{7900struct vec ext_vec, mime_vec;7901const char *list, *ext;7902size_t path_len;79037904path_len = strlen(path);79057906if ((conn == NULL) || (vec == NULL)) {7907if (vec != NULL) {7908memset(vec, '\0', sizeof(struct vec));7909}7910return;7911}79127913/* Scan user-defined mime types first, in case user wants to7914* override default mime types. */7915list = conn->dom_ctx->config[EXTRA_MIME_TYPES];7916while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {7917/* ext now points to the path suffix */7918ext = path + path_len - ext_vec.len;7919if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {7920*vec = mime_vec;7921return;7922}7923}79247925vec->ptr = mg_get_builtin_mime_type(path);7926vec->len = strlen(vec->ptr);7927}792879297930/* Stringify binary data. Output buffer must be twice as big as input,7931* because each byte takes 2 bytes in string representation */7932static void7933bin2str(char *to, const unsigned char *p, size_t len)7934{7935static const char *hex = "0123456789abcdef";79367937for (; len--; p++) {7938*to++ = hex[p[0] >> 4];7939*to++ = hex[p[0] & 0x0f];7940}7941*to = '\0';7942}794379447945/* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.7946*/7947char *7948mg_md5(char buf[33], ...)7949{7950md5_byte_t hash[16];7951const char *p;7952va_list ap;7953md5_state_t ctx;79547955md5_init(&ctx);79567957va_start(ap, buf);7958while ((p = va_arg(ap, const char *)) != NULL) {7959md5_append(&ctx, (const md5_byte_t *)p, strlen(p));7960}7961va_end(ap);79627963md5_finish(&ctx, hash);7964bin2str(buf, hash, sizeof(hash));7965return buf;7966}796779687969/* Check the user's password, return 1 if OK */7970static int7971check_password(const char *method,7972const char *ha1,7973const char *uri,7974const char *nonce,7975const char *nc,7976const char *cnonce,7977const char *qop,7978const char *response)7979{7980char ha2[32 + 1], expected_response[32 + 1];79817982/* Some of the parameters may be NULL */7983if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)7984|| (qop == NULL) || (response == NULL)) {7985return 0;7986}79877988/* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */7989if (strlen(response) != 32) {7990return 0;7991}79927993mg_md5(ha2, method, ":", uri, NULL);7994mg_md5(expected_response,7995ha1,7996":",7997nonce,7998":",7999nc,8000":",8001cnonce,8002":",8003qop,8004":",8005ha2,8006NULL);80078008return mg_strcasecmp(response, expected_response) == 0;8009}801080118012/* Use the global passwords file, if specified by auth_gpass option,8013* or search for .htpasswd in the requested directory. */8014static void8015open_auth_file(struct mg_connection *conn,8016const char *path,8017struct mg_file *filep)8018{8019if ((conn != NULL) && (conn->dom_ctx != NULL)) {8020char name[PATH_MAX];8021const char *p, *e,8022*gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];8023int truncated;80248025if (gpass != NULL) {8026/* Use global passwords file */8027if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {8028#if defined(DEBUG)8029/* Use mg_cry_internal here, since gpass has been configured. */8030mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));8031#endif8032}8033/* Important: using local struct mg_file to test path for8034* is_directory flag. If filep is used, mg_stat() makes it8035* appear as if auth file was opened.8036* TODO(mid): Check if this is still required after rewriting8037* mg_stat */8038} else if (mg_stat(conn, path, &filep->stat)8039&& filep->stat.is_directory) {8040mg_snprintf(conn,8041&truncated,8042name,8043sizeof(name),8044"%s/%s",8045path,8046PASSWORDS_FILE_NAME);80478048if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {8049#if defined(DEBUG)8050/* Don't use mg_cry_internal here, but only a trace, since this8051* is8052* a typical case. It will occur for every directory8053* without a password file. */8054DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));8055#endif8056}8057} else {8058/* Try to find .htpasswd in requested directory. */8059for (p = path, e = p + strlen(p) - 1; e > p; e--) {8060if (e[0] == '/') {8061break;8062}8063}8064mg_snprintf(conn,8065&truncated,8066name,8067sizeof(name),8068"%.*s/%s",8069(int)(e - p),8070p,8071PASSWORDS_FILE_NAME);80728073if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {8074#if defined(DEBUG)8075/* Don't use mg_cry_internal here, but only a trace, since this8076* is8077* a typical case. It will occur for every directory8078* without a password file. */8079DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));8080#endif8081}8082}8083}8084}808580868087/* Parsed Authorization header */8088struct ah {8089char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;8090};809180928093/* Return 1 on success. Always initializes the ah structure. */8094static int8095parse_auth_header(struct mg_connection *conn,8096char *buf,8097size_t buf_size,8098struct ah *ah)8099{8100char *name, *value, *s;8101const char *auth_header;8102uint64_t nonce;81038104if (!ah || !conn) {8105return 0;8106}81078108(void)memset(ah, 0, sizeof(*ah));8109if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)8110|| mg_strncasecmp(auth_header, "Digest ", 7) != 0) {8111return 0;8112}81138114/* Make modifiable copy of the auth header */8115(void)mg_strlcpy(buf, auth_header + 7, buf_size);8116s = buf;81178118/* Parse authorization header */8119for (;;) {8120/* Gobble initial spaces */8121while (isspace(*(unsigned char *)s)) {8122s++;8123}8124name = skip_quoted(&s, "=", " ", 0);8125/* Value is either quote-delimited, or ends at first comma or space.8126*/8127if (s[0] == '\"') {8128s++;8129value = skip_quoted(&s, "\"", " ", '\\');8130if (s[0] == ',') {8131s++;8132}8133} else {8134value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses8135* spaces */8136}8137if (*name == '\0') {8138break;8139}81408141if (!strcmp(name, "username")) {8142ah->user = value;8143} else if (!strcmp(name, "cnonce")) {8144ah->cnonce = value;8145} else if (!strcmp(name, "response")) {8146ah->response = value;8147} else if (!strcmp(name, "uri")) {8148ah->uri = value;8149} else if (!strcmp(name, "qop")) {8150ah->qop = value;8151} else if (!strcmp(name, "nc")) {8152ah->nc = value;8153} else if (!strcmp(name, "nonce")) {8154ah->nonce = value;8155}8156}81578158#if !defined(NO_NONCE_CHECK)8159/* Read the nonce from the response. */8160if (ah->nonce == NULL) {8161return 0;8162}8163s = NULL;8164nonce = strtoull(ah->nonce, &s, 10);8165if ((s == NULL) || (*s != 0)) {8166return 0;8167}81688169/* Convert the nonce from the client to a number. */8170nonce ^= conn->dom_ctx->auth_nonce_mask;81718172/* The converted number corresponds to the time the nounce has been8173* created. This should not be earlier than the server start. */8174/* Server side nonce check is valuable in all situations but one:8175* if the server restarts frequently, but the client should not see8176* that, so the server should accept nonces from previous starts. */8177/* However, the reasonable default is to not accept a nonce from a8178* previous start, so if anyone changed the access rights between8179* two restarts, a new login is required. */8180if (nonce < (uint64_t)conn->phys_ctx->start_time) {8181/* nonce is from a previous start of the server and no longer valid8182* (replay attack?) */8183return 0;8184}8185/* Check if the nonce is too high, so it has not (yet) been used by the8186* server. */8187if (nonce >= ((uint64_t)conn->phys_ctx->start_time8188+ conn->dom_ctx->nonce_count)) {8189return 0;8190}8191#else8192(void)nonce;8193#endif81948195/* CGI needs it as REMOTE_USER */8196if (ah->user != NULL) {8197conn->request_info.remote_user =8198mg_strdup_ctx(ah->user, conn->phys_ctx);8199} else {8200return 0;8201}82028203return 1;8204}820582068207static const char *8208mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)8209{8210#if defined(MG_USE_OPEN_FILE)8211const char *eof;8212size_t len;8213const char *memend;8214#else8215(void)p; /* parameter is unused */8216#endif82178218if (!filep) {8219return NULL;8220}82218222#if defined(MG_USE_OPEN_FILE)8223if ((filep->access.membuf != NULL) && (*p != NULL)) {8224memend = (const char *)&filep->access.membuf[filep->stat.size];8225/* Search for \n from p till the end of stream */8226eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));8227if (eof != NULL) {8228eof += 1; /* Include \n */8229} else {8230eof = memend; /* Copy remaining data */8231}8232len =8233((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);8234memcpy(buf, *p, len);8235buf[len] = '\0';8236*p += len;8237return len ? eof : NULL;8238} else /* filep->access.fp block below */8239#endif8240if (filep->access.fp != NULL) {8241return fgets(buf, (int)size, filep->access.fp);8242} else {8243return NULL;8244}8245}82468247/* Define the initial recursion depth for procesesing htpasswd files that8248* include other htpasswd8249* (or even the same) files. It is not difficult to provide a file or files8250* s.t. they force civetweb8251* to infinitely recurse and then crash.8252*/8253#define INITIAL_DEPTH 98254#if INITIAL_DEPTH <= 08255#error Bad INITIAL_DEPTH for recursion, set to at least 18256#endif82578258struct read_auth_file_struct {8259struct mg_connection *conn;8260struct ah ah;8261const char *domain;8262char buf[256 + 256 + 40];8263const char *f_user;8264const char *f_domain;8265const char *f_ha1;8266};826782688269static int8270read_auth_file(struct mg_file *filep,8271struct read_auth_file_struct *workdata,8272int depth)8273{8274char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;8275int is_authorized = 0;8276struct mg_file fp;8277size_t l;82788279if (!filep || !workdata || (0 == depth)) {8280return 0;8281}82828283/* Loop over passwords file */8284#if defined(MG_USE_OPEN_FILE)8285p = (char *)filep->access.membuf;8286#endif8287while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {8288l = strlen(workdata->buf);8289while (l > 0) {8290if (isspace(workdata->buf[l - 1])8291|| iscntrl(workdata->buf[l - 1])) {8292l--;8293workdata->buf[l] = 0;8294} else8295break;8296}8297if (l < 1) {8298continue;8299}83008301workdata->f_user = workdata->buf;83028303if (workdata->f_user[0] == ':') {8304/* user names may not contain a ':' and may not be empty,8305* so lines starting with ':' may be used for a special purpose8306*/8307if (workdata->f_user[1] == '#') {8308/* :# is a comment */8309continue;8310} else if (!strncmp(workdata->f_user + 1, "include=", 8)) {8311if (mg_fopen(workdata->conn,8312workdata->f_user + 9,8313MG_FOPEN_MODE_READ,8314&fp)) {8315is_authorized = read_auth_file(&fp, workdata, depth - 1);8316(void)mg_fclose(8317&fp.access); /* ignore error on read only file */83188319/* No need to continue processing files once we have a8320* match, since nothing will reset it back8321* to 0.8322*/8323if (is_authorized) {8324return is_authorized;8325}8326} else {8327mg_cry_internal(workdata->conn,8328"%s: cannot open authorization file: %s",8329__func__,8330workdata->buf);8331}8332continue;8333}8334/* everything is invalid for the moment (might change in the8335* future) */8336mg_cry_internal(workdata->conn,8337"%s: syntax error in authorization file: %s",8338__func__,8339workdata->buf);8340continue;8341}83428343workdata->f_domain = strchr(workdata->f_user, ':');8344if (workdata->f_domain == NULL) {8345mg_cry_internal(workdata->conn,8346"%s: syntax error in authorization file: %s",8347__func__,8348workdata->buf);8349continue;8350}8351*(char *)(workdata->f_domain) = 0;8352(workdata->f_domain)++;83538354workdata->f_ha1 = strchr(workdata->f_domain, ':');8355if (workdata->f_ha1 == NULL) {8356mg_cry_internal(workdata->conn,8357"%s: syntax error in authorization file: %s",8358__func__,8359workdata->buf);8360continue;8361}8362*(char *)(workdata->f_ha1) = 0;8363(workdata->f_ha1)++;83648365if (!strcmp(workdata->ah.user, workdata->f_user)8366&& !strcmp(workdata->domain, workdata->f_domain)) {8367return check_password(workdata->conn->request_info.request_method,8368workdata->f_ha1,8369workdata->ah.uri,8370workdata->ah.nonce,8371workdata->ah.nc,8372workdata->ah.cnonce,8373workdata->ah.qop,8374workdata->ah.response);8375}8376}83778378return is_authorized;8379}838083818382/* Authorize against the opened passwords file. Return 1 if authorized. */8383static int8384authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)8385{8386struct read_auth_file_struct workdata;8387char buf[MG_BUF_LEN];83888389if (!conn || !conn->dom_ctx) {8390return 0;8391}83928393memset(&workdata, 0, sizeof(workdata));8394workdata.conn = conn;83958396if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {8397return 0;8398}83998400if (realm) {8401workdata.domain = realm;8402} else {8403workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];8404}84058406return read_auth_file(filep, &workdata, INITIAL_DEPTH);8407}840884098410/* Public function to check http digest authentication header */8411int8412mg_check_digest_access_authentication(struct mg_connection *conn,8413const char *realm,8414const char *filename)8415{8416struct mg_file file = STRUCT_FILE_INITIALIZER;8417int auth;84188419if (!conn || !filename) {8420return -1;8421}8422if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {8423return -2;8424}84258426auth = authorize(conn, &file, realm);84278428mg_fclose(&file.access);84298430return auth;8431}843284338434/* Return 1 if request is authorised, 0 otherwise. */8435static int8436check_authorization(struct mg_connection *conn, const char *path)8437{8438char fname[PATH_MAX];8439struct vec uri_vec, filename_vec;8440const char *list;8441struct mg_file file = STRUCT_FILE_INITIALIZER;8442int authorized = 1, truncated;84438444if (!conn || !conn->dom_ctx) {8445return 0;8446}84478448list = conn->dom_ctx->config[PROTECT_URI];8449while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {8450if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {8451mg_snprintf(conn,8452&truncated,8453fname,8454sizeof(fname),8455"%.*s",8456(int)filename_vec.len,8457filename_vec.ptr);84588459if (truncated8460|| !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {8461mg_cry_internal(conn,8462"%s: cannot open %s: %s",8463__func__,8464fname,8465strerror(errno));8466}8467break;8468}8469}84708471if (!is_file_opened(&file.access)) {8472open_auth_file(conn, path, &file);8473}84748475if (is_file_opened(&file.access)) {8476authorized = authorize(conn, &file, NULL);8477(void)mg_fclose(&file.access); /* ignore error on read only file */8478}84798480return authorized;8481}848284838484/* Internal function. Assumes conn is valid */8485static void8486send_authorization_request(struct mg_connection *conn, const char *realm)8487{8488char date[64];8489time_t curtime = time(NULL);8490uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);84918492if (!realm) {8493realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];8494}84958496(void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);8497nonce += conn->dom_ctx->nonce_count;8498++conn->dom_ctx->nonce_count;8499(void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);85008501nonce ^= conn->dom_ctx->auth_nonce_mask;8502conn->status_code = 401;8503conn->must_close = 1;85048505gmt_time_string(date, sizeof(date), &curtime);85068507mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");8508send_no_cache_header(conn);8509send_additional_header(conn);8510mg_printf(conn,8511"Date: %s\r\n"8512"Connection: %s\r\n"8513"Content-Length: 0\r\n"8514"WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "8515"nonce=\"%" UINT64_FMT "\"\r\n\r\n",8516date,8517suggest_connection_header(conn),8518realm,8519nonce);8520}852185228523/* Interface function. Parameters are provided by the user, so do8524* at least some basic checks.8525*/8526int8527mg_send_digest_access_authentication_request(struct mg_connection *conn,8528const char *realm)8529{8530if (conn && conn->dom_ctx) {8531send_authorization_request(conn, realm);8532return 0;8533}8534return -1;8535}853685378538#if !defined(NO_FILES)8539static int8540is_authorized_for_put(struct mg_connection *conn)8541{8542if (conn) {8543struct mg_file file = STRUCT_FILE_INITIALIZER;8544const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];8545int ret = 0;85468547if (passfile != NULL8548&& mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {8549ret = authorize(conn, &file, NULL);8550(void)mg_fclose(&file.access); /* ignore error on read only file */8551}85528553return ret;8554}8555return 0;8556}8557#endif855885598560int8561mg_modify_passwords_file(const char *fname,8562const char *domain,8563const char *user,8564const char *pass)8565{8566int found, i;8567char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];8568FILE *fp, *fp2;85698570found = 0;8571fp = fp2 = NULL;85728573/* Regard empty password as no password - remove user record. */8574if ((pass != NULL) && (pass[0] == '\0')) {8575pass = NULL;8576}85778578/* Other arguments must not be empty */8579if ((fname == NULL) || (domain == NULL) || (user == NULL)) {8580return 0;8581}85828583/* Using the given file format, user name and domain must not contain8584* ':'8585*/8586if (strchr(user, ':') != NULL) {8587return 0;8588}8589if (strchr(domain, ':') != NULL) {8590return 0;8591}85928593/* Do not allow control characters like newline in user name and domain.8594* Do not allow excessively long names either. */8595for (i = 0; ((i < 255) && (user[i] != 0)); i++) {8596if (iscntrl(user[i])) {8597return 0;8598}8599}8600if (user[i]) {8601return 0;8602}8603for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {8604if (iscntrl(domain[i])) {8605return 0;8606}8607}8608if (domain[i]) {8609return 0;8610}86118612/* The maximum length of the path to the password file is limited */8613if ((strlen(fname) + 4) >= PATH_MAX) {8614return 0;8615}86168617/* Create a temporary file name. Length has been checked before. */8618strcpy(tmp, fname);8619strcat(tmp, ".tmp");86208621/* Create the file if does not exist */8622/* Use of fopen here is OK, since fname is only ASCII */8623if ((fp = fopen(fname, "a+")) != NULL) {8624(void)fclose(fp);8625}86268627/* Open the given file and temporary file */8628if ((fp = fopen(fname, "r")) == NULL) {8629return 0;8630} else if ((fp2 = fopen(tmp, "w+")) == NULL) {8631fclose(fp);8632return 0;8633}86348635/* Copy the stuff to temporary file */8636while (fgets(line, sizeof(line), fp) != NULL) {8637if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {8638continue;8639}8640u[255] = 0;8641d[255] = 0;86428643if (!strcmp(u, user) && !strcmp(d, domain)) {8644found++;8645if (pass != NULL) {8646mg_md5(ha1, user, ":", domain, ":", pass, NULL);8647fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);8648}8649} else {8650fprintf(fp2, "%s", line);8651}8652}86538654/* If new user, just add it */8655if (!found && (pass != NULL)) {8656mg_md5(ha1, user, ":", domain, ":", pass, NULL);8657fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);8658}86598660/* Close files */8661fclose(fp);8662fclose(fp2);86638664/* Put the temp file in place of real file */8665IGNORE_UNUSED_RESULT(remove(fname));8666IGNORE_UNUSED_RESULT(rename(tmp, fname));86678668return 1;8669}867086718672static int8673is_valid_port(unsigned long port)8674{8675return (port <= 0xffff);8676}867786788679static int8680mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)8681{8682struct addrinfo hints, *res, *ressave;8683int func_ret = 0;8684int gai_ret;86858686memset(&hints, 0, sizeof(struct addrinfo));8687hints.ai_family = af;86888689gai_ret = getaddrinfo(src, NULL, &hints, &res);8690if (gai_ret != 0) {8691/* gai_strerror could be used to convert gai_ret to a string */8692/* POSIX return values: see8693* http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html8694*/8695/* Windows return values: see8696* https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx8697*/8698return 0;8699}87008701ressave = res;87028703while (res) {8704if (dstlen >= (size_t)res->ai_addrlen) {8705memcpy(dst, res->ai_addr, res->ai_addrlen);8706func_ret = 1;8707}8708res = res->ai_next;8709}87108711freeaddrinfo(ressave);8712return func_ret;8713}871487158716static int8717connect_socket(struct mg_context *ctx /* may be NULL */,8718const char *host,8719int port,8720int use_ssl,8721char *ebuf,8722size_t ebuf_len,8723SOCKET *sock /* output: socket, must not be NULL */,8724union usa *sa /* output: socket address, must not be NULL */8725)8726{8727int ip_ver = 0;8728int conn_ret = -1;8729int ret;8730*sock = INVALID_SOCKET;8731memset(sa, 0, sizeof(*sa));87328733if (ebuf_len > 0) {8734*ebuf = 0;8735}87368737if (host == NULL) {8738mg_snprintf(NULL,8739NULL, /* No truncation check for ebuf */8740ebuf,8741ebuf_len,8742"%s",8743"NULL host");8744return 0;8745}87468747if ((port <= 0) || !is_valid_port((unsigned)port)) {8748mg_snprintf(NULL,8749NULL, /* No truncation check for ebuf */8750ebuf,8751ebuf_len,8752"%s",8753"invalid port");8754return 0;8755}87568757#if !defined(NO_SSL)8758#if !defined(NO_SSL_DL)8759#if defined(OPENSSL_API_1_1)8760if (use_ssl && (TLS_client_method == NULL)) {8761mg_snprintf(NULL,8762NULL, /* No truncation check for ebuf */8763ebuf,8764ebuf_len,8765"%s",8766"SSL is not initialized");8767return 0;8768}8769#else8770if (use_ssl && (SSLv23_client_method == NULL)) {8771mg_snprintf(NULL,8772NULL, /* No truncation check for ebuf */8773ebuf,8774ebuf_len,8775"%s",8776"SSL is not initialized");8777return 0;8778}87798780#endif /* OPENSSL_API_1_1 */8781#else8782(void)use_ssl;8783#endif /* NO_SSL_DL */8784#else8785(void)use_ssl;8786#endif /* !defined(NO_SSL) */87878788if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {8789sa->sin.sin_family = AF_INET;8790sa->sin.sin_port = htons((uint16_t)port);8791ip_ver = 4;8792#if defined(USE_IPV6)8793} else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {8794sa->sin6.sin6_family = AF_INET6;8795sa->sin6.sin6_port = htons((uint16_t)port);8796ip_ver = 6;8797} else if (host[0] == '[') {8798/* While getaddrinfo on Windows will work with [::1],8799* getaddrinfo on Linux only works with ::1 (without []). */8800size_t l = strlen(host + 1);8801char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;8802if (h) {8803h[l - 1] = 0;8804if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {8805sa->sin6.sin6_family = AF_INET6;8806sa->sin6.sin6_port = htons((uint16_t)port);8807ip_ver = 6;8808}8809mg_free(h);8810}8811#endif8812}88138814if (ip_ver == 0) {8815mg_snprintf(NULL,8816NULL, /* No truncation check for ebuf */8817ebuf,8818ebuf_len,8819"%s",8820"host not found");8821return 0;8822}88238824if (ip_ver == 4) {8825*sock = socket(PF_INET, SOCK_STREAM, 0);8826}8827#if defined(USE_IPV6)8828else if (ip_ver == 6) {8829*sock = socket(PF_INET6, SOCK_STREAM, 0);8830}8831#endif88328833if (*sock == INVALID_SOCKET) {8834mg_snprintf(NULL,8835NULL, /* No truncation check for ebuf */8836ebuf,8837ebuf_len,8838"socket(): %s",8839strerror(ERRNO));8840return 0;8841}88428843if (0 != set_non_blocking_mode(*sock)) {8844mg_snprintf(NULL,8845NULL, /* No truncation check for ebuf */8846ebuf,8847ebuf_len,8848"Cannot set socket to non-blocking: %s",8849strerror(ERRNO));8850closesocket(*sock);8851*sock = INVALID_SOCKET;8852return 0;8853}88548855set_close_on_exec(*sock, fc(ctx));88568857if (ip_ver == 4) {8858/* connected with IPv4 */8859conn_ret = connect(*sock,8860(struct sockaddr *)((void *)&sa->sin),8861sizeof(sa->sin));8862}8863#if defined(USE_IPV6)8864else if (ip_ver == 6) {8865/* connected with IPv6 */8866conn_ret = connect(*sock,8867(struct sockaddr *)((void *)&sa->sin6),8868sizeof(sa->sin6));8869}8870#endif88718872#if defined(_WIN32)8873if (conn_ret != 0) {8874DWORD err = WSAGetLastError(); /* could return WSAEWOULDBLOCK */8875conn_ret = (int)err;8876#if !defined(EINPROGRESS)8877#define EINPROGRESS (WSAEWOULDBLOCK) /* Winsock equivalent */8878#endif /* if !defined(EINPROGRESS) */8879}8880#endif88818882if ((conn_ret != 0) && (conn_ret != EINPROGRESS)) {8883/* Data for getsockopt */8884int sockerr = -1;8885void *psockerr = &sockerr;88868887#if defined(_WIN32)8888int len = (int)sizeof(sockerr);8889#else8890socklen_t len = (socklen_t)sizeof(sockerr);8891#endif88928893/* Data for poll */8894struct pollfd pfd[1];8895int pollres;8896int ms_wait = 10000; /* 10 second timeout */88978898/* For a non-blocking socket, the connect sequence is:8899* 1) call connect (will not block)8900* 2) wait until the socket is ready for writing (select or poll)8901* 3) check connection state with getsockopt8902*/8903pfd[0].fd = *sock;8904pfd[0].events = POLLOUT;8905pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));89068907if (pollres != 1) {8908/* Not connected */8909mg_snprintf(NULL,8910NULL, /* No truncation check for ebuf */8911ebuf,8912ebuf_len,8913"connect(%s:%d): timeout",8914host,8915port);8916closesocket(*sock);8917*sock = INVALID_SOCKET;8918return 0;8919}89208921#if defined(_WIN32)8922ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);8923#else8924ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);8925#endif89268927if ((ret != 0) || (sockerr != 0)) {8928/* Not connected */8929mg_snprintf(NULL,8930NULL, /* No truncation check for ebuf */8931ebuf,8932ebuf_len,8933"connect(%s:%d): error %s",8934host,8935port,8936strerror(sockerr));8937closesocket(*sock);8938*sock = INVALID_SOCKET;8939return 0;8940}8941}89428943return 1;8944}894589468947int8948mg_url_encode(const char *src, char *dst, size_t dst_len)8949{8950static const char *dont_escape = "._-$,;~()";8951static const char *hex = "0123456789abcdef";8952char *pos = dst;8953const char *end = dst + dst_len - 1;89548955for (; ((*src != '\0') && (pos < end)); src++, pos++) {8956if (isalnum(*(const unsigned char *)src)8957|| (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {8958*pos = *src;8959} else if (pos + 2 < end) {8960pos[0] = '%';8961pos[1] = hex[(*(const unsigned char *)src) >> 4];8962pos[2] = hex[(*(const unsigned char *)src) & 0xf];8963pos += 2;8964} else {8965break;8966}8967}89688969*pos = '\0';8970return (*src == '\0') ? (int)(pos - dst) : -1;8971}89728973/* Return 0 on success, non-zero if an error occurs. */89748975static int8976print_dir_entry(struct de *de)8977{8978size_t hrefsize;8979char *href;8980char size[64], mod[64];8981#if defined(REENTRANT_TIME)8982struct tm _tm;8983struct tm *tm = &_tm;8984#else8985struct tm *tm;8986#endif89878988hrefsize = PATH_MAX * 3; /* worst case */8989href = (char *)mg_malloc(hrefsize);8990if (href == NULL) {8991return -1;8992}8993if (de->file.is_directory) {8994mg_snprintf(de->conn,8995NULL, /* Buffer is big enough */8996size,8997sizeof(size),8998"%s",8999"[DIRECTORY]");9000} else {9001/* We use (signed) cast below because MSVC 6 compiler cannot9002* convert unsigned __int64 to double. Sigh. */9003if (de->file.size < 1024) {9004mg_snprintf(de->conn,9005NULL, /* Buffer is big enough */9006size,9007sizeof(size),9008"%d",9009(int)de->file.size);9010} else if (de->file.size < 0x100000) {9011mg_snprintf(de->conn,9012NULL, /* Buffer is big enough */9013size,9014sizeof(size),9015"%.1fk",9016(double)de->file.size / 1024.0);9017} else if (de->file.size < 0x40000000) {9018mg_snprintf(de->conn,9019NULL, /* Buffer is big enough */9020size,9021sizeof(size),9022"%.1fM",9023(double)de->file.size / 1048576);9024} else {9025mg_snprintf(de->conn,9026NULL, /* Buffer is big enough */9027size,9028sizeof(size),9029"%.1fG",9030(double)de->file.size / 1073741824);9031}9032}90339034/* Note: mg_snprintf will not cause a buffer overflow above.9035* So, string truncation checks are not required here. */90369037#if defined(REENTRANT_TIME)9038localtime_r(&de->file.last_modified, tm);9039#else9040tm = localtime(&de->file.last_modified);9041#endif9042if (tm != NULL) {9043strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);9044} else {9045mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));9046mod[sizeof(mod) - 1] = '\0';9047}9048mg_url_encode(de->file_name, href, hrefsize);9049mg_printf(de->conn,9050"<tr><td><a href=\"%s%s%s\">%s%s</a></td>"9051"<td> %s</td><td> %s</td></tr>\n",9052de->conn->request_info.local_uri,9053href,9054de->file.is_directory ? "/" : "",9055de->file_name,9056de->file.is_directory ? "/" : "",9057mod,9058size);9059mg_free(href);9060return 0;9061}906290639064/* This function is called from send_directory() and used for9065* sorting directory entries by size, or name, or modification time.9066* On windows, __cdecl specification is needed in case if project is built9067* with __stdcall convention. qsort always requires __cdels callback. */9068static int WINCDECL9069compare_dir_entries(const void *p1, const void *p2)9070{9071if (p1 && p2) {9072const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;9073const char *query_string = a->conn->request_info.query_string;9074int cmp_result = 0;90759076if (query_string == NULL) {9077query_string = "na";9078}90799080if (a->file.is_directory && !b->file.is_directory) {9081return -1; /* Always put directories on top */9082} else if (!a->file.is_directory && b->file.is_directory) {9083return 1; /* Always put directories on top */9084} else if (*query_string == 'n') {9085cmp_result = strcmp(a->file_name, b->file_name);9086} else if (*query_string == 's') {9087cmp_result = (a->file.size == b->file.size)9088? 09089: ((a->file.size > b->file.size) ? 1 : -1);9090} else if (*query_string == 'd') {9091cmp_result =9092(a->file.last_modified == b->file.last_modified)9093? 09094: ((a->file.last_modified > b->file.last_modified) ? 19095: -1);9096}90979098return (query_string[1] == 'd') ? -cmp_result : cmp_result;9099}9100return 0;9101}910291039104static int9105must_hide_file(struct mg_connection *conn, const char *path)9106{9107if (conn && conn->dom_ctx) {9108const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";9109const char *pattern = conn->dom_ctx->config[HIDE_FILES];9110return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)9111|| ((pattern != NULL)9112&& (match_prefix(pattern, strlen(pattern), path) > 0));9113}9114return 0;9115}911691179118static int9119scan_directory(struct mg_connection *conn,9120const char *dir,9121void *data,9122int (*cb)(struct de *, void *))9123{9124char path[PATH_MAX];9125struct dirent *dp;9126DIR *dirp;9127struct de de;9128int truncated;91299130if ((dirp = mg_opendir(conn, dir)) == NULL) {9131return 0;9132} else {9133de.conn = conn;91349135while ((dp = mg_readdir(dirp)) != NULL) {9136/* Do not show current dir and hidden files */9137if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")9138|| must_hide_file(conn, dp->d_name)) {9139continue;9140}91419142mg_snprintf(9143conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);91449145/* If we don't memset stat structure to zero, mtime will have9146* garbage and strftime() will segfault later on in9147* print_dir_entry(). memset is required only if mg_stat()9148* fails. For more details, see9149* http://code.google.com/p/mongoose/issues/detail?id=79 */9150memset(&de.file, 0, sizeof(de.file));91519152if (truncated) {9153/* If the path is not complete, skip processing. */9154continue;9155}91569157if (!mg_stat(conn, path, &de.file)) {9158mg_cry_internal(conn,9159"%s: mg_stat(%s) failed: %s",9160__func__,9161path,9162strerror(ERRNO));9163}9164de.file_name = dp->d_name;9165cb(&de, data);9166}9167(void)mg_closedir(dirp);9168}9169return 1;9170}917191729173#if !defined(NO_FILES)9174static int9175remove_directory(struct mg_connection *conn, const char *dir)9176{9177char path[PATH_MAX];9178struct dirent *dp;9179DIR *dirp;9180struct de de;9181int truncated;9182int ok = 1;91839184if ((dirp = mg_opendir(conn, dir)) == NULL) {9185return 0;9186} else {9187de.conn = conn;91889189while ((dp = mg_readdir(dirp)) != NULL) {9190/* Do not show current dir (but show hidden files as they will9191* also be removed) */9192if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {9193continue;9194}91959196mg_snprintf(9197conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);91989199/* If we don't memset stat structure to zero, mtime will have9200* garbage and strftime() will segfault later on in9201* print_dir_entry(). memset is required only if mg_stat()9202* fails. For more details, see9203* http://code.google.com/p/mongoose/issues/detail?id=79 */9204memset(&de.file, 0, sizeof(de.file));92059206if (truncated) {9207/* Do not delete anything shorter */9208ok = 0;9209continue;9210}92119212if (!mg_stat(conn, path, &de.file)) {9213mg_cry_internal(conn,9214"%s: mg_stat(%s) failed: %s",9215__func__,9216path,9217strerror(ERRNO));9218ok = 0;9219}92209221if (de.file.is_directory) {9222if (remove_directory(conn, path) == 0) {9223ok = 0;9224}9225} else {9226/* This will fail file is the file is in memory */9227if (mg_remove(conn, path) == 0) {9228ok = 0;9229}9230}9231}9232(void)mg_closedir(dirp);92339234IGNORE_UNUSED_RESULT(rmdir(dir));9235}92369237return ok;9238}9239#endif924092419242struct dir_scan_data {9243struct de *entries;9244unsigned int num_entries;9245unsigned int arr_size;9246};924792489249/* Behaves like realloc(), but frees original pointer on failure */9250static void *9251realloc2(void *ptr, size_t size)9252{9253void *new_ptr = mg_realloc(ptr, size);9254if (new_ptr == NULL) {9255mg_free(ptr);9256}9257return new_ptr;9258}925992609261static int9262dir_scan_callback(struct de *de, void *data)9263{9264struct dir_scan_data *dsd = (struct dir_scan_data *)data;92659266if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {9267dsd->arr_size *= 2;9268dsd->entries =9269(struct de *)realloc2(dsd->entries,9270dsd->arr_size * sizeof(dsd->entries[0]));9271}9272if (dsd->entries == NULL) {9273/* TODO(lsm, low): propagate an error to the caller */9274dsd->num_entries = 0;9275} else {9276dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);9277dsd->entries[dsd->num_entries].file = de->file;9278dsd->entries[dsd->num_entries].conn = de->conn;9279dsd->num_entries++;9280}92819282return 0;9283}928492859286static void9287handle_directory_request(struct mg_connection *conn, const char *dir)9288{9289unsigned int i;9290int sort_direction;9291struct dir_scan_data data = {NULL, 0, 128};9292char date[64];9293time_t curtime = time(NULL);92949295if (!scan_directory(conn, dir, &data, dir_scan_callback)) {9296mg_send_http_error(conn,9297500,9298"Error: Cannot open directory\nopendir(%s): %s",9299dir,9300strerror(ERRNO));9301return;9302}93039304gmt_time_string(date, sizeof(date), &curtime);93059306if (!conn) {9307return;9308}93099310sort_direction = ((conn->request_info.query_string != NULL)9311&& (conn->request_info.query_string[1] == 'd'))9312? 'a'9313: 'd';93149315conn->must_close = 1;9316mg_printf(conn, "HTTP/1.1 200 OK\r\n");9317send_static_cache_header(conn);9318send_additional_header(conn);9319mg_printf(conn,9320"Date: %s\r\n"9321"Connection: close\r\n"9322"Content-Type: text/html; charset=utf-8\r\n\r\n",9323date);9324mg_printf(conn,9325"<html><head><title>Index of %s</title>"9326"<style>th {text-align: left;}</style></head>"9327"<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"9328"<tr><th><a href=\"?n%c\">Name</a></th>"9329"<th><a href=\"?d%c\">Modified</a></th>"9330"<th><a href=\"?s%c\">Size</a></th></tr>"9331"<tr><td colspan=\"3\"><hr></td></tr>",9332conn->request_info.local_uri,9333conn->request_info.local_uri,9334sort_direction,9335sort_direction,9336sort_direction);93379338/* Print first entry - link to a parent directory */9339mg_printf(conn,9340"<tr><td><a href=\"%s%s\">%s</a></td>"9341"<td> %s</td><td> %s</td></tr>\n",9342conn->request_info.local_uri,9343"..",9344"Parent directory",9345"-",9346"-");93479348/* Sort and print directory entries */9349if (data.entries != NULL) {9350qsort(data.entries,9351(size_t)data.num_entries,9352sizeof(data.entries[0]),9353compare_dir_entries);9354for (i = 0; i < data.num_entries; i++) {9355print_dir_entry(&data.entries[i]);9356mg_free(data.entries[i].file_name);9357}9358mg_free(data.entries);9359}93609361mg_printf(conn, "%s", "</table></body></html>");9362conn->status_code = 200;9363}936493659366/* Send len bytes from the opened file to the client. */9367static void9368send_file_data(struct mg_connection *conn,9369struct mg_file *filep,9370int64_t offset,9371int64_t len)9372{9373char buf[MG_BUF_LEN];9374int to_read, num_read, num_written;9375int64_t size;93769377if (!filep || !conn) {9378return;9379}93809381/* Sanity check the offset */9382size = (filep->stat.size > INT64_MAX) ? INT64_MAX9383: (int64_t)(filep->stat.size);9384offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);93859386#if defined(MG_USE_OPEN_FILE)9387if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {9388/* file stored in memory */9389if (len > size - offset) {9390len = size - offset;9391}9392mg_write(conn, filep->access.membuf + offset, (size_t)len);9393} else /* else block below */9394#endif9395if (len > 0 && filep->access.fp != NULL) {9396/* file stored on disk */9397#if defined(__linux__)9398/* sendfile is only available for Linux */9399if ((conn->ssl == 0) && (conn->throttle == 0)9400&& (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],9401"yes"))) {9402off_t sf_offs = (off_t)offset;9403ssize_t sf_sent;9404int sf_file = fileno(filep->access.fp);9405int loop_cnt = 0;94069407do {9408/* 2147479552 (0x7FFFF000) is a limit found by experiment on9409* 64 bit Linux (2^31 minus one memory page of 4k?). */9410size_t sf_tosend =9411(size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);9412sf_sent =9413sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);9414if (sf_sent > 0) {9415len -= sf_sent;9416offset += sf_sent;9417} else if (loop_cnt == 0) {9418/* This file can not be sent using sendfile.9419* This might be the case for pseudo-files in the9420* /sys/ and /proc/ file system.9421* Use the regular user mode copy code instead. */9422break;9423} else if (sf_sent == 0) {9424/* No error, but 0 bytes sent. May be EOF? */9425return;9426}9427loop_cnt++;94289429} while ((len > 0) && (sf_sent >= 0));94309431if (sf_sent > 0) {9432return; /* OK */9433}94349435/* sf_sent<0 means error, thus fall back to the classic way */9436/* This is always the case, if sf_file is not a "normal" file,9437* e.g., for sending data from the output of a CGI process. */9438offset = (int64_t)sf_offs;9439}9440#endif9441if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {9442mg_cry_internal(conn,9443"%s: fseeko() failed: %s",9444__func__,9445strerror(ERRNO));9446mg_send_http_error(9447conn,9448500,9449"%s",9450"Error: Unable to access file at requested position.");9451} else {9452while (len > 0) {9453/* Calculate how much to read from the file in the buffer */9454to_read = sizeof(buf);9455if ((int64_t)to_read > len) {9456to_read = (int)len;9457}94589459/* Read from file, exit the loop on error */9460if ((num_read =9461(int)fread(buf, 1, (size_t)to_read, filep->access.fp))9462<= 0) {9463break;9464}94659466/* Send read bytes to the client, exit the loop on error */9467if ((num_written = mg_write(conn, buf, (size_t)num_read))9468!= num_read) {9469break;9470}94719472/* Both read and were successful, adjust counters */9473len -= num_written;9474}9475}9476}9477}947894799480static int9481parse_range_header(const char *header, int64_t *a, int64_t *b)9482{9483return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);9484}948594869487static void9488construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)9489{9490if ((filestat != NULL) && (buf != NULL)) {9491mg_snprintf(NULL,9492NULL, /* All calls to construct_etag use 64 byte buffer */9493buf,9494buf_len,9495"\"%lx.%" INT64_FMT "\"",9496(unsigned long)filestat->last_modified,9497filestat->size);9498}9499}950095019502static void9503fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)9504{9505if (filep != NULL && filep->fp != NULL) {9506#if defined(_WIN32)9507(void)conn; /* Unused. */9508#else9509if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {9510mg_cry_internal(conn,9511"%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",9512__func__,9513strerror(ERRNO));9514}9515#endif9516}9517}951895199520#if defined(USE_ZLIB)9521#include "mod_zlib.inl"9522#endif952395249525static void9526handle_static_file_request(struct mg_connection *conn,9527const char *path,9528struct mg_file *filep,9529const char *mime_type,9530const char *additional_headers)9531{9532char date[64], lm[64], etag[64];9533char range[128]; /* large enough, so there will be no overflow */9534const char *msg = "OK", *hdr;9535time_t curtime = time(NULL);9536int64_t cl, r1, r2;9537struct vec mime_vec;9538int n, truncated;9539char gz_path[PATH_MAX];9540const char *encoding = "";9541const char *cors1, *cors2, *cors3;9542int is_head_request;95439544#if defined(USE_ZLIB)9545/* Compression is allowed, unless there is a reason not to use compression.9546* If the file is already compressed, too small or a "range" request was9547* made, on the fly compression is not possible. */9548int allow_on_the_fly_compression = 1;9549#endif95509551if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {9552return;9553}95549555is_head_request = !strcmp(conn->request_info.request_method, "HEAD");95569557if (mime_type == NULL) {9558get_mime_type(conn, path, &mime_vec);9559} else {9560mime_vec.ptr = mime_type;9561mime_vec.len = strlen(mime_type);9562}9563if (filep->stat.size > INT64_MAX) {9564mg_send_http_error(conn,9565500,9566"Error: File size is too large to send\n%" INT64_FMT,9567filep->stat.size);9568return;9569}9570cl = (int64_t)filep->stat.size;9571conn->status_code = 200;9572range[0] = '\0';95739574#if defined(USE_ZLIB)9575/* if this file is in fact a pre-gzipped file, rewrite its filename9576* it's important to rewrite the filename after resolving9577* the mime type from it, to preserve the actual file's type */9578if (!conn->accept_gzip) {9579allow_on_the_fly_compression = 0;9580}9581#endif95829583if (filep->stat.is_gzipped) {9584mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);95859586if (truncated) {9587mg_send_http_error(conn,9588500,9589"Error: Path of zipped file too long (%s)",9590path);9591return;9592}95939594path = gz_path;9595encoding = "Content-Encoding: gzip\r\n";95969597#if defined(USE_ZLIB)9598/* File is already compressed. No "on the fly" compression. */9599allow_on_the_fly_compression = 0;9600#endif9601}96029603if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {9604mg_send_http_error(conn,9605500,9606"Error: Cannot open file\nfopen(%s): %s",9607path,9608strerror(ERRNO));9609return;9610}96119612fclose_on_exec(&filep->access, conn);96139614/* If "Range" request was made: parse header, send only selected part9615* of the file. */9616r1 = r2 = 0;9617hdr = mg_get_header(conn, "Range");9618if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)9619&& (r1 >= 0) && (r2 >= 0)) {9620/* actually, range requests don't play well with a pre-gzipped9621* file (since the range is specified in the uncompressed space) */9622if (filep->stat.is_gzipped) {9623mg_send_http_error(9624conn,9625416, /* 416 = Range Not Satisfiable */9626"%s",9627"Error: Range requests in gzipped files are not supported");9628(void)mg_fclose(9629&filep->access); /* ignore error on read only file */9630return;9631}9632conn->status_code = 206;9633cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);9634mg_snprintf(conn,9635NULL, /* range buffer is big enough */9636range,9637sizeof(range),9638"Content-Range: bytes "9639"%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",9640r1,9641r1 + cl - 1,9642filep->stat.size);9643msg = "Partial Content";96449645#if defined(USE_ZLIB)9646/* Do not compress ranges. */9647allow_on_the_fly_compression = 0;9648#endif9649}96509651/* Do not compress small files. Small files do not benefit from file9652* compression, but there is still some overhead. */9653#if defined(USE_ZLIB)9654if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {9655/* File is below the size limit. */9656allow_on_the_fly_compression = 0;9657}9658#endif96599660/* Standard CORS header */9661hdr = mg_get_header(conn, "Origin");9662if (hdr) {9663/* Cross-origin resource sharing (CORS), see9664* http://www.html5rocks.com/en/tutorials/cors/,9665* http://www.html5rocks.com/static/images/cors_server_flowchart.png9666* -9667* preflight is not supported for files. */9668cors1 = "Access-Control-Allow-Origin: ";9669cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];9670cors3 = "\r\n";9671} else {9672cors1 = cors2 = cors3 = "";9673}96749675/* Prepare Etag, Date, Last-Modified headers. Must be in UTC,9676* according to9677* http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */9678gmt_time_string(date, sizeof(date), &curtime);9679gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);9680construct_etag(etag, sizeof(etag), &filep->stat);96819682/* Send header */9683(void)mg_printf(conn,9684"HTTP/1.1 %d %s\r\n"9685"%s%s%s" /* CORS */9686"Date: %s\r\n"9687"Last-Modified: %s\r\n"9688"Etag: %s\r\n"9689"Content-Type: %.*s\r\n"9690"Connection: %s\r\n",9691conn->status_code,9692msg,9693cors1,9694cors2,9695cors3,9696date,9697lm,9698etag,9699(int)mime_vec.len,9700mime_vec.ptr,9701suggest_connection_header(conn));9702send_static_cache_header(conn);9703send_additional_header(conn);97049705#if defined(USE_ZLIB)9706/* On the fly compression allowed */9707if (allow_on_the_fly_compression) {9708/* For on the fly compression, we don't know the content size in9709* advance, so we have to use chunked encoding */9710(void)mg_printf(conn,9711"Content-Encoding: gzip\r\n"9712"Transfer-Encoding: chunked\r\n");9713} else9714#endif9715{9716/* Without on-the-fly compression, we know the content-length9717* and we can use ranges (with on-the-fly compression we cannot).9718* So we send these response headers only in this case. */9719(void)mg_printf(conn,9720"Content-Length: %" INT64_FMT "\r\n"9721"Accept-Ranges: bytes\r\n"9722"%s" /* range */9723"%s" /* encoding */,9724cl,9725range,9726encoding);9727}97289729/* The previous code must not add any header starting with X- to make9730* sure no one of the additional_headers is included twice */9731if (additional_headers != NULL) {9732(void)mg_printf(conn,9733"%.*s\r\n\r\n",9734(int)strlen(additional_headers),9735additional_headers);9736} else {9737(void)mg_printf(conn, "\r\n");9738}97399740if (!is_head_request) {9741#if defined(USE_ZLIB)9742if (allow_on_the_fly_compression) {9743/* Compress and send */9744send_compressed_data(conn, filep);9745} else9746#endif9747{9748/* Send file directly */9749send_file_data(conn, filep, r1, cl);9750}9751}9752(void)mg_fclose(&filep->access); /* ignore error on read only file */9753}975497559756int9757mg_send_file_body(struct mg_connection *conn, const char *path)9758{9759struct mg_file file = STRUCT_FILE_INITIALIZER;9760if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {9761return -1;9762}9763fclose_on_exec(&file.access, conn);9764send_file_data(conn, &file, 0, INT64_MAX);9765(void)mg_fclose(&file.access); /* Ignore errors for readonly files */9766return 0; /* >= 0 for OK */9767}976897699770#if !defined(NO_CACHING)9771/* Return True if we should reply 304 Not Modified. */9772static int9773is_not_modified(const struct mg_connection *conn,9774const struct mg_file_stat *filestat)9775{9776char etag[64];9777const char *ims = mg_get_header(conn, "If-Modified-Since");9778const char *inm = mg_get_header(conn, "If-None-Match");9779construct_etag(etag, sizeof(etag), filestat);97809781return ((inm != NULL) && !mg_strcasecmp(etag, inm))9782|| ((ims != NULL)9783&& (filestat->last_modified <= parse_date_string(ims)));9784}97859786static void9787handle_not_modified_static_file_request(struct mg_connection *conn,9788struct mg_file *filep)9789{9790char date[64], lm[64], etag[64];9791time_t curtime = time(NULL);97929793if ((conn == NULL) || (filep == NULL)) {9794return;9795}9796conn->status_code = 304;9797gmt_time_string(date, sizeof(date), &curtime);9798gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);9799construct_etag(etag, sizeof(etag), &filep->stat);98009801(void)mg_printf(conn,9802"HTTP/1.1 %d %s\r\n"9803"Date: %s\r\n",9804conn->status_code,9805mg_get_response_code_text(conn, conn->status_code),9806date);9807send_static_cache_header(conn);9808send_additional_header(conn);9809(void)mg_printf(conn,9810"Last-Modified: %s\r\n"9811"Etag: %s\r\n"9812"Connection: %s\r\n"9813"\r\n",9814lm,9815etag,9816suggest_connection_header(conn));9817}9818#endif981998209821void9822mg_send_file(struct mg_connection *conn, const char *path)9823{9824mg_send_mime_file2(conn, path, NULL, NULL);9825}982698279828void9829mg_send_mime_file(struct mg_connection *conn,9830const char *path,9831const char *mime_type)9832{9833mg_send_mime_file2(conn, path, mime_type, NULL);9834}983598369837void9838mg_send_mime_file2(struct mg_connection *conn,9839const char *path,9840const char *mime_type,9841const char *additional_headers)9842{9843struct mg_file file = STRUCT_FILE_INITIALIZER;98449845if (!conn) {9846/* No conn */9847return;9848}98499850if (mg_stat(conn, path, &file.stat)) {9851#if !defined(NO_CACHING)9852if (is_not_modified(conn, &file.stat)) {9853/* Send 304 "Not Modified" - this must not send any body data */9854handle_not_modified_static_file_request(conn, &file);9855} else9856#endif /* NO_CACHING */9857if (file.stat.is_directory) {9858if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],9859"yes")) {9860handle_directory_request(conn, path);9861} else {9862mg_send_http_error(conn,9863403,9864"%s",9865"Error: Directory listing denied");9866}9867} else {9868handle_static_file_request(9869conn, path, &file, mime_type, additional_headers);9870}9871} else {9872mg_send_http_error(conn, 404, "%s", "Error: File not found");9873}9874}987598769877/* For a given PUT path, create all intermediate subdirectories.9878* Return 0 if the path itself is a directory.9879* Return 1 if the path leads to a file.9880* Return -1 for if the path is too long.9881* Return -2 if path can not be created.9882*/9883static int9884put_dir(struct mg_connection *conn, const char *path)9885{9886char buf[PATH_MAX];9887const char *s, *p;9888struct mg_file file = STRUCT_FILE_INITIALIZER;9889size_t len;9890int res = 1;98919892for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {9893len = (size_t)(p - path);9894if (len >= sizeof(buf)) {9895/* path too long */9896res = -1;9897break;9898}9899memcpy(buf, path, len);9900buf[len] = '\0';99019902/* Try to create intermediate directory */9903DEBUG_TRACE("mkdir(%s)", buf);9904if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {9905/* path does not exixt and can not be created */9906res = -2;9907break;9908}99099910/* Is path itself a directory? */9911if (p[1] == '\0') {9912res = 0;9913}9914}99159916return res;9917}991899199920static void9921remove_bad_file(const struct mg_connection *conn, const char *path)9922{9923int r = mg_remove(conn, path);9924if (r != 0) {9925mg_cry_internal(conn,9926"%s: Cannot remove invalid file %s",9927__func__,9928path);9929}9930}993199329933long long9934mg_store_body(struct mg_connection *conn, const char *path)9935{9936char buf[MG_BUF_LEN];9937long long len = 0;9938int ret, n;9939struct mg_file fi;99409941if (conn->consumed_content != 0) {9942mg_cry_internal(conn, "%s: Contents already consumed", __func__);9943return -11;9944}99459946ret = put_dir(conn, path);9947if (ret < 0) {9948/* -1 for path too long,9949* -2 for path can not be created. */9950return ret;9951}9952if (ret != 1) {9953/* Return 0 means, path itself is a directory. */9954return 0;9955}99569957if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {9958return -12;9959}99609961ret = mg_read(conn, buf, sizeof(buf));9962while (ret > 0) {9963n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);9964if (n != ret) {9965(void)mg_fclose(9966&fi.access); /* File is bad and will be removed anyway. */9967remove_bad_file(conn, path);9968return -13;9969}9970len += ret;9971ret = mg_read(conn, buf, sizeof(buf));9972}99739974/* File is open for writing. If fclose fails, there was probably an9975* error flushing the buffer to disk, so the file on disk might be9976* broken. Delete it and return an error to the caller. */9977if (mg_fclose(&fi.access) != 0) {9978remove_bad_file(conn, path);9979return -14;9980}99819982return len;9983}998499859986/* Parse a buffer:9987* Forward the string pointer till the end of a word, then9988* terminate it and forward till the begin of the next word.9989*/9990static int9991skip_to_end_of_word_and_terminate(char **ppw, int eol)9992{9993/* Forward until a space is found - use isgraph here */9994/* See http://www.cplusplus.com/reference/cctype/ */9995while (isgraph(**ppw)) {9996(*ppw)++;9997}99989999/* Check end of word */10000if (eol) {10001/* must be a end of line */10002if ((**ppw != '\r') && (**ppw != '\n')) {10003return -1;10004}10005} else {10006/* must be a end of a word, but not a line */10007if (**ppw != ' ') {10008return -1;10009}10010}1001110012/* Terminate and forward to the next word */10013do {10014**ppw = 0;10015(*ppw)++;10016} while ((**ppw) && isspace(**ppw));1001710018/* Check after term */10019if (!eol) {10020/* if it's not the end of line, there must be a next word */10021if (!isgraph(**ppw)) {10022return -1;10023}10024}1002510026/* ok */10027return 1;10028}100291003010031/* Parse HTTP headers from the given buffer, advance buf pointer10032* to the point where parsing stopped.10033* All parameters must be valid pointers (not NULL).10034* Return <0 on error. */10035static int10036parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])10037{10038int i;10039int num_headers = 0;1004010041for (i = 0; i < (int)MG_MAX_HEADERS; i++) {10042char *dp = *buf;10043while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {10044dp++;10045}10046if (dp == *buf) {10047/* End of headers reached. */10048break;10049}10050if (*dp != ':') {10051/* This is not a valid field. */10052return -1;10053}1005410055/* End of header key (*dp == ':') */10056/* Truncate here and set the key name */10057*dp = 0;10058hdr[i].name = *buf;10059do {10060dp++;10061} while (*dp == ' ');1006210063/* The rest of the line is the value */10064hdr[i].value = dp;10065*buf = dp + strcspn(dp, "\r\n");10066if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {10067*buf = NULL;10068}1006910070num_headers = i + 1;10071if (*buf) {10072(*buf)[0] = 0;10073(*buf)[1] = 0;10074*buf += 2;10075} else {10076*buf = dp;10077break;10078}1007910080if ((*buf)[0] == '\r') {10081/* This is the end of the header */10082break;10083}10084}10085return num_headers;10086}100871008810089struct mg_http_method_info {10090const char *name;10091int request_has_body;10092int response_has_body;10093int is_safe;10094int is_idempotent;10095int is_cacheable;10096};100971009810099/* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */10100static struct mg_http_method_info http_methods[] = {10101/* HTTP (RFC 2616) */10102{"GET", 0, 1, 1, 1, 1},10103{"POST", 1, 1, 0, 0, 0},10104{"PUT", 1, 0, 0, 1, 0},10105{"DELETE", 0, 0, 0, 1, 0},10106{"HEAD", 0, 0, 1, 1, 1},10107{"OPTIONS", 0, 0, 1, 1, 0},10108{"CONNECT", 1, 1, 0, 0, 0},10109/* TRACE method (RFC 2616) is not supported for security reasons */1011010111/* PATCH method (RFC 5789) */10112{"PATCH", 1, 0, 0, 0, 0},10113/* PATCH method only allowed for CGI/Lua/LSP and callbacks. */1011410115/* WEBDAV (RFC 2518) */10116{"PROPFIND", 0, 1, 1, 1, 0},10117/* http://www.webdav.org/specs/rfc4918.html, 9.1:10118* Some PROPFIND results MAY be cached, with care,10119* as there is no cache validation mechanism for10120* most properties. This method is both safe and10121* idempotent (see Section 9.1 of [RFC2616]). */10122{"MKCOL", 0, 0, 0, 1, 0},10123/* http://www.webdav.org/specs/rfc4918.html, 9.1:10124* When MKCOL is invoked without a request body,10125* the newly created collection SHOULD have no10126* members. A MKCOL request message may contain10127* a message body. The precise behavior of a MKCOL10128* request when the body is present is undefined,10129* ... ==> We do not support MKCOL with body data.10130* This method is idempotent, but not safe (see10131* Section 9.1 of [RFC2616]). Responses to this10132* method MUST NOT be cached. */1013310134/* Unsupported WEBDAV Methods: */10135/* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */10136/* + 11 methods from RFC 3253 */10137/* ORDERPATCH (RFC 3648) */10138/* ACL (RFC 3744) */10139/* SEARCH (RFC 5323) */10140/* + MicroSoft extensions10141* https://msdn.microsoft.com/en-us/library/aa142917.aspx */1014210143/* REPORT method (RFC 3253) */10144{"REPORT", 1, 1, 1, 1, 1},10145/* REPORT method only allowed for CGI/Lua/LSP and callbacks. */10146/* It was defined for WEBDAV in RFC 3253, Sec. 3.610147* (https://tools.ietf.org/html/rfc3253#section-3.6), but seems10148* to be useful for REST in case a "GET request with body" is10149* required. */1015010151{NULL, 0, 0, 0, 0, 0}10152/* end of list */10153};101541015510156static const struct mg_http_method_info *10157get_http_method_info(const char *method)10158{10159/* Check if the method is known to the server. The list of all known10160* HTTP methods can be found here at10161* http://www.iana.org/assignments/http-methods/http-methods.xhtml10162*/10163const struct mg_http_method_info *m = http_methods;1016410165while (m->name) {10166if (!strcmp(m->name, method)) {10167return m;10168}10169m++;10170}10171return NULL;10172}101731017410175static int10176is_valid_http_method(const char *method)10177{10178return (get_http_method_info(method) != NULL);10179}101801018110182/* Parse HTTP request, fill in mg_request_info structure.10183* This function modifies the buffer by NUL-terminating10184* HTTP request components, header names and header values.10185* Parameters:10186* buf (in/out): pointer to the HTTP header to parse and split10187* len (in): length of HTTP header buffer10188* re (out): parsed header as mg_request_info10189* buf and ri must be valid pointers (not NULL), len>0.10190* Returns <0 on error. */10191static int10192parse_http_request(char *buf, int len, struct mg_request_info *ri)10193{10194int request_length;10195int init_skip = 0;1019610197/* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,10198* remote_port */10199ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =10200NULL;10201ri->num_headers = 0;1020210203/* RFC says that all initial whitespaces should be ingored */10204/* This included all leading \r and \n (isspace) */10205/* See table: http://www.cplusplus.com/reference/cctype/ */10206while ((len > 0) && isspace(*(unsigned char *)buf)) {10207buf++;10208len--;10209init_skip++;10210}1021110212if (len == 0) {10213/* Incomplete request */10214return 0;10215}1021610217/* Control characters are not allowed, including zero */10218if (iscntrl(*(unsigned char *)buf)) {10219return -1;10220}1022110222/* Find end of HTTP header */10223request_length = get_http_header_len(buf, len);10224if (request_length <= 0) {10225return request_length;10226}10227buf[request_length - 1] = '\0';1022810229if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {10230return -1;10231}1023210233/* The first word has to be the HTTP method */10234ri->request_method = buf;1023510236if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {10237return -1;10238}1023910240/* Check for a valid http method */10241if (!is_valid_http_method(ri->request_method)) {10242return -1;10243}1024410245/* The second word is the URI */10246ri->request_uri = buf;1024710248if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {10249return -1;10250}1025110252/* Next would be the HTTP version */10253ri->http_version = buf;1025410255if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {10256return -1;10257}1025810259/* Check for a valid HTTP version key */10260if (strncmp(ri->http_version, "HTTP/", 5) != 0) {10261/* Invalid request */10262return -1;10263}10264ri->http_version += 5;102651026610267/* Parse all HTTP headers */10268ri->num_headers = parse_http_headers(&buf, ri->http_headers);10269if (ri->num_headers < 0) {10270/* Error while parsing headers */10271return -1;10272}1027310274return request_length + init_skip;10275}102761027710278static int10279parse_http_response(char *buf, int len, struct mg_response_info *ri)10280{10281int response_length;10282int init_skip = 0;10283char *tmp, *tmp2;10284long l;1028510286/* Initialize elements. */10287ri->http_version = ri->status_text = NULL;10288ri->num_headers = ri->status_code = 0;1028910290/* RFC says that all initial whitespaces should be ingored */10291/* This included all leading \r and \n (isspace) */10292/* See table: http://www.cplusplus.com/reference/cctype/ */10293while ((len > 0) && isspace(*(unsigned char *)buf)) {10294buf++;10295len--;10296init_skip++;10297}1029810299if (len == 0) {10300/* Incomplete request */10301return 0;10302}1030310304/* Control characters are not allowed, including zero */10305if (iscntrl(*(unsigned char *)buf)) {10306return -1;10307}1030810309/* Find end of HTTP header */10310response_length = get_http_header_len(buf, len);10311if (response_length <= 0) {10312return response_length;10313}10314buf[response_length - 1] = '\0';1031510316if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {10317return -1;10318}1031910320/* The first word is the HTTP version */10321/* Check for a valid HTTP version key */10322if (strncmp(buf, "HTTP/", 5) != 0) {10323/* Invalid request */10324return -1;10325}10326buf += 5;10327if (!isgraph(buf[0])) {10328/* Invalid request */10329return -1;10330}10331ri->http_version = buf;1033210333if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {10334return -1;10335}1033610337/* The second word is the status as a number */10338tmp = buf;1033910340if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {10341return -1;10342}1034310344l = strtol(tmp, &tmp2, 10);10345if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {10346/* Everything else but a 3 digit code is invalid */10347return -1;10348}10349ri->status_code = (int)l;1035010351/* The rest of the line is the status text */10352ri->status_text = buf;1035310354/* Find end of status text */10355/* isgraph or isspace = isprint */10356while (isprint(*buf)) {10357buf++;10358}10359if ((*buf != '\r') && (*buf != '\n')) {10360return -1;10361}10362/* Terminate string and forward buf to next line */10363do {10364*buf = 0;10365buf++;10366} while ((*buf) && isspace(*buf));103671036810369/* Parse all HTTP headers */10370ri->num_headers = parse_http_headers(&buf, ri->http_headers);10371if (ri->num_headers < 0) {10372/* Error while parsing headers */10373return -1;10374}1037510376return response_length + init_skip;10377}103781037910380/* Keep reading the input (either opened file descriptor fd, or socket sock,10381* or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the10382* buffer (which marks the end of HTTP request). Buffer buf may already10383* have some data. The length of the data is stored in nread.10384* Upon every read operation, increase nread by the number of bytes read. */10385static int10386read_message(FILE *fp,10387struct mg_connection *conn,10388char *buf,10389int bufsiz,10390int *nread)10391{10392int request_len, n = 0;10393struct timespec last_action_time;10394double request_timeout;1039510396if (!conn) {10397return 0;10398}1039910400memset(&last_action_time, 0, sizeof(last_action_time));1040110402if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {10403/* value of request_timeout is in seconds, config in milliseconds */10404request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;10405} else {10406request_timeout = -1.0;10407}10408if (conn->handled_requests > 0) {10409if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {10410request_timeout =10411atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;10412}10413}1041410415request_len = get_http_header_len(buf, *nread);1041610417/* first time reading from this connection */10418clock_gettime(CLOCK_MONOTONIC, &last_action_time);1041910420while (request_len == 0) {10421/* Full request not yet received */10422if (conn->phys_ctx->stop_flag != 0) {10423/* Server is to be stopped. */10424return -1;10425}1042610427if (*nread >= bufsiz) {10428/* Request too long */10429return -2;10430}1043110432n = pull_inner(10433fp, conn, buf + *nread, bufsiz - *nread, request_timeout);10434if (n == -2) {10435/* Receive error */10436return -1;10437}10438if (n > 0) {10439*nread += n;10440request_len = get_http_header_len(buf, *nread);10441} else {10442request_len = 0;10443}1044410445if ((request_len == 0) && (request_timeout >= 0)) {10446if (mg_difftimespec(&last_action_time, &(conn->req_time))10447> request_timeout) {10448/* Timeout */10449return -1;10450}10451clock_gettime(CLOCK_MONOTONIC, &last_action_time);10452}10453}1045410455return request_len;10456}104571045810459#if !defined(NO_CGI) || !defined(NO_FILES)10460static int10461forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)10462{10463const char *expect, *body;10464char buf[MG_BUF_LEN];10465int to_read, nread, success = 0;10466int64_t buffered_len;10467double timeout = -1.0;1046810469if (!conn) {10470return 0;10471}10472if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {10473timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;10474}1047510476expect = mg_get_header(conn, "Expect");10477DEBUG_ASSERT(fp != NULL);10478if (!fp) {10479mg_send_http_error(conn, 500, "%s", "Error: NULL File");10480return 0;10481}1048210483if ((conn->content_len == -1) && (!conn->is_chunked)) {10484/* Content length is not specified by the client. */10485mg_send_http_error(conn,10486411,10487"%s",10488"Error: Client did not specify content length");10489} else if ((expect != NULL)10490&& (mg_strcasecmp(expect, "100-continue") != 0)) {10491/* Client sent an "Expect: xyz" header and xyz is not 100-continue.10492*/10493mg_send_http_error(conn,10494417,10495"Error: Can not fulfill expectation %s",10496expect);10497} else {10498if (expect != NULL) {10499(void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");10500conn->status_code = 100;10501} else {10502conn->status_code = 200;10503}1050410505buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len10506- conn->consumed_content;1050710508DEBUG_ASSERT(buffered_len >= 0);10509DEBUG_ASSERT(conn->consumed_content == 0);1051010511if ((buffered_len < 0) || (conn->consumed_content != 0)) {10512mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");10513return 0;10514}1051510516if (buffered_len > 0) {10517if ((int64_t)buffered_len > conn->content_len) {10518buffered_len = (int)conn->content_len;10519}10520body = conn->buf + conn->request_len + conn->consumed_content;10521push_all(10522conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);10523conn->consumed_content += buffered_len;10524}1052510526nread = 0;10527while (conn->consumed_content < conn->content_len) {10528to_read = sizeof(buf);10529if ((int64_t)to_read > conn->content_len - conn->consumed_content) {10530to_read = (int)(conn->content_len - conn->consumed_content);10531}10532nread = pull_inner(NULL, conn, buf, to_read, timeout);10533if (nread == -2) {10534/* error */10535break;10536}10537if (nread > 0) {10538if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)10539!= nread) {10540break;10541}10542}10543conn->consumed_content += nread;10544}1054510546if (conn->consumed_content == conn->content_len) {10547success = (nread >= 0);10548}1054910550/* Each error code path in this function must send an error */10551if (!success) {10552/* NOTE: Maybe some data has already been sent. */10553/* TODO (low): If some data has been sent, a correct error10554* reply can no longer be sent, so just close the connection */10555mg_send_http_error(conn, 500, "%s", "");10556}10557}1055810559return success;10560}10561#endif105621056310564#if defined(USE_TIMERS)1056510566#define TIMER_API static10567#include "timer.inl"1056810569#endif /* USE_TIMERS */105701057110572#if !defined(NO_CGI)10573/* This structure helps to create an environment for the spawned CGI10574* program.10575* Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,10576* last element must be NULL.10577* However, on Windows there is a requirement that all these10578* VARIABLE=VALUE\010579* strings must reside in a contiguous buffer. The end of the buffer is10580* marked by two '\0' characters.10581* We satisfy both worlds: we create an envp array (which is vars), all10582* entries are actually pointers inside buf. */10583struct cgi_environment {10584struct mg_connection *conn;10585/* Data block */10586char *buf; /* Environment buffer */10587size_t buflen; /* Space available in buf */10588size_t bufused; /* Space taken in buf */10589/* Index block */10590char **var; /* char **envp */10591size_t varlen; /* Number of variables available in var */10592size_t varused; /* Number of variables stored in var */10593};105941059510596static void addenv(struct cgi_environment *env,10597PRINTF_FORMAT_STRING(const char *fmt),10598...) PRINTF_ARGS(2, 3);1059910600/* Append VARIABLE=VALUE\0 string to the buffer, and add a respective10601* pointer into the vars array. Assumes env != NULL and fmt != NULL. */10602static void10603addenv(struct cgi_environment *env, const char *fmt, ...)10604{10605size_t n, space;10606int truncated = 0;10607char *added;10608va_list ap;1060910610/* Calculate how much space is left in the buffer */10611space = (env->buflen - env->bufused);1061210613/* Calculate an estimate for the required space */10614n = strlen(fmt) + 2 + 128;1061510616do {10617if (space <= n) {10618/* Allocate new buffer */10619n = env->buflen + CGI_ENVIRONMENT_SIZE;10620added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);10621if (!added) {10622/* Out of memory */10623mg_cry_internal(10624env->conn,10625"%s: Cannot allocate memory for CGI variable [%s]",10626__func__,10627fmt);10628return;10629}10630env->buf = added;10631env->buflen = n;10632space = (env->buflen - env->bufused);10633}1063410635/* Make a pointer to the free space int the buffer */10636added = env->buf + env->bufused;1063710638/* Copy VARIABLE=VALUE\0 string into the free space */10639va_start(ap, fmt);10640mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);10641va_end(ap);1064210643/* Do not add truncated strings to the environment */10644if (truncated) {10645/* Reallocate the buffer */10646space = 0;10647n = 1;10648}10649} while (truncated);1065010651/* Calculate number of bytes added to the environment */10652n = strlen(added) + 1;10653env->bufused += n;1065410655/* Now update the variable index */10656space = (env->varlen - env->varused);10657if (space < 2) {10658mg_cry_internal(env->conn,10659"%s: Cannot register CGI variable [%s]",10660__func__,10661fmt);10662return;10663}1066410665/* Append a pointer to the added string into the envp array */10666env->var[env->varused] = added;10667env->varused++;10668}1066910670/* Return 0 on success, non-zero if an error occurs. */1067110672static int10673prepare_cgi_environment(struct mg_connection *conn,10674const char *prog,10675struct cgi_environment *env)10676{10677const char *s;10678struct vec var_vec;10679char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];10680int i, truncated, uri_len;1068110682if ((conn == NULL) || (prog == NULL) || (env == NULL)) {10683return -1;10684}1068510686env->conn = conn;10687env->buflen = CGI_ENVIRONMENT_SIZE;10688env->bufused = 0;10689env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);10690if (env->buf == NULL) {10691mg_cry_internal(conn,10692"%s: Not enough memory for environmental buffer",10693__func__);10694return -1;10695}10696env->varlen = MAX_CGI_ENVIR_VARS;10697env->varused = 0;10698env->var =10699(char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);10700if (env->var == NULL) {10701mg_cry_internal(conn,10702"%s: Not enough memory for environmental variables",10703__func__);10704mg_free(env->buf);10705return -1;10706}1070710708addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);10709addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);10710addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);10711addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());1071210713/* Prepare the environment block */10714addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");10715addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");10716addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */1071710718#if defined(USE_IPV6)10719if (conn->client.lsa.sa.sa_family == AF_INET6) {10720addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));10721} else10722#endif10723{10724addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));10725}1072610727sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);10728addenv(env, "REMOTE_ADDR=%s", src_addr);1072910730addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);10731addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);1073210733addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);10734addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);1073510736/* SCRIPT_NAME */10737uri_len = (int)strlen(conn->request_info.local_uri);10738if (conn->path_info == NULL) {10739if (conn->request_info.local_uri[uri_len - 1] != '/') {10740/* URI: /path_to_script/script.cgi */10741addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);10742} else {10743/* URI: /path_to_script/ ... using index.cgi */10744const char *index_file = strrchr(prog, '/');10745if (index_file) {10746addenv(env,10747"SCRIPT_NAME=%s%s",10748conn->request_info.local_uri,10749index_file + 1);10750}10751}10752} else {10753/* URI: /path_to_script/script.cgi/path_info */10754addenv(env,10755"SCRIPT_NAME=%.*s",10756uri_len - (int)strlen(conn->path_info),10757conn->request_info.local_uri);10758}1075910760addenv(env, "SCRIPT_FILENAME=%s", prog);10761if (conn->path_info == NULL) {10762addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);10763} else {10764addenv(env,10765"PATH_TRANSLATED=%s%s",10766conn->dom_ctx->config[DOCUMENT_ROOT],10767conn->path_info);10768}1076910770addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");1077110772if ((s = mg_get_header(conn, "Content-Type")) != NULL) {10773addenv(env, "CONTENT_TYPE=%s", s);10774}10775if (conn->request_info.query_string != NULL) {10776addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);10777}10778if ((s = mg_get_header(conn, "Content-Length")) != NULL) {10779addenv(env, "CONTENT_LENGTH=%s", s);10780}10781if ((s = getenv("PATH")) != NULL) {10782addenv(env, "PATH=%s", s);10783}10784if (conn->path_info != NULL) {10785addenv(env, "PATH_INFO=%s", conn->path_info);10786}1078710788if (conn->status_code > 0) {10789/* CGI error handler should show the status code */10790addenv(env, "STATUS=%d", conn->status_code);10791}1079210793#if defined(_WIN32)10794if ((s = getenv("COMSPEC")) != NULL) {10795addenv(env, "COMSPEC=%s", s);10796}10797if ((s = getenv("SYSTEMROOT")) != NULL) {10798addenv(env, "SYSTEMROOT=%s", s);10799}10800if ((s = getenv("SystemDrive")) != NULL) {10801addenv(env, "SystemDrive=%s", s);10802}10803if ((s = getenv("ProgramFiles")) != NULL) {10804addenv(env, "ProgramFiles=%s", s);10805}10806if ((s = getenv("ProgramFiles(x86)")) != NULL) {10807addenv(env, "ProgramFiles(x86)=%s", s);10808}10809#else10810if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {10811addenv(env, "LD_LIBRARY_PATH=%s", s);10812}10813#endif /* _WIN32 */1081410815if ((s = getenv("PERLLIB")) != NULL) {10816addenv(env, "PERLLIB=%s", s);10817}1081810819if (conn->request_info.remote_user != NULL) {10820addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);10821addenv(env, "%s", "AUTH_TYPE=Digest");10822}1082310824/* Add all headers as HTTP_* variables */10825for (i = 0; i < conn->request_info.num_headers; i++) {1082610827(void)mg_snprintf(conn,10828&truncated,10829http_var_name,10830sizeof(http_var_name),10831"HTTP_%s",10832conn->request_info.http_headers[i].name);1083310834if (truncated) {10835mg_cry_internal(conn,10836"%s: HTTP header variable too long [%s]",10837__func__,10838conn->request_info.http_headers[i].name);10839continue;10840}1084110842/* Convert variable name into uppercase, and change - to _ */10843for (p = http_var_name; *p != '\0'; p++) {10844if (*p == '-') {10845*p = '_';10846}10847*p = (char)toupper(*(unsigned char *)p);10848}1084910850addenv(env,10851"%s=%s",10852http_var_name,10853conn->request_info.http_headers[i].value);10854}1085510856/* Add user-specified variables */10857s = conn->dom_ctx->config[CGI_ENVIRONMENT];10858while ((s = next_option(s, &var_vec, NULL)) != NULL) {10859addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);10860}1086110862env->var[env->varused] = NULL;10863env->buf[env->bufused] = '\0';1086410865return 0;10866}108671086810869/* Data for CGI process control: PID and number of references */10870struct process_control_data {10871pid_t pid;10872int references;10873};1087410875static int10876abort_process(void *data)10877{10878/* Waitpid checks for child status and won't work for a pid that does not10879* identify a child of the current process. Thus, if the pid is reused,10880* we will not affect a different process. */10881struct process_control_data *proc = (struct process_control_data *)data;10882int status = 0;10883int refs;10884pid_t ret_pid;1088510886ret_pid = waitpid(proc->pid, &status, WNOHANG);10887if ((ret_pid != (pid_t)-1) && (status == 0)) {10888/* Stop child process */10889DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);10890kill(proc->pid, SIGABRT);1089110892/* Wait until process is terminated (don't leave zombies) */10893while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */10894;10895} else {10896DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);10897}10898/* Dec reference counter */10899refs = mg_atomic_dec(&proc->references);10900if (refs == 0) {10901/* no more references - free data */10902mg_free(data);10903}1090410905return 0;10906}109071090810909static void10910handle_cgi_request(struct mg_connection *conn, const char *prog)10911{10912char *buf;10913size_t buflen;10914int headers_len, data_len, i, truncated;10915int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};10916const char *status, *status_text, *connection_state;10917char *pbuf, dir[PATH_MAX], *p;10918struct mg_request_info ri;10919struct cgi_environment blk;10920FILE *in = NULL, *out = NULL, *err = NULL;10921struct mg_file fout = STRUCT_FILE_INITIALIZER;10922pid_t pid = (pid_t)-1;10923struct process_control_data *proc = NULL;1092410925#if defined(USE_TIMERS)10926double cgi_timeout = -1.0;10927if (conn->dom_ctx->config[CGI_TIMEOUT]) {10928/* Get timeout in seconds */10929cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;10930}10931#endif1093210933if (conn == NULL) {10934return;10935}1093610937buf = NULL;10938buflen = conn->phys_ctx->max_request_size;10939i = prepare_cgi_environment(conn, prog, &blk);10940if (i != 0) {10941blk.buf = NULL;10942blk.var = NULL;10943goto done;10944}1094510946/* CGI must be executed in its own directory. 'dir' must point to the10947* directory containing executable program, 'p' must point to the10948* executable program name relative to 'dir'. */10949(void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);1095010951if (truncated) {10952mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);10953mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");10954goto done;10955}1095610957if ((p = strrchr(dir, '/')) != NULL) {10958*p++ = '\0';10959} else {10960dir[0] = '.';10961dir[1] = '\0';10962p = (char *)prog;10963}1096410965if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {10966status = strerror(ERRNO);10967mg_cry_internal(10968conn,10969"Error: CGI program \"%s\": Can not create CGI pipes: %s",10970prog,10971status);10972mg_send_http_error(conn,10973500,10974"Error: Cannot create CGI pipe: %s",10975status);10976goto done;10977}1097810979proc = (struct process_control_data *)10980mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);10981if (proc == NULL) {10982mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);10983mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);10984goto done;10985}1098610987DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);10988pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);1098910990if (pid == (pid_t)-1) {10991status = strerror(ERRNO);10992mg_cry_internal(10993conn,10994"Error: CGI program \"%s\": Can not spawn CGI process: %s",10995prog,10996status);10997mg_send_http_error(conn,10998500,10999"Error: Cannot spawn CGI process [%s]: %s",11000prog,11001status);11002mg_free(proc);11003proc = NULL;11004goto done;11005}1100611007/* Store data in shared process_control_data */11008proc->pid = pid;11009proc->references = 1;1101011011#if defined(USE_TIMERS)11012if (cgi_timeout > 0.0) {11013proc->references = 2;1101411015// Start a timer for CGI11016timer_add(conn->phys_ctx,11017cgi_timeout /* in seconds */,110180.0,110191,11020abort_process,11021(void *)proc);11022}11023#endif1102411025/* Make sure child closes all pipe descriptors. It must dup them to 0,1 */11026set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */11027set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */11028set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */11029set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */11030set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */11031set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */1103211033/* Parent closes only one side of the pipes.11034* If we don't mark them as closed, close() attempt before11035* return from this function throws an exception on Windows.11036* Windows does not like when closed descriptor is closed again. */11037(void)close(fdin[0]);11038(void)close(fdout[1]);11039(void)close(fderr[1]);11040fdin[0] = fdout[1] = fderr[1] = -1;1104111042if ((in = fdopen(fdin[1], "wb")) == NULL) {11043status = strerror(ERRNO);11044mg_cry_internal(conn,11045"Error: CGI program \"%s\": Can not open stdin: %s",11046prog,11047status);11048mg_send_http_error(conn,11049500,11050"Error: CGI can not open fdin\nfopen: %s",11051status);11052goto done;11053}1105411055if ((out = fdopen(fdout[0], "rb")) == NULL) {11056status = strerror(ERRNO);11057mg_cry_internal(conn,11058"Error: CGI program \"%s\": Can not open stdout: %s",11059prog,11060status);11061mg_send_http_error(conn,11062500,11063"Error: CGI can not open fdout\nfopen: %s",11064status);11065goto done;11066}1106711068if ((err = fdopen(fderr[0], "rb")) == NULL) {11069status = strerror(ERRNO);11070mg_cry_internal(conn,11071"Error: CGI program \"%s\": Can not open stderr: %s",11072prog,11073status);11074mg_send_http_error(conn,11075500,11076"Error: CGI can not open fderr\nfopen: %s",11077status);11078goto done;11079}1108011081setbuf(in, NULL);11082setbuf(out, NULL);11083setbuf(err, NULL);11084fout.access.fp = out;1108511086if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {11087DEBUG_TRACE("CGI: send body data (%lli)\n",11088(signed long long)conn->request_info.content_length);1108911090/* This is a POST/PUT request, or another request with body data. */11091if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {11092/* Error sending the body data */11093mg_cry_internal(11094conn,11095"Error: CGI program \"%s\": Forward body data failed",11096prog);11097goto done;11098}11099}1110011101/* Close so child gets an EOF. */11102fclose(in);11103in = NULL;11104fdin[1] = -1;1110511106/* Now read CGI reply into a buffer. We need to set correct11107* status code, thus we need to see all HTTP headers first.11108* Do not send anything back to client, until we buffer in all11109* HTTP headers. */11110data_len = 0;11111buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);11112if (buf == NULL) {11113mg_send_http_error(conn,11114500,11115"Error: Not enough memory for CGI buffer (%u bytes)",11116(unsigned int)buflen);11117mg_cry_internal(11118conn,11119"Error: CGI program \"%s\": Not enough memory for buffer (%u "11120"bytes)",11121prog,11122(unsigned int)buflen);11123goto done;11124}1112511126DEBUG_TRACE("CGI: %s", "wait for response");11127headers_len = read_message(out, conn, buf, (int)buflen, &data_len);11128DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);1112911130if (headers_len <= 0) {1113111132/* Could not parse the CGI response. Check if some error message on11133* stderr. */11134i = pull_all(err, conn, buf, (int)buflen);11135if (i > 0) {11136/* CGI program explicitly sent an error */11137/* Write the error message to the internal log */11138mg_cry_internal(conn,11139"Error: CGI program \"%s\" sent error "11140"message: [%.*s]",11141prog,11142i,11143buf);11144/* Don't send the error message back to the client */11145mg_send_http_error(conn,11146500,11147"Error: CGI program \"%s\" failed.",11148prog);11149} else {11150/* CGI program did not explicitly send an error, but a broken11151* respon header */11152mg_cry_internal(conn,11153"Error: CGI program sent malformed or too big "11154"(>%u bytes) HTTP headers: [%.*s]",11155(unsigned)buflen,11156data_len,11157buf);1115811159mg_send_http_error(conn,11160500,11161"Error: CGI program sent malformed or too big "11162"(>%u bytes) HTTP headers: [%.*s]",11163(unsigned)buflen,11164data_len,11165buf);11166}1116711168/* in both cases, abort processing CGI */11169goto done;11170}1117111172pbuf = buf;11173buf[headers_len - 1] = '\0';11174ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);1117511176/* Make up and send the status line */11177status_text = "OK";11178if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))11179!= NULL) {11180conn->status_code = atoi(status);11181status_text = status;11182while (isdigit(*(const unsigned char *)status_text)11183|| *status_text == ' ') {11184status_text++;11185}11186} else if (get_header(ri.http_headers, ri.num_headers, "Location")11187!= NULL) {11188conn->status_code = 307;11189} else {11190conn->status_code = 200;11191}11192connection_state =11193get_header(ri.http_headers, ri.num_headers, "Connection");11194if (!header_has_option(connection_state, "keep-alive")) {11195conn->must_close = 1;11196}1119711198DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);1119911200(void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);1120111202/* Send headers */11203for (i = 0; i < ri.num_headers; i++) {11204mg_printf(conn,11205"%s: %s\r\n",11206ri.http_headers[i].name,11207ri.http_headers[i].value);11208}11209mg_write(conn, "\r\n", 2);1121011211/* Send chunk of data that may have been read after the headers */11212mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));1121311214/* Read the rest of CGI output and send to the client */11215DEBUG_TRACE("CGI: %s", "forward all data");11216send_file_data(conn, &fout, 0, INT64_MAX);11217DEBUG_TRACE("CGI: %s", "all data sent");1121811219done:11220mg_free(blk.var);11221mg_free(blk.buf);1122211223if (pid != (pid_t)-1) {11224abort_process((void *)proc);11225}1122611227if (fdin[0] != -1) {11228close(fdin[0]);11229}11230if (fdout[1] != -1) {11231close(fdout[1]);11232}1123311234if (in != NULL) {11235fclose(in);11236} else if (fdin[1] != -1) {11237close(fdin[1]);11238}1123911240if (out != NULL) {11241fclose(out);11242} else if (fdout[0] != -1) {11243close(fdout[0]);11244}1124511246if (err != NULL) {11247fclose(err);11248} else if (fderr[0] != -1) {11249close(fderr[0]);11250}1125111252if (buf != NULL) {11253mg_free(buf);11254}11255}11256#endif /* !NO_CGI */112571125811259#if !defined(NO_FILES)11260static void11261mkcol(struct mg_connection *conn, const char *path)11262{11263int rc, body_len;11264struct de de;11265char date[64];11266time_t curtime = time(NULL);1126711268if (conn == NULL) {11269return;11270}1127111272/* TODO (mid): Check the mg_send_http_error situations in this function11273*/1127411275memset(&de.file, 0, sizeof(de.file));11276if (!mg_stat(conn, path, &de.file)) {11277mg_cry_internal(conn,11278"%s: mg_stat(%s) failed: %s",11279__func__,11280path,11281strerror(ERRNO));11282}1128311284if (de.file.last_modified) {11285/* TODO (mid): This check does not seem to make any sense ! */11286/* TODO (mid): Add a webdav unit test first, before changing11287* anything here. */11288mg_send_http_error(11289conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));11290return;11291}1129211293body_len = conn->data_len - conn->request_len;11294if (body_len > 0) {11295mg_send_http_error(11296conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));11297return;11298}1129911300rc = mg_mkdir(conn, path, 0755);1130111302if (rc == 0) {11303conn->status_code = 201;11304gmt_time_string(date, sizeof(date), &curtime);11305mg_printf(conn,11306"HTTP/1.1 %d Created\r\n"11307"Date: %s\r\n",11308conn->status_code,11309date);11310send_static_cache_header(conn);11311send_additional_header(conn);11312mg_printf(conn,11313"Content-Length: 0\r\n"11314"Connection: %s\r\n\r\n",11315suggest_connection_header(conn));11316} else {11317if (errno == EEXIST) {11318mg_send_http_error(11319conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));11320} else if (errno == EACCES) {11321mg_send_http_error(11322conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));11323} else if (errno == ENOENT) {11324mg_send_http_error(11325conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));11326} else {11327mg_send_http_error(11328conn, 500, "fopen(%s): %s", path, strerror(ERRNO));11329}11330}11331}113321133311334static void11335put_file(struct mg_connection *conn, const char *path)11336{11337struct mg_file file = STRUCT_FILE_INITIALIZER;11338const char *range;11339int64_t r1, r2;11340int rc;11341char date[64];11342time_t curtime = time(NULL);1134311344if (conn == NULL) {11345return;11346}1134711348if (mg_stat(conn, path, &file.stat)) {11349/* File already exists */11350conn->status_code = 200;1135111352if (file.stat.is_directory) {11353/* This is an already existing directory,11354* so there is nothing to do for the server. */11355rc = 0;1135611357} else {11358/* File exists and is not a directory. */11359/* Can it be replaced? */1136011361#if defined(MG_USE_OPEN_FILE)11362if (file.access.membuf != NULL) {11363/* This is an "in-memory" file, that can not be replaced */11364mg_send_http_error(conn,11365405,11366"Error: Put not possible\nReplacing %s "11367"is not supported",11368path);11369return;11370}11371#endif1137211373/* Check if the server may write this file */11374if (access(path, W_OK) == 0) {11375/* Access granted */11376conn->status_code = 200;11377rc = 1;11378} else {11379mg_send_http_error(11380conn,11381403,11382"Error: Put not possible\nReplacing %s is not allowed",11383path);11384return;11385}11386}11387} else {11388/* File should be created */11389conn->status_code = 201;11390rc = put_dir(conn, path);11391}1139211393if (rc == 0) {11394/* put_dir returns 0 if path is a directory */11395gmt_time_string(date, sizeof(date), &curtime);11396mg_printf(conn,11397"HTTP/1.1 %d %s\r\n",11398conn->status_code,11399mg_get_response_code_text(NULL, conn->status_code));11400send_no_cache_header(conn);11401send_additional_header(conn);11402mg_printf(conn,11403"Date: %s\r\n"11404"Content-Length: 0\r\n"11405"Connection: %s\r\n\r\n",11406date,11407suggest_connection_header(conn));1140811409/* Request to create a directory has been fulfilled successfully.11410* No need to put a file. */11411return;11412}1141311414if (rc == -1) {11415/* put_dir returns -1 if the path is too long */11416mg_send_http_error(conn,11417414,11418"Error: Path too long\nput_dir(%s): %s",11419path,11420strerror(ERRNO));11421return;11422}1142311424if (rc == -2) {11425/* put_dir returns -2 if the directory can not be created */11426mg_send_http_error(conn,11427500,11428"Error: Can not create directory\nput_dir(%s): %s",11429path,11430strerror(ERRNO));11431return;11432}1143311434/* A file should be created or overwritten. */11435/* Currently CivetWeb does not nead read+write access. */11436if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)11437|| file.access.fp == NULL) {11438(void)mg_fclose(&file.access);11439mg_send_http_error(conn,11440500,11441"Error: Can not create file\nfopen(%s): %s",11442path,11443strerror(ERRNO));11444return;11445}1144611447fclose_on_exec(&file.access, conn);11448range = mg_get_header(conn, "Content-Range");11449r1 = r2 = 0;11450if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {11451conn->status_code = 206; /* Partial content */11452fseeko(file.access.fp, r1, SEEK_SET);11453}1145411455if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {11456/* forward_body_data failed.11457* The error code has already been sent to the client,11458* and conn->status_code is already set. */11459(void)mg_fclose(&file.access);11460return;11461}1146211463if (mg_fclose(&file.access) != 0) {11464/* fclose failed. This might have different reasons, but a likely11465* one is "no space on disk", http 507. */11466conn->status_code = 507;11467}1146811469gmt_time_string(date, sizeof(date), &curtime);11470mg_printf(conn,11471"HTTP/1.1 %d %s\r\n",11472conn->status_code,11473mg_get_response_code_text(NULL, conn->status_code));11474send_no_cache_header(conn);11475send_additional_header(conn);11476mg_printf(conn,11477"Date: %s\r\n"11478"Content-Length: 0\r\n"11479"Connection: %s\r\n\r\n",11480date,11481suggest_connection_header(conn));11482}114831148411485static void11486delete_file(struct mg_connection *conn, const char *path)11487{11488struct de de;11489memset(&de.file, 0, sizeof(de.file));11490if (!mg_stat(conn, path, &de.file)) {11491/* mg_stat returns 0 if the file does not exist */11492mg_send_http_error(conn,11493404,11494"Error: Cannot delete file\nFile %s not found",11495path);11496return;11497}1149811499#if 0 /* Ignore if a file in memory is inside a folder */11500if (de.access.membuf != NULL) {11501/* the file is cached in memory */11502mg_send_http_error(11503conn,11504405,11505"Error: Delete not possible\nDeleting %s is not supported",11506path);11507return;11508}11509#endif1151011511if (de.file.is_directory) {11512if (remove_directory(conn, path)) {11513/* Delete is successful: Return 204 without content. */11514mg_send_http_error(conn, 204, "%s", "");11515} else {11516/* Delete is not successful: Return 500 (Server error). */11517mg_send_http_error(conn, 500, "Error: Could not delete %s", path);11518}11519return;11520}1152111522/* This is an existing file (not a directory).11523* Check if write permission is granted. */11524if (access(path, W_OK) != 0) {11525/* File is read only */11526mg_send_http_error(11527conn,11528403,11529"Error: Delete not possible\nDeleting %s is not allowed",11530path);11531return;11532}1153311534/* Try to delete it. */11535if (mg_remove(conn, path) == 0) {11536/* Delete was successful: Return 204 without content. */11537mg_send_http_error(conn, 204, "%s", "");11538} else {11539/* Delete not successful (file locked). */11540mg_send_http_error(conn,11541423,11542"Error: Cannot delete file\nremove(%s): %s",11543path,11544strerror(ERRNO));11545}11546}11547#endif /* !NO_FILES */115481154911550static void11551send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);115521155311554static void11555do_ssi_include(struct mg_connection *conn,11556const char *ssi,11557char *tag,11558int include_level)11559{11560char file_name[MG_BUF_LEN], path[512], *p;11561struct mg_file file = STRUCT_FILE_INITIALIZER;11562size_t len;11563int truncated = 0;1156411565if (conn == NULL) {11566return;11567}1156811569/* sscanf() is safe here, since send_ssi_file() also uses buffer11570* of size MG_BUF_LEN to get the tag. So strlen(tag) is11571* always < MG_BUF_LEN. */11572if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {11573/* File name is relative to the webserver root */11574file_name[511] = 0;11575(void)mg_snprintf(conn,11576&truncated,11577path,11578sizeof(path),11579"%s/%s",11580conn->dom_ctx->config[DOCUMENT_ROOT],11581file_name);1158211583} else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {11584/* File name is relative to the webserver working directory11585* or it is absolute system path */11586file_name[511] = 0;11587(void)11588mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);1158911590} else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)11591|| (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {11592/* File name is relative to the currect document */11593file_name[511] = 0;11594(void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);1159511596if (!truncated) {11597if ((p = strrchr(path, '/')) != NULL) {11598p[1] = '\0';11599}11600len = strlen(path);11601(void)mg_snprintf(conn,11602&truncated,11603path + len,11604sizeof(path) - len,11605"%s",11606file_name);11607}1160811609} else {11610mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);11611return;11612}1161311614if (truncated) {11615mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);11616return;11617}1161811619if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {11620mg_cry_internal(conn,11621"Cannot open SSI #include: [%s]: fopen(%s): %s",11622tag,11623path,11624strerror(ERRNO));11625} else {11626fclose_on_exec(&file.access, conn);11627if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],11628strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),11629path)11630> 0) {11631send_ssi_file(conn, path, &file, include_level + 1);11632} else {11633send_file_data(conn, &file, 0, INT64_MAX);11634}11635(void)mg_fclose(&file.access); /* Ignore errors for readonly files */11636}11637}116381163911640#if !defined(NO_POPEN)11641static void11642do_ssi_exec(struct mg_connection *conn, char *tag)11643{11644char cmd[1024] = "";11645struct mg_file file = STRUCT_FILE_INITIALIZER;1164611647if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {11648mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);11649} else {11650cmd[1023] = 0;11651if ((file.access.fp = popen(cmd, "r")) == NULL) {11652mg_cry_internal(conn,11653"Cannot SSI #exec: [%s]: %s",11654cmd,11655strerror(ERRNO));11656} else {11657send_file_data(conn, &file, 0, INT64_MAX);11658pclose(file.access.fp);11659}11660}11661}11662#endif /* !NO_POPEN */116631166411665static int11666mg_fgetc(struct mg_file *filep, int offset)11667{11668(void)offset; /* unused in case MG_USE_OPEN_FILE is set */1166911670if (filep == NULL) {11671return EOF;11672}11673#if defined(MG_USE_OPEN_FILE)11674if ((filep->access.membuf != NULL) && (offset >= 0)11675&& (((unsigned int)(offset)) < filep->stat.size)) {11676return ((const unsigned char *)filep->access.membuf)[offset];11677} else /* else block below */11678#endif11679if (filep->access.fp != NULL) {11680return fgetc(filep->access.fp);11681} else {11682return EOF;11683}11684}116851168611687static void11688send_ssi_file(struct mg_connection *conn,11689const char *path,11690struct mg_file *filep,11691int include_level)11692{11693char buf[MG_BUF_LEN];11694int ch, offset, len, in_tag, in_ssi_tag;1169511696if (include_level > 10) {11697mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);11698return;11699}1170011701in_tag = in_ssi_tag = len = offset = 0;1170211703/* Read file, byte by byte, and look for SSI include tags */11704while ((ch = mg_fgetc(filep, offset++)) != EOF) {1170511706if (in_tag) {11707/* We are in a tag, either SSI tag or html tag */1170811709if (ch == '>') {11710/* Tag is closing */11711buf[len++] = '>';1171211713if (in_ssi_tag) {11714/* Handle SSI tag */11715buf[len] = 0;1171611717if ((len > 12) && !memcmp(buf + 5, "include", 7)) {11718do_ssi_include(conn, path, buf + 12, include_level + 1);11719#if !defined(NO_POPEN)11720} else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {11721do_ssi_exec(conn, buf + 9);11722#endif /* !NO_POPEN */11723} else {11724mg_cry_internal(conn,11725"%s: unknown SSI "11726"command: \"%s\"",11727path,11728buf);11729}11730len = 0;11731in_ssi_tag = in_tag = 0;1173211733} else {11734/* Not an SSI tag */11735/* Flush buffer */11736(void)mg_write(conn, buf, (size_t)len);11737len = 0;11738in_tag = 0;11739}1174011741} else {11742/* Tag is still open */11743buf[len++] = (char)(ch & 0xff);1174411745if ((len == 5) && !memcmp(buf, "<!--#", 5)) {11746/* All SSI tags start with <!--# */11747in_ssi_tag = 1;11748}1174911750if ((len + 2) > (int)sizeof(buf)) {11751/* Tag to long for buffer */11752mg_cry_internal(conn, "%s: tag is too large", path);11753return;11754}11755}1175611757} else {1175811759/* We are not in a tag yet. */11760if (ch == '<') {11761/* Tag is opening */11762in_tag = 1;1176311764if (len > 0) {11765/* Flush current buffer.11766* Buffer is filled with "len" bytes. */11767(void)mg_write(conn, buf, (size_t)len);11768}11769/* Store the < */11770len = 1;11771buf[0] = '<';1177211773} else {11774/* No Tag */11775/* Add data to buffer */11776buf[len++] = (char)(ch & 0xff);11777/* Flush if buffer is full */11778if (len == (int)sizeof(buf)) {11779mg_write(conn, buf, (size_t)len);11780len = 0;11781}11782}11783}11784}1178511786/* Send the rest of buffered data */11787if (len > 0) {11788mg_write(conn, buf, (size_t)len);11789}11790}117911179211793static void11794handle_ssi_file_request(struct mg_connection *conn,11795const char *path,11796struct mg_file *filep)11797{11798char date[64];11799time_t curtime = time(NULL);11800const char *cors1, *cors2, *cors3;1180111802if ((conn == NULL) || (path == NULL) || (filep == NULL)) {11803return;11804}1180511806if (mg_get_header(conn, "Origin")) {11807/* Cross-origin resource sharing (CORS). */11808cors1 = "Access-Control-Allow-Origin: ";11809cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];11810cors3 = "\r\n";11811} else {11812cors1 = cors2 = cors3 = "";11813}1181411815if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {11816/* File exists (precondition for calling this function),11817* but can not be opened by the server. */11818mg_send_http_error(conn,11819500,11820"Error: Cannot read file\nfopen(%s): %s",11821path,11822strerror(ERRNO));11823} else {11824conn->must_close = 1;11825gmt_time_string(date, sizeof(date), &curtime);11826fclose_on_exec(&filep->access, conn);11827mg_printf(conn, "HTTP/1.1 200 OK\r\n");11828send_no_cache_header(conn);11829send_additional_header(conn);11830mg_printf(conn,11831"%s%s%s"11832"Date: %s\r\n"11833"Content-Type: text/html\r\n"11834"Connection: %s\r\n\r\n",11835cors1,11836cors2,11837cors3,11838date,11839suggest_connection_header(conn));11840send_ssi_file(conn, path, filep, 0);11841(void)mg_fclose(&filep->access); /* Ignore errors for readonly files */11842}11843}118441184511846#if !defined(NO_FILES)11847static void11848send_options(struct mg_connection *conn)11849{11850char date[64];11851time_t curtime = time(NULL);1185211853if (!conn) {11854return;11855}1185611857conn->status_code = 200;11858conn->must_close = 1;11859gmt_time_string(date, sizeof(date), &curtime);1186011861/* We do not set a "Cache-Control" header here, but leave the default.11862* Since browsers do not send an OPTIONS request, we can not test the11863* effect anyway. */11864mg_printf(conn,11865"HTTP/1.1 200 OK\r\n"11866"Date: %s\r\n"11867"Connection: %s\r\n"11868"Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "11869"PROPFIND, MKCOL\r\n"11870"DAV: 1\r\n",11871date,11872suggest_connection_header(conn));11873send_additional_header(conn);11874mg_printf(conn, "\r\n");11875}118761187711878/* Writes PROPFIND properties for a collection element */11879static void11880print_props(struct mg_connection *conn,11881const char *uri,11882struct mg_file_stat *filep)11883{11884char mtime[64];1188511886if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {11887return;11888}1188911890gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);11891mg_printf(conn,11892"<d:response>"11893"<d:href>%s</d:href>"11894"<d:propstat>"11895"<d:prop>"11896"<d:resourcetype>%s</d:resourcetype>"11897"<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"11898"<d:getlastmodified>%s</d:getlastmodified>"11899"</d:prop>"11900"<d:status>HTTP/1.1 200 OK</d:status>"11901"</d:propstat>"11902"</d:response>\n",11903uri,11904filep->is_directory ? "<d:collection/>" : "",11905filep->size,11906mtime);11907}119081190911910static int11911print_dav_dir_entry(struct de *de, void *data)11912{11913char href[PATH_MAX];11914int truncated;1191511916struct mg_connection *conn = (struct mg_connection *)data;11917if (!de || !conn) {11918return -1;11919}11920mg_snprintf(conn,11921&truncated,11922href,11923sizeof(href),11924"%s%s",11925conn->request_info.local_uri,11926de->file_name);1192711928if (!truncated) {11929size_t href_encoded_size;11930char *href_encoded;1193111932href_encoded_size = PATH_MAX * 3; /* worst case */11933href_encoded = (char *)mg_malloc(href_encoded_size);11934if (href_encoded == NULL) {11935return -1;11936}11937mg_url_encode(href, href_encoded, href_encoded_size);11938print_props(conn, href_encoded, &de->file);11939mg_free(href_encoded);11940}1194111942return 0;11943}119441194511946static void11947handle_propfind(struct mg_connection *conn,11948const char *path,11949struct mg_file_stat *filep)11950{11951const char *depth = mg_get_header(conn, "Depth");11952char date[64];11953time_t curtime = time(NULL);1195411955gmt_time_string(date, sizeof(date), &curtime);1195611957if (!conn || !path || !filep || !conn->dom_ctx) {11958return;11959}1196011961conn->must_close = 1;11962conn->status_code = 207;11963mg_printf(conn,11964"HTTP/1.1 207 Multi-Status\r\n"11965"Date: %s\r\n",11966date);11967send_static_cache_header(conn);11968send_additional_header(conn);11969mg_printf(conn,11970"Connection: %s\r\n"11971"Content-Type: text/xml; charset=utf-8\r\n\r\n",11972suggest_connection_header(conn));1197311974mg_printf(conn,11975"<?xml version=\"1.0\" encoding=\"utf-8\"?>"11976"<d:multistatus xmlns:d='DAV:'>\n");1197711978/* Print properties for the requested resource itself */11979print_props(conn, conn->request_info.local_uri, filep);1198011981/* If it is a directory, print directory entries too if Depth is not 011982*/11983if (filep->is_directory11984&& !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],11985"yes")11986&& ((depth == NULL) || (strcmp(depth, "0") != 0))) {11987scan_directory(conn, path, conn, &print_dav_dir_entry);11988}1198911990mg_printf(conn, "%s\n", "</d:multistatus>");11991}11992#endif1199311994void11995mg_lock_connection(struct mg_connection *conn)11996{11997if (conn) {11998(void)pthread_mutex_lock(&conn->mutex);11999}12000}1200112002void12003mg_unlock_connection(struct mg_connection *conn)12004{12005if (conn) {12006(void)pthread_mutex_unlock(&conn->mutex);12007}12008}1200912010void12011mg_lock_context(struct mg_context *ctx)12012{12013if (ctx) {12014(void)pthread_mutex_lock(&ctx->nonce_mutex);12015}12016}1201712018void12019mg_unlock_context(struct mg_context *ctx)12020{12021if (ctx) {12022(void)pthread_mutex_unlock(&ctx->nonce_mutex);12023}12024}120251202612027#if defined(USE_LUA)12028#include "mod_lua.inl"12029#endif /* USE_LUA */1203012031#if defined(USE_DUKTAPE)12032#include "mod_duktape.inl"12033#endif /* USE_DUKTAPE */1203412035#if defined(USE_WEBSOCKET)1203612037#if !defined(NO_SSL_DL)12038#define SHA_API static12039#include "sha1.inl"12040#endif1204112042static int12043send_websocket_handshake(struct mg_connection *conn, const char *websock_key)12044{12045static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";12046char buf[100], sha[20], b64_sha[sizeof(sha) * 2];12047SHA_CTX sha_ctx;12048int truncated;1204912050/* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */12051mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);12052if (truncated) {12053conn->must_close = 1;12054return 0;12055}1205612057DEBUG_TRACE("%s", "Send websocket handshake");1205812059SHA1_Init(&sha_ctx);12060SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));12061SHA1_Final((unsigned char *)sha, &sha_ctx);12062base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);12063mg_printf(conn,12064"HTTP/1.1 101 Switching Protocols\r\n"12065"Upgrade: websocket\r\n"12066"Connection: Upgrade\r\n"12067"Sec-WebSocket-Accept: %s\r\n",12068b64_sha);12069if (conn->request_info.acceptedWebSocketSubprotocol) {12070mg_printf(conn,12071"Sec-WebSocket-Protocol: %s\r\n\r\n",12072conn->request_info.acceptedWebSocketSubprotocol);12073} else {12074mg_printf(conn, "%s", "\r\n");12075}1207612077return 1;12078}120791208012081#if !defined(MG_MAX_UNANSWERED_PING)12082/* Configuration of the maximum number of websocket PINGs that might12083* stay unanswered before the connection is considered broken.12084* Note: The name of this define may still change (until it is12085* defined as a compile parameter in a documentation).12086*/12087#define MG_MAX_UNANSWERED_PING (5)12088#endif120891209012091static void12092read_websocket(struct mg_connection *conn,12093mg_websocket_data_handler ws_data_handler,12094void *callback_data)12095{12096/* Pointer to the beginning of the portion of the incoming websocket12097* message queue.12098* The original websocket upgrade request is never removed, so the queue12099* begins after it. */12100unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;12101int n, error, exit_by_callback;12102int ret;1210312104/* body_len is the length of the entire queue in bytes12105* len is the length of the current message12106* data_len is the length of the current message's data payload12107* header_len is the length of the current message's header */12108size_t i, len, mask_len = 0, header_len, body_len;12109uint64_t data_len = 0;1211012111/* "The masking key is a 32-bit value chosen at random by the client."12112* http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-512113*/12114unsigned char mask[4];1211512116/* data points to the place where the message is stored when passed to12117* the websocket_data callback. This is either mem on the stack, or a12118* dynamically allocated buffer if it is too large. */12119unsigned char mem[4096];12120unsigned char mop; /* mask flag and opcode */121211212212123/* Variables used for connection monitoring */12124double timeout = -1.0;12125int enable_ping_pong = 0;12126int ping_count = 0;1212712128if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {12129enable_ping_pong =12130!mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],12131"yes");12132}1213312134if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {12135timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;12136}12137if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {12138timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;12139}1214012141/* Enter data processing loop */12142DEBUG_TRACE("Websocket connection %s:%u start data processing loop",12143conn->request_info.remote_addr,12144conn->request_info.remote_port);12145conn->in_websocket_handling = 1;12146mg_set_thread_name("wsock");1214712148/* Loop continuously, reading messages from the socket, invoking the12149* callback, and waiting repeatedly until an error occurs. */12150while (!conn->phys_ctx->stop_flag && !conn->must_close) {12151header_len = 0;12152DEBUG_ASSERT(conn->data_len >= conn->request_len);12153if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {12154len = buf[1] & 127;12155mask_len = (buf[1] & 128) ? 4 : 0;12156if ((len < 126) && (body_len >= mask_len)) {12157/* inline 7-bit length field */12158data_len = len;12159header_len = 2 + mask_len;12160} else if ((len == 126) && (body_len >= (4 + mask_len))) {12161/* 16-bit length field */12162header_len = 4 + mask_len;12163data_len = ((((size_t)buf[2]) << 8) + buf[3]);12164} else if (body_len >= (10 + mask_len)) {12165/* 64-bit length field */12166uint32_t l1, l2;12167memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */12168memcpy(&l2, &buf[6], 4);12169header_len = 10 + mask_len;12170data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);1217112172if (data_len > (uint64_t)0x7FFF0000ul) {12173/* no can do */12174mg_cry_internal(12175conn,12176"%s",12177"websocket out of memory; closing connection");12178break;12179}12180}12181}1218212183if ((header_len > 0) && (body_len >= header_len)) {12184/* Allocate space to hold websocket payload */12185unsigned char *data = mem;1218612187if ((size_t)data_len > (size_t)sizeof(mem)) {12188data = (unsigned char *)mg_malloc_ctx((size_t)data_len,12189conn->phys_ctx);12190if (data == NULL) {12191/* Allocation failed, exit the loop and then close the12192* connection */12193mg_cry_internal(12194conn,12195"%s",12196"websocket out of memory; closing connection");12197break;12198}12199}1220012201/* Copy the mask before we shift the queue and destroy it */12202if (mask_len > 0) {12203memcpy(mask, buf + header_len - mask_len, sizeof(mask));12204} else {12205memset(mask, 0, sizeof(mask));12206}1220712208/* Read frame payload from the first message in the queue into12209* data and advance the queue by moving the memory in place. */12210DEBUG_ASSERT(body_len >= header_len);12211if (data_len + (uint64_t)header_len > (uint64_t)body_len) {12212mop = buf[0]; /* current mask and opcode */12213/* Overflow case */12214len = body_len - header_len;12215memcpy(data, buf + header_len, len);12216error = 0;12217while ((uint64_t)len < data_len) {12218n = pull_inner(NULL,12219conn,12220(char *)(data + len),12221(int)(data_len - len),12222timeout);12223if (n <= -2) {12224error = 1;12225break;12226} else if (n > 0) {12227len += (size_t)n;12228} else {12229/* Timeout: should retry */12230/* TODO: retry condition */12231}12232}12233if (error) {12234mg_cry_internal(12235conn,12236"%s",12237"Websocket pull failed; closing connection");12238if (data != mem) {12239mg_free(data);12240}12241break;12242}1224312244conn->data_len = conn->request_len;1224512246} else {1224712248mop = buf[0]; /* current mask and opcode, overwritten by12249* memmove() */1225012251/* Length of the message being read at the front of the12252* queue. Cast to 31 bit is OK, since we limited12253* data_len before. */12254len = (size_t)data_len + header_len;1225512256/* Copy the data payload into the data pointer for the12257* callback. Cast to 31 bit is OK, since we12258* limited data_len */12259memcpy(data, buf + header_len, (size_t)data_len);1226012261/* Move the queue forward len bytes */12262memmove(buf, buf + len, body_len - len);1226312264/* Mark the queue as advanced */12265conn->data_len -= (int)len;12266}1226712268/* Apply mask if necessary */12269if (mask_len > 0) {12270for (i = 0; i < (size_t)data_len; i++) {12271data[i] ^= mask[i & 3];12272}12273}1227412275exit_by_callback = 0;12276if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {12277/* filter PONG messages */12278DEBUG_TRACE("PONG from %s:%u",12279conn->request_info.remote_addr,12280conn->request_info.remote_port);12281/* No unanwered PINGs left */12282ping_count = 0;12283} else if (enable_ping_pong12284&& ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {12285/* reply PING messages */12286DEBUG_TRACE("Reply PING from %s:%u",12287conn->request_info.remote_addr,12288conn->request_info.remote_port);12289ret = mg_websocket_write(conn,12290MG_WEBSOCKET_OPCODE_PONG,12291(char *)data,12292(size_t)data_len);12293if (ret <= 0) {12294/* Error: send failed */12295DEBUG_TRACE("Reply PONG failed (%i)", ret);12296break;12297}122981229912300} else {12301/* Exit the loop if callback signals to exit (server side),12302* or "connection close" opcode received (client side). */12303if ((ws_data_handler != NULL)12304&& !ws_data_handler(conn,12305mop,12306(char *)data,12307(size_t)data_len,12308callback_data)) {12309exit_by_callback = 1;12310}12311}1231212313/* It a buffer has been allocated, free it again */12314if (data != mem) {12315mg_free(data);12316}1231712318if (exit_by_callback) {12319DEBUG_TRACE("Callback requests to close connection from %s:%u",12320conn->request_info.remote_addr,12321conn->request_info.remote_port);12322break;12323}12324if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {12325/* Opcode == 8, connection close */12326DEBUG_TRACE("Message requests to close connection from %s:%u",12327conn->request_info.remote_addr,12328conn->request_info.remote_port);12329break;12330}1233112332/* Not breaking the loop, process next websocket frame. */12333} else {12334/* Read from the socket into the next available location in the12335* message queue. */12336n = pull_inner(NULL,12337conn,12338conn->buf + conn->data_len,12339conn->buf_size - conn->data_len,12340timeout);12341if (n <= -2) {12342/* Error, no bytes read */12343DEBUG_TRACE("PULL from %s:%u failed",12344conn->request_info.remote_addr,12345conn->request_info.remote_port);12346break;12347}12348if (n > 0) {12349conn->data_len += n;12350/* Reset open PING count */12351ping_count = 0;12352} else {12353if (!conn->phys_ctx->stop_flag && !conn->must_close) {12354if (ping_count > MG_MAX_UNANSWERED_PING) {12355/* Stop sending PING */12356DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "12357"- closing connection",12358ping_count,12359conn->request_info.remote_addr,12360conn->request_info.remote_port);12361break;12362}12363if (enable_ping_pong) {12364/* Send Websocket PING message */12365DEBUG_TRACE("PING to %s:%u",12366conn->request_info.remote_addr,12367conn->request_info.remote_port);12368ret = mg_websocket_write(conn,12369MG_WEBSOCKET_OPCODE_PING,12370NULL,123710);1237212373if (ret <= 0) {12374/* Error: send failed */12375DEBUG_TRACE("Send PING failed (%i)", ret);12376break;12377}12378ping_count++;12379}12380}12381/* Timeout: should retry */12382/* TODO: get timeout def */12383}12384}12385}1238612387/* Leave data processing loop */12388mg_set_thread_name("worker");12389conn->in_websocket_handling = 0;12390DEBUG_TRACE("Websocket connection %s:%u left data processing loop",12391conn->request_info.remote_addr,12392conn->request_info.remote_port);12393}123941239512396static int12397mg_websocket_write_exec(struct mg_connection *conn,12398int opcode,12399const char *data,12400size_t dataLen,12401uint32_t masking_key)12402{12403unsigned char header[14];12404size_t headerLen;12405int retval;1240612407#if defined(GCC_DIAGNOSTIC)12408/* Disable spurious conversion warning for GCC */12409#pragma GCC diagnostic push12410#pragma GCC diagnostic ignored "-Wconversion"12411#endif1241212413header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);1241412415#if defined(GCC_DIAGNOSTIC)12416#pragma GCC diagnostic pop12417#endif1241812419/* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */12420if (dataLen < 126) {12421/* inline 7-bit length field */12422header[1] = (unsigned char)dataLen;12423headerLen = 2;12424} else if (dataLen <= 0xFFFF) {12425/* 16-bit length field */12426uint16_t len = htons((uint16_t)dataLen);12427header[1] = 126;12428memcpy(header + 2, &len, 2);12429headerLen = 4;12430} else {12431/* 64-bit length field */12432uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));12433uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));12434header[1] = 127;12435memcpy(header + 2, &len1, 4);12436memcpy(header + 6, &len2, 4);12437headerLen = 10;12438}1243912440if (masking_key) {12441/* add mask */12442header[1] |= 0x80;12443memcpy(header + headerLen, &masking_key, 4);12444headerLen += 4;12445}1244612447/* Note that POSIX/Winsock's send() is threadsafe12448* http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid12449* but mongoose's mg_printf/mg_write is not (because of the loop in12450* push(), although that is only a problem if the packet is large or12451* outgoing buffer is full). */1245212453/* TODO: Check if this lock should be moved to user land.12454* Currently the server sets this lock for websockets, but12455* not for any other connection. It must be set for every12456* conn read/written by more than one thread, no matter if12457* it is a websocket or regular connection. */12458(void)mg_lock_connection(conn);1245912460retval = mg_write(conn, header, headerLen);12461if (retval != (int)headerLen) {12462/* Did not send complete header */12463retval = -1;12464} else {12465if (dataLen > 0) {12466retval = mg_write(conn, data, dataLen);12467}12468/* if dataLen == 0, the header length (2) is returned */12469}1247012471/* TODO: Remove this unlock as well, when lock is removed. */12472mg_unlock_connection(conn);1247312474return retval;12475}1247612477int12478mg_websocket_write(struct mg_connection *conn,12479int opcode,12480const char *data,12481size_t dataLen)12482{12483return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);12484}124851248612487static void12488mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)12489{12490size_t i = 0;1249112492i = 0;12493if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {12494/* Convert in 32 bit words, if data is 4 byte aligned */12495while (i < (in_len - 3)) {12496*(uint32_t *)(void *)(out + i) =12497*(uint32_t *)(void *)(in + i) ^ masking_key;12498i += 4;12499}12500}12501if (i != in_len) {12502/* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/12503while (i < in_len) {12504*(uint8_t *)(void *)(out + i) =12505*(uint8_t *)(void *)(in + i)12506^ *(((uint8_t *)&masking_key) + (i % 4));12507i++;12508}12509}12510}125111251212513int12514mg_websocket_client_write(struct mg_connection *conn,12515int opcode,12516const char *data,12517size_t dataLen)12518{12519int retval = -1;12520char *masked_data =12521(char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);12522uint32_t masking_key = 0;1252312524if (masked_data == NULL) {12525/* Return -1 in an error case */12526mg_cry_internal(conn,12527"%s",12528"Cannot allocate buffer for masked websocket response: "12529"Out of memory");12530return -1;12531}1253212533do {12534/* Get a masking key - but not 0 */12535masking_key = (uint32_t)get_random();12536} while (masking_key == 0);1253712538mask_data(data, dataLen, masking_key, masked_data);1253912540retval = mg_websocket_write_exec(12541conn, opcode, masked_data, dataLen, masking_key);12542mg_free(masked_data);1254312544return retval;12545}125461254712548static void12549handle_websocket_request(struct mg_connection *conn,12550const char *path,12551int is_callback_resource,12552struct mg_websocket_subprotocols *subprotocols,12553mg_websocket_connect_handler ws_connect_handler,12554mg_websocket_ready_handler ws_ready_handler,12555mg_websocket_data_handler ws_data_handler,12556mg_websocket_close_handler ws_close_handler,12557void *cbData)12558{12559const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");12560const char *version = mg_get_header(conn, "Sec-WebSocket-Version");12561ptrdiff_t lua_websock = 0;1256212563#if !defined(USE_LUA)12564(void)path;12565#endif1256612567/* Step 1: Check websocket protocol version. */12568/* Step 1.1: Check Sec-WebSocket-Key. */12569if (!websock_key) {12570/* The RFC standard version (https://tools.ietf.org/html/rfc6455)12571* requires a Sec-WebSocket-Key header.12572*/12573/* It could be the hixie draft version12574* (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).12575*/12576const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");12577const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");12578char key3[8];1257912580if ((key1 != NULL) && (key2 != NULL)) {12581/* This version uses 8 byte body data in a GET request */12582conn->content_len = 8;12583if (8 == mg_read(conn, key3, 8)) {12584/* This is the hixie version */12585mg_send_http_error(conn,12586426,12587"%s",12588"Protocol upgrade to RFC 6455 required");12589return;12590}12591}12592/* This is an unknown version */12593mg_send_http_error(conn, 400, "%s", "Malformed websocket request");12594return;12595}1259612597/* Step 1.2: Check websocket protocol version. */12598/* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */12599if ((version == NULL) || (strcmp(version, "13") != 0)) {12600/* Reject wrong versions */12601mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");12602return;12603}1260412605/* Step 1.3: Could check for "Host", but we do not really nead this12606* value for anything, so just ignore it. */1260712608/* Step 2: If a callback is responsible, call it. */12609if (is_callback_resource) {12610/* Step 2.1 check and select subprotocol */12611const char *protocols[64]; // max 64 headers12612int nbSubprotocolHeader = get_req_headers(&conn->request_info,12613"Sec-WebSocket-Protocol",12614protocols,1261564);12616if ((nbSubprotocolHeader > 0) && subprotocols) {12617int cnt = 0;12618int idx;12619unsigned long len;12620const char *sep, *curSubProtocol,12621*acceptedWebSocketSubprotocol = NULL;126221262312624/* look for matching subprotocol */12625do {12626const char *protocol = protocols[cnt];1262712628do {12629sep = strchr(protocol, ',');12630curSubProtocol = protocol;12631len = sep ? (unsigned long)(sep - protocol)12632: (unsigned long)strlen(protocol);12633while (sep && isspace(*++sep))12634; // ignore leading whitespaces12635protocol = sep;126361263712638for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {12639if ((strlen(subprotocols->subprotocols[idx]) == len)12640&& (strncmp(curSubProtocol,12641subprotocols->subprotocols[idx],12642len)12643== 0)) {12644acceptedWebSocketSubprotocol =12645subprotocols->subprotocols[idx];12646break;12647}12648}12649} while (sep && !acceptedWebSocketSubprotocol);12650} while (++cnt < nbSubprotocolHeader12651&& !acceptedWebSocketSubprotocol);1265212653conn->request_info.acceptedWebSocketSubprotocol =12654acceptedWebSocketSubprotocol;1265512656} else if (nbSubprotocolHeader > 0) {12657/* keep legacy behavior */12658const char *protocol = protocols[0];1265912660/* The protocol is a comma separated list of names. */12661/* The server must only return one value from this list. */12662/* First check if it is a list or just a single value. */12663const char *sep = strrchr(protocol, ',');12664if (sep == NULL) {12665/* Just a single protocol -> accept it. */12666conn->request_info.acceptedWebSocketSubprotocol = protocol;12667} else {12668/* Multiple protocols -> accept the last one. */12669/* This is just a quick fix if the client offers multiple12670* protocols. The handler should have a list of accepted12671* protocols on his own12672* and use it to select one protocol among those the client12673* has12674* offered.12675*/12676while (isspace(*++sep)) {12677; /* ignore leading whitespaces */12678}12679conn->request_info.acceptedWebSocketSubprotocol = sep;12680}12681}1268212683if ((ws_connect_handler != NULL)12684&& (ws_connect_handler(conn, cbData) != 0)) {12685/* C callback has returned non-zero, do not proceed with12686* handshake.12687*/12688/* Note that C callbacks are no longer called when Lua is12689* responsible, so C can no longer filter callbacks for Lua. */12690return;12691}12692}1269312694#if defined(USE_LUA)12695/* Step 3: No callback. Check if Lua is responsible. */12696else {12697/* Step 3.1: Check if Lua is responsible. */12698if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {12699lua_websock = match_prefix(12700conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],12701strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),12702path);12703}1270412705if (lua_websock) {12706/* Step 3.2: Lua is responsible: call it. */12707conn->lua_websocket_state = lua_websocket_new(path, conn);12708if (!conn->lua_websocket_state) {12709/* Lua rejected the new client */12710return;12711}12712}12713}12714#endif1271512716/* Step 4: Check if there is a responsible websocket handler. */12717if (!is_callback_resource && !lua_websock) {12718/* There is no callback, and Lua is not responsible either. */12719/* Reply with a 404 Not Found. We are still at a standard12720* HTTP request here, before the websocket handshake, so12721* we can still send standard HTTP error replies. */12722mg_send_http_error(conn, 404, "%s", "Not found");12723return;12724}1272512726/* Step 5: The websocket connection has been accepted */12727if (!send_websocket_handshake(conn, websock_key)) {12728mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");12729return;12730}1273112732/* Step 6: Call the ready handler */12733if (is_callback_resource) {12734if (ws_ready_handler != NULL) {12735ws_ready_handler(conn, cbData);12736}12737#if defined(USE_LUA)12738} else if (lua_websock) {12739if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {12740/* the ready handler returned false */12741return;12742}12743#endif12744}1274512746/* Step 7: Enter the read loop */12747if (is_callback_resource) {12748read_websocket(conn, ws_data_handler, cbData);12749#if defined(USE_LUA)12750} else if (lua_websock) {12751read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);12752#endif12753}1275412755/* Step 8: Call the close handler */12756if (ws_close_handler) {12757ws_close_handler(conn, cbData);12758}12759}127601276112762static int12763is_websocket_protocol(const struct mg_connection *conn)12764{12765const char *upgrade, *connection;1276612767/* A websocket protocoll has the following HTTP headers:12768*12769* Connection: Upgrade12770* Upgrade: Websocket12771*/1277212773upgrade = mg_get_header(conn, "Upgrade");12774if (upgrade == NULL) {12775return 0; /* fail early, don't waste time checking other header12776* fields12777*/12778}12779if (!mg_strcasestr(upgrade, "websocket")) {12780return 0;12781}1278212783connection = mg_get_header(conn, "Connection");12784if (connection == NULL) {12785return 0;12786}12787if (!mg_strcasestr(connection, "upgrade")) {12788return 0;12789}1279012791/* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and12792* "Sec-WebSocket-Version" are also required.12793* Don't check them here, since even an unsupported websocket protocol12794* request still IS a websocket request (in contrast to a standard HTTP12795* request). It will fail later in handle_websocket_request.12796*/1279712798return 1;12799}12800#endif /* !USE_WEBSOCKET */128011280212803static int12804isbyte(int n)12805{12806return (n >= 0) && (n <= 255);12807}128081280912810static int12811parse_net(const char *spec, uint32_t *net, uint32_t *mask)12812{12813int n, a, b, c, d, slash = 32, len = 0;1281412815if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)12816|| (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))12817&& isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)12818&& (slash < 33)) {12819len = n;12820*net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)12821| (uint32_t)d;12822*mask = slash ? (0xffffffffU << (32 - slash)) : 0;12823}1282412825return len;12826}128271282812829static int12830set_throttle(const char *spec, uint32_t remote_ip, const char *uri)12831{12832int throttle = 0;12833struct vec vec, val;12834uint32_t net, mask;12835char mult;12836double v;1283712838while ((spec = next_option(spec, &vec, &val)) != NULL) {12839mult = ',';12840if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)12841|| (v < 0)12842|| ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')12843&& (mult != ','))) {12844continue;12845}12846v *= (lowercase(&mult) == 'k')12847? 102412848: ((lowercase(&mult) == 'm') ? 1048576 : 1);12849if (vec.len == 1 && vec.ptr[0] == '*') {12850throttle = (int)v;12851} else if (parse_net(vec.ptr, &net, &mask) > 0) {12852if ((remote_ip & mask) == net) {12853throttle = (int)v;12854}12855} else if (match_prefix(vec.ptr, vec.len, uri) > 0) {12856throttle = (int)v;12857}12858}1285912860return throttle;12861}128621286312864static uint32_t12865get_remote_ip(const struct mg_connection *conn)12866{12867if (!conn) {12868return 0;12869}12870return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);12871}128721287312874/* The mg_upload function is superseeded by mg_handle_form_request. */12875#include "handle_form.inl"128761287712878#if defined(MG_LEGACY_INTERFACE)12879/* Implement the deprecated mg_upload function by calling the new12880* mg_handle_form_request function. While mg_upload could only handle12881* HTML forms sent as POST request in multipart/form-data format12882* containing only file input elements, mg_handle_form_request can12883* handle all form input elements and all standard request methods. */12884struct mg_upload_user_data {12885struct mg_connection *conn;12886const char *destination_dir;12887int num_uploaded_files;12888};128891289012891/* Helper function for deprecated mg_upload. */12892static int12893mg_upload_field_found(const char *key,12894const char *filename,12895char *path,12896size_t pathlen,12897void *user_data)12898{12899int truncated = 0;12900struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;12901(void)key;1290212903if (!filename) {12904mg_cry_internal(fud->conn, "%s: No filename set", __func__);12905return FORM_FIELD_STORAGE_ABORT;12906}12907mg_snprintf(fud->conn,12908&truncated,12909path,12910pathlen - 1,12911"%s/%s",12912fud->destination_dir,12913filename);12914if (truncated) {12915mg_cry_internal(fud->conn, "%s: File path too long", __func__);12916return FORM_FIELD_STORAGE_ABORT;12917}12918return FORM_FIELD_STORAGE_STORE;12919}129201292112922/* Helper function for deprecated mg_upload. */12923static int12924mg_upload_field_get(const char *key,12925const char *value,12926size_t value_size,12927void *user_data)12928{12929/* Function should never be called */12930(void)key;12931(void)value;12932(void)value_size;12933(void)user_data;1293412935return 0;12936}129371293812939/* Helper function for deprecated mg_upload. */12940static int12941mg_upload_field_stored(const char *path, long long file_size, void *user_data)12942{12943struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;12944(void)file_size;1294512946fud->num_uploaded_files++;12947fud->conn->phys_ctx->callbacks.upload(fud->conn, path);1294812949return 0;12950}129511295212953/* Deprecated function mg_upload - use mg_handle_form_request instead. */12954int12955mg_upload(struct mg_connection *conn, const char *destination_dir)12956{12957struct mg_upload_user_data fud = {conn, destination_dir, 0};12958struct mg_form_data_handler fdh = {mg_upload_field_found,12959mg_upload_field_get,12960mg_upload_field_stored,129610};12962int ret;1296312964fdh.user_data = (void *)&fud;12965ret = mg_handle_form_request(conn, &fdh);1296612967if (ret < 0) {12968mg_cry_internal(conn, "%s: Error while parsing the request", __func__);12969}1297012971return fud.num_uploaded_files;12972}12973#endif129741297512976static int12977get_first_ssl_listener_index(const struct mg_context *ctx)12978{12979unsigned int i;12980int idx = -1;12981if (ctx) {12982for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {12983idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;12984}12985}12986return idx;12987}129881298912990/* Return host (without port) */12991/* Use mg_free to free the result */12992static const char *12993alloc_get_host(struct mg_connection *conn)12994{12995char buf[1025];12996size_t buflen = sizeof(buf);12997const char *host_header = get_header(conn->request_info.http_headers,12998conn->request_info.num_headers,12999"Host");13000char *host;1300113002if (host_header != NULL) {13003char *pos;1300413005/* Create a local copy of the "Host" header, since it might be13006* modified here. */13007mg_strlcpy(buf, host_header, buflen);13008buf[buflen - 1] = '\0';13009host = buf;13010while (isspace(*host)) {13011host++;13012}1301313014/* If the "Host" is an IPv6 address, like [::1], parse until ]13015* is found. */13016if (*host == '[') {13017pos = strchr(host, ']');13018if (!pos) {13019/* Malformed hostname starts with '[', but no ']' found */13020DEBUG_TRACE("%s", "Host name format error '[' without ']'");13021return NULL;13022}13023/* terminate after ']' */13024pos[1] = 0;13025} else {13026/* Otherwise, a ':' separates hostname and port number */13027pos = strchr(host, ':');13028if (pos != NULL) {13029*pos = '\0';13030}13031}1303213033if (conn->ssl) {13034/* This is a HTTPS connection, maybe we have a hostname13035* from SNI (set in ssl_servername_callback). */13036const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];13037if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {13038/* We are not using the default domain */13039if (mg_strcasecmp(host, sslhost)) {13040/* Mismatch between SNI domain and HTTP domain */13041DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",13042sslhost,13043host);13044return NULL;13045}13046}13047DEBUG_TRACE("HTTPS Host: %s", host);1304813049} else {13050struct mg_domain_context *dom = &(conn->phys_ctx->dd);13051while (dom) {13052if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {1305313054/* Found matching domain */13055DEBUG_TRACE("HTTP domain %s found",13056dom->config[AUTHENTICATION_DOMAIN]);1305713058/* TODO: Check if this is a HTTP or HTTPS domain */13059conn->dom_ctx = dom;13060break;13061}13062dom = dom->next;13063}1306413065DEBUG_TRACE("HTTP Host: %s", host);13066}1306713068} else {13069sockaddr_to_string(buf, buflen, &conn->client.lsa);13070host = buf;1307113072DEBUG_TRACE("IP: %s", host);13073}1307413075return mg_strdup_ctx(host, conn->phys_ctx);13076}130771307813079static void13080redirect_to_https_port(struct mg_connection *conn, int ssl_index)13081{13082char target_url[MG_BUF_LEN];13083int truncated = 0;1308413085conn->must_close = 1;1308613087/* Send host, port, uri and (if it exists) ?query_string */13088if (conn->host) {1308913090/* Use "308 Permanent Redirect" */13091int redirect_code = 308;1309213093/* Create target URL */13094mg_snprintf(13095conn,13096&truncated,13097target_url,13098sizeof(target_url),13099"https://%s:%d%s%s%s",1310013101conn->host,13102#if defined(USE_IPV6)13103(conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family13104== AF_INET6)13105? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]13106.lsa.sin6.sin6_port)13107:13108#endif13109(int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]13110.lsa.sin.sin_port),13111conn->request_info.local_uri,13112(conn->request_info.query_string == NULL) ? "" : "?",13113(conn->request_info.query_string == NULL)13114? ""13115: conn->request_info.query_string);1311613117/* Check overflow in location buffer (will not occur if MG_BUF_LEN13118* is used as buffer size) */13119if (truncated) {13120mg_send_http_error(conn, 500, "%s", "Redirect URL too long");13121return;13122}1312313124/* Use redirect helper function */13125mg_send_http_redirect(conn, target_url, redirect_code);13126}13127}131281312913130static void13131handler_info_acquire(struct mg_handler_info *handler_info)13132{13133pthread_mutex_lock(&handler_info->refcount_mutex);13134handler_info->refcount++;13135pthread_mutex_unlock(&handler_info->refcount_mutex);13136}131371313813139static void13140handler_info_release(struct mg_handler_info *handler_info)13141{13142pthread_mutex_lock(&handler_info->refcount_mutex);13143handler_info->refcount--;13144pthread_cond_signal(&handler_info->refcount_cond);13145pthread_mutex_unlock(&handler_info->refcount_mutex);13146}131471314813149static void13150handler_info_wait_unused(struct mg_handler_info *handler_info)13151{13152pthread_mutex_lock(&handler_info->refcount_mutex);13153while (handler_info->refcount) {13154pthread_cond_wait(&handler_info->refcount_cond,13155&handler_info->refcount_mutex);13156}13157pthread_mutex_unlock(&handler_info->refcount_mutex);13158}131591316013161static void13162mg_set_handler_type(struct mg_context *phys_ctx,13163struct mg_domain_context *dom_ctx,13164const char *uri,13165int handler_type,13166int is_delete_request,13167mg_request_handler handler,13168struct mg_websocket_subprotocols *subprotocols,13169mg_websocket_connect_handler connect_handler,13170mg_websocket_ready_handler ready_handler,13171mg_websocket_data_handler data_handler,13172mg_websocket_close_handler close_handler,13173mg_authorization_handler auth_handler,13174void *cbdata)13175{13176struct mg_handler_info *tmp_rh, **lastref;13177size_t urilen = strlen(uri);1317813179if (handler_type == WEBSOCKET_HANDLER) {13180DEBUG_ASSERT(handler == NULL);13181DEBUG_ASSERT(is_delete_request || connect_handler != NULL13182|| ready_handler != NULL || data_handler != NULL13183|| close_handler != NULL);1318413185DEBUG_ASSERT(auth_handler == NULL);13186if (handler != NULL) {13187return;13188}13189if (!is_delete_request && (connect_handler == NULL)13190&& (ready_handler == NULL) && (data_handler == NULL)13191&& (close_handler == NULL)) {13192return;13193}13194if (auth_handler != NULL) {13195return;13196}13197} else if (handler_type == REQUEST_HANDLER) {13198DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL13199&& data_handler == NULL && close_handler == NULL);13200DEBUG_ASSERT(is_delete_request || (handler != NULL));13201DEBUG_ASSERT(auth_handler == NULL);1320213203if ((connect_handler != NULL) || (ready_handler != NULL)13204|| (data_handler != NULL) || (close_handler != NULL)) {13205return;13206}13207if (!is_delete_request && (handler == NULL)) {13208return;13209}13210if (auth_handler != NULL) {13211return;13212}13213} else { /* AUTH_HANDLER */13214DEBUG_ASSERT(handler == NULL);13215DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL13216&& data_handler == NULL && close_handler == NULL);13217DEBUG_ASSERT(auth_handler != NULL);13218if (handler != NULL) {13219return;13220}13221if ((connect_handler != NULL) || (ready_handler != NULL)13222|| (data_handler != NULL) || (close_handler != NULL)) {13223return;13224}13225if (!is_delete_request && (auth_handler == NULL)) {13226return;13227}13228}1322913230if (!phys_ctx || !dom_ctx) {13231return;13232}1323313234mg_lock_context(phys_ctx);1323513236/* first try to find an existing handler */13237lastref = &(dom_ctx->handlers);13238for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {13239if (tmp_rh->handler_type == handler_type) {13240if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {13241if (!is_delete_request) {13242/* update existing handler */13243if (handler_type == REQUEST_HANDLER) {13244/* Wait for end of use before updating */13245handler_info_wait_unused(tmp_rh);1324613247/* Ok, the handler is no more use -> Update it */13248tmp_rh->handler = handler;13249} else if (handler_type == WEBSOCKET_HANDLER) {13250tmp_rh->subprotocols = subprotocols;13251tmp_rh->connect_handler = connect_handler;13252tmp_rh->ready_handler = ready_handler;13253tmp_rh->data_handler = data_handler;13254tmp_rh->close_handler = close_handler;13255} else { /* AUTH_HANDLER */13256tmp_rh->auth_handler = auth_handler;13257}13258tmp_rh->cbdata = cbdata;13259} else {13260/* remove existing handler */13261if (handler_type == REQUEST_HANDLER) {13262/* Wait for end of use before removing */13263handler_info_wait_unused(tmp_rh);1326413265/* Ok, the handler is no more used -> Destroy resources13266*/13267pthread_cond_destroy(&tmp_rh->refcount_cond);13268pthread_mutex_destroy(&tmp_rh->refcount_mutex);13269}13270*lastref = tmp_rh->next;13271mg_free(tmp_rh->uri);13272mg_free(tmp_rh);13273}13274mg_unlock_context(phys_ctx);13275return;13276}13277}13278lastref = &(tmp_rh->next);13279}1328013281if (is_delete_request) {13282/* no handler to set, this was a remove request to a non-existing13283* handler */13284mg_unlock_context(phys_ctx);13285return;13286}1328713288tmp_rh =13289(struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),132901,13291phys_ctx);13292if (tmp_rh == NULL) {13293mg_unlock_context(phys_ctx);13294mg_cry_internal(fc(phys_ctx),13295"%s",13296"Cannot create new request handler struct, OOM");13297return;13298}13299tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);13300if (!tmp_rh->uri) {13301mg_unlock_context(phys_ctx);13302mg_free(tmp_rh);13303mg_cry_internal(fc(phys_ctx),13304"%s",13305"Cannot create new request handler struct, OOM");13306return;13307}13308tmp_rh->uri_len = urilen;13309if (handler_type == REQUEST_HANDLER) {13310/* Init refcount mutex and condition */13311if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {13312mg_unlock_context(phys_ctx);13313mg_free(tmp_rh);13314mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");13315return;13316}13317if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {13318mg_unlock_context(phys_ctx);13319pthread_mutex_destroy(&tmp_rh->refcount_mutex);13320mg_free(tmp_rh);13321mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");13322return;13323}13324tmp_rh->refcount = 0;13325tmp_rh->handler = handler;13326} else if (handler_type == WEBSOCKET_HANDLER) {13327tmp_rh->subprotocols = subprotocols;13328tmp_rh->connect_handler = connect_handler;13329tmp_rh->ready_handler = ready_handler;13330tmp_rh->data_handler = data_handler;13331tmp_rh->close_handler = close_handler;13332} else { /* AUTH_HANDLER */13333tmp_rh->auth_handler = auth_handler;13334}13335tmp_rh->cbdata = cbdata;13336tmp_rh->handler_type = handler_type;13337tmp_rh->next = NULL;1333813339*lastref = tmp_rh;13340mg_unlock_context(phys_ctx);13341}133421334313344void13345mg_set_request_handler(struct mg_context *ctx,13346const char *uri,13347mg_request_handler handler,13348void *cbdata)13349{13350mg_set_handler_type(ctx,13351&(ctx->dd),13352uri,13353REQUEST_HANDLER,13354handler == NULL,13355handler,13356NULL,13357NULL,13358NULL,13359NULL,13360NULL,13361NULL,13362cbdata);13363}133641336513366void13367mg_set_websocket_handler(struct mg_context *ctx,13368const char *uri,13369mg_websocket_connect_handler connect_handler,13370mg_websocket_ready_handler ready_handler,13371mg_websocket_data_handler data_handler,13372mg_websocket_close_handler close_handler,13373void *cbdata)13374{13375mg_set_websocket_handler_with_subprotocols(ctx,13376uri,13377NULL,13378connect_handler,13379ready_handler,13380data_handler,13381close_handler,13382cbdata);13383}133841338513386void13387mg_set_websocket_handler_with_subprotocols(13388struct mg_context *ctx,13389const char *uri,13390struct mg_websocket_subprotocols *subprotocols,13391mg_websocket_connect_handler connect_handler,13392mg_websocket_ready_handler ready_handler,13393mg_websocket_data_handler data_handler,13394mg_websocket_close_handler close_handler,13395void *cbdata)13396{13397int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)13398&& (data_handler == NULL)13399&& (close_handler == NULL);13400mg_set_handler_type(ctx,13401&(ctx->dd),13402uri,13403WEBSOCKET_HANDLER,13404is_delete_request,13405NULL,13406subprotocols,13407connect_handler,13408ready_handler,13409data_handler,13410close_handler,13411NULL,13412cbdata);13413}134141341513416void13417mg_set_auth_handler(struct mg_context *ctx,13418const char *uri,13419mg_request_handler handler,13420void *cbdata)13421{13422mg_set_handler_type(ctx,13423&(ctx->dd),13424uri,13425AUTH_HANDLER,13426handler == NULL,13427NULL,13428NULL,13429NULL,13430NULL,13431NULL,13432NULL,13433handler,13434cbdata);13435}134361343713438static int13439get_request_handler(struct mg_connection *conn,13440int handler_type,13441mg_request_handler *handler,13442struct mg_websocket_subprotocols **subprotocols,13443mg_websocket_connect_handler *connect_handler,13444mg_websocket_ready_handler *ready_handler,13445mg_websocket_data_handler *data_handler,13446mg_websocket_close_handler *close_handler,13447mg_authorization_handler *auth_handler,13448void **cbdata,13449struct mg_handler_info **handler_info)13450{13451const struct mg_request_info *request_info = mg_get_request_info(conn);13452if (request_info) {13453const char *uri = request_info->local_uri;13454size_t urilen = strlen(uri);13455struct mg_handler_info *tmp_rh;1345613457if (!conn || !conn->phys_ctx || !conn->dom_ctx) {13458return 0;13459}1346013461mg_lock_context(conn->phys_ctx);1346213463/* first try for an exact match */13464for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;13465tmp_rh = tmp_rh->next) {13466if (tmp_rh->handler_type == handler_type) {13467if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {13468if (handler_type == WEBSOCKET_HANDLER) {13469*subprotocols = tmp_rh->subprotocols;13470*connect_handler = tmp_rh->connect_handler;13471*ready_handler = tmp_rh->ready_handler;13472*data_handler = tmp_rh->data_handler;13473*close_handler = tmp_rh->close_handler;13474} else if (handler_type == REQUEST_HANDLER) {13475*handler = tmp_rh->handler;13476/* Acquire handler and give it back */13477handler_info_acquire(tmp_rh);13478*handler_info = tmp_rh;13479} else { /* AUTH_HANDLER */13480*auth_handler = tmp_rh->auth_handler;13481}13482*cbdata = tmp_rh->cbdata;13483mg_unlock_context(conn->phys_ctx);13484return 1;13485}13486}13487}1348813489/* next try for a partial match, we will accept uri/something */13490for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;13491tmp_rh = tmp_rh->next) {13492if (tmp_rh->handler_type == handler_type) {13493if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')13494&& (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {13495if (handler_type == WEBSOCKET_HANDLER) {13496*subprotocols = tmp_rh->subprotocols;13497*connect_handler = tmp_rh->connect_handler;13498*ready_handler = tmp_rh->ready_handler;13499*data_handler = tmp_rh->data_handler;13500*close_handler = tmp_rh->close_handler;13501} else if (handler_type == REQUEST_HANDLER) {13502*handler = tmp_rh->handler;13503/* Acquire handler and give it back */13504handler_info_acquire(tmp_rh);13505*handler_info = tmp_rh;13506} else { /* AUTH_HANDLER */13507*auth_handler = tmp_rh->auth_handler;13508}13509*cbdata = tmp_rh->cbdata;13510mg_unlock_context(conn->phys_ctx);13511return 1;13512}13513}13514}1351513516/* finally try for pattern match */13517for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;13518tmp_rh = tmp_rh->next) {13519if (tmp_rh->handler_type == handler_type) {13520if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {13521if (handler_type == WEBSOCKET_HANDLER) {13522*subprotocols = tmp_rh->subprotocols;13523*connect_handler = tmp_rh->connect_handler;13524*ready_handler = tmp_rh->ready_handler;13525*data_handler = tmp_rh->data_handler;13526*close_handler = tmp_rh->close_handler;13527} else if (handler_type == REQUEST_HANDLER) {13528*handler = tmp_rh->handler;13529/* Acquire handler and give it back */13530handler_info_acquire(tmp_rh);13531*handler_info = tmp_rh;13532} else { /* AUTH_HANDLER */13533*auth_handler = tmp_rh->auth_handler;13534}13535*cbdata = tmp_rh->cbdata;13536mg_unlock_context(conn->phys_ctx);13537return 1;13538}13539}13540}1354113542mg_unlock_context(conn->phys_ctx);13543}13544return 0; /* none found */13545}135461354713548/* Check if the script file is in a path, allowed for script files.13549* This can be used if uploading files is possible not only for the server13550* admin, and the upload mechanism does not check the file extension.13551*/13552static int13553is_in_script_path(const struct mg_connection *conn, const char *path)13554{13555/* TODO (Feature): Add config value for allowed script path.13556* Default: All allowed. */13557(void)conn;13558(void)path;13559return 1;13560}135611356213563#if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)13564static int13565deprecated_websocket_connect_wrapper(const struct mg_connection *conn,13566void *cbdata)13567{13568struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;13569if (pcallbacks->websocket_connect) {13570return pcallbacks->websocket_connect(conn);13571}13572/* No handler set - assume "OK" */13573return 0;13574}135751357613577static void13578deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)13579{13580struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;13581if (pcallbacks->websocket_ready) {13582pcallbacks->websocket_ready(conn);13583}13584}135851358613587static int13588deprecated_websocket_data_wrapper(struct mg_connection *conn,13589int bits,13590char *data,13591size_t len,13592void *cbdata)13593{13594struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;13595if (pcallbacks->websocket_data) {13596return pcallbacks->websocket_data(conn, bits, data, len);13597}13598/* No handler set - assume "OK" */13599return 1;13600}13601#endif136021360313604/* This is the heart of the Civetweb's logic.13605* This function is called when the request is read, parsed and validated,13606* and Civetweb must decide what action to take: serve a file, or13607* a directory, or call embedded function, etcetera. */13608static void13609handle_request(struct mg_connection *conn)13610{13611struct mg_request_info *ri = &conn->request_info;13612char path[PATH_MAX];13613int uri_len, ssl_index;13614int is_found = 0, is_script_resource = 0, is_websocket_request = 0,13615is_put_or_delete_request = 0, is_callback_resource = 0;13616int i;13617struct mg_file file = STRUCT_FILE_INITIALIZER;13618mg_request_handler callback_handler = NULL;13619struct mg_handler_info *handler_info = NULL;13620struct mg_websocket_subprotocols *subprotocols;13621mg_websocket_connect_handler ws_connect_handler = NULL;13622mg_websocket_ready_handler ws_ready_handler = NULL;13623mg_websocket_data_handler ws_data_handler = NULL;13624mg_websocket_close_handler ws_close_handler = NULL;13625void *callback_data = NULL;13626mg_authorization_handler auth_handler = NULL;13627void *auth_callback_data = NULL;13628int handler_type;13629time_t curtime = time(NULL);13630char date[64];1363113632path[0] = 0;1363313634/* 1. get the request url */13635/* 1.1. split into url and query string */13636if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))13637!= NULL) {13638*((char *)conn->request_info.query_string++) = '\0';13639}1364013641/* 1.2. do a https redirect, if required. Do not decode URIs yet. */13642if (!conn->client.is_ssl && conn->client.ssl_redir) {13643ssl_index = get_first_ssl_listener_index(conn->phys_ctx);13644if (ssl_index >= 0) {13645redirect_to_https_port(conn, ssl_index);13646} else {13647/* A http to https forward port has been specified,13648* but no https port to forward to. */13649mg_send_http_error(conn,13650503,13651"%s",13652"Error: SSL forward not configured properly");13653mg_cry_internal(conn,13654"%s",13655"Can not redirect to SSL, no SSL port available");13656}13657return;13658}13659uri_len = (int)strlen(ri->local_uri);1366013661/* 1.3. decode url (if config says so) */13662if (should_decode_url(conn)) {13663mg_url_decode(13664ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);13665}1366613667/* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is13668* not possible */13669remove_double_dots_and_double_slashes((char *)ri->local_uri);1367013671/* step 1. completed, the url is known now */13672uri_len = (int)strlen(ri->local_uri);13673DEBUG_TRACE("URL: %s", ri->local_uri);1367413675/* 2. if this ip has limited speed, set it for this connection */13676conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],13677get_remote_ip(conn),13678ri->local_uri);1367913680/* 3. call a "handle everything" callback, if registered */13681if (conn->phys_ctx->callbacks.begin_request != NULL) {13682/* Note that since V1.7 the "begin_request" function is called13683* before an authorization check. If an authorization check is13684* required, use a request_handler instead. */13685i = conn->phys_ctx->callbacks.begin_request(conn);13686if (i > 0) {13687/* callback already processed the request. Store the13688return value as a status code for the access log. */13689conn->status_code = i;13690discard_unread_request_data(conn);13691return;13692} else if (i == 0) {13693/* civetweb should process the request */13694} else {13695/* unspecified - may change with the next version */13696return;13697}13698}1369913700/* request not yet handled by a handler or redirect, so the request13701* is processed here */1370213703/* 4. Check for CORS preflight requests and handle them (if configured).13704* https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS13705*/13706if (!strcmp(ri->request_method, "OPTIONS")) {13707/* Send a response to CORS preflights only if13708* access_control_allow_methods is not NULL and not an empty string.13709* In this case, scripts can still handle CORS. */13710const char *cors_meth_cfg =13711conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];13712const char *cors_orig_cfg =13713conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];13714const char *cors_origin =13715get_header(ri->http_headers, ri->num_headers, "Origin");13716const char *cors_acrm = get_header(ri->http_headers,13717ri->num_headers,13718"Access-Control-Request-Method");1371913720/* Todo: check if cors_origin is in cors_orig_cfg.13721* Or, let the client check this. */1372213723if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)13724&& (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)13725&& (cors_origin != NULL) && (cors_acrm != NULL)) {13726/* This is a valid CORS preflight, and the server is configured13727* to13728* handle it automatically. */13729const char *cors_acrh =13730get_header(ri->http_headers,13731ri->num_headers,13732"Access-Control-Request-Headers");1373313734gmt_time_string(date, sizeof(date), &curtime);13735mg_printf(conn,13736"HTTP/1.1 200 OK\r\n"13737"Date: %s\r\n"13738"Access-Control-Allow-Origin: %s\r\n"13739"Access-Control-Allow-Methods: %s\r\n"13740"Content-Length: 0\r\n"13741"Connection: %s\r\n",13742date,13743cors_orig_cfg,13744((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),13745suggest_connection_header(conn));1374613747if (cors_acrh != NULL) {13748/* CORS request is asking for additional headers */13749const char *cors_hdr_cfg =13750conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];1375113752if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {13753/* Allow only if access_control_allow_headers is13754* not NULL and not an empty string. If this13755* configuration is set to *, allow everything.13756* Otherwise this configuration must be a list13757* of allowed HTTP header names. */13758mg_printf(conn,13759"Access-Control-Allow-Headers: %s\r\n",13760((cors_hdr_cfg[0] == '*') ? cors_acrh13761: cors_hdr_cfg));13762}13763}13764mg_printf(conn, "Access-Control-Max-Age: 60\r\n");1376513766mg_printf(conn, "\r\n");13767return;13768}13769}1377013771/* 5. interpret the url to find out how the request must be handled13772*/13773/* 5.1. first test, if the request targets the regular http(s)://13774* protocol namespace or the websocket ws(s):// protocol namespace.13775*/13776is_websocket_request = is_websocket_protocol(conn);13777#if defined(USE_WEBSOCKET)13778handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;13779#else13780handler_type = REQUEST_HANDLER;13781#endif /* defined(USE_WEBSOCKET) */13782/* 5.2. check if the request will be handled by a callback */13783if (get_request_handler(conn,13784handler_type,13785&callback_handler,13786&subprotocols,13787&ws_connect_handler,13788&ws_ready_handler,13789&ws_data_handler,13790&ws_close_handler,13791NULL,13792&callback_data,13793&handler_info)) {13794/* 5.2.1. A callback will handle this request. All requests13795* handled13796* by a callback have to be considered as requests to a script13797* resource. */13798is_callback_resource = 1;13799is_script_resource = 1;13800is_put_or_delete_request = is_put_or_delete_method(conn);13801} else {13802no_callback_resource:1380313804/* 5.2.2. No callback is responsible for this request. The URI13805* addresses a file based resource (static content or Lua/cgi13806* scripts in the file system). */13807is_callback_resource = 0;13808interpret_uri(conn,13809path,13810sizeof(path),13811&file.stat,13812&is_found,13813&is_script_resource,13814&is_websocket_request,13815&is_put_or_delete_request);13816}1381713818/* 6. authorization check */13819/* 6.1. a custom authorization handler is installed */13820if (get_request_handler(conn,13821AUTH_HANDLER,13822NULL,13823NULL,13824NULL,13825NULL,13826NULL,13827NULL,13828&auth_handler,13829&auth_callback_data,13830NULL)) {13831if (!auth_handler(conn, auth_callback_data)) {13832return;13833}13834} else if (is_put_or_delete_request && !is_script_resource13835&& !is_callback_resource) {13836/* 6.2. this request is a PUT/DELETE to a real file */13837/* 6.2.1. thus, the server must have real files */13838#if defined(NO_FILES)13839if (1) {13840#else13841if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {13842#endif13843/* This server does not have any real files, thus the13844* PUT/DELETE methods are not valid. */13845mg_send_http_error(conn,13846405,13847"%s method not allowed",13848conn->request_info.request_method);13849return;13850}1385113852#if !defined(NO_FILES)13853/* 6.2.2. Check if put authorization for static files is13854* available.13855*/13856if (!is_authorized_for_put(conn)) {13857send_authorization_request(conn, NULL);13858return;13859}13860#endif1386113862} else {13863/* 6.3. This is either a OPTIONS, GET, HEAD or POST request,13864* or it is a PUT or DELETE request to a resource that does not13865* correspond to a file. Check authorization. */13866if (!check_authorization(conn, path)) {13867send_authorization_request(conn, NULL);13868return;13869}13870}1387113872/* request is authorized or does not need authorization */1387313874/* 7. check if there are request handlers for this uri */13875if (is_callback_resource) {13876if (!is_websocket_request) {13877i = callback_handler(conn, callback_data);1387813879/* Callback handler will not be used anymore. Release it */13880handler_info_release(handler_info);1388113882if (i > 0) {13883/* Do nothing, callback has served the request. Store13884* then return value as status code for the log and discard13885* all data from the client not used by the callback. */13886conn->status_code = i;13887discard_unread_request_data(conn);13888} else {13889/* The handler did NOT handle the request. */13890/* Some proper reactions would be:13891* a) close the connections without sending anything13892* b) send a 404 not found13893* c) try if there is a file matching the URI13894* It would be possible to do a, b or c in the callback13895* implementation, and return 1 - we cannot do anything13896* here, that is not possible in the callback.13897*13898* TODO: What would be the best reaction here?13899* (Note: The reaction may change, if there is a better13900*idea.)13901*/1390213903/* For the moment, use option c: We look for a proper file,13904* but since a file request is not always a script resource,13905* the authorization check might be different. */13906interpret_uri(conn,13907path,13908sizeof(path),13909&file.stat,13910&is_found,13911&is_script_resource,13912&is_websocket_request,13913&is_put_or_delete_request);13914callback_handler = NULL;1391513916/* Here we are at a dead end:13917* According to URI matching, a callback should be13918* responsible for handling the request,13919* we called it, but the callback declared itself13920* not responsible.13921* We use a goto here, to get out of this dead end,13922* and continue with the default handling.13923* A goto here is simpler and better to understand13924* than some curious loop. */13925goto no_callback_resource;13926}13927} else {13928#if defined(USE_WEBSOCKET)13929handle_websocket_request(conn,13930path,13931is_callback_resource,13932subprotocols,13933ws_connect_handler,13934ws_ready_handler,13935ws_data_handler,13936ws_close_handler,13937callback_data);13938#endif13939}13940return;13941}1394213943/* 8. handle websocket requests */13944#if defined(USE_WEBSOCKET)13945if (is_websocket_request) {13946if (is_script_resource) {1394713948if (is_in_script_path(conn, path)) {13949/* Websocket Lua script */13950handle_websocket_request(conn,13951path,139520 /* Lua Script */,13953NULL,13954NULL,13955NULL,13956NULL,13957NULL,13958conn->phys_ctx->user_data);13959} else {13960/* Script was in an illegal path */13961mg_send_http_error(conn, 403, "%s", "Forbidden");13962}13963} else {13964#if defined(MG_LEGACY_INTERFACE)13965handle_websocket_request(13966conn,13967path,13968!is_script_resource /* could be deprecated global callback */,13969NULL,13970deprecated_websocket_connect_wrapper,13971deprecated_websocket_ready_wrapper,13972deprecated_websocket_data_wrapper,13973NULL,13974conn->phys_ctx->user_data);13975#else13976mg_send_http_error(conn, 404, "%s", "Not found");13977#endif13978}13979return;13980} else13981#endif1398213983#if defined(NO_FILES)13984/* 9a. In case the server uses only callbacks, this uri is13985* unknown.13986* Then, all request handling ends here. */13987mg_send_http_error(conn, 404, "%s", "Not Found");1398813989#else13990/* 9b. This request is either for a static file or resource handled13991* by a script file. Thus, a DOCUMENT_ROOT must exist. */13992if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {13993mg_send_http_error(conn, 404, "%s", "Not Found");13994return;13995}1399613997/* 10. Request is handled by a script */13998if (is_script_resource) {13999handle_file_based_request(conn, path, &file);14000return;14001}1400214003/* 11. Handle put/delete/mkcol requests */14004if (is_put_or_delete_request) {14005/* 11.1. PUT method */14006if (!strcmp(ri->request_method, "PUT")) {14007put_file(conn, path);14008return;14009}14010/* 11.2. DELETE method */14011if (!strcmp(ri->request_method, "DELETE")) {14012delete_file(conn, path);14013return;14014}14015/* 11.3. MKCOL method */14016if (!strcmp(ri->request_method, "MKCOL")) {14017mkcol(conn, path);14018return;14019}14020/* 11.4. PATCH method14021* This method is not supported for static resources,14022* only for scripts (Lua, CGI) and callbacks. */14023mg_send_http_error(conn,14024405,14025"%s method not allowed",14026conn->request_info.request_method);14027return;14028}1402914030/* 11. File does not exist, or it was configured that it should be14031* hidden */14032if (!is_found || (must_hide_file(conn, path))) {14033mg_send_http_error(conn, 404, "%s", "Not found");14034return;14035}1403614037/* 12. Directory uris should end with a slash */14038if (file.stat.is_directory && (uri_len > 0)14039&& (ri->local_uri[uri_len - 1] != '/')) {14040gmt_time_string(date, sizeof(date), &curtime);14041mg_printf(conn,14042"HTTP/1.1 301 Moved Permanently\r\n"14043"Location: %s/\r\n"14044"Date: %s\r\n"14045/* "Cache-Control: private\r\n" (= default) */14046"Content-Length: 0\r\n"14047"Connection: %s\r\n",14048ri->request_uri,14049date,14050suggest_connection_header(conn));14051send_additional_header(conn);14052mg_printf(conn, "\r\n");14053return;14054}1405514056/* 13. Handle other methods than GET/HEAD */14057/* 13.1. Handle PROPFIND */14058if (!strcmp(ri->request_method, "PROPFIND")) {14059handle_propfind(conn, path, &file.stat);14060return;14061}14062/* 13.2. Handle OPTIONS for files */14063if (!strcmp(ri->request_method, "OPTIONS")) {14064/* This standard handler is only used for real files.14065* Scripts should support the OPTIONS method themselves, to allow a14066* maximum flexibility.14067* Lua and CGI scripts may fully support CORS this way (including14068* preflights). */14069send_options(conn);14070return;14071}14072/* 13.3. everything but GET and HEAD (e.g. POST) */14073if ((0 != strcmp(ri->request_method, "GET"))14074&& (0 != strcmp(ri->request_method, "HEAD"))) {14075mg_send_http_error(conn,14076405,14077"%s method not allowed",14078conn->request_info.request_method);14079return;14080}1408114082/* 14. directories */14083if (file.stat.is_directory) {14084/* Substitute files have already been handled above. */14085/* Here we can either generate and send a directory listing,14086* or send an "access denied" error. */14087if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],14088"yes")) {14089handle_directory_request(conn, path);14090} else {14091mg_send_http_error(conn,14092403,14093"%s",14094"Error: Directory listing denied");14095}14096return;14097}1409814099/* 15. read a normal file with GET or HEAD */14100handle_file_based_request(conn, path, &file);14101#endif /* !defined(NO_FILES) */14102}141031410414105static void14106handle_file_based_request(struct mg_connection *conn,14107const char *path,14108struct mg_file *file)14109{14110if (!conn || !conn->dom_ctx) {14111return;14112}1411314114if (0) {14115#if defined(USE_LUA)14116} else if (match_prefix(14117conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],14118strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),14119path)14120> 0) {14121if (is_in_script_path(conn, path)) {14122/* Lua server page: an SSI like page containing mostly plain14123* html14124* code14125* plus some tags with server generated contents. */14126handle_lsp_request(conn, path, file, NULL);14127} else {14128/* Script was in an illegal path */14129mg_send_http_error(conn, 403, "%s", "Forbidden");14130}1413114132} else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],14133strlen(14134conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),14135path)14136> 0) {14137if (is_in_script_path(conn, path)) {14138/* Lua in-server module script: a CGI like script used to14139* generate14140* the14141* entire reply. */14142mg_exec_lua_script(conn, path, NULL);14143} else {14144/* Script was in an illegal path */14145mg_send_http_error(conn, 403, "%s", "Forbidden");14146}14147#endif14148#if defined(USE_DUKTAPE)14149} else if (match_prefix(14150conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],14151strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),14152path)14153> 0) {14154if (is_in_script_path(conn, path)) {14155/* Call duktape to generate the page */14156mg_exec_duktape_script(conn, path);14157} else {14158/* Script was in an illegal path */14159mg_send_http_error(conn, 403, "%s", "Forbidden");14160}14161#endif14162#if !defined(NO_CGI)14163} else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],14164strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),14165path)14166> 0) {14167if (is_in_script_path(conn, path)) {14168/* CGI scripts may support all HTTP methods */14169handle_cgi_request(conn, path);14170} else {14171/* Script was in an illegal path */14172mg_send_http_error(conn, 403, "%s", "Forbidden");14173}14174#endif /* !NO_CGI */14175} else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],14176strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),14177path)14178> 0) {14179if (is_in_script_path(conn, path)) {14180handle_ssi_file_request(conn, path, file);14181} else {14182/* Script was in an illegal path */14183mg_send_http_error(conn, 403, "%s", "Forbidden");14184}14185#if !defined(NO_CACHING)14186} else if ((!conn->in_error_handler)14187&& is_not_modified(conn, &file->stat)) {14188/* Send 304 "Not Modified" - this must not send any body data */14189handle_not_modified_static_file_request(conn, file);14190#endif /* !NO_CACHING */14191} else {14192handle_static_file_request(conn, path, file, NULL, NULL);14193}14194}141951419614197static void14198close_all_listening_sockets(struct mg_context *ctx)14199{14200unsigned int i;14201if (!ctx) {14202return;14203}1420414205for (i = 0; i < ctx->num_listening_sockets; i++) {14206closesocket(ctx->listening_sockets[i].sock);14207ctx->listening_sockets[i].sock = INVALID_SOCKET;14208}14209mg_free(ctx->listening_sockets);14210ctx->listening_sockets = NULL;14211mg_free(ctx->listening_socket_fds);14212ctx->listening_socket_fds = NULL;14213}142141421514216/* Valid listening port specification is: [ip_address:]port[s]14217* Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s14218* Examples for IPv6: [::]:80, [::1]:80,14219* [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s14220* see https://tools.ietf.org/html/rfc3513#section-2.214221* In order to bind to both, IPv4 and IPv6, you can either add14222* both ports using 8080,[::]:8080, or the short form +8080.14223* Both forms differ in detail: 8080,[::]:8080 create two sockets,14224* one only accepting IPv4 the other only IPv6. +8080 creates14225* one socket accepting IPv4 and IPv6. Depending on the IPv614226* environment, they might work differently, or might not work14227* at all - it must be tested what options work best in the14228* relevant network environment.14229*/14230static int14231parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)14232{14233unsigned int a, b, c, d, port;14234int ch, len;14235const char *cb;14236#if defined(USE_IPV6)14237char buf[100] = {0};14238#endif1423914240/* MacOS needs that. If we do not zero it, subsequent bind() will fail.14241* Also, all-zeroes in the socket address means binding to all addresses14242* for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */14243memset(so, 0, sizeof(*so));14244so->lsa.sin.sin_family = AF_INET;14245*ip_version = 0;1424614247/* Initialize port and len as invalid. */14248port = 0;14249len = 0;1425014251/* Test for different ways to format this string */14252if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)14253== 5) {14254/* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */14255so->lsa.sin.sin_addr.s_addr =14256htonl((a << 24) | (b << 16) | (c << 8) | d);14257so->lsa.sin.sin_port = htons((uint16_t)port);14258*ip_version = 4;1425914260#if defined(USE_IPV6)14261} else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 214262&& mg_inet_pton(14263AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {14264/* IPv6 address, examples: see above */14265/* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton14266*/14267so->lsa.sin6.sin6_port = htons((uint16_t)port);14268*ip_version = 6;14269#endif1427014271} else if ((vec->ptr[0] == '+')14272&& (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {1427314274/* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */14275/* Add 1 to len for the + character we skipped before */14276len++;1427714278#if defined(USE_IPV6)14279/* Set socket family to IPv6, do not use IPV6_V6ONLY */14280so->lsa.sin6.sin6_family = AF_INET6;14281so->lsa.sin6.sin6_port = htons((uint16_t)port);14282*ip_version = 4 + 6;14283#else14284/* Bind to IPv4 only, since IPv6 is not built in. */14285so->lsa.sin.sin_port = htons((uint16_t)port);14286*ip_version = 4;14287#endif1428814289} else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {14290/* If only port is specified, bind to IPv4, INADDR_ANY */14291so->lsa.sin.sin_port = htons((uint16_t)port);14292*ip_version = 4;1429314294} else if ((cb = strchr(vec->ptr, ':')) != NULL) {14295/* String could be a hostname. This check algotithm14296* will only work for RFC 952 compliant hostnames,14297* starting with a letter, containing only letters,14298* digits and hyphen ('-'). Newer specs may allow14299* more, but this is not guaranteed here, since it14300* may interfere with rules for port option lists. */1430114302/* According to RFC 1035, hostnames are restricted to 255 characters14303* in total (63 between two dots). */14304char hostname[256];14305size_t hostnlen = (size_t)(cb - vec->ptr);1430614307if (hostnlen >= sizeof(hostname)) {14308/* This would be invalid in any case */14309*ip_version = 0;14310return 0;14311}1431214313memcpy(hostname, vec->ptr, hostnlen);14314hostname[hostnlen] = 0;1431514316if (mg_inet_pton(14317AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {14318if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {14319*ip_version = 4;14320so->lsa.sin.sin_family = AF_INET;14321so->lsa.sin.sin_port = htons((uint16_t)port);14322len += (int)(hostnlen + 1);14323} else {14324port = 0;14325len = 0;14326}14327#if defined(USE_IPV6)14328} else if (mg_inet_pton(AF_INET6,14329vec->ptr,14330&so->lsa.sin6,14331sizeof(so->lsa.sin6))) {14332if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {14333*ip_version = 6;14334so->lsa.sin6.sin6_family = AF_INET6;14335so->lsa.sin.sin_port = htons((uint16_t)port);14336len += (int)(hostnlen + 1);14337} else {14338port = 0;14339len = 0;14340}14341#endif14342}143431434414345} else {14346/* Parsing failure. */14347}1434814349/* sscanf and the option splitting code ensure the following condition14350*/14351if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {14352*ip_version = 0;14353return 0;14354}14355ch = vec->ptr[len]; /* Next character after the port number */14356so->is_ssl = (ch == 's');14357so->ssl_redir = (ch == 'r');1435814359/* Make sure the port is valid and vector ends with 's', 'r' or ',' */14360if (is_valid_port(port)14361&& ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {14362return 1;14363}1436414365/* Reset ip_version to 0 if there is an error */14366*ip_version = 0;14367return 0;14368}143691437014371/* Is there any SSL port in use? */14372static int14373is_ssl_port_used(const char *ports)14374{14375if (ports) {14376/* There are several different allowed syntax variants:14377* - "80" for a single port using every network interface14378* - "localhost:80" for a single port using only localhost14379* - "80,localhost:8080" for two ports, one bound to localhost14380* - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound14381* to IPv4 localhost, one to IPv6 localhost14382* - "+80" use port 80 for IPv4 and IPv614383* - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),14384* for both: IPv4 and IPv414385* - "+443s,localhost:8080" port 443 (HTTPS) for every interface,14386* additionally port 8080 bound to localhost connections14387*14388* If we just look for 's' anywhere in the string, "localhost:80"14389* will be detected as SSL (false positive).14390* Looking for 's' after a digit may cause false positives in14391* "my24service:8080".14392* Looking from 's' backward if there are only ':' and numbers14393* before will not work for "24service:8080" (non SSL, port 8080)14394* or "24s" (SSL, port 24).14395*14396* Remark: Initially hostnames were not allowed to start with a14397* digit (according to RFC 952), this was allowed later (RFC 1123,14398* Section 2.1).14399*14400* To get this correct, the entire string must be parsed as a whole,14401* reading it as a list element for element and parsing with an14402* algorithm equivalent to parse_port_string.14403*14404* In fact, we use local interface names here, not arbitrary hostnames,14405* so in most cases the only name will be "localhost".14406*14407* So, for now, we use this simple algorithm, that may still return14408* a false positive in bizarre cases.14409*/14410int i;14411int portslen = (int)strlen(ports);14412char prevIsNumber = 0;1441314414for (i = 0; i < portslen; i++) {14415if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {14416return 1;14417}14418if (ports[i] >= '0' && ports[i] <= '9') {14419prevIsNumber = 1;14420} else {14421prevIsNumber = 0;14422}14423}14424}14425return 0;14426}144271442814429static int14430set_ports_option(struct mg_context *phys_ctx)14431{14432const char *list;14433int on = 1;14434#if defined(USE_IPV6)14435int off = 0;14436#endif14437struct vec vec;14438struct socket so, *ptr;1443914440struct pollfd *pfd;14441union usa usa;14442socklen_t len;14443int ip_version;1444414445int portsTotal = 0;14446int portsOk = 0;1444714448if (!phys_ctx) {14449return 0;14450}1445114452memset(&so, 0, sizeof(so));14453memset(&usa, 0, sizeof(usa));14454len = sizeof(usa);14455list = phys_ctx->dd.config[LISTENING_PORTS];1445614457while ((list = next_option(list, &vec, NULL)) != NULL) {1445814459portsTotal++;1446014461if (!parse_port_string(&vec, &so, &ip_version)) {14462mg_cry_internal(14463fc(phys_ctx),14464"%.*s: invalid port spec (entry %i). Expecting list of: %s",14465(int)vec.len,14466vec.ptr,14467portsTotal,14468"[IP_ADDRESS:]PORT[s|r]");14469continue;14470}1447114472#if !defined(NO_SSL)14473if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {1447414475mg_cry_internal(fc(phys_ctx),14476"Cannot add SSL socket (entry %i)",14477portsTotal);14478continue;14479}14480#endif1448114482if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))14483== INVALID_SOCKET) {1448414485mg_cry_internal(fc(phys_ctx),14486"cannot create socket (entry %i)",14487portsTotal);14488continue;14489}1449014491#if defined(_WIN32)14492/* Windows SO_REUSEADDR lets many procs binds to a14493* socket, SO_EXCLUSIVEADDRUSE makes the bind fail14494* if someone already has the socket -- DTL */14495/* NOTE: If SO_EXCLUSIVEADDRUSE is used,14496* Windows might need a few seconds before14497* the same port can be used again in the14498* same process, so a short Sleep may be14499* required between mg_stop and mg_start.14500*/14501if (setsockopt(so.sock,14502SOL_SOCKET,14503SO_EXCLUSIVEADDRUSE,14504(SOCK_OPT_TYPE)&on,14505sizeof(on))14506!= 0) {1450714508/* Set reuse option, but don't abort on errors. */14509mg_cry_internal(14510fc(phys_ctx),14511"cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",14512portsTotal);14513}14514#else14515if (setsockopt(so.sock,14516SOL_SOCKET,14517SO_REUSEADDR,14518(SOCK_OPT_TYPE)&on,14519sizeof(on))14520!= 0) {1452114522/* Set reuse option, but don't abort on errors. */14523mg_cry_internal(fc(phys_ctx),14524"cannot set socket option SO_REUSEADDR (entry %i)",14525portsTotal);14526}14527#endif1452814529if (ip_version > 4) {14530/* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */14531#if defined(USE_IPV6)14532if (ip_version > 6) {14533if (so.lsa.sa.sa_family == AF_INET614534&& setsockopt(so.sock,14535IPPROTO_IPV6,14536IPV6_V6ONLY,14537(void *)&off,14538sizeof(off))14539!= 0) {1454014541/* Set IPv6 only option, but don't abort on errors. */14542mg_cry_internal(14543fc(phys_ctx),14544"cannot set socket option IPV6_V6ONLY=off (entry %i)",14545portsTotal);14546}14547} else {14548if (so.lsa.sa.sa_family == AF_INET614549&& setsockopt(so.sock,14550IPPROTO_IPV6,14551IPV6_V6ONLY,14552(void *)&on,14553sizeof(on))14554!= 0) {1455514556/* Set IPv6 only option, but don't abort on errors. */14557mg_cry_internal(14558fc(phys_ctx),14559"cannot set socket option IPV6_V6ONLY=on (entry %i)",14560portsTotal);14561}14562}14563#else14564mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");14565closesocket(so.sock);14566so.sock = INVALID_SOCKET;14567continue;14568#endif14569}1457014571if (so.lsa.sa.sa_family == AF_INET) {1457214573len = sizeof(so.lsa.sin);14574if (bind(so.sock, &so.lsa.sa, len) != 0) {14575mg_cry_internal(fc(phys_ctx),14576"cannot bind to %.*s: %d (%s)",14577(int)vec.len,14578vec.ptr,14579(int)ERRNO,14580strerror(errno));14581closesocket(so.sock);14582so.sock = INVALID_SOCKET;14583continue;14584}14585}14586#if defined(USE_IPV6)14587else if (so.lsa.sa.sa_family == AF_INET6) {1458814589len = sizeof(so.lsa.sin6);14590if (bind(so.sock, &so.lsa.sa, len) != 0) {14591mg_cry_internal(fc(phys_ctx),14592"cannot bind to IPv6 %.*s: %d (%s)",14593(int)vec.len,14594vec.ptr,14595(int)ERRNO,14596strerror(errno));14597closesocket(so.sock);14598so.sock = INVALID_SOCKET;14599continue;14600}14601}14602#endif14603else {14604mg_cry_internal(14605fc(phys_ctx),14606"cannot bind: address family not supported (entry %i)",14607portsTotal);14608closesocket(so.sock);14609so.sock = INVALID_SOCKET;14610continue;14611}1461214613if (listen(so.sock, SOMAXCONN) != 0) {1461414615mg_cry_internal(fc(phys_ctx),14616"cannot listen to %.*s: %d (%s)",14617(int)vec.len,14618vec.ptr,14619(int)ERRNO,14620strerror(errno));14621closesocket(so.sock);14622so.sock = INVALID_SOCKET;14623continue;14624}1462514626if ((getsockname(so.sock, &(usa.sa), &len) != 0)14627|| (usa.sa.sa_family != so.lsa.sa.sa_family)) {1462814629int err = (int)ERRNO;14630mg_cry_internal(fc(phys_ctx),14631"call to getsockname failed %.*s: %d (%s)",14632(int)vec.len,14633vec.ptr,14634err,14635strerror(errno));14636closesocket(so.sock);14637so.sock = INVALID_SOCKET;14638continue;14639}1464014641/* Update lsa port in case of random free ports */14642#if defined(USE_IPV6)14643if (so.lsa.sa.sa_family == AF_INET6) {14644so.lsa.sin6.sin6_port = usa.sin6.sin6_port;14645} else14646#endif14647{14648so.lsa.sin.sin_port = usa.sin.sin_port;14649}1465014651if ((ptr = (struct socket *)14652mg_realloc_ctx(phys_ctx->listening_sockets,14653(phys_ctx->num_listening_sockets + 1)14654* sizeof(phys_ctx->listening_sockets[0]),14655phys_ctx))14656== NULL) {1465714658mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");14659closesocket(so.sock);14660so.sock = INVALID_SOCKET;14661continue;14662}1466314664if ((pfd = (struct pollfd *)14665mg_realloc_ctx(phys_ctx->listening_socket_fds,14666(phys_ctx->num_listening_sockets + 1)14667* sizeof(phys_ctx->listening_socket_fds[0]),14668phys_ctx))14669== NULL) {1467014671mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");14672closesocket(so.sock);14673so.sock = INVALID_SOCKET;14674mg_free(ptr);14675continue;14676}1467714678set_close_on_exec(so.sock, fc(phys_ctx));14679phys_ctx->listening_sockets = ptr;14680phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;14681phys_ctx->listening_socket_fds = pfd;14682phys_ctx->num_listening_sockets++;14683portsOk++;14684}1468514686if (portsOk != portsTotal) {14687close_all_listening_sockets(phys_ctx);14688portsOk = 0;14689}1469014691return portsOk;14692}146931469414695static const char *14696header_val(const struct mg_connection *conn, const char *header)14697{14698const char *header_value;1469914700if ((header_value = mg_get_header(conn, header)) == NULL) {14701return "-";14702} else {14703return header_value;14704}14705}147061470714708#if defined(MG_EXTERNAL_FUNCTION_log_access)14709static void log_access(const struct mg_connection *conn);14710#include "external_log_access.inl"14711#else1471214713static void14714log_access(const struct mg_connection *conn)14715{14716const struct mg_request_info *ri;14717struct mg_file fi;14718char date[64], src_addr[IP_ADDR_STR_LEN];14719struct tm *tm;1472014721const char *referer;14722const char *user_agent;1472314724char buf[4096];1472514726if (!conn || !conn->dom_ctx) {14727return;14728}1472914730if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {14731if (mg_fopen(conn,14732conn->dom_ctx->config[ACCESS_LOG_FILE],14733MG_FOPEN_MODE_APPEND,14734&fi)14735== 0) {14736fi.access.fp = NULL;14737}14738} else {14739fi.access.fp = NULL;14740}1474114742/* Log is written to a file and/or a callback. If both are not set,14743* executing the rest of the function is pointless. */14744if ((fi.access.fp == NULL)14745&& (conn->phys_ctx->callbacks.log_access == NULL)) {14746return;14747}1474814749tm = localtime(&conn->conn_birth_time);14750if (tm != NULL) {14751strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);14752} else {14753mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));14754date[sizeof(date) - 1] = '\0';14755}1475614757ri = &conn->request_info;1475814759sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);14760referer = header_val(conn, "Referer");14761user_agent = header_val(conn, "User-Agent");1476214763mg_snprintf(conn,14764NULL, /* Ignore truncation in access log */14765buf,14766sizeof(buf),14767"%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",14768src_addr,14769(ri->remote_user == NULL) ? "-" : ri->remote_user,14770date,14771ri->request_method ? ri->request_method : "-",14772ri->request_uri ? ri->request_uri : "-",14773ri->query_string ? "?" : "",14774ri->query_string ? ri->query_string : "",14775ri->http_version,14776conn->status_code,14777conn->num_bytes_sent,14778referer,14779user_agent);1478014781if (conn->phys_ctx->callbacks.log_access) {14782conn->phys_ctx->callbacks.log_access(conn, buf);14783}1478414785if (fi.access.fp) {14786int ok = 1;14787flockfile(fi.access.fp);14788if (fprintf(fi.access.fp, "%s\n", buf) < 1) {14789ok = 0;14790}14791if (fflush(fi.access.fp) != 0) {14792ok = 0;14793}14794funlockfile(fi.access.fp);14795if (mg_fclose(&fi.access) != 0) {14796ok = 0;14797}14798if (!ok) {14799mg_cry_internal(conn,14800"Error writing log file %s",14801conn->dom_ctx->config[ACCESS_LOG_FILE]);14802}14803}14804}1480514806#endif /* Externally provided function */148071480814809/* Verify given socket address against the ACL.14810* Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.14811*/14812static int14813check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)14814{14815int allowed, flag;14816uint32_t net, mask;14817struct vec vec;1481814819if (phys_ctx) {14820const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];1482114822/* If any ACL is set, deny by default */14823allowed = (list == NULL) ? '+' : '-';1482414825while ((list = next_option(list, &vec, NULL)) != NULL) {14826flag = vec.ptr[0];14827if ((flag != '+' && flag != '-')14828|| (parse_net(&vec.ptr[1], &net, &mask) == 0)) {14829mg_cry_internal(fc(phys_ctx),14830"%s: subnet must be [+|-]x.x.x.x[/x]",14831__func__);14832return -1;14833}1483414835if (net == (remote_ip & mask)) {14836allowed = flag;14837}14838}1483914840return allowed == '+';14841}14842return -1;14843}148441484514846#if !defined(_WIN32)14847static int14848set_uid_option(struct mg_context *phys_ctx)14849{14850int success = 0;1485114852if (phys_ctx) {14853/* We are currently running as curr_uid. */14854const uid_t curr_uid = getuid();14855/* If set, we want to run as run_as_user. */14856const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];14857const struct passwd *to_pw = NULL;1485814859if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {14860/* run_as_user does not exist on the system. We can't proceed14861* further. */14862mg_cry_internal(fc(phys_ctx),14863"%s: unknown user [%s]",14864__func__,14865run_as_user);14866} else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {14867/* There was either no request to change user, or we're already14868* running as run_as_user. Nothing else to do.14869*/14870success = 1;14871} else {14872/* Valid change request. */14873if (setgid(to_pw->pw_gid) == -1) {14874mg_cry_internal(fc(phys_ctx),14875"%s: setgid(%s): %s",14876__func__,14877run_as_user,14878strerror(errno));14879} else if (setgroups(0, NULL) == -1) {14880mg_cry_internal(fc(phys_ctx),14881"%s: setgroups(): %s",14882__func__,14883strerror(errno));14884} else if (setuid(to_pw->pw_uid) == -1) {14885mg_cry_internal(fc(phys_ctx),14886"%s: setuid(%s): %s",14887__func__,14888run_as_user,14889strerror(errno));14890} else {14891success = 1;14892}14893}14894}1489514896return success;14897}14898#endif /* !_WIN32 */148991490014901static void14902tls_dtor(void *key)14903{14904struct mg_workerTLS *tls = (struct mg_workerTLS *)key;14905/* key == pthread_getspecific(sTlsKey); */1490614907if (tls) {14908if (tls->is_master == 2) {14909tls->is_master = -3; /* Mark memory as dead */14910mg_free(tls);14911}14912}14913pthread_setspecific(sTlsKey, NULL);14914}149151491614917#if !defined(NO_SSL)1491814919static int ssl_use_pem_file(struct mg_context *phys_ctx,14920struct mg_domain_context *dom_ctx,14921const char *pem,14922const char *chain);14923static const char *ssl_error(void);149241492514926static int14927refresh_trust(struct mg_connection *conn)14928{14929static int reload_lock = 0;14930static long int data_check = 0;14931volatile int *p_reload_lock = (volatile int *)&reload_lock;1493214933struct stat cert_buf;14934long int t;14935const char *pem;14936const char *chain;14937int should_verify_peer;1493814939if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {14940/* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,14941* refresh_trust still can not work. */14942return 0;14943}14944chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];14945if (chain == NULL) {14946/* pem is not NULL here */14947chain = pem;14948}14949if (*chain == 0) {14950chain = NULL;14951}1495214953t = data_check;14954if (stat(pem, &cert_buf) != -1) {14955t = (long int)cert_buf.st_mtime;14956}1495714958if (data_check != t) {14959data_check = t;1496014961should_verify_peer = 0;14962if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {14963if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")14964== 0) {14965should_verify_peer = 1;14966} else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],14967"optional")14968== 0) {14969should_verify_peer = 1;14970}14971}1497214973if (should_verify_peer) {14974char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];14975char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];14976if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,14977ca_file,14978ca_path)14979!= 1) {14980mg_cry_internal(14981fc(conn->phys_ctx),14982"SSL_CTX_load_verify_locations error: %s "14983"ssl_verify_peer requires setting "14984"either ssl_ca_path or ssl_ca_file. Is any of them "14985"present in "14986"the .conf file?",14987ssl_error());14988return 0;14989}14990}1499114992if (1 == mg_atomic_inc(p_reload_lock)) {14993if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)14994== 0) {14995return 0;14996}14997*p_reload_lock = 0;14998}14999}15000/* lock while cert is reloading */15001while (*p_reload_lock) {15002sleep(1);15003}1500415005return 1;15006}1500715008#if defined(OPENSSL_API_1_1)15009#else15010static pthread_mutex_t *ssl_mutexes;15011#endif /* OPENSSL_API_1_1 */1501215013static int15014sslize(struct mg_connection *conn,15015SSL_CTX *s,15016int (*func)(SSL *),15017volatile int *stop_server)15018{15019int ret, err;15020int short_trust;15021unsigned i;1502215023if (!conn) {15024return 0;15025}1502615027short_trust =15028(conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)15029&& (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);1503015031if (short_trust) {15032int trust_ret = refresh_trust(conn);15033if (!trust_ret) {15034return trust_ret;15035}15036}1503715038conn->ssl = SSL_new(s);15039if (conn->ssl == NULL) {15040return 0;15041}15042SSL_set_app_data(conn->ssl, (char *)conn);1504315044ret = SSL_set_fd(conn->ssl, conn->client.sock);15045if (ret != 1) {15046err = SSL_get_error(conn->ssl, ret);15047mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);15048SSL_free(conn->ssl);15049conn->ssl = NULL;15050/* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:15051* https://wiki.openssl.org/index.php/Talk:Library_Initialization */15052#if !defined(OPENSSL_API_1_1)15053ERR_remove_state(0);15054#endif15055return 0;15056}1505715058/* SSL functions may fail and require to be called again:15059* see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html15060* Here "func" could be SSL_connect or SSL_accept. */15061for (i = 16; i <= 1024; i *= 2) {15062ret = func(conn->ssl);15063if (ret != 1) {15064err = SSL_get_error(conn->ssl, ret);15065if ((err == SSL_ERROR_WANT_CONNECT)15066|| (err == SSL_ERROR_WANT_ACCEPT)15067|| (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)15068|| (err == SSL_ERROR_WANT_X509_LOOKUP)) {15069/* Need to retry the function call "later".15070* See https://linux.die.net/man/3/ssl_get_error15071* This is typical for non-blocking sockets. */15072if (*stop_server) {15073/* Don't wait if the server is going to be stopped. */15074break;15075}15076mg_sleep(i);1507715078} else if (err == SSL_ERROR_SYSCALL) {15079/* This is an IO error. Look at errno. */15080err = errno;15081mg_cry_internal(conn, "SSL syscall error %i", err);15082break;1508315084} else {15085/* This is an SSL specific error, e.g. SSL_ERROR_SSL */15086mg_cry_internal(conn, "sslize error: %s", ssl_error());15087break;15088}1508915090} else {15091/* success */15092break;15093}15094}1509515096if (ret != 1) {15097SSL_free(conn->ssl);15098conn->ssl = NULL;15099/* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:15100* https://wiki.openssl.org/index.php/Talk:Library_Initialization */15101#if !defined(OPENSSL_API_1_1)15102ERR_remove_state(0);15103#endif15104return 0;15105}1510615107return 1;15108}151091511015111/* Return OpenSSL error message (from CRYPTO lib) */15112static const char *15113ssl_error(void)15114{15115unsigned long err;15116err = ERR_get_error();15117return ((err == 0) ? "" : ERR_error_string(err, NULL));15118}151191512015121static int15122hexdump2string(void *mem, int memlen, char *buf, int buflen)15123{15124int i;15125const char hexdigit[] = "0123456789abcdef";1512615127if ((memlen <= 0) || (buflen <= 0)) {15128return 0;15129}15130if (buflen < (3 * memlen)) {15131return 0;15132}1513315134for (i = 0; i < memlen; i++) {15135if (i > 0) {15136buf[3 * i - 1] = ' ';15137}15138buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];15139buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];15140}15141buf[3 * memlen - 1] = 0;1514215143return 1;15144}151451514615147static void15148ssl_get_client_cert_info(struct mg_connection *conn)15149{15150X509 *cert = SSL_get_peer_certificate(conn->ssl);15151if (cert) {15152char str_subject[1024];15153char str_issuer[1024];15154char str_finger[1024];15155unsigned char buf[256];15156char *str_serial = NULL;15157unsigned int ulen;15158int ilen;15159unsigned char *tmp_buf;15160unsigned char *tmp_p;1516115162/* Handle to algorithm used for fingerprint */15163const EVP_MD *digest = EVP_get_digestbyname("sha1");1516415165/* Get Subject and issuer */15166X509_NAME *subj = X509_get_subject_name(cert);15167X509_NAME *iss = X509_get_issuer_name(cert);1516815169/* Get serial number */15170ASN1_INTEGER *serial = X509_get_serialNumber(cert);1517115172/* Translate serial number to a hex string */15173BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);15174str_serial = BN_bn2hex(serial_bn);15175BN_free(serial_bn);1517615177/* Translate subject and issuer to a string */15178(void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));15179(void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));1518015181/* Calculate SHA1 fingerprint and store as a hex string */15182ulen = 0;1518315184/* ASN1_digest is deprecated. Do the calculation manually,15185* using EVP_Digest. */15186ilen = i2d_X509(cert, NULL);15187tmp_buf = (ilen > 0)15188? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,15189conn->phys_ctx)15190: NULL;15191if (tmp_buf) {15192tmp_p = tmp_buf;15193(void)i2d_X509(cert, &tmp_p);15194if (!EVP_Digest(15195tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {15196ulen = 0;15197}15198mg_free(tmp_buf);15199}1520015201if (!hexdump2string(15202buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {15203*str_finger = 0;15204}1520515206conn->request_info.client_cert = (struct mg_client_cert *)15207mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);15208if (conn->request_info.client_cert) {15209conn->request_info.client_cert->peer_cert = (void *)cert;15210conn->request_info.client_cert->subject =15211mg_strdup_ctx(str_subject, conn->phys_ctx);15212conn->request_info.client_cert->issuer =15213mg_strdup_ctx(str_issuer, conn->phys_ctx);15214conn->request_info.client_cert->serial =15215mg_strdup_ctx(str_serial, conn->phys_ctx);15216conn->request_info.client_cert->finger =15217mg_strdup_ctx(str_finger, conn->phys_ctx);15218} else {15219mg_cry_internal(conn,15220"%s",15221"Out of memory: Cannot allocate memory for client "15222"certificate");15223}1522415225/* Strings returned from bn_bn2hex must be freed using OPENSSL_free,15226* see https://linux.die.net/man/3/bn_bn2hex */15227OPENSSL_free(str_serial);15228}15229}152301523115232#if defined(OPENSSL_API_1_1)15233#else15234static void15235ssl_locking_callback(int mode, int mutex_num, const char *file, int line)15236{15237(void)line;15238(void)file;1523915240if (mode & 1) {15241/* 1 is CRYPTO_LOCK */15242(void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);15243} else {15244(void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);15245}15246}15247#endif /* OPENSSL_API_1_1 */152481524915250#if !defined(NO_SSL_DL)15251static void *15252load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)15253{15254union {15255void *p;15256void (*fp)(void);15257} u;15258void *dll_handle;15259struct ssl_func *fp;15260int ok;15261int truncated = 0;1526215263if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {15264mg_snprintf(NULL,15265NULL, /* No truncation check for ebuf */15266ebuf,15267ebuf_len,15268"%s: cannot load %s",15269__func__,15270dll_name);15271return NULL;15272}1527315274ok = 1;15275for (fp = sw; fp->name != NULL; fp++) {15276#if defined(_WIN32)15277/* GetProcAddress() returns pointer to function */15278u.fp = (void (*)(void))dlsym(dll_handle, fp->name);15279#else15280/* dlsym() on UNIX returns void *. ISO C forbids casts of data15281* pointers to function pointers. We need to use a union to make a15282* cast. */15283u.p = dlsym(dll_handle, fp->name);15284#endif /* _WIN32 */15285if (u.fp == NULL) {15286if (ok) {15287mg_snprintf(NULL,15288&truncated,15289ebuf,15290ebuf_len,15291"%s: %s: cannot find %s",15292__func__,15293dll_name,15294fp->name);15295ok = 0;15296} else {15297size_t cur_len = strlen(ebuf);15298if (!truncated) {15299mg_snprintf(NULL,15300&truncated,15301ebuf + cur_len,15302ebuf_len - cur_len - 3,15303", %s",15304fp->name);15305if (truncated) {15306/* If truncated, add "..." */15307strcat(ebuf, "...");15308}15309}15310}15311/* Debug:15312* printf("Missing function: %s\n", fp->name); */15313} else {15314fp->ptr = u.fp;15315}15316}1531715318if (!ok) {15319(void)dlclose(dll_handle);15320return NULL;15321}1532215323return dll_handle;15324}153251532615327static void *ssllib_dll_handle; /* Store the ssl library handle. */15328static void *cryptolib_dll_handle; /* Store the crypto library handle. */1532915330#endif /* NO_SSL_DL */153311533215333#if defined(SSL_ALREADY_INITIALIZED)15334static int cryptolib_users = 1; /* Reference counter for crypto library. */15335#else15336static int cryptolib_users = 0; /* Reference counter for crypto library. */15337#endif153381533915340static int15341initialize_ssl(char *ebuf, size_t ebuf_len)15342{15343#if defined(OPENSSL_API_1_1)15344if (ebuf_len > 0) {15345ebuf[0] = 0;15346}1534715348#if !defined(NO_SSL_DL)15349if (!cryptolib_dll_handle) {15350cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);15351if (!cryptolib_dll_handle) {15352mg_snprintf(NULL,15353NULL, /* No truncation check for ebuf */15354ebuf,15355ebuf_len,15356"%s: error loading library %s",15357__func__,15358CRYPTO_LIB);15359DEBUG_TRACE("%s", ebuf);15360return 0;15361}15362}15363#endif /* NO_SSL_DL */1536415365if (mg_atomic_inc(&cryptolib_users) > 1) {15366return 1;15367}1536815369#else /* not OPENSSL_API_1_1 */15370int i, num_locks;15371size_t size;1537215373if (ebuf_len > 0) {15374ebuf[0] = 0;15375}1537615377#if !defined(NO_SSL_DL)15378if (!cryptolib_dll_handle) {15379cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);15380if (!cryptolib_dll_handle) {15381mg_snprintf(NULL,15382NULL, /* No truncation check for ebuf */15383ebuf,15384ebuf_len,15385"%s: error loading library %s",15386__func__,15387CRYPTO_LIB);15388DEBUG_TRACE("%s", ebuf);15389return 0;15390}15391}15392#endif /* NO_SSL_DL */1539315394if (mg_atomic_inc(&cryptolib_users) > 1) {15395return 1;15396}1539715398/* Initialize locking callbacks, needed for thread safety.15399* http://www.openssl.org/support/faq.html#PROG115400*/15401num_locks = CRYPTO_num_locks();15402if (num_locks < 0) {15403num_locks = 0;15404}15405size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));1540615407/* allocate mutex array, if required */15408if (num_locks == 0) {15409/* No mutex array required */15410ssl_mutexes = NULL;15411} else {15412/* Mutex array required - allocate it */15413ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);1541415415/* Check OOM */15416if (ssl_mutexes == NULL) {15417mg_snprintf(NULL,15418NULL, /* No truncation check for ebuf */15419ebuf,15420ebuf_len,15421"%s: cannot allocate mutexes: %s",15422__func__,15423ssl_error());15424DEBUG_TRACE("%s", ebuf);15425return 0;15426}1542715428/* initialize mutex array */15429for (i = 0; i < num_locks; i++) {15430if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {15431mg_snprintf(NULL,15432NULL, /* No truncation check for ebuf */15433ebuf,15434ebuf_len,15435"%s: error initializing mutex %i of %i",15436__func__,15437i,15438num_locks);15439DEBUG_TRACE("%s", ebuf);15440mg_free(ssl_mutexes);15441return 0;15442}15443}15444}1544515446CRYPTO_set_locking_callback(&ssl_locking_callback);15447CRYPTO_set_id_callback(&mg_current_thread_id);15448#endif /* OPENSSL_API_1_1 */1544915450#if !defined(NO_SSL_DL)15451if (!ssllib_dll_handle) {15452ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);15453if (!ssllib_dll_handle) {15454#if !defined(OPENSSL_API_1_1)15455mg_free(ssl_mutexes);15456#endif15457DEBUG_TRACE("%s", ebuf);15458return 0;15459}15460}15461#endif /* NO_SSL_DL */1546215463#if defined(OPENSSL_API_1_1)15464/* Initialize SSL library */15465OPENSSL_init_ssl(0, NULL);15466OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS15467| OPENSSL_INIT_LOAD_CRYPTO_STRINGS,15468NULL);15469#else15470/* Initialize SSL library */15471SSL_library_init();15472SSL_load_error_strings();15473#endif1547415475return 1;15476}154771547815479static int15480ssl_use_pem_file(struct mg_context *phys_ctx,15481struct mg_domain_context *dom_ctx,15482const char *pem,15483const char *chain)15484{15485if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {15486mg_cry_internal(fc(phys_ctx),15487"%s: cannot open certificate file %s: %s",15488__func__,15489pem,15490ssl_error());15491return 0;15492}1549315494/* could use SSL_CTX_set_default_passwd_cb_userdata */15495if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {15496mg_cry_internal(fc(phys_ctx),15497"%s: cannot open private key file %s: %s",15498__func__,15499pem,15500ssl_error());15501return 0;15502}1550315504if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {15505mg_cry_internal(fc(phys_ctx),15506"%s: certificate and private key do not match: %s",15507__func__,15508pem);15509return 0;15510}1551115512/* In contrast to OpenSSL, wolfSSL does not support certificate15513* chain files that contain private keys and certificates in15514* SSL_CTX_use_certificate_chain_file.15515* The CivetWeb-Server used pem-Files that contained both information.15516* In order to make wolfSSL work, it is split in two files.15517* One file that contains key and certificate used by the server and15518* an optional chain file for the ssl stack.15519*/15520if (chain) {15521if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {15522mg_cry_internal(fc(phys_ctx),15523"%s: cannot use certificate chain file %s: %s",15524__func__,15525pem,15526ssl_error());15527return 0;15528}15529}15530return 1;15531}155321553315534#if defined(OPENSSL_API_1_1)15535static unsigned long15536ssl_get_protocol(int version_id)15537{15538long unsigned ret = (long unsigned)SSL_OP_ALL;15539if (version_id > 0)15540ret |= SSL_OP_NO_SSLv2;15541if (version_id > 1)15542ret |= SSL_OP_NO_SSLv3;15543if (version_id > 2)15544ret |= SSL_OP_NO_TLSv1;15545if (version_id > 3)15546ret |= SSL_OP_NO_TLSv1_1;15547return ret;15548}15549#else15550static long15551ssl_get_protocol(int version_id)15552{15553long ret = (long)SSL_OP_ALL;15554if (version_id > 0)15555ret |= SSL_OP_NO_SSLv2;15556if (version_id > 1)15557ret |= SSL_OP_NO_SSLv3;15558if (version_id > 2)15559ret |= SSL_OP_NO_TLSv1;15560if (version_id > 3)15561ret |= SSL_OP_NO_TLSv1_1;15562return ret;15563}15564#endif /* OPENSSL_API_1_1 */155651556615567/* SSL callback documentation:15568* https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html15569* https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)15570* https://linux.die.net/man/3/ssl_set_info_callback */15571/* Note: There is no "const" for the first argument in the documentation,15572* however some (maybe most, but not all) headers of OpenSSL versions /15573* OpenSSL compatibility layers have it. Having a different definition15574* will cause a warning in C and an error in C++. With inconsitent15575* definitions of this function, having a warning in one version or15576* another is unavoidable. */15577static void15578ssl_info_callback(SSL *ssl, int what, int ret)15579{15580(void)ret;1558115582if (what & SSL_CB_HANDSHAKE_START) {15583SSL_get_app_data(ssl);15584}15585if (what & SSL_CB_HANDSHAKE_DONE) {15586/* TODO: check for openSSL 1.1 */15587//#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x000115588// ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;15589}15590}155911559215593static int15594ssl_servername_callback(SSL *ssl, int *ad, void *arg)15595{15596struct mg_context *ctx = (struct mg_context *)arg;15597struct mg_domain_context *dom =15598(struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;1559915600#if defined(GCC_DIAGNOSTIC)15601#pragma GCC diagnostic push15602#pragma GCC diagnostic ignored "-Wcast-align"15603#endif /* defined(GCC_DIAGNOSTIC) */1560415605/* We used an aligned pointer in SSL_set_app_data */15606struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);1560715608#if defined(GCC_DIAGNOSTIC)15609#pragma GCC diagnostic pop15610#endif /* defined(GCC_DIAGNOSTIC) */1561115612const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);1561315614(void)ad;1561515616if ((ctx == NULL) || (conn->phys_ctx == ctx)) {15617DEBUG_TRACE("%s", "internal error - assertion failed");15618return SSL_TLSEXT_ERR_NOACK;15619}1562015621/* Old clients (Win XP) will not support SNI. Then, there15622* is no server name available in the request - we can15623* only work with the default certificate.15624* Multiple HTTPS hosts on one IP+port are only possible15625* with a certificate containing all alternative names.15626*/15627if ((servername == NULL) || (*servername == 0)) {15628DEBUG_TRACE("%s", "SSL connection not supporting SNI");15629conn->dom_ctx = &(ctx->dd);15630SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);15631return SSL_TLSEXT_ERR_NOACK;15632}1563315634DEBUG_TRACE("TLS connection to host %s", servername);1563515636while (dom) {15637if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {1563815639/* Found matching domain */15640DEBUG_TRACE("TLS domain %s found",15641dom->config[AUTHENTICATION_DOMAIN]);15642SSL_set_SSL_CTX(ssl, dom->ssl_ctx);15643conn->dom_ctx = dom;15644return SSL_TLSEXT_ERR_OK;15645}15646dom = dom->next;15647}1564815649/* Default domain */15650DEBUG_TRACE("TLS default domain %s used",15651ctx->dd.config[AUTHENTICATION_DOMAIN]);15652conn->dom_ctx = &(ctx->dd);15653SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);15654return SSL_TLSEXT_ERR_OK;15655}156561565715658/* Setup SSL CTX as required by CivetWeb */15659static int15660init_ssl_ctx_impl(struct mg_context *phys_ctx,15661struct mg_domain_context *dom_ctx,15662const char *pem,15663const char *chain)15664{15665int callback_ret;15666int should_verify_peer;15667int peer_certificate_optional;15668const char *ca_path;15669const char *ca_file;15670int use_default_verify_paths;15671int verify_depth;15672struct timespec now_mt;15673md5_byte_t ssl_context_id[16];15674md5_state_t md5state;15675int protocol_ver;1567615677#if defined(OPENSSL_API_1_1)15678if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {15679mg_cry_internal(fc(phys_ctx),15680"SSL_CTX_new (server) error: %s",15681ssl_error());15682return 0;15683}15684#else15685if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {15686mg_cry_internal(fc(phys_ctx),15687"SSL_CTX_new (server) error: %s",15688ssl_error());15689return 0;15690}15691#endif /* OPENSSL_API_1_1 */1569215693SSL_CTX_clear_options(dom_ctx->ssl_ctx,15694SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv115695| SSL_OP_NO_TLSv1_1);15696protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);15697SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));15698SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);15699SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);15700SSL_CTX_set_options(dom_ctx->ssl_ctx,15701SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);15702SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);15703#if !defined(NO_SSL_DL)15704SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);15705#endif /* NO_SSL_DL */1570615707#if defined(__clang__)15708#pragma clang diagnostic push15709#pragma clang diagnostic ignored "-Wincompatible-pointer-types"15710#endif15711#if defined(GCC_DIAGNOSTIC)15712#pragma GCC diagnostic push15713#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"15714#endif15715/* Depending on the OpenSSL version, the callback may be15716* 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'15717* yielding in an "incompatible-pointer-type" warning for the other15718* version. It seems to be "unclear" what is correct:15719* https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/114752615720* https://www.openssl.org/docs/man1.0.2/ssl/ssl.html15721* https://www.openssl.org/docs/man1.1.0/ssl/ssl.html15722* https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L117315723* Disable this warning here.15724* Alternative would be a version dependent ssl_info_callback and15725* a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.15726*/15727SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);157281572915730SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,15731ssl_servername_callback);15732SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);1573315734#if defined(GCC_DIAGNOSTIC)15735#pragma GCC diagnostic pop15736#endif15737#if defined(__clang__)15738#pragma clang diagnostic pop15739#endif1574015741/* If a callback has been specified, call it. */15742callback_ret = (phys_ctx->callbacks.init_ssl == NULL)15743? 015744: (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,15745phys_ctx->user_data));1574615747/* If callback returns 0, civetweb sets up the SSL certificate.15748* If it returns 1, civetweb assumes the calback already did this.15749* If it returns -1, initializing ssl fails. */15750if (callback_ret < 0) {15751mg_cry_internal(fc(phys_ctx),15752"SSL callback returned error: %i",15753callback_ret);15754return 0;15755}15756if (callback_ret > 0) {15757/* Callback did everything. */15758return 1;15759}1576015761/* Use some combination of start time, domain and port as a SSL15762* context ID. This should be unique on the current machine. */15763md5_init(&md5state);15764clock_gettime(CLOCK_MONOTONIC, &now_mt);15765md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));15766md5_append(&md5state,15767(const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],15768strlen(phys_ctx->dd.config[LISTENING_PORTS]));15769md5_append(&md5state,15770(const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],15771strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));15772md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));15773md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));15774md5_finish(&md5state, ssl_context_id);1577515776SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,15777(unsigned char *)ssl_context_id,15778sizeof(ssl_context_id));1577915780if (pem != NULL) {15781if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {15782return 0;15783}15784}1578515786/* Should we support client certificates? */15787/* Default is "no". */15788should_verify_peer = 0;15789peer_certificate_optional = 0;15790if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {15791if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {15792/* Yes, they are mandatory */15793should_verify_peer = 1;15794peer_certificate_optional = 0;15795} else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],15796"optional")15797== 0) {15798/* Yes, they are optional */15799should_verify_peer = 1;15800peer_certificate_optional = 1;15801}15802}1580315804use_default_verify_paths =15805(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)15806&& (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")15807== 0);1580815809if (should_verify_peer) {15810ca_path = dom_ctx->config[SSL_CA_PATH];15811ca_file = dom_ctx->config[SSL_CA_FILE];15812if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)15813!= 1) {15814mg_cry_internal(fc(phys_ctx),15815"SSL_CTX_load_verify_locations error: %s "15816"ssl_verify_peer requires setting "15817"either ssl_ca_path or ssl_ca_file. "15818"Is any of them present in the "15819".conf file?",15820ssl_error());15821return 0;15822}1582315824if (peer_certificate_optional) {15825SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);15826} else {15827SSL_CTX_set_verify(dom_ctx->ssl_ctx,15828SSL_VERIFY_PEER15829| SSL_VERIFY_FAIL_IF_NO_PEER_CERT,15830NULL);15831}1583215833if (use_default_verify_paths15834&& (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {15835mg_cry_internal(fc(phys_ctx),15836"SSL_CTX_set_default_verify_paths error: %s",15837ssl_error());15838return 0;15839}1584015841if (dom_ctx->config[SSL_VERIFY_DEPTH]) {15842verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);15843SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);15844}15845}1584615847if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {15848if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,15849dom_ctx->config[SSL_CIPHER_LIST])15850!= 1) {15851mg_cry_internal(fc(phys_ctx),15852"SSL_CTX_set_cipher_list error: %s",15853ssl_error());15854}15855}1585615857return 1;15858}158591586015861/* Check if SSL is required.15862* If so, dynamically load SSL library15863* and set up ctx->ssl_ctx pointer. */15864static int15865init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)15866{15867void *ssl_ctx = 0;15868int callback_ret;15869const char *pem;15870const char *chain;15871char ebuf[128];1587215873if (!phys_ctx) {15874return 0;15875}1587615877if (!dom_ctx) {15878dom_ctx = &(phys_ctx->dd);15879}1588015881if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {15882/* No SSL port is set. No need to setup SSL. */15883return 1;15884}1588515886/* Check for external SSL_CTX */15887callback_ret =15888(phys_ctx->callbacks.external_ssl_ctx == NULL)15889? 015890: (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,15891phys_ctx->user_data));1589215893if (callback_ret < 0) {15894mg_cry_internal(fc(phys_ctx),15895"external_ssl_ctx callback returned error: %i",15896callback_ret);15897return 0;15898} else if (callback_ret > 0) {15899dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;15900if (!initialize_ssl(ebuf, sizeof(ebuf))) {15901mg_cry_internal(fc(phys_ctx), "%s", ebuf);15902return 0;15903}15904return 1;15905}15906/* else: external_ssl_ctx does not exist or returns 0,15907* CivetWeb should continue initializing SSL */1590815909/* If PEM file is not specified and the init_ssl callback15910* is not specified, setup will fail. */15911if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)15912&& (phys_ctx->callbacks.init_ssl == NULL)) {15913/* No certificate and no callback:15914* Essential data to set up TLS is missing.15915*/15916mg_cry_internal(fc(phys_ctx),15917"Initializing SSL failed: -%s is not set",15918config_options[SSL_CERTIFICATE].name);15919return 0;15920}1592115922chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];15923if (chain == NULL) {15924chain = pem;15925}15926if ((chain != NULL) && (*chain == 0)) {15927chain = NULL;15928}1592915930if (!initialize_ssl(ebuf, sizeof(ebuf))) {15931mg_cry_internal(fc(phys_ctx), "%s", ebuf);15932return 0;15933}1593415935return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);15936}159371593815939static void15940uninitialize_ssl(void)15941{15942#if defined(OPENSSL_API_1_1)1594315944if (mg_atomic_dec(&cryptolib_users) == 0) {1594515946/* Shutdown according to15947* https://wiki.openssl.org/index.php/Library_Initialization#Cleanup15948* http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl15949*/15950CONF_modules_unload(1);15951#else15952int i;1595315954if (mg_atomic_dec(&cryptolib_users) == 0) {1595515956/* Shutdown according to15957* https://wiki.openssl.org/index.php/Library_Initialization#Cleanup15958* http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl15959*/15960CRYPTO_set_locking_callback(NULL);15961CRYPTO_set_id_callback(NULL);15962ENGINE_cleanup();15963CONF_modules_unload(1);15964ERR_free_strings();15965EVP_cleanup();15966CRYPTO_cleanup_all_ex_data();15967ERR_remove_state(0);1596815969for (i = 0; i < CRYPTO_num_locks(); i++) {15970pthread_mutex_destroy(&ssl_mutexes[i]);15971}15972mg_free(ssl_mutexes);15973ssl_mutexes = NULL;15974#endif /* OPENSSL_API_1_1 */15975}15976}15977#endif /* !NO_SSL */159781597915980static int15981set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)15982{15983if (phys_ctx) {15984struct mg_file file = STRUCT_FILE_INITIALIZER;15985const char *path;15986if (!dom_ctx) {15987dom_ctx = &(phys_ctx->dd);15988}15989path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];15990if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {15991mg_cry_internal(fc(phys_ctx),15992"Cannot open %s: %s",15993path,15994strerror(ERRNO));15995return 0;15996}15997return 1;15998}15999return 0;16000}160011600216003static int16004set_acl_option(struct mg_context *phys_ctx)16005{16006return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;16007}160081600916010static void16011reset_per_request_attributes(struct mg_connection *conn)16012{16013if (!conn) {16014return;16015}16016conn->connection_type =16017CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */1601816019conn->num_bytes_sent = conn->consumed_content = 0;1602016021conn->path_info = NULL;16022conn->status_code = -1;16023conn->content_len = -1;16024conn->is_chunked = 0;16025conn->must_close = 0;16026conn->request_len = 0;16027conn->throttle = 0;16028conn->data_len = 0;16029conn->chunk_remainder = 0;16030conn->accept_gzip = 0;1603116032conn->response_info.content_length = conn->request_info.content_length = -1;16033conn->response_info.http_version = conn->request_info.http_version = NULL;16034conn->response_info.num_headers = conn->request_info.num_headers = 0;16035conn->response_info.status_text = NULL;16036conn->response_info.status_code = 0;1603716038conn->request_info.remote_user = NULL;16039conn->request_info.request_method = NULL;16040conn->request_info.request_uri = NULL;16041conn->request_info.local_uri = NULL;1604216043#if defined(MG_LEGACY_INTERFACE)16044/* Legacy before split into local_uri and request_uri */16045conn->request_info.uri = NULL;16046#endif16047}160481604916050#if 016051/* Note: set_sock_timeout is not required for non-blocking sockets.16052* Leave this function here (commented out) for reference until16053* CivetWeb 1.9 is tested, and the tests confirme this function is16054* no longer required.16055*/16056static int16057set_sock_timeout(SOCKET sock, int milliseconds)16058{16059int r0 = 0, r1, r2;1606016061#if defined(_WIN32)16062/* Windows specific */1606316064DWORD tv = (DWORD)milliseconds;1606516066#else16067/* Linux, ... (not Windows) */1606816069struct timeval tv;1607016071/* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):16072* max. time waiting for the acknowledged of TCP data before the connection16073* will be forcefully closed and ETIMEDOUT is returned to the application.16074* If this option is not set, the default timeout of 20-30 minutes is used.16075*/16076/* #define TCP_USER_TIMEOUT (18) */1607716078#if defined(TCP_USER_TIMEOUT)16079unsigned int uto = (unsigned int)milliseconds;16080r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));16081#endif1608216083memset(&tv, 0, sizeof(tv));16084tv.tv_sec = milliseconds / 1000;16085tv.tv_usec = (milliseconds * 1000) % 1000000;1608616087#endif /* _WIN32 */1608816089r1 = setsockopt(16090sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));16091r2 = setsockopt(16092sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));1609316094return r0 || r1 || r2;16095}16096#endif160971609816099static int16100set_tcp_nodelay(SOCKET sock, int nodelay_on)16101{16102if (setsockopt(sock,16103IPPROTO_TCP,16104TCP_NODELAY,16105(SOCK_OPT_TYPE)&nodelay_on,16106sizeof(nodelay_on))16107!= 0) {16108/* Error */16109return 1;16110}16111/* OK */16112return 0;16113}161141611516116static void16117close_socket_gracefully(struct mg_connection *conn)16118{16119#if defined(_WIN32)16120char buf[MG_BUF_LEN];16121int n;16122#endif16123struct linger linger;16124int error_code = 0;16125int linger_timeout = -2;16126socklen_t opt_len = sizeof(error_code);1612716128if (!conn) {16129return;16130}1613116132/* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:16133* "Note that enabling a nonzero timeout on a nonblocking socket16134* is not recommended.", so set it to blocking now */16135set_blocking_mode(conn->client.sock);1613616137/* Send FIN to the client */16138shutdown(conn->client.sock, SHUTDOWN_WR);161391614016141#if defined(_WIN32)16142/* Read and discard pending incoming data. If we do not do that and16143* close16144* the socket, the data in the send buffer may be discarded. This16145* behaviour is seen on Windows, when client keeps sending data16146* when server decides to close the connection; then when client16147* does recv() it gets no data back. */16148do {16149n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);16150} while (n > 0);16151#endif1615216153if (conn->dom_ctx->config[LINGER_TIMEOUT]) {16154linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);16155}1615616157/* Set linger option according to configuration */16158if (linger_timeout >= 0) {16159/* Set linger option to avoid socket hanging out after close. This16160* prevent ephemeral port exhaust problem under high QPS. */16161linger.l_onoff = 1;1616216163#if defined(_MSC_VER)16164#pragma warning(push)16165#pragma warning(disable : 4244)16166#endif16167#if defined(GCC_DIAGNOSTIC)16168#pragma GCC diagnostic push16169#pragma GCC diagnostic ignored "-Wconversion"16170#endif16171/* Data type of linger structure elements may differ,16172* so we don't know what cast we need here.16173* Disable type conversion warnings. */1617416175linger.l_linger = (linger_timeout + 999) / 1000;1617616177#if defined(GCC_DIAGNOSTIC)16178#pragma GCC diagnostic pop16179#endif16180#if defined(_MSC_VER)16181#pragma warning(pop)16182#endif1618316184} else {16185linger.l_onoff = 0;16186linger.l_linger = 0;16187}1618816189if (linger_timeout < -1) {16190/* Default: don't configure any linger */16191} else if (getsockopt(conn->client.sock,16192SOL_SOCKET,16193SO_ERROR,16194#if defined(_WIN32) /* WinSock uses different data type here */16195(char *)&error_code,16196#else16197&error_code,16198#endif16199&opt_len)16200!= 0) {16201/* Cannot determine if socket is already closed. This should16202* not occur and never did in a test. Log an error message16203* and continue. */16204mg_cry_internal(conn,16205"%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",16206__func__,16207strerror(ERRNO));16208} else if (error_code == ECONNRESET) {16209/* Socket already closed by client/peer, close socket without linger16210*/16211} else {1621216213/* Set linger timeout */16214if (setsockopt(conn->client.sock,16215SOL_SOCKET,16216SO_LINGER,16217(char *)&linger,16218sizeof(linger))16219!= 0) {16220mg_cry_internal(16221conn,16222"%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",16223__func__,16224linger.l_onoff,16225linger.l_linger,16226strerror(ERRNO));16227}16228}1622916230/* Now we know that our FIN is ACK-ed, safe to close */16231closesocket(conn->client.sock);16232conn->client.sock = INVALID_SOCKET;16233}162341623516236static void16237close_connection(struct mg_connection *conn)16238{16239#if defined(USE_SERVER_STATS)16240conn->conn_state = 6; /* to close */16241#endif1624216243#if defined(USE_LUA) && defined(USE_WEBSOCKET)16244if (conn->lua_websocket_state) {16245lua_websocket_close(conn, conn->lua_websocket_state);16246conn->lua_websocket_state = NULL;16247}16248#endif1624916250mg_lock_connection(conn);1625116252/* Set close flag, so keep-alive loops will stop */16253conn->must_close = 1;1625416255/* call the connection_close callback if assigned */16256if (conn->phys_ctx->callbacks.connection_close != NULL) {16257if (conn->phys_ctx->context_type == CONTEXT_SERVER) {16258conn->phys_ctx->callbacks.connection_close(conn);16259}16260}1626116262/* Reset user data, after close callback is called.16263* Do not reuse it. If the user needs a destructor,16264* it must be done in the connection_close callback. */16265mg_set_user_connection_data(conn, NULL);162661626716268#if defined(USE_SERVER_STATS)16269conn->conn_state = 7; /* closing */16270#endif1627116272#if !defined(NO_SSL)16273if (conn->ssl != NULL) {16274/* Run SSL_shutdown twice to ensure completely close SSL connection16275*/16276SSL_shutdown(conn->ssl);16277SSL_free(conn->ssl);16278/* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:16279* https://wiki.openssl.org/index.php/Talk:Library_Initialization */16280#if !defined(OPENSSL_API_1_1)16281ERR_remove_state(0);16282#endif16283conn->ssl = NULL;16284}16285#endif16286if (conn->client.sock != INVALID_SOCKET) {16287close_socket_gracefully(conn);16288conn->client.sock = INVALID_SOCKET;16289}1629016291if (conn->host) {16292mg_free((void *)conn->host);16293conn->host = NULL;16294}1629516296mg_unlock_connection(conn);1629716298#if defined(USE_SERVER_STATS)16299conn->conn_state = 8; /* closed */16300#endif16301}163021630316304void16305mg_close_connection(struct mg_connection *conn)16306{16307#if defined(USE_WEBSOCKET)16308struct mg_context *client_ctx = NULL;16309#endif /* defined(USE_WEBSOCKET) */1631016311if ((conn == NULL) || (conn->phys_ctx == NULL)) {16312return;16313}1631416315#if defined(USE_WEBSOCKET)16316if (conn->phys_ctx->context_type == CONTEXT_SERVER) {16317if (conn->in_websocket_handling) {16318/* Set close flag, so the server thread can exit. */16319conn->must_close = 1;16320return;16321}16322}16323if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {1632416325unsigned int i;1632616327/* ws/wss client */16328client_ctx = conn->phys_ctx;1632916330/* client context: loops must end */16331client_ctx->stop_flag = 1;16332conn->must_close = 1;1633316334/* We need to get the client thread out of the select/recv call16335* here. */16336/* Since we use a sleep quantum of some seconds to check for recv16337* timeouts, we will just wait a few seconds in mg_join_thread. */1633816339/* join worker thread */16340for (i = 0; i < client_ctx->cfg_worker_threads; i++) {16341if (client_ctx->worker_threadids[i] != 0) {16342mg_join_thread(client_ctx->worker_threadids[i]);16343}16344}16345}16346#endif /* defined(USE_WEBSOCKET) */1634716348close_connection(conn);1634916350#if !defined(NO_SSL)16351if (conn->client_ssl_ctx != NULL) {16352SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);16353}16354#endif1635516356#if defined(USE_WEBSOCKET)16357if (client_ctx != NULL) {16358/* free context */16359mg_free(client_ctx->worker_threadids);16360mg_free(client_ctx);16361(void)pthread_mutex_destroy(&conn->mutex);16362mg_free(conn);16363} else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {16364mg_free(conn);16365}16366#else16367if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */16368mg_free(conn);16369}16370#endif /* defined(USE_WEBSOCKET) */16371}163721637316374/* Only for memory statistics */16375static struct mg_context common_client_context;163761637716378static struct mg_connection *16379mg_connect_client_impl(const struct mg_client_options *client_options,16380int use_ssl,16381char *ebuf,16382size_t ebuf_len)16383{16384struct mg_connection *conn = NULL;16385SOCKET sock;16386union usa sa;16387struct sockaddr *psa;16388socklen_t len;1638916390unsigned max_req_size =16391(unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);1639216393/* Size of structures, aligned to 8 bytes */16394size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;16395size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;1639616397conn = (struct mg_connection *)mg_calloc_ctx(163981, conn_size + ctx_size + max_req_size, &common_client_context);1639916400if (conn == NULL) {16401mg_snprintf(NULL,16402NULL, /* No truncation check for ebuf */16403ebuf,16404ebuf_len,16405"calloc(): %s",16406strerror(ERRNO));16407return NULL;16408}1640916410#if defined(GCC_DIAGNOSTIC)16411#pragma GCC diagnostic push16412#pragma GCC diagnostic ignored "-Wcast-align"16413#endif /* defined(GCC_DIAGNOSTIC) */16414/* conn_size is aligned to 8 bytes */1641516416conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);1641716418#if defined(GCC_DIAGNOSTIC)16419#pragma GCC diagnostic pop16420#endif /* defined(GCC_DIAGNOSTIC) */1642116422conn->buf = (((char *)conn) + conn_size + ctx_size);16423conn->buf_size = (int)max_req_size;16424conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;16425conn->dom_ctx = &(conn->phys_ctx->dd);1642616427if (!connect_socket(&common_client_context,16428client_options->host,16429client_options->port,16430use_ssl,16431ebuf,16432ebuf_len,16433&sock,16434&sa)) {16435/* ebuf is set by connect_socket,16436* free all memory and return NULL; */16437mg_free(conn);16438return NULL;16439}1644016441#if !defined(NO_SSL)16442#if defined(OPENSSL_API_1_1)16443if (use_ssl16444&& (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {16445mg_snprintf(NULL,16446NULL, /* No truncation check for ebuf */16447ebuf,16448ebuf_len,16449"SSL_CTX_new error");16450closesocket(sock);16451mg_free(conn);16452return NULL;16453}16454#else16455if (use_ssl16456&& (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))16457== NULL) {16458mg_snprintf(NULL,16459NULL, /* No truncation check for ebuf */16460ebuf,16461ebuf_len,16462"SSL_CTX_new error");16463closesocket(sock);16464mg_free(conn);16465return NULL;16466}16467#endif /* OPENSSL_API_1_1 */16468#endif /* NO_SSL */164691647016471#if defined(USE_IPV6)16472len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)16473: sizeof(conn->client.rsa.sin6);16474psa = (sa.sa.sa_family == AF_INET)16475? (struct sockaddr *)&(conn->client.rsa.sin)16476: (struct sockaddr *)&(conn->client.rsa.sin6);16477#else16478len = sizeof(conn->client.rsa.sin);16479psa = (struct sockaddr *)&(conn->client.rsa.sin);16480#endif1648116482conn->client.sock = sock;16483conn->client.lsa = sa;1648416485if (getsockname(sock, psa, &len) != 0) {16486mg_cry_internal(conn,16487"%s: getsockname() failed: %s",16488__func__,16489strerror(ERRNO));16490}1649116492conn->client.is_ssl = use_ssl ? 1 : 0;16493if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {16494mg_snprintf(NULL,16495NULL, /* No truncation check for ebuf */16496ebuf,16497ebuf_len,16498"Can not create mutex");16499#if !defined(NO_SSL)16500SSL_CTX_free(conn->client_ssl_ctx);16501#endif16502closesocket(sock);16503mg_free(conn);16504return NULL;16505}165061650716508#if !defined(NO_SSL)16509if (use_ssl) {16510common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;1651116512/* TODO: Check ssl_verify_peer and ssl_ca_path here.16513* SSL_CTX_set_verify call is needed to switch off server16514* certificate checking, which is off by default in OpenSSL and16515* on in yaSSL. */16516/* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,16517* SSL_VERIFY_PEER, verify_ssl_server); */1651816519if (client_options->client_cert) {16520if (!ssl_use_pem_file(&common_client_context,16521&(common_client_context.dd),16522client_options->client_cert,16523NULL)) {16524mg_snprintf(NULL,16525NULL, /* No truncation check for ebuf */16526ebuf,16527ebuf_len,16528"Can not use SSL client certificate");16529SSL_CTX_free(conn->client_ssl_ctx);16530closesocket(sock);16531mg_free(conn);16532return NULL;16533}16534}1653516536if (client_options->server_cert) {16537SSL_CTX_load_verify_locations(conn->client_ssl_ctx,16538client_options->server_cert,16539NULL);16540SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);16541} else {16542SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);16543}1654416545if (!sslize(conn,16546conn->client_ssl_ctx,16547SSL_connect,16548&(conn->phys_ctx->stop_flag))) {16549mg_snprintf(NULL,16550NULL, /* No truncation check for ebuf */16551ebuf,16552ebuf_len,16553"SSL connection error");16554SSL_CTX_free(conn->client_ssl_ctx);16555closesocket(sock);16556mg_free(conn);16557return NULL;16558}16559}16560#endif1656116562if (0 != set_non_blocking_mode(sock)) {16563mg_cry_internal(conn,16564"Cannot set non-blocking mode for client %s:%i",16565client_options->host,16566client_options->port);16567}1656816569return conn;16570}165711657216573CIVETWEB_API struct mg_connection *16574mg_connect_client_secure(const struct mg_client_options *client_options,16575char *error_buffer,16576size_t error_buffer_size)16577{16578return mg_connect_client_impl(client_options,165791,16580error_buffer,16581error_buffer_size);16582}165831658416585struct mg_connection *16586mg_connect_client(const char *host,16587int port,16588int use_ssl,16589char *error_buffer,16590size_t error_buffer_size)16591{16592struct mg_client_options opts;16593memset(&opts, 0, sizeof(opts));16594opts.host = host;16595opts.port = port;16596return mg_connect_client_impl(&opts,16597use_ssl,16598error_buffer,16599error_buffer_size);16600}166011660216603static const struct {16604const char *proto;16605size_t proto_len;16606unsigned default_port;16607} abs_uri_protocols[] = {{"http://", 7, 80},16608{"https://", 8, 443},16609{"ws://", 5, 80},16610{"wss://", 6, 443},16611{NULL, 0, 0}};166121661316614/* Check if the uri is valid.16615* return 0 for invalid uri,16616* return 1 for *,16617* return 2 for relative uri,16618* return 3 for absolute uri without port,16619* return 4 for absolute uri with port */16620static int16621get_uri_type(const char *uri)16622{16623int i;16624const char *hostend, *portbegin;16625char *portend;16626unsigned long port;1662716628/* According to the HTTP standard16629* http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.216630* URI can be an asterisk (*) or should start with slash (relative uri),16631* or it should start with the protocol (absolute uri). */16632if ((uri[0] == '*') && (uri[1] == '\0')) {16633/* asterisk */16634return 1;16635}1663616637/* Valid URIs according to RFC 398616638* (https://www.ietf.org/rfc/rfc3986.txt)16639* must only contain reserved characters :/?#[]@!$&'()*+,;=16640* and unreserved characters A-Z a-z 0-9 and -._~16641* and % encoded symbols.16642*/16643for (i = 0; uri[i] != 0; i++) {16644if (uri[i] < 33) {16645/* control characters and spaces are invalid */16646return 0;16647}16648if (uri[i] > 126) {16649/* non-ascii characters must be % encoded */16650return 0;16651} else {16652switch (uri[i]) {16653case '"': /* 34 */16654case '<': /* 60 */16655case '>': /* 62 */16656case '\\': /* 92 */16657case '^': /* 94 */16658case '`': /* 96 */16659case '{': /* 123 */16660case '|': /* 124 */16661case '}': /* 125 */16662return 0;16663default:16664/* character is ok */16665break;16666}16667}16668}1666916670/* A relative uri starts with a / character */16671if (uri[0] == '/') {16672/* relative uri */16673return 2;16674}1667516676/* It could be an absolute uri: */16677/* This function only checks if the uri is valid, not if it is16678* addressing the current server. So civetweb can also be used16679* as a proxy server. */16680for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {16681if (mg_strncasecmp(uri,16682abs_uri_protocols[i].proto,16683abs_uri_protocols[i].proto_len)16684== 0) {1668516686hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');16687if (!hostend) {16688return 0;16689}16690portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');16691if (!portbegin) {16692return 3;16693}1669416695port = strtoul(portbegin + 1, &portend, 10);16696if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {16697return 0;16698}1669916700return 4;16701}16702}1670316704return 0;16705}167061670716708/* Return NULL or the relative uri at the current server */16709static const char *16710get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)16711{16712const char *server_domain;16713size_t server_domain_len;16714size_t request_domain_len = 0;16715unsigned long port = 0;16716int i, auth_domain_check_enabled;16717const char *hostbegin = NULL;16718const char *hostend = NULL;16719const char *portbegin;16720char *portend;1672116722auth_domain_check_enabled =16723!mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");1672416725/* DNS is case insensitive, so use case insensitive string compare here16726*/16727for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {16728if (mg_strncasecmp(uri,16729abs_uri_protocols[i].proto,16730abs_uri_protocols[i].proto_len)16731== 0) {1673216733hostbegin = uri + abs_uri_protocols[i].proto_len;16734hostend = strchr(hostbegin, '/');16735if (!hostend) {16736return 0;16737}16738portbegin = strchr(hostbegin, ':');16739if ((!portbegin) || (portbegin > hostend)) {16740port = abs_uri_protocols[i].default_port;16741request_domain_len = (size_t)(hostend - hostbegin);16742} else {16743port = strtoul(portbegin + 1, &portend, 10);16744if ((portend != hostend) || (port <= 0)16745|| !is_valid_port(port)) {16746return 0;16747}16748request_domain_len = (size_t)(portbegin - hostbegin);16749}16750/* protocol found, port set */16751break;16752}16753}1675416755if (!port) {16756/* port remains 0 if the protocol is not found */16757return 0;16758}1675916760/* Check if the request is directed to a different server. */16761/* First check if the port is the same (IPv4 and IPv6). */16762#if defined(USE_IPV6)16763if (conn->client.lsa.sa.sa_family == AF_INET6) {16764if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {16765/* Request is directed to a different port */16766return 0;16767}16768} else16769#endif16770{16771if (ntohs(conn->client.lsa.sin.sin_port) != port) {16772/* Request is directed to a different port */16773return 0;16774}16775}1677616777/* Finally check if the server corresponds to the authentication16778* domain of the server (the server domain).16779* Allow full matches (like http://mydomain.com/path/file.ext), and16780* allow subdomain matches (like http://www.mydomain.com/path/file.ext),16781* but do not allow substrings (like16782* http://notmydomain.com/path/file.ext16783* or http://mydomain.com.fake/path/file.ext).16784*/16785if (auth_domain_check_enabled) {16786server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];16787server_domain_len = strlen(server_domain);16788if ((server_domain_len == 0) || (hostbegin == NULL)) {16789return 0;16790}16791if ((request_domain_len == server_domain_len)16792&& (!memcmp(server_domain, hostbegin, server_domain_len))) {16793/* Request is directed to this server - full name match. */16794} else {16795if (request_domain_len < (server_domain_len + 2)) {16796/* Request is directed to another server: The server name16797* is longer than the request name.16798* Drop this case here to avoid overflows in the16799* following checks. */16800return 0;16801}16802if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {16803/* Request is directed to another server: It could be a16804* substring16805* like notmyserver.com */16806return 0;16807}16808if (016809!= memcmp(server_domain,16810hostbegin + request_domain_len - server_domain_len,16811server_domain_len)) {16812/* Request is directed to another server:16813* The server name is different. */16814return 0;16815}16816}16817}1681816819return hostend;16820}168211682216823static int16824get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)16825{16826if (ebuf_len > 0) {16827ebuf[0] = '\0';16828}16829*err = 0;1683016831reset_per_request_attributes(conn);1683216833if (!conn) {16834mg_snprintf(conn,16835NULL, /* No truncation check for ebuf */16836ebuf,16837ebuf_len,16838"%s",16839"Internal error");16840*err = 500;16841return 0;16842}16843/* Set the time the request was received. This value should be used for16844* timeouts. */16845clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));1684616847conn->request_len =16848read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);16849DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);16850if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {16851mg_snprintf(conn,16852NULL, /* No truncation check for ebuf */16853ebuf,16854ebuf_len,16855"%s",16856"Invalid message size");16857*err = 500;16858return 0;16859}1686016861if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {16862mg_snprintf(conn,16863NULL, /* No truncation check for ebuf */16864ebuf,16865ebuf_len,16866"%s",16867"Message too large");16868*err = 413;16869return 0;16870}1687116872if (conn->request_len <= 0) {16873if (conn->data_len > 0) {16874mg_snprintf(conn,16875NULL, /* No truncation check for ebuf */16876ebuf,16877ebuf_len,16878"%s",16879"Malformed message");16880*err = 400;16881} else {16882/* Server did not recv anything -> just close the connection */16883conn->must_close = 1;16884mg_snprintf(conn,16885NULL, /* No truncation check for ebuf */16886ebuf,16887ebuf_len,16888"%s",16889"No data received");16890*err = 0;16891}16892return 0;16893}16894return 1;16895}168961689716898static int16899get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)16900{16901const char *cl;16902if (!get_message(conn, ebuf, ebuf_len, err)) {16903return 0;16904}1690516906if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)16907<= 0) {16908mg_snprintf(conn,16909NULL, /* No truncation check for ebuf */16910ebuf,16911ebuf_len,16912"%s",16913"Bad request");16914*err = 400;16915return 0;16916}1691716918/* Message is a valid request */1691916920/* Is there a "host" ? */16921conn->host = alloc_get_host(conn);16922if (!conn->host) {16923mg_snprintf(conn,16924NULL, /* No truncation check for ebuf */16925ebuf,16926ebuf_len,16927"%s",16928"Bad request: Host mismatch");16929*err = 400;16930return 0;16931}1693216933/* Do we know the content length? */16934if ((cl = get_header(conn->request_info.http_headers,16935conn->request_info.num_headers,16936"Content-Length"))16937!= NULL) {16938/* Request/response has content length set */16939char *endptr = NULL;16940conn->content_len = strtoll(cl, &endptr, 10);16941if (endptr == cl) {16942mg_snprintf(conn,16943NULL, /* No truncation check for ebuf */16944ebuf,16945ebuf_len,16946"%s",16947"Bad request");16948*err = 411;16949return 0;16950}16951/* Publish the content length back to the request info. */16952conn->request_info.content_length = conn->content_len;16953} else if ((cl = get_header(conn->request_info.http_headers,16954conn->request_info.num_headers,16955"Transfer-Encoding"))16956!= NULL16957&& !mg_strcasecmp(cl, "chunked")) {16958conn->is_chunked = 1;16959conn->content_len = -1; /* unknown content length */16960} else {16961const struct mg_http_method_info *meth =16962get_http_method_info(conn->request_info.request_method);16963if (!meth) {16964/* No valid HTTP method */16965mg_snprintf(conn,16966NULL, /* No truncation check for ebuf */16967ebuf,16968ebuf_len,16969"%s",16970"Bad request");16971*err = 411;16972return 0;16973}16974if (meth->request_has_body) {16975/* POST or PUT request without content length set */16976conn->content_len = -1; /* unknown content length */16977} else {16978/* Other request */16979conn->content_len = 0; /* No content */16980}16981}1698216983conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */16984return 1;16985}169861698716988/* conn is assumed to be valid in this internal function */16989static int16990get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)16991{16992const char *cl;16993if (!get_message(conn, ebuf, ebuf_len, err)) {16994return 0;16995}1699616997if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)16998<= 0) {16999mg_snprintf(conn,17000NULL, /* No truncation check for ebuf */17001ebuf,17002ebuf_len,17003"%s",17004"Bad response");17005*err = 400;17006return 0;17007}1700817009/* Message is a valid response */1701017011/* Do we know the content length? */17012if ((cl = get_header(conn->response_info.http_headers,17013conn->response_info.num_headers,17014"Content-Length"))17015!= NULL) {17016/* Request/response has content length set */17017char *endptr = NULL;17018conn->content_len = strtoll(cl, &endptr, 10);17019if (endptr == cl) {17020mg_snprintf(conn,17021NULL, /* No truncation check for ebuf */17022ebuf,17023ebuf_len,17024"%s",17025"Bad request");17026*err = 411;17027return 0;17028}17029/* Publish the content length back to the response info. */17030conn->response_info.content_length = conn->content_len;1703117032/* TODO: check if it is still used in response_info */17033conn->request_info.content_length = conn->content_len;1703417035} else if ((cl = get_header(conn->response_info.http_headers,17036conn->response_info.num_headers,17037"Transfer-Encoding"))17038!= NULL17039&& !mg_strcasecmp(cl, "chunked")) {17040conn->is_chunked = 1;17041conn->content_len = -1; /* unknown content length */17042} else {17043conn->content_len = -1; /* unknown content length */17044}1704517046conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */17047return 1;17048}170491705017051int17052mg_get_response(struct mg_connection *conn,17053char *ebuf,17054size_t ebuf_len,17055int timeout)17056{17057int err, ret;17058char txt[32]; /* will not overflow */17059char *save_timeout;17060char *new_timeout;1706117062if (ebuf_len > 0) {17063ebuf[0] = '\0';17064}1706517066if (!conn) {17067mg_snprintf(conn,17068NULL, /* No truncation check for ebuf */17069ebuf,17070ebuf_len,17071"%s",17072"Parameter error");17073return -1;17074}1707517076/* Implementation of API function for HTTP clients */17077save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];1707817079if (timeout >= 0) {17080mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);17081new_timeout = txt;17082/* Not required for non-blocking sockets.17083set_sock_timeout(conn->client.sock, timeout);17084*/17085} else {17086new_timeout = NULL;17087}1708817089conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;17090ret = get_response(conn, ebuf, ebuf_len, &err);17091conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;1709217093#if defined(MG_LEGACY_INTERFACE)17094/* TODO: 1) uri is deprecated;17095* 2) here, ri.uri is the http response code */17096conn->request_info.uri = conn->request_info.request_uri;17097#endif17098conn->request_info.local_uri = conn->request_info.request_uri;1709917100/* TODO (mid): Define proper return values - maybe return length?17101* For the first test use <0 for error and >0 for OK */17102return (ret == 0) ? -1 : +1;17103}171041710517106struct mg_connection *17107mg_download(const char *host,17108int port,17109int use_ssl,17110char *ebuf,17111size_t ebuf_len,17112const char *fmt,17113...)17114{17115struct mg_connection *conn;17116va_list ap;17117int i;17118int reqerr;1711917120if (ebuf_len > 0) {17121ebuf[0] = '\0';17122}1712317124va_start(ap, fmt);1712517126/* open a connection */17127conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);1712817129if (conn != NULL) {17130i = mg_vprintf(conn, fmt, ap);17131if (i <= 0) {17132mg_snprintf(conn,17133NULL, /* No truncation check for ebuf */17134ebuf,17135ebuf_len,17136"%s",17137"Error sending request");17138} else {17139get_response(conn, ebuf, ebuf_len, &reqerr);1714017141#if defined(MG_LEGACY_INTERFACE)17142/* TODO: 1) uri is deprecated;17143* 2) here, ri.uri is the http response code */17144conn->request_info.uri = conn->request_info.request_uri;17145#endif17146conn->request_info.local_uri = conn->request_info.request_uri;17147}17148}1714917150/* if an error occurred, close the connection */17151if ((ebuf[0] != '\0') && (conn != NULL)) {17152mg_close_connection(conn);17153conn = NULL;17154}1715517156va_end(ap);17157return conn;17158}171591716017161struct websocket_client_thread_data {17162struct mg_connection *conn;17163mg_websocket_data_handler data_handler;17164mg_websocket_close_handler close_handler;17165void *callback_data;17166};171671716817169#if defined(USE_WEBSOCKET)17170#if defined(_WIN32)17171static unsigned __stdcall websocket_client_thread(void *data)17172#else17173static void *17174websocket_client_thread(void *data)17175#endif17176{17177struct websocket_client_thread_data *cdata =17178(struct websocket_client_thread_data *)data;1717917180#if !defined(_WIN32)17181struct sigaction sa;1718217183/* Ignore SIGPIPE */17184memset(&sa, 0, sizeof(sa));17185sa.sa_handler = SIG_IGN;17186sigaction(SIGPIPE, &sa, NULL);17187#endif1718817189mg_set_thread_name("ws-clnt");1719017191if (cdata->conn->phys_ctx) {17192if (cdata->conn->phys_ctx->callbacks.init_thread) {17193/* 3 indicates a websocket client thread */17194/* TODO: check if conn->phys_ctx can be set */17195cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,171963);17197}17198}1719917200read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);1720117202DEBUG_TRACE("%s", "Websocket client thread exited\n");1720317204if (cdata->close_handler != NULL) {17205cdata->close_handler(cdata->conn, cdata->callback_data);17206}1720717208/* The websocket_client context has only this thread. If it runs out,17209set the stop_flag to 2 (= "stopped"). */17210cdata->conn->phys_ctx->stop_flag = 2;1721117212mg_free((void *)cdata);1721317214#if defined(_WIN32)17215return 0;17216#else17217return NULL;17218#endif17219}17220#endif172211722217223struct mg_connection *17224mg_connect_websocket_client(const char *host,17225int port,17226int use_ssl,17227char *error_buffer,17228size_t error_buffer_size,17229const char *path,17230const char *origin,17231mg_websocket_data_handler data_func,17232mg_websocket_close_handler close_func,17233void *user_data)17234{17235struct mg_connection *conn = NULL;1723617237#if defined(USE_WEBSOCKET)17238struct mg_context *newctx = NULL;17239struct websocket_client_thread_data *thread_data;17240static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";17241static const char *handshake_req;1724217243if (origin != NULL) {17244handshake_req = "GET %s HTTP/1.1\r\n"17245"Host: %s\r\n"17246"Upgrade: websocket\r\n"17247"Connection: Upgrade\r\n"17248"Sec-WebSocket-Key: %s\r\n"17249"Sec-WebSocket-Version: 13\r\n"17250"Origin: %s\r\n"17251"\r\n";17252} else {17253handshake_req = "GET %s HTTP/1.1\r\n"17254"Host: %s\r\n"17255"Upgrade: websocket\r\n"17256"Connection: Upgrade\r\n"17257"Sec-WebSocket-Key: %s\r\n"17258"Sec-WebSocket-Version: 13\r\n"17259"\r\n";17260}1726117262#if defined(__clang__)17263#pragma clang diagnostic push17264#pragma clang diagnostic ignored "-Wformat-nonliteral"17265#endif1726617267/* Establish the client connection and request upgrade */17268conn = mg_download(host,17269port,17270use_ssl,17271error_buffer,17272error_buffer_size,17273handshake_req,17274path,17275host,17276magic,17277origin);1727817279#if defined(__clang__)17280#pragma clang diagnostic pop17281#endif1728217283/* Connection object will be null if something goes wrong */17284if (conn == NULL) {17285if (!*error_buffer) {17286/* There should be already an error message */17287mg_snprintf(conn,17288NULL, /* No truncation check for ebuf */17289error_buffer,17290error_buffer_size,17291"Unexpected error");17292}17293return NULL;17294}1729517296if (conn->response_info.status_code != 101) {17297/* We sent an "upgrade" request. For a correct websocket17298* protocol handshake, we expect a "101 Continue" response.17299* Otherwise it is a protocol violation. Maybe the HTTP17300* Server does not know websockets. */17301if (!*error_buffer) {17302/* set an error, if not yet set */17303mg_snprintf(conn,17304NULL, /* No truncation check for ebuf */17305error_buffer,17306error_buffer_size,17307"Unexpected server reply");17308}1730917310DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);17311mg_free(conn);17312return NULL;17313}1731417315/* For client connections, mg_context is fake. Since we need to set a17316* callback function, we need to create a copy and modify it. */17317newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));17318if (!newctx) {17319DEBUG_TRACE("%s\r\n", "Out of memory");17320mg_free(conn);17321return NULL;17322}1732317324memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));17325newctx->user_data = user_data;17326newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */17327newctx->cfg_worker_threads = 1; /* one worker thread will be created */17328newctx->worker_threadids =17329(pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,17330sizeof(pthread_t),17331newctx);1733217333conn->phys_ctx = newctx;17334conn->dom_ctx = &(newctx->dd);1733517336thread_data = (struct websocket_client_thread_data *)17337mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);17338if (!thread_data) {17339DEBUG_TRACE("%s\r\n", "Out of memory");17340mg_free(newctx);17341mg_free(conn);17342return NULL;17343}1734417345thread_data->conn = conn;17346thread_data->data_handler = data_func;17347thread_data->close_handler = close_func;17348thread_data->callback_data = user_data;1734917350/* Start a thread to read the websocket client connection17351* This thread will automatically stop when mg_disconnect is17352* called on the client connection */17353if (mg_start_thread_with_id(websocket_client_thread,17354(void *)thread_data,17355newctx->worker_threadids)17356!= 0) {17357mg_free((void *)thread_data);17358mg_free((void *)newctx->worker_threadids);17359mg_free((void *)newctx);17360mg_free((void *)conn);17361conn = NULL;17362DEBUG_TRACE("%s",17363"Websocket client connect thread could not be started\r\n");17364}1736517366#else17367/* Appease "unused parameter" warnings */17368(void)host;17369(void)port;17370(void)use_ssl;17371(void)error_buffer;17372(void)error_buffer_size;17373(void)path;17374(void)origin;17375(void)user_data;17376(void)data_func;17377(void)close_func;17378#endif1737917380return conn;17381}173821738317384/* Prepare connection data structure */17385static void17386init_connection(struct mg_connection *conn)17387{17388/* Is keep alive allowed by the server */17389int keep_alive_enabled =17390!mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");1739117392if (!keep_alive_enabled) {17393conn->must_close = 1;17394}1739517396/* Important: on new connection, reset the receiving buffer. Credit17397* goes to crule42. */17398conn->data_len = 0;17399conn->handled_requests = 0;17400mg_set_user_connection_data(conn, NULL);1740117402#if defined(USE_SERVER_STATS)17403conn->conn_state = 2; /* init */17404#endif1740517406/* call the init_connection callback if assigned */17407if (conn->phys_ctx->callbacks.init_connection != NULL) {17408if (conn->phys_ctx->context_type == CONTEXT_SERVER) {17409void *conn_data = NULL;17410conn->phys_ctx->callbacks.init_connection(conn, &conn_data);17411mg_set_user_connection_data(conn, conn_data);17412}17413}17414}174151741617417/* Process a connection - may handle multiple requests17418* using the same connection.17419* Must be called with a valid connection (conn and17420* conn->phys_ctx must be valid).17421*/17422static void17423process_new_connection(struct mg_connection *conn)17424{17425struct mg_request_info *ri = &conn->request_info;17426int keep_alive, discard_len;17427char ebuf[100];17428const char *hostend;17429int reqerr, uri_type;1743017431#if defined(USE_SERVER_STATS)17432int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));17433mg_atomic_add(&(conn->phys_ctx->total_connections), 1);17434if (mcon > (conn->phys_ctx->max_connections)) {17435/* could use atomic compare exchange, but this17436* seems overkill for statistics data */17437conn->phys_ctx->max_connections = mcon;17438}17439#endif1744017441init_connection(conn);1744217443DEBUG_TRACE("Start processing connection from %s",17444conn->request_info.remote_addr);1744517446/* Loop over multiple requests sent using the same connection17447* (while "keep alive"). */17448do {1744917450DEBUG_TRACE("calling get_request (%i times for this connection)",17451conn->handled_requests + 1);1745217453#if defined(USE_SERVER_STATS)17454conn->conn_state = 3; /* ready */17455#endif1745617457if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {17458/* The request sent by the client could not be understood by17459* the server, or it was incomplete or a timeout. Send an17460* error message and close the connection. */17461if (reqerr > 0) {17462DEBUG_ASSERT(ebuf[0] != '\0');17463mg_send_http_error(conn, reqerr, "%s", ebuf);17464}17465} else if (strcmp(ri->http_version, "1.0")17466&& strcmp(ri->http_version, "1.1")) {17467mg_snprintf(conn,17468NULL, /* No truncation check for ebuf */17469ebuf,17470sizeof(ebuf),17471"Bad HTTP version: [%s]",17472ri->http_version);17473mg_send_http_error(conn, 505, "%s", ebuf);17474}1747517476if (ebuf[0] == '\0') {17477uri_type = get_uri_type(conn->request_info.request_uri);17478switch (uri_type) {17479case 1:17480/* Asterisk */17481conn->request_info.local_uri = NULL;17482break;17483case 2:17484/* relative uri */17485conn->request_info.local_uri = conn->request_info.request_uri;17486break;17487case 3:17488case 4:17489/* absolute uri (with/without port) */17490hostend = get_rel_url_at_current_server(17491conn->request_info.request_uri, conn);17492if (hostend) {17493conn->request_info.local_uri = hostend;17494} else {17495conn->request_info.local_uri = NULL;17496}17497break;17498default:17499mg_snprintf(conn,17500NULL, /* No truncation check for ebuf */17501ebuf,17502sizeof(ebuf),17503"Invalid URI");17504mg_send_http_error(conn, 400, "%s", ebuf);17505conn->request_info.local_uri = NULL;17506break;17507}1750817509#if defined(MG_LEGACY_INTERFACE)17510/* Legacy before split into local_uri and request_uri */17511conn->request_info.uri = conn->request_info.local_uri;17512#endif17513}1751417515DEBUG_TRACE("http: %s, error: %s",17516(ri->http_version ? ri->http_version : "none"),17517(ebuf[0] ? ebuf : "none"));1751817519if (ebuf[0] == '\0') {17520if (conn->request_info.local_uri) {1752117522/* handle request to local server */17523#if defined(USE_SERVER_STATS)17524conn->conn_state = 4; /* processing */17525#endif17526handle_request(conn);1752717528#if defined(USE_SERVER_STATS)17529conn->conn_state = 5; /* processed */1753017531mg_atomic_add(&(conn->phys_ctx->total_data_read),17532conn->consumed_content);17533mg_atomic_add(&(conn->phys_ctx->total_data_written),17534conn->num_bytes_sent);17535#endif1753617537DEBUG_TRACE("%s", "handle_request done");1753817539if (conn->phys_ctx->callbacks.end_request != NULL) {17540conn->phys_ctx->callbacks.end_request(conn,17541conn->status_code);17542DEBUG_TRACE("%s", "end_request callback done");17543}17544log_access(conn);17545} else {17546/* TODO: handle non-local request (PROXY) */17547conn->must_close = 1;17548}17549} else {17550conn->must_close = 1;17551}1755217553if (ri->remote_user != NULL) {17554mg_free((void *)ri->remote_user);17555/* Important! When having connections with and without auth17556* would cause double free and then crash */17557ri->remote_user = NULL;17558}1755917560/* NOTE(lsm): order is important here. should_keep_alive() call17561* is using parsed request, which will be invalid after17562* memmove's below.17563* Therefore, memorize should_keep_alive() result now for later17564* use in loop exit condition. */17565keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)17566&& (conn->content_len >= 0);175671756817569/* Discard all buffered data for this request */17570discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)17571&& ((conn->request_len + conn->content_len)17572< (int64_t)conn->data_len))17573? (int)(conn->request_len + conn->content_len)17574: conn->data_len;17575DEBUG_ASSERT(discard_len >= 0);17576if (discard_len < 0) {17577DEBUG_TRACE("internal error: discard_len = %li",17578(long int)discard_len);17579break;17580}17581conn->data_len -= discard_len;17582if (conn->data_len > 0) {17583DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);17584memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);17585}1758617587DEBUG_ASSERT(conn->data_len >= 0);17588DEBUG_ASSERT(conn->data_len <= conn->buf_size);1758917590if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {17591DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",17592(long int)conn->data_len,17593(long int)conn->buf_size);17594break;17595}1759617597conn->handled_requests++;1759817599} while (keep_alive);1760017601DEBUG_TRACE("Done processing connection from %s (%f sec)",17602conn->request_info.remote_addr,17603difftime(time(NULL), conn->conn_birth_time));1760417605close_connection(conn);1760617607#if defined(USE_SERVER_STATS)17608mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);17609mg_atomic_dec(&(conn->phys_ctx->active_connections));17610#endif17611}176121761317614#if defined(ALTERNATIVE_QUEUE)1761517616static void17617produce_socket(struct mg_context *ctx, const struct socket *sp)17618{17619unsigned int i;1762017621while (!ctx->stop_flag) {17622for (i = 0; i < ctx->cfg_worker_threads; i++) {17623/* find a free worker slot and signal it */17624if (ctx->client_socks[i].in_use == 0) {17625ctx->client_socks[i] = *sp;17626ctx->client_socks[i].in_use = 1;17627event_signal(ctx->client_wait_events[i]);17628return;17629}17630}17631/* queue is full */17632mg_sleep(1);17633}17634}176351763617637static int17638consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)17639{17640DEBUG_TRACE("%s", "going idle");17641ctx->client_socks[thread_index].in_use = 0;17642event_wait(ctx->client_wait_events[thread_index]);17643*sp = ctx->client_socks[thread_index];17644DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);1764517646return !ctx->stop_flag;17647}1764817649#else /* ALTERNATIVE_QUEUE */1765017651/* Worker threads take accepted socket from the queue */17652static int17653consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)17654{17655#define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))1765617657(void)thread_index;1765817659(void)pthread_mutex_lock(&ctx->thread_mutex);17660DEBUG_TRACE("%s", "going idle");1766117662/* If the queue is empty, wait. We're idle at this point. */17663while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {17664pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);17665}1766617667/* If we're stopping, sq_head may be equal to sq_tail. */17668if (ctx->sq_head > ctx->sq_tail) {17669/* Copy socket from the queue and increment tail */17670*sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];17671ctx->sq_tail++;1767217673DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);1767417675/* Wrap pointers if needed */17676while (ctx->sq_tail > QUEUE_SIZE(ctx)) {17677ctx->sq_tail -= QUEUE_SIZE(ctx);17678ctx->sq_head -= QUEUE_SIZE(ctx);17679}17680}1768117682(void)pthread_cond_signal(&ctx->sq_empty);17683(void)pthread_mutex_unlock(&ctx->thread_mutex);1768417685return !ctx->stop_flag;17686#undef QUEUE_SIZE17687}176881768917690/* Master thread adds accepted socket to a queue */17691static void17692produce_socket(struct mg_context *ctx, const struct socket *sp)17693{17694#define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))17695if (!ctx) {17696return;17697}17698(void)pthread_mutex_lock(&ctx->thread_mutex);1769917700/* If the queue is full, wait */17701while ((ctx->stop_flag == 0)17702&& (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {17703(void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);17704}1770517706if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {17707/* Copy socket to the queue and increment head */17708ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;17709ctx->sq_head++;17710DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);17711}1771217713(void)pthread_cond_signal(&ctx->sq_full);17714(void)pthread_mutex_unlock(&ctx->thread_mutex);17715#undef QUEUE_SIZE17716}17717#endif /* ALTERNATIVE_QUEUE */177181771917720struct worker_thread_args {17721struct mg_context *ctx;17722int index;17723};177241772517726static void *17727worker_thread_run(struct worker_thread_args *thread_args)17728{17729struct mg_context *ctx = thread_args->ctx;17730struct mg_connection *conn;17731struct mg_workerTLS tls;17732#if defined(MG_LEGACY_INTERFACE)17733uint32_t addr;17734#endif1773517736mg_set_thread_name("worker");1773717738tls.is_master = 0;17739tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);17740#if defined(_WIN32)17741tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);17742#endif1774317744/* Initialize thread local storage before calling any callback */17745pthread_setspecific(sTlsKey, &tls);1774617747if (ctx->callbacks.init_thread) {17748/* call init_thread for a worker thread (type 1) */17749ctx->callbacks.init_thread(ctx, 1);17750}1775117752/* Connection structure has been pre-allocated */17753if (((int)thread_args->index < 0)17754|| ((unsigned)thread_args->index17755>= (unsigned)ctx->cfg_worker_threads)) {17756mg_cry_internal(fc(ctx),17757"Internal error: Invalid worker index %i",17758(int)thread_args->index);17759return NULL;17760}17761conn = ctx->worker_connections + thread_args->index;1776217763/* Request buffers are not pre-allocated. They are private to the17764* request and do not contain any state information that might be17765* of interest to anyone observing a server status. */17766conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);17767if (conn->buf == NULL) {17768mg_cry_internal(fc(ctx),17769"Out of memory: Cannot allocate buffer for worker %i",17770(int)thread_args->index);17771return NULL;17772}17773conn->buf_size = (int)ctx->max_request_size;1777417775conn->phys_ctx = ctx;17776conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */17777conn->host = NULL; /* until we have more information. */1777817779conn->thread_index = thread_args->index;17780conn->request_info.user_data = ctx->user_data;17781/* Allocate a mutex for this connection to allow communication both17782* within the request handler and from elsewhere in the application17783*/17784if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {17785mg_free(conn->buf);17786mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");17787return NULL;17788}1778917790#if defined(USE_SERVER_STATS)17791conn->conn_state = 1; /* not consumed */17792#endif1779317794#if defined(ALTERNATIVE_QUEUE)17795while ((ctx->stop_flag == 0)17796&& consume_socket(ctx, &conn->client, conn->thread_index)) {17797#else17798/* Call consume_socket() even when ctx->stop_flag > 0, to let it17799* signal sq_empty condvar to wake up the master waiting in17800* produce_socket() */17801while (consume_socket(ctx, &conn->client, conn->thread_index)) {17802#endif1780317804conn->conn_birth_time = time(NULL);1780517806/* Fill in IP, port info early so even if SSL setup below fails,17807* error handler would have the corresponding info.17808* Thanks to Johannes Winkelmann for the patch.17809*/17810#if defined(USE_IPV6)17811if (conn->client.rsa.sa.sa_family == AF_INET6) {17812conn->request_info.remote_port =17813ntohs(conn->client.rsa.sin6.sin6_port);17814} else17815#endif17816{17817conn->request_info.remote_port =17818ntohs(conn->client.rsa.sin.sin_port);17819}1782017821sockaddr_to_string(conn->request_info.remote_addr,17822sizeof(conn->request_info.remote_addr),17823&conn->client.rsa);1782417825DEBUG_TRACE("Start processing connection from %s",17826conn->request_info.remote_addr);1782717828conn->request_info.is_ssl = conn->client.is_ssl;1782917830if (conn->client.is_ssl) {17831#if !defined(NO_SSL)17832/* HTTPS connection */17833if (sslize(conn,17834conn->dom_ctx->ssl_ctx,17835SSL_accept,17836&(conn->phys_ctx->stop_flag))) {17837/* conn->dom_ctx is set in get_request */1783817839/* Get SSL client certificate information (if set) */17840ssl_get_client_cert_info(conn);1784117842/* process HTTPS connection */17843process_new_connection(conn);1784417845/* Free client certificate info */17846if (conn->request_info.client_cert) {17847mg_free((void *)(conn->request_info.client_cert->subject));17848mg_free((void *)(conn->request_info.client_cert->issuer));17849mg_free((void *)(conn->request_info.client_cert->serial));17850mg_free((void *)(conn->request_info.client_cert->finger));17851/* Free certificate memory */17852X509_free(17853(X509 *)conn->request_info.client_cert->peer_cert);17854conn->request_info.client_cert->peer_cert = 0;17855conn->request_info.client_cert->subject = 0;17856conn->request_info.client_cert->issuer = 0;17857conn->request_info.client_cert->serial = 0;17858conn->request_info.client_cert->finger = 0;17859mg_free(conn->request_info.client_cert);17860conn->request_info.client_cert = 0;17861}17862} else {17863/* make sure the connection is cleaned up on SSL failure */17864close_connection(conn);17865}17866#endif17867} else {17868/* process HTTP connection */17869process_new_connection(conn);17870}1787117872DEBUG_TRACE("%s", "Connection closed");17873}178741787517876pthread_setspecific(sTlsKey, NULL);17877#if defined(_WIN32)17878CloseHandle(tls.pthread_cond_helper_mutex);17879#endif17880pthread_mutex_destroy(&conn->mutex);1788117882/* Free the request buffer. */17883conn->buf_size = 0;17884mg_free(conn->buf);17885conn->buf = NULL;1788617887#if defined(USE_SERVER_STATS)17888conn->conn_state = 9; /* done */17889#endif1789017891DEBUG_TRACE("%s", "exiting");17892return NULL;17893}178941789517896/* Threads have different return types on Windows and Unix. */17897#if defined(_WIN32)17898static unsigned __stdcall worker_thread(void *thread_func_param)17899{17900struct worker_thread_args *pwta =17901(struct worker_thread_args *)thread_func_param;17902worker_thread_run(pwta);17903mg_free(thread_func_param);17904return 0;17905}17906#else17907static void *17908worker_thread(void *thread_func_param)17909{17910struct worker_thread_args *pwta =17911(struct worker_thread_args *)thread_func_param;17912struct sigaction sa;1791317914/* Ignore SIGPIPE */17915memset(&sa, 0, sizeof(sa));17916sa.sa_handler = SIG_IGN;17917sigaction(SIGPIPE, &sa, NULL);1791817919worker_thread_run(pwta);17920mg_free(thread_func_param);17921return NULL;17922}17923#endif /* _WIN32 */179241792517926/* This is an internal function, thus all arguments are expected to be17927* valid - a NULL check is not required. */17928static void17929accept_new_connection(const struct socket *listener, struct mg_context *ctx)17930{17931struct socket so;17932char src_addr[IP_ADDR_STR_LEN];17933socklen_t len = sizeof(so.rsa);17934int on = 1;1793517936if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))17937== INVALID_SOCKET) {17938} else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {17939sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);17940mg_cry_internal(fc(ctx),17941"%s: %s is not allowed to connect",17942__func__,17943src_addr);17944closesocket(so.sock);17945} else {17946/* Put so socket structure into the queue */17947DEBUG_TRACE("Accepted socket %d", (int)so.sock);17948set_close_on_exec(so.sock, fc(ctx));17949so.is_ssl = listener->is_ssl;17950so.ssl_redir = listener->ssl_redir;17951if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {17952mg_cry_internal(fc(ctx),17953"%s: getsockname() failed: %s",17954__func__,17955strerror(ERRNO));17956}1795717958/* Set TCP keep-alive. This is needed because if HTTP-level17959* keep-alive17960* is enabled, and client resets the connection, server won't get17961* TCP FIN or RST and will keep the connection open forever. With17962* TCP keep-alive, next keep-alive handshake will figure out that17963* the client is down and will close the server end.17964* Thanks to Igor Klopov who suggested the patch. */17965if (setsockopt(so.sock,17966SOL_SOCKET,17967SO_KEEPALIVE,17968(SOCK_OPT_TYPE)&on,17969sizeof(on))17970!= 0) {17971mg_cry_internal(17972fc(ctx),17973"%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",17974__func__,17975strerror(ERRNO));17976}1797717978/* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced17979* to effectively fill up the underlying IP packet payload and17980* reduce the overhead of sending lots of small buffers. However17981* this hurts the server's throughput (ie. operations per second)17982* when HTTP 1.1 persistent connections are used and the responses17983* are relatively small (eg. less than 1400 bytes).17984*/17985if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)17986&& (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {17987if (set_tcp_nodelay(so.sock, 1) != 0) {17988mg_cry_internal(17989fc(ctx),17990"%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",17991__func__,17992strerror(ERRNO));17993}17994}1799517996/* We are using non-blocking sockets. Thus, the17997* set_sock_timeout(so.sock, timeout);17998* call is no longer required. */1799918000/* The "non blocking" property should already be18001* inherited from the parent socket. Set it for18002* non-compliant socket implementations. */18003set_non_blocking_mode(so.sock);1800418005so.in_use = 0;18006produce_socket(ctx, &so);18007}18008}180091801018011static void18012master_thread_run(void *thread_func_param)18013{18014struct mg_context *ctx = (struct mg_context *)thread_func_param;18015struct mg_workerTLS tls;18016struct pollfd *pfd;18017unsigned int i;18018unsigned int workerthreadcount;1801918020if (!ctx) {18021return;18022}1802318024mg_set_thread_name("master");1802518026/* Increase priority of the master thread */18027#if defined(_WIN32)18028SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);18029#elif defined(USE_MASTER_THREAD_PRIORITY)18030int min_prio = sched_get_priority_min(SCHED_RR);18031int max_prio = sched_get_priority_max(SCHED_RR);18032if ((min_prio >= 0) && (max_prio >= 0)18033&& ((USE_MASTER_THREAD_PRIORITY) <= max_prio)18034&& ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {18035struct sched_param sched_param = {0};18036sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);18037pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);18038}18039#endif1804018041/* Initialize thread local storage */18042#if defined(_WIN32)18043tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);18044#endif18045tls.is_master = 1;18046pthread_setspecific(sTlsKey, &tls);1804718048if (ctx->callbacks.init_thread) {18049/* Callback for the master thread (type 0) */18050ctx->callbacks.init_thread(ctx, 0);18051}1805218053/* Server starts *now* */18054ctx->start_time = time(NULL);1805518056/* Start the server */18057pfd = ctx->listening_socket_fds;18058while (ctx->stop_flag == 0) {18059for (i = 0; i < ctx->num_listening_sockets; i++) {18060pfd[i].fd = ctx->listening_sockets[i].sock;18061pfd[i].events = POLLIN;18062}1806318064if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {18065for (i = 0; i < ctx->num_listening_sockets; i++) {18066/* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the18067* successful poll, and POLLIN is defined as18068* (POLLRDNORM | POLLRDBAND)18069* Therefore, we're checking pfd[i].revents & POLLIN, not18070* pfd[i].revents == POLLIN. */18071if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {18072accept_new_connection(&ctx->listening_sockets[i], ctx);18073}18074}18075}18076}1807718078/* Here stop_flag is 1 - Initiate shutdown. */18079DEBUG_TRACE("%s", "stopping workers");1808018081/* Stop signal received: somebody called mg_stop. Quit. */18082close_all_listening_sockets(ctx);1808318084/* Wakeup workers that are waiting for connections to handle. */18085(void)pthread_mutex_lock(&ctx->thread_mutex);18086#if defined(ALTERNATIVE_QUEUE)18087for (i = 0; i < ctx->cfg_worker_threads; i++) {18088event_signal(ctx->client_wait_events[i]);1808918090/* Since we know all sockets, we can shutdown the connections. */18091if (ctx->client_socks[i].in_use) {18092shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);18093}18094}18095#else18096pthread_cond_broadcast(&ctx->sq_full);18097#endif18098(void)pthread_mutex_unlock(&ctx->thread_mutex);1809918100/* Join all worker threads to avoid leaking threads. */18101workerthreadcount = ctx->cfg_worker_threads;18102for (i = 0; i < workerthreadcount; i++) {18103if (ctx->worker_threadids[i] != 0) {18104mg_join_thread(ctx->worker_threadids[i]);18105}18106}1810718108#if defined(USE_LUA)18109/* Free Lua state of lua background task */18110if (ctx->lua_background_state) {18111lua_State *lstate = (lua_State *)ctx->lua_background_state;18112lua_getglobal(lstate, LUABACKGROUNDPARAMS);18113if (lua_istable(lstate, -1)) {18114reg_boolean(lstate, "shutdown", 1);18115lua_pop(lstate, 1);18116mg_sleep(2);18117}18118lua_close(lstate);18119ctx->lua_background_state = 0;18120}18121#endif1812218123DEBUG_TRACE("%s", "exiting");1812418125#if defined(_WIN32)18126CloseHandle(tls.pthread_cond_helper_mutex);18127#endif18128pthread_setspecific(sTlsKey, NULL);1812918130/* Signal mg_stop() that we're done.18131* WARNING: This must be the very last thing this18132* thread does, as ctx becomes invalid after this line. */18133ctx->stop_flag = 2;18134}181351813618137/* Threads have different return types on Windows and Unix. */18138#if defined(_WIN32)18139static unsigned __stdcall master_thread(void *thread_func_param)18140{18141master_thread_run(thread_func_param);18142return 0;18143}18144#else18145static void *18146master_thread(void *thread_func_param)18147{18148struct sigaction sa;1814918150/* Ignore SIGPIPE */18151memset(&sa, 0, sizeof(sa));18152sa.sa_handler = SIG_IGN;18153sigaction(SIGPIPE, &sa, NULL);1815418155master_thread_run(thread_func_param);18156return NULL;18157}18158#endif /* _WIN32 */181591816018161static void18162free_context(struct mg_context *ctx)18163{18164int i;18165struct mg_handler_info *tmp_rh;1816618167if (ctx == NULL) {18168return;18169}1817018171if (ctx->callbacks.exit_context) {18172ctx->callbacks.exit_context(ctx);18173}1817418175/* All threads exited, no sync is needed. Destroy thread mutex and18176* condvars18177*/18178(void)pthread_mutex_destroy(&ctx->thread_mutex);18179#if defined(ALTERNATIVE_QUEUE)18180mg_free(ctx->client_socks);18181for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {18182event_destroy(ctx->client_wait_events[i]);18183}18184mg_free(ctx->client_wait_events);18185#else18186(void)pthread_cond_destroy(&ctx->sq_empty);18187(void)pthread_cond_destroy(&ctx->sq_full);18188#endif1818918190/* Destroy other context global data structures mutex */18191(void)pthread_mutex_destroy(&ctx->nonce_mutex);1819218193#if defined(USE_TIMERS)18194timers_exit(ctx);18195#endif1819618197/* Deallocate config parameters */18198for (i = 0; i < NUM_OPTIONS; i++) {18199if (ctx->dd.config[i] != NULL) {18200#if defined(_MSC_VER)18201#pragma warning(suppress : 6001)18202#endif18203mg_free(ctx->dd.config[i]);18204}18205}1820618207/* Deallocate request handlers */18208while (ctx->dd.handlers) {18209tmp_rh = ctx->dd.handlers;18210ctx->dd.handlers = tmp_rh->next;18211if (tmp_rh->handler_type == REQUEST_HANDLER) {18212pthread_cond_destroy(&tmp_rh->refcount_cond);18213pthread_mutex_destroy(&tmp_rh->refcount_mutex);18214}18215mg_free(tmp_rh->uri);18216mg_free(tmp_rh);18217}1821818219#if !defined(NO_SSL)18220/* Deallocate SSL context */18221if (ctx->dd.ssl_ctx != NULL) {18222void *ssl_ctx = (void *)ctx->dd.ssl_ctx;18223int callback_ret =18224(ctx->callbacks.external_ssl_ctx == NULL)18225? 018226: (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));1822718228if (callback_ret == 0) {18229SSL_CTX_free(ctx->dd.ssl_ctx);18230}18231/* else: ignore error and ommit SSL_CTX_free in case18232* callback_ret is 1 */18233}18234#endif /* !NO_SSL */1823518236/* Deallocate worker thread ID array */18237if (ctx->worker_threadids != NULL) {18238mg_free(ctx->worker_threadids);18239}1824018241/* Deallocate worker thread ID array */18242if (ctx->worker_connections != NULL) {18243mg_free(ctx->worker_connections);18244}1824518246/* deallocate system name string */18247mg_free(ctx->systemName);1824818249/* Deallocate context itself */18250mg_free(ctx);18251}182521825318254void18255mg_stop(struct mg_context *ctx)18256{18257pthread_t mt;18258if (!ctx) {18259return;18260}1826118262/* We don't use a lock here. Calling mg_stop with the same ctx from18263* two threads is not allowed. */18264mt = ctx->masterthreadid;18265if (mt == 0) {18266return;18267}1826818269ctx->masterthreadid = 0;1827018271/* Set stop flag, so all threads know they have to exit. */18272ctx->stop_flag = 1;1827318274/* Wait until everything has stopped. */18275while (ctx->stop_flag != 2) {18276(void)mg_sleep(10);18277}1827818279mg_join_thread(mt);18280free_context(ctx);1828118282#if defined(_WIN32)18283(void)WSACleanup();18284#endif /* _WIN32 */18285}182861828718288static void18289get_system_name(char **sysName)18290{18291#if defined(_WIN32)18292#if !defined(__SYMBIAN32__)18293#if defined(_WIN32_WCE)18294*sysName = mg_strdup("WinCE");18295#else18296char name[128];18297DWORD dwVersion = 0;18298DWORD dwMajorVersion = 0;18299DWORD dwMinorVersion = 0;18300DWORD dwBuild = 0;18301BOOL wowRet, isWoW = FALSE;1830218303#if defined(_MSC_VER)18304#pragma warning(push)18305/* GetVersion was declared deprecated */18306#pragma warning(disable : 4996)18307#endif18308dwVersion = GetVersion();18309#if defined(_MSC_VER)18310#pragma warning(pop)18311#endif1831218313dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));18314dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));18315dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);18316(void)dwBuild;1831718318wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);1831918320sprintf(name,18321"Windows %u.%u%s",18322(unsigned)dwMajorVersion,18323(unsigned)dwMinorVersion,18324(wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));1832518326*sysName = mg_strdup(name);18327#endif18328#else18329*sysName = mg_strdup("Symbian");18330#endif18331#else18332struct utsname name;18333memset(&name, 0, sizeof(name));18334uname(&name);18335*sysName = mg_strdup(name.sysname);18336#endif18337}183381833918340struct mg_context *18341mg_start(const struct mg_callbacks *callbacks,18342void *user_data,18343const char **options)18344{18345struct mg_context *ctx;18346const char *name, *value, *default_value;18347int idx, ok, workerthreadcount;18348unsigned int i;18349int itmp;18350void (*exit_callback)(const struct mg_context *ctx) = 0;1835118352struct mg_workerTLS tls;1835318354#if defined(_WIN32)18355WSADATA data;18356WSAStartup(MAKEWORD(2, 2), &data);18357#endif /* _WIN32 */1835818359/* Allocate context and initialize reasonable general case defaults. */18360if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {18361return NULL;18362}1836318364/* Random number generator will initialize at the first call */18365ctx->dd.auth_nonce_mask =18366(uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);1836718368if (mg_init_library_called == 0) {18369/* Legacy INIT, if mg_start is called without mg_init_library.18370* Note: This may cause a memory leak */18371const char *ports_option =18372config_options[LISTENING_PORTS].default_value;1837318374if (options) {18375const char **run_options = options;18376const char *optname = config_options[LISTENING_PORTS].name;1837718378/* Try to find the "listening_ports" option */18379while (*run_options) {18380if (!strcmp(*run_options, optname)) {18381ports_option = run_options[1];18382}18383run_options += 2;18384}18385}1838618387if (is_ssl_port_used(ports_option)) {18388/* Initialize with SSL support */18389mg_init_library(MG_FEATURES_TLS);18390} else {18391/* Initialize without SSL support */18392mg_init_library(MG_FEATURES_DEFAULT);18393}18394}1839518396tls.is_master = -1;18397tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);18398#if defined(_WIN32)18399tls.pthread_cond_helper_mutex = NULL;18400#endif18401pthread_setspecific(sTlsKey, &tls);1840218403ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));18404#if !defined(ALTERNATIVE_QUEUE)18405ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));18406ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));18407#endif18408ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));18409if (!ok) {18410/* Fatal error - abort start. However, this situation should never18411* occur in practice. */18412mg_cry_internal(fc(ctx),18413"%s",18414"Cannot initialize thread synchronization objects");18415mg_free(ctx);18416pthread_setspecific(sTlsKey, NULL);18417return NULL;18418}1841918420if (callbacks) {18421ctx->callbacks = *callbacks;18422exit_callback = callbacks->exit_context;18423ctx->callbacks.exit_context = 0;18424}18425ctx->user_data = user_data;18426ctx->dd.handlers = NULL;18427ctx->dd.next = NULL;1842818429#if defined(USE_LUA) && defined(USE_WEBSOCKET)18430ctx->dd.shared_lua_websockets = NULL;18431#endif1843218433/* Store options */18434while (options && (name = *options++) != NULL) {18435if ((idx = get_option_index(name)) == -1) {18436mg_cry_internal(fc(ctx), "Invalid option: %s", name);18437free_context(ctx);18438pthread_setspecific(sTlsKey, NULL);18439return NULL;18440} else if ((value = *options++) == NULL) {18441mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);18442free_context(ctx);18443pthread_setspecific(sTlsKey, NULL);18444return NULL;18445}18446if (ctx->dd.config[idx] != NULL) {18447mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);18448mg_free(ctx->dd.config[idx]);18449}18450ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);18451DEBUG_TRACE("[%s] -> [%s]", name, value);18452}1845318454/* Set default value if needed */18455for (i = 0; config_options[i].name != NULL; i++) {18456default_value = config_options[i].default_value;18457if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {18458ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);18459}18460}1846118462/* Request size option */18463itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);18464if (itmp < 1024) {18465mg_cry_internal(fc(ctx), "%s", "max_request_size too small");18466free_context(ctx);18467pthread_setspecific(sTlsKey, NULL);18468return NULL;18469}18470ctx->max_request_size = (unsigned)itmp;1847118472/* Worker thread count option */18473workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);1847418475if (workerthreadcount > MAX_WORKER_THREADS) {18476mg_cry_internal(fc(ctx), "%s", "Too many worker threads");18477free_context(ctx);18478pthread_setspecific(sTlsKey, NULL);18479return NULL;18480}1848118482if (workerthreadcount <= 0) {18483mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");18484free_context(ctx);18485pthread_setspecific(sTlsKey, NULL);18486return NULL;18487}1848818489/* Document root */18490#if defined(NO_FILES)18491if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {18492mg_cry_internal(fc(ctx), "%s", "Document root must not be set");18493free_context(ctx);18494pthread_setspecific(sTlsKey, NULL);18495return NULL;18496}18497#endif1849818499get_system_name(&ctx->systemName);1850018501#if defined(USE_LUA)18502/* If a Lua background script has been configured, start it. */18503if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {18504char ebuf[256];18505struct vec opt_vec;18506struct vec eq_vec;18507const char *sparams;18508lua_State *state = mg_prepare_lua_context_script(18509ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));18510if (!state) {18511mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);18512free_context(ctx);18513pthread_setspecific(sTlsKey, NULL);18514return NULL;18515}18516ctx->lua_background_state = (void *)state;1851718518lua_newtable(state);18519reg_boolean(state, "shutdown", 0);1852018521sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];1852218523while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {18524reg_llstring(18525state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);18526if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)18527break;18528}18529lua_setglobal(state, LUABACKGROUNDPARAMS);1853018531} else {18532ctx->lua_background_state = 0;18533}18534#endif1853518536/* NOTE(lsm): order is important here. SSL certificates must18537* be initialized before listening ports. UID must be set last. */18538if (!set_gpass_option(ctx, NULL) ||18539#if !defined(NO_SSL)18540!init_ssl_ctx(ctx, NULL) ||18541#endif18542!set_ports_option(ctx) ||18543#if !defined(_WIN32)18544!set_uid_option(ctx) ||18545#endif18546!set_acl_option(ctx)) {18547free_context(ctx);18548pthread_setspecific(sTlsKey, NULL);18549return NULL;18550}1855118552ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));18553ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,18554sizeof(pthread_t),18555ctx);1855618557if (ctx->worker_threadids == NULL) {18558mg_cry_internal(fc(ctx),18559"%s",18560"Not enough memory for worker thread ID array");18561free_context(ctx);18562pthread_setspecific(sTlsKey, NULL);18563return NULL;18564}18565ctx->worker_connections =18566(struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,18567sizeof(struct mg_connection),18568ctx);18569if (ctx->worker_connections == NULL) {18570mg_cry_internal(fc(ctx),18571"%s",18572"Not enough memory for worker thread connection array");18573free_context(ctx);18574pthread_setspecific(sTlsKey, NULL);18575return NULL;18576}185771857818579#if defined(ALTERNATIVE_QUEUE)18580ctx->client_wait_events =18581(void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),18582ctx->cfg_worker_threads,18583ctx);18584if (ctx->client_wait_events == NULL) {18585mg_cry_internal(fc(ctx),18586"%s",18587"Not enough memory for worker event array");18588mg_free(ctx->worker_threadids);18589free_context(ctx);18590pthread_setspecific(sTlsKey, NULL);18591return NULL;18592}1859318594ctx->client_socks =18595(struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),18596ctx->cfg_worker_threads,18597ctx);18598if (ctx->client_socks == NULL) {18599mg_cry_internal(fc(ctx),18600"%s",18601"Not enough memory for worker socket array");18602mg_free(ctx->client_wait_events);18603mg_free(ctx->worker_threadids);18604free_context(ctx);18605pthread_setspecific(sTlsKey, NULL);18606return NULL;18607}1860818609for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {18610ctx->client_wait_events[i] = event_create();18611if (ctx->client_wait_events[i] == 0) {18612mg_cry_internal(fc(ctx), "Error creating worker event %i", i);18613while (i > 0) {18614i--;18615event_destroy(ctx->client_wait_events[i]);18616}18617mg_free(ctx->client_socks);18618mg_free(ctx->client_wait_events);18619mg_free(ctx->worker_threadids);18620free_context(ctx);18621pthread_setspecific(sTlsKey, NULL);18622return NULL;18623}18624}18625#endif186261862718628#if defined(USE_TIMERS)18629if (timers_init(ctx) != 0) {18630mg_cry_internal(fc(ctx), "%s", "Error creating timers");18631free_context(ctx);18632pthread_setspecific(sTlsKey, NULL);18633return NULL;18634}18635#endif1863618637/* Context has been created - init user libraries */18638if (ctx->callbacks.init_context) {18639ctx->callbacks.init_context(ctx);18640}18641ctx->callbacks.exit_context = exit_callback;18642ctx->context_type = CONTEXT_SERVER; /* server context */1864318644/* Start master (listening) thread */18645mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);1864618647/* Start worker threads */18648for (i = 0; i < ctx->cfg_worker_threads; i++) {18649struct worker_thread_args *wta = (struct worker_thread_args *)18650mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);18651if (wta) {18652wta->ctx = ctx;18653wta->index = (int)i;18654}1865518656if ((wta == NULL)18657|| (mg_start_thread_with_id(worker_thread,18658wta,18659&ctx->worker_threadids[i])18660!= 0)) {1866118662/* thread was not created */18663if (wta != NULL) {18664mg_free(wta);18665}1866618667if (i > 0) {18668mg_cry_internal(fc(ctx),18669"Cannot start worker thread %i: error %ld",18670i + 1,18671(long)ERRNO);18672} else {18673mg_cry_internal(fc(ctx),18674"Cannot create threads: error %ld",18675(long)ERRNO);18676free_context(ctx);18677pthread_setspecific(sTlsKey, NULL);18678return NULL;18679}18680break;18681}18682}1868318684pthread_setspecific(sTlsKey, NULL);18685return ctx;18686}186871868818689#if defined(MG_EXPERIMENTAL_INTERFACES)18690/* Add an additional domain to an already running web server. */18691int18692mg_start_domain(struct mg_context *ctx, const char **options)18693{18694const char *name;18695const char *value;18696const char *default_value;18697struct mg_domain_context *new_dom;18698struct mg_domain_context *dom;18699int idx, i;1870018701if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {18702return -1;18703}1870418705new_dom = (struct mg_domain_context *)18706mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);1870718708if (!new_dom) {18709/* Out of memory */18710return -6;18711}1871218713/* Store options - TODO: unite duplicate code */18714while (options && (name = *options++) != NULL) {18715if ((idx = get_option_index(name)) == -1) {18716mg_cry_internal(fc(ctx), "Invalid option: %s", name);18717mg_free(new_dom);18718return -2;18719} else if ((value = *options++) == NULL) {18720mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);18721mg_free(new_dom);18722return -2;18723}18724if (new_dom->config[idx] != NULL) {18725mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);18726mg_free(new_dom->config[idx]);18727}18728new_dom->config[idx] = mg_strdup_ctx(value, ctx);18729DEBUG_TRACE("[%s] -> [%s]", name, value);18730}1873118732/* Authentication domain is mandatory */18733/* TODO: Maybe use a new option hostname? */18734if (!new_dom->config[AUTHENTICATION_DOMAIN]) {18735mg_cry_internal(fc(ctx), "%s", "authentication domain required");18736mg_free(new_dom);18737return -4;18738}1873918740/* Set default value if needed. Take the config value from18741* ctx as a default value. */18742for (i = 0; config_options[i].name != NULL; i++) {18743default_value = ctx->dd.config[i];18744if ((new_dom->config[i] == NULL) && (default_value != NULL)) {18745new_dom->config[i] = mg_strdup_ctx(default_value, ctx);18746}18747}1874818749new_dom->handlers = NULL;18750new_dom->next = NULL;18751new_dom->nonce_count = 0;18752new_dom->auth_nonce_mask =18753(uint64_t)get_random() ^ ((uint64_t)get_random() << 31);1875418755#if defined(USE_LUA) && defined(USE_WEBSOCKET)18756new_dom->shared_lua_websockets = NULL;18757#endif1875818759if (!init_ssl_ctx(ctx, new_dom)) {18760/* Init SSL failed */18761mg_free(new_dom);18762return -3;18763}1876418765/* Add element to linked list. */18766mg_lock_context(ctx);1876718768idx = 0;18769dom = &(ctx->dd);18770for (;;) {18771if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],18772dom->config[AUTHENTICATION_DOMAIN])) {18773/* Domain collision */18774mg_cry_internal(fc(ctx),18775"domain %s already in use",18776new_dom->config[AUTHENTICATION_DOMAIN]);18777mg_free(new_dom);18778return -5;18779}1878018781/* Count number of domains */18782idx++;1878318784if (dom->next == NULL) {18785dom->next = new_dom;18786break;18787}18788dom = dom->next;18789}1879018791mg_unlock_context(ctx);1879218793/* Return domain number */18794return idx;18795}18796#endif187971879818799/* Feature check API function */18800unsigned18801mg_check_feature(unsigned feature)18802{18803static const unsigned feature_set = 018804/* Set bits for available features according to API documentation.18805* This bit mask is created at compile time, according to the active18806* preprocessor defines. It is a single const value at runtime. */18807#if !defined(NO_FILES)18808| MG_FEATURES_FILES18809#endif18810#if !defined(NO_SSL)18811| MG_FEATURES_SSL18812#endif18813#if !defined(NO_CGI)18814| MG_FEATURES_CGI18815#endif18816#if defined(USE_IPV6)18817| MG_FEATURES_IPV618818#endif18819#if defined(USE_WEBSOCKET)18820| MG_FEATURES_WEBSOCKET18821#endif18822#if defined(USE_LUA)18823| MG_FEATURES_LUA18824#endif18825#if defined(USE_DUKTAPE)18826| MG_FEATURES_SSJS18827#endif18828#if !defined(NO_CACHING)18829| MG_FEATURES_CACHE18830#endif18831#if defined(USE_SERVER_STATS)18832| MG_FEATURES_STATS18833#endif18834#if defined(USE_ZLIB)18835| MG_FEATURES_COMPRESSION18836#endif1883718838/* Set some extra bits not defined in the API documentation.18839* These bits may change without further notice. */18840#if defined(MG_LEGACY_INTERFACE)18841| 0x00008000u18842#endif18843#if defined(MG_EXPERIMENTAL_INTERFACES)18844| 0x00004000u18845#endif18846#if defined(MEMORY_DEBUGGING)18847| 0x00001000u18848#endif18849#if defined(USE_TIMERS)18850| 0x00020000u18851#endif18852#if !defined(NO_NONCE_CHECK)18853| 0x00040000u18854#endif18855#if !defined(NO_POPEN)18856| 0x00080000u18857#endif18858;18859return (feature & feature_set);18860}188611886218863/* strcat with additional NULL check to avoid clang scan-build warning. */18864#define strcat0(a, b) \18865{ \18866if ((a != NULL) && (b != NULL)) { \18867strcat(a, b); \18868} \18869}188701887118872/* Get system information. It can be printed or stored by the caller.18873* Return the size of available information. */18874static int18875mg_get_system_info_impl(char *buffer, int buflen)18876{18877char block[256];18878int system_info_length = 0;1887918880#if defined(_WIN32)18881const char *eol = "\r\n";18882#else18883const char *eol = "\n";18884#endif1888518886const char *eoobj = "}";18887int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);1888818889if ((buffer == NULL) || (buflen < 1)) {18890buflen = 0;18891} else {18892*buffer = 0;18893}1889418895mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);18896system_info_length += (int)strlen(block);18897if (system_info_length < buflen) {18898strcat0(buffer, block);18899}1890018901/* Server version */18902{18903const char *version = mg_version();18904mg_snprintf(NULL,18905NULL,18906block,18907sizeof(block),18908"\"version\" : \"%s\",%s",18909version,18910eol);18911system_info_length += (int)strlen(block);18912if (system_info_length < buflen) {18913strcat0(buffer, block);18914}18915}1891618917/* System info */18918{18919#if defined(_WIN32)18920DWORD dwVersion = 0;18921DWORD dwMajorVersion = 0;18922DWORD dwMinorVersion = 0;18923SYSTEM_INFO si;1892418925GetSystemInfo(&si);1892618927#if defined(_MSC_VER)18928#pragma warning(push)18929/* GetVersion was declared deprecated */18930#pragma warning(disable : 4996)18931#endif18932dwVersion = GetVersion();18933#if defined(_MSC_VER)18934#pragma warning(pop)18935#endif1893618937dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));18938dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));1893918940mg_snprintf(NULL,18941NULL,18942block,18943sizeof(block),18944"\"os\" : \"Windows %u.%u\",%s",18945(unsigned)dwMajorVersion,18946(unsigned)dwMinorVersion,18947eol);18948system_info_length += (int)strlen(block);18949if (system_info_length < buflen) {18950strcat0(buffer, block);18951}1895218953mg_snprintf(NULL,18954NULL,18955block,18956sizeof(block),18957"\"cpu\" : \"type %u, cores %u, mask %x\",%s",18958(unsigned)si.wProcessorArchitecture,18959(unsigned)si.dwNumberOfProcessors,18960(unsigned)si.dwActiveProcessorMask,18961eol);18962system_info_length += (int)strlen(block);18963if (system_info_length < buflen) {18964strcat0(buffer, block);18965}18966#else18967struct utsname name;18968memset(&name, 0, sizeof(name));18969uname(&name);1897018971mg_snprintf(NULL,18972NULL,18973block,18974sizeof(block),18975"\"os\" : \"%s %s (%s) - %s\",%s",18976name.sysname,18977name.version,18978name.release,18979name.machine,18980eol);18981system_info_length += (int)strlen(block);18982if (system_info_length < buflen) {18983strcat0(buffer, block);18984}18985#endif18986}1898718988/* Features */18989{18990mg_snprintf(NULL,18991NULL,18992block,18993sizeof(block),18994"\"features\" : %lu,%s"18995"\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",18996(unsigned long)mg_check_feature(0xFFFFFFFFu),18997eol,18998mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",18999mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",19000mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",19001mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",19002mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"19003: "",19004mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",19005mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",19006mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",19007mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",19008eol);19009system_info_length += (int)strlen(block);19010if (system_info_length < buflen) {19011strcat0(buffer, block);19012}1901319014#if defined(USE_LUA)19015mg_snprintf(NULL,19016NULL,19017block,19018sizeof(block),19019"\"lua_version\" : \"%u (%s)\",%s",19020(unsigned)LUA_VERSION_NUM,19021LUA_RELEASE,19022eol);19023system_info_length += (int)strlen(block);19024if (system_info_length < buflen) {19025strcat0(buffer, block);19026}19027#endif19028#if defined(USE_DUKTAPE)19029mg_snprintf(NULL,19030NULL,19031block,19032sizeof(block),19033"\"javascript\" : \"Duktape %u.%u.%u\",%s",19034(unsigned)DUK_VERSION / 10000,19035((unsigned)DUK_VERSION / 100) % 100,19036(unsigned)DUK_VERSION % 100,19037eol);19038system_info_length += (int)strlen(block);19039if (system_info_length < buflen) {19040strcat0(buffer, block);19041}19042#endif19043}1904419045/* Build date */19046{19047#if defined(GCC_DIAGNOSTIC)19048#pragma GCC diagnostic push19049/* Disable bogus compiler warning -Wdate-time */19050#pragma GCC diagnostic ignored "-Wdate-time"19051#endif19052mg_snprintf(NULL,19053NULL,19054block,19055sizeof(block),19056"\"build\" : \"%s\",%s",19057__DATE__,19058eol);1905919060#if defined(GCC_DIAGNOSTIC)19061#pragma GCC diagnostic pop19062#endif1906319064system_info_length += (int)strlen(block);19065if (system_info_length < buflen) {19066strcat0(buffer, block);19067}19068}190691907019071/* Compiler information */19072/* http://sourceforge.net/p/predef/wiki/Compilers/ */19073{19074#if defined(_MSC_VER)19075mg_snprintf(NULL,19076NULL,19077block,19078sizeof(block),19079"\"compiler\" : \"MSC: %u (%u)\",%s",19080(unsigned)_MSC_VER,19081(unsigned)_MSC_FULL_VER,19082eol);19083system_info_length += (int)strlen(block);19084if (system_info_length < buflen) {19085strcat0(buffer, block);19086}19087#elif defined(__MINGW64__)19088mg_snprintf(NULL,19089NULL,19090block,19091sizeof(block),19092"\"compiler\" : \"MinGW64: %u.%u\",%s",19093(unsigned)__MINGW64_VERSION_MAJOR,19094(unsigned)__MINGW64_VERSION_MINOR,19095eol);19096system_info_length += (int)strlen(block);19097if (system_info_length < buflen) {19098strcat0(buffer, block);19099}19100mg_snprintf(NULL,19101NULL,19102block,19103sizeof(block),19104"\"compiler\" : \"MinGW32: %u.%u\",%s",19105(unsigned)__MINGW32_MAJOR_VERSION,19106(unsigned)__MINGW32_MINOR_VERSION,19107eol);19108system_info_length += (int)strlen(block);19109if (system_info_length < buflen) {19110strcat0(buffer, block);19111}19112#elif defined(__MINGW32__)19113mg_snprintf(NULL,19114NULL,19115block,19116sizeof(block),19117"\"compiler\" : \"MinGW32: %u.%u\",%s",19118(unsigned)__MINGW32_MAJOR_VERSION,19119(unsigned)__MINGW32_MINOR_VERSION,19120eol);19121system_info_length += (int)strlen(block);19122if (system_info_length < buflen) {19123strcat0(buffer, block);19124}19125#elif defined(__clang__)19126mg_snprintf(NULL,19127NULL,19128block,19129sizeof(block),19130"\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",19131__clang_major__,19132__clang_minor__,19133__clang_patchlevel__,19134__clang_version__,19135eol);19136system_info_length += (int)strlen(block);19137if (system_info_length < buflen) {19138strcat0(buffer, block);19139}19140#elif defined(__GNUC__)19141mg_snprintf(NULL,19142NULL,19143block,19144sizeof(block),19145"\"compiler\" : \"gcc: %u.%u.%u\",%s",19146(unsigned)__GNUC__,19147(unsigned)__GNUC_MINOR__,19148(unsigned)__GNUC_PATCHLEVEL__,19149eol);19150system_info_length += (int)strlen(block);19151if (system_info_length < buflen) {19152strcat0(buffer, block);19153}19154#elif defined(__INTEL_COMPILER)19155mg_snprintf(NULL,19156NULL,19157block,19158sizeof(block),19159"\"compiler\" : \"Intel C/C++: %u\",%s",19160(unsigned)__INTEL_COMPILER,19161eol);19162system_info_length += (int)strlen(block);19163if (system_info_length < buflen) {19164strcat0(buffer, block);19165}19166#elif defined(__BORLANDC__)19167mg_snprintf(NULL,19168NULL,19169block,19170sizeof(block),19171"\"compiler\" : \"Borland C: 0x%x\",%s",19172(unsigned)__BORLANDC__,19173eol);19174system_info_length += (int)strlen(block);19175if (system_info_length < buflen) {19176strcat0(buffer, block);19177}19178#elif defined(__SUNPRO_C)19179mg_snprintf(NULL,19180NULL,19181block,19182sizeof(block),19183"\"compiler\" : \"Solaris: 0x%x\",%s",19184(unsigned)__SUNPRO_C,19185eol);19186system_info_length += (int)strlen(block);19187if (system_info_length < buflen) {19188strcat0(buffer, block);19189}19190#else19191mg_snprintf(NULL,19192NULL,19193block,19194sizeof(block),19195"\"compiler\" : \"other\",%s",19196eol);19197system_info_length += (int)strlen(block);19198if (system_info_length < buflen) {19199strcat0(buffer, block);19200}19201#endif19202}1920319204/* Determine 32/64 bit data mode.19205* see https://en.wikipedia.org/wiki/64-bit_computing */19206{19207mg_snprintf(NULL,19208NULL,19209block,19210sizeof(block),19211"\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "19212"char:%u/%u, "19213"ptr:%u, size:%u, time:%u\"%s",19214(unsigned)sizeof(short),19215(unsigned)sizeof(int),19216(unsigned)sizeof(long),19217(unsigned)sizeof(long long),19218(unsigned)sizeof(float),19219(unsigned)sizeof(double),19220(unsigned)sizeof(long double),19221(unsigned)sizeof(char),19222(unsigned)sizeof(wchar_t),19223(unsigned)sizeof(void *),19224(unsigned)sizeof(size_t),19225(unsigned)sizeof(time_t),19226eol);19227system_info_length += (int)strlen(block);19228if (system_info_length < buflen) {19229strcat0(buffer, block);19230}19231}1923219233/* Terminate string */19234if ((buflen > 0) && buffer && buffer[0]) {19235if (system_info_length < buflen) {19236strcat0(buffer, eoobj);19237strcat0(buffer, eol);19238}19239}19240system_info_length += reserved_len;1924119242return system_info_length;19243}192441924519246#if defined(USE_SERVER_STATS)19247/* Get context information. It can be printed or stored by the caller.19248* Return the size of available information. */19249static int19250mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)1925119252{19253char block[256];19254int context_info_length = 0;1925519256#if defined(_WIN32)19257const char *eol = "\r\n";19258#else19259const char *eol = "\n";19260#endif19261struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);1926219263const char *eoobj = "}";19264int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);1926519266if ((buffer == NULL) || (buflen < 1)) {19267buflen = 0;19268} else {19269*buffer = 0;19270}1927119272mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);19273context_info_length += (int)strlen(block);19274if (context_info_length < buflen) {19275strcat0(buffer, block);19276}1927719278if (ms) { /* <-- should be always true */19279/* Memory information */19280mg_snprintf(NULL,19281NULL,19282block,19283sizeof(block),19284"\"memory\" : {%s"19285"\"blocks\" : %i,%s"19286"\"used\" : %" INT64_FMT ",%s"19287"\"maxUsed\" : %" INT64_FMT "%s"19288"}%s%s",19289eol,19290ms->blockCount,19291eol,19292ms->totalMemUsed,19293eol,19294ms->maxMemUsed,19295eol,19296(ctx ? "," : ""),19297eol);1929819299context_info_length += (int)strlen(block);19300if (context_info_length + reserved_len < buflen) {19301strcat0(buffer, block);19302}19303}1930419305if (ctx) {19306/* Declare all variables at begin of the block, to comply19307* with old C standards. */19308char start_time_str[64] = {0};19309char now_str[64] = {0};19310time_t start_time = ctx->start_time;19311time_t now = time(NULL);1931219313/* Connections information */19314mg_snprintf(NULL,19315NULL,19316block,19317sizeof(block),19318"\"connections\" : {%s"19319"\"active\" : %i,%s"19320"\"maxActive\" : %i,%s"19321"\"total\" : %" INT64_FMT "%s"19322"},%s",19323eol,19324ctx->active_connections,19325eol,19326ctx->max_connections,19327eol,19328ctx->total_connections,19329eol,19330eol);1933119332context_info_length += (int)strlen(block);19333if (context_info_length + reserved_len < buflen) {19334strcat0(buffer, block);19335}1933619337/* Requests information */19338mg_snprintf(NULL,19339NULL,19340block,19341sizeof(block),19342"\"requests\" : {%s"19343"\"total\" : %" INT64_FMT "%s"19344"},%s",19345eol,19346ctx->total_requests,19347eol,19348eol);1934919350context_info_length += (int)strlen(block);19351if (context_info_length + reserved_len < buflen) {19352strcat0(buffer, block);19353}1935419355/* Data information */19356mg_snprintf(NULL,19357NULL,19358block,19359sizeof(block),19360"\"data\" : {%s"19361"\"read\" : %" INT64_FMT "%s,"19362"\"written\" : %" INT64_FMT "%s"19363"},%s",19364eol,19365ctx->total_data_read,19366eol,19367ctx->total_data_written,19368eol,19369eol);1937019371context_info_length += (int)strlen(block);19372if (context_info_length + reserved_len < buflen) {19373strcat0(buffer, block);19374}1937519376/* Execution time information */19377gmt_time_string(start_time_str,19378sizeof(start_time_str) - 1,19379&start_time);19380gmt_time_string(now_str, sizeof(now_str) - 1, &now);1938119382mg_snprintf(NULL,19383NULL,19384block,19385sizeof(block),19386"\"time\" : {%s"19387"\"uptime\" : %.0f,%s"19388"\"start\" : \"%s\",%s"19389"\"now\" : \"%s\"%s"19390"}%s",19391eol,19392difftime(now, start_time),19393eol,19394start_time_str,19395eol,19396now_str,19397eol,19398eol);1939919400context_info_length += (int)strlen(block);19401if (context_info_length + reserved_len < buflen) {19402strcat0(buffer, block);19403}19404}1940519406/* Terminate string */19407if ((buflen > 0) && buffer && buffer[0]) {19408if (context_info_length < buflen) {19409strcat0(buffer, eoobj);19410strcat0(buffer, eol);19411}19412}19413context_info_length += reserved_len;1941419415return context_info_length;19416}19417#endif194181941919420#if defined(MG_EXPERIMENTAL_INTERFACES)19421/* Get connection information. It can be printed or stored by the caller.19422* Return the size of available information. */19423static int19424mg_get_connection_info_impl(const struct mg_context *ctx,19425int idx,19426char *buffer,19427int buflen)19428{19429const struct mg_connection *conn;19430const struct mg_request_info *ri;19431char block[256];19432int connection_info_length = 0;19433int state = 0;19434const char *state_str = "unknown";1943519436#if defined(_WIN32)19437const char *eol = "\r\n";19438#else19439const char *eol = "\n";19440#endif1944119442const char *eoobj = "}";19443int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);1944419445if ((buffer == NULL) || (buflen < 1)) {19446buflen = 0;19447} else {19448*buffer = 0;19449}1945019451if ((ctx == NULL) || (idx < 0)) {19452/* Parameter error */19453return 0;19454}1945519456if ((unsigned)idx >= ctx->cfg_worker_threads) {19457/* Out of range */19458return 0;19459}1946019461/* Take connection [idx]. This connection is not locked in19462* any way, so some other thread might use it. */19463conn = (ctx->worker_connections) + idx;1946419465/* Initialize output string */19466mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);19467connection_info_length += (int)strlen(block);19468if (connection_info_length < buflen) {19469strcat0(buffer, block);19470}1947119472/* Init variables */19473ri = &(conn->request_info);1947419475#if defined(USE_SERVER_STATS)19476state = conn->conn_state;1947719478/* State as string */19479switch (state) {19480case 0:19481state_str = "undefined";19482break;19483case 1:19484state_str = "not used";19485break;19486case 2:19487state_str = "init";19488break;19489case 3:19490state_str = "ready";19491break;19492case 4:19493state_str = "processing";19494break;19495case 5:19496state_str = "processed";19497break;19498case 6:19499state_str = "to close";19500break;19501case 7:19502state_str = "closing";19503break;19504case 8:19505state_str = "closed";19506break;19507case 9:19508state_str = "done";19509break;19510}19511#endif1951219513/* Connection info */19514if ((state >= 3) && (state < 9)) {19515mg_snprintf(NULL,19516NULL,19517block,19518sizeof(block),19519"\"connection\" : {%s"19520"\"remote\" : {%s"19521"\"protocol\" : \"%s\",%s"19522"\"addr\" : \"%s\",%s"19523"\"port\" : %u%s"19524"},%s"19525"\"handled_requests\" : %u%s"19526"},%s",19527eol,19528eol,19529get_proto_name(conn),19530eol,19531ri->remote_addr,19532eol,19533ri->remote_port,19534eol,19535eol,19536conn->handled_requests,19537eol,19538eol);1953919540connection_info_length += (int)strlen(block);19541if (connection_info_length + reserved_len < buflen) {19542strcat0(buffer, block);19543}19544}1954519546/* Request info */19547if ((state >= 4) && (state < 6)) {19548mg_snprintf(NULL,19549NULL,19550block,19551sizeof(block),19552"\"request_info\" : {%s"19553"\"method\" : \"%s\",%s"19554"\"uri\" : \"%s\",%s"19555"\"query\" : %s%s%s%s"19556"},%s",19557eol,19558ri->request_method,19559eol,19560ri->request_uri,19561eol,19562ri->query_string ? "\"" : "",19563ri->query_string ? ri->query_string : "null",19564ri->query_string ? "\"" : "",19565eol,19566eol);1956719568connection_info_length += (int)strlen(block);19569if (connection_info_length + reserved_len < buflen) {19570strcat0(buffer, block);19571}19572}1957319574/* Execution time information */19575if ((state >= 2) && (state < 9)) {19576char start_time_str[64] = {0};19577char now_str[64] = {0};19578time_t start_time = conn->conn_birth_time;19579time_t now = time(NULL);1958019581gmt_time_string(start_time_str,19582sizeof(start_time_str) - 1,19583&start_time);19584gmt_time_string(now_str, sizeof(now_str) - 1, &now);1958519586mg_snprintf(NULL,19587NULL,19588block,19589sizeof(block),19590"\"time\" : {%s"19591"\"uptime\" : %.0f,%s"19592"\"start\" : \"%s\",%s"19593"\"now\" : \"%s\"%s"19594"},%s",19595eol,19596difftime(now, start_time),19597eol,19598start_time_str,19599eol,19600now_str,19601eol,19602eol);1960319604connection_info_length += (int)strlen(block);19605if (connection_info_length + reserved_len < buflen) {19606strcat0(buffer, block);19607}19608}1960919610/* Remote user name */19611if ((ri->remote_user) && (state < 9)) {19612mg_snprintf(NULL,19613NULL,19614block,19615sizeof(block),19616"\"user\" : {%s"19617"\"name\" : \"%s\",%s"19618"},%s",19619eol,19620ri->remote_user,19621eol,19622eol);1962319624connection_info_length += (int)strlen(block);19625if (connection_info_length + reserved_len < buflen) {19626strcat0(buffer, block);19627}19628}1962919630/* Data block */19631if (state >= 3) {19632mg_snprintf(NULL,19633NULL,19634block,19635sizeof(block),19636"\"data\" : {%s"19637"\"read\" : %" INT64_FMT ",%s"19638"\"written\" : %" INT64_FMT "%s"19639"},%s",19640eol,19641conn->consumed_content,19642eol,19643conn->num_bytes_sent,19644eol,19645eol);1964619647connection_info_length += (int)strlen(block);19648if (connection_info_length + reserved_len < buflen) {19649strcat0(buffer, block);19650}19651}1965219653/* State */19654mg_snprintf(NULL,19655NULL,19656block,19657sizeof(block),19658"\"state\" : \"%s\"%s",19659state_str,19660eol);1966119662connection_info_length += (int)strlen(block);19663if (connection_info_length + reserved_len < buflen) {19664strcat0(buffer, block);19665}1966619667/* Terminate string */19668if ((buflen > 0) && buffer && buffer[0]) {19669if (connection_info_length < buflen) {19670strcat0(buffer, eoobj);19671strcat0(buffer, eol);19672}19673}19674connection_info_length += reserved_len;1967519676return connection_info_length;19677}19678#endif196791968019681/* Get system information. It can be printed or stored by the caller.19682* Return the size of available information. */19683int19684mg_get_system_info(char *buffer, int buflen)19685{19686if ((buffer == NULL) || (buflen < 1)) {19687return mg_get_system_info_impl(NULL, 0);19688} else {19689/* Reset buffer, so we can always use strcat. */19690buffer[0] = 0;19691return mg_get_system_info_impl(buffer, buflen);19692}19693}196941969519696/* Get context information. It can be printed or stored by the caller.19697* Return the size of available information. */19698int19699mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)19700{19701#if defined(USE_SERVER_STATS)19702if ((buffer == NULL) || (buflen < 1)) {19703return mg_get_context_info_impl(ctx, NULL, 0);19704} else {19705/* Reset buffer, so we can always use strcat. */19706buffer[0] = 0;19707return mg_get_context_info_impl(ctx, buffer, buflen);19708}19709#else19710(void)ctx;19711if ((buffer != NULL) && (buflen > 0)) {19712buffer[0] = 0;19713}19714return 0;19715#endif19716}197171971819719#if defined(MG_EXPERIMENTAL_INTERFACES)19720int19721mg_get_connection_info(const struct mg_context *ctx,19722int idx,19723char *buffer,19724int buflen)19725{19726if ((buffer == NULL) || (buflen < 1)) {19727return mg_get_connection_info_impl(ctx, idx, NULL, 0);19728} else {19729/* Reset buffer, so we can always use strcat. */19730buffer[0] = 0;19731return mg_get_connection_info_impl(ctx, idx, buffer, buflen);19732}19733}19734#endif197351973619737/* Initialize this library. This function does not need to be thread safe.19738*/19739unsigned19740mg_init_library(unsigned features)19741{19742#if !defined(NO_SSL)19743char ebuf[128];19744#endif1974519746unsigned features_to_init = mg_check_feature(features & 0xFFu);19747unsigned features_inited = features_to_init;1974819749if (mg_init_library_called <= 0) {19750/* Not initialized yet */19751if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {19752return 0;19753}19754}1975519756mg_global_lock();1975719758if (mg_init_library_called <= 0) {19759if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {19760/* Fatal error - abort start. However, this situation should19761* never occur in practice. */19762mg_global_unlock();19763return 0;19764}1976519766#if defined(_WIN32)19767InitializeCriticalSection(&global_log_file_lock);19768#endif19769#if !defined(_WIN32)19770pthread_mutexattr_init(&pthread_mutex_attr);19771pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);19772#endif1977319774#if defined(USE_LUA)19775lua_init_optional_libraries();19776#endif19777}1977819779mg_global_unlock();1978019781#if !defined(NO_SSL)19782if (features_to_init & MG_FEATURES_SSL) {19783if (!mg_ssl_initialized) {19784if (initialize_ssl(ebuf, sizeof(ebuf))) {19785mg_ssl_initialized = 1;19786} else {19787(void)ebuf;19788DEBUG_TRACE("Initializing SSL failed: %s", ebuf);19789features_inited &= ~((unsigned)(MG_FEATURES_SSL));19790}19791} else {19792/* ssl already initialized */19793}19794}19795#endif1979619797/* Start WinSock for Windows */19798mg_global_lock();19799if (mg_init_library_called <= 0) {19800#if defined(_WIN32)19801WSADATA data;19802WSAStartup(MAKEWORD(2, 2), &data);19803#endif /* _WIN32 */19804mg_init_library_called = 1;19805} else {19806mg_init_library_called++;19807}19808mg_global_unlock();1980919810return features_inited;19811}198121981319814/* Un-initialize this library. */19815unsigned19816mg_exit_library(void)19817{19818if (mg_init_library_called <= 0) {19819return 0;19820}1982119822mg_global_lock();1982319824mg_init_library_called--;19825if (mg_init_library_called == 0) {19826#if defined(_WIN32)19827(void)WSACleanup();19828#endif /* _WIN32 */19829#if !defined(NO_SSL)19830if (mg_ssl_initialized) {19831uninitialize_ssl();19832mg_ssl_initialized = 0;19833}19834#endif1983519836#if defined(_WIN32)19837(void)DeleteCriticalSection(&global_log_file_lock);19838#endif /* _WIN32 */19839#if !defined(_WIN32)19840(void)pthread_mutexattr_destroy(&pthread_mutex_attr);19841#endif1984219843(void)pthread_key_delete(sTlsKey);1984419845#if defined(USE_LUA)19846lua_exit_optional_libraries();19847#endif1984819849mg_global_unlock();19850(void)pthread_mutex_destroy(&global_lock_mutex);19851return 1;19852}1985319854mg_global_unlock();19855return 1;19856}198571985819859/* End of civetweb.c */198601986119862