Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
civetweb.c
Go to the documentation of this file.
1/* Copyright (c) 2013-2021 the Civetweb developers
2 * Copyright (c) 2004-2013 Sergey Lyubka
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23#if defined(__GNUC__) || defined(__MINGW32__)
24#define GCC_VERSION \
25 (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
26#if GCC_VERSION >= 40500
27/* gcc diagnostic pragmas available */
28#define GCC_DIAGNOSTIC
29#endif
30#endif
31
32#if defined(GCC_DIAGNOSTIC)
33/* Disable unused macros warnings - not all defines are required
34 * for all systems and all compilers. */
35#pragma GCC diagnostic ignored "-Wunused-macros"
36/* A padding warning is just plain useless */
37#pragma GCC diagnostic ignored "-Wpadded"
38#endif
39
40#if defined(__clang__) /* GCC does not (yet) support this pragma */
41/* We must set some flags for the headers we include. These flags
42 * are reserved ids according to C99, so we need to disable a
43 * warning for that. */
44#pragma GCC diagnostic push
45#pragma GCC diagnostic ignored "-Wreserved-id-macro"
46#endif
47
48#if defined(_WIN32)
49#if !defined(_CRT_SECURE_NO_WARNINGS)
50#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
51#endif
52#if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
53#define _WIN32_WINNT 0x0502
54#endif
55#else
56#if !defined(_GNU_SOURCE)
57#define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
58#endif
59#if defined(__linux__) && !defined(_XOPEN_SOURCE)
60#define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
61#endif
62#if defined(__LSB_VERSION__) || defined(__sun)
63#define NEED_TIMEGM
64#define NO_THREAD_NAME
65#endif
66#if !defined(_LARGEFILE_SOURCE)
67#define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
68#endif
69#if !defined(_FILE_OFFSET_BITS)
70#define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
71#endif
72#if !defined(__STDC_FORMAT_MACROS)
73#define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
74#endif
75#if !defined(__STDC_LIMIT_MACROS)
76#define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
77#endif
78#if !defined(_DARWIN_UNLIMITED_SELECT)
79#define _DARWIN_UNLIMITED_SELECT
80#endif
81#if defined(__sun)
82#define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
83#define __inline inline /* not recognized on older compiler versions */
84#endif
85#endif
86
87#if defined(__clang__)
88/* Enable reserved-id-macro warning again. */
89#pragma GCC diagnostic pop
90#endif
91
92
93#if defined(USE_LUA)
94#define USE_TIMERS
95#endif
96
97#if defined(_MSC_VER)
98/* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
99#pragma warning(disable : 4306)
100/* conditional expression is constant: introduced by FD_SET(..) */
101#pragma warning(disable : 4127)
102/* non-constant aggregate initializer: issued due to missing C99 support */
103#pragma warning(disable : 4204)
104/* padding added after data member */
105#pragma warning(disable : 4820)
106/* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
107#pragma warning(disable : 4668)
108/* no function prototype given: converting '()' to '(void)' */
109#pragma warning(disable : 4255)
110/* function has been selected for automatic inline expansion */
111#pragma warning(disable : 4711)
112#endif
113
114
115/* This code uses static_assert to check some conditions.
116 * Unfortunately some compilers still do not support it, so we have a
117 * replacement function here. */
118#if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
119#define mg_static_assert _Static_assert
120#elif defined(__cplusplus) && __cplusplus >= 201103L
121#define mg_static_assert static_assert
122#else
124#define mg_static_assert(cond, txt) \
125 extern char static_assert_replacement[(cond) ? 1 : -1]
126#endif
127
128mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
129 "int data type size check");
130mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
131 "pointer data type size check");
132mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
133
134
135/* Select queue implementation. Diagnosis features originally only implemented
136 * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
137 * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
138 * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
139 * implementation, since the queue length is independent from the number of
140 * worker threads there, while the new queue is one element per worker thread.
141 *
142 */
143#if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
144/* The queues are exclusive or - only one can be used. */
145#error \
146 "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
147#endif
148#if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
149/* Use a default implementation */
150#define NO_ALTERNATIVE_QUEUE
151#endif
152
153#if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
154/* File system access:
155 * NO_FILES = do not serve any files from the file system automatically.
156 * However, with NO_FILES CivetWeb may still write log files, read access
157 * control files, default error page files or use API functions like
158 * mg_send_file in callbacks to send files from the server local
159 * file system.
160 * NO_FILES only disables the automatic mapping between URLs and local
161 * file names.
162 * NO_FILESYSTEM = do not access any file at all. Useful for embedded
163 * devices without file system. Logging to files in not available
164 * (use callbacks instead) and API functions like mg_send_file are not
165 * available.
166 * If NO_FILESYSTEM is set, NO_FILES must be set as well.
167 */
168#error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
169#endif
170
171/* DTL -- including winsock2.h works better if lean and mean */
172#if !defined(WIN32_LEAN_AND_MEAN)
173#define WIN32_LEAN_AND_MEAN
174#endif
175
176#if defined(__SYMBIAN32__)
177/* According to https://en.wikipedia.org/wiki/Symbian#History,
178 * Symbian is no longer maintained since 2014-01-01.
179 * Support for Symbian has been removed from CivetWeb
180 */
181#error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
182#endif /* __SYMBIAN32__ */
183
184#if defined(__ZEPHYR__)
185#include <time.h>
186
187#include <ctype.h>
188#include <net/socket.h>
189#include <posix/pthread.h>
190#include <posix/time.h>
191#include <stdio.h>
192#include <stdlib.h>
193#include <string.h>
194#include <zephyr.h>
195
196#include <fcntl.h>
197
198#include <libc_extensions.h>
199
200/* Max worker threads is the max of pthreads minus the main application thread
201 * and minus the main civetweb thread, thus -2
202 */
203#define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
204
205#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
206#define ZEPHYR_STACK_SIZE USE_STACK_SIZE
207#else
208#define ZEPHYR_STACK_SIZE (1024 * 16)
209#endif
210
211K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
212K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
214 ZEPHYR_STACK_SIZE);
215
216static int zephyr_worker_stack_index;
217
218#endif
219
220#if !defined(CIVETWEB_HEADER_INCLUDED)
221/* Include the header file here, so the CivetWeb interface is defined for the
222 * entire implementation, including the following forward definitions. */
223#include "civetweb.h"
224#endif
225
226#if !defined(DEBUG_TRACE)
227#if defined(DEBUG)
228static void DEBUG_TRACE_FUNC(const char *func,
229 unsigned line,
230 PRINTF_FORMAT_STRING(const char *fmt),
231 ...) PRINTF_ARGS(3, 4);
232
233#define DEBUG_TRACE(fmt, ...) \
234 DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
235
236#define NEED_DEBUG_TRACE_FUNC
237#if !defined(DEBUG_TRACE_STREAM)
238#define DEBUG_TRACE_STREAM stdout
239#endif
240
241#else
242#define DEBUG_TRACE(fmt, ...) \
243 do { \
244 } while (0)
245#endif /* DEBUG */
246#endif /* DEBUG_TRACE */
247
248
249#if !defined(DEBUG_ASSERT)
250#if defined(DEBUG)
251#include <stdlib.h>
252#define DEBUG_ASSERT(cond) \
253 do { \
254 if (!(cond)) { \
255 DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
256 exit(2); /* Exit with error */ \
257 } \
258 } while (0)
259#else
260#define DEBUG_ASSERT(cond)
261#endif /* DEBUG */
262#endif
263
264
265#if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
266void __cyg_profile_func_enter(void *this_fn, void *call_site)
267 __attribute__((no_instrument_function));
268
269void __cyg_profile_func_exit(void *this_fn, void *call_site)
270 __attribute__((no_instrument_function));
271
272void
273__cyg_profile_func_enter(void *this_fn, void *call_site)
274{
275 if ((void *)this_fn != (void *)printf) {
276 printf("E %p %p\n", this_fn, call_site);
277 }
278}
279
280void
281__cyg_profile_func_exit(void *this_fn, void *call_site)
282{
283 if ((void *)this_fn != (void *)printf) {
284 printf("X %p %p\n", this_fn, call_site);
285 }
286}
287#endif
288
289
290#if !defined(IGNORE_UNUSED_RESULT)
291#define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
292#endif
293
294
295#if defined(__GNUC__) || defined(__MINGW32__)
296
297/* GCC unused function attribute seems fundamentally broken.
298 * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
299 * OR UNUSED" for individual functions failed.
300 * Either the compiler creates an "unused-function" warning if a
301 * function is not marked with __attribute__((unused)).
302 * On the other hand, if the function is marked with this attribute,
303 * but is used, the compiler raises a completely idiotic
304 * "used-but-marked-unused" warning - and
305 * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
306 * raises error: unknown option after "#pragma GCC diagnostic".
307 * Disable this warning completely, until the GCC guys sober up
308 * again.
309 */
310
311#pragma GCC diagnostic ignored "-Wunused-function"
312
313#define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
314
315#else
316#define FUNCTION_MAY_BE_UNUSED
317#endif
318
319
320/* Some ANSI #includes are not available on Windows CE and Zephyr */
321#if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
322#include <errno.h>
323#include <fcntl.h>
324#include <signal.h>
325#include <stdlib.h>
326#include <sys/stat.h>
327#include <sys/types.h>
328#endif /* !_WIN32_WCE */
329
330
331#if defined(__clang__)
332/* When using -Weverything, clang does not accept it's own headers
333 * in a release build configuration. Disable what is too much in
334 * -Weverything. */
335#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
336#endif
337
338#if defined(__GNUC__) || defined(__MINGW32__)
339/* Who on earth came to the conclusion, using __DATE__ should rise
340 * an "expansion of date or time macro is not reproducible"
341 * warning. That's exactly what was intended by using this macro.
342 * Just disable this nonsense warning. */
343
344/* And disabling them does not work either:
345 * #pragma clang diagnostic ignored "-Wno-error=date-time"
346 * #pragma clang diagnostic ignored "-Wdate-time"
347 * So we just have to disable ALL warnings for some lines
348 * of code.
349 * This seems to be a known GCC bug, not resolved since 2012:
350 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
351 */
352#endif
353
354
355#if defined(__MACH__) /* Apple OSX section */
356
357#if defined(__clang__)
358#if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
359/* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
360#pragma clang diagnostic ignored "-Wno-reserved-id-macro"
361#pragma clang diagnostic ignored "-Wno-keyword-macro"
362#endif
363#endif
364
365#ifndef CLOCK_MONOTONIC
366#define CLOCK_MONOTONIC (1)
367#endif
368#ifndef CLOCK_REALTIME
369#define CLOCK_REALTIME (2)
370#endif
371
372#include <mach/clock.h>
373#include <mach/mach.h>
374#include <mach/mach_time.h>
375#include <sys/errno.h>
376#include <sys/time.h>
377
378/* clock_gettime is not implemented on OSX prior to 10.12 */
379static int
380_civet_clock_gettime(int clk_id, struct timespec *t)
381{
382 memset(t, 0, sizeof(*t));
383 if (clk_id == CLOCK_REALTIME) {
384 struct timeval now;
385 int rv = gettimeofday(&now, NULL);
386 if (rv) {
387 return rv;
388 }
389 t->tv_sec = now.tv_sec;
390 t->tv_nsec = now.tv_usec * 1000;
391 return 0;
392
393 } else if (clk_id == CLOCK_MONOTONIC) {
394 static uint64_t clock_start_time = 0;
395 static mach_timebase_info_data_t timebase_ifo = {0, 0};
396
397 uint64_t now = mach_absolute_time();
398
399 if (clock_start_time == 0) {
400 kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
401 DEBUG_ASSERT(mach_status == KERN_SUCCESS);
402
403 /* appease "unused variable" warning for release builds */
404 (void)mach_status;
405
406 clock_start_time = now;
407 }
408
409 now = (uint64_t)((double)(now - clock_start_time)
410 * (double)timebase_ifo.numer
411 / (double)timebase_ifo.denom);
412
413 t->tv_sec = now / 1000000000;
414 t->tv_nsec = now % 1000000000;
415 return 0;
416 }
417 return -1; /* EINVAL - Clock ID is unknown */
418}
419
420/* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
421#if defined(__CLOCK_AVAILABILITY)
422/* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
423 * declared but it may be NULL at runtime. So we need to check before using
424 * it. */
425static int
426_civet_safe_clock_gettime(int clk_id, struct timespec *t)
427{
428 if (clock_gettime) {
429 return clock_gettime(clk_id, t);
430 }
431 return _civet_clock_gettime(clk_id, t);
432}
433#define clock_gettime _civet_safe_clock_gettime
434#else
435#define clock_gettime _civet_clock_gettime
436#endif
437
438#endif
439
440
441#if !defined(_WIN32)
442/* Unix might return different error codes indicating to try again.
443 * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
444 * decades ago, but better check both and let the compile optimize it. */
445#define ERROR_TRY_AGAIN(err) \
446 (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
447#endif
448
449#if defined(USE_ZLIB)
450#include "zconf.h"
451#include "zlib.h"
452#endif
453
454
455/********************************************************************/
456/* CivetWeb configuration defines */
457/********************************************************************/
458
459/* Maximum number of threads that can be configured.
460 * The number of threads actually created depends on the "num_threads"
461 * configuration parameter, but this is the upper limit. */
462#if !defined(MAX_WORKER_THREADS)
463#define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
464#endif
465
466/* Timeout interval for select/poll calls.
467 * The timeouts depend on "*_timeout_ms" configuration values, but long
468 * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
469 * This reduces the time required to stop the server. */
470#if !defined(SOCKET_TIMEOUT_QUANTUM)
471#define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
472#endif
473
474/* Do not try to compress files smaller than this limit. */
475#if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
476#define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
477#endif
478
479#if !defined(PASSWORDS_FILE_NAME)
480#define PASSWORDS_FILE_NAME ".htpasswd"
481#endif
482
483/* Initial buffer size for all CGI environment variables. In case there is
484 * not enough space, another block is allocated. */
485#if !defined(CGI_ENVIRONMENT_SIZE)
486#define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
487#endif
488
489/* Maximum number of environment variables. */
490#if !defined(MAX_CGI_ENVIR_VARS)
491#define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
492#endif
493
494/* General purpose buffer size. */
495#if !defined(MG_BUF_LEN) /* in bytes */
496#define MG_BUF_LEN (1024 * 8)
497#endif
498
499
500/********************************************************************/
501
502/* Helper makros */
503#if !defined(ARRAY_SIZE)
504#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
505#endif
506
507#include <stdint.h>
508
509/* Standard defines */
510#if !defined(INT64_MAX)
511#define INT64_MAX (9223372036854775807)
512#endif
513
514#define SHUTDOWN_RD (0)
515#define SHUTDOWN_WR (1)
516#define SHUTDOWN_BOTH (2)
517
519 "worker threads must be a positive number");
520
521mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
522 "size_t data type size check");
523
524
525#if defined(_WIN32) /* WINDOWS include block */
526#include <malloc.h> /* *alloc( */
527#include <stdlib.h> /* *alloc( */
528#include <time.h> /* struct timespec */
529#include <windows.h>
530#include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
531#include <ws2tcpip.h>
532
533typedef const char *SOCK_OPT_TYPE;
534
535/* For a detailed description of these *_PATH_MAX defines, see
536 * https://github.com/civetweb/civetweb/issues/937. */
537
538/* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
539 * null termination, rounded up to the next 4 bytes boundary */
540#define UTF8_PATH_MAX (3 * 260)
541/* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
542 * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
543#define UTF16_PATH_MAX (260)
544
545#if !defined(_IN_PORT_T)
546#if !defined(in_port_t)
547#define in_port_t u_short
548#endif
549#endif
550
551#if defined(_WIN32_WCE)
552#error "WinCE support has ended"
553#endif
554
555#include <direct.h>
556#include <io.h>
557#include <process.h>
558
559
560#define MAKEUQUAD(lo, hi) \
561 ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
562#define RATE_DIFF (10000000) /* 100 nsecs */
563#define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
564#define SYS2UNIX_TIME(lo, hi) \
565 ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
566
567/* Visual Studio 6 does not know __func__ or __FUNCTION__
568 * The rest of MS compilers use __FUNCTION__, not C99 __func__
569 * Also use _strtoui64 on modern M$ compilers */
570#if defined(_MSC_VER)
571#if (_MSC_VER < 1300)
572#define STRX(x) #x
573#define STR(x) STRX(x)
574#define __func__ __FILE__ ":" STR(__LINE__)
575#define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
576#define strtoll(x, y, z) (_atoi64(x))
577#else
578#define __func__ __FUNCTION__
579#define strtoull(x, y, z) (_strtoui64(x, y, z))
580#define strtoll(x, y, z) (_strtoi64(x, y, z))
581#endif
582#endif /* _MSC_VER */
583
584#define ERRNO ((int)(GetLastError()))
585#define NO_SOCKLEN_T
586
587
588#if defined(_WIN64) || defined(__MINGW64__)
589#if !defined(SSL_LIB)
590
591#if defined(OPENSSL_API_3_0)
592#define SSL_LIB "libssl-3-x64.dll"
593#define CRYPTO_LIB "libcrypto-3-x64.dll"
594#endif
595
596#if defined(OPENSSL_API_1_1)
597#define SSL_LIB "libssl-1_1-x64.dll"
598#define CRYPTO_LIB "libcrypto-1_1-x64.dll"
599#endif /* OPENSSL_API_1_1 */
600
601#if defined(OPENSSL_API_1_0)
602#define SSL_LIB "ssleay64.dll"
603#define CRYPTO_LIB "libeay64.dll"
604#endif /* OPENSSL_API_1_0 */
605
606#endif
607#else /* defined(_WIN64) || defined(__MINGW64__) */
608#if !defined(SSL_LIB)
609
610#if defined(OPENSSL_API_3_0)
611#define SSL_LIB "libssl-3.dll"
612#define CRYPTO_LIB "libcrypto-3.dll"
613#endif
614
615#if defined(OPENSSL_API_1_1)
616#define SSL_LIB "libssl-1_1.dll"
617#define CRYPTO_LIB "libcrypto-1_1.dll"
618#endif /* OPENSSL_API_1_1 */
619
620#if defined(OPENSSL_API_1_0)
621#define SSL_LIB "ssleay32.dll"
622#define CRYPTO_LIB "libeay32.dll"
623#endif /* OPENSSL_API_1_0 */
624
625#endif /* SSL_LIB */
626#endif /* defined(_WIN64) || defined(__MINGW64__) */
627
628
629#define O_NONBLOCK (0)
630#if !defined(W_OK)
631#define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
632#endif
633#define _POSIX_
634#define INT64_FMT "I64d"
635#define UINT64_FMT "I64u"
636
637#define WINCDECL __cdecl
638#define vsnprintf_impl _vsnprintf
639#define access _access
640#define mg_sleep(x) (Sleep(x))
641
642#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
643#if !defined(popen)
644#define popen(x, y) (_popen(x, y))
645#endif
646#if !defined(pclose)
647#define pclose(x) (_pclose(x))
648#endif
649#define close(x) (_close(x))
650#define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
651#define RTLD_LAZY (0)
652#define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
653#define fdopen(x, y) (_fdopen((x), (y)))
654#define write(x, y, z) (_write((x), (y), (unsigned)z))
655#define read(x, y, z) (_read((x), (y), (unsigned)z))
656#define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
657#define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
658#define sleep(x) (Sleep((x)*1000))
659#define rmdir(x) (_rmdir(x))
660#if defined(_WIN64) || !defined(__MINGW32__)
661/* Only MinGW 32 bit is missing this function */
662#define timegm(x) (_mkgmtime(x))
663#else
664time_t timegm(struct tm *tm);
665#define NEED_TIMEGM
666#endif
667
668
669#if !defined(fileno)
670#define fileno(x) (_fileno(x))
671#endif /* !fileno MINGW #defines fileno */
672
673typedef struct {
674 CRITICAL_SECTION sec; /* Immovable */
675} pthread_mutex_t;
676typedef DWORD pthread_key_t;
677typedef HANDLE pthread_t;
678typedef struct {
679 pthread_mutex_t threadIdSec;
680 struct mg_workerTLS *waiting_thread; /* The chain of threads */
682
683#if !defined(__clockid_t_defined)
684typedef DWORD clockid_t;
685#endif
686#if !defined(CLOCK_MONOTONIC)
687#define CLOCK_MONOTONIC (1)
688#endif
689#if !defined(CLOCK_REALTIME)
690#define CLOCK_REALTIME (2)
691#endif
692#if !defined(CLOCK_THREAD)
693#define CLOCK_THREAD (3)
694#endif
695#if !defined(CLOCK_PROCESS)
696#define CLOCK_PROCESS (4)
697#endif
698
699
700#if defined(_MSC_VER) && (_MSC_VER >= 1900)
701#define _TIMESPEC_DEFINED
702#endif
703#if !defined(_TIMESPEC_DEFINED)
704struct timespec {
705 time_t tv_sec; /* seconds */
706 long tv_nsec; /* nanoseconds */
707};
708#endif
709
710#if !defined(WIN_PTHREADS_TIME_H)
711#define MUST_IMPLEMENT_CLOCK_GETTIME
712#endif
713
714#if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
715#define clock_gettime mg_clock_gettime
716static int
717clock_gettime(clockid_t clk_id, struct timespec *tp)
718{
719 FILETIME ft;
720 ULARGE_INTEGER li, li2;
721 BOOL ok = FALSE;
722 double d;
723 static double perfcnt_per_sec = 0.0;
724 static BOOL initialized = FALSE;
725
726 if (!initialized) {
727 QueryPerformanceFrequency((LARGE_INTEGER *)&li);
728 perfcnt_per_sec = 1.0 / li.QuadPart;
729 initialized = TRUE;
730 }
731
732 if (tp) {
733 memset(tp, 0, sizeof(*tp));
734
735 if (clk_id == CLOCK_REALTIME) {
736
737 /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
738 GetSystemTimeAsFileTime(&ft);
739 li.LowPart = ft.dwLowDateTime;
740 li.HighPart = ft.dwHighDateTime;
741 li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
742 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
743 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
744 ok = TRUE;
745 /* END: CLOCK_REALTIME */
746
747 } else if (clk_id == CLOCK_MONOTONIC) {
748
749 /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
750 QueryPerformanceCounter((LARGE_INTEGER *)&li);
751 d = li.QuadPart * perfcnt_per_sec;
752 tp->tv_sec = (time_t)d;
753 d -= (double)tp->tv_sec;
754 tp->tv_nsec = (long)(d * 1.0E9);
755 ok = TRUE;
756 /* END: CLOCK_MONOTONIC */
757
758 } else if (clk_id == CLOCK_THREAD) {
759
760 /* BEGIN: CLOCK_THREAD = CPU usage of thread */
761 FILETIME t_create, t_exit, t_kernel, t_user;
762 if (GetThreadTimes(GetCurrentThread(),
763 &t_create,
764 &t_exit,
765 &t_kernel,
766 &t_user)) {
767 li.LowPart = t_user.dwLowDateTime;
768 li.HighPart = t_user.dwHighDateTime;
769 li2.LowPart = t_kernel.dwLowDateTime;
770 li2.HighPart = t_kernel.dwHighDateTime;
771 li.QuadPart += li2.QuadPart;
772 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
773 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
774 ok = TRUE;
775 }
776 /* END: CLOCK_THREAD */
777
778 } else if (clk_id == CLOCK_PROCESS) {
779
780 /* BEGIN: CLOCK_PROCESS = CPU usage of process */
781 FILETIME t_create, t_exit, t_kernel, t_user;
782 if (GetProcessTimes(GetCurrentProcess(),
783 &t_create,
784 &t_exit,
785 &t_kernel,
786 &t_user)) {
787 li.LowPart = t_user.dwLowDateTime;
788 li.HighPart = t_user.dwHighDateTime;
789 li2.LowPart = t_kernel.dwLowDateTime;
790 li2.HighPart = t_kernel.dwHighDateTime;
791 li.QuadPart += li2.QuadPart;
792 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
793 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
794 ok = TRUE;
795 }
796 /* END: CLOCK_PROCESS */
797
798 } else {
799
800 /* BEGIN: unknown clock */
801 /* ok = FALSE; already set by init */
802 /* END: unknown clock */
803 }
804 }
805
806 return ok ? 0 : -1;
807}
808#endif
809
810
811#define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
812
813static int pthread_mutex_lock(pthread_mutex_t *);
814static int pthread_mutex_unlock(pthread_mutex_t *);
815static void path_to_unicode(const struct mg_connection *conn,
816 const char *path,
817 wchar_t *wbuf,
818 size_t wbuf_len);
819
820/* All file operations need to be rewritten to solve #246. */
821
822struct mg_file;
823
824static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
825
826
827/* POSIX dirent interface */
828struct dirent {
829 char d_name[UTF8_PATH_MAX];
830};
831
832typedef struct DIR {
833 HANDLE handle;
834 WIN32_FIND_DATAW info;
835 struct dirent result;
836} DIR;
837
838#if defined(HAVE_POLL)
839#define mg_pollfd pollfd
840#else
841struct mg_pollfd {
842 SOCKET fd;
843 short events;
844 short revents;
845};
846#endif
847
848/* Mark required libraries */
849#if defined(_MSC_VER)
850#pragma comment(lib, "Ws2_32.lib")
851#endif
852
853#else /* defined(_WIN32) - WINDOWS vs UNIX include block */
854
855#include <inttypes.h>
856
857/* Linux & co. internally use UTF8 */
858#define UTF8_PATH_MAX (PATH_MAX)
859
860typedef const void *SOCK_OPT_TYPE;
861
862#if defined(ANDROID)
863typedef unsigned short int in_port_t;
864#endif
865
866#if !defined(__ZEPHYR__)
867#include <arpa/inet.h>
868#include <ctype.h>
869#include <dirent.h>
870#include <grp.h>
871#include <limits.h>
872#include <netdb.h>
873#include <netinet/in.h>
874#include <netinet/tcp.h>
875#include <pthread.h>
876#include <pwd.h>
877#include <stdarg.h>
878#include <stddef.h>
879#include <stdio.h>
880#include <stdlib.h>
881#include <string.h>
882#include <sys/poll.h>
883#include <sys/socket.h>
884#include <sys/time.h>
885#include <sys/utsname.h>
886#include <sys/wait.h>
887#include <time.h>
888#include <unistd.h>
889#if defined(USE_X_DOM_SOCKET)
890#include <sys/un.h>
891#endif
892#endif
893
894#define vsnprintf_impl vsnprintf
895
896#if !defined(NO_SSL_DL) && !defined(NO_SSL)
897#include <dlfcn.h>
898#endif
899
900#if defined(__MACH__)
901#define SSL_LIB "libssl.dylib"
902#define CRYPTO_LIB "libcrypto.dylib"
903#else
904#if !defined(SSL_LIB)
905#define SSL_LIB "libssl.so"
906#endif
907#if !defined(CRYPTO_LIB)
908#define CRYPTO_LIB "libcrypto.so"
909#endif
910#endif
911#if !defined(O_BINARY)
912#define O_BINARY (0)
913#endif /* O_BINARY */
914#define closesocket(a) (close(a))
915#define mg_mkdir(conn, path, mode) (mkdir(path, mode))
916#define mg_remove(conn, x) (remove(x))
917#define mg_sleep(x) (usleep((x)*1000))
918#define mg_opendir(conn, x) (opendir(x))
919#define mg_closedir(x) (closedir(x))
920#define mg_readdir(x) (readdir(x))
921#define ERRNO (errno)
922#define INVALID_SOCKET (-1)
923#define INT64_FMT PRId64
924#define UINT64_FMT PRIu64
925typedef int SOCKET;
926#define WINCDECL
927
928#if defined(__hpux)
929/* HPUX 11 does not have monotonic, fall back to realtime */
930#if !defined(CLOCK_MONOTONIC)
931#define CLOCK_MONOTONIC CLOCK_REALTIME
932#endif
933
934/* HPUX defines socklen_t incorrectly as size_t which is 64bit on
935 * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
936 * the prototypes use int* rather than socklen_t* which matches the
937 * actual library expectation. When called with the wrong size arg
938 * accept() returns a zero client inet addr and check_acl() always
939 * fails. Since socklen_t is widely used below, just force replace
940 * their typedef with int. - DTL
941 */
942#define socklen_t int
943#endif /* hpux */
944
945#define mg_pollfd pollfd
946
947#endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
948
949/* In case our C library is missing "timegm", provide an implementation */
950#if defined(NEED_TIMEGM)
951static inline int
952is_leap(int y)
953{
954 return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
955}
956
957static inline int
958count_leap(int y)
959{
960 return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
961}
962
963time_t
964timegm(struct tm *tm)
965{
966 static const unsigned short ydays[] = {
967 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
968 int year = tm->tm_year + 1900;
969 int mon = tm->tm_mon;
970 int mday = tm->tm_mday - 1;
971 int hour = tm->tm_hour;
972 int min = tm->tm_min;
973 int sec = tm->tm_sec;
974
975 if (year < 1970 || mon < 0 || mon > 11 || mday < 0
976 || (mday >= ydays[mon + 1] - ydays[mon]
977 + (mon == 1 && is_leap(year) ? 1 : 0))
978 || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
979 return -1;
980
981 time_t res = year - 1970;
982 res *= 365;
983 res += mday;
984 res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
985 res += count_leap(year);
986
987 res *= 24;
988 res += hour;
989 res *= 60;
990 res += min;
991 res *= 60;
992 res += sec;
993 return res;
994}
995#endif /* NEED_TIMEGM */
996
997
998/* va_copy should always be a macro, C99 and C++11 - DTL */
999#if !defined(va_copy)
1000#define va_copy(x, y) ((x) = (y))
1001#endif
1002
1003
1004#if defined(_WIN32)
1005/* Create substitutes for POSIX functions in Win32. */
1006
1007#if defined(GCC_DIAGNOSTIC)
1008/* Show no warning in case system functions are not used. */
1009#pragma GCC diagnostic push
1010#pragma GCC diagnostic ignored "-Wunused-function"
1011#endif
1012
1013
1014static pthread_mutex_t global_log_file_lock;
1015
1017static DWORD
1018pthread_self(void)
1019{
1020 return GetCurrentThreadId();
1021}
1022
1023
1025static int
1026pthread_key_create(
1027 pthread_key_t *key,
1028 void (*_ignored)(void *) /* destructor not supported for Windows */
1029)
1030{
1031 (void)_ignored;
1032
1033 if ((key != 0)) {
1034 *key = TlsAlloc();
1035 return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
1036 }
1037 return -2;
1038}
1039
1040
1042static int
1043pthread_key_delete(pthread_key_t key)
1044{
1045 return TlsFree(key) ? 0 : 1;
1046}
1047
1048
1050static int
1051pthread_setspecific(pthread_key_t key, void *value)
1052{
1053 return TlsSetValue(key, value) ? 0 : 1;
1054}
1055
1056
1058static void *
1059pthread_getspecific(pthread_key_t key)
1060{
1061 return TlsGetValue(key);
1062}
1063
1064#if defined(GCC_DIAGNOSTIC)
1065/* Enable unused function warning again */
1066#pragma GCC diagnostic pop
1067#endif
1068
1069static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
1070#else
1071static pthread_mutexattr_t pthread_mutex_attr;
1072#endif /* _WIN32 */
1073
1074
1075#if defined(GCC_DIAGNOSTIC)
1076/* Show no warning in case system functions are not used. */
1077#pragma GCC diagnostic push
1078#pragma GCC diagnostic ignored "-Wunused-function"
1079#endif /* defined(GCC_DIAGNOSTIC) */
1080#if defined(__clang__)
1081/* Show no warning in case system functions are not used. */
1082#pragma clang diagnostic push
1083#pragma clang diagnostic ignored "-Wunused-function"
1084#endif
1085
1086static pthread_mutex_t global_lock_mutex;
1087
1088
1090static void
1092{
1093 (void)pthread_mutex_lock(&global_lock_mutex);
1094}
1095
1096
1098static void
1100{
1101 (void)pthread_mutex_unlock(&global_lock_mutex);
1102}
1103
1104
1105#if defined(_WIN64)
1106mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
1107#elif defined(_WIN32)
1108mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
1109#endif
1110
1111
1112/* Atomic functions working on ptrdiff_t ("signed size_t").
1113 * Operations: Increment, Decrement, Add, Maximum.
1114 * Up to size_t, they do not an atomic "load" operation.
1115 */
1117static ptrdiff_t
1118mg_atomic_inc(volatile ptrdiff_t *addr)
1119{
1120 ptrdiff_t ret;
1121
1122#if defined(_WIN64) && !defined(NO_ATOMICS)
1123 ret = InterlockedIncrement64(addr);
1124#elif defined(_WIN32) && !defined(NO_ATOMICS)
1125 ret = InterlockedIncrement(addr);
1126#elif defined(__GNUC__) \
1127 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1128 && !defined(NO_ATOMICS)
1129 ret = __sync_add_and_fetch(addr, 1);
1130#else
1132 ret = (++(*addr));
1134#endif
1135 return ret;
1136}
1137
1138
1140static ptrdiff_t
1141mg_atomic_dec(volatile ptrdiff_t *addr)
1142{
1143 ptrdiff_t ret;
1144
1145#if defined(_WIN64) && !defined(NO_ATOMICS)
1146 ret = InterlockedDecrement64(addr);
1147#elif defined(_WIN32) && !defined(NO_ATOMICS)
1148 ret = InterlockedDecrement(addr);
1149#elif defined(__GNUC__) \
1150 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1151 && !defined(NO_ATOMICS)
1152 ret = __sync_sub_and_fetch(addr, 1);
1153#else
1155 ret = (--(*addr));
1157#endif
1158 return ret;
1159}
1160
1161
1162#if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
1163static ptrdiff_t
1164mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
1165{
1166 ptrdiff_t ret;
1167
1168#if defined(_WIN64) && !defined(NO_ATOMICS)
1169 ret = InterlockedAdd64(addr, value);
1170#elif defined(_WIN32) && !defined(NO_ATOMICS)
1171 ret = InterlockedExchangeAdd(addr, value) + value;
1172#elif defined(__GNUC__) \
1173 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1174 && !defined(NO_ATOMICS)
1175 ret = __sync_add_and_fetch(addr, value);
1176#else
1178 *addr += value;
1179 ret = (*addr);
1181#endif
1182 return ret;
1183}
1184
1185
1187static ptrdiff_t
1188mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
1189 ptrdiff_t oldval,
1190 ptrdiff_t newval)
1191{
1192 ptrdiff_t ret;
1193
1194#if defined(_WIN64) && !defined(NO_ATOMICS)
1195 ret = InterlockedCompareExchange64(addr, newval, oldval);
1196#elif defined(_WIN32) && !defined(NO_ATOMICS)
1197 ret = InterlockedCompareExchange(addr, newval, oldval);
1198#elif defined(__GNUC__) \
1199 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1200 && !defined(NO_ATOMICS)
1201 ret = __sync_val_compare_and_swap(addr, oldval, newval);
1202#else
1204 ret = *addr;
1205 if ((ret != newval) && (ret == oldval)) {
1206 *addr = newval;
1207 }
1209#endif
1210 return ret;
1211}
1212
1213
1214static void
1215mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
1216{
1217 register ptrdiff_t tmp = *addr;
1218
1219#if defined(_WIN64) && !defined(NO_ATOMICS)
1220 while (tmp < value) {
1221 tmp = InterlockedCompareExchange64(addr, value, tmp);
1222 }
1223#elif defined(_WIN32) && !defined(NO_ATOMICS)
1224 while (tmp < value) {
1225 tmp = InterlockedCompareExchange(addr, value, tmp);
1226 }
1227#elif defined(__GNUC__) \
1228 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1229 && !defined(NO_ATOMICS)
1230 while (tmp < value) {
1231 tmp = __sync_val_compare_and_swap(addr, tmp, value);
1232 }
1233#else
1235 if (*addr < value) {
1236 *addr = value;
1237 }
1239#endif
1240}
1241
1242
1243static int64_t
1244mg_atomic_add64(volatile int64_t *addr, int64_t value)
1245{
1246 int64_t ret;
1247
1248#if defined(_WIN64) && !defined(NO_ATOMICS)
1249 ret = InterlockedAdd64(addr, value);
1250#elif defined(_WIN32) && !defined(NO_ATOMICS)
1251 ret = InterlockedExchangeAdd64(addr, value) + value;
1252#elif defined(__GNUC__) \
1253 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1254 && !defined(NO_ATOMICS)
1255 ret = __sync_add_and_fetch(addr, value);
1256#else
1258 *addr += value;
1259 ret = (*addr);
1261#endif
1262 return ret;
1263}
1264#endif
1265
1266
1267#if defined(GCC_DIAGNOSTIC)
1268/* Show no warning in case system functions are not used. */
1269#pragma GCC diagnostic pop
1270#endif /* defined(GCC_DIAGNOSTIC) */
1271#if defined(__clang__)
1272/* Show no warning in case system functions are not used. */
1273#pragma clang diagnostic pop
1274#endif
1275
1276
1277#if defined(USE_SERVER_STATS)
1278
1279struct mg_memory_stat {
1280 volatile ptrdiff_t totalMemUsed;
1281 volatile ptrdiff_t maxMemUsed;
1282 volatile ptrdiff_t blockCount;
1283};
1284
1285
1286static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
1287
1288
1289static void *
1290mg_malloc_ex(size_t size,
1291 struct mg_context *ctx,
1292 const char *file,
1293 unsigned line)
1294{
1295 void *data = malloc(size + 2 * sizeof(uintptr_t));
1296 void *memory = 0;
1297 struct mg_memory_stat *mstat = get_memory_stat(ctx);
1298
1299#if defined(MEMORY_DEBUGGING)
1300 char mallocStr[256];
1301#else
1302 (void)file;
1303 (void)line;
1304#endif
1305
1306 if (data) {
1307 ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
1308 mg_atomic_max(&mstat->maxMemUsed, mmem);
1309
1310 mg_atomic_inc(&mstat->blockCount);
1311 ((uintptr_t *)data)[0] = size;
1312 ((uintptr_t *)data)[1] = (uintptr_t)mstat;
1313 memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1314 }
1315
1316#if defined(MEMORY_DEBUGGING)
1317 sprintf(mallocStr,
1318 "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
1319 memory,
1320 (unsigned long)size,
1321 (unsigned long)mstat->totalMemUsed,
1322 (unsigned long)mstat->blockCount,
1323 file,
1324 line);
1325 DEBUG_TRACE("%s", mallocStr);
1326#endif
1327
1328 return memory;
1329}
1330
1331
1332static void *
1333mg_calloc_ex(size_t count,
1334 size_t size,
1335 struct mg_context *ctx,
1336 const char *file,
1337 unsigned line)
1338{
1339 void *data = mg_malloc_ex(size * count, ctx, file, line);
1340
1341 if (data) {
1342 memset(data, 0, size * count);
1343 }
1344 return data;
1345}
1346
1347
1348static void
1349mg_free_ex(void *memory, const char *file, unsigned line)
1350{
1351#if defined(MEMORY_DEBUGGING)
1352 char mallocStr[256];
1353#else
1354 (void)file;
1355 (void)line;
1356#endif
1357
1358 if (memory) {
1359 void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1360 uintptr_t size = ((uintptr_t *)data)[0];
1361 struct mg_memory_stat *mstat =
1362 (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
1363 mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
1364 mg_atomic_dec(&mstat->blockCount);
1365
1366#if defined(MEMORY_DEBUGGING)
1367 sprintf(mallocStr,
1368 "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
1369 memory,
1370 (unsigned long)size,
1371 (unsigned long)mstat->totalMemUsed,
1372 (unsigned long)mstat->blockCount,
1373 file,
1374 line);
1375 DEBUG_TRACE("%s", mallocStr);
1376#endif
1377 free(data);
1378 }
1379}
1380
1381
1382static void *
1383mg_realloc_ex(void *memory,
1384 size_t newsize,
1385 struct mg_context *ctx,
1386 const char *file,
1387 unsigned line)
1388{
1389 void *data;
1390 void *_realloc;
1391 uintptr_t oldsize;
1392
1393#if defined(MEMORY_DEBUGGING)
1394 char mallocStr[256];
1395#else
1396 (void)file;
1397 (void)line;
1398#endif
1399
1400 if (newsize) {
1401 if (memory) {
1402 /* Reallocate existing block */
1403 struct mg_memory_stat *mstat;
1404 data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1405 oldsize = ((uintptr_t *)data)[0];
1406 mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
1407 _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
1408 if (_realloc) {
1409 data = _realloc;
1410 mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
1411#if defined(MEMORY_DEBUGGING)
1412 sprintf(mallocStr,
1413 "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
1414 memory,
1415 (unsigned long)oldsize,
1416 (unsigned long)mstat->totalMemUsed,
1417 (unsigned long)mstat->blockCount,
1418 file,
1419 line);
1420 DEBUG_TRACE("%s", mallocStr);
1421#endif
1422 mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
1423
1424#if defined(MEMORY_DEBUGGING)
1425 sprintf(mallocStr,
1426 "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
1427 memory,
1428 (unsigned long)newsize,
1429 (unsigned long)mstat->totalMemUsed,
1430 (unsigned long)mstat->blockCount,
1431 file,
1432 line);
1433 DEBUG_TRACE("%s", mallocStr);
1434#endif
1435 *(uintptr_t *)data = newsize;
1436 data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1437 } else {
1438#if defined(MEMORY_DEBUGGING)
1439 DEBUG_TRACE("%s", "MEM: realloc failed\n");
1440#endif
1441 return _realloc;
1442 }
1443 } else {
1444 /* Allocate new block */
1445 data = mg_malloc_ex(newsize, ctx, file, line);
1446 }
1447 } else {
1448 /* Free existing block */
1449 data = 0;
1450 mg_free_ex(memory, file, line);
1451 }
1452
1453 return data;
1454}
1455
1456
1457#define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
1458#define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
1459#define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
1460#define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
1461
1462#define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
1463#define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
1464#define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
1465
1466
1467#else /* USE_SERVER_STATS */
1468
1469
1470static __inline void *
1472{
1473 return malloc(a);
1474}
1475
1476static __inline void *
1477mg_calloc(size_t a, size_t b)
1478{
1479 return calloc(a, b);
1480}
1481
1482static __inline void *
1483mg_realloc(void *a, size_t b)
1484{
1485 return realloc(a, b);
1486}
1487
1488static __inline void
1490{
1491 free(a);
1492}
1493
1494#define mg_malloc_ctx(a, c) mg_malloc(a)
1495#define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
1496#define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
1497#define mg_free_ctx(a, c) mg_free(a)
1498
1499#endif /* USE_SERVER_STATS */
1500
1501
1502static void mg_vsnprintf(const struct mg_connection *conn,
1503 int *truncated,
1504 char *buf,
1505 size_t buflen,
1506 const char *fmt,
1507 va_list ap);
1508
1509static void mg_snprintf(const struct mg_connection *conn,
1510 int *truncated,
1511 char *buf,
1512 size_t buflen,
1513 PRINTF_FORMAT_STRING(const char *fmt),
1514 ...) PRINTF_ARGS(5, 6);
1515
1516/* This following lines are just meant as a reminder to use the mg-functions
1517 * for memory management */
1518#if defined(malloc)
1519#undef malloc
1520#endif
1521#if defined(calloc)
1522#undef calloc
1523#endif
1524#if defined(realloc)
1525#undef realloc
1526#endif
1527#if defined(free)
1528#undef free
1529#endif
1530#if defined(snprintf)
1531#undef snprintf
1532#endif
1533#if defined(vsnprintf)
1534#undef vsnprintf
1535#endif
1536#define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
1537#define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
1538#define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
1539#define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
1540#define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
1541#if defined(_WIN32)
1542/* vsnprintf must not be used in any system,
1543 * but this define only works well for Windows. */
1544#define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
1545#endif
1546
1547
1548/* mg_init_library counter */
1550
1551#if !defined(NO_SSL)
1552#if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
1553 || defined(OPENSSL_API_3_0)
1554static int mg_openssl_initialized = 0;
1555#endif
1556#if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
1557 && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
1558#error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
1559#endif
1560#if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
1561 && defined(OPENSSL_API_3_0)
1562#error "Multiple OPENSSL_API versions defined"
1563#endif
1564#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
1565 || defined(OPENSSL_API_3_0)) \
1566 && defined(USE_MBEDTLS)
1567#error "Multiple SSL libraries defined"
1568#endif
1569#endif
1570
1571
1572static pthread_key_t sTlsKey; /* Thread local storage index */
1573static volatile ptrdiff_t thread_idx_max = 0;
1574
1575#if defined(MG_LEGACY_INTERFACE)
1576#define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
1577#endif
1578
1581 unsigned long thread_idx;
1583#if defined(_WIN32)
1584 HANDLE pthread_cond_helper_mutex;
1585 struct mg_workerTLS *next_waiting_thread;
1586#endif
1587 const char *alpn_proto;
1588#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
1589 char txtbuf[4];
1590#endif
1591};
1592
1593
1594#if defined(GCC_DIAGNOSTIC)
1595/* Show no warning in case system functions are not used. */
1596#pragma GCC diagnostic push
1597#pragma GCC diagnostic ignored "-Wunused-function"
1598#endif /* defined(GCC_DIAGNOSTIC) */
1599#if defined(__clang__)
1600/* Show no warning in case system functions are not used. */
1601#pragma clang diagnostic push
1602#pragma clang diagnostic ignored "-Wunused-function"
1603#endif
1604
1605
1606/* Get a unique thread ID as unsigned long, independent from the data type
1607 * of thread IDs defined by the operating system API.
1608 * If two calls to mg_current_thread_id return the same value, they calls
1609 * are done from the same thread. If they return different values, they are
1610 * done from different threads. (Provided this function is used in the same
1611 * process context and threads are not repeatedly created and deleted, but
1612 * CivetWeb does not do that).
1613 * This function must match the signature required for SSL id callbacks:
1614 * CRYPTO_set_id_callback
1615 */
1617static unsigned long
1619{
1620#if defined(_WIN32)
1621 return GetCurrentThreadId();
1622#else
1623
1624#if defined(__clang__)
1625#pragma clang diagnostic push
1626#pragma clang diagnostic ignored "-Wunreachable-code"
1627 /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
1628 * or not, so one of the two conditions will be unreachable by construction.
1629 * Unfortunately the C standard does not define a way to check this at
1630 * compile time, since the #if preprocessor conditions can not use the
1631 * sizeof operator as an argument. */
1632#endif
1633
1634 if (sizeof(pthread_t) > sizeof(unsigned long)) {
1635 /* This is the problematic case for CRYPTO_set_id_callback:
1636 * The OS pthread_t can not be cast to unsigned long. */
1637 struct mg_workerTLS *tls =
1638 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
1639 if (tls == NULL) {
1640 /* SSL called from an unknown thread: Create some thread index.
1641 */
1642 tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
1643 tls->is_master = -2; /* -2 means "3rd party thread" */
1644 tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
1645 pthread_setspecific(sTlsKey, tls);
1646 }
1647 return tls->thread_idx;
1648 } else {
1649 /* pthread_t may be any data type, so a simple cast to unsigned long
1650 * can rise a warning/error, depending on the platform.
1651 * Here memcpy is used as an anything-to-anything cast. */
1652 unsigned long ret = 0;
1653 pthread_t t = pthread_self();
1654 memcpy(&ret, &t, sizeof(pthread_t));
1655 return ret;
1656 }
1657
1658#if defined(__clang__)
1659#pragma clang diagnostic pop
1660#endif
1661
1662#endif
1663}
1664
1665
1667static uint64_t
1669{
1670 struct timespec tsnow;
1671 clock_gettime(CLOCK_REALTIME, &tsnow);
1672 return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
1673}
1674
1675
1676#if defined(GCC_DIAGNOSTIC)
1677/* Show no warning in case system functions are not used. */
1678#pragma GCC diagnostic pop
1679#endif /* defined(GCC_DIAGNOSTIC) */
1680#if defined(__clang__)
1681/* Show no warning in case system functions are not used. */
1682#pragma clang diagnostic pop
1683#endif
1684
1685
1686#if defined(NEED_DEBUG_TRACE_FUNC)
1687static void
1688DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
1689{
1690 va_list args;
1691 struct timespec tsnow;
1692
1693 /* Get some operating system independent thread id */
1694 unsigned long thread_id = mg_current_thread_id();
1695
1696 clock_gettime(CLOCK_REALTIME, &tsnow);
1697
1698 flockfile(DEBUG_TRACE_STREAM);
1699 fprintf(DEBUG_TRACE_STREAM,
1700 "*** %lu.%09lu %lu %s:%u: ",
1701 (unsigned long)tsnow.tv_sec,
1702 (unsigned long)tsnow.tv_nsec,
1703 thread_id,
1704 func,
1705 line);
1706 va_start(args, fmt);
1707 vfprintf(DEBUG_TRACE_STREAM, fmt, args);
1708 va_end(args);
1709 putc('\n', DEBUG_TRACE_STREAM);
1710 fflush(DEBUG_TRACE_STREAM);
1711 funlockfile(DEBUG_TRACE_STREAM);
1712}
1713#endif /* NEED_DEBUG_TRACE_FUNC */
1714
1715
1716#define MD5_STATIC static
1717#include "md5.inl"
1718
1719/* Darwin prior to 7.0 and Win32 do not have socklen_t */
1720#if defined(NO_SOCKLEN_T)
1721typedef int socklen_t;
1722#endif /* NO_SOCKLEN_T */
1723
1724#define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
1725
1726#if !defined(MSG_NOSIGNAL)
1727#define MSG_NOSIGNAL (0)
1728#endif
1729
1730
1731/* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
1732#if defined(USE_MBEDTLS)
1733/* mbedTLS */
1734#include "mod_mbedtls.inl"
1735
1736#elif defined(NO_SSL)
1737/* no SSL */
1738typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
1739typedef struct SSL_CTX SSL_CTX;
1740
1741#elif defined(NO_SSL_DL)
1742/* OpenSSL without dynamic loading */
1743#include <openssl/bn.h>
1744#include <openssl/conf.h>
1745#include <openssl/crypto.h>
1746#include <openssl/dh.h>
1747#include <openssl/engine.h>
1748#include <openssl/err.h>
1749#include <openssl/opensslv.h>
1750#include <openssl/pem.h>
1751#include <openssl/ssl.h>
1752#include <openssl/tls1.h>
1753#include <openssl/x509.h>
1754
1755#if defined(WOLFSSL_VERSION)
1756/* Additional defines for WolfSSL, see
1757 * https://github.com/civetweb/civetweb/issues/583 */
1758#include "wolfssl_extras.inl"
1759#endif
1760
1761#if defined(OPENSSL_IS_BORINGSSL)
1762/* From boringssl/src/include/openssl/mem.h:
1763 *
1764 * OpenSSL has, historically, had a complex set of malloc debugging options.
1765 * However, that was written in a time before Valgrind and ASAN. Since we now
1766 * have those tools, the OpenSSL allocation functions are simply macros around
1767 * the standard memory functions.
1768 *
1769 * #define OPENSSL_free free */
1770#define free free
1771// disable for boringssl
1772#define CONF_modules_unload(a) ((void)0)
1773#define ENGINE_cleanup() ((void)0)
1774#endif
1775
1776/* If OpenSSL headers are included, automatically select the API version */
1777#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
1778#if !defined(OPENSSL_API_3_0)
1779#define OPENSSL_API_3_0
1780#endif
1781#define OPENSSL_REMOVE_THREAD_STATE()
1782#else
1783#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1784#if !defined(OPENSSL_API_1_1)
1785#define OPENSSL_API_1_1
1786#endif
1787#define OPENSSL_REMOVE_THREAD_STATE()
1788#else
1789#if !defined(OPENSSL_API_1_0)
1790#define OPENSSL_API_1_0
1791#endif
1792#define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
1793#endif
1794#endif
1795
1796
1797#else
1798/* SSL loaded dynamically from DLL / shared object */
1799/* Add all prototypes here, to be independent from OpenSSL source
1800 * installation. */
1801#include "openssl_dl.inl"
1802
1803#endif /* Various SSL bindings */
1804
1805
1806#if !defined(NO_CACHING)
1807static const char month_names[][4] = {"Jan",
1808 "Feb",
1809 "Mar",
1810 "Apr",
1811 "May",
1812 "Jun",
1813 "Jul",
1814 "Aug",
1815 "Sep",
1816 "Oct",
1817 "Nov",
1818 "Dec"};
1819#endif /* !NO_CACHING */
1820
1821
1822/* Unified socket address. For IPv6 support, add IPv6 address structure in
1823 * the union u. */
1824union usa {
1825 struct sockaddr sa;
1826 struct sockaddr_in sin;
1827#if defined(USE_IPV6)
1828 struct sockaddr_in6 sin6;
1829#endif
1830#if defined(USE_X_DOM_SOCKET)
1831 struct sockaddr_un sun;
1832#endif
1833};
1834
1835#if defined(USE_X_DOM_SOCKET)
1836static unsigned short
1837USA_IN_PORT_UNSAFE(union usa *s)
1838{
1839 if (s->sa.sa_family == AF_INET)
1840 return s->sin.sin_port;
1841#if defined(USE_IPV6)
1842 if (s->sa.sa_family == AF_INET6)
1843 return s->sin6.sin6_port;
1844#endif
1845 return 0;
1846}
1847#endif
1848#if defined(USE_IPV6)
1849#define USA_IN_PORT_UNSAFE(s) \
1850 (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
1851#else
1852#define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
1853#endif
1854
1855/* Describes a string (chunk of memory). */
1856struct vec {
1857 const char *ptr;
1858 size_t len;
1859};
1860
1862 /* File properties filled by mg_stat: */
1863 uint64_t size;
1865 int is_directory; /* Set to 1 if mg_stat is called for a directory */
1866 int is_gzipped; /* Set to 1 if the content is gzipped, in which
1867 * case we need a "Content-Eencoding: gzip" header */
1868 int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
1869};
1870
1871
1873 /* File properties filled by mg_fopen: */
1874 FILE *fp;
1875};
1876
1877struct mg_file {
1880};
1881
1882
1883#define STRUCT_FILE_INITIALIZER \
1884 { \
1885 {(uint64_t)0, (time_t)0, 0, 0, 0}, \
1886 { \
1887 (FILE *)NULL \
1888 } \
1889 }
1890
1891
1892/* Describes listening socket, or socket which was accept()-ed by the master
1893 * thread and queued for future handling by the worker thread. */
1894struct socket {
1895 SOCKET sock; /* Listening socket */
1896 union usa lsa; /* Local socket address */
1897 union usa rsa; /* Remote socket address */
1898 unsigned char is_ssl; /* Is port SSL-ed */
1899 unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
1900 * port */
1901 unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
1902};
1903
1904
1905/* Enum const for all options must be in sync with
1906 * static struct mg_option config_options[]
1907 * This is tested in the unit test (test/private.c)
1908 * "Private Config Options"
1909 */
1910enum {
1911 /* Once for each server */
1915 CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
1916 * socket option typedef TCP_NODELAY. */
1921#if defined(__linux__)
1922 ALLOW_SENDFILE_CALL,
1923#endif
1924#if defined(_WIN32)
1925 CASE_SENSITIVE_FILES,
1926#endif
1931#if defined(USE_WEBSOCKET)
1932 WEBSOCKET_TIMEOUT,
1933 ENABLE_WEBSOCKET_PING_PONG,
1934#endif
1937#if defined(USE_LUA)
1938 LUA_BACKGROUND_SCRIPT,
1939 LUA_BACKGROUND_SCRIPT_PARAMS,
1940#endif
1941#if defined(USE_HTTP2)
1942 ENABLE_HTTP2,
1943#endif
1944
1945 /* Once for each domain */
1947
1950
1955#if defined(USE_TIMERS)
1956 CGI_TIMEOUT,
1957#endif
1958
1963#if defined(USE_TIMERS)
1964 CGI2_TIMEOUT,
1965#endif
1966
1967#if defined(USE_4_CGI)
1968 CGI3_EXTENSIONS,
1969 CGI3_ENVIRONMENT,
1970 CGI3_INTERPRETER,
1971 CGI3_INTERPRETER_ARGS,
1972#if defined(USE_TIMERS)
1973 CGI3_TIMEOUT,
1974#endif
1975
1976 CGI4_EXTENSIONS,
1977 CGI4_ENVIRONMENT,
1978 CGI4_INTERPRETER,
1979 CGI4_INTERPRETER_ARGS,
1980#if defined(USE_TIMERS)
1981 CGI4_TIMEOUT,
1982#endif
1983#endif
1984
1985 PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
2008
2009#if defined(USE_LUA)
2010 LUA_PRELOAD_FILE,
2011 LUA_SCRIPT_EXTENSIONS,
2012 LUA_SERVER_PAGE_EXTENSIONS,
2013#if defined(MG_EXPERIMENTAL_INTERFACES)
2014 LUA_DEBUG_PARAMS,
2015#endif
2016#endif
2017#if defined(USE_DUKTAPE)
2018 DUKTAPE_SCRIPT_EXTENSIONS,
2019#endif
2020
2021#if defined(USE_WEBSOCKET)
2022 WEBSOCKET_ROOT,
2023#endif
2024#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2025 LUA_WEBSOCKET_EXTENSIONS,
2026#endif
2027
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 {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
2186#if !defined(NO_CACHING)
2187 {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
2188 {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
2189#endif
2190#if !defined(NO_SSL)
2191 {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
2192#endif
2193 {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
2194 {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
2195
2196 {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
2197
2198
2199/* Check if the config_options and the corresponding enum have compatible
2200 * sizes. */
2201mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
2202 == (NUM_OPTIONS + 1),
2203 "config_options and enum not sync");
2204
2205
2207
2208
2210 /* Name/Pattern of the URI. */
2211 char *uri;
2212 size_t uri_len;
2213
2214 /* handler type */
2216
2217 /* Handler for http/https or authorization requests. */
2219 unsigned int refcount;
2221
2222 /* Handler for ws/wss (websocket) requests. */
2227
2228 /* accepted subprotocols for ws/wss requests. */
2230
2231 /* Handler for authorization requests */
2233
2234 /* User supplied argument for the handler function. */
2235 void *cbdata;
2236
2237 /* next handler in a linked list */
2239};
2240
2241
2242enum {
2248
2249
2251 SSL_CTX *ssl_ctx; /* SSL context */
2252 char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
2253 struct mg_handler_info *handlers; /* linked list of uri handlers */
2255
2256 /* Server nonce */
2257 uint64_t auth_nonce_mask; /* Mask for all nonce values */
2258 unsigned long nonce_count; /* Used nonces, used for authentication */
2259
2260#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2261 /* linked list of shared lua websockets */
2262 struct mg_shared_lua_websocket_list *shared_lua_websockets;
2263#endif
2264
2265 /* Linked list of domains */
2267};
2268
2269
2270/* Stop flag can be "volatile" or require a lock.
2271 * MSDN uses volatile for "Interlocked" operations, but also explicitly
2272 * states a read operation for int is always atomic. */
2273#if defined(STOP_FLAG_NEEDS_LOCK)
2274
2275typedef ptrdiff_t volatile stop_flag_t;
2276
2277static int
2279{
2280 stop_flag_t sf = mg_atomic_add(f, 0);
2281 return (sf == 0);
2282}
2283
2284static int
2286{
2287 stop_flag_t sf = mg_atomic_add(f, 0);
2288 return (sf == 2);
2289}
2290
2291static void
2293{
2294 stop_flag_t sf;
2295 do {
2296 sf = mg_atomic_compare_and_swap(f, *f, v);
2297 } while (sf != v);
2298}
2299
2300#else /* STOP_FLAG_NEEDS_LOCK */
2301
2302typedef int volatile stop_flag_t;
2303#define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
2304#define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
2305#define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
2306
2307#endif /* STOP_FLAG_NEEDS_LOCK */
2308
2309
2311
2312 /* Part 1 - Physical context:
2313 * This holds threads, ports, timeouts, ...
2314 * set for the entire server, independent from the
2315 * addressed hostname.
2316 */
2317
2318 /* Connection related */
2319 int context_type; /* See CONTEXT_* above */
2320
2324
2325 struct mg_connection *worker_connections; /* The connection struct, pre-
2326 * allocated for each worker */
2327
2328#if defined(USE_SERVER_STATS)
2329 volatile ptrdiff_t active_connections;
2330 volatile ptrdiff_t max_active_connections;
2331 volatile ptrdiff_t total_connections;
2332 volatile ptrdiff_t total_requests;
2333 volatile int64_t total_data_read;
2334 volatile int64_t total_data_written;
2335#endif
2336
2337 /* Thread related */
2338 stop_flag_t stop_flag; /* Should we stop event loop */
2339 pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
2340
2341 pthread_t masterthreadid; /* The master thread ID */
2342 unsigned int
2343 cfg_worker_threads; /* The number of configured worker threads. */
2344 pthread_t *worker_threadids; /* The worker thread IDs */
2345 unsigned long starter_thread_idx; /* thread index which called mg_start */
2346
2347 /* Connection to thread dispatching */
2348#if defined(ALTERNATIVE_QUEUE)
2349 struct socket *client_socks;
2350 void **client_wait_events;
2351#else
2352 struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
2353 worker thread */
2354 volatile int sq_head; /* Head of the socket queue */
2355 volatile int sq_tail; /* Tail of the socket queue */
2356 pthread_cond_t sq_full; /* Signaled when socket is produced */
2357 pthread_cond_t sq_empty; /* Signaled when socket is consumed */
2358 volatile int sq_blocked; /* Status information: sq is full */
2359 int sq_size; /* No of elements in socket queue */
2360#if defined(USE_SERVER_STATS)
2361 int sq_max_fill;
2362#endif /* USE_SERVER_STATS */
2363#endif /* ALTERNATIVE_QUEUE */
2364
2365 /* Memory related */
2366 unsigned int max_request_size; /* The max request size */
2367
2368#if defined(USE_SERVER_STATS)
2369 struct mg_memory_stat ctx_memory;
2370#endif
2371
2372 /* Operating system related */
2373 char *systemName; /* What operating system is running */
2374 time_t start_time; /* Server start time, used for authentication
2375 * and for diagnstics. */
2376
2377#if defined(USE_TIMERS)
2378 struct ttimers *timers;
2379#endif
2380
2381 /* Lua specific: Background operations and shared websockets */
2382#if defined(USE_LUA)
2383 void *lua_background_state; /* lua_State (here as void *) */
2384 pthread_mutex_t lua_bg_mutex; /* Protect background state */
2385 int lua_bg_log_available; /* Use Lua background state for access log */
2386#endif
2387
2388 /* Server nonce */
2389 pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
2390 * ssl_cert_last_mtime, nonce_count, and
2391 * next (linked list) */
2392
2393 /* Server callbacks */
2394 struct mg_callbacks callbacks; /* User-defined callback function */
2395 void *user_data; /* User-defined data */
2396
2397 /* Part 2 - Logical domain:
2398 * This holds hostname, TLS certificate, document root, ...
2399 * set for a domain hosted at the server.
2400 * There may be multiple domains hosted at one physical server.
2401 * The default domain "dd" is the first element of a list of
2402 * domains.
2403 */
2404 struct mg_domain_context dd; /* default domain */
2405};
2406
2407
2408#if defined(USE_SERVER_STATS)
2409static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2410
2411static struct mg_memory_stat *
2412get_memory_stat(struct mg_context *ctx)
2413{
2414 if (ctx) {
2415 return &(ctx->ctx_memory);
2416 }
2417 return &mg_common_memory;
2418}
2419#endif
2420
2421enum {
2426
2427enum {
2432
2433
2434#if defined(USE_HTTP2)
2435#if !defined(HTTP2_DYN_TABLE_SIZE)
2436#define HTTP2_DYN_TABLE_SIZE (256)
2437#endif
2438
2439struct mg_http2_connection {
2440 uint32_t stream_id;
2441 uint32_t dyn_table_size;
2442 struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
2443};
2444#endif
2445
2446
2448 int connection_type; /* see CONNECTION_TYPE_* above */
2449 int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
2450 int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
2451 fully sent */
2452#if defined(USE_HTTP2)
2453 struct mg_http2_connection http2;
2454#endif
2455
2458
2461
2462#if defined(USE_SERVER_STATS)
2463 int conn_state; /* 0 = undef, numerical value may change in different
2464 * versions. For the current definition, see
2465 * mg_get_connection_info_impl */
2466#endif
2467
2468 SSL *ssl; /* SSL descriptor */
2469 struct socket client; /* Connected client */
2470 time_t conn_birth_time; /* Time (wall clock) when connection was
2471 * established */
2472#if defined(USE_SERVER_STATS)
2473 time_t conn_close_time; /* Time (wall clock) when connection was
2474 * closed (or 0 if still open) */
2475 double processing_time; /* Procesing time for one request. */
2476#endif
2477 struct timespec req_time; /* Time (since system start) when the request
2478 * was received */
2479 int64_t num_bytes_sent; /* Total bytes sent to client */
2480 int64_t content_len; /* How many bytes of content can be read
2481 * !is_chunked: Content-Length header value
2482 * or -1 (until connection closed,
2483 * not allowed for a request)
2484 * is_chunked: >= 0, appended gradually
2485 */
2486 int64_t consumed_content; /* How many bytes of content have been read */
2487 int is_chunked; /* Transfer-Encoding is chunked:
2488 * 0 = not chunked,
2489 * 1 = chunked, not yet, or some data read,
2490 * 2 = chunked, has error,
2491 * 3 = chunked, all data read except trailer,
2492 * 4 = chunked, all data read
2493 */
2494 char *buf; /* Buffer for received data */
2495 char *path_info; /* PATH_INFO part of the URL */
2496
2497 int must_close; /* 1 if connection must be closed */
2498 int accept_gzip; /* 1 if gzip encoding is accepted */
2499 int in_error_handler; /* 1 if in handler for user defined error
2500 * pages */
2501#if defined(USE_WEBSOCKET)
2502 int in_websocket_handling; /* 1 if in read_websocket */
2503#endif
2504#if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
2505 && defined(MG_EXPERIMENTAL_INTERFACES)
2506 /* Parameters for websocket data compression according to rfc7692 */
2507 int websocket_deflate_server_max_windows_bits;
2508 int websocket_deflate_client_max_windows_bits;
2509 int websocket_deflate_server_no_context_takeover;
2510 int websocket_deflate_client_no_context_takeover;
2511 int websocket_deflate_initialized;
2512 int websocket_deflate_flush;
2513 z_stream websocket_deflate_state;
2514 z_stream websocket_inflate_state;
2515#endif
2516 int handled_requests; /* Number of requests handled by this connection
2517 */
2518 int buf_size; /* Buffer size */
2519 int request_len; /* Size of the request + headers in a buffer */
2520 int data_len; /* Total size of data in a buffer */
2521 int status_code; /* HTTP reply status code, e.g. 200 */
2522 int throttle; /* Throttling, bytes/sec. <= 0 means no
2523 * throttle */
2524
2525 time_t last_throttle_time; /* Last time throttled data was sent */
2526 int last_throttle_bytes; /* Bytes sent this second */
2527 pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
2528 * atomic transmissions for websockets */
2529#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2530 void *lua_websocket_state; /* Lua_State for a websocket connection */
2531#endif
2532
2533 void *tls_user_ptr; /* User defined pointer in thread local storage,
2534 * for quick access */
2535};
2536
2537
2538/* Directory entry */
2539struct de {
2543};
2544
2545
2546#define mg_cry_internal(conn, fmt, ...) \
2547 mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
2548
2549#define mg_cry_ctx_internal(ctx, fmt, ...) \
2550 mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
2551
2552static void mg_cry_internal_wrap(const struct mg_connection *conn,
2553 struct mg_context *ctx,
2554 const char *func,
2555 unsigned line,
2556 const char *fmt,
2557 ...) PRINTF_ARGS(5, 6);
2558
2559
2560#if !defined(NO_THREAD_NAME)
2561#if defined(_WIN32) && defined(_MSC_VER)
2562/* Set the thread name for debugging purposes in Visual Studio
2563 * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
2564 */
2565#pragma pack(push, 8)
2566typedef struct tagTHREADNAME_INFO {
2567 DWORD dwType; /* Must be 0x1000. */
2568 LPCSTR szName; /* Pointer to name (in user addr space). */
2569 DWORD dwThreadID; /* Thread ID (-1=caller thread). */
2570 DWORD dwFlags; /* Reserved for future use, must be zero. */
2571} THREADNAME_INFO;
2572#pragma pack(pop)
2573
2574#elif defined(__linux__)
2575
2576#include <sys/prctl.h>
2577#include <sys/sendfile.h>
2578#if defined(ALTERNATIVE_QUEUE)
2579#include <sys/eventfd.h>
2580#endif /* ALTERNATIVE_QUEUE */
2581
2582
2583#if defined(ALTERNATIVE_QUEUE)
2584
2585static void *
2586event_create(void)
2587{
2588 int evhdl = eventfd(0, EFD_CLOEXEC);
2589 int *ret;
2590
2591 if (evhdl == -1) {
2592 /* Linux uses -1 on error, Windows NULL. */
2593 /* However, Linux does not return 0 on success either. */
2594 return 0;
2595 }
2596
2597 ret = (int *)mg_malloc(sizeof(int));
2598 if (ret) {
2599 *ret = evhdl;
2600 } else {
2601 (void)close(evhdl);
2602 }
2603
2604 return (void *)ret;
2605}
2606
2607
2608static int
2609event_wait(void *eventhdl)
2610{
2611 uint64_t u;
2612 int evhdl, s;
2613
2614 if (!eventhdl) {
2615 /* error */
2616 return 0;
2617 }
2618 evhdl = *(int *)eventhdl;
2619
2620 s = (int)read(evhdl, &u, sizeof(u));
2621 if (s != sizeof(u)) {
2622 /* error */
2623 return 0;
2624 }
2625 (void)u; /* the value is not required */
2626 return 1;
2627}
2628
2629
2630static int
2631event_signal(void *eventhdl)
2632{
2633 uint64_t u = 1;
2634 int evhdl, s;
2635
2636 if (!eventhdl) {
2637 /* error */
2638 return 0;
2639 }
2640 evhdl = *(int *)eventhdl;
2641
2642 s = (int)write(evhdl, &u, sizeof(u));
2643 if (s != sizeof(u)) {
2644 /* error */
2645 return 0;
2646 }
2647 return 1;
2648}
2649
2650
2651static void
2652event_destroy(void *eventhdl)
2653{
2654 int evhdl;
2655
2656 if (!eventhdl) {
2657 /* error */
2658 return;
2659 }
2660 evhdl = *(int *)eventhdl;
2661
2662 close(evhdl);
2663 mg_free(eventhdl);
2664}
2665
2666
2667#endif
2668
2669#endif
2670
2671
2672#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2673
2674struct posix_event {
2675 pthread_mutex_t mutex;
2676 pthread_cond_t cond;
2677 int signaled;
2678};
2679
2680
2681static void *
2682event_create(void)
2683{
2684 struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
2685 if (ret == 0) {
2686 /* out of memory */
2687 return 0;
2688 }
2689 if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2690 /* pthread mutex not available */
2691 mg_free(ret);
2692 return 0;
2693 }
2694 if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2695 /* pthread cond not available */
2696 pthread_mutex_destroy(&(ret->mutex));
2697 mg_free(ret);
2698 return 0;
2699 }
2700 ret->signaled = 0;
2701 return (void *)ret;
2702}
2703
2704
2705static int
2706event_wait(void *eventhdl)
2707{
2708 struct posix_event *ev = (struct posix_event *)eventhdl;
2709 pthread_mutex_lock(&(ev->mutex));
2710 while (!ev->signaled) {
2711 pthread_cond_wait(&(ev->cond), &(ev->mutex));
2712 }
2713 ev->signaled = 0;
2714 pthread_mutex_unlock(&(ev->mutex));
2715 return 1;
2716}
2717
2718
2719static int
2720event_signal(void *eventhdl)
2721{
2722 struct posix_event *ev = (struct posix_event *)eventhdl;
2723 pthread_mutex_lock(&(ev->mutex));
2724 pthread_cond_signal(&(ev->cond));
2725 ev->signaled = 1;
2726 pthread_mutex_unlock(&(ev->mutex));
2727 return 1;
2728}
2729
2730
2731static void
2732event_destroy(void *eventhdl)
2733{
2734 struct posix_event *ev = (struct posix_event *)eventhdl;
2735 pthread_cond_destroy(&(ev->cond));
2736 pthread_mutex_destroy(&(ev->mutex));
2737 mg_free(ev);
2738}
2739#endif
2740
2741
2742static void
2744{
2745 char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
2746
2748 NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
2749
2750#if defined(_WIN32)
2751#if defined(_MSC_VER)
2752 /* Windows and Visual Studio Compiler */
2753 __try {
2754 THREADNAME_INFO info;
2755 info.dwType = 0x1000;
2756 info.szName = threadName;
2757 info.dwThreadID = ~0U;
2758 info.dwFlags = 0;
2759
2760 RaiseException(0x406D1388,
2761 0,
2762 sizeof(info) / sizeof(ULONG_PTR),
2763 (ULONG_PTR *)&info);
2764 } __except (EXCEPTION_EXECUTE_HANDLER) {
2765 }
2766#elif defined(__MINGW32__)
2767 /* No option known to set thread name for MinGW known */
2768#endif
2769#elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
2770 && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
2771 /* pthread_setname_np first appeared in glibc in version 2.12 */
2772#if defined(__MACH__)
2773 /* OS X only current thread name can be changed */
2774 (void)pthread_setname_np(threadName);
2775#else
2776 (void)pthread_setname_np(pthread_self(), threadName);
2777#endif
2778#elif defined(__linux__)
2779 /* On Linux we can use the prctl function.
2780 * When building for Linux Standard Base (LSB) use
2781 * NO_THREAD_NAME. However, thread names are a big
2782 * help for debugging, so the stadard is to set them.
2783 */
2784 (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
2785#endif
2786}
2787#else /* !defined(NO_THREAD_NAME) */
2788void
2789mg_set_thread_name(const char *threadName)
2790{
2791}
2792#endif
2793
2794
2795const struct mg_option *
2797{
2798 return config_options;
2799}
2800
2801
2802/* Do not open file (unused) */
2803#define MG_FOPEN_MODE_NONE (0)
2804
2805/* Open file for read only access */
2806#define MG_FOPEN_MODE_READ (1)
2807
2808/* Open file for writing, create and overwrite */
2809#define MG_FOPEN_MODE_WRITE (2)
2810
2811/* Open file for writing, create and append */
2812#define MG_FOPEN_MODE_APPEND (4)
2813
2814
2815static int
2816is_file_opened(const struct mg_file_access *fileacc)
2817{
2818 if (!fileacc) {
2819 return 0;
2820 }
2821
2822 return (fileacc->fp != NULL);
2823}
2824
2825
2826#if !defined(NO_FILESYSTEMS)
2827static int mg_stat(const struct mg_connection *conn,
2828 const char *path,
2829 struct mg_file_stat *filep);
2830
2831
2832/* Reject files with special characters (for Windows) */
2833static int
2834mg_path_suspicious(const struct mg_connection *conn, const char *path)
2835{
2836 const uint8_t *c = (const uint8_t *)path;
2837 (void)conn; /* not used */
2838
2839 if ((c == NULL) || (c[0] == 0)) {
2840 /* Null pointer or empty path --> suspicious */
2841 return 1;
2842 }
2843
2844#if defined(_WIN32)
2845 while (*c) {
2846 if (*c < 32) {
2847 /* Control character */
2848 return 1;
2849 }
2850 if ((*c == '>') || (*c == '<') || (*c == '|')) {
2851 /* stdin/stdout redirection character */
2852 return 1;
2853 }
2854 if ((*c == '*') || (*c == '?')) {
2855 /* Wildcard character */
2856 return 1;
2857 }
2858 if (*c == '"') {
2859 /* Windows quotation */
2860 return 1;
2861 }
2862 c++;
2863 }
2864#endif
2865
2866 /* Nothing suspicious found */
2867 return 0;
2868}
2869
2870
2871/* mg_fopen will open a file either in memory or on the disk.
2872 * The input parameter path is a string in UTF-8 encoding.
2873 * The input parameter mode is MG_FOPEN_MODE_*
2874 * On success, fp will be set in the output struct mg_file.
2875 * All status members will also be set.
2876 * The function returns 1 on success, 0 on error. */
2877static int
2878mg_fopen(const struct mg_connection *conn,
2879 const char *path,
2880 int mode,
2881 struct mg_file *filep)
2882{
2883 int found;
2884
2885 if (!filep) {
2886 return 0;
2887 }
2888 filep->access.fp = NULL;
2889
2890 if (mg_path_suspicious(conn, path)) {
2891 return 0;
2892 }
2893
2894 /* filep is initialized in mg_stat: all fields with memset to,
2895 * some fields like size and modification date with values */
2896 found = mg_stat(conn, path, &(filep->stat));
2897
2898 if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
2899 /* file does not exist and will not be created */
2900 return 0;
2901 }
2902
2903#if defined(_WIN32)
2904 {
2905 wchar_t wbuf[UTF16_PATH_MAX];
2906 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
2907 switch (mode) {
2908 case MG_FOPEN_MODE_READ:
2909 filep->access.fp = _wfopen(wbuf, L"rb");
2910 break;
2912 filep->access.fp = _wfopen(wbuf, L"wb");
2913 break;
2915 filep->access.fp = _wfopen(wbuf, L"ab");
2916 break;
2917 }
2918 }
2919#else
2920 /* Linux et al already use unicode. No need to convert. */
2921 switch (mode) {
2922 case MG_FOPEN_MODE_READ:
2923 filep->access.fp = fopen(path, "r");
2924 break;
2926 filep->access.fp = fopen(path, "w");
2927 break;
2929 filep->access.fp = fopen(path, "a");
2930 break;
2931 }
2932
2933#endif
2934 if (!found) {
2935 /* File did not exist before fopen was called.
2936 * Maybe it has been created now. Get stat info
2937 * like creation time now. */
2938 found = mg_stat(conn, path, &(filep->stat));
2939 (void)found;
2940 }
2941
2942 /* return OK if file is opened */
2943 return (filep->access.fp != NULL);
2944}
2945
2946
2947/* return 0 on success, just like fclose */
2948static int
2950{
2951 int ret = -1;
2952 if (fileacc != NULL) {
2953 if (fileacc->fp != NULL) {
2954 ret = fclose(fileacc->fp);
2955 }
2956 /* reset all members of fileacc */
2957 memset(fileacc, 0, sizeof(*fileacc));
2958 }
2959 return ret;
2960}
2961#endif /* NO_FILESYSTEMS */
2962
2963
2964static void
2965mg_strlcpy(char *dst, const char *src, size_t n)
2966{
2967 for (; *src != '\0' && n > 1; n--) {
2968 *dst++ = *src++;
2969 }
2970 *dst = '\0';
2971}
2972
2973
2974static int
2975lowercase(const char *s)
2976{
2977 return tolower((unsigned char)*s);
2978}
2979
2980
2981int
2982mg_strncasecmp(const char *s1, const char *s2, size_t len)
2983{
2984 int diff = 0;
2985
2986 if (len > 0) {
2987 do {
2988 diff = lowercase(s1++) - lowercase(s2++);
2989 } while (diff == 0 && s1[-1] != '\0' && --len > 0);
2990 }
2991
2992 return diff;
2993}
2994
2995
2996int
2997mg_strcasecmp(const char *s1, const char *s2)
2998{
2999 int diff;
3000
3001 do {
3002 diff = lowercase(s1++) - lowercase(s2++);
3003 } while (diff == 0 && s1[-1] != '\0');
3004
3005 return diff;
3006}
3007
3008
3009static char *
3010mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
3011{
3012 char *p;
3013 (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
3014 * defined */
3015
3016 if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
3017 mg_strlcpy(p, ptr, len + 1);
3018 }
3019
3020 return p;
3021}
3022
3023
3024static char *
3025mg_strdup_ctx(const char *str, struct mg_context *ctx)
3026{
3027 return mg_strndup_ctx(str, strlen(str), ctx);
3028}
3029
3030static char *
3031mg_strdup(const char *str)
3032{
3033 return mg_strndup_ctx(str, strlen(str), NULL);
3034}
3035
3036
3037static const char *
3038mg_strcasestr(const char *big_str, const char *small_str)
3039{
3040 size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3041
3042 if (big_len >= small_len) {
3043 for (i = 0; i <= (big_len - small_len); i++) {
3044 if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
3045 return big_str + i;
3046 }
3047 }
3048 }
3049
3050 return NULL;
3051}
3052
3053
3054/* Return null terminated string of given maximum length.
3055 * Report errors if length is exceeded. */
3056static void
3057mg_vsnprintf(const struct mg_connection *conn,
3058 int *truncated,
3059 char *buf,
3060 size_t buflen,
3061 const char *fmt,
3062 va_list ap)
3063{
3064 int n, ok;
3065
3066 if (buflen == 0) {
3067 if (truncated) {
3068 *truncated = 1;
3069 }
3070 return;
3071 }
3072
3073#if defined(__clang__)
3074#pragma clang diagnostic push
3075#pragma clang diagnostic ignored "-Wformat-nonliteral"
3076 /* Using fmt as a non-literal is intended here, since it is mostly called
3077 * indirectly by mg_snprintf */
3078#endif
3079
3080 n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
3081 ok = (n >= 0) && ((size_t)n < buflen);
3082
3083#if defined(__clang__)
3084#pragma clang diagnostic pop
3085#endif
3086
3087 if (ok) {
3088 if (truncated) {
3089 *truncated = 0;
3090 }
3091 } else {
3092 if (truncated) {
3093 *truncated = 1;
3094 }
3095 mg_cry_internal(conn,
3096 "truncating vsnprintf buffer: [%.*s]",
3097 (int)((buflen > 200) ? 200 : (buflen - 1)),
3098 buf);
3099 n = (int)buflen - 1;
3100 }
3101 buf[n] = '\0';
3102}
3103
3104
3105static void
3106mg_snprintf(const struct mg_connection *conn,
3107 int *truncated,
3108 char *buf,
3109 size_t buflen,
3110 const char *fmt,
3111 ...)
3112{
3113 va_list ap;
3114
3115 va_start(ap, fmt);
3116 mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
3117 va_end(ap);
3118}
3119
3120
3121static int
3123{
3124 int i;
3125
3126 for (i = 0; config_options[i].name != NULL; i++) {
3127 if (strcmp(config_options[i].name, name) == 0) {
3128 return i;
3129 }
3130 }
3131 return -1;
3132}
3133
3134
3135const char *
3136mg_get_option(const struct mg_context *ctx, const char *name)
3137{
3138 int i;
3139 if ((i = get_option_index(name)) == -1) {
3140 return NULL;
3141 } else if (!ctx || ctx->dd.config[i] == NULL) {
3142 return "";
3143 } else {
3144 return ctx->dd.config[i];
3145 }
3146}
3147
3148#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3149
3150struct mg_context *
3152{
3153 return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
3154}
3155
3156
3157void *
3159{
3160 return (ctx == NULL) ? NULL : ctx->user_data;
3161}
3162
3163
3164void *
3166{
3167 return mg_get_user_data(mg_get_context(conn));
3168}
3169
3170
3171void *
3173{
3174 /* both methods should return the same pointer */
3175 if (conn) {
3176 /* quick access, in case conn is known */
3177 return conn->tls_user_ptr;
3178 } else {
3179 /* otherwise get pointer from thread local storage (TLS) */
3180 struct mg_workerTLS *tls =
3181 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3182 return tls->user_ptr;
3183 }
3184}
3185
3186
3187void
3188mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
3189{
3190 if (const_conn != NULL) {
3191 /* Const cast, since "const struct mg_connection *" does not mean
3192 * the connection object is not modified. Here "const" is used,
3193 * to indicate mg_read/mg_write/mg_send/.. must not be called. */
3194 struct mg_connection *conn = (struct mg_connection *)const_conn;
3195 conn->request_info.conn_data = data;
3196 }
3197}
3198
3199
3200void *
3202{
3203 if (conn != NULL) {
3204 return conn->request_info.conn_data;
3205 }
3206 return NULL;
3207}
3208
3209
3210int
3212 int size,
3213 struct mg_server_port *ports)
3214{
3215 int i, cnt = 0;
3216
3217 if (size <= 0) {
3218 return -1;
3219 }
3220 memset(ports, 0, sizeof(*ports) * (size_t)size);
3221 if (!ctx) {
3222 return -1;
3223 }
3224 if (!ctx->listening_sockets) {
3225 return -1;
3226 }
3227
3228 for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
3229
3230 ports[cnt].port =
3231 ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
3232 ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
3233 ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
3234
3235 if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
3236 /* IPv4 */
3237 ports[cnt].protocol = 1;
3238 cnt++;
3239 } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
3240 /* IPv6 */
3241 ports[cnt].protocol = 3;
3242 cnt++;
3243 }
3244 }
3245
3246 return cnt;
3247}
3248
3249
3250#if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
3251#define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
3252#endif
3253
3254static void
3255sockaddr_to_string(char *buf, size_t len, const union usa *usa)
3256{
3257 buf[0] = '\0';
3258
3259 if (!usa) {
3260 return;
3261 }
3262
3263 if (usa->sa.sa_family == AF_INET) {
3264 getnameinfo(&usa->sa,
3265 sizeof(usa->sin),
3266 buf,
3267 (unsigned)len,
3268 NULL,
3269 0,
3270 NI_NUMERICHOST);
3271 }
3272#if defined(USE_IPV6)
3273 else if (usa->sa.sa_family == AF_INET6) {
3274 getnameinfo(&usa->sa,
3275 sizeof(usa->sin6),
3276 buf,
3277 (unsigned)len,
3278 NULL,
3279 0,
3280 NI_NUMERICHOST);
3281 }
3282#endif
3283#if defined(USE_X_DOM_SOCKET)
3284 else if (usa->sa.sa_family == AF_UNIX) {
3285 /* TODO: Define a remote address for unix domain sockets.
3286 * This code will always return "localhost", identical to http+tcp:
3287 getnameinfo(&usa->sa,
3288 sizeof(usa->sun),
3289 buf,
3290 (unsigned)len,
3291 NULL,
3292 0,
3293 NI_NUMERICHOST);
3294 */
3295 strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
3296 buf[len-1] = 0;
3297 }
3298#endif
3299}
3300
3301
3302/* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
3303 * included in all responses other than 100, 101, 5xx. */
3304static void
3305gmt_time_string(char *buf, size_t buf_len, time_t *t)
3306{
3307#if !defined(REENTRANT_TIME)
3308 struct tm *tm;
3309
3310 tm = ((t != NULL) ? gmtime(t) : NULL);
3311 if (tm != NULL) {
3312#else
3313 struct tm _tm;
3314 struct tm *tm = &_tm;
3315
3316 if (t != NULL) {
3317 gmtime_r(t, tm);
3318#endif
3319 strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
3320 } else {
3321 mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3322 buf[buf_len - 1] = '\0';
3323 }
3324}
3325
3326
3327/* difftime for struct timespec. Return value is in seconds. */
3328static double
3329mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
3330{
3331 return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3332 + (double)(ts_now->tv_sec - ts_before->tv_sec);
3333}
3334
3335
3336#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3337static void mg_cry_internal_impl(const struct mg_connection *conn,
3338 const char *func,
3339 unsigned line,
3340 const char *fmt,
3341 va_list ap);
3342#include "external_mg_cry_internal_impl.inl"
3343#elif !defined(NO_FILESYSTEMS)
3344
3345/* Print error message to the opened error log stream. */
3346static void
3348 const char *func,
3349 unsigned line,
3350 const char *fmt,
3351 va_list ap)
3352{
3353 char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
3354 struct mg_file fi;
3355 time_t timestamp;
3356
3357 /* Unused, in the RELEASE build */
3358 (void)func;
3359 (void)line;
3360
3361#if defined(GCC_DIAGNOSTIC)
3362#pragma GCC diagnostic push
3363#pragma GCC diagnostic ignored "-Wformat-nonliteral"
3364#endif
3365
3366 IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
3367
3368#if defined(GCC_DIAGNOSTIC)
3369#pragma GCC diagnostic pop
3370#endif
3371
3372 buf[sizeof(buf) - 1] = 0;
3373
3374 DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
3375
3376 if (!conn) {
3377 puts(buf);
3378 return;
3379 }
3380
3381 /* Do not lock when getting the callback value, here and below.
3382 * I suppose this is fine, since function cannot disappear in the
3383 * same way string option can. */
3384 if ((conn->phys_ctx->callbacks.log_message == NULL)
3385 || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
3386
3387 if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
3388 if (mg_fopen(conn,
3391 &fi)
3392 == 0) {
3393 fi.access.fp = NULL;
3394 }
3395 } else {
3396 fi.access.fp = NULL;
3397 }
3398
3399 if (fi.access.fp != NULL) {
3400 flockfile(fi.access.fp);
3401 timestamp = time(NULL);
3402
3403 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
3404 fprintf(fi.access.fp,
3405 "[%010lu] [error] [client %s] ",
3406 (unsigned long)timestamp,
3407 src_addr);
3408
3409 if (conn->request_info.request_method != NULL) {
3410 fprintf(fi.access.fp,
3411 "%s %s: ",
3415 : "");
3416 }
3417
3418 fprintf(fi.access.fp, "%s", buf);
3419 fputc('\n', fi.access.fp);
3420 fflush(fi.access.fp);
3421 funlockfile(fi.access.fp);
3422 (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
3423 * mg_cry here anyway ;-) */
3424 }
3425 }
3426}
3427#else
3428#error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
3429#endif /* Externally provided function */
3430
3431
3432/* Construct fake connection structure. Used for logging, if connection
3433 * is not applicable at the moment of logging. */
3434static struct mg_connection *
3436{
3437 static const struct mg_connection conn_zero = {0};
3438 *fc = conn_zero;
3439 fc->phys_ctx = ctx;
3440 fc->dom_ctx = &(ctx->dd);
3441 return fc;
3442}
3443
3444
3445static void
3447 struct mg_context *ctx,
3448 const char *func,
3449 unsigned line,
3450 const char *fmt,
3451 ...)
3452{
3453 va_list ap;
3454 va_start(ap, fmt);
3455 if (!conn && ctx) {
3456 struct mg_connection fc;
3457 mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
3458 } else {
3459 mg_cry_internal_impl(conn, func, line, fmt, ap);
3460 }
3461 va_end(ap);
3462}
3463
3464
3465void
3466mg_cry(const struct mg_connection *conn, const char *fmt, ...)
3467{
3468 va_list ap;
3469 va_start(ap, fmt);
3470 mg_cry_internal_impl(conn, "user", 0, fmt, ap);
3471 va_end(ap);
3472}
3473
3474
3475#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3476
3477
3478const char *
3480{
3481 return CIVETWEB_VERSION;
3482}
3483
3484
3485const struct mg_request_info *
3487{
3488 if (!conn) {
3489 return NULL;
3490 }
3491#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3493 char txt[16];
3494 struct mg_workerTLS *tls =
3495 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3496
3497 sprintf(txt, "%03i", conn->response_info.status_code);
3498 if (strlen(txt) == 3) {
3499 memcpy(tls->txtbuf, txt, 4);
3500 } else {
3501 strcpy(tls->txtbuf, "ERR");
3502 }
3503
3504 ((struct mg_connection *)conn)->request_info.local_uri =
3505 tls->txtbuf; /* use thread safe buffer */
3506 ((struct mg_connection *)conn)->request_info.local_uri_raw =
3507 tls->txtbuf; /* use the same thread safe buffer */
3508 ((struct mg_connection *)conn)->request_info.request_uri =
3509 tls->txtbuf; /* use the same thread safe buffer */
3510
3511 ((struct mg_connection *)conn)->request_info.num_headers =
3513 memcpy(((struct mg_connection *)conn)->request_info.http_headers,
3515 sizeof(conn->response_info.http_headers));
3516 } else
3517#endif
3519 return NULL;
3520 }
3521 return &conn->request_info;
3522}
3523
3524
3525const struct mg_response_info *
3527{
3528 if (!conn) {
3529 return NULL;
3530 }
3532 return NULL;
3533 }
3534 return &conn->response_info;
3535}
3536
3537
3538static const char *
3540{
3541#if defined(__clang__)
3542#pragma clang diagnostic push
3543#pragma clang diagnostic ignored "-Wunreachable-code"
3544 /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
3545 * not supported. Clang raises an "unreachable code" warning for parts of ?:
3546 * unreachable, but splitting into four different #ifdef clauses here is
3547 * more complicated.
3548 */
3549#endif
3550
3551 const struct mg_request_info *ri = &conn->request_info;
3552
3553 const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
3554 ? (ri->is_ssl ? "wss" : "ws")
3555 : (ri->is_ssl ? "https" : "http"));
3556
3557 return proto;
3558
3559#if defined(__clang__)
3560#pragma clang diagnostic pop
3561#endif
3562}
3563
3564
3565static int
3567 char *buf,
3568 size_t buflen,
3569 const char *define_proto,
3570 int define_port,
3571 const char *define_uri)
3572{
3573 if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3574 return -1;
3575 } else {
3576 int truncated = 0;
3577 const struct mg_request_info *ri = &conn->request_info;
3578
3579 const char *proto =
3580 (define_proto != NULL) ? define_proto : get_proto_name(conn);
3581 const char *uri =
3582 (define_uri != NULL)
3583 ? define_uri
3584 : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
3585 int port = (define_port > 0) ? define_port : ri->server_port;
3586 int default_port = 80;
3587
3588 if (uri == NULL) {
3589 return -1;
3590 }
3591
3592#if defined(USE_X_DOM_SOCKET)
3593 if (conn->client.lsa.sa.sa_family == AF_UNIX) {
3594 /* TODO: Define and document a link for UNIX domain sockets. */
3595 /* There seems to be no official standard for this.
3596 * Common uses seem to be "httpunix://", "http.unix://" or
3597 * "http+unix://" as a protocol definition string, followed by
3598 * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
3599 * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
3600 * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
3601 * "" (completely skipping the server name part). In any case, the
3602 * last part is the server local path. */
3603 const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
3604 mg_snprintf(conn,
3605 &truncated,
3606 buf,
3607 buflen,
3608 "%s.unix://%s%s",
3609 proto,
3610 server_name,
3611 ri->local_uri);
3612 default_port = 0;
3613 return 0;
3614 }
3615#endif
3616
3617 if (define_proto) {
3618 /* If we got a protocol name, use the default port accordingly. */
3619 if ((0 == strcmp(define_proto, "https"))
3620 || (0 == strcmp(define_proto, "wss"))) {
3621 default_port = 443;
3622 }
3623 } else if (ri->is_ssl) {
3624 /* If we did not get a protocol name, use TLS as default if it is
3625 * already used. */
3626 default_port = 443;
3627 }
3628
3629 {
3630#if defined(USE_IPV6)
3631 int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
3632#endif
3633 int auth_domain_check_enabled =
3635 && (!mg_strcasecmp(
3636 conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
3637
3638 const char *server_domain =
3640
3641 char portstr[16];
3642 char server_ip[48];
3643
3644 if (port != default_port) {
3645 sprintf(portstr, ":%u", (unsigned)port);
3646 } else {
3647 portstr[0] = 0;
3648 }
3649
3650 if (!auth_domain_check_enabled || !server_domain) {
3651
3652 sockaddr_to_string(server_ip,
3653 sizeof(server_ip),
3654 &conn->client.lsa);
3655
3656 server_domain = server_ip;
3657 }
3658
3659 mg_snprintf(conn,
3660 &truncated,
3661 buf,
3662 buflen,
3663#if defined(USE_IPV6)
3664 "%s://%s%s%s%s%s",
3665 proto,
3666 (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
3667 server_domain,
3668 (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
3669#else
3670 "%s://%s%s%s",
3671 proto,
3672 server_domain,
3673#endif
3674 portstr,
3675 ri->local_uri);
3676
3677 if (truncated) {
3678 return -1;
3679 }
3680 return 0;
3681 }
3682 }
3683}
3684
3685
3686int
3687mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
3688{
3689 return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
3690}
3691
3692
3693/* Skip the characters until one of the delimiters characters found.
3694 * 0-terminate resulting word. Skip the delimiter and following whitespaces.
3695 * Advance pointer to buffer to the next word. Return found 0-terminated
3696 * word.
3697 * Delimiters can be quoted with quotechar. */
3698static char *
3699skip_quoted(char **buf,
3700 const char *delimiters,
3701 const char *whitespace,
3702 char quotechar)
3703{
3704 char *p, *begin_word, *end_word, *end_whitespace;
3705
3706 begin_word = *buf;
3707 end_word = begin_word + strcspn(begin_word, delimiters);
3708
3709 /* Check for quotechar */
3710 if (end_word > begin_word) {
3711 p = end_word - 1;
3712 while (*p == quotechar) {
3713 /* While the delimiter is quoted, look for the next delimiter.
3714 */
3715 /* This happens, e.g., in calls from parse_auth_header,
3716 * if the user name contains a " character. */
3717
3718 /* If there is anything beyond end_word, copy it. */
3719 if (*end_word != '\0') {
3720 size_t end_off = strcspn(end_word + 1, delimiters);
3721 memmove(p, end_word, end_off + 1);
3722 p += end_off; /* p must correspond to end_word - 1 */
3723 end_word += end_off + 1;
3724 } else {
3725 *p = '\0';
3726 break;
3727 }
3728 }
3729 for (p++; p < end_word; p++) {
3730 *p = '\0';
3731 }
3732 }
3733
3734 if (*end_word == '\0') {
3735 *buf = end_word;
3736 } else {
3737
3738#if defined(GCC_DIAGNOSTIC)
3739 /* Disable spurious conversion warning for GCC */
3740#pragma GCC diagnostic push
3741#pragma GCC diagnostic ignored "-Wsign-conversion"
3742#endif /* defined(GCC_DIAGNOSTIC) */
3743
3744 end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
3745
3746#if defined(GCC_DIAGNOSTIC)
3747#pragma GCC diagnostic pop
3748#endif /* defined(GCC_DIAGNOSTIC) */
3749
3750 for (p = end_word; p < end_whitespace; p++) {
3751 *p = '\0';
3752 }
3753
3754 *buf = end_whitespace;
3755 }
3756
3757 return begin_word;
3758}
3759
3760
3761/* Return HTTP header value, or NULL if not found. */
3762static const char *
3763get_header(const struct mg_header *hdr, int num_hdr, const char *name)
3764{
3765 int i;
3766 for (i = 0; i < num_hdr; i++) {
3767 if (!mg_strcasecmp(name, hdr[i].name)) {
3768 return hdr[i].value;
3769 }
3770 }
3771
3772 return NULL;
3773}
3774
3775
3776#if defined(USE_WEBSOCKET)
3777/* Retrieve requested HTTP header multiple values, and return the number of
3778 * found occurrences */
3779static int
3780get_req_headers(const struct mg_request_info *ri,
3781 const char *name,
3782 const char **output,
3783 int output_max_size)
3784{
3785 int i;
3786 int cnt = 0;
3787 if (ri) {
3788 for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
3789 if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
3790 output[cnt++] = ri->http_headers[i].value;
3791 }
3792 }
3793 }
3794 return cnt;
3795}
3796#endif
3797
3798
3799const char *
3800mg_get_header(const struct mg_connection *conn, const char *name)
3801{
3802 if (!conn) {
3803 return NULL;
3804 }
3805
3809 name);
3810 }
3814 name);
3815 }
3816 return NULL;
3817}
3818
3819
3820static const char *
3822{
3823 if (!conn) {
3824 return NULL;
3825 }
3826
3828 return conn->request_info.http_version;
3829 }
3831 return conn->response_info.http_version;
3832 }
3833 return NULL;
3834}
3835
3836
3837/* A helper function for traversing a comma separated list of values.
3838 * It returns a list pointer shifted to the next value, or NULL if the end
3839 * of the list found.
3840 * Value is stored in val vector. If value has form "x=y", then eq_val
3841 * vector is initialized to point to the "y" part, and val vector length
3842 * is adjusted to point only to "x". */
3843static const char *
3844next_option(const char *list, struct vec *val, struct vec *eq_val)
3845{
3846 int end;
3847
3848reparse:
3849 if (val == NULL || list == NULL || *list == '\0') {
3850 /* End of the list */
3851 return NULL;
3852 }
3853
3854 /* Skip over leading LWS */
3855 while (*list == ' ' || *list == '\t')
3856 list++;
3857
3858 val->ptr = list;
3859 if ((list = strchr(val->ptr, ',')) != NULL) {
3860 /* Comma found. Store length and shift the list ptr */
3861 val->len = ((size_t)(list - val->ptr));
3862 list++;
3863 } else {
3864 /* This value is the last one */
3865 list = val->ptr + strlen(val->ptr);
3866 val->len = ((size_t)(list - val->ptr));
3867 }
3868
3869 /* Adjust length for trailing LWS */
3870 end = (int)val->len - 1;
3871 while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
3872 end--;
3873 val->len = (size_t)(end) + (size_t)(1);
3874
3875 if (val->len == 0) {
3876 /* Ignore any empty entries. */
3877 goto reparse;
3878 }
3879
3880 if (eq_val != NULL) {
3881 /* Value has form "x=y", adjust pointers and lengths
3882 * so that val points to "x", and eq_val points to "y". */
3883 eq_val->len = 0;
3884 eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
3885 if (eq_val->ptr != NULL) {
3886 eq_val->ptr++; /* Skip over '=' character */
3887 eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
3888 val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
3889 }
3890 }
3891
3892 return list;
3893}
3894
3895
3896/* A helper function for checking if a comma separated list of values
3897 * contains
3898 * the given option (case insensitvely).
3899 * 'header' can be NULL, in which case false is returned. */
3900static int
3901header_has_option(const char *header, const char *option)
3902{
3903 struct vec opt_vec;
3904 struct vec eq_vec;
3905
3906 DEBUG_ASSERT(option != NULL);
3907 DEBUG_ASSERT(option[0] != '\0');
3908
3909 while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
3910 if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
3911 return 1;
3912 }
3913
3914 return 0;
3915}
3916
3917
3918/* Perform case-insensitive match of string against pattern */
3919static ptrdiff_t
3920match_prefix(const char *pattern, size_t pattern_len, const char *str)
3921{
3922 const char *or_str;
3923 ptrdiff_t i, j, len, res;
3924
3925 if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
3926 res = match_prefix(pattern, (size_t)(or_str - pattern), str);
3927 return (res > 0) ? res
3928 : match_prefix(or_str + 1,
3929 (size_t)((pattern + pattern_len)
3930 - (or_str + 1)),
3931 str);
3932 }
3933
3934 for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
3935 if ((pattern[i] == '?') && (str[j] != '\0')) {
3936 continue;
3937 } else if (pattern[i] == '$') {
3938 return (str[j] == '\0') ? j : -1;
3939 } else if (pattern[i] == '*') {
3940 i++;
3941 if (pattern[i] == '*') {
3942 i++;
3943 len = (ptrdiff_t)strlen(str + j);
3944 } else {
3945 len = (ptrdiff_t)strcspn(str + j, "/");
3946 }
3947 if (i == (ptrdiff_t)pattern_len) {
3948 return j + len;
3949 }
3950 do {
3951 res = match_prefix(pattern + i,
3952 (pattern_len - (size_t)i),
3953 str + j + len);
3954 } while (res == -1 && len-- > 0);
3955 return (res == -1) ? -1 : j + res + len;
3956 } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
3957 return -1;
3958 }
3959 }
3960 return (ptrdiff_t)j;
3961}
3962
3963
3964static ptrdiff_t
3965match_prefix_strlen(const char *pattern, const char *str)
3966{
3967 if (pattern == NULL) {
3968 return -1;
3969 }
3970 return match_prefix(pattern, strlen(pattern), str);
3971}
3972
3973
3974/* HTTP 1.1 assumes keep alive if "Connection:" header is not set
3975 * This function must tolerate situations when connection info is not
3976 * set up, for example if request parsing failed. */
3977static int
3979{
3980 const char *http_version;
3981 const char *header;
3982
3983 /* First satisfy needs of the server */
3984 if ((conn == NULL) || conn->must_close) {
3985 /* Close, if civetweb framework needs to close */
3986 return 0;
3987 }
3988
3989 if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
3990 /* Close, if keep alive is not enabled */
3991 return 0;
3992 }
3993
3994 /* Check explicit wish of the client */
3995 header = mg_get_header(conn, "Connection");
3996 if (header) {
3997 /* If there is a connection header from the client, obey */
3998 if (header_has_option(header, "keep-alive")) {
3999 return 1;
4000 }
4001 return 0;
4002 }
4003
4004 /* Use default of the standard */
4005 http_version = get_http_version(conn);
4006 if (http_version && (0 == strcmp(http_version, "1.1"))) {
4007 /* HTTP 1.1 default is keep alive */
4008 return 1;
4009 }
4010
4011 /* HTTP 1.0 (and earlier) default is to close the connection */
4012 return 0;
4013}
4014
4015
4016static int
4018{
4019 if (!conn || !conn->dom_ctx) {
4020 return 0;
4021 }
4022
4023 return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
4024}
4025
4026
4027static int
4029{
4030 if (!conn || !conn->dom_ctx) {
4031 return 0;
4032 }
4033
4034 return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
4035 == 0);
4036}
4037
4038
4039static const char *
4041{
4042 return should_keep_alive(conn) ? "keep-alive" : "close";
4043}
4044
4045
4046#include "response.inl"
4047
4048
4049static void
4051{
4052 /* Send all current and obsolete cache opt-out directives. */
4054 "Cache-Control",
4055 "no-cache, no-store, "
4056 "must-revalidate, private, max-age=0",
4057 -1);
4058 mg_response_header_add(conn, "Expires", "0", -1);
4059
4060 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
4061 /* Obsolete, but still send it for HTTP/1.0 */
4062 mg_response_header_add(conn, "Pragma", "no-cache", -1);
4063 }
4064}
4065
4066
4067static void
4069{
4070#if !defined(NO_CACHING)
4071 int max_age;
4072 char val[64];
4073
4074 const char *cache_control =
4076
4077 /* If there is a full cache-control option configured,0 use it */
4078 if (cache_control != NULL) {
4079 mg_response_header_add(conn, "Cache-Control", cache_control, -1);
4080 return;
4081 }
4082
4083 /* Read the server config to check how long a file may be cached.
4084 * The configuration is in seconds. */
4085 max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
4086 if (max_age <= 0) {
4087 /* 0 means "do not cache". All values <0 are reserved
4088 * and may be used differently in the future. */
4089 /* If a file should not be cached, do not only send
4090 * max-age=0, but also pragmas and Expires headers. */
4092 return;
4093 }
4094
4095 /* Use "Cache-Control: max-age" instead of "Expires" header.
4096 * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
4097 /* See also https://www.mnot.net/cache_docs/ */
4098 /* According to RFC 2616, Section 14.21, caching times should not exceed
4099 * one year. A year with 365 days corresponds to 31536000 seconds, a
4100 * leap
4101 * year to 31622400 seconds. For the moment, we just send whatever has
4102 * been configured, still the behavior for >1 year should be considered
4103 * as undefined. */
4105 conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
4106 mg_response_header_add(conn, "Cache-Control", val, -1);
4107
4108#else /* NO_CACHING */
4109
4111#endif /* !NO_CACHING */
4112}
4113
4114
4115static void
4117{
4118 const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
4119
4120#if !defined(NO_SSL)
4121 if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
4122 long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
4123 if (max_age >= 0) {
4124 char val[64];
4125 mg_snprintf(conn,
4126 NULL,
4127 val,
4128 sizeof(val),
4129 "max-age=%lu",
4130 (unsigned long)max_age);
4131 mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
4132 }
4133 }
4134#endif
4135
4136 if (header && header[0]) {
4137 mg_response_header_add_lines(conn, header);
4138 }
4139}
4140
4141
4142#if !defined(NO_FILESYSTEMS)
4143static void handle_file_based_request(struct mg_connection *conn,
4144 const char *path,
4145 struct mg_file *filep);
4146#endif /* NO_FILESYSTEMS */
4147
4148
4149const char *
4150mg_get_response_code_text(const struct mg_connection *conn, int response_code)
4151{
4152 /* See IANA HTTP status code assignment:
4153 * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
4154 */
4155
4156 switch (response_code) {
4157 /* RFC2616 Section 10.1 - Informational 1xx */
4158 case 100:
4159 return "Continue"; /* RFC2616 Section 10.1.1 */
4160 case 101:
4161 return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
4162 case 102:
4163 return "Processing"; /* RFC2518 Section 10.1 */
4164
4165 /* RFC2616 Section 10.2 - Successful 2xx */
4166 case 200:
4167 return "OK"; /* RFC2616 Section 10.2.1 */
4168 case 201:
4169 return "Created"; /* RFC2616 Section 10.2.2 */
4170 case 202:
4171 return "Accepted"; /* RFC2616 Section 10.2.3 */
4172 case 203:
4173 return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
4174 case 204:
4175 return "No Content"; /* RFC2616 Section 10.2.5 */
4176 case 205:
4177 return "Reset Content"; /* RFC2616 Section 10.2.6 */
4178 case 206:
4179 return "Partial Content"; /* RFC2616 Section 10.2.7 */
4180 case 207:
4181 return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
4182 */
4183 case 208:
4184 return "Already Reported"; /* RFC5842 Section 7.1 */
4185
4186 case 226:
4187 return "IM used"; /* RFC3229 Section 10.4.1 */
4188
4189 /* RFC2616 Section 10.3 - Redirection 3xx */
4190 case 300:
4191 return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
4192 case 301:
4193 return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
4194 case 302:
4195 return "Found"; /* RFC2616 Section 10.3.3 */
4196 case 303:
4197 return "See Other"; /* RFC2616 Section 10.3.4 */
4198 case 304:
4199 return "Not Modified"; /* RFC2616 Section 10.3.5 */
4200 case 305:
4201 return "Use Proxy"; /* RFC2616 Section 10.3.6 */
4202 case 307:
4203 return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
4204 case 308:
4205 return "Permanent Redirect"; /* RFC7238 Section 3 */
4206
4207 /* RFC2616 Section 10.4 - Client Error 4xx */
4208 case 400:
4209 return "Bad Request"; /* RFC2616 Section 10.4.1 */
4210 case 401:
4211 return "Unauthorized"; /* RFC2616 Section 10.4.2 */
4212 case 402:
4213 return "Payment Required"; /* RFC2616 Section 10.4.3 */
4214 case 403:
4215 return "Forbidden"; /* RFC2616 Section 10.4.4 */
4216 case 404:
4217 return "Not Found"; /* RFC2616 Section 10.4.5 */
4218 case 405:
4219 return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
4220 case 406:
4221 return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
4222 case 407:
4223 return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
4224 case 408:
4225 return "Request Time-out"; /* RFC2616 Section 10.4.9 */
4226 case 409:
4227 return "Conflict"; /* RFC2616 Section 10.4.10 */
4228 case 410:
4229 return "Gone"; /* RFC2616 Section 10.4.11 */
4230 case 411:
4231 return "Length Required"; /* RFC2616 Section 10.4.12 */
4232 case 412:
4233 return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
4234 case 413:
4235 return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
4236 case 414:
4237 return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
4238 case 415:
4239 return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
4240 case 416:
4241 return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
4242 */
4243 case 417:
4244 return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
4245
4246 case 421:
4247 return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
4248 case 422:
4249 return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
4250 * Section 11.2 */
4251 case 423:
4252 return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
4253 case 424:
4254 return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
4255 * Section 11.4 */
4256
4257 case 426:
4258 return "Upgrade Required"; /* RFC 2817 Section 4 */
4259
4260 case 428:
4261 return "Precondition Required"; /* RFC 6585, Section 3 */
4262 case 429:
4263 return "Too Many Requests"; /* RFC 6585, Section 4 */
4264
4265 case 431:
4266 return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
4267
4268 case 451:
4269 return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
4270 * Section 3 */
4271
4272 /* RFC2616 Section 10.5 - Server Error 5xx */
4273 case 500:
4274 return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
4275 case 501:
4276 return "Not Implemented"; /* RFC2616 Section 10.5.2 */
4277 case 502:
4278 return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
4279 case 503:
4280 return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
4281 case 504:
4282 return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
4283 case 505:
4284 return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
4285 case 506:
4286 return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
4287 case 507:
4288 return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
4289 * Section 11.5 */
4290 case 508:
4291 return "Loop Detected"; /* RFC5842 Section 7.1 */
4292
4293 case 510:
4294 return "Not Extended"; /* RFC 2774, Section 7 */
4295 case 511:
4296 return "Network Authentication Required"; /* RFC 6585, Section 6 */
4297
4298 /* Other status codes, not shown in the IANA HTTP status code
4299 * assignment.
4300 * E.g., "de facto" standards due to common use, ... */
4301 case 418:
4302 return "I am a teapot"; /* RFC2324 Section 2.3.2 */
4303 case 419:
4304 return "Authentication Timeout"; /* common use */
4305 case 420:
4306 return "Enhance Your Calm"; /* common use */
4307 case 440:
4308 return "Login Timeout"; /* common use */
4309 case 509:
4310 return "Bandwidth Limit Exceeded"; /* common use */
4311
4312 default:
4313 /* This error code is unknown. This should not happen. */
4314 if (conn) {
4315 mg_cry_internal(conn,
4316 "Unknown HTTP response code: %u",
4317 response_code);
4318 }
4319
4320 /* Return at least a category according to RFC 2616 Section 10. */
4321 if (response_code >= 100 && response_code < 200) {
4322 /* Unknown informational status code */
4323 return "Information";
4324 }
4325 if (response_code >= 200 && response_code < 300) {
4326 /* Unknown success code */
4327 return "Success";
4328 }
4329 if (response_code >= 300 && response_code < 400) {
4330 /* Unknown redirection code */
4331 return "Redirection";
4332 }
4333 if (response_code >= 400 && response_code < 500) {
4334 /* Unknown request error code */
4335 return "Client Error";
4336 }
4337 if (response_code >= 500 && response_code < 600) {
4338 /* Unknown server error code */
4339 return "Server Error";
4340 }
4341
4342 /* Response code not even within reasonable range */
4343 return "";
4344 }
4345}
4346
4347
4348static int
4350 int status,
4351 const char *fmt,
4352 va_list args)
4353{
4354 char errmsg_buf[MG_BUF_LEN];
4355 va_list ap;
4356 int has_body;
4357
4358#if !defined(NO_FILESYSTEMS)
4359 char path_buf[UTF8_PATH_MAX];
4360 int len, i, page_handler_found, scope, truncated;
4361 const char *error_handler = NULL;
4362 struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
4363 const char *error_page_file_ext, *tstr;
4364#endif /* NO_FILESYSTEMS */
4365 int handled_by_callback = 0;
4366
4367 if ((conn == NULL) || (fmt == NULL)) {
4368 return -2;
4369 }
4370
4371 /* Set status (for log) */
4372 conn->status_code = status;
4373
4374 /* Errors 1xx, 204 and 304 MUST NOT send a body */
4375 has_body = ((status > 199) && (status != 204) && (status != 304));
4376
4377 /* Prepare message in buf, if required */
4378 if (has_body
4379 || (!conn->in_error_handler
4380 && (conn->phys_ctx->callbacks.http_error != NULL))) {
4381 /* Store error message in errmsg_buf */
4382 va_copy(ap, args);
4383 mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
4384 va_end(ap);
4385 /* In a debug build, print all html errors */
4386 DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
4387 }
4388
4389 /* If there is a http_error callback, call it.
4390 * But don't do it recursively, if callback calls mg_send_http_error again.
4391 */
4392 if (!conn->in_error_handler
4393 && (conn->phys_ctx->callbacks.http_error != NULL)) {
4394 /* Mark in_error_handler to avoid recursion and call user callback. */
4395 conn->in_error_handler = 1;
4396 handled_by_callback =
4397 (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
4398 == 0);
4399 conn->in_error_handler = 0;
4400 }
4401
4402 if (!handled_by_callback) {
4403 /* Check for recursion */
4404 if (conn->in_error_handler) {
4406 "Recursion when handling error %u - fall back to default",
4407 status);
4408#if !defined(NO_FILESYSTEMS)
4409 } else {
4410 /* Send user defined error pages, if defined */
4411 error_handler = conn->dom_ctx->config[ERROR_PAGES];
4412 error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
4413 page_handler_found = 0;
4414
4415 if (error_handler != NULL) {
4416 for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4417 switch (scope) {
4418 case 1: /* Handler for specific error, e.g. 404 error */
4419 mg_snprintf(conn,
4420 &truncated,
4421 path_buf,
4422 sizeof(path_buf) - 32,
4423 "%serror%03u.",
4424 error_handler,
4425 status);
4426 break;
4427 case 2: /* Handler for error group, e.g., 5xx error
4428 * handler
4429 * for all server errors (500-599) */
4430 mg_snprintf(conn,
4431 &truncated,
4432 path_buf,
4433 sizeof(path_buf) - 32,
4434 "%serror%01uxx.",
4435 error_handler,
4436 status / 100);
4437 break;
4438 default: /* Handler for all errors */
4439 mg_snprintf(conn,
4440 &truncated,
4441 path_buf,
4442 sizeof(path_buf) - 32,
4443 "%serror.",
4444 error_handler);
4445 break;
4446 }
4447
4448 /* String truncation in buf may only occur if
4449 * error_handler is too long. This string is
4450 * from the config, not from a client. */
4451 (void)truncated;
4452
4453 /* The following code is redundant, but it should avoid
4454 * false positives in static source code analyzers and
4455 * vulnerability scanners.
4456 */
4457 path_buf[sizeof(path_buf) - 32] = 0;
4458 len = (int)strlen(path_buf);
4459 if (len > (int)sizeof(path_buf) - 32) {
4460 len = (int)sizeof(path_buf) - 32;
4461 }
4462
4463 /* Start with the file extenstion from the configuration. */
4464 tstr = strchr(error_page_file_ext, '.');
4465
4466 while (tstr) {
4467 for (i = 1;
4468 (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
4469 i++) {
4470 /* buffer overrun is not possible here, since
4471 * (i < 32) && (len < sizeof(path_buf) - 32)
4472 * ==> (i + len) < sizeof(path_buf) */
4473 path_buf[len + i - 1] = tstr[i];
4474 }
4475 /* buffer overrun is not possible here, since
4476 * (i <= 32) && (len < sizeof(path_buf) - 32)
4477 * ==> (i + len) <= sizeof(path_buf) */
4478 path_buf[len + i - 1] = 0;
4479
4480 if (mg_stat(conn, path_buf, &error_page_file.stat)) {
4481 DEBUG_TRACE("Check error page %s - found",
4482 path_buf);
4483 page_handler_found = 1;
4484 break;
4485 }
4486 DEBUG_TRACE("Check error page %s - not found",
4487 path_buf);
4488
4489 /* Continue with the next file extenstion from the
4490 * configuration (if there is a next one). */
4491 tstr = strchr(tstr + i, '.');
4492 }
4493 }
4494 }
4495
4496 if (page_handler_found) {
4497 conn->in_error_handler = 1;
4498 handle_file_based_request(conn, path_buf, &error_page_file);
4499 conn->in_error_handler = 0;
4500 return 0;
4501 }
4502#endif /* NO_FILESYSTEMS */
4503 }
4504
4505 /* No custom error page. Send default error page. */
4506 conn->must_close = 1;
4507 mg_response_header_start(conn, status);
4510 if (has_body) {
4512 "Content-Type",
4513 "text/plain; charset=utf-8",
4514 -1);
4515 }
4517
4518 /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
4519 if (has_body) {
4520 /* For other errors, send a generic error message. */
4521 const char *status_text = mg_get_response_code_text(conn, status);
4522 mg_printf(conn, "Error %d: %s\n", status, status_text);
4523 mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4524
4525 } else {
4526 /* No body allowed. Close the connection. */
4527 DEBUG_TRACE("Error %i", status);
4528 }
4529 }
4530 return 0;
4531}
4532
4533
4534int
4535mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
4536{
4537 va_list ap;
4538 int ret;
4539
4540 va_start(ap, fmt);
4541 ret = mg_send_http_error_impl(conn, status, fmt, ap);
4542 va_end(ap);
4543
4544 return ret;
4545}
4546
4547
4548int
4550 const char *mime_type,
4551 long long content_length)
4552{
4553 if ((mime_type == NULL) || (*mime_type == 0)) {
4554 /* No content type defined: default to text/html */
4555 mime_type = "text/html";
4556 }
4557
4558 mg_response_header_start(conn, 200);
4561 mg_response_header_add(conn, "Content-Type", mime_type, -1);
4562 if (content_length < 0) {
4563 /* Size not known. Use chunked encoding (HTTP/1.x) */
4564 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
4565 /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
4566 mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
4567 }
4568 } else {
4569 char len[32];
4570 int trunc = 0;
4571 mg_snprintf(conn,
4572 &trunc,
4573 len,
4574 sizeof(len),
4575 "%" UINT64_FMT,
4576 (uint64_t)content_length);
4577 if (!trunc) {
4578 /* Since 32 bytes is enough to hold any 64 bit decimal number,
4579 * !trunc is always true */
4580 mg_response_header_add(conn, "Content-Length", len, -1);
4581 }
4582 }
4584
4585 return 0;
4586}
4587
4588
4589int
4591 const char *target_url,
4592 int redirect_code)
4593{
4594 /* Send a 30x redirect response.
4595 *
4596 * Redirect types (status codes):
4597 *
4598 * Status | Perm/Temp | Method | Version
4599 * 301 | permanent | POST->GET undefined | HTTP/1.0
4600 * 302 | temporary | POST->GET undefined | HTTP/1.0
4601 * 303 | temporary | always use GET | HTTP/1.1
4602 * 307 | temporary | always keep method | HTTP/1.1
4603 * 308 | permanent | always keep method | HTTP/1.1
4604 */
4605 const char *redirect_text;
4606 int ret;
4607 size_t content_len = 0;
4608#if defined(MG_SEND_REDIRECT_BODY)
4609 char reply[MG_BUF_LEN];
4610#endif
4611
4612 /* In case redirect_code=0, use 307. */
4613 if (redirect_code == 0) {
4614 redirect_code = 307;
4615 }
4616
4617 /* In case redirect_code is none of the above, return error. */
4618 if ((redirect_code != 301) && (redirect_code != 302)
4619 && (redirect_code != 303) && (redirect_code != 307)
4620 && (redirect_code != 308)) {
4621 /* Parameter error */
4622 return -2;
4623 }
4624
4625 /* Get proper text for response code */
4626 redirect_text = mg_get_response_code_text(conn, redirect_code);
4627
4628 /* If target_url is not defined, redirect to "/". */
4629 if ((target_url == NULL) || (*target_url == 0)) {
4630 target_url = "/";
4631 }
4632
4633#if defined(MG_SEND_REDIRECT_BODY)
4634 /* TODO: condition name? */
4635
4636 /* Prepare a response body with a hyperlink.
4637 *
4638 * According to RFC2616 (and RFC1945 before):
4639 * Unless the request method was HEAD, the entity of the
4640 * response SHOULD contain a short hypertext note with a hyperlink to
4641 * the new URI(s).
4642 *
4643 * However, this response body is not useful in M2M communication.
4644 * Probably the original reason in the RFC was, clients not supporting
4645 * a 30x HTTP redirect could still show the HTML page and let the user
4646 * press the link. Since current browsers support 30x HTTP, the additional
4647 * HTML body does not seem to make sense anymore.
4648 *
4649 * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
4650 * but it only notes:
4651 * The server's response payload usually contains a short
4652 * hypertext note with a hyperlink to the new URI(s).
4653 *
4654 * Deactivated by default. If you need the 30x body, set the define.
4655 */
4657 conn,
4658 NULL /* ignore truncation */,
4659 reply,
4660 sizeof(reply),
4661 "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4662 redirect_text,
4663 target_url,
4664 target_url);
4665 content_len = strlen(reply);
4666#endif
4667
4668 /* Do not send any additional header. For all other options,
4669 * including caching, there are suitable defaults. */
4670 ret = mg_printf(conn,
4671 "HTTP/1.1 %i %s\r\n"
4672 "Location: %s\r\n"
4673 "Content-Length: %u\r\n"
4674 "Connection: %s\r\n\r\n",
4675 redirect_code,
4676 redirect_text,
4677 target_url,
4678 (unsigned int)content_len,
4680
4681#if defined(MG_SEND_REDIRECT_BODY)
4682 /* Send response body */
4683 if (ret > 0) {
4684 /* ... unless it is a HEAD request */
4685 if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
4686 ret = mg_write(conn, reply, content_len);
4687 }
4688 }
4689#endif
4690
4691 return (ret > 0) ? ret : -1;
4692}
4693
4694
4695#if defined(_WIN32)
4696/* Create substitutes for POSIX functions in Win32. */
4697
4698#if defined(GCC_DIAGNOSTIC)
4699/* Show no warning in case system functions are not used. */
4700#pragma GCC diagnostic push
4701#pragma GCC diagnostic ignored "-Wunused-function"
4702#endif
4703
4704
4705static int
4706pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
4707{
4708 (void)unused;
4709 /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
4710 InitializeCriticalSection(&mutex->sec);
4711 return 0;
4712}
4713
4714
4715static int
4716pthread_mutex_destroy(pthread_mutex_t *mutex)
4717{
4718 DeleteCriticalSection(&mutex->sec);
4719 return 0;
4720}
4721
4722
4723static int
4724pthread_mutex_lock(pthread_mutex_t *mutex)
4725{
4726 EnterCriticalSection(&mutex->sec);
4727 return 0;
4728}
4729
4730
4731static int
4732pthread_mutex_unlock(pthread_mutex_t *mutex)
4733{
4734 LeaveCriticalSection(&mutex->sec);
4735 return 0;
4736}
4737
4738
4740static int
4741pthread_cond_init(pthread_cond_t *cv, const void *unused)
4742{
4743 (void)unused;
4744 (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
4745 cv->waiting_thread = NULL;
4746 return 0;
4747}
4748
4749
4751static int
4752pthread_cond_timedwait(pthread_cond_t *cv,
4753 pthread_mutex_t *mutex,
4754 FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
4755{
4756 struct mg_workerTLS **ptls,
4757 *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
4758 int ok;
4759 uint64_t nsnow, nswaitabs;
4760 int64_t nswaitrel;
4761 DWORD mswaitrel;
4762
4763 pthread_mutex_lock(&cv->threadIdSec);
4764 /* Add this thread to cv's waiting list */
4765 ptls = &cv->waiting_thread;
4766 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
4767 ;
4768 tls->next_waiting_thread = NULL;
4769 *ptls = tls;
4770 pthread_mutex_unlock(&cv->threadIdSec);
4771
4772 if (abstime) {
4773 nsnow = mg_get_current_time_ns();
4774 nswaitabs =
4775 (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
4776 nswaitrel = nswaitabs - nsnow;
4777 if (nswaitrel < 0) {
4778 nswaitrel = 0;
4779 }
4780 mswaitrel = (DWORD)(nswaitrel / 1000000);
4781 } else {
4782 mswaitrel = (DWORD)INFINITE;
4783 }
4784
4785 pthread_mutex_unlock(mutex);
4786 ok = (WAIT_OBJECT_0
4787 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
4788 if (!ok) {
4789 ok = 1;
4790 pthread_mutex_lock(&cv->threadIdSec);
4791 ptls = &cv->waiting_thread;
4792 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
4793 if (*ptls == tls) {
4794 *ptls = tls->next_waiting_thread;
4795 ok = 0;
4796 break;
4797 }
4798 }
4799 pthread_mutex_unlock(&cv->threadIdSec);
4800 if (ok) {
4801 WaitForSingleObject(tls->pthread_cond_helper_mutex,
4802 (DWORD)INFINITE);
4803 }
4804 }
4805 /* This thread has been removed from cv's waiting list */
4806 pthread_mutex_lock(mutex);
4807
4808 return ok ? 0 : -1;
4809}
4810
4811
4813static int
4814pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
4815{
4816 return pthread_cond_timedwait(cv, mutex, NULL);
4817}
4818
4819
4821static int
4822pthread_cond_signal(pthread_cond_t *cv)
4823{
4824 HANDLE wkup = NULL;
4825 BOOL ok = FALSE;
4826
4827 pthread_mutex_lock(&cv->threadIdSec);
4828 if (cv->waiting_thread) {
4829 wkup = cv->waiting_thread->pthread_cond_helper_mutex;
4830 cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
4831
4832 ok = SetEvent(wkup);
4833 DEBUG_ASSERT(ok);
4834 }
4835 pthread_mutex_unlock(&cv->threadIdSec);
4836
4837 return ok ? 0 : 1;
4838}
4839
4840
4842static int
4843pthread_cond_broadcast(pthread_cond_t *cv)
4844{
4845 pthread_mutex_lock(&cv->threadIdSec);
4846 while (cv->waiting_thread) {
4847 pthread_cond_signal(cv);
4848 }
4849 pthread_mutex_unlock(&cv->threadIdSec);
4850
4851 return 0;
4852}
4853
4854
4856static int
4857pthread_cond_destroy(pthread_cond_t *cv)
4858{
4859 pthread_mutex_lock(&cv->threadIdSec);
4860 DEBUG_ASSERT(cv->waiting_thread == NULL);
4861 pthread_mutex_unlock(&cv->threadIdSec);
4862 pthread_mutex_destroy(&cv->threadIdSec);
4863
4864 return 0;
4865}
4866
4867
4868#if defined(ALTERNATIVE_QUEUE)
4870static void *
4871event_create(void)
4872{
4873 return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
4874}
4875
4876
4878static int
4879event_wait(void *eventhdl)
4880{
4881 int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
4882 return (res == WAIT_OBJECT_0);
4883}
4884
4885
4887static int
4888event_signal(void *eventhdl)
4889{
4890 return (int)SetEvent((HANDLE)eventhdl);
4891}
4892
4893
4895static void
4896event_destroy(void *eventhdl)
4897{
4898 CloseHandle((HANDLE)eventhdl);
4899}
4900#endif
4901
4902
4903#if defined(GCC_DIAGNOSTIC)
4904/* Enable unused function warning again */
4905#pragma GCC diagnostic pop
4906#endif
4907
4908
4909/* For Windows, change all slashes to backslashes in path names. */
4910static void
4911change_slashes_to_backslashes(char *path)
4912{
4913 int i;
4914
4915 for (i = 0; path[i] != '\0'; i++) {
4916 if (path[i] == '/') {
4917 path[i] = '\\';
4918 }
4919
4920 /* remove double backslash (check i > 0 to preserve UNC paths,
4921 * like \\server\file.txt) */
4922 if ((i > 0) && (path[i] == '\\')) {
4923 while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
4924 (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
4925 }
4926 }
4927 }
4928}
4929
4930
4931static int
4932mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
4933{
4934 int diff;
4935
4936 do {
4937 diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
4938 - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
4939 s1++;
4940 s2++;
4941 } while ((diff == 0) && (s1[-1] != L'\0'));
4942
4943 return diff;
4944}
4945
4946
4947/* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
4948 * wbuf and wbuf_len is a target buffer and its length. */
4949static void
4950path_to_unicode(const struct mg_connection *conn,
4951 const char *path,
4952 wchar_t *wbuf,
4953 size_t wbuf_len)
4954{
4955 char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
4956 wchar_t wbuf2[UTF16_PATH_MAX + 1];
4957 DWORD long_len, err;
4958 int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
4959
4960 mg_strlcpy(buf, path, sizeof(buf));
4961 change_slashes_to_backslashes(buf);
4962
4963 /* Convert to Unicode and back. If doubly-converted string does not
4964 * match the original, something is fishy, reject. */
4965 memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
4966 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
4967 WideCharToMultiByte(
4968 CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
4969 if (strcmp(buf, buf2) != 0) {
4970 wbuf[0] = L'\0';
4971 }
4972
4973 /* Windows file systems are not case sensitive, but you can still use
4974 * uppercase and lowercase letters (on all modern file systems).
4975 * The server can check if the URI uses the same upper/lowercase
4976 * letters an the file system, effectively making Windows servers
4977 * case sensitive (like Linux servers are). It is still not possible
4978 * to use two files with the same name in different cases on Windows
4979 * (like /a and /A) - this would be possible in Linux.
4980 * As a default, Windows is not case sensitive, but the case sensitive
4981 * file name check can be activated by an additional configuration. */
4982 if (conn) {
4983 if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
4984 && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
4985 "yes")) {
4986 /* Use case sensitive compare function */
4987 fcompare = wcscmp;
4988 }
4989 }
4990 (void)conn; /* conn is currently unused */
4991
4992 /* Only accept a full file path, not a Windows short (8.3) path. */
4993 memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
4994 long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
4995 if (long_len == 0) {
4996 err = GetLastError();
4997 if (err == ERROR_FILE_NOT_FOUND) {
4998 /* File does not exist. This is not always a problem here. */
4999 return;
5000 }
5001 }
5002 if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5003 /* Short name is used. */
5004 wbuf[0] = L'\0';
5005 }
5006}
5007
5008
5009#if !defined(NO_FILESYSTEMS)
5010/* Get file information, return 1 if file exists, 0 if not */
5011static int
5012mg_stat(const struct mg_connection *conn,
5013 const char *path,
5014 struct mg_file_stat *filep)
5015{
5016 wchar_t wbuf[UTF16_PATH_MAX];
5017 WIN32_FILE_ATTRIBUTE_DATA info;
5018 time_t creation_time;
5019 size_t len;
5020
5021 if (!filep) {
5022 return 0;
5023 }
5024 memset(filep, 0, sizeof(*filep));
5025
5026 if (mg_path_suspicious(conn, path)) {
5027 return 0;
5028 }
5029
5030 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5031 /* Windows happily opens files with some garbage at the end of file name.
5032 * For example, fopen("a.cgi ", "r") on Windows successfully opens
5033 * "a.cgi", despite one would expect an error back. */
5034 len = strlen(path);
5035 if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
5036 && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
5037 filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5038 filep->last_modified =
5039 SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5040 info.ftLastWriteTime.dwHighDateTime);
5041
5042 /* On Windows, the file creation time can be higher than the
5043 * modification time, e.g. when a file is copied.
5044 * Since the Last-Modified timestamp is used for caching
5045 * it should be based on the most recent timestamp. */
5046 creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5047 info.ftCreationTime.dwHighDateTime);
5048 if (creation_time > filep->last_modified) {
5049 filep->last_modified = creation_time;
5050 }
5051
5052 filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5053 return 1;
5054 }
5055
5056 return 0;
5057}
5058#endif
5059
5060
5061static int
5062mg_remove(const struct mg_connection *conn, const char *path)
5063{
5064 wchar_t wbuf[UTF16_PATH_MAX];
5065 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5066 return DeleteFileW(wbuf) ? 0 : -1;
5067}
5068
5069
5070static int
5071mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
5072{
5073 wchar_t wbuf[UTF16_PATH_MAX];
5074 (void)mode;
5075 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5076 return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5077}
5078
5079
5080/* Create substitutes for POSIX functions in Win32. */
5081
5082#if defined(GCC_DIAGNOSTIC)
5083/* Show no warning in case system functions are not used. */
5084#pragma GCC diagnostic push
5085#pragma GCC diagnostic ignored "-Wunused-function"
5086#endif
5087
5088
5089/* Implementation of POSIX opendir/closedir/readdir for Windows. */
5091static DIR *
5092mg_opendir(const struct mg_connection *conn, const char *name)
5093{
5094 DIR *dir = NULL;
5095 wchar_t wpath[UTF16_PATH_MAX];
5096 DWORD attrs;
5097
5098 if (name == NULL) {
5099 SetLastError(ERROR_BAD_ARGUMENTS);
5100 } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
5101 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5102 } else {
5103 path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
5104 attrs = GetFileAttributesW(wpath);
5105 if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5106 && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5107 (void)wcscat(wpath, L"\\*");
5108 dir->handle = FindFirstFileW(wpath, &dir->info);
5109 dir->result.d_name[0] = '\0';
5110 } else {
5111 mg_free(dir);
5112 dir = NULL;
5113 }
5114 }
5115
5116 return dir;
5117}
5118
5119
5121static int
5122mg_closedir(DIR *dir)
5123{
5124 int result = 0;
5125
5126 if (dir != NULL) {
5127 if (dir->handle != INVALID_HANDLE_VALUE)
5128 result = FindClose(dir->handle) ? 0 : -1;
5129
5130 mg_free(dir);
5131 } else {
5132 result = -1;
5133 SetLastError(ERROR_BAD_ARGUMENTS);
5134 }
5135
5136 return result;
5137}
5138
5139
5141static struct dirent *
5142mg_readdir(DIR *dir)
5143{
5144 struct dirent *result = 0;
5145
5146 if (dir) {
5147 if (dir->handle != INVALID_HANDLE_VALUE) {
5148 result = &dir->result;
5149 (void)WideCharToMultiByte(CP_UTF8,
5150 0,
5151 dir->info.cFileName,
5152 -1,
5153 result->d_name,
5154 sizeof(result->d_name),
5155 NULL,
5156 NULL);
5157
5158 if (!FindNextFileW(dir->handle, &dir->info)) {
5159 (void)FindClose(dir->handle);
5160 dir->handle = INVALID_HANDLE_VALUE;
5161 }
5162
5163 } else {
5164 SetLastError(ERROR_FILE_NOT_FOUND);
5165 }
5166 } else {
5167 SetLastError(ERROR_BAD_ARGUMENTS);
5168 }
5169
5170 return result;
5171}
5172
5173
5174#if !defined(HAVE_POLL)
5175#undef POLLIN
5176#undef POLLPRI
5177#undef POLLOUT
5178#undef POLLERR
5179#define POLLIN (1) /* Data ready - read will not block. */
5180#define POLLPRI (2) /* Priority data ready. */
5181#define POLLOUT (4) /* Send queue not full - write will not block. */
5182#define POLLERR (8) /* Error event */
5183
5185static int
5186poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
5187{
5188 struct timeval tv;
5189 fd_set rset;
5190 fd_set wset;
5191 fd_set eset;
5192 unsigned int i;
5193 int result;
5194 SOCKET maxfd = 0;
5195
5196 memset(&tv, 0, sizeof(tv));
5197 tv.tv_sec = milliseconds / 1000;
5198 tv.tv_usec = (milliseconds % 1000) * 1000;
5199 FD_ZERO(&rset);
5200 FD_ZERO(&wset);
5201 FD_ZERO(&eset);
5202
5203 for (i = 0; i < n; i++) {
5204 if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
5205 if (pfd[i].events & POLLIN) {
5206 FD_SET(pfd[i].fd, &rset);
5207 }
5208 if (pfd[i].events & POLLOUT) {
5209 FD_SET(pfd[i].fd, &wset);
5210 }
5211 /* Check for errors for any FD in the set */
5212 FD_SET(pfd[i].fd, &eset);
5213 }
5214 pfd[i].revents = 0;
5215
5216 if (pfd[i].fd > maxfd) {
5217 maxfd = pfd[i].fd;
5218 }
5219 }
5220
5221 if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
5222 for (i = 0; i < n; i++) {
5223 if (FD_ISSET(pfd[i].fd, &rset)) {
5224 pfd[i].revents |= POLLIN;
5225 }
5226 if (FD_ISSET(pfd[i].fd, &wset)) {
5227 pfd[i].revents |= POLLOUT;
5228 }
5229 if (FD_ISSET(pfd[i].fd, &eset)) {
5230 pfd[i].revents |= POLLERR;
5231 }
5232 }
5233 }
5234
5235 /* We should subtract the time used in select from remaining
5236 * "milliseconds", in particular if called from mg_poll with a
5237 * timeout quantum.
5238 * Unfortunately, the remaining time is not stored in "tv" in all
5239 * implementations, so the result in "tv" must be considered undefined.
5240 * See http://man7.org/linux/man-pages/man2/select.2.html */
5241
5242 return result;
5243}
5244#endif /* HAVE_POLL */
5245
5246
5247#if defined(GCC_DIAGNOSTIC)
5248/* Enable unused function warning again */
5249#pragma GCC diagnostic pop
5250#endif
5251
5252
5253static void
5255 const struct mg_connection *conn /* may be null */,
5256 struct mg_context *ctx /* may be null */)
5257{
5258 (void)conn; /* Unused. */
5259 (void)ctx;
5260
5261 (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5262}
5263
5264
5265int
5267{
5268#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5269 /* Compile-time option to control stack size, e.g.
5270 * -DUSE_STACK_SIZE=16384
5271 */
5272 return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
5273 == ((uintptr_t)(-1L)))
5274 ? -1
5275 : 0);
5276#else
5277 return (
5278 (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
5279 ? -1
5280 : 0);
5281#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5282}
5283
5284
5285/* Start a thread storing the thread context. */
5286static int
5287mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
5288 void *p,
5289 pthread_t *threadidptr)
5290{
5291 uintptr_t uip;
5292 HANDLE threadhandle;
5293 int result = -1;
5294
5295 uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
5296 threadhandle = (HANDLE)uip;
5297 if ((uip != 0) && (threadidptr != NULL)) {
5298 *threadidptr = threadhandle;
5299 result = 0;
5300 }
5301
5302 return result;
5303}
5304
5305
5306/* Wait for a thread to finish. */
5307static int
5308mg_join_thread(pthread_t threadid)
5309{
5310 int result;
5311 DWORD dwevent;
5312
5313 result = -1;
5314 dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5315 if (dwevent == WAIT_FAILED) {
5316 DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
5317 } else {
5318 if (dwevent == WAIT_OBJECT_0) {
5319 CloseHandle(threadid);
5320 result = 0;
5321 }
5322 }
5323
5324 return result;
5325}
5326
5327#if !defined(NO_SSL_DL) && !defined(NO_SSL)
5328/* If SSL is loaded dynamically, dlopen/dlclose is required. */
5329/* Create substitutes for POSIX functions in Win32. */
5330
5331#if defined(GCC_DIAGNOSTIC)
5332/* Show no warning in case system functions are not used. */
5333#pragma GCC diagnostic push
5334#pragma GCC diagnostic ignored "-Wunused-function"
5335#endif
5336
5337
5339static HANDLE
5340dlopen(const char *dll_name, int flags)
5341{
5342 wchar_t wbuf[UTF16_PATH_MAX];
5343 (void)flags;
5344 path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
5345 return LoadLibraryW(wbuf);
5346}
5347
5348
5350static int
5351dlclose(void *handle)
5352{
5353 int result;
5354
5355 if (FreeLibrary((HMODULE)handle) != 0) {
5356 result = 0;
5357 } else {
5358 result = -1;
5359 }
5360
5361 return result;
5362}
5363
5364
5365#if defined(GCC_DIAGNOSTIC)
5366/* Enable unused function warning again */
5367#pragma GCC diagnostic pop
5368#endif
5369
5370#endif
5371
5372
5373#if !defined(NO_CGI)
5374#define SIGKILL (0)
5375
5376
5377static int
5378kill(pid_t pid, int sig_num)
5379{
5380 (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5381 (void)CloseHandle((HANDLE)pid);
5382 return 0;
5383}
5384
5385
5386#if !defined(WNOHANG)
5387#define WNOHANG (1)
5388#endif
5389
5390
5391static pid_t
5392waitpid(pid_t pid, int *status, int flags)
5393{
5394 DWORD timeout = INFINITE;
5395 DWORD waitres;
5396
5397 (void)status; /* Currently not used by any client here */
5398
5399 if ((flags | WNOHANG) == WNOHANG) {
5400 timeout = 0;
5401 }
5402
5403 waitres = WaitForSingleObject((HANDLE)pid, timeout);
5404 if (waitres == WAIT_OBJECT_0) {
5405 return pid;
5406 }
5407 if (waitres == WAIT_TIMEOUT) {
5408 return 0;
5409 }
5410 return (pid_t)-1;
5411}
5412
5413
5414static void
5415trim_trailing_whitespaces(char *s)
5416{
5417 char *e = s + strlen(s);
5418 while ((e > s) && isspace((unsigned char)e[-1])) {
5419 *(--e) = '\0';
5420 }
5421}
5422
5423
5424static pid_t
5425spawn_process(struct mg_connection *conn,
5426 const char *prog,
5427 char *envblk,
5428 char *envp[],
5429 int fdin[2],
5430 int fdout[2],
5431 int fderr[2],
5432 const char *dir,
5433 unsigned char cgi_config_idx)
5434{
5435 HANDLE me;
5436 char *interp;
5437 char *interp_arg = 0;
5438 char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
5439 int truncated;
5441 STARTUPINFOA si;
5442 PROCESS_INFORMATION pi = {0};
5443
5444 (void)envp;
5445
5446 memset(&si, 0, sizeof(si));
5447 si.cb = sizeof(si);
5448
5449 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5450 si.wShowWindow = SW_HIDE;
5451
5452 me = GetCurrentProcess();
5453 DuplicateHandle(me,
5454 (HANDLE)_get_osfhandle(fdin[0]),
5455 me,
5456 &si.hStdInput,
5457 0,
5458 TRUE,
5459 DUPLICATE_SAME_ACCESS);
5460 DuplicateHandle(me,
5461 (HANDLE)_get_osfhandle(fdout[1]),
5462 me,
5463 &si.hStdOutput,
5464 0,
5465 TRUE,
5466 DUPLICATE_SAME_ACCESS);
5467 DuplicateHandle(me,
5468 (HANDLE)_get_osfhandle(fderr[1]),
5469 me,
5470 &si.hStdError,
5471 0,
5472 TRUE,
5473 DUPLICATE_SAME_ACCESS);
5474
5475 /* Mark handles that should not be inherited. See
5476 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
5477 */
5478 SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5479 HANDLE_FLAG_INHERIT,
5480 0);
5481 SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5482 HANDLE_FLAG_INHERIT,
5483 0);
5484 SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5485 HANDLE_FLAG_INHERIT,
5486 0);
5487
5488 /* First check, if there is a CGI interpreter configured for all CGI
5489 * scripts. */
5490 interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
5491 if (interp != NULL) {
5492 /* If there is a configured interpreter, check for additional arguments
5493 */
5494 interp_arg =
5495 conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
5496 } else {
5497 /* Otherwise, the interpreter must be stated in the first line of the
5498 * CGI script file, after a #! (shebang) mark. */
5499 buf[0] = buf[1] = '\0';
5500
5501 /* Get the full script path */
5503 conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
5504
5505 if (truncated) {
5506 pi.hProcess = (pid_t)-1;
5507 goto spawn_cleanup;
5508 }
5509
5510 /* Open the script file, to read the first line */
5511 if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
5512
5513 /* Read the first line of the script into the buffer */
5514 mg_fgets(buf, sizeof(buf), &file);
5515 (void)mg_fclose(&file.access); /* ignore error on read only file */
5516 buf[sizeof(buf) - 1] = '\0';
5517 }
5518
5519 if ((buf[0] == '#') && (buf[1] == '!')) {
5520 trim_trailing_whitespaces(buf + 2);
5521 } else {
5522 buf[2] = '\0';
5523 }
5524 interp = buf + 2;
5525 }
5526
5527 GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
5528
5529 if (interp[0] != '\0') {
5530 /* This is an interpreted script file. We must call the interpreter. */
5531 if ((interp_arg != 0) && (interp_arg[0] != 0)) {
5532 mg_snprintf(conn,
5533 &truncated,
5534 cmdline,
5535 sizeof(cmdline),
5536 "\"%s\" %s \"%s\\%s\"",
5537 interp,
5538 interp_arg,
5539 full_dir,
5540 prog);
5541 } else {
5542 mg_snprintf(conn,
5543 &truncated,
5544 cmdline,
5545 sizeof(cmdline),
5546 "\"%s\" \"%s\\%s\"",
5547 interp,
5548 full_dir,
5549 prog);
5550 }
5551 } else {
5552 /* This is (probably) a compiled program. We call it directly. */
5553 mg_snprintf(conn,
5554 &truncated,
5555 cmdline,
5556 sizeof(cmdline),
5557 "\"%s\\%s\"",
5558 full_dir,
5559 prog);
5560 }
5561
5562 if (truncated) {
5563 pi.hProcess = (pid_t)-1;
5564 goto spawn_cleanup;
5565 }
5566
5567 DEBUG_TRACE("Running [%s]", cmdline);
5568 if (CreateProcessA(NULL,
5569 cmdline,
5570 NULL,
5571 NULL,
5572 TRUE,
5573 CREATE_NEW_PROCESS_GROUP,
5574 envblk,
5575 NULL,
5576 &si,
5577 &pi)
5578 == 0) {
5580 conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
5581 pi.hProcess = (pid_t)-1;
5582 /* goto spawn_cleanup; */
5583 }
5584
5585spawn_cleanup:
5586 (void)CloseHandle(si.hStdOutput);
5587 (void)CloseHandle(si.hStdError);
5588 (void)CloseHandle(si.hStdInput);
5589 if (pi.hThread != NULL) {
5590 (void)CloseHandle(pi.hThread);
5591 }
5592
5593 return (pid_t)pi.hProcess;
5594}
5595#endif /* !NO_CGI */
5596
5597
5598static int
5600{
5601 unsigned long non_blocking = 0;
5602 return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5603}
5604
5605
5606static int
5608{
5609 unsigned long non_blocking = 1;
5610 return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5611}
5612
5613
5614#else
5615
5616
5617#if !defined(NO_FILESYSTEMS)
5618static int
5619mg_stat(const struct mg_connection *conn,
5620 const char *path,
5621 struct mg_file_stat *filep)
5622{
5623 struct stat st;
5624 if (!filep) {
5625 return 0;
5626 }
5627 memset(filep, 0, sizeof(*filep));
5628
5629 if (mg_path_suspicious(conn, path)) {
5630 return 0;
5631 }
5632
5633 if (0 == stat(path, &st)) {
5634 filep->size = (uint64_t)(st.st_size);
5635 filep->last_modified = st.st_mtime;
5636 filep->is_directory = S_ISDIR(st.st_mode);
5637 return 1;
5638 }
5639
5640 return 0;
5641}
5642#endif /* NO_FILESYSTEMS */
5643
5644
5645static void
5647 const struct mg_connection *conn /* may be null */,
5648 struct mg_context *ctx /* may be null */)
5649{
5650#if defined(__ZEPHYR__)
5651 (void)fd;
5652 (void)conn;
5653 (void)ctx;
5654#else
5655 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5656 if (conn || ctx) {
5657 struct mg_connection fc;
5658 mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
5659 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5660 __func__,
5661 strerror(ERRNO));
5662 }
5663 }
5664#endif
5665}
5666
5667
5668int
5670{
5671 pthread_t thread_id;
5672 pthread_attr_t attr;
5673 int result;
5674
5675 (void)pthread_attr_init(&attr);
5676 (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
5677
5678#if defined(__ZEPHYR__)
5679 pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
5680#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5681 /* Compile-time option to control stack size,
5682 * e.g. -DUSE_STACK_SIZE=16384 */
5683 (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5684#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5685
5686 result = pthread_create(&thread_id, &attr, func, param);
5687 pthread_attr_destroy(&attr);
5688
5689 return result;
5690}
5691
5692
5693/* Start a thread storing the thread context. */
5694static int
5696 void *param,
5697 pthread_t *threadidptr)
5698{
5699 pthread_t thread_id;
5700 pthread_attr_t attr;
5701 int result;
5702
5703 (void)pthread_attr_init(&attr);
5704
5705#if defined(__ZEPHYR__)
5706 pthread_attr_setstack(&attr,
5707 &civetweb_worker_stacks[zephyr_worker_stack_index++],
5708 ZEPHYR_STACK_SIZE);
5709#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5710 /* Compile-time option to control stack size,
5711 * e.g. -DUSE_STACK_SIZE=16384 */
5712 (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5713#endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
5714
5715 result = pthread_create(&thread_id, &attr, func, param);
5716 pthread_attr_destroy(&attr);
5717 if ((result == 0) && (threadidptr != NULL)) {
5718 *threadidptr = thread_id;
5719 }
5720 return result;
5721}
5722
5723
5724/* Wait for a thread to finish. */
5725static int
5726mg_join_thread(pthread_t threadid)
5727{
5728 int result;
5729
5730 result = pthread_join(threadid, NULL);
5731 return result;
5732}
5733
5734
5735#if !defined(NO_CGI)
5736static pid_t
5738 const char *prog,
5739 char *envblk,
5740 char *envp[],
5741 int fdin[2],
5742 int fdout[2],
5743 int fderr[2],
5744 const char *dir,
5745 unsigned char cgi_config_idx)
5746{
5747 pid_t pid;
5748 const char *interp;
5749
5750 (void)envblk;
5751
5752 if ((pid = fork()) == -1) {
5753 /* Parent */
5754 mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
5755 } else if (pid != 0) {
5756 /* Make sure children close parent-side descriptors.
5757 * The caller will close the child-side immediately. */
5758 set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
5759 set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
5760 set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
5761 } else {
5762 /* Child */
5763 if (chdir(dir) != 0) {
5765 conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
5766 } else if (dup2(fdin[0], 0) == -1) {
5767 mg_cry_internal(conn,
5768 "%s: dup2(%d, 0): %s",
5769 __func__,
5770 fdin[0],
5771 strerror(ERRNO));
5772 } else if (dup2(fdout[1], 1) == -1) {
5773 mg_cry_internal(conn,
5774 "%s: dup2(%d, 1): %s",
5775 __func__,
5776 fdout[1],
5777 strerror(ERRNO));
5778 } else if (dup2(fderr[1], 2) == -1) {
5779 mg_cry_internal(conn,
5780 "%s: dup2(%d, 2): %s",
5781 __func__,
5782 fderr[1],
5783 strerror(ERRNO));
5784 } else {
5785 struct sigaction sa;
5786
5787 /* Keep stderr and stdout in two different pipes.
5788 * Stdout will be sent back to the client,
5789 * stderr should go into a server error log. */
5790 (void)close(fdin[0]);
5791 (void)close(fdout[1]);
5792 (void)close(fderr[1]);
5793
5794 /* Close write end fdin and read end fdout and fderr */
5795 (void)close(fdin[1]);
5796 (void)close(fdout[0]);
5797 (void)close(fderr[0]);
5798
5799 /* After exec, all signal handlers are restored to their default
5800 * values, with one exception of SIGCHLD. According to
5801 * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
5802 * will leave unchanged after exec if it was set to be ignored.
5803 * Restore it to default action. */
5804 memset(&sa, 0, sizeof(sa));
5805 sa.sa_handler = SIG_DFL;
5806 sigaction(SIGCHLD, &sa, NULL);
5807
5808 interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
5809 if (interp == NULL) {
5810 /* no interpreter configured, call the programm directly */
5811 (void)execle(prog, prog, NULL, envp);
5812 mg_cry_internal(conn,
5813 "%s: execle(%s): %s",
5814 __func__,
5815 prog,
5816 strerror(ERRNO));
5817 } else {
5818 /* call the configured interpreter */
5819 const char *interp_args =
5820 conn->dom_ctx
5821 ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
5822
5823 if ((interp_args != NULL) && (interp_args[0] != 0)) {
5824 (void)execle(interp, interp, interp_args, prog, NULL, envp);
5825 } else {
5826 (void)execle(interp, interp, prog, NULL, envp);
5827 }
5828 mg_cry_internal(conn,
5829 "%s: execle(%s %s): %s",
5830 __func__,
5831 interp,
5832 prog,
5833 strerror(ERRNO));
5834 }
5835 }
5836 exit(EXIT_FAILURE);
5837 }
5838
5839 return pid;
5840}
5841#endif /* !NO_CGI */
5842
5843
5844static int
5846{
5847 int flags = fcntl(sock, F_GETFL, 0);
5848 if (flags < 0) {
5849 return -1;
5850 }
5851
5852 if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
5853 return -1;
5854 }
5855 return 0;
5856}
5857
5858static int
5860{
5861 int flags = fcntl(sock, F_GETFL, 0);
5862 if (flags < 0) {
5863 return -1;
5864 }
5865
5866 if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
5867 return -1;
5868 }
5869 return 0;
5870}
5871#endif /* _WIN32 / else */
5872
5873/* End of initial operating system specific define block. */
5874
5875
5876/* Get a random number (independent of C rand function) */
5877static uint64_t
5879{
5880 static uint64_t lfsr = 0; /* Linear feedback shift register */
5881 static uint64_t lcg = 0; /* Linear congruential generator */
5882 uint64_t now = mg_get_current_time_ns();
5883
5884 if (lfsr == 0) {
5885 /* lfsr will be only 0 if has not been initialized,
5886 * so this code is called only once. */
5887 lfsr = mg_get_current_time_ns();
5888 lcg = mg_get_current_time_ns();
5889 } else {
5890 /* Get the next step of both random number generators. */
5891 lfsr = (lfsr >> 1)
5892 | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
5893 << 63);
5894 lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
5895 }
5896
5897 /* Combining two pseudo-random number generators and a high resolution
5898 * part
5899 * of the current server time will make it hard (impossible?) to guess
5900 * the
5901 * next number. */
5902 return (lfsr ^ lcg ^ now);
5903}
5904
5905
5906static int
5907mg_poll(struct mg_pollfd *pfd,
5908 unsigned int n,
5909 int milliseconds,
5910 const stop_flag_t *stop_flag)
5911{
5912 /* Call poll, but only for a maximum time of a few seconds.
5913 * This will allow to stop the server after some seconds, instead
5914 * of having to wait for a long socket timeout. */
5915 int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
5916
5917 int check_pollerr = 0;
5918 if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
5919 /* If we wait for only one file descriptor, wait on error as well */
5920 pfd[0].events |= POLLERR;
5921 check_pollerr = 1;
5922 }
5923
5924 do {
5925 int result;
5926
5927 if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
5928 /* Shut down signal */
5929 return -2;
5930 }
5931
5932 if ((milliseconds >= 0) && (milliseconds < ms_now)) {
5933 ms_now = milliseconds;
5934 }
5935
5936 result = poll(pfd, n, ms_now);
5937 if (result != 0) {
5938 /* Poll returned either success (1) or error (-1).
5939 * Forward both to the caller. */
5940 if ((check_pollerr)
5941 && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
5942 == POLLERR)) {
5943 /* One and only file descriptor returned error */
5944 return -1;
5945 }
5946 return result;
5947 }
5948
5949 /* Poll returned timeout (0). */
5950 if (milliseconds > 0) {
5951 milliseconds -= ms_now;
5952 }
5953
5954 } while (milliseconds > 0);
5955
5956 /* timeout: return 0 */
5957 return 0;
5958}
5959
5960
5961/* Write data to the IO channel - opened file descriptor, socket or SSL
5962 * descriptor.
5963 * Return value:
5964 * >=0 .. number of bytes successfully written
5965 * -1 .. timeout
5966 * -2 .. error
5967 */
5968static int
5970 FILE *fp,
5971 SOCKET sock,
5972 SSL *ssl,
5973 const char *buf,
5974 int len,
5975 double timeout)
5976{
5977 uint64_t start = 0, now = 0, timeout_ns = 0;
5978 int n, err;
5979 unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
5980
5981#if defined(_WIN32)
5982 typedef int len_t;
5983#else
5984 typedef size_t len_t;
5985#endif
5986
5987 if (timeout > 0) {
5988 now = mg_get_current_time_ns();
5989 start = now;
5990 timeout_ns = (uint64_t)(timeout * 1.0E9);
5991 }
5992
5993 if (ctx == NULL) {
5994 return -2;
5995 }
5996
5997#if defined(NO_SSL) && !defined(USE_MBEDTLS)
5998 if (ssl) {
5999 return -2;
6000 }
6001#endif
6002
6003 /* Try to read until it succeeds, fails, times out, or the server
6004 * shuts down. */
6005 for (;;) {
6006
6007#if defined(USE_MBEDTLS)
6008 if (ssl != NULL) {
6009 n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
6010 if (n <= 0) {
6011 if ((n == MBEDTLS_ERR_SSL_WANT_READ)
6012 || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
6013 || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6014 n = 0;
6015 } else {
6016 fprintf(stderr, "SSL write failed, error %d\n", n);
6017 return -2;
6018 }
6019 } else {
6020 err = 0;
6021 }
6022 } else
6023#elif !defined(NO_SSL)
6024 if (ssl != NULL) {
6025 ERR_clear_error();
6026 n = SSL_write(ssl, buf, len);
6027 if (n <= 0) {
6028 err = SSL_get_error(ssl, n);
6029 if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
6030 err = ERRNO;
6031 } else if ((err == SSL_ERROR_WANT_READ)
6032 || (err == SSL_ERROR_WANT_WRITE)) {
6033 n = 0;
6034 } else {
6035 DEBUG_TRACE("SSL_write() failed, error %d", err);
6036 ERR_clear_error();
6037 return -2;
6038 }
6039 ERR_clear_error();
6040 } else {
6041 err = 0;
6042 }
6043 } else
6044#endif
6045
6046 if (fp != NULL) {
6047 n = (int)fwrite(buf, 1, (size_t)len, fp);
6048 if (ferror(fp)) {
6049 n = -1;
6050 err = ERRNO;
6051 } else {
6052 err = 0;
6053 }
6054 } else {
6055 n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
6056 err = (n < 0) ? ERRNO : 0;
6057#if defined(_WIN32)
6058 if (err == WSAEWOULDBLOCK) {
6059 err = 0;
6060 n = 0;
6061 }
6062#else
6063 if (ERROR_TRY_AGAIN(err)) {
6064 err = 0;
6065 n = 0;
6066 }
6067#endif
6068 if (n < 0) {
6069 /* shutdown of the socket at client side */
6070 return -2;
6071 }
6072 }
6073
6074 if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6075 return -2;
6076 }
6077
6078 if ((n > 0) || ((n == 0) && (len == 0))) {
6079 /* some data has been read, or no data was requested */
6080 return n;
6081 }
6082 if (n < 0) {
6083 /* socket error - check errno */
6084 DEBUG_TRACE("send() failed, error %d", err);
6085
6086 /* TODO (mid): error handling depending on the error code.
6087 * These codes are different between Windows and Linux.
6088 * Currently there is no problem with failing send calls,
6089 * if there is a reproducible situation, it should be
6090 * investigated in detail.
6091 */
6092 return -2;
6093 }
6094
6095 /* Only in case n=0 (timeout), repeat calling the write function */
6096
6097 /* If send failed, wait before retry */
6098 if (fp != NULL) {
6099 /* For files, just wait a fixed time.
6100 * Maybe it helps, maybe not. */
6101 mg_sleep(5);
6102 } else {
6103 /* For sockets, wait for the socket using poll */
6104 struct mg_pollfd pfd[1];
6105 int pollres;
6106
6107 pfd[0].fd = sock;
6108 pfd[0].events = POLLOUT;
6109 pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
6110 if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6111 return -2;
6112 }
6113 if (pollres > 0) {
6114 continue;
6115 }
6116 }
6117
6118 if (timeout > 0) {
6119 now = mg_get_current_time_ns();
6120 if ((now - start) > timeout_ns) {
6121 /* Timeout */
6122 break;
6123 }
6124 }
6125 }
6126
6127 (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
6128 used */
6129
6130 return -1;
6131}
6132
6133
6134static int
6136 FILE *fp,
6137 SOCKET sock,
6138 SSL *ssl,
6139 const char *buf,
6140 int len)
6141{
6142 double timeout = -1.0;
6143 int n, nwritten = 0;
6144
6145 if (ctx == NULL) {
6146 return -1;
6147 }
6148
6149 if (ctx->dd.config[REQUEST_TIMEOUT]) {
6150 timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
6151 }
6152 if (timeout <= 0.0) {
6153 timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
6154 / 1000.0;
6155 }
6156
6157 while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6158 n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
6159 if (n < 0) {
6160 if (nwritten == 0) {
6161 nwritten = -1; /* Propagate the error */
6162 }
6163 break;
6164 } else if (n == 0) {
6165 break; /* No more data to write */
6166 } else {
6167 nwritten += n;
6168 len -= n;
6169 }
6170 }
6171
6172 return nwritten;
6173}
6174
6175
6176/* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
6177 * Return value:
6178 * >=0 .. number of bytes successfully read
6179 * -1 .. timeout
6180 * -2 .. error
6181 */
6182static int
6183pull_inner(FILE *fp,
6184 struct mg_connection *conn,
6185 char *buf,
6186 int len,
6187 double timeout)
6188{
6189 int nread, err = 0;
6190
6191#if defined(_WIN32)
6192 typedef int len_t;
6193#else
6194 typedef size_t len_t;
6195#endif
6196
6197 /* We need an additional wait loop around this, because in some cases
6198 * with TLSwe may get data from the socket but not from SSL_read.
6199 * In this case we need to repeat at least once.
6200 */
6201
6202 if (fp != NULL) {
6203 /* Use read() instead of fread(), because if we're reading from the
6204 * CGI pipe, fread() may block until IO buffer is filled up. We
6205 * cannot afford to block and must pass all read bytes immediately
6206 * to the client. */
6207 nread = (int)read(fileno(fp), buf, (size_t)len);
6208
6209 err = (nread < 0) ? ERRNO : 0;
6210 if ((nread == 0) && (len > 0)) {
6211 /* Should get data, but got EOL */
6212 return -2;
6213 }
6214
6215#if defined(USE_MBEDTLS)
6216 } else if (conn->ssl != NULL) {
6217 struct mg_pollfd pfd[1];
6218 int to_read;
6219 int pollres;
6220
6221 to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
6222
6223 if (to_read > 0) {
6224 /* We already know there is no more data buffered in conn->buf
6225 * but there is more available in the SSL layer. So don't poll
6226 * conn->client.sock yet. */
6227
6228 pollres = 1;
6229 if (to_read > len)
6230 to_read = len;
6231 } else {
6232 pfd[0].fd = conn->client.sock;
6233 pfd[0].events = POLLIN;
6234
6235 to_read = len;
6236
6237 pollres = mg_poll(pfd,
6238 1,
6239 (int)(timeout * 1000.0),
6240 &(conn->phys_ctx->stop_flag));
6241
6242 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6243 return -2;
6244 }
6245 }
6246
6247 if (pollres > 0) {
6248 nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
6249 if (nread <= 0) {
6250 if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
6251 || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
6252 || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6253 nread = 0;
6254 } else {
6255 fprintf(stderr, "SSL read failed, error %d\n", nread);
6256 return -2;
6257 }
6258 } else {
6259 err = 0;
6260 }
6261
6262 } else if (pollres < 0) {
6263 /* Error */
6264 return -2;
6265 } else {
6266 /* pollres = 0 means timeout */
6267 nread = 0;
6268 }
6269
6270#elif !defined(NO_SSL)
6271 } else if (conn->ssl != NULL) {
6272 int ssl_pending;
6273 struct mg_pollfd pfd[1];
6274 int pollres;
6275
6276 if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
6277 /* We already know there is no more data buffered in conn->buf
6278 * but there is more available in the SSL layer. So don't poll
6279 * conn->client.sock yet. */
6280 if (ssl_pending > len) {
6281 ssl_pending = len;
6282 }
6283 pollres = 1;
6284 } else {
6285 pfd[0].fd = conn->client.sock;
6286 pfd[0].events = POLLIN;
6287 pollres = mg_poll(pfd,
6288 1,
6289 (int)(timeout * 1000.0),
6290 &(conn->phys_ctx->stop_flag));
6291 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6292 return -2;
6293 }
6294 }
6295 if (pollres > 0) {
6296 ERR_clear_error();
6297 nread =
6298 SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
6299 if (nread <= 0) {
6300 err = SSL_get_error(conn->ssl, nread);
6301 if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
6302 err = ERRNO;
6303 } else if ((err == SSL_ERROR_WANT_READ)
6304 || (err == SSL_ERROR_WANT_WRITE)) {
6305 nread = 0;
6306 } else {
6307 /* All errors should return -2 */
6308 DEBUG_TRACE("SSL_read() failed, error %d", err);
6309 ERR_clear_error();
6310 return -2;
6311 }
6312 ERR_clear_error();
6313 } else {
6314 err = 0;
6315 }
6316 } else if (pollres < 0) {
6317 /* Error */
6318 return -2;
6319 } else {
6320 /* pollres = 0 means timeout */
6321 nread = 0;
6322 }
6323#endif
6324
6325 } else {
6326 struct mg_pollfd pfd[1];
6327 int pollres;
6328
6329 pfd[0].fd = conn->client.sock;
6330 pfd[0].events = POLLIN;
6331 pollres = mg_poll(pfd,
6332 1,
6333 (int)(timeout * 1000.0),
6334 &(conn->phys_ctx->stop_flag));
6335 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6336 return -2;
6337 }
6338 if (pollres > 0) {
6339 nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
6340 err = (nread < 0) ? ERRNO : 0;
6341 if (nread <= 0) {
6342 /* shutdown of the socket at client side */
6343 return -2;
6344 }
6345 } else if (pollres < 0) {
6346 /* error callint poll */
6347 return -2;
6348 } else {
6349 /* pollres = 0 means timeout */
6350 nread = 0;
6351 }
6352 }
6353
6354 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6355 return -2;
6356 }
6357
6358 if ((nread > 0) || ((nread == 0) && (len == 0))) {
6359 /* some data has been read, or no data was requested */
6360 return nread;
6361 }
6362
6363 if (nread < 0) {
6364 /* socket error - check errno */
6365#if defined(_WIN32)
6366 if (err == WSAEWOULDBLOCK) {
6367 /* TODO (low): check if this is still required */
6368 /* standard case if called from close_socket_gracefully */
6369 return -2;
6370 } else if (err == WSAETIMEDOUT) {
6371 /* TODO (low): check if this is still required */
6372 /* timeout is handled by the while loop */
6373 return 0;
6374 } else if (err == WSAECONNABORTED) {
6375 /* See https://www.chilkatsoft.com/p/p_299.asp */
6376 return -2;
6377 } else {
6378 DEBUG_TRACE("recv() failed, error %d", err);
6379 return -2;
6380 }
6381#else
6382 /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
6383 * if the timeout is reached and if the socket was set to non-
6384 * blocking in close_socket_gracefully, so we can not distinguish
6385 * here. We have to wait for the timeout in both cases for now.
6386 */
6387 if (ERROR_TRY_AGAIN(err)) {
6388 /* TODO (low): check if this is still required */
6389 /* EAGAIN/EWOULDBLOCK:
6390 * standard case if called from close_socket_gracefully
6391 * => should return -1 */
6392 /* or timeout occurred
6393 * => the code must stay in the while loop */
6394
6395 /* EINTR can be generated on a socket with a timeout set even
6396 * when SA_RESTART is effective for all relevant signals
6397 * (see signal(7)).
6398 * => stay in the while loop */
6399 } else {
6400 DEBUG_TRACE("recv() failed, error %d", err);
6401 return -2;
6402 }
6403#endif
6404 }
6405
6406 /* Timeout occurred, but no data available. */
6407 return -1;
6408}
6409
6410
6411static int
6412pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
6413{
6414 int n, nread = 0;
6415 double timeout = -1.0;
6416 uint64_t start_time = 0, now = 0, timeout_ns = 0;
6417
6418 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
6419 timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
6420 }
6421 if (timeout <= 0.0) {
6422 timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
6423 / 1000.0;
6424 }
6425 start_time = mg_get_current_time_ns();
6426 timeout_ns = (uint64_t)(timeout * 1.0E9);
6427
6428 while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6429 n = pull_inner(fp, conn, buf + nread, len, timeout);
6430 if (n == -2) {
6431 if (nread == 0) {
6432 nread = -1; /* Propagate the error */
6433 }
6434 break;
6435 } else if (n == -1) {
6436 /* timeout */
6437 if (timeout >= 0.0) {
6438 now = mg_get_current_time_ns();
6439 if ((now - start_time) <= timeout_ns) {
6440 continue;
6441 }
6442 }
6443 break;
6444 } else if (n == 0) {
6445 break; /* No more data to read */
6446 } else {
6447 nread += n;
6448 len -= n;
6449 }
6450 }
6451
6452 return nread;
6453}
6454
6455
6456static void
6458{
6459 char buf[MG_BUF_LEN];
6460
6461 while (mg_read(conn, buf, sizeof(buf)) > 0)
6462 ;
6463}
6464
6465
6466static int
6467mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
6468{
6469 int64_t content_len, n, buffered_len, nread;
6470 int64_t len64 =
6471 (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
6472 * int, we may not read more
6473 * bytes */
6474 const char *body;
6475
6476 if (conn == NULL) {
6477 return 0;
6478 }
6479
6480 /* If Content-Length is not set for a response with body data,
6481 * we do not know in advance how much data should be read. */
6482 content_len = conn->content_len;
6483 if (content_len < 0) {
6484 /* The body data is completed when the connection is closed. */
6485 content_len = INT64_MAX;
6486 }
6487
6488 nread = 0;
6489 if (conn->consumed_content < content_len) {
6490 /* Adjust number of bytes to read. */
6491 int64_t left_to_read = content_len - conn->consumed_content;
6492 if (left_to_read < len64) {
6493 /* Do not read more than the total content length of the
6494 * request.
6495 */
6496 len64 = left_to_read;
6497 }
6498
6499 /* Return buffered data */
6500 buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
6501 - conn->consumed_content;
6502 if (buffered_len > 0) {
6503 if (len64 < buffered_len) {
6504 buffered_len = len64;
6505 }
6506 body = conn->buf + conn->request_len + conn->consumed_content;
6507 memcpy(buf, body, (size_t)buffered_len);
6508 len64 -= buffered_len;
6509 conn->consumed_content += buffered_len;
6510 nread += buffered_len;
6511 buf = (char *)buf + buffered_len;
6512 }
6513
6514 /* We have returned all buffered data. Read new data from the remote
6515 * socket.
6516 */
6517 if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
6518 conn->consumed_content += n;
6519 nread += n;
6520 } else {
6521 nread = ((nread > 0) ? nread : n);
6522 }
6523 }
6524 return (int)nread;
6525}
6526
6527
6528/* Forward declarations */
6529static void handle_request(struct mg_connection *);
6530static void log_access(const struct mg_connection *);
6531
6532
6533/* Handle request, update statistics and call access log */
6534static void
6536{
6537#if defined(USE_SERVER_STATS)
6538 struct timespec tnow;
6539 conn->conn_state = 4; /* processing */
6540#endif
6541
6542 handle_request(conn);
6543
6544
6545#if defined(USE_SERVER_STATS)
6546 conn->conn_state = 5; /* processed */
6547
6548 clock_gettime(CLOCK_MONOTONIC, &tnow);
6549 conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
6550
6551 mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
6552 mg_atomic_add64(&(conn->phys_ctx->total_data_written),
6553 conn->num_bytes_sent);
6554#endif
6555
6556 DEBUG_TRACE("%s", "handle_request done");
6557
6558 if (conn->phys_ctx->callbacks.end_request != NULL) {
6559 conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
6560 DEBUG_TRACE("%s", "end_request callback done");
6561 }
6562 log_access(conn);
6563}
6564
6565
6566#if defined(USE_HTTP2)
6567#if defined(NO_SSL)
6568#error "HTTP2 requires ALPN, APLN requires SSL/TLS"
6569#endif
6570#define USE_ALPN
6571#include "mod_http2.inl"
6572/* Not supported with HTTP/2 */
6573#define HTTP1_only \
6574 { \
6575 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
6576 http2_must_use_http1(conn); \
6577 return; \
6578 } \
6579 }
6580#else
6581#define HTTP1_only
6582#endif
6583
6584
6585int
6586mg_read(struct mg_connection *conn, void *buf, size_t len)
6587{
6588 if (len > INT_MAX) {
6589 len = INT_MAX;
6590 }
6591
6592 if (conn == NULL) {
6593 return 0;
6594 }
6595
6596 if (conn->is_chunked) {
6597 size_t all_read = 0;
6598
6599 while (len > 0) {
6600 if (conn->is_chunked >= 3) {
6601 /* No more data left to read */
6602 return 0;
6603 }
6604 if (conn->is_chunked != 1) {
6605 /* Has error */
6606 return -1;
6607 }
6608
6609 if (conn->consumed_content != conn->content_len) {
6610 /* copy from the current chunk */
6611 int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
6612
6613 if (read_ret < 1) {
6614 /* read error */
6615 conn->is_chunked = 2;
6616 return -1;
6617 }
6618
6619 all_read += (size_t)read_ret;
6620 len -= (size_t)read_ret;
6621
6622 if (conn->consumed_content == conn->content_len) {
6623 /* Add data bytes in the current chunk have been read,
6624 * so we are expecting \r\n now. */
6625 char x[2];
6626 conn->content_len += 2;
6627 if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
6628 || (x[1] != '\n')) {
6629 /* Protocol violation */
6630 conn->is_chunked = 2;
6631 return -1;
6632 }
6633 }
6634
6635 } else {
6636 /* fetch a new chunk */
6637 size_t i;
6638 char lenbuf[64];
6639 char *end = NULL;
6640 unsigned long chunkSize = 0;
6641
6642 for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
6643 conn->content_len++;
6644 if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
6645 lenbuf[i] = 0;
6646 }
6647 if ((i > 0) && (lenbuf[i] == '\r')
6648 && (lenbuf[i - 1] != '\r')) {
6649 continue;
6650 }
6651 if ((i > 1) && (lenbuf[i] == '\n')
6652 && (lenbuf[i - 1] == '\r')) {
6653 lenbuf[i + 1] = 0;
6654 chunkSize = strtoul(lenbuf, &end, 16);
6655 if (chunkSize == 0) {
6656 /* regular end of content */
6657 conn->is_chunked = 3;
6658 }
6659 break;
6660 }
6661 if (!isxdigit((unsigned char)lenbuf[i])) {
6662 /* illegal character for chunk length */
6663 conn->is_chunked = 2;
6664 return -1;
6665 }
6666 }
6667 if ((end == NULL) || (*end != '\r')) {
6668 /* chunksize not set correctly */
6669 conn->is_chunked = 2;
6670 return -1;
6671 }
6672 if (chunkSize == 0) {
6673 /* try discarding trailer for keep-alive */
6674 conn->content_len += 2;
6675 if ((mg_read_inner(conn, lenbuf, 2) == 2)
6676 && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
6677 conn->is_chunked = 4;
6678 }
6679 break;
6680 }
6681
6682 /* append a new chunk */
6683 conn->content_len += (int64_t)chunkSize;
6684 }
6685 }
6686
6687 return (int)all_read;
6688 }
6689 return mg_read_inner(conn, buf, len);
6690}
6691
6692
6693int
6694mg_write(struct mg_connection *conn, const void *buf, size_t len)
6695{
6696 time_t now;
6697 int n, total, allowed;
6698
6699 if (conn == NULL) {
6700 return 0;
6701 }
6702 if (len > INT_MAX) {
6703 return -1;
6704 }
6705
6706 /* Mark connection as "data sent" */
6707 conn->request_state = 10;
6708#if defined(USE_HTTP2)
6709 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
6710 http2_data_frame_head(conn, len, 0);
6711 }
6712#endif
6713
6714 if (conn->throttle > 0) {
6715 if ((now = time(NULL)) != conn->last_throttle_time) {
6716 conn->last_throttle_time = now;
6717 conn->last_throttle_bytes = 0;
6718 }
6719 allowed = conn->throttle - conn->last_throttle_bytes;
6720 if (allowed > (int)len) {
6721 allowed = (int)len;
6722 }
6723
6724 total = push_all(conn->phys_ctx,
6725 NULL,
6726 conn->client.sock,
6727 conn->ssl,
6728 (const char *)buf,
6729 allowed);
6730
6731 if (total == allowed) {
6732
6733 buf = (const char *)buf + total;
6734 conn->last_throttle_bytes += total;
6735 while ((total < (int)len)
6736 && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6737 allowed = (conn->throttle > ((int)len - total))
6738 ? (int)len - total
6739 : conn->throttle;
6740
6741 n = push_all(conn->phys_ctx,
6742 NULL,
6743 conn->client.sock,
6744 conn->ssl,
6745 (const char *)buf,
6746 allowed);
6747
6748 if (n != allowed) {
6749 break;
6750 }
6751 sleep(1);
6752 conn->last_throttle_bytes = allowed;
6753 conn->last_throttle_time = time(NULL);
6754 buf = (const char *)buf + n;
6755 total += n;
6756 }
6757 }
6758 } else {
6759 total = push_all(conn->phys_ctx,
6760 NULL,
6761 conn->client.sock,
6762 conn->ssl,
6763 (const char *)buf,
6764 (int)len);
6765 }
6766 if (total > 0) {
6767 conn->num_bytes_sent += total;
6768 }
6769 return total;
6770}
6771
6772
6773/* Send a chunk, if "Transfer-Encoding: chunked" is used */
6774int
6776 const char *chunk,
6777 unsigned int chunk_len)
6778{
6779 char lenbuf[16];
6780 size_t lenbuf_len;
6781 int ret;
6782 int t;
6783
6784 /* First store the length information in a text buffer. */
6785 sprintf(lenbuf, "%x\r\n", chunk_len);
6786 lenbuf_len = strlen(lenbuf);
6787
6788 /* Then send length information, chunk and terminating \r\n. */
6789 ret = mg_write(conn, lenbuf, lenbuf_len);
6790 if (ret != (int)lenbuf_len) {
6791 return -1;
6792 }
6793 t = ret;
6794
6795 ret = mg_write(conn, chunk, chunk_len);
6796 if (ret != (int)chunk_len) {
6797 return -1;
6798 }
6799 t += ret;
6800
6801 ret = mg_write(conn, "\r\n", 2);
6802 if (ret != 2) {
6803 return -1;
6804 }
6805 t += ret;
6806
6807 return t;
6808}
6809
6810
6811#if defined(GCC_DIAGNOSTIC)
6812/* This block forwards format strings to printf implementations,
6813 * so we need to disable the format-nonliteral warning. */
6814#pragma GCC diagnostic push
6815#pragma GCC diagnostic ignored "-Wformat-nonliteral"
6816#endif
6817
6818
6819/* Alternative alloc_vprintf() for non-compliant C runtimes */
6820static int
6821alloc_vprintf2(char **buf, const char *fmt, va_list ap)
6822{
6823 va_list ap_copy;
6824 size_t size = MG_BUF_LEN / 4;
6825 int len = -1;
6826
6827 *buf = NULL;
6828 while (len < 0) {
6829 if (*buf) {
6830 mg_free(*buf);
6831 }
6832
6833 size *= 4;
6834 *buf = (char *)mg_malloc(size);
6835 if (!*buf) {
6836 break;
6837 }
6838
6839 va_copy(ap_copy, ap);
6840 len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
6841 va_end(ap_copy);
6842 (*buf)[size - 1] = 0;
6843 }
6844
6845 return len;
6846}
6847
6848
6849/* Print message to buffer. If buffer is large enough to hold the message,
6850 * return buffer. If buffer is to small, allocate large enough buffer on
6851 * heap,
6852 * and return allocated buffer. */
6853static int
6854alloc_vprintf(char **out_buf,
6855 char *prealloc_buf,
6856 size_t prealloc_size,
6857 const char *fmt,
6858 va_list ap)
6859{
6860 va_list ap_copy;
6861 int len;
6862
6863 /* Windows is not standard-compliant, and vsnprintf() returns -1 if
6864 * buffer is too small. Also, older versions of msvcrt.dll do not have
6865 * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
6866 * Therefore, we make two passes: on first pass, get required message
6867 * length.
6868 * On second pass, actually print the message. */
6869 va_copy(ap_copy, ap);
6870 len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
6871 va_end(ap_copy);
6872
6873 if (len < 0) {
6874 /* C runtime is not standard compliant, vsnprintf() returned -1.
6875 * Switch to alternative code path that uses incremental
6876 * allocations.
6877 */
6878 va_copy(ap_copy, ap);
6879 len = alloc_vprintf2(out_buf, fmt, ap_copy);
6880 va_end(ap_copy);
6881
6882 } else if ((size_t)(len) >= prealloc_size) {
6883 /* The pre-allocated buffer not large enough. */
6884 /* Allocate a new buffer. */
6885 *out_buf = (char *)mg_malloc((size_t)(len) + 1);
6886 if (!*out_buf) {
6887 /* Allocation failed. Return -1 as "out of memory" error. */
6888 return -1;
6889 }
6890 /* Buffer allocation successful. Store the string there. */
6891 va_copy(ap_copy, ap);
6893 vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
6894 va_end(ap_copy);
6895
6896 } else {
6897 /* The pre-allocated buffer is large enough.
6898 * Use it to store the string and return the address. */
6899 va_copy(ap_copy, ap);
6901 vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
6902 va_end(ap_copy);
6903 *out_buf = prealloc_buf;
6904 }
6905
6906 return len;
6907}
6908
6909
6910#if defined(GCC_DIAGNOSTIC)
6911/* Enable format-nonliteral warning again. */
6912#pragma GCC diagnostic pop
6913#endif
6914
6915
6916static int
6917mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
6918{
6919 char mem[MG_BUF_LEN];
6920 char *buf = NULL;
6921 int len;
6922
6923 if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
6924 len = mg_write(conn, buf, (size_t)len);
6925 }
6926 if (buf != mem) {
6927 mg_free(buf);
6928 }
6929
6930 return len;
6931}
6932
6933
6934int
6935mg_printf(struct mg_connection *conn, const char *fmt, ...)
6936{
6937 va_list ap;
6938 int result;
6939
6940 va_start(ap, fmt);
6941 result = mg_vprintf(conn, fmt, ap);
6942 va_end(ap);
6943
6944 return result;
6945}
6946
6947
6948int
6949mg_url_decode(const char *src,
6950 int src_len,
6951 char *dst,
6952 int dst_len,
6953 int is_form_url_encoded)
6954{
6955 int i, j, a, b;
6956#define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
6957
6958 for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
6959 if ((i < src_len - 2) && (src[i] == '%')
6960 && isxdigit((unsigned char)src[i + 1])
6961 && isxdigit((unsigned char)src[i + 2])) {
6962 a = tolower((unsigned char)src[i + 1]);
6963 b = tolower((unsigned char)src[i + 2]);
6964 dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
6965 i += 2;
6966 } else if (is_form_url_encoded && (src[i] == '+')) {
6967 dst[j] = ' ';
6968 } else {
6969 dst[j] = src[i];
6970 }
6971 }
6972
6973 dst[j] = '\0'; /* Null-terminate the destination */
6974
6975 return (i >= src_len) ? j : -1;
6976}
6977
6978
6979/* form url decoding of an entire string */
6980static void
6982{
6983 int len = (int)strlen(buf);
6984 (void)mg_url_decode(buf, len, buf, len + 1, 1);
6985}
6986
6987
6988int
6989mg_get_var(const char *data,
6990 size_t data_len,
6991 const char *name,
6992 char *dst,
6993 size_t dst_len)
6994{
6995 return mg_get_var2(data, data_len, name, dst, dst_len, 0);
6996}
6997
6998
6999int
7000mg_get_var2(const char *data,
7001 size_t data_len,
7002 const char *name,
7003 char *dst,
7004 size_t dst_len,
7005 size_t occurrence)
7006{
7007 const char *p, *e, *s;
7008 size_t name_len;
7009 int len;
7010
7011 if ((dst == NULL) || (dst_len == 0)) {
7012 len = -2;
7013 } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
7014 len = -1;
7015 dst[0] = '\0';
7016 } else {
7017 name_len = strlen(name);
7018 e = data + data_len;
7019 len = -1;
7020 dst[0] = '\0';
7021
7022 /* data is "var1=val1&var2=val2...". Find variable first */
7023 for (p = data; p + name_len < e; p++) {
7024 if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
7025 && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
7026 /* Point p to variable value */
7027 p += name_len + 1;
7028
7029 /* Point s to the end of the value */
7030 s = (const char *)memchr(p, '&', (size_t)(e - p));
7031 if (s == NULL) {
7032 s = e;
7033 }
7034 DEBUG_ASSERT(s >= p);
7035 if (s < p) {
7036 return -3;
7037 }
7038
7039 /* Decode variable into destination buffer */
7040 len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
7041
7042 /* Redirect error code from -1 to -2 (destination buffer too
7043 * small). */
7044 if (len == -1) {
7045 len = -2;
7046 }
7047 break;
7048 }
7049 }
7050 }
7051
7052 return len;
7053}
7054
7055
7056/* split a string "key1=val1&key2=val2" into key/value pairs */
7057int
7059 struct mg_header *form_fields,
7060 unsigned num_form_fields)
7061{
7062 char *b;
7063 int i;
7064 int num = 0;
7065
7066 if (data == NULL) {
7067 /* parameter error */
7068 return -1;
7069 }
7070
7071 if ((form_fields == NULL) && (num_form_fields == 0)) {
7072 /* determine the number of expected fields */
7073 if (data[0] == 0) {
7074 return 0;
7075 }
7076 /* count number of & to return the number of key-value-pairs */
7077 num = 1;
7078 while (*data) {
7079 if (*data == '&') {
7080 num++;
7081 }
7082 data++;
7083 }
7084 return num;
7085 }
7086
7087 if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
7088 /* parameter error */
7089 return -1;
7090 }
7091
7092 for (i = 0; i < (int)num_form_fields; i++) {
7093 /* extract key-value pairs from input data */
7094 while ((*data == ' ') || (*data == '\t')) {
7095 /* skip initial spaces */
7096 data++;
7097 }
7098 if (*data == 0) {
7099 /* end of string reached */
7100 break;
7101 }
7102 form_fields[num].name = data;
7103
7104 /* find & or = */
7105 b = data;
7106 while ((*b != 0) && (*b != '&') && (*b != '=')) {
7107 b++;
7108 }
7109
7110 if (*b == 0) {
7111 /* last key without value */
7112 form_fields[num].value = NULL;
7113 } else if (*b == '&') {
7114 /* mid key without value */
7115 form_fields[num].value = NULL;
7116 } else {
7117 /* terminate string */
7118 *b = 0;
7119 /* value starts after '=' */
7120 data = b + 1;
7121 form_fields[num].value = data;
7122 }
7123
7124 /* new field is stored */
7125 num++;
7126
7127 /* find a next key */
7128 b = strchr(data, '&');
7129 if (b == 0) {
7130 /* no more data */
7131 break;
7132 } else {
7133 /* terminate value of last field at '&' */
7134 *b = 0;
7135 /* next key-value-pairs starts after '&' */
7136 data = b + 1;
7137 }
7138 }
7139
7140 /* Decode all values */
7141 for (i = 0; i < num; i++) {
7142 if (form_fields[i].name) {
7143 url_decode_in_place((char *)form_fields[i].name);
7144 }
7145 if (form_fields[i].value) {
7146 url_decode_in_place((char *)form_fields[i].value);
7147 }
7148 }
7149
7150 /* return number of fields found */
7151 return num;
7152}
7153
7154
7155/* HCP24: some changes to compare hole var_name */
7156int
7157mg_get_cookie(const char *cookie_header,
7158 const char *var_name,
7159 char *dst,
7160 size_t dst_size)
7161{
7162 const char *s, *p, *end;
7163 int name_len, len = -1;
7164
7165 if ((dst == NULL) || (dst_size == 0)) {
7166 return -2;
7167 }
7168
7169 dst[0] = '\0';
7170 if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
7171 return -1;
7172 }
7173
7174 name_len = (int)strlen(var_name);
7175 end = s + strlen(s);
7176 for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
7177 if (s[name_len] == '=') {
7178 /* HCP24: now check is it a substring or a full cookie name */
7179 if ((s == cookie_header) || (s[-1] == ' ')) {
7180 s += name_len + 1;
7181 if ((p = strchr(s, ' ')) == NULL) {
7182 p = end;
7183 }
7184 if (p[-1] == ';') {
7185 p--;
7186 }
7187 if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
7188 s++;
7189 p--;
7190 }
7191 if ((size_t)(p - s) < dst_size) {
7192 len = (int)(p - s);
7193 mg_strlcpy(dst, s, (size_t)len + 1);
7194 } else {
7195 len = -3;
7196 }
7197 break;
7198 }
7199 }
7200 }
7201 return len;
7202}
7203
7204
7205#if defined(USE_WEBSOCKET) || defined(USE_LUA)
7206static void
7207base64_encode(const unsigned char *src, int src_len, char *dst)
7208{
7209 static const char *b64 =
7210 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7211 int i, j, a, b, c;
7212
7213 for (i = j = 0; i < src_len; i += 3) {
7214 a = src[i];
7215 b = ((i + 1) >= src_len) ? 0 : src[i + 1];
7216 c = ((i + 2) >= src_len) ? 0 : src[i + 2];
7217
7218 dst[j++] = b64[a >> 2];
7219 dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
7220 if (i + 1 < src_len) {
7221 dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
7222 }
7223 if (i + 2 < src_len) {
7224 dst[j++] = b64[c & 63];
7225 }
7226 }
7227 while (j % 4 != 0) {
7228 dst[j++] = '=';
7229 }
7230 dst[j++] = '\0';
7231}
7232#endif
7233
7234
7235#if defined(USE_LUA)
7236static unsigned char
7237b64reverse(char letter)
7238{
7239 if ((letter >= 'A') && (letter <= 'Z')) {
7240 return letter - 'A';
7241 }
7242 if ((letter >= 'a') && (letter <= 'z')) {
7243 return letter - 'a' + 26;
7244 }
7245 if ((letter >= '0') && (letter <= '9')) {
7246 return letter - '0' + 52;
7247 }
7248 if (letter == '+') {
7249 return 62;
7250 }
7251 if (letter == '/') {
7252 return 63;
7253 }
7254 if (letter == '=') {
7255 return 255; /* normal end */
7256 }
7257 return 254; /* error */
7258}
7259
7260
7261static int
7262base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
7263{
7264 int i;
7265 unsigned char a, b, c, d;
7266
7267 *dst_len = 0;
7268
7269 for (i = 0; i < src_len; i += 4) {
7270 a = b64reverse(src[i]);
7271 if (a >= 254) {
7272 return i;
7273 }
7274
7275 b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
7276 if (b >= 254) {
7277 return i + 1;
7278 }
7279
7280 c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
7281 if (c == 254) {
7282 return i + 2;
7283 }
7284
7285 d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
7286 if (d == 254) {
7287 return i + 3;
7288 }
7289
7290 dst[(*dst_len)++] = (a << 2) + (b >> 4);
7291 if (c != 255) {
7292 dst[(*dst_len)++] = (b << 4) + (c >> 2);
7293 if (d != 255) {
7294 dst[(*dst_len)++] = (c << 6) + d;
7295 }
7296 }
7297 }
7298 return -1;
7299}
7300#endif
7301
7302
7303static int
7305{
7306 if (conn) {
7307 const char *s = conn->request_info.request_method;
7308 return (s != NULL)
7309 && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
7310 || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
7311 }
7312 return 0;
7313}
7314
7315
7316#if !defined(NO_FILES)
7317static int
7319 struct mg_connection *conn, /* in: request (must be valid) */
7320 const char *filename /* in: filename (must be valid) */
7321)
7322{
7323#if !defined(NO_CGI)
7324 unsigned char cgi_config_idx, inc, max;
7325#endif
7326
7327#if defined(USE_LUA)
7328 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
7329 filename)
7330 > 0) {
7331 return 1;
7332 }
7333#endif
7334#if defined(USE_DUKTAPE)
7335 if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
7336 filename)
7337 > 0) {
7338 return 1;
7339 }
7340#endif
7341#if !defined(NO_CGI)
7344 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
7345 if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
7347 conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
7348 filename)
7349 > 0)) {
7350 return 1;
7351 }
7352 }
7353#endif
7354 /* filename and conn could be unused, if all preocessor conditions
7355 * are false (no script language supported). */
7356 (void)filename;
7357 (void)conn;
7358
7359 return 0;
7360}
7361
7362
7363static int
7365 struct mg_connection *conn, /* in: request (must be valid) */
7366 const char *filename /* in: filename (must be valid) */
7367)
7368{
7369#if defined(USE_LUA)
7370 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
7371 filename)
7372 > 0) {
7373 return 1;
7374 }
7375#endif
7377 > 0) {
7378 return 1;
7379 }
7380 return 0;
7381}
7382
7383
7384/* For given directory path, substitute it to valid index file.
7385 * Return 1 if index file has been found, 0 if not found.
7386 * If the file is found, it's stats is returned in stp. */
7387static int
7389 char *path,
7390 size_t path_len,
7391 struct mg_file_stat *filestat)
7392{
7393 const char *list = conn->dom_ctx->config[INDEX_FILES];
7394 struct vec filename_vec;
7395 size_t n = strlen(path);
7396 int found = 0;
7397
7398 /* The 'path' given to us points to the directory. Remove all trailing
7399 * directory separator characters from the end of the path, and
7400 * then append single directory separator character. */
7401 while ((n > 0) && (path[n - 1] == '/')) {
7402 n--;
7403 }
7404 path[n] = '/';
7405
7406 /* Traverse index files list. For each entry, append it to the given
7407 * path and see if the file exists. If it exists, break the loop */
7408 while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
7409 /* Ignore too long entries that may overflow path buffer */
7410 if ((filename_vec.len + 1) > (path_len - (n + 1))) {
7411 continue;
7412 }
7413
7414 /* Prepare full path to the index file */
7415 mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
7416
7417 /* Does it exist? */
7418 if (mg_stat(conn, path, filestat)) {
7419 /* Yes it does, break the loop */
7420 found = 1;
7421 break;
7422 }
7423 }
7424
7425 /* If no index file exists, restore directory path */
7426 if (!found) {
7427 path[n] = '\0';
7428 }
7429
7430 return found;
7431}
7432#endif
7433
7434
7435static void
7436interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
7437 char *filename, /* out: filename */
7438 size_t filename_buf_len, /* in: size of filename buffer */
7439 struct mg_file_stat *filestat, /* out: file status structure */
7440 int *is_found, /* out: file found (directly) */
7441 int *is_script_resource, /* out: handled by a script? */
7442 int *is_websocket_request, /* out: websocket connetion? */
7443 int *is_put_or_delete_request, /* out: put/delete a file? */
7444 int *is_template_text /* out: SSI file or LSP file? */
7445)
7446{
7447 char const *accept_encoding;
7448
7449#if !defined(NO_FILES)
7450 const char *uri = conn->request_info.local_uri;
7451 const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
7452 const char *rewrite;
7453 struct vec a, b;
7454 ptrdiff_t match_len;
7455 char gz_path[UTF8_PATH_MAX];
7456 int truncated;
7457#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7458 char *tmp_str;
7459 size_t tmp_str_len, sep_pos;
7460 int allow_substitute_script_subresources;
7461#endif
7462#else
7463 (void)filename_buf_len; /* unused if NO_FILES is defined */
7464#endif
7465
7466 /* Step 1: Set all initially unknown outputs to zero */
7467 memset(filestat, 0, sizeof(*filestat));
7468 *filename = 0;
7469 *is_found = 0;
7470 *is_script_resource = 0;
7471 *is_template_text = 0;
7472
7473 /* Step 2: Check if the request attempts to modify the file system */
7474 *is_put_or_delete_request = is_put_or_delete_method(conn);
7475
7476 /* Step 3: Check if it is a websocket request, and modify the document
7477 * root if required */
7478#if defined(USE_WEBSOCKET)
7479 *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
7480#if !defined(NO_FILES)
7481 if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
7482 root = conn->dom_ctx->config[WEBSOCKET_ROOT];
7483 }
7484#endif /* !NO_FILES */
7485#else /* USE_WEBSOCKET */
7486 *is_websocket_request = 0;
7487#endif /* USE_WEBSOCKET */
7488
7489 /* Step 4: Check if gzip encoded response is allowed */
7490 conn->accept_gzip = 0;
7491 if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
7492 if (strstr(accept_encoding, "gzip") != NULL) {
7493 conn->accept_gzip = 1;
7494 }
7495 }
7496
7497#if !defined(NO_FILES)
7498 /* Step 5: If there is no root directory, don't look for files. */
7499 /* Note that root == NULL is a regular use case here. This occurs,
7500 * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
7501 * config is not required. */
7502 if (root == NULL) {
7503 /* all file related outputs have already been set to 0, just return
7504 */
7505 return;
7506 }
7507
7508 /* Step 6: Determine the local file path from the root path and the
7509 * request uri. */
7510 /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
7511 * part of the path one byte on the right. */
7512 truncated = 0;
7514 conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
7515
7516 if (truncated) {
7517 goto interpret_cleanup;
7518 }
7519
7520 /* Step 7: URI rewriting */
7521 rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
7522 while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
7523 if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
7524 mg_snprintf(conn,
7525 &truncated,
7526 filename,
7527 filename_buf_len - 1,
7528 "%.*s%s",
7529 (int)b.len,
7530 b.ptr,
7531 uri + match_len);
7532 break;
7533 }
7534 }
7535
7536 if (truncated) {
7537 goto interpret_cleanup;
7538 }
7539
7540 /* Step 8: Check if the file exists at the server */
7541 /* Local file path and name, corresponding to requested URI
7542 * is now stored in "filename" variable. */
7543 if (mg_stat(conn, filename, filestat)) {
7544 int uri_len = (int)strlen(uri);
7545 int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
7546
7547 /* 8.1: File exists. */
7548 *is_found = 1;
7549
7550 /* 8.2: Check if it is a script type. */
7552 /* The request addresses a CGI resource, Lua script or
7553 * server-side javascript.
7554 * The URI corresponds to the script itself (like
7555 * /path/script.cgi), and there is no additional resource
7556 * path (like /path/script.cgi/something).
7557 * Requests that modify (replace or delete) a resource, like
7558 * PUT and DELETE requests, should replace/delete the script
7559 * file.
7560 * Requests that read or write from/to a resource, like GET and
7561 * POST requests, should call the script and return the
7562 * generated response. */
7563 *is_script_resource = (!*is_put_or_delete_request);
7564 }
7565
7566 /* 8.3: Check for SSI and LSP files */
7568 /* Same as above, but for *.lsp and *.shtml files. */
7569 /* A "template text" is a file delivered directly to the client,
7570 * but with some text tags replaced by dynamic content.
7571 * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
7572 * (LP, LSP) file. */
7573 *is_template_text = (!*is_put_or_delete_request);
7574 }
7575
7576 /* 8.4: If the request target is a directory, there could be
7577 * a substitute file (index.html, index.cgi, ...). */
7578 if (filestat->is_directory && is_uri_end_slash) {
7579 /* Use a local copy here, since substitute_index_file will
7580 * change the content of the file status */
7581 struct mg_file_stat tmp_filestat;
7582 memset(&tmp_filestat, 0, sizeof(tmp_filestat));
7583
7585 conn, filename, filename_buf_len, &tmp_filestat)) {
7586
7587 /* Substitute file found. Copy stat to the output, then
7588 * check if the file is a script file */
7589 *filestat = tmp_filestat;
7590
7592 /* Substitute file is a script file */
7593 *is_script_resource = 1;
7594 } else if (extention_matches_template_text(conn, filename)) {
7595 /* Substitute file is a LSP or SSI file */
7596 *is_template_text = 1;
7597 } else {
7598 /* Substitute file is a regular file */
7599 *is_script_resource = 0;
7600 *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
7601 }
7602 }
7603 /* If there is no substitute file, the server could return
7604 * a directory listing in a later step */
7605 }
7606 return;
7607 }
7608
7609 /* Step 9: Check for zipped files: */
7610 /* If we can't find the actual file, look for the file
7611 * with the same name but a .gz extension. If we find it,
7612 * use that and set the gzipped flag in the file struct
7613 * to indicate that the response need to have the content-
7614 * encoding: gzip header.
7615 * We can only do this if the browser declares support. */
7616 if (conn->accept_gzip) {
7618 conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
7619
7620 if (truncated) {
7621 goto interpret_cleanup;
7622 }
7623
7624 if (mg_stat(conn, gz_path, filestat)) {
7625 if (filestat) {
7626 filestat->is_gzipped = 1;
7627 *is_found = 1;
7628 }
7629 /* Currently gz files can not be scripts. */
7630 return;
7631 }
7632 }
7633
7634#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7635 /* Step 10: Script resources may handle sub-resources */
7636 /* Support PATH_INFO for CGI scripts. */
7637 tmp_str_len = strlen(filename);
7638 tmp_str =
7639 (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
7640 if (!tmp_str) {
7641 /* Out of memory */
7642 goto interpret_cleanup;
7643 }
7644 memcpy(tmp_str, filename, tmp_str_len + 1);
7645
7646 /* Check config, if index scripts may have sub-resources */
7647 allow_substitute_script_subresources =
7649 "yes");
7650
7651 sep_pos = tmp_str_len;
7652 while (sep_pos > 0) {
7653 sep_pos--;
7654 if (tmp_str[sep_pos] == '/') {
7655 int is_script = 0, does_exist = 0;
7656
7657 tmp_str[sep_pos] = 0;
7658 if (tmp_str[0]) {
7659 is_script = extention_matches_script(conn, tmp_str);
7660 does_exist = mg_stat(conn, tmp_str, filestat);
7661 }
7662
7663 if (does_exist && is_script) {
7664 filename[sep_pos] = 0;
7665 memmove(filename + sep_pos + 2,
7666 filename + sep_pos + 1,
7667 strlen(filename + sep_pos + 1) + 1);
7668 conn->path_info = filename + sep_pos + 1;
7669 filename[sep_pos + 1] = '/';
7670 *is_script_resource = 1;
7671 *is_found = 1;
7672 break;
7673 }
7674
7675 if (allow_substitute_script_subresources) {
7677 conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
7678
7679 /* some intermediate directory has an index file */
7680 if (extention_matches_script(conn, tmp_str)) {
7681
7682 size_t script_name_len = strlen(tmp_str);
7683
7684 /* subres_name read before this memory locatio will be
7685 overwritten */
7686 char *subres_name = filename + sep_pos;
7687 size_t subres_name_len = strlen(subres_name);
7688
7689 DEBUG_TRACE("Substitute script %s serving path %s",
7690 tmp_str,
7691 filename);
7692
7693 /* this index file is a script */
7694 if ((script_name_len + subres_name_len + 2)
7695 >= filename_buf_len) {
7696 mg_free(tmp_str);
7697 goto interpret_cleanup;
7698 }
7699
7700 conn->path_info =
7701 filename + script_name_len + 1; /* new target */
7702 memmove(conn->path_info, subres_name, subres_name_len);
7703 conn->path_info[subres_name_len] = 0;
7704 memcpy(filename, tmp_str, script_name_len + 1);
7705
7706 *is_script_resource = 1;
7707 *is_found = 1;
7708 break;
7709
7710 } else {
7711
7712 DEBUG_TRACE("Substitute file %s serving path %s",
7713 tmp_str,
7714 filename);
7715
7716 /* non-script files will not have sub-resources */
7717 filename[sep_pos] = 0;
7718 conn->path_info = 0;
7719 *is_script_resource = 0;
7720 *is_found = 0;
7721 break;
7722 }
7723 }
7724 }
7725
7726 tmp_str[sep_pos] = '/';
7727 }
7728 }
7729
7730 mg_free(tmp_str);
7731
7732#endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
7733#endif /* !defined(NO_FILES) */
7734 return;
7735
7736#if !defined(NO_FILES)
7737/* Reset all outputs */
7738interpret_cleanup:
7739 memset(filestat, 0, sizeof(*filestat));
7740 *filename = 0;
7741 *is_found = 0;
7742 *is_script_resource = 0;
7743 *is_websocket_request = 0;
7744 *is_put_or_delete_request = 0;
7745#endif /* !defined(NO_FILES) */
7746}
7747
7748
7749/* Check whether full request is buffered. Return:
7750 * -1 if request or response is malformed
7751 * 0 if request or response is not yet fully buffered
7752 * >0 actual request length, including last \r\n\r\n */
7753static int
7754get_http_header_len(const char *buf, int buflen)
7755{
7756 int i;
7757 for (i = 0; i < buflen; i++) {
7758 /* Do an unsigned comparison in some conditions below */
7759 const unsigned char c = (unsigned char)buf[i];
7760
7761 if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
7762 && !isprint(c)) {
7763 /* abort scan as soon as one malformed character is found */
7764 return -1;
7765 }
7766
7767 if (i < buflen - 1) {
7768 if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
7769 /* Two newline, no carriage return - not standard compliant,
7770 * but it should be accepted */
7771 return i + 2;
7772 }
7773 }
7774
7775 if (i < buflen - 3) {
7776 if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
7777 && (buf[i + 3] == '\n')) {
7778 /* Two \r\n - standard compliant */
7779 return i + 4;
7780 }
7781 }
7782 }
7783
7784 return 0;
7785}
7786
7787
7788#if !defined(NO_CACHING)
7789/* Convert month to the month number. Return -1 on error, or month number */
7790static int
7791get_month_index(const char *s)
7792{
7793 size_t i;
7794
7795 for (i = 0; i < ARRAY_SIZE(month_names); i++) {
7796 if (!strcmp(s, month_names[i])) {
7797 return (int)i;
7798 }
7799 }
7800
7801 return -1;
7802}
7803
7804
7805/* Parse UTC date-time string, and return the corresponding time_t value. */
7806static time_t
7807parse_date_string(const char *datetime)
7808{
7809 char month_str[32] = {0};
7810 int second, minute, hour, day, month, year;
7811 time_t result = (time_t)0;
7812 struct tm tm;
7813
7814 if ((sscanf(datetime,
7815 "%d/%3s/%d %d:%d:%d",
7816 &day,
7817 month_str,
7818 &year,
7819 &hour,
7820 &minute,
7821 &second)
7822 == 6)
7823 || (sscanf(datetime,
7824 "%d %3s %d %d:%d:%d",
7825 &day,
7826 month_str,
7827 &year,
7828 &hour,
7829 &minute,
7830 &second)
7831 == 6)
7832 || (sscanf(datetime,
7833 "%*3s, %d %3s %d %d:%d:%d",
7834 &day,
7835 month_str,
7836 &year,
7837 &hour,
7838 &minute,
7839 &second)
7840 == 6)
7841 || (sscanf(datetime,
7842 "%d-%3s-%d %d:%d:%d",
7843 &day,
7844 month_str,
7845 &year,
7846 &hour,
7847 &minute,
7848 &second)
7849 == 6)) {
7850 month = get_month_index(month_str);
7851 if ((month >= 0) && (year >= 1970)) {
7852 memset(&tm, 0, sizeof(tm));
7853 tm.tm_year = year - 1900;
7854 tm.tm_mon = month;
7855 tm.tm_mday = day;
7856 tm.tm_hour = hour;
7857 tm.tm_min = minute;
7858 tm.tm_sec = second;
7859 result = timegm(&tm);
7860 }
7861 }
7862
7863 return result;
7864}
7865#endif /* !NO_CACHING */
7866
7867
7868/* Pre-process URIs according to RFC + protect against directory disclosure
7869 * attacks by removing '..', excessive '/' and '\' characters */
7870static void
7872{
7873 /* Windows backend protection
7874 * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
7875 * in URI by slash */
7876 char *out_end = inout;
7877 char *in = inout;
7878
7879 if (!in) {
7880 /* Param error. */
7881 return;
7882 }
7883
7884 while (*in) {
7885 if (*in == '\\') {
7886 *in = '/';
7887 }
7888 in++;
7889 }
7890
7891 /* Algorithm "remove_dot_segments" from
7892 * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
7893 /* Step 1:
7894 * The input buffer is initialized.
7895 * The output buffer is initialized to the empty string.
7896 */
7897 in = inout;
7898
7899 /* Step 2:
7900 * While the input buffer is not empty, loop as follows:
7901 */
7902 /* Less than out_end of the inout buffer is used as output, so keep
7903 * condition: out_end <= in */
7904 while (*in) {
7905 /* Step 2a:
7906 * If the input buffer begins with a prefix of "../" or "./",
7907 * then remove that prefix from the input buffer;
7908 */
7909 if (!strncmp(in, "../", 3)) {
7910 in += 3;
7911 } else if (!strncmp(in, "./", 2)) {
7912 in += 2;
7913 }
7914 /* otherwise */
7915 /* Step 2b:
7916 * if the input buffer begins with a prefix of "/./" or "/.",
7917 * where "." is a complete path segment, then replace that
7918 * prefix with "/" in the input buffer;
7919 */
7920 else if (!strncmp(in, "/./", 3)) {
7921 in += 2;
7922 } else if (!strcmp(in, "/.")) {
7923 in[1] = 0;
7924 }
7925 /* otherwise */
7926 /* Step 2c:
7927 * if the input buffer begins with a prefix of "/../" or "/..",
7928 * where ".." is a complete path segment, then replace that
7929 * prefix with "/" in the input buffer and remove the last
7930 * segment and its preceding "/" (if any) from the output
7931 * buffer;
7932 */
7933 else if (!strncmp(in, "/../", 4)) {
7934 in += 3;
7935 if (inout != out_end) {
7936 /* remove last segment */
7937 do {
7938 out_end--;
7939 } while ((inout != out_end) && (*out_end != '/'));
7940 }
7941 } else if (!strcmp(in, "/..")) {
7942 in[1] = 0;
7943 if (inout != out_end) {
7944 /* remove last segment */
7945 do {
7946 out_end--;
7947 } while ((inout != out_end) && (*out_end != '/'));
7948 }
7949 }
7950 /* otherwise */
7951 /* Step 2d:
7952 * if the input buffer consists only of "." or "..", then remove
7953 * that from the input buffer;
7954 */
7955 else if (!strcmp(in, ".") || !strcmp(in, "..")) {
7956 *in = 0;
7957 }
7958 /* otherwise */
7959 /* Step 2e:
7960 * move the first path segment in the input buffer to the end of
7961 * the output buffer, including the initial "/" character (if
7962 * any) and any subsequent characters up to, but not including,
7963 * the next "/" character or the end of the input buffer.
7964 */
7965 else {
7966 do {
7967 *out_end = *in;
7968 out_end++;
7969 in++;
7970 } while ((*in != 0) && (*in != '/'));
7971 }
7972 }
7973
7974 /* Step 3:
7975 * Finally, the output buffer is returned as the result of
7976 * remove_dot_segments.
7977 */
7978 /* Terminate output */
7979 *out_end = 0;
7980
7981 /* For Windows, the files/folders "x" and "x." (with a dot but without
7982 * extension) are identical. Replace all "./" by "/" and remove a "." at
7983 * the end. Also replace all "//" by "/". Repeat until there is no "./"
7984 * or "//" anymore.
7985 */
7986 out_end = in = inout;
7987 while (*in) {
7988 if (*in == '.') {
7989 /* remove . at the end or preceding of / */
7990 char *in_ahead = in;
7991 do {
7992 in_ahead++;
7993 } while (*in_ahead == '.');
7994 if (*in_ahead == '/') {
7995 in = in_ahead;
7996 if ((out_end != inout) && (out_end[-1] == '/')) {
7997 /* remove generated // */
7998 out_end--;
7999 }
8000 } else if (*in_ahead == 0) {
8001 in = in_ahead;
8002 } else {
8003 do {
8004 *out_end++ = '.';
8005 in++;
8006 } while (in != in_ahead);
8007 }
8008 } else if (*in == '/') {
8009 /* replace // by / */
8010 *out_end++ = '/';
8011 do {
8012 in++;
8013 } while (*in == '/');
8014 } else {
8015 *out_end++ = *in;
8016 in++;
8017 }
8018 }
8019 *out_end = 0;
8020}
8021
8022
8023static const struct {
8024 const char *extension;
8025 size_t ext_len;
8026 const char *mime_type;
8027} builtin_mime_types[] = {
8028 /* IANA registered MIME types
8029 * (http://www.iana.org/assignments/media-types)
8030 * application types */
8031 {".bin", 4, "application/octet-stream"},
8032 {".deb", 4, "application/octet-stream"},
8033 {".dmg", 4, "application/octet-stream"},
8034 {".dll", 4, "application/octet-stream"},
8035 {".doc", 4, "application/msword"},
8036 {".eps", 4, "application/postscript"},
8037 {".exe", 4, "application/octet-stream"},
8038 {".iso", 4, "application/octet-stream"},
8039 {".js", 3, "application/javascript"},
8040 {".json", 5, "application/json"},
8041 {".msi", 4, "application/octet-stream"},
8042 {".pdf", 4, "application/pdf"},
8043 {".ps", 3, "application/postscript"},
8044 {".rtf", 4, "application/rtf"},
8045 {".xhtml", 6, "application/xhtml+xml"},
8046 {".xsl", 4, "application/xml"},
8047 {".xslt", 5, "application/xml"},
8048
8049 /* fonts */
8050 {".ttf", 4, "application/font-sfnt"},
8051 {".cff", 4, "application/font-sfnt"},
8052 {".otf", 4, "application/font-sfnt"},
8053 {".aat", 4, "application/font-sfnt"},
8054 {".sil", 4, "application/font-sfnt"},
8055 {".pfr", 4, "application/font-tdpfr"},
8056 {".woff", 5, "application/font-woff"},
8057 {".woff2", 6, "application/font-woff2"},
8058
8059 /* audio */
8060 {".mp3", 4, "audio/mpeg"},
8061 {".oga", 4, "audio/ogg"},
8062 {".ogg", 4, "audio/ogg"},
8063
8064 /* image */
8065 {".gif", 4, "image/gif"},
8066 {".ief", 4, "image/ief"},
8067 {".jpeg", 5, "image/jpeg"},
8068 {".jpg", 4, "image/jpeg"},
8069 {".jpm", 4, "image/jpm"},
8070 {".jpx", 4, "image/jpx"},
8071 {".png", 4, "image/png"},
8072 {".svg", 4, "image/svg+xml"},
8073 {".tif", 4, "image/tiff"},
8074 {".tiff", 5, "image/tiff"},
8075
8076 /* model */
8077 {".wrl", 4, "model/vrml"},
8078
8079 /* text */
8080 {".css", 4, "text/css"},
8081 {".csv", 4, "text/csv"},
8082 {".htm", 4, "text/html"},
8083 {".html", 5, "text/html"},
8084 {".sgm", 4, "text/sgml"},
8085 {".shtm", 5, "text/html"},
8086 {".shtml", 6, "text/html"},
8087 {".txt", 4, "text/plain"},
8088 {".xml", 4, "text/xml"},
8089
8090 /* video */
8091 {".mov", 4, "video/quicktime"},
8092 {".mp4", 4, "video/mp4"},
8093 {".mpeg", 5, "video/mpeg"},
8094 {".mpg", 4, "video/mpeg"},
8095 {".ogv", 4, "video/ogg"},
8096 {".qt", 3, "video/quicktime"},
8097
8098 /* not registered types
8099 * (http://reference.sitepoint.com/html/mime-types-full,
8100 * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
8101 {".arj", 4, "application/x-arj-compressed"},
8102 {".gz", 3, "application/x-gunzip"},
8103 {".rar", 4, "application/x-arj-compressed"},
8104 {".swf", 4, "application/x-shockwave-flash"},
8105 {".tar", 4, "application/x-tar"},
8106 {".tgz", 4, "application/x-tar-gz"},
8107 {".torrent", 8, "application/x-bittorrent"},
8108 {".ppt", 4, "application/x-mspowerpoint"},
8109 {".xls", 4, "application/x-msexcel"},
8110 {".zip", 4, "application/x-zip-compressed"},
8111 {".aac",
8112 4,
8113 "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
8114 {".flac", 5, "audio/flac"},
8115 {".aif", 4, "audio/x-aif"},
8116 {".m3u", 4, "audio/x-mpegurl"},
8117 {".mid", 4, "audio/x-midi"},
8118 {".ra", 3, "audio/x-pn-realaudio"},
8119 {".ram", 4, "audio/x-pn-realaudio"},
8120 {".wav", 4, "audio/x-wav"},
8121 {".bmp", 4, "image/bmp"},
8122 {".ico", 4, "image/x-icon"},
8123 {".pct", 4, "image/x-pct"},
8124 {".pict", 5, "image/pict"},
8125 {".rgb", 4, "image/x-rgb"},
8126 {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
8127 {".asf", 4, "video/x-ms-asf"},
8128 {".avi", 4, "video/x-msvideo"},
8129 {".m4v", 4, "video/x-m4v"},
8130 {NULL, 0, NULL}};
8131
8132
8133const char *
8135{
8136 const char *ext;
8137 size_t i, path_len;
8138
8139 path_len = strlen(path);
8140
8141 for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
8142 ext = path + (path_len - builtin_mime_types[i].ext_len);
8143 if ((path_len > builtin_mime_types[i].ext_len)
8144 && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
8145 return builtin_mime_types[i].mime_type;
8146 }
8147 }
8148
8149 return "text/plain";
8150}
8151
8152
8153/* Look at the "path" extension and figure what mime type it has.
8154 * Store mime type in the vector. */
8155static void
8156get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
8157{
8158 struct vec ext_vec, mime_vec;
8159 const char *list, *ext;
8160 size_t path_len;
8161
8162 path_len = strlen(path);
8163
8164 if ((conn == NULL) || (vec == NULL)) {
8165 if (vec != NULL) {
8166 memset(vec, '\0', sizeof(struct vec));
8167 }
8168 return;
8169 }
8170
8171 /* Scan user-defined mime types first, in case user wants to
8172 * override default mime types. */
8173 list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
8174 while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
8175 /* ext now points to the path suffix */
8176 ext = path + path_len - ext_vec.len;
8177 if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
8178 *vec = mime_vec;
8179 return;
8180 }
8181 }
8182
8184 vec->len = strlen(vec->ptr);
8185}
8186
8187
8188/* Stringify binary data. Output buffer must be twice as big as input,
8189 * because each byte takes 2 bytes in string representation */
8190static void
8191bin2str(char *to, const unsigned char *p, size_t len)
8192{
8193 static const char *hex = "0123456789abcdef";
8194
8195 for (; len--; p++) {
8196 *to++ = hex[p[0] >> 4];
8197 *to++ = hex[p[0] & 0x0f];
8198 }
8199 *to = '\0';
8200}
8201
8202
8203/* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
8204 */
8205char *
8206mg_md5(char buf[33], ...)
8207{
8208 md5_byte_t hash[16];
8209 const char *p;
8210 va_list ap;
8211 md5_state_t ctx;
8212
8213 md5_init(&ctx);
8214
8215 va_start(ap, buf);
8216 while ((p = va_arg(ap, const char *)) != NULL) {
8217 md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
8218 }
8219 va_end(ap);
8220
8221 md5_finish(&ctx, hash);
8222 bin2str(buf, hash, sizeof(hash));
8223 return buf;
8224}
8225
8226
8227/* Check the user's password, return 1 if OK */
8228static int
8229check_password(const char *method,
8230 const char *ha1,
8231 const char *uri,
8232 const char *nonce,
8233 const char *nc,
8234 const char *cnonce,
8235 const char *qop,
8236 const char *response)
8237{
8238 char ha2[32 + 1], expected_response[32 + 1];
8239
8240 /* Some of the parameters may be NULL */
8241 if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
8242 || (qop == NULL) || (response == NULL)) {
8243 return 0;
8244 }
8245
8246 /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
8247 if (strlen(response) != 32) {
8248 return 0;
8249 }
8250
8251 mg_md5(ha2, method, ":", uri, NULL);
8252 mg_md5(expected_response,
8253 ha1,
8254 ":",
8255 nonce,
8256 ":",
8257 nc,
8258 ":",
8259 cnonce,
8260 ":",
8261 qop,
8262 ":",
8263 ha2,
8264 NULL);
8265
8266 return mg_strcasecmp(response, expected_response) == 0;
8267}
8268
8269
8270#if !defined(NO_FILESYSTEMS)
8271/* Use the global passwords file, if specified by auth_gpass option,
8272 * or search for .htpasswd in the requested directory. */
8273static void
8275 const char *path,
8276 struct mg_file *filep)
8277{
8278 if ((conn != NULL) && (conn->dom_ctx != NULL)) {
8279 char name[UTF8_PATH_MAX];
8280 const char *p, *e,
8281 *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
8282 int truncated;
8283
8284 if (gpass != NULL) {
8285 /* Use global passwords file */
8286 if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
8287#if defined(DEBUG)
8288 /* Use mg_cry_internal here, since gpass has been
8289 * configured. */
8290 mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
8291#endif
8292 }
8293 /* Important: using local struct mg_file to test path for
8294 * is_directory flag. If filep is used, mg_stat() makes it
8295 * appear as if auth file was opened.
8296 * TODO(mid): Check if this is still required after rewriting
8297 * mg_stat */
8298 } else if (mg_stat(conn, path, &filep->stat)
8299 && filep->stat.is_directory) {
8300 mg_snprintf(conn,
8301 &truncated,
8302 name,
8303 sizeof(name),
8304 "%s/%s",
8305 path,
8307
8308 if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8309#if defined(DEBUG)
8310 /* Don't use mg_cry_internal here, but only a trace, since
8311 * this is a typical case. It will occur for every directory
8312 * without a password file. */
8313 DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8314#endif
8315 }
8316 } else {
8317 /* Try to find .htpasswd in requested directory. */
8318 for (p = path, e = p + strlen(p) - 1; e > p; e--) {
8319 if (e[0] == '/') {
8320 break;
8321 }
8322 }
8323 mg_snprintf(conn,
8324 &truncated,
8325 name,
8326 sizeof(name),
8327 "%.*s/%s",
8328 (int)(e - p),
8329 p,
8331
8332 if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8333#if defined(DEBUG)
8334 /* Don't use mg_cry_internal here, but only a trace, since
8335 * this is a typical case. It will occur for every directory
8336 * without a password file. */
8337 DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8338#endif
8339 }
8340 }
8341 }
8342}
8343#endif /* NO_FILESYSTEMS */
8344
8345
8346/* Parsed Authorization header */
8347struct ah {
8348 char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
8349};
8350
8351
8352/* Return 1 on success. Always initializes the ah structure. */
8353static int
8355 char *buf,
8356 size_t buf_size,
8357 struct ah *ah)
8358{
8359 char *name, *value, *s;
8360 const char *auth_header;
8361 uint64_t nonce;
8362
8363 if (!ah || !conn) {
8364 return 0;
8365 }
8366
8367 (void)memset(ah, 0, sizeof(*ah));
8368 if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
8369 || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
8370 return 0;
8371 }
8372
8373 /* Make modifiable copy of the auth header */
8374 (void)mg_strlcpy(buf, auth_header + 7, buf_size);
8375 s = buf;
8376
8377 /* Parse authorization header */
8378 for (;;) {
8379 /* Gobble initial spaces */
8380 while (isspace((unsigned char)*s)) {
8381 s++;
8382 }
8383 name = skip_quoted(&s, "=", " ", 0);
8384 /* Value is either quote-delimited, or ends at first comma or space.
8385 */
8386 if (s[0] == '\"') {
8387 s++;
8388 value = skip_quoted(&s, "\"", " ", '\\');
8389 if (s[0] == ',') {
8390 s++;
8391 }
8392 } else {
8393 value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
8394 * uses spaces */
8395 }
8396 if (*name == '\0') {
8397 break;
8398 }
8399
8400 if (!strcmp(name, "username")) {
8401 ah->user = value;
8402 } else if (!strcmp(name, "cnonce")) {
8403 ah->cnonce = value;
8404 } else if (!strcmp(name, "response")) {
8405 ah->response = value;
8406 } else if (!strcmp(name, "uri")) {
8407 ah->uri = value;
8408 } else if (!strcmp(name, "qop")) {
8409 ah->qop = value;
8410 } else if (!strcmp(name, "nc")) {
8411 ah->nc = value;
8412 } else if (!strcmp(name, "nonce")) {
8413 ah->nonce = value;
8414 }
8415 }
8416
8417#if !defined(NO_NONCE_CHECK)
8418 /* Read the nonce from the response. */
8419 if (ah->nonce == NULL) {
8420 return 0;
8421 }
8422 s = NULL;
8423 nonce = strtoull(ah->nonce, &s, 10);
8424 if ((s == NULL) || (*s != 0)) {
8425 return 0;
8426 }
8427
8428 /* Convert the nonce from the client to a number. */
8429 nonce ^= conn->dom_ctx->auth_nonce_mask;
8430
8431 /* The converted number corresponds to the time the nounce has been
8432 * created. This should not be earlier than the server start. */
8433 /* Server side nonce check is valuable in all situations but one:
8434 * if the server restarts frequently, but the client should not see
8435 * that, so the server should accept nonces from previous starts. */
8436 /* However, the reasonable default is to not accept a nonce from a
8437 * previous start, so if anyone changed the access rights between
8438 * two restarts, a new login is required. */
8439 if (nonce < (uint64_t)conn->phys_ctx->start_time) {
8440 /* nonce is from a previous start of the server and no longer valid
8441 * (replay attack?) */
8442 return 0;
8443 }
8444 /* Check if the nonce is too high, so it has not (yet) been used by the
8445 * server. */
8446 if (nonce >= ((uint64_t)conn->phys_ctx->start_time
8447 + conn->dom_ctx->nonce_count)) {
8448 return 0;
8449 }
8450#else
8451 (void)nonce;
8452#endif
8453
8454 /* CGI needs it as REMOTE_USER */
8455 if (ah->user != NULL) {
8457 mg_strdup_ctx(ah->user, conn->phys_ctx);
8458 } else {
8459 return 0;
8460 }
8461
8462 return 1;
8463}
8464
8465
8466static const char *
8467mg_fgets(char *buf, size_t size, struct mg_file *filep)
8468{
8469 if (!filep) {
8470 return NULL;
8471 }
8472
8473 if (filep->access.fp != NULL) {
8474 return fgets(buf, (int)size, filep->access.fp);
8475 } else {
8476 return NULL;
8477 }
8478}
8479
8480/* Define the initial recursion depth for procesesing htpasswd files that
8481 * include other htpasswd
8482 * (or even the same) files. It is not difficult to provide a file or files
8483 * s.t. they force civetweb
8484 * to infinitely recurse and then crash.
8485 */
8486#define INITIAL_DEPTH 9
8487#if INITIAL_DEPTH <= 0
8488#error Bad INITIAL_DEPTH for recursion, set to at least 1
8489#endif
8490
8491#if !defined(NO_FILESYSTEMS)
8494 struct ah ah;
8495 const char *domain;
8496 char buf[256 + 256 + 40];
8497 const char *f_user;
8498 const char *f_domain;
8499 const char *f_ha1;
8500};
8501
8502
8503static int
8505 struct read_auth_file_struct *workdata,
8506 int depth)
8507{
8508 int is_authorized = 0;
8509 struct mg_file fp;
8510 size_t l;
8511
8512 if (!filep || !workdata || (0 == depth)) {
8513 return 0;
8514 }
8515
8516 /* Loop over passwords file */
8517 while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
8518 l = strlen(workdata->buf);
8519 while (l > 0) {
8520 if (isspace((unsigned char)workdata->buf[l - 1])
8521 || iscntrl((unsigned char)workdata->buf[l - 1])) {
8522 l--;
8523 workdata->buf[l] = 0;
8524 } else
8525 break;
8526 }
8527 if (l < 1) {
8528 continue;
8529 }
8530
8531 workdata->f_user = workdata->buf;
8532
8533 if (workdata->f_user[0] == ':') {
8534 /* user names may not contain a ':' and may not be empty,
8535 * so lines starting with ':' may be used for a special purpose
8536 */
8537 if (workdata->f_user[1] == '#') {
8538 /* :# is a comment */
8539 continue;
8540 } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
8541 if (mg_fopen(workdata->conn,
8542 workdata->f_user + 9,
8544 &fp)) {
8545 is_authorized = read_auth_file(&fp, workdata, depth - 1);
8546 (void)mg_fclose(
8547 &fp.access); /* ignore error on read only file */
8548
8549 /* No need to continue processing files once we have a
8550 * match, since nothing will reset it back
8551 * to 0.
8552 */
8553 if (is_authorized) {
8554 return is_authorized;
8555 }
8556 } else {
8557 mg_cry_internal(workdata->conn,
8558 "%s: cannot open authorization file: %s",
8559 __func__,
8560 workdata->buf);
8561 }
8562 continue;
8563 }
8564 /* everything is invalid for the moment (might change in the
8565 * future) */
8566 mg_cry_internal(workdata->conn,
8567 "%s: syntax error in authorization file: %s",
8568 __func__,
8569 workdata->buf);
8570 continue;
8571 }
8572
8573 workdata->f_domain = strchr(workdata->f_user, ':');
8574 if (workdata->f_domain == NULL) {
8575 mg_cry_internal(workdata->conn,
8576 "%s: syntax error in authorization file: %s",
8577 __func__,
8578 workdata->buf);
8579 continue;
8580 }
8581 *(char *)(workdata->f_domain) = 0;
8582 (workdata->f_domain)++;
8583
8584 workdata->f_ha1 = strchr(workdata->f_domain, ':');
8585 if (workdata->f_ha1 == NULL) {
8586 mg_cry_internal(workdata->conn,
8587 "%s: syntax error in authorization file: %s",
8588 __func__,
8589 workdata->buf);
8590 continue;
8591 }
8592 *(char *)(workdata->f_ha1) = 0;
8593 (workdata->f_ha1)++;
8594
8595 if (!strcmp(workdata->ah.user, workdata->f_user)
8596 && !strcmp(workdata->domain, workdata->f_domain)) {
8598 workdata->f_ha1,
8599 workdata->ah.uri,
8600 workdata->ah.nonce,
8601 workdata->ah.nc,
8602 workdata->ah.cnonce,
8603 workdata->ah.qop,
8604 workdata->ah.response);
8605 }
8606 }
8607
8608 return is_authorized;
8609}
8610
8611
8612/* Authorize against the opened passwords file. Return 1 if authorized. */
8613static int
8614authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
8615{
8616 struct read_auth_file_struct workdata;
8617 char buf[MG_BUF_LEN];
8618
8619 if (!conn || !conn->dom_ctx) {
8620 return 0;
8621 }
8622
8623 memset(&workdata, 0, sizeof(workdata));
8624 workdata.conn = conn;
8625
8626 if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
8627 return 0;
8628 }
8629
8630 if (realm) {
8631 workdata.domain = realm;
8632 } else {
8634 }
8635
8636 return read_auth_file(filep, &workdata, INITIAL_DEPTH);
8637}
8638
8639
8640/* Public function to check http digest authentication header */
8641int
8643 const char *realm,
8644 const char *filename)
8645{
8647 int auth;
8648
8649 if (!conn || !filename) {
8650 return -1;
8651 }
8652 if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
8653 return -2;
8654 }
8655
8656 auth = authorize(conn, &file, realm);
8657
8658 mg_fclose(&file.access);
8659
8660 return auth;
8661}
8662#endif /* NO_FILESYSTEMS */
8663
8664
8665/* Return 1 if request is authorised, 0 otherwise. */
8666static int
8667check_authorization(struct mg_connection *conn, const char *path)
8668{
8669#if !defined(NO_FILESYSTEMS)
8670 char fname[UTF8_PATH_MAX];
8671 struct vec uri_vec, filename_vec;
8672 const char *list;
8674 int authorized = 1, truncated;
8675
8676 if (!conn || !conn->dom_ctx) {
8677 return 0;
8678 }
8679
8680 list = conn->dom_ctx->config[PROTECT_URI];
8681 while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
8682 if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
8683 mg_snprintf(conn,
8684 &truncated,
8685 fname,
8686 sizeof(fname),
8687 "%.*s",
8688 (int)filename_vec.len,
8689 filename_vec.ptr);
8690
8691 if (truncated
8692 || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
8693 mg_cry_internal(conn,
8694 "%s: cannot open %s: %s",
8695 __func__,
8696 fname,
8697 strerror(errno));
8698 }
8699 break;
8700 }
8701 }
8702
8703 if (!is_file_opened(&file.access)) {
8704 open_auth_file(conn, path, &file);
8705 }
8706
8707 if (is_file_opened(&file.access)) {
8708 authorized = authorize(conn, &file, NULL);
8709 (void)mg_fclose(&file.access); /* ignore error on read only file */
8710 }
8711
8712 return authorized;
8713#else
8714 (void)conn;
8715 (void)path;
8716 return 1;
8717#endif /* NO_FILESYSTEMS */
8718}
8719
8720
8721/* Internal function. Assumes conn is valid */
8722static void
8723send_authorization_request(struct mg_connection *conn, const char *realm)
8724{
8725 uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
8726 int trunc = 0;
8727 char buf[128];
8728
8729 if (!realm) {
8730 realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
8731 }
8732
8734 nonce += conn->dom_ctx->nonce_count;
8735 ++conn->dom_ctx->nonce_count;
8737
8738 nonce ^= conn->dom_ctx->auth_nonce_mask;
8739 conn->must_close = 1;
8740
8741 /* Create 401 response */
8742 mg_response_header_start(conn, 401);
8745 mg_response_header_add(conn, "Content-Length", "0", -1);
8746
8747 /* Content for "WWW-Authenticate" header */
8748 mg_snprintf(conn,
8749 &trunc,
8750 buf,
8751 sizeof(buf),
8752 "Digest qop=\"auth\", realm=\"%s\", "
8753 "nonce=\"%" UINT64_FMT "\"",
8754 realm,
8755 nonce);
8756
8757 if (!trunc) {
8758 /* !trunc should always be true */
8759 mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
8760 }
8761
8762 /* Send all headers */
8764}
8765
8766
8767/* Interface function. Parameters are provided by the user, so do
8768 * at least some basic checks.
8769 */
8770int
8772 const char *realm)
8773{
8774 if (conn && conn->dom_ctx) {
8775 send_authorization_request(conn, realm);
8776 return 0;
8777 }
8778 return -1;
8779}
8780
8781
8782#if !defined(NO_FILES)
8783static int
8785{
8786 if (conn) {
8788 const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
8789 int ret = 0;
8790
8791 if (passfile != NULL
8792 && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
8793 ret = authorize(conn, &file, NULL);
8794 (void)mg_fclose(&file.access); /* ignore error on read only file */
8795 }
8796
8797 return ret;
8798 }
8799 return 0;
8800}
8801#endif
8802
8803
8804static int
8805modify_passwords_file(const char *fname,
8806 const char *domain,
8807 const char *user,
8808 const char *pass,
8809 const char *ha1)
8810{
8811 int found, i;
8812 char line[512], u[512] = "", d[512] = "", ha1buf[33],
8813 tmp[UTF8_PATH_MAX + 8];
8814 FILE *fp, *fp2;
8815
8816 found = 0;
8817 fp = fp2 = NULL;
8818
8819 /* Regard empty password as no password - remove user record. */
8820 if ((pass != NULL) && (pass[0] == '\0')) {
8821 pass = NULL;
8822 }
8823
8824 /* Other arguments must not be empty */
8825 if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
8826 return 0;
8827 }
8828
8829 /* Using the given file format, user name and domain must not contain
8830 * ':'
8831 */
8832 if (strchr(user, ':') != NULL) {
8833 return 0;
8834 }
8835 if (strchr(domain, ':') != NULL) {
8836 return 0;
8837 }
8838
8839 /* Do not allow control characters like newline in user name and domain.
8840 * Do not allow excessively long names either. */
8841 for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
8842 if (iscntrl((unsigned char)user[i])) {
8843 return 0;
8844 }
8845 }
8846 if (user[i]) {
8847 return 0;
8848 }
8849 for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
8850 if (iscntrl((unsigned char)domain[i])) {
8851 return 0;
8852 }
8853 }
8854 if (domain[i]) {
8855 return 0;
8856 }
8857
8858 /* The maximum length of the path to the password file is limited */
8859 if ((strlen(fname) + 4) >= UTF8_PATH_MAX) {
8860 return 0;
8861 }
8862
8863 /* Create a temporary file name. Length has been checked before. */
8864 strcpy(tmp, fname);
8865 strcat(tmp, ".tmp");
8866
8867 /* Create the file if does not exist */
8868 /* Use of fopen here is OK, since fname is only ASCII */
8869 if ((fp = fopen(fname, "a+")) != NULL) {
8870 (void)fclose(fp);
8871 }
8872
8873 /* Open the given file and temporary file */
8874 if ((fp = fopen(fname, "r")) == NULL) {
8875 return 0;
8876 } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
8877 fclose(fp);
8878 return 0;
8879 }
8880
8881 /* Copy the stuff to temporary file */
8882 while (fgets(line, sizeof(line), fp) != NULL) {
8883 if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
8884 continue;
8885 }
8886 u[255] = 0;
8887 d[255] = 0;
8888
8889 if (!strcmp(u, user) && !strcmp(d, domain)) {
8890 found++;
8891 if (pass != NULL) {
8892 mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
8893 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1buf);
8894 } else if (ha1 != NULL) {
8895 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8896 }
8897 } else {
8898 fprintf(fp2, "%s", line);
8899 }
8900 }
8901
8902 /* If new user, just add it */
8903 if (!found) {
8904 if (pass != NULL) {
8905 mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
8906 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1buf);
8907 } else if (ha1 != NULL) {
8908 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8909 }
8910 }
8911
8912 /* Close files */
8913 fclose(fp);
8914 fclose(fp2);
8915
8916 /* Put the temp file in place of real file */
8917 IGNORE_UNUSED_RESULT(remove(fname));
8918 IGNORE_UNUSED_RESULT(rename(tmp, fname));
8919
8920 return 1;
8921}
8922
8923
8924int
8926 const char *domain,
8927 const char *user,
8928 const char *pass)
8929{
8930 return modify_passwords_file(fname, domain, user, pass, NULL);
8931}
8932
8933
8934int
8936 const char *domain,
8937 const char *user,
8938 const char *ha1)
8939{
8940 return modify_passwords_file(fname, domain, user, NULL, ha1);
8941}
8942
8943
8944static int
8945is_valid_port(unsigned long port)
8946{
8947 return (port <= 0xffff);
8948}
8949
8950
8951static int
8952mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
8953{
8954 struct addrinfo hints, *res, *ressave;
8955 int func_ret = 0;
8956 int gai_ret;
8957
8958 memset(&hints, 0, sizeof(struct addrinfo));
8959 hints.ai_family = af;
8960 if (!resolve_src) {
8961 hints.ai_flags = AI_NUMERICHOST;
8962 }
8963
8964 gai_ret = getaddrinfo(src, NULL, &hints, &res);
8965 if (gai_ret != 0) {
8966 /* gai_strerror could be used to convert gai_ret to a string */
8967 /* POSIX return values: see
8968 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
8969 */
8970 /* Windows return values: see
8971 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
8972 */
8973 return 0;
8974 }
8975
8976 ressave = res;
8977
8978 while (res) {
8979 if ((dstlen >= (size_t)res->ai_addrlen)
8980 && (res->ai_addr->sa_family == af)) {
8981 memcpy(dst, res->ai_addr, res->ai_addrlen);
8982 func_ret = 1;
8983 }
8984 res = res->ai_next;
8985 }
8986
8987 freeaddrinfo(ressave);
8988 return func_ret;
8989}
8990
8991
8992static int
8994 struct mg_context *ctx /* may be NULL */,
8995 const char *host,
8996 int port, /* 1..65535, or -99 for domain sockets (may be changed) */
8997 int use_ssl, /* 0 or 1 */
8998 char *ebuf,
8999 size_t ebuf_len,
9000 SOCKET *sock /* output: socket, must not be NULL */,
9001 union usa *sa /* output: socket address, must not be NULL */
9002)
9003{
9004 int ip_ver = 0;
9005 int conn_ret = -1;
9006 int sockerr = 0;
9007 *sock = INVALID_SOCKET;
9008 memset(sa, 0, sizeof(*sa));
9009
9010 if (ebuf_len > 0) {
9011 *ebuf = 0;
9012 }
9013
9014 if (host == NULL) {
9015 mg_snprintf(NULL,
9016 NULL, /* No truncation check for ebuf */
9017 ebuf,
9018 ebuf_len,
9019 "%s",
9020 "NULL host");
9021 return 0;
9022 }
9023
9024#if defined(USE_X_DOM_SOCKET)
9025 if (port == -99) {
9026 /* Unix domain socket */
9027 size_t hostlen = strlen(host);
9028 if (hostlen >= sizeof(sa->sun.sun_path)) {
9029 mg_snprintf(NULL,
9030 NULL, /* No truncation check for ebuf */
9031 ebuf,
9032 ebuf_len,
9033 "%s",
9034 "host length exceeds limit");
9035 return 0;
9036 }
9037 } else
9038#endif
9039 if ((port <= 0) || !is_valid_port((unsigned)port)) {
9040 mg_snprintf(NULL,
9041 NULL, /* No truncation check for ebuf */
9042 ebuf,
9043 ebuf_len,
9044 "%s",
9045 "invalid port");
9046 return 0;
9047 }
9048
9049#if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
9050#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
9051 if (use_ssl && (TLS_client_method == NULL)) {
9052 mg_snprintf(NULL,
9053 NULL, /* No truncation check for ebuf */
9054 ebuf,
9055 ebuf_len,
9056 "%s",
9057 "SSL is not initialized");
9058 return 0;
9059 }
9060#else
9061 if (use_ssl && (SSLv23_client_method == NULL)) {
9062 mg_snprintf(NULL,
9063 NULL, /* No truncation check for ebuf */
9064 ebuf,
9065 ebuf_len,
9066 "%s",
9067 "SSL is not initialized");
9068 return 0;
9069 }
9070#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
9071#else
9072 (void)use_ssl;
9073#endif /* NO SSL */
9074
9075
9076#if defined(USE_X_DOM_SOCKET)
9077 if (port == -99) {
9078 size_t hostlen = strlen(host);
9079 /* check (hostlen < sizeof(sun.sun_path)) already passed above */
9080 ip_ver = -99;
9081 sa->sun.sun_family = AF_UNIX;
9082 memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
9083 memcpy(sa->sun.sun_path, host, hostlen);
9084 } else
9085#endif
9086 if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
9087 sa->sin.sin_port = htons((uint16_t)port);
9088 ip_ver = 4;
9089#if defined(USE_IPV6)
9090 } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
9091 sa->sin6.sin6_port = htons((uint16_t)port);
9092 ip_ver = 6;
9093 } else if (host[0] == '[') {
9094 /* While getaddrinfo on Windows will work with [::1],
9095 * getaddrinfo on Linux only works with ::1 (without []). */
9096 size_t l = strlen(host + 1);
9097 char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
9098 if (h) {
9099 h[l - 1] = 0;
9100 if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
9101 sa->sin6.sin6_port = htons((uint16_t)port);
9102 ip_ver = 6;
9103 }
9104 mg_free(h);
9105 }
9106#endif
9107 }
9108
9109 if (ip_ver == 0) {
9110 mg_snprintf(NULL,
9111 NULL, /* No truncation check for ebuf */
9112 ebuf,
9113 ebuf_len,
9114 "%s",
9115 "host not found");
9116 return 0;
9117 }
9118
9119 if (ip_ver == 4) {
9120 *sock = socket(PF_INET, SOCK_STREAM, 0);
9121 }
9122#if defined(USE_IPV6)
9123 else if (ip_ver == 6) {
9124 *sock = socket(PF_INET6, SOCK_STREAM, 0);
9125 }
9126#endif
9127#if defined(USE_X_DOM_SOCKET)
9128 else if (ip_ver == -99) {
9129 *sock = socket(AF_UNIX, SOCK_STREAM, 0);
9130 }
9131#endif
9132
9133 if (*sock == INVALID_SOCKET) {
9134 mg_snprintf(NULL,
9135 NULL, /* No truncation check for ebuf */
9136 ebuf,
9137 ebuf_len,
9138 "socket(): %s",
9139 strerror(ERRNO));
9140 return 0;
9141 }
9142
9143 if (0 != set_non_blocking_mode(*sock)) {
9144 mg_snprintf(NULL,
9145 NULL, /* No truncation check for ebuf */
9146 ebuf,
9147 ebuf_len,
9148 "Cannot set socket to non-blocking: %s",
9149 strerror(ERRNO));
9150 closesocket(*sock);
9151 *sock = INVALID_SOCKET;
9152 return 0;
9153 }
9154
9155 set_close_on_exec(*sock, NULL, ctx);
9156
9157 if (ip_ver == 4) {
9158 /* connected with IPv4 */
9159 conn_ret = connect(*sock,
9160 (struct sockaddr *)((void *)&sa->sin),
9161 sizeof(sa->sin));
9162 }
9163#if defined(USE_IPV6)
9164 else if (ip_ver == 6) {
9165 /* connected with IPv6 */
9166 conn_ret = connect(*sock,
9167 (struct sockaddr *)((void *)&sa->sin6),
9168 sizeof(sa->sin6));
9169 }
9170#endif
9171#if defined(USE_X_DOM_SOCKET)
9172 else if (ip_ver == -99) {
9173 /* connected to domain socket */
9174 conn_ret = connect(*sock,
9175 (struct sockaddr *)((void *)&sa->sun),
9176 sizeof(sa->sun));
9177 }
9178#endif
9179
9180 if (conn_ret != 0) {
9181 sockerr = ERRNO;
9182 }
9183
9184#if defined(_WIN32)
9185 if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
9186#else
9187 if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
9188#endif
9189 /* Data for getsockopt */
9190 void *psockerr = &sockerr;
9191 int ret;
9192
9193#if defined(_WIN32)
9194 int len = (int)sizeof(sockerr);
9195#else
9196 socklen_t len = (socklen_t)sizeof(sockerr);
9197#endif
9198
9199 /* Data for poll */
9200 struct mg_pollfd pfd[1];
9201 int pollres;
9202 int ms_wait = 10000; /* 10 second timeout */
9203 stop_flag_t nonstop;
9204 STOP_FLAG_ASSIGN(&nonstop, 0);
9205
9206 /* For a non-blocking socket, the connect sequence is:
9207 * 1) call connect (will not block)
9208 * 2) wait until the socket is ready for writing (select or poll)
9209 * 3) check connection state with getsockopt
9210 */
9211 pfd[0].fd = *sock;
9212 pfd[0].events = POLLOUT;
9213 pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
9214
9215 if (pollres != 1) {
9216 /* Not connected */
9217 mg_snprintf(NULL,
9218 NULL, /* No truncation check for ebuf */
9219 ebuf,
9220 ebuf_len,
9221 "connect(%s:%d): timeout",
9222 host,
9223 port);
9224 closesocket(*sock);
9225 *sock = INVALID_SOCKET;
9226 return 0;
9227 }
9228
9229#if defined(_WIN32)
9230 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
9231#else
9232 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
9233#endif
9234
9235 if ((ret == 0) && (sockerr == 0)) {
9236 conn_ret = 0;
9237 }
9238 }
9239
9240 if (conn_ret != 0) {
9241 /* Not connected */
9242 mg_snprintf(NULL,
9243 NULL, /* No truncation check for ebuf */
9244 ebuf,
9245 ebuf_len,
9246 "connect(%s:%d): error %s",
9247 host,
9248 port,
9249 strerror(sockerr));
9250 closesocket(*sock);
9251 *sock = INVALID_SOCKET;
9252 return 0;
9253 }
9254
9255 return 1;
9256}
9257
9258
9259int
9260mg_url_encode(const char *src, char *dst, size_t dst_len)
9261{
9262 static const char *dont_escape = "._-$,;~()";
9263 static const char *hex = "0123456789abcdef";
9264 char *pos = dst;
9265 const char *end = dst + dst_len - 1;
9266
9267 for (; ((*src != '\0') && (pos < end)); src++, pos++) {
9268 if (isalnum((unsigned char)*src)
9269 || (strchr(dont_escape, *src) != NULL)) {
9270 *pos = *src;
9271 } else if (pos + 2 < end) {
9272 pos[0] = '%';
9273 pos[1] = hex[(unsigned char)*src >> 4];
9274 pos[2] = hex[(unsigned char)*src & 0xf];
9275 pos += 2;
9276 } else {
9277 break;
9278 }
9279 }
9280
9281 *pos = '\0';
9282 return (*src == '\0') ? (int)(pos - dst) : -1;
9283}
9284
9285/* Return 0 on success, non-zero if an error occurs. */
9286
9287static int
9289{
9290 size_t namesize, escsize, i;
9291 char *href, *esc, *p;
9292 char size[64], mod[64];
9293#if defined(REENTRANT_TIME)
9294 struct tm _tm;
9295 struct tm *tm = &_tm;
9296#else
9297 struct tm *tm;
9298#endif
9299
9300 /* Estimate worst case size for encoding and escaping */
9301 namesize = strlen(de->file_name) + 1;
9302 escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
9303 href = (char *)mg_malloc(namesize * 3 + escsize);
9304 if (href == NULL) {
9305 return -1;
9306 }
9307 mg_url_encode(de->file_name, href, namesize * 3);
9308 esc = NULL;
9309 if (escsize > 0) {
9310 /* HTML escaping needed */
9311 esc = href + namesize * 3;
9312 for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
9313 mg_strlcpy(p, de->file_name + i, 2);
9314 if (*p == '&') {
9315 strcpy(p, "&amp;");
9316 } else if (*p == '<') {
9317 strcpy(p, "&lt;");
9318 } else if (*p == '>') {
9319 strcpy(p, "&gt;");
9320 }
9321 }
9322 }
9323
9324 if (de->file.is_directory) {
9326 NULL, /* Buffer is big enough */
9327 size,
9328 sizeof(size),
9329 "%s",
9330 "[DIRECTORY]");
9331 } else {
9332 /* We use (signed) cast below because MSVC 6 compiler cannot
9333 * convert unsigned __int64 to double. Sigh. */
9334 if (de->file.size < 1024) {
9336 NULL, /* Buffer is big enough */
9337 size,
9338 sizeof(size),
9339 "%d",
9340 (int)de->file.size);
9341 } else if (de->file.size < 0x100000) {
9343 NULL, /* Buffer is big enough */
9344 size,
9345 sizeof(size),
9346 "%.1fk",
9347 (double)de->file.size / 1024.0);
9348 } else if (de->file.size < 0x40000000) {
9350 NULL, /* Buffer is big enough */
9351 size,
9352 sizeof(size),
9353 "%.1fM",
9354 (double)de->file.size / 1048576);
9355 } else {
9357 NULL, /* Buffer is big enough */
9358 size,
9359 sizeof(size),
9360 "%.1fG",
9361 (double)de->file.size / 1073741824);
9362 }
9363 }
9364
9365 /* Note: mg_snprintf will not cause a buffer overflow above.
9366 * So, string truncation checks are not required here. */
9367
9368#if defined(REENTRANT_TIME)
9369 localtime_r(&de->file.last_modified, tm);
9370#else
9371 tm = localtime(&de->file.last_modified);
9372#endif
9373 if (tm != NULL) {
9374 strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
9375 } else {
9376 mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
9377 mod[sizeof(mod) - 1] = '\0';
9378 }
9379 mg_printf(de->conn,
9380 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
9381 "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
9382 href,
9383 de->file.is_directory ? "/" : "",
9384 esc ? esc : de->file_name,
9385 de->file.is_directory ? "/" : "",
9386 mod,
9387 size);
9388 mg_free(href);
9389 return 0;
9390}
9391
9392
9393/* This function is called from send_directory() and used for
9394 * sorting directory entries by size, or name, or modification time.
9395 * On windows, __cdecl specification is needed in case if project is built
9396 * with __stdcall convention. qsort always requires __cdels callback. */
9397static int WINCDECL
9398compare_dir_entries(const void *p1, const void *p2)
9399{
9400 if (p1 && p2) {
9401 const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
9402 const char *query_string = a->conn->request_info.query_string;
9403 int cmp_result = 0;
9404
9405 if ((query_string == NULL) || (query_string[0] == '\0')) {
9406 query_string = "n";
9407 }
9408
9409 if (a->file.is_directory && !b->file.is_directory) {
9410 return -1; /* Always put directories on top */
9411 } else if (!a->file.is_directory && b->file.is_directory) {
9412 return 1; /* Always put directories on top */
9413 } else if (*query_string == 'n') {
9414 cmp_result = strcmp(a->file_name, b->file_name);
9415 } else if (*query_string == 's') {
9416 cmp_result = (a->file.size == b->file.size)
9417 ? 0
9418 : ((a->file.size > b->file.size) ? 1 : -1);
9419 } else if (*query_string == 'd') {
9420 cmp_result =
9421 (a->file.last_modified == b->file.last_modified)
9422 ? 0
9423 : ((a->file.last_modified > b->file.last_modified) ? 1
9424 : -1);
9425 }
9426
9427 return (query_string[1] == 'd') ? -cmp_result : cmp_result;
9428 }
9429 return 0;
9430}
9431
9432
9433static int
9434must_hide_file(struct mg_connection *conn, const char *path)
9435{
9436 if (conn && conn->dom_ctx) {
9437 const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
9438 const char *pattern = conn->dom_ctx->config[HIDE_FILES];
9439 return (match_prefix_strlen(pw_pattern, path) > 0)
9440 || (match_prefix_strlen(pattern, path) > 0);
9441 }
9442 return 0;
9443}
9444
9445
9446#if !defined(NO_FILESYSTEMS)
9447static int
9449 const char *dir,
9450 void *data,
9451 int (*cb)(struct de *, void *))
9452{
9453 char path[UTF8_PATH_MAX];
9454 struct dirent *dp;
9455 DIR *dirp;
9456 struct de de;
9457 int truncated;
9458
9459 if ((dirp = mg_opendir(conn, dir)) == NULL) {
9460 return 0;
9461 } else {
9462 de.conn = conn;
9463
9464 while ((dp = mg_readdir(dirp)) != NULL) {
9465 /* Do not show current dir and hidden files */
9466 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
9467 || must_hide_file(conn, dp->d_name)) {
9468 continue;
9469 }
9470
9472 conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9473
9474 /* If we don't memset stat structure to zero, mtime will have
9475 * garbage and strftime() will segfault later on in
9476 * print_dir_entry(). memset is required only if mg_stat()
9477 * fails. For more details, see
9478 * http://code.google.com/p/mongoose/issues/detail?id=79 */
9479 memset(&de.file, 0, sizeof(de.file));
9480
9481 if (truncated) {
9482 /* If the path is not complete, skip processing. */
9483 continue;
9484 }
9485
9486 if (!mg_stat(conn, path, &de.file)) {
9488 "%s: mg_stat(%s) failed: %s",
9489 __func__,
9490 path,
9491 strerror(ERRNO));
9492 }
9493 de.file_name = dp->d_name;
9494 if (cb(&de, data)) {
9495 /* stopped */
9496 break;
9497 }
9498 }
9499 (void)mg_closedir(dirp);
9500 }
9501 return 1;
9502}
9503#endif /* NO_FILESYSTEMS */
9504
9505
9506#if !defined(NO_FILES)
9507static int
9508remove_directory(struct mg_connection *conn, const char *dir)
9509{
9510 char path[UTF8_PATH_MAX];
9511 struct dirent *dp;
9512 DIR *dirp;
9513 struct de de;
9514 int truncated;
9515 int ok = 1;
9516
9517 if ((dirp = mg_opendir(conn, dir)) == NULL) {
9518 return 0;
9519 } else {
9520 de.conn = conn;
9521
9522 while ((dp = mg_readdir(dirp)) != NULL) {
9523 /* Do not show current dir (but show hidden files as they will
9524 * also be removed) */
9525 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
9526 continue;
9527 }
9528
9530 conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9531
9532 /* If we don't memset stat structure to zero, mtime will have
9533 * garbage and strftime() will segfault later on in
9534 * print_dir_entry(). memset is required only if mg_stat()
9535 * fails. For more details, see
9536 * http://code.google.com/p/mongoose/issues/detail?id=79 */
9537 memset(&de.file, 0, sizeof(de.file));
9538
9539 if (truncated) {
9540 /* Do not delete anything shorter */
9541 ok = 0;
9542 continue;
9543 }
9544
9545 if (!mg_stat(conn, path, &de.file)) {
9547 "%s: mg_stat(%s) failed: %s",
9548 __func__,
9549 path,
9550 strerror(ERRNO));
9551 ok = 0;
9552 }
9553
9554 if (de.file.is_directory) {
9555 if (remove_directory(conn, path) == 0) {
9556 ok = 0;
9557 }
9558 } else {
9559 /* This will fail file is the file is in memory */
9560 if (mg_remove(conn, path) == 0) {
9561 ok = 0;
9562 }
9563 }
9564 }
9565 (void)mg_closedir(dirp);
9566
9567 IGNORE_UNUSED_RESULT(rmdir(dir));
9568 }
9569
9570 return ok;
9571}
9572#endif
9573
9574
9576 struct de *entries;
9578 size_t arr_size;
9579};
9580
9581
9582#if !defined(NO_FILESYSTEMS)
9583static int
9585{
9586 struct dir_scan_data *dsd = (struct dir_scan_data *)data;
9587 struct de *entries = dsd->entries;
9588
9589 if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
9590 /* Here "entries" is a temporary pointer and can be replaced,
9591 * "dsd->entries" is the original pointer */
9592 entries =
9593 (struct de *)mg_realloc(entries,
9594 dsd->arr_size * 2 * sizeof(entries[0]));
9595 if (entries == NULL) {
9596 /* stop scan */
9597 return 1;
9598 }
9599 dsd->entries = entries;
9600 dsd->arr_size *= 2;
9601 }
9602 entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
9603 if (entries[dsd->num_entries].file_name == NULL) {
9604 /* stop scan */
9605 return 1;
9606 }
9607 entries[dsd->num_entries].file = de->file;
9608 entries[dsd->num_entries].conn = de->conn;
9609 dsd->num_entries++;
9610
9611 return 0;
9612}
9613
9614
9615static void
9617{
9618 size_t i;
9619 int sort_direction;
9620 struct dir_scan_data data = {NULL, 0, 128};
9621 char date[64], *esc, *p;
9622 const char *title;
9623 time_t curtime = time(NULL);
9624
9625 if (!conn) {
9626 return;
9627 }
9628
9629 if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
9630 mg_send_http_error(conn,
9631 500,
9632 "Error: Cannot open directory\nopendir(%s): %s",
9633 dir,
9634 strerror(ERRNO));
9635 return;
9636 }
9637
9638 gmt_time_string(date, sizeof(date), &curtime);
9639
9640 esc = NULL;
9641 title = conn->request_info.local_uri;
9642 if (title[strcspn(title, "&<>")]) {
9643 /* HTML escaping needed */
9644 esc = (char *)mg_malloc(strlen(title) * 5 + 1);
9645 if (esc) {
9646 for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
9647 mg_strlcpy(p, title + i, 2);
9648 if (*p == '&') {
9649 strcpy(p, "&amp;");
9650 } else if (*p == '<') {
9651 strcpy(p, "&lt;");
9652 } else if (*p == '>') {
9653 strcpy(p, "&gt;");
9654 }
9655 }
9656 } else {
9657 title = "";
9658 }
9659 }
9660
9661 sort_direction = ((conn->request_info.query_string != NULL)
9662 && (conn->request_info.query_string[0] != '\0')
9663 && (conn->request_info.query_string[1] == 'd'))
9664 ? 'a'
9665 : 'd';
9666
9667 conn->must_close = 1;
9668
9669 /* Create 200 OK response */
9670 mg_response_header_start(conn, 200);
9674 "Content-Type",
9675 "text/html; charset=utf-8",
9676 -1);
9677
9678 /* Send all headers */
9680
9681 /* Body */
9682 mg_printf(conn,
9683 "<html><head><title>Index of %s</title>"
9684 "<style>th {text-align: left;}</style></head>"
9685 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
9686 "<tr><th><a href=\"?n%c\">Name</a></th>"
9687 "<th><a href=\"?d%c\">Modified</a></th>"
9688 "<th><a href=\"?s%c\">Size</a></th></tr>"
9689 "<tr><td colspan=\"3\"><hr></td></tr>",
9690 esc ? esc : title,
9691 esc ? esc : title,
9692 sort_direction,
9693 sort_direction,
9694 sort_direction);
9695 mg_free(esc);
9696
9697 /* Print first entry - link to a parent directory */
9698 mg_printf(conn,
9699 "<tr><td><a href=\"%s\">%s</a></td>"
9700 "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
9701 "..",
9702 "Parent directory",
9703 "-",
9704 "-");
9705
9706 /* Sort and print directory entries */
9707 if (data.entries != NULL) {
9708 qsort(data.entries,
9709 data.num_entries,
9710 sizeof(data.entries[0]),
9712 for (i = 0; i < data.num_entries; i++) {
9713 print_dir_entry(&data.entries[i]);
9714 mg_free(data.entries[i].file_name);
9715 }
9716 mg_free(data.entries);
9717 }
9718
9719 mg_printf(conn, "%s", "</table></pre></body></html>");
9720 conn->status_code = 200;
9721}
9722#endif /* NO_FILESYSTEMS */
9723
9724
9725/* Send len bytes from the opened file to the client. */
9726static void
9728 struct mg_file *filep,
9729 int64_t offset,
9730 int64_t len)
9731{
9732 char buf[MG_BUF_LEN];
9733 int to_read, num_read, num_written;
9734 int64_t size;
9735
9736 if (!filep || !conn) {
9737 return;
9738 }
9739
9740 /* Sanity check the offset */
9741 size = (filep->stat.size > INT64_MAX) ? INT64_MAX
9742 : (int64_t)(filep->stat.size);
9743 offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
9744
9745 if (len > 0 && filep->access.fp != NULL) {
9746 /* file stored on disk */
9747#if defined(__linux__)
9748 /* sendfile is only available for Linux */
9749 if ((conn->ssl == 0) && (conn->throttle == 0)
9750 && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
9751 "yes"))) {
9752 off_t sf_offs = (off_t)offset;
9753 ssize_t sf_sent;
9754 int sf_file = fileno(filep->access.fp);
9755 int loop_cnt = 0;
9756
9757 do {
9758 /* 2147479552 (0x7FFFF000) is a limit found by experiment on
9759 * 64 bit Linux (2^31 minus one memory page of 4k?). */
9760 size_t sf_tosend =
9761 (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
9762 sf_sent =
9763 sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
9764 if (sf_sent > 0) {
9765 len -= sf_sent;
9766 offset += sf_sent;
9767 } else if (loop_cnt == 0) {
9768 /* This file can not be sent using sendfile.
9769 * This might be the case for pseudo-files in the
9770 * /sys/ and /proc/ file system.
9771 * Use the regular user mode copy code instead. */
9772 break;
9773 } else if (sf_sent == 0) {
9774 /* No error, but 0 bytes sent. May be EOF? */
9775 return;
9776 }
9777 loop_cnt++;
9778
9779 } while ((len > 0) && (sf_sent >= 0));
9780
9781 if (sf_sent > 0) {
9782 return; /* OK */
9783 }
9784
9785 /* sf_sent<0 means error, thus fall back to the classic way */
9786 /* This is always the case, if sf_file is not a "normal" file,
9787 * e.g., for sending data from the output of a CGI process. */
9788 offset = (int64_t)sf_offs;
9789 }
9790#endif
9791 if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
9792 mg_cry_internal(conn,
9793 "%s: fseeko() failed: %s",
9794 __func__,
9795 strerror(ERRNO));
9797 conn,
9798 500,
9799 "%s",
9800 "Error: Unable to access file at requested position.");
9801 } else {
9802 while (len > 0) {
9803 /* Calculate how much to read from the file in the buffer */
9804 to_read = sizeof(buf);
9805 if ((int64_t)to_read > len) {
9806 to_read = (int)len;
9807 }
9808
9809 /* Read from file, exit the loop on error */
9810 if ((num_read =
9811 (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
9812 <= 0) {
9813 break;
9814 }
9815
9816 /* Send read bytes to the client, exit the loop on error */
9817 if ((num_written = mg_write(conn, buf, (size_t)num_read))
9818 != num_read) {
9819 break;
9820 }
9821
9822 /* Both read and were successful, adjust counters */
9823 len -= num_written;
9824 }
9825 }
9826 }
9827}
9828
9829
9830static int
9831parse_range_header(const char *header, int64_t *a, int64_t *b)
9832{
9833 return sscanf(header,
9834 "bytes=%" INT64_FMT "-%" INT64_FMT,
9835 a,
9836 b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
9837 // to an integer value, but function will not report
9838 // conversion errors; consider using 'strtol' instead
9839}
9840
9841
9842static void
9843construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
9844{
9845 if ((filestat != NULL) && (buf != NULL)) {
9846 mg_snprintf(NULL,
9847 NULL, /* All calls to construct_etag use 64 byte buffer */
9848 buf,
9849 buf_len,
9850 "\"%lx.%" INT64_FMT "\"",
9851 (unsigned long)filestat->last_modified,
9852 filestat->size);
9853 }
9854}
9855
9856
9857static void
9858fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
9859{
9860 if (filep != NULL && filep->fp != NULL) {
9861#if defined(_WIN32)
9862 (void)conn; /* Unused. */
9863#else
9864 if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
9865 mg_cry_internal(conn,
9866 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
9867 __func__,
9868 strerror(ERRNO));
9869 }
9870#endif
9871 }
9872}
9873
9874
9875#if defined(USE_ZLIB)
9876#include "mod_zlib.inl"
9877#endif
9878
9879
9880#if !defined(NO_FILESYSTEMS)
9881static void
9883 const char *path,
9884 struct mg_file *filep,
9885 const char *mime_type,
9886 const char *additional_headers)
9887{
9888 char lm[64], etag[64];
9889 char range[128]; /* large enough, so there will be no overflow */
9890 const char *range_hdr;
9891 int64_t cl, r1, r2;
9892 struct vec mime_vec;
9893 int n, truncated;
9894 char gz_path[UTF8_PATH_MAX];
9895 const char *encoding = 0;
9896 const char *origin_hdr;
9897 const char *cors_orig_cfg;
9898 const char *cors1, *cors2;
9899 int is_head_request;
9900
9901#if defined(USE_ZLIB)
9902 /* Compression is allowed, unless there is a reason not to use
9903 * compression. If the file is already compressed, too small or a
9904 * "range" request was made, on the fly compression is not possible. */
9905 int allow_on_the_fly_compression = 1;
9906#endif
9907
9908 if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
9909 return;
9910 }
9911
9912 is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
9913
9914 if (mime_type == NULL) {
9915 get_mime_type(conn, path, &mime_vec);
9916 } else {
9917 mime_vec.ptr = mime_type;
9918 mime_vec.len = strlen(mime_type);
9919 }
9920 if (filep->stat.size > INT64_MAX) {
9921 mg_send_http_error(conn,
9922 500,
9923 "Error: File size is too large to send\n%" INT64_FMT,
9924 filep->stat.size);
9925 return;
9926 }
9927 cl = (int64_t)filep->stat.size;
9928 conn->status_code = 200;
9929 range[0] = '\0';
9930
9931#if defined(USE_ZLIB)
9932 /* if this file is in fact a pre-gzipped file, rewrite its filename
9933 * it's important to rewrite the filename after resolving
9934 * the mime type from it, to preserve the actual file's type */
9935 if (!conn->accept_gzip) {
9936 allow_on_the_fly_compression = 0;
9937 }
9938#endif
9939
9940 /* Check if there is a range header */
9941 range_hdr = mg_get_header(conn, "Range");
9942
9943 /* For gzipped files, add *.gz */
9944 if (filep->stat.is_gzipped) {
9945 mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
9946
9947 if (truncated) {
9948 mg_send_http_error(conn,
9949 500,
9950 "Error: Path of zipped file too long (%s)",
9951 path);
9952 return;
9953 }
9954
9955 path = gz_path;
9956 encoding = "gzip";
9957
9958#if defined(USE_ZLIB)
9959 /* File is already compressed. No "on the fly" compression. */
9960 allow_on_the_fly_compression = 0;
9961#endif
9962 } else if ((conn->accept_gzip) && (range_hdr == NULL)
9963 && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
9964 struct mg_file_stat file_stat;
9965
9966 mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
9967
9968 if (!truncated && mg_stat(conn, gz_path, &file_stat)
9969 && !file_stat.is_directory) {
9970 file_stat.is_gzipped = 1;
9971 filep->stat = file_stat;
9972 cl = (int64_t)filep->stat.size;
9973 path = gz_path;
9974 encoding = "gzip";
9975
9976#if defined(USE_ZLIB)
9977 /* File is already compressed. No "on the fly" compression. */
9978 allow_on_the_fly_compression = 0;
9979#endif
9980 }
9981 }
9982
9983 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
9984 mg_send_http_error(conn,
9985 500,
9986 "Error: Cannot open file\nfopen(%s): %s",
9987 path,
9988 strerror(ERRNO));
9989 return;
9990 }
9991
9992 fclose_on_exec(&filep->access, conn);
9993
9994 /* If "Range" request was made: parse header, send only selected part
9995 * of the file. */
9996 r1 = r2 = 0;
9997 if ((range_hdr != NULL)
9998 && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
9999 && (r2 >= 0)) {
10000 /* actually, range requests don't play well with a pre-gzipped
10001 * file (since the range is specified in the uncompressed space) */
10002 if (filep->stat.is_gzipped) {
10004 conn,
10005 416, /* 416 = Range Not Satisfiable */
10006 "%s",
10007 "Error: Range requests in gzipped files are not supported");
10008 (void)mg_fclose(
10009 &filep->access); /* ignore error on read only file */
10010 return;
10011 }
10012 conn->status_code = 206;
10013 cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
10014 mg_snprintf(conn,
10015 NULL, /* range buffer is big enough */
10016 range,
10017 sizeof(range),
10018 "bytes "
10019 "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
10020 r1,
10021 r1 + cl - 1,
10022 filep->stat.size);
10023
10024#if defined(USE_ZLIB)
10025 /* Do not compress ranges. */
10026 allow_on_the_fly_compression = 0;
10027#endif
10028 }
10029
10030 /* Do not compress small files. Small files do not benefit from file
10031 * compression, but there is still some overhead. */
10032#if defined(USE_ZLIB)
10034 /* File is below the size limit. */
10035 allow_on_the_fly_compression = 0;
10036 }
10037#endif
10038
10039 /* Standard CORS header */
10040 cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
10041 origin_hdr = mg_get_header(conn, "Origin");
10042 if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
10043 /* Cross-origin resource sharing (CORS), see
10044 * http://www.html5rocks.com/en/tutorials/cors/,
10045 * http://www.html5rocks.com/static/images/cors_server_flowchart.png
10046 * -
10047 * preflight is not supported for files. */
10048 cors1 = "Access-Control-Allow-Origin";
10049 cors2 = cors_orig_cfg;
10050 } else {
10051 cors1 = cors2 = "";
10052 }
10053
10054 /* Prepare Etag, and Last-Modified headers. */
10055 gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
10056 construct_etag(etag, sizeof(etag), &filep->stat);
10057
10058 /* Create 2xx (200, 206) response */
10063 "Content-Type",
10064 mime_vec.ptr,
10065 (int)mime_vec.len);
10066 if (cors1[0] != 0) {
10067 mg_response_header_add(conn, cors1, cors2, -1);
10068 }
10069 mg_response_header_add(conn, "Last-Modified", lm, -1);
10070 mg_response_header_add(conn, "Etag", etag, -1);
10071
10072#if defined(USE_ZLIB)
10073 /* On the fly compression allowed */
10074 if (allow_on_the_fly_compression) {
10075 /* For on the fly compression, we don't know the content size in
10076 * advance, so we have to use chunked encoding */
10077 encoding = "gzip";
10078 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
10079 /* HTTP/2 is always using "chunks" (frames) */
10080 mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
10081 }
10082
10083 } else
10084#endif
10085 {
10086 /* Without on-the-fly compression, we know the content-length
10087 * and we can use ranges (with on-the-fly compression we cannot).
10088 * So we send these response headers only in this case. */
10089 char len[32];
10090 int trunc = 0;
10091 mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
10092
10093 if (!trunc) {
10094 mg_response_header_add(conn, "Content-Length", len, -1);
10095 }
10096
10097 mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
10098 }
10099
10100 if (encoding) {
10101 mg_response_header_add(conn, "Content-Encoding", encoding, -1);
10102 }
10103 if (range[0] != 0) {
10104 mg_response_header_add(conn, "Content-Range", range, -1);
10105 }
10106
10107 /* The code above does not add any header starting with X- to make
10108 * sure no one of the additional_headers is included twice */
10109 if ((additional_headers != NULL) && (*additional_headers != 0)) {
10110 mg_response_header_add_lines(conn, additional_headers);
10111 }
10112
10113 /* Send all headers */
10115
10116 if (!is_head_request) {
10117#if defined(USE_ZLIB)
10118 if (allow_on_the_fly_compression) {
10119 /* Compress and send */
10120 send_compressed_data(conn, filep);
10121 } else
10122#endif
10123 {
10124 /* Send file directly */
10125 send_file_data(conn, filep, r1, cl);
10126 }
10127 }
10128 (void)mg_fclose(&filep->access); /* ignore error on read only file */
10129}
10130
10131
10132int
10133mg_send_file_body(struct mg_connection *conn, const char *path)
10134{
10136 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
10137 return -1;
10138 }
10139 fclose_on_exec(&file.access, conn);
10140 send_file_data(conn, &file, 0, INT64_MAX);
10141 (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
10142 return 0; /* >= 0 for OK */
10143}
10144#endif /* NO_FILESYSTEMS */
10145
10146
10147#if !defined(NO_CACHING)
10148/* Return True if we should reply 304 Not Modified. */
10149static int
10151 const struct mg_file_stat *filestat)
10152{
10153 char etag[64];
10154 const char *ims = mg_get_header(conn, "If-Modified-Since");
10155 const char *inm = mg_get_header(conn, "If-None-Match");
10156 construct_etag(etag, sizeof(etag), filestat);
10157
10158 return ((inm != NULL) && !mg_strcasecmp(etag, inm))
10159 || ((ims != NULL)
10160 && (filestat->last_modified <= parse_date_string(ims)));
10161}
10162
10163
10164static void
10166 struct mg_file *filep)
10167{
10168 char lm[64], etag[64];
10169
10170 if ((conn == NULL) || (filep == NULL)) {
10171 return;
10172 }
10173
10174 gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
10175 construct_etag(etag, sizeof(etag), &filep->stat);
10176
10177 /* Create 304 "not modified" response */
10178 mg_response_header_start(conn, 304);
10181 mg_response_header_add(conn, "Last-Modified", lm, -1);
10182 mg_response_header_add(conn, "Etag", etag, -1);
10183
10184 /* Send all headers */
10186}
10187#endif
10188
10189
10190#if !defined(NO_FILESYSTEMS)
10191void
10192mg_send_file(struct mg_connection *conn, const char *path)
10193{
10194 mg_send_mime_file2(conn, path, NULL, NULL);
10195}
10196
10197
10198void
10200 const char *path,
10201 const char *mime_type)
10202{
10203 mg_send_mime_file2(conn, path, mime_type, NULL);
10204}
10205
10206
10207void
10209 const char *path,
10210 const char *mime_type,
10211 const char *additional_headers)
10212{
10214
10215 if (!conn) {
10216 /* No conn */
10217 return;
10218 }
10219
10220 if (mg_stat(conn, path, &file.stat)) {
10221#if !defined(NO_CACHING)
10222 if (is_not_modified(conn, &file.stat)) {
10223 /* Send 304 "Not Modified" - this must not send any body data */
10225 } else
10226#endif /* NO_CACHING */
10227 if (file.stat.is_directory) {
10229 "yes")) {
10230 handle_directory_request(conn, path);
10231 } else {
10232 mg_send_http_error(conn,
10233 403,
10234 "%s",
10235 "Error: Directory listing denied");
10236 }
10237 } else {
10239 conn, path, &file, mime_type, additional_headers);
10240 }
10241 } else {
10242 mg_send_http_error(conn, 404, "%s", "Error: File not found");
10243 }
10244}
10245
10246
10247/* For a given PUT path, create all intermediate subdirectories.
10248 * Return 0 if the path itself is a directory.
10249 * Return 1 if the path leads to a file.
10250 * Return -1 for if the path is too long.
10251 * Return -2 if path can not be created.
10252 */
10253static int
10254put_dir(struct mg_connection *conn, const char *path)
10255{
10256 char buf[UTF8_PATH_MAX];
10257 const char *s, *p;
10259 size_t len;
10260 int res = 1;
10261
10262 for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
10263 len = (size_t)(p - path);
10264 if (len >= sizeof(buf)) {
10265 /* path too long */
10266 res = -1;
10267 break;
10268 }
10269 memcpy(buf, path, len);
10270 buf[len] = '\0';
10271
10272 /* Try to create intermediate directory */
10273 DEBUG_TRACE("mkdir(%s)", buf);
10274 if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
10275 /* path does not exixt and can not be created */
10276 res = -2;
10277 break;
10278 }
10279
10280 /* Is path itself a directory? */
10281 if (p[1] == '\0') {
10282 res = 0;
10283 }
10284 }
10285
10286 return res;
10287}
10288
10289
10290static void
10291remove_bad_file(const struct mg_connection *conn, const char *path)
10292{
10293 int r = mg_remove(conn, path);
10294 if (r != 0) {
10295 mg_cry_internal(conn,
10296 "%s: Cannot remove invalid file %s",
10297 __func__,
10298 path);
10299 }
10300}
10301
10302
10303long long
10304mg_store_body(struct mg_connection *conn, const char *path)
10305{
10306 char buf[MG_BUF_LEN];
10307 long long len = 0;
10308 int ret, n;
10309 struct mg_file fi;
10310
10311 if (conn->consumed_content != 0) {
10312 mg_cry_internal(conn, "%s: Contents already consumed", __func__);
10313 return -11;
10314 }
10315
10316 ret = put_dir(conn, path);
10317 if (ret < 0) {
10318 /* -1 for path too long,
10319 * -2 for path can not be created. */
10320 return ret;
10321 }
10322 if (ret != 1) {
10323 /* Return 0 means, path itself is a directory. */
10324 return 0;
10325 }
10326
10327 if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
10328 return -12;
10329 }
10330
10331 ret = mg_read(conn, buf, sizeof(buf));
10332 while (ret > 0) {
10333 n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
10334 if (n != ret) {
10335 (void)mg_fclose(
10336 &fi.access); /* File is bad and will be removed anyway. */
10337 remove_bad_file(conn, path);
10338 return -13;
10339 }
10340 len += ret;
10341 ret = mg_read(conn, buf, sizeof(buf));
10342 }
10343
10344 /* File is open for writing. If fclose fails, there was probably an
10345 * error flushing the buffer to disk, so the file on disk might be
10346 * broken. Delete it and return an error to the caller. */
10347 if (mg_fclose(&fi.access) != 0) {
10348 remove_bad_file(conn, path);
10349 return -14;
10350 }
10351
10352 return len;
10353}
10354#endif /* NO_FILESYSTEMS */
10355
10356
10357/* Parse a buffer:
10358 * Forward the string pointer till the end of a word, then
10359 * terminate it and forward till the begin of the next word.
10360 */
10361static int
10363{
10364 /* Forward until a space is found - use isgraph here */
10365 /* See http://www.cplusplus.com/reference/cctype/ */
10366 while (isgraph((unsigned char)**ppw)) {
10367 (*ppw)++;
10368 }
10369
10370 /* Check end of word */
10371 if (eol) {
10372 /* must be a end of line */
10373 if ((**ppw != '\r') && (**ppw != '\n')) {
10374 return -1;
10375 }
10376 } else {
10377 /* must be a end of a word, but not a line */
10378 if (**ppw != ' ') {
10379 return -1;
10380 }
10381 }
10382
10383 /* Terminate and forward to the next word */
10384 do {
10385 **ppw = 0;
10386 (*ppw)++;
10387 } while (isspace((unsigned char)**ppw));
10388
10389 /* Check after term */
10390 if (!eol) {
10391 /* if it's not the end of line, there must be a next word */
10392 if (!isgraph((unsigned char)**ppw)) {
10393 return -1;
10394 }
10395 }
10396
10397 /* ok */
10398 return 1;
10399}
10400
10401
10402/* Parse HTTP headers from the given buffer, advance buf pointer
10403 * to the point where parsing stopped.
10404 * All parameters must be valid pointers (not NULL).
10405 * Return <0 on error. */
10406static int
10408{
10409 int i;
10410 int num_headers = 0;
10411
10412 for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
10413 char *dp = *buf;
10414
10415 /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
10416 while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
10417 dp++;
10418 }
10419 if (dp == *buf) {
10420 /* End of headers reached. */
10421 break;
10422 }
10423
10424 /* Drop all spaces after header name before : */
10425 while (*dp == ' ') {
10426 *dp = 0;
10427 dp++;
10428 }
10429 if (*dp != ':') {
10430 /* This is not a valid field. */
10431 return -1;
10432 }
10433
10434 /* End of header key (*dp == ':') */
10435 /* Truncate here and set the key name */
10436 *dp = 0;
10437 hdr[i].name = *buf;
10438
10439 /* Skip all spaces */
10440 do {
10441 dp++;
10442 } while ((*dp == ' ') || (*dp == '\t'));
10443
10444 /* The rest of the line is the value */
10445 hdr[i].value = dp;
10446
10447 /* Find end of line */
10448 while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
10449 dp++;
10450 };
10451
10452 /* eliminate \r */
10453 if (*dp == '\r') {
10454 *dp = 0;
10455 dp++;
10456 if (*dp != '\n') {
10457 /* This is not a valid line. */
10458 return -1;
10459 }
10460 }
10461
10462 /* here *dp is either 0 or '\n' */
10463 /* in any case, we have a new header */
10464 num_headers = i + 1;
10465
10466 if (*dp) {
10467 *dp = 0;
10468 dp++;
10469 *buf = dp;
10470
10471 if ((dp[0] == '\r') || (dp[0] == '\n')) {
10472 /* This is the end of the header */
10473 break;
10474 }
10475 } else {
10476 *buf = dp;
10477 break;
10478 }
10479 }
10480 return num_headers;
10481}
10482
10483
10485 const char *name;
10491};
10492
10493
10494/* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
10495static const struct mg_http_method_info http_methods[] = {
10496 /* HTTP (RFC 2616) */
10497 {"GET", 0, 1, 1, 1, 1},
10498 {"POST", 1, 1, 0, 0, 0},
10499 {"PUT", 1, 0, 0, 1, 0},
10500 {"DELETE", 0, 0, 0, 1, 0},
10501 {"HEAD", 0, 0, 1, 1, 1},
10502 {"OPTIONS", 0, 0, 1, 1, 0},
10503 {"CONNECT", 1, 1, 0, 0, 0},
10504 /* TRACE method (RFC 2616) is not supported for security reasons */
10505
10506 /* PATCH method (RFC 5789) */
10507 {"PATCH", 1, 0, 0, 0, 0},
10508 /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
10509
10510 /* WEBDAV (RFC 2518) */
10511 {"PROPFIND", 0, 1, 1, 1, 0},
10512 /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10513 * Some PROPFIND results MAY be cached, with care,
10514 * as there is no cache validation mechanism for
10515 * most properties. This method is both safe and
10516 * idempotent (see Section 9.1 of [RFC2616]). */
10517 {"MKCOL", 0, 0, 0, 1, 0},
10518 /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10519 * When MKCOL is invoked without a request body,
10520 * the newly created collection SHOULD have no
10521 * members. A MKCOL request message may contain
10522 * a message body. The precise behavior of a MKCOL
10523 * request when the body is present is undefined,
10524 * ... ==> We do not support MKCOL with body data.
10525 * This method is idempotent, but not safe (see
10526 * Section 9.1 of [RFC2616]). Responses to this
10527 * method MUST NOT be cached. */
10528
10529 /* Methods for write access to files on WEBDAV (RFC 2518) */
10530 {"LOCK", 1, 1, 0, 0, 0},
10531 {"UNLOCK", 1, 0, 0, 0, 0},
10532 {"PROPPATCH", 1, 1, 0, 0, 0},
10533
10534 /* Unsupported WEBDAV Methods: */
10535 /* COPY, MOVE (RFC 2518) */
10536 /* + 11 methods from RFC 3253 */
10537 /* ORDERPATCH (RFC 3648) */
10538 /* ACL (RFC 3744) */
10539 /* SEARCH (RFC 5323) */
10540 /* + MicroSoft extensions
10541 * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
10542
10543 /* REPORT method (RFC 3253) */
10544 {"REPORT", 1, 1, 1, 1, 1},
10545 /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
10546 /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
10547 * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
10548 * to be useful for REST in case a "GET request with body" is
10549 * required. */
10550
10551 {NULL, 0, 0, 0, 0, 0}
10552 /* end of list */
10553};
10554
10555
10556static const struct mg_http_method_info *
10557get_http_method_info(const char *method)
10558{
10559 /* Check if the method is known to the server. The list of all known
10560 * HTTP methods can be found here at
10561 * http://www.iana.org/assignments/http-methods/http-methods.xhtml
10562 */
10563 const struct mg_http_method_info *m = http_methods;
10564
10565 while (m->name) {
10566 if (!strcmp(m->name, method)) {
10567 return m;
10568 }
10569 m++;
10570 }
10571 return NULL;
10572}
10573
10574
10575static int
10576is_valid_http_method(const char *method)
10577{
10578 return (get_http_method_info(method) != NULL);
10579}
10580
10581
10582/* Parse HTTP request, fill in mg_request_info structure.
10583 * This function modifies the buffer by NUL-terminating
10584 * HTTP request components, header names and header values.
10585 * Parameters:
10586 * buf (in/out): pointer to the HTTP header to parse and split
10587 * len (in): length of HTTP header buffer
10588 * re (out): parsed header as mg_request_info
10589 * buf and ri must be valid pointers (not NULL), len>0.
10590 * Returns <0 on error. */
10591static int
10592parse_http_request(char *buf, int len, struct mg_request_info *ri)
10593{
10594 int request_length;
10595 int init_skip = 0;
10596
10597 /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
10598 * remote_port */
10599 ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
10600 NULL;
10601 ri->num_headers = 0;
10602
10603 /* RFC says that all initial whitespaces should be ignored */
10604 /* This included all leading \r and \n (isspace) */
10605 /* See table: http://www.cplusplus.com/reference/cctype/ */
10606 while ((len > 0) && isspace((unsigned char)*buf)) {
10607 buf++;
10608 len--;
10609 init_skip++;
10610 }
10611
10612 if (len == 0) {
10613 /* Incomplete request */
10614 return 0;
10615 }
10616
10617 /* Control characters are not allowed, including zero */
10618 if (iscntrl((unsigned char)*buf)) {
10619 return -1;
10620 }
10621
10622 /* Find end of HTTP header */
10623 request_length = get_http_header_len(buf, len);
10624 if (request_length <= 0) {
10625 return request_length;
10626 }
10627 buf[request_length - 1] = '\0';
10628
10629 if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10630 return -1;
10631 }
10632
10633 /* The first word has to be the HTTP method */
10634 ri->request_method = buf;
10635
10636 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10637 return -1;
10638 }
10639
10640 /* The second word is the URI */
10641 ri->request_uri = buf;
10642
10643 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10644 return -1;
10645 }
10646
10647 /* Next would be the HTTP version */
10648 ri->http_version = buf;
10649
10650 if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
10651 return -1;
10652 }
10653
10654 /* Check for a valid HTTP version key */
10655 if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
10656 /* Invalid request */
10657 return -1;
10658 }
10659 ri->http_version += 5;
10660
10661 /* Check for a valid http method */
10663 return -1;
10664 }
10665
10666 /* Parse all HTTP headers */
10668 if (ri->num_headers < 0) {
10669 /* Error while parsing headers */
10670 return -1;
10671 }
10672
10673 return request_length + init_skip;
10674}
10675
10676
10677static int
10678parse_http_response(char *buf, int len, struct mg_response_info *ri)
10679{
10680 int response_length;
10681 int init_skip = 0;
10682 char *tmp, *tmp2;
10683 long l;
10684
10685 /* Initialize elements. */
10686 ri->http_version = ri->status_text = NULL;
10687 ri->num_headers = ri->status_code = 0;
10688
10689 /* RFC says that all initial whitespaces should be ingored */
10690 /* This included all leading \r and \n (isspace) */
10691 /* See table: http://www.cplusplus.com/reference/cctype/ */
10692 while ((len > 0) && isspace((unsigned char)*buf)) {
10693 buf++;
10694 len--;
10695 init_skip++;
10696 }
10697
10698 if (len == 0) {
10699 /* Incomplete request */
10700 return 0;
10701 }
10702
10703 /* Control characters are not allowed, including zero */
10704 if (iscntrl((unsigned char)*buf)) {
10705 return -1;
10706 }
10707
10708 /* Find end of HTTP header */
10709 response_length = get_http_header_len(buf, len);
10710 if (response_length <= 0) {
10711 return response_length;
10712 }
10713 buf[response_length - 1] = '\0';
10714
10715 if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10716 return -1;
10717 }
10718
10719 /* The first word is the HTTP version */
10720 /* Check for a valid HTTP version key */
10721 if (strncmp(buf, "HTTP/", 5) != 0) {
10722 /* Invalid request */
10723 return -1;
10724 }
10725 buf += 5;
10726 if (!isgraph((unsigned char)buf[0])) {
10727 /* Invalid request */
10728 return -1;
10729 }
10730 ri->http_version = buf;
10731
10732 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10733 return -1;
10734 }
10735
10736 /* The second word is the status as a number */
10737 tmp = buf;
10738
10739 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10740 return -1;
10741 }
10742
10743 l = strtol(tmp, &tmp2, 10);
10744 if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
10745 /* Everything else but a 3 digit code is invalid */
10746 return -1;
10747 }
10748 ri->status_code = (int)l;
10749
10750 /* The rest of the line is the status text */
10751 ri->status_text = buf;
10752
10753 /* Find end of status text */
10754 /* isgraph or isspace = isprint */
10755 while (isprint((unsigned char)*buf)) {
10756 buf++;
10757 }
10758 if ((*buf != '\r') && (*buf != '\n')) {
10759 return -1;
10760 }
10761 /* Terminate string and forward buf to next line */
10762 do {
10763 *buf = 0;
10764 buf++;
10765 } while (isspace((unsigned char)*buf));
10766
10767
10768 /* Parse all HTTP headers */
10770 if (ri->num_headers < 0) {
10771 /* Error while parsing headers */
10772 return -1;
10773 }
10774
10775 return response_length + init_skip;
10776}
10777
10778
10779/* Keep reading the input (either opened file descriptor fd, or socket sock,
10780 * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
10781 * buffer (which marks the end of HTTP request). Buffer buf may already
10782 * have some data. The length of the data is stored in nread.
10783 * Upon every read operation, increase nread by the number of bytes read. */
10784static int
10786 struct mg_connection *conn,
10787 char *buf,
10788 int bufsiz,
10789 int *nread)
10790{
10791 int request_len, n = 0;
10792 struct timespec last_action_time;
10793 double request_timeout;
10794
10795 if (!conn) {
10796 return 0;
10797 }
10798
10799 memset(&last_action_time, 0, sizeof(last_action_time));
10800
10801 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
10802 /* value of request_timeout is in seconds, config in milliseconds */
10803 request_timeout =
10804 strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
10805 } else {
10806 request_timeout =
10807 strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
10808 / 1000.0;
10809 }
10810 if (conn->handled_requests > 0) {
10811 if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
10812 request_timeout =
10813 strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
10814 / 1000.0;
10815 }
10816 }
10817
10818 request_len = get_http_header_len(buf, *nread);
10819
10820 while (request_len == 0) {
10821 /* Full request not yet received */
10822 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
10823 /* Server is to be stopped. */
10824 return -1;
10825 }
10826
10827 if (*nread >= bufsiz) {
10828 /* Request too long */
10829 return -2;
10830 }
10831
10832 n = pull_inner(
10833 fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
10834 if (n == -2) {
10835 /* Receive error */
10836 return -1;
10837 }
10838
10839 /* update clock after every read request */
10840 clock_gettime(CLOCK_MONOTONIC, &last_action_time);
10841
10842 if (n > 0) {
10843 *nread += n;
10844 request_len = get_http_header_len(buf, *nread);
10845 }
10846
10847 if ((request_len == 0) && (request_timeout >= 0)) {
10848 if (mg_difftimespec(&last_action_time, &(conn->req_time))
10849 > request_timeout) {
10850 /* Timeout */
10851 return -1;
10852 }
10853 }
10854 }
10855
10856 return request_len;
10857}
10858
10859
10860#if !defined(NO_CGI) || !defined(NO_FILES)
10861static int
10862forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
10863{
10864 const char *expect;
10865 char buf[MG_BUF_LEN];
10866 int success = 0;
10867
10868 if (!conn) {
10869 return 0;
10870 }
10871
10872 expect = mg_get_header(conn, "Expect");
10873 DEBUG_ASSERT(fp != NULL);
10874 if (!fp) {
10875 mg_send_http_error(conn, 500, "%s", "Error: NULL File");
10876 return 0;
10877 }
10878
10879 if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
10880 /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
10881 */
10882 mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
10883 } else {
10884 if (expect != NULL) {
10885 (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
10886 conn->status_code = 100;
10887 } else {
10888 conn->status_code = 200;
10889 }
10890
10891 DEBUG_ASSERT(conn->consumed_content == 0);
10892
10893 if (conn->consumed_content != 0) {
10894 mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
10895 return 0;
10896 }
10897
10898 for (;;) {
10899 int nread = mg_read(conn, buf, sizeof(buf));
10900 if (nread <= 0) {
10901 success = (nread == 0);
10902 break;
10903 }
10904 if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
10905 break;
10906 }
10907 }
10908
10909 /* Each error code path in this function must send an error */
10910 if (!success) {
10911 /* NOTE: Maybe some data has already been sent. */
10912 /* TODO (low): If some data has been sent, a correct error
10913 * reply can no longer be sent, so just close the connection */
10914 mg_send_http_error(conn, 500, "%s", "");
10915 }
10916 }
10917
10918 return success;
10919}
10920#endif
10921
10922
10923#if defined(USE_TIMERS)
10924
10925#define TIMER_API static
10926#include "timer.inl"
10927
10928#endif /* USE_TIMERS */
10929
10930
10931#if !defined(NO_CGI)
10932/* This structure helps to create an environment for the spawned CGI
10933 * program.
10934 * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
10935 * last element must be NULL.
10936 * However, on Windows there is a requirement that all these
10937 * VARIABLE=VALUE\0
10938 * strings must reside in a contiguous buffer. The end of the buffer is
10939 * marked by two '\0' characters.
10940 * We satisfy both worlds: we create an envp array (which is vars), all
10941 * entries are actually pointers inside buf. */
10944 /* Data block */
10945 char *buf; /* Environment buffer */
10946 size_t buflen; /* Space available in buf */
10947 size_t bufused; /* Space taken in buf */
10948 /* Index block */
10949 char **var; /* char **envp */
10950 size_t varlen; /* Number of variables available in var */
10951 size_t varused; /* Number of variables stored in var */
10952};
10953
10954
10955static void addenv(struct cgi_environment *env,
10956 PRINTF_FORMAT_STRING(const char *fmt),
10957 ...) PRINTF_ARGS(2, 3);
10958
10959/* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
10960 * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
10961static void
10962addenv(struct cgi_environment *env, const char *fmt, ...)
10963{
10964 size_t i, n, space;
10965 int truncated = 0;
10966 char *added;
10967 va_list ap;
10968
10969 if ((env->varlen - env->varused) < 2) {
10970 mg_cry_internal(env->conn,
10971 "%s: Cannot register CGI variable [%s]",
10972 __func__,
10973 fmt);
10974 return;
10975 }
10976
10977 /* Calculate how much space is left in the buffer */
10978 space = (env->buflen - env->bufused);
10979
10980 do {
10981 /* Space for "\0\0" is always needed. */
10982 if (space <= 2) {
10983 /* Allocate new buffer */
10984 n = env->buflen + CGI_ENVIRONMENT_SIZE;
10985 added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
10986 if (!added) {
10987 /* Out of memory */
10989 env->conn,
10990 "%s: Cannot allocate memory for CGI variable [%s]",
10991 __func__,
10992 fmt);
10993 return;
10994 }
10995 /* Retarget pointers */
10996 env->buf = added;
10997 env->buflen = n;
10998 for (i = 0, n = 0; i < env->varused; i++) {
10999 env->var[i] = added + n;
11000 n += strlen(added + n) + 1;
11001 }
11002 space = (env->buflen - env->bufused);
11003 }
11004
11005 /* Make a pointer to the free space int the buffer */
11006 added = env->buf + env->bufused;
11007
11008 /* Copy VARIABLE=VALUE\0 string into the free space */
11009 va_start(ap, fmt);
11010 mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
11011 va_end(ap);
11012
11013 /* Do not add truncated strings to the environment */
11014 if (truncated) {
11015 /* Reallocate the buffer */
11016 space = 0;
11017 }
11018 } while (truncated);
11019
11020 /* Calculate number of bytes added to the environment */
11021 n = strlen(added) + 1;
11022 env->bufused += n;
11023
11024 /* Append a pointer to the added string into the envp array */
11025 env->var[env->varused] = added;
11026 env->varused++;
11027}
11028
11029/* Return 0 on success, non-zero if an error occurs. */
11030
11031static int
11033 const char *prog,
11034 struct cgi_environment *env,
11035 unsigned char cgi_config_idx)
11036{
11037 const char *s;
11038 struct vec var_vec;
11039 char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
11040 int i, truncated, uri_len;
11041
11042 if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
11043 return -1;
11044 }
11045
11046 env->conn = conn;
11048 env->bufused = 0;
11049 env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
11050 if (env->buf == NULL) {
11051 mg_cry_internal(conn,
11052 "%s: Not enough memory for environmental buffer",
11053 __func__);
11054 return -1;
11055 }
11057 env->varused = 0;
11058 env->var =
11059 (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
11060 if (env->var == NULL) {
11061 mg_cry_internal(conn,
11062 "%s: Not enough memory for environmental variables",
11063 __func__);
11064 mg_free(env->buf);
11065 return -1;
11066 }
11067
11068 addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
11069 addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11070 addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11071 addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
11072
11073 /* Prepare the environment block */
11074 addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
11075 addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
11076 addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
11077
11078 addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
11079
11080 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
11081 addenv(env, "REMOTE_ADDR=%s", src_addr);
11082
11083 addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
11084 addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
11085
11086 addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
11087 addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
11088 addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
11089
11090 /* SCRIPT_NAME */
11091 uri_len = (int)strlen(conn->request_info.local_uri);
11092 if (conn->path_info == NULL) {
11093 if (conn->request_info.local_uri[uri_len - 1] != '/') {
11094 /* URI: /path_to_script/script.cgi */
11095 addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
11096 } else {
11097 /* URI: /path_to_script/ ... using index.cgi */
11098 const char *index_file = strrchr(prog, '/');
11099 if (index_file) {
11100 addenv(env,
11101 "SCRIPT_NAME=%s%s",
11102 conn->request_info.local_uri,
11103 index_file + 1);
11104 }
11105 }
11106 } else {
11107 /* URI: /path_to_script/script.cgi/path_info */
11108 addenv(env,
11109 "SCRIPT_NAME=%.*s",
11110 uri_len - (int)strlen(conn->path_info),
11111 conn->request_info.local_uri);
11112 }
11113
11114 addenv(env, "SCRIPT_FILENAME=%s", prog);
11115 if (conn->path_info == NULL) {
11116 addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11117 } else {
11118 addenv(env,
11119 "PATH_TRANSLATED=%s%s",
11121 conn->path_info);
11122 }
11123
11124 addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
11125
11126 if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
11127 addenv(env, "CONTENT_TYPE=%s", s);
11128 }
11129 if (conn->request_info.query_string != NULL) {
11130 addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
11131 }
11132 if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
11133 addenv(env, "CONTENT_LENGTH=%s", s);
11134 }
11135 if ((s = getenv("PATH")) != NULL) {
11136 addenv(env, "PATH=%s", s);
11137 }
11138 if (conn->path_info != NULL) {
11139 addenv(env, "PATH_INFO=%s", conn->path_info);
11140 }
11141
11142 if (conn->status_code > 0) {
11143 /* CGI error handler should show the status code */
11144 addenv(env, "STATUS=%d", conn->status_code);
11145 }
11146
11147#if defined(_WIN32)
11148 if ((s = getenv("COMSPEC")) != NULL) {
11149 addenv(env, "COMSPEC=%s", s);
11150 }
11151 if ((s = getenv("SYSTEMROOT")) != NULL) {
11152 addenv(env, "SYSTEMROOT=%s", s);
11153 }
11154 if ((s = getenv("SystemDrive")) != NULL) {
11155 addenv(env, "SystemDrive=%s", s);
11156 }
11157 if ((s = getenv("ProgramFiles")) != NULL) {
11158 addenv(env, "ProgramFiles=%s", s);
11159 }
11160 if ((s = getenv("ProgramFiles(x86)")) != NULL) {
11161 addenv(env, "ProgramFiles(x86)=%s", s);
11162 }
11163#else
11164 if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
11165 addenv(env, "LD_LIBRARY_PATH=%s", s);
11166 }
11167#endif /* _WIN32 */
11168
11169 if ((s = getenv("PERLLIB")) != NULL) {
11170 addenv(env, "PERLLIB=%s", s);
11171 }
11172
11173 if (conn->request_info.remote_user != NULL) {
11174 addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
11175 addenv(env, "%s", "AUTH_TYPE=Digest");
11176 }
11177
11178 /* Add all headers as HTTP_* variables */
11179 for (i = 0; i < conn->request_info.num_headers; i++) {
11180
11181 (void)mg_snprintf(conn,
11182 &truncated,
11183 http_var_name,
11184 sizeof(http_var_name),
11185 "HTTP_%s",
11186 conn->request_info.http_headers[i].name);
11187
11188 if (truncated) {
11189 mg_cry_internal(conn,
11190 "%s: HTTP header variable too long [%s]",
11191 __func__,
11192 conn->request_info.http_headers[i].name);
11193 continue;
11194 }
11195
11196 /* Convert variable name into uppercase, and change - to _ */
11197 for (p = http_var_name; *p != '\0'; p++) {
11198 if (*p == '-') {
11199 *p = '_';
11200 }
11201 *p = (char)toupper((unsigned char)*p);
11202 }
11203
11204 addenv(env,
11205 "%s=%s",
11206 http_var_name,
11208 }
11209
11210 /* Add user-specified variables */
11211 s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
11212 while ((s = next_option(s, &var_vec, NULL)) != NULL) {
11213 addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
11214 }
11215
11216 env->var[env->varused] = NULL;
11217 env->buf[env->bufused] = '\0';
11218
11219 return 0;
11220}
11221
11222
11223/* Data for CGI process control: PID and number of references */
11225 pid_t pid;
11226 ptrdiff_t references;
11227};
11228
11229static int
11231{
11232 /* Waitpid checks for child status and won't work for a pid that does
11233 * not identify a child of the current process. Thus, if the pid is
11234 * reused, we will not affect a different process. */
11235 struct process_control_data *proc = (struct process_control_data *)data;
11236 int status = 0;
11237 ptrdiff_t refs;
11238 pid_t ret_pid;
11239
11240 ret_pid = waitpid(proc->pid, &status, WNOHANG);
11241 if ((ret_pid != (pid_t)-1) && (status == 0)) {
11242 /* Stop child process */
11243 DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
11244 kill(proc->pid, SIGABRT);
11245
11246 /* Wait until process is terminated (don't leave zombies) */
11247 while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
11248 ;
11249 } else {
11250 DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
11251 }
11252 /* Dec reference counter */
11253 refs = mg_atomic_dec(&proc->references);
11254 if (refs == 0) {
11255 /* no more references - free data */
11256 mg_free(data);
11257 }
11258
11259 return 0;
11260}
11261
11262
11263/* Local (static) function assumes all arguments are valid. */
11264static void
11266 const char *prog,
11267 unsigned char cgi_config_idx)
11268{
11269 char *buf;
11270 size_t buflen;
11271 int headers_len, data_len, i, truncated;
11272 int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
11273 const char *status, *status_text, *connection_state;
11274 char *pbuf, dir[UTF8_PATH_MAX], *p;
11275 struct mg_request_info ri;
11276 struct cgi_environment blk;
11277 FILE *in = NULL, *out = NULL, *err = NULL;
11278 struct mg_file fout = STRUCT_FILE_INITIALIZER;
11279 pid_t pid = (pid_t)-1;
11280 struct process_control_data *proc = NULL;
11281
11282#if defined(USE_TIMERS)
11283 double cgi_timeout;
11284 if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
11285 /* Get timeout in seconds */
11286 cgi_timeout =
11287 atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
11288 } else {
11289 cgi_timeout =
11290 atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
11291 }
11292
11293#endif
11294
11295 buf = NULL;
11296 buflen = conn->phys_ctx->max_request_size;
11297 i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
11298 if (i != 0) {
11299 blk.buf = NULL;
11300 blk.var = NULL;
11301 goto done;
11302 }
11303
11304 /* CGI must be executed in its own directory. 'dir' must point to the
11305 * directory containing executable program, 'p' must point to the
11306 * executable program name relative to 'dir'. */
11307 (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
11308
11309 if (truncated) {
11310 mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
11311 mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
11312 goto done;
11313 }
11314
11315 if ((p = strrchr(dir, '/')) != NULL) {
11316 *p++ = '\0';
11317 } else {
11318 dir[0] = '.';
11319 dir[1] = '\0';
11320 p = (char *)prog;
11321 }
11322
11323 if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
11324 status = strerror(ERRNO);
11326 conn,
11327 "Error: CGI program \"%s\": Can not create CGI pipes: %s",
11328 prog,
11329 status);
11330 mg_send_http_error(conn,
11331 500,
11332 "Error: Cannot create CGI pipe: %s",
11333 status);
11334 goto done;
11335 }
11336
11337 proc = (struct process_control_data *)
11338 mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
11339 if (proc == NULL) {
11340 mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
11341 mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
11342 goto done;
11343 }
11344
11345 DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
11347 conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
11348
11349 if (pid == (pid_t)-1) {
11350 status = strerror(ERRNO);
11352 conn,
11353 "Error: CGI program \"%s\": Can not spawn CGI process: %s",
11354 prog,
11355 status);
11356 mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
11357 mg_free(proc);
11358 proc = NULL;
11359 goto done;
11360 }
11361
11362 /* Store data in shared process_control_data */
11363 proc->pid = pid;
11364 proc->references = 1;
11365
11366#if defined(USE_TIMERS)
11367 if (cgi_timeout > 0.0) {
11368 proc->references = 2;
11369
11370 // Start a timer for CGI
11371 timer_add(conn->phys_ctx,
11372 cgi_timeout /* in seconds */,
11373 0.0,
11374 1,
11376 (void *)proc,
11377 NULL);
11378 }
11379#endif
11380
11381 /* Parent closes only one side of the pipes.
11382 * If we don't mark them as closed, close() attempt before
11383 * return from this function throws an exception on Windows.
11384 * Windows does not like when closed descriptor is closed again. */
11385 (void)close(fdin[0]);
11386 (void)close(fdout[1]);
11387 (void)close(fderr[1]);
11388 fdin[0] = fdout[1] = fderr[1] = -1;
11389
11390 if (((in = fdopen(fdin[1], "wb")) == NULL)
11391 || ((out = fdopen(fdout[0], "rb")) == NULL)
11392 || ((err = fdopen(fderr[0], "rb")) == NULL)) {
11393 status = strerror(ERRNO);
11394 mg_cry_internal(conn,
11395 "Error: CGI program \"%s\": Can not open fd: %s",
11396 prog,
11397 status);
11398 mg_send_http_error(conn,
11399 500,
11400 "Error: CGI can not open fd\nfdopen: %s",
11401 status);
11402 goto done;
11403 }
11404
11405 setbuf(in, NULL);
11406 setbuf(out, NULL);
11407 setbuf(err, NULL);
11408 fout.access.fp = out;
11409
11410 if ((conn->content_len != 0) || (conn->is_chunked)) {
11411 DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
11412 conn->content_len);
11413
11414 /* This is a POST/PUT request, or another request with body data. */
11415 if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
11416 /* Error sending the body data */
11418 conn,
11419 "Error: CGI program \"%s\": Forward body data failed",
11420 prog);
11421 goto done;
11422 }
11423 }
11424
11425 /* Close so child gets an EOF. */
11426 fclose(in);
11427 in = NULL;
11428 fdin[1] = -1;
11429
11430 /* Now read CGI reply into a buffer. We need to set correct
11431 * status code, thus we need to see all HTTP headers first.
11432 * Do not send anything back to client, until we buffer in all
11433 * HTTP headers. */
11434 data_len = 0;
11435 buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
11436 if (buf == NULL) {
11437 mg_send_http_error(conn,
11438 500,
11439 "Error: Not enough memory for CGI buffer (%u bytes)",
11440 (unsigned int)buflen);
11442 conn,
11443 "Error: CGI program \"%s\": Not enough memory for buffer (%u "
11444 "bytes)",
11445 prog,
11446 (unsigned int)buflen);
11447 goto done;
11448 }
11449
11450 DEBUG_TRACE("CGI: %s", "wait for response");
11451 headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
11452 DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
11453
11454 if (headers_len <= 0) {
11455
11456 /* Could not parse the CGI response. Check if some error message on
11457 * stderr. */
11458 i = pull_all(err, conn, buf, (int)buflen);
11459 if (i > 0) {
11460 /* CGI program explicitly sent an error */
11461 /* Write the error message to the internal log */
11462 mg_cry_internal(conn,
11463 "Error: CGI program \"%s\" sent error "
11464 "message: [%.*s]",
11465 prog,
11466 i,
11467 buf);
11468 /* Don't send the error message back to the client */
11469 mg_send_http_error(conn,
11470 500,
11471 "Error: CGI program \"%s\" failed.",
11472 prog);
11473 } else {
11474 /* CGI program did not explicitly send an error, but a broken
11475 * respon header */
11476 mg_cry_internal(conn,
11477 "Error: CGI program sent malformed or too big "
11478 "(>%u bytes) HTTP headers: [%.*s]",
11479 (unsigned)buflen,
11480 data_len,
11481 buf);
11482
11483 mg_send_http_error(conn,
11484 500,
11485 "Error: CGI program sent malformed or too big "
11486 "(>%u bytes) HTTP headers: [%.*s]",
11487 (unsigned)buflen,
11488 data_len,
11489 buf);
11490 }
11491
11492 /* in both cases, abort processing CGI */
11493 goto done;
11494 }
11495
11496 pbuf = buf;
11497 buf[headers_len - 1] = '\0';
11499
11500 /* Make up and send the status line */
11501 status_text = "OK";
11502 if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
11503 != NULL) {
11504 conn->status_code = atoi(status);
11505 status_text = status;
11506 while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
11507 status_text++;
11508 }
11509 } else if (get_header(ri.http_headers, ri.num_headers, "Location")
11510 != NULL) {
11511 conn->status_code = 307;
11512 } else {
11513 conn->status_code = 200;
11514 }
11515 connection_state =
11516 get_header(ri.http_headers, ri.num_headers, "Connection");
11517 if (!header_has_option(connection_state, "keep-alive")) {
11518 conn->must_close = 1;
11519 }
11520
11521 DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
11522
11523 (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
11524
11525 /* Send headers */
11526 for (i = 0; i < ri.num_headers; i++) {
11527 DEBUG_TRACE("CGI header: %s: %s",
11528 ri.http_headers[i].name,
11529 ri.http_headers[i].value);
11530 mg_printf(conn,
11531 "%s: %s\r\n",
11532 ri.http_headers[i].name,
11533 ri.http_headers[i].value);
11534 }
11535 mg_write(conn, "\r\n", 2);
11536
11537 /* Send chunk of data that may have been read after the headers */
11538 mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
11539
11540 /* Read the rest of CGI output and send to the client */
11541 DEBUG_TRACE("CGI: %s", "forward all data");
11542 send_file_data(conn, &fout, 0, INT64_MAX);
11543 DEBUG_TRACE("CGI: %s", "all data sent");
11544
11545done:
11546 mg_free(blk.var);
11547 mg_free(blk.buf);
11548
11549 if (pid != (pid_t)-1) {
11550 abort_cgi_process((void *)proc);
11551 }
11552
11553 if (fdin[0] != -1) {
11554 close(fdin[0]);
11555 }
11556 if (fdout[1] != -1) {
11557 close(fdout[1]);
11558 }
11559 if (fderr[1] != -1) {
11560 close(fderr[1]);
11561 }
11562
11563 if (in != NULL) {
11564 fclose(in);
11565 } else if (fdin[1] != -1) {
11566 close(fdin[1]);
11567 }
11568
11569 if (out != NULL) {
11570 fclose(out);
11571 } else if (fdout[0] != -1) {
11572 close(fdout[0]);
11573 }
11574
11575 if (err != NULL) {
11576 fclose(err);
11577 } else if (fderr[0] != -1) {
11578 close(fderr[0]);
11579 }
11580
11581 mg_free(buf);
11582}
11583#endif /* !NO_CGI */
11584
11585
11586#if !defined(NO_FILES)
11587static void
11588mkcol(struct mg_connection *conn, const char *path)
11589{
11590 int rc, body_len;
11591 struct de de;
11592
11593 if (conn == NULL) {
11594 return;
11595 }
11596
11597 /* TODO (mid): Check the mg_send_http_error situations in this function
11598 */
11599
11600 memset(&de.file, 0, sizeof(de.file));
11601 if (!mg_stat(conn, path, &de.file)) {
11603 "%s: mg_stat(%s) failed: %s",
11604 __func__,
11605 path,
11606 strerror(ERRNO));
11607 }
11608
11609 if (de.file.last_modified) {
11610 /* TODO (mid): This check does not seem to make any sense ! */
11611 /* TODO (mid): Add a webdav unit test first, before changing
11612 * anything here. */
11614 conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11615 return;
11616 }
11617
11618 body_len = conn->data_len - conn->request_len;
11619 if (body_len > 0) {
11621 conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11622 return;
11623 }
11624
11625 rc = mg_mkdir(conn, path, 0755);
11626
11627 if (rc == 0) {
11628
11629 /* Create 201 "Created" response */
11633 mg_response_header_add(conn, "Content-Length", "0", -1);
11634
11635 /* Send all headers - there is no body */
11637
11638 } else {
11639 if (errno == EEXIST) {
11641 conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11642 } else if (errno == EACCES) {
11644 conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11645 } else if (errno == ENOENT) {
11647 conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11648 } else {
11650 conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
11651 }
11652 }
11653}
11654
11655
11656static void
11657put_file(struct mg_connection *conn, const char *path)
11658{
11660 const char *range;
11661 int64_t r1, r2;
11662 int rc;
11663
11664 if (conn == NULL) {
11665 return;
11666 }
11667
11668 if (mg_stat(conn, path, &file.stat)) {
11669 /* File already exists */
11670 conn->status_code = 200;
11671
11672 if (file.stat.is_directory) {
11673 /* This is an already existing directory,
11674 * so there is nothing to do for the server. */
11675 rc = 0;
11676
11677 } else {
11678 /* File exists and is not a directory. */
11679 /* Can it be replaced? */
11680
11681 /* Check if the server may write this file */
11682 if (access(path, W_OK) == 0) {
11683 /* Access granted */
11684 rc = 1;
11685 } else {
11687 conn,
11688 403,
11689 "Error: Put not possible\nReplacing %s is not allowed",
11690 path);
11691 return;
11692 }
11693 }
11694 } else {
11695 /* File should be created */
11696 conn->status_code = 201;
11697 rc = put_dir(conn, path);
11698 }
11699
11700 if (rc == 0) {
11701 /* put_dir returns 0 if path is a directory */
11702
11703 /* Create response */
11707 mg_response_header_add(conn, "Content-Length", "0", -1);
11708
11709 /* Send all headers - there is no body */
11711
11712 /* Request to create a directory has been fulfilled successfully.
11713 * No need to put a file. */
11714 return;
11715 }
11716
11717 if (rc == -1) {
11718 /* put_dir returns -1 if the path is too long */
11719 mg_send_http_error(conn,
11720 414,
11721 "Error: Path too long\nput_dir(%s): %s",
11722 path,
11723 strerror(ERRNO));
11724 return;
11725 }
11726
11727 if (rc == -2) {
11728 /* put_dir returns -2 if the directory can not be created */
11729 mg_send_http_error(conn,
11730 500,
11731 "Error: Can not create directory\nput_dir(%s): %s",
11732 path,
11733 strerror(ERRNO));
11734 return;
11735 }
11736
11737 /* A file should be created or overwritten. */
11738 /* Currently CivetWeb does not nead read+write access. */
11739 if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
11740 || file.access.fp == NULL) {
11741 (void)mg_fclose(&file.access);
11742 mg_send_http_error(conn,
11743 500,
11744 "Error: Can not create file\nfopen(%s): %s",
11745 path,
11746 strerror(ERRNO));
11747 return;
11748 }
11749
11750 fclose_on_exec(&file.access, conn);
11751 range = mg_get_header(conn, "Content-Range");
11752 r1 = r2 = 0;
11753 if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
11754 conn->status_code = 206; /* Partial content */
11755 fseeko(file.access.fp, r1, SEEK_SET);
11756 }
11757
11758 if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
11759 /* forward_body_data failed.
11760 * The error code has already been sent to the client,
11761 * and conn->status_code is already set. */
11762 (void)mg_fclose(&file.access);
11763 return;
11764 }
11765
11766 if (mg_fclose(&file.access) != 0) {
11767 /* fclose failed. This might have different reasons, but a likely
11768 * one is "no space on disk", http 507. */
11769 conn->status_code = 507;
11770 }
11771
11772 /* Create response (status_code has been set before) */
11776 mg_response_header_add(conn, "Content-Length", "0", -1);
11777
11778 /* Send all headers - there is no body */
11780}
11781
11782
11783static void
11784delete_file(struct mg_connection *conn, const char *path)
11785{
11786 struct de de;
11787 memset(&de.file, 0, sizeof(de.file));
11788 if (!mg_stat(conn, path, &de.file)) {
11789 /* mg_stat returns 0 if the file does not exist */
11791 404,
11792 "Error: Cannot delete file\nFile %s not found",
11793 path);
11794 return;
11795 }
11796
11797 if (de.file.is_directory) {
11798 if (remove_directory(conn, path)) {
11799 /* Delete is successful: Return 204 without content. */
11800 mg_send_http_error(conn, 204, "%s", "");
11801 } else {
11802 /* Delete is not successful: Return 500 (Server error). */
11803 mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
11804 }
11805 return;
11806 }
11807
11808 /* This is an existing file (not a directory).
11809 * Check if write permission is granted. */
11810 if (access(path, W_OK) != 0) {
11811 /* File is read only */
11813 conn,
11814 403,
11815 "Error: Delete not possible\nDeleting %s is not allowed",
11816 path);
11817 return;
11818 }
11819
11820 /* Try to delete it. */
11821 if (mg_remove(conn, path) == 0) {
11822 /* Delete was successful: Return 204 without content. */
11826 mg_response_header_add(conn, "Content-Length", "0", -1);
11828
11829 } else {
11830 /* Delete not successful (file locked). */
11832 423,
11833 "Error: Cannot delete file\nremove(%s): %s",
11834 path,
11835 strerror(ERRNO));
11836 }
11837}
11838#endif /* !NO_FILES */
11839
11840
11841#if !defined(NO_FILESYSTEMS)
11842static void
11843send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
11844
11845
11846static void
11848 const char *ssi,
11849 char *tag,
11850 int include_level)
11851{
11852 char file_name[MG_BUF_LEN], path[512], *p;
11854 size_t len;
11855 int truncated = 0;
11856
11857 if (conn == NULL) {
11858 return;
11859 }
11860
11861 /* sscanf() is safe here, since send_ssi_file() also uses buffer
11862 * of size MG_BUF_LEN to get the tag. So strlen(tag) is
11863 * always < MG_BUF_LEN. */
11864 if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
11865 /* File name is relative to the webserver root */
11866 file_name[511] = 0;
11867 (void)mg_snprintf(conn,
11868 &truncated,
11869 path,
11870 sizeof(path),
11871 "%s/%s",
11873 file_name);
11874
11875 } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
11876 /* File name is relative to the webserver working directory
11877 * or it is absolute system path */
11878 file_name[511] = 0;
11879 (void)
11880 mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
11881
11882 } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
11883 || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
11884 /* File name is relative to the currect document */
11885 file_name[511] = 0;
11886 (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
11887
11888 if (!truncated) {
11889 if ((p = strrchr(path, '/')) != NULL) {
11890 p[1] = '\0';
11891 }
11892 len = strlen(path);
11893 (void)mg_snprintf(conn,
11894 &truncated,
11895 path + len,
11896 sizeof(path) - len,
11897 "%s",
11898 file_name);
11899 }
11900
11901 } else {
11902 mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
11903 return;
11904 }
11905
11906 if (truncated) {
11907 mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
11908 return;
11909 }
11910
11911 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
11912 mg_cry_internal(conn,
11913 "Cannot open SSI #include: [%s]: fopen(%s): %s",
11914 tag,
11915 path,
11916 strerror(ERRNO));
11917 } else {
11918 fclose_on_exec(&file.access, conn);
11920 > 0) {
11921 send_ssi_file(conn, path, &file, include_level + 1);
11922 } else {
11923 send_file_data(conn, &file, 0, INT64_MAX);
11924 }
11925 (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
11926 }
11927}
11928
11929
11930#if !defined(NO_POPEN)
11931static void
11932do_ssi_exec(struct mg_connection *conn, char *tag)
11933{
11934 char cmd[1024] = "";
11936
11937 if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
11938 mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
11939 } else {
11940 cmd[1023] = 0;
11941 if ((file.access.fp = popen(cmd, "r")) == NULL) {
11942 mg_cry_internal(conn,
11943 "Cannot SSI #exec: [%s]: %s",
11944 cmd,
11945 strerror(ERRNO));
11946 } else {
11947 send_file_data(conn, &file, 0, INT64_MAX);
11948 pclose(file.access.fp);
11949 }
11950 }
11951}
11952#endif /* !NO_POPEN */
11953
11954
11955static int
11956mg_fgetc(struct mg_file *filep)
11957{
11958 if (filep == NULL) {
11959 return EOF;
11960 }
11961
11962 if (filep->access.fp != NULL) {
11963 return fgetc(filep->access.fp);
11964 } else {
11965 return EOF;
11966 }
11967}
11968
11969
11970static void
11972 const char *path,
11973 struct mg_file *filep,
11974 int include_level)
11975{
11976 char buf[MG_BUF_LEN];
11977 int ch, len, in_tag, in_ssi_tag;
11978
11979 if (include_level > 10) {
11980 mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
11981 return;
11982 }
11983
11984 in_tag = in_ssi_tag = len = 0;
11985
11986 /* Read file, byte by byte, and look for SSI include tags */
11987 while ((ch = mg_fgetc(filep)) != EOF) {
11988
11989 if (in_tag) {
11990 /* We are in a tag, either SSI tag or html tag */
11991
11992 if (ch == '>') {
11993 /* Tag is closing */
11994 buf[len++] = '>';
11995
11996 if (in_ssi_tag) {
11997 /* Handle SSI tag */
11998 buf[len] = 0;
11999
12000 if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
12001 do_ssi_include(conn, path, buf + 12, include_level + 1);
12002#if !defined(NO_POPEN)
12003 } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
12004 do_ssi_exec(conn, buf + 9);
12005#endif /* !NO_POPEN */
12006 } else {
12007 mg_cry_internal(conn,
12008 "%s: unknown SSI "
12009 "command: \"%s\"",
12010 path,
12011 buf);
12012 }
12013 len = 0;
12014 in_ssi_tag = in_tag = 0;
12015
12016 } else {
12017 /* Not an SSI tag */
12018 /* Flush buffer */
12019 (void)mg_write(conn, buf, (size_t)len);
12020 len = 0;
12021 in_tag = 0;
12022 }
12023
12024 } else {
12025 /* Tag is still open */
12026 buf[len++] = (char)(ch & 0xff);
12027
12028 if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
12029 /* All SSI tags start with <!--# */
12030 in_ssi_tag = 1;
12031 }
12032
12033 if ((len + 2) > (int)sizeof(buf)) {
12034 /* Tag to long for buffer */
12035 mg_cry_internal(conn, "%s: tag is too large", path);
12036 return;
12037 }
12038 }
12039
12040 } else {
12041
12042 /* We are not in a tag yet. */
12043 if (ch == '<') {
12044 /* Tag is opening */
12045 in_tag = 1;
12046
12047 if (len > 0) {
12048 /* Flush current buffer.
12049 * Buffer is filled with "len" bytes. */
12050 (void)mg_write(conn, buf, (size_t)len);
12051 }
12052 /* Store the < */
12053 len = 1;
12054 buf[0] = '<';
12055
12056 } else {
12057 /* No Tag */
12058 /* Add data to buffer */
12059 buf[len++] = (char)(ch & 0xff);
12060 /* Flush if buffer is full */
12061 if (len == (int)sizeof(buf)) {
12062 mg_write(conn, buf, (size_t)len);
12063 len = 0;
12064 }
12065 }
12066 }
12067 }
12068
12069 /* Send the rest of buffered data */
12070 if (len > 0) {
12071 mg_write(conn, buf, (size_t)len);
12072 }
12073}
12074
12075
12076static void
12078 const char *path,
12079 struct mg_file *filep)
12080{
12081 char date[64];
12082 time_t curtime = time(NULL);
12083 const char *cors_orig_cfg;
12084 const char *cors1, *cors2;
12085
12086 if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
12087 return;
12088 }
12089
12090 cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
12091 if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
12092 /* Cross-origin resource sharing (CORS). */
12093 cors1 = "Access-Control-Allow-Origin";
12094 cors2 = cors_orig_cfg;
12095 } else {
12096 cors1 = cors2 = "";
12097 }
12098
12099 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
12100 /* File exists (precondition for calling this function),
12101 * but can not be opened by the server. */
12102 mg_send_http_error(conn,
12103 500,
12104 "Error: Cannot read file\nfopen(%s): %s",
12105 path,
12106 strerror(ERRNO));
12107 } else {
12108 /* Set "must_close" for HTTP/1.x, since we do not know the
12109 * content length */
12110 conn->must_close = 1;
12111 gmt_time_string(date, sizeof(date), &curtime);
12112 fclose_on_exec(&filep->access, conn);
12113
12114 /* 200 OK response */
12115 mg_response_header_start(conn, 200);
12118 mg_response_header_add(conn, "Content-Type", "text/html", -1);
12119 if (cors1[0]) {
12120 mg_response_header_add(conn, cors1, cors2, -1);
12121 }
12123
12124 /* Header sent, now send body */
12125 send_ssi_file(conn, path, filep, 0);
12126 (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
12127 }
12128}
12129#endif /* NO_FILESYSTEMS */
12130
12131
12132#if !defined(NO_FILES)
12133static void
12135{
12136 if (!conn) {
12137 return;
12138 }
12139
12140 /* We do not set a "Cache-Control" header here, but leave the default.
12141 * Since browsers do not send an OPTIONS request, we can not test the
12142 * effect anyway. */
12143
12144 mg_response_header_start(conn, 200);
12145 mg_response_header_add(conn, "Content-Type", "text/html", -1);
12146 if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
12147 /* Use the same as before */
12149 conn,
12150 "Allow",
12151 "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
12152 -1);
12153 mg_response_header_add(conn, "DAV", "1", -1);
12154 } else {
12155 /* TODO: Check this later for HTTP/2 */
12156 mg_response_header_add(conn, "Allow", "GET, POST", -1);
12157 }
12160}
12161
12162
12163/* Writes PROPFIND properties for a collection element */
12164static int
12166 const char *uri,
12167 const char *name,
12168 struct mg_file_stat *filep)
12169{
12170 size_t href_size, i, j;
12171 int len;
12172 char *href, mtime[64];
12173
12174 if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
12175 return 0;
12176 }
12177 /* Estimate worst case size for encoding */
12178 href_size = (strlen(uri) + strlen(name)) * 3 + 1;
12179 href = (char *)mg_malloc(href_size);
12180 if (href == NULL) {
12181 return 0;
12182 }
12183 len = mg_url_encode(uri, href, href_size);
12184 if (len >= 0) {
12185 /* Append an extra string */
12186 mg_url_encode(name, href + len, href_size - (size_t)len);
12187 }
12188 /* Directory separator should be preserved. */
12189 for (i = j = 0; href[i]; j++) {
12190 if (!strncmp(href + i, "%2f", 3)) {
12191 href[j] = '/';
12192 i += 3;
12193 } else {
12194 href[j] = href[i++];
12195 }
12196 }
12197 href[j] = '\0';
12198
12199 gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
12200 mg_printf(conn,
12201 "<d:response>"
12202 "<d:href>%s</d:href>"
12203 "<d:propstat>"
12204 "<d:prop>"
12205 "<d:resourcetype>%s</d:resourcetype>"
12206 "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
12207 "<d:getlastmodified>%s</d:getlastmodified>"
12208 "</d:prop>"
12209 "<d:status>HTTP/1.1 200 OK</d:status>"
12210 "</d:propstat>"
12211 "</d:response>\n",
12212 href,
12213 filep->is_directory ? "<d:collection/>" : "",
12214 filep->size,
12215 mtime);
12216 mg_free(href);
12217 return 1;
12218}
12219
12220
12221static int
12223{
12224 struct mg_connection *conn = (struct mg_connection *)data;
12225 if (!de || !conn
12226 || !print_props(
12227 conn, conn->request_info.local_uri, de->file_name, &de->file)) {
12228 /* stop scan */
12229 return 1;
12230 }
12231 return 0;
12232}
12233
12234
12235static void
12237 const char *path,
12238 struct mg_file_stat *filep)
12239{
12240 const char *depth = mg_get_header(conn, "Depth");
12241 char date[64];
12242 time_t curtime = time(NULL);
12243
12244 gmt_time_string(date, sizeof(date), &curtime);
12245
12246 if (!conn || !path || !filep || !conn->dom_ctx) {
12247 return;
12248 }
12249
12250 conn->must_close = 1;
12251
12252 /* return 207 "Multi-Status" */
12253 mg_response_header_start(conn, 207);
12256 mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
12258
12259 /* Content */
12260 mg_printf(conn,
12261 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12262 "<d:multistatus xmlns:d='DAV:'>\n");
12263
12264 /* Print properties for the requested resource itself */
12265 print_props(conn, conn->request_info.local_uri, "", filep);
12266
12267 /* If it is a directory, print directory entries too if Depth is not 0
12268 */
12269 if (filep->is_directory
12271 "yes")
12272 && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
12273 scan_directory(conn, path, conn, &print_dav_dir_entry);
12274 }
12275
12276 mg_printf(conn, "%s\n", "</d:multistatus>");
12277}
12278#endif
12279
12280void
12282{
12283 if (conn) {
12284 (void)pthread_mutex_lock(&conn->mutex);
12285 }
12286}
12287
12288void
12290{
12291 if (conn) {
12292 (void)pthread_mutex_unlock(&conn->mutex);
12293 }
12294}
12295
12296void
12298{
12299 if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
12300 (void)pthread_mutex_lock(&ctx->nonce_mutex);
12301 }
12302}
12303
12304void
12306{
12307 if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
12308 (void)pthread_mutex_unlock(&ctx->nonce_mutex);
12309 }
12310}
12311
12312
12313#if defined(USE_LUA)
12314#include "mod_lua.inl"
12315#endif /* USE_LUA */
12316
12317#if defined(USE_DUKTAPE)
12318#include "mod_duktape.inl"
12319#endif /* USE_DUKTAPE */
12320
12321#if defined(USE_WEBSOCKET)
12322
12323#if !defined(NO_SSL_DL)
12324#if !defined(OPENSSL_API_3_0)
12325#define SHA_API static
12326#include "sha1.inl"
12327#endif
12328#endif
12329
12330static int
12331send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
12332{
12333 static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
12334 char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
12335#if !defined(OPENSSL_API_3_0)
12336 SHA_CTX sha_ctx;
12337#endif
12338 int truncated;
12339
12340 /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
12341 mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
12342 if (truncated) {
12343 conn->must_close = 1;
12344 return 0;
12345 }
12346
12347 DEBUG_TRACE("%s", "Send websocket handshake");
12348
12349#if defined(OPENSSL_API_3_0)
12350 EVP_Digest((unsigned char *)buf, (uint32_t)strlen(buf), (unsigned char *)sha,
12351 NULL, EVP_get_digestbyname("sha1"), NULL);
12352#else
12353 SHA1_Init(&sha_ctx);
12354 SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
12355 SHA1_Final((unsigned char *)sha, &sha_ctx);
12356#endif
12357 base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
12358 mg_printf(conn,
12359 "HTTP/1.1 101 Switching Protocols\r\n"
12360 "Upgrade: websocket\r\n"
12361 "Connection: Upgrade\r\n"
12362 "Sec-WebSocket-Accept: %s\r\n",
12363 b64_sha);
12364
12365#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12366 // Send negotiated compression extension parameters
12367 websocket_deflate_response(conn);
12368#endif
12369
12371 mg_printf(conn,
12372 "Sec-WebSocket-Protocol: %s\r\n\r\n",
12374 } else {
12375 mg_printf(conn, "%s", "\r\n");
12376 }
12377
12378 return 1;
12379}
12380
12381
12382#if !defined(MG_MAX_UNANSWERED_PING)
12383/* Configuration of the maximum number of websocket PINGs that might
12384 * stay unanswered before the connection is considered broken.
12385 * Note: The name of this define may still change (until it is
12386 * defined as a compile parameter in a documentation).
12387 */
12388#define MG_MAX_UNANSWERED_PING (5)
12389#endif
12390
12391
12392static void
12393read_websocket(struct mg_connection *conn,
12394 mg_websocket_data_handler ws_data_handler,
12395 void *callback_data)
12396{
12397 /* Pointer to the beginning of the portion of the incoming websocket
12398 * message queue.
12399 * The original websocket upgrade request is never removed, so the queue
12400 * begins after it. */
12401 unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
12402 int n, error, exit_by_callback;
12403 int ret;
12404
12405 /* body_len is the length of the entire queue in bytes
12406 * len is the length of the current message
12407 * data_len is the length of the current message's data payload
12408 * header_len is the length of the current message's header */
12409 size_t i, len, mask_len = 0, header_len, body_len;
12410 uint64_t data_len = 0;
12411
12412 /* "The masking key is a 32-bit value chosen at random by the client."
12413 * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
12414 */
12415 unsigned char mask[4];
12416
12417 /* data points to the place where the message is stored when passed to
12418 * the websocket_data callback. This is either mem on the stack, or a
12419 * dynamically allocated buffer if it is too large. */
12420 unsigned char mem[4096];
12421 unsigned char mop; /* mask flag and opcode */
12422
12423
12424 /* Variables used for connection monitoring */
12425 double timeout = -1.0;
12426 int enable_ping_pong = 0;
12427 int ping_count = 0;
12428
12429 if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
12430 enable_ping_pong =
12431 !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
12432 "yes");
12433 }
12434
12435 if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
12436 timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
12437 }
12438 if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
12439 timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
12440 }
12441 if (timeout <= 0.0) {
12442 timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
12443 }
12444
12445 /* Enter data processing loop */
12446 DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
12449 conn->in_websocket_handling = 1;
12450 mg_set_thread_name("wsock");
12451
12452 /* Loop continuously, reading messages from the socket, invoking the
12453 * callback, and waiting repeatedly until an error occurs. */
12454 while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
12455 && (!conn->must_close)) {
12456 header_len = 0;
12457 DEBUG_ASSERT(conn->data_len >= conn->request_len);
12458 if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
12459 len = buf[1] & 127;
12460 mask_len = (buf[1] & 128) ? 4 : 0;
12461 if ((len < 126) && (body_len >= mask_len)) {
12462 /* inline 7-bit length field */
12463 data_len = len;
12464 header_len = 2 + mask_len;
12465 } else if ((len == 126) && (body_len >= (4 + mask_len))) {
12466 /* 16-bit length field */
12467 header_len = 4 + mask_len;
12468 data_len = ((((size_t)buf[2]) << 8) + buf[3]);
12469 } else if (body_len >= (10 + mask_len)) {
12470 /* 64-bit length field */
12471 uint32_t l1, l2;
12472 memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
12473 memcpy(&l2, &buf[6], 4);
12474 header_len = 10 + mask_len;
12475 data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
12476
12477 if (data_len > (uint64_t)0x7FFF0000ul) {
12478 /* no can do */
12480 conn,
12481 "%s",
12482 "websocket out of memory; closing connection");
12483 break;
12484 }
12485 }
12486 }
12487
12488 if ((header_len > 0) && (body_len >= header_len)) {
12489 /* Allocate space to hold websocket payload */
12490 unsigned char *data = mem;
12491
12492 if ((size_t)data_len > (size_t)sizeof(mem)) {
12493 data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
12494 conn->phys_ctx);
12495 if (data == NULL) {
12496 /* Allocation failed, exit the loop and then close the
12497 * connection */
12499 conn,
12500 "%s",
12501 "websocket out of memory; closing connection");
12502 break;
12503 }
12504 }
12505
12506 /* Copy the mask before we shift the queue and destroy it */
12507 if (mask_len > 0) {
12508 memcpy(mask, buf + header_len - mask_len, sizeof(mask));
12509 } else {
12510 memset(mask, 0, sizeof(mask));
12511 }
12512
12513 /* Read frame payload from the first message in the queue into
12514 * data and advance the queue by moving the memory in place. */
12515 DEBUG_ASSERT(body_len >= header_len);
12516 if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
12517 mop = buf[0]; /* current mask and opcode */
12518 /* Overflow case */
12519 len = body_len - header_len;
12520 memcpy(data, buf + header_len, len);
12521 error = 0;
12522 while ((uint64_t)len < data_len) {
12523 n = pull_inner(NULL,
12524 conn,
12525 (char *)(data + len),
12526 (int)(data_len - len),
12527 timeout);
12528 if (n <= -2) {
12529 error = 1;
12530 break;
12531 } else if (n > 0) {
12532 len += (size_t)n;
12533 } else {
12534 /* Timeout: should retry */
12535 /* TODO: retry condition */
12536 }
12537 }
12538 if (error) {
12540 conn,
12541 "%s",
12542 "Websocket pull failed; closing connection");
12543 if (data != mem) {
12544 mg_free(data);
12545 }
12546 break;
12547 }
12548
12549 conn->data_len = conn->request_len;
12550
12551 } else {
12552
12553 mop = buf[0]; /* current mask and opcode, overwritten by
12554 * memmove() */
12555
12556 /* Length of the message being read at the front of the
12557 * queue. Cast to 31 bit is OK, since we limited
12558 * data_len before. */
12559 len = (size_t)data_len + header_len;
12560
12561 /* Copy the data payload into the data pointer for the
12562 * callback. Cast to 31 bit is OK, since we
12563 * limited data_len */
12564 memcpy(data, buf + header_len, (size_t)data_len);
12565
12566 /* Move the queue forward len bytes */
12567 memmove(buf, buf + len, body_len - len);
12568
12569 /* Mark the queue as advanced */
12570 conn->data_len -= (int)len;
12571 }
12572
12573 /* Apply mask if necessary */
12574 if (mask_len > 0) {
12575 for (i = 0; i < (size_t)data_len; i++) {
12576 data[i] ^= mask[i & 3];
12577 }
12578 }
12579
12580 exit_by_callback = 0;
12581 if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
12582 /* filter PONG messages */
12583 DEBUG_TRACE("PONG from %s:%u",
12586 /* No unanwered PINGs left */
12587 ping_count = 0;
12588 } else if (enable_ping_pong
12589 && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
12590 /* reply PING messages */
12591 DEBUG_TRACE("Reply PING from %s:%u",
12594 ret = mg_websocket_write(conn,
12596 (char *)data,
12597 (size_t)data_len);
12598 if (ret <= 0) {
12599 /* Error: send failed */
12600 DEBUG_TRACE("Reply PONG failed (%i)", ret);
12601 break;
12602 }
12603
12604
12605 } else {
12606 /* Exit the loop if callback signals to exit (server side),
12607 * or "connection close" opcode received (client side). */
12608 if (ws_data_handler != NULL) {
12609#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12610 if (mop & 0x40) {
12611 /* Inflate the data received if bit RSV1 is set. */
12612 if (!conn->websocket_deflate_initialized) {
12613 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12614 exit_by_callback = 1;
12615 }
12616 if (!exit_by_callback) {
12617 size_t inflate_buf_size_old = 0;
12618 size_t inflate_buf_size =
12619 data_len
12620 * 4; // Initial guess of the inflated message
12621 // size. We double the memory when needed.
12622 Bytef *inflated = NULL;
12623 Bytef *new_mem = NULL;
12624 conn->websocket_inflate_state.avail_in =
12625 (uInt)(data_len + 4);
12626 conn->websocket_inflate_state.next_in = data;
12627 // Add trailing 0x00 0x00 0xff 0xff bytes
12628 data[data_len] = '\x00';
12629 data[data_len + 1] = '\x00';
12630 data[data_len + 2] = '\xff';
12631 data[data_len + 3] = '\xff';
12632 do {
12633 if (inflate_buf_size_old == 0) {
12634 new_mem =
12635 (Bytef *)mg_calloc(inflate_buf_size,
12636 sizeof(Bytef));
12637 } else {
12638 inflate_buf_size *= 2;
12639 new_mem =
12640 (Bytef *)mg_realloc(inflated,
12641 inflate_buf_size);
12642 }
12643 if (new_mem == NULL) {
12645 conn,
12646 "Out of memory: Cannot allocate "
12647 "inflate buffer of %lu bytes",
12648 (unsigned long)inflate_buf_size);
12649 exit_by_callback = 1;
12650 break;
12651 }
12652 inflated = new_mem;
12653 conn->websocket_inflate_state.avail_out =
12654 (uInt)(inflate_buf_size
12655 - inflate_buf_size_old);
12656 conn->websocket_inflate_state.next_out =
12657 inflated + inflate_buf_size_old;
12658 ret = inflate(&conn->websocket_inflate_state,
12659 Z_SYNC_FLUSH);
12660 if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
12661 || ret == Z_MEM_ERROR) {
12663 conn,
12664 "ZLIB inflate error: %i %s",
12665 ret,
12666 (conn->websocket_inflate_state.msg
12667 ? conn->websocket_inflate_state.msg
12668 : "<no error message>"));
12669 exit_by_callback = 1;
12670 break;
12671 }
12672 inflate_buf_size_old = inflate_buf_size;
12673
12674 } while (conn->websocket_inflate_state.avail_out
12675 == 0);
12676 inflate_buf_size -=
12677 conn->websocket_inflate_state.avail_out;
12678 if (!ws_data_handler(conn,
12679 mop,
12680 (char *)inflated,
12681 inflate_buf_size,
12682 callback_data)) {
12683 exit_by_callback = 1;
12684 }
12685 mg_free(inflated);
12686 }
12687 } else
12688#endif
12689 if (!ws_data_handler(conn,
12690 mop,
12691 (char *)data,
12692 (size_t)data_len,
12693 callback_data)) {
12694 exit_by_callback = 1;
12695 }
12696 }
12697 }
12698
12699 /* It a buffer has been allocated, free it again */
12700 if (data != mem) {
12701 mg_free(data);
12702 }
12703
12704 if (exit_by_callback) {
12705 DEBUG_TRACE("Callback requests to close connection from %s:%u",
12708 break;
12709 }
12710 if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
12711 /* Opcode == 8, connection close */
12712 DEBUG_TRACE("Message requests to close connection from %s:%u",
12715 break;
12716 }
12717
12718 /* Not breaking the loop, process next websocket frame. */
12719 } else {
12720 /* Read from the socket into the next available location in the
12721 * message queue. */
12722 n = pull_inner(NULL,
12723 conn,
12724 conn->buf + conn->data_len,
12725 conn->buf_size - conn->data_len,
12726 timeout);
12727 if (n <= -2) {
12728 /* Error, no bytes read */
12729 DEBUG_TRACE("PULL from %s:%u failed",
12732 break;
12733 }
12734 if (n > 0) {
12735 conn->data_len += n;
12736 /* Reset open PING count */
12737 ping_count = 0;
12738 } else {
12740 && (!conn->must_close)) {
12741 if (ping_count > MG_MAX_UNANSWERED_PING) {
12742 /* Stop sending PING */
12743 DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
12744 "- closing connection",
12745 ping_count,
12748 break;
12749 }
12750 if (enable_ping_pong) {
12751 /* Send Websocket PING message */
12752 DEBUG_TRACE("PING to %s:%u",
12755 ret = mg_websocket_write(conn,
12757 NULL,
12758 0);
12759
12760 if (ret <= 0) {
12761 /* Error: send failed */
12762 DEBUG_TRACE("Send PING failed (%i)", ret);
12763 break;
12764 }
12765 ping_count++;
12766 }
12767 }
12768 /* Timeout: should retry */
12769 /* TODO: get timeout def */
12770 }
12771 }
12772 }
12773
12774 /* Leave data processing loop */
12775 mg_set_thread_name("worker");
12776 conn->in_websocket_handling = 0;
12777 DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
12780}
12781
12782
12783static int
12784mg_websocket_write_exec(struct mg_connection *conn,
12785 int opcode,
12786 const char *data,
12787 size_t dataLen,
12788 uint32_t masking_key)
12789{
12790 unsigned char header[14];
12791 size_t headerLen;
12792 int retval;
12793
12794#if defined(GCC_DIAGNOSTIC)
12795 /* Disable spurious conversion warning for GCC */
12796#pragma GCC diagnostic push
12797#pragma GCC diagnostic ignored "-Wconversion"
12798#endif
12799
12800 /* Note that POSIX/Winsock's send() is threadsafe
12801 * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
12802 * but mongoose's mg_printf/mg_write is not (because of the loop in
12803 * push(), although that is only a problem if the packet is large or
12804 * outgoing buffer is full). */
12805
12806 /* TODO: Check if this lock should be moved to user land.
12807 * Currently the server sets this lock for websockets, but
12808 * not for any other connection. It must be set for every
12809 * conn read/written by more than one thread, no matter if
12810 * it is a websocket or regular connection. */
12811 (void)mg_lock_connection(conn);
12812
12813#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12814 size_t deflated_size = 0;
12815 Bytef *deflated = 0;
12816 // Deflate websocket messages over 100kb
12817 int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
12818
12819 if (use_deflate) {
12820 if (!conn->websocket_deflate_initialized) {
12821 if (websocket_deflate_initialize(conn, 1) != Z_OK)
12822 return 0;
12823 }
12824
12825 // Deflating the message
12826 header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
12827 conn->websocket_deflate_state.avail_in = (uInt)dataLen;
12828 conn->websocket_deflate_state.next_in = (unsigned char *)data;
12829 deflated_size = (Bytef *)compressBound((uLong)dataLen);
12830 deflated = mg_calloc(deflated_size, sizeof(Bytef));
12831 if (deflated == NULL) {
12833 conn,
12834 "Out of memory: Cannot allocate deflate buffer of %lu bytes",
12835 (unsigned long)deflated_size);
12837 return -1;
12838 }
12839 conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
12840 conn->websocket_deflate_state.next_out = deflated;
12841 deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
12842 dataLen = deflated_size - conn->websocket_deflate_state.avail_out
12843 - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
12844 } else
12845#endif
12846 header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
12847
12848#if defined(GCC_DIAGNOSTIC)
12849#pragma GCC diagnostic pop
12850#endif
12851
12852 /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
12853 if (dataLen < 126) {
12854 /* inline 7-bit length field */
12855 header[1] = (unsigned char)dataLen;
12856 headerLen = 2;
12857 } else if (dataLen <= 0xFFFF) {
12858 /* 16-bit length field */
12859 uint16_t len = htons((uint16_t)dataLen);
12860 header[1] = 126;
12861 memcpy(header + 2, &len, 2);
12862 headerLen = 4;
12863 } else {
12864 /* 64-bit length field */
12865 uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
12866 uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
12867 header[1] = 127;
12868 memcpy(header + 2, &len1, 4);
12869 memcpy(header + 6, &len2, 4);
12870 headerLen = 10;
12871 }
12872
12873 if (masking_key) {
12874 /* add mask */
12875 header[1] |= 0x80;
12876 memcpy(header + headerLen, &masking_key, 4);
12877 headerLen += 4;
12878 }
12879
12880 retval = mg_write(conn, header, headerLen);
12881 if (retval != (int)headerLen) {
12882 /* Did not send complete header */
12883 retval = -1;
12884 } else {
12885 if (dataLen > 0) {
12886#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
12887 if (use_deflate) {
12888 retval = mg_write(conn, deflated, dataLen);
12889 mg_free(deflated);
12890 } else
12891#endif
12892 retval = mg_write(conn, data, dataLen);
12893 }
12894 /* if dataLen == 0, the header length (2) is returned */
12895 }
12896
12897 /* TODO: Remove this unlock as well, when lock is removed. */
12899
12900 return retval;
12901}
12902
12903int
12905 int opcode,
12906 const char *data,
12907 size_t dataLen)
12908{
12909 return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
12910}
12911
12912
12913static void
12914mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
12915{
12916 size_t i = 0;
12917
12918 i = 0;
12919 if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
12920 /* Convert in 32 bit words, if data is 4 byte aligned */
12921 while (i < (in_len - 3)) {
12922 *(uint32_t *)(void *)(out + i) =
12923 *(uint32_t *)(void *)(in + i) ^ masking_key;
12924 i += 4;
12925 }
12926 }
12927 if (i != in_len) {
12928 /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
12929 while (i < in_len) {
12930 *(uint8_t *)(void *)(out + i) =
12931 *(uint8_t *)(void *)(in + i)
12932 ^ *(((uint8_t *)&masking_key) + (i % 4));
12933 i++;
12934 }
12935 }
12936}
12937
12938
12939int
12941 int opcode,
12942 const char *data,
12943 size_t dataLen)
12944{
12945 int retval = -1;
12946 char *masked_data =
12947 (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
12948 uint32_t masking_key = 0;
12949
12950 if (masked_data == NULL) {
12951 /* Return -1 in an error case */
12952 mg_cry_internal(conn,
12953 "%s",
12954 "Cannot allocate buffer for masked websocket response: "
12955 "Out of memory");
12956 return -1;
12957 }
12958
12959 do {
12960 /* Get a masking key - but not 0 */
12961 masking_key = (uint32_t)get_random();
12962 } while (masking_key == 0);
12963
12964 mask_data(data, dataLen, masking_key, masked_data);
12965
12966 retval = mg_websocket_write_exec(
12967 conn, opcode, masked_data, dataLen, masking_key);
12968 mg_free(masked_data);
12969
12970 return retval;
12971}
12972
12973
12974static void
12975handle_websocket_request(struct mg_connection *conn,
12976 const char *path,
12977 int is_callback_resource,
12978 struct mg_websocket_subprotocols *subprotocols,
12979 mg_websocket_connect_handler ws_connect_handler,
12980 mg_websocket_ready_handler ws_ready_handler,
12981 mg_websocket_data_handler ws_data_handler,
12982 mg_websocket_close_handler ws_close_handler,
12983 void *cbData)
12984{
12985 const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
12986 const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
12987 ptrdiff_t lua_websock = 0;
12988
12989#if !defined(USE_LUA)
12990 (void)path;
12991#endif
12992
12993 /* Step 1: Check websocket protocol version. */
12994 /* Step 1.1: Check Sec-WebSocket-Key. */
12995 if (!websock_key) {
12996 /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
12997 * requires a Sec-WebSocket-Key header.
12998 */
12999 /* It could be the hixie draft version
13000 * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
13001 */
13002 const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
13003 const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
13004 char key3[8];
13005
13006 if ((key1 != NULL) && (key2 != NULL)) {
13007 /* This version uses 8 byte body data in a GET request */
13008 conn->content_len = 8;
13009 if (8 == mg_read(conn, key3, 8)) {
13010 /* This is the hixie version */
13011 mg_send_http_error(conn,
13012 426,
13013 "%s",
13014 "Protocol upgrade to RFC 6455 required");
13015 return;
13016 }
13017 }
13018 /* This is an unknown version */
13019 mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
13020 return;
13021 }
13022
13023 /* Step 1.2: Check websocket protocol version. */
13024 /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
13025 if ((version == NULL) || (strcmp(version, "13") != 0)) {
13026 /* Reject wrong versions */
13027 mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
13028 return;
13029 }
13030
13031 /* Step 1.3: Could check for "Host", but we do not really nead this
13032 * value for anything, so just ignore it. */
13033
13034 /* Step 2: If a callback is responsible, call it. */
13035 if (is_callback_resource) {
13036 /* Step 2.1 check and select subprotocol */
13037 const char *protocols[64]; // max 64 headers
13038 int nbSubprotocolHeader = get_req_headers(&conn->request_info,
13039 "Sec-WebSocket-Protocol",
13040 protocols,
13041 64);
13042 if ((nbSubprotocolHeader > 0) && subprotocols) {
13043 int cnt = 0;
13044 int idx;
13045 unsigned long len;
13046 const char *sep, *curSubProtocol,
13047 *acceptedWebSocketSubprotocol = NULL;
13048
13049
13050 /* look for matching subprotocol */
13051 do {
13052 const char *protocol = protocols[cnt];
13053
13054 do {
13055 sep = strchr(protocol, ',');
13056 curSubProtocol = protocol;
13057 len = sep ? (unsigned long)(sep - protocol)
13058 : (unsigned long)strlen(protocol);
13059 while (sep && isspace((unsigned char)*++sep))
13060 ; // ignore leading whitespaces
13061 protocol = sep;
13062
13063 for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
13064 if ((strlen(subprotocols->subprotocols[idx]) == len)
13065 && (strncmp(curSubProtocol,
13066 subprotocols->subprotocols[idx],
13067 len)
13068 == 0)) {
13069 acceptedWebSocketSubprotocol =
13070 subprotocols->subprotocols[idx];
13071 break;
13072 }
13073 }
13074 } while (sep && !acceptedWebSocketSubprotocol);
13075 } while (++cnt < nbSubprotocolHeader
13076 && !acceptedWebSocketSubprotocol);
13077
13079 acceptedWebSocketSubprotocol;
13080
13081 } else if (nbSubprotocolHeader > 0) {
13082 /* keep legacy behavior */
13083 const char *protocol = protocols[0];
13084
13085 /* The protocol is a comma separated list of names. */
13086 /* The server must only return one value from this list. */
13087 /* First check if it is a list or just a single value. */
13088 const char *sep = strrchr(protocol, ',');
13089 if (sep == NULL) {
13090 /* Just a single protocol -> accept it. */
13092 } else {
13093 /* Multiple protocols -> accept the last one. */
13094 /* This is just a quick fix if the client offers multiple
13095 * protocols. The handler should have a list of accepted
13096 * protocols on his own
13097 * and use it to select one protocol among those the client
13098 * has
13099 * offered.
13100 */
13101 while (isspace((unsigned char)*++sep)) {
13102 ; /* ignore leading whitespaces */
13103 }
13105 }
13106 }
13107
13108#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13109 websocket_deflate_negotiate(conn);
13110#endif
13111
13112 if ((ws_connect_handler != NULL)
13113 && (ws_connect_handler(conn, cbData) != 0)) {
13114 /* C callback has returned non-zero, do not proceed with
13115 * handshake.
13116 */
13117 /* Note that C callbacks are no longer called when Lua is
13118 * responsible, so C can no longer filter callbacks for Lua. */
13119 return;
13120 }
13121 }
13122
13123#if defined(USE_LUA)
13124 /* Step 3: No callback. Check if Lua is responsible. */
13125 else {
13126 /* Step 3.1: Check if Lua is responsible. */
13127 if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
13128 lua_websock = match_prefix_strlen(
13129 conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
13130 }
13131
13132 if (lua_websock) {
13133 /* Step 3.2: Lua is responsible: call it. */
13134 conn->lua_websocket_state = lua_websocket_new(path, conn);
13135 if (!conn->lua_websocket_state) {
13136 /* Lua rejected the new client */
13137 return;
13138 }
13139 }
13140 }
13141#endif
13142
13143 /* Step 4: Check if there is a responsible websocket handler. */
13144 if (!is_callback_resource && !lua_websock) {
13145 /* There is no callback, and Lua is not responsible either. */
13146 /* Reply with a 404 Not Found. We are still at a standard
13147 * HTTP request here, before the websocket handshake, so
13148 * we can still send standard HTTP error replies. */
13149 mg_send_http_error(conn, 404, "%s", "Not found");
13150 return;
13151 }
13152
13153 /* Step 5: The websocket connection has been accepted */
13154 if (!send_websocket_handshake(conn, websock_key)) {
13155 mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
13156 return;
13157 }
13158
13159 /* Step 6: Call the ready handler */
13160 if (is_callback_resource) {
13161 if (ws_ready_handler != NULL) {
13162 ws_ready_handler(conn, cbData);
13163 }
13164#if defined(USE_LUA)
13165 } else if (lua_websock) {
13166 if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
13167 /* the ready handler returned false */
13168 return;
13169 }
13170#endif
13171 }
13172
13173 /* Step 7: Enter the read loop */
13174 if (is_callback_resource) {
13175 read_websocket(conn, ws_data_handler, cbData);
13176#if defined(USE_LUA)
13177 } else if (lua_websock) {
13178 read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
13179#endif
13180 }
13181
13182#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13183 /* Step 8: Close the deflate & inflate buffers */
13184 if (conn->websocket_deflate_initialized) {
13185 deflateEnd(&conn->websocket_deflate_state);
13186 inflateEnd(&conn->websocket_inflate_state);
13187 }
13188#endif
13189
13190 /* Step 9: Call the close handler */
13191 if (ws_close_handler) {
13192 ws_close_handler(conn, cbData);
13193 }
13194}
13195#endif /* !USE_WEBSOCKET */
13196
13197
13198/* Is upgrade request:
13199 * 0 = regular HTTP/1.0 or HTTP/1.1 request
13200 * 1 = upgrade to websocket
13201 * 2 = upgrade to HTTP/2
13202 * -1 = upgrade to unknown protocol
13203 */
13204static int
13206{
13207 const char *upgrade, *connection;
13208
13209 /* A websocket protocoll has the following HTTP headers:
13210 *
13211 * Connection: Upgrade
13212 * Upgrade: Websocket
13213 */
13214
13215 connection = mg_get_header(conn, "Connection");
13216 if (connection == NULL) {
13217 return PROTOCOL_TYPE_HTTP1;
13218 }
13219 if (!mg_strcasestr(connection, "upgrade")) {
13220 return PROTOCOL_TYPE_HTTP1;
13221 }
13222
13223 upgrade = mg_get_header(conn, "Upgrade");
13224 if (upgrade == NULL) {
13225 /* "Connection: Upgrade" without "Upgrade" Header --> Error */
13226 return -1;
13227 }
13228
13229 /* Upgrade to ... */
13230 if (0 != mg_strcasestr(upgrade, "websocket")) {
13231 /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
13232 * "Sec-WebSocket-Version" are also required.
13233 * Don't check them here, since even an unsupported websocket protocol
13234 * request still IS a websocket request (in contrast to a standard HTTP
13235 * request). It will fail later in handle_websocket_request.
13236 */
13237 return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
13238 }
13239 if (0 != mg_strcasestr(upgrade, "h2")) {
13240 return PROTOCOL_TYPE_HTTP2; /* Websocket */
13241 }
13242
13243 /* Upgrade to another protocol */
13244 return -1;
13245}
13246
13247
13248static int
13249parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
13250{
13251 int n;
13252 unsigned int a, b, c, d, slash;
13253
13254 if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
13255 != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
13256 // integer value, but function will not report conversion
13257 // errors; consider using 'strtol' instead
13258 slash = 32;
13259 if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
13260 != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
13261 // an integer value, but function will not report conversion
13262 // errors; consider using 'strtol' instead
13263 n = 0;
13264 }
13265 }
13266
13267 if ((n > 0) && ((size_t)n == vec->len)) {
13268 if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
13269 /* IPv4 format */
13270 if (sa->sa.sa_family == AF_INET) {
13271 uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
13272 uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
13273 | ((uint32_t)c << 8) | (uint32_t)d;
13274 uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
13275 return (ip & mask) == net;
13276 }
13277 return 0;
13278 }
13279 }
13280#if defined(USE_IPV6)
13281 else {
13282 char ad[50];
13283 const char *p;
13284
13285 if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
13286 slash = 128;
13287 if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
13288 n = 0;
13289 }
13290 }
13291
13292 if ((n <= 0) && no_strict) {
13293 /* no square brackets? */
13294 p = strchr(vec->ptr, '/');
13295 if (p && (p < (vec->ptr + vec->len))) {
13296 if (((size_t)(p - vec->ptr) < sizeof(ad))
13297 && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
13298 n += (int)(p - vec->ptr);
13299 mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
13300 } else {
13301 n = 0;
13302 }
13303 } else if (vec->len < sizeof(ad)) {
13304 n = (int)vec->len;
13305 slash = 128;
13306 mg_strlcpy(ad, vec->ptr, vec->len + 1);
13307 }
13308 }
13309
13310 if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
13311 p = ad;
13312 c = 0;
13313 /* zone indexes are unsupported, at least two colons are needed */
13314 while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
13315 if (*(p++) == ':') {
13316 c++;
13317 }
13318 }
13319 if ((*p == '\0') && (c >= 2)) {
13320 struct sockaddr_in6 sin6;
13321 unsigned int i;
13322
13323 /* for strict validation, an actual IPv6 argument is needed */
13324 if (sa->sa.sa_family != AF_INET6) {
13325 return 0;
13326 }
13327 if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
13328 /* IPv6 format */
13329 for (i = 0; i < 16; i++) {
13330 uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
13331 uint8_t net = sin6.sin6_addr.s6_addr[i];
13332 uint8_t mask = 0;
13333
13334 if (8 * i + 8 < slash) {
13335 mask = 0xFFu;
13336 } else if (8 * i < slash) {
13337 mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
13338 }
13339 if ((ip & mask) != net) {
13340 return 0;
13341 }
13342 }
13343 return 1;
13344 }
13345 }
13346 }
13347 }
13348#else
13349 (void)no_strict;
13350#endif
13351
13352 /* malformed */
13353 return -1;
13354}
13355
13356
13357static int
13358set_throttle(const char *spec, const union usa *rsa, const char *uri)
13359{
13360 int throttle = 0;
13361 struct vec vec, val;
13362 char mult;
13363 double v;
13364
13365 while ((spec = next_option(spec, &vec, &val)) != NULL) {
13366 mult = ',';
13367 if ((val.ptr == NULL)
13368 || (sscanf(val.ptr, "%lf%c", &v, &mult)
13369 < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
13370 // to an integer value, but function will not report
13371 // conversion errors; consider using 'strtol' instead
13372 || (v < 0)
13373 || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
13374 && (mult != ','))) {
13375 continue;
13376 }
13377 v *= (lowercase(&mult) == 'k')
13378 ? 1024
13379 : ((lowercase(&mult) == 'm') ? 1048576 : 1);
13380 if (vec.len == 1 && vec.ptr[0] == '*') {
13381 throttle = (int)v;
13382 } else {
13383 int matched = parse_match_net(&vec, rsa, 0);
13384 if (matched >= 0) {
13385 /* a valid IP subnet */
13386 if (matched) {
13387 throttle = (int)v;
13388 }
13389 } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
13390 throttle = (int)v;
13391 }
13392 }
13393 }
13394
13395 return throttle;
13396}
13397
13398
13399/* The mg_upload function is superseeded by mg_handle_form_request. */
13400#include "handle_form.inl"
13401
13402
13403static int
13405{
13406 unsigned int i;
13407 int idx = -1;
13408 if (ctx) {
13409 for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
13410 idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
13411 }
13412 }
13413 return idx;
13414}
13415
13416
13417/* Return host (without port) */
13418static void
13419get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
13420{
13421 const char *host_header =
13422 get_header(ri->http_headers, ri->num_headers, "Host");
13423
13424 host->ptr = NULL;
13425 host->len = 0;
13426
13427 if (host_header != NULL) {
13428 const char *pos;
13429
13430 /* If the "Host" is an IPv6 address, like [::1], parse until ]
13431 * is found. */
13432 if (*host_header == '[') {
13433 pos = strchr(host_header, ']');
13434 if (!pos) {
13435 /* Malformed hostname starts with '[', but no ']' found */
13436 DEBUG_TRACE("%s", "Host name format error '[' without ']'");
13437 return;
13438 }
13439 /* terminate after ']' */
13440 host->ptr = host_header;
13441 host->len = (size_t)(pos + 1 - host_header);
13442 } else {
13443 /* Otherwise, a ':' separates hostname and port number */
13444 pos = strchr(host_header, ':');
13445 if (pos != NULL) {
13446 host->len = (size_t)(pos - host_header);
13447 } else {
13448 host->len = strlen(host_header);
13449 }
13450 host->ptr = host_header;
13451 }
13452 }
13453}
13454
13455
13456static int
13458{
13459 struct vec host;
13460
13462
13463 if (host.ptr) {
13464 if (conn->ssl) {
13465 /* This is a HTTPS connection, maybe we have a hostname
13466 * from SNI (set in ssl_servername_callback). */
13467 const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
13468 if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
13469 /* We are not using the default domain */
13470 if ((strlen(sslhost) != host.len)
13471 || mg_strncasecmp(host.ptr, sslhost, host.len)) {
13472 /* Mismatch between SNI domain and HTTP domain */
13473 DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
13474 sslhost,
13475 (int)host.len,
13476 host.ptr);
13477 return 0;
13478 }
13479 }
13480
13481 } else {
13482 struct mg_domain_context *dom = &(conn->phys_ctx->dd);
13483 while (dom) {
13484 const char *domName = dom->config[AUTHENTICATION_DOMAIN];
13485 size_t domNameLen = strlen(domName);
13486 if ((domNameLen == host.len)
13487 && !mg_strncasecmp(host.ptr, domName, host.len)) {
13488
13489 /* Found matching domain */
13490 DEBUG_TRACE("HTTP domain %s found",
13492
13493 /* TODO: Check if this is a HTTP or HTTPS domain */
13494 conn->dom_ctx = dom;
13495 break;
13496 }
13498 dom = dom->next;
13500 }
13501 }
13502
13503 DEBUG_TRACE("HTTP%s Host: %.*s",
13504 conn->ssl ? "S" : "",
13505 (int)host.len,
13506 host.ptr);
13507
13508 } else {
13509 DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
13510 return 1;
13511 }
13512
13513 return 1;
13514}
13515
13516
13517static void
13519{
13520 char target_url[MG_BUF_LEN];
13521 int truncated = 0;
13522 const char *expect_proto =
13523 (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
13524
13525 /* Use "308 Permanent Redirect" */
13526 int redirect_code = 308;
13527
13528 /* In any case, close the current connection */
13529 conn->must_close = 1;
13530
13531 /* Send host, port, uri and (if it exists) ?query_string */
13533 conn, target_url, sizeof(target_url), expect_proto, port, NULL)
13534 < 0) {
13535 truncated = 1;
13536 } else if (conn->request_info.query_string != NULL) {
13537 size_t slen1 = strlen(target_url);
13538 size_t slen2 = strlen(conn->request_info.query_string);
13539 if ((slen1 + slen2 + 2) < sizeof(target_url)) {
13540 target_url[slen1] = '?';
13541 memcpy(target_url + slen1 + 1,
13543 slen2);
13544 target_url[slen1 + slen2 + 1] = 0;
13545 } else {
13546 truncated = 1;
13547 }
13548 }
13549
13550 /* Check overflow in location buffer (will not occur if MG_BUF_LEN
13551 * is used as buffer size) */
13552 if (truncated) {
13553 mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
13554 return;
13555 }
13556
13557 /* Use redirect helper function */
13558 mg_send_http_redirect(conn, target_url, redirect_code);
13559}
13560
13561
13562static void
13564 struct mg_domain_context *dom_ctx,
13565 const char *uri,
13566 int handler_type,
13567 int is_delete_request,
13568 mg_request_handler handler,
13569 struct mg_websocket_subprotocols *subprotocols,
13570 mg_websocket_connect_handler connect_handler,
13571 mg_websocket_ready_handler ready_handler,
13572 mg_websocket_data_handler data_handler,
13573 mg_websocket_close_handler close_handler,
13574 mg_authorization_handler auth_handler,
13575 void *cbdata)
13576{
13577 struct mg_handler_info *tmp_rh, **lastref;
13578 size_t urilen = strlen(uri);
13579
13581 DEBUG_ASSERT(handler == NULL);
13582 DEBUG_ASSERT(is_delete_request || connect_handler != NULL
13583 || ready_handler != NULL || data_handler != NULL
13584 || close_handler != NULL);
13585
13586 DEBUG_ASSERT(auth_handler == NULL);
13587 if (handler != NULL) {
13588 return;
13589 }
13590 if (!is_delete_request && (connect_handler == NULL)
13591 && (ready_handler == NULL) && (data_handler == NULL)
13592 && (close_handler == NULL)) {
13593 return;
13594 }
13595 if (auth_handler != NULL) {
13596 return;
13597 }
13598
13599 } else if (handler_type == REQUEST_HANDLER) {
13600 DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13601 && data_handler == NULL && close_handler == NULL);
13602 DEBUG_ASSERT(is_delete_request || (handler != NULL));
13603 DEBUG_ASSERT(auth_handler == NULL);
13604
13605 if ((connect_handler != NULL) || (ready_handler != NULL)
13606 || (data_handler != NULL) || (close_handler != NULL)) {
13607 return;
13608 }
13609 if (!is_delete_request && (handler == NULL)) {
13610 return;
13611 }
13612 if (auth_handler != NULL) {
13613 return;
13614 }
13615
13616 } else if (handler_type == AUTH_HANDLER) {
13617 DEBUG_ASSERT(handler == NULL);
13618 DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13619 && data_handler == NULL && close_handler == NULL);
13620 DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
13621 if (handler != NULL) {
13622 return;
13623 }
13624 if ((connect_handler != NULL) || (ready_handler != NULL)
13625 || (data_handler != NULL) || (close_handler != NULL)) {
13626 return;
13627 }
13628 if (!is_delete_request && (auth_handler == NULL)) {
13629 return;
13630 }
13631 } else {
13632 /* Unknown handler type. */
13633 return;
13634 }
13635
13636 if (!phys_ctx || !dom_ctx) {
13637 /* no context available */
13638 return;
13639 }
13640
13641 mg_lock_context(phys_ctx);
13642
13643 /* first try to find an existing handler */
13644 do {
13645 lastref = &(dom_ctx->handlers);
13646 for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
13647 tmp_rh = tmp_rh->next) {
13648 if (tmp_rh->handler_type == handler_type
13649 && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
13650 if (!is_delete_request) {
13651 /* update existing handler */
13653 /* Wait for end of use before updating */
13654 if (tmp_rh->refcount) {
13655 mg_unlock_context(phys_ctx);
13656 mg_sleep(1);
13657 mg_lock_context(phys_ctx);
13658 /* tmp_rh might have been freed, search again. */
13659 break;
13660 }
13661 /* Ok, the handler is no more use -> Update it */
13662 tmp_rh->handler = handler;
13663 } else if (handler_type == WEBSOCKET_HANDLER) {
13664 tmp_rh->subprotocols = subprotocols;
13666 tmp_rh->ready_handler = ready_handler;
13667 tmp_rh->data_handler = data_handler;
13668 tmp_rh->close_handler = close_handler;
13669 } else { /* AUTH_HANDLER */
13670 tmp_rh->auth_handler = auth_handler;
13671 }
13672 tmp_rh->cbdata = cbdata;
13673 } else {
13674 /* remove existing handler */
13676 /* Wait for end of use before removing */
13677 if (tmp_rh->refcount) {
13678 tmp_rh->removing = 1;
13679 mg_unlock_context(phys_ctx);
13680 mg_sleep(1);
13681 mg_lock_context(phys_ctx);
13682 /* tmp_rh might have been freed, search again. */
13683 break;
13684 }
13685 /* Ok, the handler is no more used */
13686 }
13687 *lastref = tmp_rh->next;
13688 mg_free(tmp_rh->uri);
13689 mg_free(tmp_rh);
13690 }
13691 mg_unlock_context(phys_ctx);
13692 return;
13693 }
13694 lastref = &(tmp_rh->next);
13695 }
13696 } while (tmp_rh != NULL);
13697
13698 if (is_delete_request) {
13699 /* no handler to set, this was a remove request to a non-existing
13700 * handler */
13701 mg_unlock_context(phys_ctx);
13702 return;
13703 }
13704
13705 tmp_rh =
13706 (struct mg_handler_info *)mg_calloc_ctx(1,
13707 sizeof(struct mg_handler_info),
13708 phys_ctx);
13709 if (tmp_rh == NULL) {
13710 mg_unlock_context(phys_ctx);
13711 mg_cry_ctx_internal(phys_ctx,
13712 "%s",
13713 "Cannot create new request handler struct, OOM");
13714 return;
13715 }
13716 tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
13717 if (!tmp_rh->uri) {
13718 mg_unlock_context(phys_ctx);
13719 mg_free(tmp_rh);
13720 mg_cry_ctx_internal(phys_ctx,
13721 "%s",
13722 "Cannot create new request handler struct, OOM");
13723 return;
13724 }
13725 tmp_rh->uri_len = urilen;
13727 tmp_rh->refcount = 0;
13728 tmp_rh->removing = 0;
13729 tmp_rh->handler = handler;
13730 } else if (handler_type == WEBSOCKET_HANDLER) {
13731 tmp_rh->subprotocols = subprotocols;
13733 tmp_rh->ready_handler = ready_handler;
13734 tmp_rh->data_handler = data_handler;
13735 tmp_rh->close_handler = close_handler;
13736 } else { /* AUTH_HANDLER */
13737 tmp_rh->auth_handler = auth_handler;
13738 }
13739 tmp_rh->cbdata = cbdata;
13740 tmp_rh->handler_type = handler_type;
13741 tmp_rh->next = NULL;
13742
13743 *lastref = tmp_rh;
13744 mg_unlock_context(phys_ctx);
13745}
13746
13747
13748void
13750 const char *uri,
13752 void *cbdata)
13753{
13755 &(ctx->dd),
13756 uri,
13758 handler == NULL,
13759 handler,
13760 NULL,
13761 NULL,
13762 NULL,
13763 NULL,
13764 NULL,
13765 NULL,
13766 cbdata);
13767}
13768
13769
13770void
13772 const char *uri,
13777 void *cbdata)
13778{
13780 uri,
13781 NULL,
13786 cbdata);
13787}
13788
13789
13790void
13792 struct mg_context *ctx,
13793 const char *uri,
13799 void *cbdata)
13800{
13801 int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
13802 && (data_handler == NULL)
13803 && (close_handler == NULL);
13805 &(ctx->dd),
13806 uri,
13808 is_delete_request,
13809 NULL,
13815 NULL,
13816 cbdata);
13817}
13818
13819
13820void
13822 const char *uri,
13824 void *cbdata)
13825{
13827 &(ctx->dd),
13828 uri,
13830 handler == NULL,
13831 NULL,
13832 NULL,
13833 NULL,
13834 NULL,
13835 NULL,
13836 NULL,
13837 handler,
13838 cbdata);
13839}
13840
13841
13842static int
13844 int handler_type,
13852 void **cbdata,
13853 struct mg_handler_info **handler_info)
13854{
13855 const struct mg_request_info *request_info = mg_get_request_info(conn);
13856 if (request_info) {
13857 const char *uri = request_info->local_uri;
13858 size_t urilen = strlen(uri);
13859 struct mg_handler_info *tmp_rh;
13860 int step, matched;
13861
13862 if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
13863 return 0;
13864 }
13865
13867
13868 for (step = 0; step < 3; step++) {
13869 for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
13870 tmp_rh = tmp_rh->next) {
13871 if (tmp_rh->handler_type != handler_type) {
13872 continue;
13873 }
13874 if (step == 0) {
13875 /* first try for an exact match */
13876 matched = (tmp_rh->uri_len == urilen)
13877 && (strcmp(tmp_rh->uri, uri) == 0);
13878 } else if (step == 1) {
13879 /* next try for a partial match, we will accept
13880 uri/something */
13881 matched =
13882 (tmp_rh->uri_len < urilen)
13883 && (uri[tmp_rh->uri_len] == '/')
13884 && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
13885 } else {
13886 /* finally try for pattern match */
13887 matched =
13888 match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
13889 }
13890 if (matched) {
13892 *subprotocols = tmp_rh->subprotocols;
13894 *ready_handler = tmp_rh->ready_handler;
13895 *data_handler = tmp_rh->data_handler;
13896 *close_handler = tmp_rh->close_handler;
13897 } else if (handler_type == REQUEST_HANDLER) {
13898 if (tmp_rh->removing) {
13899 /* Treat as none found */
13900 step = 2;
13901 break;
13902 }
13903 *handler = tmp_rh->handler;
13904 /* Acquire handler and give it back */
13905 tmp_rh->refcount++;
13906 *handler_info = tmp_rh;
13907 } else { /* AUTH_HANDLER */
13908 *auth_handler = tmp_rh->auth_handler;
13909 }
13910 *cbdata = tmp_rh->cbdata;
13912 return 1;
13913 }
13914 }
13915 }
13916
13918 }
13919 return 0; /* none found */
13920}
13921
13922
13923/* Check if the script file is in a path, allowed for script files.
13924 * This can be used if uploading files is possible not only for the server
13925 * admin, and the upload mechanism does not check the file extension.
13926 */
13927static int
13928is_in_script_path(const struct mg_connection *conn, const char *path)
13929{
13930 /* TODO (Feature): Add config value for allowed script path.
13931 * Default: All allowed. */
13932 (void)conn;
13933 (void)path;
13934 return 1;
13935}
13936
13937
13938#if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
13939static int
13940experimental_websocket_client_data_wrapper(struct mg_connection *conn,
13941 int bits,
13942 char *data,
13943 size_t len,
13944 void *cbdata)
13945{
13946 struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13947 if (pcallbacks->websocket_data) {
13948 return pcallbacks->websocket_data(conn, bits, data, len);
13949 }
13950 /* No handler set - assume "OK" */
13951 return 1;
13952}
13953
13954
13955static void
13956experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
13957 void *cbdata)
13958{
13959 struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13960 if (pcallbacks->connection_close) {
13961 pcallbacks->connection_close(conn);
13962 }
13963}
13964#endif
13965
13966
13967/* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
13968 */
13969static void
13971 struct mg_handler_info *handler_info)
13972{
13973 if (handler_info != NULL) {
13974 /* Use context lock for ref counter */
13976 handler_info->refcount--;
13978 }
13979}
13980
13981
13982/* This is the heart of the Civetweb's logic.
13983 * This function is called when the request is read, parsed and validated,
13984 * and Civetweb must decide what action to take: serve a file, or
13985 * a directory, or call embedded function, etcetera. */
13986static void
13988{
13989 struct mg_request_info *ri = &conn->request_info;
13990 char path[UTF8_PATH_MAX];
13991 int uri_len, ssl_index;
13992 int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
13993 is_put_or_delete_request = 0, is_callback_resource = 0,
13994 is_template_text_file = 0;
13995 int i;
13997 mg_request_handler callback_handler = NULL;
13998 struct mg_handler_info *handler_info = NULL;
14000 mg_websocket_connect_handler ws_connect_handler = NULL;
14001 mg_websocket_ready_handler ws_ready_handler = NULL;
14002 mg_websocket_data_handler ws_data_handler = NULL;
14003 mg_websocket_close_handler ws_close_handler = NULL;
14004 void *callback_data = NULL;
14005 mg_authorization_handler auth_handler = NULL;
14006 void *auth_callback_data = NULL;
14007 int handler_type;
14008 time_t curtime = time(NULL);
14009 char date[64];
14010 char *tmp;
14011
14012 path[0] = 0;
14013
14014 /* 0. Reset internal state (required for HTTP/2 proxy) */
14015 conn->request_state = 0;
14016
14017 /* 1. get the request url */
14018 /* 1.1. split into url and query string */
14019 if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
14020 != NULL) {
14021 *((char *)conn->request_info.query_string++) = '\0';
14022 }
14023
14024 /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
14025 if (!conn->client.is_ssl && conn->client.ssl_redir) {
14026 ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
14027 if (ssl_index >= 0) {
14028 int port = (int)ntohs(USA_IN_PORT_UNSAFE(
14029 &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
14030 redirect_to_https_port(conn, port);
14031 } else {
14032 /* A http to https forward port has been specified,
14033 * but no https port to forward to. */
14034 mg_send_http_error(conn,
14035 503,
14036 "%s",
14037 "Error: SSL forward not configured properly");
14038 mg_cry_internal(conn,
14039 "%s",
14040 "Can not redirect to SSL, no SSL port available");
14041 }
14042 return;
14043 }
14044 uri_len = (int)strlen(ri->local_uri);
14045
14046 /* 1.3. decode url (if config says so) */
14047 if (should_decode_url(conn)) {
14049 ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
14050 }
14051
14052 /* URL decode the query-string only if explicity set in the configuration */
14053 if (conn->request_info.query_string) {
14054 if (should_decode_query_string(conn)) {
14056 }
14057 }
14058
14059 /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
14060 * possible. The fact that we cleaned the URI is stored in that the
14061 * pointer to ri->local_ur and ri->local_uri_raw are now different.
14062 * ri->local_uri_raw still points to memory allocated in
14063 * worker_thread_run(). ri->local_uri is private to the request so we
14064 * don't have to use preallocated memory here. */
14065 tmp = mg_strdup(ri->local_uri_raw);
14066 if (!tmp) {
14067 /* Out of memory. We cannot do anything reasonable here. */
14068 return;
14069 }
14071 ri->local_uri = tmp;
14072
14073 /* step 1. completed, the url is known now */
14074 DEBUG_TRACE("URL: %s", ri->local_uri);
14075
14076 /* 2. if this ip has limited speed, set it for this connection */
14078 &conn->client.rsa,
14079 ri->local_uri);
14080
14081 /* 3. call a "handle everything" callback, if registered */
14082 if (conn->phys_ctx->callbacks.begin_request != NULL) {
14083 /* Note that since V1.7 the "begin_request" function is called
14084 * before an authorization check. If an authorization check is
14085 * required, use a request_handler instead. */
14086 i = conn->phys_ctx->callbacks.begin_request(conn);
14087 if (i > 0) {
14088 /* callback already processed the request. Store the
14089 return value as a status code for the access log. */
14090 conn->status_code = i;
14091 if (!conn->must_close) {
14093 }
14094 return;
14095 } else if (i == 0) {
14096 /* civetweb should process the request */
14097 } else {
14098 /* unspecified - may change with the next version */
14099 return;
14100 }
14101 }
14102
14103 /* request not yet handled by a handler or redirect, so the request
14104 * is processed here */
14105
14106 /* 4. Check for CORS preflight requests and handle them (if configured).
14107 * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
14108 */
14109 if (!strcmp(ri->request_method, "OPTIONS")) {
14110 /* Send a response to CORS preflights only if
14111 * access_control_allow_methods is not NULL and not an empty string.
14112 * In this case, scripts can still handle CORS. */
14113 const char *cors_meth_cfg =
14115 const char *cors_orig_cfg =
14117 const char *cors_origin =
14118 get_header(ri->http_headers, ri->num_headers, "Origin");
14119 const char *cors_acrm = get_header(ri->http_headers,
14120 ri->num_headers,
14121 "Access-Control-Request-Method");
14122
14123 /* Todo: check if cors_origin is in cors_orig_cfg.
14124 * Or, let the client check this. */
14125
14126 if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
14127 && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
14128 && (cors_origin != NULL) && (cors_acrm != NULL)) {
14129 /* This is a valid CORS preflight, and the server is configured
14130 * to handle it automatically. */
14131 const char *cors_acrh =
14133 ri->num_headers,
14134 "Access-Control-Request-Headers");
14135
14136 gmt_time_string(date, sizeof(date), &curtime);
14137 mg_printf(conn,
14138 "HTTP/1.1 200 OK\r\n"
14139 "Date: %s\r\n"
14140 "Access-Control-Allow-Origin: %s\r\n"
14141 "Access-Control-Allow-Methods: %s\r\n"
14142 "Content-Length: 0\r\n"
14143 "Connection: %s\r\n",
14144 date,
14145 cors_orig_cfg,
14146 ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
14148
14149 if (cors_acrh != NULL) {
14150 /* CORS request is asking for additional headers */
14151 const char *cors_hdr_cfg =
14153
14154 if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
14155 /* Allow only if access_control_allow_headers is
14156 * not NULL and not an empty string. If this
14157 * configuration is set to *, allow everything.
14158 * Otherwise this configuration must be a list
14159 * of allowed HTTP header names. */
14160 mg_printf(conn,
14161 "Access-Control-Allow-Headers: %s\r\n",
14162 ((cors_hdr_cfg[0] == '*') ? cors_acrh
14163 : cors_hdr_cfg));
14164 }
14165 }
14166 mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
14167
14168 mg_printf(conn, "\r\n");
14169 return;
14170 }
14171 }
14172
14173 /* 5. interpret the url to find out how the request must be handled
14174 */
14175 /* 5.1. first test, if the request targets the regular http(s)://
14176 * protocol namespace or the websocket ws(s):// protocol namespace.
14177 */
14178 is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
14179#if defined(USE_WEBSOCKET)
14180 handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
14181#else
14182 handler_type = REQUEST_HANDLER;
14183#endif /* defined(USE_WEBSOCKET) */
14184
14185 if (is_websocket_request) {
14186 HTTP1_only;
14187 }
14188
14189 /* 5.2. check if the request will be handled by a callback */
14190 if (get_request_handler(conn,
14191 handler_type,
14192 &callback_handler,
14193 &subprotocols,
14194 &ws_connect_handler,
14195 &ws_ready_handler,
14196 &ws_data_handler,
14197 &ws_close_handler,
14198 NULL,
14199 &callback_data,
14200 &handler_info)) {
14201 /* 5.2.1. A callback will handle this request. All requests
14202 * handled by a callback have to be considered as requests
14203 * to a script resource. */
14204 is_callback_resource = 1;
14205 is_script_resource = 1;
14206 is_put_or_delete_request = is_put_or_delete_method(conn);
14207 } else {
14208 no_callback_resource:
14209
14210 /* 5.2.2. No callback is responsible for this request. The URI
14211 * addresses a file based resource (static content or Lua/cgi
14212 * scripts in the file system). */
14213 is_callback_resource = 0;
14214 interpret_uri(conn,
14215 path,
14216 sizeof(path),
14217 &file.stat,
14218 &is_found,
14219 &is_script_resource,
14220 &is_websocket_request,
14221 &is_put_or_delete_request,
14222 &is_template_text_file);
14223 }
14224
14225 /* 6. authorization check */
14226 /* 6.1. a custom authorization handler is installed */
14227 if (get_request_handler(conn,
14229 NULL,
14230 NULL,
14231 NULL,
14232 NULL,
14233 NULL,
14234 NULL,
14235 &auth_handler,
14236 &auth_callback_data,
14237 NULL)) {
14238 if (!auth_handler(conn, auth_callback_data)) {
14239
14240 /* Callback handler will not be used anymore. Release it */
14241 release_handler_ref(conn, handler_info);
14242
14243 return;
14244 }
14245 } else if (is_put_or_delete_request && !is_script_resource
14246 && !is_callback_resource) {
14247 HTTP1_only;
14248 /* 6.2. this request is a PUT/DELETE to a real file */
14249 /* 6.2.1. thus, the server must have real files */
14250#if defined(NO_FILES)
14251 if (1) {
14252#else
14253 if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
14254#endif
14255 /* This code path will not be called for request handlers */
14256 DEBUG_ASSERT(handler_info == NULL);
14257
14258 /* This server does not have any real files, thus the
14259 * PUT/DELETE methods are not valid. */
14260 mg_send_http_error(conn,
14261 405,
14262 "%s method not allowed",
14264 return;
14265 }
14266
14267#if !defined(NO_FILES)
14268 /* 6.2.2. Check if put authorization for static files is
14269 * available.
14270 */
14271 if (!is_authorized_for_put(conn)) {
14272 send_authorization_request(conn, NULL);
14273 return;
14274 }
14275#endif
14276
14277 } else {
14278 /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
14279 * or it is a PUT or DELETE request to a resource that does not
14280 * correspond to a file. Check authorization. */
14281 if (!check_authorization(conn, path)) {
14282 send_authorization_request(conn, NULL);
14283
14284 /* Callback handler will not be used anymore. Release it */
14285 release_handler_ref(conn, handler_info);
14286
14287 return;
14288 }
14289 }
14290
14291 /* request is authorized or does not need authorization */
14292
14293 /* 7. check if there are request handlers for this uri */
14294 if (is_callback_resource) {
14295 HTTP1_only;
14296 if (!is_websocket_request) {
14297 i = callback_handler(conn, callback_data);
14298
14299 /* Callback handler will not be used anymore. Release it */
14300 release_handler_ref(conn, handler_info);
14301
14302 if (i > 0) {
14303 /* Do nothing, callback has served the request. Store
14304 * then return value as status code for the log and discard
14305 * all data from the client not used by the callback. */
14306 conn->status_code = i;
14307 if (!conn->must_close) {
14309 }
14310 } else {
14311 /* The handler did NOT handle the request. */
14312 /* Some proper reactions would be:
14313 * a) close the connections without sending anything
14314 * b) send a 404 not found
14315 * c) try if there is a file matching the URI
14316 * It would be possible to do a, b or c in the callback
14317 * implementation, and return 1 - we cannot do anything
14318 * here, that is not possible in the callback.
14319 *
14320 * TODO: What would be the best reaction here?
14321 * (Note: The reaction may change, if there is a better
14322 * idea.)
14323 */
14324
14325 /* For the moment, use option c: We look for a proper file,
14326 * but since a file request is not always a script resource,
14327 * the authorization check might be different. */
14328 interpret_uri(conn,
14329 path,
14330 sizeof(path),
14331 &file.stat,
14332 &is_found,
14333 &is_script_resource,
14334 &is_websocket_request,
14335 &is_put_or_delete_request,
14336 &is_template_text_file);
14337 callback_handler = NULL;
14338
14339 /* Here we are at a dead end:
14340 * According to URI matching, a callback should be
14341 * responsible for handling the request,
14342 * we called it, but the callback declared itself
14343 * not responsible.
14344 * We use a goto here, to get out of this dead end,
14345 * and continue with the default handling.
14346 * A goto here is simpler and better to understand
14347 * than some curious loop. */
14348 goto no_callback_resource;
14349 }
14350 } else {
14351#if defined(USE_WEBSOCKET)
14352 handle_websocket_request(conn,
14353 path,
14354 is_callback_resource,
14356 ws_connect_handler,
14357 ws_ready_handler,
14358 ws_data_handler,
14359 ws_close_handler,
14360 callback_data);
14361#endif
14362 }
14363 return;
14364 }
14365
14366 /* 8. handle websocket requests */
14367#if defined(USE_WEBSOCKET)
14368 if (is_websocket_request) {
14369 HTTP1_only;
14370 if (is_script_resource) {
14371
14372 if (is_in_script_path(conn, path)) {
14373 /* Websocket Lua script */
14374 handle_websocket_request(conn,
14375 path,
14376 0 /* Lua Script */,
14377 NULL,
14378 NULL,
14379 NULL,
14380 NULL,
14381 NULL,
14382 conn->phys_ctx->user_data);
14383 } else {
14384 /* Script was in an illegal path */
14385 mg_send_http_error(conn, 403, "%s", "Forbidden");
14386 }
14387 } else {
14388 mg_send_http_error(conn, 404, "%s", "Not found");
14389 }
14390 return;
14391 } else
14392#endif
14393
14394#if defined(NO_FILES)
14395 /* 9a. In case the server uses only callbacks, this uri is
14396 * unknown.
14397 * Then, all request handling ends here. */
14398 mg_send_http_error(conn, 404, "%s", "Not Found");
14399
14400#else
14401 /* 9b. This request is either for a static file or resource handled
14402 * by a script file. Thus, a DOCUMENT_ROOT must exist. */
14403 if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
14404 mg_send_http_error(conn, 404, "%s", "Not Found");
14405 return;
14406 }
14407
14408 /* 10. Request is handled by a script */
14409 if (is_script_resource) {
14410 HTTP1_only;
14411 handle_file_based_request(conn, path, &file);
14412 return;
14413 }
14414
14415 /* 11. Handle put/delete/mkcol requests */
14416 if (is_put_or_delete_request) {
14417 HTTP1_only;
14418 /* 11.1. PUT method */
14419 if (!strcmp(ri->request_method, "PUT")) {
14420 put_file(conn, path);
14421 return;
14422 }
14423 /* 11.2. DELETE method */
14424 if (!strcmp(ri->request_method, "DELETE")) {
14425 delete_file(conn, path);
14426 return;
14427 }
14428 /* 11.3. MKCOL method */
14429 if (!strcmp(ri->request_method, "MKCOL")) {
14430 mkcol(conn, path);
14431 return;
14432 }
14433 /* 11.4. PATCH method
14434 * This method is not supported for static resources,
14435 * only for scripts (Lua, CGI) and callbacks. */
14436 mg_send_http_error(conn,
14437 405,
14438 "%s method not allowed",
14440 return;
14441 }
14442
14443 /* 11. File does not exist, or it was configured that it should be
14444 * hidden */
14445 if (!is_found || (must_hide_file(conn, path))) {
14446 mg_send_http_error(conn, 404, "%s", "Not found");
14447 return;
14448 }
14449
14450 /* 12. Directory uris should end with a slash */
14451 if (file.stat.is_directory && (uri_len > 0)
14452 && (ri->local_uri[uri_len - 1] != '/')) {
14453
14454 size_t len = strlen(ri->request_uri);
14455 size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
14456 char *new_path = (char *)mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
14457 if (!new_path) {
14458 mg_send_http_error(conn, 500, "out or memory");
14459 } else {
14460 memcpy(new_path, ri->request_uri, len);
14461 new_path[len] = '/';
14462 new_path[len + 1] = 0;
14463 if (ri->query_string) {
14464 new_path[len + 1] = '?';
14465 /* Copy query string including terminating zero */
14466 memcpy(new_path + len + 2, ri->query_string, lenQS);
14467 }
14468 mg_send_http_redirect(conn, new_path, 301);
14469 mg_free(new_path);
14470 }
14471 return;
14472 }
14473
14474 /* 13. Handle other methods than GET/HEAD */
14475 /* 13.1. Handle PROPFIND */
14476 if (!strcmp(ri->request_method, "PROPFIND")) {
14477 handle_propfind(conn, path, &file.stat);
14478 return;
14479 }
14480 /* 13.2. Handle OPTIONS for files */
14481 if (!strcmp(ri->request_method, "OPTIONS")) {
14482 /* This standard handler is only used for real files.
14483 * Scripts should support the OPTIONS method themselves, to allow a
14484 * maximum flexibility.
14485 * Lua and CGI scripts may fully support CORS this way (including
14486 * preflights). */
14487 send_options(conn);
14488 return;
14489 }
14490 /* 13.3. everything but GET and HEAD (e.g. POST) */
14491 if ((0 != strcmp(ri->request_method, "GET"))
14492 && (0 != strcmp(ri->request_method, "HEAD"))) {
14493 mg_send_http_error(conn,
14494 405,
14495 "%s method not allowed",
14497 return;
14498 }
14499
14500 /* 14. directories */
14501 if (file.stat.is_directory) {
14502 /* Substitute files have already been handled above. */
14503 /* Here we can either generate and send a directory listing,
14504 * or send an "access denied" error. */
14506 "yes")) {
14507 handle_directory_request(conn, path);
14508 } else {
14509 mg_send_http_error(conn,
14510 403,
14511 "%s",
14512 "Error: Directory listing denied");
14513 }
14514 return;
14515 }
14516
14517 /* 15. Files with search/replace patterns: LSP and SSI */
14518 if (is_template_text_file) {
14519 HTTP1_only;
14520 handle_file_based_request(conn, path, &file);
14521 return;
14522 }
14523
14524 /* 16. Static file - maybe cached */
14525#if !defined(NO_CACHING)
14526 if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
14527 /* Send 304 "Not Modified" - this must not send any body data */
14529 return;
14530 }
14531#endif /* !NO_CACHING */
14532
14533 /* 17. Static file - not cached */
14534 handle_static_file_request(conn, path, &file, NULL, NULL);
14535
14536#endif /* !defined(NO_FILES) */
14537}
14538
14539
14540#if !defined(NO_FILESYSTEMS)
14541static void
14543 const char *path,
14544 struct mg_file *file)
14545{
14546#if !defined(NO_CGI)
14547 unsigned char cgi_config_idx, inc, max;
14548#endif
14549
14550 if (!conn || !conn->dom_ctx) {
14551 return;
14552 }
14553
14554#if defined(USE_LUA)
14555 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
14556 path)
14557 > 0) {
14558 if (is_in_script_path(conn, path)) {
14559 /* Lua server page: an SSI like page containing mostly plain
14560 * html code plus some tags with server generated contents. */
14561 handle_lsp_request(conn, path, file, NULL);
14562 } else {
14563 /* Script was in an illegal path */
14564 mg_send_http_error(conn, 403, "%s", "Forbidden");
14565 }
14566 return;
14567 }
14568
14569 if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
14570 > 0) {
14571 if (is_in_script_path(conn, path)) {
14572 /* Lua in-server module script: a CGI like script used to
14573 * generate the entire reply. */
14574 mg_exec_lua_script(conn, path, NULL);
14575 } else {
14576 /* Script was in an illegal path */
14577 mg_send_http_error(conn, 403, "%s", "Forbidden");
14578 }
14579 return;
14580 }
14581#endif
14582
14583#if defined(USE_DUKTAPE)
14584 if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
14585 path)
14586 > 0) {
14587 if (is_in_script_path(conn, path)) {
14588 /* Call duktape to generate the page */
14589 mg_exec_duktape_script(conn, path);
14590 } else {
14591 /* Script was in an illegal path */
14592 mg_send_http_error(conn, 403, "%s", "Forbidden");
14593 }
14594 return;
14595 }
14596#endif
14597
14598#if !defined(NO_CGI)
14601 for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
14602 if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
14604 conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
14605 path)
14606 > 0) {
14607 if (is_in_script_path(conn, path)) {
14608 /* CGI scripts may support all HTTP methods */
14609 handle_cgi_request(conn, path, 0);
14610 } else {
14611 /* Script was in an illegal path */
14612 mg_send_http_error(conn, 403, "%s", "Forbidden");
14613 }
14614 return;
14615 }
14616 }
14617 }
14618#endif /* !NO_CGI */
14619
14620 if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
14621 if (is_in_script_path(conn, path)) {
14622 handle_ssi_file_request(conn, path, file);
14623 } else {
14624 /* Script was in an illegal path */
14625 mg_send_http_error(conn, 403, "%s", "Forbidden");
14626 }
14627 return;
14628 }
14629
14630#if !defined(NO_CACHING)
14631 if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
14632 /* Send 304 "Not Modified" - this must not send any body data */
14634 return;
14635 }
14636#endif /* !NO_CACHING */
14637
14638 handle_static_file_request(conn, path, file, NULL, NULL);
14639}
14640#endif /* NO_FILESYSTEMS */
14641
14642
14643static void
14645{
14646 unsigned int i;
14647 if (!ctx) {
14648 return;
14649 }
14650
14651 for (i = 0; i < ctx->num_listening_sockets; i++) {
14653#if defined(USE_X_DOM_SOCKET)
14654 /* For unix domain sockets, the socket name represents a file that has
14655 * to be deleted. */
14656 /* See
14657 * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
14658 */
14659 if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
14660 && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
14662 remove(ctx->listening_sockets[i].lsa.sun.sun_path));
14663 }
14664#endif
14666 }
14668 ctx->listening_sockets = NULL;
14670 ctx->listening_socket_fds = NULL;
14671}
14672
14673
14674/* Valid listening port specification is: [ip_address:]port[s]
14675 * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
14676 * Examples for IPv6: [::]:80, [::1]:80,
14677 * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
14678 * see https://tools.ietf.org/html/rfc3513#section-2.2
14679 * In order to bind to both, IPv4 and IPv6, you can either add
14680 * both ports using 8080,[::]:8080, or the short form +8080.
14681 * Both forms differ in detail: 8080,[::]:8080 create two sockets,
14682 * one only accepting IPv4 the other only IPv6. +8080 creates
14683 * one socket accepting IPv4 and IPv6. Depending on the IPv6
14684 * environment, they might work differently, or might not work
14685 * at all - it must be tested what options work best in the
14686 * relevant network environment.
14687 */
14688static int
14689parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
14690{
14691 unsigned int a, b, c, d;
14692 unsigned port;
14693 unsigned long portUL;
14694 int ch, len;
14695 const char *cb;
14696 char *endptr;
14697#if defined(USE_IPV6)
14698 char buf[100] = {0};
14699#endif
14700
14701 /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
14702 * Also, all-zeroes in the socket address means binding to all addresses
14703 * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
14704 memset(so, 0, sizeof(*so));
14705 so->lsa.sin.sin_family = AF_INET;
14706 *ip_version = 0;
14707
14708 /* Initialize len as invalid. */
14709 port = 0;
14710 len = 0;
14711
14712 /* Test for different ways to format this string */
14713 if (sscanf(vec->ptr,
14714 "%u.%u.%u.%u:%u%n",
14715 &a,
14716 &b,
14717 &c,
14718 &d,
14719 &port,
14720 &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
14721 // to an integer value, but function will not report
14722 // conversion errors; consider using 'strtol' instead
14723 == 5) {
14724 /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
14725 so->lsa.sin.sin_addr.s_addr =
14726 htonl((a << 24) | (b << 16) | (c << 8) | d);
14727 so->lsa.sin.sin_port = htons((uint16_t)port);
14728 *ip_version = 4;
14729
14730#if defined(USE_IPV6)
14731 } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
14732 && ((size_t)len <= vec->len)
14733 && mg_inet_pton(
14734 AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
14735 /* IPv6 address, examples: see above */
14736 /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
14737 */
14738 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14739 *ip_version = 6;
14740#endif
14741
14742 } else if ((vec->ptr[0] == '+')
14743 && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
14744 == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
14745 // string to an integer value, but function will not
14746 // report conversion errors; consider using 'strtol'
14747 // instead
14748
14749 /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
14750 /* Add 1 to len for the + character we skipped before */
14751 len++;
14752
14753#if defined(USE_IPV6)
14754 /* Set socket family to IPv6, do not use IPV6_V6ONLY */
14755 so->lsa.sin6.sin6_family = AF_INET6;
14756 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14757 *ip_version = 4 + 6;
14758#else
14759 /* Bind to IPv4 only, since IPv6 is not built in. */
14760 so->lsa.sin.sin_port = htons((uint16_t)port);
14761 *ip_version = 4;
14762#endif
14763
14764 } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
14765 && (vec->ptr != endptr)) {
14766 len = (int)(endptr - vec->ptr);
14767 port = (uint16_t)portUL;
14768 /* If only port is specified, bind to IPv4, INADDR_ANY */
14769 so->lsa.sin.sin_port = htons((uint16_t)port);
14770 *ip_version = 4;
14771
14772 } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
14773 /* String could be a hostname. This check algotithm
14774 * will only work for RFC 952 compliant hostnames,
14775 * starting with a letter, containing only letters,
14776 * digits and hyphen ('-'). Newer specs may allow
14777 * more, but this is not guaranteed here, since it
14778 * may interfere with rules for port option lists. */
14779
14780 /* According to RFC 1035, hostnames are restricted to 255 characters
14781 * in total (63 between two dots). */
14782 char hostname[256];
14783 size_t hostnlen = (size_t)(cb - vec->ptr);
14784
14785 if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
14786 /* This would be invalid in any case */
14787 *ip_version = 0;
14788 return 0;
14789 }
14790
14791 mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
14792
14793 if (mg_inet_pton(
14794 AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
14795 if (sscanf(cb + 1, "%u%n", &port, &len)
14796 == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
14797 // string to an integer value, but function will not
14798 // report conversion errors; consider using 'strtol'
14799 // instead
14800 *ip_version = 4;
14801 so->lsa.sin.sin_port = htons((uint16_t)port);
14802 len += (int)(hostnlen + 1);
14803 } else {
14804 len = 0;
14805 }
14806#if defined(USE_IPV6)
14807 } else if (mg_inet_pton(AF_INET6,
14808 hostname,
14809 &so->lsa.sin6,
14810 sizeof(so->lsa.sin6),
14811 1)) {
14812 if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
14813 *ip_version = 6;
14814 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14815 len += (int)(hostnlen + 1);
14816 } else {
14817 len = 0;
14818 }
14819#endif
14820 } else {
14821 len = 0;
14822 }
14823
14824#if defined(USE_X_DOM_SOCKET)
14825
14826 } else if (vec->ptr[0] == 'x') {
14827 /* unix (linux) domain socket */
14828 if (vec->len < sizeof(so->lsa.sun.sun_path)) {
14829 len = vec->len;
14830 so->lsa.sun.sun_family = AF_UNIX;
14831 memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
14832 memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
14833 port = 0;
14834 *ip_version = 99;
14835 } else {
14836 /* String too long */
14837 len = 0;
14838 }
14839#endif
14840
14841 } else {
14842 /* Parsing failure. */
14843 len = 0;
14844 }
14845
14846 /* sscanf and the option splitting code ensure the following condition
14847 * Make sure the port is valid and vector ends with the port, 's' or 'r' */
14848 if ((len > 0) && is_valid_port(port)
14849 && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
14850 /* Next character after the port number */
14851 ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
14852 so->is_ssl = (ch == 's');
14853 so->ssl_redir = (ch == 'r');
14854 if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
14855 return 1;
14856 }
14857 }
14858
14859 /* Reset ip_version to 0 if there is an error */
14860 *ip_version = 0;
14861 return 0;
14862}
14863
14864
14865/* Is there any SSL port in use? */
14866static int
14867is_ssl_port_used(const char *ports)
14868{
14869 if (ports) {
14870 /* There are several different allowed syntax variants:
14871 * - "80" for a single port using every network interface
14872 * - "localhost:80" for a single port using only localhost
14873 * - "80,localhost:8080" for two ports, one bound to localhost
14874 * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
14875 * to IPv4 localhost, one to IPv6 localhost
14876 * - "+80" use port 80 for IPv4 and IPv6
14877 * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
14878 * for both: IPv4 and IPv4
14879 * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
14880 * additionally port 8080 bound to localhost connections
14881 *
14882 * If we just look for 's' anywhere in the string, "localhost:80"
14883 * will be detected as SSL (false positive).
14884 * Looking for 's' after a digit may cause false positives in
14885 * "my24service:8080".
14886 * Looking from 's' backward if there are only ':' and numbers
14887 * before will not work for "24service:8080" (non SSL, port 8080)
14888 * or "24s" (SSL, port 24).
14889 *
14890 * Remark: Initially hostnames were not allowed to start with a
14891 * digit (according to RFC 952), this was allowed later (RFC 1123,
14892 * Section 2.1).
14893 *
14894 * To get this correct, the entire string must be parsed as a whole,
14895 * reading it as a list element for element and parsing with an
14896 * algorithm equivalent to parse_port_string.
14897 *
14898 * In fact, we use local interface names here, not arbitrary
14899 * hostnames, so in most cases the only name will be "localhost".
14900 *
14901 * So, for now, we use this simple algorithm, that may still return
14902 * a false positive in bizarre cases.
14903 */
14904 int i;
14905 int portslen = (int)strlen(ports);
14906 char prevIsNumber = 0;
14907
14908 for (i = 0; i < portslen; i++) {
14909 if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
14910 return 1;
14911 }
14912 if (ports[i] >= '0' && ports[i] <= '9') {
14913 prevIsNumber = 1;
14914 } else {
14915 prevIsNumber = 0;
14916 }
14917 }
14918 }
14919 return 0;
14920}
14921
14922
14923static int
14925{
14926 const char *list;
14927 int on = 1;
14928#if defined(USE_IPV6)
14929 int off = 0;
14930#endif
14931 struct vec vec;
14932 struct socket so, *ptr;
14933
14934 struct mg_pollfd *pfd;
14935 union usa usa;
14936 socklen_t len;
14937 int ip_version;
14938
14939 int portsTotal = 0;
14940 int portsOk = 0;
14941
14942 const char *opt_txt;
14943 long opt_listen_backlog;
14944
14945 if (!phys_ctx) {
14946 return 0;
14947 }
14948
14949 memset(&so, 0, sizeof(so));
14950 memset(&usa, 0, sizeof(usa));
14951 len = sizeof(usa);
14952 list = phys_ctx->dd.config[LISTENING_PORTS];
14953
14954 while ((list = next_option(list, &vec, NULL)) != NULL) {
14955
14956 portsTotal++;
14957
14958 if (!parse_port_string(&vec, &so, &ip_version)) {
14960 phys_ctx,
14961 "%.*s: invalid port spec (entry %i). Expecting list of: %s",
14962 (int)vec.len,
14963 vec.ptr,
14964 portsTotal,
14965 "[IP_ADDRESS:]PORT[s|r]");
14966 continue;
14967 }
14968
14969#if !defined(NO_SSL)
14970 if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
14971
14972 mg_cry_ctx_internal(phys_ctx,
14973 "Cannot add SSL socket (entry %i)",
14974 portsTotal);
14975 continue;
14976 }
14977#endif
14978 /* Create socket. */
14979 /* For a list of protocol numbers (e.g., TCP==6) see:
14980 * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
14981 */
14982 if ((so.sock =
14983 socket(so.lsa.sa.sa_family,
14984 SOCK_STREAM,
14985 (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
14986 == INVALID_SOCKET) {
14987
14988 mg_cry_ctx_internal(phys_ctx,
14989 "cannot create socket (entry %i)",
14990 portsTotal);
14991 continue;
14992 }
14993
14994#if defined(_WIN32)
14995 /* Windows SO_REUSEADDR lets many procs binds to a
14996 * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
14997 * if someone already has the socket -- DTL */
14998 /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
14999 * Windows might need a few seconds before
15000 * the same port can be used again in the
15001 * same process, so a short Sleep may be
15002 * required between mg_stop and mg_start.
15003 */
15004 if (setsockopt(so.sock,
15005 SOL_SOCKET,
15006 SO_EXCLUSIVEADDRUSE,
15007 (SOCK_OPT_TYPE)&on,
15008 sizeof(on))
15009 != 0) {
15010
15011 /* Set reuse option, but don't abort on errors. */
15013 phys_ctx,
15014 "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
15015 portsTotal);
15016 }
15017#else
15018 if (setsockopt(so.sock,
15019 SOL_SOCKET,
15020 SO_REUSEADDR,
15021 (SOCK_OPT_TYPE)&on,
15022 sizeof(on))
15023 != 0) {
15024
15025 /* Set reuse option, but don't abort on errors. */
15027 phys_ctx,
15028 "cannot set socket option SO_REUSEADDR (entry %i)",
15029 portsTotal);
15030 }
15031#endif
15032
15033#if defined(USE_X_DOM_SOCKET)
15034 if (ip_version == 99) {
15035 /* Unix domain socket */
15036 } else
15037#endif
15038
15039 if (ip_version > 4) {
15040 /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
15041#if defined(USE_IPV6)
15042 if (ip_version > 6) {
15043 if (so.lsa.sa.sa_family == AF_INET6
15044 && setsockopt(so.sock,
15045 IPPROTO_IPV6,
15046 IPV6_V6ONLY,
15047 (void *)&off,
15048 sizeof(off))
15049 != 0) {
15050
15051 /* Set IPv6 only option, but don't abort on errors. */
15052 mg_cry_ctx_internal(phys_ctx,
15053 "cannot set socket option "
15054 "IPV6_V6ONLY=off (entry %i)",
15055 portsTotal);
15056 }
15057 } else {
15058 if (so.lsa.sa.sa_family == AF_INET6
15059 && setsockopt(so.sock,
15060 IPPROTO_IPV6,
15061 IPV6_V6ONLY,
15062 (void *)&on,
15063 sizeof(on))
15064 != 0) {
15065
15066 /* Set IPv6 only option, but don't abort on errors. */
15067 mg_cry_ctx_internal(phys_ctx,
15068 "cannot set socket option "
15069 "IPV6_V6ONLY=on (entry %i)",
15070 portsTotal);
15071 }
15072 }
15073#else
15074 mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
15075 closesocket(so.sock);
15076 so.sock = INVALID_SOCKET;
15077 continue;
15078#endif
15079 }
15080
15081 if (so.lsa.sa.sa_family == AF_INET) {
15082
15083 len = sizeof(so.lsa.sin);
15084 if (bind(so.sock, &so.lsa.sa, len) != 0) {
15085 mg_cry_ctx_internal(phys_ctx,
15086 "cannot bind to %.*s: %d (%s)",
15087 (int)vec.len,
15088 vec.ptr,
15089 (int)ERRNO,
15090 strerror(errno));
15091 closesocket(so.sock);
15092 so.sock = INVALID_SOCKET;
15093 continue;
15094 }
15095 }
15096#if defined(USE_IPV6)
15097 else if (so.lsa.sa.sa_family == AF_INET6) {
15098
15099 len = sizeof(so.lsa.sin6);
15100 if (bind(so.sock, &so.lsa.sa, len) != 0) {
15101 mg_cry_ctx_internal(phys_ctx,
15102 "cannot bind to IPv6 %.*s: %d (%s)",
15103 (int)vec.len,
15104 vec.ptr,
15105 (int)ERRNO,
15106 strerror(errno));
15107 closesocket(so.sock);
15108 so.sock = INVALID_SOCKET;
15109 continue;
15110 }
15111 }
15112#endif
15113#if defined(USE_X_DOM_SOCKET)
15114 else if (so.lsa.sa.sa_family == AF_UNIX) {
15115
15116 len = sizeof(so.lsa.sun);
15117 if (bind(so.sock, &so.lsa.sa, len) != 0) {
15118 mg_cry_ctx_internal(phys_ctx,
15119 "cannot bind to unix socket %s: %d (%s)",
15120 so.lsa.sun.sun_path,
15121 (int)ERRNO,
15122 strerror(errno));
15123 closesocket(so.sock);
15124 so.sock = INVALID_SOCKET;
15125 continue;
15126 }
15127 }
15128#endif
15129 else {
15131 phys_ctx,
15132 "cannot bind: address family not supported (entry %i)",
15133 portsTotal);
15134 closesocket(so.sock);
15135 so.sock = INVALID_SOCKET;
15136 continue;
15137 }
15138
15139 opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
15140 opt_listen_backlog = strtol(opt_txt, NULL, 10);
15141 if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
15142 mg_cry_ctx_internal(phys_ctx,
15143 "%s value \"%s\" is invalid",
15145 opt_txt);
15146 closesocket(so.sock);
15147 so.sock = INVALID_SOCKET;
15148 continue;
15149 }
15150
15151 if (listen(so.sock, (int)opt_listen_backlog) != 0) {
15152
15153 mg_cry_ctx_internal(phys_ctx,
15154 "cannot listen to %.*s: %d (%s)",
15155 (int)vec.len,
15156 vec.ptr,
15157 (int)ERRNO,
15158 strerror(errno));
15159 closesocket(so.sock);
15160 so.sock = INVALID_SOCKET;
15161 continue;
15162 }
15163
15164 if ((getsockname(so.sock, &(usa.sa), &len) != 0)
15165 || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
15166
15167 int err = (int)ERRNO;
15168 mg_cry_ctx_internal(phys_ctx,
15169 "call to getsockname failed %.*s: %d (%s)",
15170 (int)vec.len,
15171 vec.ptr,
15172 err,
15173 strerror(errno));
15174 closesocket(so.sock);
15175 so.sock = INVALID_SOCKET;
15176 continue;
15177 }
15178
15179 /* Update lsa port in case of random free ports */
15180#if defined(USE_IPV6)
15181 if (so.lsa.sa.sa_family == AF_INET6) {
15182 so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
15183 } else
15184#endif
15185 {
15186 so.lsa.sin.sin_port = usa.sin.sin_port;
15187 }
15188
15189 if ((ptr = (struct socket *)
15191 (phys_ctx->num_listening_sockets + 1)
15192 * sizeof(phys_ctx->listening_sockets[0]),
15193 phys_ctx))
15194 == NULL) {
15195
15196 mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
15197 closesocket(so.sock);
15198 so.sock = INVALID_SOCKET;
15199 continue;
15200 }
15201
15202 if ((pfd = (struct mg_pollfd *)
15204 (phys_ctx->num_listening_sockets + 1)
15205 * sizeof(phys_ctx->listening_socket_fds[0]),
15206 phys_ctx))
15207 == NULL) {
15208
15209 mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
15210 closesocket(so.sock);
15211 so.sock = INVALID_SOCKET;
15212 mg_free(ptr);
15213 continue;
15214 }
15215
15216 set_close_on_exec(so.sock, NULL, phys_ctx);
15217 phys_ctx->listening_sockets = ptr;
15218 phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
15219 phys_ctx->listening_socket_fds = pfd;
15220 phys_ctx->num_listening_sockets++;
15221 portsOk++;
15222 }
15223
15224 if (portsOk != portsTotal) {
15226 portsOk = 0;
15227 }
15228
15229 return portsOk;
15230}
15231
15232
15233static const char *
15234header_val(const struct mg_connection *conn, const char *header)
15235{
15236 const char *header_value;
15237
15238 if ((header_value = mg_get_header(conn, header)) == NULL) {
15239 return "-";
15240 } else {
15241 return header_value;
15242 }
15243}
15244
15245
15246#if defined(MG_EXTERNAL_FUNCTION_log_access)
15247#include "external_log_access.inl"
15248#elif !defined(NO_FILESYSTEMS)
15249
15250static void
15251log_access(const struct mg_connection *conn)
15252{
15253 const struct mg_request_info *ri;
15254 struct mg_file fi;
15255 char date[64], src_addr[IP_ADDR_STR_LEN];
15256 struct tm *tm;
15257
15258 const char *referer;
15259 const char *user_agent;
15260
15261 char log_buf[4096];
15262
15263 if (!conn || !conn->dom_ctx) {
15264 return;
15265 }
15266
15267 /* Set log message to "empty" */
15268 log_buf[0] = 0;
15269
15270#if defined(USE_LUA)
15271 if (conn->phys_ctx->lua_bg_log_available) {
15272 int ret;
15273 struct mg_context *ctx = conn->phys_ctx;
15274 lua_State *lstate = (lua_State *)ctx->lua_background_state;
15275 pthread_mutex_lock(&ctx->lua_bg_mutex);
15276 /* call "log()" in Lua */
15277 lua_getglobal(lstate, "log");
15278 prepare_lua_request_info_inner(conn, lstate);
15279 push_lua_response_log_data(conn, lstate);
15280
15281 ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
15282 if (ret == 0) {
15283 int t = lua_type(lstate, -1);
15284 if (t == LUA_TBOOLEAN) {
15285 if (lua_toboolean(lstate, -1) == 0) {
15286 /* log() returned false: do not log */
15287 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15288 return;
15289 }
15290 /* log returned true: continue logging */
15291 } else if (t == LUA_TSTRING) {
15292 size_t len;
15293 const char *txt = lua_tolstring(lstate, -1, &len);
15294 if ((len == 0) || (*txt == 0)) {
15295 /* log() returned empty string: do not log */
15296 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15297 return;
15298 }
15299 /* Copy test from Lua into log_buf */
15300 if (len >= sizeof(log_buf)) {
15301 len = sizeof(log_buf) - 1;
15302 }
15303 memcpy(log_buf, txt, len);
15304 log_buf[len] = 0;
15305 }
15306 } else {
15307 lua_cry(conn, ret, lstate, "lua_background_script", "log");
15308 }
15309 pthread_mutex_unlock(&ctx->lua_bg_mutex);
15310 }
15311#endif
15312
15313 if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
15314 if (mg_fopen(conn,
15317 &fi)
15318 == 0) {
15319 fi.access.fp = NULL;
15320 }
15321 } else {
15322 fi.access.fp = NULL;
15323 }
15324
15325 /* Log is written to a file and/or a callback. If both are not set,
15326 * executing the rest of the function is pointless. */
15327 if ((fi.access.fp == NULL)
15328 && (conn->phys_ctx->callbacks.log_access == NULL)) {
15329 return;
15330 }
15331
15332 /* If we did not get a log message from Lua, create it here. */
15333 if (!log_buf[0]) {
15334 tm = localtime(&conn->conn_birth_time);
15335 if (tm != NULL) {
15336 strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
15337 } else {
15338 mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
15339 date[sizeof(date) - 1] = '\0';
15340 }
15341
15342 ri = &conn->request_info;
15343
15344 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
15345 referer = header_val(conn, "Referer");
15346 user_agent = header_val(conn, "User-Agent");
15347
15348 mg_snprintf(conn,
15349 NULL, /* Ignore truncation in access log */
15350 log_buf,
15351 sizeof(log_buf),
15352 "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
15353 " %s %s",
15354 src_addr,
15355 (ri->remote_user == NULL) ? "-" : ri->remote_user,
15356 date,
15357 ri->request_method ? ri->request_method : "-",
15358 ri->request_uri ? ri->request_uri : "-",
15359 ri->query_string ? "?" : "",
15360 ri->query_string ? ri->query_string : "",
15361 ri->http_version,
15362 conn->status_code,
15363 conn->num_bytes_sent,
15364 referer,
15365 user_agent);
15366 }
15367
15368 /* Here we have a log message in log_buf. Call the callback */
15369 if (conn->phys_ctx->callbacks.log_access) {
15370 if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
15371 /* do not log if callack returns non-zero */
15372 if (fi.access.fp) {
15373 mg_fclose(&fi.access);
15374 }
15375 return;
15376 }
15377 }
15378
15379 /* Store in file */
15380 if (fi.access.fp) {
15381 int ok = 1;
15382 flockfile(fi.access.fp);
15383 if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
15384 ok = 0;
15385 }
15386 if (fflush(fi.access.fp) != 0) {
15387 ok = 0;
15388 }
15389 funlockfile(fi.access.fp);
15390 if (mg_fclose(&fi.access) != 0) {
15391 ok = 0;
15392 }
15393 if (!ok) {
15394 mg_cry_internal(conn,
15395 "Error writing log file %s",
15397 }
15398 }
15399}
15400#else
15401#error "Either enable filesystems or provide a custom log_access implementation"
15402#endif /* Externally provided function */
15403
15404
15405/* Verify given socket address against the ACL.
15406 * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
15407 */
15408static int
15409check_acl(struct mg_context *phys_ctx, const union usa *sa)
15410{
15411 int allowed, flag, matched;
15412 struct vec vec;
15413
15414 if (phys_ctx) {
15415 const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
15416
15417 /* If any ACL is set, deny by default */
15418 allowed = (list == NULL) ? '+' : '-';
15419
15420 while ((list = next_option(list, &vec, NULL)) != NULL) {
15421 flag = vec.ptr[0];
15422 matched = -1;
15423 if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
15424 vec.ptr++;
15425 vec.len--;
15426 matched = parse_match_net(&vec, sa, 1);
15427 }
15428 if (matched < 0) {
15429 mg_cry_ctx_internal(phys_ctx,
15430 "%s: subnet must be [+|-]IP-addr[/x]",
15431 __func__);
15432 return -1;
15433 }
15434 if (matched) {
15435 allowed = flag;
15436 }
15437 }
15438
15439 return allowed == '+';
15440 }
15441 return -1;
15442}
15443
15444
15445#if !defined(_WIN32) && !defined(__ZEPHYR__)
15446static int
15448{
15449 int success = 0;
15450
15451 if (phys_ctx) {
15452 /* We are currently running as curr_uid. */
15453 const uid_t curr_uid = getuid();
15454 /* If set, we want to run as run_as_user. */
15455 const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
15456 const struct passwd *to_pw = NULL;
15457
15458 if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
15459 /* run_as_user does not exist on the system. We can't proceed
15460 * further. */
15461 mg_cry_ctx_internal(phys_ctx,
15462 "%s: unknown user [%s]",
15463 __func__,
15464 run_as_user);
15465 } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
15466 /* There was either no request to change user, or we're already
15467 * running as run_as_user. Nothing else to do.
15468 */
15469 success = 1;
15470 } else {
15471 /* Valid change request. */
15472 if (setgid(to_pw->pw_gid) == -1) {
15473 mg_cry_ctx_internal(phys_ctx,
15474 "%s: setgid(%s): %s",
15475 __func__,
15476 run_as_user,
15477 strerror(errno));
15478 } else if (setgroups(0, NULL) == -1) {
15479 mg_cry_ctx_internal(phys_ctx,
15480 "%s: setgroups(): %s",
15481 __func__,
15482 strerror(errno));
15483 } else if (setuid(to_pw->pw_uid) == -1) {
15484 mg_cry_ctx_internal(phys_ctx,
15485 "%s: setuid(%s): %s",
15486 __func__,
15487 run_as_user,
15488 strerror(errno));
15489 } else {
15490 success = 1;
15491 }
15492 }
15493 }
15494
15495 return success;
15496}
15497#endif /* !_WIN32 */
15498
15499
15500static void
15501tls_dtor(void *key)
15502{
15503 struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
15504 /* key == pthread_getspecific(sTlsKey); */
15505
15506 if (tls) {
15507 if (tls->is_master == 2) {
15508 tls->is_master = -3; /* Mark memory as dead */
15509 mg_free(tls);
15510 }
15511 }
15512 pthread_setspecific(sTlsKey, NULL);
15513}
15514
15515
15516#if defined(USE_MBEDTLS)
15517/* Check if SSL is required.
15518 * If so, set up ctx->ssl_ctx pointer. */
15519static int
15520mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
15521{
15522 if (!phys_ctx) {
15523 return 0;
15524 }
15525
15526 if (!dom_ctx) {
15527 dom_ctx = &(phys_ctx->dd);
15528 }
15529
15530 if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
15531 /* No SSL port is set. No need to setup SSL. */
15532 return 1;
15533 }
15534
15535 dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
15536 if (dom_ctx->ssl_ctx == NULL) {
15537 fprintf(stderr, "ssl_ctx malloc failed\n");
15538 return 0;
15539 }
15540
15541 return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
15542 == 0
15543 ? 1
15544 : 0;
15545}
15546
15547#elif !defined(NO_SSL)
15548
15549static int ssl_use_pem_file(struct mg_context *phys_ctx,
15550 struct mg_domain_context *dom_ctx,
15551 const char *pem,
15552 const char *chain);
15553static const char *ssl_error(void);
15554
15555
15556static int
15558{
15559 struct stat cert_buf;
15560 int64_t t = 0;
15561 const char *pem;
15562 const char *chain;
15563 int should_verify_peer;
15564
15565 if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
15566 /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
15567 * refresh_trust still can not work. */
15568 return 0;
15569 }
15570 chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
15571 if (chain == NULL) {
15572 /* pem is not NULL here */
15573 chain = pem;
15574 }
15575 if (*chain == 0) {
15576 chain = NULL;
15577 }
15578
15579 if (stat(pem, &cert_buf) != -1) {
15580 t = (int64_t)cert_buf.st_mtime;
15581 }
15582
15584 if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
15585 conn->dom_ctx->ssl_cert_last_mtime = t;
15586
15587 should_verify_peer = 0;
15588 if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
15590 == 0) {
15591 should_verify_peer = 1;
15593 "optional")
15594 == 0) {
15595 should_verify_peer = 1;
15596 }
15597 }
15598
15599 if (should_verify_peer) {
15600 char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
15601 char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
15602 if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
15603 ca_file,
15604 ca_path)
15605 != 1) {
15608 conn->phys_ctx,
15609 "SSL_CTX_load_verify_locations error: %s "
15610 "ssl_verify_peer requires setting "
15611 "either ssl_ca_path or ssl_ca_file. Is any of them "
15612 "present in "
15613 "the .conf file?",
15614 ssl_error());
15615 return 0;
15616 }
15617 }
15618
15619 if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
15621 return 0;
15622 }
15623 }
15625
15626 return 1;
15627}
15628
15629#if defined(OPENSSL_API_1_1)
15630#else
15631static pthread_mutex_t *ssl_mutexes;
15632#endif /* OPENSSL_API_1_1 */
15633
15634static int
15636 int (*func)(SSL *),
15637 const struct mg_client_options *client_options)
15638{
15639 int ret, err;
15640 int short_trust;
15641 unsigned timeout = 1024;
15642 unsigned i;
15643
15644 if (!conn) {
15645 return 0;
15646 }
15647
15648 short_trust =
15649 (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
15650 && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
15651
15652 if (short_trust) {
15653 int trust_ret = refresh_trust(conn);
15654 if (!trust_ret) {
15655 return trust_ret;
15656 }
15657 }
15658
15660 conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
15662 if (conn->ssl == NULL) {
15663 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15664 OPENSSL_REMOVE_THREAD_STATE();
15665 return 0;
15666 }
15667 SSL_set_app_data(conn->ssl, (char *)conn);
15668
15669 ret = SSL_set_fd(conn->ssl, conn->client.sock);
15670 if (ret != 1) {
15671 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15672 SSL_free(conn->ssl);
15673 conn->ssl = NULL;
15674 OPENSSL_REMOVE_THREAD_STATE();
15675 return 0;
15676 }
15677
15678 if (client_options) {
15679 if (client_options->host_name) {
15680 SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
15681 }
15682 }
15683
15684 /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
15685 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
15686 /* NOTE: The loop below acts as a back-off, so we can end
15687 * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
15688 int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
15689 if (to >= 0) {
15690 timeout = (unsigned)to;
15691 }
15692 }
15693
15694 /* SSL functions may fail and require to be called again:
15695 * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
15696 * Here "func" could be SSL_connect or SSL_accept. */
15697 for (i = 0; i <= timeout; i += 50) {
15698 ERR_clear_error();
15699 /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
15700 ret = func(conn->ssl);
15701 if (ret != 1) {
15702 err = SSL_get_error(conn->ssl, ret);
15703 if ((err == SSL_ERROR_WANT_CONNECT)
15704 || (err == SSL_ERROR_WANT_ACCEPT)
15705 || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
15706 || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
15707 if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
15708 /* Don't wait if the server is going to be stopped. */
15709 break;
15710 }
15711 if (err == SSL_ERROR_WANT_X509_LOOKUP) {
15712 /* Simply retry the function call. */
15713 mg_sleep(50);
15714 } else {
15715 /* Need to retry the function call "later".
15716 * See https://linux.die.net/man/3/ssl_get_error
15717 * This is typical for non-blocking sockets. */
15718 struct mg_pollfd pfd;
15719 int pollres;
15720 pfd.fd = conn->client.sock;
15721 pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
15722 || (err == SSL_ERROR_WANT_WRITE))
15723 ? POLLOUT
15724 : POLLIN;
15725 pollres =
15726 mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
15727 if (pollres < 0) {
15728 /* Break if error occured (-1)
15729 * or server shutdown (-2) */
15730 break;
15731 }
15732 }
15733
15734 } else if (err == SSL_ERROR_SYSCALL) {
15735 /* This is an IO error. Look at errno. */
15736 mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
15737 break;
15738
15739 } else {
15740 /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
15741 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15742 break;
15743 }
15744
15745 } else {
15746 /* success */
15747 break;
15748 }
15749 }
15750 ERR_clear_error();
15751
15752 if (ret != 1) {
15753 SSL_free(conn->ssl);
15754 conn->ssl = NULL;
15755 OPENSSL_REMOVE_THREAD_STATE();
15756 return 0;
15757 }
15758
15759 return 1;
15760}
15761
15762
15763/* Return OpenSSL error message (from CRYPTO lib) */
15764static const char *
15766{
15767 unsigned long err;
15768 err = ERR_get_error();
15769 return ((err == 0) ? "" : ERR_error_string(err, NULL));
15770}
15771
15772
15773static int
15774hexdump2string(void *mem, int memlen, char *buf, int buflen)
15775{
15776 int i;
15777 const char hexdigit[] = "0123456789abcdef";
15778
15779 if ((memlen <= 0) || (buflen <= 0)) {
15780 return 0;
15781 }
15782 if (buflen < (3 * memlen)) {
15783 return 0;
15784 }
15785
15786 for (i = 0; i < memlen; i++) {
15787 if (i > 0) {
15788 buf[3 * i - 1] = ' ';
15789 }
15790 buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
15791 buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
15792 }
15793 buf[3 * memlen - 1] = 0;
15794
15795 return 1;
15796}
15797
15798
15799static int
15801 struct mg_client_cert *client_cert)
15802{
15803 X509 *cert = SSL_get_peer_certificate(conn->ssl);
15804 if (cert) {
15805 char str_buf[1024];
15806 unsigned char buf[256];
15807 char *str_serial = NULL;
15808 unsigned int ulen;
15809 int ilen;
15810 unsigned char *tmp_buf;
15811 unsigned char *tmp_p;
15812
15813 /* Handle to algorithm used for fingerprint */
15814 const EVP_MD *digest = EVP_get_digestbyname("sha1");
15815
15816 /* Get Subject and issuer */
15817 X509_NAME *subj = X509_get_subject_name(cert);
15818 X509_NAME *iss = X509_get_issuer_name(cert);
15819
15820 /* Get serial number */
15821 ASN1_INTEGER *serial = X509_get_serialNumber(cert);
15822
15823 /* Translate serial number to a hex string */
15824 BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
15825 if (serial_bn) {
15826 str_serial = BN_bn2hex(serial_bn);
15827 BN_free(serial_bn);
15828 }
15829 client_cert->serial =
15830 str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
15831
15832 /* Translate subject and issuer to a string */
15833 (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
15834 client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
15835 (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
15836 client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
15837
15838 /* Calculate SHA1 fingerprint and store as a hex string */
15839 ulen = 0;
15840
15841 /* ASN1_digest is deprecated. Do the calculation manually,
15842 * using EVP_Digest. */
15843 ilen = i2d_X509(cert, NULL);
15844 tmp_buf = (ilen > 0)
15845 ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
15846 conn->phys_ctx)
15847 : NULL;
15848 if (tmp_buf) {
15849 tmp_p = tmp_buf;
15850 (void)i2d_X509(cert, &tmp_p);
15851 if (!EVP_Digest(
15852 tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
15853 ulen = 0;
15854 }
15855 mg_free(tmp_buf);
15856 }
15857
15858 if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
15859 *str_buf = 0;
15860 }
15861 client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
15862
15863 client_cert->peer_cert = (void *)cert;
15864
15865 /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
15866 * see https://linux.die.net/man/3/bn_bn2hex */
15867 OPENSSL_free(str_serial);
15868 return 1;
15869 }
15870 return 0;
15871}
15872
15873
15874#if defined(OPENSSL_API_1_1)
15875#else
15876static void
15877ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
15878{
15879 (void)line;
15880 (void)file;
15881
15882 if (mode & 1) {
15883 /* 1 is CRYPTO_LOCK */
15884 (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
15885 } else {
15886 (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
15887 }
15888}
15889#endif /* OPENSSL_API_1_1 */
15890
15891
15892#if !defined(NO_SSL_DL)
15893/* Load a DLL/Shared Object with a TLS/SSL implementation. */
15894static void *
15895load_tls_dll(char *ebuf,
15896 size_t ebuf_len,
15897 const char *dll_name,
15898 struct ssl_func *sw,
15899 int *feature_missing)
15900{
15901 union {
15902 void *p;
15903 void (*fp)(void);
15904 } u;
15905 void *dll_handle;
15906 struct ssl_func *fp;
15907 int ok;
15908 int truncated = 0;
15909
15910 if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
15911 mg_snprintf(NULL,
15912 NULL, /* No truncation check for ebuf */
15913 ebuf,
15914 ebuf_len,
15915 "%s: cannot load %s",
15916 __func__,
15917 dll_name);
15918 return NULL;
15919 }
15920
15921 ok = 1;
15922 for (fp = sw; fp->name != NULL; fp++) {
15923#if defined(_WIN32)
15924 /* GetProcAddress() returns pointer to function */
15925 u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
15926#else
15927 /* dlsym() on UNIX returns void *. ISO C forbids casts of data
15928 * pointers to function pointers. We need to use a union to make a
15929 * cast. */
15930 u.p = dlsym(dll_handle, fp->name);
15931#endif /* _WIN32 */
15932
15933 /* Set pointer (might be NULL) */
15934 fp->ptr = u.fp;
15935
15936 if (u.fp == NULL) {
15937 DEBUG_TRACE("Missing function: %s\n", fp->name);
15938 if (feature_missing) {
15939 feature_missing[fp->required]++;
15940 }
15941 if (fp->required == TLS_Mandatory) {
15942 /* Mandatory function is missing */
15943 if (ok) {
15944 /* This is the first missing function.
15945 * Create a new error message. */
15946 mg_snprintf(NULL,
15947 &truncated,
15948 ebuf,
15949 ebuf_len,
15950 "%s: %s: cannot find %s",
15951 __func__,
15952 dll_name,
15953 fp->name);
15954 ok = 0;
15955 } else {
15956 /* This is yet anothermissing function.
15957 * Append existing error message. */
15958 size_t cur_len = strlen(ebuf);
15959 if (!truncated && ((ebuf_len - cur_len) > 3)) {
15960 mg_snprintf(NULL,
15961 &truncated,
15962 ebuf + cur_len,
15963 ebuf_len - cur_len - 3,
15964 ", %s",
15965 fp->name);
15966 if (truncated) {
15967 /* If truncated, add "..." */
15968 strcat(ebuf, "...");
15969 }
15970 }
15971 }
15972 }
15973 }
15974 }
15975
15976 if (!ok) {
15977 (void)dlclose(dll_handle);
15978 return NULL;
15979 }
15980
15981 return dll_handle;
15982}
15983
15984
15985static void *ssllib_dll_handle; /* Store the ssl library handle. */
15986static void *cryptolib_dll_handle; /* Store the crypto library handle. */
15987
15988#endif /* NO_SSL_DL */
15989
15990
15991#if defined(SSL_ALREADY_INITIALIZED)
15992static volatile ptrdiff_t cryptolib_users =
15993 1; /* Reference counter for crypto library. */
15994#else
15995static volatile ptrdiff_t cryptolib_users =
15996 0; /* Reference counter for crypto library. */
15997#endif
15998
15999
16000static int
16001initialize_openssl(char *ebuf, size_t ebuf_len)
16002{
16003#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16004 int i, num_locks;
16005 size_t size;
16006#endif
16007
16008 if (ebuf_len > 0) {
16009 ebuf[0] = 0;
16010 }
16011
16012#if !defined(NO_SSL_DL)
16013 if (!cryptolib_dll_handle) {
16014 memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
16016 ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
16017 if (!cryptolib_dll_handle) {
16018 mg_snprintf(NULL,
16019 NULL, /* No truncation check for ebuf */
16020 ebuf,
16021 ebuf_len,
16022 "%s: error loading library %s",
16023 __func__,
16024 CRYPTO_LIB);
16025 DEBUG_TRACE("%s", ebuf);
16026 return 0;
16027 }
16028 }
16029#endif /* NO_SSL_DL */
16030
16031 if (mg_atomic_inc(&cryptolib_users) > 1) {
16032 return 1;
16033 }
16034
16035#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16036 /* Initialize locking callbacks, needed for thread safety.
16037 * http://www.openssl.org/support/faq.html#PROG1
16038 */
16039 num_locks = CRYPTO_num_locks();
16040 if (num_locks < 0) {
16041 num_locks = 0;
16042 }
16043 size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
16044
16045 /* allocate mutex array, if required */
16046 if (num_locks == 0) {
16047 /* No mutex array required */
16048 ssl_mutexes = NULL;
16049 } else {
16050 /* Mutex array required - allocate it */
16051 ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
16052
16053 /* Check OOM */
16054 if (ssl_mutexes == NULL) {
16055 mg_snprintf(NULL,
16056 NULL, /* No truncation check for ebuf */
16057 ebuf,
16058 ebuf_len,
16059 "%s: cannot allocate mutexes: %s",
16060 __func__,
16061 ssl_error());
16062 DEBUG_TRACE("%s", ebuf);
16063 return 0;
16064 }
16065
16066 /* initialize mutex array */
16067 for (i = 0; i < num_locks; i++) {
16068 if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
16069 mg_snprintf(NULL,
16070 NULL, /* No truncation check for ebuf */
16071 ebuf,
16072 ebuf_len,
16073 "%s: error initializing mutex %i of %i",
16074 __func__,
16075 i,
16076 num_locks);
16077 DEBUG_TRACE("%s", ebuf);
16079 return 0;
16080 }
16081 }
16082 }
16083
16084 CRYPTO_set_locking_callback(&ssl_locking_callback);
16085 CRYPTO_set_id_callback(&mg_current_thread_id);
16086#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16087
16088#if !defined(NO_SSL_DL)
16089 if (!ssllib_dll_handle) {
16091 load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
16092 if (!ssllib_dll_handle) {
16093#if !defined(OPENSSL_API_1_1)
16095#endif
16096 DEBUG_TRACE("%s", ebuf);
16097 return 0;
16098 }
16099 }
16100#endif /* NO_SSL_DL */
16101
16102#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16103 && !defined(NO_SSL_DL)
16104 /* Initialize SSL library */
16105 OPENSSL_init_ssl(0, NULL);
16106 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
16108 NULL);
16109#else
16110 /* Initialize SSL library */
16111 SSL_library_init();
16112 SSL_load_error_strings();
16113#endif
16114
16115 return 1;
16116}
16117
16118
16119static int
16121 struct mg_domain_context *dom_ctx,
16122 const char *pem,
16123 const char *chain)
16124{
16125 if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
16126 mg_cry_ctx_internal(phys_ctx,
16127 "%s: cannot open certificate file %s: %s",
16128 __func__,
16129 pem,
16130 ssl_error());
16131 return 0;
16132 }
16133
16134 /* could use SSL_CTX_set_default_passwd_cb_userdata */
16135 if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
16136 mg_cry_ctx_internal(phys_ctx,
16137 "%s: cannot open private key file %s: %s",
16138 __func__,
16139 pem,
16140 ssl_error());
16141 return 0;
16142 }
16143
16144 if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
16145 mg_cry_ctx_internal(phys_ctx,
16146 "%s: certificate and private key do not match: %s",
16147 __func__,
16148 pem);
16149 return 0;
16150 }
16151
16152 /* In contrast to OpenSSL, wolfSSL does not support certificate
16153 * chain files that contain private keys and certificates in
16154 * SSL_CTX_use_certificate_chain_file.
16155 * The CivetWeb-Server used pem-Files that contained both information.
16156 * In order to make wolfSSL work, it is split in two files.
16157 * One file that contains key and certificate used by the server and
16158 * an optional chain file for the ssl stack.
16159 */
16160 if (chain) {
16161 if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
16162 mg_cry_ctx_internal(phys_ctx,
16163 "%s: cannot use certificate chain file %s: %s",
16164 __func__,
16165 chain,
16166 ssl_error());
16167 return 0;
16168 }
16169 }
16170 return 1;
16171}
16172
16173
16174#if defined(OPENSSL_API_1_1)
16175static unsigned long
16176ssl_get_protocol(int version_id)
16177{
16178 long unsigned ret = (long unsigned)SSL_OP_ALL;
16179 if (version_id > 0)
16180 ret |= SSL_OP_NO_SSLv2;
16181 if (version_id > 1)
16182 ret |= SSL_OP_NO_SSLv3;
16183 if (version_id > 2)
16184 ret |= SSL_OP_NO_TLSv1;
16185 if (version_id > 3)
16186 ret |= SSL_OP_NO_TLSv1_1;
16187 if (version_id > 4)
16188 ret |= SSL_OP_NO_TLSv1_2;
16189#if defined(SSL_OP_NO_TLSv1_3)
16190 if (version_id > 5)
16191 ret |= SSL_OP_NO_TLSv1_3;
16192#endif
16193 return ret;
16194}
16195#else
16196static long
16197ssl_get_protocol(int version_id)
16198{
16199 unsigned long ret = (unsigned long)SSL_OP_ALL;
16200 if (version_id > 0)
16201 ret |= SSL_OP_NO_SSLv2;
16202 if (version_id > 1)
16203 ret |= SSL_OP_NO_SSLv3;
16204 if (version_id > 2)
16205 ret |= SSL_OP_NO_TLSv1;
16206 if (version_id > 3)
16207 ret |= SSL_OP_NO_TLSv1_1;
16208 if (version_id > 4)
16209 ret |= SSL_OP_NO_TLSv1_2;
16210#if defined(SSL_OP_NO_TLSv1_3)
16211 if (version_id > 5)
16212 ret |= SSL_OP_NO_TLSv1_3;
16213#endif
16214 return (long)ret;
16215}
16216#endif /* OPENSSL_API_1_1 */
16217
16218
16219/* SSL callback documentation:
16220 * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
16221 * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
16222 * https://linux.die.net/man/3/ssl_set_info_callback */
16223/* Note: There is no "const" for the first argument in the documentation
16224 * examples, however some (maybe most, but not all) headers of OpenSSL
16225 * versions / OpenSSL compatibility layers have it. Having a different
16226 * definition will cause a warning in C and an error in C++. Use "const SSL
16227 * *", while automatical conversion from "SSL *" works for all compilers,
16228 * but not other way around */
16229static void
16230ssl_info_callback(const SSL *ssl, int what, int ret)
16231{
16232 (void)ret;
16233
16235 SSL_get_app_data(ssl);
16236 }
16238 /* TODO: check for openSSL 1.1 */
16239 //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
16240 // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
16241 }
16242}
16243
16244
16245static int
16246ssl_servername_callback(SSL *ssl, int *ad, void *arg)
16247{
16248#if defined(GCC_DIAGNOSTIC)
16249#pragma GCC diagnostic push
16250#pragma GCC diagnostic ignored "-Wcast-align"
16251#endif /* defined(GCC_DIAGNOSTIC) */
16252
16253 /* We used an aligned pointer in SSL_set_app_data */
16254 struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
16255
16256#if defined(GCC_DIAGNOSTIC)
16257#pragma GCC diagnostic pop
16258#endif /* defined(GCC_DIAGNOSTIC) */
16259
16260 const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
16261
16262 (void)ad;
16263 (void)arg;
16264
16265 if ((conn == NULL) || (conn->phys_ctx == NULL)) {
16266 DEBUG_ASSERT(0);
16267 return SSL_TLSEXT_ERR_NOACK;
16268 }
16269 conn->dom_ctx = &(conn->phys_ctx->dd);
16270
16271 /* Old clients (Win XP) will not support SNI. Then, there
16272 * is no server name available in the request - we can
16273 * only work with the default certificate.
16274 * Multiple HTTPS hosts on one IP+port are only possible
16275 * with a certificate containing all alternative names.
16276 */
16277 if ((servername == NULL) || (*servername == 0)) {
16278 DEBUG_TRACE("%s", "SSL connection not supporting SNI");
16280 SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
16282 return SSL_TLSEXT_ERR_NOACK;
16283 }
16284
16285 DEBUG_TRACE("TLS connection to host %s", servername);
16286
16287 while (conn->dom_ctx) {
16288 if (!mg_strcasecmp(servername,
16290 /* Found matching domain */
16291 DEBUG_TRACE("TLS domain %s found",
16293 break;
16294 }
16296 conn->dom_ctx = conn->dom_ctx->next;
16298 }
16299
16300 if (conn->dom_ctx == NULL) {
16301 /* Default domain */
16302 DEBUG_TRACE("TLS default domain %s used",
16304 conn->dom_ctx = &(conn->phys_ctx->dd);
16305 }
16307 SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
16309 return SSL_TLSEXT_ERR_OK;
16310}
16311
16312
16313#if defined(USE_ALPN)
16314static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
16315static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
16316 alpn_proto_list + 3 + 8,
16317 NULL};
16318#if defined(USE_HTTP2)
16319static const char *alpn_proto_order_http2[] = {alpn_proto_list,
16320 alpn_proto_list + 3,
16321 alpn_proto_list + 3 + 8,
16322 NULL};
16323#endif
16324
16325static int
16326alpn_select_cb(SSL *ssl,
16327 const unsigned char **out,
16328 unsigned char *outlen,
16329 const unsigned char *in,
16330 unsigned int inlen,
16331 void *arg)
16332{
16333 struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
16334 unsigned int i, j, enable_http2 = 0;
16335 const char **alpn_proto_order = alpn_proto_order_http1;
16336
16337 struct mg_workerTLS *tls =
16338 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
16339
16340 (void)ssl;
16341
16342 if (tls == NULL) {
16343 /* Need to store protocol in Thread Local Storage */
16344 /* If there is no Thread Local Storage, don't use ALPN */
16345 return SSL_TLSEXT_ERR_NOACK;
16346 }
16347
16348#if defined(USE_HTTP2)
16349 enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
16350 if (enable_http2) {
16351 alpn_proto_order = alpn_proto_order_http2;
16352 }
16353#endif
16354
16355 for (j = 0; alpn_proto_order[j] != NULL; j++) {
16356 /* check all accepted protocols in this order */
16357 const char *alpn_proto = alpn_proto_order[j];
16358 /* search input for matching protocol */
16359 for (i = 0; i < inlen; i++) {
16360 if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
16361 *out = in + i + 1;
16362 *outlen = in[i];
16363 tls->alpn_proto = alpn_proto;
16364 return SSL_TLSEXT_ERR_OK;
16365 }
16366 }
16367 }
16368
16369 /* Nothing found */
16370 return SSL_TLSEXT_ERR_NOACK;
16371}
16372
16373
16374static int
16375next_protos_advertised_cb(SSL *ssl,
16376 const unsigned char **data,
16377 unsigned int *len,
16378 void *arg)
16379{
16380 struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
16381 *data = (const unsigned char *)alpn_proto_list;
16382 *len = (unsigned int)strlen((const char *)data);
16383
16384 (void)ssl;
16385 (void)dom_ctx;
16386
16387 return SSL_TLSEXT_ERR_OK;
16388}
16389
16390
16391static int
16392init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16393{
16394 unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
16395 int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
16396 (const unsigned char *)alpn_proto_list,
16397 alpn_len);
16398 if (ret != 0) {
16399 mg_cry_ctx_internal(phys_ctx,
16400 "SSL_CTX_set_alpn_protos error: %s",
16401 ssl_error());
16402 }
16403
16404 SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
16405 alpn_select_cb,
16406 (void *)dom_ctx);
16407
16408 SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
16409 next_protos_advertised_cb,
16410 (void *)dom_ctx);
16411
16412 return ret;
16413}
16414#endif
16415
16416
16417/* Setup SSL CTX as required by CivetWeb */
16418static int
16420 struct mg_domain_context *dom_ctx,
16421 const char *pem,
16422 const char *chain)
16423{
16424 int callback_ret;
16425 int should_verify_peer;
16426 int peer_certificate_optional;
16427 const char *ca_path;
16428 const char *ca_file;
16429 int use_default_verify_paths;
16430 int verify_depth;
16431 struct timespec now_mt;
16432 md5_byte_t ssl_context_id[16];
16433 md5_state_t md5state;
16434 int protocol_ver;
16435 int ssl_cache_timeout;
16436
16437#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
16438 && !defined(NO_SSL_DL)
16439 if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
16440 mg_cry_ctx_internal(phys_ctx,
16441 "SSL_CTX_new (server) error: %s",
16442 ssl_error());
16443 return 0;
16444 }
16445#else
16446 if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
16447 mg_cry_ctx_internal(phys_ctx,
16448 "SSL_CTX_new (server) error: %s",
16449 ssl_error());
16450 return 0;
16451 }
16452#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16453
16454#if defined(SSL_OP_NO_TLSv1_3)
16455 SSL_CTX_clear_options(dom_ctx->ssl_ctx,
16459#else
16460 SSL_CTX_clear_options(dom_ctx->ssl_ctx,
16463#endif
16464
16465 protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
16466 SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
16467 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
16468 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
16469 SSL_CTX_set_options(dom_ctx->ssl_ctx,
16471 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
16472
16473#if defined(SSL_OP_NO_RENEGOTIATION)
16474 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
16475#endif
16476
16477#if !defined(NO_SSL_DL)
16478 SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
16479#endif /* NO_SSL_DL */
16480
16481 /* In SSL documentation examples callback defined without const
16482 * specifier 'void (*)(SSL *, int, int)' See:
16483 * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
16484 * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
16485 * But in the source code const SSL is used:
16486 * 'void (*)(const SSL *, int, int)' See:
16487 * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
16488 * Problem about wrong documentation described, but not resolved:
16489 * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
16490 * Wrong const cast ignored on C or can be suppressed by compiler flags.
16491 * But when compiled with modern C++ compiler, correct const should be
16492 * provided
16493 */
16494 SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
16495
16496 SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
16498
16499 /* If a callback has been specified, call it. */
16500 callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
16501 ? 0
16502 : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
16503 phys_ctx->user_data));
16504
16505 /* If callback returns 0, civetweb sets up the SSL certificate.
16506 * If it returns 1, civetweb assumes the calback already did this.
16507 * If it returns -1, initializing ssl fails. */
16508 if (callback_ret < 0) {
16509 mg_cry_ctx_internal(phys_ctx,
16510 "SSL callback returned error: %i",
16511 callback_ret);
16512 return 0;
16513 }
16514 if (callback_ret > 0) {
16515 /* Callback did everything. */
16516 return 1;
16517 }
16518
16519 /* If a domain callback has been specified, call it. */
16520 callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
16521 ? 0
16522 : (phys_ctx->callbacks.init_ssl_domain(
16523 dom_ctx->config[AUTHENTICATION_DOMAIN],
16524 dom_ctx->ssl_ctx,
16525 phys_ctx->user_data));
16526
16527 /* If domain callback returns 0, civetweb sets up the SSL certificate.
16528 * If it returns 1, civetweb assumes the calback already did this.
16529 * If it returns -1, initializing ssl fails. */
16530 if (callback_ret < 0) {
16531 mg_cry_ctx_internal(phys_ctx,
16532 "Domain SSL callback returned error: %i",
16533 callback_ret);
16534 return 0;
16535 }
16536 if (callback_ret > 0) {
16537 /* Domain callback did everything. */
16538 return 1;
16539 }
16540
16541 /* Use some combination of start time, domain and port as a SSL
16542 * context ID. This should be unique on the current machine. */
16543 md5_init(&md5state);
16544 clock_gettime(CLOCK_MONOTONIC, &now_mt);
16545 md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
16546 md5_append(&md5state,
16547 (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
16548 strlen(phys_ctx->dd.config[LISTENING_PORTS]));
16549 md5_append(&md5state,
16550 (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
16551 strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
16552 md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
16553 md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
16554 md5_finish(&md5state, ssl_context_id);
16555
16556 SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
16557 (unsigned char *)ssl_context_id,
16558 sizeof(ssl_context_id));
16559
16560 if (pem != NULL) {
16561 if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
16562 return 0;
16563 }
16564 }
16565
16566 /* Should we support client certificates? */
16567 /* Default is "no". */
16568 should_verify_peer = 0;
16569 peer_certificate_optional = 0;
16570 if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
16571 if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
16572 /* Yes, they are mandatory */
16573 should_verify_peer = 1;
16574 } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
16575 "optional")
16576 == 0) {
16577 /* Yes, they are optional */
16578 should_verify_peer = 1;
16579 peer_certificate_optional = 1;
16580 }
16581 }
16582
16583 use_default_verify_paths =
16584 (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
16585 && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
16586 == 0);
16587
16588 if (should_verify_peer) {
16589 ca_path = dom_ctx->config[SSL_CA_PATH];
16590 ca_file = dom_ctx->config[SSL_CA_FILE];
16591 if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
16592 != 1) {
16593 mg_cry_ctx_internal(phys_ctx,
16594 "SSL_CTX_load_verify_locations error: %s "
16595 "ssl_verify_peer requires setting "
16596 "either ssl_ca_path or ssl_ca_file. "
16597 "Is any of them present in the "
16598 ".conf file?",
16599 ssl_error());
16600 return 0;
16601 }
16602
16603 if (peer_certificate_optional) {
16604 SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
16605 } else {
16606 SSL_CTX_set_verify(dom_ctx->ssl_ctx,
16609 NULL);
16610 }
16611
16612 if (use_default_verify_paths
16613 && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
16614 mg_cry_ctx_internal(phys_ctx,
16615 "SSL_CTX_set_default_verify_paths error: %s",
16616 ssl_error());
16617 return 0;
16618 }
16619
16620 if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
16621 verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
16622 SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
16623 }
16624 }
16625
16626 if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
16627 if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
16628 dom_ctx->config[SSL_CIPHER_LIST])
16629 != 1) {
16630 mg_cry_ctx_internal(phys_ctx,
16631 "SSL_CTX_set_cipher_list error: %s",
16632 ssl_error());
16633 }
16634 }
16635
16636 /* SSL session caching */
16637 ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
16638 ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
16639 : 0);
16640 if (ssl_cache_timeout > 0) {
16641 SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
16642 /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
16643 * default */
16644 SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
16645 }
16646
16647#if defined(USE_ALPN)
16648 /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
16649#if !defined(NO_SSL_DL)
16651#endif
16652 {
16653 init_alpn(phys_ctx, dom_ctx);
16654 }
16655#endif
16656
16657 return 1;
16658}
16659
16660
16661/* Check if SSL is required.
16662 * If so, dynamically load SSL library
16663 * and set up ctx->ssl_ctx pointer. */
16664static int
16665init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16666{
16667 void *ssl_ctx = 0;
16668 int callback_ret;
16669 const char *pem;
16670 const char *chain;
16671 char ebuf[128];
16672
16673 if (!phys_ctx) {
16674 return 0;
16675 }
16676
16677 if (!dom_ctx) {
16678 dom_ctx = &(phys_ctx->dd);
16679 }
16680
16681 if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
16682 /* No SSL port is set. No need to setup SSL. */
16683 return 1;
16684 }
16685
16686 /* Check for external SSL_CTX */
16687 callback_ret =
16688 (phys_ctx->callbacks.external_ssl_ctx == NULL)
16689 ? 0
16690 : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
16691 phys_ctx->user_data));
16692
16693 if (callback_ret < 0) {
16694 /* Callback exists and returns <0: Initializing failed. */
16695 mg_cry_ctx_internal(phys_ctx,
16696 "external_ssl_ctx callback returned error: %i",
16697 callback_ret);
16698 return 0;
16699 } else if (callback_ret > 0) {
16700 /* Callback exists and returns >0: Initializing complete,
16701 * civetweb should not modify the SSL context. */
16702 dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
16703 if (!initialize_openssl(ebuf, sizeof(ebuf))) {
16704 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16705 return 0;
16706 }
16707 return 1;
16708 }
16709 /* If the callback does not exist or return 0, civetweb must initialize
16710 * the SSL context. Handle "domain" callback next. */
16711
16712 /* Check for external domain SSL_CTX callback. */
16713 callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
16714 ? 0
16716 dom_ctx->config[AUTHENTICATION_DOMAIN],
16717 &ssl_ctx,
16718 phys_ctx->user_data));
16719
16720 if (callback_ret < 0) {
16721 /* Callback < 0: Error. Abort init. */
16723 phys_ctx,
16724 "external_ssl_ctx_domain callback returned error: %i",
16725 callback_ret);
16726 return 0;
16727 } else if (callback_ret > 0) {
16728 /* Callback > 0: Consider init done. */
16729 dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
16730 if (!initialize_openssl(ebuf, sizeof(ebuf))) {
16731 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16732 return 0;
16733 }
16734 return 1;
16735 }
16736 /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
16737 * 0, CivetWeb should continue initializing SSL */
16738
16739 /* If PEM file is not specified and the init_ssl callbacks
16740 * are not specified, setup will fail. */
16741 if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
16742 && (phys_ctx->callbacks.init_ssl == NULL)
16743 && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
16744 /* No certificate and no init_ssl callbacks:
16745 * Essential data to set up TLS is missing.
16746 */
16747 mg_cry_ctx_internal(phys_ctx,
16748 "Initializing SSL failed: -%s is not set",
16750 return 0;
16751 }
16752
16753 /* If a certificate chain is configured, use it. */
16754 chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
16755 if (chain == NULL) {
16756 /* Default: certificate chain in PEM file */
16757 chain = pem;
16758 }
16759 if ((chain != NULL) && (*chain == 0)) {
16760 /* If the chain is an empty string, don't use it. */
16761 chain = NULL;
16762 }
16763
16764 if (!initialize_openssl(ebuf, sizeof(ebuf))) {
16765 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16766 return 0;
16767 }
16768
16769 return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
16770}
16771
16772
16773static void
16775{
16776#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
16777
16778 if (mg_atomic_dec(&cryptolib_users) == 0) {
16779
16780 /* Shutdown according to
16781 * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
16782 * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
16783 */
16784 CONF_modules_unload(1);
16785#else
16786 int i;
16787
16788 if (mg_atomic_dec(&cryptolib_users) == 0) {
16789
16790 /* Shutdown according to
16791 * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
16792 * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
16793 */
16794 CRYPTO_set_locking_callback(NULL);
16795 CRYPTO_set_id_callback(NULL);
16796 ENGINE_cleanup();
16797 CONF_modules_unload(1);
16798 ERR_free_strings();
16799 EVP_cleanup();
16800 CRYPTO_cleanup_all_ex_data();
16801 OPENSSL_REMOVE_THREAD_STATE();
16802
16803 for (i = 0; i < CRYPTO_num_locks(); i++) {
16804 pthread_mutex_destroy(&ssl_mutexes[i]);
16805 }
16807 ssl_mutexes = NULL;
16808#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16809 }
16810}
16811#endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
16812
16813
16814#if !defined(NO_FILESYSTEMS)
16815static int
16816set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16817{
16818 if (phys_ctx) {
16820 const char *path;
16821 struct mg_connection fc;
16822 if (!dom_ctx) {
16823 dom_ctx = &(phys_ctx->dd);
16824 }
16826 if ((path != NULL)
16827 && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
16829 "Cannot open %s: %s",
16830 path,
16831 strerror(ERRNO));
16832 return 0;
16833 }
16834 return 1;
16835 }
16836 return 0;
16837}
16838#endif /* NO_FILESYSTEMS */
16839
16840
16841static int
16843{
16844 union usa sa;
16845 memset(&sa, 0, sizeof(sa));
16846#if defined(USE_IPV6)
16847 sa.sin6.sin6_family = AF_INET6;
16848#else
16849 sa.sin.sin_family = AF_INET;
16850#endif
16851 return check_acl(phys_ctx, &sa) != -1;
16852}
16853
16854
16855static void
16857{
16858 if (!conn) {
16859 return;
16860 }
16861
16862 conn->num_bytes_sent = conn->consumed_content = 0;
16863
16864 conn->path_info = NULL;
16865 conn->status_code = -1;
16866 conn->content_len = -1;
16867 conn->is_chunked = 0;
16868 conn->must_close = 0;
16869 conn->request_len = 0;
16870 conn->request_state = 0;
16871 conn->throttle = 0;
16872 conn->accept_gzip = 0;
16873
16877 conn->response_info.status_text = NULL;
16878 conn->response_info.status_code = 0;
16879
16880 conn->request_info.remote_user = NULL;
16881 conn->request_info.request_method = NULL;
16882 conn->request_info.request_uri = NULL;
16883
16884 /* Free cleaned local URI (if any) */
16885 if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
16886 mg_free((void *)conn->request_info.local_uri);
16887 conn->request_info.local_uri = NULL;
16888 }
16889 conn->request_info.local_uri = NULL;
16890
16891#if defined(USE_SERVER_STATS)
16892 conn->processing_time = 0;
16893#endif
16894}
16895
16896
16897static int
16898set_tcp_nodelay(const struct socket *so, int nodelay_on)
16899{
16900 if ((so->lsa.sa.sa_family == AF_INET)
16901 || (so->lsa.sa.sa_family == AF_INET6)) {
16902 /* Only for TCP sockets */
16903 if (setsockopt(so->sock,
16904 IPPROTO_TCP,
16905 TCP_NODELAY,
16906 (SOCK_OPT_TYPE)&nodelay_on,
16907 sizeof(nodelay_on))
16908 != 0) {
16909 /* Error */
16910 return 1;
16911 }
16912 }
16913 /* OK */
16914 return 0;
16915}
16916
16917
16918#if !defined(__ZEPHYR__)
16919static void
16921{
16922#if defined(_WIN32)
16923 char buf[MG_BUF_LEN];
16924 int n;
16925#endif
16926 struct linger linger;
16927 int error_code = 0;
16928 int linger_timeout = -2;
16929 socklen_t opt_len = sizeof(error_code);
16930
16931 if (!conn) {
16932 return;
16933 }
16934
16935 /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
16936 * "Note that enabling a nonzero timeout on a nonblocking socket
16937 * is not recommended.", so set it to blocking now */
16939
16940 /* Send FIN to the client */
16941 shutdown(conn->client.sock, SHUTDOWN_WR);
16942
16943
16944#if defined(_WIN32)
16945 /* Read and discard pending incoming data. If we do not do that and
16946 * close
16947 * the socket, the data in the send buffer may be discarded. This
16948 * behaviour is seen on Windows, when client keeps sending data
16949 * when server decides to close the connection; then when client
16950 * does recv() it gets no data back. */
16951 do {
16952 n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
16953 } while (n > 0);
16954#endif
16955
16956 if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
16957 linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
16958 }
16959
16960 /* Set linger option according to configuration */
16961 if (linger_timeout >= 0) {
16962 /* Set linger option to avoid socket hanging out after close. This
16963 * prevent ephemeral port exhaust problem under high QPS. */
16964 linger.l_onoff = 1;
16965
16966#if defined(_MSC_VER)
16967#pragma warning(push)
16968#pragma warning(disable : 4244)
16969#endif
16970#if defined(GCC_DIAGNOSTIC)
16971#pragma GCC diagnostic push
16972#pragma GCC diagnostic ignored "-Wconversion"
16973#endif
16974 /* Data type of linger structure elements may differ,
16975 * so we don't know what cast we need here.
16976 * Disable type conversion warnings. */
16977
16978 linger.l_linger = (linger_timeout + 999) / 1000;
16979
16980#if defined(GCC_DIAGNOSTIC)
16981#pragma GCC diagnostic pop
16982#endif
16983#if defined(_MSC_VER)
16984#pragma warning(pop)
16985#endif
16986
16987 } else {
16988 linger.l_onoff = 0;
16989 linger.l_linger = 0;
16990 }
16991
16992 if (linger_timeout < -1) {
16993 /* Default: don't configure any linger */
16994 } else if (getsockopt(conn->client.sock,
16995 SOL_SOCKET,
16996 SO_ERROR,
16997#if defined(_WIN32) /* WinSock uses different data type here */
16998 (char *)&error_code,
16999#else
17000 &error_code,
17001#endif
17002 &opt_len)
17003 != 0) {
17004 /* Cannot determine if socket is already closed. This should
17005 * not occur and never did in a test. Log an error message
17006 * and continue. */
17007 mg_cry_internal(conn,
17008 "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
17009 __func__,
17010 strerror(ERRNO));
17011#if defined(_WIN32)
17012 } else if (error_code == WSAECONNRESET) {
17013#else
17014 } else if (error_code == ECONNRESET) {
17015#endif
17016 /* Socket already closed by client/peer, close socket without linger
17017 */
17018 } else {
17019
17020 /* Set linger timeout */
17021 if (setsockopt(conn->client.sock,
17022 SOL_SOCKET,
17023 SO_LINGER,
17024 (char *)&linger,
17025 sizeof(linger))
17026 != 0) {
17028 conn,
17029 "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
17030 __func__,
17031 linger.l_onoff,
17032 linger.l_linger,
17033 strerror(ERRNO));
17034 }
17035 }
17036
17037 /* Now we know that our FIN is ACK-ed, safe to close */
17038 closesocket(conn->client.sock);
17039 conn->client.sock = INVALID_SOCKET;
17040}
17041#endif
17042
17043
17044static void
17046{
17047#if defined(USE_SERVER_STATS)
17048 conn->conn_state = 6; /* to close */
17049#endif
17050
17051#if defined(USE_LUA) && defined(USE_WEBSOCKET)
17052 if (conn->lua_websocket_state) {
17053 lua_websocket_close(conn, conn->lua_websocket_state);
17054 conn->lua_websocket_state = NULL;
17055 }
17056#endif
17057
17058 mg_lock_connection(conn);
17059
17060 /* Set close flag, so keep-alive loops will stop */
17061 conn->must_close = 1;
17062
17063 /* call the connection_close callback if assigned */
17064 if (conn->phys_ctx->callbacks.connection_close != NULL) {
17065 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17066 conn->phys_ctx->callbacks.connection_close(conn);
17067 }
17068 }
17069
17070 /* Reset user data, after close callback is called.
17071 * Do not reuse it. If the user needs a destructor,
17072 * it must be done in the connection_close callback. */
17073 mg_set_user_connection_data(conn, NULL);
17074
17075
17076#if defined(USE_SERVER_STATS)
17077 conn->conn_state = 7; /* closing */
17078#endif
17079
17080#if defined(USE_MBEDTLS)
17081 if (conn->ssl != NULL) {
17082 mbed_ssl_close(conn->ssl);
17083 conn->ssl = NULL;
17084 }
17085#elif !defined(NO_SSL)
17086 if (conn->ssl != NULL) {
17087 /* Run SSL_shutdown twice to ensure completely close SSL connection
17088 */
17089 SSL_shutdown(conn->ssl);
17090 SSL_free(conn->ssl);
17091 OPENSSL_REMOVE_THREAD_STATE();
17092 conn->ssl = NULL;
17093 }
17094#endif
17095 if (conn->client.sock != INVALID_SOCKET) {
17096#if defined(__ZEPHYR__)
17097 closesocket(conn->client.sock);
17098#else
17100#endif
17101 conn->client.sock = INVALID_SOCKET;
17102 }
17103
17104 /* call the connection_closed callback if assigned */
17105 if (conn->phys_ctx->callbacks.connection_closed != NULL) {
17106 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17108 }
17109 }
17110
17112
17113#if defined(USE_SERVER_STATS)
17114 conn->conn_state = 8; /* closed */
17115#endif
17116}
17117
17118
17119void
17121{
17122 if ((conn == NULL) || (conn->phys_ctx == NULL)) {
17123 return;
17124 }
17125
17126#if defined(USE_WEBSOCKET)
17127 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17128 if (conn->in_websocket_handling) {
17129 /* Set close flag, so the server thread can exit. */
17130 conn->must_close = 1;
17131 return;
17132 }
17133 }
17134 if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
17135
17136 unsigned int i;
17137
17138 /* client context: loops must end */
17140 conn->must_close = 1;
17141
17142 /* We need to get the client thread out of the select/recv call
17143 * here. */
17144 /* Since we use a sleep quantum of some seconds to check for recv
17145 * timeouts, we will just wait a few seconds in mg_join_thread. */
17146
17147 /* join worker thread */
17148 for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
17150 }
17151 }
17152#endif /* defined(USE_WEBSOCKET) */
17153
17154 close_connection(conn);
17155
17156#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17159 && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
17160 SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
17161 }
17162#endif
17163
17164#if defined(USE_WEBSOCKET)
17165 if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
17167 (void)pthread_mutex_destroy(&conn->mutex);
17168 mg_free(conn);
17169 } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
17170 (void)pthread_mutex_destroy(&conn->mutex);
17171 mg_free(conn);
17172 }
17173#else
17174 if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
17175 (void)pthread_mutex_destroy(&conn->mutex);
17176 mg_free(conn);
17177 }
17178#endif /* defined(USE_WEBSOCKET) */
17179}
17180
17181
17182static struct mg_connection *
17183mg_connect_client_impl(const struct mg_client_options *client_options,
17184 int use_ssl,
17185 char *ebuf,
17186 size_t ebuf_len)
17187{
17188 struct mg_connection *conn = NULL;
17189 SOCKET sock;
17190 union usa sa;
17191 struct sockaddr *psa;
17192 socklen_t len;
17193
17194 unsigned max_req_size =
17195 (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
17196
17197 /* Size of structures, aligned to 8 bytes */
17198 size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
17199 size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
17200
17201 conn =
17202 (struct mg_connection *)mg_calloc(1,
17203 conn_size + ctx_size + max_req_size);
17204
17205 if (conn == NULL) {
17206 mg_snprintf(NULL,
17207 NULL, /* No truncation check for ebuf */
17208 ebuf,
17209 ebuf_len,
17210 "calloc(): %s",
17211 strerror(ERRNO));
17212 return NULL;
17213 }
17214
17215#if defined(GCC_DIAGNOSTIC)
17216#pragma GCC diagnostic push
17217#pragma GCC diagnostic ignored "-Wcast-align"
17218#endif /* defined(GCC_DIAGNOSTIC) */
17219 /* conn_size is aligned to 8 bytes */
17220
17221 conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
17222
17223#if defined(GCC_DIAGNOSTIC)
17224#pragma GCC diagnostic pop
17225#endif /* defined(GCC_DIAGNOSTIC) */
17226
17227 conn->buf = (((char *)conn) + conn_size + ctx_size);
17228 conn->buf_size = (int)max_req_size;
17230 conn->dom_ctx = &(conn->phys_ctx->dd);
17231
17232 if (!connect_socket(conn->phys_ctx,
17233 client_options->host,
17234 client_options->port,
17235 use_ssl,
17236 ebuf,
17237 ebuf_len,
17238 &sock,
17239 &sa)) {
17240 /* ebuf is set by connect_socket,
17241 * free all memory and return NULL; */
17242 mg_free(conn);
17243 return NULL;
17244 }
17245
17246#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17247#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
17248 && !defined(NO_SSL_DL)
17249 if (use_ssl
17250 && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
17251 == NULL) {
17252 mg_snprintf(NULL,
17253 NULL, /* No truncation check for ebuf */
17254 ebuf,
17255 ebuf_len,
17256 "SSL_CTX_new error: %s",
17257 ssl_error());
17258 closesocket(sock);
17259 mg_free(conn);
17260 return NULL;
17261 }
17262#else
17263 if (use_ssl
17264 && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
17265 == NULL) {
17266 mg_snprintf(NULL,
17267 NULL, /* No truncation check for ebuf */
17268 ebuf,
17269 ebuf_len,
17270 "SSL_CTX_new error: %s",
17271 ssl_error());
17272 closesocket(sock);
17273 mg_free(conn);
17274 return NULL;
17275 }
17276#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
17277#endif /* NO_SSL */
17278
17279
17280#if defined(USE_IPV6)
17281 len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
17282 : sizeof(conn->client.rsa.sin6);
17283 psa = (sa.sa.sa_family == AF_INET)
17284 ? (struct sockaddr *)&(conn->client.rsa.sin)
17285 : (struct sockaddr *)&(conn->client.rsa.sin6);
17286#else
17287 len = sizeof(conn->client.rsa.sin);
17288 psa = (struct sockaddr *)&(conn->client.rsa.sin);
17289#endif
17290
17291 conn->client.sock = sock;
17292 conn->client.lsa = sa;
17293
17294 if (getsockname(sock, psa, &len) != 0) {
17295 mg_cry_internal(conn,
17296 "%s: getsockname() failed: %s",
17297 __func__,
17298 strerror(ERRNO));
17299 }
17300
17301 conn->client.is_ssl = use_ssl ? 1 : 0;
17302 if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
17303 mg_snprintf(NULL,
17304 NULL, /* No truncation check for ebuf */
17305 ebuf,
17306 ebuf_len,
17307 "Can not create mutex");
17308#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17309 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17310#endif
17311 closesocket(sock);
17312 mg_free(conn);
17313 return NULL;
17314 }
17315
17316
17317#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17318 if (use_ssl) {
17319 /* TODO: Check ssl_verify_peer and ssl_ca_path here.
17320 * SSL_CTX_set_verify call is needed to switch off server
17321 * certificate checking, which is off by default in OpenSSL and
17322 * on in yaSSL. */
17323 /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
17324 * SSL_VERIFY_PEER, verify_ssl_server); */
17325
17326 if (client_options->client_cert) {
17327 if (!ssl_use_pem_file(conn->phys_ctx,
17328 conn->dom_ctx,
17329 client_options->client_cert,
17330 NULL)) {
17331 mg_snprintf(NULL,
17332 NULL, /* No truncation check for ebuf */
17333 ebuf,
17334 ebuf_len,
17335 "Can not use SSL client certificate");
17336 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17337 closesocket(sock);
17338 mg_free(conn);
17339 return NULL;
17340 }
17341 }
17342
17343 if (client_options->server_cert) {
17344 if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
17345 client_options->server_cert,
17346 NULL)
17347 != 1) {
17348 mg_cry_internal(conn,
17349 "SSL_CTX_load_verify_locations error: %s ",
17350 ssl_error());
17351 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17352 closesocket(sock);
17353 mg_free(conn);
17354 return NULL;
17355 }
17356 SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
17357 } else {
17358 SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
17359 }
17360
17361 if (!sslize(conn, SSL_connect, client_options)) {
17362 mg_snprintf(NULL,
17363 NULL, /* No truncation check for ebuf */
17364 ebuf,
17365 ebuf_len,
17366 "SSL connection error");
17367 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
17368 closesocket(sock);
17369 mg_free(conn);
17370 return NULL;
17371 }
17372 }
17373#endif
17374
17375 return conn;
17376}
17377
17378
17380mg_connect_client_secure(const struct mg_client_options *client_options,
17381 char *error_buffer,
17382 size_t error_buffer_size)
17383{
17384 return mg_connect_client_impl(client_options,
17385 1,
17386 error_buffer,
17387 error_buffer_size);
17388}
17389
17390
17391struct mg_connection *
17392mg_connect_client(const char *host,
17393 int port,
17394 int use_ssl,
17395 char *error_buffer,
17396 size_t error_buffer_size)
17397{
17398 struct mg_client_options opts;
17399 memset(&opts, 0, sizeof(opts));
17400 opts.host = host;
17401 opts.port = port;
17402 return mg_connect_client_impl(&opts,
17403 use_ssl,
17404 error_buffer,
17405 error_buffer_size);
17406}
17407
17408
17409#if defined(MG_EXPERIMENTAL_INTERFACES)
17410struct mg_connection *
17411mg_connect_client2(const char *host,
17412 const char *protocol,
17413 int port,
17414 const char *path,
17415 struct mg_init_data *init,
17416 struct mg_error_data *error)
17417{
17418 int is_ssl, is_ws;
17419 /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
17420
17421 if (error != NULL) {
17422 error->code = 0;
17423 if (error->text_buffer_size > 0) {
17424 *error->text = 0;
17425 }
17426 }
17427
17428 if ((host == NULL) || (protocol == NULL)) {
17429 if ((error != NULL) && (error->text_buffer_size > 0)) {
17430 mg_snprintf(NULL,
17431 NULL, /* No truncation check for error buffers */
17432 error->text,
17433 error->text_buffer_size,
17434 "%s",
17435 "Invalid parameters");
17436 }
17437 return NULL;
17438 }
17439
17440 /* check all known protocolls */
17441 if (!mg_strcasecmp(protocol, "http")) {
17442 is_ssl = 0;
17443 is_ws = 0;
17444 } else if (!mg_strcasecmp(protocol, "https")) {
17445 is_ssl = 1;
17446 is_ws = 0;
17447#if defined(USE_WEBSOCKET)
17448 } else if (!mg_strcasecmp(protocol, "ws")) {
17449 is_ssl = 0;
17450 is_ws = 1;
17451 } else if (!mg_strcasecmp(protocol, "wss")) {
17452 is_ssl = 1;
17453 is_ws = 1;
17454#endif
17455 } else {
17456 if ((error != NULL) && (error->text_buffer_size > 0)) {
17457 mg_snprintf(NULL,
17458 NULL, /* No truncation check for error buffers */
17459 error->text,
17460 error->text_buffer_size,
17461 "Protocol %s not supported",
17462 protocol);
17463 }
17464 return NULL;
17465 }
17466
17467 /* TODO: The current implementation here just calls the old
17468 * implementations, without using any new options. This is just a first
17469 * step to test the new interfaces. */
17470#if defined(USE_WEBSOCKET)
17471 if (is_ws) {
17472 /* TODO: implement all options */
17474 host,
17475 port,
17476 is_ssl,
17477 ((error != NULL) ? error->text : NULL),
17478 ((error != NULL) ? error->text_buffer_size : 0),
17479 (path ? path : ""),
17480 NULL /* TODO: origin */,
17481 experimental_websocket_client_data_wrapper,
17482 experimental_websocket_client_close_wrapper,
17483 (void *)init->callbacks);
17484 }
17485#endif
17486
17487 /* TODO: all additional options */
17488 struct mg_client_options opts;
17489 memset(&opts, 0, sizeof(opts));
17490 opts.host = host;
17491 opts.port = port;
17492 return mg_connect_client_impl(&opts,
17493 is_ssl,
17494 ((error != NULL) ? error->text : NULL),
17495 ((error != NULL) ? error->text_buffer_size
17496 : 0));
17497}
17498#endif
17499
17500
17501static const struct {
17502 const char *proto;
17505} abs_uri_protocols[] = {{"http://", 7, 80},
17506 {"https://", 8, 443},
17507 {"ws://", 5, 80},
17508 {"wss://", 6, 443},
17509 {NULL, 0, 0}};
17510
17511
17512/* Check if the uri is valid.
17513 * return 0 for invalid uri,
17514 * return 1 for *,
17515 * return 2 for relative uri,
17516 * return 3 for absolute uri without port,
17517 * return 4 for absolute uri with port */
17518static int
17519get_uri_type(const char *uri)
17520{
17521 int i;
17522 const char *hostend, *portbegin;
17523 char *portend;
17524 unsigned long port;
17525
17526 /* According to the HTTP standard
17527 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
17528 * URI can be an asterisk (*) or should start with slash (relative uri),
17529 * or it should start with the protocol (absolute uri). */
17530 if ((uri[0] == '*') && (uri[1] == '\0')) {
17531 /* asterisk */
17532 return 1;
17533 }
17534
17535 /* Valid URIs according to RFC 3986
17536 * (https://www.ietf.org/rfc/rfc3986.txt)
17537 * must only contain reserved characters :/?#[]@!$&'()*+,;=
17538 * and unreserved characters A-Z a-z 0-9 and -._~
17539 * and % encoded symbols.
17540 */
17541 for (i = 0; uri[i] != 0; i++) {
17542 if (uri[i] < 33) {
17543 /* control characters and spaces are invalid */
17544 return 0;
17545 }
17546 /* Allow everything else here (See #894) */
17547 }
17548
17549 /* A relative uri starts with a / character */
17550 if (uri[0] == '/') {
17551 /* relative uri */
17552 return 2;
17553 }
17554
17555 /* It could be an absolute uri: */
17556 /* This function only checks if the uri is valid, not if it is
17557 * addressing the current server. So civetweb can also be used
17558 * as a proxy server. */
17559 for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
17560 if (mg_strncasecmp(uri,
17563 == 0) {
17564
17565 hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
17566 if (!hostend) {
17567 return 0;
17568 }
17569 portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
17570 if (!portbegin) {
17571 return 3;
17572 }
17573
17574 port = strtoul(portbegin + 1, &portend, 10);
17575 if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
17576 return 0;
17577 }
17578
17579 return 4;
17580 }
17581 }
17582
17583 return 0;
17584}
17585
17586
17587/* Return NULL or the relative uri at the current server */
17588static const char *
17589get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
17590{
17591 const char *server_domain;
17592 size_t server_domain_len;
17593 size_t request_domain_len = 0;
17594 unsigned long port = 0;
17595 int i, auth_domain_check_enabled;
17596 const char *hostbegin = NULL;
17597 const char *hostend = NULL;
17598 const char *portbegin;
17599 char *portend;
17600
17601 auth_domain_check_enabled =
17603
17604 /* DNS is case insensitive, so use case insensitive string compare here
17605 */
17606 for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
17607 if (mg_strncasecmp(uri,
17610 == 0) {
17611
17612 hostbegin = uri + abs_uri_protocols[i].proto_len;
17613 hostend = strchr(hostbegin, '/');
17614 if (!hostend) {
17615 return 0;
17616 }
17617 portbegin = strchr(hostbegin, ':');
17618 if ((!portbegin) || (portbegin > hostend)) {
17619 port = abs_uri_protocols[i].default_port;
17620 request_domain_len = (size_t)(hostend - hostbegin);
17621 } else {
17622 port = strtoul(portbegin + 1, &portend, 10);
17623 if ((portend != hostend) || (port <= 0)
17624 || !is_valid_port(port)) {
17625 return 0;
17626 }
17627 request_domain_len = (size_t)(portbegin - hostbegin);
17628 }
17629 /* protocol found, port set */
17630 break;
17631 }
17632 }
17633
17634 if (!port) {
17635 /* port remains 0 if the protocol is not found */
17636 return 0;
17637 }
17638
17639 /* Check if the request is directed to a different server. */
17640 /* First check if the port is the same. */
17641 if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
17642 /* Request is directed to a different port */
17643 return 0;
17644 }
17645
17646 /* Finally check if the server corresponds to the authentication
17647 * domain of the server (the server domain).
17648 * Allow full matches (like http://mydomain.com/path/file.ext), and
17649 * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
17650 * but do not allow substrings (like
17651 * http://notmydomain.com/path/file.ext
17652 * or http://mydomain.com.fake/path/file.ext).
17653 */
17654 if (auth_domain_check_enabled) {
17655 server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
17656 server_domain_len = strlen(server_domain);
17657 if ((server_domain_len == 0) || (hostbegin == NULL)) {
17658 return 0;
17659 }
17660 if ((request_domain_len == server_domain_len)
17661 && (!memcmp(server_domain, hostbegin, server_domain_len))) {
17662 /* Request is directed to this server - full name match. */
17663 } else {
17664 if (request_domain_len < (server_domain_len + 2)) {
17665 /* Request is directed to another server: The server name
17666 * is longer than the request name.
17667 * Drop this case here to avoid overflows in the
17668 * following checks. */
17669 return 0;
17670 }
17671 if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
17672 /* Request is directed to another server: It could be a
17673 * substring
17674 * like notmyserver.com */
17675 return 0;
17676 }
17677 if (0
17678 != memcmp(server_domain,
17679 hostbegin + request_domain_len - server_domain_len,
17680 server_domain_len)) {
17681 /* Request is directed to another server:
17682 * The server name is different. */
17683 return 0;
17684 }
17685 }
17686 }
17687
17688 return hostend;
17689}
17690
17691
17692static int
17693get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17694{
17695 if (ebuf_len > 0) {
17696 ebuf[0] = '\0';
17697 }
17698 *err = 0;
17699
17701
17702 if (!conn) {
17703 mg_snprintf(conn,
17704 NULL, /* No truncation check for ebuf */
17705 ebuf,
17706 ebuf_len,
17707 "%s",
17708 "Internal error");
17709 *err = 500;
17710 return 0;
17711 }
17712
17713 /* Set the time the request was received. This value should be used for
17714 * timeouts. */
17715 clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
17716
17717 conn->request_len =
17718 read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
17719 DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
17720 if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
17721 mg_snprintf(conn,
17722 NULL, /* No truncation check for ebuf */
17723 ebuf,
17724 ebuf_len,
17725 "%s",
17726 "Invalid message size");
17727 *err = 500;
17728 return 0;
17729 }
17730
17731 if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
17732 mg_snprintf(conn,
17733 NULL, /* No truncation check for ebuf */
17734 ebuf,
17735 ebuf_len,
17736 "%s",
17737 "Message too large");
17738 *err = 413;
17739 return 0;
17740 }
17741
17742 if (conn->request_len <= 0) {
17743 if (conn->data_len > 0) {
17744 mg_snprintf(conn,
17745 NULL, /* No truncation check for ebuf */
17746 ebuf,
17747 ebuf_len,
17748 "%s",
17749 "Malformed message");
17750 *err = 400;
17751 } else {
17752 /* Server did not recv anything -> just close the connection */
17753 conn->must_close = 1;
17754 mg_snprintf(conn,
17755 NULL, /* No truncation check for ebuf */
17756 ebuf,
17757 ebuf_len,
17758 "%s",
17759 "No data received");
17760 *err = 0;
17761 }
17762 return 0;
17763 }
17764 return 1;
17765}
17766
17767
17768static int
17769get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17770{
17771 const char *cl;
17772
17773 conn->connection_type =
17774 CONNECTION_TYPE_REQUEST; /* request (valid of not) */
17775
17776 if (!get_message(conn, ebuf, ebuf_len, err)) {
17777 return 0;
17778 }
17779
17780 if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
17781 <= 0) {
17782 mg_snprintf(conn,
17783 NULL, /* No truncation check for ebuf */
17784 ebuf,
17785 ebuf_len,
17786 "%s",
17787 "Bad request");
17788 *err = 400;
17789 return 0;
17790 }
17791
17792 /* Message is a valid request */
17793
17794 if (!switch_domain_context(conn)) {
17795 mg_snprintf(conn,
17796 NULL, /* No truncation check for ebuf */
17797 ebuf,
17798 ebuf_len,
17799 "%s",
17800 "Bad request: Host mismatch");
17801 *err = 400;
17802 return 0;
17803 }
17804
17805#if USE_ZLIB
17806 if (((cl = get_header(conn->request_info.http_headers,
17808 "Accept-Encoding"))
17809 != NULL)
17810 && strstr(cl, "gzip")) {
17811 conn->accept_gzip = 1;
17812 }
17813#endif
17814 if (((cl = get_header(conn->request_info.http_headers,
17816 "Transfer-Encoding"))
17817 != NULL)
17818 && mg_strcasecmp(cl, "identity")) {
17819 if (mg_strcasecmp(cl, "chunked")) {
17820 mg_snprintf(conn,
17821 NULL, /* No truncation check for ebuf */
17822 ebuf,
17823 ebuf_len,
17824 "%s",
17825 "Bad request");
17826 *err = 400;
17827 return 0;
17828 }
17829 conn->is_chunked = 1;
17830 conn->content_len = 0; /* not yet read */
17831 } else if ((cl = get_header(conn->request_info.http_headers,
17833 "Content-Length"))
17834 != NULL) {
17835 /* Request has content length set */
17836 char *endptr = NULL;
17837 conn->content_len = strtoll(cl, &endptr, 10);
17838 if ((endptr == cl) || (conn->content_len < 0)) {
17839 mg_snprintf(conn,
17840 NULL, /* No truncation check for ebuf */
17841 ebuf,
17842 ebuf_len,
17843 "%s",
17844 "Bad request");
17845 *err = 411;
17846 return 0;
17847 }
17848 /* Publish the content length back to the request info. */
17850 } else {
17851 /* There is no exception, see RFC7230. */
17852 conn->content_len = 0;
17853 }
17854
17855 return 1;
17856}
17857
17858
17859/* conn is assumed to be valid in this internal function */
17860static int
17861get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17862{
17863 const char *cl;
17864
17865 conn->connection_type =
17866 CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
17867
17868 if (!get_message(conn, ebuf, ebuf_len, err)) {
17869 return 0;
17870 }
17871
17872 if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
17873 <= 0) {
17874 mg_snprintf(conn,
17875 NULL, /* No truncation check for ebuf */
17876 ebuf,
17877 ebuf_len,
17878 "%s",
17879 "Bad response");
17880 *err = 400;
17881 return 0;
17882 }
17883
17884 /* Message is a valid response */
17885
17886 if (((cl = get_header(conn->response_info.http_headers,
17888 "Transfer-Encoding"))
17889 != NULL)
17890 && mg_strcasecmp(cl, "identity")) {
17891 if (mg_strcasecmp(cl, "chunked")) {
17892 mg_snprintf(conn,
17893 NULL, /* No truncation check for ebuf */
17894 ebuf,
17895 ebuf_len,
17896 "%s",
17897 "Bad request");
17898 *err = 400;
17899 return 0;
17900 }
17901 conn->is_chunked = 1;
17902 conn->content_len = 0; /* not yet read */
17903 } else if ((cl = get_header(conn->response_info.http_headers,
17905 "Content-Length"))
17906 != NULL) {
17907 char *endptr = NULL;
17908 conn->content_len = strtoll(cl, &endptr, 10);
17909 if ((endptr == cl) || (conn->content_len < 0)) {
17910 mg_snprintf(conn,
17911 NULL, /* No truncation check for ebuf */
17912 ebuf,
17913 ebuf_len,
17914 "%s",
17915 "Bad request");
17916 *err = 411;
17917 return 0;
17918 }
17919 /* Publish the content length back to the response info. */
17921
17922 /* TODO: check if it is still used in response_info */
17924
17925 /* TODO: we should also consider HEAD method */
17926 if (conn->response_info.status_code == 304) {
17927 conn->content_len = 0;
17928 }
17929 } else {
17930 /* TODO: we should also consider HEAD method */
17931 if (((conn->response_info.status_code >= 100)
17932 && (conn->response_info.status_code <= 199))
17933 || (conn->response_info.status_code == 204)
17934 || (conn->response_info.status_code == 304)) {
17935 conn->content_len = 0;
17936 } else {
17937 conn->content_len = -1; /* unknown content length */
17938 }
17939 }
17940
17941 return 1;
17942}
17943
17944
17945int
17947 char *ebuf,
17948 size_t ebuf_len,
17949 int timeout)
17950{
17951 int err, ret;
17952 char txt[32]; /* will not overflow */
17953 char *save_timeout;
17954 char *new_timeout;
17955
17956 if (ebuf_len > 0) {
17957 ebuf[0] = '\0';
17958 }
17959
17960 if (!conn) {
17961 mg_snprintf(conn,
17962 NULL, /* No truncation check for ebuf */
17963 ebuf,
17964 ebuf_len,
17965 "%s",
17966 "Parameter error");
17967 return -1;
17968 }
17969
17970 /* Reset the previous responses */
17971 conn->data_len = 0;
17972
17973 /* Implementation of API function for HTTP clients */
17974 save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
17975
17976 if (timeout >= 0) {
17977 mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
17978 new_timeout = txt;
17979 } else {
17980 new_timeout = NULL;
17981 }
17982
17983 conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
17984 ret = get_response(conn, ebuf, ebuf_len, &err);
17985 conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
17986
17987 /* TODO: here, the URI is the http response code */
17990
17991 /* TODO (mid): Define proper return values - maybe return length?
17992 * For the first test use <0 for error and >0 for OK */
17993 return (ret == 0) ? -1 : +1;
17994}
17995
17996
17997struct mg_connection *
17998mg_download(const char *host,
17999 int port,
18000 int use_ssl,
18001 char *ebuf,
18002 size_t ebuf_len,
18003 const char *fmt,
18004 ...)
18005{
18006 struct mg_connection *conn;
18007 va_list ap;
18008 int i;
18009 int reqerr;
18010
18011 if (ebuf_len > 0) {
18012 ebuf[0] = '\0';
18013 }
18014
18015 va_start(ap, fmt);
18016
18017 /* open a connection */
18018 conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
18019
18020 if (conn != NULL) {
18021 i = mg_vprintf(conn, fmt, ap);
18022 if (i <= 0) {
18023 mg_snprintf(conn,
18024 NULL, /* No truncation check for ebuf */
18025 ebuf,
18026 ebuf_len,
18027 "%s",
18028 "Error sending request");
18029 } else {
18030 /* make sure the buffer is clear */
18031 conn->data_len = 0;
18032 get_response(conn, ebuf, ebuf_len, &reqerr);
18033
18034 /* TODO: here, the URI is the http response code */
18036 }
18037 }
18038
18039 /* if an error occurred, close the connection */
18040 if ((ebuf[0] != '\0') && (conn != NULL)) {
18041 mg_close_connection(conn);
18042 conn = NULL;
18043 }
18044
18045 va_end(ap);
18046 return conn;
18047}
18048
18049
18055};
18056
18057
18058#if defined(USE_WEBSOCKET)
18059#if defined(_WIN32)
18060static unsigned __stdcall websocket_client_thread(void *data)
18061#else
18062static void *
18063websocket_client_thread(void *data)
18064#endif
18065{
18066 struct websocket_client_thread_data *cdata =
18068
18069 void *user_thread_ptr = NULL;
18070
18071#if !defined(_WIN32) && !defined(__ZEPHYR__)
18072 struct sigaction sa;
18073
18074 /* Ignore SIGPIPE */
18075 memset(&sa, 0, sizeof(sa));
18076 sa.sa_handler = SIG_IGN;
18077 sigaction(SIGPIPE, &sa, NULL);
18078#endif
18079
18080 mg_set_thread_name("ws-clnt");
18081
18082 if (cdata->conn->phys_ctx) {
18083 if (cdata->conn->phys_ctx->callbacks.init_thread) {
18084 /* 3 indicates a websocket client thread */
18085 /* TODO: check if conn->phys_ctx can be set */
18086 user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
18087 cdata->conn->phys_ctx, 3);
18088 }
18089 }
18090
18091 read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
18092
18093 DEBUG_TRACE("%s", "Websocket client thread exited\n");
18094
18095 if (cdata->close_handler != NULL) {
18096 cdata->close_handler(cdata->conn, cdata->callback_data);
18097 }
18098
18099 /* The websocket_client context has only this thread. If it runs out,
18100 set the stop_flag to 2 (= "stopped"). */
18102
18103 if (cdata->conn->phys_ctx->callbacks.exit_thread) {
18105 3,
18106 user_thread_ptr);
18107 }
18108
18109 mg_free((void *)cdata);
18110
18111#if defined(_WIN32)
18112 return 0;
18113#else
18114 return NULL;
18115#endif
18116}
18117#endif
18118
18119
18120static struct mg_connection *
18122 int use_ssl,
18123 char *error_buffer,
18124 size_t error_buffer_size,
18125 const char *path,
18126 const char *origin,
18127 const char *extensions,
18128 mg_websocket_data_handler data_func,
18129 mg_websocket_close_handler close_func,
18130 void *user_data)
18131{
18132 struct mg_connection *conn = NULL;
18133
18134#if defined(USE_WEBSOCKET)
18135 struct websocket_client_thread_data *thread_data;
18136 static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
18137
18138 const char *host = client_options->host;
18139 int i;
18140
18141#if defined(__clang__)
18142#pragma clang diagnostic push
18143#pragma clang diagnostic ignored "-Wformat-nonliteral"
18144#endif
18145
18146 /* Establish the client connection and request upgrade */
18147 conn = mg_connect_client_impl(client_options,
18148 use_ssl,
18149 error_buffer,
18150 error_buffer_size);
18151
18152 /* Connection object will be null if something goes wrong */
18153 if (conn == NULL) {
18154 /* error_buffer should be already filled ... */
18155 if (!error_buffer[0]) {
18156 /* ... if not add an error message */
18158 NULL, /* No truncation check for ebuf */
18159 error_buffer,
18160 error_buffer_size,
18161 "Unexpected error");
18162 }
18163 return NULL;
18164 }
18165
18166 if (origin != NULL) {
18167 if (extensions != NULL) {
18168 i = mg_printf(conn,
18169 "GET %s HTTP/1.1\r\n"
18170 "Host: %s\r\n"
18171 "Upgrade: websocket\r\n"
18172 "Connection: Upgrade\r\n"
18173 "Sec-WebSocket-Key: %s\r\n"
18174 "Sec-WebSocket-Version: 13\r\n"
18175 "Sec-WebSocket-Extensions: %s\r\n"
18176 "Origin: %s\r\n"
18177 "\r\n",
18178 path,
18179 host,
18180 magic,
18181 extensions,
18182 origin);
18183 } else {
18184 i = mg_printf(conn,
18185 "GET %s HTTP/1.1\r\n"
18186 "Host: %s\r\n"
18187 "Upgrade: websocket\r\n"
18188 "Connection: Upgrade\r\n"
18189 "Sec-WebSocket-Key: %s\r\n"
18190 "Sec-WebSocket-Version: 13\r\n"
18191 "Origin: %s\r\n"
18192 "\r\n",
18193 path,
18194 host,
18195 magic,
18196 origin);
18197 }
18198 } else {
18199
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 "\r\n",
18210 path,
18211 host,
18212 magic,
18213 extensions);
18214 } else {
18215 i = mg_printf(conn,
18216 "GET %s HTTP/1.1\r\n"
18217 "Host: %s\r\n"
18218 "Upgrade: websocket\r\n"
18219 "Connection: Upgrade\r\n"
18220 "Sec-WebSocket-Key: %s\r\n"
18221 "Sec-WebSocket-Version: 13\r\n"
18222 "\r\n",
18223 path,
18224 host,
18225 magic);
18226 }
18227 }
18228 if (i <= 0) {
18230 NULL, /* No truncation check for ebuf */
18231 error_buffer,
18232 error_buffer_size,
18233 "%s",
18234 "Error sending request");
18236 return NULL;
18237 }
18238
18239 conn->data_len = 0;
18240 if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
18242 return NULL;
18243 }
18246
18247#if defined(__clang__)
18248#pragma clang diagnostic pop
18249#endif
18250
18251 if (conn->response_info.status_code != 101) {
18252 /* We sent an "upgrade" request. For a correct websocket
18253 * protocol handshake, we expect a "101 Continue" response.
18254 * Otherwise it is a protocol violation. Maybe the HTTP
18255 * Server does not know websockets. */
18256 if (!*error_buffer) {
18257 /* set an error, if not yet set */
18259 NULL, /* No truncation check for ebuf */
18260 error_buffer,
18261 error_buffer_size,
18262 "Unexpected server reply");
18263 }
18264
18265 DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
18267 return NULL;
18268 }
18269
18270 thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
18271 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
18272 if (!thread_data) {
18273 DEBUG_TRACE("%s\r\n", "Out of memory");
18275 return NULL;
18276 }
18277
18278 thread_data->conn = conn;
18279 thread_data->data_handler = data_func;
18280 thread_data->close_handler = close_func;
18281 thread_data->callback_data = user_data;
18282
18284 (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
18286 DEBUG_TRACE("%s\r\n", "Out of memory");
18287 mg_free(thread_data);
18289 return NULL;
18290 }
18291
18292 /* Now upgrade to ws/wss client context */
18293 conn->phys_ctx->user_data = user_data;
18295 conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
18296
18297 /* Start a thread to read the websocket client connection
18298 * This thread will automatically stop when mg_disconnect is
18299 * called on the client connection */
18300 if (mg_start_thread_with_id(websocket_client_thread,
18301 thread_data,
18303 != 0) {
18305 mg_free(thread_data);
18307 conn = NULL;
18308 DEBUG_TRACE("%s",
18309 "Websocket client connect thread could not be started\r\n");
18310 }
18311
18312#else
18313 /* Appease "unused parameter" warnings */
18314 (void)client_options;
18315 (void)use_ssl;
18316 (void)error_buffer;
18317 (void)error_buffer_size;
18318 (void)path;
18319 (void)origin;
18320 (void)extensions;
18321 (void)user_data;
18322 (void)data_func;
18323 (void)close_func;
18324#endif
18325
18326 return conn;
18327}
18328
18329
18330struct mg_connection *
18332 int port,
18333 int use_ssl,
18334 char *error_buffer,
18335 size_t error_buffer_size,
18336 const char *path,
18337 const char *origin,
18338 mg_websocket_data_handler data_func,
18339 mg_websocket_close_handler close_func,
18340 void *user_data)
18341{
18342 struct mg_client_options client_options;
18343 memset(&client_options, 0, sizeof(client_options));
18344 client_options.host = host;
18345 client_options.port = port;
18346
18347 return mg_connect_websocket_client_impl(&client_options,
18348 use_ssl,
18349 error_buffer,
18350 error_buffer_size,
18351 path,
18352 origin,
18353 NULL,
18354 data_func,
18355 close_func,
18356 user_data);
18357}
18358
18359
18360struct mg_connection *
18362 const struct mg_client_options *client_options,
18363 char *error_buffer,
18364 size_t error_buffer_size,
18365 const char *path,
18366 const char *origin,
18367 mg_websocket_data_handler data_func,
18368 mg_websocket_close_handler close_func,
18369 void *user_data)
18370{
18371 if (!client_options) {
18372 return NULL;
18373 }
18374 return mg_connect_websocket_client_impl(client_options,
18375 1,
18376 error_buffer,
18377 error_buffer_size,
18378 path,
18379 origin,
18380 NULL,
18381 data_func,
18382 close_func,
18383 user_data);
18384}
18385
18386struct mg_connection *
18388 int port,
18389 int use_ssl,
18390 char *error_buffer,
18391 size_t error_buffer_size,
18392 const char *path,
18393 const char *origin,
18394 const char *extensions,
18395 mg_websocket_data_handler data_func,
18396 mg_websocket_close_handler close_func,
18397 void *user_data)
18398{
18399 struct mg_client_options client_options;
18400 memset(&client_options, 0, sizeof(client_options));
18401 client_options.host = host;
18402 client_options.port = port;
18403
18404 return mg_connect_websocket_client_impl(&client_options,
18405 use_ssl,
18406 error_buffer,
18407 error_buffer_size,
18408 path,
18409 origin,
18410 extensions,
18411 data_func,
18412 close_func,
18413 user_data);
18414}
18415
18416struct mg_connection *
18418 const struct mg_client_options *client_options,
18419 char *error_buffer,
18420 size_t error_buffer_size,
18421 const char *path,
18422 const char *origin,
18423 const char *extensions,
18424 mg_websocket_data_handler data_func,
18425 mg_websocket_close_handler close_func,
18426 void *user_data)
18427{
18428 if (!client_options) {
18429 return NULL;
18430 }
18431 return mg_connect_websocket_client_impl(client_options,
18432 1,
18433 error_buffer,
18434 error_buffer_size,
18435 path,
18436 origin,
18437 extensions,
18438 data_func,
18439 close_func,
18440 user_data);
18441}
18442
18443/* Prepare connection data structure */
18444static void
18446{
18447 /* Is keep alive allowed by the server */
18448 int keep_alive_enabled =
18450
18451 if (!keep_alive_enabled) {
18452 conn->must_close = 1;
18453 }
18454
18455 /* Important: on new connection, reset the receiving buffer. Credit
18456 * goes to crule42. */
18457 conn->data_len = 0;
18458 conn->handled_requests = 0;
18460 mg_set_user_connection_data(conn, NULL);
18461
18462#if defined(USE_SERVER_STATS)
18463 conn->conn_state = 2; /* init */
18464#endif
18465
18466 /* call the init_connection callback if assigned */
18467 if (conn->phys_ctx->callbacks.init_connection != NULL) {
18468 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
18469 void *conn_data = NULL;
18470 conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
18471 mg_set_user_connection_data(conn, conn_data);
18472 }
18473 }
18474}
18475
18476
18477/* Process a connection - may handle multiple requests
18478 * using the same connection.
18479 * Must be called with a valid connection (conn and
18480 * conn->phys_ctx must be valid).
18481 */
18482static void
18484{
18485 struct mg_request_info *ri = &conn->request_info;
18486 int keep_alive, discard_len;
18487 char ebuf[100];
18488 const char *hostend;
18489 int reqerr, uri_type;
18490
18491#if defined(USE_SERVER_STATS)
18492 ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
18493 mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
18494 mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
18495#endif
18496
18497 DEBUG_TRACE("Start processing connection from %s",
18499
18500 /* Loop over multiple requests sent using the same connection
18501 * (while "keep alive"). */
18502 do {
18503 DEBUG_TRACE("calling get_request (%i times for this connection)",
18504 conn->handled_requests + 1);
18505
18506#if defined(USE_SERVER_STATS)
18507 conn->conn_state = 3; /* ready */
18508#endif
18509
18510 if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
18511 /* The request sent by the client could not be understood by
18512 * the server, or it was incomplete or a timeout. Send an
18513 * error message and close the connection. */
18514 if (reqerr > 0) {
18515 DEBUG_ASSERT(ebuf[0] != '\0');
18516 mg_send_http_error(conn, reqerr, "%s", ebuf);
18517 }
18518
18519 } else if (strcmp(ri->http_version, "1.0")
18520 && strcmp(ri->http_version, "1.1")) {
18521 /* HTTP/2 is not allowed here */
18522 mg_snprintf(conn,
18523 NULL, /* No truncation check for ebuf */
18524 ebuf,
18525 sizeof(ebuf),
18526 "Bad HTTP version: [%s]",
18527 ri->http_version);
18528 mg_send_http_error(conn, 505, "%s", ebuf);
18529 }
18530
18531 if (ebuf[0] == '\0') {
18532 uri_type = get_uri_type(conn->request_info.request_uri);
18533 switch (uri_type) {
18534 case 1:
18535 /* Asterisk */
18536 conn->request_info.local_uri_raw = 0;
18537 /* TODO: Deal with '*'. */
18538 break;
18539 case 2:
18540 /* relative uri */
18543 break;
18544 case 3:
18545 case 4:
18546 /* absolute uri (with/without port) */
18548 conn->request_info.request_uri, conn);
18549 if (hostend) {
18550 conn->request_info.local_uri_raw = hostend;
18551 } else {
18552 conn->request_info.local_uri_raw = NULL;
18553 }
18554 break;
18555 default:
18556 mg_snprintf(conn,
18557 NULL, /* No truncation check for ebuf */
18558 ebuf,
18559 sizeof(ebuf),
18560 "Invalid URI");
18561 mg_send_http_error(conn, 400, "%s", ebuf);
18562 conn->request_info.local_uri_raw = NULL;
18563 break;
18564 }
18565 conn->request_info.local_uri =
18566 (char *)conn->request_info.local_uri_raw;
18567 }
18568
18569 if (ebuf[0] != '\0') {
18570 conn->protocol_type = -1;
18571
18572 } else {
18573 /* HTTP/1 allows protocol upgrade */
18575
18576 if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
18577 /* This will occur, if a HTTP/1.1 request should be upgraded
18578 * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
18579 * Since most (all?) major browsers only support HTTP/2 using
18580 * ALPN, this is hard to test and very low priority.
18581 * Deactivate it (at least for now).
18582 */
18584 }
18585 }
18586
18587 DEBUG_TRACE("http: %s, error: %s",
18588 (ri->http_version ? ri->http_version : "none"),
18589 (ebuf[0] ? ebuf : "none"));
18590
18591 if (ebuf[0] == '\0') {
18592 if (conn->request_info.local_uri) {
18593
18594 /* handle request to local server */
18596
18597 } else {
18598 /* TODO: handle non-local request (PROXY) */
18599 conn->must_close = 1;
18600 }
18601 } else {
18602 conn->must_close = 1;
18603 }
18604
18605 /* Response complete. Free header buffer */
18607
18608 if (ri->remote_user != NULL) {
18609 mg_free((void *)ri->remote_user);
18610 /* Important! When having connections with and without auth
18611 * would cause double free and then crash */
18612 ri->remote_user = NULL;
18613 }
18614
18615 /* NOTE(lsm): order is important here. should_keep_alive() call
18616 * is using parsed request, which will be invalid after
18617 * memmove's below.
18618 * Therefore, memorize should_keep_alive() result now for later
18619 * use in loop exit condition. */
18620 /* Enable it only if this request is completely discardable. */
18621 keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
18622 && should_keep_alive(conn) && (conn->content_len >= 0)
18623 && (conn->request_len > 0)
18624 && ((conn->is_chunked == 4)
18625 || (!conn->is_chunked
18626 && ((conn->consumed_content == conn->content_len)
18627 || ((conn->request_len + conn->content_len)
18628 <= conn->data_len))))
18629 && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
18630
18631 if (keep_alive) {
18632 /* Discard all buffered data for this request */
18633 discard_len =
18634 ((conn->request_len + conn->content_len) < conn->data_len)
18635 ? (int)(conn->request_len + conn->content_len)
18636 : conn->data_len;
18637 conn->data_len -= discard_len;
18638
18639 if (conn->data_len > 0) {
18640 DEBUG_TRACE("discard_len = %d", discard_len);
18641 memmove(conn->buf,
18642 conn->buf + discard_len,
18643 (size_t)conn->data_len);
18644 }
18645 }
18646
18647 DEBUG_ASSERT(conn->data_len >= 0);
18648 DEBUG_ASSERT(conn->data_len <= conn->buf_size);
18649
18650 if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
18651 DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
18652 (long int)conn->data_len,
18653 (long int)conn->buf_size);
18654 break;
18655 }
18656 conn->handled_requests++;
18657 } while (keep_alive);
18658
18659 DEBUG_TRACE("Done processing connection from %s (%f sec)",
18661 difftime(time(NULL), conn->conn_birth_time));
18662
18663 close_connection(conn);
18664
18665#if defined(USE_SERVER_STATS)
18666 mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
18667 mg_atomic_dec(&(conn->phys_ctx->active_connections));
18668#endif
18669}
18670
18671
18672#if defined(ALTERNATIVE_QUEUE)
18673
18674static void
18675produce_socket(struct mg_context *ctx, const struct socket *sp)
18676{
18677 unsigned int i;
18678
18679 while (!ctx->stop_flag) {
18680 for (i = 0; i < ctx->cfg_worker_threads; i++) {
18681 /* find a free worker slot and signal it */
18682 if (ctx->client_socks[i].in_use == 2) {
18683 (void)pthread_mutex_lock(&ctx->thread_mutex);
18684 if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
18685 ctx->client_socks[i] = *sp;
18686 ctx->client_socks[i].in_use = 1;
18687 /* socket has been moved to the consumer */
18688 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18689 (void)event_signal(ctx->client_wait_events[i]);
18690 return;
18691 }
18692 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18693 }
18694 }
18695 /* queue is full */
18696 mg_sleep(1);
18697 }
18698 /* must consume */
18700 closesocket(sp->sock);
18701}
18702
18703
18704static int
18705consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
18706{
18707 DEBUG_TRACE("%s", "going idle");
18708 (void)pthread_mutex_lock(&ctx->thread_mutex);
18709 ctx->client_socks[thread_index].in_use = 2;
18710 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18711
18712 event_wait(ctx->client_wait_events[thread_index]);
18713
18714 (void)pthread_mutex_lock(&ctx->thread_mutex);
18715 *sp = ctx->client_socks[thread_index];
18716 if (ctx->stop_flag) {
18717 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18718 if (sp->in_use == 1) {
18719 /* must consume */
18721 closesocket(sp->sock);
18722 }
18723 return 0;
18724 }
18725 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18726 if (sp->in_use == 1) {
18727 DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
18728 return 1;
18729 }
18730 /* must not reach here */
18731 DEBUG_ASSERT(0);
18732 return 0;
18733}
18734
18735#else /* ALTERNATIVE_QUEUE */
18736
18737/* Worker threads take accepted socket from the queue */
18738static int
18739consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
18740{
18741 (void)thread_index;
18742
18743 (void)pthread_mutex_lock(&ctx->thread_mutex);
18744 DEBUG_TRACE("%s", "going idle");
18745
18746 /* If the queue is empty, wait. We're idle at this point. */
18747 while ((ctx->sq_head == ctx->sq_tail)
18748 && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
18749 pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
18750 }
18751
18752 /* If we're stopping, sq_head may be equal to sq_tail. */
18753 if (ctx->sq_head > ctx->sq_tail) {
18754 /* Copy socket from the queue and increment tail */
18755 *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
18756 ctx->sq_tail++;
18757
18758 DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
18759
18760 /* Wrap pointers if needed */
18761 while (ctx->sq_tail > ctx->sq_size) {
18762 ctx->sq_tail -= ctx->sq_size;
18763 ctx->sq_head -= ctx->sq_size;
18764 }
18765 }
18766
18767 (void)pthread_cond_signal(&ctx->sq_empty);
18768 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18769
18770 return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
18771}
18772
18773
18774/* Master thread adds accepted socket to a queue */
18775static void
18776produce_socket(struct mg_context *ctx, const struct socket *sp)
18777{
18778 int queue_filled;
18779
18780 (void)pthread_mutex_lock(&ctx->thread_mutex);
18781
18782 queue_filled = ctx->sq_head - ctx->sq_tail;
18783
18784 /* If the queue is full, wait */
18785 while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
18786 && (queue_filled >= ctx->sq_size)) {
18787 ctx->sq_blocked = 1; /* Status information: All threads busy */
18788#if defined(USE_SERVER_STATS)
18789 if (queue_filled > ctx->sq_max_fill) {
18790 ctx->sq_max_fill = queue_filled;
18791 }
18792#endif
18793 (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
18794 ctx->sq_blocked = 0; /* Not blocked now */
18795 queue_filled = ctx->sq_head - ctx->sq_tail;
18796 }
18797
18798 if (queue_filled < ctx->sq_size) {
18799 /* Copy socket to the queue and increment head */
18800 ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
18801 ctx->sq_head++;
18802 DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
18803 }
18804
18805 queue_filled = ctx->sq_head - ctx->sq_tail;
18806#if defined(USE_SERVER_STATS)
18807 if (queue_filled > ctx->sq_max_fill) {
18808 ctx->sq_max_fill = queue_filled;
18809 }
18810#endif
18811
18812 (void)pthread_cond_signal(&ctx->sq_full);
18813 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18814}
18815#endif /* ALTERNATIVE_QUEUE */
18816
18817
18818static void
18820{
18821 struct mg_context *ctx = conn->phys_ctx;
18822 int thread_index;
18823 struct mg_workerTLS tls;
18824
18825 mg_set_thread_name("worker");
18826
18827 tls.is_master = 0;
18828 tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
18829#if defined(_WIN32)
18830 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
18831#endif
18832
18833 /* Initialize thread local storage before calling any callback */
18834 pthread_setspecific(sTlsKey, &tls);
18835
18836 /* Check if there is a user callback */
18837 if (ctx->callbacks.init_thread) {
18838 /* call init_thread for a worker thread (type 1), and store the
18839 * return value */
18840 tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
18841 } else {
18842 /* No callback: set user pointer to NULL */
18843 tls.user_ptr = NULL;
18844 }
18845
18846 /* Connection structure has been pre-allocated */
18847 thread_index = (int)(conn - ctx->worker_connections);
18848 if ((thread_index < 0)
18849 || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
18851 "Internal error: Invalid worker index %i",
18852 thread_index);
18853 return;
18854 }
18855
18856 /* Request buffers are not pre-allocated. They are private to the
18857 * request and do not contain any state information that might be
18858 * of interest to anyone observing a server status. */
18859 conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
18860 if (conn->buf == NULL) {
18862 ctx,
18863 "Out of memory: Cannot allocate buffer for worker %i",
18864 thread_index);
18865 return;
18866 }
18867 conn->buf_size = (int)ctx->max_request_size;
18868
18869 conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
18870
18871 conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
18872
18873 conn->request_info.user_data = ctx->user_data;
18874 /* Allocate a mutex for this connection to allow communication both
18875 * within the request handler and from elsewhere in the application
18876 */
18877 if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
18878 mg_free(conn->buf);
18879 mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
18880 return;
18881 }
18882
18883#if defined(USE_SERVER_STATS)
18884 conn->conn_state = 1; /* not consumed */
18885#endif
18886
18887 /* Call consume_socket() even when ctx->stop_flag > 0, to let it
18888 * signal sq_empty condvar to wake up the master waiting in
18889 * produce_socket() */
18890 while (consume_socket(ctx, &conn->client, thread_index)) {
18891
18892 /* New connections must start with new protocol negotiation */
18893 tls.alpn_proto = NULL;
18894
18895#if defined(USE_SERVER_STATS)
18896 conn->conn_close_time = 0;
18897#endif
18898 conn->conn_birth_time = time(NULL);
18899
18900 /* Fill in IP, port info early so even if SSL setup below fails,
18901 * error handler would have the corresponding info.
18902 * Thanks to Johannes Winkelmann for the patch.
18903 */
18905 ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
18906
18908 ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
18909
18911 sizeof(conn->request_info.remote_addr),
18912 &conn->client.rsa);
18913
18914 DEBUG_TRACE("Incomming %sconnection from %s",
18915 (conn->client.is_ssl ? "SSL " : ""),
18917
18918 conn->request_info.is_ssl = conn->client.is_ssl;
18919
18920 if (conn->client.is_ssl) {
18921
18922#if defined(USE_MBEDTLS)
18923 /* HTTPS connection */
18924 if (mbed_ssl_accept(&(conn->ssl),
18925 conn->dom_ctx->ssl_ctx,
18926 (int *)&(conn->client.sock),
18927 conn->phys_ctx)
18928 == 0) {
18929 /* conn->dom_ctx is set in get_request */
18930 /* process HTTPS connection */
18931 init_connection(conn);
18935 } else {
18936 /* make sure the connection is cleaned up on SSL failure */
18937 close_connection(conn);
18938 }
18939
18940#elif !defined(NO_SSL)
18941 /* HTTPS connection */
18942 if (sslize(conn, SSL_accept, NULL)) {
18943 /* conn->dom_ctx is set in get_request */
18944
18945 /* Get SSL client certificate information (if set) */
18946 struct mg_client_cert client_cert;
18947 if (ssl_get_client_cert_info(conn, &client_cert)) {
18948 conn->request_info.client_cert = &client_cert;
18949 }
18950
18951 /* process HTTPS connection */
18952#if defined(USE_HTTP2)
18953 if ((tls.alpn_proto != NULL)
18954 && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
18955 /* process HTTPS/2 connection */
18956 init_connection(conn);
18959 conn->content_len =
18960 -1; /* content length is not predefined */
18961 conn->is_chunked = 0; /* HTTP2 is never chunked */
18962 process_new_http2_connection(conn);
18963 } else
18964#endif
18965 {
18966 /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
18967 init_connection(conn);
18969 /* Start with HTTP, WS will be an "upgrade" request later */
18972 }
18973
18974 /* Free client certificate info */
18975 if (conn->request_info.client_cert) {
18976 mg_free((void *)(conn->request_info.client_cert->subject));
18977 mg_free((void *)(conn->request_info.client_cert->issuer));
18978 mg_free((void *)(conn->request_info.client_cert->serial));
18979 mg_free((void *)(conn->request_info.client_cert->finger));
18980 /* Free certificate memory */
18981 X509_free(
18984 conn->request_info.client_cert->subject = 0;
18985 conn->request_info.client_cert->issuer = 0;
18986 conn->request_info.client_cert->serial = 0;
18987 conn->request_info.client_cert->finger = 0;
18988 conn->request_info.client_cert = 0;
18989 }
18990 } else {
18991 /* make sure the connection is cleaned up on SSL failure */
18992 close_connection(conn);
18993 }
18994#endif
18995
18996 } else {
18997 /* process HTTP connection */
18998 init_connection(conn);
19000 /* Start with HTTP, WS will be an "upgrade" request later */
19003 }
19004
19005 DEBUG_TRACE("%s", "Connection closed");
19006
19007#if defined(USE_SERVER_STATS)
19008 conn->conn_close_time = time(NULL);
19009#endif
19010 }
19011
19012 /* Call exit thread user callback */
19013 if (ctx->callbacks.exit_thread) {
19014 ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
19015 }
19016
19017 /* delete thread local storage objects */
19018 pthread_setspecific(sTlsKey, NULL);
19019#if defined(_WIN32)
19020 CloseHandle(tls.pthread_cond_helper_mutex);
19021#endif
19022 pthread_mutex_destroy(&conn->mutex);
19023
19024 /* Free the request buffer. */
19025 conn->buf_size = 0;
19026 mg_free(conn->buf);
19027 conn->buf = NULL;
19028
19029 /* Free cleaned URI (if any) */
19030 if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
19031 mg_free((void *)conn->request_info.local_uri);
19032 conn->request_info.local_uri = NULL;
19033 }
19034
19035#if defined(USE_SERVER_STATS)
19036 conn->conn_state = 9; /* done */
19037#endif
19038
19039 DEBUG_TRACE("%s", "exiting");
19040}
19041
19042
19043/* Threads have different return types on Windows and Unix. */
19044#if defined(_WIN32)
19045static unsigned __stdcall worker_thread(void *thread_func_param)
19046{
19047 worker_thread_run((struct mg_connection *)thread_func_param);
19048 return 0;
19049}
19050#else
19051static void *
19052worker_thread(void *thread_func_param)
19053{
19054#if !defined(__ZEPHYR__)
19055 struct sigaction sa;
19056
19057 /* Ignore SIGPIPE */
19058 memset(&sa, 0, sizeof(sa));
19059 sa.sa_handler = SIG_IGN;
19060 sigaction(SIGPIPE, &sa, NULL);
19061#endif
19062
19063 worker_thread_run((struct mg_connection *)thread_func_param);
19064 return NULL;
19065}
19066#endif /* _WIN32 */
19067
19068
19069/* This is an internal function, thus all arguments are expected to be
19070 * valid - a NULL check is not required. */
19071static void
19072accept_new_connection(const struct socket *listener, struct mg_context *ctx)
19073{
19074 struct socket so;
19075 char src_addr[IP_ADDR_STR_LEN];
19076 socklen_t len = sizeof(so.rsa);
19077#if !defined(__ZEPHYR__)
19078 int on = 1;
19079#endif
19080 memset(&so, 0, sizeof(so));
19081
19082 if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
19083 == INVALID_SOCKET) {
19084 } else if (check_acl(ctx, &so.rsa) != 1) {
19085 sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
19087 "%s: %s is not allowed to connect",
19088 __func__,
19089 src_addr);
19090 closesocket(so.sock);
19091 } else {
19092 /* Put so socket structure into the queue */
19093 DEBUG_TRACE("Accepted socket %d", (int)so.sock);
19094 set_close_on_exec(so.sock, NULL, ctx);
19095 so.is_ssl = listener->is_ssl;
19096 so.ssl_redir = listener->ssl_redir;
19097 if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
19099 "%s: getsockname() failed: %s",
19100 __func__,
19101 strerror(ERRNO));
19102 }
19103
19104#if !defined(__ZEPHYR__)
19105 if ((so.lsa.sa.sa_family == AF_INET)
19106 || (so.lsa.sa.sa_family == AF_INET6)) {
19107 /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
19108 * This is needed because if HTTP-level keep-alive
19109 * is enabled, and client resets the connection, server won't get
19110 * TCP FIN or RST and will keep the connection open forever. With
19111 * TCP keep-alive, next keep-alive handshake will figure out that
19112 * the client is down and will close the server end.
19113 * Thanks to Igor Klopov who suggested the patch. */
19114 if (setsockopt(so.sock,
19115 SOL_SOCKET,
19116 SO_KEEPALIVE,
19117 (SOCK_OPT_TYPE)&on,
19118 sizeof(on))
19119 != 0) {
19121 ctx,
19122 "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
19123 __func__,
19124 strerror(ERRNO));
19125 }
19126 }
19127#endif
19128
19129 /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
19130 * to effectively fill up the underlying IP packet payload and
19131 * reduce the overhead of sending lots of small buffers. However
19132 * this hurts the server's throughput (ie. operations per second)
19133 * when HTTP 1.1 persistent connections are used and the responses
19134 * are relatively small (eg. less than 1400 bytes).
19135 */
19136 if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
19137 && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
19138 if (set_tcp_nodelay(&so, 1) != 0) {
19140 ctx,
19141 "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
19142 __func__,
19143 strerror(ERRNO));
19144 }
19145 }
19146
19147 /* The "non blocking" property should already be
19148 * inherited from the parent socket. Set it for
19149 * non-compliant socket implementations. */
19151
19152 so.in_use = 0;
19153 produce_socket(ctx, &so);
19154 }
19155}
19156
19157
19158static void
19160{
19161 struct mg_workerTLS tls;
19162 struct mg_pollfd *pfd;
19163 unsigned int i;
19164 unsigned int workerthreadcount;
19165
19166 if (!ctx) {
19167 return;
19168 }
19169
19170 mg_set_thread_name("master");
19171
19172 /* Increase priority of the master thread */
19173#if defined(_WIN32)
19174 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
19175#elif defined(USE_MASTER_THREAD_PRIORITY)
19176 int min_prio = sched_get_priority_min(SCHED_RR);
19177 int max_prio = sched_get_priority_max(SCHED_RR);
19178 if ((min_prio >= 0) && (max_prio >= 0)
19179 && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
19180 && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
19181 struct sched_param sched_param = {0};
19182 sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
19183 pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
19184 }
19185#endif
19186
19187 /* Initialize thread local storage */
19188#if defined(_WIN32)
19189 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
19190#endif
19191 tls.is_master = 1;
19192 pthread_setspecific(sTlsKey, &tls);
19193
19194 if (ctx->callbacks.init_thread) {
19195 /* Callback for the master thread (type 0) */
19196 tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
19197 } else {
19198 tls.user_ptr = NULL;
19199 }
19200
19201 /* Lua background script "start" event */
19202#if defined(USE_LUA)
19203 if (ctx->lua_background_state) {
19204 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19205 pthread_mutex_lock(&ctx->lua_bg_mutex);
19206
19207 /* call "start()" in Lua */
19208 lua_getglobal(lstate, "start");
19209 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19210 int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
19211 if (ret != 0) {
19212 struct mg_connection fc;
19213 lua_cry(fake_connection(&fc, ctx),
19214 ret,
19215 lstate,
19216 "lua_background_script",
19217 "start");
19218 }
19219 } else {
19220 lua_pop(lstate, 1);
19221 }
19222
19223 /* determine if there is a "log()" function in Lua background script */
19224 lua_getglobal(lstate, "log");
19225 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19226 ctx->lua_bg_log_available = 1;
19227 }
19228 lua_pop(lstate, 1);
19229
19230 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19231 }
19232#endif
19233
19234 /* Server starts *now* */
19235 ctx->start_time = time(NULL);
19236
19237 /* Server accept loop */
19238 pfd = ctx->listening_socket_fds;
19239 while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
19240 for (i = 0; i < ctx->num_listening_sockets; i++) {
19241 pfd[i].fd = ctx->listening_sockets[i].sock;
19242 pfd[i].events = POLLIN;
19243 }
19244
19245 if (mg_poll(pfd,
19248 &(ctx->stop_flag))
19249 > 0) {
19250 for (i = 0; i < ctx->num_listening_sockets; i++) {
19251 /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
19252 * successful poll, and POLLIN is defined as
19253 * (POLLRDNORM | POLLRDBAND)
19254 * Therefore, we're checking pfd[i].revents & POLLIN, not
19255 * pfd[i].revents == POLLIN. */
19256 if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
19257 && (pfd[i].revents & POLLIN)) {
19259 }
19260 }
19261 }
19262 }
19263
19264 /* Here stop_flag is 1 - Initiate shutdown. */
19265 DEBUG_TRACE("%s", "stopping workers");
19266
19267 /* Stop signal received: somebody called mg_stop. Quit. */
19269
19270 /* Wakeup workers that are waiting for connections to handle. */
19271#if defined(ALTERNATIVE_QUEUE)
19272 for (i = 0; i < ctx->cfg_worker_threads; i++) {
19273 event_signal(ctx->client_wait_events[i]);
19274 }
19275#else
19276 (void)pthread_mutex_lock(&ctx->thread_mutex);
19277 pthread_cond_broadcast(&ctx->sq_full);
19278 (void)pthread_mutex_unlock(&ctx->thread_mutex);
19279#endif
19280
19281 /* Join all worker threads to avoid leaking threads. */
19282 workerthreadcount = ctx->cfg_worker_threads;
19283 for (i = 0; i < workerthreadcount; i++) {
19284 if (ctx->worker_threadids[i] != 0) {
19286 }
19287 }
19288
19289#if defined(USE_LUA)
19290 /* Free Lua state of lua background task */
19291 if (ctx->lua_background_state) {
19292 lua_State *lstate = (lua_State *)ctx->lua_background_state;
19293 ctx->lua_bg_log_available = 0;
19294
19295 /* call "stop()" in Lua */
19296 pthread_mutex_lock(&ctx->lua_bg_mutex);
19297 lua_getglobal(lstate, "stop");
19298 if (lua_type(lstate, -1) == LUA_TFUNCTION) {
19299 int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
19300 if (ret != 0) {
19301 struct mg_connection fc;
19302 lua_cry(fake_connection(&fc, ctx),
19303 ret,
19304 lstate,
19305 "lua_background_script",
19306 "stop");
19307 }
19308 }
19309 lua_close(lstate);
19310
19311 ctx->lua_background_state = 0;
19312 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19313 }
19314#endif
19315
19316 DEBUG_TRACE("%s", "exiting");
19317
19318 /* call exit thread callback */
19319 if (ctx->callbacks.exit_thread) {
19320 /* Callback for the master thread (type 0) */
19321 ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
19322 }
19323
19324#if defined(_WIN32)
19325 CloseHandle(tls.pthread_cond_helper_mutex);
19326#endif
19327 pthread_setspecific(sTlsKey, NULL);
19328
19329 /* Signal mg_stop() that we're done.
19330 * WARNING: This must be the very last thing this
19331 * thread does, as ctx becomes invalid after this line. */
19332 STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
19333}
19334
19335
19336/* Threads have different return types on Windows and Unix. */
19337#if defined(_WIN32)
19338static unsigned __stdcall master_thread(void *thread_func_param)
19339{
19340 master_thread_run((struct mg_context *)thread_func_param);
19341 return 0;
19342}
19343#else
19344static void *
19345master_thread(void *thread_func_param)
19346{
19347#if !defined(__ZEPHYR__)
19348 struct sigaction sa;
19349
19350 /* Ignore SIGPIPE */
19351 memset(&sa, 0, sizeof(sa));
19352 sa.sa_handler = SIG_IGN;
19353 sigaction(SIGPIPE, &sa, NULL);
19354#endif
19355
19356 master_thread_run((struct mg_context *)thread_func_param);
19357 return NULL;
19358}
19359#endif /* _WIN32 */
19360
19361
19362static void
19364{
19365 int i;
19366 struct mg_handler_info *tmp_rh;
19367
19368 if (ctx == NULL) {
19369 return;
19370 }
19371
19372 /* Call user callback */
19373 if (ctx->callbacks.exit_context) {
19374 ctx->callbacks.exit_context(ctx);
19375 }
19376
19377 /* All threads exited, no sync is needed. Destroy thread mutex and
19378 * condvars
19379 */
19380 (void)pthread_mutex_destroy(&ctx->thread_mutex);
19381
19382#if defined(ALTERNATIVE_QUEUE)
19383 mg_free(ctx->client_socks);
19384 if (ctx->client_wait_events != NULL) {
19385 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
19386 event_destroy(ctx->client_wait_events[i]);
19387 }
19388 mg_free(ctx->client_wait_events);
19389 }
19390#else
19391 (void)pthread_cond_destroy(&ctx->sq_empty);
19392 (void)pthread_cond_destroy(&ctx->sq_full);
19393 mg_free(ctx->squeue);
19394#endif
19395
19396 /* Destroy other context global data structures mutex */
19397 (void)pthread_mutex_destroy(&ctx->nonce_mutex);
19398
19399#if defined(USE_LUA)
19400 (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
19401#endif
19402
19403 /* Deallocate config parameters */
19404 for (i = 0; i < NUM_OPTIONS; i++) {
19405 if (ctx->dd.config[i] != NULL) {
19406#if defined(_MSC_VER)
19407#pragma warning(suppress : 6001)
19408#endif
19409 mg_free(ctx->dd.config[i]);
19410 }
19411 }
19412
19413 /* Deallocate request handlers */
19414 while (ctx->dd.handlers) {
19415 tmp_rh = ctx->dd.handlers;
19416 ctx->dd.handlers = tmp_rh->next;
19417 mg_free(tmp_rh->uri);
19418 mg_free(tmp_rh);
19419 }
19420
19421#if defined(USE_MBEDTLS)
19422 if (ctx->dd.ssl_ctx != NULL) {
19423 mbed_sslctx_uninit(ctx->dd.ssl_ctx);
19424 mg_free(ctx->dd.ssl_ctx);
19425 ctx->dd.ssl_ctx = NULL;
19426 }
19427
19428#elif !defined(NO_SSL)
19429 /* Deallocate SSL context */
19430 if (ctx->dd.ssl_ctx != NULL) {
19431 void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
19432 int callback_ret =
19433 (ctx->callbacks.external_ssl_ctx == NULL)
19434 ? 0
19435 : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
19436
19437 if (callback_ret == 0) {
19438 SSL_CTX_free(ctx->dd.ssl_ctx);
19439 }
19440 /* else: ignore error and ommit SSL_CTX_free in case
19441 * callback_ret is 1 */
19442 }
19443#endif /* !NO_SSL */
19444
19445 /* Deallocate worker thread ID array */
19447
19448 /* Deallocate worker thread ID array */
19450
19451 /* deallocate system name string */
19452 mg_free(ctx->systemName);
19453
19454 /* Deallocate context itself */
19455 mg_free(ctx);
19456}
19457
19458
19459void
19461{
19462 pthread_t mt;
19463 if (!ctx) {
19464 return;
19465 }
19466
19467 /* We don't use a lock here. Calling mg_stop with the same ctx from
19468 * two threads is not allowed. */
19469 mt = ctx->masterthreadid;
19470 if (mt == 0) {
19471 return;
19472 }
19473
19474 ctx->masterthreadid = 0;
19475
19476 /* Set stop flag, so all threads know they have to exit. */
19477 STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
19478
19479 /* Join timer thread */
19480#if defined(USE_TIMERS)
19481 timers_exit(ctx);
19482#endif
19483
19484 /* Wait until everything has stopped. */
19485 while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
19486 (void)mg_sleep(10);
19487 }
19488
19489 /* Wait to stop master thread */
19490 mg_join_thread(mt);
19491
19492 /* Close remaining Lua states */
19493#if defined(USE_LUA)
19494 lua_ctx_exit(ctx);
19495#endif
19496
19497 /* Free memory */
19498 free_context(ctx);
19499}
19500
19501
19502static void
19503get_system_name(char **sysName)
19504{
19505#if defined(_WIN32)
19506 char name[128];
19507 DWORD dwVersion = 0;
19508 DWORD dwMajorVersion = 0;
19509 DWORD dwMinorVersion = 0;
19510 DWORD dwBuild = 0;
19511 BOOL wowRet, isWoW = FALSE;
19512
19513#if defined(_MSC_VER)
19514#pragma warning(push)
19515 /* GetVersion was declared deprecated */
19516#pragma warning(disable : 4996)
19517#endif
19518 dwVersion = GetVersion();
19519#if defined(_MSC_VER)
19520#pragma warning(pop)
19521#endif
19522
19523 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
19524 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
19525 dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
19526 (void)dwBuild;
19527
19528 wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
19529
19530 sprintf(name,
19531 "Windows %u.%u%s",
19532 (unsigned)dwMajorVersion,
19533 (unsigned)dwMinorVersion,
19534 (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
19535
19536 *sysName = mg_strdup(name);
19537
19538
19539#elif defined(__ZEPHYR__)
19540 *sysName = mg_strdup("Zephyr OS");
19541#else
19542 struct utsname name;
19543 memset(&name, 0, sizeof(name));
19544 uname(&name);
19545 *sysName = mg_strdup(name.sysname);
19546#endif
19547}
19548
19549
19550static void
19551legacy_init(const char **options)
19552{
19553 const char *ports_option = config_options[LISTENING_PORTS].default_value;
19554
19555 if (options) {
19556 const char **run_options = options;
19557 const char *optname = config_options[LISTENING_PORTS].name;
19558
19559 /* Try to find the "listening_ports" option */
19560 while (*run_options) {
19561 if (!strcmp(*run_options, optname)) {
19562 ports_option = run_options[1];
19563 }
19564 run_options += 2;
19565 }
19566 }
19567
19568 if (is_ssl_port_used(ports_option)) {
19569 /* Initialize with SSL support */
19571 } else {
19572 /* Initialize without SSL support */
19574 }
19575}
19576
19577
19578struct mg_context *
19579mg_start2(struct mg_init_data *init, struct mg_error_data *error)
19580{
19581 struct mg_context *ctx;
19582 const char *name, *value, *default_value;
19583 int idx, ok, workerthreadcount;
19584 unsigned int i;
19585 int itmp;
19586 void (*exit_callback)(const struct mg_context *ctx) = 0;
19587 const char **options =
19588 ((init != NULL) ? (init->configuration_options) : (NULL));
19589
19590 struct mg_workerTLS tls;
19591
19592 if (error != NULL) {
19593 error->code = 0;
19594 if (error->text_buffer_size > 0) {
19595 *error->text = 0;
19596 }
19597 }
19598
19599 if (mg_init_library_called == 0) {
19600 /* Legacy INIT, if mg_start is called without mg_init_library.
19601 * Note: This will cause a memory leak when unloading the library.
19602 */
19603 legacy_init(options);
19604 }
19605 if (mg_init_library_called == 0) {
19606 if ((error != NULL) && (error->text_buffer_size > 0)) {
19607 mg_snprintf(NULL,
19608 NULL, /* No truncation check for error buffers */
19609 error->text,
19610 error->text_buffer_size,
19611 "%s",
19612 "Library uninitialized");
19613 }
19614 return NULL;
19615 }
19616
19617 /* Allocate context and initialize reasonable general case defaults. */
19618 if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
19619 if ((error != NULL) && (error->text_buffer_size > 0)) {
19620 mg_snprintf(NULL,
19621 NULL, /* No truncation check for error buffers */
19622 error->text,
19623 error->text_buffer_size,
19624 "%s",
19625 "Out of memory");
19626 }
19627 return NULL;
19628 }
19629
19630 /* Random number generator will initialize at the first call */
19631 ctx->dd.auth_nonce_mask =
19632 (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
19633
19634 /* Save started thread index to reuse in other external API calls
19635 * For the sake of thread synchronization all non-civetweb threads
19636 * can be considered as single external thread */
19638 tls.is_master = -1; /* Thread calling mg_start */
19639 tls.thread_idx = ctx->starter_thread_idx;
19640#if defined(_WIN32)
19641 tls.pthread_cond_helper_mutex = NULL;
19642#endif
19643 pthread_setspecific(sTlsKey, &tls);
19644
19645 ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
19646#if !defined(ALTERNATIVE_QUEUE)
19647 ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
19648 ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
19649 ctx->sq_blocked = 0;
19650#endif
19651 ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
19652#if defined(USE_LUA)
19653 ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
19654#endif
19655 if (!ok) {
19656 const char *err_msg =
19657 "Cannot initialize thread synchronization objects";
19658 /* Fatal error - abort start. However, this situation should never
19659 * occur in practice. */
19660
19661 mg_cry_ctx_internal(ctx, "%s", err_msg);
19662 if ((error != NULL) && (error->text_buffer_size > 0)) {
19663 mg_snprintf(NULL,
19664 NULL, /* No truncation check for error buffers */
19665 error->text,
19666 error->text_buffer_size,
19667 "%s",
19668 err_msg);
19669 }
19670
19671 mg_free(ctx);
19672 pthread_setspecific(sTlsKey, NULL);
19673 return NULL;
19674 }
19675
19676 if ((init != NULL) && (init->callbacks != NULL)) {
19677 /* Set all callbacks except exit_context. */
19678 ctx->callbacks = *init->callbacks;
19679 exit_callback = init->callbacks->exit_context;
19680 /* The exit callback is activated once the context is successfully
19681 * created. It should not be called, if an incomplete context object
19682 * is deleted during a failed initialization. */
19683 ctx->callbacks.exit_context = 0;
19684 }
19685 ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
19686 ctx->dd.handlers = NULL;
19687 ctx->dd.next = NULL;
19688
19689#if defined(USE_LUA)
19690 lua_ctx_init(ctx);
19691#endif
19692
19693 /* Store options */
19694 while (options && (name = *options++) != NULL) {
19695 if ((idx = get_option_index(name)) == -1) {
19696 mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
19697 if ((error != NULL) && (error->text_buffer_size > 0)) {
19698 mg_snprintf(NULL,
19699 NULL, /* No truncation check for error buffers */
19700 error->text,
19701 error->text_buffer_size,
19702 "Invalid configuration option: %s",
19703 name);
19704 }
19705 free_context(ctx);
19706 pthread_setspecific(sTlsKey, NULL);
19707 return NULL;
19708 } else if ((value = *options++) == NULL) {
19709 mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
19710 if ((error != NULL) && (error->text_buffer_size > 0)) {
19711 mg_snprintf(NULL,
19712 NULL, /* No truncation check for error buffers */
19713 error->text,
19714 error->text_buffer_size,
19715 "Invalid configuration option value: %s",
19716 name);
19717 }
19718 free_context(ctx);
19719 pthread_setspecific(sTlsKey, NULL);
19720 return NULL;
19721 }
19722 if (ctx->dd.config[idx] != NULL) {
19723 /* A duplicate configuration option is not an error - the last
19724 * option value will be used. */
19725 mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
19726 mg_free(ctx->dd.config[idx]);
19727 }
19728 ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
19729 DEBUG_TRACE("[%s] -> [%s]", name, value);
19730 }
19731
19732 /* Set default value if needed */
19733 for (i = 0; config_options[i].name != NULL; i++) {
19734 default_value = config_options[i].default_value;
19735 if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
19736 ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
19737 }
19738 }
19739
19740 /* Request size option */
19741 itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
19742 if (itmp < 1024) {
19744 "%s too small",
19746 if ((error != NULL) && (error->text_buffer_size > 0)) {
19747 mg_snprintf(NULL,
19748 NULL, /* No truncation check for error buffers */
19749 error->text,
19750 error->text_buffer_size,
19751 "Invalid configuration option value: %s",
19753 }
19754 free_context(ctx);
19755 pthread_setspecific(sTlsKey, NULL);
19756 return NULL;
19757 }
19758 ctx->max_request_size = (unsigned)itmp;
19759
19760 /* Queue length */
19761#if !defined(ALTERNATIVE_QUEUE)
19762 itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
19763 if (itmp < 1) {
19765 "%s too small",
19767 if ((error != NULL) && (error->text_buffer_size > 0)) {
19768 mg_snprintf(NULL,
19769 NULL, /* No truncation check for error buffers */
19770 error->text,
19771 error->text_buffer_size,
19772 "Invalid configuration option value: %s",
19774 }
19775 free_context(ctx);
19776 pthread_setspecific(sTlsKey, NULL);
19777 return NULL;
19778 }
19779 ctx->squeue =
19780 (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
19781 if (ctx->squeue == NULL) {
19783 "Out of memory: Cannot allocate %s",
19785 if ((error != NULL) && (error->text_buffer_size > 0)) {
19786 mg_snprintf(NULL,
19787 NULL, /* No truncation check for error buffers */
19788 error->text,
19789 error->text_buffer_size,
19790 "Out of memory: Cannot allocate %s",
19792 }
19793 free_context(ctx);
19794 pthread_setspecific(sTlsKey, NULL);
19795 return NULL;
19796 }
19797 ctx->sq_size = itmp;
19798#endif
19799
19800 /* Worker thread count option */
19801 workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
19802
19803 if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
19804 if (workerthreadcount <= 0) {
19805 mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
19806 } else {
19807 mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
19808 }
19809 if ((error != NULL) && (error->text_buffer_size > 0)) {
19810 mg_snprintf(NULL,
19811 NULL, /* No truncation check for error buffers */
19812 error->text,
19813 error->text_buffer_size,
19814 "Invalid configuration option value: %s",
19816 }
19817 free_context(ctx);
19818 pthread_setspecific(sTlsKey, NULL);
19819 return NULL;
19820 }
19821
19822 /* Document root */
19823#if defined(NO_FILES)
19824 if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
19825 mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
19826 if ((error != NULL) && (error->text_buffer_size > 0)) {
19827 mg_snprintf(NULL,
19828 NULL, /* No truncation check for error buffers */
19829 error->text,
19830 error->text_buffer_size,
19831 "Invalid configuration option value: %s",
19833 }
19834 free_context(ctx);
19835 pthread_setspecific(sTlsKey, NULL);
19836 return NULL;
19837 }
19838#endif
19839
19841
19842#if defined(USE_LUA)
19843 /* If a Lua background script has been configured, start it. */
19844 ctx->lua_bg_log_available = 0;
19845 if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
19846 char ebuf[256];
19847 struct vec opt_vec;
19848 struct vec eq_vec;
19849 const char *sparams;
19850
19851 memset(ebuf, 0, sizeof(ebuf));
19852 pthread_mutex_lock(&ctx->lua_bg_mutex);
19853
19854 /* Create a Lua state, load all standard libraries and the mg table */
19855 lua_State *state = mg_lua_context_script_prepare(
19856 ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
19857 if (!state) {
19859 "lua_background_script load error: %s",
19860 ebuf);
19861 if ((error != NULL) && (error->text_buffer_size > 0)) {
19862 mg_snprintf(NULL,
19863 NULL, /* No truncation check for error buffers */
19864 error->text,
19865 error->text_buffer_size,
19866 "Error in script %s: %s",
19867 config_options[LUA_BACKGROUND_SCRIPT].name,
19868 ebuf);
19869 }
19870 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19871
19872 free_context(ctx);
19873 pthread_setspecific(sTlsKey, NULL);
19874 return NULL;
19875 }
19876
19877 /* Add a table with parameters into mg.params */
19878 sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
19879 if (sparams && sparams[0]) {
19880 lua_getglobal(state, "mg");
19881 lua_pushstring(state, "params");
19882 lua_newtable(state);
19883
19884 while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
19885 != NULL) {
19886 reg_llstring(
19887 state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
19888 if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
19889 break;
19890 }
19891 lua_rawset(state, -3);
19892 lua_pop(state, 1);
19893 }
19894
19895 /* Call script */
19896 state = mg_lua_context_script_run(state,
19897 ctx->dd.config[LUA_BACKGROUND_SCRIPT],
19898 ctx,
19899 ebuf,
19900 sizeof(ebuf));
19901 if (!state) {
19903 "lua_background_script start error: %s",
19904 ebuf);
19905 if ((error != NULL) && (error->text_buffer_size > 0)) {
19906 mg_snprintf(NULL,
19907 NULL, /* No truncation check for error buffers */
19908 error->text,
19909 error->text_buffer_size,
19910 "Error in script %s: %s",
19912 ebuf);
19913 }
19914 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19915
19916 free_context(ctx);
19917 pthread_setspecific(sTlsKey, NULL);
19918 return NULL;
19919 }
19920
19921 /* state remains valid */
19922 ctx->lua_background_state = (void *)state;
19923 pthread_mutex_unlock(&ctx->lua_bg_mutex);
19924
19925 } else {
19926 ctx->lua_background_state = 0;
19927 }
19928#endif
19929
19930 /* Step by step initialization of ctx - depending on build options */
19931#if !defined(NO_FILESYSTEMS)
19932 if (!set_gpass_option(ctx, NULL)) {
19933 const char *err_msg = "Invalid global password file";
19934 /* Fatal error - abort start. */
19935 mg_cry_ctx_internal(ctx, "%s", err_msg);
19936
19937 if ((error != NULL) && (error->text_buffer_size > 0)) {
19938 mg_snprintf(NULL,
19939 NULL, /* No truncation check for error buffers */
19940 error->text,
19941 error->text_buffer_size,
19942 "%s",
19943 err_msg);
19944 }
19945 free_context(ctx);
19946 pthread_setspecific(sTlsKey, NULL);
19947 return NULL;
19948 }
19949#endif
19950
19951#if defined(USE_MBEDTLS)
19952 if (!mg_sslctx_init(ctx, NULL)) {
19953 const char *err_msg = "Error initializing SSL context";
19954 /* Fatal error - abort start. */
19955 mg_cry_ctx_internal(ctx, "%s", err_msg);
19956
19957 if ((error != NULL) && (error->text_buffer_size > 0)) {
19958 mg_snprintf(NULL,
19959 NULL, /* No truncation check for error buffers */
19960 error->text,
19961 error->text_buffer_size,
19962 "%s",
19963 err_msg);
19964 }
19965 free_context(ctx);
19966 pthread_setspecific(sTlsKey, NULL);
19967 return NULL;
19968 }
19969
19970#elif !defined(NO_SSL)
19971 if (!init_ssl_ctx(ctx, NULL)) {
19972 const char *err_msg = "Error initializing SSL context";
19973 /* Fatal error - abort start. */
19974 mg_cry_ctx_internal(ctx, "%s", err_msg);
19975
19976 if ((error != NULL) && (error->text_buffer_size > 0)) {
19977 mg_snprintf(NULL,
19978 NULL, /* No truncation check for error buffers */
19979 error->text,
19980 error->text_buffer_size,
19981 "%s",
19982 err_msg);
19983 }
19984 free_context(ctx);
19985 pthread_setspecific(sTlsKey, NULL);
19986 return NULL;
19987 }
19988#endif
19989
19990 if (!set_ports_option(ctx)) {
19991 const char *err_msg = "Failed to setup server ports";
19992 /* Fatal error - abort start. */
19993 mg_cry_ctx_internal(ctx, "%s", err_msg);
19994
19995 if ((error != NULL) && (error->text_buffer_size > 0)) {
19996 mg_snprintf(NULL,
19997 NULL, /* No truncation check for error buffers */
19998 error->text,
19999 error->text_buffer_size,
20000 "%s",
20001 err_msg);
20002 }
20003 free_context(ctx);
20004 pthread_setspecific(sTlsKey, NULL);
20005 return NULL;
20006 }
20007
20008
20009#if !defined(_WIN32) && !defined(__ZEPHYR__)
20010 if (!set_uid_option(ctx)) {
20011 const char *err_msg = "Failed to run as configured user";
20012 /* Fatal error - abort start. */
20013 mg_cry_ctx_internal(ctx, "%s", err_msg);
20014
20015 if ((error != NULL) && (error->text_buffer_size > 0)) {
20016 mg_snprintf(NULL,
20017 NULL, /* No truncation check for error buffers */
20018 error->text,
20019 error->text_buffer_size,
20020 "%s",
20021 err_msg);
20022 }
20023 free_context(ctx);
20024 pthread_setspecific(sTlsKey, NULL);
20025 return NULL;
20026 }
20027#endif
20028
20029 if (!set_acl_option(ctx)) {
20030 const char *err_msg = "Failed to setup access control list";
20031 /* Fatal error - abort start. */
20032 mg_cry_ctx_internal(ctx, "%s", err_msg);
20033
20034 if ((error != NULL) && (error->text_buffer_size > 0)) {
20035 mg_snprintf(NULL,
20036 NULL, /* No truncation check for error buffers */
20037 error->text,
20038 error->text_buffer_size,
20039 "%s",
20040 err_msg);
20041 }
20042 free_context(ctx);
20043 pthread_setspecific(sTlsKey, NULL);
20044 return NULL;
20045 }
20046
20047 ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
20048 ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
20049 sizeof(pthread_t),
20050 ctx);
20051
20052 if (ctx->worker_threadids == NULL) {
20053 const char *err_msg = "Not enough memory for worker thread ID array";
20054 mg_cry_ctx_internal(ctx, "%s", err_msg);
20055
20056 if ((error != NULL) && (error->text_buffer_size > 0)) {
20057 mg_snprintf(NULL,
20058 NULL, /* No truncation check for error buffers */
20059 error->text,
20060 error->text_buffer_size,
20061 "%s",
20062 err_msg);
20063 }
20064 free_context(ctx);
20065 pthread_setspecific(sTlsKey, NULL);
20066 return NULL;
20067 }
20068 ctx->worker_connections =
20070 sizeof(struct mg_connection),
20071 ctx);
20072 if (ctx->worker_connections == NULL) {
20073 const char *err_msg =
20074 "Not enough memory for worker thread connection array";
20075 mg_cry_ctx_internal(ctx, "%s", err_msg);
20076
20077 if ((error != NULL) && (error->text_buffer_size > 0)) {
20078 mg_snprintf(NULL,
20079 NULL, /* No truncation check for error buffers */
20080 error->text,
20081 error->text_buffer_size,
20082 "%s",
20083 err_msg);
20084 }
20085 free_context(ctx);
20086 pthread_setspecific(sTlsKey, NULL);
20087 return NULL;
20088 }
20089
20090#if defined(ALTERNATIVE_QUEUE)
20091 ctx->client_wait_events =
20092 (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
20093 sizeof(ctx->client_wait_events[0]),
20094 ctx);
20095 if (ctx->client_wait_events == NULL) {
20096 const char *err_msg = "Not enough memory for worker event array";
20097 mg_cry_ctx_internal(ctx, "%s", err_msg);
20099
20100 if ((error != NULL) && (error->text_buffer_size > 0)) {
20101 mg_snprintf(NULL,
20102 NULL, /* No truncation check for error buffers */
20103 error->text,
20104 error->text_buffer_size,
20105 "%s",
20106 err_msg);
20107 }
20108 free_context(ctx);
20109 pthread_setspecific(sTlsKey, NULL);
20110 return NULL;
20111 }
20112
20113 ctx->client_socks =
20115 sizeof(ctx->client_socks[0]),
20116 ctx);
20117 if (ctx->client_socks == NULL) {
20118 const char *err_msg = "Not enough memory for worker socket array";
20119 mg_cry_ctx_internal(ctx, "%s", err_msg);
20120 mg_free(ctx->client_wait_events);
20122
20123 if ((error != NULL) && (error->text_buffer_size > 0)) {
20124 mg_snprintf(NULL,
20125 NULL, /* No truncation check for error buffers */
20126 error->text,
20127 error->text_buffer_size,
20128 "%s",
20129 err_msg);
20130 }
20131 free_context(ctx);
20132 pthread_setspecific(sTlsKey, NULL);
20133 return NULL;
20134 }
20135
20136 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
20137 ctx->client_wait_events[i] = event_create();
20138 if (ctx->client_wait_events[i] == 0) {
20139 const char *err_msg = "Error creating worker event %i";
20140 mg_cry_ctx_internal(ctx, err_msg, i);
20141 while (i > 0) {
20142 i--;
20143 event_destroy(ctx->client_wait_events[i]);
20144 }
20145 mg_free(ctx->client_socks);
20146 mg_free(ctx->client_wait_events);
20148
20149 if ((error != NULL) && (error->text_buffer_size > 0)) {
20150 mg_snprintf(NULL,
20151 NULL, /* No truncation check for error buffers */
20152 error->text,
20153 error->text_buffer_size,
20154 err_msg,
20155 i);
20156 }
20157 free_context(ctx);
20158 pthread_setspecific(sTlsKey, NULL);
20159 return NULL;
20160 }
20161 }
20162#endif
20163
20164#if defined(USE_TIMERS)
20165 if (timers_init(ctx) != 0) {
20166 const char *err_msg = "Error creating timers";
20167 mg_cry_ctx_internal(ctx, "%s", err_msg);
20168
20169 if ((error != NULL) && (error->text_buffer_size > 0)) {
20170 mg_snprintf(NULL,
20171 NULL, /* No truncation check for error buffers */
20172 error->text,
20173 error->text_buffer_size,
20174 "%s",
20175 err_msg);
20176 }
20177 free_context(ctx);
20178 pthread_setspecific(sTlsKey, NULL);
20179 return NULL;
20180 }
20181#endif
20182
20183 /* Context has been created - init user libraries */
20184 if (ctx->callbacks.init_context) {
20185 ctx->callbacks.init_context(ctx);
20186 }
20187
20188 /* From now, the context is successfully created.
20189 * When it is destroyed, the exit callback should be called. */
20190 ctx->callbacks.exit_context = exit_callback;
20191 ctx->context_type = CONTEXT_SERVER; /* server context */
20192
20193 /* Start worker threads */
20194 for (i = 0; i < ctx->cfg_worker_threads; i++) {
20195 /* worker_thread sets up the other fields */
20196 ctx->worker_connections[i].phys_ctx = ctx;
20198 &ctx->worker_connections[i],
20199 &ctx->worker_threadids[i])
20200 != 0) {
20201
20202 long error_no = (long)ERRNO;
20203
20204 /* thread was not created */
20205 if (i > 0) {
20206 /* If the second, third, ... thread cannot be created, set a
20207 * warning, but keep running. */
20209 "Cannot start worker thread %i: error %ld",
20210 i + 1,
20211 error_no);
20212
20213 /* If the server initialization should stop here, all
20214 * threads that have already been created must be stopped
20215 * first, before any free_context(ctx) call.
20216 */
20217
20218 } else {
20219 /* If the first worker thread cannot be created, stop
20220 * initialization and free the entire server context. */
20222 "Cannot create threads: error %ld",
20223 error_no);
20224
20225 if ((error != NULL) && (error->text_buffer_size > 0)) {
20227 NULL,
20228 NULL, /* No truncation check for error buffers */
20229 error->text,
20230 error->text_buffer_size,
20231 "Cannot create first worker thread: error %ld",
20232 error_no);
20233 }
20234 free_context(ctx);
20235 pthread_setspecific(sTlsKey, NULL);
20236 return NULL;
20237 }
20238 break;
20239 }
20240 }
20241
20242 /* Start master (listening) thread */
20244
20245 pthread_setspecific(sTlsKey, NULL);
20246 return ctx;
20247}
20248
20249
20250struct mg_context *
20252 void *user_data,
20253 const char **options)
20254{
20255 struct mg_init_data init = {0};
20256 init.callbacks = callbacks;
20257 init.user_data = user_data;
20258 init.configuration_options = options;
20259
20260 return mg_start2(&init, NULL);
20261}
20262
20263
20264/* Add an additional domain to an already running web server. */
20265int
20267 const char **options,
20268 struct mg_error_data *error)
20269{
20270 const char *name;
20271 const char *value;
20272 const char *default_value;
20273 struct mg_domain_context *new_dom;
20274 struct mg_domain_context *dom;
20275 int idx, i;
20276
20277 if (error != NULL) {
20278 error->code = 0;
20279 if (error->text_buffer_size > 0) {
20280 *error->text = 0;
20281 }
20282 }
20283
20284 if ((ctx == NULL) || (options == NULL)) {
20285 if ((error != NULL) && (error->text_buffer_size > 0)) {
20286 mg_snprintf(NULL,
20287 NULL, /* No truncation check for error buffers */
20288 error->text,
20289 error->text_buffer_size,
20290 "%s",
20291 "Invalid parameters");
20292 }
20293 return -1;
20294 }
20295
20296 if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
20297 if ((error != NULL) && (error->text_buffer_size > 0)) {
20298 mg_snprintf(NULL,
20299 NULL, /* No truncation check for error buffers */
20300 error->text,
20301 error->text_buffer_size,
20302 "%s",
20303 "Server already stopped");
20304 }
20305 return -1;
20306 }
20307
20308 new_dom = (struct mg_domain_context *)
20309 mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
20310
20311 if (!new_dom) {
20312 /* Out of memory */
20313 if ((error != NULL) && (error->text_buffer_size > 0)) {
20314 mg_snprintf(NULL,
20315 NULL, /* No truncation check for error buffers */
20316 error->text,
20317 error->text_buffer_size,
20318 "%s",
20319 "Out or memory");
20320 }
20321 return -6;
20322 }
20323
20324 /* Store options - TODO: unite duplicate code */
20325 while (options && (name = *options++) != NULL) {
20326 if ((idx = get_option_index(name)) == -1) {
20327 mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
20328 if ((error != NULL) && (error->text_buffer_size > 0)) {
20329 mg_snprintf(NULL,
20330 NULL, /* No truncation check for error buffers */
20331 error->text,
20332 error->text_buffer_size,
20333 "Invalid option: %s",
20334 name);
20335 }
20336 mg_free(new_dom);
20337 return -2;
20338 } else if ((value = *options++) == NULL) {
20339 mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
20340 if ((error != NULL) && (error->text_buffer_size > 0)) {
20341 mg_snprintf(NULL,
20342 NULL, /* No truncation check for error buffers */
20343 error->text,
20344 error->text_buffer_size,
20345 "Invalid option value: %s",
20346 name);
20347 }
20348 mg_free(new_dom);
20349 return -2;
20350 }
20351 if (new_dom->config[idx] != NULL) {
20352 /* Duplicate option: Later values overwrite earlier ones. */
20353 mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
20354 mg_free(new_dom->config[idx]);
20355 }
20356 new_dom->config[idx] = mg_strdup_ctx(value, ctx);
20357 DEBUG_TRACE("[%s] -> [%s]", name, value);
20358 }
20359
20360 /* Authentication domain is mandatory */
20361 /* TODO: Maybe use a new option hostname? */
20362 if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
20363 mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
20364 if ((error != NULL) && (error->text_buffer_size > 0)) {
20365 mg_snprintf(NULL,
20366 NULL, /* No truncation check for error buffers */
20367 error->text,
20368 error->text_buffer_size,
20369 "Mandatory option %s missing",
20371 }
20372 mg_free(new_dom);
20373 return -4;
20374 }
20375
20376 /* Set default value if needed. Take the config value from
20377 * ctx as a default value. */
20378 for (i = 0; config_options[i].name != NULL; i++) {
20379 default_value = ctx->dd.config[i];
20380 if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
20381 new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
20382 }
20383 }
20384
20385 new_dom->handlers = NULL;
20386 new_dom->next = NULL;
20387 new_dom->nonce_count = 0;
20388 new_dom->auth_nonce_mask =
20389 (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
20390
20391#if defined(USE_LUA) && defined(USE_WEBSOCKET)
20392 new_dom->shared_lua_websockets = NULL;
20393#endif
20394
20395#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
20396 if (!init_ssl_ctx(ctx, new_dom)) {
20397 /* Init SSL failed */
20398 if ((error != NULL) && (error->text_buffer_size > 0)) {
20399 mg_snprintf(NULL,
20400 NULL, /* No truncation check for error buffers */
20401 error->text,
20402 error->text_buffer_size,
20403 "%s",
20404 "Initializing SSL context failed");
20405 }
20406 mg_free(new_dom);
20407 return -3;
20408 }
20409#endif
20410
20411 /* Add element to linked list. */
20412 mg_lock_context(ctx);
20413
20414 idx = 0;
20415 dom = &(ctx->dd);
20416 for (;;) {
20419 /* Domain collision */
20421 "domain %s already in use",
20422 new_dom->config[AUTHENTICATION_DOMAIN]);
20423 if ((error != NULL) && (error->text_buffer_size > 0)) {
20424 mg_snprintf(NULL,
20425 NULL, /* No truncation check for error buffers */
20426 error->text,
20427 error->text_buffer_size,
20428 "Domain %s specified by %s is already in use",
20429 new_dom->config[AUTHENTICATION_DOMAIN],
20431 }
20432 mg_free(new_dom);
20433 mg_unlock_context(ctx);
20434 return -5;
20435 }
20436
20437 /* Count number of domains */
20438 idx++;
20439
20440 if (dom->next == NULL) {
20441 dom->next = new_dom;
20442 break;
20443 }
20444 dom = dom->next;
20445 }
20446
20447 mg_unlock_context(ctx);
20448
20449 /* Return domain number */
20450 return idx;
20451}
20452
20453
20454int
20455mg_start_domain(struct mg_context *ctx, const char **options)
20456{
20457 return mg_start_domain2(ctx, options, NULL);
20458}
20459
20460
20461/* Feature check API function */
20462unsigned
20463mg_check_feature(unsigned feature)
20464{
20465 static const unsigned feature_set = 0
20466 /* Set bits for available features according to API documentation.
20467 * This bit mask is created at compile time, according to the active
20468 * preprocessor defines. It is a single const value at runtime. */
20469#if !defined(NO_FILES)
20471#endif
20472#if !defined(NO_SSL) || defined(USE_MBEDTLS)
20474#endif
20475#if !defined(NO_CGI)
20477#endif
20478#if defined(USE_IPV6)
20480#endif
20481#if defined(USE_WEBSOCKET)
20483#endif
20484#if defined(USE_LUA)
20486#endif
20487#if defined(USE_DUKTAPE)
20489#endif
20490#if !defined(NO_CACHING)
20492#endif
20493#if defined(USE_SERVER_STATS)
20495#endif
20496#if defined(USE_ZLIB)
20498#endif
20499#if defined(USE_HTTP2)
20501#endif
20502#if defined(USE_X_DOM_SOCKET)
20504#endif
20505
20506 /* Set some extra bits not defined in the API documentation.
20507 * These bits may change without further notice. */
20508#if defined(MG_LEGACY_INTERFACE)
20509 | 0x80000000u
20510#endif
20511#if defined(MG_EXPERIMENTAL_INTERFACES)
20512 | 0x40000000u
20513#endif
20514#if !defined(NO_RESPONSE_BUFFERING)
20515 | 0x20000000u
20516#endif
20517#if defined(MEMORY_DEBUGGING)
20518 | 0x10000000u
20519#endif
20520 ;
20521 return (feature & feature_set);
20522}
20523
20524
20525static size_t
20526mg_str_append(char **dst, char *end, const char *src)
20527{
20528 size_t len = strlen(src);
20529 if (*dst != end) {
20530 /* Append src if enough space, or close dst. */
20531 if ((size_t)(end - *dst) > len) {
20532 strcpy(*dst, src);
20533 *dst += len;
20534 } else {
20535 *dst = end;
20536 }
20537 }
20538 return len;
20539}
20540
20541
20542/* Get system information. It can be printed or stored by the caller.
20543 * Return the size of available information. */
20544int
20545mg_get_system_info(char *buffer, int buflen)
20546{
20547 char *end, *append_eoobj = NULL, block[256];
20548 size_t system_info_length = 0;
20549
20550#if defined(_WIN32)
20551 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
20552#else
20553 static const char eol[] = "\n", eoobj[] = "\n}\n";
20554#endif
20555
20556 if ((buffer == NULL) || (buflen < 1)) {
20557 buflen = 0;
20558 end = buffer;
20559 } else {
20560 *buffer = 0;
20561 end = buffer + buflen;
20562 }
20563 if (buflen > (int)(sizeof(eoobj) - 1)) {
20564 /* has enough space to append eoobj */
20565 append_eoobj = buffer;
20566 if (end) {
20567 end -= sizeof(eoobj) - 1;
20568 }
20569 }
20570
20571 system_info_length += mg_str_append(&buffer, end, "{");
20572
20573 /* Server version */
20574 {
20575 const char *version = mg_version();
20576 mg_snprintf(NULL,
20577 NULL,
20578 block,
20579 sizeof(block),
20580 "%s\"version\" : \"%s\"",
20581 eol,
20582 version);
20583 system_info_length += mg_str_append(&buffer, end, block);
20584 }
20585
20586 /* System info */
20587 {
20588#if defined(_WIN32)
20589 DWORD dwVersion = 0;
20590 DWORD dwMajorVersion = 0;
20591 DWORD dwMinorVersion = 0;
20592 SYSTEM_INFO si;
20593
20594 GetSystemInfo(&si);
20595
20596#if defined(_MSC_VER)
20597#pragma warning(push)
20598 /* GetVersion was declared deprecated */
20599#pragma warning(disable : 4996)
20600#endif
20601 dwVersion = GetVersion();
20602#if defined(_MSC_VER)
20603#pragma warning(pop)
20604#endif
20605
20606 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
20607 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
20608
20609 mg_snprintf(NULL,
20610 NULL,
20611 block,
20612 sizeof(block),
20613 ",%s\"os\" : \"Windows %u.%u\"",
20614 eol,
20615 (unsigned)dwMajorVersion,
20616 (unsigned)dwMinorVersion);
20617 system_info_length += mg_str_append(&buffer, end, block);
20618
20619 mg_snprintf(NULL,
20620 NULL,
20621 block,
20622 sizeof(block),
20623 ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
20624 eol,
20625 (unsigned)si.wProcessorArchitecture,
20626 (unsigned)si.dwNumberOfProcessors,
20627 (unsigned)si.dwActiveProcessorMask);
20628 system_info_length += mg_str_append(&buffer, end, block);
20629#elif defined(__ZEPHYR__)
20630 mg_snprintf(NULL,
20631 NULL,
20632 block,
20633 sizeof(block),
20634 ",%s\"os\" : \"%s %s\"",
20635 eol,
20636 "Zephyr OS",
20637 ZEPHYR_VERSION);
20638 system_info_length += mg_str_append(&buffer, end, block);
20639#else
20640 struct utsname name;
20641 memset(&name, 0, sizeof(name));
20642 uname(&name);
20643
20644 mg_snprintf(NULL,
20645 NULL,
20646 block,
20647 sizeof(block),
20648 ",%s\"os\" : \"%s %s (%s) - %s\"",
20649 eol,
20650 name.sysname,
20651 name.version,
20652 name.release,
20653 name.machine);
20654 system_info_length += mg_str_append(&buffer, end, block);
20655#endif
20656 }
20657
20658 /* Features */
20659 {
20660 mg_snprintf(NULL,
20661 NULL,
20662 block,
20663 sizeof(block),
20664 ",%s\"features\" : %lu"
20665 ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
20666 eol,
20667 (unsigned long)mg_check_feature(0xFFFFFFFFu),
20668 eol,
20669 mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
20670 mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
20671 mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
20672 mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
20674 : "",
20675 mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
20676 mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
20677 mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
20678 mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
20679 system_info_length += mg_str_append(&buffer, end, block);
20680
20681#if defined(USE_LUA)
20682 mg_snprintf(NULL,
20683 NULL,
20684 block,
20685 sizeof(block),
20686 ",%s\"lua_version\" : \"%u (%s)\"",
20687 eol,
20688 (unsigned)LUA_VERSION_NUM,
20689 LUA_RELEASE);
20690 system_info_length += mg_str_append(&buffer, end, block);
20691#endif
20692#if defined(USE_DUKTAPE)
20693 mg_snprintf(NULL,
20694 NULL,
20695 block,
20696 sizeof(block),
20697 ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
20698 eol,
20699 (unsigned)DUK_VERSION / 10000,
20700 ((unsigned)DUK_VERSION / 100) % 100,
20701 (unsigned)DUK_VERSION % 100);
20702 system_info_length += mg_str_append(&buffer, end, block);
20703#endif
20704 }
20705
20706 /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
20707 {
20708#if defined(BUILD_DATE)
20709 const char *bd = BUILD_DATE;
20710#else
20711#if defined(GCC_DIAGNOSTIC)
20712#if GCC_VERSION >= 40900
20713#pragma GCC diagnostic push
20714 /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
20715 * does not work in some versions. If "BUILD_DATE" is defined to some
20716 * string, it is used instead of __DATE__. */
20717#pragma GCC diagnostic ignored "-Wdate-time"
20718#endif
20719#endif
20720 const char *bd = __DATE__;
20721#if defined(GCC_DIAGNOSTIC)
20722#if GCC_VERSION >= 40900
20723#pragma GCC diagnostic pop
20724#endif
20725#endif
20726#endif
20727
20729 NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
20730
20731 system_info_length += mg_str_append(&buffer, end, block);
20732 }
20733
20734
20735 /* Compiler information */
20736 /* http://sourceforge.net/p/predef/wiki/Compilers/ */
20737 {
20738#if defined(_MSC_VER)
20739 mg_snprintf(NULL,
20740 NULL,
20741 block,
20742 sizeof(block),
20743 ",%s\"compiler\" : \"MSC: %u (%u)\"",
20744 eol,
20745 (unsigned)_MSC_VER,
20746 (unsigned)_MSC_FULL_VER);
20747 system_info_length += mg_str_append(&buffer, end, block);
20748#elif defined(__MINGW64__)
20749 mg_snprintf(NULL,
20750 NULL,
20751 block,
20752 sizeof(block),
20753 ",%s\"compiler\" : \"MinGW64: %u.%u\"",
20754 eol,
20755 (unsigned)__MINGW64_VERSION_MAJOR,
20756 (unsigned)__MINGW64_VERSION_MINOR);
20757 system_info_length += mg_str_append(&buffer, end, block);
20758 mg_snprintf(NULL,
20759 NULL,
20760 block,
20761 sizeof(block),
20762 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20763 eol,
20764 (unsigned)__MINGW32_MAJOR_VERSION,
20765 (unsigned)__MINGW32_MINOR_VERSION);
20766 system_info_length += mg_str_append(&buffer, end, block);
20767#elif defined(__MINGW32__)
20768 mg_snprintf(NULL,
20769 NULL,
20770 block,
20771 sizeof(block),
20772 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
20773 eol,
20774 (unsigned)__MINGW32_MAJOR_VERSION,
20775 (unsigned)__MINGW32_MINOR_VERSION);
20776 system_info_length += mg_str_append(&buffer, end, block);
20777#elif defined(__clang__)
20778 mg_snprintf(NULL,
20779 NULL,
20780 block,
20781 sizeof(block),
20782 ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
20783 eol,
20784 __clang_major__,
20785 __clang_minor__,
20786 __clang_patchlevel__,
20787 __clang_version__);
20788 system_info_length += mg_str_append(&buffer, end, block);
20789#elif defined(__GNUC__)
20790 mg_snprintf(NULL,
20791 NULL,
20792 block,
20793 sizeof(block),
20794 ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
20795 eol,
20796 (unsigned)__GNUC__,
20797 (unsigned)__GNUC_MINOR__,
20798 (unsigned)__GNUC_PATCHLEVEL__);
20799 system_info_length += mg_str_append(&buffer, end, block);
20800#elif defined(__INTEL_COMPILER)
20801 mg_snprintf(NULL,
20802 NULL,
20803 block,
20804 sizeof(block),
20805 ",%s\"compiler\" : \"Intel C/C++: %u\"",
20806 eol,
20807 (unsigned)__INTEL_COMPILER);
20808 system_info_length += mg_str_append(&buffer, end, block);
20809#elif defined(__BORLANDC__)
20810 mg_snprintf(NULL,
20811 NULL,
20812 block,
20813 sizeof(block),
20814 ",%s\"compiler\" : \"Borland C: 0x%x\"",
20815 eol,
20816 (unsigned)__BORLANDC__);
20817 system_info_length += mg_str_append(&buffer, end, block);
20818#elif defined(__SUNPRO_C)
20819 mg_snprintf(NULL,
20820 NULL,
20821 block,
20822 sizeof(block),
20823 ",%s\"compiler\" : \"Solaris: 0x%x\"",
20824 eol,
20825 (unsigned)__SUNPRO_C);
20826 system_info_length += mg_str_append(&buffer, end, block);
20827#else
20828 mg_snprintf(NULL,
20829 NULL,
20830 block,
20831 sizeof(block),
20832 ",%s\"compiler\" : \"other\"",
20833 eol);
20834 system_info_length += mg_str_append(&buffer, end, block);
20835#endif
20836 }
20837
20838 /* Determine 32/64 bit data mode.
20839 * see https://en.wikipedia.org/wiki/64-bit_computing */
20840 {
20841 mg_snprintf(NULL,
20842 NULL,
20843 block,
20844 sizeof(block),
20845 ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
20846 "char:%u/%u, "
20847 "ptr:%u, size:%u, time:%u\"",
20848 eol,
20849 (unsigned)sizeof(short),
20850 (unsigned)sizeof(int),
20851 (unsigned)sizeof(long),
20852 (unsigned)sizeof(long long),
20853 (unsigned)sizeof(float),
20854 (unsigned)sizeof(double),
20855 (unsigned)sizeof(long double),
20856 (unsigned)sizeof(char),
20857 (unsigned)sizeof(wchar_t),
20858 (unsigned)sizeof(void *),
20859 (unsigned)sizeof(size_t),
20860 (unsigned)sizeof(time_t));
20861 system_info_length += mg_str_append(&buffer, end, block);
20862 }
20863
20864 /* Terminate string */
20865 if (append_eoobj) {
20866 strcat(append_eoobj, eoobj);
20867 }
20868 system_info_length += sizeof(eoobj) - 1;
20869
20870 return (int)system_info_length;
20871}
20872
20873
20874/* Get context information. It can be printed or stored by the caller.
20875 * Return the size of available information. */
20876int
20877mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
20878{
20879#if defined(USE_SERVER_STATS)
20880 char *end, *append_eoobj = NULL, block[256];
20881 size_t context_info_length = 0;
20882
20883#if defined(_WIN32)
20884 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
20885#else
20886 static const char eol[] = "\n", eoobj[] = "\n}\n";
20887#endif
20888 struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
20889
20890 if ((buffer == NULL) || (buflen < 1)) {
20891 buflen = 0;
20892 end = buffer;
20893 } else {
20894 *buffer = 0;
20895 end = buffer + buflen;
20896 }
20897 if (buflen > (int)(sizeof(eoobj) - 1)) {
20898 /* has enough space to append eoobj */
20899 append_eoobj = buffer;
20900 end -= sizeof(eoobj) - 1;
20901 }
20902
20903 context_info_length += mg_str_append(&buffer, end, "{");
20904
20905 if (ms) { /* <-- should be always true */
20906 /* Memory information */
20907 int blockCount = (int)ms->blockCount;
20908 int64_t totalMemUsed = ms->totalMemUsed;
20909 int64_t maxMemUsed = ms->maxMemUsed;
20910 if (totalMemUsed > maxMemUsed) {
20911 maxMemUsed = totalMemUsed;
20912 }
20913
20914 mg_snprintf(NULL,
20915 NULL,
20916 block,
20917 sizeof(block),
20918 "%s\"memory\" : {%s"
20919 "\"blocks\" : %i,%s"
20920 "\"used\" : %" INT64_FMT ",%s"
20921 "\"maxUsed\" : %" INT64_FMT "%s"
20922 "}",
20923 eol,
20924 eol,
20925 blockCount,
20926 eol,
20927 totalMemUsed,
20928 eol,
20929 maxMemUsed,
20930 eol);
20931 context_info_length += mg_str_append(&buffer, end, block);
20932 }
20933
20934 if (ctx) {
20935 /* Declare all variables at begin of the block, to comply
20936 * with old C standards. */
20937 char start_time_str[64] = {0};
20938 char now_str[64] = {0};
20939 time_t start_time = ctx->start_time;
20940 time_t now = time(NULL);
20941 int64_t total_data_read, total_data_written;
20942 int active_connections = (int)ctx->active_connections;
20943 int max_active_connections = (int)ctx->max_active_connections;
20944 int total_connections = (int)ctx->total_connections;
20945 if (active_connections > max_active_connections) {
20946 max_active_connections = active_connections;
20947 }
20948 if (active_connections > total_connections) {
20949 total_connections = active_connections;
20950 }
20951
20952 /* Connections information */
20953 mg_snprintf(NULL,
20954 NULL,
20955 block,
20956 sizeof(block),
20957 ",%s\"connections\" : {%s"
20958 "\"active\" : %i,%s"
20959 "\"maxActive\" : %i,%s"
20960 "\"total\" : %i%s"
20961 "}",
20962 eol,
20963 eol,
20964 active_connections,
20965 eol,
20966 max_active_connections,
20967 eol,
20968 total_connections,
20969 eol);
20970 context_info_length += mg_str_append(&buffer, end, block);
20971
20972 /* Queue information */
20973#if !defined(ALTERNATIVE_QUEUE)
20974 mg_snprintf(NULL,
20975 NULL,
20976 block,
20977 sizeof(block),
20978 ",%s\"queue\" : {%s"
20979 "\"length\" : %i,%s"
20980 "\"filled\" : %i,%s"
20981 "\"maxFilled\" : %i,%s"
20982 "\"full\" : %s%s"
20983 "}",
20984 eol,
20985 eol,
20986 ctx->sq_size,
20987 eol,
20988 ctx->sq_head - ctx->sq_tail,
20989 eol,
20990 ctx->sq_max_fill,
20991 eol,
20992 (ctx->sq_blocked ? "true" : "false"),
20993 eol);
20994 context_info_length += mg_str_append(&buffer, end, block);
20995#endif
20996
20997 /* Requests information */
20998 mg_snprintf(NULL,
20999 NULL,
21000 block,
21001 sizeof(block),
21002 ",%s\"requests\" : {%s"
21003 "\"total\" : %lu%s"
21004 "}",
21005 eol,
21006 eol,
21007 (unsigned long)ctx->total_requests,
21008 eol);
21009 context_info_length += mg_str_append(&buffer, end, block);
21010
21011 /* Data information */
21012 total_data_read =
21013 mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
21014 total_data_written =
21015 mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
21016 mg_snprintf(NULL,
21017 NULL,
21018 block,
21019 sizeof(block),
21020 ",%s\"data\" : {%s"
21021 "\"read\" : %" INT64_FMT ",%s"
21022 "\"written\" : %" INT64_FMT "%s"
21023 "}",
21024 eol,
21025 eol,
21026 total_data_read,
21027 eol,
21028 total_data_written,
21029 eol);
21030 context_info_length += mg_str_append(&buffer, end, block);
21031
21032 /* Execution time information */
21033 gmt_time_string(start_time_str,
21034 sizeof(start_time_str) - 1,
21035 &start_time);
21036 gmt_time_string(now_str, sizeof(now_str) - 1, &now);
21037
21038 mg_snprintf(NULL,
21039 NULL,
21040 block,
21041 sizeof(block),
21042 ",%s\"time\" : {%s"
21043 "\"uptime\" : %.0f,%s"
21044 "\"start\" : \"%s\",%s"
21045 "\"now\" : \"%s\"%s"
21046 "}",
21047 eol,
21048 eol,
21049 difftime(now, start_time),
21050 eol,
21051 start_time_str,
21052 eol,
21053 now_str,
21054 eol);
21055 context_info_length += mg_str_append(&buffer, end, block);
21056 }
21057
21058 /* Terminate string */
21059 if (append_eoobj) {
21060 strcat(append_eoobj, eoobj);
21061 }
21062 context_info_length += sizeof(eoobj) - 1;
21063
21064 return (int)context_info_length;
21065#else
21066 (void)ctx;
21067 if ((buffer != NULL) && (buflen > 0)) {
21068 *buffer = 0;
21069 }
21070 return 0;
21071#endif
21072}
21073
21074
21075void
21077{
21078 /* https://github.com/civetweb/civetweb/issues/727 */
21079 if (conn != NULL) {
21080 conn->must_close = 1;
21081 }
21082}
21083
21084
21085#if defined(MG_EXPERIMENTAL_INTERFACES)
21086/* Get connection information. It can be printed or stored by the caller.
21087 * Return the size of available information. */
21088int
21089mg_get_connection_info(const struct mg_context *ctx,
21090 int idx,
21091 char *buffer,
21092 int buflen)
21093{
21094 const struct mg_connection *conn;
21095 const struct mg_request_info *ri;
21096 char *end, *append_eoobj = NULL, block[256];
21097 size_t connection_info_length = 0;
21098 int state = 0;
21099 const char *state_str = "unknown";
21100
21101#if defined(_WIN32)
21102 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
21103#else
21104 static const char eol[] = "\n", eoobj[] = "\n}\n";
21105#endif
21106
21107 if ((buffer == NULL) || (buflen < 1)) {
21108 buflen = 0;
21109 end = buffer;
21110 } else {
21111 *buffer = 0;
21112 end = buffer + buflen;
21113 }
21114 if (buflen > (int)(sizeof(eoobj) - 1)) {
21115 /* has enough space to append eoobj */
21116 append_eoobj = buffer;
21117 end -= sizeof(eoobj) - 1;
21118 }
21119
21120 if ((ctx == NULL) || (idx < 0)) {
21121 /* Parameter error */
21122 return 0;
21123 }
21124
21125 if ((unsigned)idx >= ctx->cfg_worker_threads) {
21126 /* Out of range */
21127 return 0;
21128 }
21129
21130 /* Take connection [idx]. This connection is not locked in
21131 * any way, so some other thread might use it. */
21132 conn = (ctx->worker_connections) + idx;
21133
21134 /* Initialize output string */
21135 connection_info_length += mg_str_append(&buffer, end, "{");
21136
21137 /* Init variables */
21138 ri = &(conn->request_info);
21139
21140#if defined(USE_SERVER_STATS)
21141 state = conn->conn_state;
21142
21143 /* State as string */
21144 switch (state) {
21145 case 0:
21146 state_str = "undefined";
21147 break;
21148 case 1:
21149 state_str = "not used";
21150 break;
21151 case 2:
21152 state_str = "init";
21153 break;
21154 case 3:
21155 state_str = "ready";
21156 break;
21157 case 4:
21158 state_str = "processing";
21159 break;
21160 case 5:
21161 state_str = "processed";
21162 break;
21163 case 6:
21164 state_str = "to close";
21165 break;
21166 case 7:
21167 state_str = "closing";
21168 break;
21169 case 8:
21170 state_str = "closed";
21171 break;
21172 case 9:
21173 state_str = "done";
21174 break;
21175 }
21176#endif
21177
21178 /* Connection info */
21179 if ((state >= 3) && (state < 9)) {
21180 mg_snprintf(NULL,
21181 NULL,
21182 block,
21183 sizeof(block),
21184 "%s\"connection\" : {%s"
21185 "\"remote\" : {%s"
21186 "\"protocol\" : \"%s\",%s"
21187 "\"addr\" : \"%s\",%s"
21188 "\"port\" : %u%s"
21189 "},%s"
21190 "\"handled_requests\" : %u%s"
21191 "}",
21192 eol,
21193 eol,
21194 eol,
21195 get_proto_name(conn),
21196 eol,
21197 ri->remote_addr,
21198 eol,
21199 ri->remote_port,
21200 eol,
21201 eol,
21202 conn->handled_requests,
21203 eol);
21204 connection_info_length += mg_str_append(&buffer, end, block);
21205 }
21206
21207 /* Request info */
21208 if ((state >= 4) && (state < 6)) {
21209 mg_snprintf(NULL,
21210 NULL,
21211 block,
21212 sizeof(block),
21213 "%s%s\"request_info\" : {%s"
21214 "\"method\" : \"%s\",%s"
21215 "\"uri\" : \"%s\",%s"
21216 "\"query\" : %s%s%s%s"
21217 "}",
21218 (connection_info_length > 1 ? "," : ""),
21219 eol,
21220 eol,
21221 ri->request_method,
21222 eol,
21223 ri->request_uri,
21224 eol,
21225 ri->query_string ? "\"" : "",
21226 ri->query_string ? ri->query_string : "null",
21227 ri->query_string ? "\"" : "",
21228 eol);
21229 connection_info_length += mg_str_append(&buffer, end, block);
21230 }
21231
21232 /* Execution time information */
21233 if ((state >= 2) && (state < 9)) {
21234 char start_time_str[64] = {0};
21235 char close_time_str[64] = {0};
21236 time_t start_time = conn->conn_birth_time;
21237 time_t close_time = 0;
21238 double time_diff;
21239
21240 gmt_time_string(start_time_str,
21241 sizeof(start_time_str) - 1,
21242 &start_time);
21243#if defined(USE_SERVER_STATS)
21244 close_time = conn->conn_close_time;
21245#endif
21246 if (close_time != 0) {
21247 time_diff = difftime(close_time, start_time);
21248 gmt_time_string(close_time_str,
21249 sizeof(close_time_str) - 1,
21250 &close_time);
21251 } else {
21252 time_t now = time(NULL);
21253 time_diff = difftime(now, start_time);
21254 close_time_str[0] = 0; /* or use "now" ? */
21255 }
21256
21257 mg_snprintf(NULL,
21258 NULL,
21259 block,
21260 sizeof(block),
21261 "%s%s\"time\" : {%s"
21262 "\"uptime\" : %.0f,%s"
21263 "\"start\" : \"%s\",%s"
21264 "\"closed\" : \"%s\"%s"
21265 "}",
21266 (connection_info_length > 1 ? "," : ""),
21267 eol,
21268 eol,
21269 time_diff,
21270 eol,
21271 start_time_str,
21272 eol,
21273 close_time_str,
21274 eol);
21275 connection_info_length += mg_str_append(&buffer, end, block);
21276 }
21277
21278 /* Remote user name */
21279 if ((ri->remote_user) && (state < 9)) {
21280 mg_snprintf(NULL,
21281 NULL,
21282 block,
21283 sizeof(block),
21284 "%s%s\"user\" : {%s"
21285 "\"name\" : \"%s\",%s"
21286 "}",
21287 (connection_info_length > 1 ? "," : ""),
21288 eol,
21289 eol,
21290 ri->remote_user,
21291 eol);
21292 connection_info_length += mg_str_append(&buffer, end, block);
21293 }
21294
21295 /* Data block */
21296 if (state >= 3) {
21297 mg_snprintf(NULL,
21298 NULL,
21299 block,
21300 sizeof(block),
21301 "%s%s\"data\" : {%s"
21302 "\"read\" : %" INT64_FMT ",%s"
21303 "\"written\" : %" INT64_FMT "%s"
21304 "}",
21305 (connection_info_length > 1 ? "," : ""),
21306 eol,
21307 eol,
21308 conn->consumed_content,
21309 eol,
21310 conn->num_bytes_sent,
21311 eol);
21312 connection_info_length += mg_str_append(&buffer, end, block);
21313 }
21314
21315 /* State */
21316 mg_snprintf(NULL,
21317 NULL,
21318 block,
21319 sizeof(block),
21320 "%s%s\"state\" : \"%s\"",
21321 (connection_info_length > 1 ? "," : ""),
21322 eol,
21323 state_str);
21324 connection_info_length += mg_str_append(&buffer, end, block);
21325
21326 /* Terminate string */
21327 if (append_eoobj) {
21328 strcat(append_eoobj, eoobj);
21329 }
21330 connection_info_length += sizeof(eoobj) - 1;
21331
21332 return (int)connection_info_length;
21333}
21334#endif
21335
21336
21337/* Initialize this library. This function does not need to be thread safe.
21338 */
21339unsigned
21340mg_init_library(unsigned features)
21341{
21342 unsigned features_to_init = mg_check_feature(features & 0xFFu);
21343 unsigned features_inited = features_to_init;
21344
21345 if (mg_init_library_called <= 0) {
21346 /* Not initialized yet */
21347 if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
21348 return 0;
21349 }
21350 }
21351
21353
21354 if (mg_init_library_called <= 0) {
21355#if defined(_WIN32)
21356 int file_mutex_init = 1;
21357 int wsa = 1;
21358#else
21359 int mutexattr_init = 1;
21360#endif
21361 int failed = 1;
21362 int key_create = pthread_key_create(&sTlsKey, tls_dtor);
21363
21364 if (key_create == 0) {
21365#if defined(_WIN32)
21366 file_mutex_init =
21367 pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
21368 if (file_mutex_init == 0) {
21369 /* Start WinSock */
21370 WSADATA data;
21371 failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
21372 }
21373#else
21374 mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
21375 if (mutexattr_init == 0) {
21376 failed = pthread_mutexattr_settype(&pthread_mutex_attr,
21377 PTHREAD_MUTEX_RECURSIVE);
21378 }
21379#endif
21380 }
21381
21382
21383 if (failed) {
21384#if defined(_WIN32)
21385 if (wsa == 0) {
21386 (void)WSACleanup();
21387 }
21388 if (file_mutex_init == 0) {
21389 (void)pthread_mutex_destroy(&global_log_file_lock);
21390 }
21391#else
21392 if (mutexattr_init == 0) {
21393 (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
21394 }
21395#endif
21396 if (key_create == 0) {
21397 (void)pthread_key_delete(sTlsKey);
21398 }
21400 (void)pthread_mutex_destroy(&global_lock_mutex);
21401 return 0;
21402 }
21403
21404#if defined(USE_LUA)
21405 lua_init_optional_libraries();
21406#endif
21407 }
21408
21410
21411#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
21412 || defined(OPENSSL_API_3_0)) \
21413 && !defined(NO_SSL)
21414 if (features_to_init & MG_FEATURES_SSL) {
21415 if (!mg_openssl_initialized) {
21416 char ebuf[128];
21417 if (initialize_openssl(ebuf, sizeof(ebuf))) {
21418 mg_openssl_initialized = 1;
21419 } else {
21420 (void)ebuf;
21421 DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
21422 features_inited &= ~((unsigned)(MG_FEATURES_SSL));
21423 }
21424 } else {
21425 /* ssl already initialized */
21426 }
21427 }
21428#endif
21429
21431 if (mg_init_library_called <= 0) {
21433 } else {
21435 }
21437
21438 return features_inited;
21439}
21440
21441
21442/* Un-initialize this library. */
21443unsigned
21445{
21446 if (mg_init_library_called <= 0) {
21447 return 0;
21448 }
21449
21451
21453 if (mg_init_library_called == 0) {
21454#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
21455 if (mg_openssl_initialized) {
21457 mg_openssl_initialized = 0;
21458 }
21459#endif
21460
21461#if defined(_WIN32)
21462 (void)WSACleanup();
21463 (void)pthread_mutex_destroy(&global_log_file_lock);
21464#else
21465 (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
21466#endif
21467
21468 (void)pthread_key_delete(sTlsKey);
21469
21470#if defined(USE_LUA)
21471 lua_exit_optional_libraries();
21472#endif
21473
21475 (void)pthread_mutex_destroy(&global_lock_mutex);
21476 return 1;
21477 }
21478
21480 return 1;
21481}
21482
21483
21484/* 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:18483
static int is_authorized_for_put(struct mg_connection *conn)
Definition civetweb.c:8784
static int consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
Definition civetweb.c:18739
static int parse_http_request(char *buf, int len, struct mg_request_info *ri)
Definition civetweb.c:10592
void mg_send_mime_file2(struct mg_connection *conn, const char *path, const char *mime_type, const char *additional_headers)
Definition civetweb.c:10208
#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:8805
static void sockaddr_to_string(char *buf, size_t len, const union usa *usa)
Definition civetweb.c:3255
static void open_auth_file(struct mg_connection *conn, const char *path, struct mg_file *filep)
Definition civetweb.c:8274
int mg_strncasecmp(const char *s1, const char *s2, size_t len)
Definition civetweb.c:2982
#define IP_ADDR_STR_LEN
Definition civetweb.c:1724
static int check_authorization(struct mg_connection *conn, const char *path)
Definition civetweb.c:8667
#define vsnprintf_impl
Definition civetweb.c:894
#define HEXTOI(x)
#define mg_malloc_ctx(a, c)
Definition civetweb.c:1494
@ CONNECTION_TYPE_RESPONSE
Definition civetweb.c:2424
@ CONNECTION_TYPE_INVALID
Definition civetweb.c:2422
@ CONNECTION_TYPE_REQUEST
Definition civetweb.c:2423
static void redirect_to_https_port(struct mg_connection *conn, int port)
Definition civetweb.c:13518
static int should_switch_to_protocol(const struct mg_connection *conn)
Definition civetweb.c:13205
void mg_unlock_connection(struct mg_connection *conn)
Definition civetweb.c:12289
static void mkcol(struct mg_connection *conn, const char *path)
Definition civetweb.c:11588
static void remove_bad_file(const struct mg_connection *conn, const char *path)
Definition civetweb.c:10291
static const struct @145 abs_uri_protocols[]
const struct mg_option * mg_get_valid_options(void)
Definition civetweb.c:2796
static int mg_path_suspicious(const struct mg_connection *conn, const char *path)
Definition civetweb.c:2834
const char * mime_type
Definition civetweb.c:8026
static int set_non_blocking_mode(SOCKET sock)
Definition civetweb.c:5845
static void ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
Definition civetweb.c:15877
const char * proto
Definition civetweb.c:17502
int mg_send_http_error(struct mg_connection *conn, int status, const char *fmt,...)
Definition civetweb.c:4535
static const char * get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
Definition civetweb.c:17589
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:3347
void mg_lock_context(struct mg_context *ctx)
Definition civetweb.c:12297
#define MAX_WORKER_THREADS
Definition civetweb.c:463
@ CONTEXT_WS_CLIENT
Definition civetweb.c:2246
@ CONTEXT_INVALID
Definition civetweb.c:2243
@ CONTEXT_SERVER
Definition civetweb.c:2244
@ CONTEXT_HTTP_CLIENT
Definition civetweb.c:2245
static void put_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:11657
static void do_ssi_exec(struct mg_connection *conn, char *tag)
Definition civetweb.c:11932
static void tls_dtor(void *key)
Definition civetweb.c:15501
#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:3901
int mg_send_http_redirect(struct mg_connection *conn, const char *target_url, int redirect_code)
Definition civetweb.c:4590
int mg_get_cookie(const char *cookie_header, const char *var_name, char *dst, size_t dst_size)
Definition civetweb.c:7157
static int ssl_get_client_cert_info(const struct mg_connection *conn, struct mg_client_cert *client_cert)
Definition civetweb.c:15800
#define mg_cry_ctx_internal(ctx, fmt,...)
Definition civetweb.c:2549
@ ENABLE_DIRECTORY_LISTING
Definition civetweb.c:1990
@ SSL_SHORT_TRUST
Definition civetweb.c:2007
@ GLOBAL_PASSWORDS_FILE
Definition civetweb.c:1991
@ ADDITIONAL_HEADER
Definition civetweb.c:2039
@ SSL_VERIFY_DEPTH
Definition civetweb.c:2003
@ ACCESS_CONTROL_ALLOW_ORIGIN
Definition civetweb.c:2028
@ SSL_PROTOCOL_VERSION
Definition civetweb.c:2006
@ SSL_DO_VERIFY_PEER
Definition civetweb.c:1999
@ SSL_CERTIFICATE
Definition civetweb.c:1995
@ RUN_AS_USER
Definition civetweb.c:1914
@ ALLOW_INDEX_SCRIPT_SUB_RES
Definition civetweb.c:2040
@ SSL_CACHE_TIMEOUT
Definition civetweb.c:2000
@ CONNECTION_QUEUE_SIZE
Definition civetweb.c:1919
@ ENABLE_KEEP_ALIVE
Definition civetweb.c:1928
@ ACCESS_CONTROL_LIST
Definition civetweb.c:1993
@ CGI_INTERPRETER_ARGS
Definition civetweb.c:1954
@ SSL_CA_PATH
Definition civetweb.c:2001
@ AUTHENTICATION_DOMAIN
Definition civetweb.c:1987
@ ACCESS_CONTROL_ALLOW_HEADERS
Definition civetweb.c:2030
@ SSL_DEFAULT_VERIFY_PATHS
Definition civetweb.c:2004
@ CGI2_EXTENSIONS
Definition civetweb.c:1959
@ ACCESS_CONTROL_ALLOW_METHODS
Definition civetweb.c:2029
@ STRICT_HTTPS_MAX_AGE
Definition civetweb.c:2037
@ HIDE_FILES
Definition civetweb.c:1998
@ ERROR_LOG_FILE
Definition civetweb.c:1949
@ CGI2_INTERPRETER_ARGS
Definition civetweb.c:1962
@ STATIC_FILE_MAX_AGE
Definition civetweb.c:2033
@ LINGER_TIMEOUT
Definition civetweb.c:1918
@ URL_REWRITE_PATTERN
Definition civetweb.c:1997
@ THROTTLE
Definition civetweb.c:1927
@ SSL_CIPHER_LIST
Definition civetweb.c:2005
@ KEEP_ALIVE_TIMEOUT
Definition civetweb.c:1930
@ CGI_EXTENSIONS
Definition civetweb.c:1951
@ STATIC_FILE_CACHE_CONTROL
Definition civetweb.c:2034
@ ERROR_PAGES
Definition civetweb.c:2031
@ CGI_ENVIRONMENT
Definition civetweb.c:1952
@ PUT_DELETE_PASSWORDS_FILE
Definition civetweb.c:1985
@ ENABLE_AUTH_DOMAIN_CHECK
Definition civetweb.c:1988
@ NUM_OPTIONS
Definition civetweb.c:2042
@ MAX_REQUEST_SIZE
Definition civetweb.c:1917
@ DECODE_URL
Definition civetweb.c:1935
@ NUM_THREADS
Definition civetweb.c:1913
@ DOCUMENT_ROOT
Definition civetweb.c:1946
@ SSL_CERTIFICATE_CHAIN
Definition civetweb.c:1996
@ CGI2_ENVIRONMENT
Definition civetweb.c:1960
@ PROTECT_URI
Definition civetweb.c:1986
@ ACCESS_LOG_FILE
Definition civetweb.c:1948
@ REQUEST_TIMEOUT
Definition civetweb.c:1929
@ SSI_EXTENSIONS
Definition civetweb.c:1989
@ CONFIG_TCP_NODELAY
Definition civetweb.c:1915
@ SSL_CA_FILE
Definition civetweb.c:2002
@ CGI_INTERPRETER
Definition civetweb.c:1953
@ LISTEN_BACKLOG_SIZE
Definition civetweb.c:1920
@ DECODE_QUERY_STRING
Definition civetweb.c:1936
@ LISTENING_PORTS
Definition civetweb.c:1912
@ CGI2_INTERPRETER
Definition civetweb.c:1961
@ INDEX_FILES
Definition civetweb.c:1992
@ EXTRA_MIME_TYPES
Definition civetweb.c:1994
static void mg_snprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, const char *fmt,...)
Definition civetweb.c:3106
#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:3010
static int put_dir(struct mg_connection *conn, const char *path)
Definition civetweb.c:10254
#define UINT64_FMT
Definition civetweb.c:924
static void send_static_cache_header(struct mg_connection *conn)
Definition civetweb.c:4068
static void handle_cgi_request(struct mg_connection *conn, const char *prog, unsigned char cgi_config_idx)
Definition civetweb.c:11265
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:8025
static int print_dav_dir_entry(struct de *de, void *data)
Definition civetweb.c:12222
static void delete_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:11784
#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:18361
#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:3211
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:6935
static int abort_cgi_process(void *data)
Definition civetweb.c:11230
static int should_keep_alive(const struct mg_connection *conn)
Definition civetweb.c:3978
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:2878
void mg_disable_connection_keep_alive(struct mg_connection *conn)
Definition civetweb.c:21076
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:9882
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:16120
static const char * ssl_error(void)
Definition civetweb.c:15765
static int must_hide_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:9434
static void log_access(const struct mg_connection *)
Definition civetweb.c:15251
const char * extension
Definition civetweb.c:8024
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:17380
#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:4549
static void close_all_listening_sockets(struct mg_context *ctx)
Definition civetweb.c:14644
#define closesocket(a)
Definition civetweb.c:914
void mg_send_file(struct mg_connection *conn, const char *path)
Definition civetweb.c:10192
static void send_authorization_request(struct mg_connection *conn, const char *realm)
Definition civetweb.c:8723
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:5737
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:8229
static int check_acl(struct mg_context *phys_ctx, const union usa *sa)
Definition civetweb.c:15409
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:10557
#define STOP_FLAG_IS_ZERO(f)
Definition civetweb.c:2303
unsigned default_port
Definition civetweb.c:17504
const char * mg_get_response_code_text(const struct mg_connection *conn, int response_code)
Definition civetweb.c:4150
static int get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
Definition civetweb.c:17861
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:3446
static int set_uid_option(struct mg_context *phys_ctx)
Definition civetweb.c:15447
static int switch_domain_context(struct mg_connection *conn)
Definition civetweb.c:13457
static struct mg_connection * fake_connection(struct mg_connection *fc, struct mg_context *ctx)
Definition civetweb.c:3435
static void reset_per_request_attributes(struct mg_connection *conn)
Definition civetweb.c:16856
static void handle_file_based_request(struct mg_connection *conn, const char *path, struct mg_file *filep)
Definition civetweb.c:14542
#define FUNCTION_MAY_BE_UNUSED
Definition civetweb.c:316
static pthread_mutex_t * ssl_mutexes
Definition civetweb.c:15631
static int get_option_index(const char *name)
Definition civetweb.c:3122
static char * mg_strdup(const char *str)
Definition civetweb.c:3031
static void send_no_cache_header(struct mg_connection *conn)
Definition civetweb.c:4050
static void master_thread_run(struct mg_context *ctx)
Definition civetweb.c:19159
static int prepare_cgi_environment(struct mg_connection *conn, const char *prog, struct cgi_environment *env, unsigned char cgi_config_idx)
Definition civetweb.c:11032
static const char month_names[][4]
Definition civetweb.c:1807
const struct mg_response_info * mg_get_response_info(const struct mg_connection *conn)
Definition civetweb.c:3526
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:19072
static volatile ptrdiff_t cryptolib_users
Definition civetweb.c:15995
static int get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
Definition civetweb.c:17693
#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:19579
#define CGI_ENVIRONMENT_SIZE
Definition civetweb.c:486
static int parse_http_headers(char **buf, struct mg_header hdr[(64)])
Definition civetweb.c:10407
#define mg_get_option
Definition civetweb.c:3148
static long ssl_get_protocol(int version_id)
Definition civetweb.c:16197
void * mg_get_user_context_data(const struct mg_connection *conn)
Definition civetweb.c:3165
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:10304
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:17998
#define DEBUG_ASSERT(cond)
Definition civetweb.c:260
static size_t mg_str_append(char **dst, char *end, const char *src)
Definition civetweb.c:20526
static int pull_inner(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
Definition civetweb.c:6183
#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:17946
#define MG_FILE_COMPRESSION_SIZE_LIMIT
Definition civetweb.c:476
#define USA_IN_PORT_UNSAFE(s)
Definition civetweb.c:1852
static struct mg_connection * mg_connect_client_impl(const struct mg_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len)
Definition civetweb.c:17183
unsigned mg_check_feature(unsigned feature)
Definition civetweb.c:20463
static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
Definition civetweb.c:6467
static int mg_send_http_error_impl(struct mg_connection *conn, int status, const char *fmt, va_list args)
Definition civetweb.c:4349
struct mg_context * mg_start(const struct mg_callbacks *callbacks, void *user_data, const char **options)
Definition civetweb.c:20251
#define MG_FOPEN_MODE_READ
Definition civetweb.c:2806
#define STOP_FLAG_ASSIGN(f, v)
Definition civetweb.c:2305
static int extention_matches_script(struct mg_connection *conn, const char *filename)
Definition civetweb.c:7318
static void get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
Definition civetweb.c:13419
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:13771
int mg_start_domain(struct mg_context *ctx, const char **options)
Definition civetweb.c:20455
static pthread_mutexattr_t pthread_mutex_attr
Definition civetweb.c:1071
void mg_unlock_context(struct mg_context *ctx)
Definition civetweb.c:12305
static int ssl_servername_callback(SSL *ssl, int *ad, void *arg)
Definition civetweb.c:16246
int mg_modify_passwords_file(const char *fname, const char *domain, const char *user, const char *pass)
Definition civetweb.c:8925
static char * skip_quoted(char **buf, const char *delimiters, const char *whitespace, char quotechar)
Definition civetweb.c:3699
static void fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
Definition civetweb.c:9858
int mg_start_thread(mg_thread_func_t func, void *param)
Definition civetweb.c:5669
static const char * get_header(const struct mg_header *hdr, int num_hdr, const char *name)
Definition civetweb.c:3763
static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
Definition civetweb.c:8952
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:16419
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:8993
unsigned mg_init_library(unsigned features)
Definition civetweb.c:21340
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:17392
static int forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
Definition civetweb.c:10862
static int set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
Definition civetweb.c:16816
static int skip_to_end_of_word_and_terminate(char **ppw, int eol)
Definition civetweb.c:10362
static int get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
Definition civetweb.c:17769
static int set_tcp_nodelay(const struct socket *so, int nodelay_on)
Definition civetweb.c:16898
int mg_get_var(const char *data, size_t data_len, const char *name, char *dst, size_t dst_len)
Definition civetweb.c:6989
#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:14689
static int get_first_ssl_listener_index(const struct mg_context *ctx)
Definition civetweb.c:13404
void mg_send_mime_file(struct mg_connection *conn, const char *path, const char *mime_type)
Definition civetweb.c:10199
const char * mg_get_header(const struct mg_connection *conn, const char *name)
Definition civetweb.c:3800
#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:7058
static int hexdump2string(void *mem, int memlen, char *buf, int buflen)
Definition civetweb.c:15774
#define UTF8_PATH_MAX
Definition civetweb.c:858
static const struct mg_http_method_info http_methods[]
Definition civetweb.c:10495
static int mg_poll(struct pollfd *pfd, unsigned int n, int milliseconds, const stop_flag_t *stop_flag)
Definition civetweb.c:5907
static void handle_directory_request(struct mg_connection *conn, const char *dir)
Definition civetweb.c:9616
static int set_ports_option(struct mg_context *phys_ctx)
Definition civetweb.c:14924
static int read_auth_file(struct mg_file *filep, struct read_auth_file_struct *workdata, int depth)
Definition civetweb.c:8504
static int mg_start_thread_with_id(mg_thread_func_t func, void *param, pthread_t *threadidptr)
Definition civetweb.c:5695
unsigned mg_exit_library(void)
Definition civetweb.c:21444
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:15895
static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
Definition civetweb.c:3305
int mg_send_digest_access_authentication_request(struct mg_connection *conn, const char *realm)
Definition civetweb.c:8771
static const char * mg_strcasestr(const char *big_str, const char *small_str)
Definition civetweb.c:3038
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:18331
static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
Definition civetweb.c:6412
static void handle_ssi_file_request(struct mg_connection *conn, const char *path, struct mg_file *filep)
Definition civetweb.c:12077
int mg_write(struct mg_connection *conn, const void *buf, size_t len)
Definition civetweb.c:6694
static int set_throttle(const char *spec, const union usa *rsa, const char *uri)
Definition civetweb.c:13358
static void ssl_info_callback(const SSL *ssl, int what, int ret)
Definition civetweb.c:16230
#define calloc
Definition civetweb.c:1537
@ PROTOCOL_TYPE_HTTP1
Definition civetweb.c:2428
@ PROTOCOL_TYPE_HTTP2
Definition civetweb.c:2430
@ PROTOCOL_TYPE_WEBSOCKET
Definition civetweb.c:2429
static void bin2str(char *to, const unsigned char *p, size_t len)
Definition civetweb.c:8191
const struct mg_request_info * mg_get_request_info(const struct mg_connection *conn)
Definition civetweb.c:3486
#define MG_FOPEN_MODE_APPEND
Definition civetweb.c:2812
char * mg_md5(char buf[33],...)
Definition civetweb.c:8206
#define STOP_FLAG_IS_TWO(f)
Definition civetweb.c:2304
static const char * next_option(const char *list, struct vec *val, struct vec *eq_val)
Definition civetweb.c:3844
static const char * suggest_connection_header(const struct mg_connection *conn)
Definition civetweb.c:4040
static ptrdiff_t match_prefix_strlen(const char *pattern, const char *str)
Definition civetweb.c:3965
static int alloc_vprintf(char **out_buf, char *prealloc_buf, size_t prealloc_size, const char *fmt, va_list ap)
Definition civetweb.c:6854
static time_t parse_date_string(const char *datetime)
Definition civetweb.c:7807
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:11847
static void uninitialize_openssl(void)
Definition civetweb.c:16774
int mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
Definition civetweb.c:3687
static int parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
Definition civetweb.c:13249
int mg_modify_passwords_file_ha1(const char *fname, const char *domain, const char *user, const char *ha1)
Definition civetweb.c:8935
static void send_options(struct mg_connection *conn)
Definition civetweb.c:12134
static int lowercase(const char *s)
Definition civetweb.c:2975
static void release_handler_ref(struct mg_connection *conn, struct mg_handler_info *handler_info)
Definition civetweb.c:13970
static int parse_range_header(const char *header, int64_t *a, int64_t *b)
Definition civetweb.c:9831
static int mg_stat(const struct mg_connection *conn, const char *path, struct mg_file_stat *filep)
Definition civetweb.c:5619
static int get_uri_type(const char *uri)
Definition civetweb.c:17519
#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:19503
int mg_url_encode(const char *src, char *dst, size_t dst_len)
Definition civetweb.c:9260
static const char * header_val(const struct mg_connection *conn, const char *header)
Definition civetweb.c:15234
#define mg_cry_internal(conn, fmt,...)
Definition civetweb.c:2546
static int set_acl_option(struct mg_context *phys_ctx)
Definition civetweb.c:16842
static void mg_set_thread_name(const char *name)
Definition civetweb.c:2743
static void get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
Definition civetweb.c:8156
static int set_blocking_mode(SOCKET sock)
Definition civetweb.c:5859
#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:9727
#define MAX_CGI_ENVIR_VARS
Definition civetweb.c:491
static char * mg_strdup_ctx(const char *str, struct mg_context *ctx)
Definition civetweb.c:3025
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:18387
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded)
Definition civetweb.c:6949
static int parse_auth_header(struct mg_connection *conn, char *buf, size_t buf_size, struct ah *ah)
Definition civetweb.c:8354
void mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
Definition civetweb.c:3188
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:7000
static int is_not_modified(const struct mg_connection *conn, const struct mg_file_stat *filestat)
Definition civetweb.c:10150
static void worker_thread_run(struct mg_connection *conn)
Definition civetweb.c:18819
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:7436
static const char * get_proto_name(const struct mg_connection *conn)
Definition civetweb.c:3539
static void * master_thread(void *thread_func_param)
Definition civetweb.c:19345
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:13563
static int is_file_opened(const struct mg_file_access *fileacc)
Definition civetweb.c:2816
static int get_http_header_len(const char *buf, int buflen)
Definition civetweb.c:7754
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:18417
void mg_close_connection(struct mg_connection *conn)
Definition civetweb.c:17120
static int is_valid_port(unsigned long port)
Definition civetweb.c:8945
static void handle_propfind(struct mg_connection *conn, const char *path, struct mg_file_stat *filep)
Definition civetweb.c:12236
static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
Definition civetweb.c:6917
#define mg_realloc_ctx(a, b, c)
Definition civetweb.c:1496
static void send_additional_header(struct mg_connection *conn)
Definition civetweb.c:4116
static int push_all(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int len)
Definition civetweb.c:6135
static int is_put_or_delete_method(const struct mg_connection *conn)
Definition civetweb.c:7304
static int read_message(FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread)
Definition civetweb.c:10785
static int print_dir_entry(struct de *de)
Definition civetweb.c:9288
#define MG_FOPEN_MODE_WRITE
Definition civetweb.c:2809
void * mg_get_user_connection_data(const struct mg_connection *conn)
Definition civetweb.c:3201
static int authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
Definition civetweb.c:8614
static void send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int)
Definition civetweb.c:11971
#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:18776
static ptrdiff_t match_prefix(const char *pattern, size_t pattern_len, const char *str)
Definition civetweb.c:3920
int mg_send_chunk(struct mg_connection *conn, const char *chunk, unsigned int chunk_len)
Definition civetweb.c:6775
static void remove_dot_segments(char *inout)
Definition civetweb.c:7871
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:13843
void mg_set_auth_handler(struct mg_context *ctx, const char *uri, mg_authorization_handler handler, void *cbdata)
Definition civetweb.c:13821
int mg_start_domain2(struct mg_context *ctx, const char **options, struct mg_error_data *error)
Definition civetweb.c:20266
#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:6821
static int extention_matches_template_text(struct mg_connection *conn, const char *filename)
Definition civetweb.c:7364
static int is_in_script_path(const struct mg_connection *conn, const char *path)
Definition civetweb.c:13928
static int should_decode_query_string(const struct mg_connection *conn)
Definition civetweb.c:4028
static double mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
Definition civetweb.c:3329
static void free_context(struct mg_context *ctx)
Definition civetweb.c:19363
static int sslize(struct mg_connection *conn, int(*func)(SSL *), const struct mg_client_options *client_options)
Definition civetweb.c:15635
static void legacy_init(const char **options)
Definition civetweb.c:19551
static void construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
Definition civetweb.c:9843
int mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
Definition civetweb.c:20877
int volatile stop_flag_t
Definition civetweb.c:2302
static int refresh_trust(struct mg_connection *conn)
Definition civetweb.c:15557
#define SHUTDOWN_WR
Definition civetweb.c:515
void * mg_get_thread_pointer(const struct mg_connection *conn)
Definition civetweb.c:3172
static int compare_dir_entries(const void *p1, const void *p2)
Definition civetweb.c:9398
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:3057
static int should_decode_url(const struct mg_connection *conn)
Definition civetweb.c:4017
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:3566
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:6581
#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:2965
static int remove_directory(struct mg_connection *conn, const char *dir)
Definition civetweb.c:9508
static const char * get_http_version(const struct mg_connection *conn)
Definition civetweb.c:3821
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:13987
static int parse_http_response(char *buf, int len, struct mg_response_info *ri)
Definition civetweb.c:10678
static void * cryptolib_dll_handle
Definition civetweb.c:15986
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:8134
static const char * mg_fgets(char *buf, size_t size, struct mg_file *filep)
Definition civetweb.c:8467
int mg_read(struct mg_connection *conn, void *buf, size_t len)
Definition civetweb.c:6586
#define IGNORE_UNUSED_RESULT(a)
Definition civetweb.c:291
static void addenv(struct cgi_environment *env, const char *fmt,...)
Definition civetweb.c:10962
static void discard_unread_request_data(struct mg_connection *conn)
Definition civetweb.c:6457
int mg_strcasecmp(const char *s1, const char *s2)
Definition civetweb.c:2997
static int mg_fclose(struct mg_file_access *fileacc)
Definition civetweb.c:2949
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:18121
void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata)
Definition civetweb.c:13749
static void * worker_thread(void *thread_func_param)
Definition civetweb.c:19052
static __inline void mg_free(void *a)
Definition civetweb.c:1489
static void handle_request_stat_log(struct mg_connection *conn)
Definition civetweb.c:6535
int mg_check_digest_access_authentication(struct mg_connection *conn, const char *realm, const char *filename)
Definition civetweb.c:8642
static int mg_join_thread(pthread_t threadid)
Definition civetweb.c:5726
static void mg_global_unlock(void)
Definition civetweb.c:1099
int mg_get_system_info(char *buffer, int buflen)
Definition civetweb.c:20545
static void handle_not_modified_static_file_request(struct mg_connection *conn, struct mg_file *filep)
Definition civetweb.c:10165
static int init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
Definition civetweb.c:16665
static void close_socket_gracefully(struct mg_connection *conn)
Definition civetweb.c:16920
struct mg_context * mg_get_context(const struct mg_connection *conn)
Definition civetweb.c:3151
static int is_ssl_port_used(const char *ports)
Definition civetweb.c:14867
static void init_connection(struct mg_connection *conn)
Definition civetweb.c:18445
static int print_props(struct mg_connection *conn, const char *uri, const char *name, struct mg_file_stat *filep)
Definition civetweb.c:12165
#define INITIAL_DEPTH
Definition civetweb.c:8486
static int dir_scan_callback(struct de *de, void *data)
Definition civetweb.c:9584
size_t proto_len
Definition civetweb.c:17503
static void set_close_on_exec(int fd, const struct mg_connection *conn, struct mg_context *ctx)
Definition civetweb.c:5646
static int get_month_index(const char *s)
Definition civetweb.c:7791
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:13791
static void * ssllib_dll_handle
Definition civetweb.c:15985
static int mg_fgetc(struct mg_file *filep)
Definition civetweb.c:11956
static const struct @144 builtin_mime_types[]
#define mg_sleep(x)
Definition civetweb.c:917
@ AUTH_HANDLER
Definition civetweb.c:2206
@ REQUEST_HANDLER
Definition civetweb.c:2206
@ WEBSOCKET_HANDLER
Definition civetweb.c:2206
#define PASSWORDS_FILE_NAME
Definition civetweb.c:480
static void close_connection(struct mg_connection *conn)
Definition civetweb.c:17045
static int initialize_openssl(char *ebuf, size_t ebuf_len)
Definition civetweb.c:16001
static int substitute_index_file(struct mg_connection *conn, char *path, size_t path_len, struct mg_file_stat *filestat)
Definition civetweb.c:7388
void mg_stop(struct mg_context *ctx)
Definition civetweb.c:19460
#define STRUCT_FILE_INITIALIZER
Definition civetweb.c:1883
static volatile ptrdiff_t thread_idx_max
Definition civetweb.c:1573
void * mg_get_user_data(const struct mg_context *ctx)
Definition civetweb.c:3158
static int scan_directory(struct mg_connection *conn, const char *dir, void *data, int(*cb)(struct de *, void *))
Definition civetweb.c:9448
static int push_inner(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int len, double timeout)
Definition civetweb.c:5969
const char * mg_version(void)
Definition civetweb.c:3479
static uint64_t get_random(void)
Definition civetweb.c:5878
void mg_lock_connection(struct mg_connection *conn)
Definition civetweb.c:12281
int mg_send_file_body(struct mg_connection *conn, const char *path)
Definition civetweb.c:10133
#define mg_cry
Definition civetweb.c:3475
static int is_valid_http_method(const char *method)
Definition civetweb.c:10576
static void url_decode_in_place(char *buf)
Definition civetweb.c:6981
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_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
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
@ 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_WEBSOCKET_OPCODE_CONNECTION_CLOSE
Definition civetweb.h:861
@ MG_WEBSOCKET_OPCODE_PONG
Definition civetweb.h:863
@ MG_WEBSOCKET_OPCODE_PING
Definition civetweb.h:862
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
void init()
Inspect hardware capabilities, and load the optimal library for RooFit computations.
RooArgList L(Args_t &&... args)
Definition RooArgList.h:156
Definition file.py:1
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:6
char * nc
Definition civetweb.c:8348
char * nonce
Definition civetweb.c:8348
char * cnonce
Definition civetweb.c:8348
char * uri
Definition civetweb.c:8348
char * user
Definition civetweb.c:8348
char * qop
Definition civetweb.c:8348
char * response
Definition civetweb.c:8348
struct mg_connection * conn
Definition civetweb.c:10943
char * file_name
Definition civetweb.c:2541
struct mg_connection * conn
Definition civetweb.c:2540
struct mg_file_stat file
Definition civetweb.c:2542
size_t num_entries
Definition civetweb.c:9577
struct de * entries
Definition civetweb.c:9576
size_t arr_size
Definition civetweb.c:9578
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:2525
int64_t content_len
Definition civetweb.c:2480
struct timespec req_time
Definition civetweb.c:2477
int64_t consumed_content
Definition civetweb.c:2486
char * path_info
Definition civetweb.c:2495
int64_t num_bytes_sent
Definition civetweb.c:2479
int connection_type
Definition civetweb.c:2448
pthread_mutex_t mutex
Definition civetweb.c:2527
struct socket client
Definition civetweb.c:2469
struct mg_response_info response_info
Definition civetweb.c:2457
void * tls_user_ptr
Definition civetweb.c:2533
struct mg_request_info request_info
Definition civetweb.c:2456
struct mg_context * phys_ctx
Definition civetweb.c:2459
struct mg_domain_context * dom_ctx
Definition civetweb.c:2460
int in_error_handler
Definition civetweb.c:2499
time_t conn_birth_time
Definition civetweb.c:2470
int handled_requests
Definition civetweb.c:2516
int last_throttle_bytes
Definition civetweb.c:2526
time_t start_time
Definition civetweb.c:2374
pthread_cond_t sq_empty
Definition civetweb.c:2357
struct socket * squeue
Definition civetweb.c:2352
pthread_t * worker_threadids
Definition civetweb.c:2344
volatile int sq_head
Definition civetweb.c:2354
stop_flag_t stop_flag
Definition civetweb.c:2338
void * user_data
Definition civetweb.c:2395
unsigned long starter_thread_idx
Definition civetweb.c:2345
struct mg_connection * worker_connections
Definition civetweb.c:2325
struct socket * listening_sockets
Definition civetweb.c:2321
char * systemName
Definition civetweb.c:2373
pthread_t masterthreadid
Definition civetweb.c:2341
int context_type
Definition civetweb.c:2319
pthread_mutex_t thread_mutex
Definition civetweb.c:2339
struct mg_callbacks callbacks
Definition civetweb.c:2394
struct mg_domain_context dd
Definition civetweb.c:2404
struct pollfd * listening_socket_fds
Definition civetweb.c:2322
pthread_cond_t sq_full
Definition civetweb.c:2356
volatile int sq_tail
Definition civetweb.c:2355
unsigned int num_listening_sockets
Definition civetweb.c:2323
unsigned int max_request_size
Definition civetweb.c:2366
unsigned int cfg_worker_threads
Definition civetweb.c:2343
pthread_mutex_t nonce_mutex
Definition civetweb.c:2389
volatile int sq_blocked
Definition civetweb.c:2358
char * config[NUM_OPTIONS]
Definition civetweb.c:2252
unsigned long nonce_count
Definition civetweb.c:2258
int64_t ssl_cert_last_mtime
Definition civetweb.c:2254
uint64_t auth_nonce_mask
Definition civetweb.c:2257
struct mg_domain_context * next
Definition civetweb.c:2266
SSL_CTX * ssl_ctx
Definition civetweb.c:2251
struct mg_handler_info * handlers
Definition civetweb.c:2253
unsigned * code
Definition civetweb.h:1672
size_t text_buffer_size
Definition civetweb.h:1674
uint64_t size
Definition civetweb.c:1863
time_t last_modified
Definition civetweb.c:1864
struct mg_file_stat stat
Definition civetweb.c:1878
struct mg_file_access access
Definition civetweb.c:1879
mg_request_handler handler
Definition civetweb.c:2218
mg_authorization_handler auth_handler
Definition civetweb.c:2232
mg_websocket_close_handler close_handler
Definition civetweb.c:2226
struct mg_handler_info * next
Definition civetweb.c:2238
unsigned int refcount
Definition civetweb.c:2219
mg_websocket_connect_handler connect_handler
Definition civetweb.c:2223
struct mg_websocket_subprotocols * subprotocols
Definition civetweb.c:2229
mg_websocket_data_handler data_handler
Definition civetweb.c:2225
mg_websocket_ready_handler ready_handler
Definition civetweb.c:2224
const char * value
Definition civetweb.h:145
const char * name
Definition civetweb.h:144
const char * name
Definition civetweb.c:10485
void * user_data
Definition civetweb.h:1679
const struct mg_callbacks * callbacks
Definition civetweb.h:1678
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:8499
const char * f_domain
Definition civetweb.c:8498
const char * f_user
Definition civetweb.c:8497
const char * domain
Definition civetweb.c:8495
char buf[256+256+40]
Definition civetweb.c:8496
struct mg_connection * conn
Definition civetweb.c:8493
unsigned char is_ssl
Definition civetweb.c:1898
union usa lsa
Definition civetweb.c:1896
unsigned char ssl_redir
Definition civetweb.c:1899
SOCKET sock
Definition civetweb.c:1895
unsigned char in_use
Definition civetweb.c:1901
union usa rsa
Definition civetweb.c:1897
void(* ptr)(void)
const char * name
enum ssl_func_category required
size_t len
Definition civetweb.c:1858
const char * ptr
Definition civetweb.c:1857
mg_websocket_close_handler close_handler
Definition civetweb.c:18053
mg_websocket_data_handler data_handler
Definition civetweb.c:18052
struct mg_connection * conn
Definition civetweb.c:18051
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
struct sockaddr sa
Definition civetweb.c:1825
struct sockaddr_in sin
Definition civetweb.c:1826
static void output()