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/err.h>
1748#include <openssl/opensslv.h>
1749#include <openssl/pem.h>
1750#include <openssl/ssl.h>
1751#include <openssl/tls1.h>
1752#include <openssl/x509.h>
1753
1754#if defined(WOLFSSL_VERSION)
1755/* Additional defines for WolfSSL, see
1756 * https://github.com/civetweb/civetweb/issues/583 */
1757#include "wolfssl_extras.inl"
1758#endif
1759
1760#if defined(OPENSSL_IS_BORINGSSL)
1761/* From boringssl/src/include/openssl/mem.h:
1762 *
1763 * OpenSSL has, historically, had a complex set of malloc debugging options.
1764 * However, that was written in a time before Valgrind and ASAN. Since we now
1765 * have those tools, the OpenSSL allocation functions are simply macros around
1766 * the standard memory functions.
1767 *
1768 * #define OPENSSL_free free */
1769#define free free
1770// disable for boringssl
1771#define CONF_modules_unload(a) ((void)0)
1772#define ENGINE_cleanup() ((void)0)
1773#endif
1774
1775/* If OpenSSL headers are included, automatically select the API version */
1776#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
1777#if !defined(OPENSSL_API_3_0)
1778#define OPENSSL_API_3_0
1779#endif
1780#define OPENSSL_REMOVE_THREAD_STATE()
1781#else
1782#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1783#if !defined(OPENSSL_API_1_1)
1784#define OPENSSL_API_1_1
1785#endif
1786#define OPENSSL_REMOVE_THREAD_STATE()
1787#else
1788#if !defined(OPENSSL_API_1_0)
1789#define OPENSSL_API_1_0
1790#endif
1791#define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
1792#endif
1793#endif
1794
1795
1796#else
1797/* SSL loaded dynamically from DLL / shared object */
1798/* Add all prototypes here, to be independent from OpenSSL source
1799 * installation. */
1800#include "openssl_dl.inl"
1801
1802#endif /* Various SSL bindings */
1803
1804
1805#if !defined(NO_CACHING)
1806static const char month_names[][4] = {"Jan",
1807 "Feb",
1808 "Mar",
1809 "Apr",
1810 "May",
1811 "Jun",
1812 "Jul",
1813 "Aug",
1814 "Sep",
1815 "Oct",
1816 "Nov",
1817 "Dec"};
1818#endif /* !NO_CACHING */
1819
1820
1821/* Unified socket address. For IPv6 support, add IPv6 address structure in
1822 * the union u. */
1823union usa {
1824 struct sockaddr sa;
1825 struct sockaddr_in sin;
1826#if defined(USE_IPV6)
1827 struct sockaddr_in6 sin6;
1828#endif
1829#if defined(USE_X_DOM_SOCKET)
1830 struct sockaddr_un sun;
1831#endif
1832};
1833
1834#if defined(USE_X_DOM_SOCKET)
1835static unsigned short
1836USA_IN_PORT_UNSAFE(union usa *s)
1837{
1838 if (s->sa.sa_family == AF_INET)
1839 return s->sin.sin_port;
1840#if defined(USE_IPV6)
1841 if (s->sa.sa_family == AF_INET6)
1842 return s->sin6.sin6_port;
1843#endif
1844 return 0;
1845}
1846#endif
1847#if defined(USE_IPV6)
1848#define USA_IN_PORT_UNSAFE(s) \
1849 (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
1850#else
1851#define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
1852#endif
1853
1854/* Describes a string (chunk of memory). */
1855struct vec {
1856 const char *ptr;
1857 size_t len;
1858};
1859
1861 /* File properties filled by mg_stat: */
1862 uint64_t size;
1864 int is_directory; /* Set to 1 if mg_stat is called for a directory */
1865 int is_gzipped; /* Set to 1 if the content is gzipped, in which
1866 * case we need a "Content-Eencoding: gzip" header */
1867 int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
1868};
1869
1870
1872 /* File properties filled by mg_fopen: */
1873 FILE *fp;
1874};
1875
1876struct mg_file {
1879};
1880
1881
1882#define STRUCT_FILE_INITIALIZER \
1883 { \
1884 {(uint64_t)0, (time_t)0, 0, 0, 0}, \
1885 { \
1886 (FILE *)NULL \
1887 } \
1888 }
1889
1890
1891/* Describes listening socket, or socket which was accept()-ed by the master
1892 * thread and queued for future handling by the worker thread. */
1893struct socket {
1894 SOCKET sock; /* Listening socket */
1895 union usa lsa; /* Local socket address */
1896 union usa rsa; /* Remote socket address */
1897 unsigned char is_ssl; /* Is port SSL-ed */
1898 unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
1899 * port */
1900 unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
1901};
1902
1903
1904/* Enum const for all options must be in sync with
1905 * static struct mg_option config_options[]
1906 * This is tested in the unit test (test/private.c)
1907 * "Private Config Options"
1908 */
1909enum {
1910 /* Once for each server */
1914 CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
1915 * socket option typedef TCP_NODELAY. */
1920#if defined(__linux__)
1921 ALLOW_SENDFILE_CALL,
1922#endif
1923#if defined(_WIN32)
1924 CASE_SENSITIVE_FILES,
1925#endif
1930#if defined(USE_WEBSOCKET)
1931 WEBSOCKET_TIMEOUT,
1932 ENABLE_WEBSOCKET_PING_PONG,
1933#endif
1936#if defined(USE_LUA)
1937 LUA_BACKGROUND_SCRIPT,
1938 LUA_BACKGROUND_SCRIPT_PARAMS,
1939#endif
1940#if defined(USE_HTTP2)
1941 ENABLE_HTTP2,
1942#endif
1943
1944 /* Once for each domain */
1946
1949
1954#if defined(USE_TIMERS)
1955 CGI_TIMEOUT,
1956#endif
1957
1962#if defined(USE_TIMERS)
1963 CGI2_TIMEOUT,
1964#endif
1965
1966#if defined(USE_4_CGI)
1967 CGI3_EXTENSIONS,
1968 CGI3_ENVIRONMENT,
1969 CGI3_INTERPRETER,
1970 CGI3_INTERPRETER_ARGS,
1971#if defined(USE_TIMERS)
1972 CGI3_TIMEOUT,
1973#endif
1974
1975 CGI4_EXTENSIONS,
1976 CGI4_ENVIRONMENT,
1977 CGI4_INTERPRETER,
1978 CGI4_INTERPRETER_ARGS,
1979#if defined(USE_TIMERS)
1980 CGI4_TIMEOUT,
1981#endif
1982#endif
1983
1984 PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
2007
2008#if defined(USE_LUA)
2009 LUA_PRELOAD_FILE,
2010 LUA_SCRIPT_EXTENSIONS,
2011 LUA_SERVER_PAGE_EXTENSIONS,
2012#if defined(MG_EXPERIMENTAL_INTERFACES)
2013 LUA_DEBUG_PARAMS,
2014#endif
2015#endif
2016#if defined(USE_DUKTAPE)
2017 DUKTAPE_SCRIPT_EXTENSIONS,
2018#endif
2019
2020#if defined(USE_WEBSOCKET)
2021 WEBSOCKET_ROOT,
2022#endif
2023#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2024 LUA_WEBSOCKET_EXTENSIONS,
2025#endif
2026
2032#if !defined(NO_CACHING)
2035#endif
2036#if !defined(NO_SSL)
2038#endif
2041
2044
2045
2046/* Config option name, config types, default value.
2047 * Must be in the same order as the enum const above.
2048 */
2049static const struct mg_option config_options[] = {
2050
2051 /* Once for each server */
2052 {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
2053 {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
2054 {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
2055 {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
2056 {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
2057 {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2058 {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
2059 {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
2060#if defined(__linux__)
2061 {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2062#endif
2063#if defined(_WIN32)
2064 {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2065#endif
2066 {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
2067 {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2068 {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
2069 {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
2070#if defined(USE_WEBSOCKET)
2071 {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2072 {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
2073#endif
2074 {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2075 {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
2076#if defined(USE_LUA)
2077 {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
2078 {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
2079#endif
2080#if defined(USE_HTTP2)
2081 {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
2082#endif
2083
2084 /* Once for each domain */
2085 {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2086
2087 {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
2088 {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
2089
2090 {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
2091 {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2092 {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2093 {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2094#if defined(USE_TIMERS)
2095 {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2096#endif
2097
2098 {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2099 {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2100 {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2101 {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2102#if defined(USE_TIMERS)
2103 {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2104#endif
2105
2106#if defined(USE_4_CGI)
2107 {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2108 {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2109 {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2110 {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2111#if defined(USE_TIMERS)
2112 {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2113#endif
2114
2115 {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2116 {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2117 {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2118 {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2119#if defined(USE_TIMERS)
2120 {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2121#endif
2122#endif
2123
2124 {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2125 {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
2126 {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
2127 {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2128 {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
2129 {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2130 {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2131 {"index_files",
2133#if defined(USE_LUA)
2134 "index.xhtml,index.html,index.htm,"
2135 "index.lp,index.lsp,index.lua,index.cgi,"
2136 "index.shtml,index.php"},
2137#else
2138 "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
2139#endif
2140 {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
2141 {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
2142 {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
2143 {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
2144 {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
2145 {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2146
2147 {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
2148 {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
2149
2150 {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
2151 {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
2152 {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
2153 {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2154 {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
2155
2156 /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
2157 * as a minimum in 2020 */
2158 {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
2159
2160 {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
2161
2162#if defined(USE_LUA)
2163 {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
2164 {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2165 {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
2166#if defined(MG_EXPERIMENTAL_INTERFACES)
2167 {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
2168#endif
2169#endif
2170#if defined(USE_DUKTAPE)
2171 /* The support for duktape is still in alpha version state.
2172 * The name of this config option might change. */
2173 {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
2174#endif
2175
2176#if defined(USE_WEBSOCKET)
2177 {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2178#endif
2179#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2180 {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2181#endif
2182 {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
2183 {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
2184 {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
2185 {"access_control_allow_credentials", MG_CONFIG_TYPE_STRING, ""},
2186 {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
2187#if !defined(NO_CACHING)
2188 {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
2189 {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
2190#endif
2191#if !defined(NO_SSL)
2192 {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
2193#endif
2194 {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
2195 {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
2196
2197 {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
2198
2199
2200/* Check if the config_options and the corresponding enum have compatible
2201 * sizes. */
2202mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
2203 == (NUM_OPTIONS + 1),
2204 "config_options and enum not sync");
2205
2206
2208
2209
2211 /* Name/Pattern of the URI. */
2212 char *uri;
2213 size_t uri_len;
2214
2215 /* handler type */
2217
2218 /* Handler for http/https or authorization requests. */
2220 unsigned int refcount;
2222
2223 /* Handler for ws/wss (websocket) requests. */
2228
2229 /* accepted subprotocols for ws/wss requests. */
2231
2232 /* Handler for authorization requests */
2234
2235 /* User supplied argument for the handler function. */
2236 void *cbdata;
2237
2238 /* next handler in a linked list */
2240};
2241
2242
2243enum {
2249
2250
2252 SSL_CTX *ssl_ctx; /* SSL context */
2253 char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
2254 struct mg_handler_info *handlers; /* linked list of uri handlers */
2256
2257 /* Server nonce */
2258 uint64_t auth_nonce_mask; /* Mask for all nonce values */
2259 unsigned long nonce_count; /* Used nonces, used for authentication */
2260
2261#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2262 /* linked list of shared lua websockets */
2263 struct mg_shared_lua_websocket_list *shared_lua_websockets;
2264#endif
2265
2266 /* Linked list of domains */
2268};
2269
2270
2271/* Stop flag can be "volatile" or require a lock.
2272 * MSDN uses volatile for "Interlocked" operations, but also explicitly
2273 * states a read operation for int is always atomic. */
2274#if defined(STOP_FLAG_NEEDS_LOCK)
2275
2276typedef ptrdiff_t volatile stop_flag_t;
2277
2278static int
2280{
2281 stop_flag_t sf = mg_atomic_add(f, 0);
2282 return (sf == 0);
2283}
2284
2285static int
2287{
2288 stop_flag_t sf = mg_atomic_add(f, 0);
2289 return (sf == 2);
2290}
2291
2292static void
2294{
2295 stop_flag_t sf;
2296 do {
2297 sf = mg_atomic_compare_and_swap(f, *f, v);
2298 } while (sf != v);
2299}
2300
2301#else /* STOP_FLAG_NEEDS_LOCK */
2302
2303typedef int volatile stop_flag_t;
2304#define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
2305#define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
2306#define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
2307
2308#endif /* STOP_FLAG_NEEDS_LOCK */
2309
2310
2312
2313 /* Part 1 - Physical context:
2314 * This holds threads, ports, timeouts, ...
2315 * set for the entire server, independent from the
2316 * addressed hostname.
2317 */
2318
2319 /* Connection related */
2320 int context_type; /* See CONTEXT_* above */
2321
2325
2326 struct mg_connection *worker_connections; /* The connection struct, pre-
2327 * allocated for each worker */
2328
2329#if defined(USE_SERVER_STATS)
2330 volatile ptrdiff_t active_connections;
2331 volatile ptrdiff_t max_active_connections;
2332 volatile ptrdiff_t total_connections;
2333 volatile ptrdiff_t total_requests;
2334 volatile int64_t total_data_read;
2335 volatile int64_t total_data_written;
2336#endif
2337
2338 /* Thread related */
2339 stop_flag_t stop_flag; /* Should we stop event loop */
2340 pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
2341
2342 pthread_t masterthreadid; /* The master thread ID */
2343 unsigned int
2344 cfg_worker_threads; /* The number of configured worker threads. */
2345 pthread_t *worker_threadids; /* The worker thread IDs */
2346 unsigned long starter_thread_idx; /* thread index which called mg_start */
2347
2348 /* Connection to thread dispatching */
2349#if defined(ALTERNATIVE_QUEUE)
2350 struct socket *client_socks;
2351 void **client_wait_events;
2352#else
2353 struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
2354 worker thread */
2355 volatile int sq_head; /* Head of the socket queue */
2356 volatile int sq_tail; /* Tail of the socket queue */
2357 pthread_cond_t sq_full; /* Signaled when socket is produced */
2358 pthread_cond_t sq_empty; /* Signaled when socket is consumed */
2359 volatile int sq_blocked; /* Status information: sq is full */
2360 int sq_size; /* No of elements in socket queue */
2361#if defined(USE_SERVER_STATS)
2362 int sq_max_fill;
2363#endif /* USE_SERVER_STATS */
2364#endif /* ALTERNATIVE_QUEUE */
2365
2366 /* Memory related */
2367 unsigned int max_request_size; /* The max request size */
2368
2369#if defined(USE_SERVER_STATS)
2370 struct mg_memory_stat ctx_memory;
2371#endif
2372
2373 /* Operating system related */
2374 char *systemName; /* What operating system is running */
2375 time_t start_time; /* Server start time, used for authentication
2376 * and for diagnstics. */
2377
2378#if defined(USE_TIMERS)
2379 struct ttimers *timers;
2380#endif
2381
2382 /* Lua specific: Background operations and shared websockets */
2383#if defined(USE_LUA)
2384 void *lua_background_state; /* lua_State (here as void *) */
2385 pthread_mutex_t lua_bg_mutex; /* Protect background state */
2386 int lua_bg_log_available; /* Use Lua background state for access log */
2387#endif
2388
2389 /* Server nonce */
2390 pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
2391 * ssl_cert_last_mtime, nonce_count, and
2392 * next (linked list) */
2393
2394 /* Server callbacks */
2395 struct mg_callbacks callbacks; /* User-defined callback function */
2396 void *user_data; /* User-defined data */
2397
2398 /* Part 2 - Logical domain:
2399 * This holds hostname, TLS certificate, document root, ...
2400 * set for a domain hosted at the server.
2401 * There may be multiple domains hosted at one physical server.
2402 * The default domain "dd" is the first element of a list of
2403 * domains.
2404 */
2405 struct mg_domain_context dd; /* default domain */
2406};
2407
2408
2409#if defined(USE_SERVER_STATS)
2410static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2411
2412static struct mg_memory_stat *
2413get_memory_stat(struct mg_context *ctx)
2414{
2415 if (ctx) {
2416 return &(ctx->ctx_memory);
2417 }
2418 return &mg_common_memory;
2419}
2420#endif
2421
2422enum {
2427
2428enum {
2433
2434
2435#if defined(USE_HTTP2)
2436#if !defined(HTTP2_DYN_TABLE_SIZE)
2437#define HTTP2_DYN_TABLE_SIZE (256)
2438#endif
2439
2440struct mg_http2_connection {
2441 uint32_t stream_id;
2442 uint32_t dyn_table_size;
2443 struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
2444};
2445#endif
2446
2447
2449 int connection_type; /* see CONNECTION_TYPE_* above */
2450 int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
2451 int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
2452 fully sent */
2453#if defined(USE_HTTP2)
2454 struct mg_http2_connection http2;
2455#endif
2456
2459
2462
2463#if defined(USE_SERVER_STATS)
2464 int conn_state; /* 0 = undef, numerical value may change in different
2465 * versions. For the current definition, see
2466 * mg_get_connection_info_impl */
2467#endif
2468
2469 SSL *ssl; /* SSL descriptor */
2470 struct socket client; /* Connected client */
2471 time_t conn_birth_time; /* Time (wall clock) when connection was
2472 * established */
2473#if defined(USE_SERVER_STATS)
2474 time_t conn_close_time; /* Time (wall clock) when connection was
2475 * closed (or 0 if still open) */
2476 double processing_time; /* Procesing time for one request. */
2477#endif
2478 struct timespec req_time; /* Time (since system start) when the request
2479 * was received */
2480 int64_t num_bytes_sent; /* Total bytes sent to client */
2481 int64_t content_len; /* How many bytes of content can be read
2482 * !is_chunked: Content-Length header value
2483 * or -1 (until connection closed,
2484 * not allowed for a request)
2485 * is_chunked: >= 0, appended gradually
2486 */
2487 int64_t consumed_content; /* How many bytes of content have been read */
2488 int is_chunked; /* Transfer-Encoding is chunked:
2489 * 0 = not chunked,
2490 * 1 = chunked, not yet, or some data read,
2491 * 2 = chunked, has error,
2492 * 3 = chunked, all data read except trailer,
2493 * 4 = chunked, all data read
2494 */
2495 char *buf; /* Buffer for received data */
2496 char *path_info; /* PATH_INFO part of the URL */
2497
2498 int must_close; /* 1 if connection must be closed */
2499 int accept_gzip; /* 1 if gzip encoding is accepted */
2500 int in_error_handler; /* 1 if in handler for user defined error
2501 * pages */
2502#if defined(USE_WEBSOCKET)
2503 int in_websocket_handling; /* 1 if in read_websocket */
2504#endif
2505#if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
2506 && defined(MG_EXPERIMENTAL_INTERFACES)
2507 /* Parameters for websocket data compression according to rfc7692 */
2508 int websocket_deflate_server_max_windows_bits;
2509 int websocket_deflate_client_max_windows_bits;
2510 int websocket_deflate_server_no_context_takeover;
2511 int websocket_deflate_client_no_context_takeover;
2512 int websocket_deflate_initialized;
2513 int websocket_deflate_flush;
2514 z_stream websocket_deflate_state;
2515 z_stream websocket_inflate_state;
2516#endif
2517 int handled_requests; /* Number of requests handled by this connection
2518 */
2519 int buf_size; /* Buffer size */
2520 int request_len; /* Size of the request + headers in a buffer */
2521 int data_len; /* Total size of data in a buffer */
2522 int status_code; /* HTTP reply status code, e.g. 200 */
2523 int throttle; /* Throttling, bytes/sec. <= 0 means no
2524 * throttle */
2525
2526 time_t last_throttle_time; /* Last time throttled data was sent */
2527 int last_throttle_bytes; /* Bytes sent this second */
2528 pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
2529 * atomic transmissions for websockets */
2530#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2531 void *lua_websocket_state; /* Lua_State for a websocket connection */
2532#endif
2533
2534 void *tls_user_ptr; /* User defined pointer in thread local storage,
2535 * for quick access */
2536};
2537
2538
2539/* Directory entry */
2540struct de {
2544};
2545
2546
2547#define mg_cry_internal(conn, fmt, ...) \
2548 mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
2549
2550#define mg_cry_ctx_internal(ctx, fmt, ...) \
2551 mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
2552
2553static void mg_cry_internal_wrap(const struct mg_connection *conn,
2554 struct mg_context *ctx,
2555 const char *func,
2556 unsigned line,
2557 const char *fmt,
2558 ...) PRINTF_ARGS(5, 6);
2559
2560
2561#if !defined(NO_THREAD_NAME)
2562#if defined(_WIN32) && defined(_MSC_VER)
2563/* Set the thread name for debugging purposes in Visual Studio
2564 * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
2565 */
2566#pragma pack(push, 8)
2567typedef struct tagTHREADNAME_INFO {
2568 DWORD dwType; /* Must be 0x1000. */
2569 LPCSTR szName; /* Pointer to name (in user addr space). */
2570 DWORD dwThreadID; /* Thread ID (-1=caller thread). */
2571 DWORD dwFlags; /* Reserved for future use, must be zero. */
2572} THREADNAME_INFO;
2573#pragma pack(pop)
2574
2575#elif defined(__linux__)
2576
2577#include <sys/prctl.h>
2578#include <sys/sendfile.h>
2579#if defined(ALTERNATIVE_QUEUE)
2580#include <sys/eventfd.h>
2581#endif /* ALTERNATIVE_QUEUE */
2582
2583
2584#if defined(ALTERNATIVE_QUEUE)
2585
2586static void *
2587event_create(void)
2588{
2589 int evhdl = eventfd(0, EFD_CLOEXEC);
2590 int *ret;
2591
2592 if (evhdl == -1) {
2593 /* Linux uses -1 on error, Windows NULL. */
2594 /* However, Linux does not return 0 on success either. */
2595 return 0;
2596 }
2597
2598 ret = (int *)mg_malloc(sizeof(int));
2599 if (ret) {
2600 *ret = evhdl;
2601 } else {
2602 (void)close(evhdl);
2603 }
2604
2605 return (void *)ret;
2606}
2607
2608
2609static int
2610event_wait(void *eventhdl)
2611{
2612 uint64_t u;
2613 int evhdl, s;
2614
2615 if (!eventhdl) {
2616 /* error */
2617 return 0;
2618 }
2619 evhdl = *(int *)eventhdl;
2620
2621 s = (int)read(evhdl, &u, sizeof(u));
2622 if (s != sizeof(u)) {
2623 /* error */
2624 return 0;
2625 }
2626 (void)u; /* the value is not required */
2627 return 1;
2628}
2629
2630
2631static int
2632event_signal(void *eventhdl)
2633{
2634 uint64_t u = 1;
2635 int evhdl, s;
2636
2637 if (!eventhdl) {
2638 /* error */
2639 return 0;
2640 }
2641 evhdl = *(int *)eventhdl;
2642
2643 s = (int)write(evhdl, &u, sizeof(u));
2644 if (s != sizeof(u)) {
2645 /* error */
2646 return 0;
2647 }
2648 return 1;
2649}
2650
2651
2652static void
2653event_destroy(void *eventhdl)
2654{
2655 int evhdl;
2656
2657 if (!eventhdl) {
2658 /* error */
2659 return;
2660 }
2661 evhdl = *(int *)eventhdl;
2662
2663 close(evhdl);
2664 mg_free(eventhdl);
2665}
2666
2667
2668#endif
2669
2670#endif
2671
2672
2673#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2674
2675struct posix_event {
2676 pthread_mutex_t mutex;
2677 pthread_cond_t cond;
2678 int signaled;
2679};
2680
2681
2682static void *
2683event_create(void)
2684{
2685 struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
2686 if (ret == 0) {
2687 /* out of memory */
2688 return 0;
2689 }
2690 if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2691 /* pthread mutex not available */
2692 mg_free(ret);
2693 return 0;
2694 }
2695 if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2696 /* pthread cond not available */
2697 pthread_mutex_destroy(&(ret->mutex));
2698 mg_free(ret);
2699 return 0;
2700 }
2701 ret->signaled = 0;
2702 return (void *)ret;
2703}
2704
2705
2706static int
2707event_wait(void *eventhdl)
2708{
2709 struct posix_event *ev = (struct posix_event *)eventhdl;
2710 pthread_mutex_lock(&(ev->mutex));
2711 while (!ev->signaled) {
2712 pthread_cond_wait(&(ev->cond), &(ev->mutex));
2713 }
2714 ev->signaled = 0;
2715 pthread_mutex_unlock(&(ev->mutex));
2716 return 1;
2717}
2718
2719
2720static int
2721event_signal(void *eventhdl)
2722{
2723 struct posix_event *ev = (struct posix_event *)eventhdl;
2724 pthread_mutex_lock(&(ev->mutex));
2725 pthread_cond_signal(&(ev->cond));
2726 ev->signaled = 1;
2727 pthread_mutex_unlock(&(ev->mutex));
2728 return 1;
2729}
2730
2731
2732static void
2733event_destroy(void *eventhdl)
2734{
2735 struct posix_event *ev = (struct posix_event *)eventhdl;
2736 pthread_cond_destroy(&(ev->cond));
2737 pthread_mutex_destroy(&(ev->mutex));
2738 mg_free(ev);
2739}
2740#endif
2741
2742
2743static void
2745{
2746 char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
2747
2749 NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
2750
2751#if defined(_WIN32)
2752#if defined(_MSC_VER)
2753 /* Windows and Visual Studio Compiler */
2754 __try {
2755 THREADNAME_INFO info;
2756 info.dwType = 0x1000;
2757 info.szName = threadName;
2758 info.dwThreadID = ~0U;
2759 info.dwFlags = 0;
2760
2761 RaiseException(0x406D1388,
2762 0,
2763 sizeof(info) / sizeof(ULONG_PTR),
2764 (ULONG_PTR *)&info);
2765 } __except (EXCEPTION_EXECUTE_HANDLER) {
2766 }
2767#elif defined(__MINGW32__)
2768 /* No option known to set thread name for MinGW known */
2769#endif
2770#elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
2771 && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
2772 /* pthread_setname_np first appeared in glibc in version 2.12 */
2773#if defined(__MACH__)
2774 /* OS X only current thread name can be changed */
2775 (void)pthread_setname_np(threadName);
2776#else
2777 (void)pthread_setname_np(pthread_self(), threadName);
2778#endif
2779#elif defined(__linux__)
2780 /* On Linux we can use the prctl function.
2781 * When building for Linux Standard Base (LSB) use
2782 * NO_THREAD_NAME. However, thread names are a big
2783 * help for debugging, so the stadard is to set them.
2784 */
2785 (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
2786#endif
2787}
2788#else /* !defined(NO_THREAD_NAME) */
2789void
2790mg_set_thread_name(const char *threadName)
2791{
2792}
2793#endif
2794
2795
2796const struct mg_option *
2798{
2799 return config_options;
2800}
2801
2802
2803/* Do not open file (unused) */
2804#define MG_FOPEN_MODE_NONE (0)
2805
2806/* Open file for read only access */
2807#define MG_FOPEN_MODE_READ (1)
2808
2809/* Open file for writing, create and overwrite */
2810#define MG_FOPEN_MODE_WRITE (2)
2811
2812/* Open file for writing, create and append */
2813#define MG_FOPEN_MODE_APPEND (4)
2814
2815
2816static int
2817is_file_opened(const struct mg_file_access *fileacc)
2818{
2819 if (!fileacc) {
2820 return 0;
2821 }
2822
2823 return (fileacc->fp != NULL);
2824}
2825
2826
2827#if !defined(NO_FILESYSTEMS)
2828static int mg_stat(const struct mg_connection *conn,
2829 const char *path,
2830 struct mg_file_stat *filep);
2831
2832
2833/* Reject files with special characters (for Windows) */
2834static int
2835mg_path_suspicious(const struct mg_connection *conn, const char *path)
2836{
2837 const uint8_t *c = (const uint8_t *)path;
2838 (void)conn; /* not used */
2839
2840 if ((c == NULL) || (c[0] == 0)) {
2841 /* Null pointer or empty path --> suspicious */
2842 return 1;
2843 }
2844
2845#if defined(_WIN32)
2846 while (*c) {
2847 if (*c < 32) {
2848 /* Control character */
2849 return 1;
2850 }
2851 if ((*c == '>') || (*c == '<') || (*c == '|')) {
2852 /* stdin/stdout redirection character */
2853 return 1;
2854 }
2855 if ((*c == '*') || (*c == '?')) {
2856 /* Wildcard character */
2857 return 1;
2858 }
2859 if (*c == '"') {
2860 /* Windows quotation */
2861 return 1;
2862 }
2863 c++;
2864 }
2865#endif
2866
2867 /* Nothing suspicious found */
2868 return 0;
2869}
2870
2871
2872/* mg_fopen will open a file either in memory or on the disk.
2873 * The input parameter path is a string in UTF-8 encoding.
2874 * The input parameter mode is MG_FOPEN_MODE_*
2875 * On success, fp will be set in the output struct mg_file.
2876 * All status members will also be set.
2877 * The function returns 1 on success, 0 on error. */
2878static int
2879mg_fopen(const struct mg_connection *conn,
2880 const char *path,
2881 int mode,
2882 struct mg_file *filep)
2883{
2884 int found;
2885
2886 if (!filep) {
2887 return 0;
2888 }
2889 filep->access.fp = NULL;
2890
2891 if (mg_path_suspicious(conn, path)) {
2892 return 0;
2893 }
2894
2895 /* filep is initialized in mg_stat: all fields with memset to,
2896 * some fields like size and modification date with values */
2897 found = mg_stat(conn, path, &(filep->stat));
2898
2899 if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
2900 /* file does not exist and will not be created */
2901 return 0;
2902 }
2903
2904#if defined(_WIN32)
2905 {
2906 wchar_t wbuf[UTF16_PATH_MAX];
2907 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
2908 switch (mode) {
2909 case MG_FOPEN_MODE_READ:
2910 filep->access.fp = _wfopen(wbuf, L"rb");
2911 break;
2913 filep->access.fp = _wfopen(wbuf, L"wb");
2914 break;
2916 filep->access.fp = _wfopen(wbuf, L"ab");
2917 break;
2918 }
2919 }
2920#else
2921 /* Linux et al already use unicode. No need to convert. */
2922 switch (mode) {
2923 case MG_FOPEN_MODE_READ:
2924 filep->access.fp = fopen(path, "r");
2925 break;
2927 filep->access.fp = fopen(path, "w");
2928 break;
2930 filep->access.fp = fopen(path, "a");
2931 break;
2932 }
2933
2934#endif
2935 if (!found) {
2936 /* File did not exist before fopen was called.
2937 * Maybe it has been created now. Get stat info
2938 * like creation time now. */
2939 found = mg_stat(conn, path, &(filep->stat));
2940 (void)found;
2941 }
2942
2943 /* return OK if file is opened */
2944 return (filep->access.fp != NULL);
2945}
2946
2947
2948/* return 0 on success, just like fclose */
2949static int
2951{
2952 int ret = -1;
2953 if (fileacc != NULL) {
2954 if (fileacc->fp != NULL) {
2955 ret = fclose(fileacc->fp);
2956 }
2957 /* reset all members of fileacc */
2958 memset(fileacc, 0, sizeof(*fileacc));
2959 }
2960 return ret;
2961}
2962#endif /* NO_FILESYSTEMS */
2963
2964
2965static void
2966mg_strlcpy(char *dst, const char *src, size_t n)
2967{
2968 for (; *src != '\0' && n > 1; n--) {
2969 *dst++ = *src++;
2970 }
2971 *dst = '\0';
2972}
2973
2974
2975static int
2976lowercase(const char *s)
2977{
2978 return tolower((unsigned char)*s);
2979}
2980
2981
2982int
2983mg_strncasecmp(const char *s1, const char *s2, size_t len)
2984{
2985 int diff = 0;
2986
2987 if (len > 0) {
2988 do {
2989 diff = lowercase(s1++) - lowercase(s2++);
2990 } while (diff == 0 && s1[-1] != '\0' && --len > 0);
2991 }
2992
2993 return diff;
2994}
2995
2996
2997int
2998mg_strcasecmp(const char *s1, const char *s2)
2999{
3000 int diff;
3001
3002 do {
3003 diff = lowercase(s1++) - lowercase(s2++);
3004 } while (diff == 0 && s1[-1] != '\0');
3005
3006 return diff;
3007}
3008
3009
3010static char *
3011mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
3012{
3013 char *p;
3014 (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
3015 * defined */
3016
3017 if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
3018 mg_strlcpy(p, ptr, len + 1);
3019 }
3020
3021 return p;
3022}
3023
3024
3025static char *
3026mg_strdup_ctx(const char *str, struct mg_context *ctx)
3027{
3028 return mg_strndup_ctx(str, strlen(str), ctx);
3029}
3030
3031static char *
3032mg_strdup(const char *str)
3033{
3034 return mg_strndup_ctx(str, strlen(str), NULL);
3035}
3036
3037
3038static const char *
3039mg_strcasestr(const char *big_str, const char *small_str)
3040{
3041 size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3042
3043 if (big_len >= small_len) {
3044 for (i = 0; i <= (big_len - small_len); i++) {
3045 if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
3046 return big_str + i;
3047 }
3048 }
3049 }
3050
3051 return NULL;
3052}
3053
3054
3055/* Return null terminated string of given maximum length.
3056 * Report errors if length is exceeded. */
3057static void
3058mg_vsnprintf(const struct mg_connection *conn,
3059 int *truncated,
3060 char *buf,
3061 size_t buflen,
3062 const char *fmt,
3063 va_list ap)
3064{
3065 int n, ok;
3066
3067 if (buflen == 0) {
3068 if (truncated) {
3069 *truncated = 1;
3070 }
3071 return;
3072 }
3073
3074#if defined(__clang__)
3075#pragma clang diagnostic push
3076#pragma clang diagnostic ignored "-Wformat-nonliteral"
3077 /* Using fmt as a non-literal is intended here, since it is mostly called
3078 * indirectly by mg_snprintf */
3079#endif
3080
3081 n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
3082 ok = (n >= 0) && ((size_t)n < buflen);
3083
3084#if defined(__clang__)
3085#pragma clang diagnostic pop
3086#endif
3087
3088 if (ok) {
3089 if (truncated) {
3090 *truncated = 0;
3091 }
3092 } else {
3093 if (truncated) {
3094 *truncated = 1;
3095 }
3096 mg_cry_internal(conn,
3097 "truncating vsnprintf buffer: [%.*s]",
3098 (int)((buflen > 200) ? 200 : (buflen - 1)),
3099 buf);
3100 n = (int)buflen - 1;
3101 }
3102 buf[n] = '\0';
3103}
3104
3105
3106static void
3107mg_snprintf(const struct mg_connection *conn,
3108 int *truncated,
3109 char *buf,
3110 size_t buflen,
3111 const char *fmt,
3112 ...)
3113{
3114 va_list ap;
3115
3116 va_start(ap, fmt);
3117 mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
3118 va_end(ap);
3119}
3120
3121
3122static int
3124{
3125 int i;
3126
3127 for (i = 0; config_options[i].name != NULL; i++) {
3128 if (strcmp(config_options[i].name, name) == 0) {
3129 return i;
3130 }
3131 }
3132 return -1;
3133}
3134
3135
3136const char *
3137mg_get_option(const struct mg_context *ctx, const char *name)
3138{
3139 int i;
3140 if ((i = get_option_index(name)) == -1) {
3141 return NULL;
3142 } else if (!ctx || ctx->dd.config[i] == NULL) {
3143 return "";
3144 } else {
3145 return ctx->dd.config[i];
3146 }
3147}
3148
3149#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3150
3151struct mg_context *
3153{
3154 return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
3155}
3156
3157
3158void *
3160{
3161 return (ctx == NULL) ? NULL : ctx->user_data;
3162}
3163
3164
3165void *
3167{
3168 return mg_get_user_data(mg_get_context(conn));
3169}
3170
3171
3172void *
3174{
3175 /* both methods should return the same pointer */
3176 if (conn) {
3177 /* quick access, in case conn is known */
3178 return conn->tls_user_ptr;
3179 } else {
3180 /* otherwise get pointer from thread local storage (TLS) */
3181 struct mg_workerTLS *tls =
3182 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3183 return tls->user_ptr;
3184 }
3185}
3186
3187
3188void
3189mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
3190{
3191 if (const_conn != NULL) {
3192 /* Const cast, since "const struct mg_connection *" does not mean
3193 * the connection object is not modified. Here "const" is used,
3194 * to indicate mg_read/mg_write/mg_send/.. must not be called. */
3195 struct mg_connection *conn = (struct mg_connection *)const_conn;
3196 conn->request_info.conn_data = data;
3197 }
3198}
3199
3200
3201void *
3203{
3204 if (conn != NULL) {
3205 return conn->request_info.conn_data;
3206 }
3207 return NULL;
3208}
3209
3210
3211int
3213 int size,
3214 struct mg_server_port *ports)
3215{
3216 int i, cnt = 0;
3217
3218 if (size <= 0) {
3219 return -1;
3220 }
3221 memset(ports, 0, sizeof(*ports) * (size_t)size);
3222 if (!ctx) {
3223 return -1;
3224 }
3225 if (!ctx->listening_sockets) {
3226 return -1;
3227 }
3228
3229 for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
3230
3231 ports[cnt].port =
3232 ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
3233 ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
3234 ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
3235
3236 if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
3237 /* IPv4 */
3238 ports[cnt].protocol = 1;
3239 cnt++;
3240 } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
3241 /* IPv6 */
3242 ports[cnt].protocol = 3;
3243 cnt++;
3244 }
3245 }
3246
3247 return cnt;
3248}
3249
3250
3251#if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
3252#define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
3253#endif
3254
3255static void
3256sockaddr_to_string(char *buf, size_t len, const union usa *usa)
3257{
3258 buf[0] = '\0';
3259
3260 if (!usa) {
3261 return;
3262 }
3263
3264 if (usa->sa.sa_family == AF_INET) {
3265 getnameinfo(&usa->sa,
3266 sizeof(usa->sin),
3267 buf,
3268 (unsigned)len,
3269 NULL,
3270 0,
3271 NI_NUMERICHOST);
3272 }
3273#if defined(USE_IPV6)
3274 else if (usa->sa.sa_family == AF_INET6) {
3275 getnameinfo(&usa->sa,
3276 sizeof(usa->sin6),
3277 buf,
3278 (unsigned)len,
3279 NULL,
3280 0,
3281 NI_NUMERICHOST);
3282 }
3283#endif
3284#if defined(USE_X_DOM_SOCKET)
3285 else if (usa->sa.sa_family == AF_UNIX) {
3286 /* TODO: Define a remote address for unix domain sockets.
3287 * This code will always return "localhost", identical to http+tcp:
3288 getnameinfo(&usa->sa,
3289 sizeof(usa->sun),
3290 buf,
3291 (unsigned)len,
3292 NULL,
3293 0,
3294 NI_NUMERICHOST);
3295 */
3296 strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
3297 buf[len-1] = 0;
3298 }
3299#endif
3300}
3301
3302
3303/* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
3304 * included in all responses other than 100, 101, 5xx. */
3305static void
3306gmt_time_string(char *buf, size_t buf_len, time_t *t)
3307{
3308#if !defined(REENTRANT_TIME)
3309 struct tm *tm;
3310
3311 tm = ((t != NULL) ? gmtime(t) : NULL);
3312 if (tm != NULL) {
3313#else
3314 struct tm _tm;
3315 struct tm *tm = &_tm;
3316
3317 if (t != NULL) {
3318 gmtime_r(t, tm);
3319#endif
3320 strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
3321 } else {
3322 mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3323 buf[buf_len - 1] = '\0';
3324 }
3325}
3326
3327
3328/* difftime for struct timespec. Return value is in seconds. */
3329static double
3330mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
3331{
3332 return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3333 + (double)(ts_now->tv_sec - ts_before->tv_sec);
3334}
3335
3336
3337#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3338static void mg_cry_internal_impl(const struct mg_connection *conn,
3339 const char *func,
3340 unsigned line,
3341 const char *fmt,
3342 va_list ap);
3343#include "external_mg_cry_internal_impl.inl"
3344#elif !defined(NO_FILESYSTEMS)
3345
3346/* Print error message to the opened error log stream. */
3347static void
3349 const char *func,
3350 unsigned line,
3351 const char *fmt,
3352 va_list ap)
3353{
3354 char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
3355 struct mg_file fi;
3356 time_t timestamp;
3357
3358 /* Unused, in the RELEASE build */
3359 (void)func;
3360 (void)line;
3361
3362#if defined(GCC_DIAGNOSTIC)
3363#pragma GCC diagnostic push
3364#pragma GCC diagnostic ignored "-Wformat-nonliteral"
3365#endif
3366
3367 IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
3368
3369#if defined(GCC_DIAGNOSTIC)
3370#pragma GCC diagnostic pop
3371#endif
3372
3373 buf[sizeof(buf) - 1] = 0;
3374
3375 DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
3376
3377 if (!conn) {
3378 puts(buf);
3379 return;
3380 }
3381
3382 /* Do not lock when getting the callback value, here and below.
3383 * I suppose this is fine, since function cannot disappear in the
3384 * same way string option can. */
3385 if ((conn->phys_ctx->callbacks.log_message == NULL)
3386 || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
3387
3388 if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
3389 if (mg_fopen(conn,
3392 &fi)
3393 == 0) {
3394 fi.access.fp = NULL;
3395 }
3396 } else {
3397 fi.access.fp = NULL;
3398 }
3399
3400 if (fi.access.fp != NULL) {
3401 flockfile(fi.access.fp);
3402 timestamp = time(NULL);
3403
3404 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
3405 fprintf(fi.access.fp,
3406 "[%010lu] [error] [client %s] ",
3407 (unsigned long)timestamp,
3408 src_addr);
3409
3410 if (conn->request_info.request_method != NULL) {
3411 fprintf(fi.access.fp,
3412 "%s %s: ",
3416 : "");
3417 }
3418
3419 fprintf(fi.access.fp, "%s", buf);
3420 fputc('\n', fi.access.fp);
3421 fflush(fi.access.fp);
3422 funlockfile(fi.access.fp);
3423 (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
3424 * mg_cry here anyway ;-) */
3425 }
3426 }
3427}
3428#else
3429#error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
3430#endif /* Externally provided function */
3431
3432
3433/* Construct fake connection structure. Used for logging, if connection
3434 * is not applicable at the moment of logging. */
3435static struct mg_connection *
3437{
3438 static const struct mg_connection conn_zero = {0};
3439 *fc = conn_zero;
3440 fc->phys_ctx = ctx;
3441 fc->dom_ctx = &(ctx->dd);
3442 return fc;
3443}
3444
3445
3446static void
3448 struct mg_context *ctx,
3449 const char *func,
3450 unsigned line,
3451 const char *fmt,
3452 ...)
3453{
3454 va_list ap;
3455 va_start(ap, fmt);
3456 if (!conn && ctx) {
3457 struct mg_connection fc;
3458 mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
3459 } else {
3460 mg_cry_internal_impl(conn, func, line, fmt, ap);
3461 }
3462 va_end(ap);
3463}
3464
3465
3466void
3467mg_cry(const struct mg_connection *conn, const char *fmt, ...)
3468{
3469 va_list ap;
3470 va_start(ap, fmt);
3471 mg_cry_internal_impl(conn, "user", 0, fmt, ap);
3472 va_end(ap);
3473}
3474
3475
3476#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3477
3478
3479const char *
3481{
3482 return CIVETWEB_VERSION;
3483}
3484
3485
3486const struct mg_request_info *
3488{
3489 if (!conn) {
3490 return NULL;
3491 }
3492#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3494 char txt[16];
3495 struct mg_workerTLS *tls =
3496 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3497
3498 sprintf(txt, "%03i", conn->response_info.status_code);
3499 if (strlen(txt) == 3) {
3500 memcpy(tls->txtbuf, txt, 4);
3501 } else {
3502 strcpy(tls->txtbuf, "ERR");
3503 }
3504
3505 ((struct mg_connection *)conn)->request_info.local_uri =
3506 tls->txtbuf; /* use thread safe buffer */
3507 ((struct mg_connection *)conn)->request_info.local_uri_raw =
3508 tls->txtbuf; /* use the same thread safe buffer */
3509 ((struct mg_connection *)conn)->request_info.request_uri =
3510 tls->txtbuf; /* use the same thread safe buffer */
3511
3512 ((struct mg_connection *)conn)->request_info.num_headers =
3514 memcpy(((struct mg_connection *)conn)->request_info.http_headers,
3516 sizeof(conn->response_info.http_headers));
3517 } else
3518#endif
3520 return NULL;
3521 }
3522 return &conn->request_info;
3523}
3524
3525
3526const struct mg_response_info *
3528{
3529 if (!conn) {
3530 return NULL;
3531 }
3533 return NULL;
3534 }
3535 return &conn->response_info;
3536}
3537
3538
3539static const char *
3541{
3542#if defined(__clang__)
3543#pragma clang diagnostic push
3544#pragma clang diagnostic ignored "-Wunreachable-code"
3545 /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
3546 * not supported. Clang raises an "unreachable code" warning for parts of ?:
3547 * unreachable, but splitting into four different #ifdef clauses here is
3548 * more complicated.
3549 */
3550#endif
3551
3552 const struct mg_request_info *ri = &conn->request_info;
3553
3554 const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
3555 ? (ri->is_ssl ? "wss" : "ws")
3556 : (ri->is_ssl ? "https" : "http"));
3557
3558 return proto;
3559
3560#if defined(__clang__)
3561#pragma clang diagnostic pop
3562#endif
3563}
3564
3565
3566static int
3568 char *buf,
3569 size_t buflen,
3570 const char *define_proto,
3571 int define_port,
3572 const char *define_uri)
3573{
3574 if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3575 return -1;
3576 } else {
3577 int truncated = 0;
3578 const struct mg_request_info *ri = &conn->request_info;
3579
3580 const char *proto =
3581 (define_proto != NULL) ? define_proto : get_proto_name(conn);
3582 const char *uri =
3583 (define_uri != NULL)
3584 ? define_uri
3585 : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
3586 int port = (define_port > 0) ? define_port : ri->server_port;
3587 int default_port = 80;
3588
3589 if (uri == NULL) {
3590 return -1;
3591 }
3592
3593#if defined(USE_X_DOM_SOCKET)
3594 if (conn->client.lsa.sa.sa_family == AF_UNIX) {
3595 /* TODO: Define and document a link for UNIX domain sockets. */
3596 /* There seems to be no official standard for this.
3597 * Common uses seem to be "httpunix://", "http.unix://" or
3598 * "http+unix://" as a protocol definition string, followed by
3599 * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
3600 * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
3601 * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
3602 * "" (completely skipping the server name part). In any case, the
3603 * last part is the server local path. */
3604 const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
3605 mg_snprintf(conn,
3606 &truncated,
3607 buf,
3608 buflen,
3609 "%s.unix://%s%s",
3610 proto,
3611 server_name,
3612 ri->local_uri);
3613 default_port = 0;
3614 return 0;
3615 }
3616#endif
3617
3618 if (define_proto) {
3619 /* If we got a protocol name, use the default port accordingly. */
3620 if ((0 == strcmp(define_proto, "https"))
3621 || (0 == strcmp(define_proto, "wss"))) {
3622 default_port = 443;
3623 }
3624 } else if (ri->is_ssl) {
3625 /* If we did not get a protocol name, use TLS as default if it is
3626 * already used. */
3627 default_port = 443;
3628 }
3629
3630 {
3631#if defined(USE_IPV6)
3632 int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
3633#endif
3634 int auth_domain_check_enabled =
3636 && (!mg_strcasecmp(
3637 conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
3638
3639 const char *server_domain =
3641
3642 char portstr[16];
3643 char server_ip[48];
3644
3645 if (port != default_port) {
3646 sprintf(portstr, ":%u", (unsigned)port);
3647 } else {
3648 portstr[0] = 0;
3649 }
3650
3651 if (!auth_domain_check_enabled || !server_domain) {
3652
3653 sockaddr_to_string(server_ip,
3654 sizeof(server_ip),
3655 &conn->client.lsa);
3656
3657 server_domain = server_ip;
3658 }
3659
3660 mg_snprintf(conn,
3661 &truncated,
3662 buf,
3663 buflen,
3664#if defined(USE_IPV6)
3665 "%s://%s%s%s%s%s",
3666 proto,
3667 (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
3668 server_domain,
3669 (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
3670#else
3671 "%s://%s%s%s",
3672 proto,
3673 server_domain,
3674#endif
3675 portstr,
3676 ri->local_uri);
3677
3678 if (truncated) {
3679 return -1;
3680 }
3681 return 0;
3682 }
3683 }
3684}
3685
3686
3687int
3688mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
3689{
3690 return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
3691}
3692
3693
3694/* Skip the characters until one of the delimiters characters found.
3695 * 0-terminate resulting word. Skip the delimiter and following whitespaces.
3696 * Advance pointer to buffer to the next word. Return found 0-terminated
3697 * word.
3698 * Delimiters can be quoted with quotechar. */
3699static char *
3700skip_quoted(char **buf,
3701 const char *delimiters,
3702 const char *whitespace,
3703 char quotechar)
3704{
3705 char *p, *begin_word, *end_word, *end_whitespace;
3706
3707 begin_word = *buf;
3708 end_word = begin_word + strcspn(begin_word, delimiters);
3709
3710 /* Check for quotechar */
3711 if (end_word > begin_word) {
3712 p = end_word - 1;
3713 while (*p == quotechar) {
3714 /* While the delimiter is quoted, look for the next delimiter.
3715 */
3716 /* This happens, e.g., in calls from parse_auth_header,
3717 * if the user name contains a " character. */
3718
3719 /* If there is anything beyond end_word, copy it. */
3720 if (*end_word != '\0') {
3721 size_t end_off = strcspn(end_word + 1, delimiters);
3722 memmove(p, end_word, end_off + 1);
3723 p += end_off; /* p must correspond to end_word - 1 */
3724 end_word += end_off + 1;
3725 } else {
3726 *p = '\0';
3727 break;
3728 }
3729 }
3730 for (p++; p < end_word; p++) {
3731 *p = '\0';
3732 }
3733 }
3734
3735 if (*end_word == '\0') {
3736 *buf = end_word;
3737 } else {
3738
3739#if defined(GCC_DIAGNOSTIC)
3740 /* Disable spurious conversion warning for GCC */
3741#pragma GCC diagnostic push
3742#pragma GCC diagnostic ignored "-Wsign-conversion"
3743#endif /* defined(GCC_DIAGNOSTIC) */
3744
3745 end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
3746
3747#if defined(GCC_DIAGNOSTIC)
3748#pragma GCC diagnostic pop
3749#endif /* defined(GCC_DIAGNOSTIC) */
3750
3751 for (p = end_word; p < end_whitespace; p++) {
3752 *p = '\0';
3753 }
3754
3755 *buf = end_whitespace;
3756 }
3757
3758 return begin_word;
3759}
3760
3761
3762/* Return HTTP header value, or NULL if not found. */
3763static const char *
3764get_header(const struct mg_header *hdr, int num_hdr, const char *name)
3765{
3766 int i;
3767 for (i = 0; i < num_hdr; i++) {
3768 if (!mg_strcasecmp(name, hdr[i].name)) {
3769 return hdr[i].value;
3770 }
3771 }
3772
3773 return NULL;
3774}
3775
3776
3777#if defined(USE_WEBSOCKET)
3778/* Retrieve requested HTTP header multiple values, and return the number of
3779 * found occurrences */
3780static int
3781get_req_headers(const struct mg_request_info *ri,
3782 const char *name,
3783 const char **output,
3784 int output_max_size)
3785{
3786 int i;
3787 int cnt = 0;
3788 if (ri) {
3789 for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
3790 if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
3791 output[cnt++] = ri->http_headers[i].value;
3792 }
3793 }
3794 }
3795 return cnt;
3796}
3797#endif
3798
3799
3800const char *
3801mg_get_header(const struct mg_connection *conn, const char *name)
3802{
3803 if (!conn) {
3804 return NULL;
3805 }
3806
3810 name);
3811 }
3815 name);
3816 }
3817 return NULL;
3818}
3819
3820
3821static const char *
3823{
3824 if (!conn) {
3825 return NULL;
3826 }
3827
3829 return conn->request_info.http_version;
3830 }
3832 return conn->response_info.http_version;
3833 }
3834 return NULL;
3835}
3836
3837
3838/* A helper function for traversing a comma separated list of values.
3839 * It returns a list pointer shifted to the next value, or NULL if the end
3840 * of the list found.
3841 * Value is stored in val vector. If value has form "x=y", then eq_val
3842 * vector is initialized to point to the "y" part, and val vector length
3843 * is adjusted to point only to "x". */
3844static const char *
3845next_option(const char *list, struct vec *val, struct vec *eq_val)
3846{
3847 int end;
3848
3849reparse:
3850 if (val == NULL || list == NULL || *list == '\0') {
3851 /* End of the list */
3852 return NULL;
3853 }
3854
3855 /* Skip over leading LWS */
3856 while (*list == ' ' || *list == '\t')
3857 list++;
3858
3859 val->ptr = list;
3860 if ((list = strchr(val->ptr, ',')) != NULL) {
3861 /* Comma found. Store length and shift the list ptr */
3862 val->len = ((size_t)(list - val->ptr));
3863 list++;
3864 } else {
3865 /* This value is the last one */
3866 list = val->ptr + strlen(val->ptr);
3867 val->len = ((size_t)(list - val->ptr));
3868 }
3869
3870 /* Adjust length for trailing LWS */
3871 end = (int)val->len - 1;
3872 while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
3873 end--;
3874 val->len = (size_t)(end) + (size_t)(1);
3875
3876 if (val->len == 0) {
3877 /* Ignore any empty entries. */
3878 goto reparse;
3879 }
3880
3881 if (eq_val != NULL) {
3882 /* Value has form "x=y", adjust pointers and lengths
3883 * so that val points to "x", and eq_val points to "y". */
3884 eq_val->len = 0;
3885 eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
3886 if (eq_val->ptr != NULL) {
3887 eq_val->ptr++; /* Skip over '=' character */
3888 eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
3889 val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
3890 }
3891 }
3892
3893 return list;
3894}
3895
3896
3897/* A helper function for checking if a comma separated list of values
3898 * contains
3899 * the given option (case insensitvely).
3900 * 'header' can be NULL, in which case false is returned. */
3901static int
3902header_has_option(const char *header, const char *option)
3903{
3904 struct vec opt_vec;
3905 struct vec eq_vec;
3906
3907 DEBUG_ASSERT(option != NULL);
3908 DEBUG_ASSERT(option[0] != '\0');
3909
3910 while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
3911 if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
3912 return 1;
3913 }
3914
3915 return 0;
3916}
3917
3918
3919/* Perform case-insensitive match of string against pattern */
3920static ptrdiff_t
3921match_prefix(const char *pattern, size_t pattern_len, const char *str)
3922{
3923 const char *or_str;
3924 ptrdiff_t i, j, len, res;
3925
3926 if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
3927 res = match_prefix(pattern, (size_t)(or_str - pattern), str);
3928 return (res > 0) ? res
3929 : match_prefix(or_str + 1,
3930 (size_t)((pattern + pattern_len)
3931 - (or_str + 1)),
3932 str);
3933 }
3934
3935 for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
3936 if ((pattern[i] == '?') && (str[j] != '\0')) {
3937 continue;
3938 } else if (pattern[i] == '$') {
3939 return (str[j] == '\0') ? j : -1;
3940 } else if (pattern[i] == '*') {
3941 i++;
3942 if (pattern[i] == '*') {
3943 i++;
3944 len = (ptrdiff_t)strlen(str + j);
3945 } else {
3946 len = (ptrdiff_t)strcspn(str + j, "/");
3947 }
3948 if (i == (ptrdiff_t)pattern_len) {
3949 return j + len;
3950 }
3951 do {
3952 res = match_prefix(pattern + i,
3953 (pattern_len - (size_t)i),
3954 str + j + len);
3955 } while (res == -1 && len-- > 0);
3956 return (res == -1) ? -1 : j + res + len;
3957 } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
3958 return -1;
3959 }
3960 }
3961 return (ptrdiff_t)j;
3962}
3963
3964
3965static ptrdiff_t
3966match_prefix_strlen(const char *pattern, const char *str)
3967{
3968 if (pattern == NULL) {
3969 return -1;
3970 }
3971 return match_prefix(pattern, strlen(pattern), str);
3972}
3973
3974
3975/* HTTP 1.1 assumes keep alive if "Connection:" header is not set
3976 * This function must tolerate situations when connection info is not
3977 * set up, for example if request parsing failed. */
3978static int
3980{
3981 const char *http_version;
3982 const char *header;
3983
3984 /* First satisfy needs of the server */
3985 if ((conn == NULL) || conn->must_close) {
3986 /* Close, if civetweb framework needs to close */
3987 return 0;
3988 }
3989
3990 if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
3991 /* Close, if keep alive is not enabled */
3992 return 0;
3993 }
3994
3995 /* Check explicit wish of the client */
3996 header = mg_get_header(conn, "Connection");
3997 if (header) {
3998 /* If there is a connection header from the client, obey */
3999 if (header_has_option(header, "keep-alive")) {
4000 return 1;
4001 }
4002 return 0;
4003 }
4004
4005 /* Use default of the standard */
4006 http_version = get_http_version(conn);
4007 if (http_version && (0 == strcmp(http_version, "1.1"))) {
4008 /* HTTP 1.1 default is keep alive */
4009 return 1;
4010 }
4011
4012 /* HTTP 1.0 (and earlier) default is to close the connection */
4013 return 0;
4014}
4015
4016
4017static int
4019{
4020 if (!conn || !conn->dom_ctx) {
4021 return 0;
4022 }
4023
4024 return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
4025}
4026
4027
4028static int
4030{
4031 if (!conn || !conn->dom_ctx) {
4032 return 0;
4033 }
4034
4035 return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
4036 == 0);
4037}
4038
4039
4040static const char *
4042{
4043 return should_keep_alive(conn) ? "keep-alive" : "close";
4044}
4045
4046
4047#include "response.inl"
4048
4049
4050static void
4052{
4053 /* Send all current and obsolete cache opt-out directives. */
4055 "Cache-Control",
4056 "no-cache, no-store, "
4057 "must-revalidate, private, max-age=0",
4058 -1);
4059 mg_response_header_add(conn, "Expires", "0", -1);
4060
4061 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
4062 /* Obsolete, but still send it for HTTP/1.0 */
4063 mg_response_header_add(conn, "Pragma", "no-cache", -1);
4064 }
4065}
4066
4067
4068static void
4070{
4071#if !defined(NO_CACHING)
4072 int max_age;
4073 char val[64];
4074
4075 const char *cache_control =
4077
4078 /* If there is a full cache-control option configured,0 use it */
4079 if (cache_control != NULL) {
4080 mg_response_header_add(conn, "Cache-Control", cache_control, -1);
4081 return;
4082 }
4083
4084 /* Read the server config to check how long a file may be cached.
4085 * The configuration is in seconds. */
4086 max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
4087 if (max_age <= 0) {
4088 /* 0 means "do not cache". All values <0 are reserved
4089 * and may be used differently in the future. */
4090 /* If a file should not be cached, do not only send
4091 * max-age=0, but also pragmas and Expires headers. */
4093 return;
4094 }
4095
4096 /* Use "Cache-Control: max-age" instead of "Expires" header.
4097 * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
4098 /* See also https://www.mnot.net/cache_docs/ */
4099 /* According to RFC 2616, Section 14.21, caching times should not exceed
4100 * one year. A year with 365 days corresponds to 31536000 seconds, a
4101 * leap
4102 * year to 31622400 seconds. For the moment, we just send whatever has
4103 * been configured, still the behavior for >1 year should be considered
4104 * as undefined. */
4106 conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
4107 mg_response_header_add(conn, "Cache-Control", val, -1);
4108
4109#else /* NO_CACHING */
4110
4112#endif /* !NO_CACHING */
4113}
4114
4115
4116static void
4118{
4119 const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
4120
4121#if !defined(NO_SSL)
4122 if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
4123 long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
4124 if (max_age >= 0) {
4125 char val[64];
4126 mg_snprintf(conn,
4127 NULL,
4128 val,
4129 sizeof(val),
4130 "max-age=%lu",
4131 (unsigned long)max_age);
4132 mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
4133 }
4134 }
4135#endif
4136
4137 if (header && header[0]) {
4138 mg_response_header_add_lines(conn, header);
4139 }
4140}
4141
4142
4143#if !defined(NO_FILESYSTEMS)
4144static void handle_file_based_request(struct mg_connection *conn,
4145 const char *path,
4146 struct mg_file *filep);
4147#endif /* NO_FILESYSTEMS */
4148
4149
4150const char *
4151mg_get_response_code_text(const struct mg_connection *conn, int response_code)
4152{
4153 /* See IANA HTTP status code assignment:
4154 * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
4155 */
4156
4157 switch (response_code) {
4158 /* RFC2616 Section 10.1 - Informational 1xx */
4159 case 100:
4160 return "Continue"; /* RFC2616 Section 10.1.1 */
4161 case 101:
4162 return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
4163 case 102:
4164 return "Processing"; /* RFC2518 Section 10.1 */
4165
4166 /* RFC2616 Section 10.2 - Successful 2xx */
4167 case 200:
4168 return "OK"; /* RFC2616 Section 10.2.1 */
4169 case 201:
4170 return "Created"; /* RFC2616 Section 10.2.2 */
4171 case 202:
4172 return "Accepted"; /* RFC2616 Section 10.2.3 */
4173 case 203:
4174 return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
4175 case 204:
4176 return "No Content"; /* RFC2616 Section 10.2.5 */
4177 case 205:
4178 return "Reset Content"; /* RFC2616 Section 10.2.6 */
4179 case 206:
4180 return "Partial Content"; /* RFC2616 Section 10.2.7 */
4181 case 207:
4182 return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
4183 */
4184 case 208:
4185 return "Already Reported"; /* RFC5842 Section 7.1 */
4186
4187 case 226:
4188 return "IM used"; /* RFC3229 Section 10.4.1 */
4189
4190 /* RFC2616 Section 10.3 - Redirection 3xx */
4191 case 300:
4192 return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
4193 case 301:
4194 return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
4195 case 302:
4196 return "Found"; /* RFC2616 Section 10.3.3 */
4197 case 303:
4198 return "See Other"; /* RFC2616 Section 10.3.4 */
4199 case 304:
4200 return "Not Modified"; /* RFC2616 Section 10.3.5 */
4201 case 305:
4202 return "Use Proxy"; /* RFC2616 Section 10.3.6 */
4203 case 307:
4204 return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
4205 case 308:
4206 return "Permanent Redirect"; /* RFC7238 Section 3 */
4207
4208 /* RFC2616 Section 10.4 - Client Error 4xx */
4209 case 400:
4210 return "Bad Request"; /* RFC2616 Section 10.4.1 */
4211 case 401:
4212 return "Unauthorized"; /* RFC2616 Section 10.4.2 */
4213 case 402:
4214 return "Payment Required"; /* RFC2616 Section 10.4.3 */
4215 case 403:
4216 return "Forbidden"; /* RFC2616 Section 10.4.4 */
4217 case 404:
4218 return "Not Found"; /* RFC2616 Section 10.4.5 */
4219 case 405:
4220 return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
4221 case 406:
4222 return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
4223 case 407:
4224 return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
4225 case 408:
4226 return "Request Time-out"; /* RFC2616 Section 10.4.9 */
4227 case 409:
4228 return "Conflict"; /* RFC2616 Section 10.4.10 */
4229 case 410:
4230 return "Gone"; /* RFC2616 Section 10.4.11 */
4231 case 411:
4232 return "Length Required"; /* RFC2616 Section 10.4.12 */
4233 case 412:
4234 return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
4235 case 413:
4236 return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
4237 case 414:
4238 return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
4239 case 415:
4240 return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
4241 case 416:
4242 return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
4243 */
4244 case 417:
4245 return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
4246
4247 case 421:
4248 return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
4249 case 422:
4250 return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
4251 * Section 11.2 */
4252 case 423:
4253 return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
4254 case 424:
4255 return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
4256 * Section 11.4 */
4257
4258 case 426:
4259 return "Upgrade Required"; /* RFC 2817 Section 4 */
4260
4261 case 428:
4262 return "Precondition Required"; /* RFC 6585, Section 3 */
4263 case 429:
4264 return "Too Many Requests"; /* RFC 6585, Section 4 */
4265
4266 case 431:
4267 return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
4268
4269 case 451:
4270 return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
4271 * Section 3 */
4272
4273 /* RFC2616 Section 10.5 - Server Error 5xx */
4274 case 500:
4275 return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
4276 case 501:
4277 return "Not Implemented"; /* RFC2616 Section 10.5.2 */
4278 case 502:
4279 return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
4280 case 503:
4281 return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
4282 case 504:
4283 return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
4284 case 505:
4285 return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
4286 case 506:
4287 return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
4288 case 507:
4289 return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
4290 * Section 11.5 */
4291 case 508:
4292 return "Loop Detected"; /* RFC5842 Section 7.1 */
4293
4294 case 510:
4295 return "Not Extended"; /* RFC 2774, Section 7 */
4296 case 511:
4297 return "Network Authentication Required"; /* RFC 6585, Section 6 */
4298
4299 /* Other status codes, not shown in the IANA HTTP status code
4300 * assignment.
4301 * E.g., "de facto" standards due to common use, ... */
4302 case 418:
4303 return "I am a teapot"; /* RFC2324 Section 2.3.2 */
4304 case 419:
4305 return "Authentication Timeout"; /* common use */
4306 case 420:
4307 return "Enhance Your Calm"; /* common use */
4308 case 440:
4309 return "Login Timeout"; /* common use */
4310 case 509:
4311 return "Bandwidth Limit Exceeded"; /* common use */
4312
4313 default:
4314 /* This error code is unknown. This should not happen. */
4315 if (conn) {
4316 mg_cry_internal(conn,
4317 "Unknown HTTP response code: %u",
4318 response_code);
4319 }
4320
4321 /* Return at least a category according to RFC 2616 Section 10. */
4322 if (response_code >= 100 && response_code < 200) {
4323 /* Unknown informational status code */
4324 return "Information";
4325 }
4326 if (response_code >= 200 && response_code < 300) {
4327 /* Unknown success code */
4328 return "Success";
4329 }
4330 if (response_code >= 300 && response_code < 400) {
4331 /* Unknown redirection code */
4332 return "Redirection";
4333 }
4334 if (response_code >= 400 && response_code < 500) {
4335 /* Unknown request error code */
4336 return "Client Error";
4337 }
4338 if (response_code >= 500 && response_code < 600) {
4339 /* Unknown server error code */
4340 return "Server Error";
4341 }
4342
4343 /* Response code not even within reasonable range */
4344 return "";
4345 }
4346}
4347
4348
4349static int
4351 int status,
4352 const char *fmt,
4353 va_list args)
4354{
4355 char errmsg_buf[MG_BUF_LEN];
4356 va_list ap;
4357 int has_body;
4358
4359#if !defined(NO_FILESYSTEMS)
4360 char path_buf[UTF8_PATH_MAX];
4361 int len, i, page_handler_found, scope, truncated;
4362 const char *error_handler = NULL;
4363 struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
4364 const char *error_page_file_ext, *tstr;
4365#endif /* NO_FILESYSTEMS */
4366 int handled_by_callback = 0;
4367
4368 if ((conn == NULL) || (fmt == NULL)) {
4369 return -2;
4370 }
4371
4372 /* Set status (for log) */
4373 conn->status_code = status;
4374
4375 /* Errors 1xx, 204 and 304 MUST NOT send a body */
4376 has_body = ((status > 199) && (status != 204) && (status != 304));
4377
4378 /* Prepare message in buf, if required */
4379 if (has_body
4380 || (!conn->in_error_handler
4381 && (conn->phys_ctx->callbacks.http_error != NULL))) {
4382 /* Store error message in errmsg_buf */
4383 va_copy(ap, args);
4384 mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
4385 va_end(ap);
4386 /* In a debug build, print all html errors */
4387 DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
4388 }
4389
4390 /* If there is a http_error callback, call it.
4391 * But don't do it recursively, if callback calls mg_send_http_error again.
4392 */
4393 if (!conn->in_error_handler
4394 && (conn->phys_ctx->callbacks.http_error != NULL)) {
4395 /* Mark in_error_handler to avoid recursion and call user callback. */
4396 conn->in_error_handler = 1;
4397 handled_by_callback =
4398 (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
4399 == 0);
4400 conn->in_error_handler = 0;
4401 }
4402
4403 if (!handled_by_callback) {
4404 /* Check for recursion */
4405 if (conn->in_error_handler) {
4407 "Recursion when handling error %u - fall back to default",
4408 status);
4409#if !defined(NO_FILESYSTEMS)
4410 } else {
4411 /* Send user defined error pages, if defined */
4412 error_handler = conn->dom_ctx->config[ERROR_PAGES];
4413 error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
4414 page_handler_found = 0;
4415
4416 if (error_handler != NULL) {
4417 for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4418 switch (scope) {
4419 case 1: /* Handler for specific error, e.g. 404 error */
4420 mg_snprintf(conn,
4421 &truncated,
4422 path_buf,
4423 sizeof(path_buf) - 32,
4424 "%serror%03u.",
4425 error_handler,
4426 status);
4427 break;
4428 case 2: /* Handler for error group, e.g., 5xx error
4429 * handler
4430 * for all server errors (500-599) */
4431 mg_snprintf(conn,
4432 &truncated,
4433 path_buf,
4434 sizeof(path_buf) - 32,
4435 "%serror%01uxx.",
4436 error_handler,
4437 status / 100);
4438 break;
4439 default: /* Handler for all errors */
4440 mg_snprintf(conn,
4441 &truncated,
4442 path_buf,
4443 sizeof(path_buf) - 32,
4444 "%serror.",
4445 error_handler);
4446 break;
4447 }
4448
4449 /* String truncation in buf may only occur if
4450 * error_handler is too long. This string is
4451 * from the config, not from a client. */
4452 (void)truncated;
4453
4454 /* The following code is redundant, but it should avoid
4455 * false positives in static source code analyzers and
4456 * vulnerability scanners.
4457 */
4458 path_buf[sizeof(path_buf) - 32] = 0;
4459 len = (int)strlen(path_buf);
4460 if (len > (int)sizeof(path_buf) - 32) {
4461 len = (int)sizeof(path_buf) - 32;
4462 }
4463
4464 /* Start with the file extenstion from the configuration. */
4465 tstr = strchr(error_page_file_ext, '.');
4466
4467 while (tstr) {
4468 for (i = 1;
4469 (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
4470 i++) {
4471 /* buffer overrun is not possible here, since
4472 * (i < 32) && (len < sizeof(path_buf) - 32)
4473 * ==> (i + len) < sizeof(path_buf) */
4474 path_buf[len + i - 1] = tstr[i];
4475 }
4476 /* buffer overrun is not possible here, since
4477 * (i <= 32) && (len < sizeof(path_buf) - 32)
4478 * ==> (i + len) <= sizeof(path_buf) */
4479 path_buf[len + i - 1] = 0;
4480
4481 if (mg_stat(conn, path_buf, &error_page_file.stat)) {
4482 DEBUG_TRACE("Check error page %s - found",
4483 path_buf);
4484 page_handler_found = 1;
4485 break;
4486 }
4487 DEBUG_TRACE("Check error page %s - not found",
4488 path_buf);
4489
4490 /* Continue with the next file extenstion from the
4491 * configuration (if there is a next one). */
4492 tstr = strchr(tstr + i, '.');
4493 }
4494 }
4495 }
4496
4497 if (page_handler_found) {
4498 conn->in_error_handler = 1;
4499 handle_file_based_request(conn, path_buf, &error_page_file);
4500 conn->in_error_handler = 0;
4501 return 0;
4502 }
4503#endif /* NO_FILESYSTEMS */
4504 }
4505
4506 /* No custom error page. Send default error page. */
4507 conn->must_close = 1;
4508 mg_response_header_start(conn, status);
4511 if (has_body) {
4513 "Content-Type",
4514 "text/plain; charset=utf-8",
4515 -1);
4516 }
4518
4519 /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
4520 if (has_body) {
4521 /* For other errors, send a generic error message. */
4522 const char *status_text = mg_get_response_code_text(conn, status);
4523 mg_printf(conn, "Error %d: %s\n", status, status_text);
4524 mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4525
4526 } else {
4527 /* No body allowed. Close the connection. */
4528 DEBUG_TRACE("Error %i", status);
4529 }
4530 }
4531 return 0;
4532}
4533
4534
4535int
4536mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
4537{
4538 va_list ap;
4539 int ret;
4540
4541 va_start(ap, fmt);
4542 ret = mg_send_http_error_impl(conn, status, fmt, ap);
4543 va_end(ap);
4544
4545 return ret;
4546}
4547
4548
4549int
4551 const char *mime_type,
4552 long long content_length)
4553{
4554 if ((mime_type == NULL) || (*mime_type == 0)) {
4555 /* No content type defined: default to text/html */
4556 mime_type = "text/html";
4557 }
4558
4559 mg_response_header_start(conn, 200);
4562 mg_response_header_add(conn, "Content-Type", mime_type, -1);
4563 if (content_length < 0) {
4564 /* Size not known. Use chunked encoding (HTTP/1.x) */
4565 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
4566 /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
4567 mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
4568 }
4569 } else {
4570 char len[32];
4571 int trunc = 0;
4572 mg_snprintf(conn,
4573 &trunc,
4574 len,
4575 sizeof(len),
4576 "%" UINT64_FMT,
4577 (uint64_t)content_length);
4578 if (!trunc) {
4579 /* Since 32 bytes is enough to hold any 64 bit decimal number,
4580 * !trunc is always true */
4581 mg_response_header_add(conn, "Content-Length", len, -1);
4582 }
4583 }
4585
4586 return 0;
4587}
4588
4589
4590int
4592 const char *target_url,
4593 int redirect_code)
4594{
4595 /* Send a 30x redirect response.
4596 *
4597 * Redirect types (status codes):
4598 *
4599 * Status | Perm/Temp | Method | Version
4600 * 301 | permanent | POST->GET undefined | HTTP/1.0
4601 * 302 | temporary | POST->GET undefined | HTTP/1.0
4602 * 303 | temporary | always use GET | HTTP/1.1
4603 * 307 | temporary | always keep method | HTTP/1.1
4604 * 308 | permanent | always keep method | HTTP/1.1
4605 */
4606 const char *redirect_text;
4607 int ret;
4608 size_t content_len = 0;
4609#if defined(MG_SEND_REDIRECT_BODY)
4610 char reply[MG_BUF_LEN];
4611#endif
4612
4613 /* In case redirect_code=0, use 307. */
4614 if (redirect_code == 0) {
4615 redirect_code = 307;
4616 }
4617
4618 /* In case redirect_code is none of the above, return error. */
4619 if ((redirect_code != 301) && (redirect_code != 302)
4620 && (redirect_code != 303) && (redirect_code != 307)
4621 && (redirect_code != 308)) {
4622 /* Parameter error */
4623 return -2;
4624 }
4625
4626 /* Get proper text for response code */
4627 redirect_text = mg_get_response_code_text(conn, redirect_code);
4628
4629 /* If target_url is not defined, redirect to "/". */
4630 if ((target_url == NULL) || (*target_url == 0)) {
4631 target_url = "/";
4632 }
4633
4634#if defined(MG_SEND_REDIRECT_BODY)
4635 /* TODO: condition name? */
4636
4637 /* Prepare a response body with a hyperlink.
4638 *
4639 * According to RFC2616 (and RFC1945 before):
4640 * Unless the request method was HEAD, the entity of the
4641 * response SHOULD contain a short hypertext note with a hyperlink to
4642 * the new URI(s).
4643 *
4644 * However, this response body is not useful in M2M communication.
4645 * Probably the original reason in the RFC was, clients not supporting
4646 * a 30x HTTP redirect could still show the HTML page and let the user
4647 * press the link. Since current browsers support 30x HTTP, the additional
4648 * HTML body does not seem to make sense anymore.
4649 *
4650 * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
4651 * but it only notes:
4652 * The server's response payload usually contains a short
4653 * hypertext note with a hyperlink to the new URI(s).
4654 *
4655 * Deactivated by default. If you need the 30x body, set the define.
4656 */
4658 conn,
4659 NULL /* ignore truncation */,
4660 reply,
4661 sizeof(reply),
4662 "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4663 redirect_text,
4664 target_url,
4665 target_url);
4666 content_len = strlen(reply);
4667#endif
4668
4669 /* Do not send any additional header. For all other options,
4670 * including caching, there are suitable defaults. */
4671 ret = mg_printf(conn,
4672 "HTTP/1.1 %i %s\r\n"
4673 "Location: %s\r\n"
4674 "Content-Length: %u\r\n"
4675 "Connection: %s\r\n\r\n",
4676 redirect_code,
4677 redirect_text,
4678 target_url,
4679 (unsigned int)content_len,
4681
4682#if defined(MG_SEND_REDIRECT_BODY)
4683 /* Send response body */
4684 if (ret > 0) {
4685 /* ... unless it is a HEAD request */
4686 if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
4687 ret = mg_write(conn, reply, content_len);
4688 }
4689 }
4690#endif
4691
4692 return (ret > 0) ? ret : -1;
4693}
4694
4695
4696#if defined(_WIN32)
4697/* Create substitutes for POSIX functions in Win32. */
4698
4699#if defined(GCC_DIAGNOSTIC)
4700/* Show no warning in case system functions are not used. */
4701#pragma GCC diagnostic push
4702#pragma GCC diagnostic ignored "-Wunused-function"
4703#endif
4704
4705
4706static int
4707pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
4708{
4709 (void)unused;
4710 /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
4711 InitializeCriticalSection(&mutex->sec);
4712 return 0;
4713}
4714
4715
4716static int
4717pthread_mutex_destroy(pthread_mutex_t *mutex)
4718{
4719 DeleteCriticalSection(&mutex->sec);
4720 return 0;
4721}
4722
4723
4724static int
4725pthread_mutex_lock(pthread_mutex_t *mutex)
4726{
4727 EnterCriticalSection(&mutex->sec);
4728 return 0;
4729}
4730
4731
4732static int
4733pthread_mutex_unlock(pthread_mutex_t *mutex)
4734{
4735 LeaveCriticalSection(&mutex->sec);
4736 return 0;
4737}
4738
4739
4741static int
4742pthread_cond_init(pthread_cond_t *cv, const void *unused)
4743{
4744 (void)unused;
4745 (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
4746 cv->waiting_thread = NULL;
4747 return 0;
4748}
4749
4750
4752static int
4753pthread_cond_timedwait(pthread_cond_t *cv,
4754 pthread_mutex_t *mutex,
4755 FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
4756{
4757 struct mg_workerTLS **ptls,
4758 *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
4759 int ok;
4760 uint64_t nsnow, nswaitabs;
4761 int64_t nswaitrel;
4762 DWORD mswaitrel;
4763
4764 pthread_mutex_lock(&cv->threadIdSec);
4765 /* Add this thread to cv's waiting list */
4766 ptls = &cv->waiting_thread;
4767 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
4768 ;
4769 tls->next_waiting_thread = NULL;
4770 *ptls = tls;
4771 pthread_mutex_unlock(&cv->threadIdSec);
4772
4773 if (abstime) {
4774 nsnow = mg_get_current_time_ns();
4775 nswaitabs =
4776 (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
4777 nswaitrel = nswaitabs - nsnow;
4778 if (nswaitrel < 0) {
4779 nswaitrel = 0;
4780 }
4781 mswaitrel = (DWORD)(nswaitrel / 1000000);
4782 } else {
4783 mswaitrel = (DWORD)INFINITE;
4784 }
4785
4786 pthread_mutex_unlock(mutex);
4787 ok = (WAIT_OBJECT_0
4788 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
4789 if (!ok) {
4790 ok = 1;
4791 pthread_mutex_lock(&cv->threadIdSec);
4792 ptls = &cv->waiting_thread;
4793 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
4794 if (*ptls == tls) {
4795 *ptls = tls->next_waiting_thread;
4796 ok = 0;
4797 break;
4798 }
4799 }
4800 pthread_mutex_unlock(&cv->threadIdSec);
4801 if (ok) {
4802 WaitForSingleObject(tls->pthread_cond_helper_mutex,
4803 (DWORD)INFINITE);
4804 }
4805 }
4806 /* This thread has been removed from cv's waiting list */
4807 pthread_mutex_lock(mutex);
4808
4809 return ok ? 0 : -1;
4810}
4811
4812
4814static int
4815pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
4816{
4817 return pthread_cond_timedwait(cv, mutex, NULL);
4818}
4819
4820
4822static int
4823pthread_cond_signal(pthread_cond_t *cv)
4824{
4825 HANDLE wkup = NULL;
4826 BOOL ok = FALSE;
4827
4828 pthread_mutex_lock(&cv->threadIdSec);
4829 if (cv->waiting_thread) {
4830 wkup = cv->waiting_thread->pthread_cond_helper_mutex;
4831 cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
4832
4833 ok = SetEvent(wkup);
4834 DEBUG_ASSERT(ok);
4835 }
4836 pthread_mutex_unlock(&cv->threadIdSec);
4837
4838 return ok ? 0 : 1;
4839}
4840
4841
4843static int
4844pthread_cond_broadcast(pthread_cond_t *cv)
4845{
4846 pthread_mutex_lock(&cv->threadIdSec);
4847 while (cv->waiting_thread) {
4848 pthread_cond_signal(cv);
4849 }
4850 pthread_mutex_unlock(&cv->threadIdSec);
4851
4852 return 0;
4853}
4854
4855
4857static int
4858pthread_cond_destroy(pthread_cond_t *cv)
4859{
4860 pthread_mutex_lock(&cv->threadIdSec);
4861 DEBUG_ASSERT(cv->waiting_thread == NULL);
4862 pthread_mutex_unlock(&cv->threadIdSec);
4863 pthread_mutex_destroy(&cv->threadIdSec);
4864
4865 return 0;
4866}
4867
4868
4869#if defined(ALTERNATIVE_QUEUE)
4871static void *
4872event_create(void)
4873{
4874 return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
4875}
4876
4877
4879static int
4880event_wait(void *eventhdl)
4881{
4882 int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
4883 return (res == WAIT_OBJECT_0);
4884}
4885
4886
4888static int
4889event_signal(void *eventhdl)
4890{
4891 return (int)SetEvent((HANDLE)eventhdl);
4892}
4893
4894
4896static void
4897event_destroy(void *eventhdl)
4898{
4899 CloseHandle((HANDLE)eventhdl);
4900}
4901#endif
4902
4903
4904#if defined(GCC_DIAGNOSTIC)
4905/* Enable unused function warning again */
4906#pragma GCC diagnostic pop
4907#endif
4908
4909
4910/* For Windows, change all slashes to backslashes in path names. */
4911static void
4912change_slashes_to_backslashes(char *path)
4913{
4914 int i;
4915
4916 for (i = 0; path[i] != '\0'; i++) {
4917 if (path[i] == '/') {
4918 path[i] = '\\';
4919 }
4920
4921 /* remove double backslash (check i > 0 to preserve UNC paths,
4922 * like \\server\file.txt) */
4923 if ((i > 0) && (path[i] == '\\')) {
4924 while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
4925 (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
4926 }
4927 }
4928 }
4929}
4930
4931
4932static int
4933mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
4934{
4935 int diff;
4936
4937 do {
4938 diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
4939 - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
4940 s1++;
4941 s2++;
4942 } while ((diff == 0) && (s1[-1] != L'\0'));
4943
4944 return diff;
4945}
4946
4947
4948/* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
4949 * wbuf and wbuf_len is a target buffer and its length. */
4950static void
4951path_to_unicode(const struct mg_connection *conn,
4952 const char *path,
4953 wchar_t *wbuf,
4954 size_t wbuf_len)
4955{
4956 char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
4957 wchar_t wbuf2[UTF16_PATH_MAX + 1];
4958 DWORD long_len, err;
4959 int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
4960
4961 mg_strlcpy(buf, path, sizeof(buf));
4962 change_slashes_to_backslashes(buf);
4963
4964 /* Convert to Unicode and back. If doubly-converted string does not
4965 * match the original, something is fishy, reject. */
4966 memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
4967 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
4968 WideCharToMultiByte(
4969 CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
4970 if (strcmp(buf, buf2) != 0) {
4971 wbuf[0] = L'\0';
4972 }
4973
4974 /* Windows file systems are not case sensitive, but you can still use
4975 * uppercase and lowercase letters (on all modern file systems).
4976 * The server can check if the URI uses the same upper/lowercase
4977 * letters an the file system, effectively making Windows servers
4978 * case sensitive (like Linux servers are). It is still not possible
4979 * to use two files with the same name in different cases on Windows
4980 * (like /a and /A) - this would be possible in Linux.
4981 * As a default, Windows is not case sensitive, but the case sensitive
4982 * file name check can be activated by an additional configuration. */
4983 if (conn) {
4984 if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
4985 && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
4986 "yes")) {
4987 /* Use case sensitive compare function */
4988 fcompare = wcscmp;
4989 }
4990 }
4991 (void)conn; /* conn is currently unused */
4992
4993 /* Only accept a full file path, not a Windows short (8.3) path. */
4994 memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
4995 long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
4996 if (long_len == 0) {
4997 err = GetLastError();
4998 if (err == ERROR_FILE_NOT_FOUND) {
4999 /* File does not exist. This is not always a problem here. */
5000 return;
5001 }
5002 }
5003 if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5004 /* Short name is used. */
5005 wbuf[0] = L'\0';
5006 }
5007}
5008
5009
5010#if !defined(NO_FILESYSTEMS)
5011/* Get file information, return 1 if file exists, 0 if not */
5012static int
5013mg_stat(const struct mg_connection *conn,
5014 const char *path,
5015 struct mg_file_stat *filep)
5016{
5017 wchar_t wbuf[UTF16_PATH_MAX];
5018 WIN32_FILE_ATTRIBUTE_DATA info;
5019 time_t creation_time;
5020 size_t len;
5021
5022 if (!filep) {
5023 return 0;
5024 }
5025 memset(filep, 0, sizeof(*filep));
5026
5027 if (mg_path_suspicious(conn, path)) {
5028 return 0;
5029 }
5030
5031 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5032 /* Windows happily opens files with some garbage at the end of file name.
5033 * For example, fopen("a.cgi ", "r") on Windows successfully opens
5034 * "a.cgi", despite one would expect an error back. */
5035 len = strlen(path);
5036 if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
5037 && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
5038 filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5039 filep->last_modified =
5040 SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5041 info.ftLastWriteTime.dwHighDateTime);
5042
5043 /* On Windows, the file creation time can be higher than the
5044 * modification time, e.g. when a file is copied.
5045 * Since the Last-Modified timestamp is used for caching
5046 * it should be based on the most recent timestamp. */
5047 creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5048 info.ftCreationTime.dwHighDateTime);
5049 if (creation_time > filep->last_modified) {
5050 filep->last_modified = creation_time;
5051 }
5052
5053 filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5054 return 1;
5055 }
5056
5057 return 0;
5058}
5059#endif
5060
5061
5062static int
5063mg_remove(const struct mg_connection *conn, const char *path)
5064{
5065 wchar_t wbuf[UTF16_PATH_MAX];
5066 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5067 return DeleteFileW(wbuf) ? 0 : -1;
5068}
5069
5070
5071static int
5072mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
5073{
5074 wchar_t wbuf[UTF16_PATH_MAX];
5075 (void)mode;
5076 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5077 return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5078}
5079
5080
5081/* Create substitutes for POSIX functions in Win32. */
5082
5083#if defined(GCC_DIAGNOSTIC)
5084/* Show no warning in case system functions are not used. */
5085#pragma GCC diagnostic push
5086#pragma GCC diagnostic ignored "-Wunused-function"
5087#endif
5088
5089
5090/* Implementation of POSIX opendir/closedir/readdir for Windows. */
5092static DIR *
5093mg_opendir(const struct mg_connection *conn, const char *name)
5094{
5095 DIR *dir = NULL;
5096 wchar_t wpath[UTF16_PATH_MAX];
5097 DWORD attrs;
5098
5099 if (name == NULL) {
5100 SetLastError(ERROR_BAD_ARGUMENTS);
5101 } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
5102 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5103 } else {
5104 path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
5105 attrs = GetFileAttributesW(wpath);
5106 if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5107 && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5108 (void)wcscat(wpath, L"\\*");
5109 dir->handle = FindFirstFileW(wpath, &dir->info);
5110 dir->result.d_name[0] = '\0';
5111 } else {
5112 mg_free(dir);
5113 dir = NULL;
5114 }
5115 }
5116
5117 return dir;
5118}
5119
5120
5122static int
5123mg_closedir(DIR *dir)
5124{
5125 int result = 0;
5126
5127 if (dir != NULL) {
5128 if (dir->handle != INVALID_HANDLE_VALUE)
5129 result = FindClose(dir->handle) ? 0 : -1;
5130
5131 mg_free(dir);
5132 } else {
5133 result = -1;
5134 SetLastError(ERROR_BAD_ARGUMENTS);
5135 }
5136
5137 return result;
5138}
5139
5140
5142static struct dirent *
5143mg_readdir(DIR *dir)
5144{
5145 struct dirent *result = 0;
5146
5147 if (dir) {
5148 if (dir->handle != INVALID_HANDLE_VALUE) {
5149 result = &dir->result;
5150 (void)WideCharToMultiByte(CP_UTF8,
5151 0,
5152 dir->info.cFileName,
5153 -1,
5154 result->d_name,
5155 sizeof(result->d_name),
5156 NULL,
5157 NULL);
5158
5159 if (!FindNextFileW(dir->handle, &dir->info)) {
5160 (void)FindClose(dir->handle);
5161 dir->handle = INVALID_HANDLE_VALUE;
5162 }
5163
5164 } else {
5165 SetLastError(ERROR_FILE_NOT_FOUND);
5166 }
5167 } else {
5168 SetLastError(ERROR_BAD_ARGUMENTS);
5169 }
5170
5171 return result;
5172}
5173
5174
5175#if !defined(HAVE_POLL)
5176#undef POLLIN
5177#undef POLLPRI
5178#undef POLLOUT
5179#undef POLLERR
5180#define POLLIN (1) /* Data ready - read will not block. */
5181#define POLLPRI (2) /* Priority data ready. */
5182#define POLLOUT (4) /* Send queue not full - write will not block. */
5183#define POLLERR (8) /* Error event */
5184
5186static int
5187poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
5188{
5189 struct timeval tv;
5190 fd_set rset;
5191 fd_set wset;
5192 fd_set eset;
5193 unsigned int i;
5194 int result;
5195 SOCKET maxfd = 0;
5196
5197 memset(&tv, 0, sizeof(tv));
5198 tv.tv_sec = milliseconds / 1000;
5199 tv.tv_usec = (milliseconds % 1000) * 1000;
5200 FD_ZERO(&rset);
5201 FD_ZERO(&wset);
5202 FD_ZERO(&eset);
5203
5204 for (i = 0; i < n; i++) {
5205 if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
5206 if (pfd[i].events & POLLIN) {
5207 FD_SET(pfd[i].fd, &rset);
5208 }
5209 if (pfd[i].events & POLLOUT) {
5210 FD_SET(pfd[i].fd, &wset);
5211 }
5212 /* Check for errors for any FD in the set */
5213 FD_SET(pfd[i].fd, &eset);
5214 }
5215 pfd[i].revents = 0;
5216
5217 if (pfd[i].fd > maxfd) {
5218 maxfd = pfd[i].fd;
5219 }
5220 }
5221
5222 if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
5223 for (i = 0; i < n; i++) {
5224 if (FD_ISSET(pfd[i].fd, &rset)) {
5225 pfd[i].revents |= POLLIN;
5226 }
5227 if (FD_ISSET(pfd[i].fd, &wset)) {
5228 pfd[i].revents |= POLLOUT;
5229 }
5230 if (FD_ISSET(pfd[i].fd, &eset)) {
5231 pfd[i].revents |= POLLERR;
5232 }
5233 }
5234 }
5235
5236 /* We should subtract the time used in select from remaining
5237 * "milliseconds", in particular if called from mg_poll with a
5238 * timeout quantum.
5239 * Unfortunately, the remaining time is not stored in "tv" in all
5240 * implementations, so the result in "tv" must be considered undefined.
5241 * See http://man7.org/linux/man-pages/man2/select.2.html */
5242
5243 return result;
5244}
5245#endif /* HAVE_POLL */
5246
5247
5248#if defined(GCC_DIAGNOSTIC)
5249/* Enable unused function warning again */
5250#pragma GCC diagnostic pop
5251#endif
5252
5253
5254static void
5256 const struct mg_connection *conn /* may be null */,
5257 struct mg_context *ctx /* may be null */)
5258{
5259 (void)conn; /* Unused. */
5260 (void)ctx;
5261
5262 (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5263}
5264
5265
5266int
5268{
5269#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5270 /* Compile-time option to control stack size, e.g.
5271 * -DUSE_STACK_SIZE=16384
5272 */
5273 return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
5274 == ((uintptr_t)(-1L)))
5275 ? -1
5276 : 0);
5277#else
5278 return (
5279 (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
5280 ? -1
5281 : 0);
5282#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5283}
5284
5285
5286/* Start a thread storing the thread context. */
5287static int
5288mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
5289 void *p,
5290 pthread_t *threadidptr)
5291{
5292 uintptr_t uip;
5293 HANDLE threadhandle;
5294 int result = -1;
5295
5296 uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
5297 threadhandle = (HANDLE)uip;
5298 if ((uip != 0) && (threadidptr != NULL)) {
5299 *threadidptr = threadhandle;
5300 result = 0;
5301 }
5302
5303 return result;
5304}
5305
5306
5307/* Wait for a thread to finish. */
5308static int
5309mg_join_thread(pthread_t threadid)
5310{
5311 int result;
5312 DWORD dwevent;
5313
5314 result = -1;
5315 dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5316 if (dwevent == WAIT_FAILED) {
5317 DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
5318 } else {
5319 if (dwevent == WAIT_OBJECT_0) {
5320 CloseHandle(threadid);
5321 result = 0;
5322 }
5323 }
5324
5325 return result;
5326}
5327
5328#if !defined(NO_SSL_DL) && !defined(NO_SSL)
5329/* If SSL is loaded dynamically, dlopen/dlclose is required. */
5330/* Create substitutes for POSIX functions in Win32. */
5331
5332#if defined(GCC_DIAGNOSTIC)
5333/* Show no warning in case system functions are not used. */
5334#pragma GCC diagnostic push
5335#pragma GCC diagnostic ignored "-Wunused-function"
5336#endif
5337
5338
5340static HANDLE
5341dlopen(const char *dll_name, int flags)
5342{
5343 wchar_t wbuf[UTF16_PATH_MAX];
5344 (void)flags;
5345 path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
5346 return LoadLibraryW(wbuf);
5347}
5348
5349
5351static int
5352dlclose(void *handle)
5353{
5354 int result;
5355
5356 if (FreeLibrary((HMODULE)handle) != 0) {
5357 result = 0;
5358 } else {
5359 result = -1;
5360 }
5361
5362 return result;
5363}
5364
5365
5366#if defined(GCC_DIAGNOSTIC)
5367/* Enable unused function warning again */
5368#pragma GCC diagnostic pop
5369#endif
5370
5371#endif
5372
5373
5374#if !defined(NO_CGI)
5375#define SIGKILL (0)
5376
5377
5378static int
5379kill(pid_t pid, int sig_num)
5380{
5381 (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5382 (void)CloseHandle((HANDLE)pid);
5383 return 0;
5384}
5385
5386
5387#if !defined(WNOHANG)
5388#define WNOHANG (1)
5389#endif
5390
5391
5392static pid_t
5393waitpid(pid_t pid, int *status, int flags)
5394{
5395 DWORD timeout = INFINITE;
5396 DWORD waitres;
5397
5398 (void)status; /* Currently not used by any client here */
5399
5400 if ((flags | WNOHANG) == WNOHANG) {
5401 timeout = 0;
5402 }
5403
5404 waitres = WaitForSingleObject((HANDLE)pid, timeout);
5405 if (waitres == WAIT_OBJECT_0) {
5406 return pid;
5407 }
5408 if (waitres == WAIT_TIMEOUT) {
5409 return 0;
5410 }
5411 return (pid_t)-1;
5412}
5413
5414
5415static void
5416trim_trailing_whitespaces(char *s)
5417{
5418 char *e = s + strlen(s);
5419 while ((e > s) && isspace((unsigned char)e[-1])) {
5420 *(--e) = '\0';
5421 }
5422}
5423
5424
5425static pid_t
5426spawn_process(struct mg_connection *conn,
5427 const char *prog,
5428 char *envblk,
5429 char *envp[],
5430 int fdin[2],
5431 int fdout[2],
5432 int fderr[2],
5433 const char *dir,
5434 unsigned char cgi_config_idx)
5435{
5436 HANDLE me;
5437 char *interp;
5438 char *interp_arg = 0;
5439 char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
5440 int truncated;
5441 struct mg_file file = STRUCT_FILE_INITIALIZER;
5442 STARTUPINFOA si;
5443 PROCESS_INFORMATION pi = {0};
5444
5445 (void)envp;
5446
5447 memset(&si, 0, sizeof(si));
5448 si.cb = sizeof(si);
5449
5450 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5451 si.wShowWindow = SW_HIDE;
5452
5453 me = GetCurrentProcess();
5454 DuplicateHandle(me,
5455 (HANDLE)_get_osfhandle(fdin[0]),
5456 me,
5457 &si.hStdInput,
5458 0,
5459 TRUE,
5460 DUPLICATE_SAME_ACCESS);
5461 DuplicateHandle(me,
5462 (HANDLE)_get_osfhandle(fdout[1]),
5463 me,
5464 &si.hStdOutput,
5465 0,
5466 TRUE,
5467 DUPLICATE_SAME_ACCESS);
5468 DuplicateHandle(me,
5469 (HANDLE)_get_osfhandle(fderr[1]),
5470 me,
5471 &si.hStdError,
5472 0,
5473 TRUE,
5474 DUPLICATE_SAME_ACCESS);
5475
5476 /* Mark handles that should not be inherited. See
5477 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
5478 */
5479 SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5480 HANDLE_FLAG_INHERIT,
5481 0);
5482 SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5483 HANDLE_FLAG_INHERIT,
5484 0);
5485 SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5486 HANDLE_FLAG_INHERIT,
5487 0);
5488
5489 /* First check, if there is a CGI interpreter configured for all CGI
5490 * scripts. */
5491 interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
5492 if (interp != NULL) {
5493 /* If there is a configured interpreter, check for additional arguments
5494 */
5495 interp_arg =
5496 conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
5497 } else {
5498 /* Otherwise, the interpreter must be stated in the first line of the
5499 * CGI script file, after a #! (shebang) mark. */
5500 buf[0] = buf[1] = '\0';
5501
5502 /* Get the full script path */
5504 conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
5505
5506 if (truncated) {
5507 pi.hProcess = (pid_t)-1;
5508 goto spawn_cleanup;
5509 }
5510
5511 /* Open the script file, to read the first line */
5512 if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
5513
5514 /* Read the first line of the script into the buffer */
5515 mg_fgets(buf, sizeof(buf), &file);
5516 (void)mg_fclose(&file.access); /* ignore error on read only file */
5517 buf[sizeof(buf) - 1] = '\0';
5518 }
5519
5520 if ((buf[0] == '#') && (buf[1] == '!')) {
5521 trim_trailing_whitespaces(buf + 2);
5522 } else {
5523 buf[2] = '\0';
5524 }
5525 interp = buf + 2;
5526 }
5527
5528 GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
5529
5530 if (interp[0] != '\0') {
5531 /* This is an interpreted script file. We must call the interpreter. */
5532 if ((interp_arg != 0) && (interp_arg[0] != 0)) {
5533 mg_snprintf(conn,
5534 &truncated,
5535 cmdline,
5536 sizeof(cmdline),
5537 "\"%s\" %s \"%s\\%s\"",
5538 interp,
5539 interp_arg,
5540 full_dir,
5541 prog);
5542 } else {
5543 mg_snprintf(conn,
5544 &truncated,
5545 cmdline,
5546 sizeof(cmdline),
5547 "\"%s\" \"%s\\%s\"",
5548 interp,
5549 full_dir,
5550 prog);
5551 }
5552 } else {
5553 /* This is (probably) a compiled program. We call it directly. */
5554 mg_snprintf(conn,
5555 &truncated,
5556 cmdline,
5557 sizeof(cmdline),
5558 "\"%s\\%s\"",
5559 full_dir,
5560 prog);
5561 }
5562
5563 if (truncated) {
5564 pi.hProcess = (pid_t)-1;
5565 goto spawn_cleanup;
5566 }
5567
5568 DEBUG_TRACE("Running [%s]", cmdline);
5569 if (CreateProcessA(NULL,
5570 cmdline,
5571 NULL,
5572 NULL,
5573 TRUE,
5574 CREATE_NEW_PROCESS_GROUP,
5575 envblk,
5576 NULL,
5577 &si,
5578 &pi)
5579 == 0) {
5581 conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
5582 pi.hProcess = (pid_t)-1;
5583 /* goto spawn_cleanup; */
5584 }
5585
5586spawn_cleanup:
5587 (void)CloseHandle(si.hStdOutput);
5588 (void)CloseHandle(si.hStdError);
5589 (void)CloseHandle(si.hStdInput);
5590 if (pi.hThread != NULL) {
5591 (void)CloseHandle(pi.hThread);
5592 }
5593
5594 return (pid_t)pi.hProcess;
5595}
5596#endif /* !NO_CGI */
5597
5598
5599static int
5601{
5602 unsigned long non_blocking = 0;
5603 return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5604}
5605
5606
5607static int
5609{
5610 unsigned long non_blocking = 1;
5611 return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5612}
5613
5614
5615#else
5616
5617
5618#if !defined(NO_FILESYSTEMS)
5619static int
5620mg_stat(const struct mg_connection *conn,
5621 const char *path,
5622 struct mg_file_stat *filep)
5623{
5624 struct stat st;
5625 if (!filep) {
5626 return 0;
5627 }
5628 memset(filep, 0, sizeof(*filep));
5629
5630 if (mg_path_suspicious(conn, path)) {
5631 return 0;
5632 }
5633
5634 if (0 == stat(path, &st)) {
5635 filep->size = (uint64_t)(st.st_size);
5636 filep->last_modified = st.st_mtime;
5637 filep->is_directory = S_ISDIR(st.st_mode);
5638 return 1;
5639 }
5640
5641 return 0;
5642}
5643#endif /* NO_FILESYSTEMS */
5644
5645
5646static void
5648 const struct mg_connection *conn /* may be null */,
5649 struct mg_context *ctx /* may be null */)
5650{
5651#if defined(__ZEPHYR__)
5652 (void)fd;
5653 (void)conn;
5654 (void)ctx;
5655#else
5656 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5657 if (conn || ctx) {
5658 struct mg_connection fc;
5659 mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
5660 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5661 __func__,
5662 strerror(ERRNO));
5663 }
5664 }
5665#endif
5666}
5667
5668
5669int
5671{
5672 pthread_t thread_id;
5673 pthread_attr_t attr;
5674 int result;
5675
5676 (void)pthread_attr_init(&attr);
5677 (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
5678
5679#if defined(__ZEPHYR__)
5680 pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
5681#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5682 /* Compile-time option to control stack size,
5683 * e.g. -DUSE_STACK_SIZE=16384 */
5684 (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5685#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5686
5687 result = pthread_create(&thread_id, &attr, func, param);
5688 pthread_attr_destroy(&attr);
5689
5690 return result;
5691}
5692
5693
5694/* Start a thread storing the thread context. */
5695static int
5697 void *param,
5698 pthread_t *threadidptr)
5699{
5700 pthread_t thread_id;
5701 pthread_attr_t attr;
5702 int result;
5703
5704 (void)pthread_attr_init(&attr);
5705
5706#if defined(__ZEPHYR__)
5707 pthread_attr_setstack(&attr,
5708 &civetweb_worker_stacks[zephyr_worker_stack_index++],
5709 ZEPHYR_STACK_SIZE);
5710#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5711 /* Compile-time option to control stack size,
5712 * e.g. -DUSE_STACK_SIZE=16384 */
5713 (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5714#endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
5715
5716 result = pthread_create(&thread_id, &attr, func, param);
5717 pthread_attr_destroy(&attr);
5718 if ((result == 0) && (threadidptr != NULL)) {
5719 *threadidptr = thread_id;
5720 }
5721 return result;
5722}
5723
5724
5725/* Wait for a thread to finish. */
5726static int
5727mg_join_thread(pthread_t threadid)
5728{
5729 int result;
5730
5731 result = pthread_join(threadid, NULL);
5732 return result;
5733}
5734
5735
5736#if !defined(NO_CGI)
5737static pid_t
5739 const char *prog,
5740 char *envblk,
5741 char *envp[],
5742 int fdin[2],
5743 int fdout[2],
5744 int fderr[2],
5745 const char *dir,
5746 unsigned char cgi_config_idx)
5747{
5748 pid_t pid;
5749 const char *interp;
5750
5751 (void)envblk;
5752
5753 if ((pid = fork()) == -1) {
5754 /* Parent */
5755 mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
5756 } else if (pid != 0) {
5757 /* Make sure children close parent-side descriptors.
5758 * The caller will close the child-side immediately. */
5759 set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
5760 set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
5761 set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
5762 } else {
5763 /* Child */
5764 if (chdir(dir) != 0) {
5766 conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
5767 } else if (dup2(fdin[0], 0) == -1) {
5768 mg_cry_internal(conn,
5769 "%s: dup2(%d, 0): %s",
5770 __func__,
5771 fdin[0],
5772 strerror(ERRNO));
5773 } else if (dup2(fdout[1], 1) == -1) {
5774 mg_cry_internal(conn,
5775 "%s: dup2(%d, 1): %s",
5776 __func__,
5777 fdout[1],
5778 strerror(ERRNO));
5779 } else if (dup2(fderr[1], 2) == -1) {
5780 mg_cry_internal(conn,
5781 "%s: dup2(%d, 2): %s",
5782 __func__,
5783 fderr[1],
5784 strerror(ERRNO));
5785 } else {
5786 struct sigaction sa;
5787
5788 /* Keep stderr and stdout in two different pipes.
5789 * Stdout will be sent back to the client,
5790 * stderr should go into a server error log. */
5791 (void)close(fdin[0]);
5792 (void)close(fdout[1]);
5793 (void)close(fderr[1]);
5794
5795 /* Close write end fdin and read end fdout and fderr */
5796 (void)close(fdin[1]);
5797 (void)close(fdout[0]);
5798 (void)close(fderr[0]);
5799
5800 /* After exec, all signal handlers are restored to their default
5801 * values, with one exception of SIGCHLD. According to
5802 * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
5803 * will leave unchanged after exec if it was set to be ignored.
5804 * Restore it to default action. */
5805 memset(&sa, 0, sizeof(sa));
5806 sa.sa_handler = SIG_DFL;
5807 sigaction(SIGCHLD, &sa, NULL);
5808
5809 interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
5810 if (interp == NULL) {
5811 /* no interpreter configured, call the programm directly */
5812 (void)execle(prog, prog, NULL, envp);
5813 mg_cry_internal(conn,
5814 "%s: execle(%s): %s",
5815 __func__,
5816 prog,
5817 strerror(ERRNO));
5818 } else {
5819 /* call the configured interpreter */
5820 const char *interp_args =
5821 conn->dom_ctx
5822 ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
5823
5824 if ((interp_args != NULL) && (interp_args[0] != 0)) {
5825 (void)execle(interp, interp, interp_args, prog, NULL, envp);
5826 } else {
5827 (void)execle(interp, interp, prog, NULL, envp);
5828 }
5829 mg_cry_internal(conn,
5830 "%s: execle(%s %s): %s",
5831 __func__,
5832 interp,
5833 prog,
5834 strerror(ERRNO));
5835 }
5836 }
5837 exit(EXIT_FAILURE);
5838 }
5839
5840 return pid;
5841}
5842#endif /* !NO_CGI */
5843
5844
5845static int
5847{
5848 int flags = fcntl(sock, F_GETFL, 0);
5849 if (flags < 0) {
5850 return -1;
5851 }
5852
5853 if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
5854 return -1;
5855 }
5856 return 0;
5857}
5858
5859static int
5861{
5862 int flags = fcntl(sock, F_GETFL, 0);
5863 if (flags < 0) {
5864 return -1;
5865 }
5866
5867 if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
5868 return -1;
5869 }
5870 return 0;
5871}
5872#endif /* _WIN32 / else */
5873
5874/* End of initial operating system specific define block. */
5875
5876
5877/* Get a random number (independent of C rand function) */
5878static uint64_t
5880{
5881 static uint64_t lfsr = 0; /* Linear feedback shift register */
5882 static uint64_t lcg = 0; /* Linear congruential generator */
5883 uint64_t now = mg_get_current_time_ns();
5884
5885 if (lfsr == 0) {
5886 /* lfsr will be only 0 if has not been initialized,
5887 * so this code is called only once. */
5888 lfsr = mg_get_current_time_ns();
5889 lcg = mg_get_current_time_ns();
5890 } else {
5891 /* Get the next step of both random number generators. */
5892 lfsr = (lfsr >> 1)
5893 | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
5894 << 63);
5895 lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
5896 }
5897
5898 /* Combining two pseudo-random number generators and a high resolution
5899 * part
5900 * of the current server time will make it hard (impossible?) to guess
5901 * the
5902 * next number. */
5903 return (lfsr ^ lcg ^ now);
5904}
5905
5906
5907static int
5908mg_poll(struct mg_pollfd *pfd,
5909 unsigned int n,
5910 int milliseconds,
5911 const stop_flag_t *stop_flag)
5912{
5913 /* Call poll, but only for a maximum time of a few seconds.
5914 * This will allow to stop the server after some seconds, instead
5915 * of having to wait for a long socket timeout. */
5916 int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
5917
5918 int check_pollerr = 0;
5919 if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
5920 /* If we wait for only one file descriptor, wait on error as well */
5921 pfd[0].events |= POLLERR;
5922 check_pollerr = 1;
5923 }
5924
5925 do {
5926 int result;
5927
5928 if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
5929 /* Shut down signal */
5930 return -2;
5931 }
5932
5933 if ((milliseconds >= 0) && (milliseconds < ms_now)) {
5934 ms_now = milliseconds;
5935 }
5936
5937 result = poll(pfd, n, ms_now);
5938 if (result != 0) {
5939 /* Poll returned either success (1) or error (-1).
5940 * Forward both to the caller. */
5941 if ((check_pollerr)
5942 && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
5943 == POLLERR)) {
5944 /* One and only file descriptor returned error */
5945 return -1;
5946 }
5947 return result;
5948 }
5949
5950 /* Poll returned timeout (0). */
5951 if (milliseconds > 0) {
5952 milliseconds -= ms_now;
5953 }
5954
5955 } while (milliseconds > 0);
5956
5957 /* timeout: return 0 */
5958 return 0;
5959}
5960
5961
5962/* Write data to the IO channel - opened file descriptor, socket or SSL
5963 * descriptor.
5964 * Return value:
5965 * >=0 .. number of bytes successfully written
5966 * -1 .. timeout
5967 * -2 .. error
5968 */
5969static int
5971 FILE *fp,
5972 SOCKET sock,
5973 SSL *ssl,
5974 const char *buf,
5975 int len,
5976 double timeout)
5977{
5978 uint64_t start = 0, now = 0, timeout_ns = 0;
5979 int n, err;
5980 unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
5981
5982#if defined(_WIN32)
5983 typedef int len_t;
5984#else
5985 typedef size_t len_t;
5986#endif
5987
5988 if (timeout > 0) {
5989 now = mg_get_current_time_ns();
5990 start = now;
5991 timeout_ns = (uint64_t)(timeout * 1.0E9);
5992 }
5993
5994 if (ctx == NULL) {
5995 return -2;
5996 }
5997
5998#if defined(NO_SSL) && !defined(USE_MBEDTLS)
5999 if (ssl) {
6000 return -2;
6001 }
6002#endif
6003
6004 /* Try to read until it succeeds, fails, times out, or the server
6005 * shuts down. */
6006 for (;;) {
6007
6008#if defined(USE_MBEDTLS)
6009 if (ssl != NULL) {
6010 n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
6011 if (n <= 0) {
6012 if ((n == MBEDTLS_ERR_SSL_WANT_READ)
6013 || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
6014 || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6015 n = 0;
6016 } else {
6017 fprintf(stderr, "SSL write failed, error %d\n", n);
6018 return -2;
6019 }
6020 } else {
6021 err = 0;
6022 }
6023 } else
6024#elif !defined(NO_SSL)
6025 if (ssl != NULL) {
6026 ERR_clear_error();
6027 n = SSL_write(ssl, buf, len);
6028 if (n <= 0) {
6029 err = SSL_get_error(ssl, n);
6030 if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
6031 err = ERRNO;
6032 } else if ((err == SSL_ERROR_WANT_READ)
6033 || (err == SSL_ERROR_WANT_WRITE)) {
6034 n = 0;
6035 } else {
6036 DEBUG_TRACE("SSL_write() failed, error %d", err);
6037 ERR_clear_error();
6038 return -2;
6039 }
6040 ERR_clear_error();
6041 } else {
6042 err = 0;
6043 }
6044 } else
6045#endif
6046
6047 if (fp != NULL) {
6048 n = (int)fwrite(buf, 1, (size_t)len, fp);
6049 if (ferror(fp)) {
6050 n = -1;
6051 err = ERRNO;
6052 } else {
6053 err = 0;
6054 }
6055 } else {
6056 n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
6057 err = (n < 0) ? ERRNO : 0;
6058#if defined(_WIN32)
6059 if (err == WSAEWOULDBLOCK) {
6060 err = 0;
6061 n = 0;
6062 }
6063#else
6064 if (ERROR_TRY_AGAIN(err)) {
6065 err = 0;
6066 n = 0;
6067 }
6068#endif
6069 if (n < 0) {
6070 /* shutdown of the socket at client side */
6071 return -2;
6072 }
6073 }
6074
6075 if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6076 return -2;
6077 }
6078
6079 if ((n > 0) || ((n == 0) && (len == 0))) {
6080 /* some data has been read, or no data was requested */
6081 return n;
6082 }
6083 if (n < 0) {
6084 /* socket error - check errno */
6085 DEBUG_TRACE("send() failed, error %d", err);
6086
6087 /* TODO (mid): error handling depending on the error code.
6088 * These codes are different between Windows and Linux.
6089 * Currently there is no problem with failing send calls,
6090 * if there is a reproducible situation, it should be
6091 * investigated in detail.
6092 */
6093 return -2;
6094 }
6095
6096 /* Only in case n=0 (timeout), repeat calling the write function */
6097
6098 /* If send failed, wait before retry */
6099 if (fp != NULL) {
6100 /* For files, just wait a fixed time.
6101 * Maybe it helps, maybe not. */
6102 mg_sleep(5);
6103 } else {
6104 /* For sockets, wait for the socket using poll */
6105 struct mg_pollfd pfd[1];
6106 int pollres;
6107
6108 pfd[0].fd = sock;
6109 pfd[0].events = POLLOUT;
6110 pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
6111 if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6112 return -2;
6113 }
6114 if (pollres > 0) {
6115 continue;
6116 }
6117 }
6118
6119 if (timeout > 0) {
6120 now = mg_get_current_time_ns();
6121 if ((now - start) > timeout_ns) {
6122 /* Timeout */
6123 break;
6124 }
6125 }
6126 }
6127
6128 (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
6129 used */
6130
6131 return -1;
6132}
6133
6134
6135static int
6137 FILE *fp,
6138 SOCKET sock,
6139 SSL *ssl,
6140 const char *buf,
6141 int len)
6142{
6143 double timeout = -1.0;
6144 int n, nwritten = 0;
6145
6146 if (ctx == NULL) {
6147 return -1;
6148 }
6149
6150 if (ctx->dd.config[REQUEST_TIMEOUT]) {
6151 timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
6152 }
6153 if (timeout <= 0.0) {
6154 timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
6155 / 1000.0;
6156 }
6157
6158 while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6159 n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
6160 if (n < 0) {
6161 if (nwritten == 0) {
6162 nwritten = -1; /* Propagate the error */
6163 }
6164 break;
6165 } else if (n == 0) {
6166 break; /* No more data to write */
6167 } else {
6168 nwritten += n;
6169 len -= n;
6170 }
6171 }
6172
6173 return nwritten;
6174}
6175
6176
6177/* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
6178 * Return value:
6179 * >=0 .. number of bytes successfully read
6180 * -1 .. timeout
6181 * -2 .. error
6182 */
6183static int
6184pull_inner(FILE *fp,
6185 struct mg_connection *conn,
6186 char *buf,
6187 int len,
6188 double timeout)
6189{
6190 int nread, err = 0;
6191
6192#if defined(_WIN32)
6193 typedef int len_t;
6194#else
6195 typedef size_t len_t;
6196#endif
6197
6198 /* We need an additional wait loop around this, because in some cases
6199 * with TLSwe may get data from the socket but not from SSL_read.
6200 * In this case we need to repeat at least once.
6201 */
6202
6203 if (fp != NULL) {
6204 /* Use read() instead of fread(), because if we're reading from the
6205 * CGI pipe, fread() may block until IO buffer is filled up. We
6206 * cannot afford to block and must pass all read bytes immediately
6207 * to the client. */
6208 nread = (int)read(fileno(fp), buf, (size_t)len);
6209
6210 err = (nread < 0) ? ERRNO : 0;
6211 if ((nread == 0) && (len > 0)) {
6212 /* Should get data, but got EOL */
6213 return -2;
6214 }
6215
6216#if defined(USE_MBEDTLS)
6217 } else if (conn->ssl != NULL) {
6218 struct mg_pollfd pfd[1];
6219 int to_read;
6220 int pollres;
6221
6222 to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
6223
6224 if (to_read > 0) {
6225 /* We already know there is no more data buffered in conn->buf
6226 * but there is more available in the SSL layer. So don't poll
6227 * conn->client.sock yet. */
6228
6229 pollres = 1;
6230 if (to_read > len)
6231 to_read = len;
6232 } else {
6233 pfd[0].fd = conn->client.sock;
6234 pfd[0].events = POLLIN;
6235
6236 to_read = len;
6237
6238 pollres = mg_poll(pfd,
6239 1,
6240 (int)(timeout * 1000.0),
6241 &(conn->phys_ctx->stop_flag));
6242
6243 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6244 return -2;
6245 }
6246 }
6247
6248 if (pollres > 0) {
6249 nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
6250 if (nread <= 0) {
6251 if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
6252 || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
6253 || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6254 nread = 0;
6255 } else {
6256 fprintf(stderr, "SSL read failed, error %d\n", nread);
6257 return -2;
6258 }
6259 } else {
6260 err = 0;
6261 }
6262
6263 } else if (pollres < 0) {
6264 /* Error */
6265 return -2;
6266 } else {
6267 /* pollres = 0 means timeout */
6268 nread = 0;
6269 }
6270
6271#elif !defined(NO_SSL)
6272 } else if (conn->ssl != NULL) {
6273 int ssl_pending;
6274 struct mg_pollfd pfd[1];
6275 int pollres;
6276
6277 if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
6278 /* We already know there is no more data buffered in conn->buf
6279 * but there is more available in the SSL layer. So don't poll
6280 * conn->client.sock yet. */
6281 if (ssl_pending > len) {
6282 ssl_pending = len;
6283 }
6284 pollres = 1;
6285 } else {
6286 pfd[0].fd = conn->client.sock;
6287 pfd[0].events = POLLIN;
6288 pollres = mg_poll(pfd,
6289 1,
6290 (int)(timeout * 1000.0),
6291 &(conn->phys_ctx->stop_flag));
6292 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6293 return -2;
6294 }
6295 }
6296 if (pollres > 0) {
6297 ERR_clear_error();
6298 nread =
6299 SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
6300 if (nread <= 0) {
6301 err = SSL_get_error(conn->ssl, nread);
6302 if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
6303 err = ERRNO;
6304 } else if ((err == SSL_ERROR_WANT_READ)
6305 || (err == SSL_ERROR_WANT_WRITE)) {
6306 nread = 0;
6307 } else {
6308 /* All errors should return -2 */
6309 DEBUG_TRACE("SSL_read() failed, error %d", err);
6310 ERR_clear_error();
6311 return -2;
6312 }
6313 ERR_clear_error();
6314 } else {
6315 err = 0;
6316 }
6317 } else if (pollres < 0) {
6318 /* Error */
6319 return -2;
6320 } else {
6321 /* pollres = 0 means timeout */
6322 nread = 0;
6323 }
6324#endif
6325
6326 } else {
6327 struct mg_pollfd pfd[1];
6328 int pollres;
6329
6330 pfd[0].fd = conn->client.sock;
6331 pfd[0].events = POLLIN;
6332 pollres = mg_poll(pfd,
6333 1,
6334 (int)(timeout * 1000.0),
6335 &(conn->phys_ctx->stop_flag));
6336 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6337 return -2;
6338 }
6339 if (pollres > 0) {
6340 nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
6341 err = (nread < 0) ? ERRNO : 0;
6342 if (nread <= 0) {
6343 /* shutdown of the socket at client side */
6344 return -2;
6345 }
6346 } else if (pollres < 0) {
6347 /* error callint poll */
6348 return -2;
6349 } else {
6350 /* pollres = 0 means timeout */
6351 nread = 0;
6352 }
6353 }
6354
6355 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6356 return -2;
6357 }
6358
6359 if ((nread > 0) || ((nread == 0) && (len == 0))) {
6360 /* some data has been read, or no data was requested */
6361 return nread;
6362 }
6363
6364 if (nread < 0) {
6365 /* socket error - check errno */
6366#if defined(_WIN32)
6367 if (err == WSAEWOULDBLOCK) {
6368 /* TODO (low): check if this is still required */
6369 /* standard case if called from close_socket_gracefully */
6370 return -2;
6371 } else if (err == WSAETIMEDOUT) {
6372 /* TODO (low): check if this is still required */
6373 /* timeout is handled by the while loop */
6374 return 0;
6375 } else if (err == WSAECONNABORTED) {
6376 /* See https://www.chilkatsoft.com/p/p_299.asp */
6377 return -2;
6378 } else {
6379 DEBUG_TRACE("recv() failed, error %d", err);
6380 return -2;
6381 }
6382#else
6383 /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
6384 * if the timeout is reached and if the socket was set to non-
6385 * blocking in close_socket_gracefully, so we can not distinguish
6386 * here. We have to wait for the timeout in both cases for now.
6387 */
6388 if (ERROR_TRY_AGAIN(err)) {
6389 /* TODO (low): check if this is still required */
6390 /* EAGAIN/EWOULDBLOCK:
6391 * standard case if called from close_socket_gracefully
6392 * => should return -1 */
6393 /* or timeout occurred
6394 * => the code must stay in the while loop */
6395
6396 /* EINTR can be generated on a socket with a timeout set even
6397 * when SA_RESTART is effective for all relevant signals
6398 * (see signal(7)).
6399 * => stay in the while loop */
6400 } else {
6401 DEBUG_TRACE("recv() failed, error %d", err);
6402 return -2;
6403 }
6404#endif
6405 }
6406
6407 /* Timeout occurred, but no data available. */
6408 return -1;
6409}
6410
6411
6412static int
6413pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
6414{
6415 int n, nread = 0;
6416 double timeout = -1.0;
6417 uint64_t start_time = 0, now = 0, timeout_ns = 0;
6418
6419 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
6420 timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
6421 }
6422 if (timeout <= 0.0) {
6423 timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
6424 / 1000.0;
6425 }
6426 start_time = mg_get_current_time_ns();
6427 timeout_ns = (uint64_t)(timeout * 1.0E9);
6428
6429 while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6430 n = pull_inner(fp, conn, buf + nread, len, timeout);
6431 if (n == -2) {
6432 if (nread == 0) {
6433 nread = -1; /* Propagate the error */
6434 }
6435 break;
6436 } else if (n == -1) {
6437 /* timeout */
6438 if (timeout >= 0.0) {
6439 now = mg_get_current_time_ns();
6440 if ((now - start_time) <= timeout_ns) {
6441 continue;
6442 }
6443 }
6444 break;
6445 } else if (n == 0) {
6446 break; /* No more data to read */
6447 } else {
6448 nread += n;
6449 len -= n;
6450 }
6451 }
6452
6453 return nread;
6454}
6455
6456
6457static void
6459{
6460 char buf[MG_BUF_LEN];
6461
6462 while (mg_read(conn, buf, sizeof(buf)) > 0)
6463 ;
6464}
6465
6466
6467static int
6468mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
6469{
6470 int64_t content_len, n, buffered_len, nread;
6471 int64_t len64 =
6472 (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
6473 * int, we may not read more
6474 * bytes */
6475 const char *body;
6476
6477 if (conn == NULL) {
6478 return 0;
6479 }
6480
6481 /* If Content-Length is not set for a response with body data,
6482 * we do not know in advance how much data should be read. */
6483 content_len = conn->content_len;
6484 if (content_len < 0) {
6485 /* The body data is completed when the connection is closed. */
6486 content_len = INT64_MAX;
6487 }
6488
6489 nread = 0;
6490 if (conn->consumed_content < content_len) {
6491 /* Adjust number of bytes to read. */
6492 int64_t left_to_read = content_len - conn->consumed_content;
6493 if (left_to_read < len64) {
6494 /* Do not read more than the total content length of the
6495 * request.
6496 */
6497 len64 = left_to_read;
6498 }
6499
6500 /* Return buffered data */
6501 buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
6502 - conn->consumed_content;
6503 if (buffered_len > 0) {
6504 if (len64 < buffered_len) {
6505 buffered_len = len64;
6506 }
6507 body = conn->buf + conn->request_len + conn->consumed_content;
6508 memcpy(buf, body, (size_t)buffered_len);
6509 len64 -= buffered_len;
6510 conn->consumed_content += buffered_len;
6511 nread += buffered_len;
6512 buf = (char *)buf + buffered_len;
6513 }
6514
6515 /* We have returned all buffered data. Read new data from the remote
6516 * socket.
6517 */
6518 if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
6519 conn->consumed_content += n;
6520 nread += n;
6521 } else {
6522 nread = ((nread > 0) ? nread : n);
6523 }
6524 }
6525 return (int)nread;
6526}
6527
6528
6529/* Forward declarations */
6530static void handle_request(struct mg_connection *);
6531static void log_access(const struct mg_connection *);
6532
6533
6534/* Handle request, update statistics and call access log */
6535static void
6537{
6538#if defined(USE_SERVER_STATS)
6539 struct timespec tnow;
6540 conn->conn_state = 4; /* processing */
6541#endif
6542
6543 handle_request(conn);
6544
6545
6546#if defined(USE_SERVER_STATS)
6547 conn->conn_state = 5; /* processed */
6548
6549 clock_gettime(CLOCK_MONOTONIC, &tnow);
6550 conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
6551
6552 mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
6553 mg_atomic_add64(&(conn->phys_ctx->total_data_written),
6554 conn->num_bytes_sent);
6555#endif
6556
6557 DEBUG_TRACE("%s", "handle_request done");
6558
6559 if (conn->phys_ctx->callbacks.end_request != NULL) {
6560 conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
6561 DEBUG_TRACE("%s", "end_request callback done");
6562 }
6563 log_access(conn);
6564}
6565
6566
6567#if defined(USE_HTTP2)
6568#if defined(NO_SSL)
6569#error "HTTP2 requires ALPN, APLN requires SSL/TLS"
6570#endif
6571#define USE_ALPN
6572#include "mod_http2.inl"
6573/* Not supported with HTTP/2 */
6574#define HTTP1_only \
6575 { \
6576 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
6577 http2_must_use_http1(conn); \
6578 return; \
6579 } \
6580 }
6581#else
6582#define HTTP1_only
6583#endif
6584
6585
6586int
6587mg_read(struct mg_connection *conn, void *buf, size_t len)
6588{
6589 if (len > INT_MAX) {
6590 len = INT_MAX;
6591 }
6592
6593 if (conn == NULL) {
6594 return 0;
6595 }
6596
6597 if (conn->is_chunked) {
6598 size_t all_read = 0;
6599
6600 while (len > 0) {
6601 if (conn->is_chunked >= 3) {
6602 /* No more data left to read */
6603 return 0;
6604 }
6605 if (conn->is_chunked != 1) {
6606 /* Has error */
6607 return -1;
6608 }
6609
6610 if (conn->consumed_content != conn->content_len) {
6611 /* copy from the current chunk */
6612 int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
6613
6614 if (read_ret < 1) {
6615 /* read error */
6616 conn->is_chunked = 2;
6617 return -1;
6618 }
6619
6620 all_read += (size_t)read_ret;
6621 len -= (size_t)read_ret;
6622
6623 if (conn->consumed_content == conn->content_len) {
6624 /* Add data bytes in the current chunk have been read,
6625 * so we are expecting \r\n now. */
6626 char x[2];
6627 conn->content_len += 2;
6628 if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
6629 || (x[1] != '\n')) {
6630 /* Protocol violation */
6631 conn->is_chunked = 2;
6632 return -1;
6633 }
6634 }
6635
6636 } else {
6637 /* fetch a new chunk */
6638 size_t i;
6639 char lenbuf[64];
6640 char *end = NULL;
6641 unsigned long chunkSize = 0;
6642
6643 for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
6644 conn->content_len++;
6645 if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
6646 lenbuf[i] = 0;
6647 }
6648 if ((i > 0) && (lenbuf[i] == '\r')
6649 && (lenbuf[i - 1] != '\r')) {
6650 continue;
6651 }
6652 if ((i > 1) && (lenbuf[i] == '\n')
6653 && (lenbuf[i - 1] == '\r')) {
6654 lenbuf[i + 1] = 0;
6655 chunkSize = strtoul(lenbuf, &end, 16);
6656 if (chunkSize == 0) {
6657 /* regular end of content */
6658 conn->is_chunked = 3;
6659 }
6660 break;
6661 }
6662 if (!isxdigit((unsigned char)lenbuf[i])) {
6663 /* illegal character for chunk length */
6664 conn->is_chunked = 2;
6665 return -1;
6666 }
6667 }
6668 if ((end == NULL) || (*end != '\r')) {
6669 /* chunksize not set correctly */
6670 conn->is_chunked = 2;
6671 return -1;
6672 }
6673 if (chunkSize == 0) {
6674 /* try discarding trailer for keep-alive */
6675 conn->content_len += 2;
6676 if ((mg_read_inner(conn, lenbuf, 2) == 2)
6677 && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
6678 conn->is_chunked = 4;
6679 }
6680 break;
6681 }
6682
6683 /* append a new chunk */
6684 conn->content_len += (int64_t)chunkSize;
6685 }
6686 }
6687
6688 return (int)all_read;
6689 }
6690 return mg_read_inner(conn, buf, len);
6691}
6692
6693
6694int
6695mg_write(struct mg_connection *conn, const void *buf, size_t len)
6696{
6697 time_t now;
6698 int n, total, allowed;
6699
6700 if (conn == NULL) {
6701 return 0;
6702 }
6703 if (len > INT_MAX) {
6704 return -1;
6705 }
6706
6707 /* Mark connection as "data sent" */
6708 conn->request_state = 10;
6709#if defined(USE_HTTP2)
6710 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
6711 http2_data_frame_head(conn, len, 0);
6712 }
6713#endif
6714
6715 if (conn->throttle > 0) {
6716 if ((now = time(NULL)) != conn->last_throttle_time) {
6717 conn->last_throttle_time = now;
6718 conn->last_throttle_bytes = 0;
6719 }
6720 allowed = conn->throttle - conn->last_throttle_bytes;
6721 if (allowed > (int)len) {
6722 allowed = (int)len;
6723 }
6724
6725 total = push_all(conn->phys_ctx,
6726 NULL,
6727 conn->client.sock,
6728 conn->ssl,
6729 (const char *)buf,
6730 allowed);
6731
6732 if (total == allowed) {
6733
6734 buf = (const char *)buf + total;
6735 conn->last_throttle_bytes += total;
6736 while ((total < (int)len)
6737 && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6738 allowed = (conn->throttle > ((int)len - total))
6739 ? (int)len - total
6740 : conn->throttle;
6741
6742 n = push_all(conn->phys_ctx,
6743 NULL,
6744 conn->client.sock,
6745 conn->ssl,
6746 (const char *)buf,
6747 allowed);
6748
6749 if (n != allowed) {
6750 break;
6751 }
6752 sleep(1);
6753 conn->last_throttle_bytes = allowed;
6754 conn->last_throttle_time = time(NULL);
6755 buf = (const char *)buf + n;
6756 total += n;
6757 }
6758 }
6759 } else {
6760 total = push_all(conn->phys_ctx,
6761 NULL,
6762 conn->client.sock,
6763 conn->ssl,
6764 (const char *)buf,
6765 (int)len);
6766 }
6767 if (total > 0) {
6768 conn->num_bytes_sent += total;
6769 }
6770 return total;
6771}
6772
6773
6774/* Send a chunk, if "Transfer-Encoding: chunked" is used */
6775int
6777 const char *chunk,
6778 unsigned int chunk_len)
6779{
6780 char lenbuf[16];
6781 size_t lenbuf_len;
6782 int ret;
6783 int t;
6784
6785 /* First store the length information in a text buffer. */
6786 sprintf(lenbuf, "%x\r\n", chunk_len);
6787 lenbuf_len = strlen(lenbuf);
6788
6789 /* Then send length information, chunk and terminating \r\n. */
6790 ret = mg_write(conn, lenbuf, lenbuf_len);
6791 if (ret != (int)lenbuf_len) {
6792 return -1;
6793 }
6794 t = ret;
6795
6796 ret = mg_write(conn, chunk, chunk_len);
6797 if (ret != (int)chunk_len) {
6798 return -1;
6799 }
6800 t += ret;
6801
6802 ret = mg_write(conn, "\r\n", 2);
6803 if (ret != 2) {
6804 return -1;
6805 }
6806 t += ret;
6807
6808 return t;
6809}
6810
6811
6812#if defined(GCC_DIAGNOSTIC)
6813/* This block forwards format strings to printf implementations,
6814 * so we need to disable the format-nonliteral warning. */
6815#pragma GCC diagnostic push
6816#pragma GCC diagnostic ignored "-Wformat-nonliteral"
6817#endif
6818
6819
6820/* Alternative alloc_vprintf() for non-compliant C runtimes */
6821static int
6822alloc_vprintf2(char **buf, const char *fmt, va_list ap)
6823{
6824 va_list ap_copy;
6825 size_t size = MG_BUF_LEN / 4;
6826 int len = -1;
6827
6828 *buf = NULL;
6829 while (len < 0) {
6830 if (*buf) {
6831 mg_free(*buf);
6832 }
6833
6834 size *= 4;
6835 *buf = (char *)mg_malloc(size);
6836 if (!*buf) {
6837 break;
6838 }
6839
6840 va_copy(ap_copy, ap);
6841 len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
6842 va_end(ap_copy);
6843 (*buf)[size - 1] = 0;
6844 }
6845
6846 return len;
6847}
6848
6849
6850/* Print message to buffer. If buffer is large enough to hold the message,
6851 * return buffer. If buffer is to small, allocate large enough buffer on
6852 * heap,
6853 * and return allocated buffer. */
6854static int
6855alloc_vprintf(char **out_buf,
6856 char *prealloc_buf,
6857 size_t prealloc_size,
6858 const char *fmt,
6859 va_list ap)
6860{
6861 va_list ap_copy;
6862 int len;
6863
6864 /* Windows is not standard-compliant, and vsnprintf() returns -1 if
6865 * buffer is too small. Also, older versions of msvcrt.dll do not have
6866 * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
6867 * Therefore, we make two passes: on first pass, get required message
6868 * length.
6869 * On second pass, actually print the message. */
6870 va_copy(ap_copy, ap);
6871 len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
6872 va_end(ap_copy);
6873
6874 if (len < 0) {
6875 /* C runtime is not standard compliant, vsnprintf() returned -1.
6876 * Switch to alternative code path that uses incremental
6877 * allocations.
6878 */
6879 va_copy(ap_copy, ap);
6880 len = alloc_vprintf2(out_buf, fmt, ap_copy);
6881 va_end(ap_copy);
6882
6883 } else if ((size_t)(len) >= prealloc_size) {
6884 /* The pre-allocated buffer not large enough. */
6885 /* Allocate a new buffer. */
6886 *out_buf = (char *)mg_malloc((size_t)(len) + 1);
6887 if (!*out_buf) {
6888 /* Allocation failed. Return -1 as "out of memory" error. */
6889 return -1;
6890 }
6891 /* Buffer allocation successful. Store the string there. */
6892 va_copy(ap_copy, ap);
6894 vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
6895 va_end(ap_copy);
6896
6897 } else {
6898 /* The pre-allocated buffer is large enough.
6899 * Use it to store the string and return the address. */
6900 va_copy(ap_copy, ap);
6902 vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
6903 va_end(ap_copy);
6904 *out_buf = prealloc_buf;
6905 }
6906
6907 return len;
6908}
6909
6910
6911#if defined(GCC_DIAGNOSTIC)
6912/* Enable format-nonliteral warning again. */
6913#pragma GCC diagnostic pop
6914#endif
6915
6916
6917static int
6918mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
6919{
6920 char mem[MG_BUF_LEN];
6921 char *buf = NULL;
6922 int len;
6923
6924 if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
6925 len = mg_write(conn, buf, (size_t)len);
6926 }
6927 if (buf != mem) {
6928 mg_free(buf);
6929 }
6930
6931 return len;
6932}
6933
6934
6935int
6936mg_printf(struct mg_connection *conn, const char *fmt, ...)
6937{
6938 va_list ap;
6939 int result;
6940
6941 va_start(ap, fmt);
6942 result = mg_vprintf(conn, fmt, ap);
6943 va_end(ap);
6944
6945 return result;
6946}
6947
6948
6949int
6950mg_url_decode(const char *src,
6951 int src_len,
6952 char *dst,
6953 int dst_len,
6954 int is_form_url_encoded)
6955{
6956 int i, j, a, b;
6957#define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
6958
6959 for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
6960 if ((i < src_len - 2) && (src[i] == '%')
6961 && isxdigit((unsigned char)src[i + 1])
6962 && isxdigit((unsigned char)src[i + 2])) {
6963 a = tolower((unsigned char)src[i + 1]);
6964 b = tolower((unsigned char)src[i + 2]);
6965 dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
6966 i += 2;
6967 } else if (is_form_url_encoded && (src[i] == '+')) {
6968 dst[j] = ' ';
6969 } else {
6970 dst[j] = src[i];
6971 }
6972 }
6973
6974 dst[j] = '\0'; /* Null-terminate the destination */
6975
6976 return (i >= src_len) ? j : -1;
6977}
6978
6979
6980/* form url decoding of an entire string */
6981static void
6983{
6984 int len = (int)strlen(buf);
6985 (void)mg_url_decode(buf, len, buf, len + 1, 1);
6986}
6987
6988
6989int
6990mg_get_var(const char *data,
6991 size_t data_len,
6992 const char *name,
6993 char *dst,
6994 size_t dst_len)
6995{
6996 return mg_get_var2(data, data_len, name, dst, dst_len, 0);
6997}
6998
6999
7000int
7001mg_get_var2(const char *data,
7002 size_t data_len,
7003 const char *name,
7004 char *dst,
7005 size_t dst_len,
7006 size_t occurrence)
7007{
7008 const char *p, *e, *s;
7009 size_t name_len;
7010 int len;
7011
7012 if ((dst == NULL) || (dst_len == 0)) {
7013 len = -2;
7014 } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
7015 len = -1;
7016 dst[0] = '\0';
7017 } else {
7018 name_len = strlen(name);
7019 e = data + data_len;
7020 len = -1;
7021 dst[0] = '\0';
7022
7023 /* data is "var1=val1&var2=val2...". Find variable first */
7024 for (p = data; p + name_len < e; p++) {
7025 if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
7026 && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
7027 /* Point p to variable value */
7028 p += name_len + 1;
7029
7030 /* Point s to the end of the value */
7031 s = (const char *)memchr(p, '&', (size_t)(e - p));
7032 if (s == NULL) {
7033 s = e;
7034 }
7035 DEBUG_ASSERT(s >= p);
7036 if (s < p) {
7037 return -3;
7038 }
7039
7040 /* Decode variable into destination buffer */
7041 len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
7042
7043 /* Redirect error code from -1 to -2 (destination buffer too
7044 * small). */
7045 if (len == -1) {
7046 len = -2;
7047 }
7048 break;
7049 }
7050 }
7051 }
7052
7053 return len;
7054}
7055
7056
7057/* split a string "key1=val1&key2=val2" into key/value pairs */
7058int
7060 struct mg_header *form_fields,
7061 unsigned num_form_fields)
7062{
7063 char *b;
7064 int i;
7065 int num = 0;
7066
7067 if (data == NULL) {
7068 /* parameter error */
7069 return -1;
7070 }
7071
7072 if ((form_fields == NULL) && (num_form_fields == 0)) {
7073 /* determine the number of expected fields */
7074 if (data[0] == 0) {
7075 return 0;
7076 }
7077 /* count number of & to return the number of key-value-pairs */
7078 num = 1;
7079 while (*data) {
7080 if (*data == '&') {
7081 num++;
7082 }
7083 data++;
7084 }
7085 return num;
7086 }
7087
7088 if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
7089 /* parameter error */
7090 return -1;
7091 }
7092
7093 for (i = 0; i < (int)num_form_fields; i++) {
7094 /* extract key-value pairs from input data */
7095 while ((*data == ' ') || (*data == '\t')) {
7096 /* skip initial spaces */
7097 data++;
7098 }
7099 if (*data == 0) {
7100 /* end of string reached */
7101 break;
7102 }
7103 form_fields[num].name = data;
7104
7105 /* find & or = */
7106 b = data;
7107 while ((*b != 0) && (*b != '&') && (*b != '=')) {
7108 b++;
7109 }
7110
7111 if (*b == 0) {
7112 /* last key without value */
7113 form_fields[num].value = NULL;
7114 } else if (*b == '&') {
7115 /* mid key without value */
7116 form_fields[num].value = NULL;
7117 } else {
7118 /* terminate string */
7119 *b = 0;
7120 /* value starts after '=' */
7121 data = b + 1;
7122 form_fields[num].value = data;
7123 }
7124
7125 /* new field is stored */
7126 num++;
7127
7128 /* find a next key */
7129 b = strchr(data, '&');
7130 if (b == 0) {
7131 /* no more data */
7132 break;
7133 } else {
7134 /* terminate value of last field at '&' */
7135 *b = 0;
7136 /* next key-value-pairs starts after '&' */
7137 data = b + 1;
7138 }
7139 }
7140
7141 /* Decode all values */
7142 for (i = 0; i < num; i++) {
7143 if (form_fields[i].name) {
7144 url_decode_in_place((char *)form_fields[i].name);
7145 }
7146 if (form_fields[i].value) {
7147 url_decode_in_place((char *)form_fields[i].value);
7148 }
7149 }
7150
7151 /* return number of fields found */
7152 return num;
7153}
7154
7155
7156/* HCP24: some changes to compare hole var_name */
7157int
7158mg_get_cookie(const char *cookie_header,
7159 const char *var_name,
7160 char *dst,
7161 size_t dst_size)
7162{
7163 const char *s, *p, *end;
7164 int name_len, len = -1;
7165
7166 if ((dst == NULL) || (dst_size == 0)) {
7167 return -2;
7168 }
7169
7170 dst[0] = '\0';
7171 if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
7172 return -1;
7173 }
7174
7175 name_len = (int)strlen(var_name);
7176 end = s + strlen(s);
7177 for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
7178 if (s[name_len] == '=') {
7179 /* HCP24: now check is it a substring or a full cookie name */
7180 if ((s == cookie_header) || (s[-1] == ' ')) {
7181 s += name_len + 1;
7182 if ((p = strchr(s, ' ')) == NULL) {
7183 p = end;
7184 }
7185 if (p[-1] == ';') {
7186 p--;
7187 }
7188 if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
7189 s++;
7190 p--;
7191 }
7192 if ((size_t)(p - s) < dst_size) {
7193 len = (int)(p - s);
7194 mg_strlcpy(dst, s, (size_t)len + 1);
7195 } else {
7196 len = -3;
7197 }
7198 break;
7199 }
7200 }
7201 }
7202 return len;
7203}
7204
7205
7206#if defined(USE_WEBSOCKET) || defined(USE_LUA)
7207static void
7208base64_encode(const unsigned char *src, int src_len, char *dst)
7209{
7210 static const char *b64 =
7211 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7212 int i, j, a, b, c;
7213
7214 for (i = j = 0; i < src_len; i += 3) {
7215 a = src[i];
7216 b = ((i + 1) >= src_len) ? 0 : src[i + 1];
7217 c = ((i + 2) >= src_len) ? 0 : src[i + 2];
7218
7219 dst[j++] = b64[a >> 2];
7220 dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
7221 if (i + 1 < src_len) {
7222 dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
7223 }
7224 if (i + 2 < src_len) {
7225 dst[j++] = b64[c & 63];
7226 }
7227 }
7228 while (j % 4 != 0) {
7229 dst[j++] = '=';
7230 }
7231 dst[j++] = '\0';
7232}
7233#endif
7234
7235
7236#if defined(USE_LUA)
7237static unsigned char
7238b64reverse(char letter)
7239{
7240 if ((letter >= 'A') && (letter <= 'Z')) {
7241 return letter - 'A';
7242 }
7243 if ((letter >= 'a') && (letter <= 'z')) {
7244 return letter - 'a' + 26;
7245 }
7246 if ((letter >= '0') && (letter <= '9')) {
7247 return letter - '0' + 52;
7248 }
7249 if (letter == '+') {
7250 return 62;
7251 }
7252 if (letter == '/') {
7253 return 63;
7254 }
7255 if (letter == '=') {
7256 return 255; /* normal end */
7257 }
7258 return 254; /* error */
7259}
7260
7261
7262static int
7263base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
7264{
7265 int i;
7266 unsigned char a, b, c, d;
7267
7268 *dst_len = 0;
7269
7270 for (i = 0; i < src_len; i += 4) {
7271 a = b64reverse(src[i]);
7272 if (a >= 254) {
7273 return i;
7274 }
7275
7276 b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
7277 if (b >= 254) {
7278 return i + 1;
7279 }
7280
7281 c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
7282 if (c == 254) {
7283 return i + 2;
7284 }
7285
7286 d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
7287 if (d == 254) {
7288 return i + 3;
7289 }
7290
7291 dst[(*dst_len)++] = (a << 2) + (b >> 4);
7292 if (c != 255) {
7293 dst[(*dst_len)++] = (b << 4) + (c >> 2);
7294 if (d != 255) {
7295 dst[(*dst_len)++] = (c << 6) + d;
7296 }
7297 }
7298 }
7299 return -1;
7300}
7301#endif
7302
7303
7304static int
7306{
7307 if (conn) {
7308 const char *s = conn->request_info.request_method;
7309 return (s != NULL)
7310 && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
7311 || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
7312 }
7313 return 0;
7314}
7315
7316
7317#if !defined(NO_FILES)
7318static int
7320 struct mg_connection *conn, /* in: request (must be valid) */
7321 const char *filename /* in: filename (must be valid) */
7322)
7323{
7324#if !defined(NO_CGI)
7325 unsigned char cgi_config_idx, inc, max;
7326#endif
7327
7328#if defined(USE_LUA)
7329 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
7330 filename)
7331 > 0) {
7332 return 1;
7333 }
7334#endif
7335#if defined(USE_DUKTAPE)
7336 if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
7337 filename)
7338 > 0) {
7339 return 1;
7340 }
7341#endif
7342#if !defined(NO_CGI)
7345 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
7346 if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
7348 conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
7349 filename)
7350 > 0)) {
7351 return 1;
7352 }
7353 }
7354#endif
7355 /* filename and conn could be unused, if all preocessor conditions
7356 * are false (no script language supported). */
7357 (void)filename;
7358 (void)conn;
7359
7360 return 0;
7361}
7362
7363
7364static int
7366 struct mg_connection *conn, /* in: request (must be valid) */
7367 const char *filename /* in: filename (must be valid) */
7368)
7369{
7370#if defined(USE_LUA)
7371 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
7372 filename)
7373 > 0) {
7374 return 1;
7375 }
7376#endif
7378 > 0) {
7379 return 1;
7380 }
7381 return 0;
7382}
7383
7384
7385/* For given directory path, substitute it to valid index file.
7386 * Return 1 if index file has been found, 0 if not found.
7387 * If the file is found, it's stats is returned in stp. */
7388static int
7390 char *path,
7391 size_t path_len,
7392 struct mg_file_stat *filestat)
7393{
7394 const char *list = conn->dom_ctx->config[INDEX_FILES];
7395 struct vec filename_vec;
7396 size_t n = strlen(path);
7397 int found = 0;
7398
7399 /* The 'path' given to us points to the directory. Remove all trailing
7400 * directory separator characters from the end of the path, and
7401 * then append single directory separator character. */
7402 while ((n > 0) && (path[n - 1] == '/')) {
7403 n--;
7404 }
7405 path[n] = '/';
7406
7407 /* Traverse index files list. For each entry, append it to the given
7408 * path and see if the file exists. If it exists, break the loop */
7409 while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
7410 /* Ignore too long entries that may overflow path buffer */
7411 if ((filename_vec.len + 1) > (path_len - (n + 1))) {
7412 continue;
7413 }
7414
7415 /* Prepare full path to the index file */
7416 mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
7417
7418 /* Does it exist? */
7419 if (mg_stat(conn, path, filestat)) {
7420 /* Yes it does, break the loop */
7421 found = 1;
7422 break;
7423 }
7424 }
7425
7426 /* If no index file exists, restore directory path */
7427 if (!found) {
7428 path[n] = '\0';
7429 }
7430
7431 return found;
7432}
7433#endif
7434
7435
7436static void
7437interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
7438 char *filename, /* out: filename */
7439 size_t filename_buf_len, /* in: size of filename buffer */
7440 struct mg_file_stat *filestat, /* out: file status structure */
7441 int *is_found, /* out: file found (directly) */
7442 int *is_script_resource, /* out: handled by a script? */
7443 int *is_websocket_request, /* out: websocket connetion? */
7444 int *is_put_or_delete_request, /* out: put/delete a file? */
7445 int *is_template_text /* out: SSI file or LSP file? */
7446)
7447{
7448 char const *accept_encoding;
7449
7450#if !defined(NO_FILES)
7451 const char *uri = conn->request_info.local_uri;
7452 const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
7453 const char *rewrite;
7454 struct vec a, b;
7455 ptrdiff_t match_len;
7456 char gz_path[UTF8_PATH_MAX];
7457 int truncated;
7458#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7459 char *tmp_str;
7460 size_t tmp_str_len, sep_pos;
7461 int allow_substitute_script_subresources;
7462#endif
7463#else
7464 (void)filename_buf_len; /* unused if NO_FILES is defined */
7465#endif
7466
7467 /* Step 1: Set all initially unknown outputs to zero */
7468 memset(filestat, 0, sizeof(*filestat));
7469 *filename = 0;
7470 *is_found = 0;
7471 *is_script_resource = 0;
7472 *is_template_text = 0;
7473
7474 /* Step 2: Check if the request attempts to modify the file system */
7475 *is_put_or_delete_request = is_put_or_delete_method(conn);
7476
7477 /* Step 3: Check if it is a websocket request, and modify the document
7478 * root if required */
7479#if defined(USE_WEBSOCKET)
7480 *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
7481#if !defined(NO_FILES)
7482 if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
7483 root = conn->dom_ctx->config[WEBSOCKET_ROOT];
7484 }
7485#endif /* !NO_FILES */
7486#else /* USE_WEBSOCKET */
7487 *is_websocket_request = 0;
7488#endif /* USE_WEBSOCKET */
7489
7490 /* Step 4: Check if gzip encoded response is allowed */
7491 conn->accept_gzip = 0;
7492 if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
7493 if (strstr(accept_encoding, "gzip") != NULL) {
7494 conn->accept_gzip = 1;
7495 }
7496 }
7497
7498#if !defined(NO_FILES)
7499 /* Step 5: If there is no root directory, don't look for files. */
7500 /* Note that root == NULL is a regular use case here. This occurs,
7501 * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
7502 * config is not required. */
7503 if (root == NULL) {
7504 /* all file related outputs have already been set to 0, just return
7505 */
7506 return;
7507 }
7508
7509 /* Step 6: Determine the local file path from the root path and the
7510 * request uri. */
7511 /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
7512 * part of the path one byte on the right. */
7513 truncated = 0;
7515 conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
7516
7517 if (truncated) {
7518 goto interpret_cleanup;
7519 }
7520
7521 /* Step 7: URI rewriting */
7522 rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
7523 while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
7524 if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
7525 mg_snprintf(conn,
7526 &truncated,
7527 filename,
7528 filename_buf_len - 1,
7529 "%.*s%s",
7530 (int)b.len,
7531 b.ptr,
7532 uri + match_len);
7533 break;
7534 }
7535 }
7536
7537 if (truncated) {
7538 goto interpret_cleanup;
7539 }
7540
7541 /* Step 8: Check if the file exists at the server */
7542 /* Local file path and name, corresponding to requested URI
7543 * is now stored in "filename" variable. */
7544 if (mg_stat(conn, filename, filestat)) {
7545 int uri_len = (int)strlen(uri);
7546 int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
7547
7548 /* 8.1: File exists. */
7549 *is_found = 1;
7550
7551 /* 8.2: Check if it is a script type. */
7553 /* The request addresses a CGI resource, Lua script or
7554 * server-side javascript.
7555 * The URI corresponds to the script itself (like
7556 * /path/script.cgi), and there is no additional resource
7557 * path (like /path/script.cgi/something).
7558 * Requests that modify (replace or delete) a resource, like
7559 * PUT and DELETE requests, should replace/delete the script
7560 * file.
7561 * Requests that read or write from/to a resource, like GET and
7562 * POST requests, should call the script and return the
7563 * generated response. */
7564 *is_script_resource = (!*is_put_or_delete_request);
7565 }
7566
7567 /* 8.3: Check for SSI and LSP files */
7569 /* Same as above, but for *.lsp and *.shtml files. */
7570 /* A "template text" is a file delivered directly to the client,
7571 * but with some text tags replaced by dynamic content.
7572 * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
7573 * (LP, LSP) file. */
7574 *is_template_text = (!*is_put_or_delete_request);
7575 }
7576
7577 /* 8.4: If the request target is a directory, there could be
7578 * a substitute file (index.html, index.cgi, ...). */
7579 if (filestat->is_directory && is_uri_end_slash) {
7580 /* Use a local copy here, since substitute_index_file will
7581 * change the content of the file status */
7582 struct mg_file_stat tmp_filestat;
7583 memset(&tmp_filestat, 0, sizeof(tmp_filestat));
7584
7586 conn, filename, filename_buf_len, &tmp_filestat)) {
7587
7588 /* Substitute file found. Copy stat to the output, then
7589 * check if the file is a script file */
7590 *filestat = tmp_filestat;
7591
7593 /* Substitute file is a script file */
7594 *is_script_resource = 1;
7595 } else if (extention_matches_template_text(conn, filename)) {
7596 /* Substitute file is a LSP or SSI file */
7597 *is_template_text = 1;
7598 } else {
7599 /* Substitute file is a regular file */
7600 *is_script_resource = 0;
7601 *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
7602 }
7603 }
7604 /* If there is no substitute file, the server could return
7605 * a directory listing in a later step */
7606 }
7607 return;
7608 }
7609
7610 /* Step 9: Check for zipped files: */
7611 /* If we can't find the actual file, look for the file
7612 * with the same name but a .gz extension. If we find it,
7613 * use that and set the gzipped flag in the file struct
7614 * to indicate that the response need to have the content-
7615 * encoding: gzip header.
7616 * We can only do this if the browser declares support. */
7617 if (conn->accept_gzip) {
7619 conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
7620
7621 if (truncated) {
7622 goto interpret_cleanup;
7623 }
7624
7625 if (mg_stat(conn, gz_path, filestat)) {
7626 if (filestat) {
7627 filestat->is_gzipped = 1;
7628 *is_found = 1;
7629 }
7630 /* Currently gz files can not be scripts. */
7631 return;
7632 }
7633 }
7634
7635#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7636 /* Step 10: Script resources may handle sub-resources */
7637 /* Support PATH_INFO for CGI scripts. */
7638 tmp_str_len = strlen(filename);
7639 tmp_str =
7640 (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
7641 if (!tmp_str) {
7642 /* Out of memory */
7643 goto interpret_cleanup;
7644 }
7645 memcpy(tmp_str, filename, tmp_str_len + 1);
7646
7647 /* Check config, if index scripts may have sub-resources */
7648 allow_substitute_script_subresources =
7650 "yes");
7651
7652 sep_pos = tmp_str_len;
7653 while (sep_pos > 0) {
7654 sep_pos--;
7655 if (tmp_str[sep_pos] == '/') {
7656 int is_script = 0, does_exist = 0;
7657
7658 tmp_str[sep_pos] = 0;
7659 if (tmp_str[0]) {
7660 is_script = extention_matches_script(conn, tmp_str);
7661 does_exist = mg_stat(conn, tmp_str, filestat);
7662 }
7663
7664 if (does_exist && is_script) {
7665 filename[sep_pos] = 0;
7666 memmove(filename + sep_pos + 2,
7667 filename + sep_pos + 1,
7668 strlen(filename + sep_pos + 1) + 1);
7669 conn->path_info = filename + sep_pos + 1;
7670 filename[sep_pos + 1] = '/';
7671 *is_script_resource = 1;
7672 *is_found = 1;
7673 break;
7674 }
7675
7676 if (allow_substitute_script_subresources) {
7678 conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
7679
7680 /* some intermediate directory has an index file */
7681 if (extention_matches_script(conn, tmp_str)) {
7682
7683 size_t script_name_len = strlen(tmp_str);
7684
7685 /* subres_name read before this memory locatio will be
7686 overwritten */
7687 char *subres_name = filename + sep_pos;
7688 size_t subres_name_len = strlen(subres_name);
7689
7690 DEBUG_TRACE("Substitute script %s serving path %s",
7691 tmp_str,
7692 filename);
7693
7694 /* this index file is a script */
7695 if ((script_name_len + subres_name_len + 2)
7696 >= filename_buf_len) {
7697 mg_free(tmp_str);
7698 goto interpret_cleanup;
7699 }
7700
7701 conn->path_info =
7702 filename + script_name_len + 1; /* new target */
7703 memmove(conn->path_info, subres_name, subres_name_len);
7704 conn->path_info[subres_name_len] = 0;
7705 memcpy(filename, tmp_str, script_name_len + 1);
7706
7707 *is_script_resource = 1;
7708 *is_found = 1;
7709 break;
7710
7711 } else {
7712
7713 DEBUG_TRACE("Substitute file %s serving path %s",
7714 tmp_str,
7715 filename);
7716
7717 /* non-script files will not have sub-resources */
7718 filename[sep_pos] = 0;
7719 conn->path_info = 0;
7720 *is_script_resource = 0;
7721 *is_found = 0;
7722 break;
7723 }
7724 }
7725 }
7726
7727 tmp_str[sep_pos] = '/';
7728 }
7729 }
7730
7731 mg_free(tmp_str);
7732
7733#endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
7734#endif /* !defined(NO_FILES) */
7735 return;
7736
7737#if !defined(NO_FILES)
7738/* Reset all outputs */
7739interpret_cleanup:
7740 memset(filestat, 0, sizeof(*filestat));
7741 *filename = 0;
7742 *is_found = 0;
7743 *is_script_resource = 0;
7744 *is_websocket_request = 0;
7745 *is_put_or_delete_request = 0;
7746#endif /* !defined(NO_FILES) */
7747}
7748
7749
7750/* Check whether full request is buffered. Return:
7751 * -1 if request or response is malformed
7752 * 0 if request or response is not yet fully buffered
7753 * >0 actual request length, including last \r\n\r\n */
7754static int
7755get_http_header_len(const char *buf, int buflen)
7756{
7757 int i;
7758 for (i = 0; i < buflen; i++) {
7759 /* Do an unsigned comparison in some conditions below */
7760 const unsigned char c = (unsigned char)buf[i];
7761
7762 if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
7763 && !isprint(c)) {
7764 /* abort scan as soon as one malformed character is found */
7765 return -1;
7766 }
7767
7768 if (i < buflen - 1) {
7769 if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
7770 /* Two newline, no carriage return - not standard compliant,
7771 * but it should be accepted */
7772 return i + 2;
7773 }
7774 }
7775
7776 if (i < buflen - 3) {
7777 if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
7778 && (buf[i + 3] == '\n')) {
7779 /* Two \r\n - standard compliant */
7780 return i + 4;
7781 }
7782 }
7783 }
7784
7785 return 0;
7786}
7787
7788
7789#if !defined(NO_CACHING)
7790/* Convert month to the month number. Return -1 on error, or month number */
7791static int
7792get_month_index(const char *s)
7793{
7794 size_t i;
7795
7796 for (i = 0; i < ARRAY_SIZE(month_names); i++) {
7797 if (!strcmp(s, month_names[i])) {
7798 return (int)i;
7799 }
7800 }
7801
7802 return -1;
7803}
7804
7805
7806/* Parse UTC date-time string, and return the corresponding time_t value. */
7807static time_t
7808parse_date_string(const char *datetime)
7809{
7810 char month_str[32] = {0};
7811 int second, minute, hour, day, month, year;
7812 time_t result = (time_t)0;
7813 struct tm tm;
7814
7815 if ((sscanf(datetime,
7816 "%d/%3s/%d %d:%d:%d",
7817 &day,
7818 month_str,
7819 &year,
7820 &hour,
7821 &minute,
7822 &second)
7823 == 6)
7824 || (sscanf(datetime,
7825 "%d %3s %d %d:%d:%d",
7826 &day,
7827 month_str,
7828 &year,
7829 &hour,
7830 &minute,
7831 &second)
7832 == 6)
7833 || (sscanf(datetime,
7834 "%*3s, %d %3s %d %d:%d:%d",
7835 &day,
7836 month_str,
7837 &year,
7838 &hour,
7839 &minute,
7840 &second)
7841 == 6)
7842 || (sscanf(datetime,
7843 "%d-%3s-%d %d:%d:%d",
7844 &day,
7845 month_str,
7846 &year,
7847 &hour,
7848 &minute,
7849 &second)
7850 == 6)) {
7851 month = get_month_index(month_str);
7852 if ((month >= 0) && (year >= 1970)) {
7853 memset(&tm, 0, sizeof(tm));
7854 tm.tm_year = year - 1900;
7855 tm.tm_mon = month;
7856 tm.tm_mday = day;
7857 tm.tm_hour = hour;
7858 tm.tm_min = minute;
7859 tm.tm_sec = second;
7860 result = timegm(&tm);
7861 }
7862 }
7863
7864 return result;
7865}
7866#endif /* !NO_CACHING */
7867
7868
7869/* Pre-process URIs according to RFC + protect against directory disclosure
7870 * attacks by removing '..', excessive '/' and '\' characters */
7871static void
7873{
7874 /* Windows backend protection
7875 * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
7876 * in URI by slash */
7877 char *out_end = inout;
7878 char *in = inout;
7879
7880 if (!in) {
7881 /* Param error. */
7882 return;
7883 }
7884
7885 while (*in) {
7886 if (*in == '\\') {
7887 *in = '/';
7888 }
7889 in++;
7890 }
7891
7892 /* Algorithm "remove_dot_segments" from
7893 * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
7894 /* Step 1:
7895 * The input buffer is initialized.
7896 * The output buffer is initialized to the empty string.
7897 */
7898 in = inout;
7899
7900 /* Step 2:
7901 * While the input buffer is not empty, loop as follows:
7902 */
7903 /* Less than out_end of the inout buffer is used as output, so keep
7904 * condition: out_end <= in */
7905 while (*in) {
7906 /* Step 2a:
7907 * If the input buffer begins with a prefix of "../" or "./",
7908 * then remove that prefix from the input buffer;
7909 */
7910 if (!strncmp(in, "../", 3)) {
7911 in += 3;
7912 } else if (!strncmp(in, "./", 2)) {
7913 in += 2;
7914 }
7915 /* otherwise */
7916 /* Step 2b:
7917 * if the input buffer begins with a prefix of "/./" or "/.",
7918 * where "." is a complete path segment, then replace that
7919 * prefix with "/" in the input buffer;
7920 */
7921 else if (!strncmp(in, "/./", 3)) {
7922 in += 2;
7923 } else if (!strcmp(in, "/.")) {
7924 in[1] = 0;
7925 }
7926 /* otherwise */
7927 /* Step 2c:
7928 * if the input buffer begins with a prefix of "/../" or "/..",
7929 * where ".." is a complete path segment, then replace that
7930 * prefix with "/" in the input buffer and remove the last
7931 * segment and its preceding "/" (if any) from the output
7932 * buffer;
7933 */
7934 else if (!strncmp(in, "/../", 4)) {
7935 in += 3;
7936 if (inout != out_end) {
7937 /* remove last segment */
7938 do {
7939 out_end--;
7940 } while ((inout != out_end) && (*out_end != '/'));
7941 }
7942 } else if (!strcmp(in, "/..")) {
7943 in[1] = 0;
7944 if (inout != out_end) {
7945 /* remove last segment */
7946 do {
7947 out_end--;
7948 } while ((inout != out_end) && (*out_end != '/'));
7949 }
7950 }
7951 /* otherwise */
7952 /* Step 2d:
7953 * if the input buffer consists only of "." or "..", then remove
7954 * that from the input buffer;
7955 */
7956 else if (!strcmp(in, ".") || !strcmp(in, "..")) {
7957 *in = 0;
7958 }
7959 /* otherwise */
7960 /* Step 2e:
7961 * move the first path segment in the input buffer to the end of
7962 * the output buffer, including the initial "/" character (if
7963 * any) and any subsequent characters up to, but not including,
7964 * the next "/" character or the end of the input buffer.
7965 */
7966 else {
7967 do {
7968 *out_end = *in;
7969 out_end++;
7970 in++;
7971 } while ((*in != 0) && (*in != '/'));
7972 }
7973 }
7974
7975 /* Step 3:
7976 * Finally, the output buffer is returned as the result of
7977 * remove_dot_segments.
7978 */
7979 /* Terminate output */
7980 *out_end = 0;
7981
7982 /* For Windows, the files/folders "x" and "x." (with a dot but without
7983 * extension) are identical. Replace all "./" by "/" and remove a "." at
7984 * the end. Also replace all "//" by "/". Repeat until there is no "./"
7985 * or "//" anymore.
7986 */
7987 out_end = in = inout;
7988 while (*in) {
7989 if (*in == '.') {
7990 /* remove . at the end or preceding of / */
7991 char *in_ahead = in;
7992 do {
7993 in_ahead++;
7994 } while (*in_ahead == '.');
7995 if (*in_ahead == '/') {
7996 in = in_ahead;
7997 if ((out_end != inout) && (out_end[-1] == '/')) {
7998 /* remove generated // */
7999 out_end--;
8000 }
8001 } else if (*in_ahead == 0) {
8002 in = in_ahead;
8003 } else {
8004 do {
8005 *out_end++ = '.';
8006 in++;
8007 } while (in != in_ahead);
8008 }
8009 } else if (*in == '/') {
8010 /* replace // by / */
8011 *out_end++ = '/';
8012 do {
8013 in++;
8014 } while (*in == '/');
8015 } else {
8016 *out_end++ = *in;
8017 in++;
8018 }
8019 }
8020 *out_end = 0;
8021}
8022
8023
8024static const struct {
8025 const char *extension;
8026 size_t ext_len;
8027 const char *mime_type;
8028} builtin_mime_types[] = {
8029 /* IANA registered MIME types
8030 * (http://www.iana.org/assignments/media-types)
8031 * application types */
8032 {".bin", 4, "application/octet-stream"},
8033 {".deb", 4, "application/octet-stream"},
8034 {".dmg", 4, "application/octet-stream"},
8035 {".dll", 4, "application/octet-stream"},
8036 {".doc", 4, "application/msword"},
8037 {".eps", 4, "application/postscript"},
8038 {".exe", 4, "application/octet-stream"},
8039 {".iso", 4, "application/octet-stream"},
8040 {".js", 3, "application/javascript"},
8041 {".json", 5, "application/json"},
8042 {".msi", 4, "application/octet-stream"},
8043 {".pdf", 4, "application/pdf"},
8044 {".ps", 3, "application/postscript"},
8045 {".rtf", 4, "application/rtf"},
8046 {".xhtml", 6, "application/xhtml+xml"},
8047 {".xsl", 4, "application/xml"},
8048 {".xslt", 5, "application/xml"},
8049
8050 /* fonts */
8051 {".ttf", 4, "application/font-sfnt"},
8052 {".cff", 4, "application/font-sfnt"},
8053 {".otf", 4, "application/font-sfnt"},
8054 {".aat", 4, "application/font-sfnt"},
8055 {".sil", 4, "application/font-sfnt"},
8056 {".pfr", 4, "application/font-tdpfr"},
8057 {".woff", 5, "application/font-woff"},
8058 {".woff2", 6, "application/font-woff2"},
8059
8060 /* audio */
8061 {".mp3", 4, "audio/mpeg"},
8062 {".oga", 4, "audio/ogg"},
8063 {".ogg", 4, "audio/ogg"},
8064
8065 /* image */
8066 {".gif", 4, "image/gif"},
8067 {".ief", 4, "image/ief"},
8068 {".jpeg", 5, "image/jpeg"},
8069 {".jpg", 4, "image/jpeg"},
8070 {".jpm", 4, "image/jpm"},
8071 {".jpx", 4, "image/jpx"},
8072 {".png", 4, "image/png"},
8073 {".svg", 4, "image/svg+xml"},
8074 {".tif", 4, "image/tiff"},
8075 {".tiff", 5, "image/tiff"},
8076
8077 /* model */
8078 {".wrl", 4, "model/vrml"},
8079
8080 /* text */
8081 {".css", 4, "text/css"},
8082 {".csv", 4, "text/csv"},
8083 {".htm", 4, "text/html"},
8084 {".html", 5, "text/html"},
8085 {".sgm", 4, "text/sgml"},
8086 {".shtm", 5, "text/html"},
8087 {".shtml", 6, "text/html"},
8088 {".txt", 4, "text/plain"},
8089 {".xml", 4, "text/xml"},
8090
8091 /* video */
8092 {".mov", 4, "video/quicktime"},
8093 {".mp4", 4, "video/mp4"},
8094 {".mpeg", 5, "video/mpeg"},
8095 {".mpg", 4, "video/mpeg"},
8096 {".ogv", 4, "video/ogg"},
8097 {".qt", 3, "video/quicktime"},
8098
8099 /* not registered types
8100 * (http://reference.sitepoint.com/html/mime-types-full,
8101 * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
8102 {".arj", 4, "application/x-arj-compressed"},
8103 {".gz", 3, "application/x-gunzip"},
8104 {".rar", 4, "application/x-arj-compressed"},
8105 {".swf", 4, "application/x-shockwave-flash"},
8106 {".tar", 4, "application/x-tar"},
8107 {".tgz", 4, "application/x-tar-gz"},
8108 {".torrent", 8, "application/x-bittorrent"},
8109 {".ppt", 4, "application/x-mspowerpoint"},
8110 {".xls", 4, "application/x-msexcel"},
8111 {".zip", 4, "application/x-zip-compressed"},
8112 {".aac",
8113 4,
8114 "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
8115 {".flac", 5, "audio/flac"},
8116 {".aif", 4, "audio/x-aif"},
8117 {".m3u", 4, "audio/x-mpegurl"},
8118 {".mid", 4, "audio/x-midi"},
8119 {".ra", 3, "audio/x-pn-realaudio"},
8120 {".ram", 4, "audio/x-pn-realaudio"},
8121 {".wav", 4, "audio/x-wav"},
8122 {".bmp", 4, "image/bmp"},
8123 {".ico", 4, "image/x-icon"},
8124 {".pct", 4, "image/x-pct"},
8125 {".pict", 5, "image/pict"},
8126 {".rgb", 4, "image/x-rgb"},
8127 {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
8128 {".asf", 4, "video/x-ms-asf"},
8129 {".avi", 4, "video/x-msvideo"},
8130 {".m4v", 4, "video/x-m4v"},
8131 {NULL, 0, NULL}};
8132
8133
8134const char *
8136{
8137 const char *ext;
8138 size_t i, path_len;
8139
8140 path_len = strlen(path);
8141
8142 for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
8143 ext = path + (path_len - builtin_mime_types[i].ext_len);
8144 if ((path_len > builtin_mime_types[i].ext_len)
8145 && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
8146 return builtin_mime_types[i].mime_type;
8147 }
8148 }
8149
8150 return "text/plain";
8151}
8152
8153
8154/* Look at the "path" extension and figure what mime type it has.
8155 * Store mime type in the vector. */
8156static void
8157get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
8158{
8159 struct vec ext_vec, mime_vec;
8160 const char *list, *ext;
8161 size_t path_len;
8162
8163 path_len = strlen(path);
8164
8165 if ((conn == NULL) || (vec == NULL)) {
8166 if (vec != NULL) {
8167 memset(vec, '\0', sizeof(struct vec));
8168 }
8169 return;
8170 }
8171
8172 /* Scan user-defined mime types first, in case user wants to
8173 * override default mime types. */
8174 list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
8175 while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
8176 /* ext now points to the path suffix */
8177 ext = path + path_len - ext_vec.len;
8178 if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
8179 *vec = mime_vec;
8180 return;
8181 }
8182 }
8183
8185 vec->len = strlen(vec->ptr);
8186}
8187
8188
8189/* Stringify binary data. Output buffer must be twice as big as input,
8190 * because each byte takes 2 bytes in string representation */
8191static void
8192bin2str(char *to, const unsigned char *p, size_t len)
8193{
8194 static const char *hex = "0123456789abcdef";
8195
8196 for (; len--; p++) {
8197 *to++ = hex[p[0] >> 4];
8198 *to++ = hex[p[0] & 0x0f];
8199 }
8200 *to = '\0';
8201}
8202
8203
8204/* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
8205 */
8206char *
8207mg_md5(char buf[33], ...)
8208{
8209 md5_byte_t hash[16];
8210 const char *p;
8211 va_list ap;
8212 md5_state_t ctx;
8213
8214 md5_init(&ctx);
8215
8216 va_start(ap, buf);
8217 while ((p = va_arg(ap, const char *)) != NULL) {
8218 md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
8219 }
8220 va_end(ap);
8221
8222 md5_finish(&ctx, hash);
8223 bin2str(buf, hash, sizeof(hash));
8224 return buf;
8225}
8226
8227
8228/* Check the user's password, return 1 if OK */
8229static int
8230check_password(const char *method,
8231 const char *ha1,
8232 const char *uri,
8233 const char *nonce,
8234 const char *nc,
8235 const char *cnonce,
8236 const char *qop,
8237 const char *response)
8238{
8239 char ha2[32 + 1], expected_response[32 + 1];
8240
8241 /* Some of the parameters may be NULL */
8242 if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
8243 || (qop == NULL) || (response == NULL)) {
8244 return 0;
8245 }
8246
8247 /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
8248 if (strlen(response) != 32) {
8249 return 0;
8250 }
8251
8252 mg_md5(ha2, method, ":", uri, NULL);
8253 mg_md5(expected_response,
8254 ha1,
8255 ":",
8256 nonce,
8257 ":",
8258 nc,
8259 ":",
8260 cnonce,
8261 ":",
8262 qop,
8263 ":",
8264 ha2,
8265 NULL);
8266
8267 return mg_strcasecmp(response, expected_response) == 0;
8268}
8269
8270
8271#if !defined(NO_FILESYSTEMS)
8272/* Use the global passwords file, if specified by auth_gpass option,
8273 * or search for .htpasswd in the requested directory. */
8274static void
8276 const char *path,
8277 struct mg_file *filep)
8278{
8279 if ((conn != NULL) && (conn->dom_ctx != NULL)) {
8280 char name[UTF8_PATH_MAX];
8281 const char *p, *e,
8282 *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
8283 int truncated;
8284
8285 if (gpass != NULL) {
8286 /* Use global passwords file */
8287 if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
8288#if defined(DEBUG)
8289 /* Use mg_cry_internal here, since gpass has been
8290 * configured. */
8291 mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
8292#endif
8293 }
8294 /* Important: using local struct mg_file to test path for
8295 * is_directory flag. If filep is used, mg_stat() makes it
8296 * appear as if auth file was opened.
8297 * TODO(mid): Check if this is still required after rewriting
8298 * mg_stat */
8299 } else if (mg_stat(conn, path, &filep->stat)
8300 && filep->stat.is_directory) {
8301 mg_snprintf(conn,
8302 &truncated,
8303 name,
8304 sizeof(name),
8305 "%s/%s",
8306 path,
8308
8309 if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8310#if defined(DEBUG)
8311 /* Don't use mg_cry_internal here, but only a trace, since
8312 * this is a typical case. It will occur for every directory
8313 * without a password file. */
8314 DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8315#endif
8316 }
8317 } else {
8318 /* Try to find .htpasswd in requested directory. */
8319 for (p = path, e = p + strlen(p) - 1; e > p; e--) {
8320 if (e[0] == '/') {
8321 break;
8322 }
8323 }
8324 mg_snprintf(conn,
8325 &truncated,
8326 name,
8327 sizeof(name),
8328 "%.*s/%s",
8329 (int)(e - p),
8330 p,
8332
8333 if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8334#if defined(DEBUG)
8335 /* Don't use mg_cry_internal here, but only a trace, since
8336 * this is a typical case. It will occur for every directory
8337 * without a password file. */
8338 DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8339#endif
8340 }
8341 }
8342 }
8343}
8344#endif /* NO_FILESYSTEMS */
8345
8346
8347/* Parsed Authorization header */
8348struct ah {
8349 char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
8350};
8351
8352
8353/* Return 1 on success. Always initializes the ah structure. */
8354static int
8356 char *buf,
8357 size_t buf_size,
8358 struct ah *ah)
8359{
8360 char *name, *value, *s;
8361 const char *auth_header;
8362 uint64_t nonce;
8363
8364 if (!ah || !conn) {
8365 return 0;
8366 }
8367
8368 (void)memset(ah, 0, sizeof(*ah));
8369 if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
8370 || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
8371 return 0;
8372 }
8373
8374 /* Make modifiable copy of the auth header */
8375 (void)mg_strlcpy(buf, auth_header + 7, buf_size);
8376 s = buf;
8377
8378 /* Parse authorization header */
8379 for (;;) {
8380 /* Gobble initial spaces */
8381 while (isspace((unsigned char)*s)) {
8382 s++;
8383 }
8384 name = skip_quoted(&s, "=", " ", 0);
8385 /* Value is either quote-delimited, or ends at first comma or space.
8386 */
8387 if (s[0] == '\"') {
8388 s++;
8389 value = skip_quoted(&s, "\"", " ", '\\');
8390 if (s[0] == ',') {
8391 s++;
8392 }
8393 } else {
8394 value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
8395 * uses spaces */
8396 }
8397 if (*name == '\0') {
8398 break;
8399 }
8400
8401 if (!strcmp(name, "username")) {
8402 ah->user = value;
8403 } else if (!strcmp(name, "cnonce")) {
8404 ah->cnonce = value;
8405 } else if (!strcmp(name, "response")) {
8406 ah->response = value;
8407 } else if (!strcmp(name, "uri")) {
8408 ah->uri = value;
8409 } else if (!strcmp(name, "qop")) {
8410 ah->qop = value;
8411 } else if (!strcmp(name, "nc")) {
8412 ah->nc = value;
8413 } else if (!strcmp(name, "nonce")) {
8414 ah->nonce = value;
8415 }
8416 }
8417
8418#if !defined(NO_NONCE_CHECK)
8419 /* Read the nonce from the response. */
8420 if (ah->nonce == NULL) {
8421 return 0;
8422 }
8423 s = NULL;
8424 nonce = strtoull(ah->nonce, &s, 10);
8425 if ((s == NULL) || (*s != 0)) {
8426 return 0;
8427 }
8428
8429 /* Convert the nonce from the client to a number. */
8430 nonce ^= conn->dom_ctx->auth_nonce_mask;
8431
8432 /* The converted number corresponds to the time the nounce has been
8433 * created. This should not be earlier than the server start. */
8434 /* Server side nonce check is valuable in all situations but one:
8435 * if the server restarts frequently, but the client should not see
8436 * that, so the server should accept nonces from previous starts. */
8437 /* However, the reasonable default is to not accept a nonce from a
8438 * previous start, so if anyone changed the access rights between
8439 * two restarts, a new login is required. */
8440 if (nonce < (uint64_t)conn->phys_ctx->start_time) {
8441 /* nonce is from a previous start of the server and no longer valid
8442 * (replay attack?) */
8443 return 0;
8444 }
8445 /* Check if the nonce is too high, so it has not (yet) been used by the
8446 * server. */
8447 if (nonce >= ((uint64_t)conn->phys_ctx->start_time
8448 + conn->dom_ctx->nonce_count)) {
8449 return 0;
8450 }
8451#else
8452 (void)nonce;
8453#endif
8454
8455 /* CGI needs it as REMOTE_USER */
8456 if (ah->user != NULL) {
8458 mg_strdup_ctx(ah->user, conn->phys_ctx);
8459 } else {
8460 return 0;
8461 }
8462
8463 return 1;
8464}
8465
8466
8467static const char *
8468mg_fgets(char *buf, size_t size, struct mg_file *filep)
8469{
8470 if (!filep) {
8471 return NULL;
8472 }
8473
8474 if (filep->access.fp != NULL) {
8475 return fgets(buf, (int)size, filep->access.fp);
8476 } else {
8477 return NULL;
8478 }
8479}
8480
8481/* Define the initial recursion depth for procesesing htpasswd files that
8482 * include other htpasswd
8483 * (or even the same) files. It is not difficult to provide a file or files
8484 * s.t. they force civetweb
8485 * to infinitely recurse and then crash.
8486 */
8487#define INITIAL_DEPTH 9
8488#if INITIAL_DEPTH <= 0
8489#error Bad INITIAL_DEPTH for recursion, set to at least 1
8490#endif
8491
8492#if !defined(NO_FILESYSTEMS)
8495 struct ah ah;
8496 const char *domain;
8497 char buf[256 + 256 + 40];
8498 const char *f_user;
8499 const char *f_domain;
8500 const char *f_ha1;
8501};
8502
8503
8504static int
8506 struct read_auth_file_struct *workdata,
8507 int depth)
8508{
8509 int is_authorized = 0;
8510 struct mg_file fp;
8511 size_t l;
8512
8513 if (!filep || !workdata || (0 == depth)) {
8514 return 0;
8515 }
8516
8517 /* Loop over passwords file */
8518 while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
8519 l = strlen(workdata->buf);
8520 while (l > 0) {
8521 if (isspace((unsigned char)workdata->buf[l - 1])
8522 || iscntrl((unsigned char)workdata->buf[l - 1])) {
8523 l--;
8524 workdata->buf[l] = 0;
8525 } else
8526 break;
8527 }
8528 if (l < 1) {
8529 continue;
8530 }
8531
8532 workdata->f_user = workdata->buf;
8533
8534 if (workdata->f_user[0] == ':') {
8535 /* user names may not contain a ':' and may not be empty,
8536 * so lines starting with ':' may be used for a special purpose
8537 */
8538 if (workdata->f_user[1] == '#') {
8539 /* :# is a comment */
8540 continue;
8541 } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
8542 if (mg_fopen(workdata->conn,
8543 workdata->f_user + 9,
8545 &fp)) {
8546 is_authorized = read_auth_file(&fp, workdata, depth - 1);
8547 (void)mg_fclose(
8548 &fp.access); /* ignore error on read only file */
8549
8550 /* No need to continue processing files once we have a
8551 * match, since nothing will reset it back
8552 * to 0.
8553 */
8554 if (is_authorized) {
8555 return is_authorized;
8556 }
8557 } else {
8558 mg_cry_internal(workdata->conn,
8559 "%s: cannot open authorization file: %s",
8560 __func__,
8561 workdata->buf);
8562 }
8563 continue;
8564 }
8565 /* everything is invalid for the moment (might change in the
8566 * future) */
8567 mg_cry_internal(workdata->conn,
8568 "%s: syntax error in authorization file: %s",
8569 __func__,
8570 workdata->buf);
8571 continue;
8572 }
8573
8574 workdata->f_domain = strchr(workdata->f_user, ':');
8575 if (workdata->f_domain == NULL) {
8576 mg_cry_internal(workdata->conn,
8577 "%s: syntax error in authorization file: %s",
8578 __func__,
8579 workdata->buf);
8580 continue;
8581 }
8582 *(char *)(workdata->f_domain) = 0;
8583 (workdata->f_domain)++;
8584
8585 workdata->f_ha1 = strchr(workdata->f_domain, ':');
8586 if (workdata->f_ha1 == NULL) {
8587 mg_cry_internal(workdata->conn,
8588 "%s: syntax error in authorization file: %s",
8589 __func__,
8590 workdata->buf);
8591 continue;
8592 }
8593 *(char *)(workdata->f_ha1) = 0;
8594 (workdata->f_ha1)++;
8595
8596 if (!strcmp(workdata->ah.user, workdata->f_user)
8597 && !strcmp(workdata->domain, workdata->f_domain)) {
8599 workdata->f_ha1,
8600 workdata->ah.uri,
8601 workdata->ah.nonce,
8602 workdata->ah.nc,
8603 workdata->ah.cnonce,
8604 workdata->ah.qop,
8605 workdata->ah.response);
8606 }
8607 }
8608
8609 return is_authorized;
8610}
8611
8612
8613/* Authorize against the opened passwords file. Return 1 if authorized. */
8614static int
8615authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
8616{
8617 struct read_auth_file_struct workdata;
8618 char buf[MG_BUF_LEN];
8619
8620 if (!conn || !conn->dom_ctx) {
8621 return 0;
8622 }
8623
8624 memset(&workdata, 0, sizeof(workdata));
8625 workdata.conn = conn;
8626
8627 if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
8628 return 0;
8629 }
8630
8631 if (realm) {
8632 workdata.domain = realm;
8633 } else {
8635 }
8636
8637 return read_auth_file(filep, &workdata, INITIAL_DEPTH);
8638}
8639
8640
8641/* Public function to check http digest authentication header */
8642int
8644 const char *realm,
8645 const char *filename)
8646{
8647 struct mg_file file = STRUCT_FILE_INITIALIZER;
8648 int auth;
8649
8650 if (!conn || !filename) {
8651 return -1;
8652 }
8653 if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
8654 return -2;
8655 }
8656
8657 auth = authorize(conn, &file, realm);
8658
8659 mg_fclose(&file.access);
8660
8661 return auth;
8662}
8663#endif /* NO_FILESYSTEMS */
8664
8665
8666/* Return 1 if request is authorised, 0 otherwise. */
8667static int
8668check_authorization(struct mg_connection *conn, const char *path)
8669{
8670#if !defined(NO_FILESYSTEMS)
8671 char fname[UTF8_PATH_MAX];
8672 struct vec uri_vec, filename_vec;
8673 const char *list;
8674 struct mg_file file = STRUCT_FILE_INITIALIZER;
8675 int authorized = 1, truncated;
8676
8677 if (!conn || !conn->dom_ctx) {
8678 return 0;
8679 }
8680
8681 list = conn->dom_ctx->config[PROTECT_URI];
8682 while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
8683 if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
8684 mg_snprintf(conn,
8685 &truncated,
8686 fname,
8687 sizeof(fname),
8688 "%.*s",
8689 (int)filename_vec.len,
8690 filename_vec.ptr);
8691
8692 if (truncated
8693 || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
8694 mg_cry_internal(conn,
8695 "%s: cannot open %s: %s",
8696 __func__,
8697 fname,
8698 strerror(errno));
8699 }
8700 break;
8701 }
8702 }
8703
8704 if (!is_file_opened(&file.access)) {
8705 open_auth_file(conn, path, &file);
8706 }
8707
8708 if (is_file_opened(&file.access)) {
8709 authorized = authorize(conn, &file, NULL);
8710 (void)mg_fclose(&file.access); /* ignore error on read only file */
8711 }
8712
8713 return authorized;
8714#else
8715 (void)conn;
8716 (void)path;
8717 return 1;
8718#endif /* NO_FILESYSTEMS */
8719}
8720
8721
8722/* Internal function. Assumes conn is valid */
8723static void
8724send_authorization_request(struct mg_connection *conn, const char *realm)
8725{
8726 uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
8727 int trunc = 0;
8728 char buf[128];
8729
8730 if (!realm) {
8731 realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
8732 }
8733
8735 nonce += conn->dom_ctx->nonce_count;
8736 ++conn->dom_ctx->nonce_count;
8738
8739 nonce ^= conn->dom_ctx->auth_nonce_mask;
8740 conn->must_close = 1;
8741
8742 /* Create 401 response */
8743 mg_response_header_start(conn, 401);
8746 mg_response_header_add(conn, "Content-Length", "0", -1);
8747
8748 /* Content for "WWW-Authenticate" header */
8749 mg_snprintf(conn,
8750 &trunc,
8751 buf,
8752 sizeof(buf),
8753 "Digest qop=\"auth\", realm=\"%s\", "
8754 "nonce=\"%" UINT64_FMT "\"",
8755 realm,
8756 nonce);
8757
8758 if (!trunc) {
8759 /* !trunc should always be true */
8760 mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
8761 }
8762
8763 /* Send all headers */
8765}
8766
8767
8768/* Interface function. Parameters are provided by the user, so do
8769 * at least some basic checks.
8770 */
8771int
8773 const char *realm)
8774{
8775 if (conn && conn->dom_ctx) {
8776 send_authorization_request(conn, realm);
8777 return 0;
8778 }
8779 return -1;
8780}
8781
8782
8783#if !defined(NO_FILES)
8784static int
8786{
8787 if (conn) {
8788 struct mg_file file = STRUCT_FILE_INITIALIZER;
8789 const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
8790 int ret = 0;
8791
8792 if (passfile != NULL
8793 && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
8794 ret = authorize(conn, &file, NULL);
8795 (void)mg_fclose(&file.access); /* ignore error on read only file */
8796 }
8797
8798 return ret;
8799 }
8800 return 0;
8801}
8802#endif
8803
8804
8805static int
8806modify_passwords_file(const char *fname,
8807 const char *domain,
8808 const char *user,
8809 const char *pass,
8810 const char *ha1)
8811{
8812 int found, i;
8813 char line[512], u[512] = "", d[512] = "", ha1buf[33],
8814 tmp[UTF8_PATH_MAX + 8];
8815 FILE *fp, *fp2;
8816
8817 found = 0;
8818 fp = fp2 = NULL;
8819
8820 /* Regard empty password as no password - remove user record. */
8821 if ((pass != NULL) && (pass[0] == '\0')) {
8822 pass = NULL;
8823 }
8824
8825 /* Other arguments must not be empty */
8826 if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
8827 return 0;
8828 }
8829
8830 /* Using the given file format, user name and domain must not contain
8831 * ':'
8832 */
8833 if (strchr(user, ':') != NULL) {
8834 return 0;
8835 }
8836 if (strchr(domain, ':') != NULL) {
8837 return 0;
8838 }
8839
8840 /* Do not allow control characters like newline in user name and domain.
8841 * Do not allow excessively long names either. */
8842 for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
8843 if (iscntrl((unsigned char)user[i])) {
8844 return 0;
8845 }
8846 }
8847 if (user[i]) {
8848 return 0;
8849 }
8850 for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
8851 if (iscntrl((unsigned char)domain[i])) {
8852 return 0;
8853 }
8854 }
8855 if (domain[i]) {
8856 return 0;
8857 }
8858
8859 /* The maximum length of the path to the password file is limited */
8860 if ((strlen(fname) + 4) >= UTF8_PATH_MAX) {
8861 return 0;
8862 }
8863
8864 /* Create a temporary file name. Length has been checked before. */
8865 strcpy(tmp, fname);
8866 strcat(tmp, ".tmp");
8867
8868 /* Create the file if does not exist */
8869 /* Use of fopen here is OK, since fname is only ASCII */
8870 if ((fp = fopen(fname, "a+")) != NULL) {
8871 (void)fclose(fp);
8872 }
8873
8874 /* Open the given file and temporary file */
8875 if ((fp = fopen(fname, "r")) == NULL) {
8876 return 0;
8877 } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
8878 fclose(fp);
8879 return 0;
8880 }
8881
8882 /* Copy the stuff to temporary file */
8883 while (fgets(line, sizeof(line), fp) != NULL) {
8884 if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
8885 continue;
8886 }
8887 u[255] = 0;
8888 d[255] = 0;
8889
8890 if (!strcmp(u, user) && !strcmp(d, domain)) {
8891 found++;
8892 if (pass != NULL) {
8893 mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
8894 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1buf);
8895 } else if (ha1 != NULL) {
8896 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8897 }
8898 } else {
8899 fprintf(fp2, "%s", line);
8900 }
8901 }
8902
8903 /* If new user, just add it */
8904 if (!found) {
8905 if (pass != NULL) {
8906 mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
8907 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1buf);
8908 } else if (ha1 != NULL) {
8909 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8910 }
8911 }
8912
8913 /* Close files */
8914 fclose(fp);
8915 fclose(fp2);
8916
8917 /* Put the temp file in place of real file */
8918 IGNORE_UNUSED_RESULT(remove(fname));
8919 IGNORE_UNUSED_RESULT(rename(tmp, fname));
8920
8921 return 1;
8922}
8923
8924
8925int
8927 const char *domain,
8928 const char *user,
8929 const char *pass)
8930{
8931 return modify_passwords_file(fname, domain, user, pass, NULL);
8932}
8933
8934
8935int
8937 const char *domain,
8938 const char *user,
8939 const char *ha1)
8940{
8941 return modify_passwords_file(fname, domain, user, NULL, ha1);
8942}
8943
8944
8945static int
8946is_valid_port(unsigned long port)
8947{
8948 return (port <= 0xffff);
8949}
8950
8951
8952static int
8953mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
8954{
8955 struct addrinfo hints, *res, *ressave;
8956 int func_ret = 0;
8957 int gai_ret;
8958
8959 memset(&hints, 0, sizeof(struct addrinfo));
8960 hints.ai_family = af;
8961 if (!resolve_src) {
8962 hints.ai_flags = AI_NUMERICHOST;
8963 }
8964
8965 gai_ret = getaddrinfo(src, NULL, &hints, &res);
8966 if (gai_ret != 0) {
8967 /* gai_strerror could be used to convert gai_ret to a string */
8968 /* POSIX return values: see
8969 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
8970 */
8971 /* Windows return values: see
8972 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
8973 */
8974 return 0;
8975 }
8976
8977 ressave = res;
8978
8979 while (res) {
8980 if ((dstlen >= (size_t)res->ai_addrlen)
8981 && (res->ai_addr->sa_family == af)) {
8982 memcpy(dst, res->ai_addr, res->ai_addrlen);
8983 func_ret = 1;
8984 }
8985 res = res->ai_next;
8986 }
8987
8988 freeaddrinfo(ressave);
8989 return func_ret;
8990}
8991
8992
8993static int
8995 struct mg_context *ctx /* may be NULL */,
8996 const char *host,
8997 int port, /* 1..65535, or -99 for domain sockets (may be changed) */
8998 int use_ssl, /* 0 or 1 */
8999 char *ebuf,
9000 size_t ebuf_len,
9001 SOCKET *sock /* output: socket, must not be NULL */,
9002 union usa *sa /* output: socket address, must not be NULL */
9003)
9004{
9005 int ip_ver = 0;
9006 int conn_ret = -1;
9007 int sockerr = 0;
9008 *sock = INVALID_SOCKET;
9009 memset(sa, 0, sizeof(*sa));
9010
9011 if (ebuf_len > 0) {
9012 *ebuf = 0;
9013 }
9014
9015 if (host == NULL) {
9016 mg_snprintf(NULL,
9017 NULL, /* No truncation check for ebuf */
9018 ebuf,
9019 ebuf_len,
9020 "%s",
9021 "NULL host");
9022 return 0;
9023 }
9024
9025#if defined(USE_X_DOM_SOCKET)
9026 if (port == -99) {
9027 /* Unix domain socket */
9028 size_t hostlen = strlen(host);
9029 if (hostlen >= sizeof(sa->sun.sun_path)) {
9030 mg_snprintf(NULL,
9031 NULL, /* No truncation check for ebuf */
9032 ebuf,
9033 ebuf_len,
9034 "%s",
9035 "host length exceeds limit");
9036 return 0;
9037 }
9038 } else
9039#endif
9040 if ((port <= 0) || !is_valid_port((unsigned)port)) {
9041 mg_snprintf(NULL,
9042 NULL, /* No truncation check for ebuf */
9043 ebuf,
9044 ebuf_len,
9045 "%s",
9046 "invalid port");
9047 return 0;
9048 }
9049
9050#if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
9051#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
9052 if (use_ssl && (TLS_client_method == NULL)) {
9053 mg_snprintf(NULL,
9054 NULL, /* No truncation check for ebuf */
9055 ebuf,
9056 ebuf_len,
9057 "%s",
9058 "SSL is not initialized");
9059 return 0;
9060 }
9061#else
9062 if (use_ssl && (SSLv23_client_method == NULL)) {
9063 mg_snprintf(NULL,
9064 NULL, /* No truncation check for ebuf */
9065 ebuf,
9066 ebuf_len,
9067 "%s",
9068 "SSL is not initialized");
9069 return 0;
9070 }
9071#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
9072#else
9073 (void)use_ssl;
9074#endif /* NO SSL */
9075
9076
9077#if defined(USE_X_DOM_SOCKET)
9078 if (port == -99) {
9079 size_t hostlen = strlen(host);
9080 /* check (hostlen < sizeof(sun.sun_path)) already passed above */
9081 ip_ver = -99;
9082 sa->sun.sun_family = AF_UNIX;
9083 memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
9084 memcpy(sa->sun.sun_path, host, hostlen);
9085 } else
9086#endif
9087 if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
9088 sa->sin.sin_port = htons((uint16_t)port);
9089 ip_ver = 4;
9090#if defined(USE_IPV6)
9091 } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
9092 sa->sin6.sin6_port = htons((uint16_t)port);
9093 ip_ver = 6;
9094 } else if (host[0] == '[') {
9095 /* While getaddrinfo on Windows will work with [::1],
9096 * getaddrinfo on Linux only works with ::1 (without []). */
9097 size_t l = strlen(host + 1);
9098 char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
9099 if (h) {
9100 h[l - 1] = 0;
9101 if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
9102 sa->sin6.sin6_port = htons((uint16_t)port);
9103 ip_ver = 6;
9104 }
9105 mg_free(h);
9106 }
9107#endif
9108 }
9109
9110 if (ip_ver == 0) {
9111 mg_snprintf(NULL,
9112 NULL, /* No truncation check for ebuf */
9113 ebuf,
9114 ebuf_len,
9115 "%s",
9116 "host not found");
9117 return 0;
9118 }
9119
9120 if (ip_ver == 4) {
9121 *sock = socket(PF_INET, SOCK_STREAM, 0);
9122 }
9123#if defined(USE_IPV6)
9124 else if (ip_ver == 6) {
9125 *sock = socket(PF_INET6, SOCK_STREAM, 0);
9126 }
9127#endif
9128#if defined(USE_X_DOM_SOCKET)
9129 else if (ip_ver == -99) {
9130 *sock = socket(AF_UNIX, SOCK_STREAM, 0);
9131 }
9132#endif
9133
9134 if (*sock == INVALID_SOCKET) {
9135 mg_snprintf(NULL,
9136 NULL, /* No truncation check for ebuf */
9137 ebuf,
9138 ebuf_len,
9139 "socket(): %s",
9140 strerror(ERRNO));
9141 return 0;
9142 }
9143
9144 if (0 != set_non_blocking_mode(*sock)) {
9145 mg_snprintf(NULL,
9146 NULL, /* No truncation check for ebuf */
9147 ebuf,
9148 ebuf_len,
9149 "Cannot set socket to non-blocking: %s",
9150 strerror(ERRNO));
9151 closesocket(*sock);
9152 *sock = INVALID_SOCKET;
9153 return 0;
9154 }
9155
9156 set_close_on_exec(*sock, NULL, ctx);
9157
9158 if (ip_ver == 4) {
9159 /* connected with IPv4 */
9160 conn_ret = connect(*sock,
9161 (struct sockaddr *)((void *)&sa->sin),
9162 sizeof(sa->sin));
9163 }
9164#if defined(USE_IPV6)
9165 else if (ip_ver == 6) {
9166 /* connected with IPv6 */
9167 conn_ret = connect(*sock,
9168 (struct sockaddr *)((void *)&sa->sin6),
9169 sizeof(sa->sin6));
9170 }
9171#endif
9172#if defined(USE_X_DOM_SOCKET)
9173 else if (ip_ver == -99) {
9174 /* connected to domain socket */
9175 conn_ret = connect(*sock,
9176 (struct sockaddr *)((void *)&sa->sun),
9177 sizeof(sa->sun));
9178 }
9179#endif
9180
9181 if (conn_ret != 0) {
9182 sockerr = ERRNO;
9183 }
9184
9185#if defined(_WIN32)
9186 if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
9187#else
9188 if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
9189#endif
9190 /* Data for getsockopt */
9191 void *psockerr = &sockerr;
9192 int ret;
9193
9194#if defined(_WIN32)
9195 int len = (int)sizeof(sockerr);
9196#else
9197 socklen_t len = (socklen_t)sizeof(sockerr);
9198#endif
9199
9200 /* Data for poll */
9201 struct mg_pollfd pfd[1];
9202 int pollres;
9203 int ms_wait = 10000; /* 10 second timeout */
9204 stop_flag_t nonstop;
9205 STOP_FLAG_ASSIGN(&nonstop, 0);
9206
9207 /* For a non-blocking socket, the connect sequence is:
9208 * 1) call connect (will not block)
9209 * 2) wait until the socket is ready for writing (select or poll)
9210 * 3) check connection state with getsockopt
9211 */
9212 pfd[0].fd = *sock;
9213 pfd[0].events = POLLOUT;
9214 pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
9215
9216 if (pollres != 1) {
9217 /* Not connected */
9218 mg_snprintf(NULL,
9219 NULL, /* No truncation check for ebuf */
9220 ebuf,
9221 ebuf_len,
9222 "connect(%s:%d): timeout",
9223 host,
9224 port);
9225 closesocket(*sock);
9226 *sock = INVALID_SOCKET;
9227 return 0;
9228 }
9229
9230#if defined(_WIN32)
9231 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
9232#else
9233 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
9234#endif
9235
9236 if ((ret == 0) && (sockerr == 0)) {
9237 conn_ret = 0;
9238 }
9239 }
9240
9241 if (conn_ret != 0) {
9242 /* Not connected */
9243 mg_snprintf(NULL,
9244 NULL, /* No truncation check for ebuf */
9245 ebuf,
9246 ebuf_len,
9247 "connect(%s:%d): error %s",
9248 host,
9249 port,
9250 strerror(sockerr));
9251 closesocket(*sock);
9252 *sock = INVALID_SOCKET;
9253 return 0;
9254 }
9255
9256 return 1;
9257}
9258
9259
9260int
9261mg_url_encode(const char *src, char *dst, size_t dst_len)
9262{
9263 static const char *dont_escape = "._-$,;~()";
9264 static const char *hex = "0123456789abcdef";
9265 char *pos = dst;
9266 const char *end = dst + dst_len - 1;
9267
9268 for (; ((*src != '\0') && (pos < end)); src++, pos++) {
9269 if (isalnum((unsigned char)*src)
9270 || (strchr(dont_escape, *src) != NULL)) {
9271 *pos = *src;
9272 } else if (pos + 2 < end) {
9273 pos[0] = '%';
9274 pos[1] = hex[(unsigned char)*src >> 4];
9275 pos[2] = hex[(unsigned char)*src & 0xf];
9276 pos += 2;
9277 } else {
9278 break;
9279 }
9280 }
9281
9282 *pos = '\0';
9283 return (*src == '\0') ? (int)(pos - dst) : -1;
9284}
9285
9286/* Return 0 on success, non-zero if an error occurs. */
9287
9288static int
9290{
9291 size_t namesize, escsize, i;
9292 char *href, *esc, *p;
9293 char size[64], mod[64];
9294#if defined(REENTRANT_TIME)
9295 struct tm _tm;
9296 struct tm *tm = &_tm;
9297#else
9298 struct tm *tm;
9299#endif
9300
9301 /* Estimate worst case size for encoding and escaping */
9302 namesize = strlen(de->file_name) + 1;
9303 escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
9304 href = (char *)mg_malloc(namesize * 3 + escsize);
9305 if (href == NULL) {
9306 return -1;
9307 }
9308 mg_url_encode(de->file_name, href, namesize * 3);
9309 esc = NULL;
9310 if (escsize > 0) {
9311 /* HTML escaping needed */
9312 esc = href + namesize * 3;
9313 for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
9314 mg_strlcpy(p, de->file_name + i, 2);
9315 if (*p == '&') {
9316 strcpy(p, "&amp;");
9317 } else if (*p == '<') {
9318 strcpy(p, "&lt;");
9319 } else if (*p == '>') {
9320 strcpy(p, "&gt;");
9321 }
9322 }
9323 }
9324
9325 if (de->file.is_directory) {
9327 NULL, /* Buffer is big enough */
9328 size,
9329 sizeof(size),
9330 "%s",
9331 "[DIRECTORY]");
9332 } else {
9333 /* We use (signed) cast below because MSVC 6 compiler cannot
9334 * convert unsigned __int64 to double. Sigh. */
9335 if (de->file.size < 1024) {
9337 NULL, /* Buffer is big enough */
9338 size,
9339 sizeof(size),
9340 "%d",
9341 (int)de->file.size);
9342 } else if (de->file.size < 0x100000) {
9344 NULL, /* Buffer is big enough */
9345 size,
9346 sizeof(size),
9347 "%.1fk",
9348 (double)de->file.size / 1024.0);
9349 } else if (de->file.size < 0x40000000) {
9351 NULL, /* Buffer is big enough */
9352 size,
9353 sizeof(size),
9354 "%.1fM",
9355 (double)de->file.size / 1048576);
9356 } else {
9358 NULL, /* Buffer is big enough */
9359 size,
9360 sizeof(size),
9361 "%.1fG",
9362 (double)de->file.size / 1073741824);
9363 }
9364 }
9365
9366 /* Note: mg_snprintf will not cause a buffer overflow above.
9367 * So, string truncation checks are not required here. */
9368
9369#if defined(REENTRANT_TIME)
9370 localtime_r(&de->file.last_modified, tm);
9371#else
9372 tm = localtime(&de->file.last_modified);
9373#endif
9374 if (tm != NULL) {
9375 strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
9376 } else {
9377 mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
9378 mod[sizeof(mod) - 1] = '\0';
9379 }
9380 mg_printf(de->conn,
9381 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
9382 "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
9383 href,
9384 de->file.is_directory ? "/" : "",
9385 esc ? esc : de->file_name,
9386 de->file.is_directory ? "/" : "",
9387 mod,
9388 size);
9389 mg_free(href);
9390 return 0;
9391}
9392
9393
9394/* This function is called from send_directory() and used for
9395 * sorting directory entries by size, or name, or modification time.
9396 * On windows, __cdecl specification is needed in case if project is built
9397 * with __stdcall convention. qsort always requires __cdels callback. */
9398static int WINCDECL
9399compare_dir_entries(const void *p1, const void *p2)
9400{
9401 if (p1 && p2) {
9402 const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
9403 const char *query_string = a->conn->request_info.query_string;
9404 int cmp_result = 0;
9405
9406 if ((query_string == NULL) || (query_string[0] == '\0')) {
9407 query_string = "n";
9408 }
9409
9410 if (a->file.is_directory && !b->file.is_directory) {
9411 return -1; /* Always put directories on top */
9412 } else if (!a->file.is_directory && b->file.is_directory) {
9413 return 1; /* Always put directories on top */
9414 } else if (*query_string == 'n') {
9415 cmp_result = strcmp(a->file_name, b->file_name);
9416 } else if (*query_string == 's') {
9417 cmp_result = (a->file.size == b->file.size)
9418 ? 0
9419 : ((a->file.size > b->file.size) ? 1 : -1);
9420 } else if (*query_string == 'd') {
9421 cmp_result =
9422 (a->file.last_modified == b->file.last_modified)
9423 ? 0
9424 : ((a->file.last_modified > b->file.last_modified) ? 1
9425 : -1);
9426 }
9427
9428 return (query_string[1] == 'd') ? -cmp_result : cmp_result;
9429 }
9430 return 0;
9431}
9432
9433
9434static int
9435must_hide_file(struct mg_connection *conn, const char *path)
9436{
9437 if (conn && conn->dom_ctx) {
9438 const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
9439 const char *pattern = conn->dom_ctx->config[HIDE_FILES];
9440 return (match_prefix_strlen(pw_pattern, path) > 0)
9441 || (match_prefix_strlen(pattern, path) > 0);
9442 }
9443 return 0;
9444}
9445
9446
9447#if !defined(NO_FILESYSTEMS)
9448static int
9450 const char *dir,
9451 void *data,
9452 int (*cb)(struct de *, void *))
9453{
9454 char path[UTF8_PATH_MAX];
9455 struct dirent *dp;
9456 DIR *dirp;
9457 struct de de;
9458 int truncated;
9459
9460 if ((dirp = mg_opendir(conn, dir)) == NULL) {
9461 return 0;
9462 } else {
9463 de.conn = conn;
9464
9465 while ((dp = mg_readdir(dirp)) != NULL) {
9466 /* Do not show current dir and hidden files */
9467 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
9468 || must_hide_file(conn, dp->d_name)) {
9469 continue;
9470 }
9471
9473 conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9474
9475 /* If we don't memset stat structure to zero, mtime will have
9476 * garbage and strftime() will segfault later on in
9477 * print_dir_entry(). memset is required only if mg_stat()
9478 * fails. For more details, see
9479 * http://code.google.com/p/mongoose/issues/detail?id=79 */
9480 memset(&de.file, 0, sizeof(de.file));
9481
9482 if (truncated) {
9483 /* If the path is not complete, skip processing. */
9484 continue;
9485 }
9486
9487 if (!mg_stat(conn, path, &de.file)) {
9489 "%s: mg_stat(%s) failed: %s",
9490 __func__,
9491 path,
9492 strerror(ERRNO));
9493 }
9494 de.file_name = dp->d_name;
9495 if (cb(&de, data)) {
9496 /* stopped */
9497 break;
9498 }
9499 }
9500 (void)mg_closedir(dirp);
9501 }
9502 return 1;
9503}
9504#endif /* NO_FILESYSTEMS */
9505
9506
9507#if !defined(NO_FILES)
9508static int
9509remove_directory(struct mg_connection *conn, const char *dir)
9510{
9511 char path[UTF8_PATH_MAX];
9512 struct dirent *dp;
9513 DIR *dirp;
9514 struct de de;
9515 int truncated;
9516 int ok = 1;
9517
9518 if ((dirp = mg_opendir(conn, dir)) == NULL) {
9519 return 0;
9520 } else {
9521 de.conn = conn;
9522
9523 while ((dp = mg_readdir(dirp)) != NULL) {
9524 /* Do not show current dir (but show hidden files as they will
9525 * also be removed) */
9526 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
9527 continue;
9528 }
9529
9531 conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9532
9533 /* If we don't memset stat structure to zero, mtime will have
9534 * garbage and strftime() will segfault later on in
9535 * print_dir_entry(). memset is required only if mg_stat()
9536 * fails. For more details, see
9537 * http://code.google.com/p/mongoose/issues/detail?id=79 */
9538 memset(&de.file, 0, sizeof(de.file));
9539
9540 if (truncated) {
9541 /* Do not delete anything shorter */
9542 ok = 0;
9543 continue;
9544 }
9545
9546 if (!mg_stat(conn, path, &de.file)) {
9548 "%s: mg_stat(%s) failed: %s",
9549 __func__,
9550 path,
9551 strerror(ERRNO));
9552 ok = 0;
9553 }
9554
9555 if (de.file.is_directory) {
9556 if (remove_directory(conn, path) == 0) {
9557 ok = 0;
9558 }
9559 } else {
9560 /* This will fail file is the file is in memory */
9561 if (mg_remove(conn, path) == 0) {
9562 ok = 0;
9563 }
9564 }
9565 }
9566 (void)mg_closedir(dirp);
9567
9568 IGNORE_UNUSED_RESULT(rmdir(dir));
9569 }
9570
9571 return ok;
9572}
9573#endif
9574
9575
9577 struct de *entries;
9579 size_t arr_size;
9580};
9581
9582
9583#if !defined(NO_FILESYSTEMS)
9584static int
9586{
9587 struct dir_scan_data *dsd = (struct dir_scan_data *)data;
9588 struct de *entries = dsd->entries;
9589
9590 if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
9591 /* Here "entries" is a temporary pointer and can be replaced,
9592 * "dsd->entries" is the original pointer */
9593 entries =
9594 (struct de *)mg_realloc(entries,
9595 dsd->arr_size * 2 * sizeof(entries[0]));
9596 if (entries == NULL) {
9597 /* stop scan */
9598 return 1;
9599 }
9600 dsd->entries = entries;
9601 dsd->arr_size *= 2;
9602 }
9603 entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
9604 if (entries[dsd->num_entries].file_name == NULL) {
9605 /* stop scan */
9606 return 1;
9607 }
9608 entries[dsd->num_entries].file = de->file;
9609 entries[dsd->num_entries].conn = de->conn;
9610 dsd->num_entries++;
9611
9612 return 0;
9613}
9614
9615
9616static void
9618{
9619 size_t i;
9620 int sort_direction;
9621 struct dir_scan_data data = {NULL, 0, 128};
9622 char date[64], *esc, *p;
9623 const char *title;
9624 time_t curtime = time(NULL);
9625
9626 if (!conn) {
9627 return;
9628 }
9629
9630 if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
9631 mg_send_http_error(conn,
9632 500,
9633 "Error: Cannot open directory\nopendir(%s): %s",
9634 dir,
9635 strerror(ERRNO));
9636 return;
9637 }
9638
9639 gmt_time_string(date, sizeof(date), &curtime);
9640
9641 esc = NULL;
9642 title = conn->request_info.local_uri;
9643 if (title[strcspn(title, "&<>")]) {
9644 /* HTML escaping needed */
9645 esc = (char *)mg_malloc(strlen(title) * 5 + 1);
9646 if (esc) {
9647 for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
9648 mg_strlcpy(p, title + i, 2);
9649 if (*p == '&') {
9650 strcpy(p, "&amp;");
9651 } else if (*p == '<') {
9652 strcpy(p, "&lt;");
9653 } else if (*p == '>') {
9654 strcpy(p, "&gt;");
9655 }
9656 }
9657 } else {
9658 title = "";
9659 }
9660 }
9661
9662 sort_direction = ((conn->request_info.query_string != NULL)
9663 && (conn->request_info.query_string[0] != '\0')
9664 && (conn->request_info.query_string[1] == 'd'))
9665 ? 'a'
9666 : 'd';
9667
9668 conn->must_close = 1;
9669
9670 /* Create 200 OK response */
9671 mg_response_header_start(conn, 200);
9675 "Content-Type",
9676 "text/html; charset=utf-8",
9677 -1);
9678
9679 /* Send all headers */
9681
9682 /* Body */
9683 mg_printf(conn,
9684 "<html><head><title>Index of %s</title>"
9685 "<style>th {text-align: left;}</style></head>"
9686 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
9687 "<tr><th><a href=\"?n%c\">Name</a></th>"
9688 "<th><a href=\"?d%c\">Modified</a></th>"
9689 "<th><a href=\"?s%c\">Size</a></th></tr>"
9690 "<tr><td colspan=\"3\"><hr></td></tr>",
9691 esc ? esc : title,
9692 esc ? esc : title,
9693 sort_direction,
9694 sort_direction,
9695 sort_direction);
9696 mg_free(esc);
9697
9698 /* Print first entry - link to a parent directory */
9699 mg_printf(conn,
9700 "<tr><td><a href=\"%s\">%s</a></td>"
9701 "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
9702 "..",
9703 "Parent directory",
9704 "-",
9705 "-");
9706
9707 /* Sort and print directory entries */
9708 if (data.entries != NULL) {
9709 qsort(data.entries,
9710 data.num_entries,
9711 sizeof(data.entries[0]),
9713 for (i = 0; i < data.num_entries; i++) {
9714 print_dir_entry(&data.entries[i]);
9715 mg_free(data.entries[i].file_name);
9716 }
9717 mg_free(data.entries);
9718 }
9719
9720 mg_printf(conn, "%s", "</table></pre></body></html>");
9721 conn->status_code = 200;
9722}
9723#endif /* NO_FILESYSTEMS */
9724
9725
9726/* Send len bytes from the opened file to the client. */
9727static void
9729 struct mg_file *filep,
9730 int64_t offset,
9731 int64_t len)
9732{
9733 char buf[MG_BUF_LEN];
9734 int to_read, num_read, num_written;
9735 int64_t size;
9736
9737 if (!filep || !conn) {
9738 return;
9739 }
9740
9741 /* Sanity check the offset */
9742 size = (filep->stat.size > INT64_MAX) ? INT64_MAX
9743 : (int64_t)(filep->stat.size);
9744 offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
9745
9746 if (len > 0 && filep->access.fp != NULL) {
9747 /* file stored on disk */
9748#if defined(__linux__)
9749 /* sendfile is only available for Linux */
9750 if ((conn->ssl == 0) && (conn->throttle == 0)
9751 && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
9752 "yes"))) {
9753 off_t sf_offs = (off_t)offset;
9754 ssize_t sf_sent;
9755 int sf_file = fileno(filep->access.fp);
9756 int loop_cnt = 0;
9757
9758 do {
9759 /* 2147479552 (0x7FFFF000) is a limit found by experiment on
9760 * 64 bit Linux (2^31 minus one memory page of 4k?). */
9761 size_t sf_tosend =
9762 (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
9763 sf_sent =
9764 sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
9765 if (sf_sent > 0) {
9766 len -= sf_sent;
9767 offset += sf_sent;
9768 } else if (loop_cnt == 0) {
9769 /* This file can not be sent using sendfile.
9770 * This might be the case for pseudo-files in the
9771 * /sys/ and /proc/ file system.
9772 * Use the regular user mode copy code instead. */
9773 break;
9774 } else if (sf_sent == 0) {
9775 /* No error, but 0 bytes sent. May be EOF? */
9776 return;
9777 }
9778 loop_cnt++;
9779
9780 } while ((len > 0) && (sf_sent >= 0));
9781
9782 if (sf_sent > 0) {
9783 return; /* OK */
9784 }
9785
9786 /* sf_sent<0 means error, thus fall back to the classic way */
9787 /* This is always the case, if sf_file is not a "normal" file,
9788 * e.g., for sending data from the output of a CGI process. */
9789 offset = (int64_t)sf_offs;
9790 }
9791#endif
9792 if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
9793 mg_cry_internal(conn,
9794 "%s: fseeko() failed: %s",
9795 __func__,
9796 strerror(ERRNO));
9798 conn,
9799 500,
9800 "%s",
9801 "Error: Unable to access file at requested position.");
9802 } else {
9803 while (len > 0) {
9804 /* Calculate how much to read from the file in the buffer */
9805 to_read = sizeof(buf);
9806 if ((int64_t)to_read > len) {
9807 to_read = (int)len;
9808 }
9809
9810 /* Read from file, exit the loop on error */
9811 if ((num_read =
9812 (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
9813 <= 0) {
9814 break;
9815 }
9816
9817 /* Send read bytes to the client, exit the loop on error */
9818 if ((num_written = mg_write(conn, buf, (size_t)num_read))
9819 != num_read) {
9820 break;
9821 }
9822
9823 /* Both read and were successful, adjust counters */
9824 len -= num_written;
9825 }
9826 }
9827 }
9828}
9829
9830
9831static int
9832parse_range_header(const char *header, int64_t *a, int64_t *b)
9833{
9834 return sscanf(header,
9835 "bytes=%" INT64_FMT "-%" INT64_FMT,
9836 a,
9837 b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
9838 // to an integer value, but function will not report
9839 // conversion errors; consider using 'strtol' instead
9840}
9841
9842
9843static void
9844construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
9845{
9846 if ((filestat != NULL) && (buf != NULL)) {
9847 mg_snprintf(NULL,
9848 NULL, /* All calls to construct_etag use 64 byte buffer */
9849 buf,
9850 buf_len,
9851 "\"%lx.%" INT64_FMT "\"",
9852 (unsigned long)filestat->last_modified,
9853 filestat->size);
9854 }
9855}
9856
9857
9858static void
9859fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
9860{
9861 if (filep != NULL && filep->fp != NULL) {
9862#if defined(_WIN32)
9863 (void)conn; /* Unused. */
9864#else
9865 if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
9866 mg_cry_internal(conn,
9867 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
9868 __func__,
9869 strerror(ERRNO));
9870 }
9871#endif
9872 }
9873}
9874
9875
9876#if defined(USE_ZLIB)
9877#include "mod_zlib.inl"
9878#endif
9879
9880
9881#if !defined(NO_FILESYSTEMS)
9882static void
9884 const char *path,
9885 struct mg_file *filep,
9886 const char *mime_type,
9887 const char *additional_headers)
9888{
9889 char lm[64], etag[64];
9890 char range[128]; /* large enough, so there will be no overflow */
9891 const char *range_hdr;
9892 int64_t cl, r1, r2;
9893 struct vec mime_vec;
9894 int n, truncated;
9895 char gz_path[UTF8_PATH_MAX];
9896 const char *encoding = 0;
9897 const char *origin_hdr;
9898 const char *cors_orig_cfg, *cors_cred_cfg;
9899 const char *cors1, *cors2, *cors3, *cors4;
9900 int is_head_request;
9901
9902#if defined(USE_ZLIB)
9903 /* Compression is allowed, unless there is a reason not to use
9904 * compression. If the file is already compressed, too small or a
9905 * "range" request was made, on the fly compression is not possible. */
9906 int allow_on_the_fly_compression = 1;
9907#endif
9908
9909 if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
9910 return;
9911 }
9912
9913 is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
9914
9915 if (mime_type == NULL) {
9916 get_mime_type(conn, path, &mime_vec);
9917 } else {
9918 mime_vec.ptr = mime_type;
9919 mime_vec.len = strlen(mime_type);
9920 }
9921 if (filep->stat.size > INT64_MAX) {
9922 mg_send_http_error(conn,
9923 500,
9924 "Error: File size is too large to send\n%" INT64_FMT,
9925 filep->stat.size);
9926 return;
9927 }
9928 cl = (int64_t)filep->stat.size;
9929 conn->status_code = 200;
9930 range[0] = '\0';
9931
9932#if defined(USE_ZLIB)
9933 /* if this file is in fact a pre-gzipped file, rewrite its filename
9934 * it's important to rewrite the filename after resolving
9935 * the mime type from it, to preserve the actual file's type */
9936 if (!conn->accept_gzip) {
9937 allow_on_the_fly_compression = 0;
9938 }
9939#endif
9940
9941 /* Check if there is a range header */
9942 range_hdr = mg_get_header(conn, "Range");
9943
9944 /* For gzipped files, add *.gz */
9945 if (filep->stat.is_gzipped) {
9946 mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
9947
9948 if (truncated) {
9949 mg_send_http_error(conn,
9950 500,
9951 "Error: Path of zipped file too long (%s)",
9952 path);
9953 return;
9954 }
9955
9956 path = gz_path;
9957 encoding = "gzip";
9958
9959#if defined(USE_ZLIB)
9960 /* File is already compressed. No "on the fly" compression. */
9961 allow_on_the_fly_compression = 0;
9962#endif
9963 } else if ((conn->accept_gzip) && (range_hdr == NULL)
9964 && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
9965 struct mg_file_stat file_stat;
9966
9967 mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
9968
9969 if (!truncated && mg_stat(conn, gz_path, &file_stat)
9970 && !file_stat.is_directory) {
9971 file_stat.is_gzipped = 1;
9972 filep->stat = file_stat;
9973 cl = (int64_t)filep->stat.size;
9974 path = gz_path;
9975 encoding = "gzip";
9976
9977#if defined(USE_ZLIB)
9978 /* File is already compressed. No "on the fly" compression. */
9979 allow_on_the_fly_compression = 0;
9980#endif
9981 }
9982 }
9983
9984 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
9985 mg_send_http_error(conn,
9986 500,
9987 "Error: Cannot open file\nfopen(%s): %s",
9988 path,
9989 strerror(ERRNO));
9990 return;
9991 }
9992
9993 fclose_on_exec(&filep->access, conn);
9994
9995 /* If "Range" request was made: parse header, send only selected part
9996 * of the file. */
9997 r1 = r2 = 0;
9998 if ((range_hdr != NULL)
9999 && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
10000 && (r2 >= 0)) {
10001 /* actually, range requests don't play well with a pre-gzipped
10002 * file (since the range is specified in the uncompressed space) */
10003 if (filep->stat.is_gzipped) {
10005 conn,
10006 416, /* 416 = Range Not Satisfiable */
10007 "%s",
10008 "Error: Range requests in gzipped files are not supported");
10009 (void)mg_fclose(
10010 &filep->access); /* ignore error on read only file */
10011 return;
10012 }
10013 conn->status_code = 206;
10014 cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
10015 mg_snprintf(conn,
10016 NULL, /* range buffer is big enough */
10017 range,
10018 sizeof(range),
10019 "bytes "
10020 "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
10021 r1,
10022 r1 + cl - 1,
10023 filep->stat.size);
10024
10025#if defined(USE_ZLIB)
10026 /* Do not compress ranges. */
10027 allow_on_the_fly_compression = 0;
10028#endif
10029 }
10030
10031 /* Do not compress small files. Small files do not benefit from file
10032 * compression, but there is still some overhead. */
10033#if defined(USE_ZLIB)
10035 /* File is below the size limit. */
10036 allow_on_the_fly_compression = 0;
10037 }
10038#endif
10039
10040 /* Standard CORS header */
10041 cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
10042 origin_hdr = mg_get_header(conn, "Origin");
10043 if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
10044 /* Cross-origin resource sharing (CORS), see
10045 * http://www.html5rocks.com/en/tutorials/cors/,
10046 * http://www.html5rocks.com/static/images/cors_server_flowchart.png
10047 * -
10048 * preflight is not supported for files. */
10049 cors1 = "Access-Control-Allow-Origin";
10050 cors2 = cors_orig_cfg;
10051 } else {
10052 cors1 = cors2 = "";
10053 }
10054
10055 /* Credentials CORS header */
10056 cors_cred_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
10057 if (cors_cred_cfg && *cors_cred_cfg && origin_hdr) {
10058 cors3 = "Access-Control-Allow-Credentials";
10059 cors4 = cors_cred_cfg;
10060 } else {
10061 cors3 = cors4 = "";
10062 }
10063
10064 /* Prepare Etag, and Last-Modified headers. */
10065 gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
10066 construct_etag(etag, sizeof(etag), &filep->stat);
10067
10068 /* Create 2xx (200, 206) response */
10073 "Content-Type",
10074 mime_vec.ptr,
10075 (int)mime_vec.len);
10076 if (cors1[0] != 0) {
10077 mg_response_header_add(conn, cors1, cors2, -1);
10078 }
10079 if (cors3[0] != 0) {
10080 mg_response_header_add(conn, cors3, cors4, -1);
10081 }
10082 mg_response_header_add(conn, "Last-Modified", lm, -1);
10083 mg_response_header_add(conn, "Etag", etag, -1);
10084
10085#if defined(USE_ZLIB)
10086 /* On the fly compression allowed */
10087 if (allow_on_the_fly_compression) {
10088 /* For on the fly compression, we don't know the content size in
10089 * advance, so we have to use chunked encoding */
10090 encoding = "gzip";
10091 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
10092 /* HTTP/2 is always using "chunks" (frames) */
10093 mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
10094 }
10095
10096 } else
10097#endif
10098 {
10099 /* Without on-the-fly compression, we know the content-length
10100 * and we can use ranges (with on-the-fly compression we cannot).
10101 * So we send these response headers only in this case. */
10102 char len[32];
10103 int trunc = 0;
10104 mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
10105
10106 if (!trunc) {
10107 mg_response_header_add(conn, "Content-Length", len, -1);
10108 }
10109
10110 mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
10111 }
10112
10113 if (encoding) {
10114 mg_response_header_add(conn, "Content-Encoding", encoding, -1);
10115 }
10116 if (range[0] != 0) {
10117 mg_response_header_add(conn, "Content-Range", range, -1);
10118 }
10119
10120 /* The code above does not add any header starting with X- to make
10121 * sure no one of the additional_headers is included twice */
10122 if ((additional_headers != NULL) && (*additional_headers != 0)) {
10123 mg_response_header_add_lines(conn, additional_headers);
10124 }
10125
10126 /* Send all headers */
10128
10129 if (!is_head_request) {
10130#if defined(USE_ZLIB)
10131 if (allow_on_the_fly_compression) {
10132 /* Compress and send */
10133 send_compressed_data(conn, filep);
10134 } else
10135#endif
10136 {
10137 /* Send file directly */
10138 send_file_data(conn, filep, r1, cl);
10139 }
10140 }
10141 (void)mg_fclose(&filep->access); /* ignore error on read only file */
10142}
10143
10144
10145int
10146mg_send_file_body(struct mg_connection *conn, const char *path)
10147{
10148 struct mg_file file = STRUCT_FILE_INITIALIZER;
10149 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
10150 return -1;
10151 }
10152 fclose_on_exec(&file.access, conn);
10153 send_file_data(conn, &file, 0, INT64_MAX);
10154 (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
10155 return 0; /* >= 0 for OK */
10156}
10157#endif /* NO_FILESYSTEMS */
10158
10159
10160#if !defined(NO_CACHING)
10161/* Return True if we should reply 304 Not Modified. */
10162static int
10164 const struct mg_file_stat *filestat)
10165{
10166 char etag[64];
10167 const char *ims = mg_get_header(conn, "If-Modified-Since");
10168 const char *inm = mg_get_header(conn, "If-None-Match");
10169 construct_etag(etag, sizeof(etag), filestat);
10170
10171 return ((inm != NULL) && !mg_strcasecmp(etag, inm))
10172 || ((ims != NULL)
10173 && (filestat->last_modified <= parse_date_string(ims)));
10174}
10175
10176
10177static void
10179 struct mg_file *filep)
10180{
10181 char lm[64], etag[64];
10182
10183 if ((conn == NULL) || (filep == NULL)) {
10184 return;
10185 }
10186
10187 gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
10188 construct_etag(etag, sizeof(etag), &filep->stat);
10189
10190 /* Create 304 "not modified" response */
10191 mg_response_header_start(conn, 304);
10194 mg_response_header_add(conn, "Last-Modified", lm, -1);
10195 mg_response_header_add(conn, "Etag", etag, -1);
10196
10197 /* Send all headers */
10199}
10200#endif
10201
10202
10203#if !defined(NO_FILESYSTEMS)
10204void
10205mg_send_file(struct mg_connection *conn, const char *path)
10206{
10207 mg_send_mime_file2(conn, path, NULL, NULL);
10208}
10209
10210
10211void
10213 const char *path,
10214 const char *mime_type)
10215{
10216 mg_send_mime_file2(conn, path, mime_type, NULL);
10217}
10218
10219
10220void
10222 const char *path,
10223 const char *mime_type,
10224 const char *additional_headers)
10225{
10226 struct mg_file file = STRUCT_FILE_INITIALIZER;
10227
10228 if (!conn) {
10229 /* No conn */
10230 return;
10231 }
10232
10233 if (mg_stat(conn, path, &file.stat)) {
10234#if !defined(NO_CACHING)
10235 if (is_not_modified(conn, &file.stat)) {
10236 /* Send 304 "Not Modified" - this must not send any body data */
10238 } else
10239#endif /* NO_CACHING */
10240 if (file.stat.is_directory) {
10242 "yes")) {
10243 handle_directory_request(conn, path);
10244 } else {
10245 mg_send_http_error(conn,
10246 403,
10247 "%s",
10248 "Error: Directory listing denied");
10249 }
10250 } else {
10252 conn, path, &file, mime_type, additional_headers);
10253 }
10254 } else {
10255 mg_send_http_error(conn, 404, "%s", "Error: File not found");
10256 }
10257}
10258
10259
10260/* For a given PUT path, create all intermediate subdirectories.
10261 * Return 0 if the path itself is a directory.
10262 * Return 1 if the path leads to a file.
10263 * Return -1 for if the path is too long.
10264 * Return -2 if path can not be created.
10265 */
10266static int
10267put_dir(struct mg_connection *conn, const char *path)
10268{
10269 char buf[UTF8_PATH_MAX];
10270 const char *s, *p;
10271 struct mg_file file = STRUCT_FILE_INITIALIZER;
10272 size_t len;
10273 int res = 1;
10274
10275 for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
10276 len = (size_t)(p - path);
10277 if (len >= sizeof(buf)) {
10278 /* path too long */
10279 res = -1;
10280 break;
10281 }
10282 memcpy(buf, path, len);
10283 buf[len] = '\0';
10284
10285 /* Try to create intermediate directory */
10286 DEBUG_TRACE("mkdir(%s)", buf);
10287 if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
10288 /* path does not exixt and can not be created */
10289 res = -2;
10290 break;
10291 }
10292
10293 /* Is path itself a directory? */
10294 if (p[1] == '\0') {
10295 res = 0;
10296 }
10297 }
10298
10299 return res;
10300}
10301
10302
10303static void
10304remove_bad_file(const struct mg_connection *conn, const char *path)
10305{
10306 int r = mg_remove(conn, path);
10307 if (r != 0) {
10308 mg_cry_internal(conn,
10309 "%s: Cannot remove invalid file %s",
10310 __func__,
10311 path);
10312 }
10313}
10314
10315
10316long long
10317mg_store_body(struct mg_connection *conn, const char *path)
10318{
10319 char buf[MG_BUF_LEN];
10320 long long len = 0;
10321 int ret, n;
10322 struct mg_file fi;
10323
10324 if (conn->consumed_content != 0) {
10325 mg_cry_internal(conn, "%s: Contents already consumed", __func__);
10326 return -11;
10327 }
10328
10329 ret = put_dir(conn, path);
10330 if (ret < 0) {
10331 /* -1 for path too long,
10332 * -2 for path can not be created. */
10333 return ret;
10334 }
10335 if (ret != 1) {
10336 /* Return 0 means, path itself is a directory. */
10337 return 0;
10338 }
10339
10340 if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
10341 return -12;
10342 }
10343
10344 ret = mg_read(conn, buf, sizeof(buf));
10345 while (ret > 0) {
10346 n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
10347 if (n != ret) {
10348 (void)mg_fclose(
10349 &fi.access); /* File is bad and will be removed anyway. */
10350 remove_bad_file(conn, path);
10351 return -13;
10352 }
10353 len += ret;
10354 ret = mg_read(conn, buf, sizeof(buf));
10355 }
10356
10357 /* File is open for writing. If fclose fails, there was probably an
10358 * error flushing the buffer to disk, so the file on disk might be
10359 * broken. Delete it and return an error to the caller. */
10360 if (mg_fclose(&fi.access) != 0) {
10361 remove_bad_file(conn, path);
10362 return -14;
10363 }
10364
10365 return len;
10366}
10367#endif /* NO_FILESYSTEMS */
10368
10369
10370/* Parse a buffer:
10371 * Forward the string pointer till the end of a word, then
10372 * terminate it and forward till the begin of the next word.
10373 */
10374static int
10376{
10377 /* Forward until a space is found - use isgraph here */
10378 /* See http://www.cplusplus.com/reference/cctype/ */
10379 while (isgraph((unsigned char)**ppw)) {
10380 (*ppw)++;
10381 }
10382
10383 /* Check end of word */
10384 if (eol) {
10385 /* must be a end of line */
10386 if ((**ppw != '\r') && (**ppw != '\n')) {
10387 return -1;
10388 }
10389 } else {
10390 /* must be a end of a word, but not a line */
10391 if (**ppw != ' ') {
10392 return -1;
10393 }
10394 }
10395
10396 /* Terminate and forward to the next word */
10397 do {
10398 **ppw = 0;
10399 (*ppw)++;
10400 } while (isspace((unsigned char)**ppw));
10401
10402 /* Check after term */
10403 if (!eol) {
10404 /* if it's not the end of line, there must be a next word */
10405 if (!isgraph((unsigned char)**ppw)) {
10406 return -1;
10407 }
10408 }
10409
10410 /* ok */
10411 return 1;
10412}
10413
10414
10415/* Parse HTTP headers from the given buffer, advance buf pointer
10416 * to the point where parsing stopped.
10417 * All parameters must be valid pointers (not NULL).
10418 * Return <0 on error. */
10419static int
10421{
10422 int i;
10423 int num_headers = 0;
10424
10425 for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
10426 char *dp = *buf;
10427
10428 /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
10429 while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
10430 dp++;
10431 }
10432 if (dp == *buf) {
10433 /* End of headers reached. */
10434 break;
10435 }
10436
10437 /* Drop all spaces after header name before : */
10438 while (*dp == ' ') {
10439 *dp = 0;
10440 dp++;
10441 }
10442 if (*dp != ':') {
10443 /* This is not a valid field. */
10444 return -1;
10445 }
10446
10447 /* End of header key (*dp == ':') */
10448 /* Truncate here and set the key name */
10449 *dp = 0;
10450 hdr[i].name = *buf;
10451
10452 /* Skip all spaces */
10453 do {
10454 dp++;
10455 } while ((*dp == ' ') || (*dp == '\t'));
10456
10457 /* The rest of the line is the value */
10458 hdr[i].value = dp;
10459
10460 /* Find end of line */
10461 while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
10462 dp++;
10463 };
10464
10465 /* eliminate \r */
10466 if (*dp == '\r') {
10467 *dp = 0;
10468 dp++;
10469 if (*dp != '\n') {
10470 /* This is not a valid line. */
10471 return -1;
10472 }
10473 }
10474
10475 /* here *dp is either 0 or '\n' */
10476 /* in any case, we have a new header */
10477 num_headers = i + 1;
10478
10479 if (*dp) {
10480 *dp = 0;
10481 dp++;
10482 *buf = dp;
10483
10484 if ((dp[0] == '\r') || (dp[0] == '\n')) {
10485 /* This is the end of the header */
10486 break;
10487 }
10488 } else {
10489 *buf = dp;
10490 break;
10491 }
10492 }
10493 return num_headers;
10494}
10495
10496
10498 const char *name;
10504};
10505
10506
10507/* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
10508static const struct mg_http_method_info http_methods[] = {
10509 /* HTTP (RFC 2616) */
10510 {"GET", 0, 1, 1, 1, 1},
10511 {"POST", 1, 1, 0, 0, 0},
10512 {"PUT", 1, 0, 0, 1, 0},
10513 {"DELETE", 0, 0, 0, 1, 0},
10514 {"HEAD", 0, 0, 1, 1, 1},
10515 {"OPTIONS", 0, 0, 1, 1, 0},
10516 {"CONNECT", 1, 1, 0, 0, 0},
10517 /* TRACE method (RFC 2616) is not supported for security reasons */
10518
10519 /* PATCH method (RFC 5789) */
10520 {"PATCH", 1, 0, 0, 0, 0},
10521 /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
10522
10523 /* WEBDAV (RFC 2518) */
10524 {"PROPFIND", 0, 1, 1, 1, 0},
10525 /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10526 * Some PROPFIND results MAY be cached, with care,
10527 * as there is no cache validation mechanism for
10528 * most properties. This method is both safe and
10529 * idempotent (see Section 9.1 of [RFC2616]). */
10530 {"MKCOL", 0, 0, 0, 1, 0},
10531 /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10532 * When MKCOL is invoked without a request body,
10533 * the newly created collection SHOULD have no
10534 * members. A MKCOL request message may contain
10535 * a message body. The precise behavior of a MKCOL
10536 * request when the body is present is undefined,
10537 * ... ==> We do not support MKCOL with body data.
10538 * This method is idempotent, but not safe (see
10539 * Section 9.1 of [RFC2616]). Responses to this
10540 * method MUST NOT be cached. */
10541
10542 /* Methods for write access to files on WEBDAV (RFC 2518) */
10543 {"LOCK", 1, 1, 0, 0, 0},
10544 {"UNLOCK", 1, 0, 0, 0, 0},
10545 {"PROPPATCH", 1, 1, 0, 0, 0},
10546
10547 /* Unsupported WEBDAV Methods: */
10548 /* COPY, MOVE (RFC 2518) */
10549 /* + 11 methods from RFC 3253 */
10550 /* ORDERPATCH (RFC 3648) */
10551 /* ACL (RFC 3744) */
10552 /* SEARCH (RFC 5323) */
10553 /* + MicroSoft extensions
10554 * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
10555
10556 /* REPORT method (RFC 3253) */
10557 {"REPORT", 1, 1, 1, 1, 1},
10558 /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
10559 /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
10560 * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
10561 * to be useful for REST in case a "GET request with body" is
10562 * required. */
10563
10564 {NULL, 0, 0, 0, 0, 0}
10565 /* end of list */
10566};
10567
10568
10569static const struct mg_http_method_info *
10570get_http_method_info(const char *method)
10571{
10572 /* Check if the method is known to the server. The list of all known
10573 * HTTP methods can be found here at
10574 * http://www.iana.org/assignments/http-methods/http-methods.xhtml
10575 */
10576 const struct mg_http_method_info *m = http_methods;
10577
10578 while (m->name) {
10579 if (!strcmp(m->name, method)) {
10580 return m;
10581 }
10582 m++;
10583 }
10584 return NULL;
10585}
10586
10587
10588static int
10589is_valid_http_method(const char *method)
10590{
10591 return (get_http_method_info(method) != NULL);
10592}
10593
10594
10595/* Parse HTTP request, fill in mg_request_info structure.
10596 * This function modifies the buffer by NUL-terminating
10597 * HTTP request components, header names and header values.
10598 * Parameters:
10599 * buf (in/out): pointer to the HTTP header to parse and split
10600 * len (in): length of HTTP header buffer
10601 * re (out): parsed header as mg_request_info
10602 * buf and ri must be valid pointers (not NULL), len>0.
10603 * Returns <0 on error. */
10604static int
10605parse_http_request(char *buf, int len, struct mg_request_info *ri)
10606{
10607 int request_length;
10608 int init_skip = 0;
10609
10610 /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
10611 * remote_port */
10612 ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
10613 NULL;
10614 ri->num_headers = 0;
10615
10616 /* RFC says that all initial whitespaces should be ignored */
10617 /* This included all leading \r and \n (isspace) */
10618 /* See table: http://www.cplusplus.com/reference/cctype/ */
10619 while ((len > 0) && isspace((unsigned char)*buf)) {
10620 buf++;
10621 len--;
10622 init_skip++;
10623 }
10624
10625 if (len == 0) {
10626 /* Incomplete request */
10627 return 0;
10628 }
10629
10630 /* Control characters are not allowed, including zero */
10631 if (iscntrl((unsigned char)*buf)) {
10632 return -1;
10633 }
10634
10635 /* Find end of HTTP header */
10636 request_length = get_http_header_len(buf, len);
10637 if (request_length <= 0) {
10638 return request_length;
10639 }
10640 buf[request_length - 1] = '\0';
10641
10642 if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10643 return -1;
10644 }
10645
10646 /* The first word has to be the HTTP method */
10647 ri->request_method = buf;
10648
10649 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10650 return -1;
10651 }
10652
10653 /* The second word is the URI */
10654 ri->request_uri = buf;
10655
10656 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10657 return -1;
10658 }
10659
10660 /* Next would be the HTTP version */
10661 ri->http_version = buf;
10662
10663 if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
10664 return -1;
10665 }
10666
10667 /* Check for a valid HTTP version key */
10668 if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
10669 /* Invalid request */
10670 return -1;
10671 }
10672 ri->http_version += 5;
10673
10674 /* Check for a valid http method */
10676 return -1;
10677 }
10678
10679 /* Parse all HTTP headers */
10681 if (ri->num_headers < 0) {
10682 /* Error while parsing headers */
10683 return -1;
10684 }
10685
10686 return request_length + init_skip;
10687}
10688
10689
10690static int
10691parse_http_response(char *buf, int len, struct mg_response_info *ri)
10692{
10693 int response_length;
10694 int init_skip = 0;
10695 char *tmp, *tmp2;
10696 long l;
10697
10698 /* Initialize elements. */
10699 ri->http_version = ri->status_text = NULL;
10700 ri->num_headers = ri->status_code = 0;
10701
10702 /* RFC says that all initial whitespaces should be ingored */
10703 /* This included all leading \r and \n (isspace) */
10704 /* See table: http://www.cplusplus.com/reference/cctype/ */
10705 while ((len > 0) && isspace((unsigned char)*buf)) {
10706 buf++;
10707 len--;
10708 init_skip++;
10709 }
10710
10711 if (len == 0) {
10712 /* Incomplete request */
10713 return 0;
10714 }
10715
10716 /* Control characters are not allowed, including zero */
10717 if (iscntrl((unsigned char)*buf)) {
10718 return -1;
10719 }
10720
10721 /* Find end of HTTP header */
10722 response_length = get_http_header_len(buf, len);
10723 if (response_length <= 0) {
10724 return response_length;
10725 }
10726 buf[response_length - 1] = '\0';
10727
10728 if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10729 return -1;
10730 }
10731
10732 /* The first word is the HTTP version */
10733 /* Check for a valid HTTP version key */
10734 if (strncmp(buf, "HTTP/", 5) != 0) {
10735 /* Invalid request */
10736 return -1;
10737 }
10738 buf += 5;
10739 if (!isgraph((unsigned char)buf[0])) {
10740 /* Invalid request */
10741 return -1;
10742 }
10743 ri->http_version = buf;
10744
10745 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10746 return -1;
10747 }
10748
10749 /* The second word is the status as a number */
10750 tmp = buf;
10751
10752 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10753 return -1;
10754 }
10755
10756 l = strtol(tmp, &tmp2, 10);
10757 if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
10758 /* Everything else but a 3 digit code is invalid */
10759 return -1;
10760 }
10761 ri->status_code = (int)l;
10762
10763 /* The rest of the line is the status text */
10764 ri->status_text = buf;
10765
10766 /* Find end of status text */
10767 /* isgraph or isspace = isprint */
10768 while (isprint((unsigned char)*buf)) {
10769 buf++;
10770 }
10771 if ((*buf != '\r') && (*buf != '\n')) {
10772 return -1;
10773 }
10774 /* Terminate string and forward buf to next line */
10775 do {
10776 *buf = 0;
10777 buf++;
10778 } while (isspace((unsigned char)*buf));
10779
10780
10781 /* Parse all HTTP headers */
10783 if (ri->num_headers < 0) {
10784 /* Error while parsing headers */
10785 return -1;
10786 }
10787
10788 return response_length + init_skip;
10789}
10790
10791
10792/* Keep reading the input (either opened file descriptor fd, or socket sock,
10793 * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
10794 * buffer (which marks the end of HTTP request). Buffer buf may already
10795 * have some data. The length of the data is stored in nread.
10796 * Upon every read operation, increase nread by the number of bytes read. */
10797static int
10799 struct mg_connection *conn,
10800 char *buf,
10801 int bufsiz,
10802 int *nread)
10803{
10804 int request_len, n = 0;
10805 struct timespec last_action_time;
10806 double request_timeout;
10807
10808 if (!conn) {
10809 return 0;
10810 }
10811
10812 memset(&last_action_time, 0, sizeof(last_action_time));
10813
10814 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
10815 /* value of request_timeout is in seconds, config in milliseconds */
10816 request_timeout =
10817 strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
10818 } else {
10819 request_timeout =
10820 strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
10821 / 1000.0;
10822 }
10823 if (conn->handled_requests > 0) {
10824 if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
10825 request_timeout =
10826 strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
10827 / 1000.0;
10828 }
10829 }
10830
10831 request_len = get_http_header_len(buf, *nread);
10832
10833 while (request_len == 0) {
10834 /* Full request not yet received */
10835 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
10836 /* Server is to be stopped. */
10837 return -1;
10838 }
10839
10840 if (*nread >= bufsiz) {
10841 /* Request too long */
10842 return -2;
10843 }
10844
10845 n = pull_inner(
10846 fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
10847 if (n == -2) {
10848 /* Receive error */
10849 return -1;
10850 }
10851
10852 /* update clock after every read request */
10853 clock_gettime(CLOCK_MONOTONIC, &last_action_time);
10854
10855 if (n > 0) {
10856 *nread += n;
10857 request_len = get_http_header_len(buf, *nread);
10858 }
10859
10860 if ((request_len == 0) && (request_timeout >= 0)) {
10861 if (mg_difftimespec(&last_action_time, &(conn->req_time))
10862 > request_timeout) {
10863 /* Timeout */
10864 return -1;
10865 }
10866 }
10867 }
10868
10869 return request_len;
10870}
10871
10872
10873#if !defined(NO_CGI) || !defined(NO_FILES)
10874static int
10875forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
10876{
10877 const char *expect;
10878 char buf[MG_BUF_LEN];
10879 int success = 0;
10880
10881 if (!conn) {
10882 return 0;
10883 }
10884
10885 expect = mg_get_header(conn, "Expect");
10886 DEBUG_ASSERT(fp != NULL);
10887 if (!fp) {
10888 mg_send_http_error(conn, 500, "%s", "Error: NULL File");
10889 return 0;
10890 }
10891
10892 if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
10893 /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
10894 */
10895 mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
10896 } else {
10897 if (expect != NULL) {
10898 (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
10899 conn->status_code = 100;
10900 } else {
10901 conn->status_code = 200;
10902 }
10903
10904 DEBUG_ASSERT(conn->consumed_content == 0);
10905
10906 if (conn->consumed_content != 0) {
10907 mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
10908 return 0;
10909 }
10910
10911 for (;;) {
10912 int nread = mg_read(conn, buf, sizeof(buf));
10913 if (nread <= 0) {
10914 success = (nread == 0);
10915 break;
10916 }
10917 if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
10918 break;
10919 }
10920 }
10921
10922 /* Each error code path in this function must send an error */
10923 if (!success) {
10924 /* NOTE: Maybe some data has already been sent. */
10925 /* TODO (low): If some data has been sent, a correct error
10926 * reply can no longer be sent, so just close the connection */
10927 mg_send_http_error(conn, 500, "%s", "");
10928 }
10929 }
10930
10931 return success;
10932}
10933#endif
10934
10935
10936#if defined(USE_TIMERS)
10937
10938#define TIMER_API static
10939#include "timer.inl"
10940
10941#endif /* USE_TIMERS */
10942
10943
10944#if !defined(NO_CGI)
10945/* This structure helps to create an environment for the spawned CGI
10946 * program.
10947 * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
10948 * last element must be NULL.
10949 * However, on Windows there is a requirement that all these
10950 * VARIABLE=VALUE\0
10951 * strings must reside in a contiguous buffer. The end of the buffer is
10952 * marked by two '\0' characters.
10953 * We satisfy both worlds: we create an envp array (which is vars), all
10954 * entries are actually pointers inside buf. */
10957 /* Data block */
10958 char *buf; /* Environment buffer */
10959 size_t buflen; /* Space available in buf */
10960 size_t bufused; /* Space taken in buf */
10961 /* Index block */
10962 char **var; /* char **envp */
10963 size_t varlen; /* Number of variables available in var */
10964 size_t varused; /* Number of variables stored in var */
10965};
10966
10967
10968static void addenv(struct cgi_environment *env,
10969 PRINTF_FORMAT_STRING(const char *fmt),
10970 ...) PRINTF_ARGS(2, 3);
10971
10972/* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
10973 * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
10974static void
10975addenv(struct cgi_environment *env, const char *fmt, ...)
10976{
10977 size_t i, n, space;
10978 int truncated = 0;
10979 char *added;
10980 va_list ap;
10981
10982 if ((env->varlen - env->varused) < 2) {
10983 mg_cry_internal(env->conn,
10984 "%s: Cannot register CGI variable [%s]",
10985 __func__,
10986 fmt);
10987 return;
10988 }
10989
10990 /* Calculate how much space is left in the buffer */
10991 space = (env->buflen - env->bufused);
10992
10993 do {
10994 /* Space for "\0\0" is always needed. */
10995 if (space <= 2) {
10996 /* Allocate new buffer */
10997 n = env->buflen + CGI_ENVIRONMENT_SIZE;
10998 added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
10999 if (!added) {
11000 /* Out of memory */
11002 env->conn,
11003 "%s: Cannot allocate memory for CGI variable [%s]",
11004 __func__,
11005 fmt);
11006 return;
11007 }
11008 /* Retarget pointers */
11009 env->buf = added;
11010 env->buflen = n;
11011 for (i = 0, n = 0; i < env->varused; i++) {
11012 env->var[i] = added + n;
11013 n += strlen(added + n) + 1;
11014 }
11015 space = (env->buflen - env->bufused);
11016 }
11017
11018 /* Make a pointer to the free space int the buffer */
11019 added = env->buf + env->bufused;
11020
11021 /* Copy VARIABLE=VALUE\0 string into the free space */
11022 va_start(ap, fmt);
11023 mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
11024 va_end(ap);
11025
11026 /* Do not add truncated strings to the environment */
11027 if (truncated) {
11028 /* Reallocate the buffer */
11029 space = 0;
11030 }
11031 } while (truncated);
11032
11033 /* Calculate number of bytes added to the environment */
11034 n = strlen(added) + 1;
11035 env->bufused += n;
11036
11037 /* Append a pointer to the added string into the envp array */
11038 env->var[env->varused] = added;
11039 env->varused++;
11040}
11041
11042/* Return 0 on success, non-zero if an error occurs. */
11043
11044static int
11046 const char *prog,
11047 struct cgi_environment *env,
11048 unsigned char cgi_config_idx)
11049{
11050 const char *s;
11051 struct vec var_vec;
11052 char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
11053 int i, truncated, uri_len;
11054
11055 if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
11056 return -1;
11057 }
11058
11059 env->conn = conn;
11061 env->bufused = 0;
11062 env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
11063 if (env->buf == NULL) {
11064 mg_cry_internal(conn,
11065 "%s: Not enough memory for environmental buffer",
11066 __func__);
11067 return -1;
11068 }
11070 env->varused = 0;
11071 env->var =
11072 (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
11073 if (env->var == NULL) {
11074 mg_cry_internal(conn,
11075 "%s: Not enough memory for environmental variables",
11076 __func__);
11077 mg_free(env->buf);
11078 return -1;
11079 }
11080
11081 addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
11082 addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11083 addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11084 addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
11085
11086 /* Prepare the environment block */
11087 addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
11088 addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
11089 addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
11090
11091 addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
11092
11093 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
11094 addenv(env, "REMOTE_ADDR=%s", src_addr);
11095
11096 addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
11097 addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
11098
11099 addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
11100 addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
11101 addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
11102
11103 /* SCRIPT_NAME */
11104 uri_len = (int)strlen(conn->request_info.local_uri);
11105 if (conn->path_info == NULL) {
11106 if (conn->request_info.local_uri[uri_len - 1] != '/') {
11107 /* URI: /path_to_script/script.cgi */
11108 addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
11109 } else {
11110 /* URI: /path_to_script/ ... using index.cgi */
11111 const char *index_file = strrchr(prog, '/');
11112 if (index_file) {
11113 addenv(env,
11114 "SCRIPT_NAME=%s%s",
11115 conn->request_info.local_uri,
11116 index_file + 1);
11117 }
11118 }
11119 } else {
11120 /* URI: /path_to_script/script.cgi/path_info */
11121 addenv(env,
11122 "SCRIPT_NAME=%.*s",
11123 uri_len - (int)strlen(conn->path_info),
11124 conn->request_info.local_uri);
11125 }
11126
11127 addenv(env, "SCRIPT_FILENAME=%s", prog);
11128 if (conn->path_info == NULL) {
11129 addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11130 } else {
11131 addenv(env,
11132 "PATH_TRANSLATED=%s%s",
11134 conn->path_info);
11135 }
11136
11137 addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
11138
11139 if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
11140 addenv(env, "CONTENT_TYPE=%s", s);
11141 }
11142 if (conn->request_info.query_string != NULL) {
11143 addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
11144 }
11145 if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
11146 addenv(env, "CONTENT_LENGTH=%s", s);
11147 }
11148 if ((s = getenv("PATH")) != NULL) {
11149 addenv(env, "PATH=%s", s);
11150 }
11151 if (conn->path_info != NULL) {
11152 addenv(env, "PATH_INFO=%s", conn->path_info);
11153 }
11154
11155 if (conn->status_code > 0) {
11156 /* CGI error handler should show the status code */
11157 addenv(env, "STATUS=%d", conn->status_code);
11158 }
11159
11160#if defined(_WIN32)
11161 if ((s = getenv("COMSPEC")) != NULL) {
11162 addenv(env, "COMSPEC=%s", s);
11163 }
11164 if ((s = getenv("SYSTEMROOT")) != NULL) {
11165 addenv(env, "SYSTEMROOT=%s", s);
11166 }
11167 if ((s = getenv("SystemDrive")) != NULL) {
11168 addenv(env, "SystemDrive=%s", s);
11169 }
11170 if ((s = getenv("ProgramFiles")) != NULL) {
11171 addenv(env, "ProgramFiles=%s", s);
11172 }
11173 if ((s = getenv("ProgramFiles(x86)")) != NULL) {
11174 addenv(env, "ProgramFiles(x86)=%s", s);
11175 }
11176#else
11177 if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
11178 addenv(env, "LD_LIBRARY_PATH=%s", s);
11179 }
11180#endif /* _WIN32 */
11181
11182 if ((s = getenv("PERLLIB")) != NULL) {
11183 addenv(env, "PERLLIB=%s", s);
11184 }
11185
11186 if (conn->request_info.remote_user != NULL) {
11187 addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
11188 addenv(env, "%s", "AUTH_TYPE=Digest");
11189 }
11190
11191 /* Add all headers as HTTP_* variables */
11192 for (i = 0; i < conn->request_info.num_headers; i++) {
11193
11194 (void)mg_snprintf(conn,
11195 &truncated,
11196 http_var_name,
11197 sizeof(http_var_name),
11198 "HTTP_%s",
11199 conn->request_info.http_headers[i].name);
11200
11201 if (truncated) {
11202 mg_cry_internal(conn,
11203 "%s: HTTP header variable too long [%s]",
11204 __func__,
11205 conn->request_info.http_headers[i].name);
11206 continue;
11207 }
11208
11209 /* Convert variable name into uppercase, and change - to _ */
11210 for (p = http_var_name; *p != '\0'; p++) {
11211 if (*p == '-') {
11212 *p = '_';
11213 }
11214 *p = (char)toupper((unsigned char)*p);
11215 }
11216
11217 addenv(env,
11218 "%s=%s",
11219 http_var_name,
11221 }
11222
11223 /* Add user-specified variables */
11224 s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
11225 while ((s = next_option(s, &var_vec, NULL)) != NULL) {
11226 addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
11227 }
11228
11229 env->var[env->varused] = NULL;
11230 env->buf[env->bufused] = '\0';
11231
11232 return 0;
11233}
11234
11235
11236/* Data for CGI process control: PID and number of references */
11238 pid_t pid;
11239 ptrdiff_t references;
11240};
11241
11242static int
11244{
11245 /* Waitpid checks for child status and won't work for a pid that does
11246 * not identify a child of the current process. Thus, if the pid is
11247 * reused, we will not affect a different process. */
11248 struct process_control_data *proc = (struct process_control_data *)data;
11249 int status = 0;
11250 ptrdiff_t refs;
11251 pid_t ret_pid;
11252
11253 ret_pid = waitpid(proc->pid, &status, WNOHANG);
11254 if ((ret_pid != (pid_t)-1) && (status == 0)) {
11255 /* Stop child process */
11256 DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
11257 kill(proc->pid, SIGABRT);
11258
11259 /* Wait until process is terminated (don't leave zombies) */
11260 while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
11261 ;
11262 } else {
11263 DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
11264 }
11265 /* Dec reference counter */
11266 refs = mg_atomic_dec(&proc->references);
11267 if (refs == 0) {
11268 /* no more references - free data */
11269 mg_free(data);
11270 }
11271
11272 return 0;
11273}
11274
11275
11276/* Local (static) function assumes all arguments are valid. */
11277static void
11279 const char *prog,
11280 unsigned char cgi_config_idx)
11281{
11282 char *buf;
11283 size_t buflen;
11284 int headers_len, data_len, i, truncated;
11285 int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
11286 const char *status, *status_text, *connection_state;
11287 char *pbuf, dir[UTF8_PATH_MAX], *p;
11288 struct mg_request_info ri;
11289 struct cgi_environment blk;
11290 FILE *in = NULL, *out = NULL, *err = NULL;
11291 struct mg_file fout = STRUCT_FILE_INITIALIZER;
11292 pid_t pid = (pid_t)-1;
11293 struct process_control_data *proc = NULL;
11294
11295#if defined(USE_TIMERS)
11296 double cgi_timeout;
11297 if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
11298 /* Get timeout in seconds */
11299 cgi_timeout =
11300 atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
11301 } else {
11302 cgi_timeout =
11303 atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
11304 }
11305
11306#endif
11307
11308 buf = NULL;
11309 buflen = conn->phys_ctx->max_request_size;
11310 i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
11311 if (i != 0) {
11312 blk.buf = NULL;
11313 blk.var = NULL;
11314 goto done;
11315 }
11316
11317 /* CGI must be executed in its own directory. 'dir' must point to the
11318 * directory containing executable program, 'p' must point to the
11319 * executable program name relative to 'dir'. */
11320 (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
11321
11322 if (truncated) {
11323 mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
11324 mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
11325 goto done;
11326 }
11327
11328 if ((p = strrchr(dir, '/')) != NULL) {
11329 *p++ = '\0';
11330 } else {
11331 dir[0] = '.';
11332 dir[1] = '\0';
11333 p = (char *)prog;
11334 }
11335
11336 if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
11337 status = strerror(ERRNO);
11339 conn,
11340 "Error: CGI program \"%s\": Can not create CGI pipes: %s",
11341 prog,
11342 status);
11343 mg_send_http_error(conn,
11344 500,
11345 "Error: Cannot create CGI pipe: %s",
11346 status);
11347 goto done;
11348 }
11349
11350 proc = (struct process_control_data *)
11351 mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
11352 if (proc == NULL) {
11353 mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
11354 mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
11355 goto done;
11356 }
11357
11358 DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
11360 conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
11361
11362 if (pid == (pid_t)-1) {
11363 status = strerror(ERRNO);
11365 conn,
11366 "Error: CGI program \"%s\": Can not spawn CGI process: %s",
11367 prog,
11368 status);
11369 mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
11370 mg_free(proc);
11371 proc = NULL;
11372 goto done;
11373 }
11374
11375 /* Store data in shared process_control_data */
11376 proc->pid = pid;
11377 proc->references = 1;
11378
11379#if defined(USE_TIMERS)
11380 if (cgi_timeout > 0.0) {
11381 proc->references = 2;
11382
11383 // Start a timer for CGI
11384 timer_add(conn->phys_ctx,
11385 cgi_timeout /* in seconds */,
11386 0.0,
11387 1,
11389 (void *)proc,
11390 NULL);
11391 }
11392#endif
11393
11394 /* Parent closes only one side of the pipes.
11395 * If we don't mark them as closed, close() attempt before
11396 * return from this function throws an exception on Windows.
11397 * Windows does not like when closed descriptor is closed again. */
11398 (void)close(fdin[0]);
11399 (void)close(fdout[1]);
11400 (void)close(fderr[1]);
11401 fdin[0] = fdout[1] = fderr[1] = -1;
11402
11403 if (((in = fdopen(fdin[1], "wb")) == NULL)
11404 || ((out = fdopen(fdout[0], "rb")) == NULL)
11405 || ((err = fdopen(fderr[0], "rb")) == NULL)) {
11406 status = strerror(ERRNO);
11407 mg_cry_internal(conn,
11408 "Error: CGI program \"%s\": Can not open fd: %s",
11409 prog,
11410 status);
11411 mg_send_http_error(conn,
11412 500,
11413 "Error: CGI can not open fd\nfdopen: %s",
11414 status);
11415 goto done;
11416 }
11417
11418 setbuf(in, NULL);
11419 setbuf(out, NULL);
11420 setbuf(err, NULL);
11421 fout.access.fp = out;
11422
11423 if ((conn->content_len != 0) || (conn->is_chunked)) {
11424 DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
11425 conn->content_len);
11426
11427 /* This is a POST/PUT request, or another request with body data. */
11428 if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
11429 /* Error sending the body data */
11431 conn,
11432 "Error: CGI program \"%s\": Forward body data failed",
11433 prog);
11434 goto done;
11435 }
11436 }
11437
11438 /* Close so child gets an EOF. */
11439 fclose(in);
11440 in = NULL;
11441 fdin[1] = -1;
11442
11443 /* Now read CGI reply into a buffer. We need to set correct
11444 * status code, thus we need to see all HTTP headers first.
11445 * Do not send anything back to client, until we buffer in all
11446 * HTTP headers. */
11447 data_len = 0;
11448 buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
11449 if (buf == NULL) {
11450 mg_send_http_error(conn,
11451 500,
11452 "Error: Not enough memory for CGI buffer (%u bytes)",
11453 (unsigned int)buflen);
11455 conn,
11456 "Error: CGI program \"%s\": Not enough memory for buffer (%u "
11457 "bytes)",
11458 prog,
11459 (unsigned int)buflen);
11460 goto done;
11461 }
11462
11463 DEBUG_TRACE("CGI: %s", "wait for response");
11464 headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
11465 DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
11466
11467 if (headers_len <= 0) {
11468
11469 /* Could not parse the CGI response. Check if some error message on
11470 * stderr. */
11471 i = pull_all(err, conn, buf, (int)buflen);
11472 if (i > 0) {
11473 /* CGI program explicitly sent an error */
11474 /* Write the error message to the internal log */
11475 mg_cry_internal(conn,
11476 "Error: CGI program \"%s\" sent error "
11477 "message: [%.*s]",
11478 prog,
11479 i,
11480 buf);
11481 /* Don't send the error message back to the client */
11482 mg_send_http_error(conn,
11483 500,
11484 "Error: CGI program \"%s\" failed.",
11485 prog);
11486 } else {
11487 /* CGI program did not explicitly send an error, but a broken
11488 * respon header */
11489 mg_cry_internal(conn,
11490 "Error: CGI program sent malformed or too big "
11491 "(>%u bytes) HTTP headers: [%.*s]",
11492 (unsigned)buflen,
11493 data_len,
11494 buf);
11495
11496 mg_send_http_error(conn,
11497 500,
11498 "Error: CGI program sent malformed or too big "
11499 "(>%u bytes) HTTP headers: [%.*s]",
11500 (unsigned)buflen,
11501 data_len,
11502 buf);
11503 }
11504
11505 /* in both cases, abort processing CGI */
11506 goto done;
11507 }
11508
11509 pbuf = buf;
11510 buf[headers_len - 1] = '\0';
11512
11513 /* Make up and send the status line */
11514 status_text = "OK";
11515 if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
11516 != NULL) {
11517 conn->status_code = atoi(status);
11518 status_text = status;
11519 while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
11520 status_text++;
11521 }
11522 } else if (get_header(ri.http_headers, ri.num_headers, "Location")
11523 != NULL) {
11524 conn->status_code = 307;
11525 } else {
11526 conn->status_code = 200;
11527 }
11528 connection_state =
11529 get_header(ri.http_headers, ri.num_headers, "Connection");
11530 if (!header_has_option(connection_state, "keep-alive")) {
11531 conn->must_close = 1;
11532 }
11533
11534 DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
11535
11536 (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
11537
11538 /* Send headers */
11539 for (i = 0; i < ri.num_headers; i++) {
11540 DEBUG_TRACE("CGI header: %s: %s",
11541 ri.http_headers[i].name,
11542 ri.http_headers[i].value);
11543 mg_printf(conn,
11544 "%s: %s\r\n",
11545 ri.http_headers[i].name,
11546 ri.http_headers[i].value);
11547 }
11548 mg_write(conn, "\r\n", 2);
11549
11550 /* Send chunk of data that may have been read after the headers */
11551 mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
11552
11553 /* Read the rest of CGI output and send to the client */
11554 DEBUG_TRACE("CGI: %s", "forward all data");
11555 send_file_data(conn, &fout, 0, INT64_MAX);
11556 DEBUG_TRACE("CGI: %s", "all data sent");
11557
11558done:
11559 mg_free(blk.var);
11560 mg_free(blk.buf);
11561
11562 if (pid != (pid_t)-1) {
11563 abort_cgi_process((void *)proc);
11564 }
11565
11566 if (fdin[0] != -1) {
11567 close(fdin[0]);
11568 }
11569 if (fdout[1] != -1) {
11570 close(fdout[1]);
11571 }
11572 if (fderr[1] != -1) {
11573 close(fderr[1]);
11574 }
11575
11576 if (in != NULL) {
11577 fclose(in);
11578 } else if (fdin[1] != -1) {
11579 close(fdin[1]);
11580 }
11581
11582 if (out != NULL) {
11583 fclose(out);
11584 } else if (fdout[0] != -1) {
11585 close(fdout[0]);
11586 }
11587
11588 if (err != NULL) {
11589 fclose(err);
11590 } else if (fderr[0] != -1) {
11591 close(fderr[0]);
11592 }
11593
11594 mg_free(buf);
11595}
11596#endif /* !NO_CGI */
11597
11598
11599#if !defined(NO_FILES)
11600static void
11601mkcol(struct mg_connection *conn, const char *path)
11602{
11603 int rc, body_len;
11604 struct de de;
11605
11606 if (conn == NULL) {
11607 return;
11608 }
11609
11610 /* TODO (mid): Check the mg_send_http_error situations in this function
11611 */
11612
11613 memset(&de.file, 0, sizeof(de.file));
11614 if (!mg_stat(conn, path, &de.file)) {
11616 "%s: mg_stat(%s) failed: %s",
11617 __func__,
11618 path,
11619 strerror(ERRNO));
11620 }
11621
11622 if (de.file.last_modified) {
11623 /* TODO (mid): This check does not seem to make any sense ! */
11624 /* TODO (mid): Add a webdav unit test first, before changing
11625 * anything here. */
11627 conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11628 return;
11629 }
11630
11631 body_len = conn->data_len - conn->request_len;
11632 if (body_len > 0) {
11634 conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11635 return;
11636 }
11637
11638 rc = mg_mkdir(conn, path, 0755);
11639
11640 if (rc == 0) {
11641
11642 /* Create 201 "Created" response */
11646 mg_response_header_add(conn, "Content-Length", "0", -1);
11647
11648 /* Send all headers - there is no body */
11650
11651 } else {
11652 if (errno == EEXIST) {
11654 conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11655 } else if (errno == EACCES) {
11657 conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11658 } else if (errno == ENOENT) {
11660 conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11661 } else {
11663 conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
11664 }
11665 }
11666}
11667
11668
11669static void
11670put_file(struct mg_connection *conn, const char *path)
11671{
11672 struct mg_file file = STRUCT_FILE_INITIALIZER;
11673 const char *range;
11674 int64_t r1, r2;
11675 int rc;
11676
11677 if (conn == NULL) {
11678 return;
11679 }
11680
11681 if (mg_stat(conn, path, &file.stat)) {
11682 /* File already exists */
11683 conn->status_code = 200;
11684
11685 if (file.stat.is_directory) {
11686 /* This is an already existing directory,
11687 * so there is nothing to do for the server. */
11688 rc = 0;
11689
11690 } else {
11691 /* File exists and is not a directory. */
11692 /* Can it be replaced? */
11693
11694 /* Check if the server may write this file */
11695 if (access(path, W_OK) == 0) {
11696 /* Access granted */
11697 rc = 1;
11698 } else {
11700 conn,
11701 403,
11702 "Error: Put not possible\nReplacing %s is not allowed",
11703 path);
11704 return;
11705 }
11706 }
11707 } else {
11708 /* File should be created */
11709 conn->status_code = 201;
11710 rc = put_dir(conn, path);
11711 }
11712
11713 if (rc == 0) {
11714 /* put_dir returns 0 if path is a directory */
11715
11716 /* Create response */
11720 mg_response_header_add(conn, "Content-Length", "0", -1);
11721
11722 /* Send all headers - there is no body */
11724
11725 /* Request to create a directory has been fulfilled successfully.
11726 * No need to put a file. */
11727 return;
11728 }
11729
11730 if (rc == -1) {
11731 /* put_dir returns -1 if the path is too long */
11732 mg_send_http_error(conn,
11733 414,
11734 "Error: Path too long\nput_dir(%s): %s",
11735 path,
11736 strerror(ERRNO));
11737 return;
11738 }
11739
11740 if (rc == -2) {
11741 /* put_dir returns -2 if the directory can not be created */
11742 mg_send_http_error(conn,
11743 500,
11744 "Error: Can not create directory\nput_dir(%s): %s",
11745 path,
11746 strerror(ERRNO));
11747 return;
11748 }
11749
11750 /* A file should be created or overwritten. */
11751 /* Currently CivetWeb does not nead read+write access. */
11752 if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
11753 || file.access.fp == NULL) {
11754 (void)mg_fclose(&file.access);
11755 mg_send_http_error(conn,
11756 500,
11757 "Error: Can not create file\nfopen(%s): %s",
11758 path,
11759 strerror(ERRNO));
11760 return;
11761 }
11762
11763 fclose_on_exec(&file.access, conn);
11764 range = mg_get_header(conn, "Content-Range");
11765 r1 = r2 = 0;
11766 if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
11767 conn->status_code = 206; /* Partial content */
11768 fseeko(file.access.fp, r1, SEEK_SET);
11769 }
11770
11771 if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
11772 /* forward_body_data failed.
11773 * The error code has already been sent to the client,
11774 * and conn->status_code is already set. */
11775 (void)mg_fclose(&file.access);
11776 return;
11777 }
11778
11779 if (mg_fclose(&file.access) != 0) {
11780 /* fclose failed. This might have different reasons, but a likely
11781 * one is "no space on disk", http 507. */
11782 conn->status_code = 507;
11783 }
11784
11785 /* Create response (status_code has been set before) */
11789 mg_response_header_add(conn, "Content-Length", "0", -1);
11790
11791 /* Send all headers - there is no body */
11793}
11794
11795
11796static void
11797delete_file(struct mg_connection *conn, const char *path)
11798{
11799 struct de de;
11800 memset(&de.file, 0, sizeof(de.file));
11801 if (!mg_stat(conn, path, &de.file)) {
11802 /* mg_stat returns 0 if the file does not exist */
11804 404,
11805 "Error: Cannot delete file\nFile %s not found",
11806 path);
11807 return;
11808 }
11809
11810 if (de.file.is_directory) {
11811 if (remove_directory(conn, path)) {
11812 /* Delete is successful: Return 204 without content. */
11813 mg_send_http_error(conn, 204, "%s", "");
11814 } else {
11815 /* Delete is not successful: Return 500 (Server error). */
11816 mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
11817 }
11818 return;
11819 }
11820
11821 /* This is an existing file (not a directory).
11822 * Check if write permission is granted. */
11823 if (access(path, W_OK) != 0) {
11824 /* File is read only */
11826 conn,
11827 403,
11828 "Error: Delete not possible\nDeleting %s is not allowed",
11829 path);
11830 return;
11831 }
11832
11833 /* Try to delete it. */
11834 if (mg_remove(conn, path) == 0) {
11835 /* Delete was successful: Return 204 without content. */
11839 mg_response_header_add(conn, "Content-Length", "0", -1);
11841
11842 } else {
11843 /* Delete not successful (file locked). */
11845 423,
11846 "Error: Cannot delete file\nremove(%s): %s",
11847 path,
11848 strerror(ERRNO));
11849 }
11850}
11851#endif /* !NO_FILES */
11852
11853
11854#if !defined(NO_FILESYSTEMS)
11855static void
11856send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
11857
11858
11859static void
11861 const char *ssi,
11862 char *tag,
11863 int include_level)
11864{
11865 char file_name[MG_BUF_LEN], path[512], *p;
11866 struct mg_file file = STRUCT_FILE_INITIALIZER;
11867 size_t len;
11868 int truncated = 0;
11869
11870 if (conn == NULL) {
11871 return;
11872 }
11873
11874 /* sscanf() is safe here, since send_ssi_file() also uses buffer
11875 * of size MG_BUF_LEN to get the tag. So strlen(tag) is
11876 * always < MG_BUF_LEN. */
11877 if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
11878 /* File name is relative to the webserver root */
11879 file_name[511] = 0;
11880 (void)mg_snprintf(conn,
11881 &truncated,
11882 path,
11883 sizeof(path),
11884 "%s/%s",
11886 file_name);
11887
11888 } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
11889 /* File name is relative to the webserver working directory
11890 * or it is absolute system path */
11891 file_name[511] = 0;
11892 (void)
11893 mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
11894
11895 } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
11896 || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
11897 /* File name is relative to the currect document */
11898 file_name[511] = 0;
11899 (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
11900
11901 if (!truncated) {
11902 if ((p = strrchr(path, '/')) != NULL) {
11903 p[1] = '\0';
11904 }
11905 len = strlen(path);
11906 (void)mg_snprintf(conn,
11907 &truncated,
11908 path + len,
11909 sizeof(path) - len,
11910 "%s",
11911 file_name);
11912 }
11913
11914 } else {
11915 mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
11916 return;
11917 }
11918
11919 if (truncated) {
11920 mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
11921 return;
11922 }
11923
11924 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
11925 mg_cry_internal(conn,
11926 "Cannot open SSI #include: [%s]: fopen(%s): %s",
11927 tag,
11928 path,
11929 strerror(ERRNO));
11930 } else {
11931 fclose_on_exec(&file.access, conn);
11933 > 0) {
11934 send_ssi_file(conn, path, &file, include_level + 1);
11935 } else {
11936 send_file_data(conn, &file, 0, INT64_MAX);
11937 }
11938 (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
11939 }
11940}
11941
11942
11943#if !defined(NO_POPEN)
11944static void
11945do_ssi_exec(struct mg_connection *conn, char *tag)
11946{
11947 char cmd[1024] = "";
11948 struct mg_file file = STRUCT_FILE_INITIALIZER;
11949
11950 if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
11951 mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
11952 } else {
11953 cmd[1023] = 0;
11954 if ((file.access.fp = popen(cmd, "r")) == NULL) {
11955 mg_cry_internal(conn,
11956 "Cannot SSI #exec: [%s]: %s",
11957 cmd,
11958 strerror(ERRNO));
11959 } else {
11960 send_file_data(conn, &file, 0, INT64_MAX);
11961 pclose(file.access.fp);
11962 }
11963 }
11964}
11965#endif /* !NO_POPEN */
11966
11967
11968static int
11969mg_fgetc(struct mg_file *filep)
11970{
11971 if (filep == NULL) {
11972 return EOF;
11973 }
11974
11975 if (filep->access.fp != NULL) {
11976 return fgetc(filep->access.fp);
11977 } else {
11978 return EOF;
11979 }
11980}
11981
11982
11983static void
11985 const char *path,
11986 struct mg_file *filep,
11987 int include_level)
11988{
11989 char buf[MG_BUF_LEN];
11990 int ch, len, in_tag, in_ssi_tag;
11991
11992 if (include_level > 10) {
11993 mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
11994 return;
11995 }
11996
11997 in_tag = in_ssi_tag = len = 0;
11998
11999 /* Read file, byte by byte, and look for SSI include tags */
12000 while ((ch = mg_fgetc(filep)) != EOF) {
12001
12002 if (in_tag) {
12003 /* We are in a tag, either SSI tag or html tag */
12004
12005 if (ch == '>') {
12006 /* Tag is closing */
12007 buf[len++] = '>';
12008
12009 if (in_ssi_tag) {
12010 /* Handle SSI tag */
12011 buf[len] = 0;
12012
12013 if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
12014 do_ssi_include(conn, path, buf + 12, include_level + 1);
12015#if !defined(NO_POPEN)
12016 } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
12017 do_ssi_exec(conn, buf + 9);
12018#endif /* !NO_POPEN */
12019 } else {
12020 mg_cry_internal(conn,
12021 "%s: unknown SSI "
12022 "command: \"%s\"",
12023 path,
12024 buf);
12025 }
12026 len = 0;
12027 in_ssi_tag = in_tag = 0;
12028
12029 } else {
12030 /* Not an SSI tag */
12031 /* Flush buffer */
12032 (void)mg_write(conn, buf, (size_t)len);
12033 len = 0;
12034 in_tag = 0;
12035 }
12036
12037 } else {
12038 /* Tag is still open */
12039 buf[len++] = (char)(ch & 0xff);
12040
12041 if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
12042 /* All SSI tags start with <!--# */
12043 in_ssi_tag = 1;
12044 }
12045
12046 if ((len + 2) > (int)sizeof(buf)) {
12047 /* Tag to long for buffer */
12048 mg_cry_internal(conn, "%s: tag is too large", path);
12049 return;
12050 }
12051 }
12052
12053 } else {
12054
12055 /* We are not in a tag yet. */
12056 if (ch == '<') {
12057 /* Tag is opening */
12058 in_tag = 1;
12059
12060 if (len > 0) {
12061 /* Flush current buffer.
12062 * Buffer is filled with "len" bytes. */
12063 (void)mg_write(conn, buf, (size_t)len);
12064 }
12065 /* Store the < */
12066 len = 1;
12067 buf[0] = '<';
12068
12069 } else {
12070 /* No Tag */
12071 /* Add data to buffer */
12072 buf[len++] = (char)(ch & 0xff);
12073 /* Flush if buffer is full */
12074 if (len == (int)sizeof(buf)) {
12075 mg_write(conn, buf, (size_t)len);
12076 len = 0;
12077 }
12078 }
12079 }
12080 }
12081
12082 /* Send the rest of buffered data */
12083 if (len > 0) {
12084 mg_write(conn, buf, (size_t)len);
12085 }
12086}
12087
12088
12089static void
12091 const char *path,
12092 struct mg_file *filep)
12093{
12094 char date[64];
12095 time_t curtime = time(NULL);
12096 const char *cors_orig_cfg, *cors_cred_cfg;
12097 const char *cors1, *cors2, *cors3, *cors4;
12098
12099 if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
12100 return;
12101 }
12102
12103 cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
12104 if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
12105 /* Cross-origin resource sharing (CORS). */
12106 cors1 = "Access-Control-Allow-Origin";
12107 cors2 = cors_orig_cfg;
12108 } else {
12109 cors1 = cors2 = "";
12110 }
12111
12112 cors_cred_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
12113 if (cors_cred_cfg && *cors_cred_cfg && mg_get_header(conn, "Origin")) {
12114 /* Credentials CORS header */
12115 cors3 = "Access-Control-Allow-Credentials";
12116 cors4 = cors_cred_cfg;
12117 } else {
12118 cors3 = cors4 = "";
12119 }
12120
12121 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
12122 /* File exists (precondition for calling this function),
12123 * but can not be opened by the server. */
12124 mg_send_http_error(conn,
12125 500,
12126 "Error: Cannot read file\nfopen(%s): %s",
12127 path,
12128 strerror(ERRNO));
12129 } else {
12130 /* Set "must_close" for HTTP/1.x, since we do not know the
12131 * content length */
12132 conn->must_close = 1;
12133 gmt_time_string(date, sizeof(date), &curtime);
12134 fclose_on_exec(&filep->access, conn);
12135
12136 /* 200 OK response */
12137 mg_response_header_start(conn, 200);
12140 mg_response_header_add(conn, "Content-Type", "text/html", -1);
12141 if (cors1[0]) {
12142 mg_response_header_add(conn, cors1, cors2, -1);
12143 }
12144 if (cors3[0]) {
12145 mg_response_header_add(conn, cors3, cors4, -1);
12146 }
12148
12149 /* Header sent, now send body */
12150 send_ssi_file(conn, path, filep, 0);
12151 (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
12152 }
12153}
12154#endif /* NO_FILESYSTEMS */
12155
12156
12157#if !defined(NO_FILES)
12158static void
12160{
12161 if (!conn) {
12162 return;
12163 }
12164
12165 /* We do not set a "Cache-Control" header here, but leave the default.
12166 * Since browsers do not send an OPTIONS request, we can not test the
12167 * effect anyway. */
12168
12169 mg_response_header_start(conn, 200);
12170 mg_response_header_add(conn, "Content-Type", "text/html", -1);
12171 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
12172 /* Use the same as before */
12174 conn,
12175 "Allow",
12176 "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
12177 -1);
12178 mg_response_header_add(conn, "DAV", "1", -1);
12179 } else {
12180 /* TODO: Check this later for HTTP/2 */
12181 mg_response_header_add(conn, "Allow", "GET, POST", -1);
12182 }
12185}
12186
12187
12188/* Writes PROPFIND properties for a collection element */
12189static int
12191 const char *uri,
12192 const char *name,
12193 struct mg_file_stat *filep)
12194{
12195 size_t href_size, i, j;
12196 int len;
12197 char *href, mtime[64];
12198
12199 if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
12200 return 0;
12201 }
12202 /* Estimate worst case size for encoding */
12203 href_size = (strlen(uri) + strlen(name)) * 3 + 1;
12204 href = (char *)mg_malloc(href_size);
12205 if (href == NULL) {
12206 return 0;
12207 }
12208 len = mg_url_encode(uri, href, href_size);
12209 if (len >= 0) {
12210 /* Append an extra string */
12211 mg_url_encode(name, href + len, href_size - (size_t)len);
12212 }
12213 /* Directory separator should be preserved. */
12214 for (i = j = 0; href[i]; j++) {
12215 if (!strncmp(href + i, "%2f", 3)) {
12216 href[j] = '/';
12217 i += 3;
12218 } else {
12219 href[j] = href[i++];
12220 }
12221 }
12222 href[j] = '\0';
12223
12224 gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
12225 mg_printf(conn,
12226 "<d:response>"
12227 "<d:href>%s</d:href>"
12228 "<d:propstat>"
12229 "<d:prop>"
12230 "<d:resourcetype>%s</d:resourcetype>"
12231 "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
12232 "<d:getlastmodified>%s</d:getlastmodified>"
12233 "</d:prop>"
12234 "<d:status>HTTP/1.1 200 OK</d:status>"
12235 "</d:propstat>"
12236 "</d:response>\n",
12237 href,
12238 filep->is_directory ? "<d:collection/>" : "",
12239 filep->size,
12240 mtime);
12241 mg_free(href);
12242 return 1;
12243}
12244
12245
12246static int
12248{
12249 struct mg_connection *conn = (struct mg_connection *)data;
12250 if (!de || !conn
12251 || !print_props(
12252 conn, conn->request_info.local_uri, de->file_name, &de->file)) {
12253 /* stop scan */
12254 return 1;
12255 }
12256 return 0;
12257}
12258
12259
12260static void
12262 const char *path,
12263 struct mg_file_stat *filep)
12264{
12265 const char *depth = mg_get_header(conn, "Depth");
12266 char date[64];
12267 time_t curtime = time(NULL);
12268
12269 gmt_time_string(date, sizeof(date), &curtime);
12270
12271 if (!conn || !path || !filep || !conn->dom_ctx) {
12272 return;
12273 }
12274
12275 conn->must_close = 1;
12276
12277 /* return 207 "Multi-Status" */
12278 mg_response_header_start(conn, 207);
12281 mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
12283
12284 /* Content */
12285 mg_printf(conn,
12286 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12287 "<d:multistatus xmlns:d='DAV:'>\n");
12288
12289 /* Print properties for the requested resource itself */
12290 print_props(conn, conn->request_info.local_uri, "", filep);
12291
12292 /* If it is a directory, print directory entries too if Depth is not 0
12293 */
12294 if (filep->is_directory
12296 "yes")
12297 && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
12298 scan_directory(conn, path, conn, &print_dav_dir_entry);
12299 }
12300
12301 mg_printf(conn, "%s\n", "</d:multistatus>");
12302}
12303#endif
12304
12305void
12307{
12308 if (conn) {
12309 (void)pthread_mutex_lock(&conn->mutex);
12310 }
12311}
12312
12313void
12315{
12316 if (conn) {
12317 (void)pthread_mutex_unlock(&conn->mutex);
12318 }
12319}
12320
12321void
12323{
12324 if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
12325 (void)pthread_mutex_lock(&ctx->nonce_mutex);
12326 }
12327}
12328
12329void
12331{
12332 if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
12333 (void)pthread_mutex_unlock(&ctx->nonce_mutex);
12334 }
12335}
12336
12337
12338#if defined(USE_LUA)
12339#include "mod_lua.inl"
12340#endif /* USE_LUA */
12341
12342#if defined(USE_DUKTAPE)
12343#include "mod_duktape.inl"
12344#endif /* USE_DUKTAPE */
12345
12346#if defined(USE_WEBSOCKET)
12347
12348#if !defined(NO_SSL_DL)
12349#if !defined(OPENSSL_API_3_0)
12350#define SHA_API static
12351#include "sha1.inl"
12352#endif
12353#endif
12354
12355static int
12356send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
12357{
12358 static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
12359 char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
12360#if !defined(OPENSSL_API_3_0)
12361 SHA_CTX sha_ctx;
12362#endif
12363 int truncated;
12364
12365 /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
12366 mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
12367 if (truncated) {
12368 conn->must_close = 1;
12369 return 0;
12370 }
12371
12372 DEBUG_TRACE("%s", "Send websocket handshake");
12373
12374#if defined(OPENSSL_API_3_0)
12375 EVP_Digest((unsigned char *)buf, (uint32_t)strlen(buf), (unsigned char *)sha,
12376 NULL, EVP_get_digestbyname("sha1"), NULL);
12377#else
12378 SHA1_Init(&sha_ctx);
12379 SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
12380 SHA1_Final((unsigned char *)sha, &sha_ctx);
12381#endif
12382 base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
12383 mg_printf(conn,
12384 "HTTP/1.1 101 Switching Protocols\r\n"
12385 "Upgrade: websocket\r\n"
12386 "Connection: Upgrade\r\n"
12387 "Sec-WebSocket-Accept: %s\r\n",
12388 b64_sha);
12389
12390#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12391 // Send negotiated compression extension parameters
12392 websocket_deflate_response(conn);
12393#endif
12394
12396 mg_printf(conn,
12397 "Sec-WebSocket-Protocol: %s\r\n\r\n",
12399 } else {
12400 mg_printf(conn, "%s", "\r\n");
12401 }
12402
12403 return 1;
12404}
12405
12406
12407#if !defined(MG_MAX_UNANSWERED_PING)
12408/* Configuration of the maximum number of websocket PINGs that might
12409 * stay unanswered before the connection is considered broken.
12410 * Note: The name of this define may still change (until it is
12411 * defined as a compile parameter in a documentation).
12412 */
12413#define MG_MAX_UNANSWERED_PING (5)
12414#endif
12415
12416
12417static void
12418read_websocket(struct mg_connection *conn,
12419 mg_websocket_data_handler ws_data_handler,
12420 void *callback_data)
12421{
12422 /* Pointer to the beginning of the portion of the incoming websocket
12423 * message queue.
12424 * The original websocket upgrade request is never removed, so the queue
12425 * begins after it. */
12426 unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
12427 int n, error, exit_by_callback;
12428 int ret;
12429
12430 /* body_len is the length of the entire queue in bytes
12431 * len is the length of the current message
12432 * data_len is the length of the current message's data payload
12433 * header_len is the length of the current message's header */
12434 size_t i, len, mask_len = 0, header_len, body_len;
12435 uint64_t data_len = 0;
12436
12437 /* "The masking key is a 32-bit value chosen at random by the client."
12438 * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
12439 */
12440 unsigned char mask[4];
12441
12442 /* data points to the place where the message is stored when passed to
12443 * the websocket_data callback. This is either mem on the stack, or a
12444 * dynamically allocated buffer if it is too large. */
12445 unsigned char mem[4096];
12446 unsigned char mop; /* mask flag and opcode */
12447
12448
12449 /* Variables used for connection monitoring */
12450 double timeout = -1.0;
12451 int enable_ping_pong = 0;
12452 int ping_count = 0;
12453
12454 if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
12455 enable_ping_pong =
12456 !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
12457 "yes");
12458 }
12459
12460 if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
12461 timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
12462 }
12463 if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
12464 timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
12465 }
12466 if (timeout <= 0.0) {
12467 timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
12468 }
12469
12470 /* Enter data processing loop */
12471 DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
12474 conn->in_websocket_handling = 1;
12475 mg_set_thread_name("wsock");
12476
12477 /* Loop continuously, reading messages from the socket, invoking the
12478 * callback, and waiting repeatedly until an error occurs. */
12479 while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
12480 && (!conn->must_close)) {
12481 header_len = 0;
12482 DEBUG_ASSERT(conn->data_len >= conn->request_len);
12483 if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
12484 len = buf[1] & 127;
12485 mask_len = (buf[1] & 128) ? 4 : 0;
12486 if ((len < 126) && (body_len >= mask_len)) {
12487 /* inline 7-bit length field */
12488 data_len = len;
12489 header_len = 2 + mask_len;
12490 } else if ((len == 126) && (body_len >= (4 + mask_len))) {
12491 /* 16-bit length field */
12492 header_len = 4 + mask_len;
12493 data_len = ((((size_t)buf[2]) << 8) + buf[3]);
12494 } else if (body_len >= (10 + mask_len)) {
12495 /* 64-bit length field */
12496 uint32_t l1, l2;
12497 memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
12498 memcpy(&l2, &buf[6], 4);
12499 header_len = 10 + mask_len;
12500 data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
12501
12502 if (data_len > (uint64_t)0x7FFF0000ul) {
12503 /* no can do */
12505 conn,
12506 "%s",
12507 "websocket out of memory; closing connection");
12508 break;
12509 }
12510 }
12511 }
12512
12513 if ((header_len > 0) && (body_len >= header_len)) {
12514 /* Allocate space to hold websocket payload */
12515 unsigned char *data = mem;
12516
12517 if ((size_t)data_len > (size_t)sizeof(mem)) {
12518 data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
12519 conn->phys_ctx);
12520 if (data == NULL) {
12521 /* Allocation failed, exit the loop and then close the
12522 * connection */
12524 conn,
12525 "%s",
12526 "websocket out of memory; closing connection");
12527 break;
12528 }
12529 }
12530
12531 /* Copy the mask before we shift the queue and destroy it */
12532 if (mask_len > 0) {
12533 memcpy(mask, buf + header_len - mask_len, sizeof(mask));
12534 } else {
12535 memset(mask, 0, sizeof(mask));
12536 }
12537
12538 /* Read frame payload from the first message in the queue into
12539 * data and advance the queue by moving the memory in place. */
12540 DEBUG_ASSERT(body_len >= header_len);
12541 if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
12542 mop = buf[0]; /* current mask and opcode */
12543 /* Overflow case */
12544 len = body_len - header_len;
12545 memcpy(data, buf + header_len, len);
12546 error = 0;
12547 while ((uint64_t)len < data_len) {
12548 n = pull_inner(NULL,
12549 conn,
12550 (char *)(data + len),
12551 (int)(data_len - len),
12552 timeout);
12553 if (n <= -2) {
12554 error = 1;
12555 break;
12556 } else if (n > 0) {
12557 len += (size_t)n;
12558 } else {
12559 /* Timeout: should retry */
12560 /* TODO: retry condition */
12561 }
12562 }
12563 if (error) {
12565 conn,
12566 "%s",
12567 "Websocket pull failed; closing connection");
12568 if (data != mem) {
12569 mg_free(data);
12570 }
12571 break;
12572 }
12573
12574 conn->data_len = conn->request_len;
12575
12576 } else {
12577
12578 mop = buf[0]; /* current mask and opcode, overwritten by
12579 * memmove() */
12580
12581 /* Length of the message being read at the front of the
12582 * queue. Cast to 31 bit is OK, since we limited
12583 * data_len before. */
12584 len = (size_t)data_len + header_len;
12585
12586 /* Copy the data payload into the data pointer for the
12587 * callback. Cast to 31 bit is OK, since we
12588 * limited data_len */
12589 memcpy(data, buf + header_len, (size_t)data_len);
12590
12591 /* Move the queue forward len bytes */
12592 memmove(buf, buf + len, body_len - len);
12593
12594 /* Mark the queue as advanced */
12595 conn->data_len -= (int)len;
12596 }
12597
12598 /* Apply mask if necessary */
12599 if (mask_len > 0) {
12600 for (i = 0; i < (size_t)data_len; i++) {
12601 data[i] ^= mask[i & 3];
12602 }
12603 }
12604
12605 exit_by_callback = 0;
12606 if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
12607 /* filter PONG messages */
12608 DEBUG_TRACE("PONG from %s:%u",
12611 /* No unanwered PINGs left */
12612 ping_count = 0;
12613 } else if (enable_ping_pong
12614 && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
12615 /* reply PING messages */
12616 DEBUG_TRACE("Reply PING from %s:%u",
12619 ret = mg_websocket_write(conn,
12621 (char *)data,
12622 (size_t)data_len);
12623 if (ret <= 0) {
12624 /* Error: send failed */
12625 DEBUG_TRACE("Reply PONG failed (%i)", ret);
12626 break;
12627 }
12628
12629
12630 } else {
12631 /* Exit the loop if callback signals to exit (server side),
12632 * or "connection close" opcode received (client side). */
12633 if (ws_data_handler != NULL) {
12634#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12635 if (mop & 0x40) {
12636 /* Inflate the data received if bit RSV1 is set. */
12637 if (!conn->websocket_deflate_initialized) {
12638 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12639 exit_by_callback = 1;
12640 }
12641 if (!exit_by_callback) {
12642 size_t inflate_buf_size_old = 0;
12643 size_t inflate_buf_size =
12644 data_len
12645 * 4; // Initial guess of the inflated message
12646 // size. We double the memory when needed.
12647 Bytef *inflated = NULL;
12648 Bytef *new_mem = NULL;
12649 conn->websocket_inflate_state.avail_in =
12650 (uInt)(data_len + 4);
12651 conn->websocket_inflate_state.next_in = data;
12652 // Add trailing 0x00 0x00 0xff 0xff bytes
12653 data[data_len] = '\x00';
12654 data[data_len + 1] = '\x00';
12655 data[data_len + 2] = '\xff';
12656 data[data_len + 3] = '\xff';
12657 do {
12658 if (inflate_buf_size_old == 0) {
12659 new_mem =
12660 (Bytef *)mg_calloc(inflate_buf_size,
12661 sizeof(Bytef));
12662 } else {
12663 inflate_buf_size *= 2;
12664 new_mem =
12665 (Bytef *)mg_realloc(inflated,
12666 inflate_buf_size);
12667 }
12668 if (new_mem == NULL) {
12670 conn,
12671 "Out of memory: Cannot allocate "
12672 "inflate buffer of %lu bytes",
12673 (unsigned long)inflate_buf_size);
12674 exit_by_callback = 1;
12675 break;
12676 }
12677 inflated = new_mem;
12678 conn->websocket_inflate_state.avail_out =
12679 (uInt)(inflate_buf_size
12680 - inflate_buf_size_old);
12681 conn->websocket_inflate_state.next_out =
12682 inflated + inflate_buf_size_old;
12683 ret = inflate(&conn->websocket_inflate_state,
12684 Z_SYNC_FLUSH);
12685 if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
12686 || ret == Z_MEM_ERROR) {
12688 conn,
12689 "ZLIB inflate error: %i %s",
12690 ret,
12691 (conn->websocket_inflate_state.msg
12692 ? conn->websocket_inflate_state.msg
12693 : "<no error message>"));
12694 exit_by_callback = 1;
12695 break;
12696 }
12697 inflate_buf_size_old = inflate_buf_size;
12698
12699 } while (conn->websocket_inflate_state.avail_out
12700 == 0);
12701 inflate_buf_size -=
12702 conn->websocket_inflate_state.avail_out;
12703 if (!ws_data_handler(conn,
12704 mop,
12705 (char *)inflated,
12706 inflate_buf_size,
12707 callback_data)) {
12708 exit_by_callback = 1;
12709 }
12710 mg_free(inflated);
12711 }
12712 } else
12713#endif
12714 if (!ws_data_handler(conn,
12715 mop,
12716 (char *)data,
12717 (size_t)data_len,
12718 callback_data)) {
12719 exit_by_callback = 1;
12720 }
12721 }
12722 }
12723
12724 /* It a buffer has been allocated, free it again */
12725 if (data != mem) {
12726 mg_free(data);
12727 }
12728
12729 if (exit_by_callback) {
12730 DEBUG_TRACE("Callback requests to close connection from %s:%u",
12733 break;
12734 }
12735 if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
12736 /* Opcode == 8, connection close */
12737 DEBUG_TRACE("Message requests to close connection from %s:%u",
12740 break;
12741 }
12742
12743 /* Not breaking the loop, process next websocket frame. */
12744 } else {
12745 /* Read from the socket into the next available location in the
12746 * message queue. */
12747 n = pull_inner(NULL,
12748 conn,
12749 conn->buf + conn->data_len,
12750 conn->buf_size - conn->data_len,
12751 timeout);
12752 if (n <= -2) {
12753 /* Error, no bytes read */
12754 DEBUG_TRACE("PULL from %s:%u failed",
12757 break;
12758 }
12759 if (n > 0) {
12760 conn->data_len += n;
12761 /* Reset open PING count */
12762 ping_count = 0;
12763 } else {
12765 && (!conn->must_close)) {
12766 if (ping_count > MG_MAX_UNANSWERED_PING) {
12767 /* Stop sending PING */
12768 DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
12769 "- closing connection",
12770 ping_count,
12773 break;
12774 }
12775 if (enable_ping_pong) {
12776 /* Send Websocket PING message */
12777 DEBUG_TRACE("PING to %s:%u",
12780 ret = mg_websocket_write(conn,
12782 NULL,
12783 0);
12784
12785 if (ret <= 0) {
12786 /* Error: send failed */
12787 DEBUG_TRACE("Send PING failed (%i)", ret);
12788 break;
12789 }
12790 ping_count++;
12791 }
12792 }
12793 /* Timeout: should retry */
12794 /* TODO: get timeout def */
12795 }
12796 }
12797 }
12798
12799 /* Leave data processing loop */
12800 mg_set_thread_name("worker");
12801 conn->in_websocket_handling = 0;
12802 DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
12805}
12806
12807
12808static int
12809mg_websocket_write_exec(struct mg_connection *conn,
12810 int opcode,
12811 const char *data,
12812 size_t dataLen,
12813 uint32_t masking_key)
12814{
12815 unsigned char header[14];
12816 size_t headerLen;
12817 int retval;
12818
12819#if defined(GCC_DIAGNOSTIC)
12820 /* Disable spurious conversion warning for GCC */
12821#pragma GCC diagnostic push
12822#pragma GCC diagnostic ignored "-Wconversion"
12823#endif
12824
12825 /* Note that POSIX/Winsock's send() is threadsafe
12826 * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
12827 * but mongoose's mg_printf/mg_write is not (because of the loop in
12828 * push(), although that is only a problem if the packet is large or
12829 * outgoing buffer is full). */
12830
12831 /* TODO: Check if this lock should be moved to user land.
12832 * Currently the server sets this lock for websockets, but
12833 * not for any other connection. It must be set for every
12834 * conn read/written by more than one thread, no matter if
12835 * it is a websocket or regular connection. */
12836 (void)mg_lock_connection(conn);
12837
12838#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12839 size_t deflated_size = 0;
12840 Bytef *deflated = 0;
12841 // Deflate websocket messages over 100kb
12842 int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
12843
12844 if (use_deflate) {
12845 if (!conn->websocket_deflate_initialized) {
12846 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12847 return 0;
12848 }
12849
12850 // Deflating the message
12851 header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
12852 conn->websocket_deflate_state.avail_in = (uInt)dataLen;
12853 conn->websocket_deflate_state.next_in = (unsigned char *)data;
12854 deflated_size = (Bytef *)compressBound((uLong)dataLen);
12855 deflated = mg_calloc(deflated_size, sizeof(Bytef));
12856 if (deflated == NULL) {
12858 conn,
12859 "Out of memory: Cannot allocate deflate buffer of %lu bytes",
12860 (unsigned long)deflated_size);
12862 return -1;
12863 }
12864 conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
12865 conn->websocket_deflate_state.next_out = deflated;
12866 deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
12867 dataLen = deflated_size - conn->websocket_deflate_state.avail_out
12868 - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
12869 } else
12870#endif
12871 header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
12872
12873#if defined(GCC_DIAGNOSTIC)
12874#pragma GCC diagnostic pop
12875#endif
12876
12877 /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
12878 if (dataLen < 126) {
12879 /* inline 7-bit length field */
12880 header[1] = (unsigned char)dataLen;
12881 headerLen = 2;
12882 } else if (dataLen <= 0xFFFF) {
12883 /* 16-bit length field */
12884 uint16_t len = htons((uint16_t)dataLen);
12885 header[1] = 126;
12886 memcpy(header + 2, &len, 2);
12887 headerLen = 4;
12888 } else {
12889 /* 64-bit length field */
12890 uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
12891 uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
12892 header[1] = 127;
12893 memcpy(header + 2, &len1, 4);
12894 memcpy(header + 6, &len2, 4);
12895 headerLen = 10;
12896 }
12897
12898 if (masking_key) {
12899 /* add mask */
12900 header[1] |= 0x80;
12901 memcpy(header + headerLen, &masking_key, 4);
12902 headerLen += 4;
12903 }
12904
12905 retval = mg_write(conn, header, headerLen);
12906 if (retval != (int)headerLen) {
12907 /* Did not send complete header */
12908 retval = -1;
12909 } else {
12910 if (dataLen > 0) {
12911#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12912 if (use_deflate) {
12913 retval = mg_write(conn, deflated, dataLen);
12914 mg_free(deflated);
12915 } else
12916#endif
12917 retval = mg_write(conn, data, dataLen);
12918 }
12919 /* if dataLen == 0, the header length (2) is returned */
12920 }
12921
12922 /* TODO: Remove this unlock as well, when lock is removed. */
12924
12925 return retval;
12926}
12927
12928int
12930 int opcode,
12931 const char *data,
12932 size_t dataLen)
12933{
12934 return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
12935}
12936
12937
12938static void
12939mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
12940{
12941 size_t i = 0;
12942
12943 i = 0;
12944 if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
12945 /* Convert in 32 bit words, if data is 4 byte aligned */
12946 while (i < (in_len - 3)) {
12947 *(uint32_t *)(void *)(out + i) =
12948 *(uint32_t *)(void *)(in + i) ^ masking_key;
12949 i += 4;
12950 }
12951 }
12952 if (i != in_len) {
12953 /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
12954 while (i < in_len) {
12955 *(uint8_t *)(void *)(out + i) =
12956 *(uint8_t *)(void *)(in + i)
12957 ^ *(((uint8_t *)&masking_key) + (i % 4));
12958 i++;
12959 }
12960 }
12961}
12962
12963
12964int
12966 int opcode,
12967 const char *data,
12968 size_t dataLen)
12969{
12970 int retval = -1;
12971 char *masked_data =
12972 (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
12973 uint32_t masking_key = 0;
12974
12975 if (masked_data == NULL) {
12976 /* Return -1 in an error case */
12977 mg_cry_internal(conn,
12978 "%s",
12979 "Cannot allocate buffer for masked websocket response: "
12980 "Out of memory");
12981 return -1;
12982 }
12983
12984 do {
12985 /* Get a masking key - but not 0 */
12986 masking_key = (uint32_t)get_random();
12987 } while (masking_key == 0);
12988
12989 mask_data(data, dataLen, masking_key, masked_data);
12990
12991 retval = mg_websocket_write_exec(
12992 conn, opcode, masked_data, dataLen, masking_key);
12993 mg_free(masked_data);
12994
12995 return retval;
12996}
12997
12998
12999static void
13000handle_websocket_request(struct mg_connection *conn,
13001 const char *path,
13002 int is_callback_resource,
13003 struct mg_websocket_subprotocols *subprotocols,
13004 mg_websocket_connect_handler ws_connect_handler,
13005 mg_websocket_ready_handler ws_ready_handler,
13006 mg_websocket_data_handler ws_data_handler,
13007 mg_websocket_close_handler ws_close_handler,
13008 void *cbData)
13009{
13010 const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
13011 const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
13012 ptrdiff_t lua_websock = 0;
13013
13014#if !defined(USE_LUA)
13015 (void)path;
13016#endif
13017
13018 /* Step 1: Check websocket protocol version. */
13019 /* Step 1.1: Check Sec-WebSocket-Key. */
13020 if (!websock_key) {
13021 /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
13022 * requires a Sec-WebSocket-Key header.
13023 */
13024 /* It could be the hixie draft version
13025 * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
13026 */
13027 const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
13028 const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
13029 char key3[8];
13030
13031 if ((key1 != NULL) && (key2 != NULL)) {
13032 /* This version uses 8 byte body data in a GET request */
13033 conn->content_len = 8;
13034 if (8 == mg_read(conn, key3, 8)) {
13035 /* This is the hixie version */
13036 mg_send_http_error(conn,
13037 426,
13038 "%s",
13039 "Protocol upgrade to RFC 6455 required");
13040 return;
13041 }
13042 }
13043 /* This is an unknown version */
13044 mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
13045 return;
13046 }
13047
13048 /* Step 1.2: Check websocket protocol version. */
13049 /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
13050 if ((version == NULL) || (strcmp(version, "13") != 0)) {
13051 /* Reject wrong versions */
13052 mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
13053 return;
13054 }
13055
13056 /* Step 1.3: Could check for "Host", but we do not really nead this
13057 * value for anything, so just ignore it. */
13058
13059 /* Step 2: If a callback is responsible, call it. */
13060 if (is_callback_resource) {
13061 /* Step 2.1 check and select subprotocol */
13062 const char *protocols[64]; // max 64 headers
13063 int nbSubprotocolHeader = get_req_headers(&conn->request_info,
13064 "Sec-WebSocket-Protocol",
13065 protocols,
13066 64);
13067 if ((nbSubprotocolHeader > 0) && subprotocols) {
13068 int cnt = 0;
13069 int idx;
13070 unsigned long len;
13071 const char *sep, *curSubProtocol,
13072 *acceptedWebSocketSubprotocol = NULL;
13073
13074
13075 /* look for matching subprotocol */
13076 do {
13077 const char *protocol = protocols[cnt];
13078
13079 do {
13080 sep = strchr(protocol, ',');
13081 curSubProtocol = protocol;
13082 len = sep ? (unsigned long)(sep - protocol)
13083 : (unsigned long)strlen(protocol);
13084 while (sep && isspace((unsigned char)*++sep))
13085 ; // ignore leading whitespaces
13086 protocol = sep;
13087
13088 for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
13089 if ((strlen(subprotocols->subprotocols[idx]) == len)
13090 && (strncmp(curSubProtocol,
13091 subprotocols->subprotocols[idx],
13092 len)
13093 == 0)) {
13094 acceptedWebSocketSubprotocol =
13095 subprotocols->subprotocols[idx];
13096 break;
13097 }
13098 }
13099 } while (sep && !acceptedWebSocketSubprotocol);
13100 } while (++cnt < nbSubprotocolHeader
13101 && !acceptedWebSocketSubprotocol);
13102
13104 acceptedWebSocketSubprotocol;
13105
13106 } else if (nbSubprotocolHeader > 0) {
13107 /* keep legacy behavior */
13108 const char *protocol = protocols[0];
13109
13110 /* The protocol is a comma separated list of names. */
13111 /* The server must only return one value from this list. */
13112 /* First check if it is a list or just a single value. */
13113 const char *sep = strrchr(protocol, ',');
13114 if (sep == NULL) {
13115 /* Just a single protocol -> accept it. */
13117 } else {
13118 /* Multiple protocols -> accept the last one. */
13119 /* This is just a quick fix if the client offers multiple
13120 * protocols. The handler should have a list of accepted
13121 * protocols on his own
13122 * and use it to select one protocol among those the client
13123 * has
13124 * offered.
13125 */
13126 while (isspace((unsigned char)*++sep)) {
13127 ; /* ignore leading whitespaces */
13128 }
13130 }
13131 }
13132
13133#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13134 websocket_deflate_negotiate(conn);
13135#endif
13136
13137 if ((ws_connect_handler != NULL)
13138 && (ws_connect_handler(conn, cbData) != 0)) {
13139 /* C callback has returned non-zero, do not proceed with
13140 * handshake.
13141 */
13142 /* Note that C callbacks are no longer called when Lua is
13143 * responsible, so C can no longer filter callbacks for Lua. */
13144 return;
13145 }
13146 }
13147
13148#if defined(USE_LUA)
13149 /* Step 3: No callback. Check if Lua is responsible. */
13150 else {
13151 /* Step 3.1: Check if Lua is responsible. */
13152 if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
13153 lua_websock = match_prefix_strlen(
13154 conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
13155 }
13156
13157 if (lua_websock) {
13158 /* Step 3.2: Lua is responsible: call it. */
13159 conn->lua_websocket_state = lua_websocket_new(path, conn);
13160 if (!conn->lua_websocket_state) {
13161 /* Lua rejected the new client */
13162 return;
13163 }
13164 }
13165 }
13166#endif
13167
13168 /* Step 4: Check if there is a responsible websocket handler. */
13169 if (!is_callback_resource && !lua_websock) {
13170 /* There is no callback, and Lua is not responsible either. */
13171 /* Reply with a 404 Not Found. We are still at a standard
13172 * HTTP request here, before the websocket handshake, so
13173 * we can still send standard HTTP error replies. */
13174 mg_send_http_error(conn, 404, "%s", "Not found");
13175 return;
13176 }
13177
13178 /* Step 5: The websocket connection has been accepted */
13179 if (!send_websocket_handshake(conn, websock_key)) {
13180 mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
13181 return;
13182 }
13183
13184 /* Step 6: Call the ready handler */
13185 if (is_callback_resource) {
13186 if (ws_ready_handler != NULL) {
13187 ws_ready_handler(conn, cbData);
13188 }
13189#if defined(USE_LUA)
13190 } else if (lua_websock) {
13191 if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
13192 /* the ready handler returned false */
13193 return;
13194 }
13195#endif
13196 }
13197
13198 /* Step 7: Enter the read loop */
13199 if (is_callback_resource) {
13200 read_websocket(conn, ws_data_handler, cbData);
13201#if defined(USE_LUA)
13202 } else if (lua_websock) {
13203 read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
13204#endif
13205 }
13206
13207#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13208 /* Step 8: Close the deflate & inflate buffers */
13209 if (conn->websocket_deflate_initialized) {
13210 deflateEnd(&conn->websocket_deflate_state);
13211 inflateEnd(&conn->websocket_inflate_state);
13212 }
13213#endif
13214
13215 /* Step 9: Call the close handler */
13216 if (ws_close_handler) {
13217 ws_close_handler(conn, cbData);
13218 }
13219}
13220#endif /* !USE_WEBSOCKET */
13221
13222
13223/* Is upgrade request:
13224 * 0 = regular HTTP/1.0 or HTTP/1.1 request
13225 * 1 = upgrade to websocket
13226 * 2 = upgrade to HTTP/2
13227 * -1 = upgrade to unknown protocol
13228 */
13229static int
13231{
13232 const char *upgrade, *connection;
13233
13234 /* A websocket protocoll has the following HTTP headers:
13235 *
13236 * Connection: Upgrade
13237 * Upgrade: Websocket
13238 */
13239
13240 connection = mg_get_header(conn, "Connection");
13241 if (connection == NULL) {
13242 return PROTOCOL_TYPE_HTTP1;
13243 }
13244 if (!mg_strcasestr(connection, "upgrade")) {
13245 return PROTOCOL_TYPE_HTTP1;
13246 }
13247
13248 upgrade = mg_get_header(conn, "Upgrade");
13249 if (upgrade == NULL) {
13250 /* "Connection: Upgrade" without "Upgrade" Header --> Error */
13251 return -1;
13252 }
13253
13254 /* Upgrade to ... */
13255 if (0 != mg_strcasestr(upgrade, "websocket")) {
13256 /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
13257 * "Sec-WebSocket-Version" are also required.
13258 * Don't check them here, since even an unsupported websocket protocol
13259 * request still IS a websocket request (in contrast to a standard HTTP
13260 * request). It will fail later in handle_websocket_request.
13261 */
13262 return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
13263 }
13264 if (0 != mg_strcasestr(upgrade, "h2")) {
13265 return PROTOCOL_TYPE_HTTP2; /* Websocket */
13266 }
13267
13268 /* Upgrade to another protocol */
13269 return -1;
13270}
13271
13272
13273static int
13274parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
13275{
13276 int n;
13277 unsigned int a, b, c, d, slash;
13278
13279 if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
13280 != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
13281 // integer value, but function will not report conversion
13282 // errors; consider using 'strtol' instead
13283 slash = 32;
13284 if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
13285 != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
13286 // an integer value, but function will not report conversion
13287 // errors; consider using 'strtol' instead
13288 n = 0;
13289 }
13290 }
13291
13292 if ((n > 0) && ((size_t)n == vec->len)) {
13293 if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
13294 /* IPv4 format */
13295 if (sa->sa.sa_family == AF_INET) {
13296 uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
13297 uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
13298 | ((uint32_t)c << 8) | (uint32_t)d;
13299 uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
13300 return (ip & mask) == net;
13301 }
13302 return 0;
13303 }
13304 }
13305#if defined(USE_IPV6)
13306 else {
13307 char ad[50];
13308 const char *p;
13309
13310 if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
13311 slash = 128;
13312 if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
13313 n = 0;
13314 }
13315 }
13316
13317 if ((n <= 0) && no_strict) {
13318 /* no square brackets? */
13319 p = strchr(vec->ptr, '/');
13320 if (p && (p < (vec->ptr + vec->len))) {
13321 if (((size_t)(p - vec->ptr) < sizeof(ad))
13322 && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
13323 n += (int)(p - vec->ptr);
13324 mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
13325 } else {
13326 n = 0;
13327 }
13328 } else if (vec->len < sizeof(ad)) {
13329 n = (int)vec->len;
13330 slash = 128;
13331 mg_strlcpy(ad, vec->ptr, vec->len + 1);
13332 }
13333 }
13334
13335 if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
13336 p = ad;
13337 c = 0;
13338 /* zone indexes are unsupported, at least two colons are needed */
13339 while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
13340 if (*(p++) == ':') {
13341 c++;
13342 }
13343 }
13344 if ((*p == '\0') && (c >= 2)) {
13345 struct sockaddr_in6 sin6;
13346 unsigned int i;
13347
13348 /* for strict validation, an actual IPv6 argument is needed */
13349 if (sa->sa.sa_family != AF_INET6) {
13350 return 0;
13351 }
13352 if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
13353 /* IPv6 format */
13354 for (i = 0; i < 16; i++) {
13355 uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
13356 uint8_t net = sin6.sin6_addr.s6_addr[i];
13357 uint8_t mask = 0;
13358
13359 if (8 * i + 8 < slash) {
13360 mask = 0xFFu;
13361 } else if (8 * i < slash) {
13362 mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
13363 }
13364 if ((ip & mask) != net) {
13365 return 0;
13366 }
13367 }
13368 return 1;
13369 }
13370 }
13371 }
13372 }
13373#else
13374 (void)no_strict;
13375#endif
13376
13377 /* malformed */
13378 return -1;
13379}
13380
13381
13382static int
13383set_throttle(const char *spec, const union usa *rsa, const char *uri)
13384{
13385 int throttle = 0;
13386 struct vec vec, val;
13387 char mult;
13388 double v;
13389
13390 while ((spec = next_option(spec, &vec, &val)) != NULL) {
13391 mult = ',';
13392 if ((val.ptr == NULL)
13393 || (sscanf(val.ptr, "%lf%c", &v, &mult)
13394 < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
13395 // to an integer value, but function will not report
13396 // conversion errors; consider using 'strtol' instead
13397 || (v < 0)
13398 || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
13399 && (mult != ','))) {
13400 continue;
13401 }
13402 v *= (lowercase(&mult) == 'k')
13403 ? 1024
13404 : ((lowercase(&mult) == 'm') ? 1048576 : 1);
13405 if (vec.len == 1 && vec.ptr[0] == '*') {
13406 throttle = (int)v;
13407 } else {
13408 int matched = parse_match_net(&vec, rsa, 0);
13409 if (matched >= 0) {
13410 /* a valid IP subnet */
13411 if (matched) {
13412 throttle = (int)v;
13413 }
13414 } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
13415 throttle = (int)v;
13416 }
13417 }
13418 }
13419
13420 return throttle;
13421}
13422
13423
13424/* The mg_upload function is superseeded by mg_handle_form_request. */
13425#include "handle_form.inl"
13426
13427
13428static int
13430{
13431 unsigned int i;
13432 int idx = -1;
13433 if (ctx) {
13434 for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
13435 idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
13436 }
13437 }
13438 return idx;
13439}
13440
13441
13442/* Return host (without port) */
13443static void
13444get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
13445{
13446 const char *host_header =
13447 get_header(ri->http_headers, ri->num_headers, "Host");
13448
13449 host->ptr = NULL;
13450 host->len = 0;
13451
13452 if (host_header != NULL) {
13453 const char *pos;
13454
13455 /* If the "Host" is an IPv6 address, like [::1], parse until ]
13456 * is found. */
13457 if (*host_header == '[') {
13458 pos = strchr(host_header, ']');
13459 if (!pos) {
13460 /* Malformed hostname starts with '[', but no ']' found */
13461 DEBUG_TRACE("%s", "Host name format error '[' without ']'");
13462 return;
13463 }
13464 /* terminate after ']' */
13465 host->ptr = host_header;
13466 host->len = (size_t)(pos + 1 - host_header);
13467 } else {
13468 /* Otherwise, a ':' separates hostname and port number */
13469 pos = strchr(host_header, ':');
13470 if (pos != NULL) {
13471 host->len = (size_t)(pos - host_header);
13472 } else {
13473 host->len = strlen(host_header);
13474 }
13475 host->ptr = host_header;
13476 }
13477 }
13478}
13479
13480
13481static int
13483{
13484 struct vec host;
13485
13487
13488 if (host.ptr) {
13489 if (conn->ssl) {
13490 /* This is a HTTPS connection, maybe we have a hostname
13491 * from SNI (set in ssl_servername_callback). */
13492 const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
13493 if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
13494 /* We are not using the default domain */
13495 if ((strlen(sslhost) != host.len)
13496 || mg_strncasecmp(host.ptr, sslhost, host.len)) {
13497 /* Mismatch between SNI domain and HTTP domain */
13498 DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
13499 sslhost,
13500 (int)host.len,
13501 host.ptr);
13502 return 0;
13503 }
13504 }
13505
13506 } else {
13507 struct mg_domain_context *dom = &(conn->phys_ctx->dd);
13508 while (dom) {
13509 const char *domName = dom->config[AUTHENTICATION_DOMAIN];
13510 size_t domNameLen = strlen(domName);
13511 if ((domNameLen == host.len)
13512 && !mg_strncasecmp(host.ptr, domName, host.len)) {
13513
13514 /* Found matching domain */
13515 DEBUG_TRACE("HTTP domain %s found",
13517
13518 /* TODO: Check if this is a HTTP or HTTPS domain */
13519 conn->dom_ctx = dom;
13520 break;
13521 }
13523 dom = dom->next;
13525 }
13526 }
13527
13528 DEBUG_TRACE("HTTP%s Host: %.*s",
13529 conn->ssl ? "S" : "",
13530 (int)host.len,
13531 host.ptr);
13532
13533 } else {
13534 DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
13535 return 1;
13536 }
13537
13538 return 1;
13539}
13540
13541
13542static void
13544{
13545 char target_url[MG_BUF_LEN];
13546 int truncated = 0;
13547 const char *expect_proto =
13548 (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
13549
13550 /* Use "308 Permanent Redirect" */
13551 int redirect_code = 308;
13552
13553 /* In any case, close the current connection */
13554 conn->must_close = 1;
13555
13556 /* Send host, port, uri and (if it exists) ?query_string */
13558 conn, target_url, sizeof(target_url), expect_proto, port, NULL)
13559 < 0) {
13560 truncated = 1;
13561 } else if (conn->request_info.query_string != NULL) {
13562 size_t slen1 = strlen(target_url);
13563 size_t slen2 = strlen(conn->request_info.query_string);
13564 if ((slen1 + slen2 + 2) < sizeof(target_url)) {
13565 target_url[slen1] = '?';
13566 memcpy(target_url + slen1 + 1,
13568 slen2);
13569 target_url[slen1 + slen2 + 1] = 0;
13570 } else {
13571 truncated = 1;
13572 }
13573 }
13574
13575 /* Check overflow in location buffer (will not occur if MG_BUF_LEN
13576 * is used as buffer size) */
13577 if (truncated) {
13578 mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
13579 return;
13580 }
13581
13582 /* Use redirect helper function */
13583 mg_send_http_redirect(conn, target_url, redirect_code);
13584}
13585
13586
13587static void
13589 struct mg_domain_context *dom_ctx,
13590 const char *uri,
13591 int handler_type,
13592 int is_delete_request,
13593 mg_request_handler handler,
13594 struct mg_websocket_subprotocols *subprotocols,
13595 mg_websocket_connect_handler connect_handler,
13596 mg_websocket_ready_handler ready_handler,
13597 mg_websocket_data_handler data_handler,
13598 mg_websocket_close_handler close_handler,
13599 mg_authorization_handler auth_handler,
13600 void *cbdata)
13601{
13602 struct mg_handler_info *tmp_rh, **lastref;
13603 size_t urilen = strlen(uri);
13604
13606 DEBUG_ASSERT(handler == NULL);
13607 DEBUG_ASSERT(is_delete_request || connect_handler != NULL
13608 || ready_handler != NULL || data_handler != NULL
13609 || close_handler != NULL);
13610
13611 DEBUG_ASSERT(auth_handler == NULL);
13612 if (handler != NULL) {
13613 return;
13614 }
13615 if (!is_delete_request && (connect_handler == NULL)
13616 && (ready_handler == NULL) && (data_handler == NULL)
13617 && (close_handler == NULL)) {
13618 return;
13619 }
13620 if (auth_handler != NULL) {
13621 return;
13622 }
13623
13624 } else if (handler_type == REQUEST_HANDLER) {
13625 DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13626 && data_handler == NULL && close_handler == NULL);
13627 DEBUG_ASSERT(is_delete_request || (handler != NULL));
13628 DEBUG_ASSERT(auth_handler == NULL);
13629
13630 if ((connect_handler != NULL) || (ready_handler != NULL)
13631 || (data_handler != NULL) || (close_handler != NULL)) {
13632 return;
13633 }
13634 if (!is_delete_request && (handler == NULL)) {
13635 return;
13636 }
13637 if (auth_handler != NULL) {
13638 return;
13639 }
13640
13641 } else if (handler_type == AUTH_HANDLER) {
13642 DEBUG_ASSERT(handler == NULL);
13643 DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13644 && data_handler == NULL && close_handler == NULL);
13645 DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
13646 if (handler != NULL) {
13647 return;
13648 }
13649 if ((connect_handler != NULL) || (ready_handler != NULL)
13650 || (data_handler != NULL) || (close_handler != NULL)) {
13651 return;
13652 }
13653 if (!is_delete_request && (auth_handler == NULL)) {
13654 return;
13655 }
13656 } else {
13657 /* Unknown handler type. */
13658 return;
13659 }
13660
13661 if (!phys_ctx || !dom_ctx) {
13662 /* no context available */
13663 return;
13664 }
13665
13666 mg_lock_context(phys_ctx);
13667
13668 /* first try to find an existing handler */
13669 do {
13670 lastref = &(dom_ctx->handlers);
13671 for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
13672 tmp_rh = tmp_rh->next) {
13673 if (tmp_rh->handler_type == handler_type
13674 && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
13675 if (!is_delete_request) {
13676 /* update existing handler */
13678 /* Wait for end of use before updating */
13679 if (tmp_rh->refcount) {
13680 mg_unlock_context(phys_ctx);
13681 mg_sleep(1);
13682 mg_lock_context(phys_ctx);
13683 /* tmp_rh might have been freed, search again. */
13684 break;
13685 }
13686 /* Ok, the handler is no more use -> Update it */
13687 tmp_rh->handler = handler;
13688 } else if (handler_type == WEBSOCKET_HANDLER) {
13689 tmp_rh->subprotocols = subprotocols;
13691 tmp_rh->ready_handler = ready_handler;
13692 tmp_rh->data_handler = data_handler;
13693 tmp_rh->close_handler = close_handler;
13694 } else { /* AUTH_HANDLER */
13695 tmp_rh->auth_handler = auth_handler;
13696 }
13697 tmp_rh->cbdata = cbdata;
13698 } else {
13699 /* remove existing handler */
13701 /* Wait for end of use before removing */
13702 if (tmp_rh->refcount) {
13703 tmp_rh->removing = 1;
13704 mg_unlock_context(phys_ctx);
13705 mg_sleep(1);
13706 mg_lock_context(phys_ctx);
13707 /* tmp_rh might have been freed, search again. */
13708 break;
13709 }
13710 /* Ok, the handler is no more used */
13711 }
13712 *lastref = tmp_rh->next;
13713 mg_free(tmp_rh->uri);
13714 mg_free(tmp_rh);
13715 }
13716 mg_unlock_context(phys_ctx);
13717 return;
13718 }
13719 lastref = &(tmp_rh->next);
13720 }
13721 } while (tmp_rh != NULL);
13722
13723 if (is_delete_request) {
13724 /* no handler to set, this was a remove request to a non-existing
13725 * handler */
13726 mg_unlock_context(phys_ctx);
13727 return;
13728 }
13729
13730 tmp_rh =
13731 (struct mg_handler_info *)mg_calloc_ctx(1,
13732 sizeof(struct mg_handler_info),
13733 phys_ctx);
13734 if (tmp_rh == NULL) {
13735 mg_unlock_context(phys_ctx);
13736 mg_cry_ctx_internal(phys_ctx,
13737 "%s",
13738 "Cannot create new request handler struct, OOM");
13739 return;
13740 }
13741 tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
13742 if (!tmp_rh->uri) {
13743 mg_unlock_context(phys_ctx);
13744 mg_free(tmp_rh);
13745 mg_cry_ctx_internal(phys_ctx,
13746 "%s",
13747 "Cannot create new request handler struct, OOM");
13748 return;
13749 }
13750 tmp_rh->uri_len = urilen;
13752 tmp_rh->refcount = 0;
13753 tmp_rh->removing = 0;
13754 tmp_rh->handler = handler;
13755 } else if (handler_type == WEBSOCKET_HANDLER) {
13756 tmp_rh->subprotocols = subprotocols;
13758 tmp_rh->ready_handler = ready_handler;
13759 tmp_rh->data_handler = data_handler;
13760 tmp_rh->close_handler = close_handler;
13761 } else { /* AUTH_HANDLER */
13762 tmp_rh->auth_handler = auth_handler;
13763 }
13764 tmp_rh->cbdata = cbdata;
13765 tmp_rh->handler_type = handler_type;
13766 tmp_rh->next = NULL;
13767
13768 *lastref = tmp_rh;
13769 mg_unlock_context(phys_ctx);
13770}
13771
13772
13773void
13775 const char *uri,
13777 void *cbdata)
13778{
13780 &(ctx->dd),
13781 uri,
13783 handler == NULL,
13784 handler,
13785 NULL,
13786 NULL,
13787 NULL,
13788 NULL,
13789 NULL,
13790 NULL,
13791 cbdata);
13792}
13793
13794
13795void
13797 const char *uri,
13802 void *cbdata)
13803{
13805 uri,
13806 NULL,
13811 cbdata);
13812}
13813
13814
13815void
13817 struct mg_context *ctx,
13818 const char *uri,
13824 void *cbdata)
13825{
13826 int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
13827 && (data_handler == NULL)
13828 && (close_handler == NULL);
13830 &(ctx->dd),
13831 uri,
13833 is_delete_request,
13834 NULL,
13840 NULL,
13841 cbdata);
13842}
13843
13844
13845void
13847 const char *uri,
13849 void *cbdata)
13850{
13852 &(ctx->dd),
13853 uri,
13855 handler == NULL,
13856 NULL,
13857 NULL,
13858 NULL,
13859 NULL,
13860 NULL,
13861 NULL,
13862 handler,
13863 cbdata);
13864}
13865
13866
13867static int
13869 int handler_type,
13877 void **cbdata,
13878 struct mg_handler_info **handler_info)
13879{
13880 const struct mg_request_info *request_info = mg_get_request_info(conn);
13881 if (request_info) {
13882 const char *uri = request_info->local_uri;
13883 size_t urilen = strlen(uri);
13884 struct mg_handler_info *tmp_rh;
13885 int step, matched;
13886
13887 if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
13888 return 0;
13889 }
13890
13892
13893 for (step = 0; step < 3; step++) {
13894 for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
13895 tmp_rh = tmp_rh->next) {
13896 if (tmp_rh->handler_type != handler_type) {
13897 continue;
13898 }
13899 if (step == 0) {
13900 /* first try for an exact match */
13901 matched = (tmp_rh->uri_len == urilen)
13902 && (strcmp(tmp_rh->uri, uri) == 0);
13903 } else if (step == 1) {
13904 /* next try for a partial match, we will accept
13905 uri/something */
13906 matched =
13907 (tmp_rh->uri_len < urilen)
13908 && (uri[tmp_rh->uri_len] == '/')
13909 && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
13910 } else {
13911 /* finally try for pattern match */
13912 matched =
13913 match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
13914 }
13915 if (matched) {
13917 *subprotocols = tmp_rh->subprotocols;
13919 *ready_handler = tmp_rh->ready_handler;
13920 *data_handler = tmp_rh->data_handler;
13921 *close_handler = tmp_rh->close_handler;
13922 } else if (handler_type == REQUEST_HANDLER) {
13923 if (tmp_rh->removing) {
13924 /* Treat as none found */
13925 step = 2;
13926 break;
13927 }
13928 *handler = tmp_rh->handler;
13929 /* Acquire handler and give it back */
13930 tmp_rh->refcount++;
13931 *handler_info = tmp_rh;
13932 } else { /* AUTH_HANDLER */
13933 *auth_handler = tmp_rh->auth_handler;
13934 }
13935 *cbdata = tmp_rh->cbdata;
13937 return 1;
13938 }
13939 }
13940 }
13941
13943 }
13944 return 0; /* none found */
13945}
13946
13947
13948/* Check if the script file is in a path, allowed for script files.
13949 * This can be used if uploading files is possible not only for the server
13950 * admin, and the upload mechanism does not check the file extension.
13951 */
13952static int
13953is_in_script_path(const struct mg_connection *conn, const char *path)
13954{
13955 /* TODO (Feature): Add config value for allowed script path.
13956 * Default: All allowed. */
13957 (void)conn;
13958 (void)path;
13959 return 1;
13960}
13961
13962
13963#if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
13964static int
13965experimental_websocket_client_data_wrapper(struct mg_connection *conn,
13966 int bits,
13967 char *data,
13968 size_t len,
13969 void *cbdata)
13970{
13971 struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13972 if (pcallbacks->websocket_data) {
13973 return pcallbacks->websocket_data(conn, bits, data, len);
13974 }
13975 /* No handler set - assume "OK" */
13976 return 1;
13977}
13978
13979
13980static void
13981experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
13982 void *cbdata)
13983{
13984 struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13985 if (pcallbacks->connection_close) {
13986 pcallbacks->connection_close(conn);
13987 }
13988}
13989#endif
13990
13991
13992/* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
13993 */
13994static void
13996 struct mg_handler_info *handler_info)
13997{
13998 if (handler_info != NULL) {
13999 /* Use context lock for ref counter */
14001 handler_info->refcount--;
14003 }
14004}
14005
14006
14007/* This is the heart of the Civetweb's logic.
14008 * This function is called when the request is read, parsed and validated,
14009 * and Civetweb must decide what action to take: serve a file, or
14010 * a directory, or call embedded function, etcetera. */
14011static void
14013{
14014 struct mg_request_info *ri = &conn->request_info;
14015 char path[UTF8_PATH_MAX];
14016 int uri_len, ssl_index;
14017 int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
14018 is_put_or_delete_request = 0, is_callback_resource = 0,
14019 is_template_text_file = 0;
14020 int i;
14021 struct mg_file file = STRUCT_FILE_INITIALIZER;
14022 mg_request_handler callback_handler = NULL;
14023 struct mg_handler_info *handler_info = NULL;
14025 mg_websocket_connect_handler ws_connect_handler = NULL;
14026 mg_websocket_ready_handler ws_ready_handler = NULL;
14027 mg_websocket_data_handler ws_data_handler = NULL;
14028 mg_websocket_close_handler ws_close_handler = NULL;
14029 void *callback_data = NULL;
14030 mg_authorization_handler auth_handler = NULL;
14031 void *auth_callback_data = NULL;
14032 int handler_type;
14033 time_t curtime = time(NULL);
14034 char date[64];
14035 char *tmp;
14036
14037 path[0] = 0;
14038
14039 /* 0. Reset internal state (required for HTTP/2 proxy) */
14040 conn->request_state = 0;
14041
14042 /* 1. get the request url */
14043 /* 1.1. split into url and query string */
14044 if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
14045 != NULL) {
14046 *((char *)conn->request_info.query_string++) = '\0';
14047 }
14048
14049 /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
14050 if (!conn->client.is_ssl && conn->client.ssl_redir) {
14051 ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
14052 if (ssl_index >= 0) {
14053 int port = (int)ntohs(USA_IN_PORT_UNSAFE(
14054 &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
14055 redirect_to_https_port(conn, port);
14056 } else {
14057 /* A http to https forward port has been specified,
14058 * but no https port to forward to. */
14059 mg_send_http_error(conn,
14060 503,
14061 "%s",
14062 "Error: SSL forward not configured properly");
14063 mg_cry_internal(conn,
14064 "%s",
14065 "Can not redirect to SSL, no SSL port available");
14066 }
14067 return;
14068 }
14069 uri_len = (int)strlen(ri->local_uri);
14070
14071 /* 1.3. decode url (if config says so) */
14072 if (should_decode_url(conn)) {
14074 ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
14075 }
14076
14077 /* URL decode the query-string only if explicity set in the configuration */
14078 if (conn->request_info.query_string) {
14079 if (should_decode_query_string(conn)) {
14081 }
14082 }
14083
14084 /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
14085 * possible. The fact that we cleaned the URI is stored in that the
14086 * pointer to ri->local_ur and ri->local_uri_raw are now different.
14087 * ri->local_uri_raw still points to memory allocated in
14088 * worker_thread_run(). ri->local_uri is private to the request so we
14089 * don't have to use preallocated memory here. */
14090 tmp = mg_strdup(ri->local_uri_raw);
14091 if (!tmp) {
14092 /* Out of memory. We cannot do anything reasonable here. */
14093 return;
14094 }
14096 ri->local_uri = tmp;
14097
14098 /* step 1. completed, the url is known now */
14099 DEBUG_TRACE("URL: %s", ri->local_uri);
14100
14101 /* 2. if this ip has limited speed, set it for this connection */
14103 &conn->client.rsa,
14104 ri->local_uri);
14105
14106 /* 3. call a "handle everything" callback, if registered */
14107 if (conn->phys_ctx->callbacks.begin_request != NULL) {
14108 /* Note that since V1.7 the "begin_request" function is called
14109 * before an authorization check. If an authorization check is
14110 * required, use a request_handler instead. */
14111 i = conn->phys_ctx->callbacks.begin_request(conn);
14112 if (i > 0) {
14113 /* callback already processed the request. Store the
14114 return value as a status code for the access log. */
14115 conn->status_code = i;
14116 if (!conn->must_close) {
14118 }
14119 return;
14120 } else if (i == 0) {
14121 /* civetweb should process the request */
14122 } else {
14123 /* unspecified - may change with the next version */
14124 return;
14125 }
14126 }
14127
14128 /* request not yet handled by a handler or redirect, so the request
14129 * is processed here */
14130
14131 /* 4. Check for CORS preflight requests and handle them (if configured).
14132 * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
14133 */
14134 if (!strcmp(ri->request_method, "OPTIONS")) {
14135 /* Send a response to CORS preflights only if
14136 * access_control_allow_methods is not NULL and not an empty string.
14137 * In this case, scripts can still handle CORS. */
14138 const char *cors_meth_cfg =
14140 const char *cors_orig_cfg =
14142 const char *cors_cred_cfg =
14144 const char *cors_origin =
14145 get_header(ri->http_headers, ri->num_headers, "Origin");
14146 const char *cors_acrm = get_header(ri->http_headers,
14147 ri->num_headers,
14148 "Access-Control-Request-Method");
14149
14150 /* Todo: check if cors_origin is in cors_orig_cfg.
14151 * Or, let the client check this. */
14152
14153 if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
14154 && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
14155 && (cors_origin != NULL) && (cors_acrm != NULL)) {
14156 /* This is a valid CORS preflight, and the server is configured
14157 * to handle it automatically. */
14158 const char *cors_acrh =
14160 ri->num_headers,
14161 "Access-Control-Request-Headers");
14162
14163 gmt_time_string(date, sizeof(date), &curtime);
14164 mg_printf(conn,
14165 "HTTP/1.1 200 OK\r\n"
14166 "Date: %s\r\n"
14167 "Access-Control-Allow-Origin: %s\r\n"
14168 "Access-Control-Allow-Methods: %s\r\n"
14169 "Content-Length: 0\r\n"
14170 "Connection: %s\r\n",
14171 date,
14172 cors_orig_cfg,
14173 ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
14175
14176 if (cors_acrh != NULL) {
14177 /* CORS request is asking for additional headers */
14178 const char *cors_hdr_cfg =
14180
14181 if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
14182 /* Allow only if access_control_allow_headers is
14183 * not NULL and not an empty string. If this
14184 * configuration is set to *, allow everything.
14185 * Otherwise this configuration must be a list
14186 * of allowed HTTP header names. */
14187 mg_printf(conn,
14188 "Access-Control-Allow-Headers: %s\r\n",
14189 ((cors_hdr_cfg[0] == '*') ? cors_acrh
14190 : cors_hdr_cfg));
14191 }
14192 }
14193 if (cors_cred_cfg && *cors_cred_cfg) {
14194 mg_printf(conn,
14195 "Access-Control-Allow-Credentials: %s\r\n",
14196 cors_cred_cfg);
14197 }
14198
14199 mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
14200
14201 mg_printf(conn, "\r\n");
14202 return;
14203 }
14204 }
14205
14206 /* 5. interpret the url to find out how the request must be handled
14207 */
14208 /* 5.1. first test, if the request targets the regular http(s)://
14209 * protocol namespace or the websocket ws(s):// protocol namespace.
14210 */
14211 is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
14212#if defined(USE_WEBSOCKET)
14213 handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
14214#else
14215 handler_type = REQUEST_HANDLER;
14216#endif /* defined(USE_WEBSOCKET) */
14217
14218 if (is_websocket_request) {
14219 HTTP1_only;
14220 }
14221
14222 /* 5.2. check if the request will be handled by a callback */
14223 if (get_request_handler(conn,
14224 handler_type,
14225 &callback_handler,
14226 &subprotocols,
14227 &ws_connect_handler,
14228 &ws_ready_handler,
14229 &ws_data_handler,
14230 &ws_close_handler,
14231 NULL,
14232 &callback_data,
14233 &handler_info)) {
14234 /* 5.2.1. A callback will handle this request. All requests
14235 * handled by a callback have to be considered as requests
14236 * to a script resource. */
14237 is_callback_resource = 1;
14238 is_script_resource = 1;
14239 is_put_or_delete_request = is_put_or_delete_method(conn);
14240 } else {
14241 no_callback_resource:
14242
14243 /* 5.2.2. No callback is responsible for this request. The URI
14244 * addresses a file based resource (static content or Lua/cgi
14245 * scripts in the file system). */
14246 is_callback_resource = 0;
14247 interpret_uri(conn,
14248 path,
14249 sizeof(path),
14250 &file.stat,
14251 &is_found,
14252 &is_script_resource,
14253 &is_websocket_request,
14254 &is_put_or_delete_request,
14255 &is_template_text_file);
14256 }
14257
14258 /* 6. authorization check */
14259 /* 6.1. a custom authorization handler is installed */
14260 if (get_request_handler(conn,
14262 NULL,
14263 NULL,
14264 NULL,
14265 NULL,
14266 NULL,
14267 NULL,
14268 &auth_handler,
14269 &auth_callback_data,
14270 NULL)) {
14271 if (!auth_handler(conn, auth_callback_data)) {
14272
14273 /* Callback handler will not be used anymore. Release it */
14274 release_handler_ref(conn, handler_info);
14275
14276 return;
14277 }
14278 } else if (is_put_or_delete_request && !is_script_resource
14279 && !is_callback_resource) {
14280 HTTP1_only;
14281 /* 6.2. this request is a PUT/DELETE to a real file */
14282 /* 6.2.1. thus, the server must have real files */
14283#if defined(NO_FILES)
14284 if (1) {
14285#else
14286 if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
14287#endif
14288 /* This code path will not be called for request handlers */
14289 DEBUG_ASSERT(handler_info == NULL);
14290
14291 /* This server does not have any real files, thus the
14292 * PUT/DELETE methods are not valid. */
14293 mg_send_http_error(conn,
14294 405,
14295 "%s method not allowed",
14297 return;
14298 }
14299
14300#if !defined(NO_FILES)
14301 /* 6.2.2. Check if put authorization for static files is
14302 * available.
14303 */
14304 if (!is_authorized_for_put(conn)) {
14305 send_authorization_request(conn, NULL);
14306 return;
14307 }
14308#endif
14309
14310 } else {
14311 /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
14312 * or it is a PUT or DELETE request to a resource that does not
14313 * correspond to a file. Check authorization. */
14314 if (!check_authorization(conn, path)) {
14315 send_authorization_request(conn, NULL);
14316
14317 /* Callback handler will not be used anymore. Release it */
14318 release_handler_ref(conn, handler_info);
14319
14320 return;
14321 }
14322 }
14323
14324 /* request is authorized or does not need authorization */
14325
14326 /* 7. check if there are request handlers for this uri */
14327 if (is_callback_resource) {
14328 HTTP1_only;
14329 if (!is_websocket_request) {
14330 i = callback_handler(conn, callback_data);
14331
14332 /* Callback handler will not be used anymore. Release it */
14333 release_handler_ref(conn, handler_info);
14334
14335 if (i > 0) {
14336 /* Do nothing, callback has served the request. Store
14337 * then return value as status code for the log and discard
14338 * all data from the client not used by the callback. */
14339 conn->status_code = i;
14340 if (!conn->must_close) {
14342 }
14343 } else {
14344 /* The handler did NOT handle the request. */
14345 /* Some proper reactions would be:
14346 * a) close the connections without sending anything
14347 * b) send a 404 not found
14348 * c) try if there is a file matching the URI
14349 * It would be possible to do a, b or c in the callback
14350 * implementation, and return 1 - we cannot do anything
14351 * here, that is not possible in the callback.
14352 *
14353 * TODO: What would be the best reaction here?
14354 * (Note: The reaction may change, if there is a better
14355 * idea.)
14356 */
14357
14358 /* For the moment, use option c: We look for a proper file,
14359 * but since a file request is not always a script resource,
14360 * the authorization check might be different. */
14361 interpret_uri(conn,
14362 path,
14363 sizeof(path),
14364 &file.stat,
14365 &is_found,
14366 &is_script_resource,
14367 &is_websocket_request,
14368 &is_put_or_delete_request,
14369 &is_template_text_file);
14370 callback_handler = NULL;
14371
14372 /* Here we are at a dead end:
14373 * According to URI matching, a callback should be
14374 * responsible for handling the request,
14375 * we called it, but the callback declared itself
14376 * not responsible.
14377 * We use a goto here, to get out of this dead end,
14378 * and continue with the default handling.
14379 * A goto here is simpler and better to understand
14380 * than some curious loop. */
14381 goto no_callback_resource;
14382 }
14383 } else {
14384#if defined(USE_WEBSOCKET)
14385 handle_websocket_request(conn,
14386 path,
14387 is_callback_resource,
14389 ws_connect_handler,
14390 ws_ready_handler,
14391 ws_data_handler,
14392 ws_close_handler,
14393 callback_data);
14394#endif
14395 }
14396 return;
14397 }
14398
14399 /* 8. handle websocket requests */
14400#if defined(USE_WEBSOCKET)
14401 if (is_websocket_request) {
14402 HTTP1_only;
14403 if (is_script_resource) {
14404
14405 if (is_in_script_path(conn, path)) {
14406 /* Websocket Lua script */
14407 handle_websocket_request(conn,
14408 path,
14409 0 /* Lua Script */,
14410 NULL,
14411 NULL,
14412 NULL,
14413 NULL,
14414 NULL,
14415 conn->phys_ctx->user_data);
14416 } else {
14417 /* Script was in an illegal path */
14418 mg_send_http_error(conn, 403, "%s", "Forbidden");
14419 }
14420 } else {
14421 mg_send_http_error(conn, 404, "%s", "Not found");
14422 }
14423 return;
14424 } else
14425#endif
14426
14427#if defined(NO_FILES)
14428 /* 9a. In case the server uses only callbacks, this uri is
14429 * unknown.
14430 * Then, all request handling ends here. */
14431 mg_send_http_error(conn, 404, "%s", "Not Found");
14432
14433#else
14434 /* 9b. This request is either for a static file or resource handled
14435 * by a script file. Thus, a DOCUMENT_ROOT must exist. */
14436 if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
14437 mg_send_http_error(conn, 404, "%s", "Not Found");
14438 return;
14439 }
14440
14441 /* 10. Request is handled by a script */
14442 if (is_script_resource) {
14443 HTTP1_only;
14444 handle_file_based_request(conn, path, &file);
14445 return;
14446 }
14447
14448 /* 11. Handle put/delete/mkcol requests */
14449 if (is_put_or_delete_request) {
14450 HTTP1_only;
14451 /* 11.1. PUT method */
14452 if (!strcmp(ri->request_method, "PUT")) {
14453 put_file(conn, path);
14454 return;
14455 }
14456 /* 11.2. DELETE method */
14457 if (!strcmp(ri->request_method, "DELETE")) {
14458 delete_file(conn, path);
14459 return;
14460 }
14461 /* 11.3. MKCOL method */
14462 if (!strcmp(ri->request_method, "MKCOL")) {
14463 mkcol(conn, path);
14464 return;
14465 }
14466 /* 11.4. PATCH method
14467 * This method is not supported for static resources,
14468 * only for scripts (Lua, CGI) and callbacks. */
14469 mg_send_http_error(conn,
14470 405,
14471 "%s method not allowed",
14473 return;
14474 }
14475
14476 /* 11. File does not exist, or it was configured that it should be
14477 * hidden */
14478 if (!is_found || (must_hide_file(conn, path))) {
14479 mg_send_http_error(conn, 404, "%s", "Not found");
14480 return;
14481 }
14482
14483 /* 12. Directory uris should end with a slash */
14484 if (file.stat.is_directory && (uri_len > 0)
14485 && (ri->local_uri[uri_len - 1] != '/')) {
14486
14487 size_t len = strlen(ri->request_uri);
14488 size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
14489 char *new_path = (char *)mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
14490 if (!new_path) {
14491 mg_send_http_error(conn, 500, "out or memory");
14492 } else {
14493 memcpy(new_path, ri->request_uri, len);
14494 new_path[len] = '/';
14495 new_path[len + 1] = 0;
14496 if (ri->query_string) {
14497 new_path[len + 1] = '?';
14498 /* Copy query string including terminating zero */
14499 memcpy(new_path + len + 2, ri->query_string, lenQS);
14500 }
14501 mg_send_http_redirect(conn, new_path, 301);
14502 mg_free(new_path);
14503 }
14504 return;
14505 }
14506
14507 /* 13. Handle other methods than GET/HEAD */
14508 /* 13.1. Handle PROPFIND */
14509 if (!strcmp(ri->request_method, "PROPFIND")) {
14510 handle_propfind(conn, path, &file.stat);
14511 return;
14512 }
14513 /* 13.2. Handle OPTIONS for files */
14514 if (!strcmp(ri->request_method, "OPTIONS")) {
14515 /* This standard handler is only used for real files.
14516 * Scripts should support the OPTIONS method themselves, to allow a
14517 * maximum flexibility.
14518 * Lua and CGI scripts may fully support CORS this way (including
14519 * preflights). */
14520 send_options(conn);
14521 return;
14522 }
14523 /* 13.3. everything but GET and HEAD (e.g. POST) */
14524 if ((0 != strcmp(ri->request_method, "GET"))
14525 && (0 != strcmp(ri->request_method, "HEAD"))) {
14526 mg_send_http_error(conn,
14527 405,
14528 "%s method not allowed",
14530 return;
14531 }
14532
14533 /* 14. directories */
14534 if (file.stat.is_directory) {
14535 /* Substitute files have already been handled above. */
14536 /* Here we can either generate and send a directory listing,
14537 * or send an "access denied" error. */
14539 "yes")) {
14540 handle_directory_request(conn, path);
14541 } else {
14542 mg_send_http_error(conn,
14543 403,
14544 "%s",
14545 "Error: Directory listing denied");
14546 }
14547 return;
14548 }
14549
14550 /* 15. Files with search/replace patterns: LSP and SSI */
14551 if (is_template_text_file) {
14552 HTTP1_only;
14553 handle_file_based_request(conn, path, &file);
14554 return;
14555 }
14556
14557 /* 16. Static file - maybe cached */
14558#if !defined(NO_CACHING)
14559 if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
14560 /* Send 304 "Not Modified" - this must not send any body data */
14562 return;
14563 }
14564#endif /* !NO_CACHING */
14565
14566 /* 17. Static file - not cached */
14567 handle_static_file_request(conn, path, &file, NULL, NULL);
14568
14569#endif /* !defined(NO_FILES) */
14570}
14571
14572
14573#if !defined(NO_FILESYSTEMS)
14574static void
14576 const char *path,
14577 struct mg_file *file)
14578{
14579#if !defined(NO_CGI)
14580 unsigned char cgi_config_idx, inc, max;
14581#endif
14582
14583 if (!conn || !conn->dom_ctx) {
14584 return;
14585 }
14586
14587#if defined(USE_LUA)
14588 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
14589 path)
14590 > 0) {
14591 if (is_in_script_path(conn, path)) {
14592 /* Lua server page: an SSI like page containing mostly plain
14593 * html code plus some tags with server generated contents. */
14594 handle_lsp_request(conn, path, file, NULL);
14595 } else {
14596 /* Script was in an illegal path */
14597 mg_send_http_error(conn, 403, "%s", "Forbidden");
14598 }
14599 return;
14600 }
14601
14602 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
14603 > 0) {
14604 if (is_in_script_path(conn, path)) {
14605 /* Lua in-server module script: a CGI like script used to
14606 * generate the entire reply. */
14607 mg_exec_lua_script(conn, path, NULL);
14608 } else {
14609 /* Script was in an illegal path */
14610 mg_send_http_error(conn, 403, "%s", "Forbidden");
14611 }
14612 return;
14613 }
14614#endif
14615
14616#if defined(USE_DUKTAPE)
14617 if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
14618 path)
14619 > 0) {
14620 if (is_in_script_path(conn, path)) {
14621 /* Call duktape to generate the page */
14622 mg_exec_duktape_script(conn, path);
14623 } else {
14624 /* Script was in an illegal path */
14625 mg_send_http_error(conn, 403, "%s", "Forbidden");
14626 }
14627 return;
14628 }
14629#endif
14630
14631#if !defined(NO_CGI)
14634 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
14635 if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
14637 conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
14638 path)
14639 > 0) {
14640 if (is_in_script_path(conn, path)) {
14641 /* CGI scripts may support all HTTP methods */
14642 handle_cgi_request(conn, path, 0);
14643 } else {
14644 /* Script was in an illegal path */
14645 mg_send_http_error(conn, 403, "%s", "Forbidden");
14646 }
14647 return;
14648 }
14649 }
14650 }
14651#endif /* !NO_CGI */
14652
14653 if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
14654 if (is_in_script_path(conn, path)) {
14655 handle_ssi_file_request(conn, path, file);
14656 } else {
14657 /* Script was in an illegal path */
14658 mg_send_http_error(conn, 403, "%s", "Forbidden");
14659 }
14660 return;
14661 }
14662
14663#if !defined(NO_CACHING)
14664 if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
14665 /* Send 304 "Not Modified" - this must not send any body data */
14667 return;
14668 }
14669#endif /* !NO_CACHING */
14670
14671 handle_static_file_request(conn, path, file, NULL, NULL);
14672}
14673#endif /* NO_FILESYSTEMS */
14674
14675
14676static void
14678{
14679 unsigned int i;
14680 if (!ctx) {
14681 return;
14682 }
14683
14684 for (i = 0; i < ctx->num_listening_sockets; i++) {
14686#if defined(USE_X_DOM_SOCKET)
14687 /* For unix domain sockets, the socket name represents a file that has
14688 * to be deleted. */
14689 /* See
14690 * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
14691 */
14692 if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
14693 && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
14695 remove(ctx->listening_sockets[i].lsa.sun.sun_path));
14696 }
14697#endif
14699 }
14701 ctx->listening_sockets = NULL;
14703 ctx->listening_socket_fds = NULL;
14704}
14705
14706
14707/* Valid listening port specification is: [ip_address:]port[s]
14708 * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
14709 * Examples for IPv6: [::]:80, [::1]:80,
14710 * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
14711 * see https://tools.ietf.org/html/rfc3513#section-2.2
14712 * In order to bind to both, IPv4 and IPv6, you can either add
14713 * both ports using 8080,[::]:8080, or the short form +8080.
14714 * Both forms differ in detail: 8080,[::]:8080 create two sockets,
14715 * one only accepting IPv4 the other only IPv6. +8080 creates
14716 * one socket accepting IPv4 and IPv6. Depending on the IPv6
14717 * environment, they might work differently, or might not work
14718 * at all - it must be tested what options work best in the
14719 * relevant network environment.
14720 */
14721static int
14722parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
14723{
14724 unsigned int a, b, c, d;
14725 unsigned port;
14726 unsigned long portUL;
14727 int ch, len;
14728 const char *cb;
14729 char *endptr;
14730#if defined(USE_IPV6)
14731 char buf[100] = {0};
14732#endif
14733
14734 /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
14735 * Also, all-zeroes in the socket address means binding to all addresses
14736 * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
14737 memset(so, 0, sizeof(*so));
14738 so->lsa.sin.sin_family = AF_INET;
14739 *ip_version = 0;
14740
14741 /* Initialize len as invalid. */
14742 port = 0;
14743 len = 0;
14744
14745 /* Test for different ways to format this string */
14746 if (sscanf(vec->ptr,
14747 "%u.%u.%u.%u:%u%n",
14748 &a,
14749 &b,
14750 &c,
14751 &d,
14752 &port,
14753 &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
14754 // to an integer value, but function will not report
14755 // conversion errors; consider using 'strtol' instead
14756 == 5) {
14757 /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
14758 so->lsa.sin.sin_addr.s_addr =
14759 htonl((a << 24) | (b << 16) | (c << 8) | d);
14760 so->lsa.sin.sin_port = htons((uint16_t)port);
14761 *ip_version = 4;
14762
14763#if defined(USE_IPV6)
14764 } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
14765 && ((size_t)len <= vec->len)
14766 && mg_inet_pton(
14767 AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
14768 /* IPv6 address, examples: see above */
14769 /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
14770 */
14771 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14772 *ip_version = 6;
14773#endif
14774
14775 } else if ((vec->ptr[0] == '+')
14776 && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
14777 == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
14778 // string to an integer value, but function will not
14779 // report conversion errors; consider using 'strtol'
14780 // instead
14781
14782 /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
14783 /* Add 1 to len for the + character we skipped before */
14784 len++;
14785
14786#if defined(USE_IPV6)
14787 /* Set socket family to IPv6, do not use IPV6_V6ONLY */
14788 so->lsa.sin6.sin6_family = AF_INET6;
14789 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14790 *ip_version = 4 + 6;
14791#else
14792 /* Bind to IPv4 only, since IPv6 is not built in. */
14793 so->lsa.sin.sin_port = htons((uint16_t)port);
14794 *ip_version = 4;
14795#endif
14796
14797 } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
14798 && (vec->ptr != endptr)) {
14799 len = (int)(endptr - vec->ptr);
14800 port = (uint16_t)portUL;
14801 /* If only port is specified, bind to IPv4, INADDR_ANY */
14802 so->lsa.sin.sin_port = htons((uint16_t)port);
14803 *ip_version = 4;
14804
14805 } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
14806 /* String could be a hostname. This check algotithm
14807 * will only work for RFC 952 compliant hostnames,
14808 * starting with a letter, containing only letters,
14809 * digits and hyphen ('-'). Newer specs may allow
14810 * more, but this is not guaranteed here, since it
14811 * may interfere with rules for port option lists. */
14812
14813 /* According to RFC 1035, hostnames are restricted to 255 characters
14814 * in total (63 between two dots). */
14815 char hostname[256];
14816 size_t hostnlen = (size_t)(cb - vec->ptr);
14817
14818 if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
14819 /* This would be invalid in any case */
14820 *ip_version = 0;
14821 return 0;
14822 }
14823
14824 mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
14825
14826 if (mg_inet_pton(
14827 AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
14828 if (sscanf(cb + 1, "%u%n", &port, &len)
14829 == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
14830 // string to an integer value, but function will not
14831 // report conversion errors; consider using 'strtol'
14832 // instead
14833 *ip_version = 4;
14834 so->lsa.sin.sin_port = htons((uint16_t)port);
14835 len += (int)(hostnlen + 1);
14836 } else {
14837 len = 0;
14838 }
14839#if defined(USE_IPV6)
14840 } else if (mg_inet_pton(AF_INET6,
14841 hostname,
14842 &so->lsa.sin6,
14843 sizeof(so->lsa.sin6),
14844 1)) {
14845 if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
14846 *ip_version = 6;
14847 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14848 len += (int)(hostnlen + 1);
14849 } else {
14850 len = 0;
14851 }
14852#endif
14853 } else {
14854 len = 0;
14855 }
14856
14857#if defined(USE_X_DOM_SOCKET)
14858
14859 } else if (vec->ptr[0] == 'x') {
14860 /* unix (linux) domain socket */
14861 if (vec->len < sizeof(so->lsa.sun.sun_path)) {
14862 len = vec->len;
14863 so->lsa.sun.sun_family = AF_UNIX;
14864 memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
14865 memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
14866 port = 0;
14867 *ip_version = 99;
14868 } else {
14869 /* String too long */
14870 len = 0;
14871 }
14872#endif
14873
14874 } else {
14875 /* Parsing failure. */
14876 len = 0;
14877 }
14878
14879 /* sscanf and the option splitting code ensure the following condition
14880 * Make sure the port is valid and vector ends with the port, 's' or 'r' */
14881 if ((len > 0) && is_valid_port(port)
14882 && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
14883 /* Next character after the port number */
14884 ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
14885 so->is_ssl = (ch == 's');
14886 so->ssl_redir = (ch == 'r');
14887 if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
14888 return 1;
14889 }
14890 }
14891
14892 /* Reset ip_version to 0 if there is an error */
14893 *ip_version = 0;
14894 return 0;
14895}
14896
14897
14898/* Is there any SSL port in use? */
14899static int
14900is_ssl_port_used(const char *ports)
14901{
14902 if (ports) {
14903 /* There are several different allowed syntax variants:
14904 * - "80" for a single port using every network interface
14905 * - "localhost:80" for a single port using only localhost
14906 * - "80,localhost:8080" for two ports, one bound to localhost
14907 * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
14908 * to IPv4 localhost, one to IPv6 localhost
14909 * - "+80" use port 80 for IPv4 and IPv6
14910 * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
14911 * for both: IPv4 and IPv4
14912 * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
14913 * additionally port 8080 bound to localhost connections
14914 *
14915 * If we just look for 's' anywhere in the string, "localhost:80"
14916 * will be detected as SSL (false positive).
14917 * Looking for 's' after a digit may cause false positives in
14918 * "my24service:8080".
14919 * Looking from 's' backward if there are only ':' and numbers
14920 * before will not work for "24service:8080" (non SSL, port 8080)
14921 * or "24s" (SSL, port 24).
14922 *
14923 * Remark: Initially hostnames were not allowed to start with a
14924 * digit (according to RFC 952), this was allowed later (RFC 1123,
14925 * Section 2.1).
14926 *
14927 * To get this correct, the entire string must be parsed as a whole,
14928 * reading it as a list element for element and parsing with an
14929 * algorithm equivalent to parse_port_string.
14930 *
14931 * In fact, we use local interface names here, not arbitrary
14932 * hostnames, so in most cases the only name will be "localhost".
14933 *
14934 * So, for now, we use this simple algorithm, that may still return
14935 * a false positive in bizarre cases.
14936 */
14937 int i;
14938 int portslen = (int)strlen(ports);
14939 char prevIsNumber = 0;
14940
14941 for (i = 0; i < portslen; i++) {
14942 if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
14943 return 1;
14944 }
14945 if (ports[i] >= '0' && ports[i] <= '9') {
14946 prevIsNumber = 1;
14947 } else {
14948 prevIsNumber = 0;
14949 }
14950 }
14951 }
14952 return 0;
14953}
14954
14955
14956static int
14958{
14959 const char *list;
14960 int on = 1;
14961#if defined(USE_IPV6)
14962 int off = 0;
14963#endif
14964 struct vec vec;
14965 struct socket so, *ptr;
14966
14967 struct mg_pollfd *pfd;
14968 union usa usa;
14969 socklen_t len;
14970 int ip_version;
14971
14972 int portsTotal = 0;
14973 int portsOk = 0;
14974
14975 const char *opt_txt;
14976 long opt_listen_backlog;
14977
14978 if (!phys_ctx) {
14979 return 0;
14980 }
14981
14982 memset(&so, 0, sizeof(so));
14983 memset(&usa, 0, sizeof(usa));
14984 len = sizeof(usa);
14985 list = phys_ctx->dd.config[LISTENING_PORTS];
14986
14987 while ((list = next_option(list, &vec, NULL)) != NULL) {
14988
14989 portsTotal++;
14990
14991 if (!parse_port_string(&vec, &so, &ip_version)) {
14993 phys_ctx,
14994 "%.*s: invalid port spec (entry %i). Expecting list of: %s",
14995 (int)vec.len,
14996 vec.ptr,
14997 portsTotal,
14998 "[IP_ADDRESS:]PORT[s|r]");
14999 continue;
15000 }
15001
15002#if !defined(NO_SSL)
15003 if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
15004
15005 mg_cry_ctx_internal(phys_ctx,
15006 "Cannot add SSL socket (entry %i)",
15007 portsTotal);
15008 continue;
15009 }
15010#endif
15011 /* Create socket. */
15012 /* For a list of protocol numbers (e.g., TCP==6) see:
15013 * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
15014 */
15015 if ((so.sock =
15016 socket(so.lsa.sa.sa_family,
15017 SOCK_STREAM,
15018 (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
15019 == INVALID_SOCKET) {
15020
15021 mg_cry_ctx_internal(phys_ctx,
15022 "cannot create socket (entry %i)",
15023 portsTotal);
15024 continue;
15025 }
15026
15027#if defined(_WIN32)
15028 /* Windows SO_REUSEADDR lets many procs binds to a
15029 * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
15030 * if someone already has the socket -- DTL */
15031 /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
15032 * Windows might need a few seconds before
15033 * the same port can be used again in the
15034 * same process, so a short Sleep may be
15035 * required between mg_stop and mg_start.
15036 */
15037 if (setsockopt(so.sock,
15038 SOL_SOCKET,
15039 SO_EXCLUSIVEADDRUSE,
15040 (SOCK_OPT_TYPE)&on,
15041 sizeof(on))
15042 != 0) {
15043
15044 /* Set reuse option, but don't abort on errors. */
15046 phys_ctx,
15047 "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
15048 portsTotal);
15049 }
15050#else
15051 if (setsockopt(so.sock,
15052 SOL_SOCKET,
15053 SO_REUSEADDR,
15054 (SOCK_OPT_TYPE)&on,
15055 sizeof(on))
15056 != 0) {
15057
15058 /* Set reuse option, but don't abort on errors. */
15060 phys_ctx,
15061 "cannot set socket option SO_REUSEADDR (entry %i)",
15062 portsTotal);
15063 }
15064#endif
15065
15066#if defined(USE_X_DOM_SOCKET)
15067 if (ip_version == 99) {
15068 /* Unix domain socket */
15069 } else
15070#endif
15071
15072 if (ip_version > 4) {
15073 /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
15074#if defined(USE_IPV6)
15075 if (ip_version > 6) {
15076 if (so.lsa.sa.sa_family == AF_INET6
15077 && setsockopt(so.sock,
15078 IPPROTO_IPV6,
15079 IPV6_V6ONLY,
15080 (void *)&off,
15081 sizeof(off))
15082 != 0) {
15083
15084 /* Set IPv6 only option, but don't abort on errors. */
15085 mg_cry_ctx_internal(phys_ctx,
15086 "cannot set socket option "
15087 "IPV6_V6ONLY=off (entry %i)",
15088 portsTotal);
15089 }
15090 } else {
15091 if (so.lsa.sa.sa_family == AF_INET6
15092 && setsockopt(so.sock,
15093 IPPROTO_IPV6,
15094 IPV6_V6ONLY,
15095 (void *)&on,
15096 sizeof(on))
15097 != 0) {
15098
15099 /* Set IPv6 only option, but don't abort on errors. */
15100 mg_cry_ctx_internal(phys_ctx,
15101 "cannot set socket option "
15102 "IPV6_V6ONLY=on (entry %i)",
15103 portsTotal);
15104 }
15105 }
15106#else
15107 mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
15108 closesocket(so.sock);
15109 so.sock = INVALID_SOCKET;
15110 continue;
15111#endif
15112 }
15113
15114 if (so.lsa.sa.sa_family == AF_INET) {
15115
15116 len = sizeof(so.lsa.sin);
15117 if (bind(so.sock, &so.lsa.sa, len) != 0) {
15118 mg_cry_ctx_internal(phys_ctx,
15119 "cannot bind to %.*s: %d (%s)",
15120 (int)vec.len,
15121 vec.ptr,
15122 (int)ERRNO,
15123 strerror(errno));
15124 closesocket(so.sock);
15125 so.sock = INVALID_SOCKET;
15126 continue;
15127 }
15128 }
15129#if defined(USE_IPV6)
15130 else if (so.lsa.sa.sa_family == AF_INET6) {
15131
15132 len = sizeof(so.lsa.sin6);
15133 if (bind(so.sock, &so.lsa.sa, len) != 0) {
15134 mg_cry_ctx_internal(phys_ctx,
15135 "cannot bind to IPv6 %.*s: %d (%s)",
15136 (int)vec.len,
15137 vec.ptr,
15138 (int)ERRNO,
15139 strerror(errno));
15140 closesocket(so.sock);
15141 so.sock = INVALID_SOCKET;
15142 continue;
15143 }
15144 }
15145#endif
15146#if defined(USE_X_DOM_SOCKET)
15147 else if (so.lsa.sa.sa_family == AF_UNIX) {
15148
15149 len = sizeof(so.lsa.sun);
15150 if (bind(so.sock, &so.lsa.sa, len) != 0) {
15151 mg_cry_ctx_internal(phys_ctx,
15152 "cannot bind to unix socket %s: %d (%s)",
15153 so.lsa.sun.sun_path,
15154 (int)ERRNO,
15155 strerror(errno));
15156 closesocket(so.sock);
15157 so.sock = INVALID_SOCKET;
15158 continue;
15159 }
15160 }
15161#endif
15162 else {
15164 phys_ctx,
15165 "cannot bind: address family not supported (entry %i)",
15166 portsTotal);
15167 closesocket(so.sock);
15168 so.sock = INVALID_SOCKET;
15169 continue;
15170 }
15171
15172 opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
15173 opt_listen_backlog = strtol(opt_txt, NULL, 10);
15174 if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
15175 mg_cry_ctx_internal(phys_ctx,
15176 "%s value \"%s\" is invalid",
15178 opt_txt);
15179 closesocket(so.sock);
15180 so.sock = INVALID_SOCKET;
15181 continue;
15182 }
15183
15184 if (listen(so.sock, (int)opt_listen_backlog) != 0) {
15185
15186 mg_cry_ctx_internal(phys_ctx,
15187 "cannot listen to %.*s: %d (%s)",
15188 (int)vec.len,
15189 vec.ptr,
15190 (int)ERRNO,
15191 strerror(errno));
15192 closesocket(so.sock);
15193 so.sock = INVALID_SOCKET;
15194 continue;
15195 }
15196
15197 if ((getsockname(so.sock, &(usa.sa), &len) != 0)
15198 || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
15199
15200 int err = (int)ERRNO;
15201 mg_cry_ctx_internal(phys_ctx,
15202 "call to getsockname failed %.*s: %d (%s)",
15203 (int)vec.len,
15204 vec.ptr,
15205 err,
15206 strerror(errno));
15207 closesocket(so.sock);
15208 so.sock = INVALID_SOCKET;
15209 continue;
15210 }
15211
15212 /* Update lsa port in case of random free ports */
15213#if defined(USE_IPV6)
15214 if (so.lsa.sa.sa_family == AF_INET6) {
15215 so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
15216 } else
15217#endif
15218 {
15219 so.lsa.sin.sin_port = usa.sin.sin_port;
15220 }
15221
15222 if ((ptr = (struct socket *)
15224 (phys_ctx->num_listening_sockets + 1)
15225 * sizeof(phys_ctx->listening_sockets[0]),
15226 phys_ctx))
15227 == NULL) {
15228
15229 mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
15230 closesocket(so.sock);
15231 so.sock = INVALID_SOCKET;
15232 continue;
15233 }
15234
15235 if ((pfd = (struct mg_pollfd *)
15237 (phys_ctx->num_listening_sockets + 1)
15238 * sizeof(phys_ctx->listening_socket_fds[0]),
15239 phys_ctx))
15240 == NULL) {
15241
15242 mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
15243 closesocket(so.sock);
15244 so.sock = INVALID_SOCKET;
15245 mg_free(ptr);
15246 continue;
15247 }
15248
15249 set_close_on_exec(so.sock, NULL, phys_ctx);
15250 phys_ctx->listening_sockets = ptr;
15251 phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
15252 phys_ctx->listening_socket_fds = pfd;
15253 phys_ctx->num_listening_sockets++;
15254 portsOk++;
15255 }
15256
15257 if (portsOk != portsTotal) {
15259 portsOk = 0;
15260 }
15261
15262 return portsOk;
15263}
15264
15265
15266static const char *
15267header_val(const struct mg_connection *conn, const char *header)
15268{
15269 const char *header_value;
15270
15271 if ((header_value = mg_get_header(conn, header)) == NULL) {
15272 return "-";
15273 } else {
15274 return header_value;
15275 }
15276}
15277
15278
15279#if defined(MG_EXTERNAL_FUNCTION_log_access)
15280#include "external_log_access.inl"
15281#elif !defined(NO_FILESYSTEMS)
15282
15283static void
15284log_access(const struct mg_connection *conn)
15285{
15286 const struct mg_request_info *ri;
15287 struct mg_file fi;
15288 char date[64], src_addr[IP_ADDR_STR_LEN];
15289 struct tm *tm;
15290
15291 const char *referer;
15292 const char *user_agent;
15293
15294 char log_buf[4096];
15295
15296 if (!conn || !conn->dom_ctx) {
15297 return;
15298 }
15299
15300 /* Set log message to "empty" */
15301 log_buf[0] = 0;
15302
15303#if defined(USE_LUA)
15304 if (conn->phys_ctx->lua_bg_log_available) {
15305 int ret;
15306 struct mg_context *ctx = conn->phys_ctx;
15307 lua_State *lstate = (lua_State *)ctx->lua_background_state;
15308 pthread_mutex_lock(&ctx->lua_bg_mutex);
15309 /* call "log()" in Lua */
15310 lua_getglobal(lstate, "log");
15311 prepare_lua_request_info_inner(conn, lstate);
15312 push_lua_response_log_data(conn, lstate);
15313
15314 ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
15315 if (ret == 0) {
15316 int t = lua_type(lstate, -1);
15317 if (t == LUA_TBOOLEAN) {
15318 if (lua_toboolean(lstate, -1) == 0) {
15319 /* log() returned false: do not log */
15320 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15321 return;
15322 }
15323 /* log returned true: continue logging */
15324 } else if (t == LUA_TSTRING) {
15325 size_t len;
15326 const char *txt = lua_tolstring(lstate, -1, &len);
15327 if ((len == 0) || (*txt == 0)) {
15328 /* log() returned empty string: do not log */
15329 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15330 return;
15331 }
15332 /* Copy test from Lua into log_buf */
15333 if (len >= sizeof(log_buf)) {
15334 len = sizeof(log_buf) - 1;
15335 }
15336 memcpy(log_buf, txt, len);
15337 log_buf[len] = 0;
15338 }
15339 } else {
15340 lua_cry(conn, ret, lstate, "lua_background_script", "log");
15341 }
15342 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15343 }
15344#endif
15345
15346 if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
15347 if (mg_fopen(conn,
15350 &fi)
15351 == 0) {
15352 fi.access.fp = NULL;
15353 }
15354 } else {
15355 fi.access.fp = NULL;
15356 }
15357
15358 /* Log is written to a file and/or a callback. If both are not set,
15359 * executing the rest of the function is pointless. */
15360 if ((fi.access.fp == NULL)
15361 && (conn->phys_ctx->callbacks.log_access == NULL)) {
15362 return;
15363 }
15364
15365 /* If we did not get a log message from Lua, create it here. */
15366 if (!log_buf[0]) {
15367 tm = localtime(&conn->conn_birth_time);
15368 if (tm != NULL) {
15369 strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
15370 } else {
15371 mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
15372 date[sizeof(date) - 1] = '\0';
15373 }
15374
15375 ri = &conn->request_info;
15376
15377 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
15378 referer = header_val(conn, "Referer");
15379 user_agent = header_val(conn, "User-Agent");
15380
15381 mg_snprintf(conn,
15382 NULL, /* Ignore truncation in access log */
15383 log_buf,
15384 sizeof(log_buf),
15385 "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
15386 " %s %s",
15387 src_addr,
15388 (ri->remote_user == NULL) ? "-" : ri->remote_user,
15389 date,
15390 ri->request_method ? ri->request_method : "-",
15391 ri->request_uri ? ri->request_uri : "-",
15392 ri->query_string ? "?" : "",
15393 ri->query_string ? ri->query_string : "",
15394 ri->http_version,
15395 conn->status_code,
15396 conn->num_bytes_sent,
15397 referer,
15398 user_agent);
15399 }
15400
15401 /* Here we have a log message in log_buf. Call the callback */
15402 if (conn->phys_ctx->callbacks.log_access) {
15403 if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
15404 /* do not log if callack returns non-zero */
15405 if (fi.access.fp) {
15406 mg_fclose(&fi.access);
15407 }
15408 return;
15409 }
15410 }
15411
15412 /* Store in file */
15413 if (fi.access.fp) {
15414 int ok = 1;
15415 flockfile(fi.access.fp);
15416 if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
15417 ok = 0;
15418 }
15419 if (fflush(fi.access.fp) != 0) {
15420 ok = 0;
15421 }
15422 funlockfile(fi.access.fp);
15423 if (mg_fclose(&fi.access) != 0) {
15424 ok = 0;
15425 }
15426 if (!ok) {
15427 mg_cry_internal(conn,
15428 "Error writing log file %s",
15430 }
15431 }
15432}
15433#else
15434#error "Either enable filesystems or provide a custom log_access implementation"
15435#endif /* Externally provided function */
15436
15437
15438/* Verify given socket address against the ACL.
15439 * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
15440 */
15441static int
15442check_acl(struct mg_context *phys_ctx, const union usa *sa)
15443{
15444 int allowed, flag, matched;
15445 struct vec vec;
15446
15447 if (phys_ctx) {
15448 const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
15449
15450 /* If any ACL is set, deny by default */
15451 allowed = (list == NULL) ? '+' : '-';
15452
15453 while ((list = next_option(list, &vec, NULL)) != NULL) {
15454 flag = vec.ptr[0];
15455 matched = -1;
15456 if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
15457 vec.ptr++;
15458 vec.len--;
15459 matched = parse_match_net(&vec, sa, 1);
15460 }
15461 if (matched < 0) {
15462 mg_cry_ctx_internal(phys_ctx,
15463 "%s: subnet must be [+|-]IP-addr[/x]",
15464 __func__);
15465 return -1;
15466 }
15467 if (matched) {
15468 allowed = flag;
15469 }
15470 }
15471
15472 return allowed == '+';
15473 }
15474 return -1;
15475}
15476
15477
15478#if !defined(_WIN32) && !defined(__ZEPHYR__)
15479static int
15481{
15482 int success = 0;
15483
15484 if (phys_ctx) {
15485 /* We are currently running as curr_uid. */
15486 const uid_t curr_uid = getuid();
15487 /* If set, we want to run as run_as_user. */
15488 const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
15489 const struct passwd *to_pw = NULL;
15490
15491 if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
15492 /* run_as_user does not exist on the system. We can't proceed
15493 * further. */
15494 mg_cry_ctx_internal(phys_ctx,
15495 "%s: unknown user [%s]",
15496 __func__,
15497 run_as_user);
15498 } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
15499 /* There was either no request to change user, or we're already
15500 * running as run_as_user. Nothing else to do.
15501 */
15502 success = 1;
15503 } else {
15504 /* Valid change request. */
15505 if (setgid(to_pw->pw_gid) == -1) {
15506 mg_cry_ctx_internal(phys_ctx,
15507 "%s: setgid(%s): %s",
15508 __func__,
15509 run_as_user,
15510 strerror(errno));
15511 } else if (setgroups(0, NULL) == -1) {
15512 mg_cry_ctx_internal(phys_ctx,
15513 "%s: setgroups(): %s",
15514 __func__,
15515 strerror(errno));
15516 } else if (setuid(to_pw->pw_uid) == -1) {
15517 mg_cry_ctx_internal(phys_ctx,
15518 "%s: setuid(%s): %s",
15519 __func__,
15520 run_as_user,
15521 strerror(errno));
15522 } else {
15523 success = 1;
15524 }
15525 }
15526 }
15527
15528 return success;
15529}
15530#endif /* !_WIN32 */
15531
15532
15533static void
15534tls_dtor(void *key)
15535{
15536 struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
15537 /* key == pthread_getspecific(sTlsKey); */
15538
15539 if (tls) {
15540 if (tls->is_master == 2) {
15541 tls->is_master = -3; /* Mark memory as dead */
15542 mg_free(tls);
15543 }
15544 }
15545 pthread_setspecific(sTlsKey, NULL);
15546}
15547
15548
15549#if defined(USE_MBEDTLS)
15550/* Check if SSL is required.
15551 * If so, set up ctx->ssl_ctx pointer. */
15552static int
15553mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
15554{
15555 if (!phys_ctx) {
15556 return 0;
15557 }
15558
15559 if (!dom_ctx) {
15560 dom_ctx = &(phys_ctx->dd);
15561 }
15562
15563 if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
15564 /* No SSL port is set. No need to setup SSL. */
15565 return 1;
15566 }
15567
15568 dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
15569 if (dom_ctx->ssl_ctx == NULL) {
15570 fprintf(stderr, "ssl_ctx malloc failed\n");
15571 return 0;
15572 }
15573
15574 return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
15575 == 0
15576 ? 1
15577 : 0;
15578}
15579
15580#elif !defined(NO_SSL)
15581
15582static int ssl_use_pem_file(struct mg_context *phys_ctx,
15583 struct mg_domain_context *dom_ctx,
15584 const char *pem,
15585 const char *chain);
15586static const char *ssl_error(void);
15587
15588
15589static int
15591{
15592 struct stat cert_buf;
15593 int64_t t = 0;
15594 const char *pem;
15595 const char *chain;
15596 int should_verify_peer;
15597
15598 if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
15599 /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
15600 * refresh_trust still can not work. */
15601 return 0;
15602 }
15603 chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
15604 if (chain == NULL) {
15605 /* pem is not NULL here */
15606 chain = pem;
15607 }
15608 if (*chain == 0) {
15609 chain = NULL;
15610 }
15611
15612 if (stat(pem, &cert_buf) != -1) {
15613 t = (int64_t)cert_buf.st_mtime;
15614 }
15615
15617 if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
15618 conn->dom_ctx->ssl_cert_last_mtime = t;
15619
15620 should_verify_peer = 0;
15621 if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
15623 == 0) {
15624 should_verify_peer = 1;
15626 "optional")
15627 == 0) {
15628 should_verify_peer = 1;
15629 }
15630 }
15631
15632 if (should_verify_peer) {
15633 char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
15634 char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
15635 if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
15636 ca_file,
15637 ca_path)
15638 != 1) {
15641 conn->phys_ctx,
15642 "SSL_CTX_load_verify_locations error: %s "
15643 "ssl_verify_peer requires setting "
15644 "either ssl_ca_path or ssl_ca_file. Is any of them "
15645 "present in "
15646 "the .conf file?",
15647 ssl_error());
15648 return 0;
15649 }
15650 }
15651
15652 if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
15654 return 0;
15655 }
15656 }
15658
15659 return 1;
15660}
15661
15662#if defined(OPENSSL_API_1_1)
15663#else
15664static pthread_mutex_t *ssl_mutexes;
15665#endif /* OPENSSL_API_1_1 */
15666
15667static int
15669 int (*func)(SSL *),
15670 const struct mg_client_options *client_options)
15671{
15672 int ret, err;
15673 int short_trust;
15674 unsigned timeout = 1024;
15675 unsigned i;
15676
15677 if (!conn) {
15678 return 0;
15679 }
15680
15681 short_trust =
15682 (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
15683 && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
15684
15685 if (short_trust) {
15686 int trust_ret = refresh_trust(conn);
15687 if (!trust_ret) {
15688 return trust_ret;
15689 }
15690 }
15691
15693 conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
15695 if (conn->ssl == NULL) {
15696 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15697 OPENSSL_REMOVE_THREAD_STATE();
15698 return 0;
15699 }
15700 SSL_set_app_data(conn->ssl, (char *)conn);
15701
15702 ret = SSL_set_fd(conn->ssl, conn->client.sock);
15703 if (ret != 1) {
15704 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15705 SSL_free(conn->ssl);
15706 conn->ssl = NULL;
15707 OPENSSL_REMOVE_THREAD_STATE();
15708 return 0;
15709 }
15710
15711 if (client_options) {
15712 if (client_options->host_name) {
15713 SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
15714 }
15715 }
15716
15717 /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
15718 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
15719 /* NOTE: The loop below acts as a back-off, so we can end
15720 * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
15721 int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
15722 if (to >= 0) {
15723 timeout = (unsigned)to;
15724 }
15725 }
15726
15727 /* SSL functions may fail and require to be called again:
15728 * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
15729 * Here "func" could be SSL_connect or SSL_accept. */
15730 for (i = 0; i <= timeout; i += 50) {
15731 ERR_clear_error();
15732 /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
15733 ret = func(conn->ssl);
15734 if (ret != 1) {
15735 err = SSL_get_error(conn->ssl, ret);
15736 if ((err == SSL_ERROR_WANT_CONNECT)
15737 || (err == SSL_ERROR_WANT_ACCEPT)
15738 || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
15739 || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
15740 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
15741 /* Don't wait if the server is going to be stopped. */
15742 break;
15743 }
15744 if (err == SSL_ERROR_WANT_X509_LOOKUP) {
15745 /* Simply retry the function call. */
15746 mg_sleep(50);
15747 } else {
15748 /* Need to retry the function call "later".
15749 * See https://linux.die.net/man/3/ssl_get_error
15750 * This is typical for non-blocking sockets. */
15751 struct mg_pollfd pfd;
15752 int pollres;
15753 pfd.fd = conn->client.sock;
15754 pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
15755 || (err == SSL_ERROR_WANT_WRITE))
15756 ? POLLOUT
15757 : POLLIN;
15758 pollres =
15759 mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
15760 if (pollres < 0) {
15761 /* Break if error occured (-1)
15762 * or server shutdown (-2) */
15763 break;
15764 }
15765 }
15766
15767 } else if (err == SSL_ERROR_SYSCALL) {
15768 /* This is an IO error. Look at errno. */
15769 mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
15770 break;
15771
15772 } else {
15773 /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
15774 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15775 break;
15776 }
15777
15778 } else {
15779 /* success */
15780 break;
15781 }
15782 }
15783 ERR_clear_error();
15784
15785 if (ret != 1) {
15786 SSL_free(conn->ssl);
15787 conn->ssl = NULL;
15788 OPENSSL_REMOVE_THREAD_STATE();
15789 return 0;
15790 }
15791
15792 return 1;
15793}
15794
15795
15796/* Return OpenSSL error message (from CRYPTO lib) */
15797static const char *
15799{
15800 unsigned long err;
15801 err = ERR_get_error();
15802 return ((err == 0) ? "" : ERR_error_string(err, NULL));
15803}
15804
15805
15806static int
15807hexdump2string(void *mem, int memlen, char *buf, int buflen)
15808{
15809 int i;
15810 const char hexdigit[] = "0123456789abcdef";
15811
15812 if ((memlen <= 0) || (buflen <= 0)) {
15813 return 0;
15814 }
15815 if (buflen < (3 * memlen)) {
15816 return 0;
15817 }
15818
15819 for (i = 0; i < memlen; i++) {
15820 if (i > 0) {
15821 buf[3 * i - 1] = ' ';
15822 }
15823 buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
15824 buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
15825 }
15826 buf[3 * memlen - 1] = 0;
15827
15828 return 1;
15829}
15830
15831
15832static int
15834 struct mg_client_cert *client_cert)
15835{
15836 X509 *cert = SSL_get_peer_certificate(conn->ssl);
15837 if (cert) {
15838 char str_buf[1024];
15839 unsigned char buf[256];
15840 char *str_serial = NULL;
15841 unsigned int ulen;
15842 int ilen;
15843 unsigned char *tmp_buf;
15844 unsigned char *tmp_p;
15845
15846 /* Handle to algorithm used for fingerprint */
15847 const EVP_MD *digest = EVP_get_digestbyname("sha1");
15848
15849 /* Get Subject and issuer */
15850 X509_NAME *subj = X509_get_subject_name(cert);
15851 X509_NAME *iss = X509_get_issuer_name(cert);
15852
15853 /* Get serial number */
15854 ASN1_INTEGER *serial = X509_get_serialNumber(cert);
15855
15856 /* Translate serial number to a hex string */
15857 BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
15858 if (serial_bn) {
15859 str_serial = BN_bn2hex(serial_bn);
15860 BN_free(serial_bn);
15861 }
15862 client_cert->serial =
15863 str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
15864
15865 /* Translate subject and issuer to a string */
15866 (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
15867 client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
15868 (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
15869 client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
15870
15871 /* Calculate SHA1 fingerprint and store as a hex string */
15872 ulen = 0;
15873
15874 /* ASN1_digest is deprecated. Do the calculation manually,
15875 * using EVP_Digest. */
15876 ilen = i2d_X509(cert, NULL);
15877 tmp_buf = (ilen > 0)
15878 ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
15879 conn->phys_ctx)
15880 : NULL;
15881 if (tmp_buf) {
15882 tmp_p = tmp_buf;
15883 (void)i2d_X509(cert, &tmp_p);
15884 if (!EVP_Digest(
15885 tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
15886 ulen = 0;
15887 }
15888 mg_free(tmp_buf);
15889 }
15890
15891 if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
15892 *str_buf = 0;
15893 }
15894 client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
15895
15896 client_cert->peer_cert = (void *)cert;
15897
15898 /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
15899 * see https://linux.die.net/man/3/bn_bn2hex */
15900 OPENSSL_free(str_serial);
15901 return 1;
15902 }
15903 return 0;
15904}
15905
15906
15907#if defined(OPENSSL_API_1_1)
15908#else
15909static void
15910ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
15911{
15912 (void)line;
15913 (void)file;
15914
15915 if (mode & 1) {
15916 /* 1 is CRYPTO_LOCK */
15917 (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
15918 } else {
15919 (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
15920 }
15921}
15922#endif /* OPENSSL_API_1_1 */
15923
15924
15925#if !defined(NO_SSL_DL)
15926/* Load a DLL/Shared Object with a TLS/SSL implementation. */
15927static void *
15928load_tls_dll(char *ebuf,
15929 size_t ebuf_len,
15930 const char *dll_name,
15931 struct ssl_func *sw,
15932 int *feature_missing)
15933{
15934 union {
15935 void *p;
15936 void (*fp)(void);
15937 } u;
15938 void *dll_handle;
15939 struct ssl_func *fp;
15940 int ok;
15941 int truncated = 0;
15942
15943 if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
15944 mg_snprintf(NULL,
15945 NULL, /* No truncation check for ebuf */
15946 ebuf,
15947 ebuf_len,
15948 "%s: cannot load %s",
15949 __func__,
15950 dll_name);
15951 return NULL;
15952 }
15953
15954 ok = 1;
15955 for (fp = sw; fp->name != NULL; fp++) {
15956#if defined(_WIN32)
15957 /* GetProcAddress() returns pointer to function */
15958 u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
15959#else
15960 /* dlsym() on UNIX returns void *. ISO C forbids casts of data
15961 * pointers to function pointers. We need to use a union to make a
15962 * cast. */
15963 u.p = dlsym(dll_handle, fp->name);
15964#endif /* _WIN32 */
15965
15966 /* Set pointer (might be NULL) */
15967 fp->ptr = u.fp;
15968
15969 if (u.fp == NULL) {
15970 DEBUG_TRACE("Missing function: %s\n", fp->name);
15971 if (feature_missing) {
15972 feature_missing[fp->required]++;
15973 }
15974 if (fp->required == TLS_Mandatory) {
15975 /* Mandatory function is missing */
15976 if (ok) {
15977 /* This is the first missing function.
15978 * Create a new error message. */
15979 mg_snprintf(NULL,
15980 &truncated,
15981 ebuf,
15982 ebuf_len,
15983 "%s: %s: cannot find %s",
15984 __func__,
15985 dll_name,
15986 fp->name);
15987 ok = 0;
15988 } else {
15989 /* This is yet anothermissing function.
15990 * Append existing error message. */
15991 size_t cur_len = strlen(ebuf);
15992 if (!truncated && ((ebuf_len - cur_len) > 3)) {
15993 mg_snprintf(NULL,
15994 &truncated,
15995 ebuf + cur_len,
15996 ebuf_len - cur_len - 3,
15997 ", %s",
15998 fp->name);
15999 if (truncated) {
16000 /* If truncated, add "..." */
16001 strcat(ebuf, "...");
16002 }
16003 }
16004 }
16005 }
16006 }
16007 }
16008
16009 if (!ok) {
16010 (void)dlclose(dll_handle);
16011 return NULL;
16012 }
16013
16014 return dll_handle;
16015}
16016
16017
16018static void *ssllib_dll_handle; /* Store the ssl library handle. */
16019static void *cryptolib_dll_handle; /* Store the crypto library handle. */
16020
16021#endif /* NO_SSL_DL */
16022
16023
16024#if defined(SSL_ALREADY_INITIALIZED)
16025static volatile ptrdiff_t cryptolib_users =
16026 1; /* Reference counter for crypto library. */
16027#else
16028static volatile ptrdiff_t cryptolib_users =
16029 0; /* Reference counter for crypto library. */
16030#endif
16031
16032
16033static int
16034initialize_openssl(char *ebuf, size_t ebuf_len)
16035{
16036#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16037 int i, num_locks;
16038 size_t size;
16039#endif
16040
16041 if (ebuf_len > 0) {
16042 ebuf[0] = 0;
16043 }
16044
16045#if !defined(NO_SSL_DL)
16046 if (!cryptolib_dll_handle) {
16047 memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
16049 ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
16050 if (!cryptolib_dll_handle) {
16051 mg_snprintf(NULL,
16052 NULL, /* No truncation check for ebuf */
16053 ebuf,
16054 ebuf_len,
16055 "%s: error loading library %s",
16056 __func__,
16057 CRYPTO_LIB);
16058 DEBUG_TRACE("%s", ebuf);
16059 return 0;
16060 }
16061 }
16062#endif /* NO_SSL_DL */
16063
16064 if (mg_atomic_inc(&cryptolib_users) > 1) {
16065 return 1;
16066 }
16067
16068#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16069 /* Initialize locking callbacks, needed for thread safety.
16070 * http://www.openssl.org/support/faq.html#PROG1
16071 */
16072 num_locks = CRYPTO_num_locks();
16073 if (num_locks < 0) {
16074 num_locks = 0;
16075 }
16076 size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
16077
16078 /* allocate mutex array, if required */
16079 if (num_locks == 0) {
16080 /* No mutex array required */
16081 ssl_mutexes = NULL;
16082 } else {
16083 /* Mutex array required - allocate it */
16084 ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
16085
16086 /* Check OOM */
16087 if (ssl_mutexes == NULL) {
16088 mg_snprintf(NULL,
16089 NULL, /* No truncation check for ebuf */
16090 ebuf,
16091 ebuf_len,
16092 "%s: cannot allocate mutexes: %s",
16093 __func__,
16094 ssl_error());
16095 DEBUG_TRACE("%s", ebuf);
16096 return 0;
16097 }
16098
16099 /* initialize mutex array */
16100 for (i = 0; i < num_locks; i++) {
16101 if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
16102 mg_snprintf(NULL,
16103 NULL, /* No truncation check for ebuf */
16104 ebuf,
16105 ebuf_len,
16106 "%s: error initializing mutex %i of %i",
16107 __func__,
16108 i,
16109 num_locks);
16110 DEBUG_TRACE("%s", ebuf);
16112 return 0;
16113 }
16114 }
16115 }
16116
16117 CRYPTO_set_locking_callback(&ssl_locking_callback);
16118 CRYPTO_set_id_callback(&mg_current_thread_id);
16119#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16120
16121#if !defined(NO_SSL_DL)
16122 if (!ssllib_dll_handle) {
16124 load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
16125 if (!ssllib_dll_handle) {
16126#if !defined(OPENSSL_API_1_1)
16128#endif
16129 DEBUG_TRACE("%s", ebuf);
16130 return 0;
16131 }
16132 }
16133#endif /* NO_SSL_DL */
16134
16135#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16136 && !defined(NO_SSL_DL)
16137 /* Initialize SSL library */
16138 OPENSSL_init_ssl(0, NULL);
16139 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
16141 NULL);
16142#else
16143 /* Initialize SSL library */
16144 SSL_library_init();
16145 SSL_load_error_strings();
16146#endif
16147
16148 return 1;
16149}
16150
16151
16152static int
16154 struct mg_domain_context *dom_ctx,
16155 const char *pem,
16156 const char *chain)
16157{
16158 if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
16159 mg_cry_ctx_internal(phys_ctx,
16160 "%s: cannot open certificate file %s: %s",
16161 __func__,
16162 pem,
16163 ssl_error());
16164 return 0;
16165 }
16166
16167 /* could use SSL_CTX_set_default_passwd_cb_userdata */
16168 if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
16169 mg_cry_ctx_internal(phys_ctx,
16170 "%s: cannot open private key file %s: %s",
16171 __func__,
16172 pem,
16173 ssl_error());
16174 return 0;
16175 }
16176
16177 if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
16178 mg_cry_ctx_internal(phys_ctx,
16179 "%s: certificate and private key do not match: %s",
16180 __func__,
16181 pem);
16182 return 0;
16183 }
16184
16185 /* In contrast to OpenSSL, wolfSSL does not support certificate
16186 * chain files that contain private keys and certificates in
16187 * SSL_CTX_use_certificate_chain_file.
16188 * The CivetWeb-Server used pem-Files that contained both information.
16189 * In order to make wolfSSL work, it is split in two files.
16190 * One file that contains key and certificate used by the server and
16191 * an optional chain file for the ssl stack.
16192 */
16193 if (chain) {
16194 if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
16195 mg_cry_ctx_internal(phys_ctx,
16196 "%s: cannot use certificate chain file %s: %s",
16197 __func__,
16198 chain,
16199 ssl_error());
16200 return 0;
16201 }
16202 }
16203 return 1;
16204}
16205
16206
16207#if defined(OPENSSL_API_1_1)
16208static unsigned long
16209ssl_get_protocol(int version_id)
16210{
16211 long unsigned ret = (long unsigned)SSL_OP_ALL;
16212 if (version_id > 0)
16213 ret |= SSL_OP_NO_SSLv2;
16214 if (version_id > 1)
16215 ret |= SSL_OP_NO_SSLv3;
16216 if (version_id > 2)
16217 ret |= SSL_OP_NO_TLSv1;
16218 if (version_id > 3)
16219 ret |= SSL_OP_NO_TLSv1_1;
16220 if (version_id > 4)
16221 ret |= SSL_OP_NO_TLSv1_2;
16222#if defined(SSL_OP_NO_TLSv1_3)
16223 if (version_id > 5)
16224 ret |= SSL_OP_NO_TLSv1_3;
16225#endif
16226 return ret;
16227}
16228#else
16229static long
16230ssl_get_protocol(int version_id)
16231{
16232 unsigned long ret = (unsigned long)SSL_OP_ALL;
16233 if (version_id > 0)
16234 ret |= SSL_OP_NO_SSLv2;
16235 if (version_id > 1)
16236 ret |= SSL_OP_NO_SSLv3;
16237 if (version_id > 2)
16238 ret |= SSL_OP_NO_TLSv1;
16239 if (version_id > 3)
16240 ret |= SSL_OP_NO_TLSv1_1;
16241 if (version_id > 4)
16242 ret |= SSL_OP_NO_TLSv1_2;
16243#if defined(SSL_OP_NO_TLSv1_3)
16244 if (version_id > 5)
16245 ret |= SSL_OP_NO_TLSv1_3;
16246#endif
16247 return (long)ret;
16248}
16249#endif /* OPENSSL_API_1_1 */
16250
16251
16252/* SSL callback documentation:
16253 * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
16254 * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
16255 * https://linux.die.net/man/3/ssl_set_info_callback */
16256/* Note: There is no "const" for the first argument in the documentation
16257 * examples, however some (maybe most, but not all) headers of OpenSSL
16258 * versions / OpenSSL compatibility layers have it. Having a different
16259 * definition will cause a warning in C and an error in C++. Use "const SSL
16260 * *", while automatical conversion from "SSL *" works for all compilers,
16261 * but not other way around */
16262static void
16263ssl_info_callback(const SSL *ssl, int what, int ret)
16264{
16265 (void)ret;
16266
16268 SSL_get_app_data(ssl);
16269 }
16271 /* TODO: check for openSSL 1.1 */
16272 //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
16273 // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
16274 }
16275}
16276
16277
16278static int
16279ssl_servername_callback(SSL *ssl, int *ad, void *arg)
16280{
16281#if defined(GCC_DIAGNOSTIC)
16282#pragma GCC diagnostic push
16283#pragma GCC diagnostic ignored "-Wcast-align"
16284#endif /* defined(GCC_DIAGNOSTIC) */
16285
16286 /* We used an aligned pointer in SSL_set_app_data */
16287 struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
16288
16289#if defined(GCC_DIAGNOSTIC)
16290#pragma GCC diagnostic pop
16291#endif /* defined(GCC_DIAGNOSTIC) */
16292
16293 const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
16294
16295 (void)ad;
16296 (void)arg;
16297
16298 if ((conn == NULL) || (conn->phys_ctx == NULL)) {
16299 DEBUG_ASSERT(0);
16300 return SSL_TLSEXT_ERR_NOACK;
16301 }
16302 conn->dom_ctx = &(conn->phys_ctx->dd);
16303
16304 /* Old clients (Win XP) will not support SNI. Then, there
16305 * is no server name available in the request - we can
16306 * only work with the default certificate.
16307 * Multiple HTTPS hosts on one IP+port are only possible
16308 * with a certificate containing all alternative names.
16309 */
16310 if ((servername == NULL) || (*servername == 0)) {
16311 DEBUG_TRACE("%s", "SSL connection not supporting SNI");
16313 SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
16315 return SSL_TLSEXT_ERR_NOACK;
16316 }
16317
16318 DEBUG_TRACE("TLS connection to host %s", servername);
16319
16320 while (conn->dom_ctx) {
16321 if (!mg_strcasecmp(servername,
16323 /* Found matching domain */
16324 DEBUG_TRACE("TLS domain %s found",
16326 break;
16327 }
16329 conn->dom_ctx = conn->dom_ctx->next;
16331 }
16332
16333 if (conn->dom_ctx == NULL) {
16334 /* Default domain */
16335 DEBUG_TRACE("TLS default domain %s used",
16337 conn->dom_ctx = &(conn->phys_ctx->dd);
16338 }
16340 SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
16342 return SSL_TLSEXT_ERR_OK;
16343}
16344
16345
16346#if defined(USE_ALPN)
16347static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
16348static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
16349 alpn_proto_list + 3 + 8,
16350 NULL};
16351#if defined(USE_HTTP2)
16352static const char *alpn_proto_order_http2[] = {alpn_proto_list,
16353 alpn_proto_list + 3,
16354 alpn_proto_list + 3 + 8,
16355 NULL};
16356#endif
16357
16358static int
16359alpn_select_cb(SSL *ssl,
16360 const unsigned char **out,
16361 unsigned char *outlen,
16362 const unsigned char *in,
16363 unsigned int inlen,
16364 void *arg)
16365{
16366 struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
16367 unsigned int i, j, enable_http2 = 0;
16368 const char **alpn_proto_order = alpn_proto_order_http1;
16369
16370 struct mg_workerTLS *tls =
16371 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
16372
16373 (void)ssl;
16374
16375 if (tls == NULL) {
16376 /* Need to store protocol in Thread Local Storage */
16377 /* If there is no Thread Local Storage, don't use ALPN */
16378 return SSL_TLSEXT_ERR_NOACK;
16379 }
16380
16381#if defined(USE_HTTP2)
16382 enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
16383 if (enable_http2) {
16384 alpn_proto_order = alpn_proto_order_http2;
16385 }
16386#endif
16387
16388 for (j = 0; alpn_proto_order[j] != NULL; j++) {
16389 /* check all accepted protocols in this order */
16390 const char *alpn_proto = alpn_proto_order[j];
16391 /* search input for matching protocol */
16392 for (i = 0; i < inlen; i++) {
16393 if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
16394 *out = in + i + 1;
16395 *outlen = in[i];
16396 tls->alpn_proto = alpn_proto;
16397 return SSL_TLSEXT_ERR_OK;
16398 }
16399 }
16400 }
16401
16402 /* Nothing found */
16403 return SSL_TLSEXT_ERR_NOACK;
16404}
16405
16406
16407static int
16408next_protos_advertised_cb(SSL *ssl,
16409 const unsigned char **data,
16410 unsigned int *len,
16411 void *arg)
16412{
16413 struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
16414 *data = (const unsigned char *)alpn_proto_list;
16415 *len = (unsigned int)strlen((const char *)data);
16416
16417 (void)ssl;
16418 (void)dom_ctx;
16419
16420 return SSL_TLSEXT_ERR_OK;
16421}
16422
16423
16424static int
16425init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16426{
16427 unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
16428 int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
16429 (const unsigned char *)alpn_proto_list,
16430 alpn_len);
16431 if (ret != 0) {
16432 mg_cry_ctx_internal(phys_ctx,
16433 "SSL_CTX_set_alpn_protos error: %s",
16434 ssl_error());
16435 }
16436
16437 SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
16438 alpn_select_cb,
16439 (void *)dom_ctx);
16440
16441 SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
16442 next_protos_advertised_cb,
16443 (void *)dom_ctx);
16444
16445 return ret;
16446}
16447#endif
16448
16449
16450/* Setup SSL CTX as required by CivetWeb */
16451static int
16453 struct mg_domain_context *dom_ctx,
16454 const char *pem,
16455 const char *chain)
16456{
16457 int callback_ret;
16458 int should_verify_peer;
16459 int peer_certificate_optional;
16460 const char *ca_path;
16461 const char *ca_file;
16462 int use_default_verify_paths;
16463 int verify_depth;
16464 struct timespec now_mt;
16465 md5_byte_t ssl_context_id[16];
16466 md5_state_t md5state;
16467 int protocol_ver;
16468 int ssl_cache_timeout;
16469
16470#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16471 && !defined(NO_SSL_DL)
16472 if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
16473 mg_cry_ctx_internal(phys_ctx,
16474 "SSL_CTX_new (server) error: %s",
16475 ssl_error());
16476 return 0;
16477 }
16478#else
16479 if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
16480 mg_cry_ctx_internal(phys_ctx,
16481 "SSL_CTX_new (server) error: %s",
16482 ssl_error());
16483 return 0;
16484 }
16485#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16486
16487#if defined(SSL_OP_NO_TLSv1_3)
16488 SSL_CTX_clear_options(dom_ctx->ssl_ctx,
16492#else
16493 SSL_CTX_clear_options(dom_ctx->ssl_ctx,
16496#endif
16497
16498 protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
16499 SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
16500 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
16501 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
16502 SSL_CTX_set_options(dom_ctx->ssl_ctx,
16504 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
16505
16506#if defined(SSL_OP_NO_RENEGOTIATION)
16507 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
16508#endif
16509
16510#if !defined(NO_SSL_DL)
16511 SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
16512#endif /* NO_SSL_DL */
16513
16514 /* In SSL documentation examples callback defined without const
16515 * specifier 'void (*)(SSL *, int, int)' See:
16516 * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
16517 * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
16518 * But in the source code const SSL is used:
16519 * 'void (*)(const SSL *, int, int)' See:
16520 * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
16521 * Problem about wrong documentation described, but not resolved:
16522 * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
16523 * Wrong const cast ignored on C or can be suppressed by compiler flags.
16524 * But when compiled with modern C++ compiler, correct const should be
16525 * provided
16526 */
16527 SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
16528
16529 SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
16531
16532 /* If a callback has been specified, call it. */
16533 callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
16534 ? 0
16535 : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
16536 phys_ctx->user_data));
16537
16538 /* If callback returns 0, civetweb sets up the SSL certificate.
16539 * If it returns 1, civetweb assumes the calback already did this.
16540 * If it returns -1, initializing ssl fails. */
16541 if (callback_ret < 0) {
16542 mg_cry_ctx_internal(phys_ctx,
16543 "SSL callback returned error: %i",
16544 callback_ret);
16545 return 0;
16546 }
16547 if (callback_ret > 0) {
16548 /* Callback did everything. */
16549 return 1;
16550 }
16551
16552 /* If a domain callback has been specified, call it. */
16553 callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
16554 ? 0
16555 : (phys_ctx->callbacks.init_ssl_domain(
16556 dom_ctx->config[AUTHENTICATION_DOMAIN],
16557 dom_ctx->ssl_ctx,
16558 phys_ctx->user_data));
16559
16560 /* If domain callback returns 0, civetweb sets up the SSL certificate.
16561 * If it returns 1, civetweb assumes the calback already did this.
16562 * If it returns -1, initializing ssl fails. */
16563 if (callback_ret < 0) {
16564 mg_cry_ctx_internal(phys_ctx,
16565 "Domain SSL callback returned error: %i",
16566 callback_ret);
16567 return 0;
16568 }
16569 if (callback_ret > 0) {
16570 /* Domain callback did everything. */
16571 return 1;
16572 }
16573
16574 /* Use some combination of start time, domain and port as a SSL
16575 * context ID. This should be unique on the current machine. */
16576 md5_init(&md5state);
16577 clock_gettime(CLOCK_MONOTONIC, &now_mt);
16578 md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
16579 md5_append(&md5state,
16580 (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
16581 strlen(phys_ctx->dd.config[LISTENING_PORTS]));
16582 md5_append(&md5state,
16583 (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
16584 strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
16585 md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
16586 md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
16587 md5_finish(&md5state, ssl_context_id);
16588
16589 SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
16590 (unsigned char *)ssl_context_id,
16591 sizeof(ssl_context_id));
16592
16593 if (pem != NULL) {
16594 if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
16595 return 0;
16596 }
16597 }
16598
16599 /* Should we support client certificates? */
16600 /* Default is "no". */
16601 should_verify_peer = 0;
16602 peer_certificate_optional = 0;
16603 if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
16604 if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
16605 /* Yes, they are mandatory */
16606 should_verify_peer = 1;
16607 } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
16608 "optional")
16609 == 0) {
16610 /* Yes, they are optional */
16611 should_verify_peer = 1;
16612 peer_certificate_optional = 1;
16613 }
16614 }
16615
16616 use_default_verify_paths =
16617 (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
16618 && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
16619 == 0);
16620
16621 if (should_verify_peer) {
16622 ca_path = dom_ctx->config[SSL_CA_PATH];
16623 ca_file = dom_ctx->config[SSL_CA_FILE];
16624 if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
16625 != 1) {
16626 mg_cry_ctx_internal(phys_ctx,
16627 "SSL_CTX_load_verify_locations error: %s "
16628 "ssl_verify_peer requires setting "
16629 "either ssl_ca_path or ssl_ca_file. "
16630 "Is any of them present in the "
16631 ".conf file?",
16632 ssl_error());
16633 return 0;
16634 }
16635
16636 if (peer_certificate_optional) {
16637 SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
16638 } else {
16639 SSL_CTX_set_verify(dom_ctx->ssl_ctx,
16642 NULL);
16643 }
16644
16645 if (use_default_verify_paths
16646 && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
16647 mg_cry_ctx_internal(phys_ctx,
16648 "SSL_CTX_set_default_verify_paths error: %s",
16649 ssl_error());
16650 return 0;
16651 }
16652
16653 if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
16654 verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
16655 SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
16656 }
16657 }
16658
16659 if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
16660 if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
16661 dom_ctx->config[SSL_CIPHER_LIST])
16662 != 1) {
16663 mg_cry_ctx_internal(phys_ctx,
16664 "SSL_CTX_set_cipher_list error: %s",
16665 ssl_error());
16666 }
16667 }
16668
16669 /* SSL session caching */
16670 ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
16671 ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
16672 : 0);
16673 if (ssl_cache_timeout > 0) {
16674 SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
16675 /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
16676 * default */
16677 SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
16678 }
16679
16680#if defined(USE_ALPN)
16681 /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
16682#if !defined(NO_SSL_DL)
16684#endif
16685 {
16686 init_alpn(phys_ctx, dom_ctx);
16687 }
16688#endif
16689
16690 return 1;
16691}
16692
16693
16694/* Check if SSL is required.
16695 * If so, dynamically load SSL library
16696 * and set up ctx->ssl_ctx pointer. */
16697static int
16698init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16699{
16700 void *ssl_ctx = 0;
16701 int callback_ret;
16702 const char *pem;
16703 const char *chain;
16704 char ebuf[128];
16705
16706 if (!phys_ctx) {
16707 return 0;
16708 }
16709
16710 if (!dom_ctx) {
16711 dom_ctx = &(phys_ctx->dd);
16712 }
16713
16714 if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
16715 /* No SSL port is set. No need to setup SSL. */
16716 return 1;
16717 }
16718
16719 /* Check for external SSL_CTX */
16720 callback_ret =
16721 (phys_ctx->callbacks.external_ssl_ctx == NULL)
16722 ? 0
16723 : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
16724 phys_ctx->user_data));
16725
16726 if (callback_ret < 0) {
16727 /* Callback exists and returns <0: Initializing failed. */
16728 mg_cry_ctx_internal(phys_ctx,
16729 "external_ssl_ctx callback returned error: %i",
16730 callback_ret);
16731 return 0;
16732 } else if (callback_ret > 0) {
16733 /* Callback exists and returns >0: Initializing complete,
16734 * civetweb should not modify the SSL context. */
16735 dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
16736 if (!initialize_openssl(ebuf, sizeof(ebuf))) {
16737 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16738 return 0;
16739 }
16740 return 1;
16741 }
16742 /* If the callback does not exist or return 0, civetweb must initialize
16743 * the SSL context. Handle "domain" callback next. */
16744
16745 /* Check for external domain SSL_CTX callback. */
16746 callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
16747 ? 0
16749 dom_ctx->config[AUTHENTICATION_DOMAIN],
16750 &ssl_ctx,
16751 phys_ctx->user_data));
16752
16753 if (callback_ret < 0) {
16754 /* Callback < 0: Error. Abort init. */
16756 phys_ctx,
16757 "external_ssl_ctx_domain callback returned error: %i",
16758 callback_ret);
16759 return 0;
16760 } else if (callback_ret > 0) {
16761 /* Callback > 0: Consider init done. */
16762 dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
16763 if (!initialize_openssl(ebuf, sizeof(ebuf))) {
16764 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16765 return 0;
16766 }
16767 return 1;
16768 }
16769 /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
16770 * 0, CivetWeb should continue initializing SSL */
16771
16772 /* If PEM file is not specified and the init_ssl callbacks
16773 * are not specified, setup will fail. */
16774 if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
16775 && (phys_ctx->callbacks.init_ssl == NULL)
16776 && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
16777 /* No certificate and no init_ssl callbacks:
16778 * Essential data to set up TLS is missing.
16779 */
16780 mg_cry_ctx_internal(phys_ctx,
16781 "Initializing SSL failed: -%s is not set",
16783 return 0;
16784 }
16785
16786 /* If a certificate chain is configured, use it. */
16787 chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
16788 if (chain == NULL) {
16789 /* Default: certificate chain in PEM file */
16790 chain = pem;
16791 }
16792 if ((chain != NULL) && (*chain == 0)) {
16793 /* If the chain is an empty string, don't use it. */
16794 chain = NULL;
16795 }
16796
16797 if (!initialize_openssl(ebuf, sizeof(ebuf))) {
16798 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16799 return 0;
16800 }
16801
16802 return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
16803}
16804
16805
16806static void
16808{
16809#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
16810
16811 if (mg_atomic_dec(&cryptolib_users) == 0) {
16812
16813 /* Shutdown according to
16814 * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
16815 * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
16816 */
16817 CONF_modules_unload(1);
16818#else
16819 int i;
16820
16821 if (mg_atomic_dec(&cryptolib_users) == 0) {
16822
16823 /* Shutdown according to
16824 * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
16825 * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
16826 */
16827 CRYPTO_set_locking_callback(NULL);
16828 CRYPTO_set_id_callback(NULL);
16829 ENGINE_cleanup();
16830 CONF_modules_unload(1);
16831 ERR_free_strings();
16832 EVP_cleanup();
16833 CRYPTO_cleanup_all_ex_data();
16834 OPENSSL_REMOVE_THREAD_STATE();
16835
16836 for (i = 0; i < CRYPTO_num_locks(); i++) {
16837 pthread_mutex_destroy(&ssl_mutexes[i]);
16838 }
16840 ssl_mutexes = NULL;
16841#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16842 }
16843}
16844#endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
16845
16846
16847#if !defined(NO_FILESYSTEMS)
16848static int
16849set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16850{
16851 if (phys_ctx) {
16852 struct mg_file file = STRUCT_FILE_INITIALIZER;
16853 const char *path;
16854 struct mg_connection fc;
16855 if (!dom_ctx) {
16856 dom_ctx = &(phys_ctx->dd);
16857 }
16859 if ((path != NULL)
16860 && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
16862 "Cannot open %s: %s",
16863 path,
16864 strerror(ERRNO));
16865 return 0;
16866 }
16867 return 1;
16868 }
16869 return 0;
16870}
16871#endif /* NO_FILESYSTEMS */
16872
16873
16874static int
16876{
16877 union usa sa;
16878 memset(&sa, 0, sizeof(sa));
16879#if defined(USE_IPV6)
16880 sa.sin6.sin6_family = AF_INET6;
16881#else
16882 sa.sin.sin_family = AF_INET;
16883#endif
16884 return check_acl(phys_ctx, &sa) != -1;
16885}
16886
16887
16888static void
16890{
16891 if (!conn) {
16892 return;
16893 }
16894
16895 conn->num_bytes_sent = conn->consumed_content = 0;
16896
16897 conn->path_info = NULL;
16898 conn->status_code = -1;
16899 conn->content_len = -1;
16900 conn->is_chunked = 0;
16901 conn->must_close = 0;
16902 conn->request_len = 0;
16903 conn->request_state = 0;
16904 conn->throttle = 0;
16905 conn->accept_gzip = 0;
16906
16910 conn->response_info.status_text = NULL;
16911 conn->response_info.status_code = 0;
16912
16913 conn->request_info.remote_user = NULL;
16914 conn->request_info.request_method = NULL;
16915 conn->request_info.request_uri = NULL;
16916
16917 /* Free cleaned local URI (if any) */
16918 if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
16919 mg_free((void *)conn->request_info.local_uri);
16920 conn->request_info.local_uri = NULL;
16921 }
16922 conn->request_info.local_uri = NULL;
16923
16924#if defined(USE_SERVER_STATS)
16925 conn->processing_time = 0;
16926#endif
16927}
16928
16929
16930static int
16931set_tcp_nodelay(const struct socket *so, int nodelay_on)
16932{
16933 if ((so->lsa.sa.sa_family == AF_INET)
16934 || (so->lsa.sa.sa_family == AF_INET6)) {
16935 /* Only for TCP sockets */
16936 if (setsockopt(so->sock,
16937 IPPROTO_TCP,
16938 TCP_NODELAY,
16939 (SOCK_OPT_TYPE)&nodelay_on,
16940 sizeof(nodelay_on))
16941 != 0) {
16942 /* Error */
16943 return 1;
16944 }
16945 }
16946 /* OK */
16947 return 0;
16948}
16949
16950
16951#if !defined(__ZEPHYR__)
16952static void
16954{
16955#if defined(_WIN32)
16956 char buf[MG_BUF_LEN];
16957 int n;
16958#endif
16959 struct linger linger;
16960 int error_code = 0;
16961 int linger_timeout = -2;
16962 socklen_t opt_len = sizeof(error_code);
16963
16964 if (!conn) {
16965 return;
16966 }
16967
16968 /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
16969 * "Note that enabling a nonzero timeout on a nonblocking socket
16970 * is not recommended.", so set it to blocking now */
16972
16973 /* Send FIN to the client */
16974 shutdown(conn->client.sock, SHUTDOWN_WR);
16975
16976
16977#if defined(_WIN32)
16978 /* Read and discard pending incoming data. If we do not do that and
16979 * close
16980 * the socket, the data in the send buffer may be discarded. This
16981 * behaviour is seen on Windows, when client keeps sending data
16982 * when server decides to close the connection; then when client
16983 * does recv() it gets no data back. */
16984 do {
16985 n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
16986 } while (n > 0);
16987#endif
16988
16989 if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
16990 linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
16991 }
16992
16993 /* Set linger option according to configuration */
16994 if (linger_timeout >= 0) {
16995 /* Set linger option to avoid socket hanging out after close. This
16996 * prevent ephemeral port exhaust problem under high QPS. */
16997 linger.l_onoff = 1;
16998
16999#if defined(_MSC_VER)
17000#pragma warning(push)
17001#pragma warning(disable : 4244)
17002#endif
17003#if defined(GCC_DIAGNOSTIC)
17004#pragma GCC diagnostic push
17005#pragma GCC diagnostic ignored "-Wconversion"
17006#endif
17007 /* Data type of linger structure elements may differ,
17008 * so we don't know what cast we need here.
17009 * Disable type conversion warnings. */
17010
17011 linger.l_linger = (linger_timeout + 999) / 1000;
17012
17013#if defined(GCC_DIAGNOSTIC)
17014#pragma GCC diagnostic pop
17015#endif
17016#if defined(_MSC_VER)
17017#pragma warning(pop)
17018#endif
17019
17020 } else {
17021 linger.l_onoff = 0;
17022 linger.l_linger = 0;
17023 }
17024
17025 if (linger_timeout < -1) {
17026 /* Default: don't configure any linger */
17027 } else if (getsockopt(conn->client.sock,
17028 SOL_SOCKET,
17029 SO_ERROR,
17030#if defined(_WIN32) /* WinSock uses different data type here */
17031 (char *)&error_code,
17032#else
17033 &error_code,
17034#endif
17035 &opt_len)
17036 != 0) {
17037 /* Cannot determine if socket is already closed. This should
17038 * not occur and never did in a test. Log an error message
17039 * and continue. */
17040 mg_cry_internal(conn,
17041 "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
17042 __func__,
17043 strerror(ERRNO));
17044#if defined(_WIN32)
17045 } else if (error_code == WSAECONNRESET) {
17046#else
17047 } else if (error_code == ECONNRESET) {
17048#endif
17049 /* Socket already closed by client/peer, close socket without linger
17050 */
17051 } else {
17052
17053 /* Set linger timeout */
17054 if (setsockopt(conn->client.sock,
17055 SOL_SOCKET,
17056 SO_LINGER,
17057 (char *)&linger,
17058 sizeof(linger))
17059 != 0) {
17061 conn,
17062 "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
17063 __func__,
17064 linger.l_onoff,
17065 linger.l_linger,
17066 strerror(ERRNO));
17067 }
17068 }
17069
17070 /* Now we know that our FIN is ACK-ed, safe to close */
17071 closesocket(conn->client.sock);
17072 conn->client.sock = INVALID_SOCKET;
17073}
17074#endif
17075
17076
17077static void
17079{
17080#if defined(USE_SERVER_STATS)
17081 conn->conn_state = 6; /* to close */
17082#endif
17083
17084#if defined(USE_LUA) && defined(USE_WEBSOCKET)
17085 if (conn->lua_websocket_state) {
17086 lua_websocket_close(conn, conn->lua_websocket_state);
17087 conn->lua_websocket_state = NULL;
17088 }
17089#endif
17090
17091 mg_lock_connection(conn);
17092
17093 /* Set close flag, so keep-alive loops will stop */
17094 conn->must_close = 1;
17095
17096 /* call the connection_close callback if assigned */
17097 if (conn->phys_ctx->callbacks.connection_close != NULL) {
17098 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17099 conn->phys_ctx->callbacks.connection_close(conn);
17100 }
17101 }
17102
17103 /* Reset user data, after close callback is called.
17104 * Do not reuse it. If the user needs a destructor,
17105 * it must be done in the connection_close callback. */
17106 mg_set_user_connection_data(conn, NULL);
17107
17108
17109#if defined(USE_SERVER_STATS)
17110 conn->conn_state = 7; /* closing */
17111#endif
17112
17113#if defined(USE_MBEDTLS)
17114 if (conn->ssl != NULL) {
17115 mbed_ssl_close(conn->ssl);
17116 conn->ssl = NULL;
17117 }
17118#elif !defined(NO_SSL)
17119 if (conn->ssl != NULL) {
17120 /* Run SSL_shutdown twice to ensure completely close SSL connection
17121 */
17122 SSL_shutdown(conn->ssl);
17123 SSL_free(conn->ssl);
17124 OPENSSL_REMOVE_THREAD_STATE();
17125 conn->ssl = NULL;
17126 }
17127#endif
17128 if (conn->client.sock != INVALID_SOCKET) {
17129#if defined(__ZEPHYR__)
17130 closesocket(conn->client.sock);
17131#else
17133#endif
17134 conn->client.sock = INVALID_SOCKET;
17135 }
17136
17137 /* call the connection_closed callback if assigned */
17138 if (conn->phys_ctx->callbacks.connection_closed != NULL) {
17139 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17141 }
17142 }
17143
17145
17146#if defined(USE_SERVER_STATS)
17147 conn->conn_state = 8; /* closed */
17148#endif
17149}
17150
17151
17152void
17154{
17155 if ((conn == NULL) || (conn->phys_ctx == NULL)) {
17156 return;
17157 }
17158
17159#if defined(USE_WEBSOCKET)
17160 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17161 if (conn->in_websocket_handling) {
17162 /* Set close flag, so the server thread can exit. */
17163 conn->must_close = 1;
17164 return;
17165 }
17166 }
17167 if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
17168
17169 unsigned int i;
17170
17171 /* client context: loops must end */
17173 conn->must_close = 1;
17174
17175 /* We need to get the client thread out of the select/recv call
17176 * here. */
17177 /* Since we use a sleep quantum of some seconds to check for recv
17178 * timeouts, we will just wait a few seconds in mg_join_thread. */
17179
17180 /* join worker thread */
17181 for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
17183 }
17184 }
17185#endif /* defined(USE_WEBSOCKET) */
17186
17187 close_connection(conn);
17188
17189#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17192 && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
17193 SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
17194 }
17195#endif
17196
17197#if defined(USE_WEBSOCKET)
17198 if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
17200 (void)pthread_mutex_destroy(&conn->mutex);
17201 mg_free(conn);
17202 } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
17203 (void)pthread_mutex_destroy(&conn->mutex);
17204 mg_free(conn);
17205 }
17206#else
17207 if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
17208 (void)pthread_mutex_destroy(&conn->mutex);
17209 mg_free(conn);
17210 }
17211#endif /* defined(USE_WEBSOCKET) */
17212}
17213
17214
17215static struct mg_connection *
17216mg_connect_client_impl(const struct mg_client_options *client_options,
17217 int use_ssl,
17218 char *ebuf,
17219 size_t ebuf_len)
17220{
17221 struct mg_connection *conn = NULL;
17222 SOCKET sock;
17223 union usa sa;
17224 struct sockaddr *psa;
17225 socklen_t len;
17226
17227 unsigned max_req_size =
17228 (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
17229
17230 /* Size of structures, aligned to 8 bytes */
17231 size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
17232 size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
17233
17234 conn =
17235 (struct mg_connection *)mg_calloc(1,
17236 conn_size + ctx_size + max_req_size);
17237
17238 if (conn == NULL) {
17239 mg_snprintf(NULL,
17240 NULL, /* No truncation check for ebuf */
17241 ebuf,
17242 ebuf_len,
17243 "calloc(): %s",
17244 strerror(ERRNO));
17245 return NULL;
17246 }
17247
17248#if defined(GCC_DIAGNOSTIC)
17249#pragma GCC diagnostic push
17250#pragma GCC diagnostic ignored "-Wcast-align"
17251#endif /* defined(GCC_DIAGNOSTIC) */
17252 /* conn_size is aligned to 8 bytes */
17253
17254 conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
17255
17256#if defined(GCC_DIAGNOSTIC)
17257#pragma GCC diagnostic pop
17258#endif /* defined(GCC_DIAGNOSTIC) */
17259
17260 conn->buf = (((char *)conn) + conn_size + ctx_size);
17261 conn->buf_size = (int)max_req_size;
17263 conn->dom_ctx = &(conn->phys_ctx->dd);
17264
17265 if (!connect_socket(conn->phys_ctx,
17266 client_options->host,
17267 client_options->port,
17268 use_ssl,
17269 ebuf,
17270 ebuf_len,
17271 &sock,
17272 &sa)) {
17273 /* ebuf is set by connect_socket,
17274 * free all memory and return NULL; */
17275 mg_free(conn);
17276 return NULL;
17277 }
17278
17279#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17280#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
17281 && !defined(NO_SSL_DL)
17282 if (use_ssl
17283 && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
17284 == NULL) {
17285 mg_snprintf(NULL,
17286 NULL, /* No truncation check for ebuf */
17287 ebuf,
17288 ebuf_len,
17289 "SSL_CTX_new error: %s",
17290 ssl_error());
17291 closesocket(sock);
17292 mg_free(conn);
17293 return NULL;
17294 }
17295#else
17296 if (use_ssl
17297 && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
17298 == NULL) {
17299 mg_snprintf(NULL,
17300 NULL, /* No truncation check for ebuf */
17301 ebuf,
17302 ebuf_len,
17303 "SSL_CTX_new error: %s",
17304 ssl_error());
17305 closesocket(sock);
17306 mg_free(conn);
17307 return NULL;
17308 }
17309#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
17310#endif /* NO_SSL */
17311
17312
17313#if defined(USE_IPV6)
17314 len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
17315 : sizeof(conn->client.rsa.sin6);
17316 psa = (sa.sa.sa_family == AF_INET)
17317 ? (struct sockaddr *)&(conn->client.rsa.sin)
17318 : (struct sockaddr *)&(conn->client.rsa.sin6);
17319#else
17320 len = sizeof(conn->client.rsa.sin);
17321 psa = (struct sockaddr *)&(conn->client.rsa.sin);
17322#endif
17323
17324 conn->client.sock = sock;
17325 conn->client.lsa = sa;
17326
17327 if (getsockname(sock, psa, &len) != 0) {
17328 mg_cry_internal(conn,
17329 "%s: getsockname() failed: %s",
17330 __func__,
17331 strerror(ERRNO));
17332 }
17333
17334 conn->client.is_ssl = use_ssl ? 1 : 0;
17335 if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
17336 mg_snprintf(NULL,
17337 NULL, /* No truncation check for ebuf */
17338 ebuf,
17339 ebuf_len,
17340 "Can not create mutex");
17341#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17342 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17343#endif
17344 closesocket(sock);
17345 mg_free(conn);
17346 return NULL;
17347 }
17348
17349
17350#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17351 if (use_ssl) {
17352 /* TODO: Check ssl_verify_peer and ssl_ca_path here.
17353 * SSL_CTX_set_verify call is needed to switch off server
17354 * certificate checking, which is off by default in OpenSSL and
17355 * on in yaSSL. */
17356 /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
17357 * SSL_VERIFY_PEER, verify_ssl_server); */
17358
17359 if (client_options->client_cert) {
17360 if (!ssl_use_pem_file(conn->phys_ctx,
17361 conn->dom_ctx,
17362 client_options->client_cert,
17363 NULL)) {
17364 mg_snprintf(NULL,
17365 NULL, /* No truncation check for ebuf */
17366 ebuf,
17367 ebuf_len,
17368 "Can not use SSL client certificate");
17369 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17370 closesocket(sock);
17371 mg_free(conn);
17372 return NULL;
17373 }
17374 }
17375
17376 if (client_options->server_cert) {
17377 if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
17378 client_options->server_cert,
17379 NULL)
17380 != 1) {
17381 mg_cry_internal(conn,
17382 "SSL_CTX_load_verify_locations error: %s ",
17383 ssl_error());
17384 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17385 closesocket(sock);
17386 mg_free(conn);
17387 return NULL;
17388 }
17389 SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
17390 } else {
17391 SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
17392 }
17393
17394 if (!sslize(conn, SSL_connect, client_options)) {
17395 mg_snprintf(NULL,
17396 NULL, /* No truncation check for ebuf */
17397 ebuf,
17398 ebuf_len,
17399 "SSL connection error");
17400 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17401 closesocket(sock);
17402 mg_free(conn);
17403 return NULL;
17404 }
17405 }
17406#endif
17407
17408 return conn;
17409}
17410
17411
17413mg_connect_client_secure(const struct mg_client_options *client_options,
17414 char *error_buffer,
17415 size_t error_buffer_size)
17416{
17417 return mg_connect_client_impl(client_options,
17418 1,
17419 error_buffer,
17420 error_buffer_size);
17421}
17422
17423
17424struct mg_connection *
17425mg_connect_client(const char *host,
17426 int port,
17427 int use_ssl,
17428 char *error_buffer,
17429 size_t error_buffer_size)
17430{
17431 struct mg_client_options opts;
17432 memset(&opts, 0, sizeof(opts));
17433 opts.host = host;
17434 opts.port = port;
17435 return mg_connect_client_impl(&opts,
17436 use_ssl,
17437 error_buffer,
17438 error_buffer_size);
17439}
17440
17441
17442#if defined(MG_EXPERIMENTAL_INTERFACES)
17443struct mg_connection *
17444mg_connect_client2(const char *host,
17445 const char *protocol,
17446 int port,
17447 const char *path,
17448 struct mg_init_data *init,
17449 struct mg_error_data *error)
17450{
17451 int is_ssl, is_ws;
17452 /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
17453
17454 if (error != NULL) {
17455 error->code = 0;
17456 if (error->text_buffer_size > 0) {
17457 *error->text = 0;
17458 }
17459 }
17460
17461 if ((host == NULL) || (protocol == NULL)) {
17462 if ((error != NULL) && (error->text_buffer_size > 0)) {
17463 mg_snprintf(NULL,
17464 NULL, /* No truncation check for error buffers */
17465 error->text,
17466 error->text_buffer_size,
17467 "%s",
17468 "Invalid parameters");
17469 }
17470 return NULL;
17471 }
17472
17473 /* check all known protocolls */
17474 if (!mg_strcasecmp(protocol, "http")) {
17475 is_ssl = 0;
17476 is_ws = 0;
17477 } else if (!mg_strcasecmp(protocol, "https")) {
17478 is_ssl = 1;
17479 is_ws = 0;
17480#if defined(USE_WEBSOCKET)
17481 } else if (!mg_strcasecmp(protocol, "ws")) {
17482 is_ssl = 0;
17483 is_ws = 1;
17484 } else if (!mg_strcasecmp(protocol, "wss")) {
17485 is_ssl = 1;
17486 is_ws = 1;
17487#endif
17488 } else {
17489 if ((error != NULL) && (error->text_buffer_size > 0)) {
17490 mg_snprintf(NULL,
17491 NULL, /* No truncation check for error buffers */
17492 error->text,
17493 error->text_buffer_size,
17494 "Protocol %s not supported",
17495 protocol);
17496 }
17497 return NULL;
17498 }
17499
17500 /* TODO: The current implementation here just calls the old
17501 * implementations, without using any new options. This is just a first
17502 * step to test the new interfaces. */
17503#if defined(USE_WEBSOCKET)
17504 if (is_ws) {
17505 /* TODO: implement all options */
17507 host,
17508 port,
17509 is_ssl,
17510 ((error != NULL) ? error->text : NULL),
17511 ((error != NULL) ? error->text_buffer_size : 0),
17512 (path ? path : ""),
17513 NULL /* TODO: origin */,
17514 experimental_websocket_client_data_wrapper,
17515 experimental_websocket_client_close_wrapper,
17516 (void *)init->callbacks);
17517 }
17518#endif
17519
17520 /* TODO: all additional options */
17521 struct mg_client_options opts;
17522 memset(&opts, 0, sizeof(opts));
17523 opts.host = host;
17524 opts.port = port;
17525 return mg_connect_client_impl(&opts,
17526 is_ssl,
17527 ((error != NULL) ? error->text : NULL),
17528 ((error != NULL) ? error->text_buffer_size
17529 : 0));
17530}
17531#endif
17532
17533
17534static const struct {
17535 const char *proto;
17538} abs_uri_protocols[] = {{"http://", 7, 80},
17539 {"https://", 8, 443},
17540 {"ws://", 5, 80},
17541 {"wss://", 6, 443},
17542 {NULL, 0, 0}};
17543
17544
17545/* Check if the uri is valid.
17546 * return 0 for invalid uri,
17547 * return 1 for *,
17548 * return 2 for relative uri,
17549 * return 3 for absolute uri without port,
17550 * return 4 for absolute uri with port */
17551static int
17552get_uri_type(const char *uri)
17553{
17554 int i;
17555 const char *hostend, *portbegin;
17556 char *portend;
17557 unsigned long port;
17558
17559 /* According to the HTTP standard
17560 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
17561 * URI can be an asterisk (*) or should start with slash (relative uri),
17562 * or it should start with the protocol (absolute uri). */
17563 if ((uri[0] == '*') && (uri[1] == '\0')) {
17564 /* asterisk */
17565 return 1;
17566 }
17567
17568 /* Valid URIs according to RFC 3986
17569 * (https://www.ietf.org/rfc/rfc3986.txt)
17570 * must only contain reserved characters :/?#[]@!$&'()*+,;=
17571 * and unreserved characters A-Z a-z 0-9 and -._~
17572 * and % encoded symbols.
17573 */
17574 for (i = 0; uri[i] != 0; i++) {
17575 if (uri[i] < 33) {
17576 /* control characters and spaces are invalid */
17577 return 0;
17578 }
17579 /* Allow everything else here (See #894) */
17580 }
17581
17582 /* A relative uri starts with a / character */
17583 if (uri[0] == '/') {
17584 /* relative uri */
17585 return 2;
17586 }
17587
17588 /* It could be an absolute uri: */
17589 /* This function only checks if the uri is valid, not if it is
17590 * addressing the current server. So civetweb can also be used
17591 * as a proxy server. */
17592 for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
17593 if (mg_strncasecmp(uri,
17596 == 0) {
17597
17598 hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
17599 if (!hostend) {
17600 return 0;
17601 }
17602 portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
17603 if (!portbegin) {
17604 return 3;
17605 }
17606
17607 port = strtoul(portbegin + 1, &portend, 10);
17608 if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
17609 return 0;
17610 }
17611
17612 return 4;
17613 }
17614 }
17615
17616 return 0;
17617}
17618
17619
17620/* Return NULL or the relative uri at the current server */
17621static const char *
17622get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
17623{
17624 const char *server_domain;
17625 size_t server_domain_len;
17626 size_t request_domain_len = 0;
17627 unsigned long port = 0;
17628 int i, auth_domain_check_enabled;
17629 const char *hostbegin = NULL;
17630 const char *hostend = NULL;
17631 const char *portbegin;
17632 char *portend;
17633
17634 auth_domain_check_enabled =
17636
17637 /* DNS is case insensitive, so use case insensitive string compare here
17638 */
17639 for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
17640 if (mg_strncasecmp(uri,
17643 == 0) {
17644
17645 hostbegin = uri + abs_uri_protocols[i].proto_len;
17646 hostend = strchr(hostbegin, '/');
17647 if (!hostend) {
17648 return 0;
17649 }
17650 portbegin = strchr(hostbegin, ':');
17651 if ((!portbegin) || (portbegin > hostend)) {
17652 port = abs_uri_protocols[i].default_port;
17653 request_domain_len = (size_t)(hostend - hostbegin);
17654 } else {
17655 port = strtoul(portbegin + 1, &portend, 10);
17656 if ((portend != hostend) || (port <= 0)
17657 || !is_valid_port(port)) {
17658 return 0;
17659 }
17660 request_domain_len = (size_t)(portbegin - hostbegin);
17661 }
17662 /* protocol found, port set */
17663 break;
17664 }
17665 }
17666
17667 if (!port) {
17668 /* port remains 0 if the protocol is not found */
17669 return 0;
17670 }
17671
17672 /* Check if the request is directed to a different server. */
17673 /* First check if the port is the same. */
17674 if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
17675 /* Request is directed to a different port */
17676 return 0;
17677 }
17678
17679 /* Finally check if the server corresponds to the authentication
17680 * domain of the server (the server domain).
17681 * Allow full matches (like http://mydomain.com/path/file.ext), and
17682 * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
17683 * but do not allow substrings (like
17684 * http://notmydomain.com/path/file.ext
17685 * or http://mydomain.com.fake/path/file.ext).
17686 */
17687 if (auth_domain_check_enabled) {
17688 server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
17689 server_domain_len = strlen(server_domain);
17690 if ((server_domain_len == 0) || (hostbegin == NULL)) {
17691 return 0;
17692 }
17693 if ((request_domain_len == server_domain_len)
17694 && (!memcmp(server_domain, hostbegin, server_domain_len))) {
17695 /* Request is directed to this server - full name match. */
17696 } else {
17697 if (request_domain_len < (server_domain_len + 2)) {
17698 /* Request is directed to another server: The server name
17699 * is longer than the request name.
17700 * Drop this case here to avoid overflows in the
17701 * following checks. */
17702 return 0;
17703 }
17704 if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
17705 /* Request is directed to another server: It could be a
17706 * substring
17707 * like notmyserver.com */
17708 return 0;
17709 }
17710 if (0
17711 != memcmp(server_domain,
17712 hostbegin + request_domain_len - server_domain_len,
17713 server_domain_len)) {
17714 /* Request is directed to another server:
17715 * The server name is different. */
17716 return 0;
17717 }
17718 }
17719 }
17720
17721 return hostend;
17722}
17723
17724
17725static int
17726get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17727{
17728 if (ebuf_len > 0) {
17729 ebuf[0] = '\0';
17730 }
17731 *err = 0;
17732
17734
17735 if (!conn) {
17736 mg_snprintf(conn,
17737 NULL, /* No truncation check for ebuf */
17738 ebuf,
17739 ebuf_len,
17740 "%s",
17741 "Internal error");
17742 *err = 500;
17743 return 0;
17744 }
17745
17746 /* Set the time the request was received. This value should be used for
17747 * timeouts. */
17748 clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
17749
17750 conn->request_len =
17751 read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
17752 DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
17753 if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
17754 mg_snprintf(conn,
17755 NULL, /* No truncation check for ebuf */
17756 ebuf,
17757 ebuf_len,
17758 "%s",
17759 "Invalid message size");
17760 *err = 500;
17761 return 0;
17762 }
17763
17764 if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
17765 mg_snprintf(conn,
17766 NULL, /* No truncation check for ebuf */
17767 ebuf,
17768 ebuf_len,
17769 "%s",
17770 "Message too large");
17771 *err = 413;
17772 return 0;
17773 }
17774
17775 if (conn->request_len <= 0) {
17776 if (conn->data_len > 0) {
17777 mg_snprintf(conn,
17778 NULL, /* No truncation check for ebuf */
17779 ebuf,
17780 ebuf_len,
17781 "%s",
17782 "Malformed message");
17783 *err = 400;
17784 } else {
17785 /* Server did not recv anything -> just close the connection */
17786 conn->must_close = 1;
17787 mg_snprintf(conn,
17788 NULL, /* No truncation check for ebuf */
17789 ebuf,
17790 ebuf_len,
17791 "%s",
17792 "No data received");
17793 *err = 0;
17794 }
17795 return 0;
17796 }
17797 return 1;
17798}
17799
17800
17801static int
17802get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17803{
17804 const char *cl;
17805
17806 conn->connection_type =
17807 CONNECTION_TYPE_REQUEST; /* request (valid of not) */
17808
17809 if (!get_message(conn, ebuf, ebuf_len, err)) {
17810 return 0;
17811 }
17812
17813 if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
17814 <= 0) {
17815 mg_snprintf(conn,
17816 NULL, /* No truncation check for ebuf */
17817 ebuf,
17818 ebuf_len,
17819 "%s",
17820 "Bad request");
17821 *err = 400;
17822 return 0;
17823 }
17824
17825 /* Message is a valid request */
17826
17827 if (!switch_domain_context(conn)) {
17828 mg_snprintf(conn,
17829 NULL, /* No truncation check for ebuf */
17830 ebuf,
17831 ebuf_len,
17832 "%s",
17833 "Bad request: Host mismatch");
17834 *err = 400;
17835 return 0;
17836 }
17837
17838#if USE_ZLIB
17839 if (((cl = get_header(conn->request_info.http_headers,
17841 "Accept-Encoding"))
17842 != NULL)
17843 && strstr(cl, "gzip")) {
17844 conn->accept_gzip = 1;
17845 }
17846#endif
17847 if (((cl = get_header(conn->request_info.http_headers,
17849 "Transfer-Encoding"))
17850 != NULL)
17851 && mg_strcasecmp(cl, "identity")) {
17852 if (mg_strcasecmp(cl, "chunked")) {
17853 mg_snprintf(conn,
17854 NULL, /* No truncation check for ebuf */
17855 ebuf,
17856 ebuf_len,
17857 "%s",
17858 "Bad request");
17859 *err = 400;
17860 return 0;
17861 }
17862 conn->is_chunked = 1;
17863 conn->content_len = 0; /* not yet read */
17864 } else if ((cl = get_header(conn->request_info.http_headers,
17866 "Content-Length"))
17867 != NULL) {
17868 /* Request has content length set */
17869 char *endptr = NULL;
17870 conn->content_len = strtoll(cl, &endptr, 10);
17871 if ((endptr == cl) || (conn->content_len < 0)) {
17872 mg_snprintf(conn,
17873 NULL, /* No truncation check for ebuf */
17874 ebuf,
17875 ebuf_len,
17876 "%s",
17877 "Bad request");
17878 *err = 411;
17879 return 0;
17880 }
17881 /* Publish the content length back to the request info. */
17883 } else {
17884 /* There is no exception, see RFC7230. */
17885 conn->content_len = 0;
17886 }
17887
17888 return 1;
17889}
17890
17891
17892/* conn is assumed to be valid in this internal function */
17893static int
17894get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17895{
17896 const char *cl;
17897
17898 conn->connection_type =
17899 CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
17900
17901 if (!get_message(conn, ebuf, ebuf_len, err)) {
17902 return 0;
17903 }
17904
17905 if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
17906 <= 0) {
17907 mg_snprintf(conn,
17908 NULL, /* No truncation check for ebuf */
17909 ebuf,
17910 ebuf_len,
17911 "%s",
17912 "Bad response");
17913 *err = 400;
17914 return 0;
17915 }
17916
17917 /* Message is a valid response */
17918
17919 if (((cl = get_header(conn->response_info.http_headers,
17921 "Transfer-Encoding"))
17922 != NULL)
17923 && mg_strcasecmp(cl, "identity")) {
17924 if (mg_strcasecmp(cl, "chunked")) {
17925 mg_snprintf(conn,
17926 NULL, /* No truncation check for ebuf */
17927 ebuf,
17928 ebuf_len,
17929 "%s",
17930 "Bad request");
17931 *err = 400;
17932 return 0;
17933 }
17934 conn->is_chunked = 1;
17935 conn->content_len = 0; /* not yet read */
17936 } else if ((cl = get_header(conn->response_info.http_headers,
17938 "Content-Length"))
17939 != NULL) {
17940 char *endptr = NULL;
17941 conn->content_len = strtoll(cl, &endptr, 10);
17942 if ((endptr == cl) || (conn->content_len < 0)) {
17943 mg_snprintf(conn,
17944 NULL, /* No truncation check for ebuf */
17945 ebuf,
17946 ebuf_len,
17947 "%s",
17948 "Bad request");
17949 *err = 411;
17950 return 0;
17951 }
17952 /* Publish the content length back to the response info. */
17954
17955 /* TODO: check if it is still used in response_info */
17957
17958 /* TODO: we should also consider HEAD method */
17959 if (conn->response_info.status_code == 304) {
17960 conn->content_len = 0;
17961 }
17962 } else {
17963 /* TODO: we should also consider HEAD method */
17964 if (((conn->response_info.status_code >= 100)
17965 && (conn->response_info.status_code <= 199))
17966 || (conn->response_info.status_code == 204)
17967 || (conn->response_info.status_code == 304)) {
17968 conn->content_len = 0;
17969 } else {
17970 conn->content_len = -1; /* unknown content length */
17971 }
17972 }
17973
17974 return 1;
17975}
17976
17977
17978int
17980 char *ebuf,
17981 size_t ebuf_len,
17982 int timeout)
17983{
17984 int err, ret;
17985 char txt[32]; /* will not overflow */
17986 char *save_timeout;
17987 char *new_timeout;
17988
17989 if (ebuf_len > 0) {
17990 ebuf[0] = '\0';
17991 }
17992
17993 if (!conn) {
17994 mg_snprintf(conn,
17995 NULL, /* No truncation check for ebuf */
17996 ebuf,
17997 ebuf_len,
17998 "%s",
17999 "Parameter error");
18000 return -1;
18001 }
18002
18003 /* Reset the previous responses */
18004 conn->data_len = 0;
18005
18006 /* Implementation of API function for HTTP clients */
18007 save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
18008
18009 if (timeout >= 0) {
18010 mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
18011 new_timeout = txt;
18012 } else {
18013 new_timeout = NULL;
18014 }
18015
18016 conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
18017 ret = get_response(conn, ebuf, ebuf_len, &err);
18018 conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
18019
18020 /* TODO: here, the URI is the http response code */
18023
18024 /* TODO (mid): Define proper return values - maybe return length?
18025 * For the first test use <0 for error and >0 for OK */
18026 return (ret == 0) ? -1 : +1;
18027}
18028
18029
18030struct mg_connection *
18031mg_download(const char *host,
18032 int port,
18033 int use_ssl,
18034 char *ebuf,
18035 size_t ebuf_len,
18036 const char *fmt,
18037 ...)
18038{
18039 struct mg_connection *conn;
18040 va_list ap;
18041 int i;
18042 int reqerr;
18043
18044 if (ebuf_len > 0) {
18045 ebuf[0] = '\0';
18046 }
18047
18048 va_start(ap, fmt);
18049
18050 /* open a connection */
18051 conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
18052
18053 if (conn != NULL) {
18054 i = mg_vprintf(conn, fmt, ap);
18055 if (i <= 0) {
18056 mg_snprintf(conn,
18057 NULL, /* No truncation check for ebuf */
18058 ebuf,
18059 ebuf_len,
18060 "%s",
18061 "Error sending request");
18062 } else {
18063 /* make sure the buffer is clear */
18064 conn->data_len = 0;
18065 get_response(conn, ebuf, ebuf_len, &reqerr);
18066
18067 /* TODO: here, the URI is the http response code */
18069 }
18070 }
18071
18072 /* if an error occurred, close the connection */
18073 if ((ebuf[0] != '\0') && (conn != NULL)) {
18074 mg_close_connection(conn);
18075 conn = NULL;
18076 }
18077
18078 va_end(ap);
18079 return conn;
18080}
18081
18082
18088};
18089
18090
18091#if defined(USE_WEBSOCKET)
18092#if defined(_WIN32)
18093static unsigned __stdcall websocket_client_thread(void *data)
18094#else
18095static void *
18096websocket_client_thread(void *data)
18097#endif
18098{
18099 struct websocket_client_thread_data *cdata =
18101
18102 void *user_thread_ptr = NULL;
18103
18104#if !defined(_WIN32) && !defined(__ZEPHYR__)
18105 struct sigaction sa;
18106
18107 /* Ignore SIGPIPE */
18108 memset(&sa, 0, sizeof(sa));
18109 sa.sa_handler = SIG_IGN;
18110 sigaction(SIGPIPE, &sa, NULL);
18111#endif
18112
18113 mg_set_thread_name("ws-clnt");
18114
18115 if (cdata->conn->phys_ctx) {
18116 if (cdata->conn->phys_ctx->callbacks.init_thread) {
18117 /* 3 indicates a websocket client thread */
18118 /* TODO: check if conn->phys_ctx can be set */
18119 user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
18120 cdata->conn->phys_ctx, 3);
18121 }
18122 }
18123
18124 read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
18125
18126 DEBUG_TRACE("%s", "Websocket client thread exited\n");
18127
18128 if (cdata->close_handler != NULL) {
18129 cdata->close_handler(cdata->conn, cdata->callback_data);
18130 }
18131
18132 /* The websocket_client context has only this thread. If it runs out,
18133 set the stop_flag to 2 (= "stopped"). */
18135
18136 if (cdata->conn->phys_ctx->callbacks.exit_thread) {
18138 3,
18139 user_thread_ptr);
18140 }
18141
18142 mg_free((void *)cdata);
18143
18144#if defined(_WIN32)
18145 return 0;
18146#else
18147 return NULL;
18148#endif
18149}
18150#endif
18151
18152
18153static struct mg_connection *
18155 int use_ssl,
18156 char *error_buffer,
18157 size_t error_buffer_size,
18158 const char *path,
18159 const char *origin,
18160 const char *extensions,
18161 mg_websocket_data_handler data_func,
18162 mg_websocket_close_handler close_func,
18163 void *user_data)
18164{
18165 struct mg_connection *conn = NULL;
18166
18167#if defined(USE_WEBSOCKET)
18168 struct websocket_client_thread_data *thread_data;
18169 static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
18170
18171 const char *host = client_options->host;
18172 int i;
18173
18174#if defined(__clang__)
18175#pragma clang diagnostic push
18176#pragma clang diagnostic ignored "-Wformat-nonliteral"
18177#endif
18178
18179 /* Establish the client connection and request upgrade */
18180 conn = mg_connect_client_impl(client_options,
18181 use_ssl,
18182 error_buffer,
18183 error_buffer_size);
18184
18185 /* Connection object will be null if something goes wrong */
18186 if (conn == NULL) {
18187 /* error_buffer should be already filled ... */
18188 if (!error_buffer[0]) {
18189 /* ... if not add an error message */
18191 NULL, /* No truncation check for ebuf */
18192 error_buffer,
18193 error_buffer_size,
18194 "Unexpected error");
18195 }
18196 return NULL;
18197 }
18198
18199 if (origin != NULL) {
18200 if (extensions != NULL) {
18201 i = mg_printf(conn,
18202 "GET %s HTTP/1.1\r\n"
18203 "Host: %s\r\n"
18204 "Upgrade: websocket\r\n"
18205 "Connection: Upgrade\r\n"
18206 "Sec-WebSocket-Key: %s\r\n"
18207 "Sec-WebSocket-Version: 13\r\n"
18208 "Sec-WebSocket-Extensions: %s\r\n"
18209 "Origin: %s\r\n"
18210 "\r\n",
18211 path,
18212 host,
18213 magic,
18214 extensions,
18215 origin);
18216 } else {
18217 i = mg_printf(conn,
18218 "GET %s HTTP/1.1\r\n"
18219 "Host: %s\r\n"
18220 "Upgrade: websocket\r\n"
18221 "Connection: Upgrade\r\n"
18222 "Sec-WebSocket-Key: %s\r\n"
18223 "Sec-WebSocket-Version: 13\r\n"
18224 "Origin: %s\r\n"
18225 "\r\n",
18226 path,
18227 host,
18228 magic,
18229 origin);
18230 }
18231 } else {
18232
18233 if (extensions != NULL) {
18234 i = mg_printf(conn,
18235 "GET %s HTTP/1.1\r\n"
18236 "Host: %s\r\n"
18237 "Upgrade: websocket\r\n"
18238 "Connection: Upgrade\r\n"
18239 "Sec-WebSocket-Key: %s\r\n"
18240 "Sec-WebSocket-Version: 13\r\n"
18241 "Sec-WebSocket-Extensions: %s\r\n"
18242 "\r\n",
18243 path,
18244 host,
18245 magic,
18246 extensions);
18247 } else {
18248 i = mg_printf(conn,
18249 "GET %s HTTP/1.1\r\n"
18250 "Host: %s\r\n"
18251 "Upgrade: websocket\r\n"
18252 "Connection: Upgrade\r\n"
18253 "Sec-WebSocket-Key: %s\r\n"
18254 "Sec-WebSocket-Version: 13\r\n"
18255 "\r\n",
18256 path,
18257 host,
18258 magic);
18259 }
18260 }
18261 if (i <= 0) {
18263 NULL, /* No truncation check for ebuf */
18264 error_buffer,
18265 error_buffer_size,
18266 "%s",
18267 "Error sending request");
18269 return NULL;
18270 }
18271
18272 conn->data_len = 0;
18273 if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
18275 return NULL;
18276 }
18279
18280#if defined(__clang__)
18281#pragma clang diagnostic pop
18282#endif
18283
18284 if (conn->response_info.status_code != 101) {
18285 /* We sent an "upgrade" request. For a correct websocket
18286 * protocol handshake, we expect a "101 Continue" response.
18287 * Otherwise it is a protocol violation. Maybe the HTTP
18288 * Server does not know websockets. */
18289 if (!*error_buffer) {
18290 /* set an error, if not yet set */
18292 NULL, /* No truncation check for ebuf */
18293 error_buffer,
18294 error_buffer_size,
18295 "Unexpected server reply");
18296 }
18297
18298 DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
18300 return NULL;
18301 }
18302
18303 thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
18304 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
18305 if (!thread_data) {
18306 DEBUG_TRACE("%s\r\n", "Out of memory");
18308 return NULL;
18309 }
18310
18311 thread_data->conn = conn;
18312 thread_data->data_handler = data_func;
18313 thread_data->close_handler = close_func;
18314 thread_data->callback_data = user_data;
18315
18317 (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
18319 DEBUG_TRACE("%s\r\n", "Out of memory");
18320 mg_free(thread_data);
18322 return NULL;
18323 }
18324
18325 /* Now upgrade to ws/wss client context */
18326 conn->phys_ctx->user_data = user_data;
18328 conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
18329
18330 /* Start a thread to read the websocket client connection
18331 * This thread will automatically stop when mg_disconnect is
18332 * called on the client connection */
18333 if (mg_start_thread_with_id(websocket_client_thread,
18334 thread_data,
18336 != 0) {
18338 mg_free(thread_data);
18340 conn = NULL;
18341 DEBUG_TRACE("%s",
18342 "Websocket client connect thread could not be started\r\n");
18343 }
18344
18345#else
18346 /* Appease "unused parameter" warnings */
18347 (void)client_options;
18348 (void)use_ssl;
18349 (void)error_buffer;
18350 (void)error_buffer_size;
18351 (void)path;
18352 (void)origin;
18353 (void)extensions;
18354 (void)user_data;
18355 (void)data_func;
18356 (void)close_func;
18357#endif
18358
18359 return conn;
18360}
18361
18362
18363struct mg_connection *
18365 int port,
18366 int use_ssl,
18367 char *error_buffer,
18368 size_t error_buffer_size,
18369 const char *path,
18370 const char *origin,
18371 mg_websocket_data_handler data_func,
18372 mg_websocket_close_handler close_func,
18373 void *user_data)
18374{
18375 struct mg_client_options client_options;
18376 memset(&client_options, 0, sizeof(client_options));
18377 client_options.host = host;
18378 client_options.port = port;
18379
18380 return mg_connect_websocket_client_impl(&client_options,
18381 use_ssl,
18382 error_buffer,
18383 error_buffer_size,
18384 path,
18385 origin,
18386 NULL,
18387 data_func,
18388 close_func,
18389 user_data);
18390}
18391
18392
18393struct mg_connection *
18395 const struct mg_client_options *client_options,
18396 char *error_buffer,
18397 size_t error_buffer_size,
18398 const char *path,
18399 const char *origin,
18400 mg_websocket_data_handler data_func,
18401 mg_websocket_close_handler close_func,
18402 void *user_data)
18403{
18404 if (!client_options) {
18405 return NULL;
18406 }
18407 return mg_connect_websocket_client_impl(client_options,
18408 1,
18409 error_buffer,
18410 error_buffer_size,
18411 path,
18412 origin,
18413 NULL,
18414 data_func,
18415 close_func,
18416 user_data);
18417}
18418
18419struct mg_connection *
18421 int port,
18422 int use_ssl,
18423 char *error_buffer,
18424 size_t error_buffer_size,
18425 const char *path,
18426 const char *origin,
18427 const char *extensions,
18428 mg_websocket_data_handler data_func,
18429 mg_websocket_close_handler close_func,
18430 void *user_data)
18431{
18432 struct mg_client_options client_options;
18433 memset(&client_options, 0, sizeof(client_options));
18434 client_options.host = host;
18435 client_options.port = port;
18436
18437 return mg_connect_websocket_client_impl(&client_options,
18438 use_ssl,
18439 error_buffer,
18440 error_buffer_size,
18441 path,
18442 origin,
18443 extensions,
18444 data_func,
18445 close_func,
18446 user_data);
18447}
18448
18449struct mg_connection *
18451 const struct mg_client_options *client_options,
18452 char *error_buffer,
18453 size_t error_buffer_size,
18454 const char *path,
18455 const char *origin,
18456 const char *extensions,
18457 mg_websocket_data_handler data_func,
18458 mg_websocket_close_handler close_func,
18459 void *user_data)
18460{
18461 if (!client_options) {
18462 return NULL;
18463 }
18464 return mg_connect_websocket_client_impl(client_options,
18465 1,
18466 error_buffer,
18467 error_buffer_size,
18468 path,
18469 origin,
18470 extensions,
18471 data_func,
18472 close_func,
18473 user_data);
18474}
18475
18476/* Prepare connection data structure */
18477static void
18479{
18480 /* Is keep alive allowed by the server */
18481 int keep_alive_enabled =
18483
18484 if (!keep_alive_enabled) {
18485 conn->must_close = 1;
18486 }
18487
18488 /* Important: on new connection, reset the receiving buffer. Credit
18489 * goes to crule42. */
18490 conn->data_len = 0;
18491 conn->handled_requests = 0;
18493 mg_set_user_connection_data(conn, NULL);
18494
18495#if defined(USE_SERVER_STATS)
18496 conn->conn_state = 2; /* init */
18497#endif
18498
18499 /* call the init_connection callback if assigned */
18500 if (conn->phys_ctx->callbacks.init_connection != NULL) {
18501 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
18502 void *conn_data = NULL;
18503 conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
18504 mg_set_user_connection_data(conn, conn_data);
18505 }
18506 }
18507}
18508
18509
18510/* Process a connection - may handle multiple requests
18511 * using the same connection.
18512 * Must be called with a valid connection (conn and
18513 * conn->phys_ctx must be valid).
18514 */
18515static void
18517{
18518 struct mg_request_info *ri = &conn->request_info;
18519 int keep_alive, discard_len;
18520 char ebuf[100];
18521 const char *hostend;
18522 int reqerr, uri_type;
18523
18524#if defined(USE_SERVER_STATS)
18525 ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
18526 mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
18527 mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
18528#endif
18529
18530 DEBUG_TRACE("Start processing connection from %s",
18532
18533 /* Loop over multiple requests sent using the same connection
18534 * (while "keep alive"). */
18535 do {
18536 DEBUG_TRACE("calling get_request (%i times for this connection)",
18537 conn->handled_requests + 1);
18538
18539#if defined(USE_SERVER_STATS)
18540 conn->conn_state = 3; /* ready */
18541#endif
18542
18543 if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
18544 /* The request sent by the client could not be understood by
18545 * the server, or it was incomplete or a timeout. Send an
18546 * error message and close the connection. */
18547 if (reqerr > 0) {
18548 DEBUG_ASSERT(ebuf[0] != '\0');
18549 mg_send_http_error(conn, reqerr, "%s", ebuf);
18550 }
18551
18552 } else if (strcmp(ri->http_version, "1.0")
18553 && strcmp(ri->http_version, "1.1")) {
18554 /* HTTP/2 is not allowed here */
18555 mg_snprintf(conn,
18556 NULL, /* No truncation check for ebuf */
18557 ebuf,
18558 sizeof(ebuf),
18559 "Bad HTTP version: [%s]",
18560 ri->http_version);
18561 mg_send_http_error(conn, 505, "%s", ebuf);
18562 }
18563
18564 if (ebuf[0] == '\0') {
18565 uri_type = get_uri_type(conn->request_info.request_uri);
18566 switch (uri_type) {
18567 case 1:
18568 /* Asterisk */
18569 conn->request_info.local_uri_raw = 0;
18570 /* TODO: Deal with '*'. */
18571 break;
18572 case 2:
18573 /* relative uri */
18576 break;
18577 case 3:
18578 case 4:
18579 /* absolute uri (with/without port) */
18581 conn->request_info.request_uri, conn);
18582 if (hostend) {
18583 conn->request_info.local_uri_raw = hostend;
18584 } else {
18585 conn->request_info.local_uri_raw = NULL;
18586 }
18587 break;
18588 default:
18589 mg_snprintf(conn,
18590 NULL, /* No truncation check for ebuf */
18591 ebuf,
18592 sizeof(ebuf),
18593 "Invalid URI");
18594 mg_send_http_error(conn, 400, "%s", ebuf);
18595 conn->request_info.local_uri_raw = NULL;
18596 break;
18597 }
18598 conn->request_info.local_uri =
18599 (char *)conn->request_info.local_uri_raw;
18600 }
18601
18602 if (ebuf[0] != '\0') {
18603 conn->protocol_type = -1;
18604
18605 } else {
18606 /* HTTP/1 allows protocol upgrade */
18608
18609 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
18610 /* This will occur, if a HTTP/1.1 request should be upgraded
18611 * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
18612 * Since most (all?) major browsers only support HTTP/2 using
18613 * ALPN, this is hard to test and very low priority.
18614 * Deactivate it (at least for now).
18615 */
18617 }
18618 }
18619
18620 DEBUG_TRACE("http: %s, error: %s",
18621 (ri->http_version ? ri->http_version : "none"),
18622 (ebuf[0] ? ebuf : "none"));
18623
18624 if (ebuf[0] == '\0') {
18625 if (conn->request_info.local_uri) {
18626
18627 /* handle request to local server */
18629
18630 } else {
18631 /* TODO: handle non-local request (PROXY) */
18632 conn->must_close = 1;
18633 }
18634 } else {
18635 conn->must_close = 1;
18636 }
18637
18638 /* Response complete. Free header buffer */
18640
18641 if (ri->remote_user != NULL) {
18642 mg_free((void *)ri->remote_user);
18643 /* Important! When having connections with and without auth
18644 * would cause double free and then crash */
18645 ri->remote_user = NULL;
18646 }
18647
18648 /* NOTE(lsm): order is important here. should_keep_alive() call
18649 * is using parsed request, which will be invalid after
18650 * memmove's below.
18651 * Therefore, memorize should_keep_alive() result now for later
18652 * use in loop exit condition. */
18653 /* Enable it only if this request is completely discardable. */
18654 keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
18655 && should_keep_alive(conn) && (conn->content_len >= 0)
18656 && (conn->request_len > 0)
18657 && ((conn->is_chunked == 4)
18658 || (!conn->is_chunked
18659 && ((conn->consumed_content == conn->content_len)
18660 || ((conn->request_len + conn->content_len)
18661 <= conn->data_len))))
18662 && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
18663
18664 if (keep_alive) {
18665 /* Discard all buffered data for this request */
18666 discard_len =
18667 ((conn->request_len + conn->content_len) < conn->data_len)
18668 ? (int)(conn->request_len + conn->content_len)
18669 : conn->data_len;
18670 conn->data_len -= discard_len;
18671
18672 if (conn->data_len > 0) {
18673 DEBUG_TRACE("discard_len = %d", discard_len);
18674 memmove(conn->buf,
18675 conn->buf + discard_len,
18676 (size_t)conn->data_len);
18677 }
18678 }
18679
18680 DEBUG_ASSERT(conn->data_len >= 0);
18681 DEBUG_ASSERT(conn->data_len <= conn->buf_size);
18682
18683 if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
18684 DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
18685 (long int)conn->data_len,
18686 (long int)conn->buf_size);
18687 break;
18688 }
18689 conn->handled_requests++;
18690 } while (keep_alive);
18691
18692 DEBUG_TRACE("Done processing connection from %s (%f sec)",
18694 difftime(time(NULL), conn->conn_birth_time));
18695
18696 close_connection(conn);
18697
18698#if defined(USE_SERVER_STATS)
18699 mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
18700 mg_atomic_dec(&(conn->phys_ctx->active_connections));
18701#endif
18702}
18703
18704
18705#if defined(ALTERNATIVE_QUEUE)
18706
18707static void
18708produce_socket(struct mg_context *ctx, const struct socket *sp)
18709{
18710 unsigned int i;
18711
18712 while (!ctx->stop_flag) {
18713 for (i = 0; i < ctx->cfg_worker_threads; i++) {
18714 /* find a free worker slot and signal it */
18715 if (ctx->client_socks[i].in_use == 2) {
18716 (void)pthread_mutex_lock(&ctx->thread_mutex);
18717 if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
18718 ctx->client_socks[i] = *sp;
18719 ctx->client_socks[i].in_use = 1;
18720 /* socket has been moved to the consumer */
18721 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18722 (void)event_signal(ctx->client_wait_events[i]);
18723 return;
18724 }
18725 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18726 }
18727 }
18728 /* queue is full */
18729 mg_sleep(1);
18730 }
18731 /* must consume */
18733 closesocket(sp->sock);
18734}
18735
18736
18737static int
18738consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
18739{
18740 DEBUG_TRACE("%s", "going idle");
18741 (void)pthread_mutex_lock(&ctx->thread_mutex);
18742 ctx->client_socks[thread_index].in_use = 2;
18743 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18744
18745 event_wait(ctx->client_wait_events[thread_index]);
18746
18747 (void)pthread_mutex_lock(&ctx->thread_mutex);
18748 *sp = ctx->client_socks[thread_index];
18749 if (ctx->stop_flag) {
18750 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18751 if (sp->in_use == 1) {
18752 /* must consume */
18754 closesocket(sp->sock);
18755 }
18756 return 0;
18757 }
18758 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18759 if (sp->in_use == 1) {
18760 DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
18761 return 1;
18762 }
18763 /* must not reach here */
18764 DEBUG_ASSERT(0);
18765 return 0;
18766}
18767
18768#else /* ALTERNATIVE_QUEUE */
18769
18770/* Worker threads take accepted socket from the queue */
18771static int
18772consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
18773{
18774 (void)thread_index;
18775
18776 (void)pthread_mutex_lock(&ctx->thread_mutex);
18777 DEBUG_TRACE("%s", "going idle");
18778
18779 /* If the queue is empty, wait. We're idle at this point. */
18780 while ((ctx->sq_head == ctx->sq_tail)
18781 && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
18782 pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
18783 }
18784
18785 /* If we're stopping, sq_head may be equal to sq_tail. */
18786 if (ctx->sq_head > ctx->sq_tail) {
18787 /* Copy socket from the queue and increment tail */
18788 *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
18789 ctx->sq_tail++;
18790
18791 DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
18792
18793 /* Wrap pointers if needed */
18794 while (ctx->sq_tail > ctx->sq_size) {
18795 ctx->sq_tail -= ctx->sq_size;
18796 ctx->sq_head -= ctx->sq_size;
18797 }
18798 }
18799
18800 (void)pthread_cond_signal(&ctx->sq_empty);
18801 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18802
18803 return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
18804}
18805
18806
18807/* Master thread adds accepted socket to a queue */
18808static void
18809produce_socket(struct mg_context *ctx, const struct socket *sp)
18810{
18811 int queue_filled;
18812
18813 (void)pthread_mutex_lock(&ctx->thread_mutex);
18814
18815 queue_filled = ctx->sq_head - ctx->sq_tail;
18816
18817 /* If the queue is full, wait */
18818 while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
18819 && (queue_filled >= ctx->sq_size)) {
18820 ctx->sq_blocked = 1; /* Status information: All threads busy */
18821#if defined(USE_SERVER_STATS)
18822 if (queue_filled > ctx->sq_max_fill) {
18823 ctx->sq_max_fill = queue_filled;
18824 }
18825#endif
18826 (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
18827 ctx->sq_blocked = 0; /* Not blocked now */
18828 queue_filled = ctx->sq_head - ctx->sq_tail;
18829 }
18830
18831 if (queue_filled < ctx->sq_size) {
18832 /* Copy socket to the queue and increment head */
18833 ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
18834 ctx->sq_head++;
18835 DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
18836 }
18837
18838 queue_filled = ctx->sq_head - ctx->sq_tail;
18839#if defined(USE_SERVER_STATS)
18840 if (queue_filled > ctx->sq_max_fill) {
18841 ctx->sq_max_fill = queue_filled;
18842 }
18843#endif
18844
18845 (void)pthread_cond_signal(&ctx->sq_full);
18846 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18847}
18848#endif /* ALTERNATIVE_QUEUE */
18849
18850
18851static void
18853{
18854 struct mg_context *ctx = conn->phys_ctx;
18855 int thread_index;
18856 struct mg_workerTLS tls;
18857
18858 mg_set_thread_name("worker");
18859
18860 tls.is_master = 0;
18861 tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
18862#if defined(_WIN32)
18863 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
18864#endif
18865
18866 /* Initialize thread local storage before calling any callback */
18867 pthread_setspecific(sTlsKey, &tls);
18868
18869 /* Check if there is a user callback */
18870 if (ctx->callbacks.init_thread) {
18871 /* call init_thread for a worker thread (type 1), and store the
18872 * return value */
18873 tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
18874 } else {
18875 /* No callback: set user pointer to NULL */
18876 tls.user_ptr = NULL;
18877 }
18878
18879 /* Connection structure has been pre-allocated */
18880 thread_index = (int)(conn - ctx->worker_connections);
18881 if ((thread_index < 0)
18882 || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
18884 "Internal error: Invalid worker index %i",
18885 thread_index);
18886 return;
18887 }
18888
18889 /* Request buffers are not pre-allocated. They are private to the
18890 * request and do not contain any state information that might be
18891 * of interest to anyone observing a server status. */
18892 conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
18893 if (conn->buf == NULL) {
18895 ctx,
18896 "Out of memory: Cannot allocate buffer for worker %i",
18897 thread_index);
18898 return;
18899 }
18900 conn->buf_size = (int)ctx->max_request_size;
18901
18902 conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
18903
18904 conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
18905
18906 conn->request_info.user_data = ctx->user_data;
18907 /* Allocate a mutex for this connection to allow communication both
18908 * within the request handler and from elsewhere in the application
18909 */
18910 if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
18911 mg_free(conn->buf);
18912 mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
18913 return;
18914 }
18915
18916#if defined(USE_SERVER_STATS)
18917 conn->conn_state = 1; /* not consumed */
18918#endif
18919
18920 /* Call consume_socket() even when ctx->stop_flag > 0, to let it
18921 * signal sq_empty condvar to wake up the master waiting in
18922 * produce_socket() */
18923 while (consume_socket(ctx, &conn->client, thread_index)) {
18924
18925 /* New connections must start with new protocol negotiation */
18926 tls.alpn_proto = NULL;
18927
18928#if defined(USE_SERVER_STATS)
18929 conn->conn_close_time = 0;
18930#endif
18931 conn->conn_birth_time = time(NULL);
18932
18933 /* Fill in IP, port info early so even if SSL setup below fails,
18934 * error handler would have the corresponding info.
18935 * Thanks to Johannes Winkelmann for the patch.
18936 */
18938 ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
18939
18941 ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
18942
18944 sizeof(conn->request_info.remote_addr),
18945 &conn->client.rsa);
18946
18947 DEBUG_TRACE("Incomming %sconnection from %s",
18948 (conn->client.is_ssl ? "SSL " : ""),
18950
18951 conn->request_info.is_ssl = conn->client.is_ssl;
18952
18953 if (conn->client.is_ssl) {
18954
18955#if defined(USE_MBEDTLS)
18956 /* HTTPS connection */
18957 if (mbed_ssl_accept(&(conn->ssl),
18958 conn->dom_ctx->ssl_ctx,
18959 (int *)&(conn->client.sock),
18960 conn->phys_ctx)
18961 == 0) {
18962 /* conn->dom_ctx is set in get_request */
18963 /* process HTTPS connection */
18964 init_connection(conn);
18968 } else {
18969 /* make sure the connection is cleaned up on SSL failure */
18970 close_connection(conn);
18971 }
18972
18973#elif !defined(NO_SSL)
18974 /* HTTPS connection */
18975 if (sslize(conn, SSL_accept, NULL)) {
18976 /* conn->dom_ctx is set in get_request */
18977
18978 /* Get SSL client certificate information (if set) */
18979 struct mg_client_cert client_cert;
18980 if (ssl_get_client_cert_info(conn, &client_cert)) {
18981 conn->request_info.client_cert = &client_cert;
18982 }
18983
18984 /* process HTTPS connection */
18985#if defined(USE_HTTP2)
18986 if ((tls.alpn_proto != NULL)
18987 && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
18988 /* process HTTPS/2 connection */
18989 init_connection(conn);
18992 conn->content_len =
18993 -1; /* content length is not predefined */
18994 conn->is_chunked = 0; /* HTTP2 is never chunked */
18995 process_new_http2_connection(conn);
18996 } else
18997#endif
18998 {
18999 /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
19000 init_connection(conn);
19002 /* Start with HTTP, WS will be an "upgrade" request later */
19005 }
19006
19007 /* Free client certificate info */
19008 if (conn->request_info.client_cert) {
19009 mg_free((void *)(conn->request_info.client_cert->subject));
19010 mg_free((void *)(conn->request_info.client_cert->issuer));
19011 mg_free((void *)(conn->request_info.client_cert->serial));
19012 mg_free((void *)(conn->request_info.client_cert->finger));
19013 /* Free certificate memory */
19014 X509_free(
19017 conn->request_info.client_cert->subject = 0;
19018 conn->request_info.client_cert->issuer = 0;
19019 conn->request_info.client_cert->serial = 0;
19020 conn->request_info.client_cert->finger = 0;
19021 conn->request_info.client_cert = 0;
19022 }
19023 } else {
19024 /* make sure the connection is cleaned up on SSL failure */
19025 close_connection(conn);
19026 }
19027#endif
19028
19029 } else {
19030 /* process HTTP connection */
19031 init_connection(conn);
19033 /* Start with HTTP, WS will be an "upgrade" request later */
19036 }
19037
19038 DEBUG_TRACE("%s", "Connection closed");
19039
19040#if defined(USE_SERVER_STATS)
19041 conn->conn_close_time = time(NULL);
19042#endif
19043 }
19044
19045 /* Call exit thread user callback */
19046 if (ctx->callbacks.exit_thread) {
19047 ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
19048 }
19049
19050 /* delete thread local storage objects */
19051 pthread_setspecific(sTlsKey, NULL);
19052#if defined(_WIN32)
19053 CloseHandle(tls.pthread_cond_helper_mutex);
19054#endif
19055 pthread_mutex_destroy(&conn->mutex);
19056
19057 /* Free the request buffer. */
19058 conn->buf_size = 0;
19059 mg_free(conn->buf);
19060 conn->buf = NULL;
19061
19062 /* Free cleaned URI (if any) */
19063 if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
19064 mg_free((void *)conn->request_info.local_uri);
19065 conn->request_info.local_uri = NULL;
19066 }
19067
19068#if defined(USE_SERVER_STATS)
19069 conn->conn_state = 9; /* done */
19070#endif
19071
19072 DEBUG_TRACE("%s", "exiting");
19073}
19074
19075
19076/* Threads have different return types on Windows and Unix. */
19077#if defined(_WIN32)
19078static unsigned __stdcall worker_thread(void *thread_func_param)
19079{
19080 worker_thread_run((struct mg_connection *)thread_func_param);
19081 return 0;
19082}
19083#else
19084static void *
19085worker_thread(void *thread_func_param)
19086{
19087#if !defined(__ZEPHYR__)
19088 struct sigaction sa;
19089
19090 /* Ignore SIGPIPE */
19091 memset(&sa, 0, sizeof(sa));
19092 sa.sa_handler = SIG_IGN;
19093 sigaction(SIGPIPE, &sa, NULL);
19094#endif
19095
19096 worker_thread_run((struct mg_connection *)thread_func_param);
19097 return NULL;
19098}
19099#endif /* _WIN32 */
19100
19101
19102/* This is an internal function, thus all arguments are expected to be
19103 * valid - a NULL check is not required. */
19104static void
19105accept_new_connection(const struct socket *listener, struct mg_context *ctx)
19106{
19107 struct socket so;
19108 char src_addr[IP_ADDR_STR_LEN];
19109 socklen_t len = sizeof(so.rsa);
19110#if !defined(__ZEPHYR__)
19111 int on = 1;
19112#endif
19113 memset(&so, 0, sizeof(so));
19114
19115 if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
19116 == INVALID_SOCKET) {
19117 } else if (check_acl(ctx, &so.rsa) != 1) {
19118 sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
19120 "%s: %s is not allowed to connect",
19121 __func__,
19122 src_addr);
19123 closesocket(so.sock);
19124 } else {
19125 /* Put so socket structure into the queue */
19126 DEBUG_TRACE("Accepted socket %d", (int)so.sock);
19127 set_close_on_exec(so.sock, NULL, ctx);
19128 so.is_ssl = listener->is_ssl;
19129 so.ssl_redir = listener->ssl_redir;
19130 if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
19132 "%s: getsockname() failed: %s",
19133 __func__,
19134 strerror(ERRNO));
19135 }
19136
19137#if !defined(__ZEPHYR__)
19138 if ((so.lsa.sa.sa_family == AF_INET)
19139 || (so.lsa.sa.sa_family == AF_INET6)) {
19140 /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
19141 * This is needed because if HTTP-level keep-alive
19142 * is enabled, and client resets the connection, server won't get
19143 * TCP FIN or RST and will keep the connection open forever. With
19144 * TCP keep-alive, next keep-alive handshake will figure out that
19145 * the client is down and will close the server end.
19146 * Thanks to Igor Klopov who suggested the patch. */
19147 if (setsockopt(so.sock,
19148 SOL_SOCKET,
19149 SO_KEEPALIVE,
19150 (SOCK_OPT_TYPE)&on,
19151 sizeof(on))
19152 != 0) {
19154 ctx,
19155 "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
19156 __func__,
19157 strerror(ERRNO));
19158 }
19159 }
19160#endif
19161
19162 /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
19163 * to effectively fill up the underlying IP packet payload and
19164 * reduce the overhead of sending lots of small buffers. However
19165 * this hurts the server's throughput (ie. operations per second)
19166 * when HTTP 1.1 persistent connections are used and the responses
19167 * are relatively small (eg. less than 1400 bytes).
19168 */
19169 if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
19170 && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
19171 if (set_tcp_nodelay(&so, 1) != 0) {
19173 ctx,
19174 "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
19175 __func__,
19176 strerror(ERRNO));
19177 }
19178 }
19179
19180 /* The "non blocking" property should already be
19181 * inherited from the parent socket. Set it for
19182 * non-compliant socket implementations. */
19184
19185 so.in_use = 0;
19186 produce_socket(ctx, &so);
19187 }
19188}
19189
19190
19191static void
19193{
19194 struct mg_workerTLS tls;
19195 struct mg_pollfd *pfd;
19196 unsigned int i;
19197 unsigned int workerthreadcount;
19198
19199 if (!ctx) {
19200 return;
19201 }
19202
19203 mg_set_thread_name("master");
19204
19205 /* Increase priority of the master thread */
19206#if defined(_WIN32)
19207 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
19208#elif defined(USE_MASTER_THREAD_PRIORITY)
19209 int min_prio = sched_get_priority_min(SCHED_RR);
19210 int max_prio = sched_get_priority_max(SCHED_RR);
19211 if ((min_prio >= 0) && (max_prio >= 0)
19212 && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
19213 && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
19214 struct sched_param sched_param = {0};
19215 sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
19216 pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
19217 }
19218#endif
19219
19220 /* Initialize thread local storage */
19221#if defined(_WIN32)
19222 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
19223#endif
19224 tls.is_master = 1;
19225 pthread_setspecific(sTlsKey, &tls);
19226
19227 if (ctx->callbacks.init_thread) {
19228 /* Callback for the master thread (type 0) */
19229 tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
19230 } else {
19231 tls.user_ptr = NULL;
19232 }
19233
19234 /* Lua background script "start" event */
19235#if defined(USE_LUA)
19236 if (ctx->lua_background_state) {
19237 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19238 pthread_mutex_lock(&ctx->lua_bg_mutex);
19239
19240 /* call "start()" in Lua */
19241 lua_getglobal(lstate, "start");
19242 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19243 int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
19244 if (ret != 0) {
19245 struct mg_connection fc;
19246 lua_cry(fake_connection(&fc, ctx),
19247 ret,
19248 lstate,
19249 "lua_background_script",
19250 "start");
19251 }
19252 } else {
19253 lua_pop(lstate, 1);
19254 }
19255
19256 /* determine if there is a "log()" function in Lua background script */
19257 lua_getglobal(lstate, "log");
19258 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19259 ctx->lua_bg_log_available = 1;
19260 }
19261 lua_pop(lstate, 1);
19262
19263 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19264 }
19265#endif
19266
19267 /* Server starts *now* */
19268 ctx->start_time = time(NULL);
19269
19270 /* Server accept loop */
19271 pfd = ctx->listening_socket_fds;
19272 while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
19273 for (i = 0; i < ctx->num_listening_sockets; i++) {
19274 pfd[i].fd = ctx->listening_sockets[i].sock;
19275 pfd[i].events = POLLIN;
19276 }
19277
19278 if (mg_poll(pfd,
19281 &(ctx->stop_flag))
19282 > 0) {
19283 for (i = 0; i < ctx->num_listening_sockets; i++) {
19284 /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
19285 * successful poll, and POLLIN is defined as
19286 * (POLLRDNORM | POLLRDBAND)
19287 * Therefore, we're checking pfd[i].revents & POLLIN, not
19288 * pfd[i].revents == POLLIN. */
19289 if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
19290 && (pfd[i].revents & POLLIN)) {
19292 }
19293 }
19294 }
19295 }
19296
19297 /* Here stop_flag is 1 - Initiate shutdown. */
19298 DEBUG_TRACE("%s", "stopping workers");
19299
19300 /* Stop signal received: somebody called mg_stop. Quit. */
19302
19303 /* Wakeup workers that are waiting for connections to handle. */
19304#if defined(ALTERNATIVE_QUEUE)
19305 for (i = 0; i < ctx->cfg_worker_threads; i++) {
19306 event_signal(ctx->client_wait_events[i]);
19307 }
19308#else
19309 (void)pthread_mutex_lock(&ctx->thread_mutex);
19310 pthread_cond_broadcast(&ctx->sq_full);
19311 (void)pthread_mutex_unlock(&ctx->thread_mutex);
19312#endif
19313
19314 /* Join all worker threads to avoid leaking threads. */
19315 workerthreadcount = ctx->cfg_worker_threads;
19316 for (i = 0; i < workerthreadcount; i++) {
19317 if (ctx->worker_threadids[i] != 0) {
19319 }
19320 }
19321
19322#if defined(USE_LUA)
19323 /* Free Lua state of lua background task */
19324 if (ctx->lua_background_state) {
19325 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19326 ctx->lua_bg_log_available = 0;
19327
19328 /* call "stop()" in Lua */
19329 pthread_mutex_lock(&ctx->lua_bg_mutex);
19330 lua_getglobal(lstate, "stop");
19331 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19332 int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
19333 if (ret != 0) {
19334 struct mg_connection fc;
19335 lua_cry(fake_connection(&fc, ctx),
19336 ret,
19337 lstate,
19338 "lua_background_script",
19339 "stop");
19340 }
19341 }
19342 lua_close(lstate);
19343
19344 ctx->lua_background_state = 0;
19345 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19346 }
19347#endif
19348
19349 DEBUG_TRACE("%s", "exiting");
19350
19351 /* call exit thread callback */
19352 if (ctx->callbacks.exit_thread) {
19353 /* Callback for the master thread (type 0) */
19354 ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
19355 }
19356
19357#if defined(_WIN32)
19358 CloseHandle(tls.pthread_cond_helper_mutex);
19359#endif
19360 pthread_setspecific(sTlsKey, NULL);
19361
19362 /* Signal mg_stop() that we're done.
19363 * WARNING: This must be the very last thing this
19364 * thread does, as ctx becomes invalid after this line. */
19365 STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
19366}
19367
19368
19369/* Threads have different return types on Windows and Unix. */
19370#if defined(_WIN32)
19371static unsigned __stdcall master_thread(void *thread_func_param)
19372{
19373 master_thread_run((struct mg_context *)thread_func_param);
19374 return 0;
19375}
19376#else
19377static void *
19378master_thread(void *thread_func_param)
19379{
19380#if !defined(__ZEPHYR__)
19381 struct sigaction sa;
19382
19383 /* Ignore SIGPIPE */
19384 memset(&sa, 0, sizeof(sa));
19385 sa.sa_handler = SIG_IGN;
19386 sigaction(SIGPIPE, &sa, NULL);
19387#endif
19388
19389 master_thread_run((struct mg_context *)thread_func_param);
19390 return NULL;
19391}
19392#endif /* _WIN32 */
19393
19394
19395static void
19397{
19398 int i;
19399 struct mg_handler_info *tmp_rh;
19400
19401 if (ctx == NULL) {
19402 return;
19403 }
19404
19405 /* Call user callback */
19406 if (ctx->callbacks.exit_context) {
19407 ctx->callbacks.exit_context(ctx);
19408 }
19409
19410 /* All threads exited, no sync is needed. Destroy thread mutex and
19411 * condvars
19412 */
19413 (void)pthread_mutex_destroy(&ctx->thread_mutex);
19414
19415#if defined(ALTERNATIVE_QUEUE)
19416 mg_free(ctx->client_socks);
19417 if (ctx->client_wait_events != NULL) {
19418 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
19419 event_destroy(ctx->client_wait_events[i]);
19420 }
19421 mg_free(ctx->client_wait_events);
19422 }
19423#else
19424 (void)pthread_cond_destroy(&ctx->sq_empty);
19425 (void)pthread_cond_destroy(&ctx->sq_full);
19426 mg_free(ctx->squeue);
19427#endif
19428
19429 /* Destroy other context global data structures mutex */
19430 (void)pthread_mutex_destroy(&ctx->nonce_mutex);
19431
19432#if defined(USE_LUA)
19433 (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
19434#endif
19435
19436 /* Deallocate config parameters */
19437 for (i = 0; i < NUM_OPTIONS; i++) {
19438 if (ctx->dd.config[i] != NULL) {
19439#if defined(_MSC_VER)
19440#pragma warning(suppress : 6001)
19441#endif
19442 mg_free(ctx->dd.config[i]);
19443 }
19444 }
19445
19446 /* Deallocate request handlers */
19447 while (ctx->dd.handlers) {
19448 tmp_rh = ctx->dd.handlers;
19449 ctx->dd.handlers = tmp_rh->next;
19450 mg_free(tmp_rh->uri);
19451 mg_free(tmp_rh);
19452 }
19453
19454#if defined(USE_MBEDTLS)
19455 if (ctx->dd.ssl_ctx != NULL) {
19456 mbed_sslctx_uninit(ctx->dd.ssl_ctx);
19457 mg_free(ctx->dd.ssl_ctx);
19458 ctx->dd.ssl_ctx = NULL;
19459 }
19460
19461#elif !defined(NO_SSL)
19462 /* Deallocate SSL context */
19463 if (ctx->dd.ssl_ctx != NULL) {
19464 void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
19465 int callback_ret =
19466 (ctx->callbacks.external_ssl_ctx == NULL)
19467 ? 0
19468 : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
19469
19470 if (callback_ret == 0) {
19471 SSL_CTX_free(ctx->dd.ssl_ctx);
19472 }
19473 /* else: ignore error and ommit SSL_CTX_free in case
19474 * callback_ret is 1 */
19475 }
19476#endif /* !NO_SSL */
19477
19478 /* Deallocate worker thread ID array */
19480
19481 /* Deallocate worker thread ID array */
19483
19484 /* deallocate system name string */
19485 mg_free(ctx->systemName);
19486
19487 /* Deallocate context itself */
19488 mg_free(ctx);
19489}
19490
19491
19492void
19494{
19495 pthread_t mt;
19496 if (!ctx) {
19497 return;
19498 }
19499
19500 /* We don't use a lock here. Calling mg_stop with the same ctx from
19501 * two threads is not allowed. */
19502 mt = ctx->masterthreadid;
19503 if (mt == 0) {
19504 return;
19505 }
19506
19507 ctx->masterthreadid = 0;
19508
19509 /* Set stop flag, so all threads know they have to exit. */
19510 STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
19511
19512 /* Join timer thread */
19513#if defined(USE_TIMERS)
19514 timers_exit(ctx);
19515#endif
19516
19517 /* Wait until everything has stopped. */
19518 while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
19519 (void)mg_sleep(10);
19520 }
19521
19522 /* Wait to stop master thread */
19523 mg_join_thread(mt);
19524
19525 /* Close remaining Lua states */
19526#if defined(USE_LUA)
19527 lua_ctx_exit(ctx);
19528#endif
19529
19530 /* Free memory */
19531 free_context(ctx);
19532}
19533
19534
19535static void
19536get_system_name(char **sysName)
19537{
19538#if defined(_WIN32)
19539 char name[128];
19540 DWORD dwVersion = 0;
19541 DWORD dwMajorVersion = 0;
19542 DWORD dwMinorVersion = 0;
19543 DWORD dwBuild = 0;
19544 BOOL wowRet, isWoW = FALSE;
19545
19546#if defined(_MSC_VER)
19547#pragma warning(push)
19548 /* GetVersion was declared deprecated */
19549#pragma warning(disable : 4996)
19550#endif
19551 dwVersion = GetVersion();
19552#if defined(_MSC_VER)
19553#pragma warning(pop)
19554#endif
19555
19556 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
19557 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
19558 dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
19559 (void)dwBuild;
19560
19561 wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
19562
19563 sprintf(name,
19564 "Windows %u.%u%s",
19565 (unsigned)dwMajorVersion,
19566 (unsigned)dwMinorVersion,
19567 (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
19568
19569 *sysName = mg_strdup(name);
19570
19571
19572#elif defined(__ZEPHYR__)
19573 *sysName = mg_strdup("Zephyr OS");
19574#else
19575 struct utsname name;
19576 memset(&name, 0, sizeof(name));
19577 uname(&name);
19578 *sysName = mg_strdup(name.sysname);
19579#endif
19580}
19581
19582
19583static void
19584legacy_init(const char **options)
19585{
19586 const char *ports_option = config_options[LISTENING_PORTS].default_value;
19587
19588 if (options) {
19589 const char **run_options = options;
19590 const char *optname = config_options[LISTENING_PORTS].name;
19591
19592 /* Try to find the "listening_ports" option */
19593 while (*run_options) {
19594 if (!strcmp(*run_options, optname)) {
19595 ports_option = run_options[1];
19596 }
19597 run_options += 2;
19598 }
19599 }
19600
19601 if (is_ssl_port_used(ports_option)) {
19602 /* Initialize with SSL support */
19604 } else {
19605 /* Initialize without SSL support */
19607 }
19608}
19609
19610
19611struct mg_context *
19612mg_start2(struct mg_init_data *init, struct mg_error_data *error)
19613{
19614 struct mg_context *ctx;
19615 const char *name, *value, *default_value;
19616 int idx, ok, workerthreadcount;
19617 unsigned int i;
19618 int itmp;
19619 void (*exit_callback)(const struct mg_context *ctx) = 0;
19620 const char **options =
19621 ((init != NULL) ? (init->configuration_options) : (NULL));
19622
19623 struct mg_workerTLS tls;
19624
19625 if (error != NULL) {
19626 error->code = 0;
19627 if (error->text_buffer_size > 0) {
19628 *error->text = 0;
19629 }
19630 }
19631
19632 if (mg_init_library_called == 0) {
19633 /* Legacy INIT, if mg_start is called without mg_init_library.
19634 * Note: This will cause a memory leak when unloading the library.
19635 */
19636 legacy_init(options);
19637 }
19638 if (mg_init_library_called == 0) {
19639 if ((error != NULL) && (error->text_buffer_size > 0)) {
19640 mg_snprintf(NULL,
19641 NULL, /* No truncation check for error buffers */
19642 error->text,
19643 error->text_buffer_size,
19644 "%s",
19645 "Library uninitialized");
19646 }
19647 return NULL;
19648 }
19649
19650 /* Allocate context and initialize reasonable general case defaults. */
19651 if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
19652 if ((error != NULL) && (error->text_buffer_size > 0)) {
19653 mg_snprintf(NULL,
19654 NULL, /* No truncation check for error buffers */
19655 error->text,
19656 error->text_buffer_size,
19657 "%s",
19658 "Out of memory");
19659 }
19660 return NULL;
19661 }
19662
19663 /* Random number generator will initialize at the first call */
19664 ctx->dd.auth_nonce_mask =
19665 (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
19666
19667 /* Save started thread index to reuse in other external API calls
19668 * For the sake of thread synchronization all non-civetweb threads
19669 * can be considered as single external thread */
19671 tls.is_master = -1; /* Thread calling mg_start */
19672 tls.thread_idx = ctx->starter_thread_idx;
19673#if defined(_WIN32)
19674 tls.pthread_cond_helper_mutex = NULL;
19675#endif
19676 pthread_setspecific(sTlsKey, &tls);
19677
19678 ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
19679#if !defined(ALTERNATIVE_QUEUE)
19680 ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
19681 ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
19682 ctx->sq_blocked = 0;
19683#endif
19684 ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
19685#if defined(USE_LUA)
19686 ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
19687#endif
19688 if (!ok) {
19689 const char *err_msg =
19690 "Cannot initialize thread synchronization objects";
19691 /* Fatal error - abort start. However, this situation should never
19692 * occur in practice. */
19693
19694 mg_cry_ctx_internal(ctx, "%s", err_msg);
19695 if ((error != NULL) && (error->text_buffer_size > 0)) {
19696 mg_snprintf(NULL,
19697 NULL, /* No truncation check for error buffers */
19698 error->text,
19699 error->text_buffer_size,
19700 "%s",
19701 err_msg);
19702 }
19703
19704 mg_free(ctx);
19705 pthread_setspecific(sTlsKey, NULL);
19706 return NULL;
19707 }
19708
19709 if ((init != NULL) && (init->callbacks != NULL)) {
19710 /* Set all callbacks except exit_context. */
19711 ctx->callbacks = *init->callbacks;
19712 exit_callback = init->callbacks->exit_context;
19713 /* The exit callback is activated once the context is successfully
19714 * created. It should not be called, if an incomplete context object
19715 * is deleted during a failed initialization. */
19716 ctx->callbacks.exit_context = 0;
19717 }
19718 ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
19719 ctx->dd.handlers = NULL;
19720 ctx->dd.next = NULL;
19721
19722#if defined(USE_LUA)
19723 lua_ctx_init(ctx);
19724#endif
19725
19726 /* Store options */
19727 while (options && (name = *options++) != NULL) {
19728 if ((idx = get_option_index(name)) == -1) {
19729 mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
19730 if ((error != NULL) && (error->text_buffer_size > 0)) {
19731 mg_snprintf(NULL,
19732 NULL, /* No truncation check for error buffers */
19733 error->text,
19734 error->text_buffer_size,
19735 "Invalid configuration option: %s",
19736 name);
19737 }
19738 free_context(ctx);
19739 pthread_setspecific(sTlsKey, NULL);
19740 return NULL;
19741 } else if ((value = *options++) == NULL) {
19742 mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
19743 if ((error != NULL) && (error->text_buffer_size > 0)) {
19744 mg_snprintf(NULL,
19745 NULL, /* No truncation check for error buffers */
19746 error->text,
19747 error->text_buffer_size,
19748 "Invalid configuration option value: %s",
19749 name);
19750 }
19751 free_context(ctx);
19752 pthread_setspecific(sTlsKey, NULL);
19753 return NULL;
19754 }
19755 if (ctx->dd.config[idx] != NULL) {
19756 /* A duplicate configuration option is not an error - the last
19757 * option value will be used. */
19758 mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
19759 mg_free(ctx->dd.config[idx]);
19760 }
19761 ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
19762 DEBUG_TRACE("[%s] -> [%s]", name, value);
19763 }
19764
19765 /* Set default value if needed */
19766 for (i = 0; config_options[i].name != NULL; i++) {
19767 default_value = config_options[i].default_value;
19768 if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
19769 ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
19770 }
19771 }
19772
19773 /* Request size option */
19774 itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
19775 if (itmp < 1024) {
19777 "%s too small",
19779 if ((error != NULL) && (error->text_buffer_size > 0)) {
19780 mg_snprintf(NULL,
19781 NULL, /* No truncation check for error buffers */
19782 error->text,
19783 error->text_buffer_size,
19784 "Invalid configuration option value: %s",
19786 }
19787 free_context(ctx);
19788 pthread_setspecific(sTlsKey, NULL);
19789 return NULL;
19790 }
19791 ctx->max_request_size = (unsigned)itmp;
19792
19793 /* Queue length */
19794#if !defined(ALTERNATIVE_QUEUE)
19795 itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
19796 if (itmp < 1) {
19798 "%s too small",
19800 if ((error != NULL) && (error->text_buffer_size > 0)) {
19801 mg_snprintf(NULL,
19802 NULL, /* No truncation check for error buffers */
19803 error->text,
19804 error->text_buffer_size,
19805 "Invalid configuration option value: %s",
19807 }
19808 free_context(ctx);
19809 pthread_setspecific(sTlsKey, NULL);
19810 return NULL;
19811 }
19812 ctx->squeue =
19813 (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
19814 if (ctx->squeue == NULL) {
19816 "Out of memory: Cannot allocate %s",
19818 if ((error != NULL) && (error->text_buffer_size > 0)) {
19819 mg_snprintf(NULL,
19820 NULL, /* No truncation check for error buffers */
19821 error->text,
19822 error->text_buffer_size,
19823 "Out of memory: Cannot allocate %s",
19825 }
19826 free_context(ctx);
19827 pthread_setspecific(sTlsKey, NULL);
19828 return NULL;
19829 }
19830 ctx->sq_size = itmp;
19831#endif
19832
19833 /* Worker thread count option */
19834 workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
19835
19836 if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
19837 if (workerthreadcount <= 0) {
19838 mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
19839 } else {
19840 mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
19841 }
19842 if ((error != NULL) && (error->text_buffer_size > 0)) {
19843 mg_snprintf(NULL,
19844 NULL, /* No truncation check for error buffers */
19845 error->text,
19846 error->text_buffer_size,
19847 "Invalid configuration option value: %s",
19849 }
19850 free_context(ctx);
19851 pthread_setspecific(sTlsKey, NULL);
19852 return NULL;
19853 }
19854
19855 /* Document root */
19856#if defined(NO_FILES)
19857 if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
19858 mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
19859 if ((error != NULL) && (error->text_buffer_size > 0)) {
19860 mg_snprintf(NULL,
19861 NULL, /* No truncation check for error buffers */
19862 error->text,
19863 error->text_buffer_size,
19864 "Invalid configuration option value: %s",
19866 }
19867 free_context(ctx);
19868 pthread_setspecific(sTlsKey, NULL);
19869 return NULL;
19870 }
19871#endif
19872
19874
19875#if defined(USE_LUA)
19876 /* If a Lua background script has been configured, start it. */
19877 ctx->lua_bg_log_available = 0;
19878 if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
19879 char ebuf[256];
19880 struct vec opt_vec;
19881 struct vec eq_vec;
19882 const char *sparams;
19883
19884 memset(ebuf, 0, sizeof(ebuf));
19885 pthread_mutex_lock(&ctx->lua_bg_mutex);
19886
19887 /* Create a Lua state, load all standard libraries and the mg table */
19888 lua_State *state = mg_lua_context_script_prepare(
19889 ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
19890 if (!state) {
19892 "lua_background_script load error: %s",
19893 ebuf);
19894 if ((error != NULL) && (error->text_buffer_size > 0)) {
19895 mg_snprintf(NULL,
19896 NULL, /* No truncation check for error buffers */
19897 error->text,
19898 error->text_buffer_size,
19899 "Error in script %s: %s",
19900 config_options[LUA_BACKGROUND_SCRIPT].name,
19901 ebuf);
19902 }
19903 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19904
19905 free_context(ctx);
19906 pthread_setspecific(sTlsKey, NULL);
19907 return NULL;
19908 }
19909
19910 /* Add a table with parameters into mg.params */
19911 sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
19912 if (sparams && sparams[0]) {
19913 lua_getglobal(state, "mg");
19914 lua_pushstring(state, "params");
19915 lua_newtable(state);
19916
19917 while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
19918 != NULL) {
19919 reg_llstring(
19920 state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
19921 if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
19922 break;
19923 }
19924 lua_rawset(state, -3);
19925 lua_pop(state, 1);
19926 }
19927
19928 /* Call script */
19929 state = mg_lua_context_script_run(state,
19930 ctx->dd.config[LUA_BACKGROUND_SCRIPT],
19931 ctx,
19932 ebuf,
19933 sizeof(ebuf));
19934 if (!state) {
19936 "lua_background_script start error: %s",
19937 ebuf);
19938 if ((error != NULL) && (error->text_buffer_size > 0)) {
19939 mg_snprintf(NULL,
19940 NULL, /* No truncation check for error buffers */
19941 error->text,
19942 error->text_buffer_size,
19943 "Error in script %s: %s",
19945 ebuf);
19946 }
19947 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19948
19949 free_context(ctx);
19950 pthread_setspecific(sTlsKey, NULL);
19951 return NULL;
19952 }
19953
19954 /* state remains valid */
19955 ctx->lua_background_state = (void *)state;
19956 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19957
19958 } else {
19959 ctx->lua_background_state = 0;
19960 }
19961#endif
19962
19963 /* Step by step initialization of ctx - depending on build options */
19964#if !defined(NO_FILESYSTEMS)
19965 if (!set_gpass_option(ctx, NULL)) {
19966 const char *err_msg = "Invalid global password file";
19967 /* Fatal error - abort start. */
19968 mg_cry_ctx_internal(ctx, "%s", err_msg);
19969
19970 if ((error != NULL) && (error->text_buffer_size > 0)) {
19971 mg_snprintf(NULL,
19972 NULL, /* No truncation check for error buffers */
19973 error->text,
19974 error->text_buffer_size,
19975 "%s",
19976 err_msg);
19977 }
19978 free_context(ctx);
19979 pthread_setspecific(sTlsKey, NULL);
19980 return NULL;
19981 }
19982#endif
19983
19984#if defined(USE_MBEDTLS)
19985 if (!mg_sslctx_init(ctx, NULL)) {
19986 const char *err_msg = "Error initializing SSL context";
19987 /* Fatal error - abort start. */
19988 mg_cry_ctx_internal(ctx, "%s", err_msg);
19989
19990 if ((error != NULL) && (error->text_buffer_size > 0)) {
19991 mg_snprintf(NULL,
19992 NULL, /* No truncation check for error buffers */
19993 error->text,
19994 error->text_buffer_size,
19995 "%s",
19996 err_msg);
19997 }
19998 free_context(ctx);
19999 pthread_setspecific(sTlsKey, NULL);
20000 return NULL;
20001 }
20002
20003#elif !defined(NO_SSL)
20004 if (!init_ssl_ctx(ctx, NULL)) {
20005 const char *err_msg = "Error initializing SSL context";
20006 /* Fatal error - abort start. */
20007 mg_cry_ctx_internal(ctx, "%s", err_msg);
20008
20009 if ((error != NULL) && (error->text_buffer_size > 0)) {
20010 mg_snprintf(NULL,
20011 NULL, /* No truncation check for error buffers */
20012 error->text,
20013 error->text_buffer_size,
20014 "%s",
20015 err_msg);
20016 }
20017 free_context(ctx);
20018 pthread_setspecific(sTlsKey, NULL);
20019 return NULL;
20020 }
20021#endif
20022
20023 if (!set_ports_option(ctx)) {
20024 const char *err_msg = "Failed to setup server ports";
20025 /* Fatal error - abort start. */
20026 mg_cry_ctx_internal(ctx, "%s", err_msg);
20027
20028 if ((error != NULL) && (error->text_buffer_size > 0)) {
20029 mg_snprintf(NULL,
20030 NULL, /* No truncation check for error buffers */
20031 error->text,
20032 error->text_buffer_size,
20033 "%s",
20034 err_msg);
20035 }
20036 free_context(ctx);
20037 pthread_setspecific(sTlsKey, NULL);
20038 return NULL;
20039 }
20040
20041
20042#if !defined(_WIN32) && !defined(__ZEPHYR__)
20043 if (!set_uid_option(ctx)) {
20044 const char *err_msg = "Failed to run as configured user";
20045 /* Fatal error - abort start. */
20046 mg_cry_ctx_internal(ctx, "%s", err_msg);
20047
20048 if ((error != NULL) && (error->text_buffer_size > 0)) {
20049 mg_snprintf(NULL,
20050 NULL, /* No truncation check for error buffers */
20051 error->text,
20052 error->text_buffer_size,
20053 "%s",
20054 err_msg);
20055 }
20056 free_context(ctx);
20057 pthread_setspecific(sTlsKey, NULL);
20058 return NULL;
20059 }
20060#endif
20061
20062 if (!set_acl_option(ctx)) {
20063 const char *err_msg = "Failed to setup access control list";
20064 /* Fatal error - abort start. */
20065 mg_cry_ctx_internal(ctx, "%s", err_msg);
20066
20067 if ((error != NULL) && (error->text_buffer_size > 0)) {
20068 mg_snprintf(NULL,
20069 NULL, /* No truncation check for error buffers */
20070 error->text,
20071 error->text_buffer_size,
20072 "%s",
20073 err_msg);
20074 }
20075 free_context(ctx);
20076 pthread_setspecific(sTlsKey, NULL);
20077 return NULL;
20078 }
20079
20080 ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
20081 ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
20082 sizeof(pthread_t),
20083 ctx);
20084
20085 if (ctx->worker_threadids == NULL) {
20086 const char *err_msg = "Not enough memory for worker thread ID array";
20087 mg_cry_ctx_internal(ctx, "%s", err_msg);
20088
20089 if ((error != NULL) && (error->text_buffer_size > 0)) {
20090 mg_snprintf(NULL,
20091 NULL, /* No truncation check for error buffers */
20092 error->text,
20093 error->text_buffer_size,
20094 "%s",
20095 err_msg);
20096 }
20097 free_context(ctx);
20098 pthread_setspecific(sTlsKey, NULL);
20099 return NULL;
20100 }
20101 ctx->worker_connections =
20103 sizeof(struct mg_connection),
20104 ctx);
20105 if (ctx->worker_connections == NULL) {
20106 const char *err_msg =
20107 "Not enough memory for worker thread connection array";
20108 mg_cry_ctx_internal(ctx, "%s", err_msg);
20109
20110 if ((error != NULL) && (error->text_buffer_size > 0)) {
20111 mg_snprintf(NULL,
20112 NULL, /* No truncation check for error buffers */
20113 error->text,
20114 error->text_buffer_size,
20115 "%s",
20116 err_msg);
20117 }
20118 free_context(ctx);
20119 pthread_setspecific(sTlsKey, NULL);
20120 return NULL;
20121 }
20122
20123#if defined(ALTERNATIVE_QUEUE)
20124 ctx->client_wait_events =
20125 (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
20126 sizeof(ctx->client_wait_events[0]),
20127 ctx);
20128 if (ctx->client_wait_events == NULL) {
20129 const char *err_msg = "Not enough memory for worker event array";
20130 mg_cry_ctx_internal(ctx, "%s", err_msg);
20132
20133 if ((error != NULL) && (error->text_buffer_size > 0)) {
20134 mg_snprintf(NULL,
20135 NULL, /* No truncation check for error buffers */
20136 error->text,
20137 error->text_buffer_size,
20138 "%s",
20139 err_msg);
20140 }
20141 free_context(ctx);
20142 pthread_setspecific(sTlsKey, NULL);
20143 return NULL;
20144 }
20145
20146 ctx->client_socks =
20148 sizeof(ctx->client_socks[0]),
20149 ctx);
20150 if (ctx->client_socks == NULL) {
20151 const char *err_msg = "Not enough memory for worker socket array";
20152 mg_cry_ctx_internal(ctx, "%s", err_msg);
20153 mg_free(ctx->client_wait_events);
20155
20156 if ((error != NULL) && (error->text_buffer_size > 0)) {
20157 mg_snprintf(NULL,
20158 NULL, /* No truncation check for error buffers */
20159 error->text,
20160 error->text_buffer_size,
20161 "%s",
20162 err_msg);
20163 }
20164 free_context(ctx);
20165 pthread_setspecific(sTlsKey, NULL);
20166 return NULL;
20167 }
20168
20169 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
20170 ctx->client_wait_events[i] = event_create();
20171 if (ctx->client_wait_events[i] == 0) {
20172 const char *err_msg = "Error creating worker event %i";
20173 mg_cry_ctx_internal(ctx, err_msg, i);
20174 while (i > 0) {
20175 i--;
20176 event_destroy(ctx->client_wait_events[i]);
20177 }
20178 mg_free(ctx->client_socks);
20179 mg_free(ctx->client_wait_events);
20181
20182 if ((error != NULL) && (error->text_buffer_size > 0)) {
20183 mg_snprintf(NULL,
20184 NULL, /* No truncation check for error buffers */
20185 error->text,
20186 error->text_buffer_size,
20187 err_msg,
20188 i);
20189 }
20190 free_context(ctx);
20191 pthread_setspecific(sTlsKey, NULL);
20192 return NULL;
20193 }
20194 }
20195#endif
20196
20197#if defined(USE_TIMERS)
20198 if (timers_init(ctx) != 0) {
20199 const char *err_msg = "Error creating timers";
20200 mg_cry_ctx_internal(ctx, "%s", err_msg);
20201
20202 if ((error != NULL) && (error->text_buffer_size > 0)) {
20203 mg_snprintf(NULL,
20204 NULL, /* No truncation check for error buffers */
20205 error->text,
20206 error->text_buffer_size,
20207 "%s",
20208 err_msg);
20209 }
20210 free_context(ctx);
20211 pthread_setspecific(sTlsKey, NULL);
20212 return NULL;
20213 }
20214#endif
20215
20216 /* Context has been created - init user libraries */
20217 if (ctx->callbacks.init_context) {
20218 ctx->callbacks.init_context(ctx);
20219 }
20220
20221 /* From now, the context is successfully created.
20222 * When it is destroyed, the exit callback should be called. */
20223 ctx->callbacks.exit_context = exit_callback;
20224 ctx->context_type = CONTEXT_SERVER; /* server context */
20225
20226 /* Start worker threads */
20227 for (i = 0; i < ctx->cfg_worker_threads; i++) {
20228 /* worker_thread sets up the other fields */
20229 ctx->worker_connections[i].phys_ctx = ctx;
20231 &ctx->worker_connections[i],
20232 &ctx->worker_threadids[i])
20233 != 0) {
20234
20235 long error_no = (long)ERRNO;
20236
20237 /* thread was not created */
20238 if (i > 0) {
20239 /* If the second, third, ... thread cannot be created, set a
20240 * warning, but keep running. */
20242 "Cannot start worker thread %i: error %ld",
20243 i + 1,
20244 error_no);
20245
20246 /* If the server initialization should stop here, all
20247 * threads that have already been created must be stopped
20248 * first, before any free_context(ctx) call.
20249 */
20250
20251 } else {
20252 /* If the first worker thread cannot be created, stop
20253 * initialization and free the entire server context. */
20255 "Cannot create threads: error %ld",
20256 error_no);
20257
20258 if ((error != NULL) && (error->text_buffer_size > 0)) {
20260 NULL,
20261 NULL, /* No truncation check for error buffers */
20262 error->text,
20263 error->text_buffer_size,
20264 "Cannot create first worker thread: error %ld",
20265 error_no);
20266 }
20267 free_context(ctx);
20268 pthread_setspecific(sTlsKey, NULL);
20269 return NULL;
20270 }
20271 break;
20272 }
20273 }
20274
20275 /* Start master (listening) thread */
20277
20278 pthread_setspecific(sTlsKey, NULL);
20279 return ctx;
20280}
20281
20282
20283struct mg_context *
20285 void *user_data,
20286 const char **options)
20287{
20288 struct mg_init_data init = {0};
20289 init.callbacks = callbacks;
20290 init.user_data = user_data;
20291 init.configuration_options = options;
20292
20293 return mg_start2(&init, NULL);
20294}
20295
20296
20297/* Add an additional domain to an already running web server. */
20298int
20300 const char **options,
20301 struct mg_error_data *error)
20302{
20303 const char *name;
20304 const char *value;
20305 const char *default_value;
20306 struct mg_domain_context *new_dom;
20307 struct mg_domain_context *dom;
20308 int idx, i;
20309
20310 if (error != NULL) {
20311 error->code = 0;
20312 if (error->text_buffer_size > 0) {
20313 *error->text = 0;
20314 }
20315 }
20316
20317 if ((ctx == NULL) || (options == NULL)) {
20318 if ((error != NULL) && (error->text_buffer_size > 0)) {
20319 mg_snprintf(NULL,
20320 NULL, /* No truncation check for error buffers */
20321 error->text,
20322 error->text_buffer_size,
20323 "%s",
20324 "Invalid parameters");
20325 }
20326 return -1;
20327 }
20328
20329 if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
20330 if ((error != NULL) && (error->text_buffer_size > 0)) {
20331 mg_snprintf(NULL,
20332 NULL, /* No truncation check for error buffers */
20333 error->text,
20334 error->text_buffer_size,
20335 "%s",
20336 "Server already stopped");
20337 }
20338 return -1;
20339 }
20340
20341 new_dom = (struct mg_domain_context *)
20342 mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
20343
20344 if (!new_dom) {
20345 /* Out of memory */
20346 if ((error != NULL) && (error->text_buffer_size > 0)) {
20347 mg_snprintf(NULL,
20348 NULL, /* No truncation check for error buffers */
20349 error->text,
20350 error->text_buffer_size,
20351 "%s",
20352 "Out or memory");
20353 }
20354 return -6;
20355 }
20356
20357 /* Store options - TODO: unite duplicate code */
20358 while (options && (name = *options++) != NULL) {
20359 if ((idx = get_option_index(name)) == -1) {
20360 mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
20361 if ((error != NULL) && (error->text_buffer_size > 0)) {
20362 mg_snprintf(NULL,
20363 NULL, /* No truncation check for error buffers */
20364 error->text,
20365 error->text_buffer_size,
20366 "Invalid option: %s",
20367 name);
20368 }
20369 mg_free(new_dom);
20370 return -2;
20371 } else if ((value = *options++) == NULL) {
20372 mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
20373 if ((error != NULL) && (error->text_buffer_size > 0)) {
20374 mg_snprintf(NULL,
20375 NULL, /* No truncation check for error buffers */
20376 error->text,
20377 error->text_buffer_size,
20378 "Invalid option value: %s",
20379 name);
20380 }
20381 mg_free(new_dom);
20382 return -2;
20383 }
20384 if (new_dom->config[idx] != NULL) {
20385 /* Duplicate option: Later values overwrite earlier ones. */
20386 mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
20387 mg_free(new_dom->config[idx]);
20388 }
20389 new_dom->config[idx] = mg_strdup_ctx(value, ctx);
20390 DEBUG_TRACE("[%s] -> [%s]", name, value);
20391 }
20392
20393 /* Authentication domain is mandatory */
20394 /* TODO: Maybe use a new option hostname? */
20395 if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
20396 mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
20397 if ((error != NULL) && (error->text_buffer_size > 0)) {
20398 mg_snprintf(NULL,
20399 NULL, /* No truncation check for error buffers */
20400 error->text,
20401 error->text_buffer_size,
20402 "Mandatory option %s missing",
20404 }
20405 mg_free(new_dom);
20406 return -4;
20407 }
20408
20409 /* Set default value if needed. Take the config value from
20410 * ctx as a default value. */
20411 for (i = 0; config_options[i].name != NULL; i++) {
20412 default_value = ctx->dd.config[i];
20413 if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
20414 new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
20415 }
20416 }
20417
20418 new_dom->handlers = NULL;
20419 new_dom->next = NULL;
20420 new_dom->nonce_count = 0;
20421 new_dom->auth_nonce_mask =
20422 (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
20423
20424#if defined(USE_LUA) && defined(USE_WEBSOCKET)
20425 new_dom->shared_lua_websockets = NULL;
20426#endif
20427
20428#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
20429 if (!init_ssl_ctx(ctx, new_dom)) {
20430 /* Init SSL failed */
20431 if ((error != NULL) && (error->text_buffer_size > 0)) {
20432 mg_snprintf(NULL,
20433 NULL, /* No truncation check for error buffers */
20434 error->text,
20435 error->text_buffer_size,
20436 "%s",
20437 "Initializing SSL context failed");
20438 }
20439 mg_free(new_dom);
20440 return -3;
20441 }
20442#endif
20443
20444 /* Add element to linked list. */
20445 mg_lock_context(ctx);
20446
20447 idx = 0;
20448 dom = &(ctx->dd);
20449 for (;;) {
20452 /* Domain collision */
20454 "domain %s already in use",
20455 new_dom->config[AUTHENTICATION_DOMAIN]);
20456 if ((error != NULL) && (error->text_buffer_size > 0)) {
20457 mg_snprintf(NULL,
20458 NULL, /* No truncation check for error buffers */
20459 error->text,
20460 error->text_buffer_size,
20461 "Domain %s specified by %s is already in use",
20462 new_dom->config[AUTHENTICATION_DOMAIN],
20464 }
20465 mg_free(new_dom);
20466 mg_unlock_context(ctx);
20467 return -5;
20468 }
20469
20470 /* Count number of domains */
20471 idx++;
20472
20473 if (dom->next == NULL) {
20474 dom->next = new_dom;
20475 break;
20476 }
20477 dom = dom->next;
20478 }
20479
20480 mg_unlock_context(ctx);
20481
20482 /* Return domain number */
20483 return idx;
20484}
20485
20486
20487int
20488mg_start_domain(struct mg_context *ctx, const char **options)
20489{
20490 return mg_start_domain2(ctx, options, NULL);
20491}
20492
20493
20494/* Feature check API function */
20495unsigned
20496mg_check_feature(unsigned feature)
20497{
20498 static const unsigned feature_set = 0
20499 /* Set bits for available features according to API documentation.
20500 * This bit mask is created at compile time, according to the active
20501 * preprocessor defines. It is a single const value at runtime. */
20502#if !defined(NO_FILES)
20504#endif
20505#if !defined(NO_SSL) || defined(USE_MBEDTLS)
20507#endif
20508#if !defined(NO_CGI)
20510#endif
20511#if defined(USE_IPV6)
20513#endif
20514#if defined(USE_WEBSOCKET)
20516#endif
20517#if defined(USE_LUA)
20519#endif
20520#if defined(USE_DUKTAPE)
20522#endif
20523#if !defined(NO_CACHING)
20525#endif
20526#if defined(USE_SERVER_STATS)
20528#endif
20529#if defined(USE_ZLIB)
20531#endif
20532#if defined(USE_HTTP2)
20534#endif
20535#if defined(USE_X_DOM_SOCKET)
20537#endif
20538
20539 /* Set some extra bits not defined in the API documentation.
20540 * These bits may change without further notice. */
20541#if defined(MG_LEGACY_INTERFACE)
20542 | 0x80000000u
20543#endif
20544#if defined(MG_EXPERIMENTAL_INTERFACES)
20545 | 0x40000000u
20546#endif
20547#if !defined(NO_RESPONSE_BUFFERING)
20548 | 0x20000000u
20549#endif
20550#if defined(MEMORY_DEBUGGING)
20551 | 0x10000000u
20552#endif
20553 ;
20554 return (feature & feature_set);
20555}
20556
20557
20558static size_t
20559mg_str_append(char **dst, char *end, const char *src)
20560{
20561 size_t len = strlen(src);
20562 if (*dst != end) {
20563 /* Append src if enough space, or close dst. */
20564 if ((size_t)(end - *dst) > len) {
20565 strcpy(*dst, src);
20566 *dst += len;
20567 } else {
20568 *dst = end;
20569 }
20570 }
20571 return len;
20572}
20573
20574
20575/* Get system information. It can be printed or stored by the caller.
20576 * Return the size of available information. */
20577int
20578mg_get_system_info(char *buffer, int buflen)
20579{
20580 char *end, *append_eoobj = NULL, block[256];
20581 size_t system_info_length = 0;
20582
20583#if defined(_WIN32)
20584 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
20585#else
20586 static const char eol[] = "\n", eoobj[] = "\n}\n";
20587#endif
20588
20589 if ((buffer == NULL) || (buflen < 1)) {
20590 buflen = 0;
20591 end = buffer;
20592 } else {
20593 *buffer = 0;
20594 end = buffer + buflen;
20595 }
20596 if (buflen > (int)(sizeof(eoobj) - 1)) {
20597 /* has enough space to append eoobj */
20598 append_eoobj = buffer;
20599 if (end) {
20600 end -= sizeof(eoobj) - 1;
20601 }
20602 }
20603
20604 system_info_length += mg_str_append(&buffer, end, "{");
20605
20606 /* Server version */
20607 {
20608 const char *version = mg_version();
20609 mg_snprintf(NULL,
20610 NULL,
20611 block,
20612 sizeof(block),
20613 "%s\"version\" : \"%s\"",
20614 eol,
20615 version);
20616 system_info_length += mg_str_append(&buffer, end, block);
20617 }
20618
20619 /* System info */
20620 {
20621#if defined(_WIN32)
20622 DWORD dwVersion = 0;
20623 DWORD dwMajorVersion = 0;
20624 DWORD dwMinorVersion = 0;
20625 SYSTEM_INFO si;
20626
20627 GetSystemInfo(&si);
20628
20629#if defined(_MSC_VER)
20630#pragma warning(push)
20631 /* GetVersion was declared deprecated */
20632#pragma warning(disable : 4996)
20633#endif
20634 dwVersion = GetVersion();
20635#if defined(_MSC_VER)
20636#pragma warning(pop)
20637#endif
20638
20639 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
20640 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
20641
20642 mg_snprintf(NULL,
20643 NULL,
20644 block,
20645 sizeof(block),
20646 ",%s\"os\" : \"Windows %u.%u\"",
20647 eol,
20648 (unsigned)dwMajorVersion,
20649 (unsigned)dwMinorVersion);
20650 system_info_length += mg_str_append(&buffer, end, block);
20651
20652 mg_snprintf(NULL,
20653 NULL,
20654 block,
20655 sizeof(block),
20656 ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
20657 eol,
20658 (unsigned)si.wProcessorArchitecture,
20659 (unsigned)si.dwNumberOfProcessors,
20660 (unsigned)si.dwActiveProcessorMask);
20661 system_info_length += mg_str_append(&buffer, end, block);
20662#elif defined(__ZEPHYR__)
20663 mg_snprintf(NULL,
20664 NULL,
20665 block,
20666 sizeof(block),
20667 ",%s\"os\" : \"%s %s\"",
20668 eol,
20669 "Zephyr OS",
20670 ZEPHYR_VERSION);
20671 system_info_length += mg_str_append(&buffer, end, block);
20672#else
20673 struct utsname name;
20674 memset(&name, 0, sizeof(name));
20675 uname(&name);
20676
20677 mg_snprintf(NULL,
20678 NULL,
20679 block,
20680 sizeof(block),
20681 ",%s\"os\" : \"%s %s (%s) - %s\"",
20682 eol,
20683 name.sysname,
20684 name.version,
20685 name.release,
20686 name.machine);
20687 system_info_length += mg_str_append(&buffer, end, block);
20688#endif
20689 }
20690
20691 /* Features */
20692 {
20693 mg_snprintf(NULL,
20694 NULL,
20695 block,
20696 sizeof(block),
20697 ",%s\"features\" : %lu"
20698 ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
20699 eol,
20700 (unsigned long)mg_check_feature(0xFFFFFFFFu),
20701 eol,
20702 mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
20703 mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
20704 mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
20705 mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
20707 : "",
20708 mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
20709 mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
20710 mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
20711 mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
20712 system_info_length += mg_str_append(&buffer, end, block);
20713
20714#if defined(USE_LUA)
20715 mg_snprintf(NULL,
20716 NULL,
20717 block,
20718 sizeof(block),
20719 ",%s\"lua_version\" : \"%u (%s)\"",
20720 eol,
20721 (unsigned)LUA_VERSION_NUM,
20722 LUA_RELEASE);
20723 system_info_length += mg_str_append(&buffer, end, block);
20724#endif
20725#if defined(USE_DUKTAPE)
20726 mg_snprintf(NULL,
20727 NULL,
20728 block,
20729 sizeof(block),
20730 ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
20731 eol,
20732 (unsigned)DUK_VERSION / 10000,
20733 ((unsigned)DUK_VERSION / 100) % 100,
20734 (unsigned)DUK_VERSION % 100);
20735 system_info_length += mg_str_append(&buffer, end, block);
20736#endif
20737 }
20738
20739 /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
20740 {
20741#if defined(BUILD_DATE)
20742 const char *bd = BUILD_DATE;
20743#else
20744#if defined(GCC_DIAGNOSTIC)
20745#if GCC_VERSION >= 40900
20746#pragma GCC diagnostic push
20747 /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
20748 * does not work in some versions. If "BUILD_DATE" is defined to some
20749 * string, it is used instead of __DATE__. */
20750#pragma GCC diagnostic ignored "-Wdate-time"
20751#endif
20752#endif
20753 const char *bd = __DATE__;
20754#if defined(GCC_DIAGNOSTIC)
20755#if GCC_VERSION >= 40900
20756#pragma GCC diagnostic pop
20757#endif
20758#endif
20759#endif
20760
20762 NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
20763
20764 system_info_length += mg_str_append(&buffer, end, block);
20765 }
20766
20767
20768 /* Compiler information */
20769 /* http://sourceforge.net/p/predef/wiki/Compilers/ */
20770 {
20771#if defined(_MSC_VER)
20772 mg_snprintf(NULL,
20773 NULL,
20774 block,
20775 sizeof(block),
20776 ",%s\"compiler\" : \"MSC: %u (%u)\"",
20777 eol,
20778 (unsigned)_MSC_VER,
20779 (unsigned)_MSC_FULL_VER);
20780 system_info_length += mg_str_append(&buffer, end, block);
20781#elif defined(__MINGW64__)
20782 mg_snprintf(NULL,
20783 NULL,
20784 block,
20785 sizeof(block),
20786 ",%s\"compiler\" : \"MinGW64: %u.%u\"",
20787 eol,
20788 (unsigned)__MINGW64_VERSION_MAJOR,
20789 (unsigned)__MINGW64_VERSION_MINOR);
20790 system_info_length += mg_str_append(&buffer, end, block);
20791 mg_snprintf(NULL,
20792 NULL,
20793 block,
20794 sizeof(block),
20795 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20796 eol,
20797 (unsigned)__MINGW32_MAJOR_VERSION,
20798 (unsigned)__MINGW32_MINOR_VERSION);
20799 system_info_length += mg_str_append(&buffer, end, block);
20800#elif defined(__MINGW32__)
20801 mg_snprintf(NULL,
20802 NULL,
20803 block,
20804 sizeof(block),
20805 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20806 eol,
20807 (unsigned)__MINGW32_MAJOR_VERSION,
20808 (unsigned)__MINGW32_MINOR_VERSION);
20809 system_info_length += mg_str_append(&buffer, end, block);
20810#elif defined(__clang__)
20811 mg_snprintf(NULL,
20812 NULL,
20813 block,
20814 sizeof(block),
20815 ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
20816 eol,
20817 __clang_major__,
20818 __clang_minor__,
20819 __clang_patchlevel__,
20820 __clang_version__);
20821 system_info_length += mg_str_append(&buffer, end, block);
20822#elif defined(__GNUC__)
20823 mg_snprintf(NULL,
20824 NULL,
20825 block,
20826 sizeof(block),
20827 ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
20828 eol,
20829 (unsigned)__GNUC__,
20830 (unsigned)__GNUC_MINOR__,
20831 (unsigned)__GNUC_PATCHLEVEL__);
20832 system_info_length += mg_str_append(&buffer, end, block);
20833#elif defined(__INTEL_COMPILER)
20834 mg_snprintf(NULL,
20835 NULL,
20836 block,
20837 sizeof(block),
20838 ",%s\"compiler\" : \"Intel C/C++: %u\"",
20839 eol,
20840 (unsigned)__INTEL_COMPILER);
20841 system_info_length += mg_str_append(&buffer, end, block);
20842#elif defined(__BORLANDC__)
20843 mg_snprintf(NULL,
20844 NULL,
20845 block,
20846 sizeof(block),
20847 ",%s\"compiler\" : \"Borland C: 0x%x\"",
20848 eol,
20849 (unsigned)__BORLANDC__);
20850 system_info_length += mg_str_append(&buffer, end, block);
20851#elif defined(__SUNPRO_C)
20852 mg_snprintf(NULL,
20853 NULL,
20854 block,
20855 sizeof(block),
20856 ",%s\"compiler\" : \"Solaris: 0x%x\"",
20857 eol,
20858 (unsigned)__SUNPRO_C);
20859 system_info_length += mg_str_append(&buffer, end, block);
20860#else
20861 mg_snprintf(NULL,
20862 NULL,
20863 block,
20864 sizeof(block),
20865 ",%s\"compiler\" : \"other\"",
20866 eol);
20867 system_info_length += mg_str_append(&buffer, end, block);
20868#endif
20869 }
20870
20871 /* Determine 32/64 bit data mode.
20872 * see https://en.wikipedia.org/wiki/64-bit_computing */
20873 {
20874 mg_snprintf(NULL,
20875 NULL,
20876 block,
20877 sizeof(block),
20878 ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
20879 "char:%u/%u, "
20880 "ptr:%u, size:%u, time:%u\"",
20881 eol,
20882 (unsigned)sizeof(short),
20883 (unsigned)sizeof(int),
20884 (unsigned)sizeof(long),
20885 (unsigned)sizeof(long long),
20886 (unsigned)sizeof(float),
20887 (unsigned)sizeof(double),
20888 (unsigned)sizeof(long double),
20889 (unsigned)sizeof(char),
20890 (unsigned)sizeof(wchar_t),
20891 (unsigned)sizeof(void *),
20892 (unsigned)sizeof(size_t),
20893 (unsigned)sizeof(time_t));
20894 system_info_length += mg_str_append(&buffer, end, block);
20895 }
20896
20897 /* Terminate string */
20898 if (append_eoobj) {
20899 strcat(append_eoobj, eoobj);
20900 }
20901 system_info_length += sizeof(eoobj) - 1;
20902
20903 return (int)system_info_length;
20904}
20905
20906
20907/* Get context information. It can be printed or stored by the caller.
20908 * Return the size of available information. */
20909int
20910mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
20911{
20912#if defined(USE_SERVER_STATS)
20913 char *end, *append_eoobj = NULL, block[256];
20914 size_t context_info_length = 0;
20915
20916#if defined(_WIN32)
20917 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
20918#else
20919 static const char eol[] = "\n", eoobj[] = "\n}\n";
20920#endif
20921 struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
20922
20923 if ((buffer == NULL) || (buflen < 1)) {
20924 buflen = 0;
20925 end = buffer;
20926 } else {
20927 *buffer = 0;
20928 end = buffer + buflen;
20929 }
20930 if (buflen > (int)(sizeof(eoobj) - 1)) {
20931 /* has enough space to append eoobj */
20932 append_eoobj = buffer;
20933 end -= sizeof(eoobj) - 1;
20934 }
20935
20936 context_info_length += mg_str_append(&buffer, end, "{");
20937
20938 if (ms) { /* <-- should be always true */
20939 /* Memory information */
20940 int blockCount = (int)ms->blockCount;
20941 int64_t totalMemUsed = ms->totalMemUsed;
20942 int64_t maxMemUsed = ms->maxMemUsed;
20943 if (totalMemUsed > maxMemUsed) {
20944 maxMemUsed = totalMemUsed;
20945 }
20946
20947 mg_snprintf(NULL,
20948 NULL,
20949 block,
20950 sizeof(block),
20951 "%s\"memory\" : {%s"
20952 "\"blocks\" : %i,%s"
20953 "\"used\" : %" INT64_FMT ",%s"
20954 "\"maxUsed\" : %" INT64_FMT "%s"
20955 "}",
20956 eol,
20957 eol,
20958 blockCount,
20959 eol,
20960 totalMemUsed,
20961 eol,
20962 maxMemUsed,
20963 eol);
20964 context_info_length += mg_str_append(&buffer, end, block);
20965 }
20966
20967 if (ctx) {
20968 /* Declare all variables at begin of the block, to comply
20969 * with old C standards. */
20970 char start_time_str[64] = {0};
20971 char now_str[64] = {0};
20972 time_t start_time = ctx->start_time;
20973 time_t now = time(NULL);
20974 int64_t total_data_read, total_data_written;
20975 int active_connections = (int)ctx->active_connections;
20976 int max_active_connections = (int)ctx->max_active_connections;
20977 int total_connections = (int)ctx->total_connections;
20978 if (active_connections > max_active_connections) {
20979 max_active_connections = active_connections;
20980 }
20981 if (active_connections > total_connections) {
20982 total_connections = active_connections;
20983 }
20984
20985 /* Connections information */
20986 mg_snprintf(NULL,
20987 NULL,
20988 block,
20989 sizeof(block),
20990 ",%s\"connections\" : {%s"
20991 "\"active\" : %i,%s"
20992 "\"maxActive\" : %i,%s"
20993 "\"total\" : %i%s"
20994 "}",
20995 eol,
20996 eol,
20997 active_connections,
20998 eol,
20999 max_active_connections,
21000 eol,
21001 total_connections,
21002 eol);
21003 context_info_length += mg_str_append(&buffer, end, block);
21004
21005 /* Queue information */
21006#if !defined(ALTERNATIVE_QUEUE)
21007 mg_snprintf(NULL,
21008 NULL,
21009 block,
21010 sizeof(block),
21011 ",%s\"queue\" : {%s"
21012 "\"length\" : %i,%s"
21013 "\"filled\" : %i,%s"
21014 "\"maxFilled\" : %i,%s"
21015 "\"full\" : %s%s"
21016 "}",
21017 eol,
21018 eol,
21019 ctx->sq_size,
21020 eol,
21021 ctx->sq_head - ctx->sq_tail,
21022 eol,
21023 ctx->sq_max_fill,
21024 eol,
21025 (ctx->sq_blocked ? "true" : "false"),
21026 eol);
21027 context_info_length += mg_str_append(&buffer, end, block);
21028#endif
21029
21030 /* Requests information */
21031 mg_snprintf(NULL,
21032 NULL,
21033 block,
21034 sizeof(block),
21035 ",%s\"requests\" : {%s"
21036 "\"total\" : %lu%s"
21037 "}",
21038 eol,
21039 eol,
21040 (unsigned long)ctx->total_requests,
21041 eol);
21042 context_info_length += mg_str_append(&buffer, end, block);
21043
21044 /* Data information */
21045 total_data_read =
21046 mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
21047 total_data_written =
21048 mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
21049 mg_snprintf(NULL,
21050 NULL,
21051 block,
21052 sizeof(block),
21053 ",%s\"data\" : {%s"
21054 "\"read\" : %" INT64_FMT ",%s"
21055 "\"written\" : %" INT64_FMT "%s"
21056 "}",
21057 eol,
21058 eol,
21059 total_data_read,
21060 eol,
21061 total_data_written,
21062 eol);
21063 context_info_length += mg_str_append(&buffer, end, block);
21064
21065 /* Execution time information */
21066 gmt_time_string(start_time_str,
21067 sizeof(start_time_str) - 1,
21068 &start_time);
21069 gmt_time_string(now_str, sizeof(now_str) - 1, &now);
21070
21071 mg_snprintf(NULL,
21072 NULL,
21073 block,
21074 sizeof(block),
21075 ",%s\"time\" : {%s"
21076 "\"uptime\" : %.0f,%s"
21077 "\"start\" : \"%s\",%s"
21078 "\"now\" : \"%s\"%s"
21079 "}",
21080 eol,
21081 eol,
21082 difftime(now, start_time),
21083 eol,
21084 start_time_str,
21085 eol,
21086 now_str,
21087 eol);
21088 context_info_length += mg_str_append(&buffer, end, block);
21089 }
21090
21091 /* Terminate string */
21092 if (append_eoobj) {
21093 strcat(append_eoobj, eoobj);
21094 }
21095 context_info_length += sizeof(eoobj) - 1;
21096
21097 return (int)context_info_length;
21098#else
21099 (void)ctx;
21100 if ((buffer != NULL) && (buflen > 0)) {
21101 *buffer = 0;
21102 }
21103 return 0;
21104#endif
21105}
21106
21107
21108void
21110{
21111 /* https://github.com/civetweb/civetweb/issues/727 */
21112 if (conn != NULL) {
21113 conn->must_close = 1;
21114 }
21115}
21116
21117
21118#if defined(MG_EXPERIMENTAL_INTERFACES)
21119/* Get connection information. It can be printed or stored by the caller.
21120 * Return the size of available information. */
21121int
21122mg_get_connection_info(const struct mg_context *ctx,
21123 int idx,
21124 char *buffer,
21125 int buflen)
21126{
21127 const struct mg_connection *conn;
21128 const struct mg_request_info *ri;
21129 char *end, *append_eoobj = NULL, block[256];
21130 size_t connection_info_length = 0;
21131 int state = 0;
21132 const char *state_str = "unknown";
21133
21134#if defined(_WIN32)
21135 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
21136#else
21137 static const char eol[] = "\n", eoobj[] = "\n}\n";
21138#endif
21139
21140 if ((buffer == NULL) || (buflen < 1)) {
21141 buflen = 0;
21142 end = buffer;
21143 } else {
21144 *buffer = 0;
21145 end = buffer + buflen;
21146 }
21147 if (buflen > (int)(sizeof(eoobj) - 1)) {
21148 /* has enough space to append eoobj */
21149 append_eoobj = buffer;
21150 end -= sizeof(eoobj) - 1;
21151 }
21152
21153 if ((ctx == NULL) || (idx < 0)) {
21154 /* Parameter error */
21155 return 0;
21156 }
21157
21158 if ((unsigned)idx >= ctx->cfg_worker_threads) {
21159 /* Out of range */
21160 return 0;
21161 }
21162
21163 /* Take connection [idx]. This connection is not locked in
21164 * any way, so some other thread might use it. */
21165 conn = (ctx->worker_connections) + idx;
21166
21167 /* Initialize output string */
21168 connection_info_length += mg_str_append(&buffer, end, "{");
21169
21170 /* Init variables */
21171 ri = &(conn->request_info);
21172
21173#if defined(USE_SERVER_STATS)
21174 state = conn->conn_state;
21175
21176 /* State as string */
21177 switch (state) {
21178 case 0:
21179 state_str = "undefined";
21180 break;
21181 case 1:
21182 state_str = "not used";
21183 break;
21184 case 2:
21185 state_str = "init";
21186 break;
21187 case 3:
21188 state_str = "ready";
21189 break;
21190 case 4:
21191 state_str = "processing";
21192 break;
21193 case 5:
21194 state_str = "processed";
21195 break;
21196 case 6:
21197 state_str = "to close";
21198 break;
21199 case 7:
21200 state_str = "closing";
21201 break;
21202 case 8:
21203 state_str = "closed";
21204 break;
21205 case 9:
21206 state_str = "done";
21207 break;
21208 }
21209#endif
21210
21211 /* Connection info */
21212 if ((state >= 3) && (state < 9)) {
21213 mg_snprintf(NULL,
21214 NULL,
21215 block,
21216 sizeof(block),
21217 "%s\"connection\" : {%s"
21218 "\"remote\" : {%s"
21219 "\"protocol\" : \"%s\",%s"
21220 "\"addr\" : \"%s\",%s"
21221 "\"port\" : %u%s"
21222 "},%s"
21223 "\"handled_requests\" : %u%s"
21224 "}",
21225 eol,
21226 eol,
21227 eol,
21228 get_proto_name(conn),
21229 eol,
21230 ri->remote_addr,
21231 eol,
21232 ri->remote_port,
21233 eol,
21234 eol,
21235 conn->handled_requests,
21236 eol);
21237 connection_info_length += mg_str_append(&buffer, end, block);
21238 }
21239
21240 /* Request info */
21241 if ((state >= 4) && (state < 6)) {
21242 mg_snprintf(NULL,
21243 NULL,
21244 block,
21245 sizeof(block),
21246 "%s%s\"request_info\" : {%s"
21247 "\"method\" : \"%s\",%s"
21248 "\"uri\" : \"%s\",%s"
21249 "\"query\" : %s%s%s%s"
21250 "}",
21251 (connection_info_length > 1 ? "," : ""),
21252 eol,
21253 eol,
21254 ri->request_method,
21255 eol,
21256 ri->request_uri,
21257 eol,
21258 ri->query_string ? "\"" : "",
21259 ri->query_string ? ri->query_string : "null",
21260 ri->query_string ? "\"" : "",
21261 eol);
21262 connection_info_length += mg_str_append(&buffer, end, block);
21263 }
21264
21265 /* Execution time information */
21266 if ((state >= 2) && (state < 9)) {
21267 char start_time_str[64] = {0};
21268 char close_time_str[64] = {0};
21269 time_t start_time = conn->conn_birth_time;
21270 time_t close_time = 0;
21271 double time_diff;
21272
21273 gmt_time_string(start_time_str,
21274 sizeof(start_time_str) - 1,
21275 &start_time);
21276#if defined(USE_SERVER_STATS)
21277 close_time = conn->conn_close_time;
21278#endif
21279 if (close_time != 0) {
21280 time_diff = difftime(close_time, start_time);
21281 gmt_time_string(close_time_str,
21282 sizeof(close_time_str) - 1,
21283 &close_time);
21284 } else {
21285 time_t now = time(NULL);
21286 time_diff = difftime(now, start_time);
21287 close_time_str[0] = 0; /* or use "now" ? */
21288 }
21289
21290 mg_snprintf(NULL,
21291 NULL,
21292 block,
21293 sizeof(block),
21294 "%s%s\"time\" : {%s"
21295 "\"uptime\" : %.0f,%s"
21296 "\"start\" : \"%s\",%s"
21297 "\"closed\" : \"%s\"%s"
21298 "}",
21299 (connection_info_length > 1 ? "," : ""),
21300 eol,
21301 eol,
21302 time_diff,
21303 eol,
21304 start_time_str,
21305 eol,
21306 close_time_str,
21307 eol);
21308 connection_info_length += mg_str_append(&buffer, end, block);
21309 }
21310
21311 /* Remote user name */
21312 if ((ri->remote_user) && (state < 9)) {
21313 mg_snprintf(NULL,
21314 NULL,
21315 block,
21316 sizeof(block),
21317 "%s%s\"user\" : {%s"
21318 "\"name\" : \"%s\",%s"
21319 "}",
21320 (connection_info_length > 1 ? "," : ""),
21321 eol,
21322 eol,
21323 ri->remote_user,
21324 eol);
21325 connection_info_length += mg_str_append(&buffer, end, block);
21326 }
21327
21328 /* Data block */
21329 if (state >= 3) {
21330 mg_snprintf(NULL,
21331 NULL,
21332 block,
21333 sizeof(block),
21334 "%s%s\"data\" : {%s"
21335 "\"read\" : %" INT64_FMT ",%s"
21336 "\"written\" : %" INT64_FMT "%s"
21337 "}",
21338 (connection_info_length > 1 ? "," : ""),
21339 eol,
21340 eol,
21341 conn->consumed_content,
21342 eol,
21343 conn->num_bytes_sent,
21344 eol);
21345 connection_info_length += mg_str_append(&buffer, end, block);
21346 }
21347
21348 /* State */
21349 mg_snprintf(NULL,
21350 NULL,
21351 block,
21352 sizeof(block),
21353 "%s%s\"state\" : \"%s\"",
21354 (connection_info_length > 1 ? "," : ""),
21355 eol,
21356 state_str);
21357 connection_info_length += mg_str_append(&buffer, end, block);
21358
21359 /* Terminate string */
21360 if (append_eoobj) {
21361 strcat(append_eoobj, eoobj);
21362 }
21363 connection_info_length += sizeof(eoobj) - 1;
21364
21365 return (int)connection_info_length;
21366}
21367#endif
21368
21369
21370/* Initialize this library. This function does not need to be thread safe.
21371 */
21372unsigned
21373mg_init_library(unsigned features)
21374{
21375 unsigned features_to_init = mg_check_feature(features & 0xFFu);
21376 unsigned features_inited = features_to_init;
21377
21378 if (mg_init_library_called <= 0) {
21379 /* Not initialized yet */
21380 if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
21381 return 0;
21382 }
21383 }
21384
21386
21387 if (mg_init_library_called <= 0) {
21388#if defined(_WIN32)
21389 int file_mutex_init = 1;
21390 int wsa = 1;
21391#else
21392 int mutexattr_init = 1;
21393#endif
21394 int failed = 1;
21395 int key_create = pthread_key_create(&sTlsKey, tls_dtor);
21396
21397 if (key_create == 0) {
21398#if defined(_WIN32)
21399 file_mutex_init =
21400 pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
21401 if (file_mutex_init == 0) {
21402 /* Start WinSock */
21403 WSADATA data;
21404 failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
21405 }
21406#else
21407 mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
21408 if (mutexattr_init == 0) {
21409 failed = pthread_mutexattr_settype(&pthread_mutex_attr,
21410 PTHREAD_MUTEX_RECURSIVE);
21411 }
21412#endif
21413 }
21414
21415
21416 if (failed) {
21417#if defined(_WIN32)
21418 if (wsa == 0) {
21419 (void)WSACleanup();
21420 }
21421 if (file_mutex_init == 0) {
21422 (void)pthread_mutex_destroy(&global_log_file_lock);
21423 }
21424#else
21425 if (mutexattr_init == 0) {
21426 (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
21427 }
21428#endif
21429 if (key_create == 0) {
21430 (void)pthread_key_delete(sTlsKey);
21431 }
21433 (void)pthread_mutex_destroy(&global_lock_mutex);
21434 return 0;
21435 }
21436
21437#if defined(USE_LUA)
21438 lua_init_optional_libraries();
21439#endif
21440 }
21441
21443
21444#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
21445 || defined(OPENSSL_API_3_0)) \
21446 && !defined(NO_SSL)
21447 if (features_to_init & MG_FEATURES_SSL) {
21448 if (!mg_openssl_initialized) {
21449 char ebuf[128];
21450 if (initialize_openssl(ebuf, sizeof(ebuf))) {
21451 mg_openssl_initialized = 1;
21452 } else {
21453 (void)ebuf;
21454 DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
21455 features_inited &= ~((unsigned)(MG_FEATURES_SSL));
21456 }
21457 } else {
21458 /* ssl already initialized */
21459 }
21460 }
21461#endif
21462
21464 if (mg_init_library_called <= 0) {
21466 } else {
21468 }
21470
21471 return features_inited;
21472}
21473
21474
21475/* Un-initialize this library. */
21476unsigned
21478{
21479 if (mg_init_library_called <= 0) {
21480 return 0;
21481 }
21482
21484
21486 if (mg_init_library_called == 0) {
21487#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
21488 if (mg_openssl_initialized) {
21490 mg_openssl_initialized = 0;
21491 }
21492#endif
21493
21494#if defined(_WIN32)
21495 (void)WSACleanup();
21496 (void)pthread_mutex_destroy(&global_log_file_lock);
21497#else
21498 (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
21499#endif
21500
21501 (void)pthread_key_delete(sTlsKey);
21502
21503#if defined(USE_LUA)
21504 lua_exit_optional_libraries();
21505#endif
21506
21508 (void)pthread_mutex_destroy(&global_lock_mutex);
21509 return 1;
21510 }
21511
21513 return 1;
21514}
21515
21516
21517/* 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 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 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 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:18516
static int is_authorized_for_put(struct mg_connection *conn)
Definition civetweb.c:8785
static int consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
Definition civetweb.c:18772
static int parse_http_request(char *buf, int len, struct mg_request_info *ri)
Definition civetweb.c:10605
void mg_send_mime_file2(struct mg_connection *conn, const char *path, const char *mime_type, const char *additional_headers)
Definition civetweb.c:10221
#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:8806
static void sockaddr_to_string(char *buf, size_t len, const union usa *usa)
Definition civetweb.c:3256
static void open_auth_file(struct mg_connection *conn, const char *path, struct mg_file *filep)
Definition civetweb.c:8275
int mg_strncasecmp(const char *s1, const char *s2, size_t len)
Definition civetweb.c:2983
#define IP_ADDR_STR_LEN
Definition civetweb.c:1724
static int check_authorization(struct mg_connection *conn, const char *path)
Definition civetweb.c:8668
#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:13543
static int should_switch_to_protocol(const struct mg_connection *conn)
Definition civetweb.c:13230
void mg_unlock_connection(struct mg_connection *conn)
Definition civetweb.c:12314
static void mkcol(struct mg_connection *conn, const char *path)
Definition civetweb.c:11601
static void remove_bad_file(const struct mg_connection *conn, const char *path)
Definition civetweb.c:10304
const struct mg_option * mg_get_valid_options(void)
Definition civetweb.c:2797
static int mg_path_suspicious(const struct mg_connection *conn, const char *path)
Definition civetweb.c:2835
const char * mime_type
Definition civetweb.c:8027
static int set_non_blocking_mode(SOCKET sock)
Definition civetweb.c:5846
static void ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
Definition civetweb.c:15910
const char * proto
Definition civetweb.c:17535
int mg_send_http_error(struct mg_connection *conn, int status, const char *fmt,...)
Definition civetweb.c:4536
static const char * get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
Definition civetweb.c:17622
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:3348
void mg_lock_context(struct mg_context *ctx)
Definition civetweb.c:12322
#define MAX_WORKER_THREADS
Definition civetweb.c:463
@ PROTOCOL_TYPE_HTTP1
Definition civetweb.c:2429
@ PROTOCOL_TYPE_HTTP2
Definition civetweb.c:2431
@ PROTOCOL_TYPE_WEBSOCKET
Definition civetweb.c:2430
static void put_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:11670
static void do_ssi_exec(struct mg_connection *conn, char *tag)
Definition civetweb.c:11945
static void tls_dtor(void *key)
Definition civetweb.c:15534
#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:3902
int mg_send_http_redirect(struct mg_connection *conn, const char *target_url, int redirect_code)
Definition civetweb.c:4591
int mg_get_cookie(const char *cookie_header, const char *var_name, char *dst, size_t dst_size)
Definition civetweb.c:7158
static int ssl_get_client_cert_info(const struct mg_connection *conn, struct mg_client_cert *client_cert)
Definition civetweb.c:15833
#define mg_cry_ctx_internal(ctx, fmt,...)
Definition civetweb.c:2550
@ CONTEXT_WS_CLIENT
Definition civetweb.c:2247
@ CONTEXT_INVALID
Definition civetweb.c:2244
@ CONTEXT_SERVER
Definition civetweb.c:2245
@ CONTEXT_HTTP_CLIENT
Definition civetweb.c:2246
static void mg_snprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, const char *fmt,...)
Definition civetweb.c:3107
#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:3011
static int put_dir(struct mg_connection *conn, const char *path)
Definition civetweb.c:10267
#define UINT64_FMT
Definition civetweb.c:924
static void send_static_cache_header(struct mg_connection *conn)
Definition civetweb.c:4069
static void handle_cgi_request(struct mg_connection *conn, const char *prog, unsigned char cgi_config_idx)
Definition civetweb.c:11278
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:8026
static int print_dav_dir_entry(struct de *de, void *data)
Definition civetweb.c:12247
static void delete_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:11797
#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:18394
#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:3212
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:6936
static int abort_cgi_process(void *data)
Definition civetweb.c:11243
static int should_keep_alive(const struct mg_connection *conn)
Definition civetweb.c:3979
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:2879
void mg_disable_connection_keep_alive(struct mg_connection *conn)
Definition civetweb.c:21109
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:9883
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:16153
static const char * ssl_error(void)
Definition civetweb.c:15798
static int must_hide_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:9435
static void log_access(const struct mg_connection *)
Definition civetweb.c:15284
const char * extension
Definition civetweb.c:8025
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:17413
#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:4550
static void close_all_listening_sockets(struct mg_context *ctx)
Definition civetweb.c:14677
#define closesocket(a)
Definition civetweb.c:914
void mg_send_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:10205
static void send_authorization_request(struct mg_connection *conn, const char *realm)
Definition civetweb.c:8724
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:5738
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:8230
static int check_acl(struct mg_context *phys_ctx, const union usa *sa)
Definition civetweb.c:15442
static const struct mg_option config_options[]
Definition civetweb.c:2049
static const struct mg_http_method_info * get_http_method_info(const char *method)
Definition civetweb.c:10570
#define STOP_FLAG_IS_ZERO(f)
Definition civetweb.c:2304
unsigned default_port
Definition civetweb.c:17537
const char * mg_get_response_code_text(const struct mg_connection *conn, int response_code)
Definition civetweb.c:4151
static int get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
Definition civetweb.c:17894
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:3447
static int set_uid_option(struct mg_context *phys_ctx)
Definition civetweb.c:15480
static int switch_domain_context(struct mg_connection *conn)
Definition civetweb.c:13482
static struct mg_connection * fake_connection(struct mg_connection *fc, struct mg_context *ctx)
Definition civetweb.c:3436
static void reset_per_request_attributes(struct mg_connection *conn)
Definition civetweb.c:16889
static void handle_file_based_request(struct mg_connection *conn, const char *path, struct mg_file *filep)
Definition civetweb.c:14575
#define FUNCTION_MAY_BE_UNUSED
Definition civetweb.c:316
static pthread_mutex_t * ssl_mutexes
Definition civetweb.c:15664
static int get_option_index(const char *name)
Definition civetweb.c:3123
static char * mg_strdup(const char *str)
Definition civetweb.c:3032
static void send_no_cache_header(struct mg_connection *conn)
Definition civetweb.c:4051
static void master_thread_run(struct mg_context *ctx)
Definition civetweb.c:19192
static int prepare_cgi_environment(struct mg_connection *conn, const char *prog, struct cgi_environment *env, unsigned char cgi_config_idx)
Definition civetweb.c:11045
static const char month_names[][4]
Definition civetweb.c:1806
const struct mg_response_info * mg_get_response_info(const struct mg_connection *conn)
Definition civetweb.c:3527
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:19105
static volatile ptrdiff_t cryptolib_users
Definition civetweb.c:16028
static int get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
Definition civetweb.c:17726
#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:19612
#define CGI_ENVIRONMENT_SIZE
Definition civetweb.c:486
static int parse_http_headers(char **buf, struct mg_header hdr[(64)])
Definition civetweb.c:10420
#define mg_get_option
Definition civetweb.c:3149
static long ssl_get_protocol(int version_id)
Definition civetweb.c:16230
void * mg_get_user_context_data(const struct mg_connection *conn)
Definition civetweb.c:3166
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:10317
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:18031
#define DEBUG_ASSERT(cond)
Definition civetweb.c:260
static size_t mg_str_append(char **dst, char *end, const char *src)
Definition civetweb.c:20559
static int pull_inner(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
Definition civetweb.c:6184
#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:17979
#define MG_FILE_COMPRESSION_SIZE_LIMIT
Definition civetweb.c:476
#define USA_IN_PORT_UNSAFE(s)
Definition civetweb.c:1851
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:17216
unsigned mg_check_feature(unsigned feature)
Definition civetweb.c:20496
static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
Definition civetweb.c:6468
static int mg_send_http_error_impl(struct mg_connection *conn, int status, const char *fmt, va_list args)
Definition civetweb.c:4350
struct mg_context * mg_start(const struct mg_callbacks *callbacks, void *user_data, const char **options)
Definition civetweb.c:20284
#define MG_FOPEN_MODE_READ
Definition civetweb.c:2807
#define STOP_FLAG_ASSIGN(f, v)
Definition civetweb.c:2306
static int extention_matches_script(struct mg_connection *conn, const char *filename)
Definition civetweb.c:7319
static void get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
Definition civetweb.c:13444
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:13796
int mg_start_domain(struct mg_context *ctx, const char **options)
Definition civetweb.c:20488
static pthread_mutexattr_t pthread_mutex_attr
Definition civetweb.c:1071
void mg_unlock_context(struct mg_context *ctx)
Definition civetweb.c:12330
static int ssl_servername_callback(SSL *ssl, int *ad, void *arg)
Definition civetweb.c:16279
int mg_modify_passwords_file(const char *fname, const char *domain, const char *user, const char *pass)
Definition civetweb.c:8926
static char * skip_quoted(char **buf, const char *delimiters, const char *whitespace, char quotechar)
Definition civetweb.c:3700
static void fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
Definition civetweb.c:9859
int mg_start_thread(mg_thread_func_t func, void *param)
Definition civetweb.c:5670
static const char * get_header(const struct mg_header *hdr, int num_hdr, const char *name)
Definition civetweb.c:3764
static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
Definition civetweb.c:8953
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:16452
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:8994
unsigned mg_init_library(unsigned features)
Definition civetweb.c:21373
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:17425
static int forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
Definition civetweb.c:10875
static int set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
Definition civetweb.c:16849
static int skip_to_end_of_word_and_terminate(char **ppw, int eol)
Definition civetweb.c:10375
static int get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
Definition civetweb.c:17802
static int set_tcp_nodelay(const struct socket *so, int nodelay_on)
Definition civetweb.c:16931
int mg_get_var(const char *data, size_t data_len, const char *name, char *dst, size_t dst_len)
Definition civetweb.c:6990
#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:14722
static int get_first_ssl_listener_index(const struct mg_context *ctx)
Definition civetweb.c:13429
void mg_send_mime_file(struct mg_connection *conn, const char *path, const char *mime_type)
Definition civetweb.c:10212
const char * mg_get_header(const struct mg_connection *conn, const char *name)
Definition civetweb.c:3801
#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:7059
static int hexdump2string(void *mem, int memlen, char *buf, int buflen)
Definition civetweb.c:15807
#define UTF8_PATH_MAX
Definition civetweb.c:858
static const struct mg_http_method_info http_methods[]
Definition civetweb.c:10508
static int mg_poll(struct pollfd *pfd, unsigned int n, int milliseconds, const stop_flag_t *stop_flag)
Definition civetweb.c:5908
static void handle_directory_request(struct mg_connection *conn, const char *dir)
Definition civetweb.c:9617
static int set_ports_option(struct mg_context *phys_ctx)
Definition civetweb.c:14957
static int read_auth_file(struct mg_file *filep, struct read_auth_file_struct *workdata, int depth)
Definition civetweb.c:8505
static int mg_start_thread_with_id(mg_thread_func_t func, void *param, pthread_t *threadidptr)
Definition civetweb.c:5696
unsigned mg_exit_library(void)
Definition civetweb.c:21477
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:15928
static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
Definition civetweb.c:3306
int mg_send_digest_access_authentication_request(struct mg_connection *conn, const char *realm)
Definition civetweb.c:8772
static const char * mg_strcasestr(const char *big_str, const char *small_str)
Definition civetweb.c:3039
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:18364
static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
Definition civetweb.c:6413
static void handle_ssi_file_request(struct mg_connection *conn, const char *path, struct mg_file *filep)
Definition civetweb.c:12090
int mg_write(struct mg_connection *conn, const void *buf, size_t len)
Definition civetweb.c:6695
static int set_throttle(const char *spec, const union usa *rsa, const char *uri)
Definition civetweb.c:13383
static void ssl_info_callback(const SSL *ssl, int what, int ret)
Definition civetweb.c:16263
#define calloc
Definition civetweb.c:1537
static void bin2str(char *to, const unsigned char *p, size_t len)
Definition civetweb.c:8192
const struct mg_request_info * mg_get_request_info(const struct mg_connection *conn)
Definition civetweb.c:3487
#define MG_FOPEN_MODE_APPEND
Definition civetweb.c:2813
char * mg_md5(char buf[33],...)
Definition civetweb.c:8207
#define STOP_FLAG_IS_TWO(f)
Definition civetweb.c:2305
static const char * next_option(const char *list, struct vec *val, struct vec *eq_val)
Definition civetweb.c:3845
static const char * suggest_connection_header(const struct mg_connection *conn)
Definition civetweb.c:4041
static ptrdiff_t match_prefix_strlen(const char *pattern, const char *str)
Definition civetweb.c:3966
static int alloc_vprintf(char **out_buf, char *prealloc_buf, size_t prealloc_size, const char *fmt, va_list ap)
Definition civetweb.c:6855
static time_t parse_date_string(const char *datetime)
Definition civetweb.c:7808
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:11860
static void uninitialize_openssl(void)
Definition civetweb.c:16807
int mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
Definition civetweb.c:3688
static int parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
Definition civetweb.c:13274
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:8936
static void send_options(struct mg_connection *conn)
Definition civetweb.c:12159
static int lowercase(const char *s)
Definition civetweb.c:2976
static void release_handler_ref(struct mg_connection *conn, struct mg_handler_info *handler_info)
Definition civetweb.c:13995
static int parse_range_header(const char *header, int64_t *a, int64_t *b)
Definition civetweb.c:9832
static int mg_stat(const struct mg_connection *conn, const char *path, struct mg_file_stat *filep)
Definition civetweb.c:5620
static int get_uri_type(const char *uri)
Definition civetweb.c:17552
#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:19536
int mg_url_encode(const char *src, char *dst, size_t dst_len)
Definition civetweb.c:9261
static const char * header_val(const struct mg_connection *conn, const char *header)
Definition civetweb.c:15267
#define mg_cry_internal(conn, fmt,...)
Definition civetweb.c:2547
static int set_acl_option(struct mg_context *phys_ctx)
Definition civetweb.c:16875
static void mg_set_thread_name(const char *name)
Definition civetweb.c:2744
static void get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
Definition civetweb.c:8157
static int set_blocking_mode(SOCKET sock)
Definition civetweb.c:5860
#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:9728
#define MAX_CGI_ENVIR_VARS
Definition civetweb.c:491
static char * mg_strdup_ctx(const char *str, struct mg_context *ctx)
Definition civetweb.c:3026
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:18420
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded)
Definition civetweb.c:6950
static int parse_auth_header(struct mg_connection *conn, char *buf, size_t buf_size, struct ah *ah)
Definition civetweb.c:8355
void mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
Definition civetweb.c:3189
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:7001
static int is_not_modified(const struct mg_connection *conn, const struct mg_file_stat *filestat)
Definition civetweb.c:10163
static void worker_thread_run(struct mg_connection *conn)
Definition civetweb.c:18852
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:7437
static const char * get_proto_name(const struct mg_connection *conn)
Definition civetweb.c:3540
static void * master_thread(void *thread_func_param)
Definition civetweb.c:19378
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:13588
static int is_file_opened(const struct mg_file_access *fileacc)
Definition civetweb.c:2817
static int get_http_header_len(const char *buf, int buflen)
Definition civetweb.c:7755
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:18450
void mg_close_connection(struct mg_connection *conn)
Definition civetweb.c:17153
static int is_valid_port(unsigned long port)
Definition civetweb.c:8946
static void handle_propfind(struct mg_connection *conn, const char *path, struct mg_file_stat *filep)
Definition civetweb.c:12261
static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
Definition civetweb.c:6918
#define mg_realloc_ctx(a, b, c)
Definition civetweb.c:1496
static void send_additional_header(struct mg_connection *conn)
Definition civetweb.c:4117
static int push_all(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int len)
Definition civetweb.c:6136
static int is_put_or_delete_method(const struct mg_connection *conn)
Definition civetweb.c:7305
static int read_message(FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread)
Definition civetweb.c:10798
static int print_dir_entry(struct de *de)
Definition civetweb.c:9289
#define MG_FOPEN_MODE_WRITE
Definition civetweb.c:2810
void * mg_get_user_connection_data(const struct mg_connection *conn)
Definition civetweb.c:3202
static int authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
Definition civetweb.c:8615
static void send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int)
Definition civetweb.c:11984
#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:18809
static ptrdiff_t match_prefix(const char *pattern, size_t pattern_len, const char *str)
Definition civetweb.c:3921
int mg_send_chunk(struct mg_connection *conn, const char *chunk, unsigned int chunk_len)
Definition civetweb.c:6776
static void remove_dot_segments(char *inout)
Definition civetweb.c:7872
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:13868
void mg_set_auth_handler(struct mg_context *ctx, const char *uri, mg_authorization_handler handler, void *cbdata)
Definition civetweb.c:13846
int mg_start_domain2(struct mg_context *ctx, const char **options, struct mg_error_data *error)
Definition civetweb.c:20299
#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:6822
static const struct @142 builtin_mime_types[]
static int extention_matches_template_text(struct mg_connection *conn, const char *filename)
Definition civetweb.c:7365
static int is_in_script_path(const struct mg_connection *conn, const char *path)
Definition civetweb.c:13953
static int should_decode_query_string(const struct mg_connection *conn)
Definition civetweb.c:4029
static double mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
Definition civetweb.c:3330
static void free_context(struct mg_context *ctx)
Definition civetweb.c:19396
static int sslize(struct mg_connection *conn, int(*func)(SSL *), const struct mg_client_options *client_options)
Definition civetweb.c:15668
static void legacy_init(const char **options)
Definition civetweb.c:19584
static void construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
Definition civetweb.c:9844
int mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
Definition civetweb.c:20910
int volatile stop_flag_t
Definition civetweb.c:2303
static int refresh_trust(struct mg_connection *conn)
Definition civetweb.c:15590
#define SHUTDOWN_WR
Definition civetweb.c:515
void * mg_get_thread_pointer(const struct mg_connection *conn)
Definition civetweb.c:3173
static int compare_dir_entries(const void *p1, const void *p2)
Definition civetweb.c:9399
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:3058
static int should_decode_url(const struct mg_connection *conn)
Definition civetweb.c:4018
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:3567
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:6582
@ AUTH_HANDLER
Definition civetweb.c:2207
@ REQUEST_HANDLER
Definition civetweb.c:2207
@ WEBSOCKET_HANDLER
Definition civetweb.c:2207
#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:2966
static int remove_directory(struct mg_connection *conn, const char *dir)
Definition civetweb.c:9509
static const char * get_http_version(const struct mg_connection *conn)
Definition civetweb.c:3822
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:14012
static int parse_http_response(char *buf, int len, struct mg_response_info *ri)
Definition civetweb.c:10691
static void * cryptolib_dll_handle
Definition civetweb.c:16019
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:8135
static const char * mg_fgets(char *buf, size_t size, struct mg_file *filep)
Definition civetweb.c:8468
int mg_read(struct mg_connection *conn, void *buf, size_t len)
Definition civetweb.c:6587
#define IGNORE_UNUSED_RESULT(a)
Definition civetweb.c:291
static void addenv(struct cgi_environment *env, const char *fmt,...)
Definition civetweb.c:10975
static void discard_unread_request_data(struct mg_connection *conn)
Definition civetweb.c:6458
int mg_strcasecmp(const char *s1, const char *s2)
Definition civetweb.c:2998
static int mg_fclose(struct mg_file_access *fileacc)
Definition civetweb.c:2950
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:18154
void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata)
Definition civetweb.c:13774
static void * worker_thread(void *thread_func_param)
Definition civetweb.c:19085
static __inline void mg_free(void *a)
Definition civetweb.c:1489
static void handle_request_stat_log(struct mg_connection *conn)
Definition civetweb.c:6536
int mg_check_digest_access_authentication(struct mg_connection *conn, const char *realm, const char *filename)
Definition civetweb.c:8643
static int mg_join_thread(pthread_t threadid)
Definition civetweb.c:5727
static void mg_global_unlock(void)
Definition civetweb.c:1099
int mg_get_system_info(char *buffer, int buflen)
Definition civetweb.c:20578
static void handle_not_modified_static_file_request(struct mg_connection *conn, struct mg_file *filep)
Definition civetweb.c:10178
static int init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
Definition civetweb.c:16698
static void close_socket_gracefully(struct mg_connection *conn)
Definition civetweb.c:16953
struct mg_context * mg_get_context(const struct mg_connection *conn)
Definition civetweb.c:3152
static int is_ssl_port_used(const char *ports)
Definition civetweb.c:14900
static void init_connection(struct mg_connection *conn)
Definition civetweb.c:18478
static int print_props(struct mg_connection *conn, const char *uri, const char *name, struct mg_file_stat *filep)
Definition civetweb.c:12190
#define INITIAL_DEPTH
Definition civetweb.c:8487
static int dir_scan_callback(struct de *de, void *data)
Definition civetweb.c:9585
size_t proto_len
Definition civetweb.c:17536
static void set_close_on_exec(int fd, const struct mg_connection *conn, struct mg_context *ctx)
Definition civetweb.c:5647
static int get_month_index(const char *s)
Definition civetweb.c:7792
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:13816
static void * ssllib_dll_handle
Definition civetweb.c:16018
static int mg_fgetc(struct mg_file *filep)
Definition civetweb.c:11969
#define mg_sleep(x)
Definition civetweb.c:917
@ CONNECTION_TYPE_RESPONSE
Definition civetweb.c:2425
@ CONNECTION_TYPE_INVALID
Definition civetweb.c:2423
@ CONNECTION_TYPE_REQUEST
Definition civetweb.c:2424
#define PASSWORDS_FILE_NAME
Definition civetweb.c:480
static void close_connection(struct mg_connection *conn)
Definition civetweb.c:17078
@ ENABLE_DIRECTORY_LISTING
Definition civetweb.c:1989
@ SSL_SHORT_TRUST
Definition civetweb.c:2006
@ GLOBAL_PASSWORDS_FILE
Definition civetweb.c:1990
@ ADDITIONAL_HEADER
Definition civetweb.c:2039
@ SSL_VERIFY_DEPTH
Definition civetweb.c:2002
@ ACCESS_CONTROL_ALLOW_ORIGIN
Definition civetweb.c:2027
@ SSL_PROTOCOL_VERSION
Definition civetweb.c:2005
@ SSL_DO_VERIFY_PEER
Definition civetweb.c:1998
@ SSL_CERTIFICATE
Definition civetweb.c:1994
@ RUN_AS_USER
Definition civetweb.c:1913
@ ALLOW_INDEX_SCRIPT_SUB_RES
Definition civetweb.c:2040
@ SSL_CACHE_TIMEOUT
Definition civetweb.c:1999
@ CONNECTION_QUEUE_SIZE
Definition civetweb.c:1918
@ ENABLE_KEEP_ALIVE
Definition civetweb.c:1927
@ ACCESS_CONTROL_LIST
Definition civetweb.c:1992
@ CGI_INTERPRETER_ARGS
Definition civetweb.c:1953
@ SSL_CA_PATH
Definition civetweb.c:2000
@ AUTHENTICATION_DOMAIN
Definition civetweb.c:1986
@ ACCESS_CONTROL_ALLOW_HEADERS
Definition civetweb.c:2029
@ SSL_DEFAULT_VERIFY_PATHS
Definition civetweb.c:2003
@ CGI2_EXTENSIONS
Definition civetweb.c:1958
@ ACCESS_CONTROL_ALLOW_METHODS
Definition civetweb.c:2028
@ STRICT_HTTPS_MAX_AGE
Definition civetweb.c:2037
@ HIDE_FILES
Definition civetweb.c:1997
@ ERROR_LOG_FILE
Definition civetweb.c:1948
@ CGI2_INTERPRETER_ARGS
Definition civetweb.c:1961
@ STATIC_FILE_MAX_AGE
Definition civetweb.c:2033
@ LINGER_TIMEOUT
Definition civetweb.c:1917
@ URL_REWRITE_PATTERN
Definition civetweb.c:1996
@ THROTTLE
Definition civetweb.c:1926
@ SSL_CIPHER_LIST
Definition civetweb.c:2004
@ KEEP_ALIVE_TIMEOUT
Definition civetweb.c:1929
@ CGI_EXTENSIONS
Definition civetweb.c:1950
@ STATIC_FILE_CACHE_CONTROL
Definition civetweb.c:2034
@ ERROR_PAGES
Definition civetweb.c:2031
@ CGI_ENVIRONMENT
Definition civetweb.c:1951
@ PUT_DELETE_PASSWORDS_FILE
Definition civetweb.c:1984
@ ENABLE_AUTH_DOMAIN_CHECK
Definition civetweb.c:1987
@ NUM_OPTIONS
Definition civetweb.c:2042
@ MAX_REQUEST_SIZE
Definition civetweb.c:1916
@ DECODE_URL
Definition civetweb.c:1934
@ NUM_THREADS
Definition civetweb.c:1912
@ DOCUMENT_ROOT
Definition civetweb.c:1945
@ SSL_CERTIFICATE_CHAIN
Definition civetweb.c:1995
@ CGI2_ENVIRONMENT
Definition civetweb.c:1959
@ PROTECT_URI
Definition civetweb.c:1985
@ ACCESS_LOG_FILE
Definition civetweb.c:1947
@ ACCESS_CONTROL_ALLOW_CREDENTIALS
Definition civetweb.c:2030
@ REQUEST_TIMEOUT
Definition civetweb.c:1928
@ SSI_EXTENSIONS
Definition civetweb.c:1988
@ CONFIG_TCP_NODELAY
Definition civetweb.c:1914
@ SSL_CA_FILE
Definition civetweb.c:2001
@ CGI_INTERPRETER
Definition civetweb.c:1952
@ LISTEN_BACKLOG_SIZE
Definition civetweb.c:1919
@ DECODE_QUERY_STRING
Definition civetweb.c:1935
@ LISTENING_PORTS
Definition civetweb.c:1911
@ CGI2_INTERPRETER
Definition civetweb.c:1960
@ INDEX_FILES
Definition civetweb.c:1991
@ EXTRA_MIME_TYPES
Definition civetweb.c:1993
static int initialize_openssl(char *ebuf, size_t ebuf_len)
Definition civetweb.c:16034
static int substitute_index_file(struct mg_connection *conn, char *path, size_t path_len, struct mg_file_stat *filestat)
Definition civetweb.c:7389
void mg_stop(struct mg_context *ctx)
Definition civetweb.c:19493
#define STRUCT_FILE_INITIALIZER
Definition civetweb.c:1882
static volatile ptrdiff_t thread_idx_max
Definition civetweb.c:1573
void * mg_get_user_data(const struct mg_context *ctx)
Definition civetweb.c:3159
static int scan_directory(struct mg_connection *conn, const char *dir, void *data, int(*cb)(struct de *, void *))
Definition civetweb.c:9449
static int push_inner(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int len, double timeout)
Definition civetweb.c:5970
const char * mg_version(void)
Definition civetweb.c:3480
static uint64_t get_random(void)
Definition civetweb.c:5879
void mg_lock_connection(struct mg_connection *conn)
Definition civetweb.c:12306
int mg_send_file_body(struct mg_connection *conn, const char *path)
Definition civetweb.c:10146
#define mg_cry
Definition civetweb.c:3476
static int is_valid_http_method(const char *method)
Definition civetweb.c:10589
static void url_decode_in_place(char *buf)
Definition civetweb.c:6982
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:8349
char * nonce
Definition civetweb.c:8349
char * cnonce
Definition civetweb.c:8349
char * uri
Definition civetweb.c:8349
char * user
Definition civetweb.c:8349
char * qop
Definition civetweb.c:8349
char * response
Definition civetweb.c:8349
struct mg_connection * conn
Definition civetweb.c:10956
char * file_name
Definition civetweb.c:2542
struct mg_connection * conn
Definition civetweb.c:2541
struct mg_file_stat file
Definition civetweb.c:2543
size_t num_entries
Definition civetweb.c:9578
struct de * entries
Definition civetweb.c:9577
size_t arr_size
Definition civetweb.c:9579
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:2526
int64_t content_len
Definition civetweb.c:2481
struct timespec req_time
Definition civetweb.c:2478
int64_t consumed_content
Definition civetweb.c:2487
char * path_info
Definition civetweb.c:2496
int64_t num_bytes_sent
Definition civetweb.c:2480
int connection_type
Definition civetweb.c:2449
pthread_mutex_t mutex
Definition civetweb.c:2528
struct socket client
Definition civetweb.c:2470
struct mg_response_info response_info
Definition civetweb.c:2458
void * tls_user_ptr
Definition civetweb.c:2534
struct mg_request_info request_info
Definition civetweb.c:2457
struct mg_context * phys_ctx
Definition civetweb.c:2460
struct mg_domain_context * dom_ctx
Definition civetweb.c:2461
int in_error_handler
Definition civetweb.c:2500
time_t conn_birth_time
Definition civetweb.c:2471
int handled_requests
Definition civetweb.c:2517
int last_throttle_bytes
Definition civetweb.c:2527
time_t start_time
Definition civetweb.c:2375
pthread_cond_t sq_empty
Definition civetweb.c:2358
struct socket * squeue
Definition civetweb.c:2353
pthread_t * worker_threadids
Definition civetweb.c:2345
volatile int sq_head
Definition civetweb.c:2355
stop_flag_t stop_flag
Definition civetweb.c:2339
void * user_data
Definition civetweb.c:2396
unsigned long starter_thread_idx
Definition civetweb.c:2346
struct mg_connection * worker_connections
Definition civetweb.c:2326
struct socket * listening_sockets
Definition civetweb.c:2322
char * systemName
Definition civetweb.c:2374
pthread_t masterthreadid
Definition civetweb.c:2342
int context_type
Definition civetweb.c:2320
pthread_mutex_t thread_mutex
Definition civetweb.c:2340
struct mg_callbacks callbacks
Definition civetweb.c:2395
struct mg_domain_context dd
Definition civetweb.c:2405
struct pollfd * listening_socket_fds
Definition civetweb.c:2323
pthread_cond_t sq_full
Definition civetweb.c:2357
volatile int sq_tail
Definition civetweb.c:2356
unsigned int num_listening_sockets
Definition civetweb.c:2324
unsigned int max_request_size
Definition civetweb.c:2367
unsigned int cfg_worker_threads
Definition civetweb.c:2344
pthread_mutex_t nonce_mutex
Definition civetweb.c:2390
volatile int sq_blocked
Definition civetweb.c:2359
char * config[NUM_OPTIONS]
Definition civetweb.c:2253
unsigned long nonce_count
Definition civetweb.c:2259
int64_t ssl_cert_last_mtime
Definition civetweb.c:2255
uint64_t auth_nonce_mask
Definition civetweb.c:2258
struct mg_domain_context * next
Definition civetweb.c:2267
SSL_CTX * ssl_ctx
Definition civetweb.c:2252
struct mg_handler_info * handlers
Definition civetweb.c:2254
unsigned * code
Definition civetweb.h:1672
size_t text_buffer_size
Definition civetweb.h:1674
uint64_t size
Definition civetweb.c:1862
time_t last_modified
Definition civetweb.c:1863
struct mg_file_stat stat
Definition civetweb.c:1877
struct mg_file_access access
Definition civetweb.c:1878
mg_request_handler handler
Definition civetweb.c:2219
mg_authorization_handler auth_handler
Definition civetweb.c:2233
mg_websocket_close_handler close_handler
Definition civetweb.c:2227
struct mg_handler_info * next
Definition civetweb.c:2239
unsigned int refcount
Definition civetweb.c:2220
mg_websocket_connect_handler connect_handler
Definition civetweb.c:2224
struct mg_websocket_subprotocols * subprotocols
Definition civetweb.c:2230
mg_websocket_data_handler data_handler
Definition civetweb.c:2226
mg_websocket_ready_handler ready_handler
Definition civetweb.c:2225
const char * value
Definition civetweb.h:145
const char * name
Definition civetweb.h:144
const char * name
Definition civetweb.c:10498
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:8500
const char * f_domain
Definition civetweb.c:8499
const char * f_user
Definition civetweb.c:8498
const char * domain
Definition civetweb.c:8496
char buf[256+256+40]
Definition civetweb.c:8497
struct mg_connection * conn
Definition civetweb.c:8494
unsigned char is_ssl
Definition civetweb.c:1897
union usa lsa
Definition civetweb.c:1895
unsigned char ssl_redir
Definition civetweb.c:1898
SOCKET sock
Definition civetweb.c:1894
unsigned char in_use
Definition civetweb.c:1900
union usa rsa
Definition civetweb.c:1896
void(* ptr)(void)
const char * name
enum ssl_func_category required
size_t len
Definition civetweb.c:1857
const char * ptr
Definition civetweb.c:1856
mg_websocket_close_handler close_handler
Definition civetweb.c:18086
mg_websocket_data_handler data_handler
Definition civetweb.c:18085
struct mg_connection * conn
Definition civetweb.c:18084
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
struct sockaddr sa
Definition civetweb.c:1824
struct sockaddr_in sin
Definition civetweb.c:1825
static void output()