Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
civetweb.c
Go to the documentation of this file.
1/* Copyright (c) 2013-2021 the Civetweb developers
2 * Copyright (c) 2004-2013 Sergey Lyubka
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23#if defined(__GNUC__) || defined(__MINGW32__)
24#define GCC_VERSION \
25 (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
26#if GCC_VERSION >= 40500
27/* gcc diagnostic pragmas available */
28#define GCC_DIAGNOSTIC
29#endif
30#endif
31
32#if defined(GCC_DIAGNOSTIC)
33/* Disable unused macros warnings - not all defines are required
34 * for all systems and all compilers. */
35#pragma GCC diagnostic ignored "-Wunused-macros"
36/* A padding warning is just plain useless */
37#pragma GCC diagnostic ignored "-Wpadded"
38#endif
39
40#if defined(__clang__) /* GCC does not (yet) support this pragma */
41/* We must set some flags for the headers we include. These flags
42 * are reserved ids according to C99, so we need to disable a
43 * warning for that. */
44#pragma GCC diagnostic push
45#pragma GCC diagnostic ignored "-Wreserved-id-macro"
46#endif
47
48#if defined(_WIN32)
49#if !defined(_CRT_SECURE_NO_WARNINGS)
50#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
51#endif
52#if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
53#define _WIN32_WINNT 0x0502
54#endif
55#else
56#if !defined(_GNU_SOURCE)
57#define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
58#endif
59#if defined(__linux__) && !defined(_XOPEN_SOURCE)
60#define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
61#endif
62#if defined(__LSB_VERSION__) || defined(__sun)
63#define NEED_TIMEGM
64#define NO_THREAD_NAME
65#endif
66#if !defined(_LARGEFILE_SOURCE)
67#define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
68#endif
69#if !defined(_FILE_OFFSET_BITS)
70#define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
71#endif
72#if !defined(__STDC_FORMAT_MACROS)
73#define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
74#endif
75#if !defined(__STDC_LIMIT_MACROS)
76#define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
77#endif
78#if !defined(_DARWIN_UNLIMITED_SELECT)
79#define _DARWIN_UNLIMITED_SELECT
80#endif
81#if defined(__sun)
82#define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
83#define __inline inline /* not recognized on older compiler versions */
84#endif
85#endif
86
87#if defined(__clang__)
88/* Enable reserved-id-macro warning again. */
89#pragma GCC diagnostic pop
90#endif
91
92
93#if defined(USE_LUA)
94#define USE_TIMERS
95#endif
96
97#if defined(_MSC_VER)
98/* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
99#pragma warning(disable : 4306)
100/* conditional expression is constant: introduced by FD_SET(..) */
101#pragma warning(disable : 4127)
102/* non-constant aggregate initializer: issued due to missing C99 support */
103#pragma warning(disable : 4204)
104/* padding added after data member */
105#pragma warning(disable : 4820)
106/* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
107#pragma warning(disable : 4668)
108/* no function prototype given: converting '()' to '(void)' */
109#pragma warning(disable : 4255)
110/* function has been selected for automatic inline expansion */
111#pragma warning(disable : 4711)
112#endif
113
114
115/* This code uses static_assert to check some conditions.
116 * Unfortunately some compilers still do not support it, so we have a
117 * replacement function here. */
118#if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
119#define mg_static_assert _Static_assert
120#elif defined(__cplusplus) && __cplusplus >= 201103L
121#define mg_static_assert static_assert
122#else
124#define mg_static_assert(cond, txt) \
125 extern char static_assert_replacement[(cond) ? 1 : -1]
126#endif
127
128mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
129 "int data type size check");
130mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
131 "pointer data type size check");
132mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
133
134
135/* Select queue implementation. Diagnosis features originally only implemented
136 * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
137 * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
138 * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
139 * implementation, since the queue length is independent from the number of
140 * worker threads there, while the new queue is one element per worker thread.
141 *
142 */
143#if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
144/* The queues are exclusive or - only one can be used. */
145#error \
146 "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
147#endif
148#if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
149/* Use a default implementation */
150#define NO_ALTERNATIVE_QUEUE
151#endif
152
153#if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
154/* File system access:
155 * NO_FILES = do not serve any files from the file system automatically.
156 * However, with NO_FILES CivetWeb may still write log files, read access
157 * control files, default error page files or use API functions like
158 * mg_send_file in callbacks to send files from the server local
159 * file system.
160 * NO_FILES only disables the automatic mapping between URLs and local
161 * file names.
162 * NO_FILESYSTEM = do not access any file at all. Useful for embedded
163 * devices without file system. Logging to files in not available
164 * (use callbacks instead) and API functions like mg_send_file are not
165 * available.
166 * If NO_FILESYSTEM is set, NO_FILES must be set as well.
167 */
168#error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
169#endif
170
171/* DTL -- including winsock2.h works better if lean and mean */
172#if !defined(WIN32_LEAN_AND_MEAN)
173#define WIN32_LEAN_AND_MEAN
174#endif
175
176#if defined(__SYMBIAN32__)
177/* According to https://en.wikipedia.org/wiki/Symbian#History,
178 * Symbian is no longer maintained since 2014-01-01.
179 * Support for Symbian has been removed from CivetWeb
180 */
181#error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
182#endif /* __SYMBIAN32__ */
183
184#if defined(__ZEPHYR__)
185#include <time.h>
186
187#include <ctype.h>
188#include <net/socket.h>
189#include <posix/pthread.h>
190#include <posix/time.h>
191#include <stdio.h>
192#include <stdlib.h>
193#include <string.h>
194#include <zephyr.h>
195
196#include <fcntl.h>
197
198#include <libc_extensions.h>
199
200/* Max worker threads is the max of pthreads minus the main application thread
201 * and minus the main civetweb thread, thus -2
202 */
203#define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
204
205#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
206#define ZEPHYR_STACK_SIZE USE_STACK_SIZE
207#else
208#define ZEPHYR_STACK_SIZE (1024 * 16)
209#endif
210
211K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
212K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
214 ZEPHYR_STACK_SIZE);
215
216static int zephyr_worker_stack_index;
217
218#endif
219
220#if !defined(CIVETWEB_HEADER_INCLUDED)
221/* Include the header file here, so the CivetWeb interface is defined for the
222 * entire implementation, including the following forward definitions. */
223#include "civetweb.h"
224#endif
225
226#if !defined(DEBUG_TRACE)
227#if defined(DEBUG)
228static void DEBUG_TRACE_FUNC(const char *func,
229 unsigned line,
230 PRINTF_FORMAT_STRING(const char *fmt),
231 ...) PRINTF_ARGS(3, 4);
232
233#define DEBUG_TRACE(fmt, ...) \
234 DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
235
236#define NEED_DEBUG_TRACE_FUNC
237#if !defined(DEBUG_TRACE_STREAM)
238#define DEBUG_TRACE_STREAM stdout
239#endif
240
241#else
242#define DEBUG_TRACE(fmt, ...) \
243 do { \
244 } while (0)
245#endif /* DEBUG */
246#endif /* DEBUG_TRACE */
247
248
249#if !defined(DEBUG_ASSERT)
250#if defined(DEBUG)
251#include <stdlib.h>
252#define DEBUG_ASSERT(cond) \
253 do { \
254 if (!(cond)) { \
255 DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
256 exit(2); /* Exit with error */ \
257 } \
258 } while (0)
259#else
260#define DEBUG_ASSERT(cond)
261#endif /* DEBUG */
262#endif
263
264
265#if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
266void __cyg_profile_func_enter(void *this_fn, void *call_site)
267 __attribute__((no_instrument_function));
268
269void __cyg_profile_func_exit(void *this_fn, void *call_site)
270 __attribute__((no_instrument_function));
271
272void
273__cyg_profile_func_enter(void *this_fn, void *call_site)
274{
275 if ((void *)this_fn != (void *)printf) {
276 printf("E %p %p\n", this_fn, call_site);
277 }
278}
279
280void
281__cyg_profile_func_exit(void *this_fn, void *call_site)
282{
283 if ((void *)this_fn != (void *)printf) {
284 printf("X %p %p\n", this_fn, call_site);
285 }
286}
287#endif
288
289
290#if !defined(IGNORE_UNUSED_RESULT)
291#define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
292#endif
293
294
295#if defined(__GNUC__) || defined(__MINGW32__)
296
297/* GCC unused function attribute seems fundamentally broken.
298 * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
299 * OR UNUSED" for individual functions failed.
300 * Either the compiler creates an "unused-function" warning if a
301 * function is not marked with __attribute__((unused)).
302 * On the other hand, if the function is marked with this attribute,
303 * but is used, the compiler raises a completely idiotic
304 * "used-but-marked-unused" warning - and
305 * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
306 * raises error: unknown option after "#pragma GCC diagnostic".
307 * Disable this warning completely, until the GCC guys sober up
308 * again.
309 */
310
311#pragma GCC diagnostic ignored "-Wunused-function"
312
313#define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
314
315#else
316#define FUNCTION_MAY_BE_UNUSED
317#endif
318
319
320/* Some ANSI #includes are not available on Windows CE and Zephyr */
321#if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
322#include <errno.h>
323#include <fcntl.h>
324#include <signal.h>
325#include <stdlib.h>
326#include <sys/stat.h>
327#include <sys/types.h>
328#endif /* !_WIN32_WCE */
329
330
331#if defined(__clang__)
332/* When using -Weverything, clang does not accept it's own headers
333 * in a release build configuration. Disable what is too much in
334 * -Weverything. */
335#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
336#endif
337
338#if defined(__GNUC__) || defined(__MINGW32__)
339/* Who on earth came to the conclusion, using __DATE__ should rise
340 * an "expansion of date or time macro is not reproducible"
341 * warning. That's exactly what was intended by using this macro.
342 * Just disable this nonsense warning. */
343
344/* And disabling them does not work either:
345 * #pragma clang diagnostic ignored "-Wno-error=date-time"
346 * #pragma clang diagnostic ignored "-Wdate-time"
347 * So we just have to disable ALL warnings for some lines
348 * of code.
349 * This seems to be a known GCC bug, not resolved since 2012:
350 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
351 */
352#endif
353
354
355#if defined(__MACH__) /* Apple OSX section */
356
357#if defined(__clang__)
358#if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
359/* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
360#pragma clang diagnostic ignored "-Wno-reserved-id-macro"
361#pragma clang diagnostic ignored "-Wno-keyword-macro"
362#endif
363#endif
364
365#ifndef CLOCK_MONOTONIC
366#define CLOCK_MONOTONIC (1)
367#endif
368#ifndef CLOCK_REALTIME
369#define CLOCK_REALTIME (2)
370#endif
371
372#include <mach/clock.h>
373#include <mach/mach.h>
374#include <mach/mach_time.h>
375#include <sys/errno.h>
376#include <sys/time.h>
377
378/* clock_gettime is not implemented on OSX prior to 10.12 */
379static int
380_civet_clock_gettime(int clk_id, struct timespec *t)
381{
382 memset(t, 0, sizeof(*t));
383 if (clk_id == CLOCK_REALTIME) {
384 struct timeval now;
385 int rv = gettimeofday(&now, NULL);
386 if (rv) {
387 return rv;
388 }
389 t->tv_sec = now.tv_sec;
390 t->tv_nsec = now.tv_usec * 1000;
391 return 0;
392
393 } else if (clk_id == CLOCK_MONOTONIC) {
394 static uint64_t clock_start_time = 0;
395 static mach_timebase_info_data_t timebase_ifo = {0, 0};
396
397 uint64_t now = mach_absolute_time();
398
399 if (clock_start_time == 0) {
400 kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
401 DEBUG_ASSERT(mach_status == KERN_SUCCESS);
402
403 /* appease "unused variable" warning for release builds */
404 (void)mach_status;
405
406 clock_start_time = now;
407 }
408
409 now = (uint64_t)((double)(now - clock_start_time)
410 * (double)timebase_ifo.numer
411 / (double)timebase_ifo.denom);
412
413 t->tv_sec = now / 1000000000;
414 t->tv_nsec = now % 1000000000;
415 return 0;
416 }
417 return -1; /* EINVAL - Clock ID is unknown */
418}
419
420/* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
421#if defined(__CLOCK_AVAILABILITY)
422/* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
423 * declared but it may be NULL at runtime. So we need to check before using
424 * it. */
425static int
426_civet_safe_clock_gettime(int clk_id, struct timespec *t)
427{
428 if (clock_gettime) {
429 return clock_gettime(clk_id, t);
430 }
431 return _civet_clock_gettime(clk_id, t);
432}
433#define clock_gettime _civet_safe_clock_gettime
434#else
435#define clock_gettime _civet_clock_gettime
436#endif
437
438#endif
439
440
441#if !defined(_WIN32)
442/* Unix might return different error codes indicating to try again.
443 * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
444 * decades ago, but better check both and let the compile optimize it. */
445#define ERROR_TRY_AGAIN(err) \
446 (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
447#endif
448
449#if defined(USE_ZLIB)
450#include "zconf.h"
451#include "zlib.h"
452#endif
453
454
455/********************************************************************/
456/* CivetWeb configuration defines */
457/********************************************************************/
458
459/* Maximum number of threads that can be configured.
460 * The number of threads actually created depends on the "num_threads"
461 * configuration parameter, but this is the upper limit. */
462#if !defined(MAX_WORKER_THREADS)
463#define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
464#endif
465
466/* Timeout interval for select/poll calls.
467 * The timeouts depend on "*_timeout_ms" configuration values, but long
468 * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
469 * This reduces the time required to stop the server. */
470#if !defined(SOCKET_TIMEOUT_QUANTUM)
471#define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
472#endif
473
474/* Do not try to compress files smaller than this limit. */
475#if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
476#define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
477#endif
478
479#if !defined(PASSWORDS_FILE_NAME)
480#define PASSWORDS_FILE_NAME ".htpasswd"
481#endif
482
483/* Initial buffer size for all CGI environment variables. In case there is
484 * not enough space, another block is allocated. */
485#if !defined(CGI_ENVIRONMENT_SIZE)
486#define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
487#endif
488
489/* Maximum number of environment variables. */
490#if !defined(MAX_CGI_ENVIR_VARS)
491#define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
492#endif
493
494/* General purpose buffer size. */
495#if !defined(MG_BUF_LEN) /* in bytes */
496#define MG_BUF_LEN (1024 * 8)
497#endif
498
499
500/********************************************************************/
501
502/* Helper makros */
503#if !defined(ARRAY_SIZE)
504#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
505#endif
506
507#include <stdint.h>
508
509/* Standard defines */
510#if !defined(INT64_MAX)
511#define INT64_MAX (9223372036854775807)
512#endif
513
514#define SHUTDOWN_RD (0)
515#define SHUTDOWN_WR (1)
516#define SHUTDOWN_BOTH (2)
517
519 "worker threads must be a positive number");
520
521mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
522 "size_t data type size check");
523
524
525#if defined(_WIN32) /* WINDOWS include block */
526#include <malloc.h> /* *alloc( */
527#include <stdlib.h> /* *alloc( */
528#include <time.h> /* struct timespec */
529#include <windows.h>
530#include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
531#include <ws2tcpip.h>
532
533typedef const char *SOCK_OPT_TYPE;
534
535/* For a detailed description of these *_PATH_MAX defines, see
536 * https://github.com/civetweb/civetweb/issues/937. */
537
538/* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
539 * null termination, rounded up to the next 4 bytes boundary */
540#define UTF8_PATH_MAX (3 * 260)
541/* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
542 * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
543#define UTF16_PATH_MAX (260)
544
545#if !defined(_IN_PORT_T)
546#if !defined(in_port_t)
547#define in_port_t u_short
548#endif
549#endif
550
551#if defined(_WIN32_WCE)
552#error "WinCE support has ended"
553#endif
554
555#include <direct.h>
556#include <io.h>
557#include <process.h>
558
559
560#define MAKEUQUAD(lo, hi) \
561 ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
562#define RATE_DIFF (10000000) /* 100 nsecs */
563#define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
564#define SYS2UNIX_TIME(lo, hi) \
565 ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
566
567/* Visual Studio 6 does not know __func__ or __FUNCTION__
568 * The rest of MS compilers use __FUNCTION__, not C99 __func__
569 * Also use _strtoui64 on modern M$ compilers */
570#if defined(_MSC_VER)
571#if (_MSC_VER < 1300)
572#define STRX(x) #x
573#define STR(x) STRX(x)
574#define __func__ __FILE__ ":" STR(__LINE__)
575#define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
576#define strtoll(x, y, z) (_atoi64(x))
577#else
578#define __func__ __FUNCTION__
579#define strtoull(x, y, z) (_strtoui64(x, y, z))
580#define strtoll(x, y, z) (_strtoi64(x, y, z))
581#endif
582#endif /* _MSC_VER */
583
584#define ERRNO ((int)(GetLastError()))
585#define NO_SOCKLEN_T
586
587
588#if defined(_WIN64) || defined(__MINGW64__)
589#if !defined(SSL_LIB)
590
591#if defined(OPENSSL_API_3_0)
592#define SSL_LIB "libssl-3-x64.dll"
593#define CRYPTO_LIB "libcrypto-3-x64.dll"
594#endif
595
596#if defined(OPENSSL_API_1_1)
597#define SSL_LIB "libssl-1_1-x64.dll"
598#define CRYPTO_LIB "libcrypto-1_1-x64.dll"
599#endif /* OPENSSL_API_1_1 */
600
601#if defined(OPENSSL_API_1_0)
602#define SSL_LIB "ssleay64.dll"
603#define CRYPTO_LIB "libeay64.dll"
604#endif /* OPENSSL_API_1_0 */
605
606#endif
607#else /* defined(_WIN64) || defined(__MINGW64__) */
608#if !defined(SSL_LIB)
609
610#if defined(OPENSSL_API_3_0)
611#define SSL_LIB "libssl-3.dll"
612#define CRYPTO_LIB "libcrypto-3.dll"
613#endif
614
615#if defined(OPENSSL_API_1_1)
616#define SSL_LIB "libssl-1_1.dll"
617#define CRYPTO_LIB "libcrypto-1_1.dll"
618#endif /* OPENSSL_API_1_1 */
619
620#if defined(OPENSSL_API_1_0)
621#define SSL_LIB "ssleay32.dll"
622#define CRYPTO_LIB "libeay32.dll"
623#endif /* OPENSSL_API_1_0 */
624
625#endif /* SSL_LIB */
626#endif /* defined(_WIN64) || defined(__MINGW64__) */
627
628
629#define O_NONBLOCK (0)
630#if !defined(W_OK)
631#define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
632#endif
633#define _POSIX_
634#define INT64_FMT "I64d"
635#define UINT64_FMT "I64u"
636
637#define WINCDECL __cdecl
638#define vsnprintf_impl _vsnprintf
639#define access _access
640#define mg_sleep(x) (Sleep(x))
641
642#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
643#if !defined(popen)
644#define popen(x, y) (_popen(x, y))
645#endif
646#if !defined(pclose)
647#define pclose(x) (_pclose(x))
648#endif
649#define close(x) (_close(x))
650#define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
651#define RTLD_LAZY (0)
652#define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
653#define fdopen(x, y) (_fdopen((x), (y)))
654#define write(x, y, z) (_write((x), (y), (unsigned)z))
655#define read(x, y, z) (_read((x), (y), (unsigned)z))
656#define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
657#define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
658#define sleep(x) (Sleep((x)*1000))
659#define rmdir(x) (_rmdir(x))
660#if defined(_WIN64) || !defined(__MINGW32__)
661/* Only MinGW 32 bit is missing this function */
662#define timegm(x) (_mkgmtime(x))
663#else
664time_t timegm(struct tm *tm);
665#define NEED_TIMEGM
666#endif
667
668
669#if !defined(fileno)
670#define fileno(x) (_fileno(x))
671#endif /* !fileno MINGW #defines fileno */
672
673typedef struct {
674 CRITICAL_SECTION sec; /* Immovable */
675} pthread_mutex_t;
676typedef DWORD pthread_key_t;
677typedef HANDLE pthread_t;
678typedef struct {
679 pthread_mutex_t threadIdSec;
680 struct mg_workerTLS *waiting_thread; /* The chain of threads */
682
683#if !defined(__clockid_t_defined)
684typedef DWORD clockid_t;
685#endif
686#if !defined(CLOCK_MONOTONIC)
687#define CLOCK_MONOTONIC (1)
688#endif
689#if !defined(CLOCK_REALTIME)
690#define CLOCK_REALTIME (2)
691#endif
692#if !defined(CLOCK_THREAD)
693#define CLOCK_THREAD (3)
694#endif
695#if !defined(CLOCK_PROCESS)
696#define CLOCK_PROCESS (4)
697#endif
698
699
700#if defined(_MSC_VER) && (_MSC_VER >= 1900)
701#define _TIMESPEC_DEFINED
702#endif
703#if !defined(_TIMESPEC_DEFINED)
704struct timespec {
705 time_t tv_sec; /* seconds */
706 long tv_nsec; /* nanoseconds */
707};
708#endif
709
710#if !defined(WIN_PTHREADS_TIME_H)
711#define MUST_IMPLEMENT_CLOCK_GETTIME
712#endif
713
714#if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
715#define clock_gettime mg_clock_gettime
716static int
717clock_gettime(clockid_t clk_id, struct timespec *tp)
718{
719 FILETIME ft;
720 ULARGE_INTEGER li, li2;
721 BOOL ok = FALSE;
722 double d;
723 static double perfcnt_per_sec = 0.0;
724 static BOOL initialized = FALSE;
725
726 if (!initialized) {
727 QueryPerformanceFrequency((LARGE_INTEGER *)&li);
728 perfcnt_per_sec = 1.0 / li.QuadPart;
729 initialized = TRUE;
730 }
731
732 if (tp) {
733 memset(tp, 0, sizeof(*tp));
734
735 if (clk_id == CLOCK_REALTIME) {
736
737 /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
738 GetSystemTimeAsFileTime(&ft);
739 li.LowPart = ft.dwLowDateTime;
740 li.HighPart = ft.dwHighDateTime;
741 li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
742 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
743 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
744 ok = TRUE;
745 /* END: CLOCK_REALTIME */
746
747 } else if (clk_id == CLOCK_MONOTONIC) {
748
749 /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
750 QueryPerformanceCounter((LARGE_INTEGER *)&li);
751 d = li.QuadPart * perfcnt_per_sec;
752 tp->tv_sec = (time_t)d;
753 d -= (double)tp->tv_sec;
754 tp->tv_nsec = (long)(d * 1.0E9);
755 ok = TRUE;
756 /* END: CLOCK_MONOTONIC */
757
758 } else if (clk_id == CLOCK_THREAD) {
759
760 /* BEGIN: CLOCK_THREAD = CPU usage of thread */
761 FILETIME t_create, t_exit, t_kernel, t_user;
762 if (GetThreadTimes(GetCurrentThread(),
763 &t_create,
764 &t_exit,
765 &t_kernel,
766 &t_user)) {
767 li.LowPart = t_user.dwLowDateTime;
768 li.HighPart = t_user.dwHighDateTime;
769 li2.LowPart = t_kernel.dwLowDateTime;
770 li2.HighPart = t_kernel.dwHighDateTime;
771 li.QuadPart += li2.QuadPart;
772 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
773 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
774 ok = TRUE;
775 }
776 /* END: CLOCK_THREAD */
777
778 } else if (clk_id == CLOCK_PROCESS) {
779
780 /* BEGIN: CLOCK_PROCESS = CPU usage of process */
781 FILETIME t_create, t_exit, t_kernel, t_user;
782 if (GetProcessTimes(GetCurrentProcess(),
783 &t_create,
784 &t_exit,
785 &t_kernel,
786 &t_user)) {
787 li.LowPart = t_user.dwLowDateTime;
788 li.HighPart = t_user.dwHighDateTime;
789 li2.LowPart = t_kernel.dwLowDateTime;
790 li2.HighPart = t_kernel.dwHighDateTime;
791 li.QuadPart += li2.QuadPart;
792 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
793 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
794 ok = TRUE;
795 }
796 /* END: CLOCK_PROCESS */
797
798 } else {
799
800 /* BEGIN: unknown clock */
801 /* ok = FALSE; already set by init */
802 /* END: unknown clock */
803 }
804 }
805
806 return ok ? 0 : -1;
807}
808#endif
809
810
811#define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
812
813static int pthread_mutex_lock(pthread_mutex_t *);
814static int pthread_mutex_unlock(pthread_mutex_t *);
815static void path_to_unicode(const struct mg_connection *conn,
816 const char *path,
817 wchar_t *wbuf,
818 size_t wbuf_len);
819
820/* All file operations need to be rewritten to solve #246. */
821
822struct mg_file;
823
824static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
825
826
827/* POSIX dirent interface */
828struct dirent {
829 char d_name[UTF8_PATH_MAX];
830};
831
832typedef struct DIR {
833 HANDLE handle;
834 WIN32_FIND_DATAW info;
835 struct dirent result;
836} DIR;
837
838#if defined(HAVE_POLL)
839#define mg_pollfd pollfd
840#else
841struct mg_pollfd {
842 SOCKET fd;
843 short events;
844 short revents;
845};
846#endif
847
848/* Mark required libraries */
849#if defined(_MSC_VER)
850#pragma comment(lib, "Ws2_32.lib")
851#endif
852
853#else /* defined(_WIN32) - WINDOWS vs UNIX include block */
854
855#include <inttypes.h>
856
857/* Linux & co. internally use UTF8 */
858#define UTF8_PATH_MAX (PATH_MAX)
859
860typedef const void *SOCK_OPT_TYPE;
861
862#if defined(ANDROID)
863typedef unsigned short int in_port_t;
864#endif
865
866#if !defined(__ZEPHYR__)
867#include <arpa/inet.h>
868#include <ctype.h>
869#include <dirent.h>
870#include <grp.h>
871#include <limits.h>
872#include <netdb.h>
873#include <netinet/in.h>
874#include <netinet/tcp.h>
875#include <pthread.h>
876#include <pwd.h>
877#include <stdarg.h>
878#include <stddef.h>
879#include <stdio.h>
880#include <stdlib.h>
881#include <string.h>
882#include <sys/poll.h>
883#include <sys/socket.h>
884#include <sys/time.h>
885#include <sys/utsname.h>
886#include <sys/wait.h>
887#include <time.h>
888#include <unistd.h>
889#if defined(USE_X_DOM_SOCKET)
890#include <sys/un.h>
891#endif
892#endif
893
894#define vsnprintf_impl vsnprintf
895
896#if !defined(NO_SSL_DL) && !defined(NO_SSL)
897#include <dlfcn.h>
898#endif
899
900#if defined(__MACH__)
901#define SSL_LIB "libssl.dylib"
902#define CRYPTO_LIB "libcrypto.dylib"
903#else
904#if !defined(SSL_LIB)
905#define SSL_LIB "libssl.so"
906#endif
907#if !defined(CRYPTO_LIB)
908#define CRYPTO_LIB "libcrypto.so"
909#endif
910#endif
911#if !defined(O_BINARY)
912#define O_BINARY (0)
913#endif /* O_BINARY */
914#define closesocket(a) (close(a))
915#define mg_mkdir(conn, path, mode) (mkdir(path, mode))
916#define mg_remove(conn, x) (remove(x))
917#define mg_sleep(x) (usleep((x)*1000))
918#define mg_opendir(conn, x) (opendir(x))
919#define mg_closedir(x) (closedir(x))
920#define mg_readdir(x) (readdir(x))
921#define ERRNO (errno)
922#define INVALID_SOCKET (-1)
923#define INT64_FMT PRId64
924#define UINT64_FMT PRIu64
925typedef int SOCKET;
926#define WINCDECL
927
928#if defined(__hpux)
929/* HPUX 11 does not have monotonic, fall back to realtime */
930#if !defined(CLOCK_MONOTONIC)
931#define CLOCK_MONOTONIC CLOCK_REALTIME
932#endif
933
934/* HPUX defines socklen_t incorrectly as size_t which is 64bit on
935 * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
936 * the prototypes use int* rather than socklen_t* which matches the
937 * actual library expectation. When called with the wrong size arg
938 * accept() returns a zero client inet addr and check_acl() always
939 * fails. Since socklen_t is widely used below, just force replace
940 * their typedef with int. - DTL
941 */
942#define socklen_t int
943#endif /* hpux */
944
945#define mg_pollfd pollfd
946
947#endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
948
949/* In case our C library is missing "timegm", provide an implementation */
950#if defined(NEED_TIMEGM)
951static inline int
952is_leap(int y)
953{
954 return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
955}
956
957static inline int
958count_leap(int y)
959{
960 return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
961}
962
963time_t
964timegm(struct tm *tm)
965{
966 static const unsigned short ydays[] = {
967 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
968 int year = tm->tm_year + 1900;
969 int mon = tm->tm_mon;
970 int mday = tm->tm_mday - 1;
971 int hour = tm->tm_hour;
972 int min = tm->tm_min;
973 int sec = tm->tm_sec;
974
975 if (year < 1970 || mon < 0 || mon > 11 || mday < 0
976 || (mday >= ydays[mon + 1] - ydays[mon]
977 + (mon == 1 && is_leap(year) ? 1 : 0))
978 || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
979 return -1;
980
981 time_t res = year - 1970;
982 res *= 365;
983 res += mday;
984 res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
985 res += count_leap(year);
986
987 res *= 24;
988 res += hour;
989 res *= 60;
990 res += min;
991 res *= 60;
992 res += sec;
993 return res;
994}
995#endif /* NEED_TIMEGM */
996
997
998/* va_copy should always be a macro, C99 and C++11 - DTL */
999#if !defined(va_copy)
1000#define va_copy(x, y) ((x) = (y))
1001#endif
1002
1003
1004#if defined(_WIN32)
1005/* Create substitutes for POSIX functions in Win32. */
1006
1007#if defined(GCC_DIAGNOSTIC)
1008/* Show no warning in case system functions are not used. */
1009#pragma GCC diagnostic push
1010#pragma GCC diagnostic ignored "-Wunused-function"
1011#endif
1012
1013
1014static pthread_mutex_t global_log_file_lock;
1015
1017static DWORD
1018pthread_self(void)
1019{
1020 return GetCurrentThreadId();
1021}
1022
1023
1025static int
1026pthread_key_create(
1027 pthread_key_t *key,
1028 void (*_ignored)(void *) /* destructor not supported for Windows */
1029)
1030{
1031 (void)_ignored;
1032
1033 if ((key != 0)) {
1034 *key = TlsAlloc();
1035 return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
1036 }
1037 return -2;
1038}
1039
1040
1042static int
1043pthread_key_delete(pthread_key_t key)
1044{
1045 return TlsFree(key) ? 0 : 1;
1046}
1047
1048
1050static int
1051pthread_setspecific(pthread_key_t key, void *value)
1052{
1053 return TlsSetValue(key, value) ? 0 : 1;
1054}
1055
1056
1058static void *
1059pthread_getspecific(pthread_key_t key)
1060{
1061 return TlsGetValue(key);
1062}
1063
1064#if defined(GCC_DIAGNOSTIC)
1065/* Enable unused function warning again */
1066#pragma GCC diagnostic pop
1067#endif
1068
1069static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
1070#else
1071static pthread_mutexattr_t pthread_mutex_attr;
1072#endif /* _WIN32 */
1073
1074
1075#if defined(GCC_DIAGNOSTIC)
1076/* Show no warning in case system functions are not used. */
1077#pragma GCC diagnostic push
1078#pragma GCC diagnostic ignored "-Wunused-function"
1079#endif /* defined(GCC_DIAGNOSTIC) */
1080#if defined(__clang__)
1081/* Show no warning in case system functions are not used. */
1082#pragma clang diagnostic push
1083#pragma clang diagnostic ignored "-Wunused-function"
1084#endif
1085
1086static pthread_mutex_t global_lock_mutex;
1087
1088
1090static void
1092{
1093 (void)pthread_mutex_lock(&global_lock_mutex);
1094}
1095
1096
1098static void
1100{
1101 (void)pthread_mutex_unlock(&global_lock_mutex);
1102}
1103
1104
1105#if defined(_WIN64)
1106mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
1107#elif defined(_WIN32)
1108mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
1109#endif
1110
1111
1112/* Atomic functions working on ptrdiff_t ("signed size_t").
1113 * Operations: Increment, Decrement, Add, Maximum.
1114 * Up to size_t, they do not an atomic "load" operation.
1115 */
1117static ptrdiff_t
1118mg_atomic_inc(volatile ptrdiff_t *addr)
1119{
1120 ptrdiff_t ret;
1121
1122#if defined(_WIN64) && !defined(NO_ATOMICS)
1123 ret = InterlockedIncrement64(addr);
1124#elif defined(_WIN32) && !defined(NO_ATOMICS)
1125 ret = InterlockedIncrement(addr);
1126#elif defined(__GNUC__) \
1127 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1128 && !defined(NO_ATOMICS)
1129 ret = __sync_add_and_fetch(addr, 1);
1130#else
1132 ret = (++(*addr));
1134#endif
1135 return ret;
1136}
1137
1138
1140static ptrdiff_t
1141mg_atomic_dec(volatile ptrdiff_t *addr)
1142{
1143 ptrdiff_t ret;
1144
1145#if defined(_WIN64) && !defined(NO_ATOMICS)
1146 ret = InterlockedDecrement64(addr);
1147#elif defined(_WIN32) && !defined(NO_ATOMICS)
1148 ret = InterlockedDecrement(addr);
1149#elif defined(__GNUC__) \
1150 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1151 && !defined(NO_ATOMICS)
1152 ret = __sync_sub_and_fetch(addr, 1);
1153#else
1155 ret = (--(*addr));
1157#endif
1158 return ret;
1159}
1160
1161
1162#if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
1163static ptrdiff_t
1164mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
1165{
1166 ptrdiff_t ret;
1167
1168#if defined(_WIN64) && !defined(NO_ATOMICS)
1169 ret = InterlockedAdd64(addr, value);
1170#elif defined(_WIN32) && !defined(NO_ATOMICS)
1171 ret = InterlockedExchangeAdd(addr, value) + value;
1172#elif defined(__GNUC__) \
1173 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1174 && !defined(NO_ATOMICS)
1175 ret = __sync_add_and_fetch(addr, value);
1176#else
1178 *addr += value;
1179 ret = (*addr);
1181#endif
1182 return ret;
1183}
1184
1185
1187static ptrdiff_t
1188mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
1189 ptrdiff_t oldval,
1190 ptrdiff_t newval)
1191{
1192 ptrdiff_t ret;
1193
1194#if defined(_WIN64) && !defined(NO_ATOMICS)
1195 ret = InterlockedCompareExchange64(addr, newval, oldval);
1196#elif defined(_WIN32) && !defined(NO_ATOMICS)
1197 ret = InterlockedCompareExchange(addr, newval, oldval);
1198#elif defined(__GNUC__) \
1199 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1200 && !defined(NO_ATOMICS)
1201 ret = __sync_val_compare_and_swap(addr, oldval, newval);
1202#else
1204 ret = *addr;
1205 if ((ret != newval) && (ret == oldval)) {
1206 *addr = newval;
1207 }
1209#endif
1210 return ret;
1211}
1212
1213
1214static void
1215mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
1216{
1217 register ptrdiff_t tmp = *addr;
1218
1219#if defined(_WIN64) && !defined(NO_ATOMICS)
1220 while (tmp < value) {
1221 tmp = InterlockedCompareExchange64(addr, value, tmp);
1222 }
1223#elif defined(_WIN32) && !defined(NO_ATOMICS)
1224 while (tmp < value) {
1225 tmp = InterlockedCompareExchange(addr, value, tmp);
1226 }
1227#elif defined(__GNUC__) \
1228 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1229 && !defined(NO_ATOMICS)
1230 while (tmp < value) {
1231 tmp = __sync_val_compare_and_swap(addr, tmp, value);
1232 }
1233#else
1235 if (*addr < value) {
1236 *addr = value;
1237 }
1239#endif
1240}
1241
1242
1243static int64_t
1244mg_atomic_add64(volatile int64_t *addr, int64_t value)
1245{
1246 int64_t ret;
1247
1248#if defined(_WIN64) && !defined(NO_ATOMICS)
1249 ret = InterlockedAdd64(addr, value);
1250#elif defined(_WIN32) && !defined(NO_ATOMICS)
1251 ret = InterlockedExchangeAdd64(addr, value) + value;
1252#elif defined(__GNUC__) \
1253 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1254 && !defined(NO_ATOMICS)
1255 ret = __sync_add_and_fetch(addr, value);
1256#else
1258 *addr += value;
1259 ret = (*addr);
1261#endif
1262 return ret;
1263}
1264#endif
1265
1266
1267#if defined(GCC_DIAGNOSTIC)
1268/* Show no warning in case system functions are not used. */
1269#pragma GCC diagnostic pop
1270#endif /* defined(GCC_DIAGNOSTIC) */
1271#if defined(__clang__)
1272/* Show no warning in case system functions are not used. */
1273#pragma clang diagnostic pop
1274#endif
1275
1276
1277#if defined(USE_SERVER_STATS)
1278
1279struct mg_memory_stat {
1280 volatile ptrdiff_t totalMemUsed;
1281 volatile ptrdiff_t maxMemUsed;
1282 volatile ptrdiff_t blockCount;
1283};
1284
1285
1286static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
1287
1288
1289static void *
1290mg_malloc_ex(size_t size,
1291 struct mg_context *ctx,
1292 const char *file,
1293 unsigned line)
1294{
1295 void *data = malloc(size + 2 * sizeof(uintptr_t));
1296 void *memory = 0;
1297 struct mg_memory_stat *mstat = get_memory_stat(ctx);
1298
1299#if defined(MEMORY_DEBUGGING)
1300 char mallocStr[256];
1301#else
1302 (void)file;
1303 (void)line;
1304#endif
1305
1306 if (data) {
1307 ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
1308 mg_atomic_max(&mstat->maxMemUsed, mmem);
1309
1310 mg_atomic_inc(&mstat->blockCount);
1311 ((uintptr_t *)data)[0] = size;
1312 ((uintptr_t *)data)[1] = (uintptr_t)mstat;
1313 memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1314 }
1315
1316#if defined(MEMORY_DEBUGGING)
1317 sprintf(mallocStr,
1318 "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
1319 memory,
1320 (unsigned long)size,
1321 (unsigned long)mstat->totalMemUsed,
1322 (unsigned long)mstat->blockCount,
1323 file,
1324 line);
1325 DEBUG_TRACE("%s", mallocStr);
1326#endif
1327
1328 return memory;
1329}
1330
1331
1332static void *
1333mg_calloc_ex(size_t count,
1334 size_t size,
1335 struct mg_context *ctx,
1336 const char *file,
1337 unsigned line)
1338{
1339 void *data = mg_malloc_ex(size * count, ctx, file, line);
1340
1341 if (data) {
1342 memset(data, 0, size * count);
1343 }
1344 return data;
1345}
1346
1347
1348static void
1349mg_free_ex(void *memory, const char *file, unsigned line)
1350{
1351#if defined(MEMORY_DEBUGGING)
1352 char mallocStr[256];
1353#else
1354 (void)file;
1355 (void)line;
1356#endif
1357
1358 if (memory) {
1359 void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1360 uintptr_t size = ((uintptr_t *)data)[0];
1361 struct mg_memory_stat *mstat =
1362 (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
1363 mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
1364 mg_atomic_dec(&mstat->blockCount);
1365
1366#if defined(MEMORY_DEBUGGING)
1367 sprintf(mallocStr,
1368 "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
1369 memory,
1370 (unsigned long)size,
1371 (unsigned long)mstat->totalMemUsed,
1372 (unsigned long)mstat->blockCount,
1373 file,
1374 line);
1375 DEBUG_TRACE("%s", mallocStr);
1376#endif
1377 free(data);
1378 }
1379}
1380
1381
1382static void *
1383mg_realloc_ex(void *memory,
1384 size_t newsize,
1385 struct mg_context *ctx,
1386 const char *file,
1387 unsigned line)
1388{
1389 void *data;
1390 void *_realloc;
1391 uintptr_t oldsize;
1392
1393#if defined(MEMORY_DEBUGGING)
1394 char mallocStr[256];
1395#else
1396 (void)file;
1397 (void)line;
1398#endif
1399
1400 if (newsize) {
1401 if (memory) {
1402 /* Reallocate existing block */
1403 struct mg_memory_stat *mstat;
1404 data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1405 oldsize = ((uintptr_t *)data)[0];
1406 mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
1407 _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
1408 if (_realloc) {
1409 data = _realloc;
1410 mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
1411#if defined(MEMORY_DEBUGGING)
1412 sprintf(mallocStr,
1413 "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
1414 memory,
1415 (unsigned long)oldsize,
1416 (unsigned long)mstat->totalMemUsed,
1417 (unsigned long)mstat->blockCount,
1418 file,
1419 line);
1420 DEBUG_TRACE("%s", mallocStr);
1421#endif
1422 mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
1423
1424#if defined(MEMORY_DEBUGGING)
1425 sprintf(mallocStr,
1426 "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
1427 memory,
1428 (unsigned long)newsize,
1429 (unsigned long)mstat->totalMemUsed,
1430 (unsigned long)mstat->blockCount,
1431 file,
1432 line);
1433 DEBUG_TRACE("%s", mallocStr);
1434#endif
1435 *(uintptr_t *)data = newsize;
1436 data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1437 } else {
1438#if defined(MEMORY_DEBUGGING)
1439 DEBUG_TRACE("%s", "MEM: realloc failed\n");
1440#endif
1441 return _realloc;
1442 }
1443 } else {
1444 /* Allocate new block */
1445 data = mg_malloc_ex(newsize, ctx, file, line);
1446 }
1447 } else {
1448 /* Free existing block */
1449 data = 0;
1450 mg_free_ex(memory, file, line);
1451 }
1452
1453 return data;
1454}
1455
1456
1457#define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
1458#define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
1459#define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
1460#define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
1461
1462#define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
1463#define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
1464#define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
1465
1466
1467#else /* USE_SERVER_STATS */
1468
1469
1470static __inline void *
1472{
1473 return malloc(a);
1474}
1475
1476static __inline void *
1477mg_calloc(size_t a, size_t b)
1478{
1479 return calloc(a, b);
1480}
1481
1482static __inline void *
1483mg_realloc(void *a, size_t b)
1484{
1485 return realloc(a, b);
1486}
1487
1488static __inline void
1490{
1491 free(a);
1492}
1493
1494#define mg_malloc_ctx(a, c) mg_malloc(a)
1495#define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
1496#define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
1497#define mg_free_ctx(a, c) mg_free(a)
1498
1499#endif /* USE_SERVER_STATS */
1500
1501
1502static void mg_vsnprintf(const struct mg_connection *conn,
1503 int *truncated,
1504 char *buf,
1505 size_t buflen,
1506 const char *fmt,
1507 va_list ap);
1508
1509static void mg_snprintf(const struct mg_connection *conn,
1510 int *truncated,
1511 char *buf,
1512 size_t buflen,
1513 PRINTF_FORMAT_STRING(const char *fmt),
1514 ...) PRINTF_ARGS(5, 6);
1515
1516/* This following lines are just meant as a reminder to use the mg-functions
1517 * for memory management */
1518#if defined(malloc)
1519#undef malloc
1520#endif
1521#if defined(calloc)
1522#undef calloc
1523#endif
1524#if defined(realloc)
1525#undef realloc
1526#endif
1527#if defined(free)
1528#undef free
1529#endif
1530#if defined(snprintf)
1531#undef snprintf
1532#endif
1533#if defined(vsnprintf)
1534#undef vsnprintf
1535#endif
1536#define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
1537#define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
1538#define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
1539#define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
1540#define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
1541#if defined(_WIN32)
1542/* vsnprintf must not be used in any system,
1543 * but this define only works well for Windows. */
1544#define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
1545#endif
1546
1547
1548/* mg_init_library counter */
1550
1551#if !defined(NO_SSL)
1552#if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
1553 || defined(OPENSSL_API_3_0)
1554static int mg_openssl_initialized = 0;
1555#endif
1556#if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
1557 && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
1558#error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
1559#endif
1560#if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
1561 && defined(OPENSSL_API_3_0)
1562#error "Multiple OPENSSL_API versions defined"
1563#endif
1564#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
1565 || defined(OPENSSL_API_3_0)) \
1566 && defined(USE_MBEDTLS)
1567#error "Multiple SSL libraries defined"
1568#endif
1569#endif
1570
1571
1572static pthread_key_t sTlsKey; /* Thread local storage index */
1573static volatile ptrdiff_t thread_idx_max = 0;
1574
1575#if defined(MG_LEGACY_INTERFACE)
1576#define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
1577#endif
1578
1581 unsigned long thread_idx;
1583#if defined(_WIN32)
1584 HANDLE pthread_cond_helper_mutex;
1585 struct mg_workerTLS *next_waiting_thread;
1586#endif
1587 const char *alpn_proto;
1588#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
1589 char txtbuf[4];
1590#endif
1591};
1592
1593
1594#if defined(GCC_DIAGNOSTIC)
1595/* Show no warning in case system functions are not used. */
1596#pragma GCC diagnostic push
1597#pragma GCC diagnostic ignored "-Wunused-function"
1598#endif /* defined(GCC_DIAGNOSTIC) */
1599#if defined(__clang__)
1600/* Show no warning in case system functions are not used. */
1601#pragma clang diagnostic push
1602#pragma clang diagnostic ignored "-Wunused-function"
1603#endif
1604
1605
1606/* Get a unique thread ID as unsigned long, independent from the data type
1607 * of thread IDs defined by the operating system API.
1608 * If two calls to mg_current_thread_id return the same value, they calls
1609 * are done from the same thread. If they return different values, they are
1610 * done from different threads. (Provided this function is used in the same
1611 * process context and threads are not repeatedly created and deleted, but
1612 * CivetWeb does not do that).
1613 * This function must match the signature required for SSL id callbacks:
1614 * CRYPTO_set_id_callback
1615 */
1617static unsigned long
1619{
1620#if defined(_WIN32)
1621 return GetCurrentThreadId();
1622#else
1623
1624#if defined(__clang__)
1625#pragma clang diagnostic push
1626#pragma clang diagnostic ignored "-Wunreachable-code"
1627 /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
1628 * or not, so one of the two conditions will be unreachable by construction.
1629 * Unfortunately the C standard does not define a way to check this at
1630 * compile time, since the #if preprocessor conditions can not use the
1631 * sizeof operator as an argument. */
1632#endif
1633
1634 if (sizeof(pthread_t) > sizeof(unsigned long)) {
1635 /* This is the problematic case for CRYPTO_set_id_callback:
1636 * The OS pthread_t can not be cast to unsigned long. */
1637 struct mg_workerTLS *tls =
1638 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
1639 if (tls == NULL) {
1640 /* SSL called from an unknown thread: Create some thread index.
1641 */
1642 tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
1643 tls->is_master = -2; /* -2 means "3rd party thread" */
1644 tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
1645 pthread_setspecific(sTlsKey, tls);
1646 }
1647 return tls->thread_idx;
1648 } else {
1649 /* pthread_t may be any data type, so a simple cast to unsigned long
1650 * can rise a warning/error, depending on the platform.
1651 * Here memcpy is used as an anything-to-anything cast. */
1652 unsigned long ret = 0;
1653 pthread_t t = pthread_self();
1654 memcpy(&ret, &t, sizeof(pthread_t));
1655 return ret;
1656 }
1657
1658#if defined(__clang__)
1659#pragma clang diagnostic pop
1660#endif
1661
1662#endif
1663}
1664
1665
1667static uint64_t
1669{
1670 struct timespec tsnow;
1671 clock_gettime(CLOCK_REALTIME, &tsnow);
1672 return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
1673}
1674
1675
1676#if defined(GCC_DIAGNOSTIC)
1677/* Show no warning in case system functions are not used. */
1678#pragma GCC diagnostic pop
1679#endif /* defined(GCC_DIAGNOSTIC) */
1680#if defined(__clang__)
1681/* Show no warning in case system functions are not used. */
1682#pragma clang diagnostic pop
1683#endif
1684
1685
1686#if defined(NEED_DEBUG_TRACE_FUNC)
1687static void
1688DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
1689{
1690 va_list args;
1691 struct timespec tsnow;
1692
1693 /* Get some operating system independent thread id */
1694 unsigned long thread_id = mg_current_thread_id();
1695
1696 clock_gettime(CLOCK_REALTIME, &tsnow);
1697
1698 flockfile(DEBUG_TRACE_STREAM);
1699 fprintf(DEBUG_TRACE_STREAM,
1700 "*** %lu.%09lu %lu %s:%u: ",
1701 (unsigned long)tsnow.tv_sec,
1702 (unsigned long)tsnow.tv_nsec,
1703 thread_id,
1704 func,
1705 line);
1706 va_start(args, fmt);
1707 vfprintf(DEBUG_TRACE_STREAM, fmt, args);
1708 va_end(args);
1709 putc('\n', DEBUG_TRACE_STREAM);
1710 fflush(DEBUG_TRACE_STREAM);
1711 funlockfile(DEBUG_TRACE_STREAM);
1712}
1713#endif /* NEED_DEBUG_TRACE_FUNC */
1714
1715
1716#define MD5_STATIC static
1717#include "md5.inl"
1718
1719/* Darwin prior to 7.0 and Win32 do not have socklen_t */
1720#if defined(NO_SOCKLEN_T)
1721typedef int socklen_t;
1722#endif /* NO_SOCKLEN_T */
1723
1724#define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
1725
1726#if !defined(MSG_NOSIGNAL)
1727#define MSG_NOSIGNAL (0)
1728#endif
1729
1730
1731/* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
1732#if defined(USE_MBEDTLS)
1733/* mbedTLS */
1734#include "mod_mbedtls.inl"
1735
1736#elif defined(NO_SSL)
1737/* no SSL */
1738typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
1739typedef struct SSL_CTX SSL_CTX;
1740
1741#elif defined(NO_SSL_DL)
1742/* OpenSSL without dynamic loading */
1743#include <openssl/bn.h>
1744#include <openssl/conf.h>
1745#include <openssl/crypto.h>
1746#include <openssl/dh.h>
1747#include <openssl/engine.h>
1748#include <openssl/err.h>
1749#include <openssl/opensslv.h>
1750#include <openssl/pem.h>
1751#include <openssl/ssl.h>
1752#include <openssl/tls1.h>
1753#include <openssl/x509.h>
1754
1755#if defined(WOLFSSL_VERSION)
1756/* Additional defines for WolfSSL, see
1757 * https://github.com/civetweb/civetweb/issues/583 */
1758#include "wolfssl_extras.inl"
1759#endif
1760
1761#if defined(OPENSSL_IS_BORINGSSL)
1762/* From boringssl/src/include/openssl/mem.h:
1763 *
1764 * OpenSSL has, historically, had a complex set of malloc debugging options.
1765 * However, that was written in a time before Valgrind and ASAN. Since we now
1766 * have those tools, the OpenSSL allocation functions are simply macros around
1767 * the standard memory functions.
1768 *
1769 * #define OPENSSL_free free */
1770#define free free
1771// disable for boringssl
1772#define CONF_modules_unload(a) ((void)0)
1773#define ENGINE_cleanup() ((void)0)
1774#endif
1775
1776/* If OpenSSL headers are included, automatically select the API version */
1777#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
1778#if !defined(OPENSSL_API_3_0)
1779#define OPENSSL_API_3_0
1780#endif
1781#define OPENSSL_REMOVE_THREAD_STATE()
1782#else
1783#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1784#if !defined(OPENSSL_API_1_1)
1785#define OPENSSL_API_1_1
1786#endif
1787#define OPENSSL_REMOVE_THREAD_STATE()
1788#else
1789#if !defined(OPENSSL_API_1_0)
1790#define OPENSSL_API_1_0
1791#endif
1792#define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
1793#endif
1794#endif
1795
1796
1797#else
1798/* SSL loaded dynamically from DLL / shared object */
1799/* Add all prototypes here, to be independent from OpenSSL source
1800 * installation. */
1801#include "openssl_dl.inl"
1802
1803#endif /* Various SSL bindings */
1804
1805
1806#if !defined(NO_CACHING)
1807static const char month_names[][4] = {"Jan",
1808 "Feb",
1809 "Mar",
1810 "Apr",
1811 "May",
1812 "Jun",
1813 "Jul",
1814 "Aug",
1815 "Sep",
1816 "Oct",
1817 "Nov",
1818 "Dec"};
1819#endif /* !NO_CACHING */
1820
1821
1822/* Unified socket address. For IPv6 support, add IPv6 address structure in
1823 * the union u. */
1824union usa {
1825 struct sockaddr sa;
1826 struct sockaddr_in sin;
1827#if defined(USE_IPV6)
1828 struct sockaddr_in6 sin6;
1829#endif
1830#if defined(USE_X_DOM_SOCKET)
1831 struct sockaddr_un sun;
1832#endif
1833};
1834
1835#if defined(USE_X_DOM_SOCKET)
1836static unsigned short
1837USA_IN_PORT_UNSAFE(union usa *s)
1838{
1839 if (s->sa.sa_family == AF_INET)
1840 return s->sin.sin_port;
1841#if defined(USE_IPV6)
1842 if (s->sa.sa_family == AF_INET6)
1843 return s->sin6.sin6_port;
1844#endif
1845 return 0;
1846}
1847#endif
1848#if defined(USE_IPV6)
1849#define USA_IN_PORT_UNSAFE(s) \
1850 (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
1851#else
1852#define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
1853#endif
1854
1855/* Describes a string (chunk of memory). */
1856struct vec {
1857 const char *ptr;
1858 size_t len;
1859};
1860
1862 /* File properties filled by mg_stat: */
1863 uint64_t size;
1865 int is_directory; /* Set to 1 if mg_stat is called for a directory */
1866 int is_gzipped; /* Set to 1 if the content is gzipped, in which
1867 * case we need a "Content-Eencoding: gzip" header */
1868 int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
1869};
1870
1871
1873 /* File properties filled by mg_fopen: */
1874 FILE *fp;
1875};
1876
1877struct mg_file {
1880};
1881
1882
1883#define STRUCT_FILE_INITIALIZER \
1884 { \
1885 {(uint64_t)0, (time_t)0, 0, 0, 0}, \
1886 { \
1887 (FILE *)NULL \
1888 } \
1889 }
1890
1891
1892/* Describes listening socket, or socket which was accept()-ed by the master
1893 * thread and queued for future handling by the worker thread. */
1894struct socket {
1895 SOCKET sock; /* Listening socket */
1896 union usa lsa; /* Local socket address */
1897 union usa rsa; /* Remote socket address */
1898 unsigned char is_ssl; /* Is port SSL-ed */
1899 unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
1900 * port */
1901 unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
1902};
1903
1904
1905/* Enum const for all options must be in sync with
1906 * static struct mg_option config_options[]
1907 * This is tested in the unit test (test/private.c)
1908 * "Private Config Options"
1909 */
1910enum {
1911 /* Once for each server */
1915 CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
1916 * socket option typedef TCP_NODELAY. */
1921#if defined(__linux__)
1922 ALLOW_SENDFILE_CALL,
1923#endif
1924#if defined(_WIN32)
1925 CASE_SENSITIVE_FILES,
1926#endif
1931#if defined(USE_WEBSOCKET)
1932 WEBSOCKET_TIMEOUT,
1933 ENABLE_WEBSOCKET_PING_PONG,
1934#endif
1937#if defined(USE_LUA)
1938 LUA_BACKGROUND_SCRIPT,
1939 LUA_BACKGROUND_SCRIPT_PARAMS,
1940#endif
1941#if defined(USE_HTTP2)
1942 ENABLE_HTTP2,
1943#endif
1944
1945 /* Once for each domain */
1947
1950
1955#if defined(USE_TIMERS)
1956 CGI_TIMEOUT,
1957#endif
1958
1963#if defined(USE_TIMERS)
1964 CGI2_TIMEOUT,
1965#endif
1966
1967#if defined(USE_4_CGI)
1968 CGI3_EXTENSIONS,
1969 CGI3_ENVIRONMENT,
1970 CGI3_INTERPRETER,
1971 CGI3_INTERPRETER_ARGS,
1972#if defined(USE_TIMERS)
1973 CGI3_TIMEOUT,
1974#endif
1975
1976 CGI4_EXTENSIONS,
1977 CGI4_ENVIRONMENT,
1978 CGI4_INTERPRETER,
1979 CGI4_INTERPRETER_ARGS,
1980#if defined(USE_TIMERS)
1981 CGI4_TIMEOUT,
1982#endif
1983#endif
1984
1985 PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
2008
2009#if defined(USE_LUA)
2010 LUA_PRELOAD_FILE,
2011 LUA_SCRIPT_EXTENSIONS,
2012 LUA_SERVER_PAGE_EXTENSIONS,
2013#if defined(MG_EXPERIMENTAL_INTERFACES)
2014 LUA_DEBUG_PARAMS,
2015#endif
2016#endif
2017#if defined(USE_DUKTAPE)
2018 DUKTAPE_SCRIPT_EXTENSIONS,
2019#endif
2020
2021#if defined(USE_WEBSOCKET)
2022 WEBSOCKET_ROOT,
2023#endif
2024#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2025 LUA_WEBSOCKET_EXTENSIONS,
2026#endif
2027
2033#if !defined(NO_CACHING)
2036#endif
2037#if !defined(NO_SSL)
2039#endif
2042
2045
2046
2047/* Config option name, config types, default value.
2048 * Must be in the same order as the enum const above.
2049 */
2050static const struct mg_option config_options[] = {
2051
2052 /* Once for each server */
2053 {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
2054 {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
2055 {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
2056 {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
2057 {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
2058 {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2059 {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
2060 {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
2061#if defined(__linux__)
2062 {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2063#endif
2064#if defined(_WIN32)
2065 {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2066#endif
2067 {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
2068 {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2069 {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
2070 {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
2071#if defined(USE_WEBSOCKET)
2072 {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2073 {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
2074#endif
2075 {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2076 {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
2077#if defined(USE_LUA)
2078 {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
2079 {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
2080#endif
2081#if defined(USE_HTTP2)
2082 {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
2083#endif
2084
2085 /* Once for each domain */
2086 {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2087
2088 {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
2089 {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
2090
2091 {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
2092 {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2093 {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2094 {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2095#if defined(USE_TIMERS)
2096 {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2097#endif
2098
2099 {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2100 {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2101 {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2102 {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2103#if defined(USE_TIMERS)
2104 {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2105#endif
2106
2107#if defined(USE_4_CGI)
2108 {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2109 {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2110 {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2111 {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2112#if defined(USE_TIMERS)
2113 {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2114#endif
2115
2116 {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2117 {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2118 {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2119 {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2120#if defined(USE_TIMERS)
2121 {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2122#endif
2123#endif
2124
2125 {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2126 {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
2127 {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
2128 {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2129 {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
2130 {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2131 {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2132 {"index_files",
2134#if defined(USE_LUA)
2135 "index.xhtml,index.html,index.htm,"
2136 "index.lp,index.lsp,index.lua,index.cgi,"
2137 "index.shtml,index.php"},
2138#else
2139 "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
2140#endif
2141 {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
2142 {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
2143 {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
2144 {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
2145 {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
2146 {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2147
2148 {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
2149 {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
2150
2151 {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
2152 {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
2153 {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
2154 {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2155 {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
2156
2157 /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
2158 * as a minimum in 2020 */
2159 {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
2160
2161 {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
2162
2163#if defined(USE_LUA)
2164 {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
2165 {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2166 {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
2167#if defined(MG_EXPERIMENTAL_INTERFACES)
2168 {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
2169#endif
2170#endif
2171#if defined(USE_DUKTAPE)
2172 /* The support for duktape is still in alpha version state.
2173 * The name of this config option might change. */
2174 {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
2175#endif
2176
2177#if defined(USE_WEBSOCKET)
2178 {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2179#endif
2180#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2181 {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2182#endif
2183 {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
2184 {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
2185 {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
2186 {"access_control_allow_credentials", MG_CONFIG_TYPE_STRING, ""},
2187 {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
2188#if !defined(NO_CACHING)
2189 {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
2190 {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
2191#endif
2192#if !defined(NO_SSL)
2193 {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
2194#endif
2195 {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
2196 {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
2197
2198 {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
2199
2200
2201/* Check if the config_options and the corresponding enum have compatible
2202 * sizes. */
2203mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
2204 == (NUM_OPTIONS + 1),
2205 "config_options and enum not sync");
2206
2207
2209
2210
2212 /* Name/Pattern of the URI. */
2213 char *uri;
2214 size_t uri_len;
2215
2216 /* handler type */
2218
2219 /* Handler for http/https or authorization requests. */
2221 unsigned int refcount;
2223
2224 /* Handler for ws/wss (websocket) requests. */
2229
2230 /* accepted subprotocols for ws/wss requests. */
2232
2233 /* Handler for authorization requests */
2235
2236 /* User supplied argument for the handler function. */
2237 void *cbdata;
2238
2239 /* next handler in a linked list */
2241};
2242
2243
2244enum {
2250
2251
2253 SSL_CTX *ssl_ctx; /* SSL context */
2254 char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
2255 struct mg_handler_info *handlers; /* linked list of uri handlers */
2257
2258 /* Server nonce */
2259 uint64_t auth_nonce_mask; /* Mask for all nonce values */
2260 unsigned long nonce_count; /* Used nonces, used for authentication */
2261
2262#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2263 /* linked list of shared lua websockets */
2264 struct mg_shared_lua_websocket_list *shared_lua_websockets;
2265#endif
2266
2267 /* Linked list of domains */
2269};
2270
2271
2272/* Stop flag can be "volatile" or require a lock.
2273 * MSDN uses volatile for "Interlocked" operations, but also explicitly
2274 * states a read operation for int is always atomic. */
2275#if defined(STOP_FLAG_NEEDS_LOCK)
2276
2277typedef ptrdiff_t volatile stop_flag_t;
2278
2279static int
2281{
2282 stop_flag_t sf = mg_atomic_add(f, 0);
2283 return (sf == 0);
2284}
2285
2286static int
2288{
2289 stop_flag_t sf = mg_atomic_add(f, 0);
2290 return (sf == 2);
2291}
2292
2293static void
2295{
2296 stop_flag_t sf;
2297 do {
2298 sf = mg_atomic_compare_and_swap(f, *f, v);
2299 } while (sf != v);
2300}
2301
2302#else /* STOP_FLAG_NEEDS_LOCK */
2303
2304typedef int volatile stop_flag_t;
2305#define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
2306#define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
2307#define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
2308
2309#endif /* STOP_FLAG_NEEDS_LOCK */
2310
2311
2313
2314 /* Part 1 - Physical context:
2315 * This holds threads, ports, timeouts, ...
2316 * set for the entire server, independent from the
2317 * addressed hostname.
2318 */
2319
2320 /* Connection related */
2321 int context_type; /* See CONTEXT_* above */
2322
2326
2327 struct mg_connection *worker_connections; /* The connection struct, pre-
2328 * allocated for each worker */
2329
2330#if defined(USE_SERVER_STATS)
2331 volatile ptrdiff_t active_connections;
2332 volatile ptrdiff_t max_active_connections;
2333 volatile ptrdiff_t total_connections;
2334 volatile ptrdiff_t total_requests;
2335 volatile int64_t total_data_read;
2336 volatile int64_t total_data_written;
2337#endif
2338
2339 /* Thread related */
2340 stop_flag_t stop_flag; /* Should we stop event loop */
2341 pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
2342
2343 pthread_t masterthreadid; /* The master thread ID */
2344 unsigned int
2345 cfg_worker_threads; /* The number of configured worker threads. */
2346 pthread_t *worker_threadids; /* The worker thread IDs */
2347 unsigned long starter_thread_idx; /* thread index which called mg_start */
2348
2349 /* Connection to thread dispatching */
2350#if defined(ALTERNATIVE_QUEUE)
2351 struct socket *client_socks;
2352 void **client_wait_events;
2353#else
2354 struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
2355 worker thread */
2356 volatile int sq_head; /* Head of the socket queue */
2357 volatile int sq_tail; /* Tail of the socket queue */
2358 pthread_cond_t sq_full; /* Signaled when socket is produced */
2359 pthread_cond_t sq_empty; /* Signaled when socket is consumed */
2360 volatile int sq_blocked; /* Status information: sq is full */
2361 int sq_size; /* No of elements in socket queue */
2362#if defined(USE_SERVER_STATS)
2363 int sq_max_fill;
2364#endif /* USE_SERVER_STATS */
2365#endif /* ALTERNATIVE_QUEUE */
2366
2367 /* Memory related */
2368 unsigned int max_request_size; /* The max request size */
2369
2370#if defined(USE_SERVER_STATS)
2371 struct mg_memory_stat ctx_memory;
2372#endif
2373
2374 /* Operating system related */
2375 char *systemName; /* What operating system is running */
2376 time_t start_time; /* Server start time, used for authentication
2377 * and for diagnstics. */
2378
2379#if defined(USE_TIMERS)
2380 struct ttimers *timers;
2381#endif
2382
2383 /* Lua specific: Background operations and shared websockets */
2384#if defined(USE_LUA)
2385 void *lua_background_state; /* lua_State (here as void *) */
2386 pthread_mutex_t lua_bg_mutex; /* Protect background state */
2387 int lua_bg_log_available; /* Use Lua background state for access log */
2388#endif
2389
2390 /* Server nonce */
2391 pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
2392 * ssl_cert_last_mtime, nonce_count, and
2393 * next (linked list) */
2394
2395 /* Server callbacks */
2396 struct mg_callbacks callbacks; /* User-defined callback function */
2397 void *user_data; /* User-defined data */
2398
2399 /* Part 2 - Logical domain:
2400 * This holds hostname, TLS certificate, document root, ...
2401 * set for a domain hosted at the server.
2402 * There may be multiple domains hosted at one physical server.
2403 * The default domain "dd" is the first element of a list of
2404 * domains.
2405 */
2406 struct mg_domain_context dd; /* default domain */
2407};
2408
2409
2410#if defined(USE_SERVER_STATS)
2411static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2412
2413static struct mg_memory_stat *
2414get_memory_stat(struct mg_context *ctx)
2415{
2416 if (ctx) {
2417 return &(ctx->ctx_memory);
2418 }
2419 return &mg_common_memory;
2420}
2421#endif
2422
2423enum {
2428
2429enum {
2434
2435
2436#if defined(USE_HTTP2)
2437#if !defined(HTTP2_DYN_TABLE_SIZE)
2438#define HTTP2_DYN_TABLE_SIZE (256)
2439#endif
2440
2441struct mg_http2_connection {
2442 uint32_t stream_id;
2443 uint32_t dyn_table_size;
2444 struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
2445};
2446#endif
2447
2448
2450 int connection_type; /* see CONNECTION_TYPE_* above */
2451 int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
2452 int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
2453 fully sent */
2454#if defined(USE_HTTP2)
2455 struct mg_http2_connection http2;
2456#endif
2457
2460
2463
2464#if defined(USE_SERVER_STATS)
2465 int conn_state; /* 0 = undef, numerical value may change in different
2466 * versions. For the current definition, see
2467 * mg_get_connection_info_impl */
2468#endif
2469
2470 SSL *ssl; /* SSL descriptor */
2471 struct socket client; /* Connected client */
2472 time_t conn_birth_time; /* Time (wall clock) when connection was
2473 * established */
2474#if defined(USE_SERVER_STATS)
2475 time_t conn_close_time; /* Time (wall clock) when connection was
2476 * closed (or 0 if still open) */
2477 double processing_time; /* Procesing time for one request. */
2478#endif
2479 struct timespec req_time; /* Time (since system start) when the request
2480 * was received */
2481 int64_t num_bytes_sent; /* Total bytes sent to client */
2482 int64_t content_len; /* How many bytes of content can be read
2483 * !is_chunked: Content-Length header value
2484 * or -1 (until connection closed,
2485 * not allowed for a request)
2486 * is_chunked: >= 0, appended gradually
2487 */
2488 int64_t consumed_content; /* How many bytes of content have been read */
2489 int is_chunked; /* Transfer-Encoding is chunked:
2490 * 0 = not chunked,
2491 * 1 = chunked, not yet, or some data read,
2492 * 2 = chunked, has error,
2493 * 3 = chunked, all data read except trailer,
2494 * 4 = chunked, all data read
2495 */
2496 char *buf; /* Buffer for received data */
2497 char *path_info; /* PATH_INFO part of the URL */
2498
2499 int must_close; /* 1 if connection must be closed */
2500 int accept_gzip; /* 1 if gzip encoding is accepted */
2501 int in_error_handler; /* 1 if in handler for user defined error
2502 * pages */
2503#if defined(USE_WEBSOCKET)
2504 int in_websocket_handling; /* 1 if in read_websocket */
2505#endif
2506#if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
2507 && defined(MG_EXPERIMENTAL_INTERFACES)
2508 /* Parameters for websocket data compression according to rfc7692 */
2509 int websocket_deflate_server_max_windows_bits;
2510 int websocket_deflate_client_max_windows_bits;
2511 int websocket_deflate_server_no_context_takeover;
2512 int websocket_deflate_client_no_context_takeover;
2513 int websocket_deflate_initialized;
2514 int websocket_deflate_flush;
2515 z_stream websocket_deflate_state;
2516 z_stream websocket_inflate_state;
2517#endif
2518 int handled_requests; /* Number of requests handled by this connection
2519 */
2520 int buf_size; /* Buffer size */
2521 int request_len; /* Size of the request + headers in a buffer */
2522 int data_len; /* Total size of data in a buffer */
2523 int status_code; /* HTTP reply status code, e.g. 200 */
2524 int throttle; /* Throttling, bytes/sec. <= 0 means no
2525 * throttle */
2526
2527 time_t last_throttle_time; /* Last time throttled data was sent */
2528 int last_throttle_bytes; /* Bytes sent this second */
2529 pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
2530 * atomic transmissions for websockets */
2531#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2532 void *lua_websocket_state; /* Lua_State for a websocket connection */
2533#endif
2534
2535 void *tls_user_ptr; /* User defined pointer in thread local storage,
2536 * for quick access */
2537};
2538
2539
2540/* Directory entry */
2541struct de {
2545};
2546
2547
2548#define mg_cry_internal(conn, fmt, ...) \
2549 mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
2550
2551#define mg_cry_ctx_internal(ctx, fmt, ...) \
2552 mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
2553
2554static void mg_cry_internal_wrap(const struct mg_connection *conn,
2555 struct mg_context *ctx,
2556 const char *func,
2557 unsigned line,
2558 const char *fmt,
2559 ...) PRINTF_ARGS(5, 6);
2560
2561
2562#if !defined(NO_THREAD_NAME)
2563#if defined(_WIN32) && defined(_MSC_VER)
2564/* Set the thread name for debugging purposes in Visual Studio
2565 * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
2566 */
2567#pragma pack(push, 8)
2568typedef struct tagTHREADNAME_INFO {
2569 DWORD dwType; /* Must be 0x1000. */
2570 LPCSTR szName; /* Pointer to name (in user addr space). */
2571 DWORD dwThreadID; /* Thread ID (-1=caller thread). */
2572 DWORD dwFlags; /* Reserved for future use, must be zero. */
2573} THREADNAME_INFO;
2574#pragma pack(pop)
2575
2576#elif defined(__linux__)
2577
2578#include <sys/prctl.h>
2579#include <sys/sendfile.h>
2580#if defined(ALTERNATIVE_QUEUE)
2581#include <sys/eventfd.h>
2582#endif /* ALTERNATIVE_QUEUE */
2583
2584
2585#if defined(ALTERNATIVE_QUEUE)
2586
2587static void *
2588event_create(void)
2589{
2590 int evhdl = eventfd(0, EFD_CLOEXEC);
2591 int *ret;
2592
2593 if (evhdl == -1) {
2594 /* Linux uses -1 on error, Windows NULL. */
2595 /* However, Linux does not return 0 on success either. */
2596 return 0;
2597 }
2598
2599 ret = (int *)mg_malloc(sizeof(int));
2600 if (ret) {
2601 *ret = evhdl;
2602 } else {
2603 (void)close(evhdl);
2604 }
2605
2606 return (void *)ret;
2607}
2608
2609
2610static int
2611event_wait(void *eventhdl)
2612{
2613 uint64_t u;
2614 int evhdl, s;
2615
2616 if (!eventhdl) {
2617 /* error */
2618 return 0;
2619 }
2620 evhdl = *(int *)eventhdl;
2621
2622 s = (int)read(evhdl, &u, sizeof(u));
2623 if (s != sizeof(u)) {
2624 /* error */
2625 return 0;
2626 }
2627 (void)u; /* the value is not required */
2628 return 1;
2629}
2630
2631
2632static int
2633event_signal(void *eventhdl)
2634{
2635 uint64_t u = 1;
2636 int evhdl, s;
2637
2638 if (!eventhdl) {
2639 /* error */
2640 return 0;
2641 }
2642 evhdl = *(int *)eventhdl;
2643
2644 s = (int)write(evhdl, &u, sizeof(u));
2645 if (s != sizeof(u)) {
2646 /* error */
2647 return 0;
2648 }
2649 return 1;
2650}
2651
2652
2653static void
2654event_destroy(void *eventhdl)
2655{
2656 int evhdl;
2657
2658 if (!eventhdl) {
2659 /* error */
2660 return;
2661 }
2662 evhdl = *(int *)eventhdl;
2663
2664 close(evhdl);
2665 mg_free(eventhdl);
2666}
2667
2668
2669#endif
2670
2671#endif
2672
2673
2674#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2675
2676struct posix_event {
2677 pthread_mutex_t mutex;
2678 pthread_cond_t cond;
2679 int signaled;
2680};
2681
2682
2683static void *
2684event_create(void)
2685{
2686 struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
2687 if (ret == 0) {
2688 /* out of memory */
2689 return 0;
2690 }
2691 if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2692 /* pthread mutex not available */
2693 mg_free(ret);
2694 return 0;
2695 }
2696 if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2697 /* pthread cond not available */
2698 pthread_mutex_destroy(&(ret->mutex));
2699 mg_free(ret);
2700 return 0;
2701 }
2702 ret->signaled = 0;
2703 return (void *)ret;
2704}
2705
2706
2707static int
2708event_wait(void *eventhdl)
2709{
2710 struct posix_event *ev = (struct posix_event *)eventhdl;
2711 pthread_mutex_lock(&(ev->mutex));
2712 while (!ev->signaled) {
2713 pthread_cond_wait(&(ev->cond), &(ev->mutex));
2714 }
2715 ev->signaled = 0;
2716 pthread_mutex_unlock(&(ev->mutex));
2717 return 1;
2718}
2719
2720
2721static int
2722event_signal(void *eventhdl)
2723{
2724 struct posix_event *ev = (struct posix_event *)eventhdl;
2725 pthread_mutex_lock(&(ev->mutex));
2726 pthread_cond_signal(&(ev->cond));
2727 ev->signaled = 1;
2728 pthread_mutex_unlock(&(ev->mutex));
2729 return 1;
2730}
2731
2732
2733static void
2734event_destroy(void *eventhdl)
2735{
2736 struct posix_event *ev = (struct posix_event *)eventhdl;
2737 pthread_cond_destroy(&(ev->cond));
2738 pthread_mutex_destroy(&(ev->mutex));
2739 mg_free(ev);
2740}
2741#endif
2742
2743
2744static void
2746{
2747 char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
2748
2750 NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
2751
2752#if defined(_WIN32)
2753#if defined(_MSC_VER)
2754 /* Windows and Visual Studio Compiler */
2755 __try {
2756 THREADNAME_INFO info;
2757 info.dwType = 0x1000;
2758 info.szName = threadName;
2759 info.dwThreadID = ~0U;
2760 info.dwFlags = 0;
2761
2762 RaiseException(0x406D1388,
2763 0,
2764 sizeof(info) / sizeof(ULONG_PTR),
2765 (ULONG_PTR *)&info);
2766 } __except (EXCEPTION_EXECUTE_HANDLER) {
2767 }
2768#elif defined(__MINGW32__)
2769 /* No option known to set thread name for MinGW known */
2770#endif
2771#elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
2772 && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
2773 /* pthread_setname_np first appeared in glibc in version 2.12 */
2774#if defined(__MACH__)
2775 /* OS X only current thread name can be changed */
2776 (void)pthread_setname_np(threadName);
2777#else
2778 (void)pthread_setname_np(pthread_self(), threadName);
2779#endif
2780#elif defined(__linux__)
2781 /* On Linux we can use the prctl function.
2782 * When building for Linux Standard Base (LSB) use
2783 * NO_THREAD_NAME. However, thread names are a big
2784 * help for debugging, so the stadard is to set them.
2785 */
2786 (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
2787#endif
2788}
2789#else /* !defined(NO_THREAD_NAME) */
2790void
2791mg_set_thread_name(const char *threadName)
2792{
2793}
2794#endif
2795
2796
2797const struct mg_option *
2799{
2800 return config_options;
2801}
2802
2803
2804/* Do not open file (unused) */
2805#define MG_FOPEN_MODE_NONE (0)
2806
2807/* Open file for read only access */
2808#define MG_FOPEN_MODE_READ (1)
2809
2810/* Open file for writing, create and overwrite */
2811#define MG_FOPEN_MODE_WRITE (2)
2812
2813/* Open file for writing, create and append */
2814#define MG_FOPEN_MODE_APPEND (4)
2815
2816
2817static int
2818is_file_opened(const struct mg_file_access *fileacc)
2819{
2820 if (!fileacc) {
2821 return 0;
2822 }
2823
2824 return (fileacc->fp != NULL);
2825}
2826
2827
2828#if !defined(NO_FILESYSTEMS)
2829static int mg_stat(const struct mg_connection *conn,
2830 const char *path,
2831 struct mg_file_stat *filep);
2832
2833
2834/* Reject files with special characters (for Windows) */
2835static int
2836mg_path_suspicious(const struct mg_connection *conn, const char *path)
2837{
2838 const uint8_t *c = (const uint8_t *)path;
2839 (void)conn; /* not used */
2840
2841 if ((c == NULL) || (c[0] == 0)) {
2842 /* Null pointer or empty path --> suspicious */
2843 return 1;
2844 }
2845
2846#if defined(_WIN32)
2847 while (*c) {
2848 if (*c < 32) {
2849 /* Control character */
2850 return 1;
2851 }
2852 if ((*c == '>') || (*c == '<') || (*c == '|')) {
2853 /* stdin/stdout redirection character */
2854 return 1;
2855 }
2856 if ((*c == '*') || (*c == '?')) {
2857 /* Wildcard character */
2858 return 1;
2859 }
2860 if (*c == '"') {
2861 /* Windows quotation */
2862 return 1;
2863 }
2864 c++;
2865 }
2866#endif
2867
2868 /* Nothing suspicious found */
2869 return 0;
2870}
2871
2872
2873/* mg_fopen will open a file either in memory or on the disk.
2874 * The input parameter path is a string in UTF-8 encoding.
2875 * The input parameter mode is MG_FOPEN_MODE_*
2876 * On success, fp will be set in the output struct mg_file.
2877 * All status members will also be set.
2878 * The function returns 1 on success, 0 on error. */
2879static int
2880mg_fopen(const struct mg_connection *conn,
2881 const char *path,
2882 int mode,
2883 struct mg_file *filep)
2884{
2885 int found;
2886
2887 if (!filep) {
2888 return 0;
2889 }
2890 filep->access.fp = NULL;
2891
2892 if (mg_path_suspicious(conn, path)) {
2893 return 0;
2894 }
2895
2896 /* filep is initialized in mg_stat: all fields with memset to,
2897 * some fields like size and modification date with values */
2898 found = mg_stat(conn, path, &(filep->stat));
2899
2900 if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
2901 /* file does not exist and will not be created */
2902 return 0;
2903 }
2904
2905#if defined(_WIN32)
2906 {
2907 wchar_t wbuf[UTF16_PATH_MAX];
2908 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
2909 switch (mode) {
2910 case MG_FOPEN_MODE_READ:
2911 filep->access.fp = _wfopen(wbuf, L"rb");
2912 break;
2914 filep->access.fp = _wfopen(wbuf, L"wb");
2915 break;
2917 filep->access.fp = _wfopen(wbuf, L"ab");
2918 break;
2919 }
2920 }
2921#else
2922 /* Linux et al already use unicode. No need to convert. */
2923 switch (mode) {
2924 case MG_FOPEN_MODE_READ:
2925 filep->access.fp = fopen(path, "r");
2926 break;
2928 filep->access.fp = fopen(path, "w");
2929 break;
2931 filep->access.fp = fopen(path, "a");
2932 break;
2933 }
2934
2935#endif
2936 if (!found) {
2937 /* File did not exist before fopen was called.
2938 * Maybe it has been created now. Get stat info
2939 * like creation time now. */
2940 found = mg_stat(conn, path, &(filep->stat));
2941 (void)found;
2942 }
2943
2944 /* return OK if file is opened */
2945 return (filep->access.fp != NULL);
2946}
2947
2948
2949/* return 0 on success, just like fclose */
2950static int
2952{
2953 int ret = -1;
2954 if (fileacc != NULL) {
2955 if (fileacc->fp != NULL) {
2956 ret = fclose(fileacc->fp);
2957 }
2958 /* reset all members of fileacc */
2959 memset(fileacc, 0, sizeof(*fileacc));
2960 }
2961 return ret;
2962}
2963#endif /* NO_FILESYSTEMS */
2964
2965
2966static void
2967mg_strlcpy(char *dst, const char *src, size_t n)
2968{
2969 for (; *src != '\0' && n > 1; n--) {
2970 *dst++ = *src++;
2971 }
2972 *dst = '\0';
2973}
2974
2975
2976static int
2977lowercase(const char *s)
2978{
2979 return tolower((unsigned char)*s);
2980}
2981
2982
2983int
2984mg_strncasecmp(const char *s1, const char *s2, size_t len)
2985{
2986 int diff = 0;
2987
2988 if (len > 0) {
2989 do {
2990 diff = lowercase(s1++) - lowercase(s2++);
2991 } while (diff == 0 && s1[-1] != '\0' && --len > 0);
2992 }
2993
2994 return diff;
2995}
2996
2997
2998int
2999mg_strcasecmp(const char *s1, const char *s2)
3000{
3001 int diff;
3002
3003 do {
3004 diff = lowercase(s1++) - lowercase(s2++);
3005 } while (diff == 0 && s1[-1] != '\0');
3006
3007 return diff;
3008}
3009
3010
3011static char *
3012mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
3013{
3014 char *p;
3015 (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
3016 * defined */
3017
3018 if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
3019 mg_strlcpy(p, ptr, len + 1);
3020 }
3021
3022 return p;
3023}
3024
3025
3026static char *
3027mg_strdup_ctx(const char *str, struct mg_context *ctx)
3028{
3029 return mg_strndup_ctx(str, strlen(str), ctx);
3030}
3031
3032static char *
3033mg_strdup(const char *str)
3034{
3035 return mg_strndup_ctx(str, strlen(str), NULL);
3036}
3037
3038
3039static const char *
3040mg_strcasestr(const char *big_str, const char *small_str)
3041{
3042 size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3043
3044 if (big_len >= small_len) {
3045 for (i = 0; i <= (big_len - small_len); i++) {
3046 if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
3047 return big_str + i;
3048 }
3049 }
3050 }
3051
3052 return NULL;
3053}
3054
3055
3056/* Return null terminated string of given maximum length.
3057 * Report errors if length is exceeded. */
3058static void
3059mg_vsnprintf(const struct mg_connection *conn,
3060 int *truncated,
3061 char *buf,
3062 size_t buflen,
3063 const char *fmt,
3064 va_list ap)
3065{
3066 int n, ok;
3067
3068 if (buflen == 0) {
3069 if (truncated) {
3070 *truncated = 1;
3071 }
3072 return;
3073 }
3074
3075#if defined(__clang__)
3076#pragma clang diagnostic push
3077#pragma clang diagnostic ignored "-Wformat-nonliteral"
3078 /* Using fmt as a non-literal is intended here, since it is mostly called
3079 * indirectly by mg_snprintf */
3080#endif
3081
3082 n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
3083 ok = (n >= 0) && ((size_t)n < buflen);
3084
3085#if defined(__clang__)
3086#pragma clang diagnostic pop
3087#endif
3088
3089 if (ok) {
3090 if (truncated) {
3091 *truncated = 0;
3092 }
3093 } else {
3094 if (truncated) {
3095 *truncated = 1;
3096 }
3097 mg_cry_internal(conn,
3098 "truncating vsnprintf buffer: [%.*s]",
3099 (int)((buflen > 200) ? 200 : (buflen - 1)),
3100 buf);
3101 n = (int)buflen - 1;
3102 }
3103 buf[n] = '\0';
3104}
3105
3106
3107static void
3108mg_snprintf(const struct mg_connection *conn,
3109 int *truncated,
3110 char *buf,
3111 size_t buflen,
3112 const char *fmt,
3113 ...)
3114{
3115 va_list ap;
3116
3117 va_start(ap, fmt);
3118 mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
3119 va_end(ap);
3120}
3121
3122
3123static int
3125{
3126 int i;
3127
3128 for (i = 0; config_options[i].name != NULL; i++) {
3129 if (strcmp(config_options[i].name, name) == 0) {
3130 return i;
3131 }
3132 }
3133 return -1;
3134}
3135
3136
3137const char *
3138mg_get_option(const struct mg_context *ctx, const char *name)
3139{
3140 int i;
3141 if ((i = get_option_index(name)) == -1) {
3142 return NULL;
3143 } else if (!ctx || ctx->dd.config[i] == NULL) {
3144 return "";
3145 } else {
3146 return ctx->dd.config[i];
3147 }
3148}
3149
3150#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3151
3152struct mg_context *
3154{
3155 return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
3156}
3157
3158
3159void *
3161{
3162 return (ctx == NULL) ? NULL : ctx->user_data;
3163}
3164
3165
3166void *
3168{
3169 return mg_get_user_data(mg_get_context(conn));
3170}
3171
3172
3173void *
3175{
3176 /* both methods should return the same pointer */
3177 if (conn) {
3178 /* quick access, in case conn is known */
3179 return conn->tls_user_ptr;
3180 } else {
3181 /* otherwise get pointer from thread local storage (TLS) */
3182 struct mg_workerTLS *tls =
3183 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3184 return tls->user_ptr;
3185 }
3186}
3187
3188
3189void
3190mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
3191{
3192 if (const_conn != NULL) {
3193 /* Const cast, since "const struct mg_connection *" does not mean
3194 * the connection object is not modified. Here "const" is used,
3195 * to indicate mg_read/mg_write/mg_send/.. must not be called. */
3196 struct mg_connection *conn = (struct mg_connection *)const_conn;
3197 conn->request_info.conn_data = data;
3198 }
3199}
3200
3201
3202void *
3204{
3205 if (conn != NULL) {
3206 return conn->request_info.conn_data;
3207 }
3208 return NULL;
3209}
3210
3211
3212int
3214 int size,
3215 struct mg_server_port *ports)
3216{
3217 int i, cnt = 0;
3218
3219 if (size <= 0) {
3220 return -1;
3221 }
3222 memset(ports, 0, sizeof(*ports) * (size_t)size);
3223 if (!ctx) {
3224 return -1;
3225 }
3226 if (!ctx->listening_sockets) {
3227 return -1;
3228 }
3229
3230 for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
3231
3232 ports[cnt].port =
3233 ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
3234 ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
3235 ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
3236
3237 if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
3238 /* IPv4 */
3239 ports[cnt].protocol = 1;
3240 cnt++;
3241 } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
3242 /* IPv6 */
3243 ports[cnt].protocol = 3;
3244 cnt++;
3245 }
3246 }
3247
3248 return cnt;
3249}
3250
3251
3252#if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
3253#define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
3254#endif
3255
3256static void
3257sockaddr_to_string(char *buf, size_t len, const union usa *usa)
3258{
3259 buf[0] = '\0';
3260
3261 if (!usa) {
3262 return;
3263 }
3264
3265 if (usa->sa.sa_family == AF_INET) {
3266 getnameinfo(&usa->sa,
3267 sizeof(usa->sin),
3268 buf,
3269 (unsigned)len,
3270 NULL,
3271 0,
3272 NI_NUMERICHOST);
3273 }
3274#if defined(USE_IPV6)
3275 else if (usa->sa.sa_family == AF_INET6) {
3276 getnameinfo(&usa->sa,
3277 sizeof(usa->sin6),
3278 buf,
3279 (unsigned)len,
3280 NULL,
3281 0,
3282 NI_NUMERICHOST);
3283 }
3284#endif
3285#if defined(USE_X_DOM_SOCKET)
3286 else if (usa->sa.sa_family == AF_UNIX) {
3287 /* TODO: Define a remote address for unix domain sockets.
3288 * This code will always return "localhost", identical to http+tcp:
3289 getnameinfo(&usa->sa,
3290 sizeof(usa->sun),
3291 buf,
3292 (unsigned)len,
3293 NULL,
3294 0,
3295 NI_NUMERICHOST);
3296 */
3297 strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
3298 buf[len-1] = 0;
3299 }
3300#endif
3301}
3302
3303
3304/* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
3305 * included in all responses other than 100, 101, 5xx. */
3306static void
3307gmt_time_string(char *buf, size_t buf_len, time_t *t)
3308{
3309#if !defined(REENTRANT_TIME)
3310 struct tm *tm;
3311
3312 tm = ((t != NULL) ? gmtime(t) : NULL);
3313 if (tm != NULL) {
3314#else
3315 struct tm _tm;
3316 struct tm *tm = &_tm;
3317
3318 if (t != NULL) {
3319 gmtime_r(t, tm);
3320#endif
3321 strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
3322 } else {
3323 mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3324 buf[buf_len - 1] = '\0';
3325 }
3326}
3327
3328
3329/* difftime for struct timespec. Return value is in seconds. */
3330static double
3331mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
3332{
3333 return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3334 + (double)(ts_now->tv_sec - ts_before->tv_sec);
3335}
3336
3337
3338#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3339static void mg_cry_internal_impl(const struct mg_connection *conn,
3340 const char *func,
3341 unsigned line,
3342 const char *fmt,
3343 va_list ap);
3344#include "external_mg_cry_internal_impl.inl"
3345#elif !defined(NO_FILESYSTEMS)
3346
3347/* Print error message to the opened error log stream. */
3348static void
3350 const char *func,
3351 unsigned line,
3352 const char *fmt,
3353 va_list ap)
3354{
3355 char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
3356 struct mg_file fi;
3357 time_t timestamp;
3358
3359 /* Unused, in the RELEASE build */
3360 (void)func;
3361 (void)line;
3362
3363#if defined(GCC_DIAGNOSTIC)
3364#pragma GCC diagnostic push
3365#pragma GCC diagnostic ignored "-Wformat-nonliteral"
3366#endif
3367
3368 IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
3369
3370#if defined(GCC_DIAGNOSTIC)
3371#pragma GCC diagnostic pop
3372#endif
3373
3374 buf[sizeof(buf) - 1] = 0;
3375
3376 DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
3377
3378 if (!conn) {
3379 puts(buf);
3380 return;
3381 }
3382
3383 /* Do not lock when getting the callback value, here and below.
3384 * I suppose this is fine, since function cannot disappear in the
3385 * same way string option can. */
3386 if ((conn->phys_ctx->callbacks.log_message == NULL)
3387 || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
3388
3389 if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
3390 if (mg_fopen(conn,
3393 &fi)
3394 == 0) {
3395 fi.access.fp = NULL;
3396 }
3397 } else {
3398 fi.access.fp = NULL;
3399 }
3400
3401 if (fi.access.fp != NULL) {
3402 flockfile(fi.access.fp);
3403 timestamp = time(NULL);
3404
3405 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
3406 fprintf(fi.access.fp,
3407 "[%010lu] [error] [client %s] ",
3408 (unsigned long)timestamp,
3409 src_addr);
3410
3411 if (conn->request_info.request_method != NULL) {
3412 fprintf(fi.access.fp,
3413 "%s %s: ",
3417 : "");
3418 }
3419
3420 fprintf(fi.access.fp, "%s", buf);
3421 fputc('\n', fi.access.fp);
3422 fflush(fi.access.fp);
3423 funlockfile(fi.access.fp);
3424 (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
3425 * mg_cry here anyway ;-) */
3426 }
3427 }
3428}
3429#else
3430#error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
3431#endif /* Externally provided function */
3432
3433
3434/* Construct fake connection structure. Used for logging, if connection
3435 * is not applicable at the moment of logging. */
3436static struct mg_connection *
3438{
3439 static const struct mg_connection conn_zero = {0};
3440 *fc = conn_zero;
3441 fc->phys_ctx = ctx;
3442 fc->dom_ctx = &(ctx->dd);
3443 return fc;
3444}
3445
3446
3447static void
3449 struct mg_context *ctx,
3450 const char *func,
3451 unsigned line,
3452 const char *fmt,
3453 ...)
3454{
3455 va_list ap;
3456 va_start(ap, fmt);
3457 if (!conn && ctx) {
3458 struct mg_connection fc;
3459 mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
3460 } else {
3461 mg_cry_internal_impl(conn, func, line, fmt, ap);
3462 }
3463 va_end(ap);
3464}
3465
3466
3467void
3468mg_cry(const struct mg_connection *conn, const char *fmt, ...)
3469{
3470 va_list ap;
3471 va_start(ap, fmt);
3472 mg_cry_internal_impl(conn, "user", 0, fmt, ap);
3473 va_end(ap);
3474}
3475
3476
3477#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3478
3479
3480const char *
3482{
3483 return CIVETWEB_VERSION;
3484}
3485
3486
3487const struct mg_request_info *
3489{
3490 if (!conn) {
3491 return NULL;
3492 }
3493#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3495 char txt[16];
3496 struct mg_workerTLS *tls =
3497 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3498
3499 sprintf(txt, "%03i", conn->response_info.status_code);
3500 if (strlen(txt) == 3) {
3501 memcpy(tls->txtbuf, txt, 4);
3502 } else {
3503 strcpy(tls->txtbuf, "ERR");
3504 }
3505
3506 ((struct mg_connection *)conn)->request_info.local_uri =
3507 tls->txtbuf; /* use thread safe buffer */
3508 ((struct mg_connection *)conn)->request_info.local_uri_raw =
3509 tls->txtbuf; /* use the same thread safe buffer */
3510 ((struct mg_connection *)conn)->request_info.request_uri =
3511 tls->txtbuf; /* use the same thread safe buffer */
3512
3513 ((struct mg_connection *)conn)->request_info.num_headers =
3515 memcpy(((struct mg_connection *)conn)->request_info.http_headers,
3517 sizeof(conn->response_info.http_headers));
3518 } else
3519#endif
3521 return NULL;
3522 }
3523 return &conn->request_info;
3524}
3525
3526
3527const struct mg_response_info *
3529{
3530 if (!conn) {
3531 return NULL;
3532 }
3534 return NULL;
3535 }
3536 return &conn->response_info;
3537}
3538
3539
3540static const char *
3542{
3543#if defined(__clang__)
3544#pragma clang diagnostic push
3545#pragma clang diagnostic ignored "-Wunreachable-code"
3546 /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
3547 * not supported. Clang raises an "unreachable code" warning for parts of ?:
3548 * unreachable, but splitting into four different #ifdef clauses here is
3549 * more complicated.
3550 */
3551#endif
3552
3553 const struct mg_request_info *ri = &conn->request_info;
3554
3555 const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
3556 ? (ri->is_ssl ? "wss" : "ws")
3557 : (ri->is_ssl ? "https" : "http"));
3558
3559 return proto;
3560
3561#if defined(__clang__)
3562#pragma clang diagnostic pop
3563#endif
3564}
3565
3566
3567static int
3569 char *buf,
3570 size_t buflen,
3571 const char *define_proto,
3572 int define_port,
3573 const char *define_uri)
3574{
3575 if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3576 return -1;
3577 } else {
3578 int truncated = 0;
3579 const struct mg_request_info *ri = &conn->request_info;
3580
3581 const char *proto =
3582 (define_proto != NULL) ? define_proto : get_proto_name(conn);
3583 const char *uri =
3584 (define_uri != NULL)
3585 ? define_uri
3586 : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
3587 int port = (define_port > 0) ? define_port : ri->server_port;
3588 int default_port = 80;
3589
3590 if (uri == NULL) {
3591 return -1;
3592 }
3593
3594#if defined(USE_X_DOM_SOCKET)
3595 if (conn->client.lsa.sa.sa_family == AF_UNIX) {
3596 /* TODO: Define and document a link for UNIX domain sockets. */
3597 /* There seems to be no official standard for this.
3598 * Common uses seem to be "httpunix://", "http.unix://" or
3599 * "http+unix://" as a protocol definition string, followed by
3600 * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
3601 * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
3602 * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
3603 * "" (completely skipping the server name part). In any case, the
3604 * last part is the server local path. */
3605 const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
3606 mg_snprintf(conn,
3607 &truncated,
3608 buf,
3609 buflen,
3610 "%s.unix://%s%s",
3611 proto,
3612 server_name,
3613 ri->local_uri);
3614 default_port = 0;
3615 return 0;
3616 }
3617#endif
3618
3619 if (define_proto) {
3620 /* If we got a protocol name, use the default port accordingly. */
3621 if ((0 == strcmp(define_proto, "https"))
3622 || (0 == strcmp(define_proto, "wss"))) {
3623 default_port = 443;
3624 }
3625 } else if (ri->is_ssl) {
3626 /* If we did not get a protocol name, use TLS as default if it is
3627 * already used. */
3628 default_port = 443;
3629 }
3630
3631 {
3632#if defined(USE_IPV6)
3633 int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
3634#endif
3635 int auth_domain_check_enabled =
3637 && (!mg_strcasecmp(
3638 conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
3639
3640 const char *server_domain =
3642
3643 char portstr[16];
3644 char server_ip[48];
3645
3646 if (port != default_port) {
3647 sprintf(portstr, ":%u", (unsigned)port);
3648 } else {
3649 portstr[0] = 0;
3650 }
3651
3652 if (!auth_domain_check_enabled || !server_domain) {
3653
3654 sockaddr_to_string(server_ip,
3655 sizeof(server_ip),
3656 &conn->client.lsa);
3657
3658 server_domain = server_ip;
3659 }
3660
3661 mg_snprintf(conn,
3662 &truncated,
3663 buf,
3664 buflen,
3665#if defined(USE_IPV6)
3666 "%s://%s%s%s%s%s",
3667 proto,
3668 (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
3669 server_domain,
3670 (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
3671#else
3672 "%s://%s%s%s",
3673 proto,
3674 server_domain,
3675#endif
3676 portstr,
3677 ri->local_uri);
3678
3679 if (truncated) {
3680 return -1;
3681 }
3682 return 0;
3683 }
3684 }
3685}
3686
3687
3688int
3689mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
3690{
3691 return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
3692}
3693
3694
3695/* Skip the characters until one of the delimiters characters found.
3696 * 0-terminate resulting word. Skip the delimiter and following whitespaces.
3697 * Advance pointer to buffer to the next word. Return found 0-terminated
3698 * word.
3699 * Delimiters can be quoted with quotechar. */
3700static char *
3701skip_quoted(char **buf,
3702 const char *delimiters,
3703 const char *whitespace,
3704 char quotechar)
3705{
3706 char *p, *begin_word, *end_word, *end_whitespace;
3707
3708 begin_word = *buf;
3709 end_word = begin_word + strcspn(begin_word, delimiters);
3710
3711 /* Check for quotechar */
3712 if (end_word > begin_word) {
3713 p = end_word - 1;
3714 while (*p == quotechar) {
3715 /* While the delimiter is quoted, look for the next delimiter.
3716 */
3717 /* This happens, e.g., in calls from parse_auth_header,
3718 * if the user name contains a " character. */
3719
3720 /* If there is anything beyond end_word, copy it. */
3721 if (*end_word != '\0') {
3722 size_t end_off = strcspn(end_word + 1, delimiters);
3723 memmove(p, end_word, end_off + 1);
3724 p += end_off; /* p must correspond to end_word - 1 */
3725 end_word += end_off + 1;
3726 } else {
3727 *p = '\0';
3728 break;
3729 }
3730 }
3731 for (p++; p < end_word; p++) {
3732 *p = '\0';
3733 }
3734 }
3735
3736 if (*end_word == '\0') {
3737 *buf = end_word;
3738 } else {
3739
3740#if defined(GCC_DIAGNOSTIC)
3741 /* Disable spurious conversion warning for GCC */
3742#pragma GCC diagnostic push
3743#pragma GCC diagnostic ignored "-Wsign-conversion"
3744#endif /* defined(GCC_DIAGNOSTIC) */
3745
3746 end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
3747
3748#if defined(GCC_DIAGNOSTIC)
3749#pragma GCC diagnostic pop
3750#endif /* defined(GCC_DIAGNOSTIC) */
3751
3752 for (p = end_word; p < end_whitespace; p++) {
3753 *p = '\0';
3754 }
3755
3756 *buf = end_whitespace;
3757 }
3758
3759 return begin_word;
3760}
3761
3762
3763/* Return HTTP header value, or NULL if not found. */
3764static const char *
3765get_header(const struct mg_header *hdr, int num_hdr, const char *name)
3766{
3767 int i;
3768 for (i = 0; i < num_hdr; i++) {
3769 if (!mg_strcasecmp(name, hdr[i].name)) {
3770 return hdr[i].value;
3771 }
3772 }
3773
3774 return NULL;
3775}
3776
3777
3778#if defined(USE_WEBSOCKET)
3779/* Retrieve requested HTTP header multiple values, and return the number of
3780 * found occurrences */
3781static int
3782get_req_headers(const struct mg_request_info *ri,
3783 const char *name,
3784 const char **output,
3785 int output_max_size)
3786{
3787 int i;
3788 int cnt = 0;
3789 if (ri) {
3790 for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
3791 if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
3792 output[cnt++] = ri->http_headers[i].value;
3793 }
3794 }
3795 }
3796 return cnt;
3797}
3798#endif
3799
3800
3801const char *
3802mg_get_header(const struct mg_connection *conn, const char *name)
3803{
3804 if (!conn) {
3805 return NULL;
3806 }
3807
3811 name);
3812 }
3816 name);
3817 }
3818 return NULL;
3819}
3820
3821
3822static const char *
3824{
3825 if (!conn) {
3826 return NULL;
3827 }
3828
3830 return conn->request_info.http_version;
3831 }
3833 return conn->response_info.http_version;
3834 }
3835 return NULL;
3836}
3837
3838
3839/* A helper function for traversing a comma separated list of values.
3840 * It returns a list pointer shifted to the next value, or NULL if the end
3841 * of the list found.
3842 * Value is stored in val vector. If value has form "x=y", then eq_val
3843 * vector is initialized to point to the "y" part, and val vector length
3844 * is adjusted to point only to "x". */
3845static const char *
3846next_option(const char *list, struct vec *val, struct vec *eq_val)
3847{
3848 int end;
3849
3850reparse:
3851 if (val == NULL || list == NULL || *list == '\0') {
3852 /* End of the list */
3853 return NULL;
3854 }
3855
3856 /* Skip over leading LWS */
3857 while (*list == ' ' || *list == '\t')
3858 list++;
3859
3860 val->ptr = list;
3861 if ((list = strchr(val->ptr, ',')) != NULL) {
3862 /* Comma found. Store length and shift the list ptr */
3863 val->len = ((size_t)(list - val->ptr));
3864 list++;
3865 } else {
3866 /* This value is the last one */
3867 list = val->ptr + strlen(val->ptr);
3868 val->len = ((size_t)(list - val->ptr));
3869 }
3870
3871 /* Adjust length for trailing LWS */
3872 end = (int)val->len - 1;
3873 while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
3874 end--;
3875 val->len = (size_t)(end) + (size_t)(1);
3876
3877 if (val->len == 0) {
3878 /* Ignore any empty entries. */
3879 goto reparse;
3880 }
3881
3882 if (eq_val != NULL) {
3883 /* Value has form "x=y", adjust pointers and lengths
3884 * so that val points to "x", and eq_val points to "y". */
3885 eq_val->len = 0;
3886 eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
3887 if (eq_val->ptr != NULL) {
3888 eq_val->ptr++; /* Skip over '=' character */
3889 eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
3890 val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
3891 }
3892 }
3893
3894 return list;
3895}
3896
3897
3898/* A helper function for checking if a comma separated list of values
3899 * contains
3900 * the given option (case insensitvely).
3901 * 'header' can be NULL, in which case false is returned. */
3902static int
3903header_has_option(const char *header, const char *option)
3904{
3905 struct vec opt_vec;
3906 struct vec eq_vec;
3907
3908 DEBUG_ASSERT(option != NULL);
3909 DEBUG_ASSERT(option[0] != '\0');
3910
3911 while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
3912 if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
3913 return 1;
3914 }
3915
3916 return 0;
3917}
3918
3919
3920/* Perform case-insensitive match of string against pattern */
3921static ptrdiff_t
3922match_prefix(const char *pattern, size_t pattern_len, const char *str)
3923{
3924 const char *or_str;
3925 ptrdiff_t i, j, len, res;
3926
3927 if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
3928 res = match_prefix(pattern, (size_t)(or_str - pattern), str);
3929 return (res > 0) ? res
3930 : match_prefix(or_str + 1,
3931 (size_t)((pattern + pattern_len)
3932 - (or_str + 1)),
3933 str);
3934 }
3935
3936 for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
3937 if ((pattern[i] == '?') && (str[j] != '\0')) {
3938 continue;
3939 } else if (pattern[i] == '$') {
3940 return (str[j] == '\0') ? j : -1;
3941 } else if (pattern[i] == '*') {
3942 i++;
3943 if (pattern[i] == '*') {
3944 i++;
3945 len = (ptrdiff_t)strlen(str + j);
3946 } else {
3947 len = (ptrdiff_t)strcspn(str + j, "/");
3948 }
3949 if (i == (ptrdiff_t)pattern_len) {
3950 return j + len;
3951 }
3952 do {
3953 res = match_prefix(pattern + i,
3954 (pattern_len - (size_t)i),
3955 str + j + len);
3956 } while (res == -1 && len-- > 0);
3957 return (res == -1) ? -1 : j + res + len;
3958 } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
3959 return -1;
3960 }
3961 }
3962 return (ptrdiff_t)j;
3963}
3964
3965
3966static ptrdiff_t
3967match_prefix_strlen(const char *pattern, const char *str)
3968{
3969 if (pattern == NULL) {
3970 return -1;
3971 }
3972 return match_prefix(pattern, strlen(pattern), str);
3973}
3974
3975
3976/* HTTP 1.1 assumes keep alive if "Connection:" header is not set
3977 * This function must tolerate situations when connection info is not
3978 * set up, for example if request parsing failed. */
3979static int
3981{
3982 const char *http_version;
3983 const char *header;
3984
3985 /* First satisfy needs of the server */
3986 if ((conn == NULL) || conn->must_close) {
3987 /* Close, if civetweb framework needs to close */
3988 return 0;
3989 }
3990
3991 if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
3992 /* Close, if keep alive is not enabled */
3993 return 0;
3994 }
3995
3996 /* Check explicit wish of the client */
3997 header = mg_get_header(conn, "Connection");
3998 if (header) {
3999 /* If there is a connection header from the client, obey */
4000 if (header_has_option(header, "keep-alive")) {
4001 return 1;
4002 }
4003 return 0;
4004 }
4005
4006 /* Use default of the standard */
4007 http_version = get_http_version(conn);
4008 if (http_version && (0 == strcmp(http_version, "1.1"))) {
4009 /* HTTP 1.1 default is keep alive */
4010 return 1;
4011 }
4012
4013 /* HTTP 1.0 (and earlier) default is to close the connection */
4014 return 0;
4015}
4016
4017
4018static int
4020{
4021 if (!conn || !conn->dom_ctx) {
4022 return 0;
4023 }
4024
4025 return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
4026}
4027
4028
4029static int
4031{
4032 if (!conn || !conn->dom_ctx) {
4033 return 0;
4034 }
4035
4036 return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
4037 == 0);
4038}
4039
4040
4041static const char *
4043{
4044 return should_keep_alive(conn) ? "keep-alive" : "close";
4045}
4046
4047
4048#include "response.inl"
4049
4050
4051static void
4053{
4054 /* Send all current and obsolete cache opt-out directives. */
4056 "Cache-Control",
4057 "no-cache, no-store, "
4058 "must-revalidate, private, max-age=0",
4059 -1);
4060 mg_response_header_add(conn, "Expires", "0", -1);
4061
4062 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
4063 /* Obsolete, but still send it for HTTP/1.0 */
4064 mg_response_header_add(conn, "Pragma", "no-cache", -1);
4065 }
4066}
4067
4068
4069static void
4071{
4072#if !defined(NO_CACHING)
4073 int max_age;
4074 char val[64];
4075
4076 const char *cache_control =
4078
4079 /* If there is a full cache-control option configured,0 use it */
4080 if (cache_control != NULL) {
4081 mg_response_header_add(conn, "Cache-Control", cache_control, -1);
4082 return;
4083 }
4084
4085 /* Read the server config to check how long a file may be cached.
4086 * The configuration is in seconds. */
4087 max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
4088 if (max_age <= 0) {
4089 /* 0 means "do not cache". All values <0 are reserved
4090 * and may be used differently in the future. */
4091 /* If a file should not be cached, do not only send
4092 * max-age=0, but also pragmas and Expires headers. */
4094 return;
4095 }
4096
4097 /* Use "Cache-Control: max-age" instead of "Expires" header.
4098 * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
4099 /* See also https://www.mnot.net/cache_docs/ */
4100 /* According to RFC 2616, Section 14.21, caching times should not exceed
4101 * one year. A year with 365 days corresponds to 31536000 seconds, a
4102 * leap
4103 * year to 31622400 seconds. For the moment, we just send whatever has
4104 * been configured, still the behavior for >1 year should be considered
4105 * as undefined. */
4107 conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
4108 mg_response_header_add(conn, "Cache-Control", val, -1);
4109
4110#else /* NO_CACHING */
4111
4113#endif /* !NO_CACHING */
4114}
4115
4116
4117static void
4119{
4120 const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
4121
4122#if !defined(NO_SSL)
4123 if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
4124 long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
4125 if (max_age >= 0) {
4126 char val[64];
4127 mg_snprintf(conn,
4128 NULL,
4129 val,
4130 sizeof(val),
4131 "max-age=%lu",
4132 (unsigned long)max_age);
4133 mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
4134 }
4135 }
4136#endif
4137
4138 if (header && header[0]) {
4139 mg_response_header_add_lines(conn, header);
4140 }
4141}
4142
4143
4144#if !defined(NO_FILESYSTEMS)
4145static void handle_file_based_request(struct mg_connection *conn,
4146 const char *path,
4147 struct mg_file *filep);
4148#endif /* NO_FILESYSTEMS */
4149
4150
4151const char *
4152mg_get_response_code_text(const struct mg_connection *conn, int response_code)
4153{
4154 /* See IANA HTTP status code assignment:
4155 * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
4156 */
4157
4158 switch (response_code) {
4159 /* RFC2616 Section 10.1 - Informational 1xx */
4160 case 100:
4161 return "Continue"; /* RFC2616 Section 10.1.1 */
4162 case 101:
4163 return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
4164 case 102:
4165 return "Processing"; /* RFC2518 Section 10.1 */
4166
4167 /* RFC2616 Section 10.2 - Successful 2xx */
4168 case 200:
4169 return "OK"; /* RFC2616 Section 10.2.1 */
4170 case 201:
4171 return "Created"; /* RFC2616 Section 10.2.2 */
4172 case 202:
4173 return "Accepted"; /* RFC2616 Section 10.2.3 */
4174 case 203:
4175 return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
4176 case 204:
4177 return "No Content"; /* RFC2616 Section 10.2.5 */
4178 case 205:
4179 return "Reset Content"; /* RFC2616 Section 10.2.6 */
4180 case 206:
4181 return "Partial Content"; /* RFC2616 Section 10.2.7 */
4182 case 207:
4183 return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
4184 */
4185 case 208:
4186 return "Already Reported"; /* RFC5842 Section 7.1 */
4187
4188 case 226:
4189 return "IM used"; /* RFC3229 Section 10.4.1 */
4190
4191 /* RFC2616 Section 10.3 - Redirection 3xx */
4192 case 300:
4193 return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
4194 case 301:
4195 return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
4196 case 302:
4197 return "Found"; /* RFC2616 Section 10.3.3 */
4198 case 303:
4199 return "See Other"; /* RFC2616 Section 10.3.4 */
4200 case 304:
4201 return "Not Modified"; /* RFC2616 Section 10.3.5 */
4202 case 305:
4203 return "Use Proxy"; /* RFC2616 Section 10.3.6 */
4204 case 307:
4205 return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
4206 case 308:
4207 return "Permanent Redirect"; /* RFC7238 Section 3 */
4208
4209 /* RFC2616 Section 10.4 - Client Error 4xx */
4210 case 400:
4211 return "Bad Request"; /* RFC2616 Section 10.4.1 */
4212 case 401:
4213 return "Unauthorized"; /* RFC2616 Section 10.4.2 */
4214 case 402:
4215 return "Payment Required"; /* RFC2616 Section 10.4.3 */
4216 case 403:
4217 return "Forbidden"; /* RFC2616 Section 10.4.4 */
4218 case 404:
4219 return "Not Found"; /* RFC2616 Section 10.4.5 */
4220 case 405:
4221 return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
4222 case 406:
4223 return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
4224 case 407:
4225 return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
4226 case 408:
4227 return "Request Time-out"; /* RFC2616 Section 10.4.9 */
4228 case 409:
4229 return "Conflict"; /* RFC2616 Section 10.4.10 */
4230 case 410:
4231 return "Gone"; /* RFC2616 Section 10.4.11 */
4232 case 411:
4233 return "Length Required"; /* RFC2616 Section 10.4.12 */
4234 case 412:
4235 return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
4236 case 413:
4237 return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
4238 case 414:
4239 return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
4240 case 415:
4241 return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
4242 case 416:
4243 return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
4244 */
4245 case 417:
4246 return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
4247
4248 case 421:
4249 return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
4250 case 422:
4251 return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
4252 * Section 11.2 */
4253 case 423:
4254 return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
4255 case 424:
4256 return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
4257 * Section 11.4 */
4258
4259 case 426:
4260 return "Upgrade Required"; /* RFC 2817 Section 4 */
4261
4262 case 428:
4263 return "Precondition Required"; /* RFC 6585, Section 3 */
4264 case 429:
4265 return "Too Many Requests"; /* RFC 6585, Section 4 */
4266
4267 case 431:
4268 return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
4269
4270 case 451:
4271 return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
4272 * Section 3 */
4273
4274 /* RFC2616 Section 10.5 - Server Error 5xx */
4275 case 500:
4276 return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
4277 case 501:
4278 return "Not Implemented"; /* RFC2616 Section 10.5.2 */
4279 case 502:
4280 return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
4281 case 503:
4282 return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
4283 case 504:
4284 return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
4285 case 505:
4286 return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
4287 case 506:
4288 return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
4289 case 507:
4290 return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
4291 * Section 11.5 */
4292 case 508:
4293 return "Loop Detected"; /* RFC5842 Section 7.1 */
4294
4295 case 510:
4296 return "Not Extended"; /* RFC 2774, Section 7 */
4297 case 511:
4298 return "Network Authentication Required"; /* RFC 6585, Section 6 */
4299
4300 /* Other status codes, not shown in the IANA HTTP status code
4301 * assignment.
4302 * E.g., "de facto" standards due to common use, ... */
4303 case 418:
4304 return "I am a teapot"; /* RFC2324 Section 2.3.2 */
4305 case 419:
4306 return "Authentication Timeout"; /* common use */
4307 case 420:
4308 return "Enhance Your Calm"; /* common use */
4309 case 440:
4310 return "Login Timeout"; /* common use */
4311 case 509:
4312 return "Bandwidth Limit Exceeded"; /* common use */
4313
4314 default:
4315 /* This error code is unknown. This should not happen. */
4316 if (conn) {
4317 mg_cry_internal(conn,
4318 "Unknown HTTP response code: %u",
4319 response_code);
4320 }
4321
4322 /* Return at least a category according to RFC 2616 Section 10. */
4323 if (response_code >= 100 && response_code < 200) {
4324 /* Unknown informational status code */
4325 return "Information";
4326 }
4327 if (response_code >= 200 && response_code < 300) {
4328 /* Unknown success code */
4329 return "Success";
4330 }
4331 if (response_code >= 300 && response_code < 400) {
4332 /* Unknown redirection code */
4333 return "Redirection";
4334 }
4335 if (response_code >= 400 && response_code < 500) {
4336 /* Unknown request error code */
4337 return "Client Error";
4338 }
4339 if (response_code >= 500 && response_code < 600) {
4340 /* Unknown server error code */
4341 return "Server Error";
4342 }
4343
4344 /* Response code not even within reasonable range */
4345 return "";
4346 }
4347}
4348
4349
4350static int
4352 int status,
4353 const char *fmt,
4354 va_list args)
4355{
4356 char errmsg_buf[MG_BUF_LEN];
4357 va_list ap;
4358 int has_body;
4359
4360#if !defined(NO_FILESYSTEMS)
4361 char path_buf[UTF8_PATH_MAX];
4362 int len, i, page_handler_found, scope, truncated;
4363 const char *error_handler = NULL;
4364 struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
4365 const char *error_page_file_ext, *tstr;
4366#endif /* NO_FILESYSTEMS */
4367 int handled_by_callback = 0;
4368
4369 if ((conn == NULL) || (fmt == NULL)) {
4370 return -2;
4371 }
4372
4373 /* Set status (for log) */
4374 conn->status_code = status;
4375
4376 /* Errors 1xx, 204 and 304 MUST NOT send a body */
4377 has_body = ((status > 199) && (status != 204) && (status != 304));
4378
4379 /* Prepare message in buf, if required */
4380 if (has_body
4381 || (!conn->in_error_handler
4382 && (conn->phys_ctx->callbacks.http_error != NULL))) {
4383 /* Store error message in errmsg_buf */
4384 va_copy(ap, args);
4385 mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
4386 va_end(ap);
4387 /* In a debug build, print all html errors */
4388 DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
4389 }
4390
4391 /* If there is a http_error callback, call it.
4392 * But don't do it recursively, if callback calls mg_send_http_error again.
4393 */
4394 if (!conn->in_error_handler
4395 && (conn->phys_ctx->callbacks.http_error != NULL)) {
4396 /* Mark in_error_handler to avoid recursion and call user callback. */
4397 conn->in_error_handler = 1;
4398 handled_by_callback =
4399 (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
4400 == 0);
4401 conn->in_error_handler = 0;
4402 }
4403
4404 if (!handled_by_callback) {
4405 /* Check for recursion */
4406 if (conn->in_error_handler) {
4408 "Recursion when handling error %u - fall back to default",
4409 status);
4410#if !defined(NO_FILESYSTEMS)
4411 } else {
4412 /* Send user defined error pages, if defined */
4413 error_handler = conn->dom_ctx->config[ERROR_PAGES];
4414 error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
4415 page_handler_found = 0;
4416
4417 if (error_handler != NULL) {
4418 for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4419 switch (scope) {
4420 case 1: /* Handler for specific error, e.g. 404 error */
4421 mg_snprintf(conn,
4422 &truncated,
4423 path_buf,
4424 sizeof(path_buf) - 32,
4425 "%serror%03u.",
4426 error_handler,
4427 status);
4428 break;
4429 case 2: /* Handler for error group, e.g., 5xx error
4430 * handler
4431 * for all server errors (500-599) */
4432 mg_snprintf(conn,
4433 &truncated,
4434 path_buf,
4435 sizeof(path_buf) - 32,
4436 "%serror%01uxx.",
4437 error_handler,
4438 status / 100);
4439 break;
4440 default: /* Handler for all errors */
4441 mg_snprintf(conn,
4442 &truncated,
4443 path_buf,
4444 sizeof(path_buf) - 32,
4445 "%serror.",
4446 error_handler);
4447 break;
4448 }
4449
4450 /* String truncation in buf may only occur if
4451 * error_handler is too long. This string is
4452 * from the config, not from a client. */
4453 (void)truncated;
4454
4455 /* The following code is redundant, but it should avoid
4456 * false positives in static source code analyzers and
4457 * vulnerability scanners.
4458 */
4459 path_buf[sizeof(path_buf) - 32] = 0;
4460 len = (int)strlen(path_buf);
4461 if (len > (int)sizeof(path_buf) - 32) {
4462 len = (int)sizeof(path_buf) - 32;
4463 }
4464
4465 /* Start with the file extenstion from the configuration. */
4466 tstr = strchr(error_page_file_ext, '.');
4467
4468 while (tstr) {
4469 for (i = 1;
4470 (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
4471 i++) {
4472 /* buffer overrun is not possible here, since
4473 * (i < 32) && (len < sizeof(path_buf) - 32)
4474 * ==> (i + len) < sizeof(path_buf) */
4475 path_buf[len + i - 1] = tstr[i];
4476 }
4477 /* buffer overrun is not possible here, since
4478 * (i <= 32) && (len < sizeof(path_buf) - 32)
4479 * ==> (i + len) <= sizeof(path_buf) */
4480 path_buf[len + i - 1] = 0;
4481
4482 if (mg_stat(conn, path_buf, &error_page_file.stat)) {
4483 DEBUG_TRACE("Check error page %s - found",
4484 path_buf);
4485 page_handler_found = 1;
4486 break;
4487 }
4488 DEBUG_TRACE("Check error page %s - not found",
4489 path_buf);
4490
4491 /* Continue with the next file extenstion from the
4492 * configuration (if there is a next one). */
4493 tstr = strchr(tstr + i, '.');
4494 }
4495 }
4496 }
4497
4498 if (page_handler_found) {
4499 conn->in_error_handler = 1;
4500 handle_file_based_request(conn, path_buf, &error_page_file);
4501 conn->in_error_handler = 0;
4502 return 0;
4503 }
4504#endif /* NO_FILESYSTEMS */
4505 }
4506
4507 /* No custom error page. Send default error page. */
4508 conn->must_close = 1;
4509 mg_response_header_start(conn, status);
4512 if (has_body) {
4514 "Content-Type",
4515 "text/plain; charset=utf-8",
4516 -1);
4517 }
4519
4520 /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
4521 if (has_body) {
4522 /* For other errors, send a generic error message. */
4523 const char *status_text = mg_get_response_code_text(conn, status);
4524 mg_printf(conn, "Error %d: %s\n", status, status_text);
4525 mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4526
4527 } else {
4528 /* No body allowed. Close the connection. */
4529 DEBUG_TRACE("Error %i", status);
4530 }
4531 }
4532 return 0;
4533}
4534
4535
4536int
4537mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
4538{
4539 va_list ap;
4540 int ret;
4541
4542 va_start(ap, fmt);
4543 ret = mg_send_http_error_impl(conn, status, fmt, ap);
4544 va_end(ap);
4545
4546 return ret;
4547}
4548
4549
4550int
4552 const char *mime_type,
4553 long long content_length)
4554{
4555 if ((mime_type == NULL) || (*mime_type == 0)) {
4556 /* No content type defined: default to text/html */
4557 mime_type = "text/html";
4558 }
4559
4560 mg_response_header_start(conn, 200);
4563 mg_response_header_add(conn, "Content-Type", mime_type, -1);
4564 if (content_length < 0) {
4565 /* Size not known. Use chunked encoding (HTTP/1.x) */
4566 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
4567 /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
4568 mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
4569 }
4570 } else {
4571 char len[32];
4572 int trunc = 0;
4573 mg_snprintf(conn,
4574 &trunc,
4575 len,
4576 sizeof(len),
4577 "%" UINT64_FMT,
4578 (uint64_t)content_length);
4579 if (!trunc) {
4580 /* Since 32 bytes is enough to hold any 64 bit decimal number,
4581 * !trunc is always true */
4582 mg_response_header_add(conn, "Content-Length", len, -1);
4583 }
4584 }
4586
4587 return 0;
4588}
4589
4590
4591int
4593 const char *target_url,
4594 int redirect_code)
4595{
4596 /* Send a 30x redirect response.
4597 *
4598 * Redirect types (status codes):
4599 *
4600 * Status | Perm/Temp | Method | Version
4601 * 301 | permanent | POST->GET undefined | HTTP/1.0
4602 * 302 | temporary | POST->GET undefined | HTTP/1.0
4603 * 303 | temporary | always use GET | HTTP/1.1
4604 * 307 | temporary | always keep method | HTTP/1.1
4605 * 308 | permanent | always keep method | HTTP/1.1
4606 */
4607 const char *redirect_text;
4608 int ret;
4609 size_t content_len = 0;
4610#if defined(MG_SEND_REDIRECT_BODY)
4611 char reply[MG_BUF_LEN];
4612#endif
4613
4614 /* In case redirect_code=0, use 307. */
4615 if (redirect_code == 0) {
4616 redirect_code = 307;
4617 }
4618
4619 /* In case redirect_code is none of the above, return error. */
4620 if ((redirect_code != 301) && (redirect_code != 302)
4621 && (redirect_code != 303) && (redirect_code != 307)
4622 && (redirect_code != 308)) {
4623 /* Parameter error */
4624 return -2;
4625 }
4626
4627 /* Get proper text for response code */
4628 redirect_text = mg_get_response_code_text(conn, redirect_code);
4629
4630 /* If target_url is not defined, redirect to "/". */
4631 if ((target_url == NULL) || (*target_url == 0)) {
4632 target_url = "/";
4633 }
4634
4635#if defined(MG_SEND_REDIRECT_BODY)
4636 /* TODO: condition name? */
4637
4638 /* Prepare a response body with a hyperlink.
4639 *
4640 * According to RFC2616 (and RFC1945 before):
4641 * Unless the request method was HEAD, the entity of the
4642 * response SHOULD contain a short hypertext note with a hyperlink to
4643 * the new URI(s).
4644 *
4645 * However, this response body is not useful in M2M communication.
4646 * Probably the original reason in the RFC was, clients not supporting
4647 * a 30x HTTP redirect could still show the HTML page and let the user
4648 * press the link. Since current browsers support 30x HTTP, the additional
4649 * HTML body does not seem to make sense anymore.
4650 *
4651 * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
4652 * but it only notes:
4653 * The server's response payload usually contains a short
4654 * hypertext note with a hyperlink to the new URI(s).
4655 *
4656 * Deactivated by default. If you need the 30x body, set the define.
4657 */
4659 conn,
4660 NULL /* ignore truncation */,
4661 reply,
4662 sizeof(reply),
4663 "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4664 redirect_text,
4665 target_url,
4666 target_url);
4667 content_len = strlen(reply);
4668#endif
4669
4670 /* Do not send any additional header. For all other options,
4671 * including caching, there are suitable defaults. */
4672 ret = mg_printf(conn,
4673 "HTTP/1.1 %i %s\r\n"
4674 "Location: %s\r\n"
4675 "Content-Length: %u\r\n"
4676 "Connection: %s\r\n\r\n",
4677 redirect_code,
4678 redirect_text,
4679 target_url,
4680 (unsigned int)content_len,
4682
4683#if defined(MG_SEND_REDIRECT_BODY)
4684 /* Send response body */
4685 if (ret > 0) {
4686 /* ... unless it is a HEAD request */
4687 if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
4688 ret = mg_write(conn, reply, content_len);
4689 }
4690 }
4691#endif
4692
4693 return (ret > 0) ? ret : -1;
4694}
4695
4696
4697#if defined(_WIN32)
4698/* Create substitutes for POSIX functions in Win32. */
4699
4700#if defined(GCC_DIAGNOSTIC)
4701/* Show no warning in case system functions are not used. */
4702#pragma GCC diagnostic push
4703#pragma GCC diagnostic ignored "-Wunused-function"
4704#endif
4705
4706
4707static int
4708pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
4709{
4710 (void)unused;
4711 /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
4712 InitializeCriticalSection(&mutex->sec);
4713 return 0;
4714}
4715
4716
4717static int
4718pthread_mutex_destroy(pthread_mutex_t *mutex)
4719{
4720 DeleteCriticalSection(&mutex->sec);
4721 return 0;
4722}
4723
4724
4725static int
4726pthread_mutex_lock(pthread_mutex_t *mutex)
4727{
4728 EnterCriticalSection(&mutex->sec);
4729 return 0;
4730}
4731
4732
4733static int
4734pthread_mutex_unlock(pthread_mutex_t *mutex)
4735{
4736 LeaveCriticalSection(&mutex->sec);
4737 return 0;
4738}
4739
4740
4742static int
4743pthread_cond_init(pthread_cond_t *cv, const void *unused)
4744{
4745 (void)unused;
4746 (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
4747 cv->waiting_thread = NULL;
4748 return 0;
4749}
4750
4751
4753static int
4754pthread_cond_timedwait(pthread_cond_t *cv,
4755 pthread_mutex_t *mutex,
4756 FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
4757{
4758 struct mg_workerTLS **ptls,
4759 *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
4760 int ok;
4761 uint64_t nsnow, nswaitabs;
4762 int64_t nswaitrel;
4763 DWORD mswaitrel;
4764
4765 pthread_mutex_lock(&cv->threadIdSec);
4766 /* Add this thread to cv's waiting list */
4767 ptls = &cv->waiting_thread;
4768 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
4769 ;
4770 tls->next_waiting_thread = NULL;
4771 *ptls = tls;
4772 pthread_mutex_unlock(&cv->threadIdSec);
4773
4774 if (abstime) {
4775 nsnow = mg_get_current_time_ns();
4776 nswaitabs =
4777 (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
4778 nswaitrel = nswaitabs - nsnow;
4779 if (nswaitrel < 0) {
4780 nswaitrel = 0;
4781 }
4782 mswaitrel = (DWORD)(nswaitrel / 1000000);
4783 } else {
4784 mswaitrel = (DWORD)INFINITE;
4785 }
4786
4787 pthread_mutex_unlock(mutex);
4788 ok = (WAIT_OBJECT_0
4789 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
4790 if (!ok) {
4791 ok = 1;
4792 pthread_mutex_lock(&cv->threadIdSec);
4793 ptls = &cv->waiting_thread;
4794 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
4795 if (*ptls == tls) {
4796 *ptls = tls->next_waiting_thread;
4797 ok = 0;
4798 break;
4799 }
4800 }
4801 pthread_mutex_unlock(&cv->threadIdSec);
4802 if (ok) {
4803 WaitForSingleObject(tls->pthread_cond_helper_mutex,
4804 (DWORD)INFINITE);
4805 }
4806 }
4807 /* This thread has been removed from cv's waiting list */
4808 pthread_mutex_lock(mutex);
4809
4810 return ok ? 0 : -1;
4811}
4812
4813
4815static int
4816pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
4817{
4818 return pthread_cond_timedwait(cv, mutex, NULL);
4819}
4820
4821
4823static int
4824pthread_cond_signal(pthread_cond_t *cv)
4825{
4826 HANDLE wkup = NULL;
4827 BOOL ok = FALSE;
4828
4829 pthread_mutex_lock(&cv->threadIdSec);
4830 if (cv->waiting_thread) {
4831 wkup = cv->waiting_thread->pthread_cond_helper_mutex;
4832 cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
4833
4834 ok = SetEvent(wkup);
4835 DEBUG_ASSERT(ok);
4836 }
4837 pthread_mutex_unlock(&cv->threadIdSec);
4838
4839 return ok ? 0 : 1;
4840}
4841
4842
4844static int
4845pthread_cond_broadcast(pthread_cond_t *cv)
4846{
4847 pthread_mutex_lock(&cv->threadIdSec);
4848 while (cv->waiting_thread) {
4849 pthread_cond_signal(cv);
4850 }
4851 pthread_mutex_unlock(&cv->threadIdSec);
4852
4853 return 0;
4854}
4855
4856
4858static int
4859pthread_cond_destroy(pthread_cond_t *cv)
4860{
4861 pthread_mutex_lock(&cv->threadIdSec);
4862 DEBUG_ASSERT(cv->waiting_thread == NULL);
4863 pthread_mutex_unlock(&cv->threadIdSec);
4864 pthread_mutex_destroy(&cv->threadIdSec);
4865
4866 return 0;
4867}
4868
4869
4870#if defined(ALTERNATIVE_QUEUE)
4872static void *
4873event_create(void)
4874{
4875 return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
4876}
4877
4878
4880static int
4881event_wait(void *eventhdl)
4882{
4883 int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
4884 return (res == WAIT_OBJECT_0);
4885}
4886
4887
4889static int
4890event_signal(void *eventhdl)
4891{
4892 return (int)SetEvent((HANDLE)eventhdl);
4893}
4894
4895
4897static void
4898event_destroy(void *eventhdl)
4899{
4900 CloseHandle((HANDLE)eventhdl);
4901}
4902#endif
4903
4904
4905#if defined(GCC_DIAGNOSTIC)
4906/* Enable unused function warning again */
4907#pragma GCC diagnostic pop
4908#endif
4909
4910
4911/* For Windows, change all slashes to backslashes in path names. */
4912static void
4913change_slashes_to_backslashes(char *path)
4914{
4915 int i;
4916
4917 for (i = 0; path[i] != '\0'; i++) {
4918 if (path[i] == '/') {
4919 path[i] = '\\';
4920 }
4921
4922 /* remove double backslash (check i > 0 to preserve UNC paths,
4923 * like \\server\file.txt) */
4924 if ((i > 0) && (path[i] == '\\')) {
4925 while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
4926 (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
4927 }
4928 }
4929 }
4930}
4931
4932
4933static int
4934mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
4935{
4936 int diff;
4937
4938 do {
4939 diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
4940 - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
4941 s1++;
4942 s2++;
4943 } while ((diff == 0) && (s1[-1] != L'\0'));
4944
4945 return diff;
4946}
4947
4948
4949/* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
4950 * wbuf and wbuf_len is a target buffer and its length. */
4951static void
4952path_to_unicode(const struct mg_connection *conn,
4953 const char *path,
4954 wchar_t *wbuf,
4955 size_t wbuf_len)
4956{
4957 char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
4958 wchar_t wbuf2[UTF16_PATH_MAX + 1];
4959 DWORD long_len, err;
4960 int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
4961
4962 mg_strlcpy(buf, path, sizeof(buf));
4963 change_slashes_to_backslashes(buf);
4964
4965 /* Convert to Unicode and back. If doubly-converted string does not
4966 * match the original, something is fishy, reject. */
4967 memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
4968 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
4969 WideCharToMultiByte(
4970 CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
4971 if (strcmp(buf, buf2) != 0) {
4972 wbuf[0] = L'\0';
4973 }
4974
4975 /* Windows file systems are not case sensitive, but you can still use
4976 * uppercase and lowercase letters (on all modern file systems).
4977 * The server can check if the URI uses the same upper/lowercase
4978 * letters an the file system, effectively making Windows servers
4979 * case sensitive (like Linux servers are). It is still not possible
4980 * to use two files with the same name in different cases on Windows
4981 * (like /a and /A) - this would be possible in Linux.
4982 * As a default, Windows is not case sensitive, but the case sensitive
4983 * file name check can be activated by an additional configuration. */
4984 if (conn) {
4985 if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
4986 && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
4987 "yes")) {
4988 /* Use case sensitive compare function */
4989 fcompare = wcscmp;
4990 }
4991 }
4992 (void)conn; /* conn is currently unused */
4993
4994 /* Only accept a full file path, not a Windows short (8.3) path. */
4995 memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
4996 long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
4997 if (long_len == 0) {
4998 err = GetLastError();
4999 if (err == ERROR_FILE_NOT_FOUND) {
5000 /* File does not exist. This is not always a problem here. */
5001 return;
5002 }
5003 }
5004 if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5005 /* Short name is used. */
5006 wbuf[0] = L'\0';
5007 }
5008}
5009
5010
5011#if !defined(NO_FILESYSTEMS)
5012/* Get file information, return 1 if file exists, 0 if not */
5013static int
5014mg_stat(const struct mg_connection *conn,
5015 const char *path,
5016 struct mg_file_stat *filep)
5017{
5018 wchar_t wbuf[UTF16_PATH_MAX];
5019 WIN32_FILE_ATTRIBUTE_DATA info;
5020 time_t creation_time;
5021 size_t len;
5022
5023 if (!filep) {
5024 return 0;
5025 }
5026 memset(filep, 0, sizeof(*filep));
5027
5028 if (mg_path_suspicious(conn, path)) {
5029 return 0;
5030 }
5031
5032 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5033 /* Windows happily opens files with some garbage at the end of file name.
5034 * For example, fopen("a.cgi ", "r") on Windows successfully opens
5035 * "a.cgi", despite one would expect an error back. */
5036 len = strlen(path);
5037 if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
5038 && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
5039 filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5040 filep->last_modified =
5041 SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5042 info.ftLastWriteTime.dwHighDateTime);
5043
5044 /* On Windows, the file creation time can be higher than the
5045 * modification time, e.g. when a file is copied.
5046 * Since the Last-Modified timestamp is used for caching
5047 * it should be based on the most recent timestamp. */
5048 creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5049 info.ftCreationTime.dwHighDateTime);
5050 if (creation_time > filep->last_modified) {
5051 filep->last_modified = creation_time;
5052 }
5053
5054 filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5055 return 1;
5056 }
5057
5058 return 0;
5059}
5060#endif
5061
5062
5063static int
5064mg_remove(const struct mg_connection *conn, const char *path)
5065{
5066 wchar_t wbuf[UTF16_PATH_MAX];
5067 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5068 return DeleteFileW(wbuf) ? 0 : -1;
5069}
5070
5071
5072static int
5073mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
5074{
5075 wchar_t wbuf[UTF16_PATH_MAX];
5076 (void)mode;
5077 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5078 return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5079}
5080
5081
5082/* Create substitutes for POSIX functions in Win32. */
5083
5084#if defined(GCC_DIAGNOSTIC)
5085/* Show no warning in case system functions are not used. */
5086#pragma GCC diagnostic push
5087#pragma GCC diagnostic ignored "-Wunused-function"
5088#endif
5089
5090
5091/* Implementation of POSIX opendir/closedir/readdir for Windows. */
5093static DIR *
5094mg_opendir(const struct mg_connection *conn, const char *name)
5095{
5096 DIR *dir = NULL;
5097 wchar_t wpath[UTF16_PATH_MAX];
5098 DWORD attrs;
5099
5100 if (name == NULL) {
5101 SetLastError(ERROR_BAD_ARGUMENTS);
5102 } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
5103 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5104 } else {
5105 path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
5106 attrs = GetFileAttributesW(wpath);
5107 if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5108 && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5109 (void)wcscat(wpath, L"\\*");
5110 dir->handle = FindFirstFileW(wpath, &dir->info);
5111 dir->result.d_name[0] = '\0';
5112 } else {
5113 mg_free(dir);
5114 dir = NULL;
5115 }
5116 }
5117
5118 return dir;
5119}
5120
5121
5123static int
5124mg_closedir(DIR *dir)
5125{
5126 int result = 0;
5127
5128 if (dir != NULL) {
5129 if (dir->handle != INVALID_HANDLE_VALUE)
5130 result = FindClose(dir->handle) ? 0 : -1;
5131
5132 mg_free(dir);
5133 } else {
5134 result = -1;
5135 SetLastError(ERROR_BAD_ARGUMENTS);
5136 }
5137
5138 return result;
5139}
5140
5141
5143static struct dirent *
5144mg_readdir(DIR *dir)
5145{
5146 struct dirent *result = 0;
5147
5148 if (dir) {
5149 if (dir->handle != INVALID_HANDLE_VALUE) {
5150 result = &dir->result;
5151 (void)WideCharToMultiByte(CP_UTF8,
5152 0,
5153 dir->info.cFileName,
5154 -1,
5155 result->d_name,
5156 sizeof(result->d_name),
5157 NULL,
5158 NULL);
5159
5160 if (!FindNextFileW(dir->handle, &dir->info)) {
5161 (void)FindClose(dir->handle);
5162 dir->handle = INVALID_HANDLE_VALUE;
5163 }
5164
5165 } else {
5166 SetLastError(ERROR_FILE_NOT_FOUND);
5167 }
5168 } else {
5169 SetLastError(ERROR_BAD_ARGUMENTS);
5170 }
5171
5172 return result;
5173}
5174
5175
5176#if !defined(HAVE_POLL)
5177#undef POLLIN
5178#undef POLLPRI
5179#undef POLLOUT
5180#undef POLLERR
5181#define POLLIN (1) /* Data ready - read will not block. */
5182#define POLLPRI (2) /* Priority data ready. */
5183#define POLLOUT (4) /* Send queue not full - write will not block. */
5184#define POLLERR (8) /* Error event */
5185
5187static int
5188poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
5189{
5190 struct timeval tv;
5191 fd_set rset;
5192 fd_set wset;
5193 fd_set eset;
5194 unsigned int i;
5195 int result;
5196 SOCKET maxfd = 0;
5197
5198 memset(&tv, 0, sizeof(tv));
5199 tv.tv_sec = milliseconds / 1000;
5200 tv.tv_usec = (milliseconds % 1000) * 1000;
5201 FD_ZERO(&rset);
5202 FD_ZERO(&wset);
5203 FD_ZERO(&eset);
5204
5205 for (i = 0; i < n; i++) {
5206 if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
5207 if (pfd[i].events & POLLIN) {
5208 FD_SET(pfd[i].fd, &rset);
5209 }
5210 if (pfd[i].events & POLLOUT) {
5211 FD_SET(pfd[i].fd, &wset);
5212 }
5213 /* Check for errors for any FD in the set */
5214 FD_SET(pfd[i].fd, &eset);
5215 }
5216 pfd[i].revents = 0;
5217
5218 if (pfd[i].fd > maxfd) {
5219 maxfd = pfd[i].fd;
5220 }
5221 }
5222
5223 if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
5224 for (i = 0; i < n; i++) {
5225 if (FD_ISSET(pfd[i].fd, &rset)) {
5226 pfd[i].revents |= POLLIN;
5227 }
5228 if (FD_ISSET(pfd[i].fd, &wset)) {
5229 pfd[i].revents |= POLLOUT;
5230 }
5231 if (FD_ISSET(pfd[i].fd, &eset)) {
5232 pfd[i].revents |= POLLERR;
5233 }
5234 }
5235 }
5236
5237 /* We should subtract the time used in select from remaining
5238 * "milliseconds", in particular if called from mg_poll with a
5239 * timeout quantum.
5240 * Unfortunately, the remaining time is not stored in "tv" in all
5241 * implementations, so the result in "tv" must be considered undefined.
5242 * See http://man7.org/linux/man-pages/man2/select.2.html */
5243
5244 return result;
5245}
5246#endif /* HAVE_POLL */
5247
5248
5249#if defined(GCC_DIAGNOSTIC)
5250/* Enable unused function warning again */
5251#pragma GCC diagnostic pop
5252#endif
5253
5254
5255static void
5257 const struct mg_connection *conn /* may be null */,
5258 struct mg_context *ctx /* may be null */)
5259{
5260 (void)conn; /* Unused. */
5261 (void)ctx;
5262
5263 (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5264}
5265
5266
5267int
5269{
5270#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5271 /* Compile-time option to control stack size, e.g.
5272 * -DUSE_STACK_SIZE=16384
5273 */
5274 return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
5275 == ((uintptr_t)(-1L)))
5276 ? -1
5277 : 0);
5278#else
5279 return (
5280 (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
5281 ? -1
5282 : 0);
5283#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5284}
5285
5286
5287/* Start a thread storing the thread context. */
5288static int
5289mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
5290 void *p,
5291 pthread_t *threadidptr)
5292{
5293 uintptr_t uip;
5294 HANDLE threadhandle;
5295 int result = -1;
5296
5297 uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
5298 threadhandle = (HANDLE)uip;
5299 if ((uip != 0) && (threadidptr != NULL)) {
5300 *threadidptr = threadhandle;
5301 result = 0;
5302 }
5303
5304 return result;
5305}
5306
5307
5308/* Wait for a thread to finish. */
5309static int
5310mg_join_thread(pthread_t threadid)
5311{
5312 int result;
5313 DWORD dwevent;
5314
5315 result = -1;
5316 dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5317 if (dwevent == WAIT_FAILED) {
5318 DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
5319 } else {
5320 if (dwevent == WAIT_OBJECT_0) {
5321 CloseHandle(threadid);
5322 result = 0;
5323 }
5324 }
5325
5326 return result;
5327}
5328
5329#if !defined(NO_SSL_DL) && !defined(NO_SSL)
5330/* If SSL is loaded dynamically, dlopen/dlclose is required. */
5331/* Create substitutes for POSIX functions in Win32. */
5332
5333#if defined(GCC_DIAGNOSTIC)
5334/* Show no warning in case system functions are not used. */
5335#pragma GCC diagnostic push
5336#pragma GCC diagnostic ignored "-Wunused-function"
5337#endif
5338
5339
5341static HANDLE
5342dlopen(const char *dll_name, int flags)
5343{
5344 wchar_t wbuf[UTF16_PATH_MAX];
5345 (void)flags;
5346 path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
5347 return LoadLibraryW(wbuf);
5348}
5349
5350
5352static int
5353dlclose(void *handle)
5354{
5355 int result;
5356
5357 if (FreeLibrary((HMODULE)handle) != 0) {
5358 result = 0;
5359 } else {
5360 result = -1;
5361 }
5362
5363 return result;
5364}
5365
5366
5367#if defined(GCC_DIAGNOSTIC)
5368/* Enable unused function warning again */
5369#pragma GCC diagnostic pop
5370#endif
5371
5372#endif
5373
5374
5375#if !defined(NO_CGI)
5376#define SIGKILL (0)
5377
5378
5379static int
5380kill(pid_t pid, int sig_num)
5381{
5382 (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5383 (void)CloseHandle((HANDLE)pid);
5384 return 0;
5385}
5386
5387
5388#if !defined(WNOHANG)
5389#define WNOHANG (1)
5390#endif
5391
5392
5393static pid_t
5394waitpid(pid_t pid, int *status, int flags)
5395{
5396 DWORD timeout = INFINITE;
5397 DWORD waitres;
5398
5399 (void)status; /* Currently not used by any client here */
5400
5401 if ((flags | WNOHANG) == WNOHANG) {
5402 timeout = 0;
5403 }
5404
5405 waitres = WaitForSingleObject((HANDLE)pid, timeout);
5406 if (waitres == WAIT_OBJECT_0) {
5407 return pid;
5408 }
5409 if (waitres == WAIT_TIMEOUT) {
5410 return 0;
5411 }
5412 return (pid_t)-1;
5413}
5414
5415
5416static void
5417trim_trailing_whitespaces(char *s)
5418{
5419 char *e = s + strlen(s);
5420 while ((e > s) && isspace((unsigned char)e[-1])) {
5421 *(--e) = '\0';
5422 }
5423}
5424
5425
5426static pid_t
5427spawn_process(struct mg_connection *conn,
5428 const char *prog,
5429 char *envblk,
5430 char *envp[],
5431 int fdin[2],
5432 int fdout[2],
5433 int fderr[2],
5434 const char *dir,
5435 unsigned char cgi_config_idx)
5436{
5437 HANDLE me;
5438 char *interp;
5439 char *interp_arg = 0;
5440 char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
5441 int truncated;
5442 struct mg_file file = STRUCT_FILE_INITIALIZER;
5443 STARTUPINFOA si;
5444 PROCESS_INFORMATION pi = {0};
5445
5446 (void)envp;
5447
5448 memset(&si, 0, sizeof(si));
5449 si.cb = sizeof(si);
5450
5451 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5452 si.wShowWindow = SW_HIDE;
5453
5454 me = GetCurrentProcess();
5455 DuplicateHandle(me,
5456 (HANDLE)_get_osfhandle(fdin[0]),
5457 me,
5458 &si.hStdInput,
5459 0,
5460 TRUE,
5461 DUPLICATE_SAME_ACCESS);
5462 DuplicateHandle(me,
5463 (HANDLE)_get_osfhandle(fdout[1]),
5464 me,
5465 &si.hStdOutput,
5466 0,
5467 TRUE,
5468 DUPLICATE_SAME_ACCESS);
5469 DuplicateHandle(me,
5470 (HANDLE)_get_osfhandle(fderr[1]),
5471 me,
5472 &si.hStdError,
5473 0,
5474 TRUE,
5475 DUPLICATE_SAME_ACCESS);
5476
5477 /* Mark handles that should not be inherited. See
5478 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
5479 */
5480 SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5481 HANDLE_FLAG_INHERIT,
5482 0);
5483 SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5484 HANDLE_FLAG_INHERIT,
5485 0);
5486 SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5487 HANDLE_FLAG_INHERIT,
5488 0);
5489
5490 /* First check, if there is a CGI interpreter configured for all CGI
5491 * scripts. */
5492 interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
5493 if (interp != NULL) {
5494 /* If there is a configured interpreter, check for additional arguments
5495 */
5496 interp_arg =
5497 conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
5498 } else {
5499 /* Otherwise, the interpreter must be stated in the first line of the
5500 * CGI script file, after a #! (shebang) mark. */
5501 buf[0] = buf[1] = '\0';
5502
5503 /* Get the full script path */
5505 conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
5506
5507 if (truncated) {
5508 pi.hProcess = (pid_t)-1;
5509 goto spawn_cleanup;
5510 }
5511
5512 /* Open the script file, to read the first line */
5513 if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
5514
5515 /* Read the first line of the script into the buffer */
5516 mg_fgets(buf, sizeof(buf), &file);
5517 (void)mg_fclose(&file.access); /* ignore error on read only file */
5518 buf[sizeof(buf) - 1] = '\0';
5519 }
5520
5521 if ((buf[0] == '#') && (buf[1] == '!')) {
5522 trim_trailing_whitespaces(buf + 2);
5523 } else {
5524 buf[2] = '\0';
5525 }
5526 interp = buf + 2;
5527 }
5528
5529 GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
5530
5531 if (interp[0] != '\0') {
5532 /* This is an interpreted script file. We must call the interpreter. */
5533 if ((interp_arg != 0) && (interp_arg[0] != 0)) {
5534 mg_snprintf(conn,
5535 &truncated,
5536 cmdline,
5537 sizeof(cmdline),
5538 "\"%s\" %s \"%s\\%s\"",
5539 interp,
5540 interp_arg,
5541 full_dir,
5542 prog);
5543 } else {
5544 mg_snprintf(conn,
5545 &truncated,
5546 cmdline,
5547 sizeof(cmdline),
5548 "\"%s\" \"%s\\%s\"",
5549 interp,
5550 full_dir,
5551 prog);
5552 }
5553 } else {
5554 /* This is (probably) a compiled program. We call it directly. */
5555 mg_snprintf(conn,
5556 &truncated,
5557 cmdline,
5558 sizeof(cmdline),
5559 "\"%s\\%s\"",
5560 full_dir,
5561 prog);
5562 }
5563
5564 if (truncated) {
5565 pi.hProcess = (pid_t)-1;
5566 goto spawn_cleanup;
5567 }
5568
5569 DEBUG_TRACE("Running [%s]", cmdline);
5570 if (CreateProcessA(NULL,
5571 cmdline,
5572 NULL,
5573 NULL,
5574 TRUE,
5575 CREATE_NEW_PROCESS_GROUP,
5576 envblk,
5577 NULL,
5578 &si,
5579 &pi)
5580 == 0) {
5582 conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
5583 pi.hProcess = (pid_t)-1;
5584 /* goto spawn_cleanup; */
5585 }
5586
5587spawn_cleanup:
5588 (void)CloseHandle(si.hStdOutput);
5589 (void)CloseHandle(si.hStdError);
5590 (void)CloseHandle(si.hStdInput);
5591 if (pi.hThread != NULL) {
5592 (void)CloseHandle(pi.hThread);
5593 }
5594
5595 return (pid_t)pi.hProcess;
5596}
5597#endif /* !NO_CGI */
5598
5599
5600static int
5602{
5603 unsigned long non_blocking = 0;
5604 return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5605}
5606
5607
5608static int
5610{
5611 unsigned long non_blocking = 1;
5612 return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5613}
5614
5615
5616#else
5617
5618
5619#if !defined(NO_FILESYSTEMS)
5620static int
5621mg_stat(const struct mg_connection *conn,
5622 const char *path,
5623 struct mg_file_stat *filep)
5624{
5625 struct stat st;
5626 if (!filep) {
5627 return 0;
5628 }
5629 memset(filep, 0, sizeof(*filep));
5630
5631 if (mg_path_suspicious(conn, path)) {
5632 return 0;
5633 }
5634
5635 if (0 == stat(path, &st)) {
5636 filep->size = (uint64_t)(st.st_size);
5637 filep->last_modified = st.st_mtime;
5638 filep->is_directory = S_ISDIR(st.st_mode);
5639 return 1;
5640 }
5641
5642 return 0;
5643}
5644#endif /* NO_FILESYSTEMS */
5645
5646
5647static void
5649 const struct mg_connection *conn /* may be null */,
5650 struct mg_context *ctx /* may be null */)
5651{
5652#if defined(__ZEPHYR__)
5653 (void)fd;
5654 (void)conn;
5655 (void)ctx;
5656#else
5657 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5658 if (conn || ctx) {
5659 struct mg_connection fc;
5660 mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
5661 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5662 __func__,
5663 strerror(ERRNO));
5664 }
5665 }
5666#endif
5667}
5668
5669
5670int
5672{
5673 pthread_t thread_id;
5674 pthread_attr_t attr;
5675 int result;
5676
5677 (void)pthread_attr_init(&attr);
5678 (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
5679
5680#if defined(__ZEPHYR__)
5681 pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
5682#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5683 /* Compile-time option to control stack size,
5684 * e.g. -DUSE_STACK_SIZE=16384 */
5685 (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5686#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5687
5688 result = pthread_create(&thread_id, &attr, func, param);
5689 pthread_attr_destroy(&attr);
5690
5691 return result;
5692}
5693
5694
5695/* Start a thread storing the thread context. */
5696static int
5698 void *param,
5699 pthread_t *threadidptr)
5700{
5701 pthread_t thread_id;
5702 pthread_attr_t attr;
5703 int result;
5704
5705 (void)pthread_attr_init(&attr);
5706
5707#if defined(__ZEPHYR__)
5708 pthread_attr_setstack(&attr,
5709 &civetweb_worker_stacks[zephyr_worker_stack_index++],
5710 ZEPHYR_STACK_SIZE);
5711#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5712 /* Compile-time option to control stack size,
5713 * e.g. -DUSE_STACK_SIZE=16384 */
5714 (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5715#endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
5716
5717 result = pthread_create(&thread_id, &attr, func, param);
5718 pthread_attr_destroy(&attr);
5719 if ((result == 0) && (threadidptr != NULL)) {
5720 *threadidptr = thread_id;
5721 }
5722 return result;
5723}
5724
5725
5726/* Wait for a thread to finish. */
5727static int
5728mg_join_thread(pthread_t threadid)
5729{
5730 int result;
5731
5732 result = pthread_join(threadid, NULL);
5733 return result;
5734}
5735
5736
5737#if !defined(NO_CGI)
5738static pid_t
5740 const char *prog,
5741 char *envblk,
5742 char *envp[],
5743 int fdin[2],
5744 int fdout[2],
5745 int fderr[2],
5746 const char *dir,
5747 unsigned char cgi_config_idx)
5748{
5749 pid_t pid;
5750 const char *interp;
5751
5752 (void)envblk;
5753
5754 if ((pid = fork()) == -1) {
5755 /* Parent */
5756 mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
5757 } else if (pid != 0) {
5758 /* Make sure children close parent-side descriptors.
5759 * The caller will close the child-side immediately. */
5760 set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
5761 set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
5762 set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
5763 } else {
5764 /* Child */
5765 if (chdir(dir) != 0) {
5767 conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
5768 } else if (dup2(fdin[0], 0) == -1) {
5769 mg_cry_internal(conn,
5770 "%s: dup2(%d, 0): %s",
5771 __func__,
5772 fdin[0],
5773 strerror(ERRNO));
5774 } else if (dup2(fdout[1], 1) == -1) {
5775 mg_cry_internal(conn,
5776 "%s: dup2(%d, 1): %s",
5777 __func__,
5778 fdout[1],
5779 strerror(ERRNO));
5780 } else if (dup2(fderr[1], 2) == -1) {
5781 mg_cry_internal(conn,
5782 "%s: dup2(%d, 2): %s",
5783 __func__,
5784 fderr[1],
5785 strerror(ERRNO));
5786 } else {
5787 struct sigaction sa;
5788
5789 /* Keep stderr and stdout in two different pipes.
5790 * Stdout will be sent back to the client,
5791 * stderr should go into a server error log. */
5792 (void)close(fdin[0]);
5793 (void)close(fdout[1]);
5794 (void)close(fderr[1]);
5795
5796 /* Close write end fdin and read end fdout and fderr */
5797 (void)close(fdin[1]);
5798 (void)close(fdout[0]);
5799 (void)close(fderr[0]);
5800
5801 /* After exec, all signal handlers are restored to their default
5802 * values, with one exception of SIGCHLD. According to
5803 * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
5804 * will leave unchanged after exec if it was set to be ignored.
5805 * Restore it to default action. */
5806 memset(&sa, 0, sizeof(sa));
5807 sa.sa_handler = SIG_DFL;
5808 sigaction(SIGCHLD, &sa, NULL);
5809
5810 interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
5811 if (interp == NULL) {
5812 /* no interpreter configured, call the programm directly */
5813 (void)execle(prog, prog, NULL, envp);
5814 mg_cry_internal(conn,
5815 "%s: execle(%s): %s",
5816 __func__,
5817 prog,
5818 strerror(ERRNO));
5819 } else {
5820 /* call the configured interpreter */
5821 const char *interp_args =
5822 conn->dom_ctx
5823 ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
5824
5825 if ((interp_args != NULL) && (interp_args[0] != 0)) {
5826 (void)execle(interp, interp, interp_args, prog, NULL, envp);
5827 } else {
5828 (void)execle(interp, interp, prog, NULL, envp);
5829 }
5830 mg_cry_internal(conn,
5831 "%s: execle(%s %s): %s",
5832 __func__,
5833 interp,
5834 prog,
5835 strerror(ERRNO));
5836 }
5837 }
5838 exit(EXIT_FAILURE);
5839 }
5840
5841 return pid;
5842}
5843#endif /* !NO_CGI */
5844
5845
5846static int
5848{
5849 int flags = fcntl(sock, F_GETFL, 0);
5850 if (flags < 0) {
5851 return -1;
5852 }
5853
5854 if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
5855 return -1;
5856 }
5857 return 0;
5858}
5859
5860static int
5862{
5863 int flags = fcntl(sock, F_GETFL, 0);
5864 if (flags < 0) {
5865 return -1;
5866 }
5867
5868 if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
5869 return -1;
5870 }
5871 return 0;
5872}
5873#endif /* _WIN32 / else */
5874
5875/* End of initial operating system specific define block. */
5876
5877
5878/* Get a random number (independent of C rand function) */
5879static uint64_t
5881{
5882 static uint64_t lfsr = 0; /* Linear feedback shift register */
5883 static uint64_t lcg = 0; /* Linear congruential generator */
5884 uint64_t now = mg_get_current_time_ns();
5885
5886 if (lfsr == 0) {
5887 /* lfsr will be only 0 if has not been initialized,
5888 * so this code is called only once. */
5889 lfsr = mg_get_current_time_ns();
5890 lcg = mg_get_current_time_ns();
5891 } else {
5892 /* Get the next step of both random number generators. */
5893 lfsr = (lfsr >> 1)
5894 | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
5895 << 63);
5896 lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
5897 }
5898
5899 /* Combining two pseudo-random number generators and a high resolution
5900 * part
5901 * of the current server time will make it hard (impossible?) to guess
5902 * the
5903 * next number. */
5904 return (lfsr ^ lcg ^ now);
5905}
5906
5907
5908static int
5909mg_poll(struct mg_pollfd *pfd,
5910 unsigned int n,
5911 int milliseconds,
5912 const stop_flag_t *stop_flag)
5913{
5914 /* Call poll, but only for a maximum time of a few seconds.
5915 * This will allow to stop the server after some seconds, instead
5916 * of having to wait for a long socket timeout. */
5917 int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
5918
5919 int check_pollerr = 0;
5920 if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
5921 /* If we wait for only one file descriptor, wait on error as well */
5922 pfd[0].events |= POLLERR;
5923 check_pollerr = 1;
5924 }
5925
5926 do {
5927 int result;
5928
5929 if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
5930 /* Shut down signal */
5931 return -2;
5932 }
5933
5934 if ((milliseconds >= 0) && (milliseconds < ms_now)) {
5935 ms_now = milliseconds;
5936 }
5937
5938 result = poll(pfd, n, ms_now);
5939 if (result != 0) {
5940 /* Poll returned either success (1) or error (-1).
5941 * Forward both to the caller. */
5942 if ((check_pollerr)
5943 && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
5944 == POLLERR)) {
5945 /* One and only file descriptor returned error */
5946 return -1;
5947 }
5948 return result;
5949 }
5950
5951 /* Poll returned timeout (0). */
5952 if (milliseconds > 0) {
5953 milliseconds -= ms_now;
5954 }
5955
5956 } while (milliseconds > 0);
5957
5958 /* timeout: return 0 */
5959 return 0;
5960}
5961
5962
5963/* Write data to the IO channel - opened file descriptor, socket or SSL
5964 * descriptor.
5965 * Return value:
5966 * >=0 .. number of bytes successfully written
5967 * -1 .. timeout
5968 * -2 .. error
5969 */
5970static int
5972 FILE *fp,
5973 SOCKET sock,
5974 SSL *ssl,
5975 const char *buf,
5976 int len,
5977 double timeout)
5978{
5979 uint64_t start = 0, now = 0, timeout_ns = 0;
5980 int n, err;
5981 unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
5982
5983#if defined(_WIN32)
5984 typedef int len_t;
5985#else
5986 typedef size_t len_t;
5987#endif
5988
5989 if (timeout > 0) {
5990 now = mg_get_current_time_ns();
5991 start = now;
5992 timeout_ns = (uint64_t)(timeout * 1.0E9);
5993 }
5994
5995 if (ctx == NULL) {
5996 return -2;
5997 }
5998
5999#if defined(NO_SSL) && !defined(USE_MBEDTLS)
6000 if (ssl) {
6001 return -2;
6002 }
6003#endif
6004
6005 /* Try to read until it succeeds, fails, times out, or the server
6006 * shuts down. */
6007 for (;;) {
6008
6009#if defined(USE_MBEDTLS)
6010 if (ssl != NULL) {
6011 n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
6012 if (n <= 0) {
6013 if ((n == MBEDTLS_ERR_SSL_WANT_READ)
6014 || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
6015 || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6016 n = 0;
6017 } else {
6018 fprintf(stderr, "SSL write failed, error %d\n", n);
6019 return -2;
6020 }
6021 } else {
6022 err = 0;
6023 }
6024 } else
6025#elif !defined(NO_SSL)
6026 if (ssl != NULL) {
6027 ERR_clear_error();
6028 n = SSL_write(ssl, buf, len);
6029 if (n <= 0) {
6030 err = SSL_get_error(ssl, n);
6031 if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
6032 err = ERRNO;
6033 } else if ((err == SSL_ERROR_WANT_READ)
6034 || (err == SSL_ERROR_WANT_WRITE)) {
6035 n = 0;
6036 } else {
6037 DEBUG_TRACE("SSL_write() failed, error %d", err);
6038 ERR_clear_error();
6039 return -2;
6040 }
6041 ERR_clear_error();
6042 } else {
6043 err = 0;
6044 }
6045 } else
6046#endif
6047
6048 if (fp != NULL) {
6049 n = (int)fwrite(buf, 1, (size_t)len, fp);
6050 if (ferror(fp)) {
6051 n = -1;
6052 err = ERRNO;
6053 } else {
6054 err = 0;
6055 }
6056 } else {
6057 n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
6058 err = (n < 0) ? ERRNO : 0;
6059#if defined(_WIN32)
6060 if (err == WSAEWOULDBLOCK) {
6061 err = 0;
6062 n = 0;
6063 }
6064#else
6065 if (ERROR_TRY_AGAIN(err)) {
6066 err = 0;
6067 n = 0;
6068 }
6069#endif
6070 if (n < 0) {
6071 /* shutdown of the socket at client side */
6072 return -2;
6073 }
6074 }
6075
6076 if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6077 return -2;
6078 }
6079
6080 if ((n > 0) || ((n == 0) && (len == 0))) {
6081 /* some data has been read, or no data was requested */
6082 return n;
6083 }
6084 if (n < 0) {
6085 /* socket error - check errno */
6086 DEBUG_TRACE("send() failed, error %d", err);
6087
6088 /* TODO (mid): error handling depending on the error code.
6089 * These codes are different between Windows and Linux.
6090 * Currently there is no problem with failing send calls,
6091 * if there is a reproducible situation, it should be
6092 * investigated in detail.
6093 */
6094 return -2;
6095 }
6096
6097 /* Only in case n=0 (timeout), repeat calling the write function */
6098
6099 /* If send failed, wait before retry */
6100 if (fp != NULL) {
6101 /* For files, just wait a fixed time.
6102 * Maybe it helps, maybe not. */
6103 mg_sleep(5);
6104 } else {
6105 /* For sockets, wait for the socket using poll */
6106 struct mg_pollfd pfd[1];
6107 int pollres;
6108
6109 pfd[0].fd = sock;
6110 pfd[0].events = POLLOUT;
6111 pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
6112 if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6113 return -2;
6114 }
6115 if (pollres > 0) {
6116 continue;
6117 }
6118 }
6119
6120 if (timeout > 0) {
6121 now = mg_get_current_time_ns();
6122 if ((now - start) > timeout_ns) {
6123 /* Timeout */
6124 break;
6125 }
6126 }
6127 }
6128
6129 (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
6130 used */
6131
6132 return -1;
6133}
6134
6135
6136static int
6138 FILE *fp,
6139 SOCKET sock,
6140 SSL *ssl,
6141 const char *buf,
6142 int len)
6143{
6144 double timeout = -1.0;
6145 int n, nwritten = 0;
6146
6147 if (ctx == NULL) {
6148 return -1;
6149 }
6150
6151 if (ctx->dd.config[REQUEST_TIMEOUT]) {
6152 timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
6153 }
6154 if (timeout <= 0.0) {
6155 timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
6156 / 1000.0;
6157 }
6158
6159 while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6160 n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
6161 if (n < 0) {
6162 if (nwritten == 0) {
6163 nwritten = -1; /* Propagate the error */
6164 }
6165 break;
6166 } else if (n == 0) {
6167 break; /* No more data to write */
6168 } else {
6169 nwritten += n;
6170 len -= n;
6171 }
6172 }
6173
6174 return nwritten;
6175}
6176
6177
6178/* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
6179 * Return value:
6180 * >=0 .. number of bytes successfully read
6181 * -1 .. timeout
6182 * -2 .. error
6183 */
6184static int
6185pull_inner(FILE *fp,
6186 struct mg_connection *conn,
6187 char *buf,
6188 int len,
6189 double timeout)
6190{
6191 int nread, err = 0;
6192
6193#if defined(_WIN32)
6194 typedef int len_t;
6195#else
6196 typedef size_t len_t;
6197#endif
6198
6199 /* We need an additional wait loop around this, because in some cases
6200 * with TLSwe may get data from the socket but not from SSL_read.
6201 * In this case we need to repeat at least once.
6202 */
6203
6204 if (fp != NULL) {
6205 /* Use read() instead of fread(), because if we're reading from the
6206 * CGI pipe, fread() may block until IO buffer is filled up. We
6207 * cannot afford to block and must pass all read bytes immediately
6208 * to the client. */
6209 nread = (int)read(fileno(fp), buf, (size_t)len);
6210
6211 err = (nread < 0) ? ERRNO : 0;
6212 if ((nread == 0) && (len > 0)) {
6213 /* Should get data, but got EOL */
6214 return -2;
6215 }
6216
6217#if defined(USE_MBEDTLS)
6218 } else if (conn->ssl != NULL) {
6219 struct mg_pollfd pfd[1];
6220 int to_read;
6221 int pollres;
6222
6223 to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
6224
6225 if (to_read > 0) {
6226 /* We already know there is no more data buffered in conn->buf
6227 * but there is more available in the SSL layer. So don't poll
6228 * conn->client.sock yet. */
6229
6230 pollres = 1;
6231 if (to_read > len)
6232 to_read = len;
6233 } else {
6234 pfd[0].fd = conn->client.sock;
6235 pfd[0].events = POLLIN;
6236
6237 to_read = len;
6238
6239 pollres = mg_poll(pfd,
6240 1,
6241 (int)(timeout * 1000.0),
6242 &(conn->phys_ctx->stop_flag));
6243
6244 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6245 return -2;
6246 }
6247 }
6248
6249 if (pollres > 0) {
6250 nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
6251 if (nread <= 0) {
6252 if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
6253 || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
6254 || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6255 nread = 0;
6256 } else {
6257 fprintf(stderr, "SSL read failed, error %d\n", nread);
6258 return -2;
6259 }
6260 } else {
6261 err = 0;
6262 }
6263
6264 } else if (pollres < 0) {
6265 /* Error */
6266 return -2;
6267 } else {
6268 /* pollres = 0 means timeout */
6269 nread = 0;
6270 }
6271
6272#elif !defined(NO_SSL)
6273 } else if (conn->ssl != NULL) {
6274 int ssl_pending;
6275 struct mg_pollfd pfd[1];
6276 int pollres;
6277
6278 if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
6279 /* We already know there is no more data buffered in conn->buf
6280 * but there is more available in the SSL layer. So don't poll
6281 * conn->client.sock yet. */
6282 if (ssl_pending > len) {
6283 ssl_pending = len;
6284 }
6285 pollres = 1;
6286 } else {
6287 pfd[0].fd = conn->client.sock;
6288 pfd[0].events = POLLIN;
6289 pollres = mg_poll(pfd,
6290 1,
6291 (int)(timeout * 1000.0),
6292 &(conn->phys_ctx->stop_flag));
6293 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6294 return -2;
6295 }
6296 }
6297 if (pollres > 0) {
6298 ERR_clear_error();
6299 nread =
6300 SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
6301 if (nread <= 0) {
6302 err = SSL_get_error(conn->ssl, nread);
6303 if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
6304 err = ERRNO;
6305 } else if ((err == SSL_ERROR_WANT_READ)
6306 || (err == SSL_ERROR_WANT_WRITE)) {
6307 nread = 0;
6308 } else {
6309 /* All errors should return -2 */
6310 DEBUG_TRACE("SSL_read() failed, error %d", err);
6311 ERR_clear_error();
6312 return -2;
6313 }
6314 ERR_clear_error();
6315 } else {
6316 err = 0;
6317 }
6318 } else if (pollres < 0) {
6319 /* Error */
6320 return -2;
6321 } else {
6322 /* pollres = 0 means timeout */
6323 nread = 0;
6324 }
6325#endif
6326
6327 } else {
6328 struct mg_pollfd pfd[1];
6329 int pollres;
6330
6331 pfd[0].fd = conn->client.sock;
6332 pfd[0].events = POLLIN;
6333 pollres = mg_poll(pfd,
6334 1,
6335 (int)(timeout * 1000.0),
6336 &(conn->phys_ctx->stop_flag));
6337 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6338 return -2;
6339 }
6340 if (pollres > 0) {
6341 nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
6342 err = (nread < 0) ? ERRNO : 0;
6343 if (nread <= 0) {
6344 /* shutdown of the socket at client side */
6345 return -2;
6346 }
6347 } else if (pollres < 0) {
6348 /* error callint poll */
6349 return -2;
6350 } else {
6351 /* pollres = 0 means timeout */
6352 nread = 0;
6353 }
6354 }
6355
6356 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6357 return -2;
6358 }
6359
6360 if ((nread > 0) || ((nread == 0) && (len == 0))) {
6361 /* some data has been read, or no data was requested */
6362 return nread;
6363 }
6364
6365 if (nread < 0) {
6366 /* socket error - check errno */
6367#if defined(_WIN32)
6368 if (err == WSAEWOULDBLOCK) {
6369 /* TODO (low): check if this is still required */
6370 /* standard case if called from close_socket_gracefully */
6371 return -2;
6372 } else if (err == WSAETIMEDOUT) {
6373 /* TODO (low): check if this is still required */
6374 /* timeout is handled by the while loop */
6375 return 0;
6376 } else if (err == WSAECONNABORTED) {
6377 /* See https://www.chilkatsoft.com/p/p_299.asp */
6378 return -2;
6379 } else {
6380 DEBUG_TRACE("recv() failed, error %d", err);
6381 return -2;
6382 }
6383#else
6384 /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
6385 * if the timeout is reached and if the socket was set to non-
6386 * blocking in close_socket_gracefully, so we can not distinguish
6387 * here. We have to wait for the timeout in both cases for now.
6388 */
6389 if (ERROR_TRY_AGAIN(err)) {
6390 /* TODO (low): check if this is still required */
6391 /* EAGAIN/EWOULDBLOCK:
6392 * standard case if called from close_socket_gracefully
6393 * => should return -1 */
6394 /* or timeout occurred
6395 * => the code must stay in the while loop */
6396
6397 /* EINTR can be generated on a socket with a timeout set even
6398 * when SA_RESTART is effective for all relevant signals
6399 * (see signal(7)).
6400 * => stay in the while loop */
6401 } else {
6402 DEBUG_TRACE("recv() failed, error %d", err);
6403 return -2;
6404 }
6405#endif
6406 }
6407
6408 /* Timeout occurred, but no data available. */
6409 return -1;
6410}
6411
6412
6413static int
6414pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
6415{
6416 int n, nread = 0;
6417 double timeout = -1.0;
6418 uint64_t start_time = 0, now = 0, timeout_ns = 0;
6419
6420 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
6421 timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
6422 }
6423 if (timeout <= 0.0) {
6424 timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
6425 / 1000.0;
6426 }
6427 start_time = mg_get_current_time_ns();
6428 timeout_ns = (uint64_t)(timeout * 1.0E9);
6429
6430 while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6431 n = pull_inner(fp, conn, buf + nread, len, timeout);
6432 if (n == -2) {
6433 if (nread == 0) {
6434 nread = -1; /* Propagate the error */
6435 }
6436 break;
6437 } else if (n == -1) {
6438 /* timeout */
6439 if (timeout >= 0.0) {
6440 now = mg_get_current_time_ns();
6441 if ((now - start_time) <= timeout_ns) {
6442 continue;
6443 }
6444 }
6445 break;
6446 } else if (n == 0) {
6447 break; /* No more data to read */
6448 } else {
6449 nread += n;
6450 len -= n;
6451 }
6452 }
6453
6454 return nread;
6455}
6456
6457
6458static void
6460{
6461 char buf[MG_BUF_LEN];
6462
6463 while (mg_read(conn, buf, sizeof(buf)) > 0)
6464 ;
6465}
6466
6467
6468static int
6469mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
6470{
6471 int64_t content_len, n, buffered_len, nread;
6472 int64_t len64 =
6473 (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
6474 * int, we may not read more
6475 * bytes */
6476 const char *body;
6477
6478 if (conn == NULL) {
6479 return 0;
6480 }
6481
6482 /* If Content-Length is not set for a response with body data,
6483 * we do not know in advance how much data should be read. */
6484 content_len = conn->content_len;
6485 if (content_len < 0) {
6486 /* The body data is completed when the connection is closed. */
6487 content_len = INT64_MAX;
6488 }
6489
6490 nread = 0;
6491 if (conn->consumed_content < content_len) {
6492 /* Adjust number of bytes to read. */
6493 int64_t left_to_read = content_len - conn->consumed_content;
6494 if (left_to_read < len64) {
6495 /* Do not read more than the total content length of the
6496 * request.
6497 */
6498 len64 = left_to_read;
6499 }
6500
6501 /* Return buffered data */
6502 buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
6503 - conn->consumed_content;
6504 if (buffered_len > 0) {
6505 if (len64 < buffered_len) {
6506 buffered_len = len64;
6507 }
6508 body = conn->buf + conn->request_len + conn->consumed_content;
6509 memcpy(buf, body, (size_t)buffered_len);
6510 len64 -= buffered_len;
6511 conn->consumed_content += buffered_len;
6512 nread += buffered_len;
6513 buf = (char *)buf + buffered_len;
6514 }
6515
6516 /* We have returned all buffered data. Read new data from the remote
6517 * socket.
6518 */
6519 if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
6520 conn->consumed_content += n;
6521 nread += n;
6522 } else {
6523 nread = ((nread > 0) ? nread : n);
6524 }
6525 }
6526 return (int)nread;
6527}
6528
6529
6530/* Forward declarations */
6531static void handle_request(struct mg_connection *);
6532static void log_access(const struct mg_connection *);
6533
6534
6535/* Handle request, update statistics and call access log */
6536static void
6538{
6539#if defined(USE_SERVER_STATS)
6540 struct timespec tnow;
6541 conn->conn_state = 4; /* processing */
6542#endif
6543
6544 handle_request(conn);
6545
6546
6547#if defined(USE_SERVER_STATS)
6548 conn->conn_state = 5; /* processed */
6549
6550 clock_gettime(CLOCK_MONOTONIC, &tnow);
6551 conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
6552
6553 mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
6554 mg_atomic_add64(&(conn->phys_ctx->total_data_written),
6555 conn->num_bytes_sent);
6556#endif
6557
6558 DEBUG_TRACE("%s", "handle_request done");
6559
6560 if (conn->phys_ctx->callbacks.end_request != NULL) {
6561 conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
6562 DEBUG_TRACE("%s", "end_request callback done");
6563 }
6564 log_access(conn);
6565}
6566
6567
6568#if defined(USE_HTTP2)
6569#if defined(NO_SSL)
6570#error "HTTP2 requires ALPN, APLN requires SSL/TLS"
6571#endif
6572#define USE_ALPN
6573#include "mod_http2.inl"
6574/* Not supported with HTTP/2 */
6575#define HTTP1_only \
6576 { \
6577 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
6578 http2_must_use_http1(conn); \
6579 return; \
6580 } \
6581 }
6582#else
6583#define HTTP1_only
6584#endif
6585
6586
6587int
6588mg_read(struct mg_connection *conn, void *buf, size_t len)
6589{
6590 if (len > INT_MAX) {
6591 len = INT_MAX;
6592 }
6593
6594 if (conn == NULL) {
6595 return 0;
6596 }
6597
6598 if (conn->is_chunked) {
6599 size_t all_read = 0;
6600
6601 while (len > 0) {
6602 if (conn->is_chunked >= 3) {
6603 /* No more data left to read */
6604 return 0;
6605 }
6606 if (conn->is_chunked != 1) {
6607 /* Has error */
6608 return -1;
6609 }
6610
6611 if (conn->consumed_content != conn->content_len) {
6612 /* copy from the current chunk */
6613 int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
6614
6615 if (read_ret < 1) {
6616 /* read error */
6617 conn->is_chunked = 2;
6618 return -1;
6619 }
6620
6621 all_read += (size_t)read_ret;
6622 len -= (size_t)read_ret;
6623
6624 if (conn->consumed_content == conn->content_len) {
6625 /* Add data bytes in the current chunk have been read,
6626 * so we are expecting \r\n now. */
6627 char x[2];
6628 conn->content_len += 2;
6629 if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
6630 || (x[1] != '\n')) {
6631 /* Protocol violation */
6632 conn->is_chunked = 2;
6633 return -1;
6634 }
6635 }
6636
6637 } else {
6638 /* fetch a new chunk */
6639 size_t i;
6640 char lenbuf[64];
6641 char *end = NULL;
6642 unsigned long chunkSize = 0;
6643
6644 for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
6645 conn->content_len++;
6646 if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
6647 lenbuf[i] = 0;
6648 }
6649 if ((i > 0) && (lenbuf[i] == '\r')
6650 && (lenbuf[i - 1] != '\r')) {
6651 continue;
6652 }
6653 if ((i > 1) && (lenbuf[i] == '\n')
6654 && (lenbuf[i - 1] == '\r')) {
6655 lenbuf[i + 1] = 0;
6656 chunkSize = strtoul(lenbuf, &end, 16);
6657 if (chunkSize == 0) {
6658 /* regular end of content */
6659 conn->is_chunked = 3;
6660 }
6661 break;
6662 }
6663 if (!isxdigit((unsigned char)lenbuf[i])) {
6664 /* illegal character for chunk length */
6665 conn->is_chunked = 2;
6666 return -1;
6667 }
6668 }
6669 if ((end == NULL) || (*end != '\r')) {
6670 /* chunksize not set correctly */
6671 conn->is_chunked = 2;
6672 return -1;
6673 }
6674 if (chunkSize == 0) {
6675 /* try discarding trailer for keep-alive */
6676 conn->content_len += 2;
6677 if ((mg_read_inner(conn, lenbuf, 2) == 2)
6678 && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
6679 conn->is_chunked = 4;
6680 }
6681 break;
6682 }
6683
6684 /* append a new chunk */
6685 conn->content_len += (int64_t)chunkSize;
6686 }
6687 }
6688
6689 return (int)all_read;
6690 }
6691 return mg_read_inner(conn, buf, len);
6692}
6693
6694
6695int
6696mg_write(struct mg_connection *conn, const void *buf, size_t len)
6697{
6698 time_t now;
6699 int n, total, allowed;
6700
6701 if (conn == NULL) {
6702 return 0;
6703 }
6704 if (len > INT_MAX) {
6705 return -1;
6706 }
6707
6708 /* Mark connection as "data sent" */
6709 conn->request_state = 10;
6710#if defined(USE_HTTP2)
6711 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
6712 http2_data_frame_head(conn, len, 0);
6713 }
6714#endif
6715
6716 if (conn->throttle > 0) {
6717 if ((now = time(NULL)) != conn->last_throttle_time) {
6718 conn->last_throttle_time = now;
6719 conn->last_throttle_bytes = 0;
6720 }
6721 allowed = conn->throttle - conn->last_throttle_bytes;
6722 if (allowed > (int)len) {
6723 allowed = (int)len;
6724 }
6725
6726 total = push_all(conn->phys_ctx,
6727 NULL,
6728 conn->client.sock,
6729 conn->ssl,
6730 (const char *)buf,
6731 allowed);
6732
6733 if (total == allowed) {
6734
6735 buf = (const char *)buf + total;
6736 conn->last_throttle_bytes += total;
6737 while ((total < (int)len)
6738 && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6739 allowed = (conn->throttle > ((int)len - total))
6740 ? (int)len - total
6741 : conn->throttle;
6742
6743 n = push_all(conn->phys_ctx,
6744 NULL,
6745 conn->client.sock,
6746 conn->ssl,
6747 (const char *)buf,
6748 allowed);
6749
6750 if (n != allowed) {
6751 break;
6752 }
6753 sleep(1);
6754 conn->last_throttle_bytes = allowed;
6755 conn->last_throttle_time = time(NULL);
6756 buf = (const char *)buf + n;
6757 total += n;
6758 }
6759 }
6760 } else {
6761 total = push_all(conn->phys_ctx,
6762 NULL,
6763 conn->client.sock,
6764 conn->ssl,
6765 (const char *)buf,
6766 (int)len);
6767 }
6768 if (total > 0) {
6769 conn->num_bytes_sent += total;
6770 }
6771 return total;
6772}
6773
6774
6775/* Send a chunk, if "Transfer-Encoding: chunked" is used */
6776int
6778 const char *chunk,
6779 unsigned int chunk_len)
6780{
6781 char lenbuf[16];
6782 size_t lenbuf_len;
6783 int ret;
6784 int t;
6785
6786 /* First store the length information in a text buffer. */
6787 sprintf(lenbuf, "%x\r\n", chunk_len);
6788 lenbuf_len = strlen(lenbuf);
6789
6790 /* Then send length information, chunk and terminating \r\n. */
6791 ret = mg_write(conn, lenbuf, lenbuf_len);
6792 if (ret != (int)lenbuf_len) {
6793 return -1;
6794 }
6795 t = ret;
6796
6797 ret = mg_write(conn, chunk, chunk_len);
6798 if (ret != (int)chunk_len) {
6799 return -1;
6800 }
6801 t += ret;
6802
6803 ret = mg_write(conn, "\r\n", 2);
6804 if (ret != 2) {
6805 return -1;
6806 }
6807 t += ret;
6808
6809 return t;
6810}
6811
6812
6813#if defined(GCC_DIAGNOSTIC)
6814/* This block forwards format strings to printf implementations,
6815 * so we need to disable the format-nonliteral warning. */
6816#pragma GCC diagnostic push
6817#pragma GCC diagnostic ignored "-Wformat-nonliteral"
6818#endif
6819
6820
6821/* Alternative alloc_vprintf() for non-compliant C runtimes */
6822static int
6823alloc_vprintf2(char **buf, const char *fmt, va_list ap)
6824{
6825 va_list ap_copy;
6826 size_t size = MG_BUF_LEN / 4;
6827 int len = -1;
6828
6829 *buf = NULL;
6830 while (len < 0) {
6831 if (*buf) {
6832 mg_free(*buf);
6833 }
6834
6835 size *= 4;
6836 *buf = (char *)mg_malloc(size);
6837 if (!*buf) {
6838 break;
6839 }
6840
6841 va_copy(ap_copy, ap);
6842 len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
6843 va_end(ap_copy);
6844 (*buf)[size - 1] = 0;
6845 }
6846
6847 return len;
6848}
6849
6850
6851/* Print message to buffer. If buffer is large enough to hold the message,
6852 * return buffer. If buffer is to small, allocate large enough buffer on
6853 * heap,
6854 * and return allocated buffer. */
6855static int
6856alloc_vprintf(char **out_buf,
6857 char *prealloc_buf,
6858 size_t prealloc_size,
6859 const char *fmt,
6860 va_list ap)
6861{
6862 va_list ap_copy;
6863 int len;
6864
6865 /* Windows is not standard-compliant, and vsnprintf() returns -1 if
6866 * buffer is too small. Also, older versions of msvcrt.dll do not have
6867 * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
6868 * Therefore, we make two passes: on first pass, get required message
6869 * length.
6870 * On second pass, actually print the message. */
6871 va_copy(ap_copy, ap);
6872 len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
6873 va_end(ap_copy);
6874
6875 if (len < 0) {
6876 /* C runtime is not standard compliant, vsnprintf() returned -1.
6877 * Switch to alternative code path that uses incremental
6878 * allocations.
6879 */
6880 va_copy(ap_copy, ap);
6881 len = alloc_vprintf2(out_buf, fmt, ap_copy);
6882 va_end(ap_copy);
6883
6884 } else if ((size_t)(len) >= prealloc_size) {
6885 /* The pre-allocated buffer not large enough. */
6886 /* Allocate a new buffer. */
6887 *out_buf = (char *)mg_malloc((size_t)(len) + 1);
6888 if (!*out_buf) {
6889 /* Allocation failed. Return -1 as "out of memory" error. */
6890 return -1;
6891 }
6892 /* Buffer allocation successful. Store the string there. */
6893 va_copy(ap_copy, ap);
6895 vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
6896 va_end(ap_copy);
6897
6898 } else {
6899 /* The pre-allocated buffer is large enough.
6900 * Use it to store the string and return the address. */
6901 va_copy(ap_copy, ap);
6903 vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
6904 va_end(ap_copy);
6905 *out_buf = prealloc_buf;
6906 }
6907
6908 return len;
6909}
6910
6911
6912#if defined(GCC_DIAGNOSTIC)
6913/* Enable format-nonliteral warning again. */
6914#pragma GCC diagnostic pop
6915#endif
6916
6917
6918static int
6919mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
6920{
6921 char mem[MG_BUF_LEN];
6922 char *buf = NULL;
6923 int len;
6924
6925 if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
6926 len = mg_write(conn, buf, (size_t)len);
6927 }
6928 if (buf != mem) {
6929 mg_free(buf);
6930 }
6931
6932 return len;
6933}
6934
6935
6936int
6937mg_printf(struct mg_connection *conn, const char *fmt, ...)
6938{
6939 va_list ap;
6940 int result;
6941
6942 va_start(ap, fmt);
6943 result = mg_vprintf(conn, fmt, ap);
6944 va_end(ap);
6945
6946 return result;
6947}
6948
6949
6950int
6951mg_url_decode(const char *src,
6952 int src_len,
6953 char *dst,
6954 int dst_len,
6955 int is_form_url_encoded)
6956{
6957 int i, j, a, b;
6958#define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
6959
6960 for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
6961 if ((i < src_len - 2) && (src[i] == '%')
6962 && isxdigit((unsigned char)src[i + 1])
6963 && isxdigit((unsigned char)src[i + 2])) {
6964 a = tolower((unsigned char)src[i + 1]);
6965 b = tolower((unsigned char)src[i + 2]);
6966 dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
6967 i += 2;
6968 } else if (is_form_url_encoded && (src[i] == '+')) {
6969 dst[j] = ' ';
6970 } else {
6971 dst[j] = src[i];
6972 }
6973 }
6974
6975 dst[j] = '\0'; /* Null-terminate the destination */
6976
6977 return (i >= src_len) ? j : -1;
6978}
6979
6980
6981/* form url decoding of an entire string */
6982static void
6984{
6985 int len = (int)strlen(buf);
6986 (void)mg_url_decode(buf, len, buf, len + 1, 1);
6987}
6988
6989
6990int
6991mg_get_var(const char *data,
6992 size_t data_len,
6993 const char *name,
6994 char *dst,
6995 size_t dst_len)
6996{
6997 return mg_get_var2(data, data_len, name, dst, dst_len, 0);
6998}
6999
7000
7001int
7002mg_get_var2(const char *data,
7003 size_t data_len,
7004 const char *name,
7005 char *dst,
7006 size_t dst_len,
7007 size_t occurrence)
7008{
7009 const char *p, *e, *s;
7010 size_t name_len;
7011 int len;
7012
7013 if ((dst == NULL) || (dst_len == 0)) {
7014 len = -2;
7015 } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
7016 len = -1;
7017 dst[0] = '\0';
7018 } else {
7019 name_len = strlen(name);
7020 e = data + data_len;
7021 len = -1;
7022 dst[0] = '\0';
7023
7024 /* data is "var1=val1&var2=val2...". Find variable first */
7025 for (p = data; p + name_len < e; p++) {
7026 if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
7027 && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
7028 /* Point p to variable value */
7029 p += name_len + 1;
7030
7031 /* Point s to the end of the value */
7032 s = (const char *)memchr(p, '&', (size_t)(e - p));
7033 if (s == NULL) {
7034 s = e;
7035 }
7036 DEBUG_ASSERT(s >= p);
7037 if (s < p) {
7038 return -3;
7039 }
7040
7041 /* Decode variable into destination buffer */
7042 len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
7043
7044 /* Redirect error code from -1 to -2 (destination buffer too
7045 * small). */
7046 if (len == -1) {
7047 len = -2;
7048 }
7049 break;
7050 }
7051 }
7052 }
7053
7054 return len;
7055}
7056
7057
7058/* split a string "key1=val1&key2=val2" into key/value pairs */
7059int
7061 struct mg_header *form_fields,
7062 unsigned num_form_fields)
7063{
7064 char *b;
7065 int i;
7066 int num = 0;
7067
7068 if (data == NULL) {
7069 /* parameter error */
7070 return -1;
7071 }
7072
7073 if ((form_fields == NULL) && (num_form_fields == 0)) {
7074 /* determine the number of expected fields */
7075 if (data[0] == 0) {
7076 return 0;
7077 }
7078 /* count number of & to return the number of key-value-pairs */
7079 num = 1;
7080 while (*data) {
7081 if (*data == '&') {
7082 num++;
7083 }
7084 data++;
7085 }
7086 return num;
7087 }
7088
7089 if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
7090 /* parameter error */
7091 return -1;
7092 }
7093
7094 for (i = 0; i < (int)num_form_fields; i++) {
7095 /* extract key-value pairs from input data */
7096 while ((*data == ' ') || (*data == '\t')) {
7097 /* skip initial spaces */
7098 data++;
7099 }
7100 if (*data == 0) {
7101 /* end of string reached */
7102 break;
7103 }
7104 form_fields[num].name = data;
7105
7106 /* find & or = */
7107 b = data;
7108 while ((*b != 0) && (*b != '&') && (*b != '=')) {
7109 b++;
7110 }
7111
7112 if (*b == 0) {
7113 /* last key without value */
7114 form_fields[num].value = NULL;
7115 } else if (*b == '&') {
7116 /* mid key without value */
7117 form_fields[num].value = NULL;
7118 } else {
7119 /* terminate string */
7120 *b = 0;
7121 /* value starts after '=' */
7122 data = b + 1;
7123 form_fields[num].value = data;
7124 }
7125
7126 /* new field is stored */
7127 num++;
7128
7129 /* find a next key */
7130 b = strchr(data, '&');
7131 if (b == 0) {
7132 /* no more data */
7133 break;
7134 } else {
7135 /* terminate value of last field at '&' */
7136 *b = 0;
7137 /* next key-value-pairs starts after '&' */
7138 data = b + 1;
7139 }
7140 }
7141
7142 /* Decode all values */
7143 for (i = 0; i < num; i++) {
7144 if (form_fields[i].name) {
7145 url_decode_in_place((char *)form_fields[i].name);
7146 }
7147 if (form_fields[i].value) {
7148 url_decode_in_place((char *)form_fields[i].value);
7149 }
7150 }
7151
7152 /* return number of fields found */
7153 return num;
7154}
7155
7156
7157/* HCP24: some changes to compare hole var_name */
7158int
7159mg_get_cookie(const char *cookie_header,
7160 const char *var_name,
7161 char *dst,
7162 size_t dst_size)
7163{
7164 const char *s, *p, *end;
7165 int name_len, len = -1;
7166
7167 if ((dst == NULL) || (dst_size == 0)) {
7168 return -2;
7169 }
7170
7171 dst[0] = '\0';
7172 if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
7173 return -1;
7174 }
7175
7176 name_len = (int)strlen(var_name);
7177 end = s + strlen(s);
7178 for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
7179 if (s[name_len] == '=') {
7180 /* HCP24: now check is it a substring or a full cookie name */
7181 if ((s == cookie_header) || (s[-1] == ' ')) {
7182 s += name_len + 1;
7183 if ((p = strchr(s, ' ')) == NULL) {
7184 p = end;
7185 }
7186 if (p[-1] == ';') {
7187 p--;
7188 }
7189 if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
7190 s++;
7191 p--;
7192 }
7193 if ((size_t)(p - s) < dst_size) {
7194 len = (int)(p - s);
7195 mg_strlcpy(dst, s, (size_t)len + 1);
7196 } else {
7197 len = -3;
7198 }
7199 break;
7200 }
7201 }
7202 }
7203 return len;
7204}
7205
7206
7207#if defined(USE_WEBSOCKET) || defined(USE_LUA)
7208static void
7209base64_encode(const unsigned char *src, int src_len, char *dst)
7210{
7211 static const char *b64 =
7212 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7213 int i, j, a, b, c;
7214
7215 for (i = j = 0; i < src_len; i += 3) {
7216 a = src[i];
7217 b = ((i + 1) >= src_len) ? 0 : src[i + 1];
7218 c = ((i + 2) >= src_len) ? 0 : src[i + 2];
7219
7220 dst[j++] = b64[a >> 2];
7221 dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
7222 if (i + 1 < src_len) {
7223 dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
7224 }
7225 if (i + 2 < src_len) {
7226 dst[j++] = b64[c & 63];
7227 }
7228 }
7229 while (j % 4 != 0) {
7230 dst[j++] = '=';
7231 }
7232 dst[j++] = '\0';
7233}
7234#endif
7235
7236
7237#if defined(USE_LUA)
7238static unsigned char
7239b64reverse(char letter)
7240{
7241 if ((letter >= 'A') && (letter <= 'Z')) {
7242 return letter - 'A';
7243 }
7244 if ((letter >= 'a') && (letter <= 'z')) {
7245 return letter - 'a' + 26;
7246 }
7247 if ((letter >= '0') && (letter <= '9')) {
7248 return letter - '0' + 52;
7249 }
7250 if (letter == '+') {
7251 return 62;
7252 }
7253 if (letter == '/') {
7254 return 63;
7255 }
7256 if (letter == '=') {
7257 return 255; /* normal end */
7258 }
7259 return 254; /* error */
7260}
7261
7262
7263static int
7264base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
7265{
7266 int i;
7267 unsigned char a, b, c, d;
7268
7269 *dst_len = 0;
7270
7271 for (i = 0; i < src_len; i += 4) {
7272 a = b64reverse(src[i]);
7273 if (a >= 254) {
7274 return i;
7275 }
7276
7277 b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
7278 if (b >= 254) {
7279 return i + 1;
7280 }
7281
7282 c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
7283 if (c == 254) {
7284 return i + 2;
7285 }
7286
7287 d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
7288 if (d == 254) {
7289 return i + 3;
7290 }
7291
7292 dst[(*dst_len)++] = (a << 2) + (b >> 4);
7293 if (c != 255) {
7294 dst[(*dst_len)++] = (b << 4) + (c >> 2);
7295 if (d != 255) {
7296 dst[(*dst_len)++] = (c << 6) + d;
7297 }
7298 }
7299 }
7300 return -1;
7301}
7302#endif
7303
7304
7305static int
7307{
7308 if (conn) {
7309 const char *s = conn->request_info.request_method;
7310 return (s != NULL)
7311 && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
7312 || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
7313 }
7314 return 0;
7315}
7316
7317
7318#if !defined(NO_FILES)
7319static int
7321 struct mg_connection *conn, /* in: request (must be valid) */
7322 const char *filename /* in: filename (must be valid) */
7323)
7324{
7325#if !defined(NO_CGI)
7326 unsigned char cgi_config_idx, inc, max;
7327#endif
7328
7329#if defined(USE_LUA)
7330 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
7331 filename)
7332 > 0) {
7333 return 1;
7334 }
7335#endif
7336#if defined(USE_DUKTAPE)
7337 if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
7338 filename)
7339 > 0) {
7340 return 1;
7341 }
7342#endif
7343#if !defined(NO_CGI)
7346 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
7347 if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
7349 conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
7350 filename)
7351 > 0)) {
7352 return 1;
7353 }
7354 }
7355#endif
7356 /* filename and conn could be unused, if all preocessor conditions
7357 * are false (no script language supported). */
7358 (void)filename;
7359 (void)conn;
7360
7361 return 0;
7362}
7363
7364
7365static int
7367 struct mg_connection *conn, /* in: request (must be valid) */
7368 const char *filename /* in: filename (must be valid) */
7369)
7370{
7371#if defined(USE_LUA)
7372 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
7373 filename)
7374 > 0) {
7375 return 1;
7376 }
7377#endif
7379 > 0) {
7380 return 1;
7381 }
7382 return 0;
7383}
7384
7385
7386/* For given directory path, substitute it to valid index file.
7387 * Return 1 if index file has been found, 0 if not found.
7388 * If the file is found, it's stats is returned in stp. */
7389static int
7391 char *path,
7392 size_t path_len,
7393 struct mg_file_stat *filestat)
7394{
7395 const char *list = conn->dom_ctx->config[INDEX_FILES];
7396 struct vec filename_vec;
7397 size_t n = strlen(path);
7398 int found = 0;
7399
7400 /* The 'path' given to us points to the directory. Remove all trailing
7401 * directory separator characters from the end of the path, and
7402 * then append single directory separator character. */
7403 while ((n > 0) && (path[n - 1] == '/')) {
7404 n--;
7405 }
7406 path[n] = '/';
7407
7408 /* Traverse index files list. For each entry, append it to the given
7409 * path and see if the file exists. If it exists, break the loop */
7410 while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
7411 /* Ignore too long entries that may overflow path buffer */
7412 if ((filename_vec.len + 1) > (path_len - (n + 1))) {
7413 continue;
7414 }
7415
7416 /* Prepare full path to the index file */
7417 mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
7418
7419 /* Does it exist? */
7420 if (mg_stat(conn, path, filestat)) {
7421 /* Yes it does, break the loop */
7422 found = 1;
7423 break;
7424 }
7425 }
7426
7427 /* If no index file exists, restore directory path */
7428 if (!found) {
7429 path[n] = '\0';
7430 }
7431
7432 return found;
7433}
7434#endif
7435
7436
7437static void
7438interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
7439 char *filename, /* out: filename */
7440 size_t filename_buf_len, /* in: size of filename buffer */
7441 struct mg_file_stat *filestat, /* out: file status structure */
7442 int *is_found, /* out: file found (directly) */
7443 int *is_script_resource, /* out: handled by a script? */
7444 int *is_websocket_request, /* out: websocket connetion? */
7445 int *is_put_or_delete_request, /* out: put/delete a file? */
7446 int *is_template_text /* out: SSI file or LSP file? */
7447)
7448{
7449 char const *accept_encoding;
7450
7451#if !defined(NO_FILES)
7452 const char *uri = conn->request_info.local_uri;
7453 const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
7454 const char *rewrite;
7455 struct vec a, b;
7456 ptrdiff_t match_len;
7457 char gz_path[UTF8_PATH_MAX];
7458 int truncated;
7459#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7460 char *tmp_str;
7461 size_t tmp_str_len, sep_pos;
7462 int allow_substitute_script_subresources;
7463#endif
7464#else
7465 (void)filename_buf_len; /* unused if NO_FILES is defined */
7466#endif
7467
7468 /* Step 1: Set all initially unknown outputs to zero */
7469 memset(filestat, 0, sizeof(*filestat));
7470 *filename = 0;
7471 *is_found = 0;
7472 *is_script_resource = 0;
7473 *is_template_text = 0;
7474
7475 /* Step 2: Check if the request attempts to modify the file system */
7476 *is_put_or_delete_request = is_put_or_delete_method(conn);
7477
7478 /* Step 3: Check if it is a websocket request, and modify the document
7479 * root if required */
7480#if defined(USE_WEBSOCKET)
7481 *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
7482#if !defined(NO_FILES)
7483 if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
7484 root = conn->dom_ctx->config[WEBSOCKET_ROOT];
7485 }
7486#endif /* !NO_FILES */
7487#else /* USE_WEBSOCKET */
7488 *is_websocket_request = 0;
7489#endif /* USE_WEBSOCKET */
7490
7491 /* Step 4: Check if gzip encoded response is allowed */
7492 conn->accept_gzip = 0;
7493 if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
7494 if (strstr(accept_encoding, "gzip") != NULL) {
7495 conn->accept_gzip = 1;
7496 }
7497 }
7498
7499#if !defined(NO_FILES)
7500 /* Step 5: If there is no root directory, don't look for files. */
7501 /* Note that root == NULL is a regular use case here. This occurs,
7502 * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
7503 * config is not required. */
7504 if (root == NULL) {
7505 /* all file related outputs have already been set to 0, just return
7506 */
7507 return;
7508 }
7509
7510 /* Step 6: Determine the local file path from the root path and the
7511 * request uri. */
7512 /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
7513 * part of the path one byte on the right. */
7514 truncated = 0;
7516 conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
7517
7518 if (truncated) {
7519 goto interpret_cleanup;
7520 }
7521
7522 /* Step 7: URI rewriting */
7523 rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
7524 while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
7525 if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
7526 mg_snprintf(conn,
7527 &truncated,
7528 filename,
7529 filename_buf_len - 1,
7530 "%.*s%s",
7531 (int)b.len,
7532 b.ptr,
7533 uri + match_len);
7534 break;
7535 }
7536 }
7537
7538 if (truncated) {
7539 goto interpret_cleanup;
7540 }
7541
7542 /* Step 8: Check if the file exists at the server */
7543 /* Local file path and name, corresponding to requested URI
7544 * is now stored in "filename" variable. */
7545 if (mg_stat(conn, filename, filestat)) {
7546 int uri_len = (int)strlen(uri);
7547 int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
7548
7549 /* 8.1: File exists. */
7550 *is_found = 1;
7551
7552 /* 8.2: Check if it is a script type. */
7554 /* The request addresses a CGI resource, Lua script or
7555 * server-side javascript.
7556 * The URI corresponds to the script itself (like
7557 * /path/script.cgi), and there is no additional resource
7558 * path (like /path/script.cgi/something).
7559 * Requests that modify (replace or delete) a resource, like
7560 * PUT and DELETE requests, should replace/delete the script
7561 * file.
7562 * Requests that read or write from/to a resource, like GET and
7563 * POST requests, should call the script and return the
7564 * generated response. */
7565 *is_script_resource = (!*is_put_or_delete_request);
7566 }
7567
7568 /* 8.3: Check for SSI and LSP files */
7570 /* Same as above, but for *.lsp and *.shtml files. */
7571 /* A "template text" is a file delivered directly to the client,
7572 * but with some text tags replaced by dynamic content.
7573 * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
7574 * (LP, LSP) file. */
7575 *is_template_text = (!*is_put_or_delete_request);
7576 }
7577
7578 /* 8.4: If the request target is a directory, there could be
7579 * a substitute file (index.html, index.cgi, ...). */
7580 if (filestat->is_directory && is_uri_end_slash) {
7581 /* Use a local copy here, since substitute_index_file will
7582 * change the content of the file status */
7583 struct mg_file_stat tmp_filestat;
7584 memset(&tmp_filestat, 0, sizeof(tmp_filestat));
7585
7587 conn, filename, filename_buf_len, &tmp_filestat)) {
7588
7589 /* Substitute file found. Copy stat to the output, then
7590 * check if the file is a script file */
7591 *filestat = tmp_filestat;
7592
7594 /* Substitute file is a script file */
7595 *is_script_resource = 1;
7596 } else if (extention_matches_template_text(conn, filename)) {
7597 /* Substitute file is a LSP or SSI file */
7598 *is_template_text = 1;
7599 } else {
7600 /* Substitute file is a regular file */
7601 *is_script_resource = 0;
7602 *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
7603 }
7604 }
7605 /* If there is no substitute file, the server could return
7606 * a directory listing in a later step */
7607 }
7608 return;
7609 }
7610
7611 /* Step 9: Check for zipped files: */
7612 /* If we can't find the actual file, look for the file
7613 * with the same name but a .gz extension. If we find it,
7614 * use that and set the gzipped flag in the file struct
7615 * to indicate that the response need to have the content-
7616 * encoding: gzip header.
7617 * We can only do this if the browser declares support. */
7618 if (conn->accept_gzip) {
7620 conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
7621
7622 if (truncated) {
7623 goto interpret_cleanup;
7624 }
7625
7626 if (mg_stat(conn, gz_path, filestat)) {
7627 if (filestat) {
7628 filestat->is_gzipped = 1;
7629 *is_found = 1;
7630 }
7631 /* Currently gz files can not be scripts. */
7632 return;
7633 }
7634 }
7635
7636#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7637 /* Step 10: Script resources may handle sub-resources */
7638 /* Support PATH_INFO for CGI scripts. */
7639 tmp_str_len = strlen(filename);
7640 tmp_str =
7641 (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
7642 if (!tmp_str) {
7643 /* Out of memory */
7644 goto interpret_cleanup;
7645 }
7646 memcpy(tmp_str, filename, tmp_str_len + 1);
7647
7648 /* Check config, if index scripts may have sub-resources */
7649 allow_substitute_script_subresources =
7651 "yes");
7652
7653 sep_pos = tmp_str_len;
7654 while (sep_pos > 0) {
7655 sep_pos--;
7656 if (tmp_str[sep_pos] == '/') {
7657 int is_script = 0, does_exist = 0;
7658
7659 tmp_str[sep_pos] = 0;
7660 if (tmp_str[0]) {
7661 is_script = extention_matches_script(conn, tmp_str);
7662 does_exist = mg_stat(conn, tmp_str, filestat);
7663 }
7664
7665 if (does_exist && is_script) {
7666 filename[sep_pos] = 0;
7667 memmove(filename + sep_pos + 2,
7668 filename + sep_pos + 1,
7669 strlen(filename + sep_pos + 1) + 1);
7670 conn->path_info = filename + sep_pos + 1;
7671 filename[sep_pos + 1] = '/';
7672 *is_script_resource = 1;
7673 *is_found = 1;
7674 break;
7675 }
7676
7677 if (allow_substitute_script_subresources) {
7679 conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
7680
7681 /* some intermediate directory has an index file */
7682 if (extention_matches_script(conn, tmp_str)) {
7683
7684 size_t script_name_len = strlen(tmp_str);
7685
7686 /* subres_name read before this memory locatio will be
7687 overwritten */
7688 char *subres_name = filename + sep_pos;
7689 size_t subres_name_len = strlen(subres_name);
7690
7691 DEBUG_TRACE("Substitute script %s serving path %s",
7692 tmp_str,
7693 filename);
7694
7695 /* this index file is a script */
7696 if ((script_name_len + subres_name_len + 2)
7697 >= filename_buf_len) {
7698 mg_free(tmp_str);
7699 goto interpret_cleanup;
7700 }
7701
7702 conn->path_info =
7703 filename + script_name_len + 1; /* new target */
7704 memmove(conn->path_info, subres_name, subres_name_len);
7705 conn->path_info[subres_name_len] = 0;
7706 memcpy(filename, tmp_str, script_name_len + 1);
7707
7708 *is_script_resource = 1;
7709 *is_found = 1;
7710 break;
7711
7712 } else {
7713
7714 DEBUG_TRACE("Substitute file %s serving path %s",
7715 tmp_str,
7716 filename);
7717
7718 /* non-script files will not have sub-resources */
7719 filename[sep_pos] = 0;
7720 conn->path_info = 0;
7721 *is_script_resource = 0;
7722 *is_found = 0;
7723 break;
7724 }
7725 }
7726 }
7727
7728 tmp_str[sep_pos] = '/';
7729 }
7730 }
7731
7732 mg_free(tmp_str);
7733
7734#endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
7735#endif /* !defined(NO_FILES) */
7736 return;
7737
7738#if !defined(NO_FILES)
7739/* Reset all outputs */
7740interpret_cleanup:
7741 memset(filestat, 0, sizeof(*filestat));
7742 *filename = 0;
7743 *is_found = 0;
7744 *is_script_resource = 0;
7745 *is_websocket_request = 0;
7746 *is_put_or_delete_request = 0;
7747#endif /* !defined(NO_FILES) */
7748}
7749
7750
7751/* Check whether full request is buffered. Return:
7752 * -1 if request or response is malformed
7753 * 0 if request or response is not yet fully buffered
7754 * >0 actual request length, including last \r\n\r\n */
7755static int
7756get_http_header_len(const char *buf, int buflen)
7757{
7758 int i;
7759 for (i = 0; i < buflen; i++) {
7760 /* Do an unsigned comparison in some conditions below */
7761 const unsigned char c = (unsigned char)buf[i];
7762
7763 if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
7764 && !isprint(c)) {
7765 /* abort scan as soon as one malformed character is found */
7766 return -1;
7767 }
7768
7769 if (i < buflen - 1) {
7770 if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
7771 /* Two newline, no carriage return - not standard compliant,
7772 * but it should be accepted */
7773 return i + 2;
7774 }
7775 }
7776
7777 if (i < buflen - 3) {
7778 if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
7779 && (buf[i + 3] == '\n')) {
7780 /* Two \r\n - standard compliant */
7781 return i + 4;
7782 }
7783 }
7784 }
7785
7786 return 0;
7787}
7788
7789
7790#if !defined(NO_CACHING)
7791/* Convert month to the month number. Return -1 on error, or month number */
7792static int
7793get_month_index(const char *s)
7794{
7795 size_t i;
7796
7797 for (i = 0; i < ARRAY_SIZE(month_names); i++) {
7798 if (!strcmp(s, month_names[i])) {
7799 return (int)i;
7800 }
7801 }
7802
7803 return -1;
7804}
7805
7806
7807/* Parse UTC date-time string, and return the corresponding time_t value. */
7808static time_t
7809parse_date_string(const char *datetime)
7810{
7811 char month_str[32] = {0};
7812 int second, minute, hour, day, month, year;
7813 time_t result = (time_t)0;
7814 struct tm tm;
7815
7816 if ((sscanf(datetime,
7817 "%d/%3s/%d %d:%d:%d",
7818 &day,
7819 month_str,
7820 &year,
7821 &hour,
7822 &minute,
7823 &second)
7824 == 6)
7825 || (sscanf(datetime,
7826 "%d %3s %d %d:%d:%d",
7827 &day,
7828 month_str,
7829 &year,
7830 &hour,
7831 &minute,
7832 &second)
7833 == 6)
7834 || (sscanf(datetime,
7835 "%*3s, %d %3s %d %d:%d:%d",
7836 &day,
7837 month_str,
7838 &year,
7839 &hour,
7840 &minute,
7841 &second)
7842 == 6)
7843 || (sscanf(datetime,
7844 "%d-%3s-%d %d:%d:%d",
7845 &day,
7846 month_str,
7847 &year,
7848 &hour,
7849 &minute,
7850 &second)
7851 == 6)) {
7852 month = get_month_index(month_str);
7853 if ((month >= 0) && (year >= 1970)) {
7854 memset(&tm, 0, sizeof(tm));
7855 tm.tm_year = year - 1900;
7856 tm.tm_mon = month;
7857 tm.tm_mday = day;
7858 tm.tm_hour = hour;
7859 tm.tm_min = minute;
7860 tm.tm_sec = second;
7861 result = timegm(&tm);
7862 }
7863 }
7864
7865 return result;
7866}
7867#endif /* !NO_CACHING */
7868
7869
7870/* Pre-process URIs according to RFC + protect against directory disclosure
7871 * attacks by removing '..', excessive '/' and '\' characters */
7872static void
7874{
7875 /* Windows backend protection
7876 * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
7877 * in URI by slash */
7878 char *out_end = inout;
7879 char *in = inout;
7880
7881 if (!in) {
7882 /* Param error. */
7883 return;
7884 }
7885
7886 while (*in) {
7887 if (*in == '\\') {
7888 *in = '/';
7889 }
7890 in++;
7891 }
7892
7893 /* Algorithm "remove_dot_segments" from
7894 * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
7895 /* Step 1:
7896 * The input buffer is initialized.
7897 * The output buffer is initialized to the empty string.
7898 */
7899 in = inout;
7900
7901 /* Step 2:
7902 * While the input buffer is not empty, loop as follows:
7903 */
7904 /* Less than out_end of the inout buffer is used as output, so keep
7905 * condition: out_end <= in */
7906 while (*in) {
7907 /* Step 2a:
7908 * If the input buffer begins with a prefix of "../" or "./",
7909 * then remove that prefix from the input buffer;
7910 */
7911 if (!strncmp(in, "../", 3)) {
7912 in += 3;
7913 } else if (!strncmp(in, "./", 2)) {
7914 in += 2;
7915 }
7916 /* otherwise */
7917 /* Step 2b:
7918 * if the input buffer begins with a prefix of "/./" or "/.",
7919 * where "." is a complete path segment, then replace that
7920 * prefix with "/" in the input buffer;
7921 */
7922 else if (!strncmp(in, "/./", 3)) {
7923 in += 2;
7924 } else if (!strcmp(in, "/.")) {
7925 in[1] = 0;
7926 }
7927 /* otherwise */
7928 /* Step 2c:
7929 * if the input buffer begins with a prefix of "/../" or "/..",
7930 * where ".." is a complete path segment, then replace that
7931 * prefix with "/" in the input buffer and remove the last
7932 * segment and its preceding "/" (if any) from the output
7933 * buffer;
7934 */
7935 else if (!strncmp(in, "/../", 4)) {
7936 in += 3;
7937 if (inout != out_end) {
7938 /* remove last segment */
7939 do {
7940 out_end--;
7941 } while ((inout != out_end) && (*out_end != '/'));
7942 }
7943 } else if (!strcmp(in, "/..")) {
7944 in[1] = 0;
7945 if (inout != out_end) {
7946 /* remove last segment */
7947 do {
7948 out_end--;
7949 } while ((inout != out_end) && (*out_end != '/'));
7950 }
7951 }
7952 /* otherwise */
7953 /* Step 2d:
7954 * if the input buffer consists only of "." or "..", then remove
7955 * that from the input buffer;
7956 */
7957 else if (!strcmp(in, ".") || !strcmp(in, "..")) {
7958 *in = 0;
7959 }
7960 /* otherwise */
7961 /* Step 2e:
7962 * move the first path segment in the input buffer to the end of
7963 * the output buffer, including the initial "/" character (if
7964 * any) and any subsequent characters up to, but not including,
7965 * the next "/" character or the end of the input buffer.
7966 */
7967 else {
7968 do {
7969 *out_end = *in;
7970 out_end++;
7971 in++;
7972 } while ((*in != 0) && (*in != '/'));
7973 }
7974 }
7975
7976 /* Step 3:
7977 * Finally, the output buffer is returned as the result of
7978 * remove_dot_segments.
7979 */
7980 /* Terminate output */
7981 *out_end = 0;
7982
7983 /* For Windows, the files/folders "x" and "x." (with a dot but without
7984 * extension) are identical. Replace all "./" by "/" and remove a "." at
7985 * the end. Also replace all "//" by "/". Repeat until there is no "./"
7986 * or "//" anymore.
7987 */
7988 out_end = in = inout;
7989 while (*in) {
7990 if (*in == '.') {
7991 /* remove . at the end or preceding of / */
7992 char *in_ahead = in;
7993 do {
7994 in_ahead++;
7995 } while (*in_ahead == '.');
7996 if (*in_ahead == '/') {
7997 in = in_ahead;
7998 if ((out_end != inout) && (out_end[-1] == '/')) {
7999 /* remove generated // */
8000 out_end--;
8001 }
8002 } else if (*in_ahead == 0) {
8003 in = in_ahead;
8004 } else {
8005 do {
8006 *out_end++ = '.';
8007 in++;
8008 } while (in != in_ahead);
8009 }
8010 } else if (*in == '/') {
8011 /* replace // by / */
8012 *out_end++ = '/';
8013 do {
8014 in++;
8015 } while (*in == '/');
8016 } else {
8017 *out_end++ = *in;
8018 in++;
8019 }
8020 }
8021 *out_end = 0;
8022}
8023
8024
8025static const struct {
8026 const char *extension;
8027 size_t ext_len;
8028 const char *mime_type;
8029} builtin_mime_types[] = {
8030 /* IANA registered MIME types
8031 * (http://www.iana.org/assignments/media-types)
8032 * application types */
8033 {".bin", 4, "application/octet-stream"},
8034 {".deb", 4, "application/octet-stream"},
8035 {".dmg", 4, "application/octet-stream"},
8036 {".dll", 4, "application/octet-stream"},
8037 {".doc", 4, "application/msword"},
8038 {".eps", 4, "application/postscript"},
8039 {".exe", 4, "application/octet-stream"},
8040 {".iso", 4, "application/octet-stream"},
8041 {".js", 3, "application/javascript"},
8042 {".json", 5, "application/json"},
8043 {".msi", 4, "application/octet-stream"},
8044 {".pdf", 4, "application/pdf"},
8045 {".ps", 3, "application/postscript"},
8046 {".rtf", 4, "application/rtf"},
8047 {".xhtml", 6, "application/xhtml+xml"},
8048 {".xsl", 4, "application/xml"},
8049 {".xslt", 5, "application/xml"},
8050
8051 /* fonts */
8052 {".ttf", 4, "application/font-sfnt"},
8053 {".cff", 4, "application/font-sfnt"},
8054 {".otf", 4, "application/font-sfnt"},
8055 {".aat", 4, "application/font-sfnt"},
8056 {".sil", 4, "application/font-sfnt"},
8057 {".pfr", 4, "application/font-tdpfr"},
8058 {".woff", 5, "application/font-woff"},
8059 {".woff2", 6, "application/font-woff2"},
8060
8061 /* audio */
8062 {".mp3", 4, "audio/mpeg"},
8063 {".oga", 4, "audio/ogg"},
8064 {".ogg", 4, "audio/ogg"},
8065
8066 /* image */
8067 {".gif", 4, "image/gif"},
8068 {".ief", 4, "image/ief"},
8069 {".jpeg", 5, "image/jpeg"},
8070 {".jpg", 4, "image/jpeg"},
8071 {".jpm", 4, "image/jpm"},
8072 {".jpx", 4, "image/jpx"},
8073 {".png", 4, "image/png"},
8074 {".svg", 4, "image/svg+xml"},
8075 {".tif", 4, "image/tiff"},
8076 {".tiff", 5, "image/tiff"},
8077
8078 /* model */
8079 {".wrl", 4, "model/vrml"},
8080
8081 /* text */
8082 {".css", 4, "text/css"},
8083 {".csv", 4, "text/csv"},
8084 {".htm", 4, "text/html"},
8085 {".html", 5, "text/html"},
8086 {".sgm", 4, "text/sgml"},
8087 {".shtm", 5, "text/html"},
8088 {".shtml", 6, "text/html"},
8089 {".txt", 4, "text/plain"},
8090 {".xml", 4, "text/xml"},
8091
8092 /* video */
8093 {".mov", 4, "video/quicktime"},
8094 {".mp4", 4, "video/mp4"},
8095 {".mpeg", 5, "video/mpeg"},
8096 {".mpg", 4, "video/mpeg"},
8097 {".ogv", 4, "video/ogg"},
8098 {".qt", 3, "video/quicktime"},
8099
8100 /* not registered types
8101 * (http://reference.sitepoint.com/html/mime-types-full,
8102 * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
8103 {".arj", 4, "application/x-arj-compressed"},
8104 {".gz", 3, "application/x-gunzip"},
8105 {".rar", 4, "application/x-arj-compressed"},
8106 {".swf", 4, "application/x-shockwave-flash"},
8107 {".tar", 4, "application/x-tar"},
8108 {".tgz", 4, "application/x-tar-gz"},
8109 {".torrent", 8, "application/x-bittorrent"},
8110 {".ppt", 4, "application/x-mspowerpoint"},
8111 {".xls", 4, "application/x-msexcel"},
8112 {".zip", 4, "application/x-zip-compressed"},
8113 {".aac",
8114 4,
8115 "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
8116 {".flac", 5, "audio/flac"},
8117 {".aif", 4, "audio/x-aif"},
8118 {".m3u", 4, "audio/x-mpegurl"},
8119 {".mid", 4, "audio/x-midi"},
8120 {".ra", 3, "audio/x-pn-realaudio"},
8121 {".ram", 4, "audio/x-pn-realaudio"},
8122 {".wav", 4, "audio/x-wav"},
8123 {".bmp", 4, "image/bmp"},
8124 {".ico", 4, "image/x-icon"},
8125 {".pct", 4, "image/x-pct"},
8126 {".pict", 5, "image/pict"},
8127 {".rgb", 4, "image/x-rgb"},
8128 {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
8129 {".asf", 4, "video/x-ms-asf"},
8130 {".avi", 4, "video/x-msvideo"},
8131 {".m4v", 4, "video/x-m4v"},
8132 {NULL, 0, NULL}};
8133
8134
8135const char *
8137{
8138 const char *ext;
8139 size_t i, path_len;
8140
8141 path_len = strlen(path);
8142
8143 for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
8144 ext = path + (path_len - builtin_mime_types[i].ext_len);
8145 if ((path_len > builtin_mime_types[i].ext_len)
8146 && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
8147 return builtin_mime_types[i].mime_type;
8148 }
8149 }
8150
8151 return "text/plain";
8152}
8153
8154
8155/* Look at the "path" extension and figure what mime type it has.
8156 * Store mime type in the vector. */
8157static void
8158get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
8159{
8160 struct vec ext_vec, mime_vec;
8161 const char *list, *ext;
8162 size_t path_len;
8163
8164 path_len = strlen(path);
8165
8166 if ((conn == NULL) || (vec == NULL)) {
8167 if (vec != NULL) {
8168 memset(vec, '\0', sizeof(struct vec));
8169 }
8170 return;
8171 }
8172
8173 /* Scan user-defined mime types first, in case user wants to
8174 * override default mime types. */
8175 list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
8176 while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
8177 /* ext now points to the path suffix */
8178 ext = path + path_len - ext_vec.len;
8179 if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
8180 *vec = mime_vec;
8181 return;
8182 }
8183 }
8184
8186 vec->len = strlen(vec->ptr);
8187}
8188
8189
8190/* Stringify binary data. Output buffer must be twice as big as input,
8191 * because each byte takes 2 bytes in string representation */
8192static void
8193bin2str(char *to, const unsigned char *p, size_t len)
8194{
8195 static const char *hex = "0123456789abcdef";
8196
8197 for (; len--; p++) {
8198 *to++ = hex[p[0] >> 4];
8199 *to++ = hex[p[0] & 0x0f];
8200 }
8201 *to = '\0';
8202}
8203
8204
8205/* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
8206 */
8207char *
8208mg_md5(char buf[33], ...)
8209{
8210 md5_byte_t hash[16];
8211 const char *p;
8212 va_list ap;
8213 md5_state_t ctx;
8214
8215 md5_init(&ctx);
8216
8217 va_start(ap, buf);
8218 while ((p = va_arg(ap, const char *)) != NULL) {
8219 md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
8220 }
8221 va_end(ap);
8222
8223 md5_finish(&ctx, hash);
8224 bin2str(buf, hash, sizeof(hash));
8225 return buf;
8226}
8227
8228
8229/* Check the user's password, return 1 if OK */
8230static int
8231check_password(const char *method,
8232 const char *ha1,
8233 const char *uri,
8234 const char *nonce,
8235 const char *nc,
8236 const char *cnonce,
8237 const char *qop,
8238 const char *response)
8239{
8240 char ha2[32 + 1], expected_response[32 + 1];
8241
8242 /* Some of the parameters may be NULL */
8243 if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
8244 || (qop == NULL) || (response == NULL)) {
8245 return 0;
8246 }
8247
8248 /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
8249 if (strlen(response) != 32) {
8250 return 0;
8251 }
8252
8253 mg_md5(ha2, method, ":", uri, NULL);
8254 mg_md5(expected_response,
8255 ha1,
8256 ":",
8257 nonce,
8258 ":",
8259 nc,
8260 ":",
8261 cnonce,
8262 ":",
8263 qop,
8264 ":",
8265 ha2,
8266 NULL);
8267
8268 return mg_strcasecmp(response, expected_response) == 0;
8269}
8270
8271
8272#if !defined(NO_FILESYSTEMS)
8273/* Use the global passwords file, if specified by auth_gpass option,
8274 * or search for .htpasswd in the requested directory. */
8275static void
8277 const char *path,
8278 struct mg_file *filep)
8279{
8280 if ((conn != NULL) && (conn->dom_ctx != NULL)) {
8281 char name[UTF8_PATH_MAX];
8282 const char *p, *e,
8283 *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
8284 int truncated;
8285
8286 if (gpass != NULL) {
8287 /* Use global passwords file */
8288 if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
8289#if defined(DEBUG)
8290 /* Use mg_cry_internal here, since gpass has been
8291 * configured. */
8292 mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
8293#endif
8294 }
8295 /* Important: using local struct mg_file to test path for
8296 * is_directory flag. If filep is used, mg_stat() makes it
8297 * appear as if auth file was opened.
8298 * TODO(mid): Check if this is still required after rewriting
8299 * mg_stat */
8300 } else if (mg_stat(conn, path, &filep->stat)
8301 && filep->stat.is_directory) {
8302 mg_snprintf(conn,
8303 &truncated,
8304 name,
8305 sizeof(name),
8306 "%s/%s",
8307 path,
8309
8310 if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8311#if defined(DEBUG)
8312 /* Don't use mg_cry_internal here, but only a trace, since
8313 * this is a typical case. It will occur for every directory
8314 * without a password file. */
8315 DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8316#endif
8317 }
8318 } else {
8319 /* Try to find .htpasswd in requested directory. */
8320 for (p = path, e = p + strlen(p) - 1; e > p; e--) {
8321 if (e[0] == '/') {
8322 break;
8323 }
8324 }
8325 mg_snprintf(conn,
8326 &truncated,
8327 name,
8328 sizeof(name),
8329 "%.*s/%s",
8330 (int)(e - p),
8331 p,
8333
8334 if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8335#if defined(DEBUG)
8336 /* Don't use mg_cry_internal here, but only a trace, since
8337 * this is a typical case. It will occur for every directory
8338 * without a password file. */
8339 DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8340#endif
8341 }
8342 }
8343 }
8344}
8345#endif /* NO_FILESYSTEMS */
8346
8347
8348/* Parsed Authorization header */
8349struct ah {
8350 char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
8351};
8352
8353
8354/* Return 1 on success. Always initializes the ah structure. */
8355static int
8357 char *buf,
8358 size_t buf_size,
8359 struct ah *ah)
8360{
8361 char *name, *value, *s;
8362 const char *auth_header;
8363 uint64_t nonce;
8364
8365 if (!ah || !conn) {
8366 return 0;
8367 }
8368
8369 (void)memset(ah, 0, sizeof(*ah));
8370 if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
8371 || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
8372 return 0;
8373 }
8374
8375 /* Make modifiable copy of the auth header */
8376 (void)mg_strlcpy(buf, auth_header + 7, buf_size);
8377 s = buf;
8378
8379 /* Parse authorization header */
8380 for (;;) {
8381 /* Gobble initial spaces */
8382 while (isspace((unsigned char)*s)) {
8383 s++;
8384 }
8385 name = skip_quoted(&s, "=", " ", 0);
8386 /* Value is either quote-delimited, or ends at first comma or space.
8387 */
8388 if (s[0] == '\"') {
8389 s++;
8390 value = skip_quoted(&s, "\"", " ", '\\');
8391 if (s[0] == ',') {
8392 s++;
8393 }
8394 } else {
8395 value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
8396 * uses spaces */
8397 }
8398 if (*name == '\0') {
8399 break;
8400 }
8401
8402 if (!strcmp(name, "username")) {
8403 ah->user = value;
8404 } else if (!strcmp(name, "cnonce")) {
8405 ah->cnonce = value;
8406 } else if (!strcmp(name, "response")) {
8407 ah->response = value;
8408 } else if (!strcmp(name, "uri")) {
8409 ah->uri = value;
8410 } else if (!strcmp(name, "qop")) {
8411 ah->qop = value;
8412 } else if (!strcmp(name, "nc")) {
8413 ah->nc = value;
8414 } else if (!strcmp(name, "nonce")) {
8415 ah->nonce = value;
8416 }
8417 }
8418
8419#if !defined(NO_NONCE_CHECK)
8420 /* Read the nonce from the response. */
8421 if (ah->nonce == NULL) {
8422 return 0;
8423 }
8424 s = NULL;
8425 nonce = strtoull(ah->nonce, &s, 10);
8426 if ((s == NULL) || (*s != 0)) {
8427 return 0;
8428 }
8429
8430 /* Convert the nonce from the client to a number. */
8431 nonce ^= conn->dom_ctx->auth_nonce_mask;
8432
8433 /* The converted number corresponds to the time the nounce has been
8434 * created. This should not be earlier than the server start. */
8435 /* Server side nonce check is valuable in all situations but one:
8436 * if the server restarts frequently, but the client should not see
8437 * that, so the server should accept nonces from previous starts. */
8438 /* However, the reasonable default is to not accept a nonce from a
8439 * previous start, so if anyone changed the access rights between
8440 * two restarts, a new login is required. */
8441 if (nonce < (uint64_t)conn->phys_ctx->start_time) {
8442 /* nonce is from a previous start of the server and no longer valid
8443 * (replay attack?) */
8444 return 0;
8445 }
8446 /* Check if the nonce is too high, so it has not (yet) been used by the
8447 * server. */
8448 if (nonce >= ((uint64_t)conn->phys_ctx->start_time
8449 + conn->dom_ctx->nonce_count)) {
8450 return 0;
8451 }
8452#else
8453 (void)nonce;
8454#endif
8455
8456 /* CGI needs it as REMOTE_USER */
8457 if (ah->user != NULL) {
8459 mg_strdup_ctx(ah->user, conn->phys_ctx);
8460 } else {
8461 return 0;
8462 }
8463
8464 return 1;
8465}
8466
8467
8468static const char *
8469mg_fgets(char *buf, size_t size, struct mg_file *filep)
8470{
8471 if (!filep) {
8472 return NULL;
8473 }
8474
8475 if (filep->access.fp != NULL) {
8476 return fgets(buf, (int)size, filep->access.fp);
8477 } else {
8478 return NULL;
8479 }
8480}
8481
8482/* Define the initial recursion depth for procesesing htpasswd files that
8483 * include other htpasswd
8484 * (or even the same) files. It is not difficult to provide a file or files
8485 * s.t. they force civetweb
8486 * to infinitely recurse and then crash.
8487 */
8488#define INITIAL_DEPTH 9
8489#if INITIAL_DEPTH <= 0
8490#error Bad INITIAL_DEPTH for recursion, set to at least 1
8491#endif
8492
8493#if !defined(NO_FILESYSTEMS)
8496 struct ah ah;
8497 const char *domain;
8498 char buf[256 + 256 + 40];
8499 const char *f_user;
8500 const char *f_domain;
8501 const char *f_ha1;
8502};
8503
8504
8505static int
8507 struct read_auth_file_struct *workdata,
8508 int depth)
8509{
8510 int is_authorized = 0;
8511 struct mg_file fp;
8512 size_t l;
8513
8514 if (!filep || !workdata || (0 == depth)) {
8515 return 0;
8516 }
8517
8518 /* Loop over passwords file */
8519 while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
8520 l = strlen(workdata->buf);
8521 while (l > 0) {
8522 if (isspace((unsigned char)workdata->buf[l - 1])
8523 || iscntrl((unsigned char)workdata->buf[l - 1])) {
8524 l--;
8525 workdata->buf[l] = 0;
8526 } else
8527 break;
8528 }
8529 if (l < 1) {
8530 continue;
8531 }
8532
8533 workdata->f_user = workdata->buf;
8534
8535 if (workdata->f_user[0] == ':') {
8536 /* user names may not contain a ':' and may not be empty,
8537 * so lines starting with ':' may be used for a special purpose
8538 */
8539 if (workdata->f_user[1] == '#') {
8540 /* :# is a comment */
8541 continue;
8542 } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
8543 if (mg_fopen(workdata->conn,
8544 workdata->f_user + 9,
8546 &fp)) {
8547 is_authorized = read_auth_file(&fp, workdata, depth - 1);
8548 (void)mg_fclose(
8549 &fp.access); /* ignore error on read only file */
8550
8551 /* No need to continue processing files once we have a
8552 * match, since nothing will reset it back
8553 * to 0.
8554 */
8555 if (is_authorized) {
8556 return is_authorized;
8557 }
8558 } else {
8559 mg_cry_internal(workdata->conn,
8560 "%s: cannot open authorization file: %s",
8561 __func__,
8562 workdata->buf);
8563 }
8564 continue;
8565 }
8566 /* everything is invalid for the moment (might change in the
8567 * future) */
8568 mg_cry_internal(workdata->conn,
8569 "%s: syntax error in authorization file: %s",
8570 __func__,
8571 workdata->buf);
8572 continue;
8573 }
8574
8575 workdata->f_domain = strchr(workdata->f_user, ':');
8576 if (workdata->f_domain == NULL) {
8577 mg_cry_internal(workdata->conn,
8578 "%s: syntax error in authorization file: %s",
8579 __func__,
8580 workdata->buf);
8581 continue;
8582 }
8583 *(char *)(workdata->f_domain) = 0;
8584 (workdata->f_domain)++;
8585
8586 workdata->f_ha1 = strchr(workdata->f_domain, ':');
8587 if (workdata->f_ha1 == NULL) {
8588 mg_cry_internal(workdata->conn,
8589 "%s: syntax error in authorization file: %s",
8590 __func__,
8591 workdata->buf);
8592 continue;
8593 }
8594 *(char *)(workdata->f_ha1) = 0;
8595 (workdata->f_ha1)++;
8596
8597 if (!strcmp(workdata->ah.user, workdata->f_user)
8598 && !strcmp(workdata->domain, workdata->f_domain)) {
8600 workdata->f_ha1,
8601 workdata->ah.uri,
8602 workdata->ah.nonce,
8603 workdata->ah.nc,
8604 workdata->ah.cnonce,
8605 workdata->ah.qop,
8606 workdata->ah.response);
8607 }
8608 }
8609
8610 return is_authorized;
8611}
8612
8613
8614/* Authorize against the opened passwords file. Return 1 if authorized. */
8615static int
8616authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
8617{
8618 struct read_auth_file_struct workdata;
8619 char buf[MG_BUF_LEN];
8620
8621 if (!conn || !conn->dom_ctx) {
8622 return 0;
8623 }
8624
8625 memset(&workdata, 0, sizeof(workdata));
8626 workdata.conn = conn;
8627
8628 if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
8629 return 0;
8630 }
8631
8632 if (realm) {
8633 workdata.domain = realm;
8634 } else {
8636 }
8637
8638 return read_auth_file(filep, &workdata, INITIAL_DEPTH);
8639}
8640
8641
8642/* Public function to check http digest authentication header */
8643int
8645 const char *realm,
8646 const char *filename)
8647{
8648 struct mg_file file = STRUCT_FILE_INITIALIZER;
8649 int auth;
8650
8651 if (!conn || !filename) {
8652 return -1;
8653 }
8654 if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
8655 return -2;
8656 }
8657
8658 auth = authorize(conn, &file, realm);
8659
8660 mg_fclose(&file.access);
8661
8662 return auth;
8663}
8664#endif /* NO_FILESYSTEMS */
8665
8666
8667/* Return 1 if request is authorised, 0 otherwise. */
8668static int
8669check_authorization(struct mg_connection *conn, const char *path)
8670{
8671#if !defined(NO_FILESYSTEMS)
8672 char fname[UTF8_PATH_MAX];
8673 struct vec uri_vec, filename_vec;
8674 const char *list;
8675 struct mg_file file = STRUCT_FILE_INITIALIZER;
8676 int authorized = 1, truncated;
8677
8678 if (!conn || !conn->dom_ctx) {
8679 return 0;
8680 }
8681
8682 list = conn->dom_ctx->config[PROTECT_URI];
8683 while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
8684 if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
8685 mg_snprintf(conn,
8686 &truncated,
8687 fname,
8688 sizeof(fname),
8689 "%.*s",
8690 (int)filename_vec.len,
8691 filename_vec.ptr);
8692
8693 if (truncated
8694 || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
8695 mg_cry_internal(conn,
8696 "%s: cannot open %s: %s",
8697 __func__,
8698 fname,
8699 strerror(errno));
8700 }
8701 break;
8702 }
8703 }
8704
8705 if (!is_file_opened(&file.access)) {
8706 open_auth_file(conn, path, &file);
8707 }
8708
8709 if (is_file_opened(&file.access)) {
8710 authorized = authorize(conn, &file, NULL);
8711 (void)mg_fclose(&file.access); /* ignore error on read only file */
8712 }
8713
8714 return authorized;
8715#else
8716 (void)conn;
8717 (void)path;
8718 return 1;
8719#endif /* NO_FILESYSTEMS */
8720}
8721
8722
8723/* Internal function. Assumes conn is valid */
8724static void
8725send_authorization_request(struct mg_connection *conn, const char *realm)
8726{
8727 uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
8728 int trunc = 0;
8729 char buf[128];
8730
8731 if (!realm) {
8732 realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
8733 }
8734
8736 nonce += conn->dom_ctx->nonce_count;
8737 ++conn->dom_ctx->nonce_count;
8739
8740 nonce ^= conn->dom_ctx->auth_nonce_mask;
8741 conn->must_close = 1;
8742
8743 /* Create 401 response */
8744 mg_response_header_start(conn, 401);
8747 mg_response_header_add(conn, "Content-Length", "0", -1);
8748
8749 /* Content for "WWW-Authenticate" header */
8750 mg_snprintf(conn,
8751 &trunc,
8752 buf,
8753 sizeof(buf),
8754 "Digest qop=\"auth\", realm=\"%s\", "
8755 "nonce=\"%" UINT64_FMT "\"",
8756 realm,
8757 nonce);
8758
8759 if (!trunc) {
8760 /* !trunc should always be true */
8761 mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
8762 }
8763
8764 /* Send all headers */
8766}
8767
8768
8769/* Interface function. Parameters are provided by the user, so do
8770 * at least some basic checks.
8771 */
8772int
8774 const char *realm)
8775{
8776 if (conn && conn->dom_ctx) {
8777 send_authorization_request(conn, realm);
8778 return 0;
8779 }
8780 return -1;
8781}
8782
8783
8784#if !defined(NO_FILES)
8785static int
8787{
8788 if (conn) {
8789 struct mg_file file = STRUCT_FILE_INITIALIZER;
8790 const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
8791 int ret = 0;
8792
8793 if (passfile != NULL
8794 && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
8795 ret = authorize(conn, &file, NULL);
8796 (void)mg_fclose(&file.access); /* ignore error on read only file */
8797 }
8798
8799 return ret;
8800 }
8801 return 0;
8802}
8803#endif
8804
8805
8806static int
8807modify_passwords_file(const char *fname,
8808 const char *domain,
8809 const char *user,
8810 const char *pass,
8811 const char *ha1)
8812{
8813 int found, i;
8814 char line[512], u[512] = "", d[512] = "", ha1buf[33],
8815 tmp[UTF8_PATH_MAX + 8];
8816 FILE *fp, *fp2;
8817
8818 found = 0;
8819 fp = fp2 = NULL;
8820
8821 /* Regard empty password as no password - remove user record. */
8822 if ((pass != NULL) && (pass[0] == '\0')) {
8823 pass = NULL;
8824 }
8825
8826 /* Other arguments must not be empty */
8827 if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
8828 return 0;
8829 }
8830
8831 /* Using the given file format, user name and domain must not contain
8832 * ':'
8833 */
8834 if (strchr(user, ':') != NULL) {
8835 return 0;
8836 }
8837 if (strchr(domain, ':') != NULL) {
8838 return 0;
8839 }
8840
8841 /* Do not allow control characters like newline in user name and domain.
8842 * Do not allow excessively long names either. */
8843 for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
8844 if (iscntrl((unsigned char)user[i])) {
8845 return 0;
8846 }
8847 }
8848 if (user[i]) {
8849 return 0;
8850 }
8851 for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
8852 if (iscntrl((unsigned char)domain[i])) {
8853 return 0;
8854 }
8855 }
8856 if (domain[i]) {
8857 return 0;
8858 }
8859
8860 /* The maximum length of the path to the password file is limited */
8861 if ((strlen(fname) + 4) >= UTF8_PATH_MAX) {
8862 return 0;
8863 }
8864
8865 /* Create a temporary file name. Length has been checked before. */
8866 strcpy(tmp, fname);
8867 strcat(tmp, ".tmp");
8868
8869 /* Create the file if does not exist */
8870 /* Use of fopen here is OK, since fname is only ASCII */
8871 if ((fp = fopen(fname, "a+")) != NULL) {
8872 (void)fclose(fp);
8873 }
8874
8875 /* Open the given file and temporary file */
8876 if ((fp = fopen(fname, "r")) == NULL) {
8877 return 0;
8878 } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
8879 fclose(fp);
8880 return 0;
8881 }
8882
8883 /* Copy the stuff to temporary file */
8884 while (fgets(line, sizeof(line), fp) != NULL) {
8885 if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
8886 continue;
8887 }
8888 u[255] = 0;
8889 d[255] = 0;
8890
8891 if (!strcmp(u, user) && !strcmp(d, domain)) {
8892 found++;
8893 if (pass != NULL) {
8894 mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
8895 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1buf);
8896 } else if (ha1 != NULL) {
8897 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8898 }
8899 } else {
8900 fprintf(fp2, "%s", line);
8901 }
8902 }
8903
8904 /* If new user, just add it */
8905 if (!found) {
8906 if (pass != NULL) {
8907 mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
8908 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1buf);
8909 } else if (ha1 != NULL) {
8910 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8911 }
8912 }
8913
8914 /* Close files */
8915 fclose(fp);
8916 fclose(fp2);
8917
8918 /* Put the temp file in place of real file */
8919 IGNORE_UNUSED_RESULT(remove(fname));
8920 IGNORE_UNUSED_RESULT(rename(tmp, fname));
8921
8922 return 1;
8923}
8924
8925
8926int
8928 const char *domain,
8929 const char *user,
8930 const char *pass)
8931{
8932 return modify_passwords_file(fname, domain, user, pass, NULL);
8933}
8934
8935
8936int
8938 const char *domain,
8939 const char *user,
8940 const char *ha1)
8941{
8942 return modify_passwords_file(fname, domain, user, NULL, ha1);
8943}
8944
8945
8946static int
8947is_valid_port(unsigned long port)
8948{
8949 return (port <= 0xffff);
8950}
8951
8952
8953static int
8954mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
8955{
8956 struct addrinfo hints, *res, *ressave;
8957 int func_ret = 0;
8958 int gai_ret;
8959
8960 memset(&hints, 0, sizeof(struct addrinfo));
8961 hints.ai_family = af;
8962 if (!resolve_src) {
8963 hints.ai_flags = AI_NUMERICHOST;
8964 }
8965
8966 gai_ret = getaddrinfo(src, NULL, &hints, &res);
8967 if (gai_ret != 0) {
8968 /* gai_strerror could be used to convert gai_ret to a string */
8969 /* POSIX return values: see
8970 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
8971 */
8972 /* Windows return values: see
8973 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
8974 */
8975 return 0;
8976 }
8977
8978 ressave = res;
8979
8980 while (res) {
8981 if ((dstlen >= (size_t)res->ai_addrlen)
8982 && (res->ai_addr->sa_family == af)) {
8983 memcpy(dst, res->ai_addr, res->ai_addrlen);
8984 func_ret = 1;
8985 }
8986 res = res->ai_next;
8987 }
8988
8989 freeaddrinfo(ressave);
8990 return func_ret;
8991}
8992
8993
8994static int
8996 struct mg_context *ctx /* may be NULL */,
8997 const char *host,
8998 int port, /* 1..65535, or -99 for domain sockets (may be changed) */
8999 int use_ssl, /* 0 or 1 */
9000 char *ebuf,
9001 size_t ebuf_len,
9002 SOCKET *sock /* output: socket, must not be NULL */,
9003 union usa *sa /* output: socket address, must not be NULL */
9004)
9005{
9006 int ip_ver = 0;
9007 int conn_ret = -1;
9008 int sockerr = 0;
9009 *sock = INVALID_SOCKET;
9010 memset(sa, 0, sizeof(*sa));
9011
9012 if (ebuf_len > 0) {
9013 *ebuf = 0;
9014 }
9015
9016 if (host == NULL) {
9017 mg_snprintf(NULL,
9018 NULL, /* No truncation check for ebuf */
9019 ebuf,
9020 ebuf_len,
9021 "%s",
9022 "NULL host");
9023 return 0;
9024 }
9025
9026#if defined(USE_X_DOM_SOCKET)
9027 if (port == -99) {
9028 /* Unix domain socket */
9029 size_t hostlen = strlen(host);
9030 if (hostlen >= sizeof(sa->sun.sun_path)) {
9031 mg_snprintf(NULL,
9032 NULL, /* No truncation check for ebuf */
9033 ebuf,
9034 ebuf_len,
9035 "%s",
9036 "host length exceeds limit");
9037 return 0;
9038 }
9039 } else
9040#endif
9041 if ((port <= 0) || !is_valid_port((unsigned)port)) {
9042 mg_snprintf(NULL,
9043 NULL, /* No truncation check for ebuf */
9044 ebuf,
9045 ebuf_len,
9046 "%s",
9047 "invalid port");
9048 return 0;
9049 }
9050
9051#if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
9052#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
9053 if (use_ssl && (TLS_client_method == NULL)) {
9054 mg_snprintf(NULL,
9055 NULL, /* No truncation check for ebuf */
9056 ebuf,
9057 ebuf_len,
9058 "%s",
9059 "SSL is not initialized");
9060 return 0;
9061 }
9062#else
9063 if (use_ssl && (SSLv23_client_method == NULL)) {
9064 mg_snprintf(NULL,
9065 NULL, /* No truncation check for ebuf */
9066 ebuf,
9067 ebuf_len,
9068 "%s",
9069 "SSL is not initialized");
9070 return 0;
9071 }
9072#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
9073#else
9074 (void)use_ssl;
9075#endif /* NO SSL */
9076
9077
9078#if defined(USE_X_DOM_SOCKET)
9079 if (port == -99) {
9080 size_t hostlen = strlen(host);
9081 /* check (hostlen < sizeof(sun.sun_path)) already passed above */
9082 ip_ver = -99;
9083 sa->sun.sun_family = AF_UNIX;
9084 memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
9085 memcpy(sa->sun.sun_path, host, hostlen);
9086 } else
9087#endif
9088 if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
9089 sa->sin.sin_port = htons((uint16_t)port);
9090 ip_ver = 4;
9091#if defined(USE_IPV6)
9092 } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
9093 sa->sin6.sin6_port = htons((uint16_t)port);
9094 ip_ver = 6;
9095 } else if (host[0] == '[') {
9096 /* While getaddrinfo on Windows will work with [::1],
9097 * getaddrinfo on Linux only works with ::1 (without []). */
9098 size_t l = strlen(host + 1);
9099 char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
9100 if (h) {
9101 h[l - 1] = 0;
9102 if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
9103 sa->sin6.sin6_port = htons((uint16_t)port);
9104 ip_ver = 6;
9105 }
9106 mg_free(h);
9107 }
9108#endif
9109 }
9110
9111 if (ip_ver == 0) {
9112 mg_snprintf(NULL,
9113 NULL, /* No truncation check for ebuf */
9114 ebuf,
9115 ebuf_len,
9116 "%s",
9117 "host not found");
9118 return 0;
9119 }
9120
9121 if (ip_ver == 4) {
9122 *sock = socket(PF_INET, SOCK_STREAM, 0);
9123 }
9124#if defined(USE_IPV6)
9125 else if (ip_ver == 6) {
9126 *sock = socket(PF_INET6, SOCK_STREAM, 0);
9127 }
9128#endif
9129#if defined(USE_X_DOM_SOCKET)
9130 else if (ip_ver == -99) {
9131 *sock = socket(AF_UNIX, SOCK_STREAM, 0);
9132 }
9133#endif
9134
9135 if (*sock == INVALID_SOCKET) {
9136 mg_snprintf(NULL,
9137 NULL, /* No truncation check for ebuf */
9138 ebuf,
9139 ebuf_len,
9140 "socket(): %s",
9141 strerror(ERRNO));
9142 return 0;
9143 }
9144
9145 if (0 != set_non_blocking_mode(*sock)) {
9146 mg_snprintf(NULL,
9147 NULL, /* No truncation check for ebuf */
9148 ebuf,
9149 ebuf_len,
9150 "Cannot set socket to non-blocking: %s",
9151 strerror(ERRNO));
9152 closesocket(*sock);
9153 *sock = INVALID_SOCKET;
9154 return 0;
9155 }
9156
9157 set_close_on_exec(*sock, NULL, ctx);
9158
9159 if (ip_ver == 4) {
9160 /* connected with IPv4 */
9161 conn_ret = connect(*sock,
9162 (struct sockaddr *)((void *)&sa->sin),
9163 sizeof(sa->sin));
9164 }
9165#if defined(USE_IPV6)
9166 else if (ip_ver == 6) {
9167 /* connected with IPv6 */
9168 conn_ret = connect(*sock,
9169 (struct sockaddr *)((void *)&sa->sin6),
9170 sizeof(sa->sin6));
9171 }
9172#endif
9173#if defined(USE_X_DOM_SOCKET)
9174 else if (ip_ver == -99) {
9175 /* connected to domain socket */
9176 conn_ret = connect(*sock,
9177 (struct sockaddr *)((void *)&sa->sun),
9178 sizeof(sa->sun));
9179 }
9180#endif
9181
9182 if (conn_ret != 0) {
9183 sockerr = ERRNO;
9184 }
9185
9186#if defined(_WIN32)
9187 if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
9188#else
9189 if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
9190#endif
9191 /* Data for getsockopt */
9192 void *psockerr = &sockerr;
9193 int ret;
9194
9195#if defined(_WIN32)
9196 int len = (int)sizeof(sockerr);
9197#else
9198 socklen_t len = (socklen_t)sizeof(sockerr);
9199#endif
9200
9201 /* Data for poll */
9202 struct mg_pollfd pfd[1];
9203 int pollres;
9204 int ms_wait = 10000; /* 10 second timeout */
9205 stop_flag_t nonstop;
9206 STOP_FLAG_ASSIGN(&nonstop, 0);
9207
9208 /* For a non-blocking socket, the connect sequence is:
9209 * 1) call connect (will not block)
9210 * 2) wait until the socket is ready for writing (select or poll)
9211 * 3) check connection state with getsockopt
9212 */
9213 pfd[0].fd = *sock;
9214 pfd[0].events = POLLOUT;
9215 pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
9216
9217 if (pollres != 1) {
9218 /* Not connected */
9219 mg_snprintf(NULL,
9220 NULL, /* No truncation check for ebuf */
9221 ebuf,
9222 ebuf_len,
9223 "connect(%s:%d): timeout",
9224 host,
9225 port);
9226 closesocket(*sock);
9227 *sock = INVALID_SOCKET;
9228 return 0;
9229 }
9230
9231#if defined(_WIN32)
9232 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
9233#else
9234 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
9235#endif
9236
9237 if ((ret == 0) && (sockerr == 0)) {
9238 conn_ret = 0;
9239 }
9240 }
9241
9242 if (conn_ret != 0) {
9243 /* Not connected */
9244 mg_snprintf(NULL,
9245 NULL, /* No truncation check for ebuf */
9246 ebuf,
9247 ebuf_len,
9248 "connect(%s:%d): error %s",
9249 host,
9250 port,
9251 strerror(sockerr));
9252 closesocket(*sock);
9253 *sock = INVALID_SOCKET;
9254 return 0;
9255 }
9256
9257 return 1;
9258}
9259
9260
9261int
9262mg_url_encode(const char *src, char *dst, size_t dst_len)
9263{
9264 static const char *dont_escape = "._-$,;~()";
9265 static const char *hex = "0123456789abcdef";
9266 char *pos = dst;
9267 const char *end = dst + dst_len - 1;
9268
9269 for (; ((*src != '\0') && (pos < end)); src++, pos++) {
9270 if (isalnum((unsigned char)*src)
9271 || (strchr(dont_escape, *src) != NULL)) {
9272 *pos = *src;
9273 } else if (pos + 2 < end) {
9274 pos[0] = '%';
9275 pos[1] = hex[(unsigned char)*src >> 4];
9276 pos[2] = hex[(unsigned char)*src & 0xf];
9277 pos += 2;
9278 } else {
9279 break;
9280 }
9281 }
9282
9283 *pos = '\0';
9284 return (*src == '\0') ? (int)(pos - dst) : -1;
9285}
9286
9287/* Return 0 on success, non-zero if an error occurs. */
9288
9289static int
9291{
9292 size_t namesize, escsize, i;
9293 char *href, *esc, *p;
9294 char size[64], mod[64];
9295#if defined(REENTRANT_TIME)
9296 struct tm _tm;
9297 struct tm *tm = &_tm;
9298#else
9299 struct tm *tm;
9300#endif
9301
9302 /* Estimate worst case size for encoding and escaping */
9303 namesize = strlen(de->file_name) + 1;
9304 escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
9305 href = (char *)mg_malloc(namesize * 3 + escsize);
9306 if (href == NULL) {
9307 return -1;
9308 }
9309 mg_url_encode(de->file_name, href, namesize * 3);
9310 esc = NULL;
9311 if (escsize > 0) {
9312 /* HTML escaping needed */
9313 esc = href + namesize * 3;
9314 for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
9315 mg_strlcpy(p, de->file_name + i, 2);
9316 if (*p == '&') {
9317 strcpy(p, "&amp;");
9318 } else if (*p == '<') {
9319 strcpy(p, "&lt;");
9320 } else if (*p == '>') {
9321 strcpy(p, "&gt;");
9322 }
9323 }
9324 }
9325
9326 if (de->file.is_directory) {
9328 NULL, /* Buffer is big enough */
9329 size,
9330 sizeof(size),
9331 "%s",
9332 "[DIRECTORY]");
9333 } else {
9334 /* We use (signed) cast below because MSVC 6 compiler cannot
9335 * convert unsigned __int64 to double. Sigh. */
9336 if (de->file.size < 1024) {
9338 NULL, /* Buffer is big enough */
9339 size,
9340 sizeof(size),
9341 "%d",
9342 (int)de->file.size);
9343 } else if (de->file.size < 0x100000) {
9345 NULL, /* Buffer is big enough */
9346 size,
9347 sizeof(size),
9348 "%.1fk",
9349 (double)de->file.size / 1024.0);
9350 } else if (de->file.size < 0x40000000) {
9352 NULL, /* Buffer is big enough */
9353 size,
9354 sizeof(size),
9355 "%.1fM",
9356 (double)de->file.size / 1048576);
9357 } else {
9359 NULL, /* Buffer is big enough */
9360 size,
9361 sizeof(size),
9362 "%.1fG",
9363 (double)de->file.size / 1073741824);
9364 }
9365 }
9366
9367 /* Note: mg_snprintf will not cause a buffer overflow above.
9368 * So, string truncation checks are not required here. */
9369
9370#if defined(REENTRANT_TIME)
9371 localtime_r(&de->file.last_modified, tm);
9372#else
9373 tm = localtime(&de->file.last_modified);
9374#endif
9375 if (tm != NULL) {
9376 strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
9377 } else {
9378 mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
9379 mod[sizeof(mod) - 1] = '\0';
9380 }
9381 mg_printf(de->conn,
9382 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
9383 "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
9384 href,
9385 de->file.is_directory ? "/" : "",
9386 esc ? esc : de->file_name,
9387 de->file.is_directory ? "/" : "",
9388 mod,
9389 size);
9390 mg_free(href);
9391 return 0;
9392}
9393
9394
9395/* This function is called from send_directory() and used for
9396 * sorting directory entries by size, or name, or modification time.
9397 * On windows, __cdecl specification is needed in case if project is built
9398 * with __stdcall convention. qsort always requires __cdels callback. */
9399static int WINCDECL
9400compare_dir_entries(const void *p1, const void *p2)
9401{
9402 if (p1 && p2) {
9403 const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
9404 const char *query_string = a->conn->request_info.query_string;
9405 int cmp_result = 0;
9406
9407 if ((query_string == NULL) || (query_string[0] == '\0')) {
9408 query_string = "n";
9409 }
9410
9411 if (a->file.is_directory && !b->file.is_directory) {
9412 return -1; /* Always put directories on top */
9413 } else if (!a->file.is_directory && b->file.is_directory) {
9414 return 1; /* Always put directories on top */
9415 } else if (*query_string == 'n') {
9416 cmp_result = strcmp(a->file_name, b->file_name);
9417 } else if (*query_string == 's') {
9418 cmp_result = (a->file.size == b->file.size)
9419 ? 0
9420 : ((a->file.size > b->file.size) ? 1 : -1);
9421 } else if (*query_string == 'd') {
9422 cmp_result =
9423 (a->file.last_modified == b->file.last_modified)
9424 ? 0
9425 : ((a->file.last_modified > b->file.last_modified) ? 1
9426 : -1);
9427 }
9428
9429 return (query_string[1] == 'd') ? -cmp_result : cmp_result;
9430 }
9431 return 0;
9432}
9433
9434
9435static int
9436must_hide_file(struct mg_connection *conn, const char *path)
9437{
9438 if (conn && conn->dom_ctx) {
9439 const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
9440 const char *pattern = conn->dom_ctx->config[HIDE_FILES];
9441 return (match_prefix_strlen(pw_pattern, path) > 0)
9442 || (match_prefix_strlen(pattern, path) > 0);
9443 }
9444 return 0;
9445}
9446
9447
9448#if !defined(NO_FILESYSTEMS)
9449static int
9451 const char *dir,
9452 void *data,
9453 int (*cb)(struct de *, void *))
9454{
9455 char path[UTF8_PATH_MAX];
9456 struct dirent *dp;
9457 DIR *dirp;
9458 struct de de;
9459 int truncated;
9460
9461 if ((dirp = mg_opendir(conn, dir)) == NULL) {
9462 return 0;
9463 } else {
9464 de.conn = conn;
9465
9466 while ((dp = mg_readdir(dirp)) != NULL) {
9467 /* Do not show current dir and hidden files */
9468 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
9469 || must_hide_file(conn, dp->d_name)) {
9470 continue;
9471 }
9472
9474 conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9475
9476 /* If we don't memset stat structure to zero, mtime will have
9477 * garbage and strftime() will segfault later on in
9478 * print_dir_entry(). memset is required only if mg_stat()
9479 * fails. For more details, see
9480 * http://code.google.com/p/mongoose/issues/detail?id=79 */
9481 memset(&de.file, 0, sizeof(de.file));
9482
9483 if (truncated) {
9484 /* If the path is not complete, skip processing. */
9485 continue;
9486 }
9487
9488 if (!mg_stat(conn, path, &de.file)) {
9490 "%s: mg_stat(%s) failed: %s",
9491 __func__,
9492 path,
9493 strerror(ERRNO));
9494 }
9495 de.file_name = dp->d_name;
9496 if (cb(&de, data)) {
9497 /* stopped */
9498 break;
9499 }
9500 }
9501 (void)mg_closedir(dirp);
9502 }
9503 return 1;
9504}
9505#endif /* NO_FILESYSTEMS */
9506
9507
9508#if !defined(NO_FILES)
9509static int
9510remove_directory(struct mg_connection *conn, const char *dir)
9511{
9512 char path[UTF8_PATH_MAX];
9513 struct dirent *dp;
9514 DIR *dirp;
9515 struct de de;
9516 int truncated;
9517 int ok = 1;
9518
9519 if ((dirp = mg_opendir(conn, dir)) == NULL) {
9520 return 0;
9521 } else {
9522 de.conn = conn;
9523
9524 while ((dp = mg_readdir(dirp)) != NULL) {
9525 /* Do not show current dir (but show hidden files as they will
9526 * also be removed) */
9527 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
9528 continue;
9529 }
9530
9532 conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9533
9534 /* If we don't memset stat structure to zero, mtime will have
9535 * garbage and strftime() will segfault later on in
9536 * print_dir_entry(). memset is required only if mg_stat()
9537 * fails. For more details, see
9538 * http://code.google.com/p/mongoose/issues/detail?id=79 */
9539 memset(&de.file, 0, sizeof(de.file));
9540
9541 if (truncated) {
9542 /* Do not delete anything shorter */
9543 ok = 0;
9544 continue;
9545 }
9546
9547 if (!mg_stat(conn, path, &de.file)) {
9549 "%s: mg_stat(%s) failed: %s",
9550 __func__,
9551 path,
9552 strerror(ERRNO));
9553 ok = 0;
9554 }
9555
9556 if (de.file.is_directory) {
9557 if (remove_directory(conn, path) == 0) {
9558 ok = 0;
9559 }
9560 } else {
9561 /* This will fail file is the file is in memory */
9562 if (mg_remove(conn, path) == 0) {
9563 ok = 0;
9564 }
9565 }
9566 }
9567 (void)mg_closedir(dirp);
9568
9569 IGNORE_UNUSED_RESULT(rmdir(dir));
9570 }
9571
9572 return ok;
9573}
9574#endif
9575
9576
9578 struct de *entries;
9580 size_t arr_size;
9581};
9582
9583
9584#if !defined(NO_FILESYSTEMS)
9585static int
9587{
9588 struct dir_scan_data *dsd = (struct dir_scan_data *)data;
9589 struct de *entries = dsd->entries;
9590
9591 if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
9592 /* Here "entries" is a temporary pointer and can be replaced,
9593 * "dsd->entries" is the original pointer */
9594 entries =
9595 (struct de *)mg_realloc(entries,
9596 dsd->arr_size * 2 * sizeof(entries[0]));
9597 if (entries == NULL) {
9598 /* stop scan */
9599 return 1;
9600 }
9601 dsd->entries = entries;
9602 dsd->arr_size *= 2;
9603 }
9604 entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
9605 if (entries[dsd->num_entries].file_name == NULL) {
9606 /* stop scan */
9607 return 1;
9608 }
9609 entries[dsd->num_entries].file = de->file;
9610 entries[dsd->num_entries].conn = de->conn;
9611 dsd->num_entries++;
9612
9613 return 0;
9614}
9615
9616
9617static void
9619{
9620 size_t i;
9621 int sort_direction;
9622 struct dir_scan_data data = {NULL, 0, 128};
9623 char date[64], *esc, *p;
9624 const char *title;
9625 time_t curtime = time(NULL);
9626
9627 if (!conn) {
9628 return;
9629 }
9630
9631 if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
9632 mg_send_http_error(conn,
9633 500,
9634 "Error: Cannot open directory\nopendir(%s): %s",
9635 dir,
9636 strerror(ERRNO));
9637 return;
9638 }
9639
9640 gmt_time_string(date, sizeof(date), &curtime);
9641
9642 esc = NULL;
9643 title = conn->request_info.local_uri;
9644 if (title[strcspn(title, "&<>")]) {
9645 /* HTML escaping needed */
9646 esc = (char *)mg_malloc(strlen(title) * 5 + 1);
9647 if (esc) {
9648 for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
9649 mg_strlcpy(p, title + i, 2);
9650 if (*p == '&') {
9651 strcpy(p, "&amp;");
9652 } else if (*p == '<') {
9653 strcpy(p, "&lt;");
9654 } else if (*p == '>') {
9655 strcpy(p, "&gt;");
9656 }
9657 }
9658 } else {
9659 title = "";
9660 }
9661 }
9662
9663 sort_direction = ((conn->request_info.query_string != NULL)
9664 && (conn->request_info.query_string[0] != '\0')
9665 && (conn->request_info.query_string[1] == 'd'))
9666 ? 'a'
9667 : 'd';
9668
9669 conn->must_close = 1;
9670
9671 /* Create 200 OK response */
9672 mg_response_header_start(conn, 200);
9676 "Content-Type",
9677 "text/html; charset=utf-8",
9678 -1);
9679
9680 /* Send all headers */
9682
9683 /* Body */
9684 mg_printf(conn,
9685 "<html><head><title>Index of %s</title>"
9686 "<style>th {text-align: left;}</style></head>"
9687 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
9688 "<tr><th><a href=\"?n%c\">Name</a></th>"
9689 "<th><a href=\"?d%c\">Modified</a></th>"
9690 "<th><a href=\"?s%c\">Size</a></th></tr>"
9691 "<tr><td colspan=\"3\"><hr></td></tr>",
9692 esc ? esc : title,
9693 esc ? esc : title,
9694 sort_direction,
9695 sort_direction,
9696 sort_direction);
9697 mg_free(esc);
9698
9699 /* Print first entry - link to a parent directory */
9700 mg_printf(conn,
9701 "<tr><td><a href=\"%s\">%s</a></td>"
9702 "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
9703 "..",
9704 "Parent directory",
9705 "-",
9706 "-");
9707
9708 /* Sort and print directory entries */
9709 if (data.entries != NULL) {
9710 qsort(data.entries,
9711 data.num_entries,
9712 sizeof(data.entries[0]),
9714 for (i = 0; i < data.num_entries; i++) {
9715 print_dir_entry(&data.entries[i]);
9716 mg_free(data.entries[i].file_name);
9717 }
9718 mg_free(data.entries);
9719 }
9720
9721 mg_printf(conn, "%s", "</table></pre></body></html>");
9722 conn->status_code = 200;
9723}
9724#endif /* NO_FILESYSTEMS */
9725
9726
9727/* Send len bytes from the opened file to the client. */
9728static void
9730 struct mg_file *filep,
9731 int64_t offset,
9732 int64_t len)
9733{
9734 char buf[MG_BUF_LEN];
9735 int to_read, num_read, num_written;
9736 int64_t size;
9737
9738 if (!filep || !conn) {
9739 return;
9740 }
9741
9742 /* Sanity check the offset */
9743 size = (filep->stat.size > INT64_MAX) ? INT64_MAX
9744 : (int64_t)(filep->stat.size);
9745 offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
9746
9747 if (len > 0 && filep->access.fp != NULL) {
9748 /* file stored on disk */
9749#if defined(__linux__)
9750 /* sendfile is only available for Linux */
9751 if ((conn->ssl == 0) && (conn->throttle == 0)
9752 && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
9753 "yes"))) {
9754 off_t sf_offs = (off_t)offset;
9755 ssize_t sf_sent;
9756 int sf_file = fileno(filep->access.fp);
9757 int loop_cnt = 0;
9758
9759 do {
9760 /* 2147479552 (0x7FFFF000) is a limit found by experiment on
9761 * 64 bit Linux (2^31 minus one memory page of 4k?). */
9762 size_t sf_tosend =
9763 (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
9764 sf_sent =
9765 sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
9766 if (sf_sent > 0) {
9767 len -= sf_sent;
9768 offset += sf_sent;
9769 } else if (loop_cnt == 0) {
9770 /* This file can not be sent using sendfile.
9771 * This might be the case for pseudo-files in the
9772 * /sys/ and /proc/ file system.
9773 * Use the regular user mode copy code instead. */
9774 break;
9775 } else if (sf_sent == 0) {
9776 /* No error, but 0 bytes sent. May be EOF? */
9777 return;
9778 }
9779 loop_cnt++;
9780
9781 } while ((len > 0) && (sf_sent >= 0));
9782
9783 if (sf_sent > 0) {
9784 return; /* OK */
9785 }
9786
9787 /* sf_sent<0 means error, thus fall back to the classic way */
9788 /* This is always the case, if sf_file is not a "normal" file,
9789 * e.g., for sending data from the output of a CGI process. */
9790 offset = (int64_t)sf_offs;
9791 }
9792#endif
9793 if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
9794 mg_cry_internal(conn,
9795 "%s: fseeko() failed: %s",
9796 __func__,
9797 strerror(ERRNO));
9799 conn,
9800 500,
9801 "%s",
9802 "Error: Unable to access file at requested position.");
9803 } else {
9804 while (len > 0) {
9805 /* Calculate how much to read from the file in the buffer */
9806 to_read = sizeof(buf);
9807 if ((int64_t)to_read > len) {
9808 to_read = (int)len;
9809 }
9810
9811 /* Read from file, exit the loop on error */
9812 if ((num_read =
9813 (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
9814 <= 0) {
9815 break;
9816 }
9817
9818 /* Send read bytes to the client, exit the loop on error */
9819 if ((num_written = mg_write(conn, buf, (size_t)num_read))
9820 != num_read) {
9821 break;
9822 }
9823
9824 /* Both read and were successful, adjust counters */
9825 len -= num_written;
9826 }
9827 }
9828 }
9829}
9830
9831
9832static int
9833parse_range_header(const char *header, int64_t *a, int64_t *b)
9834{
9835 return sscanf(header,
9836 "bytes=%" INT64_FMT "-%" INT64_FMT,
9837 a,
9838 b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
9839 // to an integer value, but function will not report
9840 // conversion errors; consider using 'strtol' instead
9841}
9842
9843
9844static void
9845construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
9846{
9847 if ((filestat != NULL) && (buf != NULL)) {
9848 mg_snprintf(NULL,
9849 NULL, /* All calls to construct_etag use 64 byte buffer */
9850 buf,
9851 buf_len,
9852 "\"%lx.%" INT64_FMT "\"",
9853 (unsigned long)filestat->last_modified,
9854 filestat->size);
9855 }
9856}
9857
9858
9859static void
9860fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
9861{
9862 if (filep != NULL && filep->fp != NULL) {
9863#if defined(_WIN32)
9864 (void)conn; /* Unused. */
9865#else
9866 if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
9867 mg_cry_internal(conn,
9868 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
9869 __func__,
9870 strerror(ERRNO));
9871 }
9872#endif
9873 }
9874}
9875
9876
9877#if defined(USE_ZLIB)
9878#include "mod_zlib.inl"
9879#endif
9880
9881
9882#if !defined(NO_FILESYSTEMS)
9883static void
9885 const char *path,
9886 struct mg_file *filep,
9887 const char *mime_type,
9888 const char *additional_headers)
9889{
9890 char lm[64], etag[64];
9891 char range[128]; /* large enough, so there will be no overflow */
9892 const char *range_hdr;
9893 int64_t cl, r1, r2;
9894 struct vec mime_vec;
9895 int n, truncated;
9896 char gz_path[UTF8_PATH_MAX];
9897 const char *encoding = 0;
9898 const char *origin_hdr;
9899 const char *cors_orig_cfg, *cors_cred_cfg;
9900 const char *cors1, *cors2, *cors3, *cors4;
9901 int is_head_request;
9902
9903#if defined(USE_ZLIB)
9904 /* Compression is allowed, unless there is a reason not to use
9905 * compression. If the file is already compressed, too small or a
9906 * "range" request was made, on the fly compression is not possible. */
9907 int allow_on_the_fly_compression = 1;
9908#endif
9909
9910 if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
9911 return;
9912 }
9913
9914 is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
9915
9916 if (mime_type == NULL) {
9917 get_mime_type(conn, path, &mime_vec);
9918 } else {
9919 mime_vec.ptr = mime_type;
9920 mime_vec.len = strlen(mime_type);
9921 }
9922 if (filep->stat.size > INT64_MAX) {
9923 mg_send_http_error(conn,
9924 500,
9925 "Error: File size is too large to send\n%" INT64_FMT,
9926 filep->stat.size);
9927 return;
9928 }
9929 cl = (int64_t)filep->stat.size;
9930 conn->status_code = 200;
9931 range[0] = '\0';
9932
9933#if defined(USE_ZLIB)
9934 /* if this file is in fact a pre-gzipped file, rewrite its filename
9935 * it's important to rewrite the filename after resolving
9936 * the mime type from it, to preserve the actual file's type */
9937 if (!conn->accept_gzip) {
9938 allow_on_the_fly_compression = 0;
9939 }
9940#endif
9941
9942 /* Check if there is a range header */
9943 range_hdr = mg_get_header(conn, "Range");
9944
9945 /* For gzipped files, add *.gz */
9946 if (filep->stat.is_gzipped) {
9947 mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
9948
9949 if (truncated) {
9950 mg_send_http_error(conn,
9951 500,
9952 "Error: Path of zipped file too long (%s)",
9953 path);
9954 return;
9955 }
9956
9957 path = gz_path;
9958 encoding = "gzip";
9959
9960#if defined(USE_ZLIB)
9961 /* File is already compressed. No "on the fly" compression. */
9962 allow_on_the_fly_compression = 0;
9963#endif
9964 } else if ((conn->accept_gzip) && (range_hdr == NULL)
9965 && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
9966 struct mg_file_stat file_stat;
9967
9968 mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
9969
9970 if (!truncated && mg_stat(conn, gz_path, &file_stat)
9971 && !file_stat.is_directory) {
9972 file_stat.is_gzipped = 1;
9973 filep->stat = file_stat;
9974 cl = (int64_t)filep->stat.size;
9975 path = gz_path;
9976 encoding = "gzip";
9977
9978#if defined(USE_ZLIB)
9979 /* File is already compressed. No "on the fly" compression. */
9980 allow_on_the_fly_compression = 0;
9981#endif
9982 }
9983 }
9984
9985 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
9986 mg_send_http_error(conn,
9987 500,
9988 "Error: Cannot open file\nfopen(%s): %s",
9989 path,
9990 strerror(ERRNO));
9991 return;
9992 }
9993
9994 fclose_on_exec(&filep->access, conn);
9995
9996 /* If "Range" request was made: parse header, send only selected part
9997 * of the file. */
9998 r1 = r2 = 0;
9999 if ((range_hdr != NULL)
10000 && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
10001 && (r2 >= 0)) {
10002 /* actually, range requests don't play well with a pre-gzipped
10003 * file (since the range is specified in the uncompressed space) */
10004 if (filep->stat.is_gzipped) {
10006 conn,
10007 416, /* 416 = Range Not Satisfiable */
10008 "%s",
10009 "Error: Range requests in gzipped files are not supported");
10010 (void)mg_fclose(
10011 &filep->access); /* ignore error on read only file */
10012 return;
10013 }
10014 conn->status_code = 206;
10015 cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
10016 mg_snprintf(conn,
10017 NULL, /* range buffer is big enough */
10018 range,
10019 sizeof(range),
10020 "bytes "
10021 "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
10022 r1,
10023 r1 + cl - 1,
10024 filep->stat.size);
10025
10026#if defined(USE_ZLIB)
10027 /* Do not compress ranges. */
10028 allow_on_the_fly_compression = 0;
10029#endif
10030 }
10031
10032 /* Do not compress small files. Small files do not benefit from file
10033 * compression, but there is still some overhead. */
10034#if defined(USE_ZLIB)
10036 /* File is below the size limit. */
10037 allow_on_the_fly_compression = 0;
10038 }
10039#endif
10040
10041 /* Standard CORS header */
10042 cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
10043 origin_hdr = mg_get_header(conn, "Origin");
10044 if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
10045 /* Cross-origin resource sharing (CORS), see
10046 * http://www.html5rocks.com/en/tutorials/cors/,
10047 * http://www.html5rocks.com/static/images/cors_server_flowchart.png
10048 * -
10049 * preflight is not supported for files. */
10050 cors1 = "Access-Control-Allow-Origin";
10051 cors2 = cors_orig_cfg;
10052 } else {
10053 cors1 = cors2 = "";
10054 }
10055
10056 /* Credentials CORS header */
10057 cors_cred_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
10058 if (cors_cred_cfg && *cors_cred_cfg && origin_hdr) {
10059 cors3 = "Access-Control-Allow-Credentials";
10060 cors4 = cors_cred_cfg;
10061 } else {
10062 cors3 = cors4 = "";
10063 }
10064
10065 /* Prepare Etag, and Last-Modified headers. */
10066 gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
10067 construct_etag(etag, sizeof(etag), &filep->stat);
10068
10069 /* Create 2xx (200, 206) response */
10074 "Content-Type",
10075 mime_vec.ptr,
10076 (int)mime_vec.len);
10077 if (cors1[0] != 0) {
10078 mg_response_header_add(conn, cors1, cors2, -1);
10079 }
10080 if (cors3[0] != 0) {
10081 mg_response_header_add(conn, cors3, cors4, -1);
10082 }
10083 mg_response_header_add(conn, "Last-Modified", lm, -1);
10084 mg_response_header_add(conn, "Etag", etag, -1);
10085
10086#if defined(USE_ZLIB)
10087 /* On the fly compression allowed */
10088 if (allow_on_the_fly_compression) {
10089 /* For on the fly compression, we don't know the content size in
10090 * advance, so we have to use chunked encoding */
10091 encoding = "gzip";
10092 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
10093 /* HTTP/2 is always using "chunks" (frames) */
10094 mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
10095 }
10096
10097 } else
10098#endif
10099 {
10100 /* Without on-the-fly compression, we know the content-length
10101 * and we can use ranges (with on-the-fly compression we cannot).
10102 * So we send these response headers only in this case. */
10103 char len[32];
10104 int trunc = 0;
10105 mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
10106
10107 if (!trunc) {
10108 mg_response_header_add(conn, "Content-Length", len, -1);
10109 }
10110
10111 mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
10112 }
10113
10114 if (encoding) {
10115 mg_response_header_add(conn, "Content-Encoding", encoding, -1);
10116 }
10117 if (range[0] != 0) {
10118 mg_response_header_add(conn, "Content-Range", range, -1);
10119 }
10120
10121 /* The code above does not add any header starting with X- to make
10122 * sure no one of the additional_headers is included twice */
10123 if ((additional_headers != NULL) && (*additional_headers != 0)) {
10124 mg_response_header_add_lines(conn, additional_headers);
10125 }
10126
10127 /* Send all headers */
10129
10130 if (!is_head_request) {
10131#if defined(USE_ZLIB)
10132 if (allow_on_the_fly_compression) {
10133 /* Compress and send */
10134 send_compressed_data(conn, filep);
10135 } else
10136#endif
10137 {
10138 /* Send file directly */
10139 send_file_data(conn, filep, r1, cl);
10140 }
10141 }
10142 (void)mg_fclose(&filep->access); /* ignore error on read only file */
10143}
10144
10145
10146int
10147mg_send_file_body(struct mg_connection *conn, const char *path)
10148{
10149 struct mg_file file = STRUCT_FILE_INITIALIZER;
10150 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
10151 return -1;
10152 }
10153 fclose_on_exec(&file.access, conn);
10154 send_file_data(conn, &file, 0, INT64_MAX);
10155 (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
10156 return 0; /* >= 0 for OK */
10157}
10158#endif /* NO_FILESYSTEMS */
10159
10160
10161#if !defined(NO_CACHING)
10162/* Return True if we should reply 304 Not Modified. */
10163static int
10165 const struct mg_file_stat *filestat)
10166{
10167 char etag[64];
10168 const char *ims = mg_get_header(conn, "If-Modified-Since");
10169 const char *inm = mg_get_header(conn, "If-None-Match");
10170 construct_etag(etag, sizeof(etag), filestat);
10171
10172 return ((inm != NULL) && !mg_strcasecmp(etag, inm))
10173 || ((ims != NULL)
10174 && (filestat->last_modified <= parse_date_string(ims)));
10175}
10176
10177
10178static void
10180 struct mg_file *filep)
10181{
10182 char lm[64], etag[64];
10183
10184 if ((conn == NULL) || (filep == NULL)) {
10185 return;
10186 }
10187
10188 gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
10189 construct_etag(etag, sizeof(etag), &filep->stat);
10190
10191 /* Create 304 "not modified" response */
10192 mg_response_header_start(conn, 304);
10195 mg_response_header_add(conn, "Last-Modified", lm, -1);
10196 mg_response_header_add(conn, "Etag", etag, -1);
10197
10198 /* Send all headers */
10200}
10201#endif
10202
10203
10204#if !defined(NO_FILESYSTEMS)
10205void
10206mg_send_file(struct mg_connection *conn, const char *path)
10207{
10208 mg_send_mime_file2(conn, path, NULL, NULL);
10209}
10210
10211
10212void
10214 const char *path,
10215 const char *mime_type)
10216{
10217 mg_send_mime_file2(conn, path, mime_type, NULL);
10218}
10219
10220
10221void
10223 const char *path,
10224 const char *mime_type,
10225 const char *additional_headers)
10226{
10227 struct mg_file file = STRUCT_FILE_INITIALIZER;
10228
10229 if (!conn) {
10230 /* No conn */
10231 return;
10232 }
10233
10234 if (mg_stat(conn, path, &file.stat)) {
10235#if !defined(NO_CACHING)
10236 if (is_not_modified(conn, &file.stat)) {
10237 /* Send 304 "Not Modified" - this must not send any body data */
10239 } else
10240#endif /* NO_CACHING */
10241 if (file.stat.is_directory) {
10243 "yes")) {
10244 handle_directory_request(conn, path);
10245 } else {
10246 mg_send_http_error(conn,
10247 403,
10248 "%s",
10249 "Error: Directory listing denied");
10250 }
10251 } else {
10253 conn, path, &file, mime_type, additional_headers);
10254 }
10255 } else {
10256 mg_send_http_error(conn, 404, "%s", "Error: File not found");
10257 }
10258}
10259
10260
10261/* For a given PUT path, create all intermediate subdirectories.
10262 * Return 0 if the path itself is a directory.
10263 * Return 1 if the path leads to a file.
10264 * Return -1 for if the path is too long.
10265 * Return -2 if path can not be created.
10266 */
10267static int
10268put_dir(struct mg_connection *conn, const char *path)
10269{
10270 char buf[UTF8_PATH_MAX];
10271 const char *s, *p;
10272 struct mg_file file = STRUCT_FILE_INITIALIZER;
10273 size_t len;
10274 int res = 1;
10275
10276 for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
10277 len = (size_t)(p - path);
10278 if (len >= sizeof(buf)) {
10279 /* path too long */
10280 res = -1;
10281 break;
10282 }
10283 memcpy(buf, path, len);
10284 buf[len] = '\0';
10285
10286 /* Try to create intermediate directory */
10287 DEBUG_TRACE("mkdir(%s)", buf);
10288 if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
10289 /* path does not exixt and can not be created */
10290 res = -2;
10291 break;
10292 }
10293
10294 /* Is path itself a directory? */
10295 if (p[1] == '\0') {
10296 res = 0;
10297 }
10298 }
10299
10300 return res;
10301}
10302
10303
10304static void
10305remove_bad_file(const struct mg_connection *conn, const char *path)
10306{
10307 int r = mg_remove(conn, path);
10308 if (r != 0) {
10309 mg_cry_internal(conn,
10310 "%s: Cannot remove invalid file %s",
10311 __func__,
10312 path);
10313 }
10314}
10315
10316
10317long long
10318mg_store_body(struct mg_connection *conn, const char *path)
10319{
10320 char buf[MG_BUF_LEN];
10321 long long len = 0;
10322 int ret, n;
10323 struct mg_file fi;
10324
10325 if (conn->consumed_content != 0) {
10326 mg_cry_internal(conn, "%s: Contents already consumed", __func__);
10327 return -11;
10328 }
10329
10330 ret = put_dir(conn, path);
10331 if (ret < 0) {
10332 /* -1 for path too long,
10333 * -2 for path can not be created. */
10334 return ret;
10335 }
10336 if (ret != 1) {
10337 /* Return 0 means, path itself is a directory. */
10338 return 0;
10339 }
10340
10341 if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
10342 return -12;
10343 }
10344
10345 ret = mg_read(conn, buf, sizeof(buf));
10346 while (ret > 0) {
10347 n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
10348 if (n != ret) {
10349 (void)mg_fclose(
10350 &fi.access); /* File is bad and will be removed anyway. */
10351 remove_bad_file(conn, path);
10352 return -13;
10353 }
10354 len += ret;
10355 ret = mg_read(conn, buf, sizeof(buf));
10356 }
10357
10358 /* File is open for writing. If fclose fails, there was probably an
10359 * error flushing the buffer to disk, so the file on disk might be
10360 * broken. Delete it and return an error to the caller. */
10361 if (mg_fclose(&fi.access) != 0) {
10362 remove_bad_file(conn, path);
10363 return -14;
10364 }
10365
10366 return len;
10367}
10368#endif /* NO_FILESYSTEMS */
10369
10370
10371/* Parse a buffer:
10372 * Forward the string pointer till the end of a word, then
10373 * terminate it and forward till the begin of the next word.
10374 */
10375static int
10377{
10378 /* Forward until a space is found - use isgraph here */
10379 /* See http://www.cplusplus.com/reference/cctype/ */
10380 while (isgraph((unsigned char)**ppw)) {
10381 (*ppw)++;
10382 }
10383
10384 /* Check end of word */
10385 if (eol) {
10386 /* must be a end of line */
10387 if ((**ppw != '\r') && (**ppw != '\n')) {
10388 return -1;
10389 }
10390 } else {
10391 /* must be a end of a word, but not a line */
10392 if (**ppw != ' ') {
10393 return -1;
10394 }
10395 }
10396
10397 /* Terminate and forward to the next word */
10398 do {
10399 **ppw = 0;
10400 (*ppw)++;
10401 } while (isspace((unsigned char)**ppw));
10402
10403 /* Check after term */
10404 if (!eol) {
10405 /* if it's not the end of line, there must be a next word */
10406 if (!isgraph((unsigned char)**ppw)) {
10407 return -1;
10408 }
10409 }
10410
10411 /* ok */
10412 return 1;
10413}
10414
10415
10416/* Parse HTTP headers from the given buffer, advance buf pointer
10417 * to the point where parsing stopped.
10418 * All parameters must be valid pointers (not NULL).
10419 * Return <0 on error. */
10420static int
10422{
10423 int i;
10424 int num_headers = 0;
10425
10426 for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
10427 char *dp = *buf;
10428
10429 /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
10430 while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
10431 dp++;
10432 }
10433 if (dp == *buf) {
10434 /* End of headers reached. */
10435 break;
10436 }
10437
10438 /* Drop all spaces after header name before : */
10439 while (*dp == ' ') {
10440 *dp = 0;
10441 dp++;
10442 }
10443 if (*dp != ':') {
10444 /* This is not a valid field. */
10445 return -1;
10446 }
10447
10448 /* End of header key (*dp == ':') */
10449 /* Truncate here and set the key name */
10450 *dp = 0;
10451 hdr[i].name = *buf;
10452
10453 /* Skip all spaces */
10454 do {
10455 dp++;
10456 } while ((*dp == ' ') || (*dp == '\t'));
10457
10458 /* The rest of the line is the value */
10459 hdr[i].value = dp;
10460
10461 /* Find end of line */
10462 while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
10463 dp++;
10464 };
10465
10466 /* eliminate \r */
10467 if (*dp == '\r') {
10468 *dp = 0;
10469 dp++;
10470 if (*dp != '\n') {
10471 /* This is not a valid line. */
10472 return -1;
10473 }
10474 }
10475
10476 /* here *dp is either 0 or '\n' */
10477 /* in any case, we have a new header */
10478 num_headers = i + 1;
10479
10480 if (*dp) {
10481 *dp = 0;
10482 dp++;
10483 *buf = dp;
10484
10485 if ((dp[0] == '\r') || (dp[0] == '\n')) {
10486 /* This is the end of the header */
10487 break;
10488 }
10489 } else {
10490 *buf = dp;
10491 break;
10492 }
10493 }
10494 return num_headers;
10495}
10496
10497
10499 const char *name;
10505};
10506
10507
10508/* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
10509static const struct mg_http_method_info http_methods[] = {
10510 /* HTTP (RFC 2616) */
10511 {"GET", 0, 1, 1, 1, 1},
10512 {"POST", 1, 1, 0, 0, 0},
10513 {"PUT", 1, 0, 0, 1, 0},
10514 {"DELETE", 0, 0, 0, 1, 0},
10515 {"HEAD", 0, 0, 1, 1, 1},
10516 {"OPTIONS", 0, 0, 1, 1, 0},
10517 {"CONNECT", 1, 1, 0, 0, 0},
10518 /* TRACE method (RFC 2616) is not supported for security reasons */
10519
10520 /* PATCH method (RFC 5789) */
10521 {"PATCH", 1, 0, 0, 0, 0},
10522 /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
10523
10524 /* WEBDAV (RFC 2518) */
10525 {"PROPFIND", 0, 1, 1, 1, 0},
10526 /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10527 * Some PROPFIND results MAY be cached, with care,
10528 * as there is no cache validation mechanism for
10529 * most properties. This method is both safe and
10530 * idempotent (see Section 9.1 of [RFC2616]). */
10531 {"MKCOL", 0, 0, 0, 1, 0},
10532 /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10533 * When MKCOL is invoked without a request body,
10534 * the newly created collection SHOULD have no
10535 * members. A MKCOL request message may contain
10536 * a message body. The precise behavior of a MKCOL
10537 * request when the body is present is undefined,
10538 * ... ==> We do not support MKCOL with body data.
10539 * This method is idempotent, but not safe (see
10540 * Section 9.1 of [RFC2616]). Responses to this
10541 * method MUST NOT be cached. */
10542
10543 /* Methods for write access to files on WEBDAV (RFC 2518) */
10544 {"LOCK", 1, 1, 0, 0, 0},
10545 {"UNLOCK", 1, 0, 0, 0, 0},
10546 {"PROPPATCH", 1, 1, 0, 0, 0},
10547
10548 /* Unsupported WEBDAV Methods: */
10549 /* COPY, MOVE (RFC 2518) */
10550 /* + 11 methods from RFC 3253 */
10551 /* ORDERPATCH (RFC 3648) */
10552 /* ACL (RFC 3744) */
10553 /* SEARCH (RFC 5323) */
10554 /* + MicroSoft extensions
10555 * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
10556
10557 /* REPORT method (RFC 3253) */
10558 {"REPORT", 1, 1, 1, 1, 1},
10559 /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
10560 /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
10561 * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
10562 * to be useful for REST in case a "GET request with body" is
10563 * required. */
10564
10565 {NULL, 0, 0, 0, 0, 0}
10566 /* end of list */
10567};
10568
10569
10570static const struct mg_http_method_info *
10571get_http_method_info(const char *method)
10572{
10573 /* Check if the method is known to the server. The list of all known
10574 * HTTP methods can be found here at
10575 * http://www.iana.org/assignments/http-methods/http-methods.xhtml
10576 */
10577 const struct mg_http_method_info *m = http_methods;
10578
10579 while (m->name) {
10580 if (!strcmp(m->name, method)) {
10581 return m;
10582 }
10583 m++;
10584 }
10585 return NULL;
10586}
10587
10588
10589static int
10590is_valid_http_method(const char *method)
10591{
10592 return (get_http_method_info(method) != NULL);
10593}
10594
10595
10596/* Parse HTTP request, fill in mg_request_info structure.
10597 * This function modifies the buffer by NUL-terminating
10598 * HTTP request components, header names and header values.
10599 * Parameters:
10600 * buf (in/out): pointer to the HTTP header to parse and split
10601 * len (in): length of HTTP header buffer
10602 * re (out): parsed header as mg_request_info
10603 * buf and ri must be valid pointers (not NULL), len>0.
10604 * Returns <0 on error. */
10605static int
10606parse_http_request(char *buf, int len, struct mg_request_info *ri)
10607{
10608 int request_length;
10609 int init_skip = 0;
10610
10611 /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
10612 * remote_port */
10613 ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
10614 NULL;
10615 ri->num_headers = 0;
10616
10617 /* RFC says that all initial whitespaces should be ignored */
10618 /* This included all leading \r and \n (isspace) */
10619 /* See table: http://www.cplusplus.com/reference/cctype/ */
10620 while ((len > 0) && isspace((unsigned char)*buf)) {
10621 buf++;
10622 len--;
10623 init_skip++;
10624 }
10625
10626 if (len == 0) {
10627 /* Incomplete request */
10628 return 0;
10629 }
10630
10631 /* Control characters are not allowed, including zero */
10632 if (iscntrl((unsigned char)*buf)) {
10633 return -1;
10634 }
10635
10636 /* Find end of HTTP header */
10637 request_length = get_http_header_len(buf, len);
10638 if (request_length <= 0) {
10639 return request_length;
10640 }
10641 buf[request_length - 1] = '\0';
10642
10643 if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10644 return -1;
10645 }
10646
10647 /* The first word has to be the HTTP method */
10648 ri->request_method = buf;
10649
10650 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10651 return -1;
10652 }
10653
10654 /* The second word is the URI */
10655 ri->request_uri = buf;
10656
10657 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10658 return -1;
10659 }
10660
10661 /* Next would be the HTTP version */
10662 ri->http_version = buf;
10663
10664 if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
10665 return -1;
10666 }
10667
10668 /* Check for a valid HTTP version key */
10669 if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
10670 /* Invalid request */
10671 return -1;
10672 }
10673 ri->http_version += 5;
10674
10675 /* Check for a valid http method */
10677 return -1;
10678 }
10679
10680 /* Parse all HTTP headers */
10682 if (ri->num_headers < 0) {
10683 /* Error while parsing headers */
10684 return -1;
10685 }
10686
10687 return request_length + init_skip;
10688}
10689
10690
10691static int
10692parse_http_response(char *buf, int len, struct mg_response_info *ri)
10693{
10694 int response_length;
10695 int init_skip = 0;
10696 char *tmp, *tmp2;
10697 long l;
10698
10699 /* Initialize elements. */
10700 ri->http_version = ri->status_text = NULL;
10701 ri->num_headers = ri->status_code = 0;
10702
10703 /* RFC says that all initial whitespaces should be ingored */
10704 /* This included all leading \r and \n (isspace) */
10705 /* See table: http://www.cplusplus.com/reference/cctype/ */
10706 while ((len > 0) && isspace((unsigned char)*buf)) {
10707 buf++;
10708 len--;
10709 init_skip++;
10710 }
10711
10712 if (len == 0) {
10713 /* Incomplete request */
10714 return 0;
10715 }
10716
10717 /* Control characters are not allowed, including zero */
10718 if (iscntrl((unsigned char)*buf)) {
10719 return -1;
10720 }
10721
10722 /* Find end of HTTP header */
10723 response_length = get_http_header_len(buf, len);
10724 if (response_length <= 0) {
10725 return response_length;
10726 }
10727 buf[response_length - 1] = '\0';
10728
10729 if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10730 return -1;
10731 }
10732
10733 /* The first word is the HTTP version */
10734 /* Check for a valid HTTP version key */
10735 if (strncmp(buf, "HTTP/", 5) != 0) {
10736 /* Invalid request */
10737 return -1;
10738 }
10739 buf += 5;
10740 if (!isgraph((unsigned char)buf[0])) {
10741 /* Invalid request */
10742 return -1;
10743 }
10744 ri->http_version = buf;
10745
10746 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10747 return -1;
10748 }
10749
10750 /* The second word is the status as a number */
10751 tmp = buf;
10752
10753 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10754 return -1;
10755 }
10756
10757 l = strtol(tmp, &tmp2, 10);
10758 if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
10759 /* Everything else but a 3 digit code is invalid */
10760 return -1;
10761 }
10762 ri->status_code = (int)l;
10763
10764 /* The rest of the line is the status text */
10765 ri->status_text = buf;
10766
10767 /* Find end of status text */
10768 /* isgraph or isspace = isprint */
10769 while (isprint((unsigned char)*buf)) {
10770 buf++;
10771 }
10772 if ((*buf != '\r') && (*buf != '\n')) {
10773 return -1;
10774 }
10775 /* Terminate string and forward buf to next line */
10776 do {
10777 *buf = 0;
10778 buf++;
10779 } while (isspace((unsigned char)*buf));
10780
10781
10782 /* Parse all HTTP headers */
10784 if (ri->num_headers < 0) {
10785 /* Error while parsing headers */
10786 return -1;
10787 }
10788
10789 return response_length + init_skip;
10790}
10791
10792
10793/* Keep reading the input (either opened file descriptor fd, or socket sock,
10794 * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
10795 * buffer (which marks the end of HTTP request). Buffer buf may already
10796 * have some data. The length of the data is stored in nread.
10797 * Upon every read operation, increase nread by the number of bytes read. */
10798static int
10800 struct mg_connection *conn,
10801 char *buf,
10802 int bufsiz,
10803 int *nread)
10804{
10805 int request_len, n = 0;
10806 struct timespec last_action_time;
10807 double request_timeout;
10808
10809 if (!conn) {
10810 return 0;
10811 }
10812
10813 memset(&last_action_time, 0, sizeof(last_action_time));
10814
10815 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
10816 /* value of request_timeout is in seconds, config in milliseconds */
10817 request_timeout =
10818 strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
10819 } else {
10820 request_timeout =
10821 strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
10822 / 1000.0;
10823 }
10824 if (conn->handled_requests > 0) {
10825 if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
10826 request_timeout =
10827 strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
10828 / 1000.0;
10829 }
10830 }
10831
10832 request_len = get_http_header_len(buf, *nread);
10833
10834 while (request_len == 0) {
10835 /* Full request not yet received */
10836 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
10837 /* Server is to be stopped. */
10838 return -1;
10839 }
10840
10841 if (*nread >= bufsiz) {
10842 /* Request too long */
10843 return -2;
10844 }
10845
10846 n = pull_inner(
10847 fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
10848 if (n == -2) {
10849 /* Receive error */
10850 return -1;
10851 }
10852
10853 /* update clock after every read request */
10854 clock_gettime(CLOCK_MONOTONIC, &last_action_time);
10855
10856 if (n > 0) {
10857 *nread += n;
10858 request_len = get_http_header_len(buf, *nread);
10859 }
10860
10861 if ((request_len == 0) && (request_timeout >= 0)) {
10862 if (mg_difftimespec(&last_action_time, &(conn->req_time))
10863 > request_timeout) {
10864 /* Timeout */
10865 return -1;
10866 }
10867 }
10868 }
10869
10870 return request_len;
10871}
10872
10873
10874#if !defined(NO_CGI) || !defined(NO_FILES)
10875static int
10876forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
10877{
10878 const char *expect;
10879 char buf[MG_BUF_LEN];
10880 int success = 0;
10881
10882 if (!conn) {
10883 return 0;
10884 }
10885
10886 expect = mg_get_header(conn, "Expect");
10887 DEBUG_ASSERT(fp != NULL);
10888 if (!fp) {
10889 mg_send_http_error(conn, 500, "%s", "Error: NULL File");
10890 return 0;
10891 }
10892
10893 if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
10894 /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
10895 */
10896 mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
10897 } else {
10898 if (expect != NULL) {
10899 (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
10900 conn->status_code = 100;
10901 } else {
10902 conn->status_code = 200;
10903 }
10904
10905 DEBUG_ASSERT(conn->consumed_content == 0);
10906
10907 if (conn->consumed_content != 0) {
10908 mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
10909 return 0;
10910 }
10911
10912 for (;;) {
10913 int nread = mg_read(conn, buf, sizeof(buf));
10914 if (nread <= 0) {
10915 success = (nread == 0);
10916 break;
10917 }
10918 if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
10919 break;
10920 }
10921 }
10922
10923 /* Each error code path in this function must send an error */
10924 if (!success) {
10925 /* NOTE: Maybe some data has already been sent. */
10926 /* TODO (low): If some data has been sent, a correct error
10927 * reply can no longer be sent, so just close the connection */
10928 mg_send_http_error(conn, 500, "%s", "");
10929 }
10930 }
10931
10932 return success;
10933}
10934#endif
10935
10936
10937#if defined(USE_TIMERS)
10938
10939#define TIMER_API static
10940#include "timer.inl"
10941
10942#endif /* USE_TIMERS */
10943
10944
10945#if !defined(NO_CGI)
10946/* This structure helps to create an environment for the spawned CGI
10947 * program.
10948 * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
10949 * last element must be NULL.
10950 * However, on Windows there is a requirement that all these
10951 * VARIABLE=VALUE\0
10952 * strings must reside in a contiguous buffer. The end of the buffer is
10953 * marked by two '\0' characters.
10954 * We satisfy both worlds: we create an envp array (which is vars), all
10955 * entries are actually pointers inside buf. */
10958 /* Data block */
10959 char *buf; /* Environment buffer */
10960 size_t buflen; /* Space available in buf */
10961 size_t bufused; /* Space taken in buf */
10962 /* Index block */
10963 char **var; /* char **envp */
10964 size_t varlen; /* Number of variables available in var */
10965 size_t varused; /* Number of variables stored in var */
10966};
10967
10968
10969static void addenv(struct cgi_environment *env,
10970 PRINTF_FORMAT_STRING(const char *fmt),
10971 ...) PRINTF_ARGS(2, 3);
10972
10973/* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
10974 * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
10975static void
10976addenv(struct cgi_environment *env, const char *fmt, ...)
10977{
10978 size_t i, n, space;
10979 int truncated = 0;
10980 char *added;
10981 va_list ap;
10982
10983 if ((env->varlen - env->varused) < 2) {
10984 mg_cry_internal(env->conn,
10985 "%s: Cannot register CGI variable [%s]",
10986 __func__,
10987 fmt);
10988 return;
10989 }
10990
10991 /* Calculate how much space is left in the buffer */
10992 space = (env->buflen - env->bufused);
10993
10994 do {
10995 /* Space for "\0\0" is always needed. */
10996 if (space <= 2) {
10997 /* Allocate new buffer */
10998 n = env->buflen + CGI_ENVIRONMENT_SIZE;
10999 added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
11000 if (!added) {
11001 /* Out of memory */
11003 env->conn,
11004 "%s: Cannot allocate memory for CGI variable [%s]",
11005 __func__,
11006 fmt);
11007 return;
11008 }
11009 /* Retarget pointers */
11010 env->buf = added;
11011 env->buflen = n;
11012 for (i = 0, n = 0; i < env->varused; i++) {
11013 env->var[i] = added + n;
11014 n += strlen(added + n) + 1;
11015 }
11016 space = (env->buflen - env->bufused);
11017 }
11018
11019 /* Make a pointer to the free space int the buffer */
11020 added = env->buf + env->bufused;
11021
11022 /* Copy VARIABLE=VALUE\0 string into the free space */
11023 va_start(ap, fmt);
11024 mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
11025 va_end(ap);
11026
11027 /* Do not add truncated strings to the environment */
11028 if (truncated) {
11029 /* Reallocate the buffer */
11030 space = 0;
11031 }
11032 } while (truncated);
11033
11034 /* Calculate number of bytes added to the environment */
11035 n = strlen(added) + 1;
11036 env->bufused += n;
11037
11038 /* Append a pointer to the added string into the envp array */
11039 env->var[env->varused] = added;
11040 env->varused++;
11041}
11042
11043/* Return 0 on success, non-zero if an error occurs. */
11044
11045static int
11047 const char *prog,
11048 struct cgi_environment *env,
11049 unsigned char cgi_config_idx)
11050{
11051 const char *s;
11052 struct vec var_vec;
11053 char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
11054 int i, truncated, uri_len;
11055
11056 if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
11057 return -1;
11058 }
11059
11060 env->conn = conn;
11062 env->bufused = 0;
11063 env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
11064 if (env->buf == NULL) {
11065 mg_cry_internal(conn,
11066 "%s: Not enough memory for environmental buffer",
11067 __func__);
11068 return -1;
11069 }
11071 env->varused = 0;
11072 env->var =
11073 (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
11074 if (env->var == NULL) {
11075 mg_cry_internal(conn,
11076 "%s: Not enough memory for environmental variables",
11077 __func__);
11078 mg_free(env->buf);
11079 return -1;
11080 }
11081
11082 addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
11083 addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11084 addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11085 addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
11086
11087 /* Prepare the environment block */
11088 addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
11089 addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
11090 addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
11091
11092 addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
11093
11094 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
11095 addenv(env, "REMOTE_ADDR=%s", src_addr);
11096
11097 addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
11098 addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
11099
11100 addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
11101 addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
11102 addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
11103
11104 /* SCRIPT_NAME */
11105 uri_len = (int)strlen(conn->request_info.local_uri);
11106 if (conn->path_info == NULL) {
11107 if (conn->request_info.local_uri[uri_len - 1] != '/') {
11108 /* URI: /path_to_script/script.cgi */
11109 addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
11110 } else {
11111 /* URI: /path_to_script/ ... using index.cgi */
11112 const char *index_file = strrchr(prog, '/');
11113 if (index_file) {
11114 addenv(env,
11115 "SCRIPT_NAME=%s%s",
11116 conn->request_info.local_uri,
11117 index_file + 1);
11118 }
11119 }
11120 } else {
11121 /* URI: /path_to_script/script.cgi/path_info */
11122 addenv(env,
11123 "SCRIPT_NAME=%.*s",
11124 uri_len - (int)strlen(conn->path_info),
11125 conn->request_info.local_uri);
11126 }
11127
11128 addenv(env, "SCRIPT_FILENAME=%s", prog);
11129 if (conn->path_info == NULL) {
11130 addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11131 } else {
11132 addenv(env,
11133 "PATH_TRANSLATED=%s%s",
11135 conn->path_info);
11136 }
11137
11138 addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
11139
11140 if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
11141 addenv(env, "CONTENT_TYPE=%s", s);
11142 }
11143 if (conn->request_info.query_string != NULL) {
11144 addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
11145 }
11146 if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
11147 addenv(env, "CONTENT_LENGTH=%s", s);
11148 }
11149 if ((s = getenv("PATH")) != NULL) {
11150 addenv(env, "PATH=%s", s);
11151 }
11152 if (conn->path_info != NULL) {
11153 addenv(env, "PATH_INFO=%s", conn->path_info);
11154 }
11155
11156 if (conn->status_code > 0) {
11157 /* CGI error handler should show the status code */
11158 addenv(env, "STATUS=%d", conn->status_code);
11159 }
11160
11161#if defined(_WIN32)
11162 if ((s = getenv("COMSPEC")) != NULL) {
11163 addenv(env, "COMSPEC=%s", s);
11164 }
11165 if ((s = getenv("SYSTEMROOT")) != NULL) {
11166 addenv(env, "SYSTEMROOT=%s", s);
11167 }
11168 if ((s = getenv("SystemDrive")) != NULL) {
11169 addenv(env, "SystemDrive=%s", s);
11170 }
11171 if ((s = getenv("ProgramFiles")) != NULL) {
11172 addenv(env, "ProgramFiles=%s", s);
11173 }
11174 if ((s = getenv("ProgramFiles(x86)")) != NULL) {
11175 addenv(env, "ProgramFiles(x86)=%s", s);
11176 }
11177#else
11178 if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
11179 addenv(env, "LD_LIBRARY_PATH=%s", s);
11180 }
11181#endif /* _WIN32 */
11182
11183 if ((s = getenv("PERLLIB")) != NULL) {
11184 addenv(env, "PERLLIB=%s", s);
11185 }
11186
11187 if (conn->request_info.remote_user != NULL) {
11188 addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
11189 addenv(env, "%s", "AUTH_TYPE=Digest");
11190 }
11191
11192 /* Add all headers as HTTP_* variables */
11193 for (i = 0; i < conn->request_info.num_headers; i++) {
11194
11195 (void)mg_snprintf(conn,
11196 &truncated,
11197 http_var_name,
11198 sizeof(http_var_name),
11199 "HTTP_%s",
11200 conn->request_info.http_headers[i].name);
11201
11202 if (truncated) {
11203 mg_cry_internal(conn,
11204 "%s: HTTP header variable too long [%s]",
11205 __func__,
11206 conn->request_info.http_headers[i].name);
11207 continue;
11208 }
11209
11210 /* Convert variable name into uppercase, and change - to _ */
11211 for (p = http_var_name; *p != '\0'; p++) {
11212 if (*p == '-') {
11213 *p = '_';
11214 }
11215 *p = (char)toupper((unsigned char)*p);
11216 }
11217
11218 addenv(env,
11219 "%s=%s",
11220 http_var_name,
11222 }
11223
11224 /* Add user-specified variables */
11225 s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
11226 while ((s = next_option(s, &var_vec, NULL)) != NULL) {
11227 addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
11228 }
11229
11230 env->var[env->varused] = NULL;
11231 env->buf[env->bufused] = '\0';
11232
11233 return 0;
11234}
11235
11236
11237/* Data for CGI process control: PID and number of references */
11239 pid_t pid;
11240 ptrdiff_t references;
11241};
11242
11243static int
11245{
11246 /* Waitpid checks for child status and won't work for a pid that does
11247 * not identify a child of the current process. Thus, if the pid is
11248 * reused, we will not affect a different process. */
11249 struct process_control_data *proc = (struct process_control_data *)data;
11250 int status = 0;
11251 ptrdiff_t refs;
11252 pid_t ret_pid;
11253
11254 ret_pid = waitpid(proc->pid, &status, WNOHANG);
11255 if ((ret_pid != (pid_t)-1) && (status == 0)) {
11256 /* Stop child process */
11257 DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
11258 kill(proc->pid, SIGABRT);
11259
11260 /* Wait until process is terminated (don't leave zombies) */
11261 while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
11262 ;
11263 } else {
11264 DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
11265 }
11266 /* Dec reference counter */
11267 refs = mg_atomic_dec(&proc->references);
11268 if (refs == 0) {
11269 /* no more references - free data */
11270 mg_free(data);
11271 }
11272
11273 return 0;
11274}
11275
11276
11277/* Local (static) function assumes all arguments are valid. */
11278static void
11280 const char *prog,
11281 unsigned char cgi_config_idx)
11282{
11283 char *buf;
11284 size_t buflen;
11285 int headers_len, data_len, i, truncated;
11286 int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
11287 const char *status, *status_text, *connection_state;
11288 char *pbuf, dir[UTF8_PATH_MAX], *p;
11289 struct mg_request_info ri;
11290 struct cgi_environment blk;
11291 FILE *in = NULL, *out = NULL, *err = NULL;
11292 struct mg_file fout = STRUCT_FILE_INITIALIZER;
11293 pid_t pid = (pid_t)-1;
11294 struct process_control_data *proc = NULL;
11295
11296#if defined(USE_TIMERS)
11297 double cgi_timeout;
11298 if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
11299 /* Get timeout in seconds */
11300 cgi_timeout =
11301 atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
11302 } else {
11303 cgi_timeout =
11304 atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
11305 }
11306
11307#endif
11308
11309 buf = NULL;
11310 buflen = conn->phys_ctx->max_request_size;
11311 i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
11312 if (i != 0) {
11313 blk.buf = NULL;
11314 blk.var = NULL;
11315 goto done;
11316 }
11317
11318 /* CGI must be executed in its own directory. 'dir' must point to the
11319 * directory containing executable program, 'p' must point to the
11320 * executable program name relative to 'dir'. */
11321 (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
11322
11323 if (truncated) {
11324 mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
11325 mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
11326 goto done;
11327 }
11328
11329 if ((p = strrchr(dir, '/')) != NULL) {
11330 *p++ = '\0';
11331 } else {
11332 dir[0] = '.';
11333 dir[1] = '\0';
11334 p = (char *)prog;
11335 }
11336
11337 if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
11338 status = strerror(ERRNO);
11340 conn,
11341 "Error: CGI program \"%s\": Can not create CGI pipes: %s",
11342 prog,
11343 status);
11344 mg_send_http_error(conn,
11345 500,
11346 "Error: Cannot create CGI pipe: %s",
11347 status);
11348 goto done;
11349 }
11350
11351 proc = (struct process_control_data *)
11352 mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
11353 if (proc == NULL) {
11354 mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
11355 mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
11356 goto done;
11357 }
11358
11359 DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
11361 conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
11362
11363 if (pid == (pid_t)-1) {
11364 status = strerror(ERRNO);
11366 conn,
11367 "Error: CGI program \"%s\": Can not spawn CGI process: %s",
11368 prog,
11369 status);
11370 mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
11371 mg_free(proc);
11372 proc = NULL;
11373 goto done;
11374 }
11375
11376 /* Store data in shared process_control_data */
11377 proc->pid = pid;
11378 proc->references = 1;
11379
11380#if defined(USE_TIMERS)
11381 if (cgi_timeout > 0.0) {
11382 proc->references = 2;
11383
11384 // Start a timer for CGI
11385 timer_add(conn->phys_ctx,
11386 cgi_timeout /* in seconds */,
11387 0.0,
11388 1,
11390 (void *)proc,
11391 NULL);
11392 }
11393#endif
11394
11395 /* Parent closes only one side of the pipes.
11396 * If we don't mark them as closed, close() attempt before
11397 * return from this function throws an exception on Windows.
11398 * Windows does not like when closed descriptor is closed again. */
11399 (void)close(fdin[0]);
11400 (void)close(fdout[1]);
11401 (void)close(fderr[1]);
11402 fdin[0] = fdout[1] = fderr[1] = -1;
11403
11404 if (((in = fdopen(fdin[1], "wb")) == NULL)
11405 || ((out = fdopen(fdout[0], "rb")) == NULL)
11406 || ((err = fdopen(fderr[0], "rb")) == NULL)) {
11407 status = strerror(ERRNO);
11408 mg_cry_internal(conn,
11409 "Error: CGI program \"%s\": Can not open fd: %s",
11410 prog,
11411 status);
11412 mg_send_http_error(conn,
11413 500,
11414 "Error: CGI can not open fd\nfdopen: %s",
11415 status);
11416 goto done;
11417 }
11418
11419 setbuf(in, NULL);
11420 setbuf(out, NULL);
11421 setbuf(err, NULL);
11422 fout.access.fp = out;
11423
11424 if ((conn->content_len != 0) || (conn->is_chunked)) {
11425 DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
11426 conn->content_len);
11427
11428 /* This is a POST/PUT request, or another request with body data. */
11429 if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
11430 /* Error sending the body data */
11432 conn,
11433 "Error: CGI program \"%s\": Forward body data failed",
11434 prog);
11435 goto done;
11436 }
11437 }
11438
11439 /* Close so child gets an EOF. */
11440 fclose(in);
11441 in = NULL;
11442 fdin[1] = -1;
11443
11444 /* Now read CGI reply into a buffer. We need to set correct
11445 * status code, thus we need to see all HTTP headers first.
11446 * Do not send anything back to client, until we buffer in all
11447 * HTTP headers. */
11448 data_len = 0;
11449 buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
11450 if (buf == NULL) {
11451 mg_send_http_error(conn,
11452 500,
11453 "Error: Not enough memory for CGI buffer (%u bytes)",
11454 (unsigned int)buflen);
11456 conn,
11457 "Error: CGI program \"%s\": Not enough memory for buffer (%u "
11458 "bytes)",
11459 prog,
11460 (unsigned int)buflen);
11461 goto done;
11462 }
11463
11464 DEBUG_TRACE("CGI: %s", "wait for response");
11465 headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
11466 DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
11467
11468 if (headers_len <= 0) {
11469
11470 /* Could not parse the CGI response. Check if some error message on
11471 * stderr. */
11472 i = pull_all(err, conn, buf, (int)buflen);
11473 if (i > 0) {
11474 /* CGI program explicitly sent an error */
11475 /* Write the error message to the internal log */
11476 mg_cry_internal(conn,
11477 "Error: CGI program \"%s\" sent error "
11478 "message: [%.*s]",
11479 prog,
11480 i,
11481 buf);
11482 /* Don't send the error message back to the client */
11483 mg_send_http_error(conn,
11484 500,
11485 "Error: CGI program \"%s\" failed.",
11486 prog);
11487 } else {
11488 /* CGI program did not explicitly send an error, but a broken
11489 * respon header */
11490 mg_cry_internal(conn,
11491 "Error: CGI program sent malformed or too big "
11492 "(>%u bytes) HTTP headers: [%.*s]",
11493 (unsigned)buflen,
11494 data_len,
11495 buf);
11496
11497 mg_send_http_error(conn,
11498 500,
11499 "Error: CGI program sent malformed or too big "
11500 "(>%u bytes) HTTP headers: [%.*s]",
11501 (unsigned)buflen,
11502 data_len,
11503 buf);
11504 }
11505
11506 /* in both cases, abort processing CGI */
11507 goto done;
11508 }
11509
11510 pbuf = buf;
11511 buf[headers_len - 1] = '\0';
11513
11514 /* Make up and send the status line */
11515 status_text = "OK";
11516 if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
11517 != NULL) {
11518 conn->status_code = atoi(status);
11519 status_text = status;
11520 while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
11521 status_text++;
11522 }
11523 } else if (get_header(ri.http_headers, ri.num_headers, "Location")
11524 != NULL) {
11525 conn->status_code = 307;
11526 } else {
11527 conn->status_code = 200;
11528 }
11529 connection_state =
11530 get_header(ri.http_headers, ri.num_headers, "Connection");
11531 if (!header_has_option(connection_state, "keep-alive")) {
11532 conn->must_close = 1;
11533 }
11534
11535 DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
11536
11537 (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
11538
11539 /* Send headers */
11540 for (i = 0; i < ri.num_headers; i++) {
11541 DEBUG_TRACE("CGI header: %s: %s",
11542 ri.http_headers[i].name,
11543 ri.http_headers[i].value);
11544 mg_printf(conn,
11545 "%s: %s\r\n",
11546 ri.http_headers[i].name,
11547 ri.http_headers[i].value);
11548 }
11549 mg_write(conn, "\r\n", 2);
11550
11551 /* Send chunk of data that may have been read after the headers */
11552 mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
11553
11554 /* Read the rest of CGI output and send to the client */
11555 DEBUG_TRACE("CGI: %s", "forward all data");
11556 send_file_data(conn, &fout, 0, INT64_MAX);
11557 DEBUG_TRACE("CGI: %s", "all data sent");
11558
11559done:
11560 mg_free(blk.var);
11561 mg_free(blk.buf);
11562
11563 if (pid != (pid_t)-1) {
11564 abort_cgi_process((void *)proc);
11565 }
11566
11567 if (fdin[0] != -1) {
11568 close(fdin[0]);
11569 }
11570 if (fdout[1] != -1) {
11571 close(fdout[1]);
11572 }
11573 if (fderr[1] != -1) {
11574 close(fderr[1]);
11575 }
11576
11577 if (in != NULL) {
11578 fclose(in);
11579 } else if (fdin[1] != -1) {
11580 close(fdin[1]);
11581 }
11582
11583 if (out != NULL) {
11584 fclose(out);
11585 } else if (fdout[0] != -1) {
11586 close(fdout[0]);
11587 }
11588
11589 if (err != NULL) {
11590 fclose(err);
11591 } else if (fderr[0] != -1) {
11592 close(fderr[0]);
11593 }
11594
11595 mg_free(buf);
11596}
11597#endif /* !NO_CGI */
11598
11599
11600#if !defined(NO_FILES)
11601static void
11602mkcol(struct mg_connection *conn, const char *path)
11603{
11604 int rc, body_len;
11605 struct de de;
11606
11607 if (conn == NULL) {
11608 return;
11609 }
11610
11611 /* TODO (mid): Check the mg_send_http_error situations in this function
11612 */
11613
11614 memset(&de.file, 0, sizeof(de.file));
11615 if (!mg_stat(conn, path, &de.file)) {
11617 "%s: mg_stat(%s) failed: %s",
11618 __func__,
11619 path,
11620 strerror(ERRNO));
11621 }
11622
11623 if (de.file.last_modified) {
11624 /* TODO (mid): This check does not seem to make any sense ! */
11625 /* TODO (mid): Add a webdav unit test first, before changing
11626 * anything here. */
11628 conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11629 return;
11630 }
11631
11632 body_len = conn->data_len - conn->request_len;
11633 if (body_len > 0) {
11635 conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11636 return;
11637 }
11638
11639 rc = mg_mkdir(conn, path, 0755);
11640
11641 if (rc == 0) {
11642
11643 /* Create 201 "Created" response */
11647 mg_response_header_add(conn, "Content-Length", "0", -1);
11648
11649 /* Send all headers - there is no body */
11651
11652 } else {
11653 if (errno == EEXIST) {
11655 conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11656 } else if (errno == EACCES) {
11658 conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11659 } else if (errno == ENOENT) {
11661 conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11662 } else {
11664 conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
11665 }
11666 }
11667}
11668
11669
11670static void
11671put_file(struct mg_connection *conn, const char *path)
11672{
11673 struct mg_file file = STRUCT_FILE_INITIALIZER;
11674 const char *range;
11675 int64_t r1, r2;
11676 int rc;
11677
11678 if (conn == NULL) {
11679 return;
11680 }
11681
11682 if (mg_stat(conn, path, &file.stat)) {
11683 /* File already exists */
11684 conn->status_code = 200;
11685
11686 if (file.stat.is_directory) {
11687 /* This is an already existing directory,
11688 * so there is nothing to do for the server. */
11689 rc = 0;
11690
11691 } else {
11692 /* File exists and is not a directory. */
11693 /* Can it be replaced? */
11694
11695 /* Check if the server may write this file */
11696 if (access(path, W_OK) == 0) {
11697 /* Access granted */
11698 rc = 1;
11699 } else {
11701 conn,
11702 403,
11703 "Error: Put not possible\nReplacing %s is not allowed",
11704 path);
11705 return;
11706 }
11707 }
11708 } else {
11709 /* File should be created */
11710 conn->status_code = 201;
11711 rc = put_dir(conn, path);
11712 }
11713
11714 if (rc == 0) {
11715 /* put_dir returns 0 if path is a directory */
11716
11717 /* Create response */
11721 mg_response_header_add(conn, "Content-Length", "0", -1);
11722
11723 /* Send all headers - there is no body */
11725
11726 /* Request to create a directory has been fulfilled successfully.
11727 * No need to put a file. */
11728 return;
11729 }
11730
11731 if (rc == -1) {
11732 /* put_dir returns -1 if the path is too long */
11733 mg_send_http_error(conn,
11734 414,
11735 "Error: Path too long\nput_dir(%s): %s",
11736 path,
11737 strerror(ERRNO));
11738 return;
11739 }
11740
11741 if (rc == -2) {
11742 /* put_dir returns -2 if the directory can not be created */
11743 mg_send_http_error(conn,
11744 500,
11745 "Error: Can not create directory\nput_dir(%s): %s",
11746 path,
11747 strerror(ERRNO));
11748 return;
11749 }
11750
11751 /* A file should be created or overwritten. */
11752 /* Currently CivetWeb does not nead read+write access. */
11753 if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
11754 || file.access.fp == NULL) {
11755 (void)mg_fclose(&file.access);
11756 mg_send_http_error(conn,
11757 500,
11758 "Error: Can not create file\nfopen(%s): %s",
11759 path,
11760 strerror(ERRNO));
11761 return;
11762 }
11763
11764 fclose_on_exec(&file.access, conn);
11765 range = mg_get_header(conn, "Content-Range");
11766 r1 = r2 = 0;
11767 if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
11768 conn->status_code = 206; /* Partial content */
11769 fseeko(file.access.fp, r1, SEEK_SET);
11770 }
11771
11772 if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
11773 /* forward_body_data failed.
11774 * The error code has already been sent to the client,
11775 * and conn->status_code is already set. */
11776 (void)mg_fclose(&file.access);
11777 return;
11778 }
11779
11780 if (mg_fclose(&file.access) != 0) {
11781 /* fclose failed. This might have different reasons, but a likely
11782 * one is "no space on disk", http 507. */
11783 conn->status_code = 507;
11784 }
11785
11786 /* Create response (status_code has been set before) */
11790 mg_response_header_add(conn, "Content-Length", "0", -1);
11791
11792 /* Send all headers - there is no body */
11794}
11795
11796
11797static void
11798delete_file(struct mg_connection *conn, const char *path)
11799{
11800 struct de de;
11801 memset(&de.file, 0, sizeof(de.file));
11802 if (!mg_stat(conn, path, &de.file)) {
11803 /* mg_stat returns 0 if the file does not exist */
11805 404,
11806 "Error: Cannot delete file\nFile %s not found",
11807 path);
11808 return;
11809 }
11810
11811 if (de.file.is_directory) {
11812 if (remove_directory(conn, path)) {
11813 /* Delete is successful: Return 204 without content. */
11814 mg_send_http_error(conn, 204, "%s", "");
11815 } else {
11816 /* Delete is not successful: Return 500 (Server error). */
11817 mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
11818 }
11819 return;
11820 }
11821
11822 /* This is an existing file (not a directory).
11823 * Check if write permission is granted. */
11824 if (access(path, W_OK) != 0) {
11825 /* File is read only */
11827 conn,
11828 403,
11829 "Error: Delete not possible\nDeleting %s is not allowed",
11830 path);
11831 return;
11832 }
11833
11834 /* Try to delete it. */
11835 if (mg_remove(conn, path) == 0) {
11836 /* Delete was successful: Return 204 without content. */
11840 mg_response_header_add(conn, "Content-Length", "0", -1);
11842
11843 } else {
11844 /* Delete not successful (file locked). */
11846 423,
11847 "Error: Cannot delete file\nremove(%s): %s",
11848 path,
11849 strerror(ERRNO));
11850 }
11851}
11852#endif /* !NO_FILES */
11853
11854
11855#if !defined(NO_FILESYSTEMS)
11856static void
11857send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
11858
11859
11860static void
11862 const char *ssi,
11863 char *tag,
11864 int include_level)
11865{
11866 char file_name[MG_BUF_LEN], path[512], *p;
11867 struct mg_file file = STRUCT_FILE_INITIALIZER;
11868 size_t len;
11869 int truncated = 0;
11870
11871 if (conn == NULL) {
11872 return;
11873 }
11874
11875 /* sscanf() is safe here, since send_ssi_file() also uses buffer
11876 * of size MG_BUF_LEN to get the tag. So strlen(tag) is
11877 * always < MG_BUF_LEN. */
11878 if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
11879 /* File name is relative to the webserver root */
11880 file_name[511] = 0;
11881 (void)mg_snprintf(conn,
11882 &truncated,
11883 path,
11884 sizeof(path),
11885 "%s/%s",
11887 file_name);
11888
11889 } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
11890 /* File name is relative to the webserver working directory
11891 * or it is absolute system path */
11892 file_name[511] = 0;
11893 (void)
11894 mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
11895
11896 } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
11897 || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
11898 /* File name is relative to the currect document */
11899 file_name[511] = 0;
11900 (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
11901
11902 if (!truncated) {
11903 if ((p = strrchr(path, '/')) != NULL) {
11904 p[1] = '\0';
11905 }
11906 len = strlen(path);
11907 (void)mg_snprintf(conn,
11908 &truncated,
11909 path + len,
11910 sizeof(path) - len,
11911 "%s",
11912 file_name);
11913 }
11914
11915 } else {
11916 mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
11917 return;
11918 }
11919
11920 if (truncated) {
11921 mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
11922 return;
11923 }
11924
11925 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
11926 mg_cry_internal(conn,
11927 "Cannot open SSI #include: [%s]: fopen(%s): %s",
11928 tag,
11929 path,
11930 strerror(ERRNO));
11931 } else {
11932 fclose_on_exec(&file.access, conn);
11934 > 0) {
11935 send_ssi_file(conn, path, &file, include_level + 1);
11936 } else {
11937 send_file_data(conn, &file, 0, INT64_MAX);
11938 }
11939 (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
11940 }
11941}
11942
11943
11944#if !defined(NO_POPEN)
11945static void
11946do_ssi_exec(struct mg_connection *conn, char *tag)
11947{
11948 char cmd[1024] = "";
11949 struct mg_file file = STRUCT_FILE_INITIALIZER;
11950
11951 if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
11952 mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
11953 } else {
11954 cmd[1023] = 0;
11955 if ((file.access.fp = popen(cmd, "r")) == NULL) {
11956 mg_cry_internal(conn,
11957 "Cannot SSI #exec: [%s]: %s",
11958 cmd,
11959 strerror(ERRNO));
11960 } else {
11961 send_file_data(conn, &file, 0, INT64_MAX);
11962 pclose(file.access.fp);
11963 }
11964 }
11965}
11966#endif /* !NO_POPEN */
11967
11968
11969static int
11970mg_fgetc(struct mg_file *filep)
11971{
11972 if (filep == NULL) {
11973 return EOF;
11974 }
11975
11976 if (filep->access.fp != NULL) {
11977 return fgetc(filep->access.fp);
11978 } else {
11979 return EOF;
11980 }
11981}
11982
11983
11984static void
11986 const char *path,
11987 struct mg_file *filep,
11988 int include_level)
11989{
11990 char buf[MG_BUF_LEN];
11991 int ch, len, in_tag, in_ssi_tag;
11992
11993 if (include_level > 10) {
11994 mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
11995 return;
11996 }
11997
11998 in_tag = in_ssi_tag = len = 0;
11999
12000 /* Read file, byte by byte, and look for SSI include tags */
12001 while ((ch = mg_fgetc(filep)) != EOF) {
12002
12003 if (in_tag) {
12004 /* We are in a tag, either SSI tag or html tag */
12005
12006 if (ch == '>') {
12007 /* Tag is closing */
12008 buf[len++] = '>';
12009
12010 if (in_ssi_tag) {
12011 /* Handle SSI tag */
12012 buf[len] = 0;
12013
12014 if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
12015 do_ssi_include(conn, path, buf + 12, include_level + 1);
12016#if !defined(NO_POPEN)
12017 } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
12018 do_ssi_exec(conn, buf + 9);
12019#endif /* !NO_POPEN */
12020 } else {
12021 mg_cry_internal(conn,
12022 "%s: unknown SSI "
12023 "command: \"%s\"",
12024 path,
12025 buf);
12026 }
12027 len = 0;
12028 in_ssi_tag = in_tag = 0;
12029
12030 } else {
12031 /* Not an SSI tag */
12032 /* Flush buffer */
12033 (void)mg_write(conn, buf, (size_t)len);
12034 len = 0;
12035 in_tag = 0;
12036 }
12037
12038 } else {
12039 /* Tag is still open */
12040 buf[len++] = (char)(ch & 0xff);
12041
12042 if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
12043 /* All SSI tags start with <!--# */
12044 in_ssi_tag = 1;
12045 }
12046
12047 if ((len + 2) > (int)sizeof(buf)) {
12048 /* Tag to long for buffer */
12049 mg_cry_internal(conn, "%s: tag is too large", path);
12050 return;
12051 }
12052 }
12053
12054 } else {
12055
12056 /* We are not in a tag yet. */
12057 if (ch == '<') {
12058 /* Tag is opening */
12059 in_tag = 1;
12060
12061 if (len > 0) {
12062 /* Flush current buffer.
12063 * Buffer is filled with "len" bytes. */
12064 (void)mg_write(conn, buf, (size_t)len);
12065 }
12066 /* Store the < */
12067 len = 1;
12068 buf[0] = '<';
12069
12070 } else {
12071 /* No Tag */
12072 /* Add data to buffer */
12073 buf[len++] = (char)(ch & 0xff);
12074 /* Flush if buffer is full */
12075 if (len == (int)sizeof(buf)) {
12076 mg_write(conn, buf, (size_t)len);
12077 len = 0;
12078 }
12079 }
12080 }
12081 }
12082
12083 /* Send the rest of buffered data */
12084 if (len > 0) {
12085 mg_write(conn, buf, (size_t)len);
12086 }
12087}
12088
12089
12090static void
12092 const char *path,
12093 struct mg_file *filep)
12094{
12095 char date[64];
12096 time_t curtime = time(NULL);
12097 const char *cors_orig_cfg, *cors_cred_cfg;
12098 const char *cors1, *cors2, *cors3, *cors4;
12099
12100 if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
12101 return;
12102 }
12103
12104 cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
12105 if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
12106 /* Cross-origin resource sharing (CORS). */
12107 cors1 = "Access-Control-Allow-Origin";
12108 cors2 = cors_orig_cfg;
12109 } else {
12110 cors1 = cors2 = "";
12111 }
12112
12113 cors_cred_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
12114 if (cors_cred_cfg && *cors_cred_cfg && mg_get_header(conn, "Origin")) {
12115 /* Credentials CORS header */
12116 cors3 = "Access-Control-Allow-Credentials";
12117 cors4 = cors_cred_cfg;
12118 } else {
12119 cors3 = cors4 = "";
12120 }
12121
12122 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
12123 /* File exists (precondition for calling this function),
12124 * but can not be opened by the server. */
12125 mg_send_http_error(conn,
12126 500,
12127 "Error: Cannot read file\nfopen(%s): %s",
12128 path,
12129 strerror(ERRNO));
12130 } else {
12131 /* Set "must_close" for HTTP/1.x, since we do not know the
12132 * content length */
12133 conn->must_close = 1;
12134 gmt_time_string(date, sizeof(date), &curtime);
12135 fclose_on_exec(&filep->access, conn);
12136
12137 /* 200 OK response */
12138 mg_response_header_start(conn, 200);
12141 mg_response_header_add(conn, "Content-Type", "text/html", -1);
12142 if (cors1[0]) {
12143 mg_response_header_add(conn, cors1, cors2, -1);
12144 }
12145 if (cors3[0]) {
12146 mg_response_header_add(conn, cors3, cors4, -1);
12147 }
12149
12150 /* Header sent, now send body */
12151 send_ssi_file(conn, path, filep, 0);
12152 (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
12153 }
12154}
12155#endif /* NO_FILESYSTEMS */
12156
12157
12158#if !defined(NO_FILES)
12159static void
12161{
12162 if (!conn) {
12163 return;
12164 }
12165
12166 /* We do not set a "Cache-Control" header here, but leave the default.
12167 * Since browsers do not send an OPTIONS request, we can not test the
12168 * effect anyway. */
12169
12170 mg_response_header_start(conn, 200);
12171 mg_response_header_add(conn, "Content-Type", "text/html", -1);
12172 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
12173 /* Use the same as before */
12175 conn,
12176 "Allow",
12177 "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
12178 -1);
12179 mg_response_header_add(conn, "DAV", "1", -1);
12180 } else {
12181 /* TODO: Check this later for HTTP/2 */
12182 mg_response_header_add(conn, "Allow", "GET, POST", -1);
12183 }
12186}
12187
12188
12189/* Writes PROPFIND properties for a collection element */
12190static int
12192 const char *uri,
12193 const char *name,
12194 struct mg_file_stat *filep)
12195{
12196 size_t href_size, i, j;
12197 int len;
12198 char *href, mtime[64];
12199
12200 if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
12201 return 0;
12202 }
12203 /* Estimate worst case size for encoding */
12204 href_size = (strlen(uri) + strlen(name)) * 3 + 1;
12205 href = (char *)mg_malloc(href_size);
12206 if (href == NULL) {
12207 return 0;
12208 }
12209 len = mg_url_encode(uri, href, href_size);
12210 if (len >= 0) {
12211 /* Append an extra string */
12212 mg_url_encode(name, href + len, href_size - (size_t)len);
12213 }
12214 /* Directory separator should be preserved. */
12215 for (i = j = 0; href[i]; j++) {
12216 if (!strncmp(href + i, "%2f", 3)) {
12217 href[j] = '/';
12218 i += 3;
12219 } else {
12220 href[j] = href[i++];
12221 }
12222 }
12223 href[j] = '\0';
12224
12225 gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
12226 mg_printf(conn,
12227 "<d:response>"
12228 "<d:href>%s</d:href>"
12229 "<d:propstat>"
12230 "<d:prop>"
12231 "<d:resourcetype>%s</d:resourcetype>"
12232 "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
12233 "<d:getlastmodified>%s</d:getlastmodified>"
12234 "</d:prop>"
12235 "<d:status>HTTP/1.1 200 OK</d:status>"
12236 "</d:propstat>"
12237 "</d:response>\n",
12238 href,
12239 filep->is_directory ? "<d:collection/>" : "",
12240 filep->size,
12241 mtime);
12242 mg_free(href);
12243 return 1;
12244}
12245
12246
12247static int
12249{
12250 struct mg_connection *conn = (struct mg_connection *)data;
12251 if (!de || !conn
12252 || !print_props(
12253 conn, conn->request_info.local_uri, de->file_name, &de->file)) {
12254 /* stop scan */
12255 return 1;
12256 }
12257 return 0;
12258}
12259
12260
12261static void
12263 const char *path,
12264 struct mg_file_stat *filep)
12265{
12266 const char *depth = mg_get_header(conn, "Depth");
12267 char date[64];
12268 time_t curtime = time(NULL);
12269
12270 gmt_time_string(date, sizeof(date), &curtime);
12271
12272 if (!conn || !path || !filep || !conn->dom_ctx) {
12273 return;
12274 }
12275
12276 conn->must_close = 1;
12277
12278 /* return 207 "Multi-Status" */
12279 mg_response_header_start(conn, 207);
12282 mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
12284
12285 /* Content */
12286 mg_printf(conn,
12287 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12288 "<d:multistatus xmlns:d='DAV:'>\n");
12289
12290 /* Print properties for the requested resource itself */
12291 print_props(conn, conn->request_info.local_uri, "", filep);
12292
12293 /* If it is a directory, print directory entries too if Depth is not 0
12294 */
12295 if (filep->is_directory
12297 "yes")
12298 && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
12299 scan_directory(conn, path, conn, &print_dav_dir_entry);
12300 }
12301
12302 mg_printf(conn, "%s\n", "</d:multistatus>");
12303}
12304#endif
12305
12306void
12308{
12309 if (conn) {
12310 (void)pthread_mutex_lock(&conn->mutex);
12311 }
12312}
12313
12314void
12316{
12317 if (conn) {
12318 (void)pthread_mutex_unlock(&conn->mutex);
12319 }
12320}
12321
12322void
12324{
12325 if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
12326 (void)pthread_mutex_lock(&ctx->nonce_mutex);
12327 }
12328}
12329
12330void
12332{
12333 if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
12334 (void)pthread_mutex_unlock(&ctx->nonce_mutex);
12335 }
12336}
12337
12338
12339#if defined(USE_LUA)
12340#include "mod_lua.inl"
12341#endif /* USE_LUA */
12342
12343#if defined(USE_DUKTAPE)
12344#include "mod_duktape.inl"
12345#endif /* USE_DUKTAPE */
12346
12347#if defined(USE_WEBSOCKET)
12348
12349#if !defined(NO_SSL_DL)
12350#if !defined(OPENSSL_API_3_0)
12351#define SHA_API static
12352#include "sha1.inl"
12353#endif
12354#endif
12355
12356static int
12357send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
12358{
12359 static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
12360 char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
12361#if !defined(OPENSSL_API_3_0)
12362 SHA_CTX sha_ctx;
12363#endif
12364 int truncated;
12365
12366 /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
12367 mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
12368 if (truncated) {
12369 conn->must_close = 1;
12370 return 0;
12371 }
12372
12373 DEBUG_TRACE("%s", "Send websocket handshake");
12374
12375#if defined(OPENSSL_API_3_0)
12376 EVP_Digest((unsigned char *)buf, (uint32_t)strlen(buf), (unsigned char *)sha,
12377 NULL, EVP_get_digestbyname("sha1"), NULL);
12378#else
12379 SHA1_Init(&sha_ctx);
12380 SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
12381 SHA1_Final((unsigned char *)sha, &sha_ctx);
12382#endif
12383 base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
12384 mg_printf(conn,
12385 "HTTP/1.1 101 Switching Protocols\r\n"
12386 "Upgrade: websocket\r\n"
12387 "Connection: Upgrade\r\n"
12388 "Sec-WebSocket-Accept: %s\r\n",
12389 b64_sha);
12390
12391#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12392 // Send negotiated compression extension parameters
12393 websocket_deflate_response(conn);
12394#endif
12395
12397 mg_printf(conn,
12398 "Sec-WebSocket-Protocol: %s\r\n\r\n",
12400 } else {
12401 mg_printf(conn, "%s", "\r\n");
12402 }
12403
12404 return 1;
12405}
12406
12407
12408#if !defined(MG_MAX_UNANSWERED_PING)
12409/* Configuration of the maximum number of websocket PINGs that might
12410 * stay unanswered before the connection is considered broken.
12411 * Note: The name of this define may still change (until it is
12412 * defined as a compile parameter in a documentation).
12413 */
12414#define MG_MAX_UNANSWERED_PING (5)
12415#endif
12416
12417
12418static void
12419read_websocket(struct mg_connection *conn,
12420 mg_websocket_data_handler ws_data_handler,
12421 void *callback_data)
12422{
12423 /* Pointer to the beginning of the portion of the incoming websocket
12424 * message queue.
12425 * The original websocket upgrade request is never removed, so the queue
12426 * begins after it. */
12427 unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
12428 int n, error, exit_by_callback;
12429 int ret;
12430
12431 /* body_len is the length of the entire queue in bytes
12432 * len is the length of the current message
12433 * data_len is the length of the current message's data payload
12434 * header_len is the length of the current message's header */
12435 size_t i, len, mask_len = 0, header_len, body_len;
12436 uint64_t data_len = 0;
12437
12438 /* "The masking key is a 32-bit value chosen at random by the client."
12439 * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
12440 */
12441 unsigned char mask[4];
12442
12443 /* data points to the place where the message is stored when passed to
12444 * the websocket_data callback. This is either mem on the stack, or a
12445 * dynamically allocated buffer if it is too large. */
12446 unsigned char mem[4096];
12447 unsigned char mop; /* mask flag and opcode */
12448
12449
12450 /* Variables used for connection monitoring */
12451 double timeout = -1.0;
12452 int enable_ping_pong = 0;
12453 int ping_count = 0;
12454
12455 if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
12456 enable_ping_pong =
12457 !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
12458 "yes");
12459 }
12460
12461 if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
12462 timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
12463 }
12464 if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
12465 timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
12466 }
12467 if (timeout <= 0.0) {
12468 timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
12469 }
12470
12471 /* Enter data processing loop */
12472 DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
12475 conn->in_websocket_handling = 1;
12476 mg_set_thread_name("wsock");
12477
12478 /* Loop continuously, reading messages from the socket, invoking the
12479 * callback, and waiting repeatedly until an error occurs. */
12480 while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
12481 && (!conn->must_close)) {
12482 header_len = 0;
12483 DEBUG_ASSERT(conn->data_len >= conn->request_len);
12484 if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
12485 len = buf[1] & 127;
12486 mask_len = (buf[1] & 128) ? 4 : 0;
12487 if ((len < 126) && (body_len >= mask_len)) {
12488 /* inline 7-bit length field */
12489 data_len = len;
12490 header_len = 2 + mask_len;
12491 } else if ((len == 126) && (body_len >= (4 + mask_len))) {
12492 /* 16-bit length field */
12493 header_len = 4 + mask_len;
12494 data_len = ((((size_t)buf[2]) << 8) + buf[3]);
12495 } else if (body_len >= (10 + mask_len)) {
12496 /* 64-bit length field */
12497 uint32_t l1, l2;
12498 memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
12499 memcpy(&l2, &buf[6], 4);
12500 header_len = 10 + mask_len;
12501 data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
12502
12503 if (data_len > (uint64_t)0x7FFF0000ul) {
12504 /* no can do */
12506 conn,
12507 "%s",
12508 "websocket out of memory; closing connection");
12509 break;
12510 }
12511 }
12512 }
12513
12514 if ((header_len > 0) && (body_len >= header_len)) {
12515 /* Allocate space to hold websocket payload */
12516 unsigned char *data = mem;
12517
12518 if ((size_t)data_len > (size_t)sizeof(mem)) {
12519 data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
12520 conn->phys_ctx);
12521 if (data == NULL) {
12522 /* Allocation failed, exit the loop and then close the
12523 * connection */
12525 conn,
12526 "%s",
12527 "websocket out of memory; closing connection");
12528 break;
12529 }
12530 }
12531
12532 /* Copy the mask before we shift the queue and destroy it */
12533 if (mask_len > 0) {
12534 memcpy(mask, buf + header_len - mask_len, sizeof(mask));
12535 } else {
12536 memset(mask, 0, sizeof(mask));
12537 }
12538
12539 /* Read frame payload from the first message in the queue into
12540 * data and advance the queue by moving the memory in place. */
12541 DEBUG_ASSERT(body_len >= header_len);
12542 if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
12543 mop = buf[0]; /* current mask and opcode */
12544 /* Overflow case */
12545 len = body_len - header_len;
12546 memcpy(data, buf + header_len, len);
12547 error = 0;
12548 while ((uint64_t)len < data_len) {
12549 n = pull_inner(NULL,
12550 conn,
12551 (char *)(data + len),
12552 (int)(data_len - len),
12553 timeout);
12554 if (n <= -2) {
12555 error = 1;
12556 break;
12557 } else if (n > 0) {
12558 len += (size_t)n;
12559 } else {
12560 /* Timeout: should retry */
12561 /* TODO: retry condition */
12562 }
12563 }
12564 if (error) {
12566 conn,
12567 "%s",
12568 "Websocket pull failed; closing connection");
12569 if (data != mem) {
12570 mg_free(data);
12571 }
12572 break;
12573 }
12574
12575 conn->data_len = conn->request_len;
12576
12577 } else {
12578
12579 mop = buf[0]; /* current mask and opcode, overwritten by
12580 * memmove() */
12581
12582 /* Length of the message being read at the front of the
12583 * queue. Cast to 31 bit is OK, since we limited
12584 * data_len before. */
12585 len = (size_t)data_len + header_len;
12586
12587 /* Copy the data payload into the data pointer for the
12588 * callback. Cast to 31 bit is OK, since we
12589 * limited data_len */
12590 memcpy(data, buf + header_len, (size_t)data_len);
12591
12592 /* Move the queue forward len bytes */
12593 memmove(buf, buf + len, body_len - len);
12594
12595 /* Mark the queue as advanced */
12596 conn->data_len -= (int)len;
12597 }
12598
12599 /* Apply mask if necessary */
12600 if (mask_len > 0) {
12601 for (i = 0; i < (size_t)data_len; i++) {
12602 data[i] ^= mask[i & 3];
12603 }
12604 }
12605
12606 exit_by_callback = 0;
12607 if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
12608 /* filter PONG messages */
12609 DEBUG_TRACE("PONG from %s:%u",
12612 /* No unanwered PINGs left */
12613 ping_count = 0;
12614 } else if (enable_ping_pong
12615 && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
12616 /* reply PING messages */
12617 DEBUG_TRACE("Reply PING from %s:%u",
12620 ret = mg_websocket_write(conn,
12622 (char *)data,
12623 (size_t)data_len);
12624 if (ret <= 0) {
12625 /* Error: send failed */
12626 DEBUG_TRACE("Reply PONG failed (%i)", ret);
12627 break;
12628 }
12629
12630
12631 } else {
12632 /* Exit the loop if callback signals to exit (server side),
12633 * or "connection close" opcode received (client side). */
12634 if (ws_data_handler != NULL) {
12635#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12636 if (mop & 0x40) {
12637 /* Inflate the data received if bit RSV1 is set. */
12638 if (!conn->websocket_deflate_initialized) {
12639 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12640 exit_by_callback = 1;
12641 }
12642 if (!exit_by_callback) {
12643 size_t inflate_buf_size_old = 0;
12644 size_t inflate_buf_size =
12645 data_len
12646 * 4; // Initial guess of the inflated message
12647 // size. We double the memory when needed.
12648 Bytef *inflated = NULL;
12649 Bytef *new_mem = NULL;
12650 conn->websocket_inflate_state.avail_in =
12651 (uInt)(data_len + 4);
12652 conn->websocket_inflate_state.next_in = data;
12653 // Add trailing 0x00 0x00 0xff 0xff bytes
12654 data[data_len] = '\x00';
12655 data[data_len + 1] = '\x00';
12656 data[data_len + 2] = '\xff';
12657 data[data_len + 3] = '\xff';
12658 do {
12659 if (inflate_buf_size_old == 0) {
12660 new_mem =
12661 (Bytef *)mg_calloc(inflate_buf_size,
12662 sizeof(Bytef));
12663 } else {
12664 inflate_buf_size *= 2;
12665 new_mem =
12666 (Bytef *)mg_realloc(inflated,
12667 inflate_buf_size);
12668 }
12669 if (new_mem == NULL) {
12671 conn,
12672 "Out of memory: Cannot allocate "
12673 "inflate buffer of %lu bytes",
12674 (unsigned long)inflate_buf_size);
12675 exit_by_callback = 1;
12676 break;
12677 }
12678 inflated = new_mem;
12679 conn->websocket_inflate_state.avail_out =
12680 (uInt)(inflate_buf_size
12681 - inflate_buf_size_old);
12682 conn->websocket_inflate_state.next_out =
12683 inflated + inflate_buf_size_old;
12684 ret = inflate(&conn->websocket_inflate_state,
12685 Z_SYNC_FLUSH);
12686 if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
12687 || ret == Z_MEM_ERROR) {
12689 conn,
12690 "ZLIB inflate error: %i %s",
12691 ret,
12692 (conn->websocket_inflate_state.msg
12693 ? conn->websocket_inflate_state.msg
12694 : "<no error message>"));
12695 exit_by_callback = 1;
12696 break;
12697 }
12698 inflate_buf_size_old = inflate_buf_size;
12699
12700 } while (conn->websocket_inflate_state.avail_out
12701 == 0);
12702 inflate_buf_size -=
12703 conn->websocket_inflate_state.avail_out;
12704 if (!ws_data_handler(conn,
12705 mop,
12706 (char *)inflated,
12707 inflate_buf_size,
12708 callback_data)) {
12709 exit_by_callback = 1;
12710 }
12711 mg_free(inflated);
12712 }
12713 } else
12714#endif
12715 if (!ws_data_handler(conn,
12716 mop,
12717 (char *)data,
12718 (size_t)data_len,
12719 callback_data)) {
12720 exit_by_callback = 1;
12721 }
12722 }
12723 }
12724
12725 /* It a buffer has been allocated, free it again */
12726 if (data != mem) {
12727 mg_free(data);
12728 }
12729
12730 if (exit_by_callback) {
12731 DEBUG_TRACE("Callback requests to close connection from %s:%u",
12734 break;
12735 }
12736 if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
12737 /* Opcode == 8, connection close */
12738 DEBUG_TRACE("Message requests to close connection from %s:%u",
12741 break;
12742 }
12743
12744 /* Not breaking the loop, process next websocket frame. */
12745 } else {
12746 /* Read from the socket into the next available location in the
12747 * message queue. */
12748 n = pull_inner(NULL,
12749 conn,
12750 conn->buf + conn->data_len,
12751 conn->buf_size - conn->data_len,
12752 timeout);
12753 if (n <= -2) {
12754 /* Error, no bytes read */
12755 DEBUG_TRACE("PULL from %s:%u failed",
12758 break;
12759 }
12760 if (n > 0) {
12761 conn->data_len += n;
12762 /* Reset open PING count */
12763 ping_count = 0;
12764 } else {
12766 && (!conn->must_close)) {
12767 if (ping_count > MG_MAX_UNANSWERED_PING) {
12768 /* Stop sending PING */
12769 DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
12770 "- closing connection",
12771 ping_count,
12774 break;
12775 }
12776 if (enable_ping_pong) {
12777 /* Send Websocket PING message */
12778 DEBUG_TRACE("PING to %s:%u",
12781 ret = mg_websocket_write(conn,
12783 NULL,
12784 0);
12785
12786 if (ret <= 0) {
12787 /* Error: send failed */
12788 DEBUG_TRACE("Send PING failed (%i)", ret);
12789 break;
12790 }
12791 ping_count++;
12792 }
12793 }
12794 /* Timeout: should retry */
12795 /* TODO: get timeout def */
12796 }
12797 }
12798 }
12799
12800 /* Leave data processing loop */
12801 mg_set_thread_name("worker");
12802 conn->in_websocket_handling = 0;
12803 DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
12806}
12807
12808
12809static int
12810mg_websocket_write_exec(struct mg_connection *conn,
12811 int opcode,
12812 const char *data,
12813 size_t dataLen,
12814 uint32_t masking_key)
12815{
12816 unsigned char header[14];
12817 size_t headerLen;
12818 int retval;
12819
12820#if defined(GCC_DIAGNOSTIC)
12821 /* Disable spurious conversion warning for GCC */
12822#pragma GCC diagnostic push
12823#pragma GCC diagnostic ignored "-Wconversion"
12824#endif
12825
12826 /* Note that POSIX/Winsock's send() is threadsafe
12827 * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
12828 * but mongoose's mg_printf/mg_write is not (because of the loop in
12829 * push(), although that is only a problem if the packet is large or
12830 * outgoing buffer is full). */
12831
12832 /* TODO: Check if this lock should be moved to user land.
12833 * Currently the server sets this lock for websockets, but
12834 * not for any other connection. It must be set for every
12835 * conn read/written by more than one thread, no matter if
12836 * it is a websocket or regular connection. */
12837 (void)mg_lock_connection(conn);
12838
12839#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12840 size_t deflated_size = 0;
12841 Bytef *deflated = 0;
12842 // Deflate websocket messages over 100kb
12843 int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
12844
12845 if (use_deflate) {
12846 if (!conn->websocket_deflate_initialized) {
12847 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12848 return 0;
12849 }
12850
12851 // Deflating the message
12852 header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
12853 conn->websocket_deflate_state.avail_in = (uInt)dataLen;
12854 conn->websocket_deflate_state.next_in = (unsigned char *)data;
12855 deflated_size = (Bytef *)compressBound((uLong)dataLen);
12856 deflated = mg_calloc(deflated_size, sizeof(Bytef));
12857 if (deflated == NULL) {
12859 conn,
12860 "Out of memory: Cannot allocate deflate buffer of %lu bytes",
12861 (unsigned long)deflated_size);
12863 return -1;
12864 }
12865 conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
12866 conn->websocket_deflate_state.next_out = deflated;
12867 deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
12868 dataLen = deflated_size - conn->websocket_deflate_state.avail_out
12869 - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
12870 } else
12871#endif
12872 header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
12873
12874#if defined(GCC_DIAGNOSTIC)
12875#pragma GCC diagnostic pop
12876#endif
12877
12878 /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
12879 if (dataLen < 126) {
12880 /* inline 7-bit length field */
12881 header[1] = (unsigned char)dataLen;
12882 headerLen = 2;
12883 } else if (dataLen <= 0xFFFF) {
12884 /* 16-bit length field */
12885 uint16_t len = htons((uint16_t)dataLen);
12886 header[1] = 126;
12887 memcpy(header + 2, &len, 2);
12888 headerLen = 4;
12889 } else {
12890 /* 64-bit length field */
12891 uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
12892 uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
12893 header[1] = 127;
12894 memcpy(header + 2, &len1, 4);
12895 memcpy(header + 6, &len2, 4);
12896 headerLen = 10;
12897 }
12898
12899 if (masking_key) {
12900 /* add mask */
12901 header[1] |= 0x80;
12902 memcpy(header + headerLen, &masking_key, 4);
12903 headerLen += 4;
12904 }
12905
12906 retval = mg_write(conn, header, headerLen);
12907 if (retval != (int)headerLen) {
12908 /* Did not send complete header */
12909 retval = -1;
12910 } else {
12911 if (dataLen > 0) {
12912#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12913 if (use_deflate) {
12914 retval = mg_write(conn, deflated, dataLen);
12915 mg_free(deflated);
12916 } else
12917#endif
12918 retval = mg_write(conn, data, dataLen);
12919 }
12920 /* if dataLen == 0, the header length (2) is returned */
12921 }
12922
12923 /* TODO: Remove this unlock as well, when lock is removed. */
12925
12926 return retval;
12927}
12928
12929int
12931 int opcode,
12932 const char *data,
12933 size_t dataLen)
12934{
12935 return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
12936}
12937
12938
12939static void
12940mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
12941{
12942 size_t i = 0;
12943
12944 i = 0;
12945 if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
12946 /* Convert in 32 bit words, if data is 4 byte aligned */
12947 while (i < (in_len - 3)) {
12948 *(uint32_t *)(void *)(out + i) =
12949 *(uint32_t *)(void *)(in + i) ^ masking_key;
12950 i += 4;
12951 }
12952 }
12953 if (i != in_len) {
12954 /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
12955 while (i < in_len) {
12956 *(uint8_t *)(void *)(out + i) =
12957 *(uint8_t *)(void *)(in + i)
12958 ^ *(((uint8_t *)&masking_key) + (i % 4));
12959 i++;
12960 }
12961 }
12962}
12963
12964
12965int
12967 int opcode,
12968 const char *data,
12969 size_t dataLen)
12970{
12971 int retval = -1;
12972 char *masked_data =
12973 (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
12974 uint32_t masking_key = 0;
12975
12976 if (masked_data == NULL) {
12977 /* Return -1 in an error case */
12978 mg_cry_internal(conn,
12979 "%s",
12980 "Cannot allocate buffer for masked websocket response: "
12981 "Out of memory");
12982 return -1;
12983 }
12984
12985 do {
12986 /* Get a masking key - but not 0 */
12987 masking_key = (uint32_t)get_random();
12988 } while (masking_key == 0);
12989
12990 mask_data(data, dataLen, masking_key, masked_data);
12991
12992 retval = mg_websocket_write_exec(
12993 conn, opcode, masked_data, dataLen, masking_key);
12994 mg_free(masked_data);
12995
12996 return retval;
12997}
12998
12999
13000static void
13001handle_websocket_request(struct mg_connection *conn,
13002 const char *path,
13003 int is_callback_resource,
13004 struct mg_websocket_subprotocols *subprotocols,
13005 mg_websocket_connect_handler ws_connect_handler,
13006 mg_websocket_ready_handler ws_ready_handler,
13007 mg_websocket_data_handler ws_data_handler,
13008 mg_websocket_close_handler ws_close_handler,
13009 void *cbData)
13010{
13011 const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
13012 const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
13013 ptrdiff_t lua_websock = 0;
13014
13015#if !defined(USE_LUA)
13016 (void)path;
13017#endif
13018
13019 /* Step 1: Check websocket protocol version. */
13020 /* Step 1.1: Check Sec-WebSocket-Key. */
13021 if (!websock_key) {
13022 /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
13023 * requires a Sec-WebSocket-Key header.
13024 */
13025 /* It could be the hixie draft version
13026 * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
13027 */
13028 const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
13029 const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
13030 char key3[8];
13031
13032 if ((key1 != NULL) && (key2 != NULL)) {
13033 /* This version uses 8 byte body data in a GET request */
13034 conn->content_len = 8;
13035 if (8 == mg_read(conn, key3, 8)) {
13036 /* This is the hixie version */
13037 mg_send_http_error(conn,
13038 426,
13039 "%s",
13040 "Protocol upgrade to RFC 6455 required");
13041 return;
13042 }
13043 }
13044 /* This is an unknown version */
13045 mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
13046 return;
13047 }
13048
13049 /* Step 1.2: Check websocket protocol version. */
13050 /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
13051 if ((version == NULL) || (strcmp(version, "13") != 0)) {
13052 /* Reject wrong versions */
13053 mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
13054 return;
13055 }
13056
13057 /* Step 1.3: Could check for "Host", but we do not really nead this
13058 * value for anything, so just ignore it. */
13059
13060 /* Step 2: If a callback is responsible, call it. */
13061 if (is_callback_resource) {
13062 /* Step 2.1 check and select subprotocol */
13063 const char *protocols[64]; // max 64 headers
13064 int nbSubprotocolHeader = get_req_headers(&conn->request_info,
13065 "Sec-WebSocket-Protocol",
13066 protocols,
13067 64);
13068 if ((nbSubprotocolHeader > 0) && subprotocols) {
13069 int cnt = 0;
13070 int idx;
13071 unsigned long len;
13072 const char *sep, *curSubProtocol,
13073 *acceptedWebSocketSubprotocol = NULL;
13074
13075
13076 /* look for matching subprotocol */
13077 do {
13078 const char *protocol = protocols[cnt];
13079
13080 do {
13081 sep = strchr(protocol, ',');
13082 curSubProtocol = protocol;
13083 len = sep ? (unsigned long)(sep - protocol)
13084 : (unsigned long)strlen(protocol);
13085 while (sep && isspace((unsigned char)*++sep))
13086 ; // ignore leading whitespaces
13087 protocol = sep;
13088
13089 for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
13090 if ((strlen(subprotocols->subprotocols[idx]) == len)
13091 && (strncmp(curSubProtocol,
13092 subprotocols->subprotocols[idx],
13093 len)
13094 == 0)) {
13095 acceptedWebSocketSubprotocol =
13096 subprotocols->subprotocols[idx];
13097 break;
13098 }
13099 }
13100 } while (sep && !acceptedWebSocketSubprotocol);
13101 } while (++cnt < nbSubprotocolHeader
13102 && !acceptedWebSocketSubprotocol);
13103
13105 acceptedWebSocketSubprotocol;
13106
13107 } else if (nbSubprotocolHeader > 0) {
13108 /* keep legacy behavior */
13109 const char *protocol = protocols[0];
13110
13111 /* The protocol is a comma separated list of names. */
13112 /* The server must only return one value from this list. */
13113 /* First check if it is a list or just a single value. */
13114 const char *sep = strrchr(protocol, ',');
13115 if (sep == NULL) {
13116 /* Just a single protocol -> accept it. */
13118 } else {
13119 /* Multiple protocols -> accept the last one. */
13120 /* This is just a quick fix if the client offers multiple
13121 * protocols. The handler should have a list of accepted
13122 * protocols on his own
13123 * and use it to select one protocol among those the client
13124 * has
13125 * offered.
13126 */
13127 while (isspace((unsigned char)*++sep)) {
13128 ; /* ignore leading whitespaces */
13129 }
13131 }
13132 }
13133
13134#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13135 websocket_deflate_negotiate(conn);
13136#endif
13137
13138 if ((ws_connect_handler != NULL)
13139 && (ws_connect_handler(conn, cbData) != 0)) {
13140 /* C callback has returned non-zero, do not proceed with
13141 * handshake.
13142 */
13143 /* Note that C callbacks are no longer called when Lua is
13144 * responsible, so C can no longer filter callbacks for Lua. */
13145 return;
13146 }
13147 }
13148
13149#if defined(USE_LUA)
13150 /* Step 3: No callback. Check if Lua is responsible. */
13151 else {
13152 /* Step 3.1: Check if Lua is responsible. */
13153 if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
13154 lua_websock = match_prefix_strlen(
13155 conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
13156 }
13157
13158 if (lua_websock) {
13159 /* Step 3.2: Lua is responsible: call it. */
13160 conn->lua_websocket_state = lua_websocket_new(path, conn);
13161 if (!conn->lua_websocket_state) {
13162 /* Lua rejected the new client */
13163 return;
13164 }
13165 }
13166 }
13167#endif
13168
13169 /* Step 4: Check if there is a responsible websocket handler. */
13170 if (!is_callback_resource && !lua_websock) {
13171 /* There is no callback, and Lua is not responsible either. */
13172 /* Reply with a 404 Not Found. We are still at a standard
13173 * HTTP request here, before the websocket handshake, so
13174 * we can still send standard HTTP error replies. */
13175 mg_send_http_error(conn, 404, "%s", "Not found");
13176 return;
13177 }
13178
13179 /* Step 5: The websocket connection has been accepted */
13180 if (!send_websocket_handshake(conn, websock_key)) {
13181 mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
13182 return;
13183 }
13184
13185 /* Step 6: Call the ready handler */
13186 if (is_callback_resource) {
13187 if (ws_ready_handler != NULL) {
13188 ws_ready_handler(conn, cbData);
13189 }
13190#if defined(USE_LUA)
13191 } else if (lua_websock) {
13192 if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
13193 /* the ready handler returned false */
13194 return;
13195 }
13196#endif
13197 }
13198
13199 /* Step 7: Enter the read loop */
13200 if (is_callback_resource) {
13201 read_websocket(conn, ws_data_handler, cbData);
13202#if defined(USE_LUA)
13203 } else if (lua_websock) {
13204 read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
13205#endif
13206 }
13207
13208#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13209 /* Step 8: Close the deflate & inflate buffers */
13210 if (conn->websocket_deflate_initialized) {
13211 deflateEnd(&conn->websocket_deflate_state);
13212 inflateEnd(&conn->websocket_inflate_state);
13213 }
13214#endif
13215
13216 /* Step 9: Call the close handler */
13217 if (ws_close_handler) {
13218 ws_close_handler(conn, cbData);
13219 }
13220}
13221#endif /* !USE_WEBSOCKET */
13222
13223
13224/* Is upgrade request:
13225 * 0 = regular HTTP/1.0 or HTTP/1.1 request
13226 * 1 = upgrade to websocket
13227 * 2 = upgrade to HTTP/2
13228 * -1 = upgrade to unknown protocol
13229 */
13230static int
13232{
13233 const char *upgrade, *connection;
13234
13235 /* A websocket protocoll has the following HTTP headers:
13236 *
13237 * Connection: Upgrade
13238 * Upgrade: Websocket
13239 */
13240
13241 connection = mg_get_header(conn, "Connection");
13242 if (connection == NULL) {
13243 return PROTOCOL_TYPE_HTTP1;
13244 }
13245 if (!mg_strcasestr(connection, "upgrade")) {
13246 return PROTOCOL_TYPE_HTTP1;
13247 }
13248
13249 upgrade = mg_get_header(conn, "Upgrade");
13250 if (upgrade == NULL) {
13251 /* "Connection: Upgrade" without "Upgrade" Header --> Error */
13252 return -1;
13253 }
13254
13255 /* Upgrade to ... */
13256 if (0 != mg_strcasestr(upgrade, "websocket")) {
13257 /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
13258 * "Sec-WebSocket-Version" are also required.
13259 * Don't check them here, since even an unsupported websocket protocol
13260 * request still IS a websocket request (in contrast to a standard HTTP
13261 * request). It will fail later in handle_websocket_request.
13262 */
13263 return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
13264 }
13265 if (0 != mg_strcasestr(upgrade, "h2")) {
13266 return PROTOCOL_TYPE_HTTP2; /* Websocket */
13267 }
13268
13269 /* Upgrade to another protocol */
13270 return -1;
13271}
13272
13273
13274static int
13275parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
13276{
13277 int n;
13278 unsigned int a, b, c, d, slash;
13279
13280 if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
13281 != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
13282 // integer value, but function will not report conversion
13283 // errors; consider using 'strtol' instead
13284 slash = 32;
13285 if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
13286 != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
13287 // an integer value, but function will not report conversion
13288 // errors; consider using 'strtol' instead
13289 n = 0;
13290 }
13291 }
13292
13293 if ((n > 0) && ((size_t)n == vec->len)) {
13294 if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
13295 /* IPv4 format */
13296 if (sa->sa.sa_family == AF_INET) {
13297 uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
13298 uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
13299 | ((uint32_t)c << 8) | (uint32_t)d;
13300 uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
13301 return (ip & mask) == net;
13302 }
13303 return 0;
13304 }
13305 }
13306#if defined(USE_IPV6)
13307 else {
13308 char ad[50];
13309 const char *p;
13310
13311 if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
13312 slash = 128;
13313 if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
13314 n = 0;
13315 }
13316 }
13317
13318 if ((n <= 0) && no_strict) {
13319 /* no square brackets? */
13320 p = strchr(vec->ptr, '/');
13321 if (p && (p < (vec->ptr + vec->len))) {
13322 if (((size_t)(p - vec->ptr) < sizeof(ad))
13323 && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
13324 n += (int)(p - vec->ptr);
13325 mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
13326 } else {
13327 n = 0;
13328 }
13329 } else if (vec->len < sizeof(ad)) {
13330 n = (int)vec->len;
13331 slash = 128;
13332 mg_strlcpy(ad, vec->ptr, vec->len + 1);
13333 }
13334 }
13335
13336 if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
13337 p = ad;
13338 c = 0;
13339 /* zone indexes are unsupported, at least two colons are needed */
13340 while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
13341 if (*(p++) == ':') {
13342 c++;
13343 }
13344 }
13345 if ((*p == '\0') && (c >= 2)) {
13346 struct sockaddr_in6 sin6;
13347 unsigned int i;
13348
13349 /* for strict validation, an actual IPv6 argument is needed */
13350 if (sa->sa.sa_family != AF_INET6) {
13351 return 0;
13352 }
13353 if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
13354 /* IPv6 format */
13355 for (i = 0; i < 16; i++) {
13356 uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
13357 uint8_t net = sin6.sin6_addr.s6_addr[i];
13358 uint8_t mask = 0;
13359
13360 if (8 * i + 8 < slash) {
13361 mask = 0xFFu;
13362 } else if (8 * i < slash) {
13363 mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
13364 }
13365 if ((ip & mask) != net) {
13366 return 0;
13367 }
13368 }
13369 return 1;
13370 }
13371 }
13372 }
13373 }
13374#else
13375 (void)no_strict;
13376#endif
13377
13378 /* malformed */
13379 return -1;
13380}
13381
13382
13383static int
13384set_throttle(const char *spec, const union usa *rsa, const char *uri)
13385{
13386 int throttle = 0;
13387 struct vec vec, val;
13388 char mult;
13389 double v;
13390
13391 while ((spec = next_option(spec, &vec, &val)) != NULL) {
13392 mult = ',';
13393 if ((val.ptr == NULL)
13394 || (sscanf(val.ptr, "%lf%c", &v, &mult)
13395 < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
13396 // to an integer value, but function will not report
13397 // conversion errors; consider using 'strtol' instead
13398 || (v < 0)
13399 || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
13400 && (mult != ','))) {
13401 continue;
13402 }
13403 v *= (lowercase(&mult) == 'k')
13404 ? 1024
13405 : ((lowercase(&mult) == 'm') ? 1048576 : 1);
13406 if (vec.len == 1 && vec.ptr[0] == '*') {
13407 throttle = (int)v;
13408 } else {
13409 int matched = parse_match_net(&vec, rsa, 0);
13410 if (matched >= 0) {
13411 /* a valid IP subnet */
13412 if (matched) {
13413 throttle = (int)v;
13414 }
13415 } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
13416 throttle = (int)v;
13417 }
13418 }
13419 }
13420
13421 return throttle;
13422}
13423
13424
13425/* The mg_upload function is superseeded by mg_handle_form_request. */
13426#include "handle_form.inl"
13427
13428
13429static int
13431{
13432 unsigned int i;
13433 int idx = -1;
13434 if (ctx) {
13435 for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
13436 idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
13437 }
13438 }
13439 return idx;
13440}
13441
13442
13443/* Return host (without port) */
13444static void
13445get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
13446{
13447 const char *host_header =
13448 get_header(ri->http_headers, ri->num_headers, "Host");
13449
13450 host->ptr = NULL;
13451 host->len = 0;
13452
13453 if (host_header != NULL) {
13454 const char *pos;
13455
13456 /* If the "Host" is an IPv6 address, like [::1], parse until ]
13457 * is found. */
13458 if (*host_header == '[') {
13459 pos = strchr(host_header, ']');
13460 if (!pos) {
13461 /* Malformed hostname starts with '[', but no ']' found */
13462 DEBUG_TRACE("%s", "Host name format error '[' without ']'");
13463 return;
13464 }
13465 /* terminate after ']' */
13466 host->ptr = host_header;
13467 host->len = (size_t)(pos + 1 - host_header);
13468 } else {
13469 /* Otherwise, a ':' separates hostname and port number */
13470 pos = strchr(host_header, ':');
13471 if (pos != NULL) {
13472 host->len = (size_t)(pos - host_header);
13473 } else {
13474 host->len = strlen(host_header);
13475 }
13476 host->ptr = host_header;
13477 }
13478 }
13479}
13480
13481
13482static int
13484{
13485 struct vec host;
13486
13488
13489 if (host.ptr) {
13490 if (conn->ssl) {
13491 /* This is a HTTPS connection, maybe we have a hostname
13492 * from SNI (set in ssl_servername_callback). */
13493 const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
13494 if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
13495 /* We are not using the default domain */
13496 if ((strlen(sslhost) != host.len)
13497 || mg_strncasecmp(host.ptr, sslhost, host.len)) {
13498 /* Mismatch between SNI domain and HTTP domain */
13499 DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
13500 sslhost,
13501 (int)host.len,
13502 host.ptr);
13503 return 0;
13504 }
13505 }
13506
13507 } else {
13508 struct mg_domain_context *dom = &(conn->phys_ctx->dd);
13509 while (dom) {
13510 const char *domName = dom->config[AUTHENTICATION_DOMAIN];
13511 size_t domNameLen = strlen(domName);
13512 if ((domNameLen == host.len)
13513 && !mg_strncasecmp(host.ptr, domName, host.len)) {
13514
13515 /* Found matching domain */
13516 DEBUG_TRACE("HTTP domain %s found",
13518
13519 /* TODO: Check if this is a HTTP or HTTPS domain */
13520 conn->dom_ctx = dom;
13521 break;
13522 }
13524 dom = dom->next;
13526 }
13527 }
13528
13529 DEBUG_TRACE("HTTP%s Host: %.*s",
13530 conn->ssl ? "S" : "",
13531 (int)host.len,
13532 host.ptr);
13533
13534 } else {
13535 DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
13536 return 1;
13537 }
13538
13539 return 1;
13540}
13541
13542
13543static void
13545{
13546 char target_url[MG_BUF_LEN];
13547 int truncated = 0;
13548 const char *expect_proto =
13549 (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
13550
13551 /* Use "308 Permanent Redirect" */
13552 int redirect_code = 308;
13553
13554 /* In any case, close the current connection */
13555 conn->must_close = 1;
13556
13557 /* Send host, port, uri and (if it exists) ?query_string */
13559 conn, target_url, sizeof(target_url), expect_proto, port, NULL)
13560 < 0) {
13561 truncated = 1;
13562 } else if (conn->request_info.query_string != NULL) {
13563 size_t slen1 = strlen(target_url);
13564 size_t slen2 = strlen(conn->request_info.query_string);
13565 if ((slen1 + slen2 + 2) < sizeof(target_url)) {
13566 target_url[slen1] = '?';
13567 memcpy(target_url + slen1 + 1,
13569 slen2);
13570 target_url[slen1 + slen2 + 1] = 0;
13571 } else {
13572 truncated = 1;
13573 }
13574 }
13575
13576 /* Check overflow in location buffer (will not occur if MG_BUF_LEN
13577 * is used as buffer size) */
13578 if (truncated) {
13579 mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
13580 return;
13581 }
13582
13583 /* Use redirect helper function */
13584 mg_send_http_redirect(conn, target_url, redirect_code);
13585}
13586
13587
13588static void
13590 struct mg_domain_context *dom_ctx,
13591 const char *uri,
13592 int handler_type,
13593 int is_delete_request,
13594 mg_request_handler handler,
13595 struct mg_websocket_subprotocols *subprotocols,
13596 mg_websocket_connect_handler connect_handler,
13597 mg_websocket_ready_handler ready_handler,
13598 mg_websocket_data_handler data_handler,
13599 mg_websocket_close_handler close_handler,
13600 mg_authorization_handler auth_handler,
13601 void *cbdata)
13602{
13603 struct mg_handler_info *tmp_rh, **lastref;
13604 size_t urilen = strlen(uri);
13605
13607 DEBUG_ASSERT(handler == NULL);
13608 DEBUG_ASSERT(is_delete_request || connect_handler != NULL
13609 || ready_handler != NULL || data_handler != NULL
13610 || close_handler != NULL);
13611
13612 DEBUG_ASSERT(auth_handler == NULL);
13613 if (handler != NULL) {
13614 return;
13615 }
13616 if (!is_delete_request && (connect_handler == NULL)
13617 && (ready_handler == NULL) && (data_handler == NULL)
13618 && (close_handler == NULL)) {
13619 return;
13620 }
13621 if (auth_handler != NULL) {
13622 return;
13623 }
13624
13625 } else if (handler_type == REQUEST_HANDLER) {
13626 DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13627 && data_handler == NULL && close_handler == NULL);
13628 DEBUG_ASSERT(is_delete_request || (handler != NULL));
13629 DEBUG_ASSERT(auth_handler == NULL);
13630
13631 if ((connect_handler != NULL) || (ready_handler != NULL)
13632 || (data_handler != NULL) || (close_handler != NULL)) {
13633 return;
13634 }
13635 if (!is_delete_request && (handler == NULL)) {
13636 return;
13637 }
13638 if (auth_handler != NULL) {
13639 return;
13640 }
13641
13642 } else if (handler_type == AUTH_HANDLER) {
13643 DEBUG_ASSERT(handler == NULL);
13644 DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13645 && data_handler == NULL && close_handler == NULL);
13646 DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
13647 if (handler != NULL) {
13648 return;
13649 }
13650 if ((connect_handler != NULL) || (ready_handler != NULL)
13651 || (data_handler != NULL) || (close_handler != NULL)) {
13652 return;
13653 }
13654 if (!is_delete_request && (auth_handler == NULL)) {
13655 return;
13656 }
13657 } else {
13658 /* Unknown handler type. */
13659 return;
13660 }
13661
13662 if (!phys_ctx || !dom_ctx) {
13663 /* no context available */
13664 return;
13665 }
13666
13667 mg_lock_context(phys_ctx);
13668
13669 /* first try to find an existing handler */
13670 do {
13671 lastref = &(dom_ctx->handlers);
13672 for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
13673 tmp_rh = tmp_rh->next) {
13674 if (tmp_rh->handler_type == handler_type
13675 && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
13676 if (!is_delete_request) {
13677 /* update existing handler */
13679 /* Wait for end of use before updating */
13680 if (tmp_rh->refcount) {
13681 mg_unlock_context(phys_ctx);
13682 mg_sleep(1);
13683 mg_lock_context(phys_ctx);
13684 /* tmp_rh might have been freed, search again. */
13685 break;
13686 }
13687 /* Ok, the handler is no more use -> Update it */
13688 tmp_rh->handler = handler;
13689 } else if (handler_type == WEBSOCKET_HANDLER) {
13690 tmp_rh->subprotocols = subprotocols;
13692 tmp_rh->ready_handler = ready_handler;
13693 tmp_rh->data_handler = data_handler;
13694 tmp_rh->close_handler = close_handler;
13695 } else { /* AUTH_HANDLER */
13696 tmp_rh->auth_handler = auth_handler;
13697 }
13698 tmp_rh->cbdata = cbdata;
13699 } else {
13700 /* remove existing handler */
13702 /* Wait for end of use before removing */
13703 if (tmp_rh->refcount) {
13704 tmp_rh->removing = 1;
13705 mg_unlock_context(phys_ctx);
13706 mg_sleep(1);
13707 mg_lock_context(phys_ctx);
13708 /* tmp_rh might have been freed, search again. */
13709 break;
13710 }
13711 /* Ok, the handler is no more used */
13712 }
13713 *lastref = tmp_rh->next;
13714 mg_free(tmp_rh->uri);
13715 mg_free(tmp_rh);
13716 }
13717 mg_unlock_context(phys_ctx);
13718 return;
13719 }
13720 lastref = &(tmp_rh->next);
13721 }
13722 } while (tmp_rh != NULL);
13723
13724 if (is_delete_request) {
13725 /* no handler to set, this was a remove request to a non-existing
13726 * handler */
13727 mg_unlock_context(phys_ctx);
13728 return;
13729 }
13730
13731 tmp_rh =
13732 (struct mg_handler_info *)mg_calloc_ctx(1,
13733 sizeof(struct mg_handler_info),
13734 phys_ctx);
13735 if (tmp_rh == NULL) {
13736 mg_unlock_context(phys_ctx);
13737 mg_cry_ctx_internal(phys_ctx,
13738 "%s",
13739 "Cannot create new request handler struct, OOM");
13740 return;
13741 }
13742 tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
13743 if (!tmp_rh->uri) {
13744 mg_unlock_context(phys_ctx);
13745 mg_free(tmp_rh);
13746 mg_cry_ctx_internal(phys_ctx,
13747 "%s",
13748 "Cannot create new request handler struct, OOM");
13749 return;
13750 }
13751 tmp_rh->uri_len = urilen;
13753 tmp_rh->refcount = 0;
13754 tmp_rh->removing = 0;
13755 tmp_rh->handler = handler;
13756 } else if (handler_type == WEBSOCKET_HANDLER) {
13757 tmp_rh->subprotocols = subprotocols;
13759 tmp_rh->ready_handler = ready_handler;
13760 tmp_rh->data_handler = data_handler;
13761 tmp_rh->close_handler = close_handler;
13762 } else { /* AUTH_HANDLER */
13763 tmp_rh->auth_handler = auth_handler;
13764 }
13765 tmp_rh->cbdata = cbdata;
13766 tmp_rh->handler_type = handler_type;
13767 tmp_rh->next = NULL;
13768
13769 *lastref = tmp_rh;
13770 mg_unlock_context(phys_ctx);
13771}
13772
13773
13774void
13776 const char *uri,
13778 void *cbdata)
13779{
13781 &(ctx->dd),
13782 uri,
13784 handler == NULL,
13785 handler,
13786 NULL,
13787 NULL,
13788 NULL,
13789 NULL,
13790 NULL,
13791 NULL,
13792 cbdata);
13793}
13794
13795
13796void
13798 const char *uri,
13803 void *cbdata)
13804{
13806 uri,
13807 NULL,
13812 cbdata);
13813}
13814
13815
13816void
13818 struct mg_context *ctx,
13819 const char *uri,
13825 void *cbdata)
13826{
13827 int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
13828 && (data_handler == NULL)
13829 && (close_handler == NULL);
13831 &(ctx->dd),
13832 uri,
13834 is_delete_request,
13835 NULL,
13841 NULL,
13842 cbdata);
13843}
13844
13845
13846void
13848 const char *uri,
13850 void *cbdata)
13851{
13853 &(ctx->dd),
13854 uri,
13856 handler == NULL,
13857 NULL,
13858 NULL,
13859 NULL,
13860 NULL,
13861 NULL,
13862 NULL,
13863 handler,
13864 cbdata);
13865}
13866
13867
13868static int
13870 int handler_type,
13878 void **cbdata,
13879 struct mg_handler_info **handler_info)
13880{
13881 const struct mg_request_info *request_info = mg_get_request_info(conn);
13882 if (request_info) {
13883 const char *uri = request_info->local_uri;
13884 size_t urilen = strlen(uri);
13885 struct mg_handler_info *tmp_rh;
13886 int step, matched;
13887
13888 if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
13889 return 0;
13890 }
13891
13893
13894 for (step = 0; step < 3; step++) {
13895 for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
13896 tmp_rh = tmp_rh->next) {
13897 if (tmp_rh->handler_type != handler_type) {
13898 continue;
13899 }
13900 if (step == 0) {
13901 /* first try for an exact match */
13902 matched = (tmp_rh->uri_len == urilen)
13903 && (strcmp(tmp_rh->uri, uri) == 0);
13904 } else if (step == 1) {
13905 /* next try for a partial match, we will accept
13906 uri/something */
13907 matched =
13908 (tmp_rh->uri_len < urilen)
13909 && (uri[tmp_rh->uri_len] == '/')
13910 && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
13911 } else {
13912 /* finally try for pattern match */
13913 matched =
13914 match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
13915 }
13916 if (matched) {
13918 *subprotocols = tmp_rh->subprotocols;
13920 *ready_handler = tmp_rh->ready_handler;
13921 *data_handler = tmp_rh->data_handler;
13922 *close_handler = tmp_rh->close_handler;
13923 } else if (handler_type == REQUEST_HANDLER) {
13924 if (tmp_rh->removing) {
13925 /* Treat as none found */
13926 step = 2;
13927 break;
13928 }
13929 *handler = tmp_rh->handler;
13930 /* Acquire handler and give it back */
13931 tmp_rh->refcount++;
13932 *handler_info = tmp_rh;
13933 } else { /* AUTH_HANDLER */
13934 *auth_handler = tmp_rh->auth_handler;
13935 }
13936 *cbdata = tmp_rh->cbdata;
13938 return 1;
13939 }
13940 }
13941 }
13942
13944 }
13945 return 0; /* none found */
13946}
13947
13948
13949/* Check if the script file is in a path, allowed for script files.
13950 * This can be used if uploading files is possible not only for the server
13951 * admin, and the upload mechanism does not check the file extension.
13952 */
13953static int
13954is_in_script_path(const struct mg_connection *conn, const char *path)
13955{
13956 /* TODO (Feature): Add config value for allowed script path.
13957 * Default: All allowed. */
13958 (void)conn;
13959 (void)path;
13960 return 1;
13961}
13962
13963
13964#if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
13965static int
13966experimental_websocket_client_data_wrapper(struct mg_connection *conn,
13967 int bits,
13968 char *data,
13969 size_t len,
13970 void *cbdata)
13971{
13972 struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13973 if (pcallbacks->websocket_data) {
13974 return pcallbacks->websocket_data(conn, bits, data, len);
13975 }
13976 /* No handler set - assume "OK" */
13977 return 1;
13978}
13979
13980
13981static void
13982experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
13983 void *cbdata)
13984{
13985 struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13986 if (pcallbacks->connection_close) {
13987 pcallbacks->connection_close(conn);
13988 }
13989}
13990#endif
13991
13992
13993/* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
13994 */
13995static void
13997 struct mg_handler_info *handler_info)
13998{
13999 if (handler_info != NULL) {
14000 /* Use context lock for ref counter */
14002 handler_info->refcount--;
14004 }
14005}
14006
14007
14008/* This is the heart of the Civetweb's logic.
14009 * This function is called when the request is read, parsed and validated,
14010 * and Civetweb must decide what action to take: serve a file, or
14011 * a directory, or call embedded function, etcetera. */
14012static void
14014{
14015 struct mg_request_info *ri = &conn->request_info;
14016 char path[UTF8_PATH_MAX];
14017 int uri_len, ssl_index;
14018 int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
14019 is_put_or_delete_request = 0, is_callback_resource = 0,
14020 is_template_text_file = 0;
14021 int i;
14022 struct mg_file file = STRUCT_FILE_INITIALIZER;
14023 mg_request_handler callback_handler = NULL;
14024 struct mg_handler_info *handler_info = NULL;
14026 mg_websocket_connect_handler ws_connect_handler = NULL;
14027 mg_websocket_ready_handler ws_ready_handler = NULL;
14028 mg_websocket_data_handler ws_data_handler = NULL;
14029 mg_websocket_close_handler ws_close_handler = NULL;
14030 void *callback_data = NULL;
14031 mg_authorization_handler auth_handler = NULL;
14032 void *auth_callback_data = NULL;
14033 int handler_type;
14034 time_t curtime = time(NULL);
14035 char date[64];
14036 char *tmp;
14037
14038 path[0] = 0;
14039
14040 /* 0. Reset internal state (required for HTTP/2 proxy) */
14041 conn->request_state = 0;
14042
14043 /* 1. get the request url */
14044 /* 1.1. split into url and query string */
14045 if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
14046 != NULL) {
14047 *((char *)conn->request_info.query_string++) = '\0';
14048 }
14049
14050 /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
14051 if (!conn->client.is_ssl && conn->client.ssl_redir) {
14052 ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
14053 if (ssl_index >= 0) {
14054 int port = (int)ntohs(USA_IN_PORT_UNSAFE(
14055 &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
14056 redirect_to_https_port(conn, port);
14057 } else {
14058 /* A http to https forward port has been specified,
14059 * but no https port to forward to. */
14060 mg_send_http_error(conn,
14061 503,
14062 "%s",
14063 "Error: SSL forward not configured properly");
14064 mg_cry_internal(conn,
14065 "%s",
14066 "Can not redirect to SSL, no SSL port available");
14067 }
14068 return;
14069 }
14070 uri_len = (int)strlen(ri->local_uri);
14071
14072 /* 1.3. decode url (if config says so) */
14073 if (should_decode_url(conn)) {
14075 ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
14076 }
14077
14078 /* URL decode the query-string only if explicity set in the configuration */
14079 if (conn->request_info.query_string) {
14080 if (should_decode_query_string(conn)) {
14082 }
14083 }
14084
14085 /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
14086 * possible. The fact that we cleaned the URI is stored in that the
14087 * pointer to ri->local_ur and ri->local_uri_raw are now different.
14088 * ri->local_uri_raw still points to memory allocated in
14089 * worker_thread_run(). ri->local_uri is private to the request so we
14090 * don't have to use preallocated memory here. */
14091 tmp = mg_strdup(ri->local_uri_raw);
14092 if (!tmp) {
14093 /* Out of memory. We cannot do anything reasonable here. */
14094 return;
14095 }
14097 ri->local_uri = tmp;
14098
14099 /* step 1. completed, the url is known now */
14100 DEBUG_TRACE("URL: %s", ri->local_uri);
14101
14102 /* 2. if this ip has limited speed, set it for this connection */
14104 &conn->client.rsa,
14105 ri->local_uri);
14106
14107 /* 3. call a "handle everything" callback, if registered */
14108 if (conn->phys_ctx->callbacks.begin_request != NULL) {
14109 /* Note that since V1.7 the "begin_request" function is called
14110 * before an authorization check. If an authorization check is
14111 * required, use a request_handler instead. */
14112 i = conn->phys_ctx->callbacks.begin_request(conn);
14113 if (i > 0) {
14114 /* callback already processed the request. Store the
14115 return value as a status code for the access log. */
14116 conn->status_code = i;
14117 if (!conn->must_close) {
14119 }
14120 return;
14121 } else if (i == 0) {
14122 /* civetweb should process the request */
14123 } else {
14124 /* unspecified - may change with the next version */
14125 return;
14126 }
14127 }
14128
14129 /* request not yet handled by a handler or redirect, so the request
14130 * is processed here */
14131
14132 /* 4. Check for CORS preflight requests and handle them (if configured).
14133 * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
14134 */
14135 if (!strcmp(ri->request_method, "OPTIONS")) {
14136 /* Send a response to CORS preflights only if
14137 * access_control_allow_methods is not NULL and not an empty string.
14138 * In this case, scripts can still handle CORS. */
14139 const char *cors_meth_cfg =
14141 const char *cors_orig_cfg =
14143 const char *cors_cred_cfg =
14145 const char *cors_origin =
14146 get_header(ri->http_headers, ri->num_headers, "Origin");
14147 const char *cors_acrm = get_header(ri->http_headers,
14148 ri->num_headers,
14149 "Access-Control-Request-Method");
14150
14151 /* Todo: check if cors_origin is in cors_orig_cfg.
14152 * Or, let the client check this. */
14153
14154 if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
14155 && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
14156 && (cors_origin != NULL) && (cors_acrm != NULL)) {
14157 /* This is a valid CORS preflight, and the server is configured
14158 * to handle it automatically. */
14159 const char *cors_acrh =
14161 ri->num_headers,
14162 "Access-Control-Request-Headers");
14163
14164 gmt_time_string(date, sizeof(date), &curtime);
14165 mg_printf(conn,
14166 "HTTP/1.1 200 OK\r\n"
14167 "Date: %s\r\n"
14168 "Access-Control-Allow-Origin: %s\r\n"
14169 "Access-Control-Allow-Methods: %s\r\n"
14170 "Content-Length: 0\r\n"
14171 "Connection: %s\r\n",
14172 date,
14173 cors_orig_cfg,
14174 ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
14176
14177 if (cors_acrh != NULL) {
14178 /* CORS request is asking for additional headers */
14179 const char *cors_hdr_cfg =
14181
14182 if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
14183 /* Allow only if access_control_allow_headers is
14184 * not NULL and not an empty string. If this
14185 * configuration is set to *, allow everything.
14186 * Otherwise this configuration must be a list
14187 * of allowed HTTP header names. */
14188 mg_printf(conn,
14189 "Access-Control-Allow-Headers: %s\r\n",
14190 ((cors_hdr_cfg[0] == '*') ? cors_acrh
14191 : cors_hdr_cfg));
14192 }
14193 }
14194 if (cors_cred_cfg && *cors_cred_cfg) {
14195 mg_printf(conn,
14196 "Access-Control-Allow-Credentials: %s\r\n",
14197 cors_cred_cfg);
14198 }
14199
14200 mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
14201
14202 mg_printf(conn, "\r\n");
14203 return;
14204 }
14205 }
14206
14207 /* 5. interpret the url to find out how the request must be handled
14208 */
14209 /* 5.1. first test, if the request targets the regular http(s)://
14210 * protocol namespace or the websocket ws(s):// protocol namespace.
14211 */
14212 is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
14213#if defined(USE_WEBSOCKET)
14214 handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
14215#else
14216 handler_type = REQUEST_HANDLER;
14217#endif /* defined(USE_WEBSOCKET) */
14218
14219 if (is_websocket_request) {
14220 HTTP1_only;
14221 }
14222
14223 /* 5.2. check if the request will be handled by a callback */
14224 if (get_request_handler(conn,
14225 handler_type,
14226 &callback_handler,
14227 &subprotocols,
14228 &ws_connect_handler,
14229 &ws_ready_handler,
14230 &ws_data_handler,
14231 &ws_close_handler,
14232 NULL,
14233 &callback_data,
14234 &handler_info)) {
14235 /* 5.2.1. A callback will handle this request. All requests
14236 * handled by a callback have to be considered as requests
14237 * to a script resource. */
14238 is_callback_resource = 1;
14239 is_script_resource = 1;
14240 is_put_or_delete_request = is_put_or_delete_method(conn);
14241 } else {
14242 no_callback_resource:
14243
14244 /* 5.2.2. No callback is responsible for this request. The URI
14245 * addresses a file based resource (static content or Lua/cgi
14246 * scripts in the file system). */
14247 is_callback_resource = 0;
14248 interpret_uri(conn,
14249 path,
14250 sizeof(path),
14251 &file.stat,
14252 &is_found,
14253 &is_script_resource,
14254 &is_websocket_request,
14255 &is_put_or_delete_request,
14256 &is_template_text_file);
14257 }
14258
14259 /* 6. authorization check */
14260 /* 6.1. a custom authorization handler is installed */
14261 if (get_request_handler(conn,
14263 NULL,
14264 NULL,
14265 NULL,
14266 NULL,
14267 NULL,
14268 NULL,
14269 &auth_handler,
14270 &auth_callback_data,
14271 NULL)) {
14272 if (!auth_handler(conn, auth_callback_data)) {
14273
14274 /* Callback handler will not be used anymore. Release it */
14275 release_handler_ref(conn, handler_info);
14276
14277 return;
14278 }
14279 } else if (is_put_or_delete_request && !is_script_resource
14280 && !is_callback_resource) {
14281 HTTP1_only;
14282 /* 6.2. this request is a PUT/DELETE to a real file */
14283 /* 6.2.1. thus, the server must have real files */
14284#if defined(NO_FILES)
14285 if (1) {
14286#else
14287 if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
14288#endif
14289 /* This code path will not be called for request handlers */
14290 DEBUG_ASSERT(handler_info == NULL);
14291
14292 /* This server does not have any real files, thus the
14293 * PUT/DELETE methods are not valid. */
14294 mg_send_http_error(conn,
14295 405,
14296 "%s method not allowed",
14298 return;
14299 }
14300
14301#if !defined(NO_FILES)
14302 /* 6.2.2. Check if put authorization for static files is
14303 * available.
14304 */
14305 if (!is_authorized_for_put(conn)) {
14306 send_authorization_request(conn, NULL);
14307 return;
14308 }
14309#endif
14310
14311 } else {
14312 /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
14313 * or it is a PUT or DELETE request to a resource that does not
14314 * correspond to a file. Check authorization. */
14315 if (!check_authorization(conn, path)) {
14316 send_authorization_request(conn, NULL);
14317
14318 /* Callback handler will not be used anymore. Release it */
14319 release_handler_ref(conn, handler_info);
14320
14321 return;
14322 }
14323 }
14324
14325 /* request is authorized or does not need authorization */
14326
14327 /* 7. check if there are request handlers for this uri */
14328 if (is_callback_resource) {
14329 HTTP1_only;
14330 if (!is_websocket_request) {
14331 i = callback_handler(conn, callback_data);
14332
14333 /* Callback handler will not be used anymore. Release it */
14334 release_handler_ref(conn, handler_info);
14335
14336 if (i > 0) {
14337 /* Do nothing, callback has served the request. Store
14338 * then return value as status code for the log and discard
14339 * all data from the client not used by the callback. */
14340 conn->status_code = i;
14341 if (!conn->must_close) {
14343 }
14344 } else {
14345 /* The handler did NOT handle the request. */
14346 /* Some proper reactions would be:
14347 * a) close the connections without sending anything
14348 * b) send a 404 not found
14349 * c) try if there is a file matching the URI
14350 * It would be possible to do a, b or c in the callback
14351 * implementation, and return 1 - we cannot do anything
14352 * here, that is not possible in the callback.
14353 *
14354 * TODO: What would be the best reaction here?
14355 * (Note: The reaction may change, if there is a better
14356 * idea.)
14357 */
14358
14359 /* For the moment, use option c: We look for a proper file,
14360 * but since a file request is not always a script resource,
14361 * the authorization check might be different. */
14362 interpret_uri(conn,
14363 path,
14364 sizeof(path),
14365 &file.stat,
14366 &is_found,
14367 &is_script_resource,
14368 &is_websocket_request,
14369 &is_put_or_delete_request,
14370 &is_template_text_file);
14371 callback_handler = NULL;
14372
14373 /* Here we are at a dead end:
14374 * According to URI matching, a callback should be
14375 * responsible for handling the request,
14376 * we called it, but the callback declared itself
14377 * not responsible.
14378 * We use a goto here, to get out of this dead end,
14379 * and continue with the default handling.
14380 * A goto here is simpler and better to understand
14381 * than some curious loop. */
14382 goto no_callback_resource;
14383 }
14384 } else {
14385#if defined(USE_WEBSOCKET)
14386 handle_websocket_request(conn,
14387 path,
14388 is_callback_resource,
14390 ws_connect_handler,
14391 ws_ready_handler,
14392 ws_data_handler,
14393 ws_close_handler,
14394 callback_data);
14395#endif
14396 }
14397 return;
14398 }
14399
14400 /* 8. handle websocket requests */
14401#if defined(USE_WEBSOCKET)
14402 if (is_websocket_request) {
14403 HTTP1_only;
14404 if (is_script_resource) {
14405
14406 if (is_in_script_path(conn, path)) {
14407 /* Websocket Lua script */
14408 handle_websocket_request(conn,
14409 path,
14410 0 /* Lua Script */,
14411 NULL,
14412 NULL,
14413 NULL,
14414 NULL,
14415 NULL,
14416 conn->phys_ctx->user_data);
14417 } else {
14418 /* Script was in an illegal path */
14419 mg_send_http_error(conn, 403, "%s", "Forbidden");
14420 }
14421 } else {
14422 mg_send_http_error(conn, 404, "%s", "Not found");
14423 }
14424 return;
14425 } else
14426#endif
14427
14428#if defined(NO_FILES)
14429 /* 9a. In case the server uses only callbacks, this uri is
14430 * unknown.
14431 * Then, all request handling ends here. */
14432 mg_send_http_error(conn, 404, "%s", "Not Found");
14433
14434#else
14435 /* 9b. This request is either for a static file or resource handled
14436 * by a script file. Thus, a DOCUMENT_ROOT must exist. */
14437 if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
14438 mg_send_http_error(conn, 404, "%s", "Not Found");
14439 return;
14440 }
14441
14442 /* 10. Request is handled by a script */
14443 if (is_script_resource) {
14444 HTTP1_only;
14445 handle_file_based_request(conn, path, &file);
14446 return;
14447 }
14448
14449 /* 11. Handle put/delete/mkcol requests */
14450 if (is_put_or_delete_request) {
14451 HTTP1_only;
14452 /* 11.1. PUT method */
14453 if (!strcmp(ri->request_method, "PUT")) {
14454 put_file(conn, path);
14455 return;
14456 }
14457 /* 11.2. DELETE method */
14458 if (!strcmp(ri->request_method, "DELETE")) {
14459 delete_file(conn, path);
14460 return;
14461 }
14462 /* 11.3. MKCOL method */
14463 if (!strcmp(ri->request_method, "MKCOL")) {
14464 mkcol(conn, path);
14465 return;
14466 }
14467 /* 11.4. PATCH method
14468 * This method is not supported for static resources,
14469 * only for scripts (Lua, CGI) and callbacks. */
14470 mg_send_http_error(conn,
14471 405,
14472 "%s method not allowed",
14474 return;
14475 }
14476
14477 /* 11. File does not exist, or it was configured that it should be
14478 * hidden */
14479 if (!is_found || (must_hide_file(conn, path))) {
14480 mg_send_http_error(conn, 404, "%s", "Not found");
14481 return;
14482 }
14483
14484 /* 12. Directory uris should end with a slash */
14485 if (file.stat.is_directory && (uri_len > 0)
14486 && (ri->local_uri[uri_len - 1] != '/')) {
14487
14488 size_t len = strlen(ri->request_uri);
14489 size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
14490 char *new_path = (char *)mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
14491 if (!new_path) {
14492 mg_send_http_error(conn, 500, "out or memory");
14493 } else {
14494 memcpy(new_path, ri->request_uri, len);
14495 new_path[len] = '/';
14496 new_path[len + 1] = 0;
14497 if (ri->query_string) {
14498 new_path[len + 1] = '?';
14499 /* Copy query string including terminating zero */
14500 memcpy(new_path + len + 2, ri->query_string, lenQS);
14501 }
14502 mg_send_http_redirect(conn, new_path, 301);
14503 mg_free(new_path);
14504 }
14505 return;
14506 }
14507
14508 /* 13. Handle other methods than GET/HEAD */
14509 /* 13.1. Handle PROPFIND */
14510 if (!strcmp(ri->request_method, "PROPFIND")) {
14511 handle_propfind(conn, path, &file.stat);
14512 return;
14513 }
14514 /* 13.2. Handle OPTIONS for files */
14515 if (!strcmp(ri->request_method, "OPTIONS")) {
14516 /* This standard handler is only used for real files.
14517 * Scripts should support the OPTIONS method themselves, to allow a
14518 * maximum flexibility.
14519 * Lua and CGI scripts may fully support CORS this way (including
14520 * preflights). */
14521 send_options(conn);
14522 return;
14523 }
14524 /* 13.3. everything but GET and HEAD (e.g. POST) */
14525 if ((0 != strcmp(ri->request_method, "GET"))
14526 && (0 != strcmp(ri->request_method, "HEAD"))) {
14527 mg_send_http_error(conn,
14528 405,
14529 "%s method not allowed",
14531 return;
14532 }
14533
14534 /* 14. directories */
14535 if (file.stat.is_directory) {
14536 /* Substitute files have already been handled above. */
14537 /* Here we can either generate and send a directory listing,
14538 * or send an "access denied" error. */
14540 "yes")) {
14541 handle_directory_request(conn, path);
14542 } else {
14543 mg_send_http_error(conn,
14544 403,
14545 "%s",
14546 "Error: Directory listing denied");
14547 }
14548 return;
14549 }
14550
14551 /* 15. Files with search/replace patterns: LSP and SSI */
14552 if (is_template_text_file) {
14553 HTTP1_only;
14554 handle_file_based_request(conn, path, &file);
14555 return;
14556 }
14557
14558 /* 16. Static file - maybe cached */
14559#if !defined(NO_CACHING)
14560 if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
14561 /* Send 304 "Not Modified" - this must not send any body data */
14563 return;
14564 }
14565#endif /* !NO_CACHING */
14566
14567 /* 17. Static file - not cached */
14568 handle_static_file_request(conn, path, &file, NULL, NULL);
14569
14570#endif /* !defined(NO_FILES) */
14571}
14572
14573
14574#if !defined(NO_FILESYSTEMS)
14575static void
14577 const char *path,
14578 struct mg_file *file)
14579{
14580#if !defined(NO_CGI)
14581 unsigned char cgi_config_idx, inc, max;
14582#endif
14583
14584 if (!conn || !conn->dom_ctx) {
14585 return;
14586 }
14587
14588#if defined(USE_LUA)
14589 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
14590 path)
14591 > 0) {
14592 if (is_in_script_path(conn, path)) {
14593 /* Lua server page: an SSI like page containing mostly plain
14594 * html code plus some tags with server generated contents. */
14595 handle_lsp_request(conn, path, file, NULL);
14596 } else {
14597 /* Script was in an illegal path */
14598 mg_send_http_error(conn, 403, "%s", "Forbidden");
14599 }
14600 return;
14601 }
14602
14603 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
14604 > 0) {
14605 if (is_in_script_path(conn, path)) {
14606 /* Lua in-server module script: a CGI like script used to
14607 * generate the entire reply. */
14608 mg_exec_lua_script(conn, path, NULL);
14609 } else {
14610 /* Script was in an illegal path */
14611 mg_send_http_error(conn, 403, "%s", "Forbidden");
14612 }
14613 return;
14614 }
14615#endif
14616
14617#if defined(USE_DUKTAPE)
14618 if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
14619 path)
14620 > 0) {
14621 if (is_in_script_path(conn, path)) {
14622 /* Call duktape to generate the page */
14623 mg_exec_duktape_script(conn, path);
14624 } else {
14625 /* Script was in an illegal path */
14626 mg_send_http_error(conn, 403, "%s", "Forbidden");
14627 }
14628 return;
14629 }
14630#endif
14631
14632#if !defined(NO_CGI)
14635 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
14636 if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
14638 conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
14639 path)
14640 > 0) {
14641 if (is_in_script_path(conn, path)) {
14642 /* CGI scripts may support all HTTP methods */
14643 handle_cgi_request(conn, path, 0);
14644 } else {
14645 /* Script was in an illegal path */
14646 mg_send_http_error(conn, 403, "%s", "Forbidden");
14647 }
14648 return;
14649 }
14650 }
14651 }
14652#endif /* !NO_CGI */
14653
14654 if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
14655 if (is_in_script_path(conn, path)) {
14656 handle_ssi_file_request(conn, path, file);
14657 } else {
14658 /* Script was in an illegal path */
14659 mg_send_http_error(conn, 403, "%s", "Forbidden");
14660 }
14661 return;
14662 }
14663
14664#if !defined(NO_CACHING)
14665 if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
14666 /* Send 304 "Not Modified" - this must not send any body data */
14668 return;
14669 }
14670#endif /* !NO_CACHING */
14671
14672 handle_static_file_request(conn, path, file, NULL, NULL);
14673}
14674#endif /* NO_FILESYSTEMS */
14675
14676
14677static void
14679{
14680 unsigned int i;
14681 if (!ctx) {
14682 return;
14683 }
14684
14685 for (i = 0; i < ctx->num_listening_sockets; i++) {
14687#if defined(USE_X_DOM_SOCKET)
14688 /* For unix domain sockets, the socket name represents a file that has
14689 * to be deleted. */
14690 /* See
14691 * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
14692 */
14693 if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
14694 && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
14696 remove(ctx->listening_sockets[i].lsa.sun.sun_path));
14697 }
14698#endif
14700 }
14702 ctx->listening_sockets = NULL;
14704 ctx->listening_socket_fds = NULL;
14705}
14706
14707
14708/* Valid listening port specification is: [ip_address:]port[s]
14709 * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
14710 * Examples for IPv6: [::]:80, [::1]:80,
14711 * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
14712 * see https://tools.ietf.org/html/rfc3513#section-2.2
14713 * In order to bind to both, IPv4 and IPv6, you can either add
14714 * both ports using 8080,[::]:8080, or the short form +8080.
14715 * Both forms differ in detail: 8080,[::]:8080 create two sockets,
14716 * one only accepting IPv4 the other only IPv6. +8080 creates
14717 * one socket accepting IPv4 and IPv6. Depending on the IPv6
14718 * environment, they might work differently, or might not work
14719 * at all - it must be tested what options work best in the
14720 * relevant network environment.
14721 */
14722static int
14723parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
14724{
14725 unsigned int a, b, c, d;
14726 unsigned port;
14727 unsigned long portUL;
14728 int ch, len;
14729 const char *cb;
14730 char *endptr;
14731#if defined(USE_IPV6)
14732 char buf[100] = {0};
14733#endif
14734
14735 /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
14736 * Also, all-zeroes in the socket address means binding to all addresses
14737 * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
14738 memset(so, 0, sizeof(*so));
14739 so->lsa.sin.sin_family = AF_INET;
14740 *ip_version = 0;
14741
14742 /* Initialize len as invalid. */
14743 port = 0;
14744 len = 0;
14745
14746 /* Test for different ways to format this string */
14747 if (sscanf(vec->ptr,
14748 "%u.%u.%u.%u:%u%n",
14749 &a,
14750 &b,
14751 &c,
14752 &d,
14753 &port,
14754 &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
14755 // to an integer value, but function will not report
14756 // conversion errors; consider using 'strtol' instead
14757 == 5) {
14758 /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
14759 so->lsa.sin.sin_addr.s_addr =
14760 htonl((a << 24) | (b << 16) | (c << 8) | d);
14761 so->lsa.sin.sin_port = htons((uint16_t)port);
14762 *ip_version = 4;
14763
14764#if defined(USE_IPV6)
14765 } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
14766 && ((size_t)len <= vec->len)
14767 && mg_inet_pton(
14768 AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
14769 /* IPv6 address, examples: see above */
14770 /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
14771 */
14772 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14773 *ip_version = 6;
14774#endif
14775
14776 } else if ((vec->ptr[0] == '+')
14777 && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
14778 == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
14779 // string to an integer value, but function will not
14780 // report conversion errors; consider using 'strtol'
14781 // instead
14782
14783 /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
14784 /* Add 1 to len for the + character we skipped before */
14785 len++;
14786
14787#if defined(USE_IPV6)
14788 /* Set socket family to IPv6, do not use IPV6_V6ONLY */
14789 so->lsa.sin6.sin6_family = AF_INET6;
14790 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14791 *ip_version = 4 + 6;
14792#else
14793 /* Bind to IPv4 only, since IPv6 is not built in. */
14794 so->lsa.sin.sin_port = htons((uint16_t)port);
14795 *ip_version = 4;
14796#endif
14797
14798 } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
14799 && (vec->ptr != endptr)) {
14800 len = (int)(endptr - vec->ptr);
14801 port = (uint16_t)portUL;
14802 /* If only port is specified, bind to IPv4, INADDR_ANY */
14803 so->lsa.sin.sin_port = htons((uint16_t)port);
14804 *ip_version = 4;
14805
14806 } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
14807 /* String could be a hostname. This check algotithm
14808 * will only work for RFC 952 compliant hostnames,
14809 * starting with a letter, containing only letters,
14810 * digits and hyphen ('-'). Newer specs may allow
14811 * more, but this is not guaranteed here, since it
14812 * may interfere with rules for port option lists. */
14813
14814 /* According to RFC 1035, hostnames are restricted to 255 characters
14815 * in total (63 between two dots). */
14816 char hostname[256];
14817 size_t hostnlen = (size_t)(cb - vec->ptr);
14818
14819 if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
14820 /* This would be invalid in any case */
14821 *ip_version = 0;
14822 return 0;
14823 }
14824
14825 mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
14826
14827 if (mg_inet_pton(
14828 AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
14829 if (sscanf(cb + 1, "%u%n", &port, &len)
14830 == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
14831 // string to an integer value, but function will not
14832 // report conversion errors; consider using 'strtol'
14833 // instead
14834 *ip_version = 4;
14835 so->lsa.sin.sin_port = htons((uint16_t)port);
14836 len += (int)(hostnlen + 1);
14837 } else {
14838 len = 0;
14839 }
14840#if defined(USE_IPV6)
14841 } else if (mg_inet_pton(AF_INET6,
14842 hostname,
14843 &so->lsa.sin6,
14844 sizeof(so->lsa.sin6),
14845 1)) {
14846 if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
14847 *ip_version = 6;
14848 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14849 len += (int)(hostnlen + 1);
14850 } else {
14851 len = 0;
14852 }
14853#endif
14854 } else {
14855 len = 0;
14856 }
14857
14858#if defined(USE_X_DOM_SOCKET)
14859
14860 } else if (vec->ptr[0] == 'x') {
14861 /* unix (linux) domain socket */
14862 if (vec->len < sizeof(so->lsa.sun.sun_path)) {
14863 len = vec->len;
14864 so->lsa.sun.sun_family = AF_UNIX;
14865 memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
14866 memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
14867 port = 0;
14868 *ip_version = 99;
14869 } else {
14870 /* String too long */
14871 len = 0;
14872 }
14873#endif
14874
14875 } else {
14876 /* Parsing failure. */
14877 len = 0;
14878 }
14879
14880 /* sscanf and the option splitting code ensure the following condition
14881 * Make sure the port is valid and vector ends with the port, 's' or 'r' */
14882 if ((len > 0) && is_valid_port(port)
14883 && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
14884 /* Next character after the port number */
14885 ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
14886 so->is_ssl = (ch == 's');
14887 so->ssl_redir = (ch == 'r');
14888 if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
14889 return 1;
14890 }
14891 }
14892
14893 /* Reset ip_version to 0 if there is an error */
14894 *ip_version = 0;
14895 return 0;
14896}
14897
14898
14899/* Is there any SSL port in use? */
14900static int
14901is_ssl_port_used(const char *ports)
14902{
14903 if (ports) {
14904 /* There are several different allowed syntax variants:
14905 * - "80" for a single port using every network interface
14906 * - "localhost:80" for a single port using only localhost
14907 * - "80,localhost:8080" for two ports, one bound to localhost
14908 * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
14909 * to IPv4 localhost, one to IPv6 localhost
14910 * - "+80" use port 80 for IPv4 and IPv6
14911 * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
14912 * for both: IPv4 and IPv4
14913 * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
14914 * additionally port 8080 bound to localhost connections
14915 *
14916 * If we just look for 's' anywhere in the string, "localhost:80"
14917 * will be detected as SSL (false positive).
14918 * Looking for 's' after a digit may cause false positives in
14919 * "my24service:8080".
14920 * Looking from 's' backward if there are only ':' and numbers
14921 * before will not work for "24service:8080" (non SSL, port 8080)
14922 * or "24s" (SSL, port 24).
14923 *
14924 * Remark: Initially hostnames were not allowed to start with a
14925 * digit (according to RFC 952), this was allowed later (RFC 1123,
14926 * Section 2.1).
14927 *
14928 * To get this correct, the entire string must be parsed as a whole,
14929 * reading it as a list element for element and parsing with an
14930 * algorithm equivalent to parse_port_string.
14931 *
14932 * In fact, we use local interface names here, not arbitrary
14933 * hostnames, so in most cases the only name will be "localhost".
14934 *
14935 * So, for now, we use this simple algorithm, that may still return
14936 * a false positive in bizarre cases.
14937 */
14938 int i;
14939 int portslen = (int)strlen(ports);
14940 char prevIsNumber = 0;
14941
14942 for (i = 0; i < portslen; i++) {
14943 if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
14944 return 1;
14945 }
14946 if (ports[i] >= '0' && ports[i] <= '9') {
14947 prevIsNumber = 1;
14948 } else {
14949 prevIsNumber = 0;
14950 }
14951 }
14952 }
14953 return 0;
14954}
14955
14956
14957static int
14959{
14960 const char *list;
14961 int on = 1;
14962#if defined(USE_IPV6)
14963 int off = 0;
14964#endif
14965 struct vec vec;
14966 struct socket so, *ptr;
14967
14968 struct mg_pollfd *pfd;
14969 union usa usa;
14970 socklen_t len;
14971 int ip_version;
14972
14973 int portsTotal = 0;
14974 int portsOk = 0;
14975
14976 const char *opt_txt;
14977 long opt_listen_backlog;
14978
14979 if (!phys_ctx) {
14980 return 0;
14981 }
14982
14983 memset(&so, 0, sizeof(so));
14984 memset(&usa, 0, sizeof(usa));
14985 len = sizeof(usa);
14986 list = phys_ctx->dd.config[LISTENING_PORTS];
14987
14988 while ((list = next_option(list, &vec, NULL)) != NULL) {
14989
14990 portsTotal++;
14991
14992 if (!parse_port_string(&vec, &so, &ip_version)) {
14994 phys_ctx,
14995 "%.*s: invalid port spec (entry %i). Expecting list of: %s",
14996 (int)vec.len,
14997 vec.ptr,
14998 portsTotal,
14999 "[IP_ADDRESS:]PORT[s|r]");
15000 continue;
15001 }
15002
15003#if !defined(NO_SSL)
15004 if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
15005
15006 mg_cry_ctx_internal(phys_ctx,
15007 "Cannot add SSL socket (entry %i)",
15008 portsTotal);
15009 continue;
15010 }
15011#endif
15012 /* Create socket. */
15013 /* For a list of protocol numbers (e.g., TCP==6) see:
15014 * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
15015 */
15016 if ((so.sock =
15017 socket(so.lsa.sa.sa_family,
15018 SOCK_STREAM,
15019 (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
15020 == INVALID_SOCKET) {
15021
15022 mg_cry_ctx_internal(phys_ctx,
15023 "cannot create socket (entry %i)",
15024 portsTotal);
15025 continue;
15026 }
15027
15028#if defined(_WIN32)
15029 /* Windows SO_REUSEADDR lets many procs binds to a
15030 * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
15031 * if someone already has the socket -- DTL */
15032 /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
15033 * Windows might need a few seconds before
15034 * the same port can be used again in the
15035 * same process, so a short Sleep may be
15036 * required between mg_stop and mg_start.
15037 */
15038 if (setsockopt(so.sock,
15039 SOL_SOCKET,
15040 SO_EXCLUSIVEADDRUSE,
15041 (SOCK_OPT_TYPE)&on,
15042 sizeof(on))
15043 != 0) {
15044
15045 /* Set reuse option, but don't abort on errors. */
15047 phys_ctx,
15048 "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
15049 portsTotal);
15050 }
15051#else
15052 if (setsockopt(so.sock,
15053 SOL_SOCKET,
15054 SO_REUSEADDR,
15055 (SOCK_OPT_TYPE)&on,
15056 sizeof(on))
15057 != 0) {
15058
15059 /* Set reuse option, but don't abort on errors. */
15061 phys_ctx,
15062 "cannot set socket option SO_REUSEADDR (entry %i)",
15063 portsTotal);
15064 }
15065#endif
15066
15067#if defined(USE_X_DOM_SOCKET)
15068 if (ip_version == 99) {
15069 /* Unix domain socket */
15070 } else
15071#endif
15072
15073 if (ip_version > 4) {
15074 /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
15075#if defined(USE_IPV6)
15076 if (ip_version > 6) {
15077 if (so.lsa.sa.sa_family == AF_INET6
15078 && setsockopt(so.sock,
15079 IPPROTO_IPV6,
15080 IPV6_V6ONLY,
15081 (void *)&off,
15082 sizeof(off))
15083 != 0) {
15084
15085 /* Set IPv6 only option, but don't abort on errors. */
15086 mg_cry_ctx_internal(phys_ctx,
15087 "cannot set socket option "
15088 "IPV6_V6ONLY=off (entry %i)",
15089 portsTotal);
15090 }
15091 } else {
15092 if (so.lsa.sa.sa_family == AF_INET6
15093 && setsockopt(so.sock,
15094 IPPROTO_IPV6,
15095 IPV6_V6ONLY,
15096 (void *)&on,
15097 sizeof(on))
15098 != 0) {
15099
15100 /* Set IPv6 only option, but don't abort on errors. */
15101 mg_cry_ctx_internal(phys_ctx,
15102 "cannot set socket option "
15103 "IPV6_V6ONLY=on (entry %i)",
15104 portsTotal);
15105 }
15106 }
15107#else
15108 mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
15109 closesocket(so.sock);
15110 so.sock = INVALID_SOCKET;
15111 continue;
15112#endif
15113 }
15114
15115 if (so.lsa.sa.sa_family == AF_INET) {
15116
15117 len = sizeof(so.lsa.sin);
15118 if (bind(so.sock, &so.lsa.sa, len) != 0) {
15119 mg_cry_ctx_internal(phys_ctx,
15120 "cannot bind to %.*s: %d (%s)",
15121 (int)vec.len,
15122 vec.ptr,
15123 (int)ERRNO,
15124 strerror(errno));
15125 closesocket(so.sock);
15126 so.sock = INVALID_SOCKET;
15127 continue;
15128 }
15129 }
15130#if defined(USE_IPV6)
15131 else if (so.lsa.sa.sa_family == AF_INET6) {
15132
15133 len = sizeof(so.lsa.sin6);
15134 if (bind(so.sock, &so.lsa.sa, len) != 0) {
15135 mg_cry_ctx_internal(phys_ctx,
15136 "cannot bind to IPv6 %.*s: %d (%s)",
15137 (int)vec.len,
15138 vec.ptr,
15139 (int)ERRNO,
15140 strerror(errno));
15141 closesocket(so.sock);
15142 so.sock = INVALID_SOCKET;
15143 continue;
15144 }
15145 }
15146#endif
15147#if defined(USE_X_DOM_SOCKET)
15148 else if (so.lsa.sa.sa_family == AF_UNIX) {
15149
15150 len = sizeof(so.lsa.sun);
15151 if (bind(so.sock, &so.lsa.sa, len) != 0) {
15152 mg_cry_ctx_internal(phys_ctx,
15153 "cannot bind to unix socket %s: %d (%s)",
15154 so.lsa.sun.sun_path,
15155 (int)ERRNO,
15156 strerror(errno));
15157 closesocket(so.sock);
15158 so.sock = INVALID_SOCKET;
15159 continue;
15160 }
15161 }
15162#endif
15163 else {
15165 phys_ctx,
15166 "cannot bind: address family not supported (entry %i)",
15167 portsTotal);
15168 closesocket(so.sock);
15169 so.sock = INVALID_SOCKET;
15170 continue;
15171 }
15172
15173 opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
15174 opt_listen_backlog = strtol(opt_txt, NULL, 10);
15175 if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
15176 mg_cry_ctx_internal(phys_ctx,
15177 "%s value \"%s\" is invalid",
15179 opt_txt);
15180 closesocket(so.sock);
15181 so.sock = INVALID_SOCKET;
15182 continue;
15183 }
15184
15185 if (listen(so.sock, (int)opt_listen_backlog) != 0) {
15186
15187 mg_cry_ctx_internal(phys_ctx,
15188 "cannot listen to %.*s: %d (%s)",
15189 (int)vec.len,
15190 vec.ptr,
15191 (int)ERRNO,
15192 strerror(errno));
15193 closesocket(so.sock);
15194 so.sock = INVALID_SOCKET;
15195 continue;
15196 }
15197
15198 if ((getsockname(so.sock, &(usa.sa), &len) != 0)
15199 || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
15200
15201 int err = (int)ERRNO;
15202 mg_cry_ctx_internal(phys_ctx,
15203 "call to getsockname failed %.*s: %d (%s)",
15204 (int)vec.len,
15205 vec.ptr,
15206 err,
15207 strerror(errno));
15208 closesocket(so.sock);
15209 so.sock = INVALID_SOCKET;
15210 continue;
15211 }
15212
15213 /* Update lsa port in case of random free ports */
15214#if defined(USE_IPV6)
15215 if (so.lsa.sa.sa_family == AF_INET6) {
15216 so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
15217 } else
15218#endif
15219 {
15220 so.lsa.sin.sin_port = usa.sin.sin_port;
15221 }
15222
15223 if ((ptr = (struct socket *)
15225 (phys_ctx->num_listening_sockets + 1)
15226 * sizeof(phys_ctx->listening_sockets[0]),
15227 phys_ctx))
15228 == NULL) {
15229
15230 mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
15231 closesocket(so.sock);
15232 so.sock = INVALID_SOCKET;
15233 continue;
15234 }
15235
15236 if ((pfd = (struct mg_pollfd *)
15238 (phys_ctx->num_listening_sockets + 1)
15239 * sizeof(phys_ctx->listening_socket_fds[0]),
15240 phys_ctx))
15241 == NULL) {
15242
15243 mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
15244 closesocket(so.sock);
15245 so.sock = INVALID_SOCKET;
15246 mg_free(ptr);
15247 continue;
15248 }
15249
15250 set_close_on_exec(so.sock, NULL, phys_ctx);
15251 phys_ctx->listening_sockets = ptr;
15252 phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
15253 phys_ctx->listening_socket_fds = pfd;
15254 phys_ctx->num_listening_sockets++;
15255 portsOk++;
15256 }
15257
15258 if (portsOk != portsTotal) {
15260 portsOk = 0;
15261 }
15262
15263 return portsOk;
15264}
15265
15266
15267static const char *
15268header_val(const struct mg_connection *conn, const char *header)
15269{
15270 const char *header_value;
15271
15272 if ((header_value = mg_get_header(conn, header)) == NULL) {
15273 return "-";
15274 } else {
15275 return header_value;
15276 }
15277}
15278
15279
15280#if defined(MG_EXTERNAL_FUNCTION_log_access)
15281#include "external_log_access.inl"
15282#elif !defined(NO_FILESYSTEMS)
15283
15284static void
15285log_access(const struct mg_connection *conn)
15286{
15287 const struct mg_request_info *ri;
15288 struct mg_file fi;
15289 char date[64], src_addr[IP_ADDR_STR_LEN];
15290 struct tm *tm;
15291
15292 const char *referer;
15293 const char *user_agent;
15294
15295 char log_buf[4096];
15296
15297 if (!conn || !conn->dom_ctx) {
15298 return;
15299 }
15300
15301 /* Set log message to "empty" */
15302 log_buf[0] = 0;
15303
15304#if defined(USE_LUA)
15305 if (conn->phys_ctx->lua_bg_log_available) {
15306 int ret;
15307 struct mg_context *ctx = conn->phys_ctx;
15308 lua_State *lstate = (lua_State *)ctx->lua_background_state;
15309 pthread_mutex_lock(&ctx->lua_bg_mutex);
15310 /* call "log()" in Lua */
15311 lua_getglobal(lstate, "log");
15312 prepare_lua_request_info_inner(conn, lstate);
15313 push_lua_response_log_data(conn, lstate);
15314
15315 ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
15316 if (ret == 0) {
15317 int t = lua_type(lstate, -1);
15318 if (t == LUA_TBOOLEAN) {
15319 if (lua_toboolean(lstate, -1) == 0) {
15320 /* log() returned false: do not log */
15321 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15322 return;
15323 }
15324 /* log returned true: continue logging */
15325 } else if (t == LUA_TSTRING) {
15326 size_t len;
15327 const char *txt = lua_tolstring(lstate, -1, &len);
15328 if ((len == 0) || (*txt == 0)) {
15329 /* log() returned empty string: do not log */
15330 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15331 return;
15332 }
15333 /* Copy test from Lua into log_buf */
15334 if (len >= sizeof(log_buf)) {
15335 len = sizeof(log_buf) - 1;
15336 }
15337 memcpy(log_buf, txt, len);
15338 log_buf[len] = 0;
15339 }
15340 } else {
15341 lua_cry(conn, ret, lstate, "lua_background_script", "log");
15342 }
15343 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15344 }
15345#endif
15346
15347 if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
15348 if (mg_fopen(conn,
15351 &fi)
15352 == 0) {
15353 fi.access.fp = NULL;
15354 }
15355 } else {
15356 fi.access.fp = NULL;
15357 }
15358
15359 /* Log is written to a file and/or a callback. If both are not set,
15360 * executing the rest of the function is pointless. */
15361 if ((fi.access.fp == NULL)
15362 && (conn->phys_ctx->callbacks.log_access == NULL)) {
15363 return;
15364 }
15365
15366 /* If we did not get a log message from Lua, create it here. */
15367 if (!log_buf[0]) {
15368 tm = localtime(&conn->conn_birth_time);
15369 if (tm != NULL) {
15370 strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
15371 } else {
15372 mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
15373 date[sizeof(date) - 1] = '\0';
15374 }
15375
15376 ri = &conn->request_info;
15377
15378 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
15379 referer = header_val(conn, "Referer");
15380 user_agent = header_val(conn, "User-Agent");
15381
15382 mg_snprintf(conn,
15383 NULL, /* Ignore truncation in access log */
15384 log_buf,
15385 sizeof(log_buf),
15386 "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
15387 " %s %s",
15388 src_addr,
15389 (ri->remote_user == NULL) ? "-" : ri->remote_user,
15390 date,
15391 ri->request_method ? ri->request_method : "-",
15392 ri->request_uri ? ri->request_uri : "-",
15393 ri->query_string ? "?" : "",
15394 ri->query_string ? ri->query_string : "",
15395 ri->http_version,
15396 conn->status_code,
15397 conn->num_bytes_sent,
15398 referer,
15399 user_agent);
15400 }
15401
15402 /* Here we have a log message in log_buf. Call the callback */
15403 if (conn->phys_ctx->callbacks.log_access) {
15404 if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
15405 /* do not log if callack returns non-zero */
15406 if (fi.access.fp) {
15407 mg_fclose(&fi.access);
15408 }
15409 return;
15410 }
15411 }
15412
15413 /* Store in file */
15414 if (fi.access.fp) {
15415 int ok = 1;
15416 flockfile(fi.access.fp);
15417 if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
15418 ok = 0;
15419 }
15420 if (fflush(fi.access.fp) != 0) {
15421 ok = 0;
15422 }
15423 funlockfile(fi.access.fp);
15424 if (mg_fclose(&fi.access) != 0) {
15425 ok = 0;
15426 }
15427 if (!ok) {
15428 mg_cry_internal(conn,
15429 "Error writing log file %s",
15431 }
15432 }
15433}
15434#else
15435#error "Either enable filesystems or provide a custom log_access implementation"
15436#endif /* Externally provided function */
15437
15438
15439/* Verify given socket address against the ACL.
15440 * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
15441 */
15442static int
15443check_acl(struct mg_context *phys_ctx, const union usa *sa)
15444{
15445 int allowed, flag, matched;
15446 struct vec vec;
15447
15448 if (phys_ctx) {
15449 const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
15450
15451 /* If any ACL is set, deny by default */
15452 allowed = (list == NULL) ? '+' : '-';
15453
15454 while ((list = next_option(list, &vec, NULL)) != NULL) {
15455 flag = vec.ptr[0];
15456 matched = -1;
15457 if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
15458 vec.ptr++;
15459 vec.len--;
15460 matched = parse_match_net(&vec, sa, 1);
15461 }
15462 if (matched < 0) {
15463 mg_cry_ctx_internal(phys_ctx,
15464 "%s: subnet must be [+|-]IP-addr[/x]",
15465 __func__);
15466 return -1;
15467 }
15468 if (matched) {
15469 allowed = flag;
15470 }
15471 }
15472
15473 return allowed == '+';
15474 }
15475 return -1;
15476}
15477
15478
15479#if !defined(_WIN32) && !defined(__ZEPHYR__)
15480static int
15482{
15483 int success = 0;
15484
15485 if (phys_ctx) {
15486 /* We are currently running as curr_uid. */
15487 const uid_t curr_uid = getuid();
15488 /* If set, we want to run as run_as_user. */
15489 const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
15490 const struct passwd *to_pw = NULL;
15491
15492 if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
15493 /* run_as_user does not exist on the system. We can't proceed
15494 * further. */
15495 mg_cry_ctx_internal(phys_ctx,
15496 "%s: unknown user [%s]",
15497 __func__,
15498 run_as_user);
15499 } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
15500 /* There was either no request to change user, or we're already
15501 * running as run_as_user. Nothing else to do.
15502 */
15503 success = 1;
15504 } else {
15505 /* Valid change request. */
15506 if (setgid(to_pw->pw_gid) == -1) {
15507 mg_cry_ctx_internal(phys_ctx,
15508 "%s: setgid(%s): %s",
15509 __func__,
15510 run_as_user,
15511 strerror(errno));
15512 } else if (setgroups(0, NULL) == -1) {
15513 mg_cry_ctx_internal(phys_ctx,
15514 "%s: setgroups(): %s",
15515 __func__,
15516 strerror(errno));
15517 } else if (setuid(to_pw->pw_uid) == -1) {
15518 mg_cry_ctx_internal(phys_ctx,
15519 "%s: setuid(%s): %s",
15520 __func__,
15521 run_as_user,
15522 strerror(errno));
15523 } else {
15524 success = 1;
15525 }
15526 }
15527 }
15528
15529 return success;
15530}
15531#endif /* !_WIN32 */
15532
15533
15534static void
15535tls_dtor(void *key)
15536{
15537 struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
15538 /* key == pthread_getspecific(sTlsKey); */
15539
15540 if (tls) {
15541 if (tls->is_master == 2) {
15542 tls->is_master = -3; /* Mark memory as dead */
15543 mg_free(tls);
15544 }
15545 }
15546 pthread_setspecific(sTlsKey, NULL);
15547}
15548
15549
15550#if defined(USE_MBEDTLS)
15551/* Check if SSL is required.
15552 * If so, set up ctx->ssl_ctx pointer. */
15553static int
15554mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
15555{
15556 if (!phys_ctx) {
15557 return 0;
15558 }
15559
15560 if (!dom_ctx) {
15561 dom_ctx = &(phys_ctx->dd);
15562 }
15563
15564 if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
15565 /* No SSL port is set. No need to setup SSL. */
15566 return 1;
15567 }
15568
15569 dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
15570 if (dom_ctx->ssl_ctx == NULL) {
15571 fprintf(stderr, "ssl_ctx malloc failed\n");
15572 return 0;
15573 }
15574
15575 return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
15576 == 0
15577 ? 1
15578 : 0;
15579}
15580
15581#elif !defined(NO_SSL)
15582
15583static int ssl_use_pem_file(struct mg_context *phys_ctx,
15584 struct mg_domain_context *dom_ctx,
15585 const char *pem,
15586 const char *chain);
15587static const char *ssl_error(void);
15588
15589
15590static int
15592{
15593 struct stat cert_buf;
15594 int64_t t = 0;
15595 const char *pem;
15596 const char *chain;
15597 int should_verify_peer;
15598
15599 if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
15600 /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
15601 * refresh_trust still can not work. */
15602 return 0;
15603 }
15604 chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
15605 if (chain == NULL) {
15606 /* pem is not NULL here */
15607 chain = pem;
15608 }
15609 if (*chain == 0) {
15610 chain = NULL;
15611 }
15612
15613 if (stat(pem, &cert_buf) != -1) {
15614 t = (int64_t)cert_buf.st_mtime;
15615 }
15616
15618 if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
15619 conn->dom_ctx->ssl_cert_last_mtime = t;
15620
15621 should_verify_peer = 0;
15622 if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
15624 == 0) {
15625 should_verify_peer = 1;
15627 "optional")
15628 == 0) {
15629 should_verify_peer = 1;
15630 }
15631 }
15632
15633 if (should_verify_peer) {
15634 char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
15635 char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
15636 if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
15637 ca_file,
15638 ca_path)
15639 != 1) {
15642 conn->phys_ctx,
15643 "SSL_CTX_load_verify_locations error: %s "
15644 "ssl_verify_peer requires setting "
15645 "either ssl_ca_path or ssl_ca_file. Is any of them "
15646 "present in "
15647 "the .conf file?",
15648 ssl_error());
15649 return 0;
15650 }
15651 }
15652
15653 if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
15655 return 0;
15656 }
15657 }
15659
15660 return 1;
15661}
15662
15663#if defined(OPENSSL_API_1_1)
15664#else
15665static pthread_mutex_t *ssl_mutexes;
15666#endif /* OPENSSL_API_1_1 */
15667
15668static int
15670 int (*func)(SSL *),
15671 const struct mg_client_options *client_options)
15672{
15673 int ret, err;
15674 int short_trust;
15675 unsigned timeout = 1024;
15676 unsigned i;
15677
15678 if (!conn) {
15679 return 0;
15680 }
15681
15682 short_trust =
15683 (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
15684 && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
15685
15686 if (short_trust) {
15687 int trust_ret = refresh_trust(conn);
15688 if (!trust_ret) {
15689 return trust_ret;
15690 }
15691 }
15692
15694 conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
15696 if (conn->ssl == NULL) {
15697 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15698 OPENSSL_REMOVE_THREAD_STATE();
15699 return 0;
15700 }
15701 SSL_set_app_data(conn->ssl, (char *)conn);
15702
15703 ret = SSL_set_fd(conn->ssl, conn->client.sock);
15704 if (ret != 1) {
15705 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15706 SSL_free(conn->ssl);
15707 conn->ssl = NULL;
15708 OPENSSL_REMOVE_THREAD_STATE();
15709 return 0;
15710 }
15711
15712 if (client_options) {
15713 if (client_options->host_name) {
15714 SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
15715 }
15716 }
15717
15718 /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
15719 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
15720 /* NOTE: The loop below acts as a back-off, so we can end
15721 * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
15722 int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
15723 if (to >= 0) {
15724 timeout = (unsigned)to;
15725 }
15726 }
15727
15728 /* SSL functions may fail and require to be called again:
15729 * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
15730 * Here "func" could be SSL_connect or SSL_accept. */
15731 for (i = 0; i <= timeout; i += 50) {
15732 ERR_clear_error();
15733 /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
15734 ret = func(conn->ssl);
15735 if (ret != 1) {
15736 err = SSL_get_error(conn->ssl, ret);
15737 if ((err == SSL_ERROR_WANT_CONNECT)
15738 || (err == SSL_ERROR_WANT_ACCEPT)
15739 || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
15740 || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
15741 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
15742 /* Don't wait if the server is going to be stopped. */
15743 break;
15744 }
15745 if (err == SSL_ERROR_WANT_X509_LOOKUP) {
15746 /* Simply retry the function call. */
15747 mg_sleep(50);
15748 } else {
15749 /* Need to retry the function call "later".
15750 * See https://linux.die.net/man/3/ssl_get_error
15751 * This is typical for non-blocking sockets. */
15752 struct mg_pollfd pfd;
15753 int pollres;
15754 pfd.fd = conn->client.sock;
15755 pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
15756 || (err == SSL_ERROR_WANT_WRITE))
15757 ? POLLOUT
15758 : POLLIN;
15759 pollres =
15760 mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
15761 if (pollres < 0) {
15762 /* Break if error occured (-1)
15763 * or server shutdown (-2) */
15764 break;
15765 }
15766 }
15767
15768 } else if (err == SSL_ERROR_SYSCALL) {
15769 /* This is an IO error. Look at errno. */
15770 mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
15771 break;
15772
15773 } else {
15774 /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
15775 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15776 break;
15777 }
15778
15779 } else {
15780 /* success */
15781 break;
15782 }
15783 }
15784 ERR_clear_error();
15785
15786 if (ret != 1) {
15787 SSL_free(conn->ssl);
15788 conn->ssl = NULL;
15789 OPENSSL_REMOVE_THREAD_STATE();
15790 return 0;
15791 }
15792
15793 return 1;
15794}
15795
15796
15797/* Return OpenSSL error message (from CRYPTO lib) */
15798static const char *
15800{
15801 unsigned long err;
15802 err = ERR_get_error();
15803 return ((err == 0) ? "" : ERR_error_string(err, NULL));
15804}
15805
15806
15807static int
15808hexdump2string(void *mem, int memlen, char *buf, int buflen)
15809{
15810 int i;
15811 const char hexdigit[] = "0123456789abcdef";
15812
15813 if ((memlen <= 0) || (buflen <= 0)) {
15814 return 0;
15815 }
15816 if (buflen < (3 * memlen)) {
15817 return 0;
15818 }
15819
15820 for (i = 0; i < memlen; i++) {
15821 if (i > 0) {
15822 buf[3 * i - 1] = ' ';
15823 }
15824 buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
15825 buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
15826 }
15827 buf[3 * memlen - 1] = 0;
15828
15829 return 1;
15830}
15831
15832
15833static int
15835 struct mg_client_cert *client_cert)
15836{
15837 X509 *cert = SSL_get_peer_certificate(conn->ssl);
15838 if (cert) {
15839 char str_buf[1024];
15840 unsigned char buf[256];
15841 char *str_serial = NULL;
15842 unsigned int ulen;
15843 int ilen;
15844 unsigned char *tmp_buf;
15845 unsigned char *tmp_p;
15846
15847 /* Handle to algorithm used for fingerprint */
15848 const EVP_MD *digest = EVP_get_digestbyname("sha1");
15849
15850 /* Get Subject and issuer */
15851 X509_NAME *subj = X509_get_subject_name(cert);
15852 X509_NAME *iss = X509_get_issuer_name(cert);
15853
15854 /* Get serial number */
15855 ASN1_INTEGER *serial = X509_get_serialNumber(cert);
15856
15857 /* Translate serial number to a hex string */
15858 BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
15859 if (serial_bn) {
15860 str_serial = BN_bn2hex(serial_bn);
15861 BN_free(serial_bn);
15862 }
15863 client_cert->serial =
15864 str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
15865
15866 /* Translate subject and issuer to a string */
15867 (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
15868 client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
15869 (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
15870 client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
15871
15872 /* Calculate SHA1 fingerprint and store as a hex string */
15873 ulen = 0;
15874
15875 /* ASN1_digest is deprecated. Do the calculation manually,
15876 * using EVP_Digest. */
15877 ilen = i2d_X509(cert, NULL);
15878 tmp_buf = (ilen > 0)
15879 ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
15880 conn->phys_ctx)
15881 : NULL;
15882 if (tmp_buf) {
15883 tmp_p = tmp_buf;
15884 (void)i2d_X509(cert, &tmp_p);
15885 if (!EVP_Digest(
15886 tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
15887 ulen = 0;
15888 }
15889 mg_free(tmp_buf);
15890 }
15891
15892 if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
15893 *str_buf = 0;
15894 }
15895 client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
15896
15897 client_cert->peer_cert = (void *)cert;
15898
15899 /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
15900 * see https://linux.die.net/man/3/bn_bn2hex */
15901 OPENSSL_free(str_serial);
15902 return 1;
15903 }
15904 return 0;
15905}
15906
15907
15908#if defined(OPENSSL_API_1_1)
15909#else
15910static void
15911ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
15912{
15913 (void)line;
15914 (void)file;
15915
15916 if (mode & 1) {
15917 /* 1 is CRYPTO_LOCK */
15918 (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
15919 } else {
15920 (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
15921 }
15922}
15923#endif /* OPENSSL_API_1_1 */
15924
15925
15926#if !defined(NO_SSL_DL)
15927/* Load a DLL/Shared Object with a TLS/SSL implementation. */
15928static void *
15929load_tls_dll(char *ebuf,
15930 size_t ebuf_len,
15931 const char *dll_name,
15932 struct ssl_func *sw,
15933 int *feature_missing)
15934{
15935 union {
15936 void *p;
15937 void (*fp)(void);
15938 } u;
15939 void *dll_handle;
15940 struct ssl_func *fp;
15941 int ok;
15942 int truncated = 0;
15943
15944 if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
15945 mg_snprintf(NULL,
15946 NULL, /* No truncation check for ebuf */
15947 ebuf,
15948 ebuf_len,
15949 "%s: cannot load %s",
15950 __func__,
15951 dll_name);
15952 return NULL;
15953 }
15954
15955 ok = 1;
15956 for (fp = sw; fp->name != NULL; fp++) {
15957#if defined(_WIN32)
15958 /* GetProcAddress() returns pointer to function */
15959 u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
15960#else
15961 /* dlsym() on UNIX returns void *. ISO C forbids casts of data
15962 * pointers to function pointers. We need to use a union to make a
15963 * cast. */
15964 u.p = dlsym(dll_handle, fp->name);
15965#endif /* _WIN32 */
15966
15967 /* Set pointer (might be NULL) */
15968 fp->ptr = u.fp;
15969
15970 if (u.fp == NULL) {
15971 DEBUG_TRACE("Missing function: %s\n", fp->name);
15972 if (feature_missing) {
15973 feature_missing[fp->required]++;
15974 }
15975 if (fp->required == TLS_Mandatory) {
15976 /* Mandatory function is missing */
15977 if (ok) {
15978 /* This is the first missing function.
15979 * Create a new error message. */
15980 mg_snprintf(NULL,
15981 &truncated,
15982 ebuf,
15983 ebuf_len,
15984 "%s: %s: cannot find %s",
15985 __func__,
15986 dll_name,
15987 fp->name);
15988 ok = 0;
15989 } else {
15990 /* This is yet anothermissing function.
15991 * Append existing error message. */
15992 size_t cur_len = strlen(ebuf);
15993 if (!truncated && ((ebuf_len - cur_len) > 3)) {
15994 mg_snprintf(NULL,
15995 &truncated,
15996 ebuf + cur_len,
15997 ebuf_len - cur_len - 3,
15998 ", %s",
15999 fp->name);
16000 if (truncated) {
16001 /* If truncated, add "..." */
16002 strcat(ebuf, "...");
16003 }
16004 }
16005 }
16006 }
16007 }
16008 }
16009
16010 if (!ok) {
16011 (void)dlclose(dll_handle);
16012 return NULL;
16013 }
16014
16015 return dll_handle;
16016}
16017
16018
16019static void *ssllib_dll_handle; /* Store the ssl library handle. */
16020static void *cryptolib_dll_handle; /* Store the crypto library handle. */
16021
16022#endif /* NO_SSL_DL */
16023
16024
16025#if defined(SSL_ALREADY_INITIALIZED)
16026static volatile ptrdiff_t cryptolib_users =
16027 1; /* Reference counter for crypto library. */
16028#else
16029static volatile ptrdiff_t cryptolib_users =
16030 0; /* Reference counter for crypto library. */
16031#endif
16032
16033
16034static int
16035initialize_openssl(char *ebuf, size_t ebuf_len)
16036{
16037#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16038 int i, num_locks;
16039 size_t size;
16040#endif
16041
16042 if (ebuf_len > 0) {
16043 ebuf[0] = 0;
16044 }
16045
16046#if !defined(NO_SSL_DL)
16047 if (!cryptolib_dll_handle) {
16048 memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
16050 ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
16051 if (!cryptolib_dll_handle) {
16052 mg_snprintf(NULL,
16053 NULL, /* No truncation check for ebuf */
16054 ebuf,
16055 ebuf_len,
16056 "%s: error loading library %s",
16057 __func__,
16058 CRYPTO_LIB);
16059 DEBUG_TRACE("%s", ebuf);
16060 return 0;
16061 }
16062 }
16063#endif /* NO_SSL_DL */
16064
16065 if (mg_atomic_inc(&cryptolib_users) > 1) {
16066 return 1;
16067 }
16068
16069#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16070 /* Initialize locking callbacks, needed for thread safety.
16071 * http://www.openssl.org/support/faq.html#PROG1
16072 */
16073 num_locks = CRYPTO_num_locks();
16074 if (num_locks < 0) {
16075 num_locks = 0;
16076 }
16077 size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
16078
16079 /* allocate mutex array, if required */
16080 if (num_locks == 0) {
16081 /* No mutex array required */
16082 ssl_mutexes = NULL;
16083 } else {
16084 /* Mutex array required - allocate it */
16085 ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
16086
16087 /* Check OOM */
16088 if (ssl_mutexes == NULL) {
16089 mg_snprintf(NULL,
16090 NULL, /* No truncation check for ebuf */
16091 ebuf,
16092 ebuf_len,
16093 "%s: cannot allocate mutexes: %s",
16094 __func__,
16095 ssl_error());
16096 DEBUG_TRACE("%s", ebuf);
16097 return 0;
16098 }
16099
16100 /* initialize mutex array */
16101 for (i = 0; i < num_locks; i++) {
16102 if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
16103 mg_snprintf(NULL,
16104 NULL, /* No truncation check for ebuf */
16105 ebuf,
16106 ebuf_len,
16107 "%s: error initializing mutex %i of %i",
16108 __func__,
16109 i,
16110 num_locks);
16111 DEBUG_TRACE("%s", ebuf);
16113 return 0;
16114 }
16115 }
16116 }
16117
16118 CRYPTO_set_locking_callback(&ssl_locking_callback);
16119 CRYPTO_set_id_callback(&mg_current_thread_id);
16120#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16121
16122#if !defined(NO_SSL_DL)
16123 if (!ssllib_dll_handle) {
16125 load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
16126 if (!ssllib_dll_handle) {
16127#if !defined(OPENSSL_API_1_1)
16129#endif
16130 DEBUG_TRACE("%s", ebuf);
16131 return 0;
16132 }
16133 }
16134#endif /* NO_SSL_DL */
16135
16136#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16137 && !defined(NO_SSL_DL)
16138 /* Initialize SSL library */
16139 OPENSSL_init_ssl(0, NULL);
16140 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
16142 NULL);
16143#else
16144 /* Initialize SSL library */
16145 SSL_library_init();
16146 SSL_load_error_strings();
16147#endif
16148
16149 return 1;
16150}
16151
16152
16153static int
16155 struct mg_domain_context *dom_ctx,
16156 const char *pem,
16157 const char *chain)
16158{
16159 if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
16160 mg_cry_ctx_internal(phys_ctx,
16161 "%s: cannot open certificate file %s: %s",
16162 __func__,
16163 pem,
16164 ssl_error());
16165 return 0;
16166 }
16167
16168 /* could use SSL_CTX_set_default_passwd_cb_userdata */
16169 if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
16170 mg_cry_ctx_internal(phys_ctx,
16171 "%s: cannot open private key file %s: %s",
16172 __func__,
16173 pem,
16174 ssl_error());
16175 return 0;
16176 }
16177
16178 if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
16179 mg_cry_ctx_internal(phys_ctx,
16180 "%s: certificate and private key do not match: %s",
16181 __func__,
16182 pem);
16183 return 0;
16184 }
16185
16186 /* In contrast to OpenSSL, wolfSSL does not support certificate
16187 * chain files that contain private keys and certificates in
16188 * SSL_CTX_use_certificate_chain_file.
16189 * The CivetWeb-Server used pem-Files that contained both information.
16190 * In order to make wolfSSL work, it is split in two files.
16191 * One file that contains key and certificate used by the server and
16192 * an optional chain file for the ssl stack.
16193 */
16194 if (chain) {
16195 if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
16196 mg_cry_ctx_internal(phys_ctx,
16197 "%s: cannot use certificate chain file %s: %s",
16198 __func__,
16199 chain,
16200 ssl_error());
16201 return 0;
16202 }
16203 }
16204 return 1;
16205}
16206
16207
16208#if defined(OPENSSL_API_1_1)
16209static unsigned long
16210ssl_get_protocol(int version_id)
16211{
16212 long unsigned ret = (long unsigned)SSL_OP_ALL;
16213 if (version_id > 0)
16214 ret |= SSL_OP_NO_SSLv2;
16215 if (version_id > 1)
16216 ret |= SSL_OP_NO_SSLv3;
16217 if (version_id > 2)
16218 ret |= SSL_OP_NO_TLSv1;
16219 if (version_id > 3)
16220 ret |= SSL_OP_NO_TLSv1_1;
16221 if (version_id > 4)
16222 ret |= SSL_OP_NO_TLSv1_2;
16223#if defined(SSL_OP_NO_TLSv1_3)
16224 if (version_id > 5)
16225 ret |= SSL_OP_NO_TLSv1_3;
16226#endif
16227 return ret;
16228}
16229#else
16230static long
16231ssl_get_protocol(int version_id)
16232{
16233 unsigned long ret = (unsigned long)SSL_OP_ALL;
16234 if (version_id > 0)
16235 ret |= SSL_OP_NO_SSLv2;
16236 if (version_id > 1)
16237 ret |= SSL_OP_NO_SSLv3;
16238 if (version_id > 2)
16239 ret |= SSL_OP_NO_TLSv1;
16240 if (version_id > 3)
16241 ret |= SSL_OP_NO_TLSv1_1;
16242 if (version_id > 4)
16243 ret |= SSL_OP_NO_TLSv1_2;
16244#if defined(SSL_OP_NO_TLSv1_3)
16245 if (version_id > 5)
16246 ret |= SSL_OP_NO_TLSv1_3;
16247#endif
16248 return (long)ret;
16249}
16250#endif /* OPENSSL_API_1_1 */
16251
16252
16253/* SSL callback documentation:
16254 * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
16255 * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
16256 * https://linux.die.net/man/3/ssl_set_info_callback */
16257/* Note: There is no "const" for the first argument in the documentation
16258 * examples, however some (maybe most, but not all) headers of OpenSSL
16259 * versions / OpenSSL compatibility layers have it. Having a different
16260 * definition will cause a warning in C and an error in C++. Use "const SSL
16261 * *", while automatical conversion from "SSL *" works for all compilers,
16262 * but not other way around */
16263static void
16264ssl_info_callback(const SSL *ssl, int what, int ret)
16265{
16266 (void)ret;
16267
16269 SSL_get_app_data(ssl);
16270 }
16272 /* TODO: check for openSSL 1.1 */
16273 //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
16274 // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
16275 }
16276}
16277
16278
16279static int
16280ssl_servername_callback(SSL *ssl, int *ad, void *arg)
16281{
16282#if defined(GCC_DIAGNOSTIC)
16283#pragma GCC diagnostic push
16284#pragma GCC diagnostic ignored "-Wcast-align"
16285#endif /* defined(GCC_DIAGNOSTIC) */
16286
16287 /* We used an aligned pointer in SSL_set_app_data */
16288 struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
16289
16290#if defined(GCC_DIAGNOSTIC)
16291#pragma GCC diagnostic pop
16292#endif /* defined(GCC_DIAGNOSTIC) */
16293
16294 const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
16295
16296 (void)ad;
16297 (void)arg;
16298
16299 if ((conn == NULL) || (conn->phys_ctx == NULL)) {
16300 DEBUG_ASSERT(0);
16301 return SSL_TLSEXT_ERR_NOACK;
16302 }
16303 conn->dom_ctx = &(conn->phys_ctx->dd);
16304
16305 /* Old clients (Win XP) will not support SNI. Then, there
16306 * is no server name available in the request - we can
16307 * only work with the default certificate.
16308 * Multiple HTTPS hosts on one IP+port are only possible
16309 * with a certificate containing all alternative names.
16310 */
16311 if ((servername == NULL) || (*servername == 0)) {
16312 DEBUG_TRACE("%s", "SSL connection not supporting SNI");
16314 SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
16316 return SSL_TLSEXT_ERR_NOACK;
16317 }
16318
16319 DEBUG_TRACE("TLS connection to host %s", servername);
16320
16321 while (conn->dom_ctx) {
16322 if (!mg_strcasecmp(servername,
16324 /* Found matching domain */
16325 DEBUG_TRACE("TLS domain %s found",
16327 break;
16328 }
16330 conn->dom_ctx = conn->dom_ctx->next;
16332 }
16333
16334 if (conn->dom_ctx == NULL) {
16335 /* Default domain */
16336 DEBUG_TRACE("TLS default domain %s used",
16338 conn->dom_ctx = &(conn->phys_ctx->dd);
16339 }
16341 SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
16343 return SSL_TLSEXT_ERR_OK;
16344}
16345
16346
16347#if defined(USE_ALPN)
16348static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
16349static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
16350 alpn_proto_list + 3 + 8,
16351 NULL};
16352#if defined(USE_HTTP2)
16353static const char *alpn_proto_order_http2[] = {alpn_proto_list,
16354 alpn_proto_list + 3,
16355 alpn_proto_list + 3 + 8,
16356 NULL};
16357#endif
16358
16359static int
16360alpn_select_cb(SSL *ssl,
16361 const unsigned char **out,
16362 unsigned char *outlen,
16363 const unsigned char *in,
16364 unsigned int inlen,
16365 void *arg)
16366{
16367 struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
16368 unsigned int i, j, enable_http2 = 0;
16369 const char **alpn_proto_order = alpn_proto_order_http1;
16370
16371 struct mg_workerTLS *tls =
16372 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
16373
16374 (void)ssl;
16375
16376 if (tls == NULL) {
16377 /* Need to store protocol in Thread Local Storage */
16378 /* If there is no Thread Local Storage, don't use ALPN */
16379 return SSL_TLSEXT_ERR_NOACK;
16380 }
16381
16382#if defined(USE_HTTP2)
16383 enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
16384 if (enable_http2) {
16385 alpn_proto_order = alpn_proto_order_http2;
16386 }
16387#endif
16388
16389 for (j = 0; alpn_proto_order[j] != NULL; j++) {
16390 /* check all accepted protocols in this order */
16391 const char *alpn_proto = alpn_proto_order[j];
16392 /* search input for matching protocol */
16393 for (i = 0; i < inlen; i++) {
16394 if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
16395 *out = in + i + 1;
16396 *outlen = in[i];
16397 tls->alpn_proto = alpn_proto;
16398 return SSL_TLSEXT_ERR_OK;
16399 }
16400 }
16401 }
16402
16403 /* Nothing found */
16404 return SSL_TLSEXT_ERR_NOACK;
16405}
16406
16407
16408static int
16409next_protos_advertised_cb(SSL *ssl,
16410 const unsigned char **data,
16411 unsigned int *len,
16412 void *arg)
16413{
16414 struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
16415 *data = (const unsigned char *)alpn_proto_list;
16416 *len = (unsigned int)strlen((const char *)data);
16417
16418 (void)ssl;
16419 (void)dom_ctx;
16420
16421 return SSL_TLSEXT_ERR_OK;
16422}
16423
16424
16425static int
16426init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16427{
16428 unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
16429 int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
16430 (const unsigned char *)alpn_proto_list,
16431 alpn_len);
16432 if (ret != 0) {
16433 mg_cry_ctx_internal(phys_ctx,
16434 "SSL_CTX_set_alpn_protos error: %s",
16435 ssl_error());
16436 }
16437
16438 SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
16439 alpn_select_cb,
16440 (void *)dom_ctx);
16441
16442 SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
16443 next_protos_advertised_cb,
16444 (void *)dom_ctx);
16445
16446 return ret;
16447}
16448#endif
16449
16450
16451/* Setup SSL CTX as required by CivetWeb */
16452static int
16454 struct mg_domain_context *dom_ctx,
16455 const char *pem,
16456 const char *chain)
16457{
16458 int callback_ret;
16459 int should_verify_peer;
16460 int peer_certificate_optional;
16461 const char *ca_path;
16462 const char *ca_file;
16463 int use_default_verify_paths;
16464 int verify_depth;
16465 struct timespec now_mt;
16466 md5_byte_t ssl_context_id[16];
16467 md5_state_t md5state;
16468 int protocol_ver;
16469 int ssl_cache_timeout;
16470
16471#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16472 && !defined(NO_SSL_DL)
16473 if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
16474 mg_cry_ctx_internal(phys_ctx,
16475 "SSL_CTX_new (server) error: %s",
16476 ssl_error());
16477 return 0;
16478 }
16479#else
16480 if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
16481 mg_cry_ctx_internal(phys_ctx,
16482 "SSL_CTX_new (server) error: %s",
16483 ssl_error());
16484 return 0;
16485 }
16486#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16487
16488#if defined(SSL_OP_NO_TLSv1_3)
16489 SSL_CTX_clear_options(dom_ctx->ssl_ctx,
16493#else
16494 SSL_CTX_clear_options(dom_ctx->ssl_ctx,
16497#endif
16498
16499 protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
16500 SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
16501 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
16502 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
16503 SSL_CTX_set_options(dom_ctx->ssl_ctx,
16505 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
16506
16507#if defined(SSL_OP_NO_RENEGOTIATION)
16508 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
16509#endif
16510
16511#if !defined(NO_SSL_DL)
16512 SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
16513#endif /* NO_SSL_DL */
16514
16515 /* In SSL documentation examples callback defined without const
16516 * specifier 'void (*)(SSL *, int, int)' See:
16517 * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
16518 * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
16519 * But in the source code const SSL is used:
16520 * 'void (*)(const SSL *, int, int)' See:
16521 * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
16522 * Problem about wrong documentation described, but not resolved:
16523 * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
16524 * Wrong const cast ignored on C or can be suppressed by compiler flags.
16525 * But when compiled with modern C++ compiler, correct const should be
16526 * provided
16527 */
16528 SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
16529
16530 SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
16532
16533 /* If a callback has been specified, call it. */
16534 callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
16535 ? 0
16536 : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
16537 phys_ctx->user_data));
16538
16539 /* If callback returns 0, civetweb sets up the SSL certificate.
16540 * If it returns 1, civetweb assumes the calback already did this.
16541 * If it returns -1, initializing ssl fails. */
16542 if (callback_ret < 0) {
16543 mg_cry_ctx_internal(phys_ctx,
16544 "SSL callback returned error: %i",
16545 callback_ret);
16546 return 0;
16547 }
16548 if (callback_ret > 0) {
16549 /* Callback did everything. */
16550 return 1;
16551 }
16552
16553 /* If a domain callback has been specified, call it. */
16554 callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
16555 ? 0
16556 : (phys_ctx->callbacks.init_ssl_domain(
16557 dom_ctx->config[AUTHENTICATION_DOMAIN],
16558 dom_ctx->ssl_ctx,
16559 phys_ctx->user_data));
16560
16561 /* If domain callback returns 0, civetweb sets up the SSL certificate.
16562 * If it returns 1, civetweb assumes the calback already did this.
16563 * If it returns -1, initializing ssl fails. */
16564 if (callback_ret < 0) {
16565 mg_cry_ctx_internal(phys_ctx,
16566 "Domain SSL callback returned error: %i",
16567 callback_ret);
16568 return 0;
16569 }
16570 if (callback_ret > 0) {
16571 /* Domain callback did everything. */
16572 return 1;
16573 }
16574
16575 /* Use some combination of start time, domain and port as a SSL
16576 * context ID. This should be unique on the current machine. */
16577 md5_init(&md5state);
16578 clock_gettime(CLOCK_MONOTONIC, &now_mt);
16579 md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
16580 md5_append(&md5state,
16581 (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
16582 strlen(phys_ctx->dd.config[LISTENING_PORTS]));
16583 md5_append(&md5state,
16584 (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
16585 strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
16586 md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
16587 md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
16588 md5_finish(&md5state, ssl_context_id);
16589
16590 SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
16591 (unsigned char *)ssl_context_id,
16592 sizeof(ssl_context_id));
16593
16594 if (pem != NULL) {
16595 if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
16596 return 0;
16597 }
16598 }
16599
16600 /* Should we support client certificates? */
16601 /* Default is "no". */
16602 should_verify_peer = 0;
16603 peer_certificate_optional = 0;
16604 if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
16605 if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
16606 /* Yes, they are mandatory */
16607 should_verify_peer = 1;
16608 } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
16609 "optional")
16610 == 0) {
16611 /* Yes, they are optional */
16612 should_verify_peer = 1;
16613 peer_certificate_optional = 1;
16614 }
16615 }
16616
16617 use_default_verify_paths =
16618 (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
16619 && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
16620 == 0);
16621
16622 if (should_verify_peer) {
16623 ca_path = dom_ctx->config[SSL_CA_PATH];
16624 ca_file = dom_ctx->config[SSL_CA_FILE];
16625 if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
16626 != 1) {
16627 mg_cry_ctx_internal(phys_ctx,
16628 "SSL_CTX_load_verify_locations error: %s "
16629 "ssl_verify_peer requires setting "
16630 "either ssl_ca_path or ssl_ca_file. "
16631 "Is any of them present in the "
16632 ".conf file?",
16633 ssl_error());
16634 return 0;
16635 }
16636
16637 if (peer_certificate_optional) {
16638 SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
16639 } else {
16640 SSL_CTX_set_verify(dom_ctx->ssl_ctx,
16643 NULL);
16644 }
16645
16646 if (use_default_verify_paths
16647 && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
16648 mg_cry_ctx_internal(phys_ctx,
16649 "SSL_CTX_set_default_verify_paths error: %s",
16650 ssl_error());
16651 return 0;
16652 }
16653
16654 if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
16655 verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
16656 SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
16657 }
16658 }
16659
16660 if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
16661 if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
16662 dom_ctx->config[SSL_CIPHER_LIST])
16663 != 1) {
16664 mg_cry_ctx_internal(phys_ctx,
16665 "SSL_CTX_set_cipher_list error: %s",
16666 ssl_error());
16667 }
16668 }
16669
16670 /* SSL session caching */
16671 ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
16672 ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
16673 : 0);
16674 if (ssl_cache_timeout > 0) {
16675 SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
16676 /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
16677 * default */
16678 SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
16679 }
16680
16681#if defined(USE_ALPN)
16682 /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
16683#if !defined(NO_SSL_DL)
16685#endif
16686 {
16687 init_alpn(phys_ctx, dom_ctx);
16688 }
16689#endif
16690
16691 return 1;
16692}
16693
16694
16695/* Check if SSL is required.
16696 * If so, dynamically load SSL library
16697 * and set up ctx->ssl_ctx pointer. */
16698static int
16699init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16700{
16701 void *ssl_ctx = 0;
16702 int callback_ret;
16703 const char *pem;
16704 const char *chain;
16705 char ebuf[128];
16706
16707 if (!phys_ctx) {
16708 return 0;
16709 }
16710
16711 if (!dom_ctx) {
16712 dom_ctx = &(phys_ctx->dd);
16713 }
16714
16715 if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
16716 /* No SSL port is set. No need to setup SSL. */
16717 return 1;
16718 }
16719
16720 /* Check for external SSL_CTX */
16721 callback_ret =
16722 (phys_ctx->callbacks.external_ssl_ctx == NULL)
16723 ? 0
16724 : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
16725 phys_ctx->user_data));
16726
16727 if (callback_ret < 0) {
16728 /* Callback exists and returns <0: Initializing failed. */
16729 mg_cry_ctx_internal(phys_ctx,
16730 "external_ssl_ctx callback returned error: %i",
16731 callback_ret);
16732 return 0;
16733 } else if (callback_ret > 0) {
16734 /* Callback exists and returns >0: Initializing complete,
16735 * civetweb should not modify the SSL context. */
16736 dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
16737 if (!initialize_openssl(ebuf, sizeof(ebuf))) {
16738 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16739 return 0;
16740 }
16741 return 1;
16742 }
16743 /* If the callback does not exist or return 0, civetweb must initialize
16744 * the SSL context. Handle "domain" callback next. */
16745
16746 /* Check for external domain SSL_CTX callback. */
16747 callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
16748 ? 0
16750 dom_ctx->config[AUTHENTICATION_DOMAIN],
16751 &ssl_ctx,
16752 phys_ctx->user_data));
16753
16754 if (callback_ret < 0) {
16755 /* Callback < 0: Error. Abort init. */
16757 phys_ctx,
16758 "external_ssl_ctx_domain callback returned error: %i",
16759 callback_ret);
16760 return 0;
16761 } else if (callback_ret > 0) {
16762 /* Callback > 0: Consider init done. */
16763 dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
16764 if (!initialize_openssl(ebuf, sizeof(ebuf))) {
16765 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16766 return 0;
16767 }
16768 return 1;
16769 }
16770 /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
16771 * 0, CivetWeb should continue initializing SSL */
16772
16773 /* If PEM file is not specified and the init_ssl callbacks
16774 * are not specified, setup will fail. */
16775 if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
16776 && (phys_ctx->callbacks.init_ssl == NULL)
16777 && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
16778 /* No certificate and no init_ssl callbacks:
16779 * Essential data to set up TLS is missing.
16780 */
16781 mg_cry_ctx_internal(phys_ctx,
16782 "Initializing SSL failed: -%s is not set",
16784 return 0;
16785 }
16786
16787 /* If a certificate chain is configured, use it. */
16788 chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
16789 if (chain == NULL) {
16790 /* Default: certificate chain in PEM file */
16791 chain = pem;
16792 }
16793 if ((chain != NULL) && (*chain == 0)) {
16794 /* If the chain is an empty string, don't use it. */
16795 chain = NULL;
16796 }
16797
16798 if (!initialize_openssl(ebuf, sizeof(ebuf))) {
16799 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16800 return 0;
16801 }
16802
16803 return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
16804}
16805
16806
16807static void
16809{
16810#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
16811
16812 if (mg_atomic_dec(&cryptolib_users) == 0) {
16813
16814 /* Shutdown according to
16815 * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
16816 * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
16817 */
16818 CONF_modules_unload(1);
16819#else
16820 int i;
16821
16822 if (mg_atomic_dec(&cryptolib_users) == 0) {
16823
16824 /* Shutdown according to
16825 * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
16826 * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
16827 */
16828 CRYPTO_set_locking_callback(NULL);
16829 CRYPTO_set_id_callback(NULL);
16830 ENGINE_cleanup();
16831 CONF_modules_unload(1);
16832 ERR_free_strings();
16833 EVP_cleanup();
16834 CRYPTO_cleanup_all_ex_data();
16835 OPENSSL_REMOVE_THREAD_STATE();
16836
16837 for (i = 0; i < CRYPTO_num_locks(); i++) {
16838 pthread_mutex_destroy(&ssl_mutexes[i]);
16839 }
16841 ssl_mutexes = NULL;
16842#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16843 }
16844}
16845#endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
16846
16847
16848#if !defined(NO_FILESYSTEMS)
16849static int
16850set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16851{
16852 if (phys_ctx) {
16853 struct mg_file file = STRUCT_FILE_INITIALIZER;
16854 const char *path;
16855 struct mg_connection fc;
16856 if (!dom_ctx) {
16857 dom_ctx = &(phys_ctx->dd);
16858 }
16860 if ((path != NULL)
16861 && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
16863 "Cannot open %s: %s",
16864 path,
16865 strerror(ERRNO));
16866 return 0;
16867 }
16868 return 1;
16869 }
16870 return 0;
16871}
16872#endif /* NO_FILESYSTEMS */
16873
16874
16875static int
16877{
16878 union usa sa;
16879 memset(&sa, 0, sizeof(sa));
16880#if defined(USE_IPV6)
16881 sa.sin6.sin6_family = AF_INET6;
16882#else
16883 sa.sin.sin_family = AF_INET;
16884#endif
16885 return check_acl(phys_ctx, &sa) != -1;
16886}
16887
16888
16889static void
16891{
16892 if (!conn) {
16893 return;
16894 }
16895
16896 conn->num_bytes_sent = conn->consumed_content = 0;
16897
16898 conn->path_info = NULL;
16899 conn->status_code = -1;
16900 conn->content_len = -1;
16901 conn->is_chunked = 0;
16902 conn->must_close = 0;
16903 conn->request_len = 0;
16904 conn->request_state = 0;
16905 conn->throttle = 0;
16906 conn->accept_gzip = 0;
16907
16911 conn->response_info.status_text = NULL;
16912 conn->response_info.status_code = 0;
16913
16914 conn->request_info.remote_user = NULL;
16915 conn->request_info.request_method = NULL;
16916 conn->request_info.request_uri = NULL;
16917
16918 /* Free cleaned local URI (if any) */
16919 if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
16920 mg_free((void *)conn->request_info.local_uri);
16921 conn->request_info.local_uri = NULL;
16922 }
16923 conn->request_info.local_uri = NULL;
16924
16925#if defined(USE_SERVER_STATS)
16926 conn->processing_time = 0;
16927#endif
16928}
16929
16930
16931static int
16932set_tcp_nodelay(const struct socket *so, int nodelay_on)
16933{
16934 if ((so->lsa.sa.sa_family == AF_INET)
16935 || (so->lsa.sa.sa_family == AF_INET6)) {
16936 /* Only for TCP sockets */
16937 if (setsockopt(so->sock,
16938 IPPROTO_TCP,
16939 TCP_NODELAY,
16940 (SOCK_OPT_TYPE)&nodelay_on,
16941 sizeof(nodelay_on))
16942 != 0) {
16943 /* Error */
16944 return 1;
16945 }
16946 }
16947 /* OK */
16948 return 0;
16949}
16950
16951
16952#if !defined(__ZEPHYR__)
16953static void
16955{
16956#if defined(_WIN32)
16957 char buf[MG_BUF_LEN];
16958 int n;
16959#endif
16960 struct linger linger;
16961 int error_code = 0;
16962 int linger_timeout = -2;
16963 socklen_t opt_len = sizeof(error_code);
16964
16965 if (!conn) {
16966 return;
16967 }
16968
16969 /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
16970 * "Note that enabling a nonzero timeout on a nonblocking socket
16971 * is not recommended.", so set it to blocking now */
16973
16974 /* Send FIN to the client */
16975 shutdown(conn->client.sock, SHUTDOWN_WR);
16976
16977
16978#if defined(_WIN32)
16979 /* Read and discard pending incoming data. If we do not do that and
16980 * close
16981 * the socket, the data in the send buffer may be discarded. This
16982 * behaviour is seen on Windows, when client keeps sending data
16983 * when server decides to close the connection; then when client
16984 * does recv() it gets no data back. */
16985 do {
16986 n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
16987 } while (n > 0);
16988#endif
16989
16990 if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
16991 linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
16992 }
16993
16994 /* Set linger option according to configuration */
16995 if (linger_timeout >= 0) {
16996 /* Set linger option to avoid socket hanging out after close. This
16997 * prevent ephemeral port exhaust problem under high QPS. */
16998 linger.l_onoff = 1;
16999
17000#if defined(_MSC_VER)
17001#pragma warning(push)
17002#pragma warning(disable : 4244)
17003#endif
17004#if defined(GCC_DIAGNOSTIC)
17005#pragma GCC diagnostic push
17006#pragma GCC diagnostic ignored "-Wconversion"
17007#endif
17008 /* Data type of linger structure elements may differ,
17009 * so we don't know what cast we need here.
17010 * Disable type conversion warnings. */
17011
17012 linger.l_linger = (linger_timeout + 999) / 1000;
17013
17014#if defined(GCC_DIAGNOSTIC)
17015#pragma GCC diagnostic pop
17016#endif
17017#if defined(_MSC_VER)
17018#pragma warning(pop)
17019#endif
17020
17021 } else {
17022 linger.l_onoff = 0;
17023 linger.l_linger = 0;
17024 }
17025
17026 if (linger_timeout < -1) {
17027 /* Default: don't configure any linger */
17028 } else if (getsockopt(conn->client.sock,
17029 SOL_SOCKET,
17030 SO_ERROR,
17031#if defined(_WIN32) /* WinSock uses different data type here */
17032 (char *)&error_code,
17033#else
17034 &error_code,
17035#endif
17036 &opt_len)
17037 != 0) {
17038 /* Cannot determine if socket is already closed. This should
17039 * not occur and never did in a test. Log an error message
17040 * and continue. */
17041 mg_cry_internal(conn,
17042 "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
17043 __func__,
17044 strerror(ERRNO));
17045#if defined(_WIN32)
17046 } else if (error_code == WSAECONNRESET) {
17047#else
17048 } else if (error_code == ECONNRESET) {
17049#endif
17050 /* Socket already closed by client/peer, close socket without linger
17051 */
17052 } else {
17053
17054 /* Set linger timeout */
17055 if (setsockopt(conn->client.sock,
17056 SOL_SOCKET,
17057 SO_LINGER,
17058 (char *)&linger,
17059 sizeof(linger))
17060 != 0) {
17062 conn,
17063 "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
17064 __func__,
17065 linger.l_onoff,
17066 linger.l_linger,
17067 strerror(ERRNO));
17068 }
17069 }
17070
17071 /* Now we know that our FIN is ACK-ed, safe to close */
17072 closesocket(conn->client.sock);
17073 conn->client.sock = INVALID_SOCKET;
17074}
17075#endif
17076
17077
17078static void
17080{
17081#if defined(USE_SERVER_STATS)
17082 conn->conn_state = 6; /* to close */
17083#endif
17084
17085#if defined(USE_LUA) && defined(USE_WEBSOCKET)
17086 if (conn->lua_websocket_state) {
17087 lua_websocket_close(conn, conn->lua_websocket_state);
17088 conn->lua_websocket_state = NULL;
17089 }
17090#endif
17091
17092 mg_lock_connection(conn);
17093
17094 /* Set close flag, so keep-alive loops will stop */
17095 conn->must_close = 1;
17096
17097 /* call the connection_close callback if assigned */
17098 if (conn->phys_ctx->callbacks.connection_close != NULL) {
17099 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17100 conn->phys_ctx->callbacks.connection_close(conn);
17101 }
17102 }
17103
17104 /* Reset user data, after close callback is called.
17105 * Do not reuse it. If the user needs a destructor,
17106 * it must be done in the connection_close callback. */
17107 mg_set_user_connection_data(conn, NULL);
17108
17109
17110#if defined(USE_SERVER_STATS)
17111 conn->conn_state = 7; /* closing */
17112#endif
17113
17114#if defined(USE_MBEDTLS)
17115 if (conn->ssl != NULL) {
17116 mbed_ssl_close(conn->ssl);
17117 conn->ssl = NULL;
17118 }
17119#elif !defined(NO_SSL)
17120 if (conn->ssl != NULL) {
17121 /* Run SSL_shutdown twice to ensure completely close SSL connection
17122 */
17123 SSL_shutdown(conn->ssl);
17124 SSL_free(conn->ssl);
17125 OPENSSL_REMOVE_THREAD_STATE();
17126 conn->ssl = NULL;
17127 }
17128#endif
17129 if (conn->client.sock != INVALID_SOCKET) {
17130#if defined(__ZEPHYR__)
17131 closesocket(conn->client.sock);
17132#else
17134#endif
17135 conn->client.sock = INVALID_SOCKET;
17136 }
17137
17138 /* call the connection_closed callback if assigned */
17139 if (conn->phys_ctx->callbacks.connection_closed != NULL) {
17140 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17142 }
17143 }
17144
17146
17147#if defined(USE_SERVER_STATS)
17148 conn->conn_state = 8; /* closed */
17149#endif
17150}
17151
17152
17153void
17155{
17156 if ((conn == NULL) || (conn->phys_ctx == NULL)) {
17157 return;
17158 }
17159
17160#if defined(USE_WEBSOCKET)
17161 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17162 if (conn->in_websocket_handling) {
17163 /* Set close flag, so the server thread can exit. */
17164 conn->must_close = 1;
17165 return;
17166 }
17167 }
17168 if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
17169
17170 unsigned int i;
17171
17172 /* client context: loops must end */
17174 conn->must_close = 1;
17175
17176 /* We need to get the client thread out of the select/recv call
17177 * here. */
17178 /* Since we use a sleep quantum of some seconds to check for recv
17179 * timeouts, we will just wait a few seconds in mg_join_thread. */
17180
17181 /* join worker thread */
17182 for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
17184 }
17185 }
17186#endif /* defined(USE_WEBSOCKET) */
17187
17188 close_connection(conn);
17189
17190#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17193 && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
17194 SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
17195 }
17196#endif
17197
17198#if defined(USE_WEBSOCKET)
17199 if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
17201 (void)pthread_mutex_destroy(&conn->mutex);
17202 mg_free(conn);
17203 } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
17204 (void)pthread_mutex_destroy(&conn->mutex);
17205 mg_free(conn);
17206 }
17207#else
17208 if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
17209 (void)pthread_mutex_destroy(&conn->mutex);
17210 mg_free(conn);
17211 }
17212#endif /* defined(USE_WEBSOCKET) */
17213}
17214
17215
17216static struct mg_connection *
17217mg_connect_client_impl(const struct mg_client_options *client_options,
17218 int use_ssl,
17219 char *ebuf,
17220 size_t ebuf_len)
17221{
17222 struct mg_connection *conn = NULL;
17223 SOCKET sock;
17224 union usa sa;
17225 struct sockaddr *psa;
17226 socklen_t len;
17227
17228 unsigned max_req_size =
17229 (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
17230
17231 /* Size of structures, aligned to 8 bytes */
17232 size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
17233 size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
17234
17235 conn =
17236 (struct mg_connection *)mg_calloc(1,
17237 conn_size + ctx_size + max_req_size);
17238
17239 if (conn == NULL) {
17240 mg_snprintf(NULL,
17241 NULL, /* No truncation check for ebuf */
17242 ebuf,
17243 ebuf_len,
17244 "calloc(): %s",
17245 strerror(ERRNO));
17246 return NULL;
17247 }
17248
17249#if defined(GCC_DIAGNOSTIC)
17250#pragma GCC diagnostic push
17251#pragma GCC diagnostic ignored "-Wcast-align"
17252#endif /* defined(GCC_DIAGNOSTIC) */
17253 /* conn_size is aligned to 8 bytes */
17254
17255 conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
17256
17257#if defined(GCC_DIAGNOSTIC)
17258#pragma GCC diagnostic pop
17259#endif /* defined(GCC_DIAGNOSTIC) */
17260
17261 conn->buf = (((char *)conn) + conn_size + ctx_size);
17262 conn->buf_size = (int)max_req_size;
17264 conn->dom_ctx = &(conn->phys_ctx->dd);
17265
17266 if (!connect_socket(conn->phys_ctx,
17267 client_options->host,
17268 client_options->port,
17269 use_ssl,
17270 ebuf,
17271 ebuf_len,
17272 &sock,
17273 &sa)) {
17274 /* ebuf is set by connect_socket,
17275 * free all memory and return NULL; */
17276 mg_free(conn);
17277 return NULL;
17278 }
17279
17280#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17281#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
17282 && !defined(NO_SSL_DL)
17283 if (use_ssl
17284 && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
17285 == NULL) {
17286 mg_snprintf(NULL,
17287 NULL, /* No truncation check for ebuf */
17288 ebuf,
17289 ebuf_len,
17290 "SSL_CTX_new error: %s",
17291 ssl_error());
17292 closesocket(sock);
17293 mg_free(conn);
17294 return NULL;
17295 }
17296#else
17297 if (use_ssl
17298 && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
17299 == NULL) {
17300 mg_snprintf(NULL,
17301 NULL, /* No truncation check for ebuf */
17302 ebuf,
17303 ebuf_len,
17304 "SSL_CTX_new error: %s",
17305 ssl_error());
17306 closesocket(sock);
17307 mg_free(conn);
17308 return NULL;
17309 }
17310#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
17311#endif /* NO_SSL */
17312
17313
17314#if defined(USE_IPV6)
17315 len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
17316 : sizeof(conn->client.rsa.sin6);
17317 psa = (sa.sa.sa_family == AF_INET)
17318 ? (struct sockaddr *)&(conn->client.rsa.sin)
17319 : (struct sockaddr *)&(conn->client.rsa.sin6);
17320#else
17321 len = sizeof(conn->client.rsa.sin);
17322 psa = (struct sockaddr *)&(conn->client.rsa.sin);
17323#endif
17324
17325 conn->client.sock = sock;
17326 conn->client.lsa = sa;
17327
17328 if (getsockname(sock, psa, &len) != 0) {
17329 mg_cry_internal(conn,
17330 "%s: getsockname() failed: %s",
17331 __func__,
17332 strerror(ERRNO));
17333 }
17334
17335 conn->client.is_ssl = use_ssl ? 1 : 0;
17336 if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
17337 mg_snprintf(NULL,
17338 NULL, /* No truncation check for ebuf */
17339 ebuf,
17340 ebuf_len,
17341 "Can not create mutex");
17342#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17343 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17344#endif
17345 closesocket(sock);
17346 mg_free(conn);
17347 return NULL;
17348 }
17349
17350
17351#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17352 if (use_ssl) {
17353 /* TODO: Check ssl_verify_peer and ssl_ca_path here.
17354 * SSL_CTX_set_verify call is needed to switch off server
17355 * certificate checking, which is off by default in OpenSSL and
17356 * on in yaSSL. */
17357 /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
17358 * SSL_VERIFY_PEER, verify_ssl_server); */
17359
17360 if (client_options->client_cert) {
17361 if (!ssl_use_pem_file(conn->phys_ctx,
17362 conn->dom_ctx,
17363 client_options->client_cert,
17364 NULL)) {
17365 mg_snprintf(NULL,
17366 NULL, /* No truncation check for ebuf */
17367 ebuf,
17368 ebuf_len,
17369 "Can not use SSL client certificate");
17370 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17371 closesocket(sock);
17372 mg_free(conn);
17373 return NULL;
17374 }
17375 }
17376
17377 if (client_options->server_cert) {
17378 if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
17379 client_options->server_cert,
17380 NULL)
17381 != 1) {
17382 mg_cry_internal(conn,
17383 "SSL_CTX_load_verify_locations error: %s ",
17384 ssl_error());
17385 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17386 closesocket(sock);
17387 mg_free(conn);
17388 return NULL;
17389 }
17390 SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
17391 } else {
17392 SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
17393 }
17394
17395 if (!sslize(conn, SSL_connect, client_options)) {
17396 mg_snprintf(NULL,
17397 NULL, /* No truncation check for ebuf */
17398 ebuf,
17399 ebuf_len,
17400 "SSL connection error");
17401 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17402 closesocket(sock);
17403 mg_free(conn);
17404 return NULL;
17405 }
17406 }
17407#endif
17408
17409 return conn;
17410}
17411
17412
17414mg_connect_client_secure(const struct mg_client_options *client_options,
17415 char *error_buffer,
17416 size_t error_buffer_size)
17417{
17418 return mg_connect_client_impl(client_options,
17419 1,
17420 error_buffer,
17421 error_buffer_size);
17422}
17423
17424
17425struct mg_connection *
17426mg_connect_client(const char *host,
17427 int port,
17428 int use_ssl,
17429 char *error_buffer,
17430 size_t error_buffer_size)
17431{
17432 struct mg_client_options opts;
17433 memset(&opts, 0, sizeof(opts));
17434 opts.host = host;
17435 opts.port = port;
17436 return mg_connect_client_impl(&opts,
17437 use_ssl,
17438 error_buffer,
17439 error_buffer_size);
17440}
17441
17442
17443#if defined(MG_EXPERIMENTAL_INTERFACES)
17444struct mg_connection *
17445mg_connect_client2(const char *host,
17446 const char *protocol,
17447 int port,
17448 const char *path,
17449 struct mg_init_data *init,
17450 struct mg_error_data *error)
17451{
17452 int is_ssl, is_ws;
17453 /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
17454
17455 if (error != NULL) {
17456 error->code = 0;
17457 if (error->text_buffer_size > 0) {
17458 *error->text = 0;
17459 }
17460 }
17461
17462 if ((host == NULL) || (protocol == NULL)) {
17463 if ((error != NULL) && (error->text_buffer_size > 0)) {
17464 mg_snprintf(NULL,
17465 NULL, /* No truncation check for error buffers */
17466 error->text,
17467 error->text_buffer_size,
17468 "%s",
17469 "Invalid parameters");
17470 }
17471 return NULL;
17472 }
17473
17474 /* check all known protocolls */
17475 if (!mg_strcasecmp(protocol, "http")) {
17476 is_ssl = 0;
17477 is_ws = 0;
17478 } else if (!mg_strcasecmp(protocol, "https")) {
17479 is_ssl = 1;
17480 is_ws = 0;
17481#if defined(USE_WEBSOCKET)
17482 } else if (!mg_strcasecmp(protocol, "ws")) {
17483 is_ssl = 0;
17484 is_ws = 1;
17485 } else if (!mg_strcasecmp(protocol, "wss")) {
17486 is_ssl = 1;
17487 is_ws = 1;
17488#endif
17489 } else {
17490 if ((error != NULL) && (error->text_buffer_size > 0)) {
17491 mg_snprintf(NULL,
17492 NULL, /* No truncation check for error buffers */
17493 error->text,
17494 error->text_buffer_size,
17495 "Protocol %s not supported",
17496 protocol);
17497 }
17498 return NULL;
17499 }
17500
17501 /* TODO: The current implementation here just calls the old
17502 * implementations, without using any new options. This is just a first
17503 * step to test the new interfaces. */
17504#if defined(USE_WEBSOCKET)
17505 if (is_ws) {
17506 /* TODO: implement all options */
17508 host,
17509 port,
17510 is_ssl,
17511 ((error != NULL) ? error->text : NULL),
17512 ((error != NULL) ? error->text_buffer_size : 0),
17513 (path ? path : ""),
17514 NULL /* TODO: origin */,
17515 experimental_websocket_client_data_wrapper,
17516 experimental_websocket_client_close_wrapper,
17517 (void *)init->callbacks);
17518 }
17519#endif
17520
17521 /* TODO: all additional options */
17522 struct mg_client_options opts;
17523 memset(&opts, 0, sizeof(opts));
17524 opts.host = host;
17525 opts.port = port;
17526 return mg_connect_client_impl(&opts,
17527 is_ssl,
17528 ((error != NULL) ? error->text : NULL),
17529 ((error != NULL) ? error->text_buffer_size
17530 : 0));
17531}
17532#endif
17533
17534
17535static const struct {
17536 const char *proto;
17539} abs_uri_protocols[] = {{"http://", 7, 80},
17540 {"https://", 8, 443},
17541 {"ws://", 5, 80},
17542 {"wss://", 6, 443},
17543 {NULL, 0, 0}};
17544
17545
17546/* Check if the uri is valid.
17547 * return 0 for invalid uri,
17548 * return 1 for *,
17549 * return 2 for relative uri,
17550 * return 3 for absolute uri without port,
17551 * return 4 for absolute uri with port */
17552static int
17553get_uri_type(const char *uri)
17554{
17555 int i;
17556 const char *hostend, *portbegin;
17557 char *portend;
17558 unsigned long port;
17559
17560 /* According to the HTTP standard
17561 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
17562 * URI can be an asterisk (*) or should start with slash (relative uri),
17563 * or it should start with the protocol (absolute uri). */
17564 if ((uri[0] == '*') && (uri[1] == '\0')) {
17565 /* asterisk */
17566 return 1;
17567 }
17568
17569 /* Valid URIs according to RFC 3986
17570 * (https://www.ietf.org/rfc/rfc3986.txt)
17571 * must only contain reserved characters :/?#[]@!$&'()*+,;=
17572 * and unreserved characters A-Z a-z 0-9 and -._~
17573 * and % encoded symbols.
17574 */
17575 for (i = 0; uri[i] != 0; i++) {
17576 if (uri[i] < 33) {
17577 /* control characters and spaces are invalid */
17578 return 0;
17579 }
17580 /* Allow everything else here (See #894) */
17581 }
17582
17583 /* A relative uri starts with a / character */
17584 if (uri[0] == '/') {
17585 /* relative uri */
17586 return 2;
17587 }
17588
17589 /* It could be an absolute uri: */
17590 /* This function only checks if the uri is valid, not if it is
17591 * addressing the current server. So civetweb can also be used
17592 * as a proxy server. */
17593 for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
17594 if (mg_strncasecmp(uri,
17597 == 0) {
17598
17599 hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
17600 if (!hostend) {
17601 return 0;
17602 }
17603 portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
17604 if (!portbegin) {
17605 return 3;
17606 }
17607
17608 port = strtoul(portbegin + 1, &portend, 10);
17609 if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
17610 return 0;
17611 }
17612
17613 return 4;
17614 }
17615 }
17616
17617 return 0;
17618}
17619
17620
17621/* Return NULL or the relative uri at the current server */
17622static const char *
17623get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
17624{
17625 const char *server_domain;
17626 size_t server_domain_len;
17627 size_t request_domain_len = 0;
17628 unsigned long port = 0;
17629 int i, auth_domain_check_enabled;
17630 const char *hostbegin = NULL;
17631 const char *hostend = NULL;
17632 const char *portbegin;
17633 char *portend;
17634
17635 auth_domain_check_enabled =
17637
17638 /* DNS is case insensitive, so use case insensitive string compare here
17639 */
17640 for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
17641 if (mg_strncasecmp(uri,
17644 == 0) {
17645
17646 hostbegin = uri + abs_uri_protocols[i].proto_len;
17647 hostend = strchr(hostbegin, '/');
17648 if (!hostend) {
17649 return 0;
17650 }
17651 portbegin = strchr(hostbegin, ':');
17652 if ((!portbegin) || (portbegin > hostend)) {
17653 port = abs_uri_protocols[i].default_port;
17654 request_domain_len = (size_t)(hostend - hostbegin);
17655 } else {
17656 port = strtoul(portbegin + 1, &portend, 10);
17657 if ((portend != hostend) || (port <= 0)
17658 || !is_valid_port(port)) {
17659 return 0;
17660 }
17661 request_domain_len = (size_t)(portbegin - hostbegin);
17662 }
17663 /* protocol found, port set */
17664 break;
17665 }
17666 }
17667
17668 if (!port) {
17669 /* port remains 0 if the protocol is not found */
17670 return 0;
17671 }
17672
17673 /* Check if the request is directed to a different server. */
17674 /* First check if the port is the same. */
17675 if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
17676 /* Request is directed to a different port */
17677 return 0;
17678 }
17679
17680 /* Finally check if the server corresponds to the authentication
17681 * domain of the server (the server domain).
17682 * Allow full matches (like http://mydomain.com/path/file.ext), and
17683 * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
17684 * but do not allow substrings (like
17685 * http://notmydomain.com/path/file.ext
17686 * or http://mydomain.com.fake/path/file.ext).
17687 */
17688 if (auth_domain_check_enabled) {
17689 server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
17690 server_domain_len = strlen(server_domain);
17691 if ((server_domain_len == 0) || (hostbegin == NULL)) {
17692 return 0;
17693 }
17694 if ((request_domain_len == server_domain_len)
17695 && (!memcmp(server_domain, hostbegin, server_domain_len))) {
17696 /* Request is directed to this server - full name match. */
17697 } else {
17698 if (request_domain_len < (server_domain_len + 2)) {
17699 /* Request is directed to another server: The server name
17700 * is longer than the request name.
17701 * Drop this case here to avoid overflows in the
17702 * following checks. */
17703 return 0;
17704 }
17705 if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
17706 /* Request is directed to another server: It could be a
17707 * substring
17708 * like notmyserver.com */
17709 return 0;
17710 }
17711 if (0
17712 != memcmp(server_domain,
17713 hostbegin + request_domain_len - server_domain_len,
17714 server_domain_len)) {
17715 /* Request is directed to another server:
17716 * The server name is different. */
17717 return 0;
17718 }
17719 }
17720 }
17721
17722 return hostend;
17723}
17724
17725
17726static int
17727get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17728{
17729 if (ebuf_len > 0) {
17730 ebuf[0] = '\0';
17731 }
17732 *err = 0;
17733
17735
17736 if (!conn) {
17737 mg_snprintf(conn,
17738 NULL, /* No truncation check for ebuf */
17739 ebuf,
17740 ebuf_len,
17741 "%s",
17742 "Internal error");
17743 *err = 500;
17744 return 0;
17745 }
17746
17747 /* Set the time the request was received. This value should be used for
17748 * timeouts. */
17749 clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
17750
17751 conn->request_len =
17752 read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
17753 DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
17754 if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
17755 mg_snprintf(conn,
17756 NULL, /* No truncation check for ebuf */
17757 ebuf,
17758 ebuf_len,
17759 "%s",
17760 "Invalid message size");
17761 *err = 500;
17762 return 0;
17763 }
17764
17765 if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
17766 mg_snprintf(conn,
17767 NULL, /* No truncation check for ebuf */
17768 ebuf,
17769 ebuf_len,
17770 "%s",
17771 "Message too large");
17772 *err = 413;
17773 return 0;
17774 }
17775
17776 if (conn->request_len <= 0) {
17777 if (conn->data_len > 0) {
17778 mg_snprintf(conn,
17779 NULL, /* No truncation check for ebuf */
17780 ebuf,
17781 ebuf_len,
17782 "%s",
17783 "Malformed message");
17784 *err = 400;
17785 } else {
17786 /* Server did not recv anything -> just close the connection */
17787 conn->must_close = 1;
17788 mg_snprintf(conn,
17789 NULL, /* No truncation check for ebuf */
17790 ebuf,
17791 ebuf_len,
17792 "%s",
17793 "No data received");
17794 *err = 0;
17795 }
17796 return 0;
17797 }
17798 return 1;
17799}
17800
17801
17802static int
17803get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17804{
17805 const char *cl;
17806
17807 conn->connection_type =
17808 CONNECTION_TYPE_REQUEST; /* request (valid of not) */
17809
17810 if (!get_message(conn, ebuf, ebuf_len, err)) {
17811 return 0;
17812 }
17813
17814 if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
17815 <= 0) {
17816 mg_snprintf(conn,
17817 NULL, /* No truncation check for ebuf */
17818 ebuf,
17819 ebuf_len,
17820 "%s",
17821 "Bad request");
17822 *err = 400;
17823 return 0;
17824 }
17825
17826 /* Message is a valid request */
17827
17828 if (!switch_domain_context(conn)) {
17829 mg_snprintf(conn,
17830 NULL, /* No truncation check for ebuf */
17831 ebuf,
17832 ebuf_len,
17833 "%s",
17834 "Bad request: Host mismatch");
17835 *err = 400;
17836 return 0;
17837 }
17838
17839#if USE_ZLIB
17840 if (((cl = get_header(conn->request_info.http_headers,
17842 "Accept-Encoding"))
17843 != NULL)
17844 && strstr(cl, "gzip")) {
17845 conn->accept_gzip = 1;
17846 }
17847#endif
17848 if (((cl = get_header(conn->request_info.http_headers,
17850 "Transfer-Encoding"))
17851 != NULL)
17852 && mg_strcasecmp(cl, "identity")) {
17853 if (mg_strcasecmp(cl, "chunked")) {
17854 mg_snprintf(conn,
17855 NULL, /* No truncation check for ebuf */
17856 ebuf,
17857 ebuf_len,
17858 "%s",
17859 "Bad request");
17860 *err = 400;
17861 return 0;
17862 }
17863 conn->is_chunked = 1;
17864 conn->content_len = 0; /* not yet read */
17865 } else if ((cl = get_header(conn->request_info.http_headers,
17867 "Content-Length"))
17868 != NULL) {
17869 /* Request has content length set */
17870 char *endptr = NULL;
17871 conn->content_len = strtoll(cl, &endptr, 10);
17872 if ((endptr == cl) || (conn->content_len < 0)) {
17873 mg_snprintf(conn,
17874 NULL, /* No truncation check for ebuf */
17875 ebuf,
17876 ebuf_len,
17877 "%s",
17878 "Bad request");
17879 *err = 411;
17880 return 0;
17881 }
17882 /* Publish the content length back to the request info. */
17884 } else {
17885 /* There is no exception, see RFC7230. */
17886 conn->content_len = 0;
17887 }
17888
17889 return 1;
17890}
17891
17892
17893/* conn is assumed to be valid in this internal function */
17894static int
17895get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17896{
17897 const char *cl;
17898
17899 conn->connection_type =
17900 CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
17901
17902 if (!get_message(conn, ebuf, ebuf_len, err)) {
17903 return 0;
17904 }
17905
17906 if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
17907 <= 0) {
17908 mg_snprintf(conn,
17909 NULL, /* No truncation check for ebuf */
17910 ebuf,
17911 ebuf_len,
17912 "%s",
17913 "Bad response");
17914 *err = 400;
17915 return 0;
17916 }
17917
17918 /* Message is a valid response */
17919
17920 if (((cl = get_header(conn->response_info.http_headers,
17922 "Transfer-Encoding"))
17923 != NULL)
17924 && mg_strcasecmp(cl, "identity")) {
17925 if (mg_strcasecmp(cl, "chunked")) {
17926 mg_snprintf(conn,
17927 NULL, /* No truncation check for ebuf */
17928 ebuf,
17929 ebuf_len,
17930 "%s",
17931 "Bad request");
17932 *err = 400;
17933 return 0;
17934 }
17935 conn->is_chunked = 1;
17936 conn->content_len = 0; /* not yet read */
17937 } else if ((cl = get_header(conn->response_info.http_headers,
17939 "Content-Length"))
17940 != NULL) {
17941 char *endptr = NULL;
17942 conn->content_len = strtoll(cl, &endptr, 10);
17943 if ((endptr == cl) || (conn->content_len < 0)) {
17944 mg_snprintf(conn,
17945 NULL, /* No truncation check for ebuf */
17946 ebuf,
17947 ebuf_len,
17948 "%s",
17949 "Bad request");
17950 *err = 411;
17951 return 0;
17952 }
17953 /* Publish the content length back to the response info. */
17955
17956 /* TODO: check if it is still used in response_info */
17958
17959 /* TODO: we should also consider HEAD method */
17960 if (conn->response_info.status_code == 304) {
17961 conn->content_len = 0;
17962 }
17963 } else {
17964 /* TODO: we should also consider HEAD method */
17965 if (((conn->response_info.status_code >= 100)
17966 && (conn->response_info.status_code <= 199))
17967 || (conn->response_info.status_code == 204)
17968 || (conn->response_info.status_code == 304)) {
17969 conn->content_len = 0;
17970 } else {
17971 conn->content_len = -1; /* unknown content length */
17972 }
17973 }
17974
17975 return 1;
17976}
17977
17978
17979int
17981 char *ebuf,
17982 size_t ebuf_len,
17983 int timeout)
17984{
17985 int err, ret;
17986 char txt[32]; /* will not overflow */
17987 char *save_timeout;
17988 char *new_timeout;
17989
17990 if (ebuf_len > 0) {
17991 ebuf[0] = '\0';
17992 }
17993
17994 if (!conn) {
17995 mg_snprintf(conn,
17996 NULL, /* No truncation check for ebuf */
17997 ebuf,
17998 ebuf_len,
17999 "%s",
18000 "Parameter error");
18001 return -1;
18002 }
18003
18004 /* Reset the previous responses */
18005 conn->data_len = 0;
18006
18007 /* Implementation of API function for HTTP clients */
18008 save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
18009
18010 if (timeout >= 0) {
18011 mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
18012 new_timeout = txt;
18013 } else {
18014 new_timeout = NULL;
18015 }
18016
18017 conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
18018 ret = get_response(conn, ebuf, ebuf_len, &err);
18019 conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
18020
18021 /* TODO: here, the URI is the http response code */
18024
18025 /* TODO (mid): Define proper return values - maybe return length?
18026 * For the first test use <0 for error and >0 for OK */
18027 return (ret == 0) ? -1 : +1;
18028}
18029
18030
18031struct mg_connection *
18032mg_download(const char *host,
18033 int port,
18034 int use_ssl,
18035 char *ebuf,
18036 size_t ebuf_len,
18037 const char *fmt,
18038 ...)
18039{
18040 struct mg_connection *conn;
18041 va_list ap;
18042 int i;
18043 int reqerr;
18044
18045 if (ebuf_len > 0) {
18046 ebuf[0] = '\0';
18047 }
18048
18049 va_start(ap, fmt);
18050
18051 /* open a connection */
18052 conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
18053
18054 if (conn != NULL) {
18055 i = mg_vprintf(conn, fmt, ap);
18056 if (i <= 0) {
18057 mg_snprintf(conn,
18058 NULL, /* No truncation check for ebuf */
18059 ebuf,
18060 ebuf_len,
18061 "%s",
18062 "Error sending request");
18063 } else {
18064 /* make sure the buffer is clear */
18065 conn->data_len = 0;
18066 get_response(conn, ebuf, ebuf_len, &reqerr);
18067
18068 /* TODO: here, the URI is the http response code */
18070 }
18071 }
18072
18073 /* if an error occurred, close the connection */
18074 if ((ebuf[0] != '\0') && (conn != NULL)) {
18075 mg_close_connection(conn);
18076 conn = NULL;
18077 }
18078
18079 va_end(ap);
18080 return conn;
18081}
18082
18083
18089};
18090
18091
18092#if defined(USE_WEBSOCKET)
18093#if defined(_WIN32)
18094static unsigned __stdcall websocket_client_thread(void *data)
18095#else
18096static void *
18097websocket_client_thread(void *data)
18098#endif
18099{
18100 struct websocket_client_thread_data *cdata =
18102
18103 void *user_thread_ptr = NULL;
18104
18105#if !defined(_WIN32) && !defined(__ZEPHYR__)
18106 struct sigaction sa;
18107
18108 /* Ignore SIGPIPE */
18109 memset(&sa, 0, sizeof(sa));
18110 sa.sa_handler = SIG_IGN;
18111 sigaction(SIGPIPE, &sa, NULL);
18112#endif
18113
18114 mg_set_thread_name("ws-clnt");
18115
18116 if (cdata->conn->phys_ctx) {
18117 if (cdata->conn->phys_ctx->callbacks.init_thread) {
18118 /* 3 indicates a websocket client thread */
18119 /* TODO: check if conn->phys_ctx can be set */
18120 user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
18121 cdata->conn->phys_ctx, 3);
18122 }
18123 }
18124
18125 read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
18126
18127 DEBUG_TRACE("%s", "Websocket client thread exited\n");
18128
18129 if (cdata->close_handler != NULL) {
18130 cdata->close_handler(cdata->conn, cdata->callback_data);
18131 }
18132
18133 /* The websocket_client context has only this thread. If it runs out,
18134 set the stop_flag to 2 (= "stopped"). */
18136
18137 if (cdata->conn->phys_ctx->callbacks.exit_thread) {
18139 3,
18140 user_thread_ptr);
18141 }
18142
18143 mg_free((void *)cdata);
18144
18145#if defined(_WIN32)
18146 return 0;
18147#else
18148 return NULL;
18149#endif
18150}
18151#endif
18152
18153
18154static struct mg_connection *
18156 int use_ssl,
18157 char *error_buffer,
18158 size_t error_buffer_size,
18159 const char *path,
18160 const char *origin,
18161 const char *extensions,
18162 mg_websocket_data_handler data_func,
18163 mg_websocket_close_handler close_func,
18164 void *user_data)
18165{
18166 struct mg_connection *conn = NULL;
18167
18168#if defined(USE_WEBSOCKET)
18169 struct websocket_client_thread_data *thread_data;
18170 static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
18171
18172 const char *host = client_options->host;
18173 int i;
18174
18175#if defined(__clang__)
18176#pragma clang diagnostic push
18177#pragma clang diagnostic ignored "-Wformat-nonliteral"
18178#endif
18179
18180 /* Establish the client connection and request upgrade */
18181 conn = mg_connect_client_impl(client_options,
18182 use_ssl,
18183 error_buffer,
18184 error_buffer_size);
18185
18186 /* Connection object will be null if something goes wrong */
18187 if (conn == NULL) {
18188 /* error_buffer should be already filled ... */
18189 if (!error_buffer[0]) {
18190 /* ... if not add an error message */
18192 NULL, /* No truncation check for ebuf */
18193 error_buffer,
18194 error_buffer_size,
18195 "Unexpected error");
18196 }
18197 return NULL;
18198 }
18199
18200 if (origin != NULL) {
18201 if (extensions != NULL) {
18202 i = mg_printf(conn,
18203 "GET %s HTTP/1.1\r\n"
18204 "Host: %s\r\n"
18205 "Upgrade: websocket\r\n"
18206 "Connection: Upgrade\r\n"
18207 "Sec-WebSocket-Key: %s\r\n"
18208 "Sec-WebSocket-Version: 13\r\n"
18209 "Sec-WebSocket-Extensions: %s\r\n"
18210 "Origin: %s\r\n"
18211 "\r\n",
18212 path,
18213 host,
18214 magic,
18215 extensions,
18216 origin);
18217 } else {
18218 i = mg_printf(conn,
18219 "GET %s HTTP/1.1\r\n"
18220 "Host: %s\r\n"
18221 "Upgrade: websocket\r\n"
18222 "Connection: Upgrade\r\n"
18223 "Sec-WebSocket-Key: %s\r\n"
18224 "Sec-WebSocket-Version: 13\r\n"
18225 "Origin: %s\r\n"
18226 "\r\n",
18227 path,
18228 host,
18229 magic,
18230 origin);
18231 }
18232 } else {
18233
18234 if (extensions != NULL) {
18235 i = mg_printf(conn,
18236 "GET %s HTTP/1.1\r\n"
18237 "Host: %s\r\n"
18238 "Upgrade: websocket\r\n"
18239 "Connection: Upgrade\r\n"
18240 "Sec-WebSocket-Key: %s\r\n"
18241 "Sec-WebSocket-Version: 13\r\n"
18242 "Sec-WebSocket-Extensions: %s\r\n"
18243 "\r\n",
18244 path,
18245 host,
18246 magic,
18247 extensions);
18248 } else {
18249 i = mg_printf(conn,
18250 "GET %s HTTP/1.1\r\n"
18251 "Host: %s\r\n"
18252 "Upgrade: websocket\r\n"
18253 "Connection: Upgrade\r\n"
18254 "Sec-WebSocket-Key: %s\r\n"
18255 "Sec-WebSocket-Version: 13\r\n"
18256 "\r\n",
18257 path,
18258 host,
18259 magic);
18260 }
18261 }
18262 if (i <= 0) {
18264 NULL, /* No truncation check for ebuf */
18265 error_buffer,
18266 error_buffer_size,
18267 "%s",
18268 "Error sending request");
18270 return NULL;
18271 }
18272
18273 conn->data_len = 0;
18274 if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
18276 return NULL;
18277 }
18280
18281#if defined(__clang__)
18282#pragma clang diagnostic pop
18283#endif
18284
18285 if (conn->response_info.status_code != 101) {
18286 /* We sent an "upgrade" request. For a correct websocket
18287 * protocol handshake, we expect a "101 Continue" response.
18288 * Otherwise it is a protocol violation. Maybe the HTTP
18289 * Server does not know websockets. */
18290 if (!*error_buffer) {
18291 /* set an error, if not yet set */
18293 NULL, /* No truncation check for ebuf */
18294 error_buffer,
18295 error_buffer_size,
18296 "Unexpected server reply");
18297 }
18298
18299 DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
18301 return NULL;
18302 }
18303
18304 thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
18305 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
18306 if (!thread_data) {
18307 DEBUG_TRACE("%s\r\n", "Out of memory");
18309 return NULL;
18310 }
18311
18312 thread_data->conn = conn;
18313 thread_data->data_handler = data_func;
18314 thread_data->close_handler = close_func;
18315 thread_data->callback_data = user_data;
18316
18318 (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
18320 DEBUG_TRACE("%s\r\n", "Out of memory");
18321 mg_free(thread_data);
18323 return NULL;
18324 }
18325
18326 /* Now upgrade to ws/wss client context */
18327 conn->phys_ctx->user_data = user_data;
18329 conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
18330
18331 /* Start a thread to read the websocket client connection
18332 * This thread will automatically stop when mg_disconnect is
18333 * called on the client connection */
18334 if (mg_start_thread_with_id(websocket_client_thread,
18335 thread_data,
18337 != 0) {
18339 mg_free(thread_data);
18341 conn = NULL;
18342 DEBUG_TRACE("%s",
18343 "Websocket client connect thread could not be started\r\n");
18344 }
18345
18346#else
18347 /* Appease "unused parameter" warnings */
18348 (void)client_options;
18349 (void)use_ssl;
18350 (void)error_buffer;
18351 (void)error_buffer_size;
18352 (void)path;
18353 (void)origin;
18354 (void)extensions;
18355 (void)user_data;
18356 (void)data_func;
18357 (void)close_func;
18358#endif
18359
18360 return conn;
18361}
18362
18363
18364struct mg_connection *
18366 int port,
18367 int use_ssl,
18368 char *error_buffer,
18369 size_t error_buffer_size,
18370 const char *path,
18371 const char *origin,
18372 mg_websocket_data_handler data_func,
18373 mg_websocket_close_handler close_func,
18374 void *user_data)
18375{
18376 struct mg_client_options client_options;
18377 memset(&client_options, 0, sizeof(client_options));
18378 client_options.host = host;
18379 client_options.port = port;
18380
18381 return mg_connect_websocket_client_impl(&client_options,
18382 use_ssl,
18383 error_buffer,
18384 error_buffer_size,
18385 path,
18386 origin,
18387 NULL,
18388 data_func,
18389 close_func,
18390 user_data);
18391}
18392
18393
18394struct mg_connection *
18396 const struct mg_client_options *client_options,
18397 char *error_buffer,
18398 size_t error_buffer_size,
18399 const char *path,
18400 const char *origin,
18401 mg_websocket_data_handler data_func,
18402 mg_websocket_close_handler close_func,
18403 void *user_data)
18404{
18405 if (!client_options) {
18406 return NULL;
18407 }
18408 return mg_connect_websocket_client_impl(client_options,
18409 1,
18410 error_buffer,
18411 error_buffer_size,
18412 path,
18413 origin,
18414 NULL,
18415 data_func,
18416 close_func,
18417 user_data);
18418}
18419
18420struct mg_connection *
18422 int port,
18423 int use_ssl,
18424 char *error_buffer,
18425 size_t error_buffer_size,
18426 const char *path,
18427 const char *origin,
18428 const char *extensions,
18429 mg_websocket_data_handler data_func,
18430 mg_websocket_close_handler close_func,
18431 void *user_data)
18432{
18433 struct mg_client_options client_options;
18434 memset(&client_options, 0, sizeof(client_options));
18435 client_options.host = host;
18436 client_options.port = port;
18437
18438 return mg_connect_websocket_client_impl(&client_options,
18439 use_ssl,
18440 error_buffer,
18441 error_buffer_size,
18442 path,
18443 origin,
18444 extensions,
18445 data_func,
18446 close_func,
18447 user_data);
18448}
18449
18450struct mg_connection *
18452 const struct mg_client_options *client_options,
18453 char *error_buffer,
18454 size_t error_buffer_size,
18455 const char *path,
18456 const char *origin,
18457 const char *extensions,
18458 mg_websocket_data_handler data_func,
18459 mg_websocket_close_handler close_func,
18460 void *user_data)
18461{
18462 if (!client_options) {
18463 return NULL;
18464 }
18465 return mg_connect_websocket_client_impl(client_options,
18466 1,
18467 error_buffer,
18468 error_buffer_size,
18469 path,
18470 origin,
18471 extensions,
18472 data_func,
18473 close_func,
18474 user_data);
18475}
18476
18477/* Prepare connection data structure */
18478static void
18480{
18481 /* Is keep alive allowed by the server */
18482 int keep_alive_enabled =
18484
18485 if (!keep_alive_enabled) {
18486 conn->must_close = 1;
18487 }
18488
18489 /* Important: on new connection, reset the receiving buffer. Credit
18490 * goes to crule42. */
18491 conn->data_len = 0;
18492 conn->handled_requests = 0;
18494 mg_set_user_connection_data(conn, NULL);
18495
18496#if defined(USE_SERVER_STATS)
18497 conn->conn_state = 2; /* init */
18498#endif
18499
18500 /* call the init_connection callback if assigned */
18501 if (conn->phys_ctx->callbacks.init_connection != NULL) {
18502 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
18503 void *conn_data = NULL;
18504 conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
18505 mg_set_user_connection_data(conn, conn_data);
18506 }
18507 }
18508}
18509
18510
18511/* Process a connection - may handle multiple requests
18512 * using the same connection.
18513 * Must be called with a valid connection (conn and
18514 * conn->phys_ctx must be valid).
18515 */
18516static void
18518{
18519 struct mg_request_info *ri = &conn->request_info;
18520 int keep_alive, discard_len;
18521 char ebuf[100];
18522 const char *hostend;
18523 int reqerr, uri_type;
18524
18525#if defined(USE_SERVER_STATS)
18526 ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
18527 mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
18528 mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
18529#endif
18530
18531 DEBUG_TRACE("Start processing connection from %s",
18533
18534 /* Loop over multiple requests sent using the same connection
18535 * (while "keep alive"). */
18536 do {
18537 DEBUG_TRACE("calling get_request (%i times for this connection)",
18538 conn->handled_requests + 1);
18539
18540#if defined(USE_SERVER_STATS)
18541 conn->conn_state = 3; /* ready */
18542#endif
18543
18544 if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
18545 /* The request sent by the client could not be understood by
18546 * the server, or it was incomplete or a timeout. Send an
18547 * error message and close the connection. */
18548 if (reqerr > 0) {
18549 DEBUG_ASSERT(ebuf[0] != '\0');
18550 mg_send_http_error(conn, reqerr, "%s", ebuf);
18551 }
18552
18553 } else if (strcmp(ri->http_version, "1.0")
18554 && strcmp(ri->http_version, "1.1")) {
18555 /* HTTP/2 is not allowed here */
18556 mg_snprintf(conn,
18557 NULL, /* No truncation check for ebuf */
18558 ebuf,
18559 sizeof(ebuf),
18560 "Bad HTTP version: [%s]",
18561 ri->http_version);
18562 mg_send_http_error(conn, 505, "%s", ebuf);
18563 }
18564
18565 if (ebuf[0] == '\0') {
18566 uri_type = get_uri_type(conn->request_info.request_uri);
18567 switch (uri_type) {
18568 case 1:
18569 /* Asterisk */
18570 conn->request_info.local_uri_raw = 0;
18571 /* TODO: Deal with '*'. */
18572 break;
18573 case 2:
18574 /* relative uri */
18577 break;
18578 case 3:
18579 case 4:
18580 /* absolute uri (with/without port) */
18582 conn->request_info.request_uri, conn);
18583 if (hostend) {
18584 conn->request_info.local_uri_raw = hostend;
18585 } else {
18586 conn->request_info.local_uri_raw = NULL;
18587 }
18588 break;
18589 default:
18590 mg_snprintf(conn,
18591 NULL, /* No truncation check for ebuf */
18592 ebuf,
18593 sizeof(ebuf),
18594 "Invalid URI");
18595 mg_send_http_error(conn, 400, "%s", ebuf);
18596 conn->request_info.local_uri_raw = NULL;
18597 break;
18598 }
18599 conn->request_info.local_uri =
18600 (char *)conn->request_info.local_uri_raw;
18601 }
18602
18603 if (ebuf[0] != '\0') {
18604 conn->protocol_type = -1;
18605
18606 } else {
18607 /* HTTP/1 allows protocol upgrade */
18609
18610 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
18611 /* This will occur, if a HTTP/1.1 request should be upgraded
18612 * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
18613 * Since most (all?) major browsers only support HTTP/2 using
18614 * ALPN, this is hard to test and very low priority.
18615 * Deactivate it (at least for now).
18616 */
18618 }
18619 }
18620
18621 DEBUG_TRACE("http: %s, error: %s",
18622 (ri->http_version ? ri->http_version : "none"),
18623 (ebuf[0] ? ebuf : "none"));
18624
18625 if (ebuf[0] == '\0') {
18626 if (conn->request_info.local_uri) {
18627
18628 /* handle request to local server */
18630
18631 } else {
18632 /* TODO: handle non-local request (PROXY) */
18633 conn->must_close = 1;
18634 }
18635 } else {
18636 conn->must_close = 1;
18637 }
18638
18639 /* Response complete. Free header buffer */
18641
18642 if (ri->remote_user != NULL) {
18643 mg_free((void *)ri->remote_user);
18644 /* Important! When having connections with and without auth
18645 * would cause double free and then crash */
18646 ri->remote_user = NULL;
18647 }
18648
18649 /* NOTE(lsm): order is important here. should_keep_alive() call
18650 * is using parsed request, which will be invalid after
18651 * memmove's below.
18652 * Therefore, memorize should_keep_alive() result now for later
18653 * use in loop exit condition. */
18654 /* Enable it only if this request is completely discardable. */
18655 keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
18656 && should_keep_alive(conn) && (conn->content_len >= 0)
18657 && (conn->request_len > 0)
18658 && ((conn->is_chunked == 4)
18659 || (!conn->is_chunked
18660 && ((conn->consumed_content == conn->content_len)
18661 || ((conn->request_len + conn->content_len)
18662 <= conn->data_len))))
18663 && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
18664
18665 if (keep_alive) {
18666 /* Discard all buffered data for this request */
18667 discard_len =
18668 ((conn->request_len + conn->content_len) < conn->data_len)
18669 ? (int)(conn->request_len + conn->content_len)
18670 : conn->data_len;
18671 conn->data_len -= discard_len;
18672
18673 if (conn->data_len > 0) {
18674 DEBUG_TRACE("discard_len = %d", discard_len);
18675 memmove(conn->buf,
18676 conn->buf + discard_len,
18677 (size_t)conn->data_len);
18678 }
18679 }
18680
18681 DEBUG_ASSERT(conn->data_len >= 0);
18682 DEBUG_ASSERT(conn->data_len <= conn->buf_size);
18683
18684 if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
18685 DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
18686 (long int)conn->data_len,
18687 (long int)conn->buf_size);
18688 break;
18689 }
18690 conn->handled_requests++;
18691 } while (keep_alive);
18692
18693 DEBUG_TRACE("Done processing connection from %s (%f sec)",
18695 difftime(time(NULL), conn->conn_birth_time));
18696
18697 close_connection(conn);
18698
18699#if defined(USE_SERVER_STATS)
18700 mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
18701 mg_atomic_dec(&(conn->phys_ctx->active_connections));
18702#endif
18703}
18704
18705
18706#if defined(ALTERNATIVE_QUEUE)
18707
18708static void
18709produce_socket(struct mg_context *ctx, const struct socket *sp)
18710{
18711 unsigned int i;
18712
18713 while (!ctx->stop_flag) {
18714 for (i = 0; i < ctx->cfg_worker_threads; i++) {
18715 /* find a free worker slot and signal it */
18716 if (ctx->client_socks[i].in_use == 2) {
18717 (void)pthread_mutex_lock(&ctx->thread_mutex);
18718 if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
18719 ctx->client_socks[i] = *sp;
18720 ctx->client_socks[i].in_use = 1;
18721 /* socket has been moved to the consumer */
18722 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18723 (void)event_signal(ctx->client_wait_events[i]);
18724 return;
18725 }
18726 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18727 }
18728 }
18729 /* queue is full */
18730 mg_sleep(1);
18731 }
18732 /* must consume */
18734 closesocket(sp->sock);
18735}
18736
18737
18738static int
18739consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
18740{
18741 DEBUG_TRACE("%s", "going idle");
18742 (void)pthread_mutex_lock(&ctx->thread_mutex);
18743 ctx->client_socks[thread_index].in_use = 2;
18744 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18745
18746 event_wait(ctx->client_wait_events[thread_index]);
18747
18748 (void)pthread_mutex_lock(&ctx->thread_mutex);
18749 *sp = ctx->client_socks[thread_index];
18750 if (ctx->stop_flag) {
18751 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18752 if (sp->in_use == 1) {
18753 /* must consume */
18755 closesocket(sp->sock);
18756 }
18757 return 0;
18758 }
18759 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18760 if (sp->in_use == 1) {
18761 DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
18762 return 1;
18763 }
18764 /* must not reach here */
18765 DEBUG_ASSERT(0);
18766 return 0;
18767}
18768
18769#else /* ALTERNATIVE_QUEUE */
18770
18771/* Worker threads take accepted socket from the queue */
18772static int
18773consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
18774{
18775 (void)thread_index;
18776
18777 (void)pthread_mutex_lock(&ctx->thread_mutex);
18778 DEBUG_TRACE("%s", "going idle");
18779
18780 /* If the queue is empty, wait. We're idle at this point. */
18781 while ((ctx->sq_head == ctx->sq_tail)
18782 && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
18783 pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
18784 }
18785
18786 /* If we're stopping, sq_head may be equal to sq_tail. */
18787 if (ctx->sq_head > ctx->sq_tail) {
18788 /* Copy socket from the queue and increment tail */
18789 *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
18790 ctx->sq_tail++;
18791
18792 DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
18793
18794 /* Wrap pointers if needed */
18795 while (ctx->sq_tail > ctx->sq_size) {
18796 ctx->sq_tail -= ctx->sq_size;
18797 ctx->sq_head -= ctx->sq_size;
18798 }
18799 }
18800
18801 (void)pthread_cond_signal(&ctx->sq_empty);
18802 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18803
18804 return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
18805}
18806
18807
18808/* Master thread adds accepted socket to a queue */
18809static void
18810produce_socket(struct mg_context *ctx, const struct socket *sp)
18811{
18812 int queue_filled;
18813
18814 (void)pthread_mutex_lock(&ctx->thread_mutex);
18815
18816 queue_filled = ctx->sq_head - ctx->sq_tail;
18817
18818 /* If the queue is full, wait */
18819 while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
18820 && (queue_filled >= ctx->sq_size)) {
18821 ctx->sq_blocked = 1; /* Status information: All threads busy */
18822#if defined(USE_SERVER_STATS)
18823 if (queue_filled > ctx->sq_max_fill) {
18824 ctx->sq_max_fill = queue_filled;
18825 }
18826#endif
18827 (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
18828 ctx->sq_blocked = 0; /* Not blocked now */
18829 queue_filled = ctx->sq_head - ctx->sq_tail;
18830 }
18831
18832 if (queue_filled < ctx->sq_size) {
18833 /* Copy socket to the queue and increment head */
18834 ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
18835 ctx->sq_head++;
18836 DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
18837 }
18838
18839 queue_filled = ctx->sq_head - ctx->sq_tail;
18840#if defined(USE_SERVER_STATS)
18841 if (queue_filled > ctx->sq_max_fill) {
18842 ctx->sq_max_fill = queue_filled;
18843 }
18844#endif
18845
18846 (void)pthread_cond_signal(&ctx->sq_full);
18847 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18848}
18849#endif /* ALTERNATIVE_QUEUE */
18850
18851
18852static void
18854{
18855 struct mg_context *ctx = conn->phys_ctx;
18856 int thread_index;
18857 struct mg_workerTLS tls;
18858
18859 mg_set_thread_name("worker");
18860
18861 tls.is_master = 0;
18862 tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
18863#if defined(_WIN32)
18864 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
18865#endif
18866
18867 /* Initialize thread local storage before calling any callback */
18868 pthread_setspecific(sTlsKey, &tls);
18869
18870 /* Check if there is a user callback */
18871 if (ctx->callbacks.init_thread) {
18872 /* call init_thread for a worker thread (type 1), and store the
18873 * return value */
18874 tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
18875 } else {
18876 /* No callback: set user pointer to NULL */
18877 tls.user_ptr = NULL;
18878 }
18879
18880 /* Connection structure has been pre-allocated */
18881 thread_index = (int)(conn - ctx->worker_connections);
18882 if ((thread_index < 0)
18883 || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
18885 "Internal error: Invalid worker index %i",
18886 thread_index);
18887 return;
18888 }
18889
18890 /* Request buffers are not pre-allocated. They are private to the
18891 * request and do not contain any state information that might be
18892 * of interest to anyone observing a server status. */
18893 conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
18894 if (conn->buf == NULL) {
18896 ctx,
18897 "Out of memory: Cannot allocate buffer for worker %i",
18898 thread_index);
18899 return;
18900 }
18901 conn->buf_size = (int)ctx->max_request_size;
18902
18903 conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
18904
18905 conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
18906
18907 conn->request_info.user_data = ctx->user_data;
18908 /* Allocate a mutex for this connection to allow communication both
18909 * within the request handler and from elsewhere in the application
18910 */
18911 if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
18912 mg_free(conn->buf);
18913 mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
18914 return;
18915 }
18916
18917#if defined(USE_SERVER_STATS)
18918 conn->conn_state = 1; /* not consumed */
18919#endif
18920
18921 /* Call consume_socket() even when ctx->stop_flag > 0, to let it
18922 * signal sq_empty condvar to wake up the master waiting in
18923 * produce_socket() */
18924 while (consume_socket(ctx, &conn->client, thread_index)) {
18925
18926 /* New connections must start with new protocol negotiation */
18927 tls.alpn_proto = NULL;
18928
18929#if defined(USE_SERVER_STATS)
18930 conn->conn_close_time = 0;
18931#endif
18932 conn->conn_birth_time = time(NULL);
18933
18934 /* Fill in IP, port info early so even if SSL setup below fails,
18935 * error handler would have the corresponding info.
18936 * Thanks to Johannes Winkelmann for the patch.
18937 */
18939 ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
18940
18942 ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
18943
18945 sizeof(conn->request_info.remote_addr),
18946 &conn->client.rsa);
18947
18948 DEBUG_TRACE("Incomming %sconnection from %s",
18949 (conn->client.is_ssl ? "SSL " : ""),
18951
18952 conn->request_info.is_ssl = conn->client.is_ssl;
18953
18954 if (conn->client.is_ssl) {
18955
18956#if defined(USE_MBEDTLS)
18957 /* HTTPS connection */
18958 if (mbed_ssl_accept(&(conn->ssl),
18959 conn->dom_ctx->ssl_ctx,
18960 (int *)&(conn->client.sock),
18961 conn->phys_ctx)
18962 == 0) {
18963 /* conn->dom_ctx is set in get_request */
18964 /* process HTTPS connection */
18965 init_connection(conn);
18969 } else {
18970 /* make sure the connection is cleaned up on SSL failure */
18971 close_connection(conn);
18972 }
18973
18974#elif !defined(NO_SSL)
18975 /* HTTPS connection */
18976 if (sslize(conn, SSL_accept, NULL)) {
18977 /* conn->dom_ctx is set in get_request */
18978
18979 /* Get SSL client certificate information (if set) */
18980 struct mg_client_cert client_cert;
18981 if (ssl_get_client_cert_info(conn, &client_cert)) {
18982 conn->request_info.client_cert = &client_cert;
18983 }
18984
18985 /* process HTTPS connection */
18986#if defined(USE_HTTP2)
18987 if ((tls.alpn_proto != NULL)
18988 && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
18989 /* process HTTPS/2 connection */
18990 init_connection(conn);
18993 conn->content_len =
18994 -1; /* content length is not predefined */
18995 conn->is_chunked = 0; /* HTTP2 is never chunked */
18996 process_new_http2_connection(conn);
18997 } else
18998#endif
18999 {
19000 /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
19001 init_connection(conn);
19003 /* Start with HTTP, WS will be an "upgrade" request later */
19006 }
19007
19008 /* Free client certificate info */
19009 if (conn->request_info.client_cert) {
19010 mg_free((void *)(conn->request_info.client_cert->subject));
19011 mg_free((void *)(conn->request_info.client_cert->issuer));
19012 mg_free((void *)(conn->request_info.client_cert->serial));
19013 mg_free((void *)(conn->request_info.client_cert->finger));
19014 /* Free certificate memory */
19015 X509_free(
19018 conn->request_info.client_cert->subject = 0;
19019 conn->request_info.client_cert->issuer = 0;
19020 conn->request_info.client_cert->serial = 0;
19021 conn->request_info.client_cert->finger = 0;
19022 conn->request_info.client_cert = 0;
19023 }
19024 } else {
19025 /* make sure the connection is cleaned up on SSL failure */
19026 close_connection(conn);
19027 }
19028#endif
19029
19030 } else {
19031 /* process HTTP connection */
19032 init_connection(conn);
19034 /* Start with HTTP, WS will be an "upgrade" request later */
19037 }
19038
19039 DEBUG_TRACE("%s", "Connection closed");
19040
19041#if defined(USE_SERVER_STATS)
19042 conn->conn_close_time = time(NULL);
19043#endif
19044 }
19045
19046 /* Call exit thread user callback */
19047 if (ctx->callbacks.exit_thread) {
19048 ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
19049 }
19050
19051 /* delete thread local storage objects */
19052 pthread_setspecific(sTlsKey, NULL);
19053#if defined(_WIN32)
19054 CloseHandle(tls.pthread_cond_helper_mutex);
19055#endif
19056 pthread_mutex_destroy(&conn->mutex);
19057
19058 /* Free the request buffer. */
19059 conn->buf_size = 0;
19060 mg_free(conn->buf);
19061 conn->buf = NULL;
19062
19063 /* Free cleaned URI (if any) */
19064 if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
19065 mg_free((void *)conn->request_info.local_uri);
19066 conn->request_info.local_uri = NULL;
19067 }
19068
19069#if defined(USE_SERVER_STATS)
19070 conn->conn_state = 9; /* done */
19071#endif
19072
19073 DEBUG_TRACE("%s", "exiting");
19074}
19075
19076
19077/* Threads have different return types on Windows and Unix. */
19078#if defined(_WIN32)
19079static unsigned __stdcall worker_thread(void *thread_func_param)
19080{
19081 worker_thread_run((struct mg_connection *)thread_func_param);
19082 return 0;
19083}
19084#else
19085static void *
19086worker_thread(void *thread_func_param)
19087{
19088#if !defined(__ZEPHYR__)
19089 struct sigaction sa;
19090
19091 /* Ignore SIGPIPE */
19092 memset(&sa, 0, sizeof(sa));
19093 sa.sa_handler = SIG_IGN;
19094 sigaction(SIGPIPE, &sa, NULL);
19095#endif
19096
19097 worker_thread_run((struct mg_connection *)thread_func_param);
19098 return NULL;
19099}
19100#endif /* _WIN32 */
19101
19102
19103/* This is an internal function, thus all arguments are expected to be
19104 * valid - a NULL check is not required. */
19105static void
19106accept_new_connection(const struct socket *listener, struct mg_context *ctx)
19107{
19108 struct socket so;
19109 char src_addr[IP_ADDR_STR_LEN];
19110 socklen_t len = sizeof(so.rsa);
19111#if !defined(__ZEPHYR__)
19112 int on = 1;
19113#endif
19114 memset(&so, 0, sizeof(so));
19115
19116 if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
19117 == INVALID_SOCKET) {
19118 } else if (check_acl(ctx, &so.rsa) != 1) {
19119 sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
19121 "%s: %s is not allowed to connect",
19122 __func__,
19123 src_addr);
19124 closesocket(so.sock);
19125 } else {
19126 /* Put so socket structure into the queue */
19127 DEBUG_TRACE("Accepted socket %d", (int)so.sock);
19128 set_close_on_exec(so.sock, NULL, ctx);
19129 so.is_ssl = listener->is_ssl;
19130 so.ssl_redir = listener->ssl_redir;
19131 if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
19133 "%s: getsockname() failed: %s",
19134 __func__,
19135 strerror(ERRNO));
19136 }
19137
19138#if !defined(__ZEPHYR__)
19139 if ((so.lsa.sa.sa_family == AF_INET)
19140 || (so.lsa.sa.sa_family == AF_INET6)) {
19141 /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
19142 * This is needed because if HTTP-level keep-alive
19143 * is enabled, and client resets the connection, server won't get
19144 * TCP FIN or RST and will keep the connection open forever. With
19145 * TCP keep-alive, next keep-alive handshake will figure out that
19146 * the client is down and will close the server end.
19147 * Thanks to Igor Klopov who suggested the patch. */
19148 if (setsockopt(so.sock,
19149 SOL_SOCKET,
19150 SO_KEEPALIVE,
19151 (SOCK_OPT_TYPE)&on,
19152 sizeof(on))
19153 != 0) {
19155 ctx,
19156 "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
19157 __func__,
19158 strerror(ERRNO));
19159 }
19160 }
19161#endif
19162
19163 /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
19164 * to effectively fill up the underlying IP packet payload and
19165 * reduce the overhead of sending lots of small buffers. However
19166 * this hurts the server's throughput (ie. operations per second)
19167 * when HTTP 1.1 persistent connections are used and the responses
19168 * are relatively small (eg. less than 1400 bytes).
19169 */
19170 if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
19171 && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
19172 if (set_tcp_nodelay(&so, 1) != 0) {
19174 ctx,
19175 "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
19176 __func__,
19177 strerror(ERRNO));
19178 }
19179 }
19180
19181 /* The "non blocking" property should already be
19182 * inherited from the parent socket. Set it for
19183 * non-compliant socket implementations. */
19185
19186 so.in_use = 0;
19187 produce_socket(ctx, &so);
19188 }
19189}
19190
19191
19192static void
19194{
19195 struct mg_workerTLS tls;
19196 struct mg_pollfd *pfd;
19197 unsigned int i;
19198 unsigned int workerthreadcount;
19199
19200 if (!ctx) {
19201 return;
19202 }
19203
19204 mg_set_thread_name("master");
19205
19206 /* Increase priority of the master thread */
19207#if defined(_WIN32)
19208 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
19209#elif defined(USE_MASTER_THREAD_PRIORITY)
19210 int min_prio = sched_get_priority_min(SCHED_RR);
19211 int max_prio = sched_get_priority_max(SCHED_RR);
19212 if ((min_prio >= 0) && (max_prio >= 0)
19213 && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
19214 && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
19215 struct sched_param sched_param = {0};
19216 sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
19217 pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
19218 }
19219#endif
19220
19221 /* Initialize thread local storage */
19222#if defined(_WIN32)
19223 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
19224#endif
19225 tls.is_master = 1;
19226 pthread_setspecific(sTlsKey, &tls);
19227
19228 if (ctx->callbacks.init_thread) {
19229 /* Callback for the master thread (type 0) */
19230 tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
19231 } else {
19232 tls.user_ptr = NULL;
19233 }
19234
19235 /* Lua background script "start" event */
19236#if defined(USE_LUA)
19237 if (ctx->lua_background_state) {
19238 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19239 pthread_mutex_lock(&ctx->lua_bg_mutex);
19240
19241 /* call "start()" in Lua */
19242 lua_getglobal(lstate, "start");
19243 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19244 int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
19245 if (ret != 0) {
19246 struct mg_connection fc;
19247 lua_cry(fake_connection(&fc, ctx),
19248 ret,
19249 lstate,
19250 "lua_background_script",
19251 "start");
19252 }
19253 } else {
19254 lua_pop(lstate, 1);
19255 }
19256
19257 /* determine if there is a "log()" function in Lua background script */
19258 lua_getglobal(lstate, "log");
19259 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19260 ctx->lua_bg_log_available = 1;
19261 }
19262 lua_pop(lstate, 1);
19263
19264 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19265 }
19266#endif
19267
19268 /* Server starts *now* */
19269 ctx->start_time = time(NULL);
19270
19271 /* Server accept loop */
19272 pfd = ctx->listening_socket_fds;
19273 while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
19274 for (i = 0; i < ctx->num_listening_sockets; i++) {
19275 pfd[i].fd = ctx->listening_sockets[i].sock;
19276 pfd[i].events = POLLIN;
19277 }
19278
19279 if (mg_poll(pfd,
19282 &(ctx->stop_flag))
19283 > 0) {
19284 for (i = 0; i < ctx->num_listening_sockets; i++) {
19285 /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
19286 * successful poll, and POLLIN is defined as
19287 * (POLLRDNORM | POLLRDBAND)
19288 * Therefore, we're checking pfd[i].revents & POLLIN, not
19289 * pfd[i].revents == POLLIN. */
19290 if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
19291 && (pfd[i].revents & POLLIN)) {
19293 }
19294 }
19295 }
19296 }
19297
19298 /* Here stop_flag is 1 - Initiate shutdown. */
19299 DEBUG_TRACE("%s", "stopping workers");
19300
19301 /* Stop signal received: somebody called mg_stop. Quit. */
19303
19304 /* Wakeup workers that are waiting for connections to handle. */
19305#if defined(ALTERNATIVE_QUEUE)
19306 for (i = 0; i < ctx->cfg_worker_threads; i++) {
19307 event_signal(ctx->client_wait_events[i]);
19308 }
19309#else
19310 (void)pthread_mutex_lock(&ctx->thread_mutex);
19311 pthread_cond_broadcast(&ctx->sq_full);
19312 (void)pthread_mutex_unlock(&ctx->thread_mutex);
19313#endif
19314
19315 /* Join all worker threads to avoid leaking threads. */
19316 workerthreadcount = ctx->cfg_worker_threads;
19317 for (i = 0; i < workerthreadcount; i++) {
19318 if (ctx->worker_threadids[i] != 0) {
19320 }
19321 }
19322
19323#if defined(USE_LUA)
19324 /* Free Lua state of lua background task */
19325 if (ctx->lua_background_state) {
19326 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19327 ctx->lua_bg_log_available = 0;
19328
19329 /* call "stop()" in Lua */
19330 pthread_mutex_lock(&ctx->lua_bg_mutex);
19331 lua_getglobal(lstate, "stop");
19332 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19333 int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
19334 if (ret != 0) {
19335 struct mg_connection fc;
19336 lua_cry(fake_connection(&fc, ctx),
19337 ret,
19338 lstate,
19339 "lua_background_script",
19340 "stop");
19341 }
19342 }
19343 lua_close(lstate);
19344
19345 ctx->lua_background_state = 0;
19346 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19347 }
19348#endif
19349
19350 DEBUG_TRACE("%s", "exiting");
19351
19352 /* call exit thread callback */
19353 if (ctx->callbacks.exit_thread) {
19354 /* Callback for the master thread (type 0) */
19355 ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
19356 }
19357
19358#if defined(_WIN32)
19359 CloseHandle(tls.pthread_cond_helper_mutex);
19360#endif
19361 pthread_setspecific(sTlsKey, NULL);
19362
19363 /* Signal mg_stop() that we're done.
19364 * WARNING: This must be the very last thing this
19365 * thread does, as ctx becomes invalid after this line. */
19366 STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
19367}
19368
19369
19370/* Threads have different return types on Windows and Unix. */
19371#if defined(_WIN32)
19372static unsigned __stdcall master_thread(void *thread_func_param)
19373{
19374 master_thread_run((struct mg_context *)thread_func_param);
19375 return 0;
19376}
19377#else
19378static void *
19379master_thread(void *thread_func_param)
19380{
19381#if !defined(__ZEPHYR__)
19382 struct sigaction sa;
19383
19384 /* Ignore SIGPIPE */
19385 memset(&sa, 0, sizeof(sa));
19386 sa.sa_handler = SIG_IGN;
19387 sigaction(SIGPIPE, &sa, NULL);
19388#endif
19389
19390 master_thread_run((struct mg_context *)thread_func_param);
19391 return NULL;
19392}
19393#endif /* _WIN32 */
19394
19395
19396static void
19398{
19399 int i;
19400 struct mg_handler_info *tmp_rh;
19401
19402 if (ctx == NULL) {
19403 return;
19404 }
19405
19406 /* Call user callback */
19407 if (ctx->callbacks.exit_context) {
19408 ctx->callbacks.exit_context(ctx);
19409 }
19410
19411 /* All threads exited, no sync is needed. Destroy thread mutex and
19412 * condvars
19413 */
19414 (void)pthread_mutex_destroy(&ctx->thread_mutex);
19415
19416#if defined(ALTERNATIVE_QUEUE)
19417 mg_free(ctx->client_socks);
19418 if (ctx->client_wait_events != NULL) {
19419 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
19420 event_destroy(ctx->client_wait_events[i]);
19421 }
19422 mg_free(ctx->client_wait_events);
19423 }
19424#else
19425 (void)pthread_cond_destroy(&ctx->sq_empty);
19426 (void)pthread_cond_destroy(&ctx->sq_full);
19427 mg_free(ctx->squeue);
19428#endif
19429
19430 /* Destroy other context global data structures mutex */
19431 (void)pthread_mutex_destroy(&ctx->nonce_mutex);
19432
19433#if defined(USE_LUA)
19434 (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
19435#endif
19436
19437 /* Deallocate config parameters */
19438 for (i = 0; i < NUM_OPTIONS; i++) {
19439 if (ctx->dd.config[i] != NULL) {
19440#if defined(_MSC_VER)
19441#pragma warning(suppress : 6001)
19442#endif
19443 mg_free(ctx->dd.config[i]);
19444 }
19445 }
19446
19447 /* Deallocate request handlers */
19448 while (ctx->dd.handlers) {
19449 tmp_rh = ctx->dd.handlers;
19450 ctx->dd.handlers = tmp_rh->next;
19451 mg_free(tmp_rh->uri);
19452 mg_free(tmp_rh);
19453 }
19454
19455#if defined(USE_MBEDTLS)
19456 if (ctx->dd.ssl_ctx != NULL) {
19457 mbed_sslctx_uninit(ctx->dd.ssl_ctx);
19458 mg_free(ctx->dd.ssl_ctx);
19459 ctx->dd.ssl_ctx = NULL;
19460 }
19461
19462#elif !defined(NO_SSL)
19463 /* Deallocate SSL context */
19464 if (ctx->dd.ssl_ctx != NULL) {
19465 void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
19466 int callback_ret =
19467 (ctx->callbacks.external_ssl_ctx == NULL)
19468 ? 0
19469 : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
19470
19471 if (callback_ret == 0) {
19472 SSL_CTX_free(ctx->dd.ssl_ctx);
19473 }
19474 /* else: ignore error and ommit SSL_CTX_free in case
19475 * callback_ret is 1 */
19476 }
19477#endif /* !NO_SSL */
19478
19479 /* Deallocate worker thread ID array */
19481
19482 /* Deallocate worker thread ID array */
19484
19485 /* deallocate system name string */
19486 mg_free(ctx->systemName);
19487
19488 /* Deallocate context itself */
19489 mg_free(ctx);
19490}
19491
19492
19493void
19495{
19496 pthread_t mt;
19497 if (!ctx) {
19498 return;
19499 }
19500
19501 /* We don't use a lock here. Calling mg_stop with the same ctx from
19502 * two threads is not allowed. */
19503 mt = ctx->masterthreadid;
19504 if (mt == 0) {
19505 return;
19506 }
19507
19508 ctx->masterthreadid = 0;
19509
19510 /* Set stop flag, so all threads know they have to exit. */
19511 STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
19512
19513 /* Join timer thread */
19514#if defined(USE_TIMERS)
19515 timers_exit(ctx);
19516#endif
19517
19518 /* Wait until everything has stopped. */
19519 while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
19520 (void)mg_sleep(10);
19521 }
19522
19523 /* Wait to stop master thread */
19524 mg_join_thread(mt);
19525
19526 /* Close remaining Lua states */
19527#if defined(USE_LUA)
19528 lua_ctx_exit(ctx);
19529#endif
19530
19531 /* Free memory */
19532 free_context(ctx);
19533}
19534
19535
19536static void
19537get_system_name(char **sysName)
19538{
19539#if defined(_WIN32)
19540 char name[128];
19541 DWORD dwVersion = 0;
19542 DWORD dwMajorVersion = 0;
19543 DWORD dwMinorVersion = 0;
19544 DWORD dwBuild = 0;
19545 BOOL wowRet, isWoW = FALSE;
19546
19547#if defined(_MSC_VER)
19548#pragma warning(push)
19549 /* GetVersion was declared deprecated */
19550#pragma warning(disable : 4996)
19551#endif
19552 dwVersion = GetVersion();
19553#if defined(_MSC_VER)
19554#pragma warning(pop)
19555#endif
19556
19557 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
19558 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
19559 dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
19560 (void)dwBuild;
19561
19562 wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
19563
19564 sprintf(name,
19565 "Windows %u.%u%s",
19566 (unsigned)dwMajorVersion,
19567 (unsigned)dwMinorVersion,
19568 (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
19569
19570 *sysName = mg_strdup(name);
19571
19572
19573#elif defined(__ZEPHYR__)
19574 *sysName = mg_strdup("Zephyr OS");
19575#else
19576 struct utsname name;
19577 memset(&name, 0, sizeof(name));
19578 uname(&name);
19579 *sysName = mg_strdup(name.sysname);
19580#endif
19581}
19582
19583
19584static void
19585legacy_init(const char **options)
19586{
19587 const char *ports_option = config_options[LISTENING_PORTS].default_value;
19588
19589 if (options) {
19590 const char **run_options = options;
19591 const char *optname = config_options[LISTENING_PORTS].name;
19592
19593 /* Try to find the "listening_ports" option */
19594 while (*run_options) {
19595 if (!strcmp(*run_options, optname)) {
19596 ports_option = run_options[1];
19597 }
19598 run_options += 2;
19599 }
19600 }
19601
19602 if (is_ssl_port_used(ports_option)) {
19603 /* Initialize with SSL support */
19605 } else {
19606 /* Initialize without SSL support */
19608 }
19609}
19610
19611
19612struct mg_context *
19613mg_start2(struct mg_init_data *init, struct mg_error_data *error)
19614{
19615 struct mg_context *ctx;
19616 const char *name, *value, *default_value;
19617 int idx, ok, workerthreadcount;
19618 unsigned int i;
19619 int itmp;
19620 void (*exit_callback)(const struct mg_context *ctx) = 0;
19621 const char **options =
19622 ((init != NULL) ? (init->configuration_options) : (NULL));
19623
19624 struct mg_workerTLS tls;
19625
19626 if (error != NULL) {
19627 error->code = 0;
19628 if (error->text_buffer_size > 0) {
19629 *error->text = 0;
19630 }
19631 }
19632
19633 if (mg_init_library_called == 0) {
19634 /* Legacy INIT, if mg_start is called without mg_init_library.
19635 * Note: This will cause a memory leak when unloading the library.
19636 */
19637 legacy_init(options);
19638 }
19639 if (mg_init_library_called == 0) {
19640 if ((error != NULL) && (error->text_buffer_size > 0)) {
19641 mg_snprintf(NULL,
19642 NULL, /* No truncation check for error buffers */
19643 error->text,
19644 error->text_buffer_size,
19645 "%s",
19646 "Library uninitialized");
19647 }
19648 return NULL;
19649 }
19650
19651 /* Allocate context and initialize reasonable general case defaults. */
19652 if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
19653 if ((error != NULL) && (error->text_buffer_size > 0)) {
19654 mg_snprintf(NULL,
19655 NULL, /* No truncation check for error buffers */
19656 error->text,
19657 error->text_buffer_size,
19658 "%s",
19659 "Out of memory");
19660 }
19661 return NULL;
19662 }
19663
19664 /* Random number generator will initialize at the first call */
19665 ctx->dd.auth_nonce_mask =
19666 (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
19667
19668 /* Save started thread index to reuse in other external API calls
19669 * For the sake of thread synchronization all non-civetweb threads
19670 * can be considered as single external thread */
19672 tls.is_master = -1; /* Thread calling mg_start */
19673 tls.thread_idx = ctx->starter_thread_idx;
19674#if defined(_WIN32)
19675 tls.pthread_cond_helper_mutex = NULL;
19676#endif
19677 pthread_setspecific(sTlsKey, &tls);
19678
19679 ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
19680#if !defined(ALTERNATIVE_QUEUE)
19681 ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
19682 ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
19683 ctx->sq_blocked = 0;
19684#endif
19685 ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
19686#if defined(USE_LUA)
19687 ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
19688#endif
19689 if (!ok) {
19690 const char *err_msg =
19691 "Cannot initialize thread synchronization objects";
19692 /* Fatal error - abort start. However, this situation should never
19693 * occur in practice. */
19694
19695 mg_cry_ctx_internal(ctx, "%s", err_msg);
19696 if ((error != NULL) && (error->text_buffer_size > 0)) {
19697 mg_snprintf(NULL,
19698 NULL, /* No truncation check for error buffers */
19699 error->text,
19700 error->text_buffer_size,
19701 "%s",
19702 err_msg);
19703 }
19704
19705 mg_free(ctx);
19706 pthread_setspecific(sTlsKey, NULL);
19707 return NULL;
19708 }
19709
19710 if ((init != NULL) && (init->callbacks != NULL)) {
19711 /* Set all callbacks except exit_context. */
19712 ctx->callbacks = *init->callbacks;
19713 exit_callback = init->callbacks->exit_context;
19714 /* The exit callback is activated once the context is successfully
19715 * created. It should not be called, if an incomplete context object
19716 * is deleted during a failed initialization. */
19717 ctx->callbacks.exit_context = 0;
19718 }
19719 ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
19720 ctx->dd.handlers = NULL;
19721 ctx->dd.next = NULL;
19722
19723#if defined(USE_LUA)
19724 lua_ctx_init(ctx);
19725#endif
19726
19727 /* Store options */
19728 while (options && (name = *options++) != NULL) {
19729 if ((idx = get_option_index(name)) == -1) {
19730 mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
19731 if ((error != NULL) && (error->text_buffer_size > 0)) {
19732 mg_snprintf(NULL,
19733 NULL, /* No truncation check for error buffers */
19734 error->text,
19735 error->text_buffer_size,
19736 "Invalid configuration option: %s",
19737 name);
19738 }
19739 free_context(ctx);
19740 pthread_setspecific(sTlsKey, NULL);
19741 return NULL;
19742 } else if ((value = *options++) == NULL) {
19743 mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
19744 if ((error != NULL) && (error->text_buffer_size > 0)) {
19745 mg_snprintf(NULL,
19746 NULL, /* No truncation check for error buffers */
19747 error->text,
19748 error->text_buffer_size,
19749 "Invalid configuration option value: %s",
19750 name);
19751 }
19752 free_context(ctx);
19753 pthread_setspecific(sTlsKey, NULL);
19754 return NULL;
19755 }
19756 if (ctx->dd.config[idx] != NULL) {
19757 /* A duplicate configuration option is not an error - the last
19758 * option value will be used. */
19759 mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
19760 mg_free(ctx->dd.config[idx]);
19761 }
19762 ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
19763 DEBUG_TRACE("[%s] -> [%s]", name, value);
19764 }
19765
19766 /* Set default value if needed */
19767 for (i = 0; config_options[i].name != NULL; i++) {
19768 default_value = config_options[i].default_value;
19769 if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
19770 ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
19771 }
19772 }
19773
19774 /* Request size option */
19775 itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
19776 if (itmp < 1024) {
19778 "%s too small",
19780 if ((error != NULL) && (error->text_buffer_size > 0)) {
19781 mg_snprintf(NULL,
19782 NULL, /* No truncation check for error buffers */
19783 error->text,
19784 error->text_buffer_size,
19785 "Invalid configuration option value: %s",
19787 }
19788 free_context(ctx);
19789 pthread_setspecific(sTlsKey, NULL);
19790 return NULL;
19791 }
19792 ctx->max_request_size = (unsigned)itmp;
19793
19794 /* Queue length */
19795#if !defined(ALTERNATIVE_QUEUE)
19796 itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
19797 if (itmp < 1) {
19799 "%s too small",
19801 if ((error != NULL) && (error->text_buffer_size > 0)) {
19802 mg_snprintf(NULL,
19803 NULL, /* No truncation check for error buffers */
19804 error->text,
19805 error->text_buffer_size,
19806 "Invalid configuration option value: %s",
19808 }
19809 free_context(ctx);
19810 pthread_setspecific(sTlsKey, NULL);
19811 return NULL;
19812 }
19813 ctx->squeue =
19814 (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
19815 if (ctx->squeue == NULL) {
19817 "Out of memory: Cannot allocate %s",
19819 if ((error != NULL) && (error->text_buffer_size > 0)) {
19820 mg_snprintf(NULL,
19821 NULL, /* No truncation check for error buffers */
19822 error->text,
19823 error->text_buffer_size,
19824 "Out of memory: Cannot allocate %s",
19826 }
19827 free_context(ctx);
19828 pthread_setspecific(sTlsKey, NULL);
19829 return NULL;
19830 }
19831 ctx->sq_size = itmp;
19832#endif
19833
19834 /* Worker thread count option */
19835 workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
19836
19837 if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
19838 if (workerthreadcount <= 0) {
19839 mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
19840 } else {
19841 mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
19842 }
19843 if ((error != NULL) && (error->text_buffer_size > 0)) {
19844 mg_snprintf(NULL,
19845 NULL, /* No truncation check for error buffers */
19846 error->text,
19847 error->text_buffer_size,
19848 "Invalid configuration option value: %s",
19850 }
19851 free_context(ctx);
19852 pthread_setspecific(sTlsKey, NULL);
19853 return NULL;
19854 }
19855
19856 /* Document root */
19857#if defined(NO_FILES)
19858 if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
19859 mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
19860 if ((error != NULL) && (error->text_buffer_size > 0)) {
19861 mg_snprintf(NULL,
19862 NULL, /* No truncation check for error buffers */
19863 error->text,
19864 error->text_buffer_size,
19865 "Invalid configuration option value: %s",
19867 }
19868 free_context(ctx);
19869 pthread_setspecific(sTlsKey, NULL);
19870 return NULL;
19871 }
19872#endif
19873
19875
19876#if defined(USE_LUA)
19877 /* If a Lua background script has been configured, start it. */
19878 ctx->lua_bg_log_available = 0;
19879 if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
19880 char ebuf[256];
19881 struct vec opt_vec;
19882 struct vec eq_vec;
19883 const char *sparams;
19884
19885 memset(ebuf, 0, sizeof(ebuf));
19886 pthread_mutex_lock(&ctx->lua_bg_mutex);
19887
19888 /* Create a Lua state, load all standard libraries and the mg table */
19889 lua_State *state = mg_lua_context_script_prepare(
19890 ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
19891 if (!state) {
19893 "lua_background_script load error: %s",
19894 ebuf);
19895 if ((error != NULL) && (error->text_buffer_size > 0)) {
19896 mg_snprintf(NULL,
19897 NULL, /* No truncation check for error buffers */
19898 error->text,
19899 error->text_buffer_size,
19900 "Error in script %s: %s",
19901 config_options[LUA_BACKGROUND_SCRIPT].name,
19902 ebuf);
19903 }
19904 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19905
19906 free_context(ctx);
19907 pthread_setspecific(sTlsKey, NULL);
19908 return NULL;
19909 }
19910
19911 /* Add a table with parameters into mg.params */
19912 sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
19913 if (sparams && sparams[0]) {
19914 lua_getglobal(state, "mg");
19915 lua_pushstring(state, "params");
19916 lua_newtable(state);
19917
19918 while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
19919 != NULL) {
19920 reg_llstring(
19921 state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
19922 if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
19923 break;
19924 }
19925 lua_rawset(state, -3);
19926 lua_pop(state, 1);
19927 }
19928
19929 /* Call script */
19930 state = mg_lua_context_script_run(state,
19931 ctx->dd.config[LUA_BACKGROUND_SCRIPT],
19932 ctx,
19933 ebuf,
19934 sizeof(ebuf));
19935 if (!state) {
19937 "lua_background_script start error: %s",
19938 ebuf);
19939 if ((error != NULL) && (error->text_buffer_size > 0)) {
19940 mg_snprintf(NULL,
19941 NULL, /* No truncation check for error buffers */
19942 error->text,
19943 error->text_buffer_size,
19944 "Error in script %s: %s",
19946 ebuf);
19947 }
19948 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19949
19950 free_context(ctx);
19951 pthread_setspecific(sTlsKey, NULL);
19952 return NULL;
19953 }
19954
19955 /* state remains valid */
19956 ctx->lua_background_state = (void *)state;
19957 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19958
19959 } else {
19960 ctx->lua_background_state = 0;
19961 }
19962#endif
19963
19964 /* Step by step initialization of ctx - depending on build options */
19965#if !defined(NO_FILESYSTEMS)
19966 if (!set_gpass_option(ctx, NULL)) {
19967 const char *err_msg = "Invalid global password file";
19968 /* Fatal error - abort start. */
19969 mg_cry_ctx_internal(ctx, "%s", err_msg);
19970
19971 if ((error != NULL) && (error->text_buffer_size > 0)) {
19972 mg_snprintf(NULL,
19973 NULL, /* No truncation check for error buffers */
19974 error->text,
19975 error->text_buffer_size,
19976 "%s",
19977 err_msg);
19978 }
19979 free_context(ctx);
19980 pthread_setspecific(sTlsKey, NULL);
19981 return NULL;
19982 }
19983#endif
19984
19985#if defined(USE_MBEDTLS)
19986 if (!mg_sslctx_init(ctx, NULL)) {
19987 const char *err_msg = "Error initializing SSL context";
19988 /* Fatal error - abort start. */
19989 mg_cry_ctx_internal(ctx, "%s", err_msg);
19990
19991 if ((error != NULL) && (error->text_buffer_size > 0)) {
19992 mg_snprintf(NULL,
19993 NULL, /* No truncation check for error buffers */
19994 error->text,
19995 error->text_buffer_size,
19996 "%s",
19997 err_msg);
19998 }
19999 free_context(ctx);
20000 pthread_setspecific(sTlsKey, NULL);
20001 return NULL;
20002 }
20003
20004#elif !defined(NO_SSL)
20005 if (!init_ssl_ctx(ctx, NULL)) {
20006 const char *err_msg = "Error initializing SSL context";
20007 /* Fatal error - abort start. */
20008 mg_cry_ctx_internal(ctx, "%s", err_msg);
20009
20010 if ((error != NULL) && (error->text_buffer_size > 0)) {
20011 mg_snprintf(NULL,
20012 NULL, /* No truncation check for error buffers */
20013 error->text,
20014 error->text_buffer_size,
20015 "%s",
20016 err_msg);
20017 }
20018 free_context(ctx);
20019 pthread_setspecific(sTlsKey, NULL);
20020 return NULL;
20021 }
20022#endif
20023
20024 if (!set_ports_option(ctx)) {
20025 const char *err_msg = "Failed to setup server ports";
20026 /* Fatal error - abort start. */
20027 mg_cry_ctx_internal(ctx, "%s", err_msg);
20028
20029 if ((error != NULL) && (error->text_buffer_size > 0)) {
20030 mg_snprintf(NULL,
20031 NULL, /* No truncation check for error buffers */
20032 error->text,
20033 error->text_buffer_size,
20034 "%s",
20035 err_msg);
20036 }
20037 free_context(ctx);
20038 pthread_setspecific(sTlsKey, NULL);
20039 return NULL;
20040 }
20041
20042
20043#if !defined(_WIN32) && !defined(__ZEPHYR__)
20044 if (!set_uid_option(ctx)) {
20045 const char *err_msg = "Failed to run as configured user";
20046 /* Fatal error - abort start. */
20047 mg_cry_ctx_internal(ctx, "%s", err_msg);
20048
20049 if ((error != NULL) && (error->text_buffer_size > 0)) {
20050 mg_snprintf(NULL,
20051 NULL, /* No truncation check for error buffers */
20052 error->text,
20053 error->text_buffer_size,
20054 "%s",
20055 err_msg);
20056 }
20057 free_context(ctx);
20058 pthread_setspecific(sTlsKey, NULL);
20059 return NULL;
20060 }
20061#endif
20062
20063 if (!set_acl_option(ctx)) {
20064 const char *err_msg = "Failed to setup access control list";
20065 /* Fatal error - abort start. */
20066 mg_cry_ctx_internal(ctx, "%s", err_msg);
20067
20068 if ((error != NULL) && (error->text_buffer_size > 0)) {
20069 mg_snprintf(NULL,
20070 NULL, /* No truncation check for error buffers */
20071 error->text,
20072 error->text_buffer_size,
20073 "%s",
20074 err_msg);
20075 }
20076 free_context(ctx);
20077 pthread_setspecific(sTlsKey, NULL);
20078 return NULL;
20079 }
20080
20081 ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
20082 ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
20083 sizeof(pthread_t),
20084 ctx);
20085
20086 if (ctx->worker_threadids == NULL) {
20087 const char *err_msg = "Not enough memory for worker thread ID array";
20088 mg_cry_ctx_internal(ctx, "%s", err_msg);
20089
20090 if ((error != NULL) && (error->text_buffer_size > 0)) {
20091 mg_snprintf(NULL,
20092 NULL, /* No truncation check for error buffers */
20093 error->text,
20094 error->text_buffer_size,
20095 "%s",
20096 err_msg);
20097 }
20098 free_context(ctx);
20099 pthread_setspecific(sTlsKey, NULL);
20100 return NULL;
20101 }
20102 ctx->worker_connections =
20104 sizeof(struct mg_connection),
20105 ctx);
20106 if (ctx->worker_connections == NULL) {
20107 const char *err_msg =
20108 "Not enough memory for worker thread connection array";
20109 mg_cry_ctx_internal(ctx, "%s", err_msg);
20110
20111 if ((error != NULL) && (error->text_buffer_size > 0)) {
20112 mg_snprintf(NULL,
20113 NULL, /* No truncation check for error buffers */
20114 error->text,
20115 error->text_buffer_size,
20116 "%s",
20117 err_msg);
20118 }
20119 free_context(ctx);
20120 pthread_setspecific(sTlsKey, NULL);
20121 return NULL;
20122 }
20123
20124#if defined(ALTERNATIVE_QUEUE)
20125 ctx->client_wait_events =
20126 (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
20127 sizeof(ctx->client_wait_events[0]),
20128 ctx);
20129 if (ctx->client_wait_events == NULL) {
20130 const char *err_msg = "Not enough memory for worker event array";
20131 mg_cry_ctx_internal(ctx, "%s", err_msg);
20133
20134 if ((error != NULL) && (error->text_buffer_size > 0)) {
20135 mg_snprintf(NULL,
20136 NULL, /* No truncation check for error buffers */
20137 error->text,
20138 error->text_buffer_size,
20139 "%s",
20140 err_msg);
20141 }
20142 free_context(ctx);
20143 pthread_setspecific(sTlsKey, NULL);
20144 return NULL;
20145 }
20146
20147 ctx->client_socks =
20149 sizeof(ctx->client_socks[0]),
20150 ctx);
20151 if (ctx->client_socks == NULL) {
20152 const char *err_msg = "Not enough memory for worker socket array";
20153 mg_cry_ctx_internal(ctx, "%s", err_msg);
20154 mg_free(ctx->client_wait_events);
20156
20157 if ((error != NULL) && (error->text_buffer_size > 0)) {
20158 mg_snprintf(NULL,
20159 NULL, /* No truncation check for error buffers */
20160 error->text,
20161 error->text_buffer_size,
20162 "%s",
20163 err_msg);
20164 }
20165 free_context(ctx);
20166 pthread_setspecific(sTlsKey, NULL);
20167 return NULL;
20168 }
20169
20170 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
20171 ctx->client_wait_events[i] = event_create();
20172 if (ctx->client_wait_events[i] == 0) {
20173 const char *err_msg = "Error creating worker event %i";
20174 mg_cry_ctx_internal(ctx, err_msg, i);
20175 while (i > 0) {
20176 i--;
20177 event_destroy(ctx->client_wait_events[i]);
20178 }
20179 mg_free(ctx->client_socks);
20180 mg_free(ctx->client_wait_events);
20182
20183 if ((error != NULL) && (error->text_buffer_size > 0)) {
20184 mg_snprintf(NULL,
20185 NULL, /* No truncation check for error buffers */
20186 error->text,
20187 error->text_buffer_size,
20188 err_msg,
20189 i);
20190 }
20191 free_context(ctx);
20192 pthread_setspecific(sTlsKey, NULL);
20193 return NULL;
20194 }
20195 }
20196#endif
20197
20198#if defined(USE_TIMERS)
20199 if (timers_init(ctx) != 0) {
20200 const char *err_msg = "Error creating timers";
20201 mg_cry_ctx_internal(ctx, "%s", err_msg);
20202
20203 if ((error != NULL) && (error->text_buffer_size > 0)) {
20204 mg_snprintf(NULL,
20205 NULL, /* No truncation check for error buffers */
20206 error->text,
20207 error->text_buffer_size,
20208 "%s",
20209 err_msg);
20210 }
20211 free_context(ctx);
20212 pthread_setspecific(sTlsKey, NULL);
20213 return NULL;
20214 }
20215#endif
20216
20217 /* Context has been created - init user libraries */
20218 if (ctx->callbacks.init_context) {
20219 ctx->callbacks.init_context(ctx);
20220 }
20221
20222 /* From now, the context is successfully created.
20223 * When it is destroyed, the exit callback should be called. */
20224 ctx->callbacks.exit_context = exit_callback;
20225 ctx->context_type = CONTEXT_SERVER; /* server context */
20226
20227 /* Start worker threads */
20228 for (i = 0; i < ctx->cfg_worker_threads; i++) {
20229 /* worker_thread sets up the other fields */
20230 ctx->worker_connections[i].phys_ctx = ctx;
20232 &ctx->worker_connections[i],
20233 &ctx->worker_threadids[i])
20234 != 0) {
20235
20236 long error_no = (long)ERRNO;
20237
20238 /* thread was not created */
20239 if (i > 0) {
20240 /* If the second, third, ... thread cannot be created, set a
20241 * warning, but keep running. */
20243 "Cannot start worker thread %i: error %ld",
20244 i + 1,
20245 error_no);
20246
20247 /* If the server initialization should stop here, all
20248 * threads that have already been created must be stopped
20249 * first, before any free_context(ctx) call.
20250 */
20251
20252 } else {
20253 /* If the first worker thread cannot be created, stop
20254 * initialization and free the entire server context. */
20256 "Cannot create threads: error %ld",
20257 error_no);
20258
20259 if ((error != NULL) && (error->text_buffer_size > 0)) {
20261 NULL,
20262 NULL, /* No truncation check for error buffers */
20263 error->text,
20264 error->text_buffer_size,
20265 "Cannot create first worker thread: error %ld",
20266 error_no);
20267 }
20268 free_context(ctx);
20269 pthread_setspecific(sTlsKey, NULL);
20270 return NULL;
20271 }
20272 break;
20273 }
20274 }
20275
20276 /* Start master (listening) thread */
20278
20279 pthread_setspecific(sTlsKey, NULL);
20280 return ctx;
20281}
20282
20283
20284struct mg_context *
20286 void *user_data,
20287 const char **options)
20288{
20289 struct mg_init_data init = {0};
20290 init.callbacks = callbacks;
20291 init.user_data = user_data;
20292 init.configuration_options = options;
20293
20294 return mg_start2(&init, NULL);
20295}
20296
20297
20298/* Add an additional domain to an already running web server. */
20299int
20301 const char **options,
20302 struct mg_error_data *error)
20303{
20304 const char *name;
20305 const char *value;
20306 const char *default_value;
20307 struct mg_domain_context *new_dom;
20308 struct mg_domain_context *dom;
20309 int idx, i;
20310
20311 if (error != NULL) {
20312 error->code = 0;
20313 if (error->text_buffer_size > 0) {
20314 *error->text = 0;
20315 }
20316 }
20317
20318 if ((ctx == NULL) || (options == NULL)) {
20319 if ((error != NULL) && (error->text_buffer_size > 0)) {
20320 mg_snprintf(NULL,
20321 NULL, /* No truncation check for error buffers */
20322 error->text,
20323 error->text_buffer_size,
20324 "%s",
20325 "Invalid parameters");
20326 }
20327 return -1;
20328 }
20329
20330 if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
20331 if ((error != NULL) && (error->text_buffer_size > 0)) {
20332 mg_snprintf(NULL,
20333 NULL, /* No truncation check for error buffers */
20334 error->text,
20335 error->text_buffer_size,
20336 "%s",
20337 "Server already stopped");
20338 }
20339 return -1;
20340 }
20341
20342 new_dom = (struct mg_domain_context *)
20343 mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
20344
20345 if (!new_dom) {
20346 /* Out of memory */
20347 if ((error != NULL) && (error->text_buffer_size > 0)) {
20348 mg_snprintf(NULL,
20349 NULL, /* No truncation check for error buffers */
20350 error->text,
20351 error->text_buffer_size,
20352 "%s",
20353 "Out or memory");
20354 }
20355 return -6;
20356 }
20357
20358 /* Store options - TODO: unite duplicate code */
20359 while (options && (name = *options++) != NULL) {
20360 if ((idx = get_option_index(name)) == -1) {
20361 mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
20362 if ((error != NULL) && (error->text_buffer_size > 0)) {
20363 mg_snprintf(NULL,
20364 NULL, /* No truncation check for error buffers */
20365 error->text,
20366 error->text_buffer_size,
20367 "Invalid option: %s",
20368 name);
20369 }
20370 mg_free(new_dom);
20371 return -2;
20372 } else if ((value = *options++) == NULL) {
20373 mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
20374 if ((error != NULL) && (error->text_buffer_size > 0)) {
20375 mg_snprintf(NULL,
20376 NULL, /* No truncation check for error buffers */
20377 error->text,
20378 error->text_buffer_size,
20379 "Invalid option value: %s",
20380 name);
20381 }
20382 mg_free(new_dom);
20383 return -2;
20384 }
20385 if (new_dom->config[idx] != NULL) {
20386 /* Duplicate option: Later values overwrite earlier ones. */
20387 mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
20388 mg_free(new_dom->config[idx]);
20389 }
20390 new_dom->config[idx] = mg_strdup_ctx(value, ctx);
20391 DEBUG_TRACE("[%s] -> [%s]", name, value);
20392 }
20393
20394 /* Authentication domain is mandatory */
20395 /* TODO: Maybe use a new option hostname? */
20396 if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
20397 mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
20398 if ((error != NULL) && (error->text_buffer_size > 0)) {
20399 mg_snprintf(NULL,
20400 NULL, /* No truncation check for error buffers */
20401 error->text,
20402 error->text_buffer_size,
20403 "Mandatory option %s missing",
20405 }
20406 mg_free(new_dom);
20407 return -4;
20408 }
20409
20410 /* Set default value if needed. Take the config value from
20411 * ctx as a default value. */
20412 for (i = 0; config_options[i].name != NULL; i++) {
20413 default_value = ctx->dd.config[i];
20414 if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
20415 new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
20416 }
20417 }
20418
20419 new_dom->handlers = NULL;
20420 new_dom->next = NULL;
20421 new_dom->nonce_count = 0;
20422 new_dom->auth_nonce_mask =
20423 (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
20424
20425#if defined(USE_LUA) && defined(USE_WEBSOCKET)
20426 new_dom->shared_lua_websockets = NULL;
20427#endif
20428
20429#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
20430 if (!init_ssl_ctx(ctx, new_dom)) {
20431 /* Init SSL failed */
20432 if ((error != NULL) && (error->text_buffer_size > 0)) {
20433 mg_snprintf(NULL,
20434 NULL, /* No truncation check for error buffers */
20435 error->text,
20436 error->text_buffer_size,
20437 "%s",
20438 "Initializing SSL context failed");
20439 }
20440 mg_free(new_dom);
20441 return -3;
20442 }
20443#endif
20444
20445 /* Add element to linked list. */
20446 mg_lock_context(ctx);
20447
20448 idx = 0;
20449 dom = &(ctx->dd);
20450 for (;;) {
20453 /* Domain collision */
20455 "domain %s already in use",
20456 new_dom->config[AUTHENTICATION_DOMAIN]);
20457 if ((error != NULL) && (error->text_buffer_size > 0)) {
20458 mg_snprintf(NULL,
20459 NULL, /* No truncation check for error buffers */
20460 error->text,
20461 error->text_buffer_size,
20462 "Domain %s specified by %s is already in use",
20463 new_dom->config[AUTHENTICATION_DOMAIN],
20465 }
20466 mg_free(new_dom);
20467 mg_unlock_context(ctx);
20468 return -5;
20469 }
20470
20471 /* Count number of domains */
20472 idx++;
20473
20474 if (dom->next == NULL) {
20475 dom->next = new_dom;
20476 break;
20477 }
20478 dom = dom->next;
20479 }
20480
20481 mg_unlock_context(ctx);
20482
20483 /* Return domain number */
20484 return idx;
20485}
20486
20487
20488int
20489mg_start_domain(struct mg_context *ctx, const char **options)
20490{
20491 return mg_start_domain2(ctx, options, NULL);
20492}
20493
20494
20495/* Feature check API function */
20496unsigned
20497mg_check_feature(unsigned feature)
20498{
20499 static const unsigned feature_set = 0
20500 /* Set bits for available features according to API documentation.
20501 * This bit mask is created at compile time, according to the active
20502 * preprocessor defines. It is a single const value at runtime. */
20503#if !defined(NO_FILES)
20505#endif
20506#if !defined(NO_SSL) || defined(USE_MBEDTLS)
20508#endif
20509#if !defined(NO_CGI)
20511#endif
20512#if defined(USE_IPV6)
20514#endif
20515#if defined(USE_WEBSOCKET)
20517#endif
20518#if defined(USE_LUA)
20520#endif
20521#if defined(USE_DUKTAPE)
20523#endif
20524#if !defined(NO_CACHING)
20526#endif
20527#if defined(USE_SERVER_STATS)
20529#endif
20530#if defined(USE_ZLIB)
20532#endif
20533#if defined(USE_HTTP2)
20535#endif
20536#if defined(USE_X_DOM_SOCKET)
20538#endif
20539
20540 /* Set some extra bits not defined in the API documentation.
20541 * These bits may change without further notice. */
20542#if defined(MG_LEGACY_INTERFACE)
20543 | 0x80000000u
20544#endif
20545#if defined(MG_EXPERIMENTAL_INTERFACES)
20546 | 0x40000000u
20547#endif
20548#if !defined(NO_RESPONSE_BUFFERING)
20549 | 0x20000000u
20550#endif
20551#if defined(MEMORY_DEBUGGING)
20552 | 0x10000000u
20553#endif
20554 ;
20555 return (feature & feature_set);
20556}
20557
20558
20559static size_t
20560mg_str_append(char **dst, char *end, const char *src)
20561{
20562 size_t len = strlen(src);
20563 if (*dst != end) {
20564 /* Append src if enough space, or close dst. */
20565 if ((size_t)(end - *dst) > len) {
20566 strcpy(*dst, src);
20567 *dst += len;
20568 } else {
20569 *dst = end;
20570 }
20571 }
20572 return len;
20573}
20574
20575
20576/* Get system information. It can be printed or stored by the caller.
20577 * Return the size of available information. */
20578int
20579mg_get_system_info(char *buffer, int buflen)
20580{
20581 char *end, *append_eoobj = NULL, block[256];
20582 size_t system_info_length = 0;
20583
20584#if defined(_WIN32)
20585 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
20586#else
20587 static const char eol[] = "\n", eoobj[] = "\n}\n";
20588#endif
20589
20590 if ((buffer == NULL) || (buflen < 1)) {
20591 buflen = 0;
20592 end = buffer;
20593 } else {
20594 *buffer = 0;
20595 end = buffer + buflen;
20596 }
20597 if (buflen > (int)(sizeof(eoobj) - 1)) {
20598 /* has enough space to append eoobj */
20599 append_eoobj = buffer;
20600 if (end) {
20601 end -= sizeof(eoobj) - 1;
20602 }
20603 }
20604
20605 system_info_length += mg_str_append(&buffer, end, "{");
20606
20607 /* Server version */
20608 {
20609 const char *version = mg_version();
20610 mg_snprintf(NULL,
20611 NULL,
20612 block,
20613 sizeof(block),
20614 "%s\"version\" : \"%s\"",
20615 eol,
20616 version);
20617 system_info_length += mg_str_append(&buffer, end, block);
20618 }
20619
20620 /* System info */
20621 {
20622#if defined(_WIN32)
20623 DWORD dwVersion = 0;
20624 DWORD dwMajorVersion = 0;
20625 DWORD dwMinorVersion = 0;
20626 SYSTEM_INFO si;
20627
20628 GetSystemInfo(&si);
20629
20630#if defined(_MSC_VER)
20631#pragma warning(push)
20632 /* GetVersion was declared deprecated */
20633#pragma warning(disable : 4996)
20634#endif
20635 dwVersion = GetVersion();
20636#if defined(_MSC_VER)
20637#pragma warning(pop)
20638#endif
20639
20640 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
20641 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
20642
20643 mg_snprintf(NULL,
20644 NULL,
20645 block,
20646 sizeof(block),
20647 ",%s\"os\" : \"Windows %u.%u\"",
20648 eol,
20649 (unsigned)dwMajorVersion,
20650 (unsigned)dwMinorVersion);
20651 system_info_length += mg_str_append(&buffer, end, block);
20652
20653 mg_snprintf(NULL,
20654 NULL,
20655 block,
20656 sizeof(block),
20657 ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
20658 eol,
20659 (unsigned)si.wProcessorArchitecture,
20660 (unsigned)si.dwNumberOfProcessors,
20661 (unsigned)si.dwActiveProcessorMask);
20662 system_info_length += mg_str_append(&buffer, end, block);
20663#elif defined(__ZEPHYR__)
20664 mg_snprintf(NULL,
20665 NULL,
20666 block,
20667 sizeof(block),
20668 ",%s\"os\" : \"%s %s\"",
20669 eol,
20670 "Zephyr OS",
20671 ZEPHYR_VERSION);
20672 system_info_length += mg_str_append(&buffer, end, block);
20673#else
20674 struct utsname name;
20675 memset(&name, 0, sizeof(name));
20676 uname(&name);
20677
20678 mg_snprintf(NULL,
20679 NULL,
20680 block,
20681 sizeof(block),
20682 ",%s\"os\" : \"%s %s (%s) - %s\"",
20683 eol,
20684 name.sysname,
20685 name.version,
20686 name.release,
20687 name.machine);
20688 system_info_length += mg_str_append(&buffer, end, block);
20689#endif
20690 }
20691
20692 /* Features */
20693 {
20694 mg_snprintf(NULL,
20695 NULL,
20696 block,
20697 sizeof(block),
20698 ",%s\"features\" : %lu"
20699 ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
20700 eol,
20701 (unsigned long)mg_check_feature(0xFFFFFFFFu),
20702 eol,
20703 mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
20704 mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
20705 mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
20706 mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
20708 : "",
20709 mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
20710 mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
20711 mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
20712 mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
20713 system_info_length += mg_str_append(&buffer, end, block);
20714
20715#if defined(USE_LUA)
20716 mg_snprintf(NULL,
20717 NULL,
20718 block,
20719 sizeof(block),
20720 ",%s\"lua_version\" : \"%u (%s)\"",
20721 eol,
20722 (unsigned)LUA_VERSION_NUM,
20723 LUA_RELEASE);
20724 system_info_length += mg_str_append(&buffer, end, block);
20725#endif
20726#if defined(USE_DUKTAPE)
20727 mg_snprintf(NULL,
20728 NULL,
20729 block,
20730 sizeof(block),
20731 ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
20732 eol,
20733 (unsigned)DUK_VERSION / 10000,
20734 ((unsigned)DUK_VERSION / 100) % 100,
20735 (unsigned)DUK_VERSION % 100);
20736 system_info_length += mg_str_append(&buffer, end, block);
20737#endif
20738 }
20739
20740 /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
20741 {
20742#if defined(BUILD_DATE)
20743 const char *bd = BUILD_DATE;
20744#else
20745#if defined(GCC_DIAGNOSTIC)
20746#if GCC_VERSION >= 40900
20747#pragma GCC diagnostic push
20748 /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
20749 * does not work in some versions. If "BUILD_DATE" is defined to some
20750 * string, it is used instead of __DATE__. */
20751#pragma GCC diagnostic ignored "-Wdate-time"
20752#endif
20753#endif
20754 const char *bd = __DATE__;
20755#if defined(GCC_DIAGNOSTIC)
20756#if GCC_VERSION >= 40900
20757#pragma GCC diagnostic pop
20758#endif
20759#endif
20760#endif
20761
20763 NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
20764
20765 system_info_length += mg_str_append(&buffer, end, block);
20766 }
20767
20768
20769 /* Compiler information */
20770 /* http://sourceforge.net/p/predef/wiki/Compilers/ */
20771 {
20772#if defined(_MSC_VER)
20773 mg_snprintf(NULL,
20774 NULL,
20775 block,
20776 sizeof(block),
20777 ",%s\"compiler\" : \"MSC: %u (%u)\"",
20778 eol,
20779 (unsigned)_MSC_VER,
20780 (unsigned)_MSC_FULL_VER);
20781 system_info_length += mg_str_append(&buffer, end, block);
20782#elif defined(__MINGW64__)
20783 mg_snprintf(NULL,
20784 NULL,
20785 block,
20786 sizeof(block),
20787 ",%s\"compiler\" : \"MinGW64: %u.%u\"",
20788 eol,
20789 (unsigned)__MINGW64_VERSION_MAJOR,
20790 (unsigned)__MINGW64_VERSION_MINOR);
20791 system_info_length += mg_str_append(&buffer, end, block);
20792 mg_snprintf(NULL,
20793 NULL,
20794 block,
20795 sizeof(block),
20796 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20797 eol,
20798 (unsigned)__MINGW32_MAJOR_VERSION,
20799 (unsigned)__MINGW32_MINOR_VERSION);
20800 system_info_length += mg_str_append(&buffer, end, block);
20801#elif defined(__MINGW32__)
20802 mg_snprintf(NULL,
20803 NULL,
20804 block,
20805 sizeof(block),
20806 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20807 eol,
20808 (unsigned)__MINGW32_MAJOR_VERSION,
20809 (unsigned)__MINGW32_MINOR_VERSION);
20810 system_info_length += mg_str_append(&buffer, end, block);
20811#elif defined(__clang__)
20812 mg_snprintf(NULL,
20813 NULL,
20814 block,
20815 sizeof(block),
20816 ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
20817 eol,
20818 __clang_major__,
20819 __clang_minor__,
20820 __clang_patchlevel__,
20821 __clang_version__);
20822 system_info_length += mg_str_append(&buffer, end, block);
20823#elif defined(__GNUC__)
20824 mg_snprintf(NULL,
20825 NULL,
20826 block,
20827 sizeof(block),
20828 ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
20829 eol,
20830 (unsigned)__GNUC__,
20831 (unsigned)__GNUC_MINOR__,
20832 (unsigned)__GNUC_PATCHLEVEL__);
20833 system_info_length += mg_str_append(&buffer, end, block);
20834#elif defined(__INTEL_COMPILER)
20835 mg_snprintf(NULL,
20836 NULL,
20837 block,
20838 sizeof(block),
20839 ",%s\"compiler\" : \"Intel C/C++: %u\"",
20840 eol,
20841 (unsigned)__INTEL_COMPILER);
20842 system_info_length += mg_str_append(&buffer, end, block);
20843#elif defined(__BORLANDC__)
20844 mg_snprintf(NULL,
20845 NULL,
20846 block,
20847 sizeof(block),
20848 ",%s\"compiler\" : \"Borland C: 0x%x\"",
20849 eol,
20850 (unsigned)__BORLANDC__);
20851 system_info_length += mg_str_append(&buffer, end, block);
20852#elif defined(__SUNPRO_C)
20853 mg_snprintf(NULL,
20854 NULL,
20855 block,
20856 sizeof(block),
20857 ",%s\"compiler\" : \"Solaris: 0x%x\"",
20858 eol,
20859 (unsigned)__SUNPRO_C);
20860 system_info_length += mg_str_append(&buffer, end, block);
20861#else
20862 mg_snprintf(NULL,
20863 NULL,
20864 block,
20865 sizeof(block),
20866 ",%s\"compiler\" : \"other\"",
20867 eol);
20868 system_info_length += mg_str_append(&buffer, end, block);
20869#endif
20870 }
20871
20872 /* Determine 32/64 bit data mode.
20873 * see https://en.wikipedia.org/wiki/64-bit_computing */
20874 {
20875 mg_snprintf(NULL,
20876 NULL,
20877 block,
20878 sizeof(block),
20879 ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
20880 "char:%u/%u, "
20881 "ptr:%u, size:%u, time:%u\"",
20882 eol,
20883 (unsigned)sizeof(short),
20884 (unsigned)sizeof(int),
20885 (unsigned)sizeof(long),
20886 (unsigned)sizeof(long long),
20887 (unsigned)sizeof(float),
20888 (unsigned)sizeof(double),
20889 (unsigned)sizeof(long double),
20890 (unsigned)sizeof(char),
20891 (unsigned)sizeof(wchar_t),
20892 (unsigned)sizeof(void *),
20893 (unsigned)sizeof(size_t),
20894 (unsigned)sizeof(time_t));
20895 system_info_length += mg_str_append(&buffer, end, block);
20896 }
20897
20898 /* Terminate string */
20899 if (append_eoobj) {
20900 strcat(append_eoobj, eoobj);
20901 }
20902 system_info_length += sizeof(eoobj) - 1;
20903
20904 return (int)system_info_length;
20905}
20906
20907
20908/* Get context information. It can be printed or stored by the caller.
20909 * Return the size of available information. */
20910int
20911mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
20912{
20913#if defined(USE_SERVER_STATS)
20914 char *end, *append_eoobj = NULL, block[256];
20915 size_t context_info_length = 0;
20916
20917#if defined(_WIN32)
20918 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
20919#else
20920 static const char eol[] = "\n", eoobj[] = "\n}\n";
20921#endif
20922 struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
20923
20924 if ((buffer == NULL) || (buflen < 1)) {
20925 buflen = 0;
20926 end = buffer;
20927 } else {
20928 *buffer = 0;
20929 end = buffer + buflen;
20930 }
20931 if (buflen > (int)(sizeof(eoobj) - 1)) {
20932 /* has enough space to append eoobj */
20933 append_eoobj = buffer;
20934 end -= sizeof(eoobj) - 1;
20935 }
20936
20937 context_info_length += mg_str_append(&buffer, end, "{");
20938
20939 if (ms) { /* <-- should be always true */
20940 /* Memory information */
20941 int blockCount = (int)ms->blockCount;
20942 int64_t totalMemUsed = ms->totalMemUsed;
20943 int64_t maxMemUsed = ms->maxMemUsed;
20944 if (totalMemUsed > maxMemUsed) {
20945 maxMemUsed = totalMemUsed;
20946 }
20947
20948 mg_snprintf(NULL,
20949 NULL,
20950 block,
20951 sizeof(block),
20952 "%s\"memory\" : {%s"
20953 "\"blocks\" : %i,%s"
20954 "\"used\" : %" INT64_FMT ",%s"
20955 "\"maxUsed\" : %" INT64_FMT "%s"
20956 "}",
20957 eol,
20958 eol,
20959 blockCount,
20960 eol,
20961 totalMemUsed,
20962 eol,
20963 maxMemUsed,
20964 eol);
20965 context_info_length += mg_str_append(&buffer, end, block);
20966 }
20967
20968 if (ctx) {
20969 /* Declare all variables at begin of the block, to comply
20970 * with old C standards. */
20971 char start_time_str[64] = {0};
20972 char now_str[64] = {0};
20973 time_t start_time = ctx->start_time;
20974 time_t now = time(NULL);
20975 int64_t total_data_read, total_data_written;
20976 int active_connections = (int)ctx->active_connections;
20977 int max_active_connections = (int)ctx->max_active_connections;
20978 int total_connections = (int)ctx->total_connections;
20979 if (active_connections > max_active_connections) {
20980 max_active_connections = active_connections;
20981 }
20982 if (active_connections > total_connections) {
20983 total_connections = active_connections;
20984 }
20985
20986 /* Connections information */
20987 mg_snprintf(NULL,
20988 NULL,
20989 block,
20990 sizeof(block),
20991 ",%s\"connections\" : {%s"
20992 "\"active\" : %i,%s"
20993 "\"maxActive\" : %i,%s"
20994 "\"total\" : %i%s"
20995 "}",
20996 eol,
20997 eol,
20998 active_connections,
20999 eol,
21000 max_active_connections,
21001 eol,
21002 total_connections,
21003 eol);
21004 context_info_length += mg_str_append(&buffer, end, block);
21005
21006 /* Queue information */
21007#if !defined(ALTERNATIVE_QUEUE)
21008 mg_snprintf(NULL,
21009 NULL,
21010 block,
21011 sizeof(block),
21012 ",%s\"queue\" : {%s"
21013 "\"length\" : %i,%s"
21014 "\"filled\" : %i,%s"
21015 "\"maxFilled\" : %i,%s"
21016 "\"full\" : %s%s"
21017 "}",
21018 eol,
21019 eol,
21020 ctx->sq_size,
21021 eol,
21022 ctx->sq_head - ctx->sq_tail,
21023 eol,
21024 ctx->sq_max_fill,
21025 eol,
21026 (ctx->sq_blocked ? "true" : "false"),
21027 eol);
21028 context_info_length += mg_str_append(&buffer, end, block);
21029#endif
21030
21031 /* Requests information */
21032 mg_snprintf(NULL,
21033 NULL,
21034 block,
21035 sizeof(block),
21036 ",%s\"requests\" : {%s"
21037 "\"total\" : %lu%s"
21038 "}",
21039 eol,
21040 eol,
21041 (unsigned long)ctx->total_requests,
21042 eol);
21043 context_info_length += mg_str_append(&buffer, end, block);
21044
21045 /* Data information */
21046 total_data_read =
21047 mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
21048 total_data_written =
21049 mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
21050 mg_snprintf(NULL,
21051 NULL,
21052 block,
21053 sizeof(block),
21054 ",%s\"data\" : {%s"
21055 "\"read\" : %" INT64_FMT ",%s"
21056 "\"written\" : %" INT64_FMT "%s"
21057 "}",
21058 eol,
21059 eol,
21060 total_data_read,
21061 eol,
21062 total_data_written,
21063 eol);
21064 context_info_length += mg_str_append(&buffer, end, block);
21065
21066 /* Execution time information */
21067 gmt_time_string(start_time_str,
21068 sizeof(start_time_str) - 1,
21069 &start_time);
21070 gmt_time_string(now_str, sizeof(now_str) - 1, &now);
21071
21072 mg_snprintf(NULL,
21073 NULL,
21074 block,
21075 sizeof(block),
21076 ",%s\"time\" : {%s"
21077 "\"uptime\" : %.0f,%s"
21078 "\"start\" : \"%s\",%s"
21079 "\"now\" : \"%s\"%s"
21080 "}",
21081 eol,
21082 eol,
21083 difftime(now, start_time),
21084 eol,
21085 start_time_str,
21086 eol,
21087 now_str,
21088 eol);
21089 context_info_length += mg_str_append(&buffer, end, block);
21090 }
21091
21092 /* Terminate string */
21093 if (append_eoobj) {
21094 strcat(append_eoobj, eoobj);
21095 }
21096 context_info_length += sizeof(eoobj) - 1;
21097
21098 return (int)context_info_length;
21099#else
21100 (void)ctx;
21101 if ((buffer != NULL) && (buflen > 0)) {
21102 *buffer = 0;
21103 }
21104 return 0;
21105#endif
21106}
21107
21108
21109void
21111{
21112 /* https://github.com/civetweb/civetweb/issues/727 */
21113 if (conn != NULL) {
21114 conn->must_close = 1;
21115 }
21116}
21117
21118
21119#if defined(MG_EXPERIMENTAL_INTERFACES)
21120/* Get connection information. It can be printed or stored by the caller.
21121 * Return the size of available information. */
21122int
21123mg_get_connection_info(const struct mg_context *ctx,
21124 int idx,
21125 char *buffer,
21126 int buflen)
21127{
21128 const struct mg_connection *conn;
21129 const struct mg_request_info *ri;
21130 char *end, *append_eoobj = NULL, block[256];
21131 size_t connection_info_length = 0;
21132 int state = 0;
21133 const char *state_str = "unknown";
21134
21135#if defined(_WIN32)
21136 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
21137#else
21138 static const char eol[] = "\n", eoobj[] = "\n}\n";
21139#endif
21140
21141 if ((buffer == NULL) || (buflen < 1)) {
21142 buflen = 0;
21143 end = buffer;
21144 } else {
21145 *buffer = 0;
21146 end = buffer + buflen;
21147 }
21148 if (buflen > (int)(sizeof(eoobj) - 1)) {
21149 /* has enough space to append eoobj */
21150 append_eoobj = buffer;
21151 end -= sizeof(eoobj) - 1;
21152 }
21153
21154 if ((ctx == NULL) || (idx < 0)) {
21155 /* Parameter error */
21156 return 0;
21157 }
21158
21159 if ((unsigned)idx >= ctx->cfg_worker_threads) {
21160 /* Out of range */
21161 return 0;
21162 }
21163
21164 /* Take connection [idx]. This connection is not locked in
21165 * any way, so some other thread might use it. */
21166 conn = (ctx->worker_connections) + idx;
21167
21168 /* Initialize output string */
21169 connection_info_length += mg_str_append(&buffer, end, "{");
21170
21171 /* Init variables */
21172 ri = &(conn->request_info);
21173
21174#if defined(USE_SERVER_STATS)
21175 state = conn->conn_state;
21176
21177 /* State as string */
21178 switch (state) {
21179 case 0:
21180 state_str = "undefined";
21181 break;
21182 case 1:
21183 state_str = "not used";
21184 break;
21185 case 2:
21186 state_str = "init";
21187 break;
21188 case 3:
21189 state_str = "ready";
21190 break;
21191 case 4:
21192 state_str = "processing";
21193 break;
21194 case 5:
21195 state_str = "processed";
21196 break;
21197 case 6:
21198 state_str = "to close";
21199 break;
21200 case 7:
21201 state_str = "closing";
21202 break;
21203 case 8:
21204 state_str = "closed";
21205 break;
21206 case 9:
21207 state_str = "done";
21208 break;
21209 }
21210#endif
21211
21212 /* Connection info */
21213 if ((state >= 3) && (state < 9)) {
21214 mg_snprintf(NULL,
21215 NULL,
21216 block,
21217 sizeof(block),
21218 "%s\"connection\" : {%s"
21219 "\"remote\" : {%s"
21220 "\"protocol\" : \"%s\",%s"
21221 "\"addr\" : \"%s\",%s"
21222 "\"port\" : %u%s"
21223 "},%s"
21224 "\"handled_requests\" : %u%s"
21225 "}",
21226 eol,
21227 eol,
21228 eol,
21229 get_proto_name(conn),
21230 eol,
21231 ri->remote_addr,
21232 eol,
21233 ri->remote_port,
21234 eol,
21235 eol,
21236 conn->handled_requests,
21237 eol);
21238 connection_info_length += mg_str_append(&buffer, end, block);
21239 }
21240
21241 /* Request info */
21242 if ((state >= 4) && (state < 6)) {
21243 mg_snprintf(NULL,
21244 NULL,
21245 block,
21246 sizeof(block),
21247 "%s%s\"request_info\" : {%s"
21248 "\"method\" : \"%s\",%s"
21249 "\"uri\" : \"%s\",%s"
21250 "\"query\" : %s%s%s%s"
21251 "}",
21252 (connection_info_length > 1 ? "," : ""),
21253 eol,
21254 eol,
21255 ri->request_method,
21256 eol,
21257 ri->request_uri,
21258 eol,
21259 ri->query_string ? "\"" : "",
21260 ri->query_string ? ri->query_string : "null",
21261 ri->query_string ? "\"" : "",
21262 eol);
21263 connection_info_length += mg_str_append(&buffer, end, block);
21264 }
21265
21266 /* Execution time information */
21267 if ((state >= 2) && (state < 9)) {
21268 char start_time_str[64] = {0};
21269 char close_time_str[64] = {0};
21270 time_t start_time = conn->conn_birth_time;
21271 time_t close_time = 0;
21272 double time_diff;
21273
21274 gmt_time_string(start_time_str,
21275 sizeof(start_time_str) - 1,
21276 &start_time);
21277#if defined(USE_SERVER_STATS)
21278 close_time = conn->conn_close_time;
21279#endif
21280 if (close_time != 0) {
21281 time_diff = difftime(close_time, start_time);
21282 gmt_time_string(close_time_str,
21283 sizeof(close_time_str) - 1,
21284 &close_time);
21285 } else {
21286 time_t now = time(NULL);
21287 time_diff = difftime(now, start_time);
21288 close_time_str[0] = 0; /* or use "now" ? */
21289 }
21290
21291 mg_snprintf(NULL,
21292 NULL,
21293 block,
21294 sizeof(block),
21295 "%s%s\"time\" : {%s"
21296 "\"uptime\" : %.0f,%s"
21297 "\"start\" : \"%s\",%s"
21298 "\"closed\" : \"%s\"%s"
21299 "}",
21300 (connection_info_length > 1 ? "," : ""),
21301 eol,
21302 eol,
21303 time_diff,
21304 eol,
21305 start_time_str,
21306 eol,
21307 close_time_str,
21308 eol);
21309 connection_info_length += mg_str_append(&buffer, end, block);
21310 }
21311
21312 /* Remote user name */
21313 if ((ri->remote_user) && (state < 9)) {
21314 mg_snprintf(NULL,
21315 NULL,
21316 block,
21317 sizeof(block),
21318 "%s%s\"user\" : {%s"
21319 "\"name\" : \"%s\",%s"
21320 "}",
21321 (connection_info_length > 1 ? "," : ""),
21322 eol,
21323 eol,
21324 ri->remote_user,
21325 eol);
21326 connection_info_length += mg_str_append(&buffer, end, block);
21327 }
21328
21329 /* Data block */
21330 if (state >= 3) {
21331 mg_snprintf(NULL,
21332 NULL,
21333 block,
21334 sizeof(block),
21335 "%s%s\"data\" : {%s"
21336 "\"read\" : %" INT64_FMT ",%s"
21337 "\"written\" : %" INT64_FMT "%s"
21338 "}",
21339 (connection_info_length > 1 ? "," : ""),
21340 eol,
21341 eol,
21342 conn->consumed_content,
21343 eol,
21344 conn->num_bytes_sent,
21345 eol);
21346 connection_info_length += mg_str_append(&buffer, end, block);
21347 }
21348
21349 /* State */
21350 mg_snprintf(NULL,
21351 NULL,
21352 block,
21353 sizeof(block),
21354 "%s%s\"state\" : \"%s\"",
21355 (connection_info_length > 1 ? "," : ""),
21356 eol,
21357 state_str);
21358 connection_info_length += mg_str_append(&buffer, end, block);
21359
21360 /* Terminate string */
21361 if (append_eoobj) {
21362 strcat(append_eoobj, eoobj);
21363 }
21364 connection_info_length += sizeof(eoobj) - 1;
21365
21366 return (int)connection_info_length;
21367}
21368#endif
21369
21370
21371/* Initialize this library. This function does not need to be thread safe.
21372 */
21373unsigned
21374mg_init_library(unsigned features)
21375{
21376 unsigned features_to_init = mg_check_feature(features & 0xFFu);
21377 unsigned features_inited = features_to_init;
21378
21379 if (mg_init_library_called <= 0) {
21380 /* Not initialized yet */
21381 if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
21382 return 0;
21383 }
21384 }
21385
21387
21388 if (mg_init_library_called <= 0) {
21389#if defined(_WIN32)
21390 int file_mutex_init = 1;
21391 int wsa = 1;
21392#else
21393 int mutexattr_init = 1;
21394#endif
21395 int failed = 1;
21396 int key_create = pthread_key_create(&sTlsKey, tls_dtor);
21397
21398 if (key_create == 0) {
21399#if defined(_WIN32)
21400 file_mutex_init =
21401 pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
21402 if (file_mutex_init == 0) {
21403 /* Start WinSock */
21404 WSADATA data;
21405 failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
21406 }
21407#else
21408 mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
21409 if (mutexattr_init == 0) {
21410 failed = pthread_mutexattr_settype(&pthread_mutex_attr,
21411 PTHREAD_MUTEX_RECURSIVE);
21412 }
21413#endif
21414 }
21415
21416
21417 if (failed) {
21418#if defined(_WIN32)
21419 if (wsa == 0) {
21420 (void)WSACleanup();
21421 }
21422 if (file_mutex_init == 0) {
21423 (void)pthread_mutex_destroy(&global_log_file_lock);
21424 }
21425#else
21426 if (mutexattr_init == 0) {
21427 (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
21428 }
21429#endif
21430 if (key_create == 0) {
21431 (void)pthread_key_delete(sTlsKey);
21432 }
21434 (void)pthread_mutex_destroy(&global_lock_mutex);
21435 return 0;
21436 }
21437
21438#if defined(USE_LUA)
21439 lua_init_optional_libraries();
21440#endif
21441 }
21442
21444
21445#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
21446 || defined(OPENSSL_API_3_0)) \
21447 && !defined(NO_SSL)
21448 if (features_to_init & MG_FEATURES_SSL) {
21449 if (!mg_openssl_initialized) {
21450 char ebuf[128];
21451 if (initialize_openssl(ebuf, sizeof(ebuf))) {
21452 mg_openssl_initialized = 1;
21453 } else {
21454 (void)ebuf;
21455 DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
21456 features_inited &= ~((unsigned)(MG_FEATURES_SSL));
21457 }
21458 } else {
21459 /* ssl already initialized */
21460 }
21461 }
21462#endif
21463
21465 if (mg_init_library_called <= 0) {
21467 } else {
21469 }
21471
21472 return features_inited;
21473}
21474
21475
21476/* Un-initialize this library. */
21477unsigned
21479{
21480 if (mg_init_library_called <= 0) {
21481 return 0;
21482 }
21483
21485
21487 if (mg_init_library_called == 0) {
21488#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
21489 if (mg_openssl_initialized) {
21491 mg_openssl_initialized = 0;
21492 }
21493#endif
21494
21495#if defined(_WIN32)
21496 (void)WSACleanup();
21497 (void)pthread_mutex_destroy(&global_log_file_lock);
21498#else
21499 (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
21500#endif
21501
21502 (void)pthread_key_delete(sTlsKey);
21503
21504#if defined(USE_LUA)
21505 lua_exit_optional_libraries();
21506#endif
21507
21509 (void)pthread_mutex_destroy(&global_lock_mutex);
21510 return 1;
21511 }
21512
21514 return 1;
21515}
21516
21517
21518/* End of civetweb.c */
static int esc(const char **)
Map escape sequences into their equivalent symbols.
Definition Match.cxx:438
#define d(i)
Definition RSha256.hxx:102
#define b(i)
Definition RSha256.hxx:100
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define s1(x)
Definition RSha256.hxx:91
#define h(i)
Definition RSha256.hxx:106
#define e(i)
Definition RSha256.hxx:103
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
static unsigned int total
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t option
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t mask
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void on
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t attr
Option_t Option_t TPoint TPoint const char mode
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t src
char name[80]
Definition TGX11.cxx:110
#define INVALID_HANDLE_VALUE
Definition TMapFile.cxx:84
R__EXTERN C unsigned int sleep(unsigned int seconds)
static void process_new_connection(struct mg_connection *conn)
Definition civetweb.c:18517
static int is_authorized_for_put(struct mg_connection *conn)
Definition civetweb.c:8786
static int consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
Definition civetweb.c:18773
static int parse_http_request(char *buf, int len, struct mg_request_info *ri)
Definition civetweb.c:10606
void mg_send_mime_file2(struct mg_connection *conn, const char *path, const char *mime_type, const char *additional_headers)
Definition civetweb.c:10222
#define mg_readdir(x)
Definition civetweb.c:920
static pthread_key_t sTlsKey
Definition civetweb.c:1572
static int modify_passwords_file(const char *fname, const char *domain, const char *user, const char *pass, const char *ha1)
Definition civetweb.c:8807
static void sockaddr_to_string(char *buf, size_t len, const union usa *usa)
Definition civetweb.c:3257
static void open_auth_file(struct mg_connection *conn, const char *path, struct mg_file *filep)
Definition civetweb.c:8276
int mg_strncasecmp(const char *s1, const char *s2, size_t len)
Definition civetweb.c:2984
#define IP_ADDR_STR_LEN
Definition civetweb.c:1724
static int check_authorization(struct mg_connection *conn, const char *path)
Definition civetweb.c:8669
#define vsnprintf_impl
Definition civetweb.c:894
#define HEXTOI(x)
#define mg_malloc_ctx(a, c)
Definition civetweb.c:1494
static void redirect_to_https_port(struct mg_connection *conn, int port)
Definition civetweb.c:13544
static int should_switch_to_protocol(const struct mg_connection *conn)
Definition civetweb.c:13231
void mg_unlock_connection(struct mg_connection *conn)
Definition civetweb.c:12315
static void mkcol(struct mg_connection *conn, const char *path)
Definition civetweb.c:11602
static void remove_bad_file(const struct mg_connection *conn, const char *path)
Definition civetweb.c:10305
const struct mg_option * mg_get_valid_options(void)
Definition civetweb.c:2798
static int mg_path_suspicious(const struct mg_connection *conn, const char *path)
Definition civetweb.c:2836
const char * mime_type
Definition civetweb.c:8028
static int set_non_blocking_mode(SOCKET sock)
Definition civetweb.c:5847
static void ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
Definition civetweb.c:15911
const char * proto
Definition civetweb.c:17536
int mg_send_http_error(struct mg_connection *conn, int status, const char *fmt,...)
Definition civetweb.c:4537
static const char * get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
Definition civetweb.c:17623
static void mg_cry_internal_impl(const struct mg_connection *conn, const char *func, unsigned line, const char *fmt, va_list ap)
Definition civetweb.c:3349
void mg_lock_context(struct mg_context *ctx)
Definition civetweb.c:12323
#define MAX_WORKER_THREADS
Definition civetweb.c:463
@ PROTOCOL_TYPE_HTTP1
Definition civetweb.c:2430
@ PROTOCOL_TYPE_HTTP2
Definition civetweb.c:2432
@ PROTOCOL_TYPE_WEBSOCKET
Definition civetweb.c:2431
static void put_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:11671
static void do_ssi_exec(struct mg_connection *conn, char *tag)
Definition civetweb.c:11946
static void tls_dtor(void *key)
Definition civetweb.c:15535
#define realloc
Definition civetweb.c:1538
const void * SOCK_OPT_TYPE
Definition civetweb.c:860
static int header_has_option(const char *header, const char *option)
Definition civetweb.c:3903
int mg_send_http_redirect(struct mg_connection *conn, const char *target_url, int redirect_code)
Definition civetweb.c:4592
int mg_get_cookie(const char *cookie_header, const char *var_name, char *dst, size_t dst_size)
Definition civetweb.c:7159
static int ssl_get_client_cert_info(const struct mg_connection *conn, struct mg_client_cert *client_cert)
Definition civetweb.c:15834
#define mg_cry_ctx_internal(ctx, fmt,...)
Definition civetweb.c:2551
@ CONTEXT_WS_CLIENT
Definition civetweb.c:2248
@ CONTEXT_INVALID
Definition civetweb.c:2245
@ CONTEXT_SERVER
Definition civetweb.c:2246
@ CONTEXT_HTTP_CLIENT
Definition civetweb.c:2247
static void mg_snprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, const char *fmt,...)
Definition civetweb.c:3108
#define mg_opendir(conn, x)
Definition civetweb.c:918
static char * mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
Definition civetweb.c:3012
static int put_dir(struct mg_connection *conn, const char *path)
Definition civetweb.c:10268
#define UINT64_FMT
Definition civetweb.c:924
static void send_static_cache_header(struct mg_connection *conn)
Definition civetweb.c:4070
static void handle_cgi_request(struct mg_connection *conn, const char *prog, unsigned char cgi_config_idx)
Definition civetweb.c:11279
static ptrdiff_t mg_atomic_dec(volatile ptrdiff_t *addr)
Definition civetweb.c:1141
#define INVALID_SOCKET
Definition civetweb.c:922
size_t ext_len
Definition civetweb.c:8027
static int print_dav_dir_entry(struct de *de, void *data)
Definition civetweb.c:12248
static void delete_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:11798
#define mg_calloc_ctx(a, b, c)
Definition civetweb.c:1495
struct mg_connection * mg_connect_websocket_client_secure(const struct mg_client_options *client_options, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
Definition civetweb.c:18395
#define mg_closedir(x)
Definition civetweb.c:919
#define free
Definition civetweb.c:1539
int mg_get_server_ports(const struct mg_context *ctx, int size, struct mg_server_port *ports)
Definition civetweb.c:3213
static ptrdiff_t mg_atomic_inc(volatile ptrdiff_t *addr)
Definition civetweb.c:1118
int mg_printf(struct mg_connection *conn, const char *fmt,...)
Definition civetweb.c:6937
static int abort_cgi_process(void *data)
Definition civetweb.c:11244
static int should_keep_alive(const struct mg_connection *conn)
Definition civetweb.c:3980
static __inline void * mg_malloc(size_t a)
Definition civetweb.c:1471
static int mg_fopen(const struct mg_connection *conn, const char *path, int mode, struct mg_file *filep)
Definition civetweb.c:2880
void mg_disable_connection_keep_alive(struct mg_connection *conn)
Definition civetweb.c:21110
static void mg_global_lock(void)
Definition civetweb.c:1091
static void handle_static_file_request(struct mg_connection *conn, const char *path, struct mg_file *filep, const char *mime_type, const char *additional_headers)
Definition civetweb.c:9884
static int ssl_use_pem_file(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *pem, const char *chain)
Definition civetweb.c:16154
static const char * ssl_error(void)
Definition civetweb.c:15799
static int must_hide_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:9436
static void log_access(const struct mg_connection *)
Definition civetweb.c:15285
const char * extension
Definition civetweb.c:8026
struct mg_connection * mg_connect_client_secure(const struct mg_client_options *client_options, char *error_buffer, size_t error_buffer_size)
Definition civetweb.c:17414
#define ERRNO
Definition civetweb.c:921
#define mg_remove(conn, x)
Definition civetweb.c:916
int mg_send_http_ok(struct mg_connection *conn, const char *mime_type, long long content_length)
Definition civetweb.c:4551
static void close_all_listening_sockets(struct mg_context *ctx)
Definition civetweb.c:14678
#define closesocket(a)
Definition civetweb.c:914
void mg_send_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:10206
static void send_authorization_request(struct mg_connection *conn, const char *realm)
Definition civetweb.c:8725
static pid_t spawn_process(struct mg_connection *conn, const char *prog, char *envblk, char *envp[], int fdin[2], int fdout[2], int fderr[2], const char *dir, unsigned char cgi_config_idx)
Definition civetweb.c:5739
static int check_password(const char *method, const char *ha1, const char *uri, const char *nonce, const char *nc, const char *cnonce, const char *qop, const char *response)
Definition civetweb.c:8231
static int check_acl(struct mg_context *phys_ctx, const union usa *sa)
Definition civetweb.c:15443
static const struct mg_option config_options[]
Definition civetweb.c:2050
static const struct mg_http_method_info * get_http_method_info(const char *method)
Definition civetweb.c:10571
#define STOP_FLAG_IS_ZERO(f)
Definition civetweb.c:2305
unsigned default_port
Definition civetweb.c:17538
const char * mg_get_response_code_text(const struct mg_connection *conn, int response_code)
Definition civetweb.c:4152
static int get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
Definition civetweb.c:17895
static void mg_cry_internal_wrap(const struct mg_connection *conn, struct mg_context *ctx, const char *func, unsigned line, const char *fmt,...)
Definition civetweb.c:3448
static int set_uid_option(struct mg_context *phys_ctx)
Definition civetweb.c:15481
static int switch_domain_context(struct mg_connection *conn)
Definition civetweb.c:13483
static struct mg_connection * fake_connection(struct mg_connection *fc, struct mg_context *ctx)
Definition civetweb.c:3437
static void reset_per_request_attributes(struct mg_connection *conn)
Definition civetweb.c:16890
static void handle_file_based_request(struct mg_connection *conn, const char *path, struct mg_file *filep)
Definition civetweb.c:14576
#define FUNCTION_MAY_BE_UNUSED
Definition civetweb.c:316
static pthread_mutex_t * ssl_mutexes
Definition civetweb.c:15665
static int get_option_index(const char *name)
Definition civetweb.c:3124
static char * mg_strdup(const char *str)
Definition civetweb.c:3033
static void send_no_cache_header(struct mg_connection *conn)
Definition civetweb.c:4052
static void master_thread_run(struct mg_context *ctx)
Definition civetweb.c:19193
static int prepare_cgi_environment(struct mg_connection *conn, const char *prog, struct cgi_environment *env, unsigned char cgi_config_idx)
Definition civetweb.c:11046
static const char month_names[][4]
Definition civetweb.c:1807
const struct mg_response_info * mg_get_response_info(const struct mg_connection *conn)
Definition civetweb.c:3528
static __inline void * mg_realloc(void *a, size_t b)
Definition civetweb.c:1483
static void accept_new_connection(const struct socket *listener, struct mg_context *ctx)
Definition civetweb.c:19106
static volatile ptrdiff_t cryptolib_users
Definition civetweb.c:16029
static int get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
Definition civetweb.c:17727
#define CRYPTO_LIB
Definition civetweb.c:908
static pthread_mutex_t global_lock_mutex
Definition civetweb.c:1086
struct mg_context * mg_start2(struct mg_init_data *init, struct mg_error_data *error)
Definition civetweb.c:19613
#define CGI_ENVIRONMENT_SIZE
Definition civetweb.c:486
static int parse_http_headers(char **buf, struct mg_header hdr[(64)])
Definition civetweb.c:10421
#define mg_get_option
Definition civetweb.c:3150
static long ssl_get_protocol(int version_id)
Definition civetweb.c:16231
void * mg_get_user_context_data(const struct mg_connection *conn)
Definition civetweb.c:3167
static int mg_init_library_called
Definition civetweb.c:1549
long long mg_store_body(struct mg_connection *conn, const char *path)
Definition civetweb.c:10318
struct mg_connection * mg_download(const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, const char *fmt,...)
Definition civetweb.c:18032
#define DEBUG_ASSERT(cond)
Definition civetweb.c:260
static size_t mg_str_append(char **dst, char *end, const char *src)
Definition civetweb.c:20560
static int pull_inner(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
Definition civetweb.c:6185
#define INT64_FMT
Definition civetweb.c:923
int mg_get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int timeout)
Definition civetweb.c:17980
#define MG_FILE_COMPRESSION_SIZE_LIMIT
Definition civetweb.c:476
#define USA_IN_PORT_UNSAFE(s)
Definition civetweb.c:1852
static struct mg_connection * mg_connect_client_impl(const struct mg_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len)
Definition civetweb.c:17217
unsigned mg_check_feature(unsigned feature)
Definition civetweb.c:20497
static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
Definition civetweb.c:6469
static int mg_send_http_error_impl(struct mg_connection *conn, int status, const char *fmt, va_list args)
Definition civetweb.c:4351
struct mg_context * mg_start(const struct mg_callbacks *callbacks, void *user_data, const char **options)
Definition civetweb.c:20285
#define MG_FOPEN_MODE_READ
Definition civetweb.c:2808
#define STOP_FLAG_ASSIGN(f, v)
Definition civetweb.c:2307
static int extention_matches_script(struct mg_connection *conn, const char *filename)
Definition civetweb.c:7320
static void get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
Definition civetweb.c:13445
void mg_set_websocket_handler(struct mg_context *ctx, const char *uri, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, void *cbdata)
Definition civetweb.c:13797
int mg_start_domain(struct mg_context *ctx, const char **options)
Definition civetweb.c:20489
static pthread_mutexattr_t pthread_mutex_attr
Definition civetweb.c:1071
void mg_unlock_context(struct mg_context *ctx)
Definition civetweb.c:12331
static int ssl_servername_callback(SSL *ssl, int *ad, void *arg)
Definition civetweb.c:16280
int mg_modify_passwords_file(const char *fname, const char *domain, const char *user, const char *pass)
Definition civetweb.c:8927
static char * skip_quoted(char **buf, const char *delimiters, const char *whitespace, char quotechar)
Definition civetweb.c:3701
static void fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
Definition civetweb.c:9860
int mg_start_thread(mg_thread_func_t func, void *param)
Definition civetweb.c:5671
static const char * get_header(const struct mg_header *hdr, int num_hdr, const char *name)
Definition civetweb.c:3765
static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
Definition civetweb.c:8954
static int init_ssl_ctx_impl(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *pem, const char *chain)
Definition civetweb.c:16453
static int connect_socket(struct mg_context *ctx, const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, SOCKET *sock, union usa *sa)
Definition civetweb.c:8995
unsigned mg_init_library(unsigned features)
Definition civetweb.c:21374
struct mg_connection * mg_connect_client(const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size)
Definition civetweb.c:17426
static int forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
Definition civetweb.c:10876
static int set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
Definition civetweb.c:16850
static int skip_to_end_of_word_and_terminate(char **ppw, int eol)
Definition civetweb.c:10376
static int get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
Definition civetweb.c:17803
static int set_tcp_nodelay(const struct socket *so, int nodelay_on)
Definition civetweb.c:16932
int mg_get_var(const char *data, size_t data_len, const char *name, char *dst, size_t dst_len)
Definition civetweb.c:6991
#define ARRAY_SIZE(array)
Definition civetweb.c:504
static int parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
Definition civetweb.c:14723
static int get_first_ssl_listener_index(const struct mg_context *ctx)
Definition civetweb.c:13430
void mg_send_mime_file(struct mg_connection *conn, const char *path, const char *mime_type)
Definition civetweb.c:10213
const char * mg_get_header(const struct mg_connection *conn, const char *name)
Definition civetweb.c:3802
#define mg_mkdir(conn, path, mode)
Definition civetweb.c:915
int mg_split_form_urlencoded(char *data, struct mg_header *form_fields, unsigned num_form_fields)
Definition civetweb.c:7060
static int hexdump2string(void *mem, int memlen, char *buf, int buflen)
Definition civetweb.c:15808
#define UTF8_PATH_MAX
Definition civetweb.c:858
static const struct mg_http_method_info http_methods[]
Definition civetweb.c:10509
static int mg_poll(struct pollfd *pfd, unsigned int n, int milliseconds, const stop_flag_t *stop_flag)
Definition civetweb.c:5909
static void handle_directory_request(struct mg_connection *conn, const char *dir)
Definition civetweb.c:9618
static int set_ports_option(struct mg_context *phys_ctx)
Definition civetweb.c:14958
static int read_auth_file(struct mg_file *filep, struct read_auth_file_struct *workdata, int depth)
Definition civetweb.c:8506
static int mg_start_thread_with_id(mg_thread_func_t func, void *param, pthread_t *threadidptr)
Definition civetweb.c:5697
unsigned mg_exit_library(void)
Definition civetweb.c:21478
static void * load_tls_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw, int *feature_missing)
Definition civetweb.c:15929
static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
Definition civetweb.c:3307
int mg_send_digest_access_authentication_request(struct mg_connection *conn, const char *realm)
Definition civetweb.c:8773
static const char * mg_strcasestr(const char *big_str, const char *small_str)
Definition civetweb.c:3040
struct mg_connection * mg_connect_websocket_client(const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
Definition civetweb.c:18365
static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
Definition civetweb.c:6414
static void handle_ssi_file_request(struct mg_connection *conn, const char *path, struct mg_file *filep)
Definition civetweb.c:12091
int mg_write(struct mg_connection *conn, const void *buf, size_t len)
Definition civetweb.c:6696
static int set_throttle(const char *spec, const union usa *rsa, const char *uri)
Definition civetweb.c:13384
static void ssl_info_callback(const SSL *ssl, int what, int ret)
Definition civetweb.c:16264
#define calloc
Definition civetweb.c:1537
static void bin2str(char *to, const unsigned char *p, size_t len)
Definition civetweb.c:8193
const struct mg_request_info * mg_get_request_info(const struct mg_connection *conn)
Definition civetweb.c:3488
#define MG_FOPEN_MODE_APPEND
Definition civetweb.c:2814
char * mg_md5(char buf[33],...)
Definition civetweb.c:8208
#define STOP_FLAG_IS_TWO(f)
Definition civetweb.c:2306
static const char * next_option(const char *list, struct vec *val, struct vec *eq_val)
Definition civetweb.c:3846
static const char * suggest_connection_header(const struct mg_connection *conn)
Definition civetweb.c:4042
static ptrdiff_t match_prefix_strlen(const char *pattern, const char *str)
Definition civetweb.c:3967
static int alloc_vprintf(char **out_buf, char *prealloc_buf, size_t prealloc_size, const char *fmt, va_list ap)
Definition civetweb.c:6856
static time_t parse_date_string(const char *datetime)
Definition civetweb.c:7809
int SOCKET
Definition civetweb.c:925
static void do_ssi_include(struct mg_connection *conn, const char *ssi, char *tag, int include_level)
Definition civetweb.c:11861
static void uninitialize_openssl(void)
Definition civetweb.c:16808
int mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
Definition civetweb.c:3689
static int parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
Definition civetweb.c:13275
static const struct @143 abs_uri_protocols[]
int mg_modify_passwords_file_ha1(const char *fname, const char *domain, const char *user, const char *ha1)
Definition civetweb.c:8937
static void send_options(struct mg_connection *conn)
Definition civetweb.c:12160
static int lowercase(const char *s)
Definition civetweb.c:2977
static void release_handler_ref(struct mg_connection *conn, struct mg_handler_info *handler_info)
Definition civetweb.c:13996
static int parse_range_header(const char *header, int64_t *a, int64_t *b)
Definition civetweb.c:9833
static int mg_stat(const struct mg_connection *conn, const char *path, struct mg_file_stat *filep)
Definition civetweb.c:5621
static int get_uri_type(const char *uri)
Definition civetweb.c:17553
#define SSL_LIB
Definition civetweb.c:905
#define DEBUG_TRACE(fmt,...)
Definition civetweb.c:242
static void get_system_name(char **sysName)
Definition civetweb.c:19537
int mg_url_encode(const char *src, char *dst, size_t dst_len)
Definition civetweb.c:9262
static const char * header_val(const struct mg_connection *conn, const char *header)
Definition civetweb.c:15268
#define mg_cry_internal(conn, fmt,...)
Definition civetweb.c:2548
static int set_acl_option(struct mg_context *phys_ctx)
Definition civetweb.c:16876
static void mg_set_thread_name(const char *name)
Definition civetweb.c:2745
static void get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
Definition civetweb.c:8158
static int set_blocking_mode(SOCKET sock)
Definition civetweb.c:5861
#define MSG_NOSIGNAL
Definition civetweb.c:1727
static void send_file_data(struct mg_connection *conn, struct mg_file *filep, int64_t offset, int64_t len)
Definition civetweb.c:9729
#define MAX_CGI_ENVIR_VARS
Definition civetweb.c:491
static char * mg_strdup_ctx(const char *str, struct mg_context *ctx)
Definition civetweb.c:3027
struct mg_connection * mg_connect_websocket_client_extensions(const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, const char *extensions, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
Definition civetweb.c:18421
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded)
Definition civetweb.c:6951
static int parse_auth_header(struct mg_connection *conn, char *buf, size_t buf_size, struct ah *ah)
Definition civetweb.c:8356
void mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
Definition civetweb.c:3190
int mg_get_var2(const char *data, size_t data_len, const char *name, char *dst, size_t dst_len, size_t occurrence)
Definition civetweb.c:7002
static int is_not_modified(const struct mg_connection *conn, const struct mg_file_stat *filestat)
Definition civetweb.c:10164
static void worker_thread_run(struct mg_connection *conn)
Definition civetweb.c:18853
static void interpret_uri(struct mg_connection *conn, char *filename, size_t filename_buf_len, struct mg_file_stat *filestat, int *is_found, int *is_script_resource, int *is_websocket_request, int *is_put_or_delete_request, int *is_template_text)
Definition civetweb.c:7438
static const char * get_proto_name(const struct mg_connection *conn)
Definition civetweb.c:3541
static void * master_thread(void *thread_func_param)
Definition civetweb.c:19379
static void mg_set_handler_type(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *uri, int handler_type, int is_delete_request, mg_request_handler handler, struct mg_websocket_subprotocols *subprotocols, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, mg_authorization_handler auth_handler, void *cbdata)
Definition civetweb.c:13589
static int is_file_opened(const struct mg_file_access *fileacc)
Definition civetweb.c:2818
static int get_http_header_len(const char *buf, int buflen)
Definition civetweb.c:7756
struct mg_connection * mg_connect_websocket_client_secure_extensions(const struct mg_client_options *client_options, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, const char *extensions, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
Definition civetweb.c:18451
void mg_close_connection(struct mg_connection *conn)
Definition civetweb.c:17154
static int is_valid_port(unsigned long port)
Definition civetweb.c:8947
static void handle_propfind(struct mg_connection *conn, const char *path, struct mg_file_stat *filep)
Definition civetweb.c:12262
static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
Definition civetweb.c:6919
#define mg_realloc_ctx(a, b, c)
Definition civetweb.c:1496
static void send_additional_header(struct mg_connection *conn)
Definition civetweb.c:4118
static int push_all(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int len)
Definition civetweb.c:6137
static int is_put_or_delete_method(const struct mg_connection *conn)
Definition civetweb.c:7306
static int read_message(FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread)
Definition civetweb.c:10799
static int print_dir_entry(struct de *de)
Definition civetweb.c:9290
#define MG_FOPEN_MODE_WRITE
Definition civetweb.c:2811
void * mg_get_user_connection_data(const struct mg_connection *conn)
Definition civetweb.c:3203
static int authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
Definition civetweb.c:8616
static void send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int)
Definition civetweb.c:11985
#define mg_static_assert(cond, txt)
Definition civetweb.c:124
#define SOCKET_TIMEOUT_QUANTUM
Definition civetweb.c:471
static void produce_socket(struct mg_context *ctx, const struct socket *sp)
Definition civetweb.c:18810
static ptrdiff_t match_prefix(const char *pattern, size_t pattern_len, const char *str)
Definition civetweb.c:3922
int mg_send_chunk(struct mg_connection *conn, const char *chunk, unsigned int chunk_len)
Definition civetweb.c:6777
static void remove_dot_segments(char *inout)
Definition civetweb.c:7873
static int get_request_handler(struct mg_connection *conn, int handler_type, mg_request_handler *handler, struct mg_websocket_subprotocols **subprotocols, mg_websocket_connect_handler *connect_handler, mg_websocket_ready_handler *ready_handler, mg_websocket_data_handler *data_handler, mg_websocket_close_handler *close_handler, mg_authorization_handler *auth_handler, void **cbdata, struct mg_handler_info **handler_info)
Definition civetweb.c:13869
void mg_set_auth_handler(struct mg_context *ctx, const char *uri, mg_authorization_handler handler, void *cbdata)
Definition civetweb.c:13847
int mg_start_domain2(struct mg_context *ctx, const char **options, struct mg_error_data *error)
Definition civetweb.c:20300
#define mg_pollfd
Definition civetweb.c:945
#define MG_BUF_LEN
Definition civetweb.c:496
static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
Definition civetweb.c:6823
static const struct @142 builtin_mime_types[]
static int extention_matches_template_text(struct mg_connection *conn, const char *filename)
Definition civetweb.c:7366
static int is_in_script_path(const struct mg_connection *conn, const char *path)
Definition civetweb.c:13954
static int should_decode_query_string(const struct mg_connection *conn)
Definition civetweb.c:4030
static double mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
Definition civetweb.c:3331
static void free_context(struct mg_context *ctx)
Definition civetweb.c:19397
static int sslize(struct mg_connection *conn, int(*func)(SSL *), const struct mg_client_options *client_options)
Definition civetweb.c:15669
static void legacy_init(const char **options)
Definition civetweb.c:19585
static void construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
Definition civetweb.c:9845
int mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
Definition civetweb.c:20911
int volatile stop_flag_t
Definition civetweb.c:2304
static int refresh_trust(struct mg_connection *conn)
Definition civetweb.c:15591
#define SHUTDOWN_WR
Definition civetweb.c:515
void * mg_get_thread_pointer(const struct mg_connection *conn)
Definition civetweb.c:3174
static int compare_dir_entries(const void *p1, const void *p2)
Definition civetweb.c:9400
static void mg_vsnprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, const char *fmt, va_list ap)
Definition civetweb.c:3059
static int should_decode_url(const struct mg_connection *conn)
Definition civetweb.c:4019
static int mg_construct_local_link(const struct mg_connection *conn, char *buf, size_t buflen, const char *define_proto, int define_port, const char *define_uri)
Definition civetweb.c:3568
char static_assert_replacement[1]
Definition civetweb.c:123
#define ERROR_TRY_AGAIN(err)
Definition civetweb.c:445
static unsigned long mg_current_thread_id(void)
Definition civetweb.c:1618
#define HTTP1_only
Definition civetweb.c:6583
@ AUTH_HANDLER
Definition civetweb.c:2208
@ REQUEST_HANDLER
Definition civetweb.c:2208
@ WEBSOCKET_HANDLER
Definition civetweb.c:2208
#define malloc
Definition civetweb.c:1536
#define INT64_MAX
Definition civetweb.c:511
static void mg_strlcpy(char *dst, const char *src, size_t n)
Definition civetweb.c:2967
static int remove_directory(struct mg_connection *conn, const char *dir)
Definition civetweb.c:9510
static const char * get_http_version(const struct mg_connection *conn)
Definition civetweb.c:3823
static __inline void * mg_calloc(size_t a, size_t b)
Definition civetweb.c:1477
#define WINCDECL
Definition civetweb.c:926
#define va_copy(x, y)
Definition civetweb.c:1000
static void handle_request(struct mg_connection *)
Definition civetweb.c:14013
static int parse_http_response(char *buf, int len, struct mg_response_info *ri)
Definition civetweb.c:10692
static void * cryptolib_dll_handle
Definition civetweb.c:16020
static uint64_t mg_get_current_time_ns(void)
Definition civetweb.c:1668
const char * mg_get_builtin_mime_type(const char *path)
Definition civetweb.c:8136
static const char * mg_fgets(char *buf, size_t size, struct mg_file *filep)
Definition civetweb.c:8469
int mg_read(struct mg_connection *conn, void *buf, size_t len)
Definition civetweb.c:6588
#define IGNORE_UNUSED_RESULT(a)
Definition civetweb.c:291
static void addenv(struct cgi_environment *env, const char *fmt,...)
Definition civetweb.c:10976
static void discard_unread_request_data(struct mg_connection *conn)
Definition civetweb.c:6459
int mg_strcasecmp(const char *s1, const char *s2)
Definition civetweb.c:2999
static int mg_fclose(struct mg_file_access *fileacc)
Definition civetweb.c:2951
static struct mg_connection * mg_connect_websocket_client_impl(const struct mg_client_options *client_options, int use_ssl, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, const char *extensions, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data)
Definition civetweb.c:18155
void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata)
Definition civetweb.c:13775
static void * worker_thread(void *thread_func_param)
Definition civetweb.c:19086
static __inline void mg_free(void *a)
Definition civetweb.c:1489
static void handle_request_stat_log(struct mg_connection *conn)
Definition civetweb.c:6537
int mg_check_digest_access_authentication(struct mg_connection *conn, const char *realm, const char *filename)
Definition civetweb.c:8644
static int mg_join_thread(pthread_t threadid)
Definition civetweb.c:5728
static void mg_global_unlock(void)
Definition civetweb.c:1099
int mg_get_system_info(char *buffer, int buflen)
Definition civetweb.c:20579
static void handle_not_modified_static_file_request(struct mg_connection *conn, struct mg_file *filep)
Definition civetweb.c:10179
static int init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
Definition civetweb.c:16699
static void close_socket_gracefully(struct mg_connection *conn)
Definition civetweb.c:16954
struct mg_context * mg_get_context(const struct mg_connection *conn)
Definition civetweb.c:3153
static int is_ssl_port_used(const char *ports)
Definition civetweb.c:14901
static void init_connection(struct mg_connection *conn)
Definition civetweb.c:18479
static int print_props(struct mg_connection *conn, const char *uri, const char *name, struct mg_file_stat *filep)
Definition civetweb.c:12191
#define INITIAL_DEPTH
Definition civetweb.c:8488
static int dir_scan_callback(struct de *de, void *data)
Definition civetweb.c:9586
size_t proto_len
Definition civetweb.c:17537
static void set_close_on_exec(int fd, const struct mg_connection *conn, struct mg_context *ctx)
Definition civetweb.c:5648
static int get_month_index(const char *s)
Definition civetweb.c:7793
void mg_set_websocket_handler_with_subprotocols(struct mg_context *ctx, const char *uri, struct mg_websocket_subprotocols *subprotocols, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, void *cbdata)
Definition civetweb.c:13817
static void * ssllib_dll_handle
Definition civetweb.c:16019
static int mg_fgetc(struct mg_file *filep)
Definition civetweb.c:11970
#define mg_sleep(x)
Definition civetweb.c:917
@ CONNECTION_TYPE_RESPONSE
Definition civetweb.c:2426
@ CONNECTION_TYPE_INVALID
Definition civetweb.c:2424
@ CONNECTION_TYPE_REQUEST
Definition civetweb.c:2425
#define PASSWORDS_FILE_NAME
Definition civetweb.c:480
static void close_connection(struct mg_connection *conn)
Definition civetweb.c:17079
@ ENABLE_DIRECTORY_LISTING
Definition civetweb.c:1990
@ SSL_SHORT_TRUST
Definition civetweb.c:2007
@ GLOBAL_PASSWORDS_FILE
Definition civetweb.c:1991
@ ADDITIONAL_HEADER
Definition civetweb.c:2040
@ SSL_VERIFY_DEPTH
Definition civetweb.c:2003
@ ACCESS_CONTROL_ALLOW_ORIGIN
Definition civetweb.c:2028
@ SSL_PROTOCOL_VERSION
Definition civetweb.c:2006
@ SSL_DO_VERIFY_PEER
Definition civetweb.c:1999
@ SSL_CERTIFICATE
Definition civetweb.c:1995
@ RUN_AS_USER
Definition civetweb.c:1914
@ ALLOW_INDEX_SCRIPT_SUB_RES
Definition civetweb.c:2041
@ SSL_CACHE_TIMEOUT
Definition civetweb.c:2000
@ CONNECTION_QUEUE_SIZE
Definition civetweb.c:1919
@ ENABLE_KEEP_ALIVE
Definition civetweb.c:1928
@ ACCESS_CONTROL_LIST
Definition civetweb.c:1993
@ CGI_INTERPRETER_ARGS
Definition civetweb.c:1954
@ SSL_CA_PATH
Definition civetweb.c:2001
@ AUTHENTICATION_DOMAIN
Definition civetweb.c:1987
@ ACCESS_CONTROL_ALLOW_HEADERS
Definition civetweb.c:2030
@ SSL_DEFAULT_VERIFY_PATHS
Definition civetweb.c:2004
@ CGI2_EXTENSIONS
Definition civetweb.c:1959
@ ACCESS_CONTROL_ALLOW_METHODS
Definition civetweb.c:2029
@ STRICT_HTTPS_MAX_AGE
Definition civetweb.c:2038
@ HIDE_FILES
Definition civetweb.c:1998
@ ERROR_LOG_FILE
Definition civetweb.c:1949
@ CGI2_INTERPRETER_ARGS
Definition civetweb.c:1962
@ STATIC_FILE_MAX_AGE
Definition civetweb.c:2034
@ LINGER_TIMEOUT
Definition civetweb.c:1918
@ URL_REWRITE_PATTERN
Definition civetweb.c:1997
@ THROTTLE
Definition civetweb.c:1927
@ SSL_CIPHER_LIST
Definition civetweb.c:2005
@ KEEP_ALIVE_TIMEOUT
Definition civetweb.c:1930
@ CGI_EXTENSIONS
Definition civetweb.c:1951
@ STATIC_FILE_CACHE_CONTROL
Definition civetweb.c:2035
@ ERROR_PAGES
Definition civetweb.c:2032
@ CGI_ENVIRONMENT
Definition civetweb.c:1952
@ PUT_DELETE_PASSWORDS_FILE
Definition civetweb.c:1985
@ ENABLE_AUTH_DOMAIN_CHECK
Definition civetweb.c:1988
@ NUM_OPTIONS
Definition civetweb.c:2043
@ MAX_REQUEST_SIZE
Definition civetweb.c:1917
@ DECODE_URL
Definition civetweb.c:1935
@ NUM_THREADS
Definition civetweb.c:1913
@ DOCUMENT_ROOT
Definition civetweb.c:1946
@ SSL_CERTIFICATE_CHAIN
Definition civetweb.c:1996
@ CGI2_ENVIRONMENT
Definition civetweb.c:1960
@ PROTECT_URI
Definition civetweb.c:1986
@ ACCESS_LOG_FILE
Definition civetweb.c:1948
@ ACCESS_CONTROL_ALLOW_CREDENTIALS
Definition civetweb.c:2031
@ REQUEST_TIMEOUT
Definition civetweb.c:1929
@ SSI_EXTENSIONS
Definition civetweb.c:1989
@ CONFIG_TCP_NODELAY
Definition civetweb.c:1915
@ SSL_CA_FILE
Definition civetweb.c:2002
@ CGI_INTERPRETER
Definition civetweb.c:1953
@ LISTEN_BACKLOG_SIZE
Definition civetweb.c:1920
@ DECODE_QUERY_STRING
Definition civetweb.c:1936
@ LISTENING_PORTS
Definition civetweb.c:1912
@ CGI2_INTERPRETER
Definition civetweb.c:1961
@ INDEX_FILES
Definition civetweb.c:1992
@ EXTRA_MIME_TYPES
Definition civetweb.c:1994
static int initialize_openssl(char *ebuf, size_t ebuf_len)
Definition civetweb.c:16035
static int substitute_index_file(struct mg_connection *conn, char *path, size_t path_len, struct mg_file_stat *filestat)
Definition civetweb.c:7390
void mg_stop(struct mg_context *ctx)
Definition civetweb.c:19494
#define STRUCT_FILE_INITIALIZER
Definition civetweb.c:1883
static volatile ptrdiff_t thread_idx_max
Definition civetweb.c:1573
void * mg_get_user_data(const struct mg_context *ctx)
Definition civetweb.c:3160
static int scan_directory(struct mg_connection *conn, const char *dir, void *data, int(*cb)(struct de *, void *))
Definition civetweb.c:9450
static int push_inner(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int len, double timeout)
Definition civetweb.c:5971
const char * mg_version(void)
Definition civetweb.c:3481
static uint64_t get_random(void)
Definition civetweb.c:5880
void mg_lock_connection(struct mg_connection *conn)
Definition civetweb.c:12307
int mg_send_file_body(struct mg_connection *conn, const char *path)
Definition civetweb.c:10147
#define mg_cry
Definition civetweb.c:3477
static int is_valid_http_method(const char *method)
Definition civetweb.c:10590
static void url_decode_in_place(char *buf)
Definition civetweb.c:6983
int mg_websocket_client_write(struct mg_connection *conn, int opcode, const char *data, size_t data_len)
#define MG_MAX_HEADERS
Definition civetweb.h:141
int mg_response_header_add(struct mg_connection *conn, const char *header, const char *value, int value_len)
Definition response.inl:120
void *(* mg_thread_func_t)(void *)
Definition civetweb.h:1307
int mg_response_header_send(struct mg_connection *conn)
Definition response.inl:259
int mg_websocket_write(struct mg_connection *conn, int opcode, const char *data, size_t data_len)
#define CIVETWEB_VERSION
Definition civetweb.h:26
#define PRINTF_FORMAT_STRING(s)
Definition civetweb.h:877
int(* mg_authorization_handler)(struct mg_connection *conn, void *cbdata)
Definition civetweb.h:606
@ MG_CONFIG_TYPE_UNKNOWN
Definition civetweb.h:694
@ MG_CONFIG_TYPE_FILE
Definition civetweb.h:697
@ MG_CONFIG_TYPE_STRING
Definition civetweb.h:696
@ MG_CONFIG_TYPE_DIRECTORY
Definition civetweb.h:698
@ MG_CONFIG_TYPE_EXT_PATTERN
Definition civetweb.h:700
@ MG_CONFIG_TYPE_STRING_MULTILINE
Definition civetweb.h:702
@ MG_CONFIG_TYPE_STRING_LIST
Definition civetweb.h:701
@ MG_CONFIG_TYPE_YES_NO_OPTIONAL
Definition civetweb.h:703
@ MG_CONFIG_TYPE_NUMBER
Definition civetweb.h:695
@ MG_CONFIG_TYPE_BOOLEAN
Definition civetweb.h:699
@ MG_FEATURES_HTTP2
Definition civetweb.h:102
@ MG_FEATURES_STATS
Definition civetweb.h:95
@ MG_FEATURES_CACHE
Definition civetweb.h:91
@ MG_FEATURES_FILES
Definition civetweb.h:61
@ MG_FEATURES_CGI
Definition civetweb.h:71
@ MG_FEATURES_IPV6
Definition civetweb.h:75
@ MG_FEATURES_DEFAULT
Definition civetweb.h:57
@ MG_FEATURES_TLS
Definition civetweb.h:66
@ MG_FEATURES_X_DOMAIN_SOCKET
Definition civetweb.h:105
@ MG_FEATURES_SSL
Definition civetweb.h:67
@ MG_FEATURES_LUA
Definition civetweb.h:83
@ MG_FEATURES_WEBSOCKET
Definition civetweb.h:79
@ MG_FEATURES_SSJS
Definition civetweb.h:87
@ MG_FEATURES_COMPRESSION
Definition civetweb.h:99
@ MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE
Definition civetweb.h:861
@ MG_WEBSOCKET_OPCODE_PONG
Definition civetweb.h:863
@ MG_WEBSOCKET_OPCODE_PING
Definition civetweb.h:862
void(* mg_websocket_ready_handler)(struct mg_connection *, void *)
Definition civetweb.h:549
#define CIVETWEB_API
Definition civetweb.h:43
int mg_response_header_add_lines(struct mg_connection *conn, const char *http1_headers)
Definition response.inl:209
#define PRINTF_ARGS(x, y)
Definition civetweb.h:883
int(* mg_websocket_data_handler)(struct mg_connection *, int, char *, size_t, void *)
Definition civetweb.h:550
int(* mg_request_handler)(struct mg_connection *conn, void *cbdata)
Definition civetweb.h:492
int mg_response_header_start(struct mg_connection *conn, int status)
Definition response.inl:73
void(* mg_websocket_close_handler)(const struct mg_connection *, void *)
Definition civetweb.h:555
int(* mg_websocket_connect_handler)(const struct mg_connection *, void *)
Definition civetweb.h:547
TLine * line
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
unsigned char md5_byte_t
Definition md5.inl:50
MD5_STATIC void md5_finish(md5_state_t *pms, md5_byte_t digest[16])
Definition md5.inl:450
MD5_STATIC void md5_init(md5_state_t *pms)
Definition md5.inl:402
MD5_STATIC void md5_append(md5_state_t *pms, const md5_byte_t *data, size_t nbytes)
Definition md5.inl:412
#define TRUE
Definition mesh.c:42
#define FALSE
Definition mesh.c:45
void(off) SmallVectorTemplateBase< T
RooArgList L(Args_t &&... args)
Definition RooArgList.h:156
const char * cnt
Definition TXMLSetup.cxx:75
#define SSL_VERIFY_NONE
struct asn1_integer ASN1_INTEGER
#define SSL_OP_CIPHER_SERVER_PREFERENCE
#define SSL_OP_NO_SSLv2
struct ssl_ctx_st SSL_CTX
#define SSL_OP_NO_TLSv1_3
#define SSL_OP_SINGLE_DH_USE
@ TLS_ALPN
@ TLS_Mandatory
#define SSL_VERIFY_FAIL_IF_NO_PEER_CERT
#define SSL_SESS_CACHE_BOTH
#define SSL_TLSEXT_ERR_OK
#define SSL_TLSEXT_ERR_NOACK
#define OPENSSL_INIT_LOAD_CRYPTO_STRINGS
struct x509 X509
#define SSL_OP_NO_COMPRESSION
#define SSL_ERROR_SYSCALL
#define SSL_ERROR_WANT_READ
#define SSL_VERIFY_PEER
struct ssl_st SSL
#define SSL_OP_NO_TLSv1
#define SSL_ERROR_WANT_ACCEPT
#define SSL_ERROR_WANT_X509_LOOKUP
#define SSL_CB_HANDSHAKE_START
#define SSL_ERROR_WANT_CONNECT
#define SSL_OP_NO_TLSv1_2
#define SSL_OP_NO_SSLv3
struct evp_md EVP_MD
#define SSL_OP_NO_RENEGOTIATION
struct x509_name X509_NAME
#define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
#define TLSEXT_NAMETYPE_host_name
#define SSL_CB_HANDSHAKE_DONE
#define SSL_OP_ALL
#define OPENSSL_INIT_LOAD_SSL_STRINGS
#define SSL_OP_NO_TLSv1_1
struct bignum BIGNUM
static int tls_feature_missing[TLS_END_OF_LIST]
#define SSL_ERROR_WANT_WRITE
static void free_buffered_response_header_list(struct mg_connection *conn)
Definition response.inl:17
SHA_API void SHA1_Init(SHA_CTX *context)
Definition sha1.inl:258
SHA_API void SHA1_Update(SHA_CTX *context, const uint8_t *data, const uint32_t len)
Definition sha1.inl:271
SHA_API void SHA1_Final(unsigned char *digest, SHA_CTX *context)
Definition sha1.inl:298
#define blk(block, i)
Definition sha1.inl:124
TCanvas * slash()
Definition slash.C:1
static const char * what
Definition stlLoader.cc:5
char * nc
Definition civetweb.c:8350
char * nonce
Definition civetweb.c:8350
char * cnonce
Definition civetweb.c:8350
char * uri
Definition civetweb.c:8350
char * user
Definition civetweb.c:8350
char * qop
Definition civetweb.c:8350
char * response
Definition civetweb.c:8350
struct mg_connection * conn
Definition civetweb.c:10957
char * file_name
Definition civetweb.c:2543
struct mg_connection * conn
Definition civetweb.c:2542
struct mg_file_stat file
Definition civetweb.c:2544
size_t num_entries
Definition civetweb.c:9579
struct de * entries
Definition civetweb.c:9578
size_t arr_size
Definition civetweb.c:9580
int(* init_ssl)(void *ssl_ctx, void *user_data)
Definition civetweb.h:254
int(* log_message)(const struct mg_connection *, const char *message)
Definition civetweb.h:240
void *(* init_thread)(const struct mg_context *ctx, int thread_type)
Definition civetweb.h:393
void(* end_request)(const struct mg_connection *, int reply_status_code)
Definition civetweb.h:236
int(* init_connection)(const struct mg_connection *conn, void **conn_data)
Definition civetweb.h:417
void(* connection_close)(const struct mg_connection *)
Definition civetweb.h:320
int(* http_error)(struct mg_connection *conn, int status, const char *errmsg)
Definition civetweb.h:359
void(* exit_context)(const struct mg_context *ctx)
Definition civetweb.h:372
int(* init_ssl_domain)(const char *server_domain, void *ssl_ctx, void *user_data)
Definition civetweb.h:265
int(* external_ssl_ctx)(void **ssl_ctx, void *user_data)
Definition civetweb.h:278
void(* exit_thread)(const struct mg_context *ctx, int thread_type, void *thread_pointer)
Definition civetweb.h:400
int(* begin_request)(struct mg_connection *)
Definition civetweb.h:233
int(* log_access)(const struct mg_connection *, const char *message)
Definition civetweb.h:244
void(* init_context)(const struct mg_context *ctx)
Definition civetweb.h:367
void(* connection_closed)(const struct mg_connection *)
Definition civetweb.h:330
int(* external_ssl_ctx_domain)(const char *server_domain, void **ssl_ctx, void *user_data)
Definition civetweb.h:290
const char * issuer
Definition civetweb.h:209
const char * finger
Definition civetweb.h:211
void * peer_cert
Definition civetweb.h:207
const char * subject
Definition civetweb.h:208
const char * serial
Definition civetweb.h:210
const char * host_name
Definition civetweb.h:1438
const char * client_cert
Definition civetweb.h:1436
const char * server_cert
Definition civetweb.h:1437
const char * host
Definition civetweb.h:1434
time_t last_throttle_time
Definition civetweb.c:2527
int64_t content_len
Definition civetweb.c:2482
struct timespec req_time
Definition civetweb.c:2479
int64_t consumed_content
Definition civetweb.c:2488
char * path_info
Definition civetweb.c:2497
int64_t num_bytes_sent
Definition civetweb.c:2481
int connection_type
Definition civetweb.c:2450
pthread_mutex_t mutex
Definition civetweb.c:2529
struct socket client
Definition civetweb.c:2471
struct mg_response_info response_info
Definition civetweb.c:2459
void * tls_user_ptr
Definition civetweb.c:2535
struct mg_request_info request_info
Definition civetweb.c:2458
struct mg_context * phys_ctx
Definition civetweb.c:2461
struct mg_domain_context * dom_ctx
Definition civetweb.c:2462
int in_error_handler
Definition civetweb.c:2501
time_t conn_birth_time
Definition civetweb.c:2472
int handled_requests
Definition civetweb.c:2518
int last_throttle_bytes
Definition civetweb.c:2528
time_t start_time
Definition civetweb.c:2376
pthread_cond_t sq_empty
Definition civetweb.c:2359
struct socket * squeue
Definition civetweb.c:2354
pthread_t * worker_threadids
Definition civetweb.c:2346
volatile int sq_head
Definition civetweb.c:2356
stop_flag_t stop_flag
Definition civetweb.c:2340
void * user_data
Definition civetweb.c:2397
unsigned long starter_thread_idx
Definition civetweb.c:2347
struct mg_connection * worker_connections
Definition civetweb.c:2327
struct socket * listening_sockets
Definition civetweb.c:2323
char * systemName
Definition civetweb.c:2375
pthread_t masterthreadid
Definition civetweb.c:2343
int context_type
Definition civetweb.c:2321
pthread_mutex_t thread_mutex
Definition civetweb.c:2341
struct mg_callbacks callbacks
Definition civetweb.c:2396
struct mg_domain_context dd
Definition civetweb.c:2406
struct pollfd * listening_socket_fds
Definition civetweb.c:2324
pthread_cond_t sq_full
Definition civetweb.c:2358
volatile int sq_tail
Definition civetweb.c:2357
unsigned int num_listening_sockets
Definition civetweb.c:2325
unsigned int max_request_size
Definition civetweb.c:2368
unsigned int cfg_worker_threads
Definition civetweb.c:2345
pthread_mutex_t nonce_mutex
Definition civetweb.c:2391
volatile int sq_blocked
Definition civetweb.c:2360
char * config[NUM_OPTIONS]
Definition civetweb.c:2254
unsigned long nonce_count
Definition civetweb.c:2260
int64_t ssl_cert_last_mtime
Definition civetweb.c:2256
uint64_t auth_nonce_mask
Definition civetweb.c:2259
struct mg_domain_context * next
Definition civetweb.c:2268
SSL_CTX * ssl_ctx
Definition civetweb.c:2253
struct mg_handler_info * handlers
Definition civetweb.c:2255
unsigned * code
Definition civetweb.h:1672
size_t text_buffer_size
Definition civetweb.h:1674
uint64_t size
Definition civetweb.c:1863
time_t last_modified
Definition civetweb.c:1864
struct mg_file_stat stat
Definition civetweb.c:1878
struct mg_file_access access
Definition civetweb.c:1879
mg_request_handler handler
Definition civetweb.c:2220
mg_authorization_handler auth_handler
Definition civetweb.c:2234
mg_websocket_close_handler close_handler
Definition civetweb.c:2228
struct mg_handler_info * next
Definition civetweb.c:2240
unsigned int refcount
Definition civetweb.c:2221
mg_websocket_connect_handler connect_handler
Definition civetweb.c:2225
struct mg_websocket_subprotocols * subprotocols
Definition civetweb.c:2231
mg_websocket_data_handler data_handler
Definition civetweb.c:2227
mg_websocket_ready_handler ready_handler
Definition civetweb.c:2226
const char * value
Definition civetweb.h:145
const char * name
Definition civetweb.h:144
const char * name
Definition civetweb.c:10499
void * user_data
Definition civetweb.h:1679
const struct mg_callbacks * callbacks
Definition civetweb.h:1678
const char ** configuration_options
Definition civetweb.h:1680
const char * default_value
Definition civetweb.h:688
const char * name
Definition civetweb.h:686
struct mg_header http_headers[(64)]
Definition civetweb.h:179
const char * local_uri
Definition civetweb.h:157
void * user_data
Definition civetweb.h:175
const char * local_uri_raw
Definition civetweb.h:154
const char * request_method
Definition civetweb.h:151
struct mg_client_cert * client_cert
Definition civetweb.h:182
const char * query_string
Definition civetweb.h:162
long long content_length
Definition civetweb.h:168
void * conn_data
Definition civetweb.h:176
char remote_addr[48]
Definition civetweb.h:166
const char * http_version
Definition civetweb.h:161
const char * request_uri
Definition civetweb.h:152
const char * acceptedWebSocketSubprotocol
Definition civetweb.h:184
const char * remote_user
Definition civetweb.h:164
struct mg_header http_headers[(64)]
Definition civetweb.h:200
long long content_length
Definition civetweb.h:196
const char * http_version
Definition civetweb.h:194
const char * status_text
Definition civetweb.h:193
const char ** subprotocols
Definition civetweb.h:564
void * user_ptr
Definition civetweb.c:1582
const char * alpn_proto
Definition civetweb.c:1587
unsigned long thread_idx
Definition civetweb.c:1581
int pw_gid
int pw_uid
const char * f_ha1
Definition civetweb.c:8501
const char * f_domain
Definition civetweb.c:8500
const char * f_user
Definition civetweb.c:8499
const char * domain
Definition civetweb.c:8497
char buf[256+256+40]
Definition civetweb.c:8498
struct mg_connection * conn
Definition civetweb.c:8495
unsigned char is_ssl
Definition civetweb.c:1898
union usa lsa
Definition civetweb.c:1896
unsigned char ssl_redir
Definition civetweb.c:1899
SOCKET sock
Definition civetweb.c:1895
unsigned char in_use
Definition civetweb.c:1901
union usa rsa
Definition civetweb.c:1897
void(* ptr)(void)
const char * name
enum ssl_func_category required
size_t len
Definition civetweb.c:1858
const char * ptr
Definition civetweb.c:1857
mg_websocket_close_handler close_handler
Definition civetweb.c:18087
mg_websocket_data_handler data_handler
Definition civetweb.c:18086
struct mg_connection * conn
Definition civetweb.c:18085
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
struct sockaddr sa
Definition civetweb.c:1825
struct sockaddr_in sin
Definition civetweb.c:1826
static void output()