Coverage Report

Created: 2023-03-26 07:35

/src/civetweb/src/civetweb.c
Line
Count
Source (jump to first uncovered line)
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
#ifndef GCC_VERSION
25
#define GCC_VERSION                                                            \
26
  (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
27
#endif
28
#if GCC_VERSION >= 40500
29
/* gcc diagnostic pragmas available */
30
#define GCC_DIAGNOSTIC
31
#endif
32
#endif
33
34
#if defined(GCC_DIAGNOSTIC)
35
/* Disable unused macros warnings - not all defines are required
36
 * for all systems and all compilers. */
37
#pragma GCC diagnostic ignored "-Wunused-macros"
38
/* A padding warning is just plain useless */
39
#pragma GCC diagnostic ignored "-Wpadded"
40
#endif
41
42
#if defined(__clang__) /* GCC does not (yet) support this pragma */
43
/* We must set some flags for the headers we include. These flags
44
 * are reserved ids according to C99, so we need to disable a
45
 * warning for that. */
46
#pragma GCC diagnostic push
47
#pragma GCC diagnostic ignored "-Wreserved-id-macro"
48
#endif
49
50
#if defined(_WIN32)
51
#if !defined(_CRT_SECURE_NO_WARNINGS)
52
#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
53
#endif
54
#if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
55
#define _WIN32_WINNT 0x0502
56
#endif
57
#else
58
#if !defined(_GNU_SOURCE)
59
#define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
60
#endif
61
#if defined(__linux__) && !defined(_XOPEN_SOURCE)
62
#define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
63
#endif
64
#if defined(__LSB_VERSION__) || defined(__sun)
65
#define NEED_TIMEGM
66
#define NO_THREAD_NAME
67
#endif
68
#if !defined(_LARGEFILE_SOURCE)
69
#define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
70
#endif
71
#if !defined(_FILE_OFFSET_BITS)
72
#define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
73
#endif
74
#if !defined(__STDC_FORMAT_MACROS)
75
#define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
76
#endif
77
#if !defined(__STDC_LIMIT_MACROS)
78
#define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
79
#endif
80
#if !defined(_DARWIN_UNLIMITED_SELECT)
81
#define _DARWIN_UNLIMITED_SELECT
82
#endif
83
#if defined(__sun)
84
#define __EXTENSIONS__  /* to expose flockfile and friends in stdio.h */
85
#define __inline inline /* not recognized on older compiler versions */
86
#endif
87
#endif
88
89
#if defined(__clang__)
90
/* Enable reserved-id-macro warning again. */
91
#pragma GCC diagnostic pop
92
#endif
93
94
95
#if defined(USE_LUA)
96
#define USE_TIMERS
97
#endif
98
99
#if defined(_MSC_VER)
100
/* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
101
#pragma warning(disable : 4306)
102
/* conditional expression is constant: introduced by FD_SET(..) */
103
#pragma warning(disable : 4127)
104
/* non-constant aggregate initializer: issued due to missing C99 support */
105
#pragma warning(disable : 4204)
106
/* padding added after data member */
107
#pragma warning(disable : 4820)
108
/* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
109
#pragma warning(disable : 4668)
110
/* no function prototype given: converting '()' to '(void)' */
111
#pragma warning(disable : 4255)
112
/* function has been selected for automatic inline expansion */
113
#pragma warning(disable : 4711)
114
#endif
115
116
117
/* This code uses static_assert to check some conditions.
118
 * Unfortunately some compilers still do not support it, so we have a
119
 * replacement function here. */
120
#if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
121
#define mg_static_assert _Static_assert
122
#elif defined(__cplusplus) && __cplusplus >= 201103L
123
#define mg_static_assert static_assert
124
#else
125
char static_assert_replacement[1];
126
#define mg_static_assert(cond, txt)                                            \
127
  extern char static_assert_replacement[(cond) ? 1 : -1]
128
#endif
129
130
mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
131
                 "int data type size check");
132
mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
133
                 "pointer data type size check");
134
mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
135
136
137
/* Select queue implementation. Diagnosis features originally only implemented
138
 * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
139
 * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
140
 * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
141
 * implementation, since the queue length is independent from the number of
142
 * worker threads there, while the new queue is one element per worker thread.
143
 *
144
 */
145
#if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
146
/* The queues are exclusive or - only one can be used. */
147
#error                                                                         \
148
    "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
149
#endif
150
#if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
151
/* Use a default implementation */
152
#define NO_ALTERNATIVE_QUEUE
153
#endif
154
155
#if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
156
/* File system access:
157
 * NO_FILES = do not serve any files from the file system automatically.
158
 * However, with NO_FILES CivetWeb may still write log files, read access
159
 * control files, default error page files or use API functions like
160
 * mg_send_file in callbacks to send files from the server local
161
 * file system.
162
 * NO_FILES only disables the automatic mapping between URLs and local
163
 * file names.
164
 * NO_FILESYSTEM = do not access any file at all. Useful for embedded
165
 * devices without file system. Logging to files in not available
166
 * (use callbacks instead) and API functions like mg_send_file are not
167
 * available.
168
 * If NO_FILESYSTEM is set, NO_FILES must be set as well.
169
 */
170
#error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
171
#endif
172
173
/* DTL -- including winsock2.h works better if lean and mean */
174
#if !defined(WIN32_LEAN_AND_MEAN)
175
#define WIN32_LEAN_AND_MEAN
176
#endif
177
178
#if defined(__SYMBIAN32__)
179
/* According to https://en.wikipedia.org/wiki/Symbian#History,
180
 * Symbian is no longer maintained since 2014-01-01.
181
 * Support for Symbian has been removed from CivetWeb
182
 */
183
#error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
184
#endif /* __SYMBIAN32__ */
185
186
#if defined(__ZEPHYR__)
187
#include <ctype.h>
188
#include <fcntl.h>
189
#include <netdb.h>
190
#include <poll.h>
191
#include <pthread.h>
192
#include <stdio.h>
193
#include <stdlib.h>
194
#include <string.h>
195
#include <sys/socket.h>
196
#include <time.h>
197
198
#include <zephyr/kernel.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
211
K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
212
K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
213
                            MAX_WORKER_THREADS,
214
                            ZEPHYR_STACK_SIZE);
215
216
static 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)
228
static 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
208
  do {                                                                       \
244
208
  } 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)
266
void __cyg_profile_func_enter(void *this_fn, void *call_site)
267
    __attribute__((no_instrument_function));
268
269
void __cyg_profile_func_exit(void *this_fn, void *call_site)
270
    __attribute__((no_instrument_function));
271
272
void
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
280
void
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
34
#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__) && defined(__APPLE__) /* 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 */
379
static 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. */
425
static 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
#define ERROR_TRY_AGAIN(err) ((err) == WSAEWOULDBLOCK)
443
#else
444
/* Unix might return different error codes indicating to try again.
445
 * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
446
 * decades ago, but better check both and let the compiler optimize it. */
447
#define ERROR_TRY_AGAIN(err)                                                   \
448
34
  (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
449
#endif
450
451
#if defined(USE_ZLIB)
452
#include "zconf.h"
453
#include "zlib.h"
454
#endif
455
456
457
/********************************************************************/
458
/* CivetWeb configuration defines */
459
/********************************************************************/
460
461
/* Maximum number of threads that can be configured.
462
 * The number of threads actually created depends on the "num_threads"
463
 * configuration parameter, but this is the upper limit. */
464
#if !defined(MAX_WORKER_THREADS)
465
2
#define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
466
#endif
467
468
/* Timeout interval for select/poll calls.
469
 * The timeouts depend on "*_timeout_ms" configuration values, but long
470
 * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
471
 * This reduces the time required to stop the server. */
472
#if !defined(SOCKET_TIMEOUT_QUANTUM)
473
124
#define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
474
#endif
475
476
/* Do not try to compress files smaller than this limit. */
477
#if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
478
0
#define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
479
#endif
480
481
#if !defined(PASSWORDS_FILE_NAME)
482
0
#define PASSWORDS_FILE_NAME ".htpasswd"
483
#endif
484
485
/* Initial buffer size for all CGI environment variables. In case there is
486
 * not enough space, another block is allocated. */
487
#if !defined(CGI_ENVIRONMENT_SIZE)
488
0
#define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
489
#endif
490
491
/* Maximum number of environment variables. */
492
#if !defined(MAX_CGI_ENVIR_VARS)
493
0
#define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
494
#endif
495
496
/* General purpose buffer size. */
497
#if !defined(MG_BUF_LEN) /* in bytes */
498
0
#define MG_BUF_LEN (1024 * 8)
499
#endif
500
501
502
/********************************************************************/
503
504
/* Helper macros */
505
#if !defined(ARRAY_SIZE)
506
0
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
507
#endif
508
509
#include <stdint.h>
510
511
/* Standard defines */
512
#if !defined(INT64_MAX)
513
#define INT64_MAX (9223372036854775807)
514
#endif
515
516
#define SHUTDOWN_RD (0)
517
34
#define SHUTDOWN_WR (1)
518
#define SHUTDOWN_BOTH (2)
519
520
mg_static_assert(MAX_WORKER_THREADS >= 1,
521
                 "worker threads must be a positive number");
522
523
mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
524
                 "size_t data type size check");
525
526
527
#if defined(_WIN32) /* WINDOWS include block */
528
#include <malloc.h> /* *alloc( */
529
#include <stdlib.h> /* *alloc( */
530
#include <time.h>   /* struct timespec */
531
#include <windows.h>
532
#include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
533
#include <ws2tcpip.h>
534
535
typedef const char *SOCK_OPT_TYPE;
536
537
/* For a detailed description of these *_PATH_MAX defines, see
538
 * https://github.com/civetweb/civetweb/issues/937. */
539
540
/* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
541
 * null termination, rounded up to the next 4 bytes boundary */
542
#define UTF8_PATH_MAX (3 * 260)
543
/* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
544
 * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
545
#define UTF16_PATH_MAX (260)
546
547
#if !defined(_IN_PORT_T)
548
#if !defined(in_port_t)
549
#define in_port_t u_short
550
#endif
551
#endif
552
553
#if defined(_WIN32_WCE)
554
#error "WinCE support has ended"
555
#endif
556
557
#include <direct.h>
558
#include <io.h>
559
#include <process.h>
560
561
562
#define MAKEUQUAD(lo, hi)                                                      \
563
  ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
564
#define RATE_DIFF (10000000) /* 100 nsecs */
565
#define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
566
#define SYS2UNIX_TIME(lo, hi)                                                  \
567
  ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
568
569
/* Visual Studio 6 does not know __func__ or __FUNCTION__
570
 * The rest of MS compilers use __FUNCTION__, not C99 __func__
571
 * Also use _strtoui64 on modern M$ compilers */
572
#if defined(_MSC_VER)
573
#if (_MSC_VER < 1300)
574
#define STRX(x) #x
575
#define STR(x) STRX(x)
576
#define __func__ __FILE__ ":" STR(__LINE__)
577
#define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
578
#define strtoll(x, y, z) (_atoi64(x))
579
#else
580
#define __func__ __FUNCTION__
581
#define strtoull(x, y, z) (_strtoui64(x, y, z))
582
#define strtoll(x, y, z) (_strtoi64(x, y, z))
583
#endif
584
#endif /* _MSC_VER */
585
586
587
#define ERRNO ((int)(GetLastError()))
588
#define NO_SOCKLEN_T
589
590
591
#if defined(_WIN64) || defined(__MINGW64__)
592
#if !defined(SSL_LIB)
593
594
#if defined(OPENSSL_API_3_0)
595
#define SSL_LIB "libssl-3-x64.dll"
596
#define CRYPTO_LIB "libcrypto-3-x64.dll"
597
#endif
598
599
#if defined(OPENSSL_API_1_1)
600
#define SSL_LIB "libssl-1_1-x64.dll"
601
#define CRYPTO_LIB "libcrypto-1_1-x64.dll"
602
#endif /* OPENSSL_API_1_1 */
603
604
#if defined(OPENSSL_API_1_0)
605
#define SSL_LIB "ssleay64.dll"
606
#define CRYPTO_LIB "libeay64.dll"
607
#endif /* OPENSSL_API_1_0 */
608
609
#endif
610
#else /* defined(_WIN64) || defined(__MINGW64__) */
611
#if !defined(SSL_LIB)
612
613
#if defined(OPENSSL_API_3_0)
614
#define SSL_LIB "libssl-3.dll"
615
#define CRYPTO_LIB "libcrypto-3.dll"
616
#endif
617
618
#if defined(OPENSSL_API_1_1)
619
#define SSL_LIB "libssl-1_1.dll"
620
#define CRYPTO_LIB "libcrypto-1_1.dll"
621
#endif /* OPENSSL_API_1_1 */
622
623
#if defined(OPENSSL_API_1_0)
624
#define SSL_LIB "ssleay32.dll"
625
#define CRYPTO_LIB "libeay32.dll"
626
#endif /* OPENSSL_API_1_0 */
627
628
#endif /* SSL_LIB */
629
#endif /* defined(_WIN64) || defined(__MINGW64__) */
630
631
632
#define O_NONBLOCK (0)
633
#if !defined(W_OK)
634
#define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
635
#endif
636
#define _POSIX_
637
#define INT64_FMT "I64d"
638
#define UINT64_FMT "I64u"
639
640
#define WINCDECL __cdecl
641
#define vsnprintf_impl _vsnprintf
642
#define access _access
643
#define mg_sleep(x) (Sleep(x))
644
645
#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
646
#if !defined(popen)
647
#define popen(x, y) (_popen(x, y))
648
#endif
649
#if !defined(pclose)
650
#define pclose(x) (_pclose(x))
651
#endif
652
#define close(x) (_close(x))
653
#define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
654
#define RTLD_LAZY (0)
655
#define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
656
#define fdopen(x, y) (_fdopen((x), (y)))
657
#define write(x, y, z) (_write((x), (y), (unsigned)z))
658
#define read(x, y, z) (_read((x), (y), (unsigned)z))
659
#define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
660
#define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
661
#define sleep(x) (Sleep((x)*1000))
662
#define rmdir(x) (_rmdir(x))
663
#if defined(_WIN64) || !defined(__MINGW32__)
664
/* Only MinGW 32 bit is missing this function */
665
#define timegm(x) (_mkgmtime(x))
666
#else
667
time_t timegm(struct tm *tm);
668
#define NEED_TIMEGM
669
#endif
670
671
672
#if !defined(fileno)
673
#define fileno(x) (_fileno(x))
674
#endif /* !fileno MINGW #defines fileno */
675
676
typedef struct {
677
  CRITICAL_SECTION sec; /* Immovable */
678
} pthread_mutex_t;
679
typedef DWORD pthread_key_t;
680
typedef HANDLE pthread_t;
681
typedef struct {
682
  pthread_mutex_t threadIdSec;
683
  struct mg_workerTLS *waiting_thread; /* The chain of threads */
684
} pthread_cond_t;
685
686
#if !defined(__clockid_t_defined)
687
typedef DWORD clockid_t;
688
#endif
689
#if !defined(CLOCK_MONOTONIC)
690
#define CLOCK_MONOTONIC (1)
691
#endif
692
#if !defined(CLOCK_REALTIME)
693
#define CLOCK_REALTIME (2)
694
#endif
695
#if !defined(CLOCK_THREAD)
696
#define CLOCK_THREAD (3)
697
#endif
698
#if !defined(CLOCK_PROCESS)
699
#define CLOCK_PROCESS (4)
700
#endif
701
702
703
#if defined(_MSC_VER) && (_MSC_VER >= 1900)
704
#define _TIMESPEC_DEFINED
705
#endif
706
#if !defined(_TIMESPEC_DEFINED)
707
struct timespec {
708
  time_t tv_sec; /* seconds */
709
  long tv_nsec;  /* nanoseconds */
710
};
711
#endif
712
713
#if !defined(WIN_PTHREADS_TIME_H)
714
#define MUST_IMPLEMENT_CLOCK_GETTIME
715
#endif
716
717
#if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
718
#define clock_gettime mg_clock_gettime
719
static int
720
clock_gettime(clockid_t clk_id, struct timespec *tp)
721
{
722
  FILETIME ft;
723
  ULARGE_INTEGER li, li2;
724
  BOOL ok = FALSE;
725
  double d;
726
  static double perfcnt_per_sec = 0.0;
727
  static BOOL initialized = FALSE;
728
729
  if (!initialized) {
730
    QueryPerformanceFrequency((LARGE_INTEGER *)&li);
731
    perfcnt_per_sec = 1.0 / li.QuadPart;
732
    initialized = TRUE;
733
  }
734
735
  if (tp) {
736
    memset(tp, 0, sizeof(*tp));
737
738
    if (clk_id == CLOCK_REALTIME) {
739
740
      /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
741
      GetSystemTimeAsFileTime(&ft);
742
      li.LowPart = ft.dwLowDateTime;
743
      li.HighPart = ft.dwHighDateTime;
744
      li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
745
      tp->tv_sec = (time_t)(li.QuadPart / 10000000);
746
      tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
747
      ok = TRUE;
748
      /* END: CLOCK_REALTIME */
749
750
    } else if (clk_id == CLOCK_MONOTONIC) {
751
752
      /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
753
      QueryPerformanceCounter((LARGE_INTEGER *)&li);
754
      d = li.QuadPart * perfcnt_per_sec;
755
      tp->tv_sec = (time_t)d;
756
      d -= (double)tp->tv_sec;
757
      tp->tv_nsec = (long)(d * 1.0E9);
758
      ok = TRUE;
759
      /* END: CLOCK_MONOTONIC */
760
761
    } else if (clk_id == CLOCK_THREAD) {
762
763
      /* BEGIN: CLOCK_THREAD = CPU usage of thread */
764
      FILETIME t_create, t_exit, t_kernel, t_user;
765
      if (GetThreadTimes(GetCurrentThread(),
766
                         &t_create,
767
                         &t_exit,
768
                         &t_kernel,
769
                         &t_user)) {
770
        li.LowPart = t_user.dwLowDateTime;
771
        li.HighPart = t_user.dwHighDateTime;
772
        li2.LowPart = t_kernel.dwLowDateTime;
773
        li2.HighPart = t_kernel.dwHighDateTime;
774
        li.QuadPart += li2.QuadPart;
775
        tp->tv_sec = (time_t)(li.QuadPart / 10000000);
776
        tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
777
        ok = TRUE;
778
      }
779
      /* END: CLOCK_THREAD */
780
781
    } else if (clk_id == CLOCK_PROCESS) {
782
783
      /* BEGIN: CLOCK_PROCESS = CPU usage of process */
784
      FILETIME t_create, t_exit, t_kernel, t_user;
785
      if (GetProcessTimes(GetCurrentProcess(),
786
                          &t_create,
787
                          &t_exit,
788
                          &t_kernel,
789
                          &t_user)) {
790
        li.LowPart = t_user.dwLowDateTime;
791
        li.HighPart = t_user.dwHighDateTime;
792
        li2.LowPart = t_kernel.dwLowDateTime;
793
        li2.HighPart = t_kernel.dwHighDateTime;
794
        li.QuadPart += li2.QuadPart;
795
        tp->tv_sec = (time_t)(li.QuadPart / 10000000);
796
        tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
797
        ok = TRUE;
798
      }
799
      /* END: CLOCK_PROCESS */
800
801
    } else {
802
803
      /* BEGIN: unknown clock */
804
      /* ok = FALSE; already set by init */
805
      /* END: unknown clock */
806
    }
807
  }
808
809
  return ok ? 0 : -1;
810
}
811
#endif
812
813
814
#define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
815
816
static int pthread_mutex_lock(pthread_mutex_t *);
817
static int pthread_mutex_unlock(pthread_mutex_t *);
818
static void path_to_unicode(const struct mg_connection *conn,
819
                            const char *path,
820
                            wchar_t *wbuf,
821
                            size_t wbuf_len);
822
823
/* All file operations need to be rewritten to solve #246. */
824
825
struct mg_file;
826
827
static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
828
829
830
/* POSIX dirent interface */
831
struct dirent {
832
  char d_name[UTF8_PATH_MAX];
833
};
834
835
typedef struct DIR {
836
  HANDLE handle;
837
  WIN32_FIND_DATAW info;
838
  struct dirent result;
839
} DIR;
840
841
#if defined(HAVE_POLL)
842
#define mg_pollfd pollfd
843
#else
844
struct mg_pollfd {
845
  SOCKET fd;
846
  short events;
847
  short revents;
848
};
849
#endif
850
851
/* Mark required libraries */
852
#if defined(_MSC_VER)
853
#pragma comment(lib, "Ws2_32.lib")
854
#endif
855
856
#else /* defined(_WIN32) - WINDOWS vs UNIX include block */
857
858
#include <inttypes.h>
859
860
/* Linux & co. internally use UTF8 */
861
0
#define UTF8_PATH_MAX (PATH_MAX)
862
863
typedef const void *SOCK_OPT_TYPE;
864
865
#if defined(ANDROID)
866
typedef unsigned short int in_port_t;
867
#endif
868
869
#if !defined(__ZEPHYR__)
870
#include <arpa/inet.h>
871
#include <ctype.h>
872
#include <dirent.h>
873
#include <grp.h>
874
#include <limits.h>
875
#include <netdb.h>
876
#include <netinet/in.h>
877
#include <netinet/tcp.h>
878
#include <poll.h>
879
#include <pthread.h>
880
#include <pwd.h>
881
#include <stdarg.h>
882
#include <stddef.h>
883
#include <stdio.h>
884
#include <stdlib.h>
885
#include <string.h>
886
#include <sys/socket.h>
887
#include <sys/time.h>
888
#include <sys/utsname.h>
889
#include <sys/wait.h>
890
#include <time.h>
891
#include <unistd.h>
892
#if defined(USE_X_DOM_SOCKET)
893
#include <sys/un.h>
894
#endif
895
#endif
896
897
203
#define vsnprintf_impl vsnprintf
898
899
#if !defined(NO_SSL_DL) && !defined(NO_SSL)
900
#include <dlfcn.h>
901
#endif
902
903
#if defined(__MACH__) && defined(__APPLE__)
904
#define SSL_LIB "libssl.dylib"
905
#define CRYPTO_LIB "libcrypto.dylib"
906
#else
907
#if !defined(SSL_LIB)
908
0
#define SSL_LIB "libssl.so"
909
#endif
910
#if !defined(CRYPTO_LIB)
911
0
#define CRYPTO_LIB "libcrypto.so"
912
#endif
913
#endif
914
#if !defined(O_BINARY)
915
#define O_BINARY (0)
916
#endif /* O_BINARY */
917
36
#define closesocket(a) (close(a))
918
0
#define mg_mkdir(conn, path, mode) (mkdir(path, mode))
919
0
#define mg_remove(conn, x) (remove(x))
920
198
#define mg_sleep(x) (usleep((x)*1000))
921
0
#define mg_opendir(conn, x) (opendir(x))
922
0
#define mg_closedir(x) (closedir(x))
923
0
#define mg_readdir(x) (readdir(x))
924
112
#define ERRNO (errno)
925
174
#define INVALID_SOCKET (-1)
926
0
#define INT64_FMT PRId64
927
0
#define UINT64_FMT PRIu64
928
typedef int SOCKET;
929
#define WINCDECL
930
931
#if defined(__hpux)
932
/* HPUX 11 does not have monotonic, fall back to realtime */
933
#if !defined(CLOCK_MONOTONIC)
934
#define CLOCK_MONOTONIC CLOCK_REALTIME
935
#endif
936
937
/* HPUX defines socklen_t incorrectly as size_t which is 64bit on
938
 * Itanium.  Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
939
 * the prototypes use int* rather than socklen_t* which matches the
940
 * actual library expectation.  When called with the wrong size arg
941
 * accept() returns a zero client inet addr and check_acl() always
942
 * fails.  Since socklen_t is widely used below, just force replace
943
 * their typedef with int. - DTL
944
 */
945
#define socklen_t int
946
#endif /* hpux */
947
948
#define mg_pollfd pollfd
949
950
#endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
951
952
/* In case our C library is missing "timegm", provide an implementation */
953
#if defined(NEED_TIMEGM)
954
static inline int
955
is_leap(int y)
956
{
957
  return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
958
}
959
960
static inline int
961
count_leap(int y)
962
{
963
  return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
964
}
965
966
time_t
967
timegm(struct tm *tm)
968
{
969
  static const unsigned short ydays[] = {
970
      0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
971
  int year = tm->tm_year + 1900;
972
  int mon = tm->tm_mon;
973
  int mday = tm->tm_mday - 1;
974
  int hour = tm->tm_hour;
975
  int min = tm->tm_min;
976
  int sec = tm->tm_sec;
977
978
  if (year < 1970 || mon < 0 || mon > 11 || mday < 0
979
      || (mday >= ydays[mon + 1] - ydays[mon]
980
                      + (mon == 1 && is_leap(year) ? 1 : 0))
981
      || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
982
    return -1;
983
984
  time_t res = year - 1970;
985
  res *= 365;
986
  res += mday;
987
  res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
988
  res += count_leap(year);
989
990
  res *= 24;
991
  res += hour;
992
  res *= 60;
993
  res += min;
994
  res *= 60;
995
  res += sec;
996
  return res;
997
}
998
#endif /* NEED_TIMEGM */
999
1000
1001
/* va_copy should always be a macro, C99 and C++11 - DTL */
1002
#if !defined(va_copy)
1003
#define va_copy(x, y) ((x) = (y))
1004
#endif
1005
1006
1007
#if defined(_WIN32)
1008
/* Create substitutes for POSIX functions in Win32. */
1009
1010
#if defined(GCC_DIAGNOSTIC)
1011
/* Show no warning in case system functions are not used. */
1012
#pragma GCC diagnostic push
1013
#pragma GCC diagnostic ignored "-Wunused-function"
1014
#endif
1015
1016
1017
static pthread_mutex_t global_log_file_lock;
1018
1019
FUNCTION_MAY_BE_UNUSED
1020
static DWORD
1021
pthread_self(void)
1022
{
1023
  return GetCurrentThreadId();
1024
}
1025
1026
1027
FUNCTION_MAY_BE_UNUSED
1028
static int
1029
pthread_key_create(
1030
    pthread_key_t *key,
1031
    void (*_ignored)(void *) /* destructor not supported for Windows */
1032
)
1033
{
1034
  (void)_ignored;
1035
1036
  if ((key != 0)) {
1037
    *key = TlsAlloc();
1038
    return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
1039
  }
1040
  return -2;
1041
}
1042
1043
1044
FUNCTION_MAY_BE_UNUSED
1045
static int
1046
pthread_key_delete(pthread_key_t key)
1047
{
1048
  return TlsFree(key) ? 0 : 1;
1049
}
1050
1051
1052
FUNCTION_MAY_BE_UNUSED
1053
static int
1054
pthread_setspecific(pthread_key_t key, void *value)
1055
{
1056
  return TlsSetValue(key, value) ? 0 : 1;
1057
}
1058
1059
1060
FUNCTION_MAY_BE_UNUSED
1061
static void *
1062
pthread_getspecific(pthread_key_t key)
1063
{
1064
  return TlsGetValue(key);
1065
}
1066
1067
#if defined(GCC_DIAGNOSTIC)
1068
/* Enable unused function warning again */
1069
#pragma GCC diagnostic pop
1070
#endif
1071
1072
static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
1073
#else
1074
static pthread_mutexattr_t pthread_mutex_attr;
1075
#endif /* _WIN32 */
1076
1077
1078
#if defined(GCC_DIAGNOSTIC)
1079
/* Show no warning in case system functions are not used. */
1080
#pragma GCC diagnostic push
1081
#pragma GCC diagnostic ignored "-Wunused-function"
1082
#endif /* defined(GCC_DIAGNOSTIC) */
1083
#if defined(__clang__)
1084
/* Show no warning in case system functions are not used. */
1085
#pragma clang diagnostic push
1086
#pragma clang diagnostic ignored "-Wunused-function"
1087
#endif
1088
1089
static pthread_mutex_t global_lock_mutex;
1090
1091
1092
FUNCTION_MAY_BE_UNUSED
1093
static void
1094
mg_global_lock(void)
1095
2
{
1096
2
  (void)pthread_mutex_lock(&global_lock_mutex);
1097
2
}
1098
1099
1100
FUNCTION_MAY_BE_UNUSED
1101
static void
1102
mg_global_unlock(void)
1103
2
{
1104
2
  (void)pthread_mutex_unlock(&global_lock_mutex);
1105
2
}
1106
1107
1108
#if defined(_WIN64)
1109
mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
1110
#elif defined(_WIN32)
1111
mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
1112
#endif
1113
1114
1115
/* Atomic functions working on ptrdiff_t ("signed size_t").
1116
 * Operations: Increment, Decrement, Add, Maximum.
1117
 * Up to size_t, they do not an atomic "load" operation.
1118
 */
1119
FUNCTION_MAY_BE_UNUSED
1120
static ptrdiff_t
1121
mg_atomic_inc(volatile ptrdiff_t *addr)
1122
102
{
1123
102
  ptrdiff_t ret;
1124
1125
#if defined(_WIN64) && !defined(NO_ATOMICS)
1126
  ret = InterlockedIncrement64(addr);
1127
#elif defined(_WIN32) && !defined(NO_ATOMICS)
1128
  ret = InterlockedIncrement(addr);
1129
#elif defined(__GNUC__)                                                        \
1130
    && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))           \
1131
    && !defined(NO_ATOMICS)
1132
102
  ret = __sync_add_and_fetch(addr, 1);
1133
#else
1134
  mg_global_lock();
1135
  ret = (++(*addr));
1136
  mg_global_unlock();
1137
#endif
1138
102
  return ret;
1139
102
}
1140
1141
1142
FUNCTION_MAY_BE_UNUSED
1143
static ptrdiff_t
1144
mg_atomic_dec(volatile ptrdiff_t *addr)
1145
0
{
1146
0
  ptrdiff_t ret;
1147
1148
#if defined(_WIN64) && !defined(NO_ATOMICS)
1149
  ret = InterlockedDecrement64(addr);
1150
#elif defined(_WIN32) && !defined(NO_ATOMICS)
1151
  ret = InterlockedDecrement(addr);
1152
#elif defined(__GNUC__)                                                        \
1153
    && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))           \
1154
    && !defined(NO_ATOMICS)
1155
0
  ret = __sync_sub_and_fetch(addr, 1);
1156
#else
1157
  mg_global_lock();
1158
  ret = (--(*addr));
1159
  mg_global_unlock();
1160
#endif
1161
0
  return ret;
1162
0
}
1163
1164
1165
#if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
1166
static ptrdiff_t
1167
mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
1168
{
1169
  ptrdiff_t ret;
1170
1171
#if defined(_WIN64) && !defined(NO_ATOMICS)
1172
  ret = InterlockedAdd64(addr, value);
1173
#elif defined(_WIN32) && !defined(NO_ATOMICS)
1174
  ret = InterlockedExchangeAdd(addr, value) + value;
1175
#elif defined(__GNUC__)                                                        \
1176
    && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))           \
1177
    && !defined(NO_ATOMICS)
1178
  ret = __sync_add_and_fetch(addr, value);
1179
#else
1180
  mg_global_lock();
1181
  *addr += value;
1182
  ret = (*addr);
1183
  mg_global_unlock();
1184
#endif
1185
  return ret;
1186
}
1187
1188
1189
FUNCTION_MAY_BE_UNUSED
1190
static ptrdiff_t
1191
mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
1192
                           ptrdiff_t oldval,
1193
                           ptrdiff_t newval)
1194
{
1195
  ptrdiff_t ret;
1196
1197
#if defined(_WIN64) && !defined(NO_ATOMICS)
1198
  ret = InterlockedCompareExchange64(addr, newval, oldval);
1199
#elif defined(_WIN32) && !defined(NO_ATOMICS)
1200
  ret = InterlockedCompareExchange(addr, newval, oldval);
1201
#elif defined(__GNUC__)                                                        \
1202
    && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))           \
1203
    && !defined(NO_ATOMICS)
1204
  ret = __sync_val_compare_and_swap(addr, oldval, newval);
1205
#else
1206
  mg_global_lock();
1207
  ret = *addr;
1208
  if ((ret != newval) && (ret == oldval)) {
1209
    *addr = newval;
1210
  }
1211
  mg_global_unlock();
1212
#endif
1213
  return ret;
1214
}
1215
1216
1217
static void
1218
mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
1219
{
1220
  register ptrdiff_t tmp = *addr;
1221
1222
#if defined(_WIN64) && !defined(NO_ATOMICS)
1223
  while (tmp < value) {
1224
    tmp = InterlockedCompareExchange64(addr, value, tmp);
1225
  }
1226
#elif defined(_WIN32) && !defined(NO_ATOMICS)
1227
  while (tmp < value) {
1228
    tmp = InterlockedCompareExchange(addr, value, tmp);
1229
  }
1230
#elif defined(__GNUC__)                                                        \
1231
    && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))           \
1232
    && !defined(NO_ATOMICS)
1233
  while (tmp < value) {
1234
    tmp = __sync_val_compare_and_swap(addr, tmp, value);
1235
  }
1236
#else
1237
  mg_global_lock();
1238
  if (*addr < value) {
1239
    *addr = value;
1240
  }
1241
  mg_global_unlock();
1242
#endif
1243
}
1244
1245
1246
static int64_t
1247
mg_atomic_add64(volatile int64_t *addr, int64_t value)
1248
{
1249
  int64_t ret;
1250
1251
#if defined(_WIN64) && !defined(NO_ATOMICS)
1252
  ret = InterlockedAdd64(addr, value);
1253
#elif defined(_WIN32) && !defined(NO_ATOMICS)
1254
  ret = InterlockedExchangeAdd64(addr, value) + value;
1255
#elif defined(__GNUC__)                                                        \
1256
    && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))           \
1257
    && !defined(NO_ATOMICS)
1258
  ret = __sync_add_and_fetch(addr, value);
1259
#else
1260
  mg_global_lock();
1261
  *addr += value;
1262
  ret = (*addr);
1263
  mg_global_unlock();
1264
#endif
1265
  return ret;
1266
}
1267
#endif
1268
1269
1270
#if defined(GCC_DIAGNOSTIC)
1271
/* Show no warning in case system functions are not used. */
1272
#pragma GCC diagnostic pop
1273
#endif /* defined(GCC_DIAGNOSTIC) */
1274
#if defined(__clang__)
1275
/* Show no warning in case system functions are not used. */
1276
#pragma clang diagnostic pop
1277
#endif
1278
1279
1280
#if defined(USE_SERVER_STATS)
1281
1282
struct mg_memory_stat {
1283
  volatile ptrdiff_t totalMemUsed;
1284
  volatile ptrdiff_t maxMemUsed;
1285
  volatile ptrdiff_t blockCount;
1286
};
1287
1288
1289
static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
1290
1291
1292
static void *
1293
mg_malloc_ex(size_t size,
1294
             struct mg_context *ctx,
1295
             const char *file,
1296
             unsigned line)
1297
{
1298
  void *data = malloc(size + 2 * sizeof(uintptr_t));
1299
  void *memory = 0;
1300
  struct mg_memory_stat *mstat = get_memory_stat(ctx);
1301
1302
#if defined(MEMORY_DEBUGGING)
1303
  char mallocStr[256];
1304
#else
1305
  (void)file;
1306
  (void)line;
1307
#endif
1308
1309
  if (data) {
1310
    ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
1311
    mg_atomic_max(&mstat->maxMemUsed, mmem);
1312
1313
    mg_atomic_inc(&mstat->blockCount);
1314
    ((uintptr_t *)data)[0] = size;
1315
    ((uintptr_t *)data)[1] = (uintptr_t)mstat;
1316
    memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1317
  }
1318
1319
#if defined(MEMORY_DEBUGGING)
1320
  sprintf(mallocStr,
1321
          "MEM: %p %5lu alloc   %7lu %4lu --- %s:%u\n",
1322
          memory,
1323
          (unsigned long)size,
1324
          (unsigned long)mstat->totalMemUsed,
1325
          (unsigned long)mstat->blockCount,
1326
          file,
1327
          line);
1328
  DEBUG_TRACE("%s", mallocStr);
1329
#endif
1330
1331
  return memory;
1332
}
1333
1334
1335
static void *
1336
mg_calloc_ex(size_t count,
1337
             size_t size,
1338
             struct mg_context *ctx,
1339
             const char *file,
1340
             unsigned line)
1341
{
1342
  void *data = mg_malloc_ex(size * count, ctx, file, line);
1343
1344
  if (data) {
1345
    memset(data, 0, size * count);
1346
  }
1347
  return data;
1348
}
1349
1350
1351
static void
1352
mg_free_ex(void *memory, const char *file, unsigned line)
1353
{
1354
#if defined(MEMORY_DEBUGGING)
1355
  char mallocStr[256];
1356
#else
1357
  (void)file;
1358
  (void)line;
1359
#endif
1360
1361
  if (memory) {
1362
    void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1363
    uintptr_t size = ((uintptr_t *)data)[0];
1364
    struct mg_memory_stat *mstat =
1365
        (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
1366
    mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
1367
    mg_atomic_dec(&mstat->blockCount);
1368
1369
#if defined(MEMORY_DEBUGGING)
1370
    sprintf(mallocStr,
1371
            "MEM: %p %5lu free    %7lu %4lu --- %s:%u\n",
1372
            memory,
1373
            (unsigned long)size,
1374
            (unsigned long)mstat->totalMemUsed,
1375
            (unsigned long)mstat->blockCount,
1376
            file,
1377
            line);
1378
    DEBUG_TRACE("%s", mallocStr);
1379
#endif
1380
    free(data);
1381
  }
1382
}
1383
1384
1385
static void *
1386
mg_realloc_ex(void *memory,
1387
              size_t newsize,
1388
              struct mg_context *ctx,
1389
              const char *file,
1390
              unsigned line)
1391
{
1392
  void *data;
1393
  void *_realloc;
1394
  uintptr_t oldsize;
1395
1396
#if defined(MEMORY_DEBUGGING)
1397
  char mallocStr[256];
1398
#else
1399
  (void)file;
1400
  (void)line;
1401
#endif
1402
1403
  if (newsize) {
1404
    if (memory) {
1405
      /* Reallocate existing block */
1406
      struct mg_memory_stat *mstat;
1407
      data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1408
      oldsize = ((uintptr_t *)data)[0];
1409
      mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
1410
      _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
1411
      if (_realloc) {
1412
        data = _realloc;
1413
        mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
1414
#if defined(MEMORY_DEBUGGING)
1415
        sprintf(mallocStr,
1416
                "MEM: %p %5lu r-free  %7lu %4lu --- %s:%u\n",
1417
                memory,
1418
                (unsigned long)oldsize,
1419
                (unsigned long)mstat->totalMemUsed,
1420
                (unsigned long)mstat->blockCount,
1421
                file,
1422
                line);
1423
        DEBUG_TRACE("%s", mallocStr);
1424
#endif
1425
        mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
1426
1427
#if defined(MEMORY_DEBUGGING)
1428
        sprintf(mallocStr,
1429
                "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
1430
                memory,
1431
                (unsigned long)newsize,
1432
                (unsigned long)mstat->totalMemUsed,
1433
                (unsigned long)mstat->blockCount,
1434
                file,
1435
                line);
1436
        DEBUG_TRACE("%s", mallocStr);
1437
#endif
1438
        *(uintptr_t *)data = newsize;
1439
        data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1440
      } else {
1441
#if defined(MEMORY_DEBUGGING)
1442
        DEBUG_TRACE("%s", "MEM: realloc failed\n");
1443
#endif
1444
        return _realloc;
1445
      }
1446
    } else {
1447
      /* Allocate new block */
1448
      data = mg_malloc_ex(newsize, ctx, file, line);
1449
    }
1450
  } else {
1451
    /* Free existing block */
1452
    data = 0;
1453
    mg_free_ex(memory, file, line);
1454
  }
1455
1456
  return data;
1457
}
1458
1459
1460
#define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
1461
#define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
1462
#define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
1463
#define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
1464
1465
#define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
1466
#define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
1467
#define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
1468
1469
1470
#else /* USE_SERVER_STATS */
1471
1472
1473
static __inline void *
1474
mg_malloc(size_t a)
1475
170
{
1476
170
  return malloc(a);
1477
170
}
1478
1479
static __inline void *
1480
mg_calloc(size_t a, size_t b)
1481
42
{
1482
42
  return calloc(a, b);
1483
42
}
1484
1485
static __inline void *
1486
mg_realloc(void *a, size_t b)
1487
4
{
1488
4
  return realloc(a, b);
1489
4
}
1490
1491
static __inline void
1492
mg_free(void *a)
1493
214
{
1494
214
  free(a);
1495
214
}
1496
1497
168
#define mg_malloc_ctx(a, c) mg_malloc(a)
1498
4
#define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
1499
4
#define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
1500
#define mg_free_ctx(a, c) mg_free(a)
1501
1502
#endif /* USE_SERVER_STATS */
1503
1504
1505
static void mg_vsnprintf(const struct mg_connection *conn,
1506
                         int *truncated,
1507
                         char *buf,
1508
                         size_t buflen,
1509
                         const char *fmt,
1510
                         va_list ap);
1511
1512
static void mg_snprintf(const struct mg_connection *conn,
1513
                        int *truncated,
1514
                        char *buf,
1515
                        size_t buflen,
1516
                        PRINTF_FORMAT_STRING(const char *fmt),
1517
                        ...) PRINTF_ARGS(5, 6);
1518
1519
/* This following lines are just meant as a reminder to use the mg-functions
1520
 * for memory management */
1521
#if defined(malloc)
1522
#undef malloc
1523
#endif
1524
#if defined(calloc)
1525
#undef calloc
1526
#endif
1527
#if defined(realloc)
1528
#undef realloc
1529
#endif
1530
#if defined(free)
1531
#undef free
1532
#endif
1533
#if defined(snprintf)
1534
#undef snprintf
1535
#endif
1536
#if defined(vsnprintf)
1537
#undef vsnprintf
1538
#endif
1539
#define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
1540
#define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
1541
#define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
1542
#define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
1543
#define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
1544
#if defined(_WIN32)
1545
/* vsnprintf must not be used in any system,
1546
 * but this define only works well for Windows. */
1547
#define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
1548
#endif
1549
1550
1551
/* mg_init_library counter */
1552
static int mg_init_library_called = 0;
1553
1554
#if !defined(NO_SSL)
1555
#if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)                       \
1556
    || defined(OPENSSL_API_3_0)
1557
static int mg_openssl_initialized = 0;
1558
#endif
1559
#if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1)                     \
1560
    && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
1561
#error "Please define OPENSSL_API_#_# or USE_MBEDTLS"
1562
#endif
1563
#if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
1564
#error "Multiple OPENSSL_API versions defined"
1565
#endif
1566
#if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
1567
#error "Multiple OPENSSL_API versions defined"
1568
#endif
1569
#if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
1570
#error "Multiple OPENSSL_API versions defined"
1571
#endif
1572
#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)                      \
1573
     || defined(OPENSSL_API_3_0))                                              \
1574
    && defined(USE_MBEDTLS)
1575
#error "Multiple SSL libraries defined"
1576
#endif
1577
#endif
1578
1579
1580
static pthread_key_t sTlsKey; /* Thread local storage index */
1581
static volatile ptrdiff_t thread_idx_max = 0;
1582
1583
#if defined(MG_LEGACY_INTERFACE)
1584
#define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
1585
#endif
1586
1587
struct mg_workerTLS {
1588
  int is_master;
1589
  unsigned long thread_idx;
1590
  void *user_ptr;
1591
#if defined(_WIN32)
1592
  HANDLE pthread_cond_helper_mutex;
1593
  struct mg_workerTLS *next_waiting_thread;
1594
#endif
1595
  const char *alpn_proto;
1596
#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
1597
  char txtbuf[4];
1598
#endif
1599
};
1600
1601
1602
#if defined(GCC_DIAGNOSTIC)
1603
/* Show no warning in case system functions are not used. */
1604
#pragma GCC diagnostic push
1605
#pragma GCC diagnostic ignored "-Wunused-function"
1606
#endif /* defined(GCC_DIAGNOSTIC) */
1607
#if defined(__clang__)
1608
/* Show no warning in case system functions are not used. */
1609
#pragma clang diagnostic push
1610
#pragma clang diagnostic ignored "-Wunused-function"
1611
#endif
1612
1613
1614
/* Get a unique thread ID as unsigned long, independent from the data type
1615
 * of thread IDs defined by the operating system API.
1616
 * If two calls to mg_current_thread_id  return the same value, they calls
1617
 * are done from the same thread. If they return different values, they are
1618
 * done from different threads. (Provided this function is used in the same
1619
 * process context and threads are not repeatedly created and deleted, but
1620
 * CivetWeb does not do that).
1621
 * This function must match the signature required for SSL id callbacks:
1622
 * CRYPTO_set_id_callback
1623
 */
1624
FUNCTION_MAY_BE_UNUSED
1625
static unsigned long
1626
mg_current_thread_id(void)
1627
0
{
1628
0
#if defined(_WIN32)
1629
0
  return GetCurrentThreadId();
1630
0
#else
1631
0
1632
0
#if defined(__clang__)
1633
0
#pragma clang diagnostic push
1634
0
#pragma clang diagnostic ignored "-Wunreachable-code"
1635
0
  /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
1636
0
   * or not, so one of the two conditions will be unreachable by construction.
1637
0
   * Unfortunately the C standard does not define a way to check this at
1638
0
   * compile time, since the #if preprocessor conditions can not use the
1639
0
   * sizeof operator as an argument. */
1640
0
#endif
1641
0
1642
0
  if (sizeof(pthread_t) > sizeof(unsigned long)) {
1643
0
    /* This is the problematic case for CRYPTO_set_id_callback:
1644
0
     * The OS pthread_t can not be cast to unsigned long. */
1645
0
    struct mg_workerTLS *tls =
1646
0
        (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
1647
0
    if (tls == NULL) {
1648
0
      /* SSL called from an unknown thread: Create some thread index.
1649
0
       */
1650
0
      tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
1651
0
      tls->is_master = -2; /* -2 means "3rd party thread" */
1652
0
      tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
1653
0
      pthread_setspecific(sTlsKey, tls);
1654
0
    }
1655
0
    return tls->thread_idx;
1656
0
  } else {
1657
0
    /* pthread_t may be any data type, so a simple cast to unsigned long
1658
0
     * can rise a warning/error, depending on the platform.
1659
0
     * Here memcpy is used as an anything-to-anything cast. */
1660
0
    unsigned long ret = 0;
1661
0
    pthread_t t = pthread_self();
1662
0
    memcpy(&ret, &t, sizeof(pthread_t));
1663
0
    return ret;
1664
0
  }
1665
0
1666
0
#if defined(__clang__)
1667
0
#pragma clang diagnostic pop
1668
0
#endif
1669
0
1670
0
#endif
1671
0
}
1672
1673
1674
FUNCTION_MAY_BE_UNUSED
1675
static uint64_t
1676
mg_get_current_time_ns(void)
1677
40
{
1678
40
  struct timespec tsnow;
1679
40
  clock_gettime(CLOCK_REALTIME, &tsnow);
1680
40
  return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
1681
40
}
1682
1683
1684
#if defined(GCC_DIAGNOSTIC)
1685
/* Show no warning in case system functions are not used. */
1686
#pragma GCC diagnostic pop
1687
#endif /* defined(GCC_DIAGNOSTIC) */
1688
#if defined(__clang__)
1689
/* Show no warning in case system functions are not used. */
1690
#pragma clang diagnostic pop
1691
#endif
1692
1693
1694
#if defined(NEED_DEBUG_TRACE_FUNC)
1695
static void
1696
DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
1697
{
1698
  va_list args;
1699
  struct timespec tsnow;
1700
1701
  /* Get some operating system independent thread id */
1702
  unsigned long thread_id = mg_current_thread_id();
1703
1704
  clock_gettime(CLOCK_REALTIME, &tsnow);
1705
1706
  flockfile(DEBUG_TRACE_STREAM);
1707
  fprintf(DEBUG_TRACE_STREAM,
1708
          "*** %lu.%09lu %lu %s:%u: ",
1709
          (unsigned long)tsnow.tv_sec,
1710
          (unsigned long)tsnow.tv_nsec,
1711
          thread_id,
1712
          func,
1713
          line);
1714
  va_start(args, fmt);
1715
  vfprintf(DEBUG_TRACE_STREAM, fmt, args);
1716
  va_end(args);
1717
  putc('\n', DEBUG_TRACE_STREAM);
1718
  fflush(DEBUG_TRACE_STREAM);
1719
  funlockfile(DEBUG_TRACE_STREAM);
1720
}
1721
#endif /* NEED_DEBUG_TRACE_FUNC */
1722
1723
1724
#define MD5_STATIC static
1725
#include "md5.inl"
1726
1727
/* Darwin prior to 7.0 and Win32 do not have socklen_t */
1728
#if defined(NO_SOCKLEN_T)
1729
typedef int socklen_t;
1730
#endif /* NO_SOCKLEN_T */
1731
1732
#define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
1733
1734
#if !defined(MSG_NOSIGNAL)
1735
#define MSG_NOSIGNAL (0)
1736
#endif
1737
1738
1739
/* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
1740
#if defined(USE_MBEDTLS)
1741
/* mbedTLS */
1742
#include "mod_mbedtls.inl"
1743
1744
#elif defined(NO_SSL)
1745
/* no SSL */
1746
typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
1747
typedef struct SSL_CTX SSL_CTX;
1748
1749
#elif defined(NO_SSL_DL)
1750
/* OpenSSL without dynamic loading */
1751
#include <openssl/bn.h>
1752
#include <openssl/conf.h>
1753
#include <openssl/crypto.h>
1754
#include <openssl/dh.h>
1755
#include <openssl/engine.h>
1756
#include <openssl/err.h>
1757
#include <openssl/opensslv.h>
1758
#include <openssl/pem.h>
1759
#include <openssl/ssl.h>
1760
#include <openssl/tls1.h>
1761
#include <openssl/x509.h>
1762
1763
#if defined(WOLFSSL_VERSION)
1764
/* Additional defines for WolfSSL, see
1765
 * https://github.com/civetweb/civetweb/issues/583 */
1766
#include "wolfssl_extras.inl"
1767
#endif
1768
1769
#if defined(OPENSSL_IS_BORINGSSL)
1770
/* From boringssl/src/include/openssl/mem.h:
1771
 *
1772
 * OpenSSL has, historically, had a complex set of malloc debugging options.
1773
 * However, that was written in a time before Valgrind and ASAN. Since we now
1774
 * have those tools, the OpenSSL allocation functions are simply macros around
1775
 * the standard memory functions.
1776
 *
1777
 * #define OPENSSL_free free */
1778
#define free free
1779
// disable for boringssl
1780
#define CONF_modules_unload(a) ((void)0)
1781
#define ENGINE_cleanup() ((void)0)
1782
#endif
1783
1784
/* If OpenSSL headers are included, automatically select the API version */
1785
#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
1786
#if !defined(OPENSSL_API_3_0)
1787
#define OPENSSL_API_3_0
1788
#endif
1789
#define OPENSSL_REMOVE_THREAD_STATE()
1790
#else
1791
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1792
#if !defined(OPENSSL_API_1_1)
1793
#define OPENSSL_API_1_1
1794
#endif
1795
#define OPENSSL_REMOVE_THREAD_STATE()
1796
#else
1797
#if !defined(OPENSSL_API_1_0)
1798
#define OPENSSL_API_1_0
1799
#endif
1800
#define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
1801
#endif
1802
#endif
1803
1804
1805
#else
1806
/* SSL loaded dynamically from DLL / shared object */
1807
/* Add all prototypes here, to be independent from OpenSSL source
1808
 * installation. */
1809
#include "openssl_dl.inl"
1810
1811
#endif /* Various SSL bindings */
1812
1813
1814
#if !defined(NO_CACHING)
1815
static const char month_names[][4] = {"Jan",
1816
                                      "Feb",
1817
                                      "Mar",
1818
                                      "Apr",
1819
                                      "May",
1820
                                      "Jun",
1821
                                      "Jul",
1822
                                      "Aug",
1823
                                      "Sep",
1824
                                      "Oct",
1825
                                      "Nov",
1826
                                      "Dec"};
1827
#endif /* !NO_CACHING */
1828
1829
1830
/* Unified socket address. For IPv6 support, add IPv6 address structure in
1831
 * the union u. */
1832
union usa {
1833
  struct sockaddr sa;
1834
  struct sockaddr_in sin;
1835
#if defined(USE_IPV6)
1836
  struct sockaddr_in6 sin6;
1837
#endif
1838
#if defined(USE_X_DOM_SOCKET)
1839
  struct sockaddr_un sun;
1840
#endif
1841
};
1842
1843
#if defined(USE_X_DOM_SOCKET)
1844
static unsigned short
1845
USA_IN_PORT_UNSAFE(union usa *s)
1846
{
1847
  if (s->sa.sa_family == AF_INET)
1848
    return s->sin.sin_port;
1849
#if defined(USE_IPV6)
1850
  if (s->sa.sa_family == AF_INET6)
1851
    return s->sin6.sin6_port;
1852
#endif
1853
  return 0;
1854
}
1855
#endif
1856
#if defined(USE_IPV6)
1857
#define USA_IN_PORT_UNSAFE(s)                                                  \
1858
  (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
1859
#else
1860
#define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
1861
#endif
1862
1863
/* Describes a string (chunk of memory). */
1864
struct vec {
1865
  const char *ptr;
1866
  size_t len;
1867
};
1868
1869
struct mg_file_stat {
1870
  /* File properties filled by mg_stat: */
1871
  uint64_t size;
1872
  time_t last_modified;
1873
  int is_directory; /* Set to 1 if mg_stat is called for a directory */
1874
  int is_gzipped;   /* Set to 1 if the content is gzipped, in which
1875
                     * case we need a "Content-Eencoding: gzip" header */
1876
  int location;     /* 0 = nowhere, 1 = on disk, 2 = in memory */
1877
};
1878
1879
1880
struct mg_file_access {
1881
  /* File properties filled by mg_fopen: */
1882
  FILE *fp;
1883
};
1884
1885
struct mg_file {
1886
  struct mg_file_stat stat;
1887
  struct mg_file_access access;
1888
};
1889
1890
1891
#define STRUCT_FILE_INITIALIZER                                                \
1892
2
  {                                                                          \
1893
2
    {(uint64_t)0, (time_t)0, 0, 0, 0},                                     \
1894
2
    {                                                                      \
1895
2
      (FILE *)NULL                                                       \
1896
2
    }                                                                      \
1897
2
  }
1898
1899
1900
/* Describes listening socket, or socket which was accept()-ed by the master
1901
 * thread and queued for future handling by the worker thread. */
1902
struct socket {
1903
  SOCKET sock;             /* Listening socket */
1904
  union usa lsa;           /* Local socket address */
1905
  union usa rsa;           /* Remote socket address */
1906
  unsigned char is_ssl;    /* Is port SSL-ed */
1907
  unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
1908
                            * port */
1909
  unsigned char in_use;    /* 0: invalid, 1: valid, 2: free */
1910
};
1911
1912
1913
/* Enum const for all options must be in sync with
1914
 * static struct mg_option config_options[]
1915
 * This is tested in the unit test (test/private.c)
1916
 * "Private Config Options"
1917
 */
1918
enum {
1919
  /* Once for each server */
1920
  LISTENING_PORTS,
1921
  NUM_THREADS,
1922
  RUN_AS_USER,
1923
  CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
1924
                       * socket option typedef TCP_NODELAY. */
1925
  MAX_REQUEST_SIZE,
1926
  LINGER_TIMEOUT,
1927
  CONNECTION_QUEUE_SIZE,
1928
  LISTEN_BACKLOG_SIZE,
1929
#if defined(__linux__)
1930
  ALLOW_SENDFILE_CALL,
1931
#endif
1932
#if defined(_WIN32)
1933
  CASE_SENSITIVE_FILES,
1934
#endif
1935
  THROTTLE,
1936
  ENABLE_KEEP_ALIVE,
1937
  REQUEST_TIMEOUT,
1938
  KEEP_ALIVE_TIMEOUT,
1939
#if defined(USE_WEBSOCKET)
1940
  WEBSOCKET_TIMEOUT,
1941
  ENABLE_WEBSOCKET_PING_PONG,
1942
#endif
1943
  DECODE_URL,
1944
  DECODE_QUERY_STRING,
1945
#if defined(USE_LUA)
1946
  LUA_BACKGROUND_SCRIPT,
1947
  LUA_BACKGROUND_SCRIPT_PARAMS,
1948
#endif
1949
#if defined(USE_HTTP2)
1950
  ENABLE_HTTP2,
1951
#endif
1952
1953
  /* Once for each domain */
1954
  DOCUMENT_ROOT,
1955
1956
  ACCESS_LOG_FILE,
1957
  ERROR_LOG_FILE,
1958
1959
  CGI_EXTENSIONS,
1960
  CGI_ENVIRONMENT,
1961
  CGI_INTERPRETER,
1962
  CGI_INTERPRETER_ARGS,
1963
#if defined(USE_TIMERS)
1964
  CGI_TIMEOUT,
1965
#endif
1966
  CGI_BUFFERING,
1967
1968
  CGI2_EXTENSIONS,
1969
  CGI2_ENVIRONMENT,
1970
  CGI2_INTERPRETER,
1971
  CGI2_INTERPRETER_ARGS,
1972
#if defined(USE_TIMERS)
1973
  CGI2_TIMEOUT,
1974
#endif
1975
  CGI2_BUFFERING,
1976
1977
#if defined(USE_4_CGI)
1978
  CGI3_EXTENSIONS,
1979
  CGI3_ENVIRONMENT,
1980
  CGI3_INTERPRETER,
1981
  CGI3_INTERPRETER_ARGS,
1982
#if defined(USE_TIMERS)
1983
  CGI3_TIMEOUT,
1984
#endif
1985
  CGI3_BUFFERING,
1986
1987
  CGI4_EXTENSIONS,
1988
  CGI4_ENVIRONMENT,
1989
  CGI4_INTERPRETER,
1990
  CGI4_INTERPRETER_ARGS,
1991
#if defined(USE_TIMERS)
1992
  CGI4_TIMEOUT,
1993
#endif
1994
  CGI4_BUFFERING,
1995
#endif
1996
1997
  PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
1998
  PROTECT_URI,
1999
  AUTHENTICATION_DOMAIN,
2000
  ENABLE_AUTH_DOMAIN_CHECK,
2001
  SSI_EXTENSIONS,
2002
  ENABLE_DIRECTORY_LISTING,
2003
  ENABLE_WEBDAV,
2004
  GLOBAL_PASSWORDS_FILE,
2005
  INDEX_FILES,
2006
  ACCESS_CONTROL_LIST,
2007
  EXTRA_MIME_TYPES,
2008
  SSL_CERTIFICATE,
2009
  SSL_CERTIFICATE_CHAIN,
2010
  URL_REWRITE_PATTERN,
2011
  HIDE_FILES,
2012
  SSL_DO_VERIFY_PEER,
2013
  SSL_CACHE_TIMEOUT,
2014
  SSL_CA_PATH,
2015
  SSL_CA_FILE,
2016
  SSL_VERIFY_DEPTH,
2017
  SSL_DEFAULT_VERIFY_PATHS,
2018
  SSL_CIPHER_LIST,
2019
  SSL_PROTOCOL_VERSION,
2020
  SSL_SHORT_TRUST,
2021
2022
#if defined(USE_LUA)
2023
  LUA_PRELOAD_FILE,
2024
  LUA_SCRIPT_EXTENSIONS,
2025
  LUA_SERVER_PAGE_EXTENSIONS,
2026
#if defined(MG_EXPERIMENTAL_INTERFACES)
2027
  LUA_DEBUG_PARAMS,
2028
#endif
2029
#endif
2030
#if defined(USE_DUKTAPE)
2031
  DUKTAPE_SCRIPT_EXTENSIONS,
2032
#endif
2033
2034
#if defined(USE_WEBSOCKET)
2035
  WEBSOCKET_ROOT,
2036
#endif
2037
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2038
  LUA_WEBSOCKET_EXTENSIONS,
2039
#endif
2040
2041
  ACCESS_CONTROL_ALLOW_ORIGIN,
2042
  ACCESS_CONTROL_ALLOW_METHODS,
2043
  ACCESS_CONTROL_ALLOW_HEADERS,
2044
  ERROR_PAGES,
2045
#if !defined(NO_CACHING)
2046
  STATIC_FILE_MAX_AGE,
2047
  STATIC_FILE_CACHE_CONTROL,
2048
#endif
2049
#if !defined(NO_SSL)
2050
  STRICT_HTTPS_MAX_AGE,
2051
#endif
2052
  ADDITIONAL_HEADER,
2053
  ALLOW_INDEX_SCRIPT_SUB_RES,
2054
2055
  NUM_OPTIONS
2056
};
2057
2058
2059
/* Config option name, config types, default value.
2060
 * Must be in the same order as the enum const above.
2061
 */
2062
static const struct mg_option config_options[] = {
2063
2064
    /* Once for each server */
2065
    {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
2066
    {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
2067
    {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
2068
    {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
2069
    {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
2070
    {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2071
    {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
2072
    {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
2073
#if defined(__linux__)
2074
    {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2075
#endif
2076
#if defined(_WIN32)
2077
    {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2078
#endif
2079
    {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
2080
    {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2081
    {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
2082
    {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
2083
#if defined(USE_WEBSOCKET)
2084
    {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2085
    {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
2086
#endif
2087
    {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2088
    {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
2089
#if defined(USE_LUA)
2090
    {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
2091
    {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
2092
#endif
2093
#if defined(USE_HTTP2)
2094
    {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
2095
#endif
2096
2097
    /* Once for each domain */
2098
    {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2099
2100
    {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
2101
    {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
2102
2103
    {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
2104
    {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2105
    {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2106
    {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2107
#if defined(USE_TIMERS)
2108
    {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2109
#endif
2110
    {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2111
2112
    {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2113
    {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2114
    {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2115
    {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2116
#if defined(USE_TIMERS)
2117
    {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2118
#endif
2119
    {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2120
2121
#if defined(USE_4_CGI)
2122
    {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2123
    {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2124
    {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2125
    {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2126
#if defined(USE_TIMERS)
2127
    {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2128
#endif
2129
    {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2130
2131
    {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2132
    {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2133
    {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2134
    {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
2135
#if defined(USE_TIMERS)
2136
    {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2137
#endif
2138
    {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2139
2140
#endif
2141
2142
    {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2143
    {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
2144
    {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
2145
    {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2146
    {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
2147
    {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2148
    {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
2149
    {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2150
    {"index_files",
2151
     MG_CONFIG_TYPE_STRING_LIST,
2152
#if defined(USE_LUA)
2153
     "index.xhtml,index.html,index.htm,"
2154
     "index.lp,index.lsp,index.lua,index.cgi,"
2155
     "index.shtml,index.php"},
2156
#else
2157
     "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
2158
#endif
2159
    {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
2160
    {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
2161
    {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
2162
    {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
2163
    {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
2164
    {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2165
2166
    {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
2167
    {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
2168
2169
    {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
2170
    {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
2171
    {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
2172
    {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2173
    {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
2174
2175
    /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
2176
     * as a minimum in 2020 */
2177
    {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
2178
2179
    {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
2180
2181
#if defined(USE_LUA)
2182
    {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
2183
    {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2184
    {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
2185
#if defined(MG_EXPERIMENTAL_INTERFACES)
2186
    {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
2187
#endif
2188
#endif
2189
#if defined(USE_DUKTAPE)
2190
    /* The support for duktape is still in alpha version state.
2191
     * The name of this config option might change. */
2192
    {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
2193
#endif
2194
2195
#if defined(USE_WEBSOCKET)
2196
    {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2197
#endif
2198
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2199
    {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2200
#endif
2201
    {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
2202
    {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
2203
    {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
2204
    {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
2205
#if !defined(NO_CACHING)
2206
    {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
2207
    {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
2208
#endif
2209
#if !defined(NO_SSL)
2210
    {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
2211
#endif
2212
    {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
2213
    {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
2214
2215
    {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
2216
2217
2218
/* Check if the config_options and the corresponding enum have compatible
2219
 * sizes. */
2220
mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
2221
                     == (NUM_OPTIONS + 1),
2222
                 "config_options and enum not sync");
2223
2224
2225
enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
2226
2227
2228
struct mg_handler_info {
2229
  /* Name/Pattern of the URI. */
2230
  char *uri;
2231
  size_t uri_len;
2232
2233
  /* handler type */
2234
  int handler_type;
2235
2236
  /* Handler for http/https or requests. */
2237
  mg_request_handler handler;
2238
  unsigned int refcount;
2239
  int removing;
2240
2241
  /* Handler for ws/wss (websocket) requests. */
2242
  mg_websocket_connect_handler connect_handler;
2243
  mg_websocket_ready_handler ready_handler;
2244
  mg_websocket_data_handler data_handler;
2245
  mg_websocket_close_handler close_handler;
2246
2247
  /* accepted subprotocols for ws/wss requests. */
2248
  struct mg_websocket_subprotocols *subprotocols;
2249
2250
  /* Handler for authorization requests */
2251
  mg_authorization_handler auth_handler;
2252
2253
  /* User supplied argument for the handler function. */
2254
  void *cbdata;
2255
2256
  /* next handler in a linked list */
2257
  struct mg_handler_info *next;
2258
};
2259
2260
2261
enum {
2262
  CONTEXT_INVALID,
2263
  CONTEXT_SERVER,
2264
  CONTEXT_HTTP_CLIENT,
2265
  CONTEXT_WS_CLIENT
2266
};
2267
2268
2269
struct mg_domain_context {
2270
  SSL_CTX *ssl_ctx;                 /* SSL context */
2271
  char *config[NUM_OPTIONS];        /* Civetweb configuration parameters */
2272
  struct mg_handler_info *handlers; /* linked list of uri handlers */
2273
  int64_t ssl_cert_last_mtime;
2274
2275
  /* Server nonce */
2276
  uint64_t auth_nonce_mask;  /* Mask for all nonce values */
2277
  unsigned long nonce_count; /* Used nonces, used for authentication */
2278
2279
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2280
  /* linked list of shared lua websockets */
2281
  struct mg_shared_lua_websocket_list *shared_lua_websockets;
2282
#endif
2283
2284
  /* Linked list of domains */
2285
  struct mg_domain_context *next;
2286
};
2287
2288
2289
/* Stop flag can be "volatile" or require a lock.
2290
 * MSDN uses volatile for "Interlocked" operations, but also explicitly
2291
 * states a read operation for int is always atomic. */
2292
#if defined(STOP_FLAG_NEEDS_LOCK)
2293
2294
typedef ptrdiff_t volatile stop_flag_t;
2295
2296
static int
2297
STOP_FLAG_IS_ZERO(const stop_flag_t *f)
2298
{
2299
  stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
2300
  return (sf == 0);
2301
}
2302
2303
static int
2304
STOP_FLAG_IS_TWO(stop_flag_t *f)
2305
{
2306
  stop_flag_t sf = mg_atomic_add(f, 0);
2307
  return (sf == 2);
2308
}
2309
2310
static void
2311
STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
2312
{
2313
  stop_flag_t sf;
2314
  do {
2315
    sf = mg_atomic_compare_and_swap(f, *f, v);
2316
  } while (sf != v);
2317
}
2318
2319
#else /* STOP_FLAG_NEEDS_LOCK */
2320
2321
typedef int volatile stop_flag_t;
2322
582
#define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
2323
200
#define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
2324
38
#define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
2325
2326
#endif /* STOP_FLAG_NEEDS_LOCK */
2327
2328
2329
#if !defined(NUM_WEBDAV_LOCKS)
2330
0
#define NUM_WEBDAV_LOCKS 10
2331
#endif
2332
#if !defined(LOCK_DURATION_S)
2333
0
#define LOCK_DURATION_S 60
2334
#endif
2335
2336
2337
struct twebdav_lock {
2338
  uint64_t locktime;
2339
  char token[33];
2340
  char path[UTF8_PATH_MAX * 2];
2341
  char user[UTF8_PATH_MAX * 2];
2342
};
2343
2344
2345
struct mg_context {
2346
2347
  /* Part 1 - Physical context:
2348
   * This holds threads, ports, timeouts, ...
2349
   * set for the entire server, independent from the
2350
   * addressed hostname.
2351
   */
2352
2353
  /* Connection related */
2354
  int context_type; /* See CONTEXT_* above */
2355
2356
  struct socket *listening_sockets;
2357
  struct mg_pollfd *listening_socket_fds;
2358
  unsigned int num_listening_sockets;
2359
2360
  struct mg_connection *worker_connections; /* The connection struct, pre-
2361
                                             * allocated for each worker */
2362
2363
#if defined(USE_SERVER_STATS)
2364
  volatile ptrdiff_t active_connections;
2365
  volatile ptrdiff_t max_active_connections;
2366
  volatile ptrdiff_t total_connections;
2367
  volatile ptrdiff_t total_requests;
2368
  volatile int64_t total_data_read;
2369
  volatile int64_t total_data_written;
2370
#endif
2371
2372
  /* Thread related */
2373
  stop_flag_t stop_flag;        /* Should we stop event loop */
2374
  pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
2375
2376
  pthread_t masterthreadid; /* The master thread ID */
2377
  unsigned int
2378
      cfg_worker_threads;      /* The number of configured worker threads. */
2379
  pthread_t *worker_threadids; /* The worker thread IDs */
2380
  unsigned long starter_thread_idx; /* thread index which called mg_start */
2381
2382
  /* Connection to thread dispatching */
2383
#if defined(ALTERNATIVE_QUEUE)
2384
  struct socket *client_socks;
2385
  void **client_wait_events;
2386
#else
2387
  struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
2388
                         worker thread */
2389
  volatile int sq_head;  /* Head of the socket queue */
2390
  volatile int sq_tail;  /* Tail of the socket queue */
2391
  pthread_cond_t sq_full;  /* Signaled when socket is produced */
2392
  pthread_cond_t sq_empty; /* Signaled when socket is consumed */
2393
  volatile int sq_blocked; /* Status information: sq is full */
2394
  int sq_size;             /* No of elements in socket queue */
2395
#if defined(USE_SERVER_STATS)
2396
  int sq_max_fill;
2397
#endif /* USE_SERVER_STATS */
2398
#endif /* ALTERNATIVE_QUEUE */
2399
2400
  /* Memory related */
2401
  unsigned int max_request_size; /* The max request size */
2402
2403
#if defined(USE_SERVER_STATS)
2404
  struct mg_memory_stat ctx_memory;
2405
#endif
2406
2407
  /* WebDAV lock structures */
2408
  struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
2409
2410
  /* Operating system related */
2411
  char *systemName;  /* What operating system is running */
2412
  time_t start_time; /* Server start time, used for authentication
2413
                      * and for diagnstics. */
2414
2415
#if defined(USE_TIMERS)
2416
  struct ttimers *timers;
2417
#endif
2418
2419
  /* Lua specific: Background operations and shared websockets */
2420
#if defined(USE_LUA)
2421
  void *lua_background_state;   /* lua_State (here as void *) */
2422
  pthread_mutex_t lua_bg_mutex; /* Protect background state */
2423
  int lua_bg_log_available;     /* Use Lua background state for access log */
2424
#endif
2425
2426
  /* Server nonce */
2427
  pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
2428
                                * ssl_cert_last_mtime, nonce_count, and
2429
                                * next (linked list) */
2430
2431
  /* Server callbacks */
2432
  struct mg_callbacks callbacks; /* User-defined callback function */
2433
  void *user_data;               /* User-defined data */
2434
2435
  /* Part 2 - Logical domain:
2436
   * This holds hostname, TLS certificate, document root, ...
2437
   * set for a domain hosted at the server.
2438
   * There may be multiple domains hosted at one physical server.
2439
   * The default domain "dd" is the first element of a list of
2440
   * domains.
2441
   */
2442
  struct mg_domain_context dd; /* default domain */
2443
};
2444
2445
2446
#if defined(USE_SERVER_STATS)
2447
static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2448
2449
static struct mg_memory_stat *
2450
get_memory_stat(struct mg_context *ctx)
2451
{
2452
  if (ctx) {
2453
    return &(ctx->ctx_memory);
2454
  }
2455
  return &mg_common_memory;
2456
}
2457
#endif
2458
2459
enum {
2460
  CONNECTION_TYPE_INVALID = 0,
2461
  CONNECTION_TYPE_REQUEST = 1,
2462
  CONNECTION_TYPE_RESPONSE = 2
2463
};
2464
2465
enum {
2466
  PROTOCOL_TYPE_HTTP1 = 0,
2467
  PROTOCOL_TYPE_WEBSOCKET = 1,
2468
  PROTOCOL_TYPE_HTTP2 = 2
2469
};
2470
2471
2472
#if defined(USE_HTTP2)
2473
#if !defined(HTTP2_DYN_TABLE_SIZE)
2474
#define HTTP2_DYN_TABLE_SIZE (256)
2475
#endif
2476
2477
struct mg_http2_connection {
2478
  uint32_t stream_id;
2479
  uint32_t dyn_table_size;
2480
  struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
2481
};
2482
#endif
2483
2484
2485
struct mg_connection {
2486
  int connection_type; /* see CONNECTION_TYPE_* above */
2487
  int protocol_type;   /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
2488
  int request_state;   /* 0: nothing sent, 1: header partially sent, 2: header
2489
                       fully sent */
2490
#if defined(USE_HTTP2)
2491
  struct mg_http2_connection http2;
2492
#endif
2493
2494
  struct mg_request_info request_info;
2495
  struct mg_response_info response_info;
2496
2497
  struct mg_context *phys_ctx;
2498
  struct mg_domain_context *dom_ctx;
2499
2500
#if defined(USE_SERVER_STATS)
2501
  int conn_state; /* 0 = undef, numerical value may change in different
2502
                   * versions. For the current definition, see
2503
                   * mg_get_connection_info_impl */
2504
#endif
2505
2506
  SSL *ssl;               /* SSL descriptor */
2507
  struct socket client;   /* Connected client */
2508
  time_t conn_birth_time; /* Time (wall clock) when connection was
2509
                           * established */
2510
#if defined(USE_SERVER_STATS)
2511
  time_t conn_close_time; /* Time (wall clock) when connection was
2512
                           * closed (or 0 if still open) */
2513
  double processing_time; /* Processing time for one request. */
2514
#endif
2515
  struct timespec req_time; /* Time (since system start) when the request
2516
                             * was received */
2517
  int64_t num_bytes_sent;   /* Total bytes sent to client */
2518
  int64_t content_len;      /* How many bytes of content can be read
2519
                             * !is_chunked: Content-Length header value
2520
                             *              or -1 (until connection closed,
2521
                             *                     not allowed for a request)
2522
                             * is_chunked: >= 0, appended gradually
2523
                             */
2524
  int64_t consumed_content; /* How many bytes of content have been read */
2525
  int is_chunked;           /* Transfer-Encoding is chunked:
2526
                             * 0 = not chunked,
2527
                             * 1 = chunked, not yet, or some data read,
2528
                             * 2 = chunked, has error,
2529
                             * 3 = chunked, all data read except trailer,
2530
                             * 4 = chunked, all data read
2531
                             */
2532
  char *buf;                /* Buffer for received data */
2533
  char *path_info;          /* PATH_INFO part of the URL */
2534
2535
  int must_close;       /* 1 if connection must be closed */
2536
  int accept_gzip;      /* 1 if gzip encoding is accepted */
2537
  int in_error_handler; /* 1 if in handler for user defined error
2538
                         * pages */
2539
#if defined(USE_WEBSOCKET)
2540
  int in_websocket_handling; /* 1 if in read_websocket */
2541
#endif
2542
#if defined(USE_ZLIB) && defined(USE_WEBSOCKET)                                \
2543
    && defined(MG_EXPERIMENTAL_INTERFACES)
2544
  /* Parameters for websocket data compression according to rfc7692 */
2545
  int websocket_deflate_server_max_windows_bits;
2546
  int websocket_deflate_client_max_windows_bits;
2547
  int websocket_deflate_server_no_context_takeover;
2548
  int websocket_deflate_client_no_context_takeover;
2549
  int websocket_deflate_initialized;
2550
  int websocket_deflate_flush;
2551
  z_stream websocket_deflate_state;
2552
  z_stream websocket_inflate_state;
2553
#endif
2554
  int handled_requests; /* Number of requests handled by this connection
2555
                         */
2556
  int buf_size;         /* Buffer size */
2557
  int request_len;      /* Size of the request + headers in a buffer */
2558
  int data_len;         /* Total size of data in a buffer */
2559
  int status_code;      /* HTTP reply status code, e.g. 200 */
2560
  int throttle;         /* Throttling, bytes/sec. <= 0 means no
2561
                         * throttle */
2562
2563
  time_t last_throttle_time; /* Last time throttled data was sent */
2564
  int last_throttle_bytes;   /* Bytes sent this second */
2565
  pthread_mutex_t mutex;     /* Used by mg_(un)lock_connection to ensure
2566
                              * atomic transmissions for websockets */
2567
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2568
  void *lua_websocket_state; /* Lua_State for a websocket connection */
2569
#endif
2570
2571
  void *tls_user_ptr; /* User defined pointer in thread local storage,
2572
                       * for quick access */
2573
};
2574
2575
2576
/* Directory entry */
2577
struct de {
2578
  char *file_name;
2579
  struct mg_file_stat file;
2580
};
2581
2582
2583
#define mg_cry_internal(conn, fmt, ...)                                        \
2584
0
  mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
2585
2586
#define mg_cry_ctx_internal(ctx, fmt, ...)                                     \
2587
0
  mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
2588
2589
static void mg_cry_internal_wrap(const struct mg_connection *conn,
2590
                                 struct mg_context *ctx,
2591
                                 const char *func,
2592
                                 unsigned line,
2593
                                 const char *fmt,
2594
                                 ...) PRINTF_ARGS(5, 6);
2595
2596
2597
#if !defined(NO_THREAD_NAME)
2598
#if defined(_WIN32) && defined(_MSC_VER)
2599
/* Set the thread name for debugging purposes in Visual Studio
2600
 * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
2601
 */
2602
#pragma pack(push, 8)
2603
typedef struct tagTHREADNAME_INFO {
2604
  DWORD dwType;     /* Must be 0x1000. */
2605
  LPCSTR szName;    /* Pointer to name (in user addr space). */
2606
  DWORD dwThreadID; /* Thread ID (-1=caller thread). */
2607
  DWORD dwFlags;    /* Reserved for future use, must be zero. */
2608
} THREADNAME_INFO;
2609
#pragma pack(pop)
2610
2611
#elif defined(__linux__)
2612
2613
#include <sys/prctl.h>
2614
#include <sys/sendfile.h>
2615
#if defined(ALTERNATIVE_QUEUE)
2616
#include <sys/eventfd.h>
2617
#endif /* ALTERNATIVE_QUEUE */
2618
2619
2620
#if defined(ALTERNATIVE_QUEUE)
2621
2622
static void *
2623
event_create(void)
2624
{
2625
  int evhdl = eventfd(0, EFD_CLOEXEC);
2626
  int *ret;
2627
2628
  if (evhdl == -1) {
2629
    /* Linux uses -1 on error, Windows NULL. */
2630
    /* However, Linux does not return 0 on success either. */
2631
    return 0;
2632
  }
2633
2634
  ret = (int *)mg_malloc(sizeof(int));
2635
  if (ret) {
2636
    *ret = evhdl;
2637
  } else {
2638
    (void)close(evhdl);
2639
  }
2640
2641
  return (void *)ret;
2642
}
2643
2644
2645
static int
2646
event_wait(void *eventhdl)
2647
{
2648
  uint64_t u;
2649
  int evhdl, s;
2650
2651
  if (!eventhdl) {
2652
    /* error */
2653
    return 0;
2654
  }
2655
  evhdl = *(int *)eventhdl;
2656
2657
  s = (int)read(evhdl, &u, sizeof(u));
2658
  if (s != sizeof(u)) {
2659
    /* error */
2660
    return 0;
2661
  }
2662
  (void)u; /* the value is not required */
2663
  return 1;
2664
}
2665
2666
2667
static int
2668
event_signal(void *eventhdl)
2669
{
2670
  uint64_t u = 1;
2671
  int evhdl, s;
2672
2673
  if (!eventhdl) {
2674
    /* error */
2675
    return 0;
2676
  }
2677
  evhdl = *(int *)eventhdl;
2678
2679
  s = (int)write(evhdl, &u, sizeof(u));
2680
  if (s != sizeof(u)) {
2681
    /* error */
2682
    return 0;
2683
  }
2684
  return 1;
2685
}
2686
2687
2688
static void
2689
event_destroy(void *eventhdl)
2690
{
2691
  int evhdl;
2692
2693
  if (!eventhdl) {
2694
    /* error */
2695
    return;
2696
  }
2697
  evhdl = *(int *)eventhdl;
2698
2699
  close(evhdl);
2700
  mg_free(eventhdl);
2701
}
2702
2703
2704
#endif
2705
2706
#endif
2707
2708
2709
#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2710
2711
struct posix_event {
2712
  pthread_mutex_t mutex;
2713
  pthread_cond_t cond;
2714
  int signaled;
2715
};
2716
2717
2718
static void *
2719
event_create(void)
2720
{
2721
  struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
2722
  if (ret == 0) {
2723
    /* out of memory */
2724
    return 0;
2725
  }
2726
  if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2727
    /* pthread mutex not available */
2728
    mg_free(ret);
2729
    return 0;
2730
  }
2731
  if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2732
    /* pthread cond not available */
2733
    pthread_mutex_destroy(&(ret->mutex));
2734
    mg_free(ret);
2735
    return 0;
2736
  }
2737
  ret->signaled = 0;
2738
  return (void *)ret;
2739
}
2740
2741
2742
static int
2743
event_wait(void *eventhdl)
2744
{
2745
  struct posix_event *ev = (struct posix_event *)eventhdl;
2746
  pthread_mutex_lock(&(ev->mutex));
2747
  while (!ev->signaled) {
2748
    pthread_cond_wait(&(ev->cond), &(ev->mutex));
2749
  }
2750
  ev->signaled = 0;
2751
  pthread_mutex_unlock(&(ev->mutex));
2752
  return 1;
2753
}
2754
2755
2756
static int
2757
event_signal(void *eventhdl)
2758
{
2759
  struct posix_event *ev = (struct posix_event *)eventhdl;
2760
  pthread_mutex_lock(&(ev->mutex));
2761
  pthread_cond_signal(&(ev->cond));
2762
  ev->signaled = 1;
2763
  pthread_mutex_unlock(&(ev->mutex));
2764
  return 1;
2765
}
2766
2767
2768
static void
2769
event_destroy(void *eventhdl)
2770
{
2771
  struct posix_event *ev = (struct posix_event *)eventhdl;
2772
  pthread_cond_destroy(&(ev->cond));
2773
  pthread_mutex_destroy(&(ev->mutex));
2774
  mg_free(ev);
2775
}
2776
#endif
2777
2778
2779
static void
2780
mg_set_thread_name(const char *name)
2781
102
{
2782
102
  char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
2783
2784
102
  mg_snprintf(
2785
102
      NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
2786
2787
#if defined(_WIN32)
2788
#if defined(_MSC_VER)
2789
  /* Windows and Visual Studio Compiler */
2790
  __try {
2791
    THREADNAME_INFO info;
2792
    info.dwType = 0x1000;
2793
    info.szName = threadName;
2794
    info.dwThreadID = ~0U;
2795
    info.dwFlags = 0;
2796
2797
    RaiseException(0x406D1388,
2798
                   0,
2799
                   sizeof(info) / sizeof(ULONG_PTR),
2800
                   (ULONG_PTR *)&info);
2801
  } __except (EXCEPTION_EXECUTE_HANDLER) {
2802
  }
2803
#elif defined(__MINGW32__)
2804
  /* No option known to set thread name for MinGW known */
2805
#endif
2806
#elif defined(_GNU_SOURCE) && defined(__GLIBC__)                               \
2807
    && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
2808
  /* pthread_setname_np first appeared in glibc in version 2.12 */
2809
#if defined(__MACH__) && defined(__APPLE__)
2810
  /* OS X only current thread name can be changed */
2811
  (void)pthread_setname_np(threadName);
2812
#else
2813
102
  (void)pthread_setname_np(pthread_self(), threadName);
2814
102
#endif
2815
#elif defined(__linux__)
2816
  /* On Linux we can use the prctl function.
2817
   * When building for Linux Standard Base (LSB) use
2818
   * NO_THREAD_NAME. However, thread names are a big
2819
   * help for debugging, so the stadard is to set them.
2820
   */
2821
  (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
2822
#endif
2823
102
}
2824
#else /* !defined(NO_THREAD_NAME) */
2825
static void
2826
mg_set_thread_name(const char *threadName)
2827
{
2828
}
2829
#endif
2830
2831
2832
CIVETWEB_API const struct mg_option *
2833
mg_get_valid_options(void)
2834
0
{
2835
0
  return config_options;
2836
0
}
2837
2838
2839
/* Do not open file (unused) */
2840
#define MG_FOPEN_MODE_NONE (0)
2841
2842
/* Open file for read only access */
2843
0
#define MG_FOPEN_MODE_READ (1)
2844
2845
/* Open file for writing, create and overwrite */
2846
0
#define MG_FOPEN_MODE_WRITE (2)
2847
2848
/* Open file for writing, create and append */
2849
0
#define MG_FOPEN_MODE_APPEND (4)
2850
2851
2852
static int
2853
is_file_opened(const struct mg_file_access *fileacc)
2854
0
{
2855
0
  if (!fileacc) {
2856
0
    return 0;
2857
0
  }
2858
2859
0
  return (fileacc->fp != NULL);
2860
0
}
2861
2862
2863
#if !defined(NO_FILESYSTEMS)
2864
static int mg_stat(const struct mg_connection *conn,
2865
                   const char *path,
2866
                   struct mg_file_stat *filep);
2867
2868
2869
/* Reject files with special characters (for Windows) */
2870
static int
2871
mg_path_suspicious(const struct mg_connection *conn, const char *path)
2872
0
{
2873
0
  const uint8_t *c = (const uint8_t *)path;
2874
0
  (void)conn; /* not used */
2875
2876
0
  if ((c == NULL) || (c[0] == 0)) {
2877
    /* Null pointer or empty path --> suspicious */
2878
0
    return 1;
2879
0
  }
2880
2881
#if defined(_WIN32)
2882
  while (*c) {
2883
    if (*c < 32) {
2884
      /* Control character */
2885
      return 1;
2886
    }
2887
    if ((*c == '>') || (*c == '<') || (*c == '|')) {
2888
      /* stdin/stdout redirection character */
2889
      return 1;
2890
    }
2891
    if ((*c == '*') || (*c == '?')) {
2892
      /* Wildcard character */
2893
      return 1;
2894
    }
2895
    if (*c == '"') {
2896
      /* Windows quotation */
2897
      return 1;
2898
    }
2899
    c++;
2900
  }
2901
#endif
2902
2903
  /* Nothing suspicious found */
2904
0
  return 0;
2905
0
}
2906
2907
2908
/* mg_fopen will open a file either in memory or on the disk.
2909
 * The input parameter path is a string in UTF-8 encoding.
2910
 * The input parameter mode is MG_FOPEN_MODE_*
2911
 * On success, fp will be set in the output struct mg_file.
2912
 * All status members will also be set.
2913
 * The function returns 1 on success, 0 on error. */
2914
static int
2915
mg_fopen(const struct mg_connection *conn,
2916
         const char *path,
2917
         int mode,
2918
         struct mg_file *filep)
2919
0
{
2920
0
  int found;
2921
2922
0
  if (!filep) {
2923
0
    return 0;
2924
0
  }
2925
0
  filep->access.fp = NULL;
2926
2927
0
  if (mg_path_suspicious(conn, path)) {
2928
0
    return 0;
2929
0
  }
2930
2931
  /* filep is initialized in mg_stat: all fields with memset to,
2932
   * some fields like size and modification date with values */
2933
0
  found = mg_stat(conn, path, &(filep->stat));
2934
2935
0
  if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
2936
    /* file does not exist and will not be created */
2937
0
    return 0;
2938
0
  }
2939
2940
#if defined(_WIN32)
2941
  {
2942
    wchar_t wbuf[UTF16_PATH_MAX];
2943
    path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
2944
    switch (mode) {
2945
    case MG_FOPEN_MODE_READ:
2946
      filep->access.fp = _wfopen(wbuf, L"rb");
2947
      break;
2948
    case MG_FOPEN_MODE_WRITE:
2949
      filep->access.fp = _wfopen(wbuf, L"wb");
2950
      break;
2951
    case MG_FOPEN_MODE_APPEND:
2952
      filep->access.fp = _wfopen(wbuf, L"ab");
2953
      break;
2954
    }
2955
  }
2956
#else
2957
  /* Linux et al already use unicode. No need to convert. */
2958
0
  switch (mode) {
2959
0
  case MG_FOPEN_MODE_READ:
2960
0
    filep->access.fp = fopen(path, "r");
2961
0
    break;
2962
0
  case MG_FOPEN_MODE_WRITE:
2963
0
    filep->access.fp = fopen(path, "w");
2964
0
    break;
2965
0
  case MG_FOPEN_MODE_APPEND:
2966
0
    filep->access.fp = fopen(path, "a");
2967
0
    break;
2968
0
  }
2969
2970
0
#endif
2971
0
  if (!found) {
2972
    /* File did not exist before fopen was called.
2973
     * Maybe it has been created now. Get stat info
2974
     * like creation time now. */
2975
0
    found = mg_stat(conn, path, &(filep->stat));
2976
0
    (void)found;
2977
0
  }
2978
2979
  /* return OK if file is opened */
2980
0
  return (filep->access.fp != NULL);
2981
0
}
2982
2983
2984
/* return 0 on success, just like fclose */
2985
static int
2986
mg_fclose(struct mg_file_access *fileacc)
2987
0
{
2988
0
  int ret = -1;
2989
0
  if (fileacc != NULL) {
2990
0
    if (fileacc->fp != NULL) {
2991
0
      ret = fclose(fileacc->fp);
2992
0
    }
2993
    /* reset all members of fileacc */
2994
0
    memset(fileacc, 0, sizeof(*fileacc));
2995
0
  }
2996
0
  return ret;
2997
0
}
2998
#endif /* NO_FILESYSTEMS */
2999
3000
3001
static void
3002
mg_strlcpy(char *dst, const char *src, size_t n)
3003
68
{
3004
474
  for (; *src != '\0' && n > 1; n--) {
3005
406
    *dst++ = *src++;
3006
406
  }
3007
68
  *dst = '\0';
3008
68
}
3009
3010
3011
static int
3012
lowercase(const char *s)
3013
0
{
3014
0
  return tolower((unsigned char)*s);
3015
0
}
3016
3017
3018
CIVETWEB_API int
3019
mg_strncasecmp(const char *s1, const char *s2, size_t len)
3020
0
{
3021
0
  int diff = 0;
3022
3023
0
  if (len > 0) {
3024
0
    do {
3025
0
      diff = lowercase(s1++) - lowercase(s2++);
3026
0
    } while (diff == 0 && s1[-1] != '\0' && --len > 0);
3027
0
  }
3028
3029
0
  return diff;
3030
0
}
3031
3032
3033
CIVETWEB_API int
3034
mg_strcasecmp(const char *s1, const char *s2)
3035
0
{
3036
0
  int diff;
3037
3038
0
  do {
3039
0
    diff = lowercase(s1++) - lowercase(s2++);
3040
0
  } while (diff == 0 && s1[-1] != '\0');
3041
3042
0
  return diff;
3043
0
}
3044
3045
3046
static char *
3047
mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
3048
68
{
3049
68
  char *p;
3050
68
  (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
3051
              * defined */
3052
3053
68
  if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
3054
68
    mg_strlcpy(p, ptr, len + 1);
3055
68
  }
3056
3057
68
  return p;
3058
68
}
3059
3060
3061
static char *
3062
mg_strdup_ctx(const char *str, struct mg_context *ctx)
3063
66
{
3064
66
  return mg_strndup_ctx(str, strlen(str), ctx);
3065
66
}
3066
3067
static char *
3068
mg_strdup(const char *str)
3069
2
{
3070
2
  return mg_strndup_ctx(str, strlen(str), NULL);
3071
2
}
3072
3073
3074
static const char *
3075
mg_strcasestr(const char *big_str, const char *small_str)
3076
0
{
3077
0
  size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3078
3079
0
  if (big_len >= small_len) {
3080
0
    for (i = 0; i <= (big_len - small_len); i++) {
3081
0
      if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
3082
0
        return big_str + i;
3083
0
      }
3084
0
    }
3085
0
  }
3086
3087
0
  return NULL;
3088
0
}
3089
3090
3091
/* Return null terminated string of given maximum length.
3092
 * Report errors if length is exceeded. */
3093
static void
3094
mg_vsnprintf(const struct mg_connection *conn,
3095
             int *truncated,
3096
             char *buf,
3097
             size_t buflen,
3098
             const char *fmt,
3099
             va_list ap)
3100
169
{
3101
169
  int n, ok;
3102
3103
169
  if (buflen == 0) {
3104
0
    if (truncated) {
3105
0
      *truncated = 1;
3106
0
    }
3107
0
    return;
3108
0
  }
3109
3110
169
#if defined(__clang__)
3111
169
#pragma clang diagnostic push
3112
169
#pragma clang diagnostic ignored "-Wformat-nonliteral"
3113
  /* Using fmt as a non-literal is intended here, since it is mostly called
3114
   * indirectly by mg_snprintf */
3115
169
#endif
3116
3117
169
  n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
3118
169
  ok = (n >= 0) && ((size_t)n < buflen);
3119
3120
169
#if defined(__clang__)
3121
169
#pragma clang diagnostic pop
3122
169
#endif
3123
3124
169
  if (ok) {
3125
169
    if (truncated) {
3126
0
      *truncated = 0;
3127
0
    }
3128
169
  } else {
3129
0
    if (truncated) {
3130
0
      *truncated = 1;
3131
0
    }
3132
0
    mg_cry_internal(conn,
3133
0
                    "truncating vsnprintf buffer: [%.*s]",
3134
0
                    (int)((buflen > 200) ? 200 : (buflen - 1)),
3135
0
                    buf);
3136
0
    n = (int)buflen - 1;
3137
0
  }
3138
169
  buf[n] = '\0';
3139
169
}
3140
3141
3142
static void
3143
mg_snprintf(const struct mg_connection *conn,
3144
            int *truncated,
3145
            char *buf,
3146
            size_t buflen,
3147
            const char *fmt,
3148
            ...)
3149
169
{
3150
169
  va_list ap;
3151
3152
169
  va_start(ap, fmt);
3153
169
  mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
3154
169
  va_end(ap);
3155
169
}
3156
3157
3158
static int
3159
get_option_index(const char *name)
3160
4
{
3161
4
  int i;
3162
3163
34
  for (i = 0; config_options[i].name != NULL; i++) {
3164
34
    if (strcmp(config_options[i].name, name) == 0) {
3165
4
      return i;
3166
4
    }
3167
34
  }
3168
0
  return -1;
3169
4
}
3170
3171
3172
CIVETWEB_API const char *
3173
mg_get_option(const struct mg_context *ctx, const char *name)
3174
0
{
3175
0
  int i;
3176
0
  if ((i = get_option_index(name)) == -1) {
3177
0
    return NULL;
3178
0
  } else if (!ctx || ctx->dd.config[i] == NULL) {
3179
0
    return "";
3180
0
  } else {
3181
0
    return ctx->dd.config[i];
3182
0
  }
3183
0
}
3184
3185
#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3186
3187
CIVETWEB_API struct mg_context *
3188
mg_get_context(const struct mg_connection *conn)
3189
0
{
3190
0
  return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
3191
0
}
3192
3193
3194
CIVETWEB_API void *
3195
mg_get_user_data(const struct mg_context *ctx)
3196
0
{
3197
0
  return (ctx == NULL) ? NULL : ctx->user_data;
3198
0
}
3199
3200
3201
CIVETWEB_API void *
3202
mg_get_user_context_data(const struct mg_connection *conn)
3203
0
{
3204
0
  return mg_get_user_data(mg_get_context(conn));
3205
0
}
3206
3207
3208
CIVETWEB_API void *
3209
mg_get_thread_pointer(const struct mg_connection *conn)
3210
0
{
3211
  /* both methods should return the same pointer */
3212
0
  if (conn) {
3213
    /* quick access, in case conn is known */
3214
0
    return conn->tls_user_ptr;
3215
0
  } else {
3216
    /* otherwise get pointer from thread local storage (TLS) */
3217
0
    struct mg_workerTLS *tls =
3218
0
        (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3219
0
    return tls->user_ptr;
3220
0
  }
3221
0
}
3222
3223
3224
CIVETWEB_API void
3225
mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
3226
34
{
3227
34
  if (const_conn != NULL) {
3228
    /* Const cast, since "const struct mg_connection *" does not mean
3229
     * the connection object is not modified. Here "const" is used,
3230
     * to indicate mg_read/mg_write/mg_send/.. must not be called. */
3231
34
    struct mg_connection *conn = (struct mg_connection *)const_conn;
3232
34
    conn->request_info.conn_data = data;
3233
34
  }
3234
34
}
3235
3236
3237
CIVETWEB_API void *
3238
mg_get_user_connection_data(const struct mg_connection *conn)
3239
0
{
3240
0
  if (conn != NULL) {
3241
0
    return conn->request_info.conn_data;
3242
0
  }
3243
0
  return NULL;
3244
0
}
3245
3246
3247
CIVETWEB_API int
3248
mg_get_server_ports(const struct mg_context *ctx,
3249
                    int size,
3250
                    struct mg_server_port *ports)
3251
2
{
3252
2
  int i, cnt = 0;
3253
3254
2
  if (size <= 0) {
3255
0
    return -1;
3256
0
  }
3257
2
  memset(ports, 0, sizeof(*ports) * (size_t)size);
3258
2
  if (!ctx) {
3259
0
    return -1;
3260
0
  }
3261
2
  if (!ctx->listening_sockets) {
3262
0
    return -1;
3263
0
  }
3264
3265
4
  for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
3266
3267
2
    ports[cnt].port =
3268
2
        ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
3269
2
    ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
3270
2
    ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
3271
3272
2
    if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
3273
      /* IPv4 */
3274
2
      ports[cnt].protocol = 1;
3275
2
      cnt++;
3276
2
    } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
3277
      /* IPv6 */
3278
0
      ports[cnt].protocol = 3;
3279
0
      cnt++;
3280
0
    }
3281
2
  }
3282
3283
2
  return cnt;
3284
2
}
3285
3286
3287
#if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
3288
#define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
3289
#endif
3290
3291
static void
3292
sockaddr_to_string(char *buf, size_t len, const union usa *usa)
3293
0
{
3294
0
  buf[0] = '\0';
3295
3296
0
  if (!usa) {
3297
0
    return;
3298
0
  }
3299
3300
0
  if (usa->sa.sa_family == AF_INET) {
3301
0
    getnameinfo(&usa->sa,
3302
0
                sizeof(usa->sin),
3303
0
                buf,
3304
0
                (unsigned)len,
3305
0
                NULL,
3306
0
                0,
3307
0
                NI_NUMERICHOST);
3308
0
  }
3309
#if defined(USE_IPV6)
3310
  else if (usa->sa.sa_family == AF_INET6) {
3311
    getnameinfo(&usa->sa,
3312
                sizeof(usa->sin6),
3313
                buf,
3314
                (unsigned)len,
3315
                NULL,
3316
                0,
3317
                NI_NUMERICHOST);
3318
  }
3319
#endif
3320
#if defined(USE_X_DOM_SOCKET)
3321
  else if (usa->sa.sa_family == AF_UNIX) {
3322
    /* TODO: Define a remote address for unix domain sockets.
3323
    * This code will always return "localhost", identical to http+tcp:
3324
    getnameinfo(&usa->sa,
3325
    sizeof(usa->sun),
3326
    buf,
3327
    (unsigned)len,
3328
    NULL,
3329
    0,
3330
    NI_NUMERICHOST);
3331
    */
3332
    mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
3333
  }
3334
#endif
3335
0
}
3336
3337
3338
/* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
3339
 * included in all responses other than 100, 101, 5xx. */
3340
static void
3341
gmt_time_string(char *buf, size_t buf_len, time_t *t)
3342
0
{
3343
0
#if !defined(REENTRANT_TIME)
3344
0
  struct tm *tm;
3345
3346
0
  tm = ((t != NULL) ? gmtime(t) : NULL);
3347
0
  if (tm != NULL) {
3348
#else
3349
  struct tm _tm;
3350
  struct tm *tm = &_tm;
3351
3352
  if (t != NULL) {
3353
    gmtime_r(t, tm);
3354
#endif
3355
0
    strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
3356
0
  } else {
3357
0
    mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3358
0
  }
3359
0
}
3360
3361
3362
/* difftime for struct timespec. Return value is in seconds. */
3363
static double
3364
mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
3365
10
{
3366
10
  return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3367
10
         + (double)(ts_now->tv_sec - ts_before->tv_sec);
3368
10
}
3369
3370
3371
#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3372
static void mg_cry_internal_impl(const struct mg_connection *conn,
3373
                                 const char *func,
3374
                                 unsigned line,
3375
                                 const char *fmt,
3376
                                 va_list ap);
3377
#include "external_mg_cry_internal_impl.inl"
3378
#elif !defined(NO_FILESYSTEMS)
3379
3380
/* Print error message to the opened error log stream. */
3381
static void
3382
mg_cry_internal_impl(const struct mg_connection *conn,
3383
                     const char *func,
3384
                     unsigned line,
3385
                     const char *fmt,
3386
                     va_list ap)
3387
0
{
3388
0
  char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
3389
0
  struct mg_file fi;
3390
0
  time_t timestamp;
3391
3392
  /* Unused, in the RELEASE build */
3393
0
  (void)func;
3394
0
  (void)line;
3395
3396
#if defined(GCC_DIAGNOSTIC)
3397
#pragma GCC diagnostic push
3398
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
3399
#endif
3400
3401
0
  IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
3402
3403
#if defined(GCC_DIAGNOSTIC)
3404
#pragma GCC diagnostic pop
3405
#endif
3406
3407
0
  buf[sizeof(buf) - 1] = 0;
3408
3409
0
  DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
3410
3411
0
  if (!conn) {
3412
0
    puts(buf);
3413
0
    return;
3414
0
  }
3415
3416
  /* Do not lock when getting the callback value, here and below.
3417
   * I suppose this is fine, since function cannot disappear in the
3418
   * same way string option can. */
3419
0
  if ((conn->phys_ctx->callbacks.log_message == NULL)
3420
0
      || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
3421
3422
0
    if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
3423
0
      if (mg_fopen(conn,
3424
0
                   conn->dom_ctx->config[ERROR_LOG_FILE],
3425
0
                   MG_FOPEN_MODE_APPEND,
3426
0
                   &fi)
3427
0
          == 0) {
3428
0
        fi.access.fp = NULL;
3429
0
      }
3430
0
    } else {
3431
0
      fi.access.fp = NULL;
3432
0
    }
3433
3434
0
    if (fi.access.fp != NULL) {
3435
0
      flockfile(fi.access.fp);
3436
0
      timestamp = time(NULL);
3437
3438
0
      sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
3439
0
      fprintf(fi.access.fp,
3440
0
              "[%010lu] [error] [client %s] ",
3441
0
              (unsigned long)timestamp,
3442
0
              src_addr);
3443
3444
0
      if (conn->request_info.request_method != NULL) {
3445
0
        fprintf(fi.access.fp,
3446
0
                "%s %s: ",
3447
0
                conn->request_info.request_method,
3448
0
                conn->request_info.request_uri
3449
0
                    ? conn->request_info.request_uri
3450
0
                    : "");
3451
0
      }
3452
3453
0
      fprintf(fi.access.fp, "%s", buf);
3454
0
      fputc('\n', fi.access.fp);
3455
0
      fflush(fi.access.fp);
3456
0
      funlockfile(fi.access.fp);
3457
0
      (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
3458
                                    * mg_cry here anyway ;-) */
3459
0
    }
3460
0
  }
3461
0
}
3462
#else
3463
#error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
3464
#endif /* Externally provided function */
3465
3466
3467
/* Construct fake connection structure. Used for logging, if connection
3468
 * is not applicable at the moment of logging. */
3469
static struct mg_connection *
3470
fake_connection(struct mg_connection *fc, struct mg_context *ctx)
3471
0
{
3472
0
  static const struct mg_connection conn_zero = {0};
3473
0
  *fc = conn_zero;
3474
0
  fc->phys_ctx = ctx;
3475
0
  fc->dom_ctx = &(ctx->dd);
3476
0
  return fc;
3477
0
}
3478
3479
3480
static void
3481
mg_cry_internal_wrap(const struct mg_connection *conn,
3482
                     struct mg_context *ctx,
3483
                     const char *func,
3484
                     unsigned line,
3485
                     const char *fmt,
3486
                     ...)
3487
0
{
3488
0
  va_list ap;
3489
0
  va_start(ap, fmt);
3490
0
  if (!conn && ctx) {
3491
0
    struct mg_connection fc;
3492
0
    mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
3493
0
  } else {
3494
0
    mg_cry_internal_impl(conn, func, line, fmt, ap);
3495
0
  }
3496
0
  va_end(ap);
3497
0
}
3498
3499
3500
CIVETWEB_API void
3501
mg_cry(const struct mg_connection *conn, const char *fmt, ...)
3502
0
{
3503
0
  va_list ap;
3504
0
  va_start(ap, fmt);
3505
0
  mg_cry_internal_impl(conn, "user", 0, fmt, ap);
3506
0
  va_end(ap);
3507
0
}
3508
3509
3510
#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3511
3512
3513
CIVETWEB_API const char *
3514
mg_version(void)
3515
0
{
3516
0
  return CIVETWEB_VERSION;
3517
0
}
3518
3519
3520
CIVETWEB_API const struct mg_request_info *
3521
mg_get_request_info(const struct mg_connection *conn)
3522
0
{
3523
0
  if (!conn) {
3524
0
    return NULL;
3525
0
  }
3526
#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3527
  if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
3528
    char txt[16];
3529
    struct mg_workerTLS *tls =
3530
        (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3531
3532
    sprintf(txt, "%03i", conn->response_info.status_code);
3533
    if (strlen(txt) == 3) {
3534
      memcpy(tls->txtbuf, txt, 4);
3535
    } else {
3536
      strcpy(tls->txtbuf, "ERR");
3537
    }
3538
3539
    ((struct mg_connection *)conn)->request_info.local_uri =
3540
        tls->txtbuf; /* use thread safe buffer */
3541
    ((struct mg_connection *)conn)->request_info.local_uri_raw =
3542
        tls->txtbuf; /* use the same thread safe buffer */
3543
    ((struct mg_connection *)conn)->request_info.request_uri =
3544
        tls->txtbuf; /* use  the same thread safe buffer */
3545
3546
    ((struct mg_connection *)conn)->request_info.num_headers =
3547
        conn->response_info.num_headers;
3548
    memcpy(((struct mg_connection *)conn)->request_info.http_headers,
3549
           conn->response_info.http_headers,
3550
           sizeof(conn->response_info.http_headers));
3551
  } else
3552
#endif
3553
0
      if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
3554
0
    return NULL;
3555
0
  }
3556
0
  return &conn->request_info;
3557
0
}
3558
3559
3560
CIVETWEB_API const struct mg_response_info *
3561
mg_get_response_info(const struct mg_connection *conn)
3562
34
{
3563
34
  if (!conn) {
3564
0
    return NULL;
3565
0
  }
3566
34
  if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
3567
0
    return NULL;
3568
0
  }
3569
34
  return &conn->response_info;
3570
34
}
3571
3572
3573
static const char *
3574
get_proto_name(const struct mg_connection *conn)
3575
0
{
3576
0
#if defined(__clang__)
3577
0
#pragma clang diagnostic push
3578
0
#pragma clang diagnostic ignored "-Wunreachable-code"
3579
  /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
3580
   * not supported. Clang raises an "unreachable code" warning for parts of ?:
3581
   * unreachable, but splitting into four different #ifdef clauses here is
3582
   * more complicated.
3583
   */
3584
0
#endif
3585
3586
0
  const struct mg_request_info *ri = &conn->request_info;
3587
3588
0
  const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
3589
0
                           ? (ri->is_ssl ? "wss" : "ws")
3590
0
                           : (ri->is_ssl ? "https" : "http"));
3591
3592
0
  return proto;
3593
3594
0
#if defined(__clang__)
3595
0
#pragma clang diagnostic pop
3596
0
#endif
3597
0
}
3598
3599
3600
static int
3601
mg_construct_local_link(const struct mg_connection *conn,
3602
                        char *buf,
3603
                        size_t buflen,
3604
                        const char *define_proto,
3605
                        int define_port,
3606
                        const char *define_uri)
3607
0
{
3608
0
  if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3609
0
    return -1;
3610
0
  } else {
3611
0
    int i, j;
3612
0
    int truncated = 0;
3613
0
    const struct mg_request_info *ri = &conn->request_info;
3614
3615
0
    const char *proto =
3616
0
        (define_proto != NULL) ? define_proto : get_proto_name(conn);
3617
0
    const char *uri =
3618
0
        (define_uri != NULL)
3619
0
            ? define_uri
3620
0
            : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
3621
0
    int port = (define_port > 0) ? define_port : ri->server_port;
3622
0
    int default_port = 80;
3623
0
    char *uri_encoded;
3624
0
    size_t uri_encoded_len;
3625
3626
0
    if (uri == NULL) {
3627
0
      return -1;
3628
0
    }
3629
3630
0
    uri_encoded_len = strlen(uri) * 3 + 1;
3631
0
    uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
3632
0
    if (uri_encoded == NULL) {
3633
0
      return -1;
3634
0
    }
3635
0
    mg_url_encode(uri, uri_encoded, uri_encoded_len);
3636
3637
    /* Directory separator should be preserved. */
3638
0
    for (i = j = 0; uri_encoded[i]; j++) {
3639
0
      if (!strncmp(uri_encoded + i, "%2f", 3)) {
3640
0
        uri_encoded[j] = '/';
3641
0
        i += 3;
3642
0
      } else {
3643
0
        uri_encoded[j] = uri_encoded[i++];
3644
0
      }
3645
0
    }
3646
0
    uri_encoded[j] = '\0';
3647
3648
#if defined(USE_X_DOM_SOCKET)
3649
    if (conn->client.lsa.sa.sa_family == AF_UNIX) {
3650
      /* TODO: Define and document a link for UNIX domain sockets. */
3651
      /* There seems to be no official standard for this.
3652
       * Common uses seem to be "httpunix://", "http.unix://" or
3653
       * "http+unix://" as a protocol definition string, followed by
3654
       * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
3655
       * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
3656
       * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
3657
       * "" (completely skipping the server name part). In any case, the
3658
       * last part is the server local path. */
3659
      const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
3660
      mg_snprintf(conn,
3661
                  &truncated,
3662
                  buf,
3663
                  buflen,
3664
                  "%s.unix://%s%s",
3665
                  proto,
3666
                  server_name,
3667
                  ri->local_uri);
3668
      default_port = 0;
3669
      mg_free(uri_encoded);
3670
      return 0;
3671
    }
3672
#endif
3673
3674
0
    if (define_proto) {
3675
      /* If we got a protocol name, use the default port accordingly. */
3676
0
      if ((0 == strcmp(define_proto, "https"))
3677
0
          || (0 == strcmp(define_proto, "wss"))) {
3678
0
        default_port = 443;
3679
0
      }
3680
0
    } else if (ri->is_ssl) {
3681
      /* If we did not get a protocol name, use TLS as default if it is
3682
       * already used. */
3683
0
      default_port = 443;
3684
0
    }
3685
3686
0
    {
3687
#if defined(USE_IPV6)
3688
      int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
3689
#endif
3690
0
      int auth_domain_check_enabled =
3691
0
          conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
3692
0
          && (!mg_strcasecmp(
3693
0
                 conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
3694
3695
0
      const char *server_domain =
3696
0
          conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
3697
3698
0
      char portstr[16];
3699
0
      char server_ip[48];
3700
3701
0
      if (port != default_port) {
3702
0
        sprintf(portstr, ":%u", (unsigned)port);
3703
0
      } else {
3704
0
        portstr[0] = 0;
3705
0
      }
3706
3707
0
      if (!auth_domain_check_enabled || !server_domain) {
3708
3709
0
        sockaddr_to_string(server_ip,
3710
0
                           sizeof(server_ip),
3711
0
                           &conn->client.lsa);
3712
3713
0
        server_domain = server_ip;
3714
0
      }
3715
3716
0
      mg_snprintf(conn,
3717
0
                  &truncated,
3718
0
                  buf,
3719
0
                  buflen,
3720
#if defined(USE_IPV6)
3721
                  "%s://%s%s%s%s%s",
3722
                  proto,
3723
                  (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
3724
                  server_domain,
3725
                  (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
3726
#else
3727
0
                  "%s://%s%s%s",
3728
0
                  proto,
3729
0
                  server_domain,
3730
0
#endif
3731
0
                  portstr,
3732
0
                  uri_encoded);
3733
3734
0
      mg_free(uri_encoded);
3735
0
      if (truncated) {
3736
0
        return -1;
3737
0
      }
3738
0
      return 0;
3739
0
    }
3740
0
  }
3741
0
}
3742
3743
3744
CIVETWEB_API int
3745
mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
3746
0
{
3747
0
  return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
3748
0
}
3749
3750
3751
/* Skip the characters until one of the delimiters characters found.
3752
 * 0-terminate resulting word. Skip the delimiter and following whitespaces.
3753
 * Advance pointer to buffer to the next word. Return found 0-terminated
3754
 * word.
3755
 * Delimiters can be quoted with quotechar. */
3756
static char *
3757
skip_quoted(char **buf,
3758
            const char *delimiters,
3759
            const char *whitespace,
3760
            char quotechar)
3761
0
{
3762
0
  char *p, *begin_word, *end_word, *end_whitespace;
3763
3764
0
  begin_word = *buf;
3765
0
  end_word = begin_word + strcspn(begin_word, delimiters);
3766
3767
  /* Check for quotechar */
3768
0
  if (end_word > begin_word) {
3769
0
    p = end_word - 1;
3770
0
    while (*p == quotechar) {
3771
      /* While the delimiter is quoted, look for the next delimiter. */
3772
      /* This happens, e.g., in calls from parse_auth_header,
3773
       * if the user name contains a " character. */
3774
3775
      /* If there is anything beyond end_word, copy it. */
3776
0
      if (*end_word != '\0') {
3777
0
        size_t end_off = strcspn(end_word + 1, delimiters);
3778
0
        memmove(p, end_word, end_off + 1);
3779
0
        p += end_off; /* p must correspond to end_word - 1 */
3780
0
        end_word += end_off + 1;
3781
0
      } else {
3782
0
        *p = '\0';
3783
0
        break;
3784
0
      }
3785
0
    }
3786
0
    for (p++; p < end_word; p++) {
3787
0
      *p = '\0';
3788
0
    }
3789
0
  }
3790
3791
0
  if (*end_word == '\0') {
3792
0
    *buf = end_word;
3793
0
  } else {
3794
3795
#if defined(GCC_DIAGNOSTIC)
3796
    /* Disable spurious conversion warning for GCC */
3797
#pragma GCC diagnostic push
3798
#pragma GCC diagnostic ignored "-Wsign-conversion"
3799
#endif /* defined(GCC_DIAGNOSTIC) */
3800
3801
0
    end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
3802
3803
#if defined(GCC_DIAGNOSTIC)
3804
#pragma GCC diagnostic pop
3805
#endif /* defined(GCC_DIAGNOSTIC) */
3806
3807
0
    for (p = end_word; p < end_whitespace; p++) {
3808
0
      *p = '\0';
3809
0
    }
3810
3811
0
    *buf = end_whitespace;
3812
0
  }
3813
3814
0
  return begin_word;
3815
0
}
3816
3817
3818
/* Return HTTP header value, or NULL if not found. */
3819
static const char *
3820
get_header(const struct mg_header *hdr, int num_hdr, const char *name)
3821
2
{
3822
2
  int i;
3823
2
  for (i = 0; i < num_hdr; i++) {
3824
0
    if (!mg_strcasecmp(name, hdr[i].name)) {
3825
0
      return hdr[i].value;
3826
0
    }
3827
0
  }
3828
3829
2
  return NULL;
3830
2
}
3831
3832
3833
/* Retrieve requested HTTP header multiple values, and return the number of
3834
 * found occurrences */
3835
static int
3836
get_req_headers(const struct mg_request_info *ri,
3837
                const char *name,
3838
                const char **output,
3839
                int output_max_size)
3840
0
{
3841
0
  int i;
3842
0
  int cnt = 0;
3843
0
  if (ri) {
3844
0
    for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
3845
0
      if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
3846
0
        output[cnt++] = ri->http_headers[i].value;
3847
0
      }
3848
0
    }
3849
0
  }
3850
0
  return cnt;
3851
0
}
3852
3853
3854
CIVETWEB_API const char *
3855
mg_get_header(const struct mg_connection *conn, const char *name)
3856
0
{
3857
0
  if (!conn) {
3858
0
    return NULL;
3859
0
  }
3860
3861
0
  if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
3862
0
    return get_header(conn->request_info.http_headers,
3863
0
                      conn->request_info.num_headers,
3864
0
                      name);
3865
0
  }
3866
0
  if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
3867
0
    return get_header(conn->response_info.http_headers,
3868
0
                      conn->response_info.num_headers,
3869
0
                      name);
3870
0
  }
3871
0
  return NULL;
3872
0
}
3873
3874
3875
static const char *
3876
get_http_version(const struct mg_connection *conn)
3877
0
{
3878
0
  if (!conn) {
3879
0
    return NULL;
3880
0
  }
3881
3882
0
  if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
3883
0
    return conn->request_info.http_version;
3884
0
  }
3885
0
  if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
3886
0
    return conn->response_info.http_version;
3887
0
  }
3888
0
  return NULL;
3889
0
}
3890
3891
3892
/* A helper function for traversing a comma separated list of values.
3893
 * It returns a list pointer shifted to the next value, or NULL if the end
3894
 * of the list found.
3895
 * Value is stored in val vector. If value has form "x=y", then eq_val
3896
 * vector is initialized to point to the "y" part, and val vector length
3897
 * is adjusted to point only to "x". */
3898
static const char *
3899
next_option(const char *list, struct vec *val, struct vec *eq_val)
3900
6
{
3901
6
  int end;
3902
3903
6
reparse:
3904
6
  if (val == NULL || list == NULL || *list == '\0') {
3905
    /* End of the list */
3906
4
    return NULL;
3907
4
  }
3908
3909
  /* Skip over leading LWS */
3910
2
  while (*list == ' ' || *list == '\t')
3911
0
    list++;
3912
3913
2
  val->ptr = list;
3914
2
  if ((list = strchr(val->ptr, ',')) != NULL) {
3915
    /* Comma found. Store length and shift the list ptr */
3916
0
    val->len = ((size_t)(list - val->ptr));
3917
0
    list++;
3918
2
  } else {
3919
    /* This value is the last one */
3920
2
    list = val->ptr + strlen(val->ptr);
3921
2
    val->len = ((size_t)(list - val->ptr));
3922
2
  }
3923
3924
  /* Adjust length for trailing LWS */
3925
2
  end = (int)val->len - 1;
3926
2
  while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
3927
0
    end--;
3928
2
  val->len = (size_t)(end) + (size_t)(1);
3929
3930
2
  if (val->len == 0) {
3931
    /* Ignore any empty entries. */
3932
0
    goto reparse;
3933
0
  }
3934
3935
2
  if (eq_val != NULL) {
3936
    /* Value has form "x=y", adjust pointers and lengths
3937
     * so that val points to "x", and eq_val points to "y". */
3938
0
    eq_val->len = 0;
3939
0
    eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
3940
0
    if (eq_val->ptr != NULL) {
3941
0
      eq_val->ptr++; /* Skip over '=' character */
3942
0
      eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
3943
0
      val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
3944
0
    }
3945
0
  }
3946
3947
2
  return list;
3948
2
}
3949
3950
3951
/* A helper function for checking if a comma separated list of values
3952
 * contains
3953
 * the given option (case insensitvely).
3954
 * 'header' can be NULL, in which case false is returned. */
3955
static int
3956
header_has_option(const char *header, const char *option)
3957
0
{
3958
0
  struct vec opt_vec;
3959
0
  struct vec eq_vec;
3960
3961
0
  DEBUG_ASSERT(option != NULL);
3962
0
  DEBUG_ASSERT(option[0] != '\0');
3963
3964
0
  while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
3965
0
    if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
3966
0
      return 1;
3967
0
  }
3968
3969
0
  return 0;
3970
0
}
3971
3972
3973
/* Sorting function implemented in a separate file */
3974
#include "sort.inl"
3975
3976
/* Pattern matching has been reimplemented in a new file */
3977
#include "match.inl"
3978
3979
3980
/* HTTP 1.1 assumes keep alive if "Connection:" header is not set
3981
 * This function must tolerate situations when connection info is not
3982
 * set up, for example if request parsing failed. */
3983
static int
3984
should_keep_alive(const struct mg_connection *conn)
3985
0
{
3986
0
  const char *http_version;
3987
0
  const char *header;
3988
3989
  /* First satisfy needs of the server */
3990
0
  if ((conn == NULL) || conn->must_close) {
3991
    /* Close, if civetweb framework needs to close */
3992
0
    return 0;
3993
0
  }
3994
3995
0
  if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
3996
    /* Close, if keep alive is not enabled */
3997
0
    return 0;
3998
0
  }
3999
4000
  /* Check explicit wish of the client */
4001
0
  header = mg_get_header(conn, "Connection");
4002
0
  if (header) {
4003
    /* If there is a connection header from the client, obey */
4004
0
    if (header_has_option(header, "keep-alive")) {
4005
0
      return 1;
4006
0
    }
4007
0
    return 0;
4008
0
  }
4009
4010
  /* Use default of the standard */
4011
0
  http_version = get_http_version(conn);
4012
0
  if (http_version && (0 == strcmp(http_version, "1.1"))) {
4013
    /* HTTP 1.1 default is keep alive */
4014
0
    return 1;
4015
0
  }
4016
4017
  /* HTTP 1.0 (and earlier) default is to close the connection */
4018
0
  return 0;
4019
0
}
4020
4021
4022
static int
4023
should_decode_url(const struct mg_connection *conn)
4024
0
{
4025
0
  if (!conn || !conn->dom_ctx) {
4026
0
    return 0;
4027
0
  }
4028
4029
0
  return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
4030
0
}
4031
4032
4033
static int
4034
should_decode_query_string(const struct mg_connection *conn)
4035
0
{
4036
0
  if (!conn || !conn->dom_ctx) {
4037
0
    return 0;
4038
0
  }
4039
4040
0
  return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
4041
0
          == 0);
4042
0
}
4043
4044
4045
static const char *
4046
suggest_connection_header(const struct mg_connection *conn)
4047
0
{
4048
0
  return should_keep_alive(conn) ? "keep-alive" : "close";
4049
0
}
4050
4051
4052
#include "response.inl"
4053
4054
4055
static void
4056
send_no_cache_header(struct mg_connection *conn)
4057
0
{
4058
  /* Send all current and obsolete cache opt-out directives. */
4059
0
  mg_response_header_add(conn,
4060
0
                         "Cache-Control",
4061
0
                         "no-cache, no-store, "
4062
0
                         "must-revalidate, private, max-age=0",
4063
0
                         -1);
4064
0
  mg_response_header_add(conn, "Expires", "0", -1);
4065
4066
0
  if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
4067
    /* Obsolete, but still send it for HTTP/1.0 */
4068
0
    mg_response_header_add(conn, "Pragma", "no-cache", -1);
4069
0
  }
4070
0
}
4071
4072
4073
static void
4074
send_static_cache_header(struct mg_connection *conn)
4075
0
{
4076
0
#if !defined(NO_CACHING)
4077
0
  int max_age;
4078
0
  char val[64];
4079
4080
0
  const char *cache_control =
4081
0
      conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
4082
4083
  /* If there is a full cache-control option configured,0 use it */
4084
0
  if (cache_control != NULL) {
4085
0
    mg_response_header_add(conn, "Cache-Control", cache_control, -1);
4086
0
    return;
4087
0
  }
4088
4089
  /* Read the server config to check how long a file may be cached.
4090
   * The configuration is in seconds. */
4091
0
  max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
4092
0
  if (max_age <= 0) {
4093
    /* 0 means "do not cache". All values <0 are reserved
4094
     * and may be used differently in the future. */
4095
    /* If a file should not be cached, do not only send
4096
     * max-age=0, but also pragmas and Expires headers. */
4097
0
    send_no_cache_header(conn);
4098
0
    return;
4099
0
  }
4100
4101
  /* Use "Cache-Control: max-age" instead of "Expires" header.
4102
   * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
4103
  /* See also https://www.mnot.net/cache_docs/ */
4104
  /* According to RFC 2616, Section 14.21, caching times should not exceed
4105
   * one year. A year with 365 days corresponds to 31536000 seconds, a
4106
   * leap
4107
   * year to 31622400 seconds. For the moment, we just send whatever has
4108
   * been configured, still the behavior for >1 year should be considered
4109
   * as undefined. */
4110
0
  mg_snprintf(
4111
0
      conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
4112
0
  mg_response_header_add(conn, "Cache-Control", val, -1);
4113
4114
#else  /* NO_CACHING */
4115
4116
  send_no_cache_header(conn);
4117
#endif /* !NO_CACHING */
4118
0
}
4119
4120
4121
static void
4122
send_additional_header(struct mg_connection *conn)
4123
0
{
4124
0
  const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
4125
4126
0
#if !defined(NO_SSL)
4127
0
  if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
4128
0
    long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
4129
0
    if (max_age >= 0) {
4130
0
      char val[64];
4131
0
      mg_snprintf(conn,
4132
0
                  NULL,
4133
0
                  val,
4134
0
                  sizeof(val),
4135
0
                  "max-age=%lu",
4136
0
                  (unsigned long)max_age);
4137
0
      mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
4138
0
    }
4139
0
  }
4140
0
#endif
4141
4142
0
  if (header && header[0]) {
4143
0
    mg_response_header_add_lines(conn, header);
4144
0
  }
4145
0
}
4146
4147
4148
static void
4149
send_cors_header(struct mg_connection *conn)
4150
0
{
4151
0
  const char *origin_hdr = mg_get_header(conn, "Origin");
4152
0
  const char *cors_orig_cfg =
4153
0
      conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
4154
4155
0
  if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
4156
    /* Cross-origin resource sharing (CORS), see
4157
     * http://www.html5rocks.com/en/tutorials/cors/,
4158
     * http://www.html5rocks.com/static/images/cors_server_flowchart.png
4159
     * CORS preflight is not supported for files. */
4160
0
    mg_response_header_add(conn,
4161
0
                           "Access-Control-Allow-Origin",
4162
0
                           cors_orig_cfg,
4163
0
                           -1);
4164
0
  }
4165
0
}
4166
4167
4168
#if !defined(NO_FILESYSTEMS)
4169
static void handle_file_based_request(struct mg_connection *conn,
4170
                                      const char *path,
4171
                                      struct mg_file *filep);
4172
#endif /* NO_FILESYSTEMS */
4173
4174
4175
CIVETWEB_API const char *
4176
mg_get_response_code_text(const struct mg_connection *conn, int response_code)
4177
0
{
4178
  /* See IANA HTTP status code assignment:
4179
   * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
4180
   */
4181
4182
0
  switch (response_code) {
4183
    /* RFC2616 Section 10.1 - Informational 1xx */
4184
0
  case 100:
4185
0
    return "Continue"; /* RFC2616 Section 10.1.1 */
4186
0
  case 101:
4187
0
    return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
4188
0
  case 102:
4189
0
    return "Processing"; /* RFC2518 Section 10.1 */
4190
4191
    /* RFC2616 Section 10.2 - Successful 2xx */
4192
0
  case 200:
4193
0
    return "OK"; /* RFC2616 Section 10.2.1 */
4194
0
  case 201:
4195
0
    return "Created"; /* RFC2616 Section 10.2.2 */
4196
0
  case 202:
4197
0
    return "Accepted"; /* RFC2616 Section 10.2.3 */
4198
0
  case 203:
4199
0
    return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
4200
0
  case 204:
4201
0
    return "No Content"; /* RFC2616 Section 10.2.5 */
4202
0
  case 205:
4203
0
    return "Reset Content"; /* RFC2616 Section 10.2.6 */
4204
0
  case 206:
4205
0
    return "Partial Content"; /* RFC2616 Section 10.2.7 */
4206
0
  case 207:
4207
0
    return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
4208
                            */
4209
0
  case 208:
4210
0
    return "Already Reported"; /* RFC5842 Section 7.1 */
4211
4212
0
  case 226:
4213
0
    return "IM used"; /* RFC3229 Section 10.4.1 */
4214
4215
    /* RFC2616 Section 10.3 - Redirection 3xx */
4216
0
  case 300:
4217
0
    return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
4218
0
  case 301:
4219
0
    return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
4220
0
  case 302:
4221
0
    return "Found"; /* RFC2616 Section 10.3.3 */
4222
0
  case 303:
4223
0
    return "See Other"; /* RFC2616 Section 10.3.4 */
4224
0
  case 304:
4225
0
    return "Not Modified"; /* RFC2616 Section 10.3.5 */
4226
0
  case 305:
4227
0
    return "Use Proxy"; /* RFC2616 Section 10.3.6 */
4228
0
  case 307:
4229
0
    return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
4230
0
  case 308:
4231
0
    return "Permanent Redirect"; /* RFC7238 Section 3 */
4232
4233
    /* RFC2616 Section 10.4 - Client Error 4xx */
4234
0
  case 400:
4235
0
    return "Bad Request"; /* RFC2616 Section 10.4.1 */
4236
0
  case 401:
4237
0
    return "Unauthorized"; /* RFC2616 Section 10.4.2 */
4238
0
  case 402:
4239
0
    return "Payment Required"; /* RFC2616 Section 10.4.3 */
4240
0
  case 403:
4241
0
    return "Forbidden"; /* RFC2616 Section 10.4.4 */
4242
0
  case 404:
4243
0
    return "Not Found"; /* RFC2616 Section 10.4.5 */
4244
0
  case 405:
4245
0
    return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
4246
0
  case 406:
4247
0
    return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
4248
0
  case 407:
4249
0
    return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
4250
0
  case 408:
4251
0
    return "Request Time-out"; /* RFC2616 Section 10.4.9 */
4252
0
  case 409:
4253
0
    return "Conflict"; /* RFC2616 Section 10.4.10 */
4254
0
  case 410:
4255
0
    return "Gone"; /* RFC2616 Section 10.4.11 */
4256
0
  case 411:
4257
0
    return "Length Required"; /* RFC2616 Section 10.4.12 */
4258
0
  case 412:
4259
0
    return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
4260
0
  case 413:
4261
0
    return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
4262
0
  case 414:
4263
0
    return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
4264
0
  case 415:
4265
0
    return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
4266
0
  case 416:
4267
0
    return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
4268
                                               */
4269
0
  case 417:
4270
0
    return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
4271
4272
0
  case 421:
4273
0
    return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
4274
0
  case 422:
4275
0
    return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
4276
                                     * Section 11.2 */
4277
0
  case 423:
4278
0
    return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
4279
0
  case 424:
4280
0
    return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
4281
                                 * Section 11.4 */
4282
4283
0
  case 426:
4284
0
    return "Upgrade Required"; /* RFC 2817 Section 4 */
4285
4286
0
  case 428:
4287
0
    return "Precondition Required"; /* RFC 6585, Section 3 */
4288
0
  case 429:
4289
0
    return "Too Many Requests"; /* RFC 6585, Section 4 */
4290
4291
0
  case 431:
4292
0
    return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
4293
4294
0
  case 451:
4295
0
    return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
4296
                                             * Section 3 */
4297
4298
    /* RFC2616 Section 10.5 - Server Error 5xx */
4299
0
  case 500:
4300
0
    return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
4301
0
  case 501:
4302
0
    return "Not Implemented"; /* RFC2616 Section 10.5.2 */
4303
0
  case 502:
4304
0
    return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
4305
0
  case 503:
4306
0
    return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
4307
0
  case 504:
4308
0
    return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
4309
0
  case 505:
4310
0
    return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
4311
0
  case 506:
4312
0
    return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
4313
0
  case 507:
4314
0
    return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
4315
                                    * Section 11.5 */
4316
0
  case 508:
4317
0
    return "Loop Detected"; /* RFC5842 Section 7.1 */
4318
4319
0
  case 510:
4320
0
    return "Not Extended"; /* RFC 2774, Section 7 */
4321
0
  case 511:
4322
0
    return "Network Authentication Required"; /* RFC 6585, Section 6 */
4323
4324
    /* Other status codes, not shown in the IANA HTTP status code
4325
     * assignment.
4326
     * E.g., "de facto" standards due to common use, ... */
4327
0
  case 418:
4328
0
    return "I am a teapot"; /* RFC2324 Section 2.3.2 */
4329
0
  case 419:
4330
0
    return "Authentication Timeout"; /* common use */
4331
0
  case 420:
4332
0
    return "Enhance Your Calm"; /* common use */
4333
0
  case 440:
4334
0
    return "Login Timeout"; /* common use */
4335
0
  case 509:
4336
0
    return "Bandwidth Limit Exceeded"; /* common use */
4337
4338
0
  default:
4339
    /* This error code is unknown. This should not happen. */
4340
0
    if (conn) {
4341
0
      mg_cry_internal(conn,
4342
0
                      "Unknown HTTP response code: %u",
4343
0
                      response_code);
4344
0
    }
4345
4346
    /* Return at least a category according to RFC 2616 Section 10. */
4347
0
    if (response_code >= 100 && response_code < 200) {
4348
      /* Unknown informational status code */
4349
0
      return "Information";
4350
0
    }
4351
0
    if (response_code >= 200 && response_code < 300) {
4352
      /* Unknown success code */
4353
0
      return "Success";
4354
0
    }
4355
0
    if (response_code >= 300 && response_code < 400) {
4356
      /* Unknown redirection code */
4357
0
      return "Redirection";
4358
0
    }
4359
0
    if (response_code >= 400 && response_code < 500) {
4360
      /* Unknown request error code */
4361
0
      return "Client Error";
4362
0
    }
4363
0
    if (response_code >= 500 && response_code < 600) {
4364
      /* Unknown server error code */
4365
0
      return "Server Error";
4366
0
    }
4367
4368
    /* Response code not even within reasonable range */
4369
0
    return "";
4370
0
  }
4371
0
}
4372
4373
4374
static int
4375
mg_send_http_error_impl(struct mg_connection *conn,
4376
                        int status,
4377
                        const char *fmt,
4378
                        va_list args)
4379
0
{
4380
0
  char errmsg_buf[MG_BUF_LEN];
4381
0
  va_list ap;
4382
0
  int has_body;
4383
4384
0
#if !defined(NO_FILESYSTEMS)
4385
0
  char path_buf[UTF8_PATH_MAX];
4386
0
  int len, i, page_handler_found, scope, truncated;
4387
0
  const char *error_handler = NULL;
4388
0
  struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
4389
0
  const char *error_page_file_ext, *tstr;
4390
0
#endif /* NO_FILESYSTEMS */
4391
0
  int handled_by_callback = 0;
4392
4393
0
  if ((conn == NULL) || (fmt == NULL)) {
4394
0
    return -2;
4395
0
  }
4396
4397
  /* Set status (for log) */
4398
0
  conn->status_code = status;
4399
4400
  /* Errors 1xx, 204 and 304 MUST NOT send a body */
4401
0
  has_body = ((status > 199) && (status != 204) && (status != 304));
4402
4403
  /* Prepare message in buf, if required */
4404
0
  if (has_body
4405
0
      || (!conn->in_error_handler
4406
0
          && (conn->phys_ctx->callbacks.http_error != NULL))) {
4407
    /* Store error message in errmsg_buf */
4408
0
    va_copy(ap, args);
4409
0
    mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
4410
0
    va_end(ap);
4411
    /* In a debug build, print all html errors */
4412
0
    DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
4413
0
  }
4414
4415
  /* If there is a http_error callback, call it.
4416
   * But don't do it recursively, if callback calls mg_send_http_error again.
4417
   */
4418
0
  if (!conn->in_error_handler
4419
0
      && (conn->phys_ctx->callbacks.http_error != NULL)) {
4420
    /* Mark in_error_handler to avoid recursion and call user callback. */
4421
0
    conn->in_error_handler = 1;
4422
0
    handled_by_callback =
4423
0
        (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
4424
0
         == 0);
4425
0
    conn->in_error_handler = 0;
4426
0
  }
4427
4428
0
  if (!handled_by_callback) {
4429
    /* Check for recursion */
4430
0
    if (conn->in_error_handler) {
4431
0
      DEBUG_TRACE(
4432
0
          "Recursion when handling error %u - fall back to default",
4433
0
          status);
4434
0
#if !defined(NO_FILESYSTEMS)
4435
0
    } else {
4436
      /* Send user defined error pages, if defined */
4437
0
      error_handler = conn->dom_ctx->config[ERROR_PAGES];
4438
0
      error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
4439
0
      page_handler_found = 0;
4440
4441
0
      if (error_handler != NULL) {
4442
0
        for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4443
0
          switch (scope) {
4444
0
          case 1: /* Handler for specific error, e.g. 404 error */
4445
0
            mg_snprintf(conn,
4446
0
                        &truncated,
4447
0
                        path_buf,
4448
0
                        sizeof(path_buf) - 32,
4449
0
                        "%serror%03u.",
4450
0
                        error_handler,
4451
0
                        status);
4452
0
            break;
4453
0
          case 2: /* Handler for error group, e.g., 5xx error
4454
                   * handler
4455
                   * for all server errors (500-599) */
4456
0
            mg_snprintf(conn,
4457
0
                        &truncated,
4458
0
                        path_buf,
4459
0
                        sizeof(path_buf) - 32,
4460
0
                        "%serror%01uxx.",
4461
0
                        error_handler,
4462
0
                        status / 100);
4463
0
            break;
4464
0
          default: /* Handler for all errors */
4465
0
            mg_snprintf(conn,
4466
0
                        &truncated,
4467
0
                        path_buf,
4468
0
                        sizeof(path_buf) - 32,
4469
0
                        "%serror.",
4470
0
                        error_handler);
4471
0
            break;
4472
0
          }
4473
4474
          /* String truncation in buf may only occur if
4475
           * error_handler is too long. This string is
4476
           * from the config, not from a client. */
4477
0
          (void)truncated;
4478
4479
          /* The following code is redundant, but it should avoid
4480
           * false positives in static source code analyzers and
4481
           * vulnerability scanners.
4482
           */
4483
0
          path_buf[sizeof(path_buf) - 32] = 0;
4484
0
          len = (int)strlen(path_buf);
4485
0
          if (len > (int)sizeof(path_buf) - 32) {
4486
0
            len = (int)sizeof(path_buf) - 32;
4487
0
          }
4488
4489
          /* Start with the file extension from the configuration. */
4490
0
          tstr = strchr(error_page_file_ext, '.');
4491
4492
0
          while (tstr) {
4493
0
            for (i = 1;
4494
0
                 (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
4495
0
                 i++) {
4496
              /* buffer overrun is not possible here, since
4497
               * (i < 32) && (len < sizeof(path_buf) - 32)
4498
               * ==> (i + len) < sizeof(path_buf) */
4499
0
              path_buf[len + i - 1] = tstr[i];
4500
0
            }
4501
            /* buffer overrun is not possible here, since
4502
             * (i <= 32) && (len < sizeof(path_buf) - 32)
4503
             * ==> (i + len) <= sizeof(path_buf) */
4504
0
            path_buf[len + i - 1] = 0;
4505
4506
0
            if (mg_stat(conn, path_buf, &error_page_file.stat)) {
4507
0
              DEBUG_TRACE("Check error page %s - found",
4508
0
                          path_buf);
4509
0
              page_handler_found = 1;
4510
0
              break;
4511
0
            }
4512
0
            DEBUG_TRACE("Check error page %s - not found",
4513
0
                        path_buf);
4514
4515
            /* Continue with the next file extension from the
4516
             * configuration (if there is a next one). */
4517
0
            tstr = strchr(tstr + i, '.');
4518
0
          }
4519
0
        }
4520
0
      }
4521
4522
0
      if (page_handler_found) {
4523
0
        conn->in_error_handler = 1;
4524
0
        handle_file_based_request(conn, path_buf, &error_page_file);
4525
0
        conn->in_error_handler = 0;
4526
0
        return 0;
4527
0
      }
4528
0
#endif /* NO_FILESYSTEMS */
4529
0
    }
4530
4531
    /* No custom error page. Send default error page. */
4532
0
    conn->must_close = 1;
4533
0
    mg_response_header_start(conn, status);
4534
0
    send_no_cache_header(conn);
4535
0
    send_additional_header(conn);
4536
0
    send_cors_header(conn);
4537
0
    if (has_body) {
4538
0
      mg_response_header_add(conn,
4539
0
                             "Content-Type",
4540
0
                             "text/plain; charset=utf-8",
4541
0
                             -1);
4542
0
    }
4543
0
    mg_response_header_send(conn);
4544
4545
    /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
4546
0
    if (has_body) {
4547
      /* For other errors, send a generic error message. */
4548
0
      const char *status_text = mg_get_response_code_text(conn, status);
4549
0
      mg_printf(conn, "Error %d: %s\n", status, status_text);
4550
0
      mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4551
4552
0
    } else {
4553
      /* No body allowed. Close the connection. */
4554
0
      DEBUG_TRACE("Error %i", status);
4555
0
    }
4556
0
  }
4557
0
  return 0;
4558
0
}
4559
4560
4561
CIVETWEB_API int
4562
mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
4563
0
{
4564
0
  va_list ap;
4565
0
  int ret;
4566
4567
0
  va_start(ap, fmt);
4568
0
  ret = mg_send_http_error_impl(conn, status, fmt, ap);
4569
0
  va_end(ap);
4570
4571
0
  return ret;
4572
0
}
4573
4574
4575
CIVETWEB_API int
4576
mg_send_http_ok(struct mg_connection *conn,
4577
                const char *mime_type,
4578
                long long content_length)
4579
0
{
4580
0
  if ((mime_type == NULL) || (*mime_type == 0)) {
4581
    /* No content type defined: default to text/html */
4582
0
    mime_type = "text/html";
4583
0
  }
4584
4585
0
  mg_response_header_start(conn, 200);
4586
0
  send_no_cache_header(conn);
4587
0
  send_additional_header(conn);
4588
0
  send_cors_header(conn);
4589
0
  mg_response_header_add(conn, "Content-Type", mime_type, -1);
4590
0
  if (content_length < 0) {
4591
    /* Size not known. Use chunked encoding (HTTP/1.x) */
4592
0
    if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
4593
      /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
4594
0
      mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
4595
0
    }
4596
0
  } else {
4597
0
    char len[32];
4598
0
    int trunc = 0;
4599
0
    mg_snprintf(conn,
4600
0
                &trunc,
4601
0
                len,
4602
0
                sizeof(len),
4603
0
                "%" UINT64_FMT,
4604
0
                (uint64_t)content_length);
4605
0
    if (!trunc) {
4606
      /* Since 32 bytes is enough to hold any 64 bit decimal number,
4607
       * !trunc is always true */
4608
0
      mg_response_header_add(conn, "Content-Length", len, -1);
4609
0
    }
4610
0
  }
4611
0
  mg_response_header_send(conn);
4612
4613
0
  return 0;
4614
0
}
4615
4616
4617
CIVETWEB_API int
4618
mg_send_http_redirect(struct mg_connection *conn,
4619
                      const char *target_url,
4620
                      int redirect_code)
4621
0
{
4622
  /* Send a 30x redirect response.
4623
   *
4624
   * Redirect types (status codes):
4625
   *
4626
   * Status | Perm/Temp | Method              | Version
4627
   *   301  | permanent | POST->GET undefined | HTTP/1.0
4628
   *   302  | temporary | POST->GET undefined | HTTP/1.0
4629
   *   303  | temporary | always use GET      | HTTP/1.1
4630
   *   307  | temporary | always keep method  | HTTP/1.1
4631
   *   308  | permanent | always keep method  | HTTP/1.1
4632
   */
4633
4634
#if defined(MG_SEND_REDIRECT_BODY)
4635
  char redirect_body[MG_BUF_LEN];
4636
  size_t content_len = 0;
4637
  char content_len_text[32];
4638
#endif
4639
4640
  /* In case redirect_code=0, use 307. */
4641
0
  if (redirect_code == 0) {
4642
0
    redirect_code = 307;
4643
0
  }
4644
4645
  /* In case redirect_code is none of the above, return error. */
4646
0
  if ((redirect_code != 301) && (redirect_code != 302)
4647
0
      && (redirect_code != 303) && (redirect_code != 307)
4648
0
      && (redirect_code != 308)) {
4649
    /* Parameter error */
4650
0
    return -2;
4651
0
  }
4652
4653
  /* If target_url is not defined, redirect to "/". */
4654
0
  if ((target_url == NULL) || (*target_url == 0)) {
4655
0
    target_url = "/";
4656
0
  }
4657
4658
#if defined(MG_SEND_REDIRECT_BODY)
4659
  /* TODO: condition name? */
4660
4661
  /* Prepare a response body with a hyperlink.
4662
   *
4663
   * According to RFC2616 (and RFC1945 before):
4664
   * Unless the request method was HEAD, the entity of the
4665
   * response SHOULD contain a short hypertext note with a hyperlink to
4666
   * the new URI(s).
4667
   *
4668
   * However, this response body is not useful in M2M communication.
4669
   * Probably the original reason in the RFC was, clients not supporting
4670
   * a 30x HTTP redirect could still show the HTML page and let the user
4671
   * press the link. Since current browsers support 30x HTTP, the additional
4672
   * HTML body does not seem to make sense anymore.
4673
   *
4674
   * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
4675
   * but it only notes:
4676
   * The server's response payload usually contains a short
4677
   * hypertext note with a hyperlink to the new URI(s).
4678
   *
4679
   * Deactivated by default. If you need the 30x body, set the define.
4680
   */
4681
  mg_snprintf(
4682
      conn,
4683
      NULL /* ignore truncation */,
4684
      redirect_body,
4685
      sizeof(redirect_body),
4686
      "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4687
      redirect_text,
4688
      target_url,
4689
      target_url);
4690
  content_len = strlen(reply);
4691
  sprintf(content_len_text, "%lu", (unsigned long)content_len);
4692
#endif
4693
4694
  /* Send all required headers */
4695
0
  mg_response_header_start(conn, redirect_code);
4696
0
  mg_response_header_add(conn, "Location", target_url, -1);
4697
0
  if ((redirect_code == 301) || (redirect_code == 308)) {
4698
    /* Permanent redirect */
4699
0
    send_static_cache_header(conn);
4700
0
  } else {
4701
    /* Temporary redirect */
4702
0
    send_no_cache_header(conn);
4703
0
  }
4704
0
  send_additional_header(conn);
4705
0
  send_cors_header(conn);
4706
#if defined(MG_SEND_REDIRECT_BODY)
4707
  mg_response_header_add(conn, "Content-Type", "text/html", -1);
4708
  mg_response_header_add(conn, "Content-Length", content_len_text, -1);
4709
#else
4710
0
  mg_response_header_add(conn, "Content-Length", "0", 1);
4711
0
#endif
4712
0
  mg_response_header_send(conn);
4713
4714
#if defined(MG_SEND_REDIRECT_BODY)
4715
  /* Send response body */
4716
  /* ... unless it is a HEAD request */
4717
  if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
4718
    ret = mg_write(conn, redirect_body, content_len);
4719
  }
4720
#endif
4721
4722
0
  return 1;
4723
0
}
4724
4725
4726
#if defined(_WIN32)
4727
/* Create substitutes for POSIX functions in Win32. */
4728
4729
#if defined(GCC_DIAGNOSTIC)
4730
/* Show no warning in case system functions are not used. */
4731
#pragma GCC diagnostic push
4732
#pragma GCC diagnostic ignored "-Wunused-function"
4733
#endif
4734
4735
4736
static int
4737
pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
4738
{
4739
  (void)unused;
4740
  /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
4741
  InitializeCriticalSection(&mutex->sec);
4742
  return 0;
4743
}
4744
4745
4746
static int
4747
pthread_mutex_destroy(pthread_mutex_t *mutex)
4748
{
4749
  DeleteCriticalSection(&mutex->sec);
4750
  return 0;
4751
}
4752
4753
4754
static int
4755
pthread_mutex_lock(pthread_mutex_t *mutex)
4756
{
4757
  EnterCriticalSection(&mutex->sec);
4758
  return 0;
4759
}
4760
4761
4762
static int
4763
pthread_mutex_unlock(pthread_mutex_t *mutex)
4764
{
4765
  LeaveCriticalSection(&mutex->sec);
4766
  return 0;
4767
}
4768
4769
4770
FUNCTION_MAY_BE_UNUSED
4771
static int
4772
pthread_cond_init(pthread_cond_t *cv, const void *unused)
4773
{
4774
  (void)unused;
4775
  (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
4776
  cv->waiting_thread = NULL;
4777
  return 0;
4778
}
4779
4780
4781
FUNCTION_MAY_BE_UNUSED
4782
static int
4783
pthread_cond_timedwait(pthread_cond_t *cv,
4784
                       pthread_mutex_t *mutex,
4785
                       FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
4786
{
4787
  struct mg_workerTLS **ptls,
4788
      *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
4789
  int ok;
4790
  uint64_t nsnow, nswaitabs;
4791
  int64_t nswaitrel;
4792
  DWORD mswaitrel;
4793
4794
  pthread_mutex_lock(&cv->threadIdSec);
4795
  /* Add this thread to cv's waiting list */
4796
  ptls = &cv->waiting_thread;
4797
  for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
4798
    ;
4799
  tls->next_waiting_thread = NULL;
4800
  *ptls = tls;
4801
  pthread_mutex_unlock(&cv->threadIdSec);
4802
4803
  if (abstime) {
4804
    nsnow = mg_get_current_time_ns();
4805
    nswaitabs =
4806
        (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
4807
    nswaitrel = nswaitabs - nsnow;
4808
    if (nswaitrel < 0) {
4809
      nswaitrel = 0;
4810
    }
4811
    mswaitrel = (DWORD)(nswaitrel / 1000000);
4812
  } else {
4813
    mswaitrel = (DWORD)INFINITE;
4814
  }
4815
4816
  pthread_mutex_unlock(mutex);
4817
  ok = (WAIT_OBJECT_0
4818
        == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
4819
  if (!ok) {
4820
    ok = 1;
4821
    pthread_mutex_lock(&cv->threadIdSec);
4822
    ptls = &cv->waiting_thread;
4823
    for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
4824
      if (*ptls == tls) {
4825
        *ptls = tls->next_waiting_thread;
4826
        ok = 0;
4827
        break;
4828
      }
4829
    }
4830
    pthread_mutex_unlock(&cv->threadIdSec);
4831
    if (ok) {
4832
      WaitForSingleObject(tls->pthread_cond_helper_mutex,
4833
                          (DWORD)INFINITE);
4834
    }
4835
  }
4836
  /* This thread has been removed from cv's waiting list */
4837
  pthread_mutex_lock(mutex);
4838
4839
  return ok ? 0 : -1;
4840
}
4841
4842
4843
FUNCTION_MAY_BE_UNUSED
4844
static int
4845
pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
4846
{
4847
  return pthread_cond_timedwait(cv, mutex, NULL);
4848
}
4849
4850
4851
FUNCTION_MAY_BE_UNUSED
4852
static int
4853
pthread_cond_signal(pthread_cond_t *cv)
4854
{
4855
  HANDLE wkup = NULL;
4856
  BOOL ok = FALSE;
4857
4858
  pthread_mutex_lock(&cv->threadIdSec);
4859
  if (cv->waiting_thread) {
4860
    wkup = cv->waiting_thread->pthread_cond_helper_mutex;
4861
    cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
4862
4863
    ok = SetEvent(wkup);
4864
    DEBUG_ASSERT(ok);
4865
  }
4866
  pthread_mutex_unlock(&cv->threadIdSec);
4867
4868
  return ok ? 0 : 1;
4869
}
4870
4871
4872
FUNCTION_MAY_BE_UNUSED
4873
static int
4874
pthread_cond_broadcast(pthread_cond_t *cv)
4875
{
4876
  pthread_mutex_lock(&cv->threadIdSec);
4877
  while (cv->waiting_thread) {
4878
    pthread_cond_signal(cv);
4879
  }
4880
  pthread_mutex_unlock(&cv->threadIdSec);
4881
4882
  return 0;
4883
}
4884
4885
4886
FUNCTION_MAY_BE_UNUSED
4887
static int
4888
pthread_cond_destroy(pthread_cond_t *cv)
4889
{
4890
  pthread_mutex_lock(&cv->threadIdSec);
4891
  DEBUG_ASSERT(cv->waiting_thread == NULL);
4892
  pthread_mutex_unlock(&cv->threadIdSec);
4893
  pthread_mutex_destroy(&cv->threadIdSec);
4894
4895
  return 0;
4896
}
4897
4898
4899
#if defined(ALTERNATIVE_QUEUE)
4900
FUNCTION_MAY_BE_UNUSED
4901
static void *
4902
event_create(void)
4903
{
4904
  return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
4905
}
4906
4907
4908
FUNCTION_MAY_BE_UNUSED
4909
static int
4910
event_wait(void *eventhdl)
4911
{
4912
  int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
4913
  return (res == WAIT_OBJECT_0);
4914
}
4915
4916
4917
FUNCTION_MAY_BE_UNUSED
4918
static int
4919
event_signal(void *eventhdl)
4920
{
4921
  return (int)SetEvent((HANDLE)eventhdl);
4922
}
4923
4924
4925
FUNCTION_MAY_BE_UNUSED
4926
static void
4927
event_destroy(void *eventhdl)
4928
{
4929
  CloseHandle((HANDLE)eventhdl);
4930
}
4931
#endif
4932
4933
4934
#if defined(GCC_DIAGNOSTIC)
4935
/* Enable unused function warning again */
4936
#pragma GCC diagnostic pop
4937
#endif
4938
4939
4940
/* For Windows, change all slashes to backslashes in path names. */
4941
static void
4942
change_slashes_to_backslashes(char *path)
4943
{
4944
  int i;
4945
4946
  for (i = 0; path[i] != '\0'; i++) {
4947
    if (path[i] == '/') {
4948
      path[i] = '\\';
4949
    }
4950
4951
    /* remove double backslash (check i > 0 to preserve UNC paths,
4952
     * like \\server\file.txt) */
4953
    if ((i > 0) && (path[i] == '\\')) {
4954
      while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
4955
        (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
4956
      }
4957
    }
4958
  }
4959
}
4960
4961
4962
static int
4963
mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
4964
{
4965
  int diff;
4966
4967
  do {
4968
    diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
4969
           - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
4970
    s1++;
4971
    s2++;
4972
  } while ((diff == 0) && (s1[-1] != L'\0'));
4973
4974
  return diff;
4975
}
4976
4977
4978
/* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
4979
 * wbuf and wbuf_len is a target buffer and its length. */
4980
static void
4981
path_to_unicode(const struct mg_connection *conn,
4982
                const char *path,
4983
                wchar_t *wbuf,
4984
                size_t wbuf_len)
4985
{
4986
  char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
4987
  wchar_t wbuf2[UTF16_PATH_MAX + 1];
4988
  DWORD long_len, err;
4989
  int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
4990
4991
  mg_strlcpy(buf, path, sizeof(buf));
4992
  change_slashes_to_backslashes(buf);
4993
4994
  /* Convert to Unicode and back. If doubly-converted string does not
4995
   * match the original, something is fishy, reject. */
4996
  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
4997
  MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
4998
  WideCharToMultiByte(
4999
      CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
5000
  if (strcmp(buf, buf2) != 0) {
5001
    wbuf[0] = L'\0';
5002
  }
5003
5004
  /* Windows file systems are not case sensitive, but you can still use
5005
   * uppercase and lowercase letters (on all modern file systems).
5006
   * The server can check if the URI uses the same upper/lowercase
5007
   * letters an the file system, effectively making Windows servers
5008
   * case sensitive (like Linux servers are). It is still not possible
5009
   * to use two files with the same name in different cases on Windows
5010
   * (like /a and /A) - this would be possible in Linux.
5011
   * As a default, Windows is not case sensitive, but the case sensitive
5012
   * file name check can be activated by an additional configuration. */
5013
  if (conn) {
5014
    if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
5015
        && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
5016
                          "yes")) {
5017
      /* Use case sensitive compare function */
5018
      fcompare = wcscmp;
5019
    }
5020
  }
5021
  (void)conn; /* conn is currently unused */
5022
5023
  /* Only accept a full file path, not a Windows short (8.3) path. */
5024
  memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
5025
  long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
5026
  if (long_len == 0) {
5027
    err = GetLastError();
5028
    if (err == ERROR_FILE_NOT_FOUND) {
5029
      /* File does not exist. This is not always a problem here. */
5030
      return;
5031
    }
5032
  }
5033
  if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5034
    /* Short name is used. */
5035
    wbuf[0] = L'\0';
5036
  }
5037
}
5038
5039
5040
#if !defined(NO_FILESYSTEMS)
5041
/* Get file information, return 1 if file exists, 0 if not */
5042
static int
5043
mg_stat(const struct mg_connection *conn,
5044
        const char *path,
5045
        struct mg_file_stat *filep)
5046
{
5047
  wchar_t wbuf[UTF16_PATH_MAX];
5048
  WIN32_FILE_ATTRIBUTE_DATA info;
5049
  time_t creation_time;
5050
  size_t len;
5051
5052
  if (!filep) {
5053
    return 0;
5054
  }
5055
  memset(filep, 0, sizeof(*filep));
5056
5057
  if (mg_path_suspicious(conn, path)) {
5058
    return 0;
5059
  }
5060
5061
  path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5062
  /* Windows happily opens files with some garbage at the end of file name.
5063
   * For example, fopen("a.cgi    ", "r") on Windows successfully opens
5064
   * "a.cgi", despite one would expect an error back. */
5065
  len = strlen(path);
5066
  if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
5067
      && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
5068
    filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5069
    filep->last_modified =
5070
        SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5071
                      info.ftLastWriteTime.dwHighDateTime);
5072
5073
    /* On Windows, the file creation time can be higher than the
5074
     * modification time, e.g. when a file is copied.
5075
     * Since the Last-Modified timestamp is used for caching
5076
     * it should be based on the most recent timestamp. */
5077
    creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5078
                                  info.ftCreationTime.dwHighDateTime);
5079
    if (creation_time > filep->last_modified) {
5080
      filep->last_modified = creation_time;
5081
    }
5082
5083
    filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5084
    return 1;
5085
  }
5086
5087
  return 0;
5088
}
5089
#endif
5090
5091
5092
static int
5093
mg_remove(const struct mg_connection *conn, const char *path)
5094
{
5095
  wchar_t wbuf[UTF16_PATH_MAX];
5096
  path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5097
  return DeleteFileW(wbuf) ? 0 : -1;
5098
}
5099
5100
5101
static int
5102
mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
5103
{
5104
  wchar_t wbuf[UTF16_PATH_MAX];
5105
  (void)mode;
5106
  path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5107
  return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5108
}
5109
5110
5111
/* Create substitutes for POSIX functions in Win32. */
5112
5113
#if defined(GCC_DIAGNOSTIC)
5114
/* Show no warning in case system functions are not used. */
5115
#pragma GCC diagnostic push
5116
#pragma GCC diagnostic ignored "-Wunused-function"
5117
#endif
5118
5119
5120
/* Implementation of POSIX opendir/closedir/readdir for Windows. */
5121
FUNCTION_MAY_BE_UNUSED
5122
static DIR *
5123
mg_opendir(const struct mg_connection *conn, const char *name)
5124
{
5125
  DIR *dir = NULL;
5126
  wchar_t wpath[UTF16_PATH_MAX];
5127
  DWORD attrs;
5128
5129
  if (name == NULL) {
5130
    SetLastError(ERROR_BAD_ARGUMENTS);
5131
  } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
5132
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5133
  } else {
5134
    path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
5135
    attrs = GetFileAttributesW(wpath);
5136
    if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5137
        && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5138
      (void)wcscat(wpath, L"\\*");
5139
      dir->handle = FindFirstFileW(wpath, &dir->info);
5140
      dir->result.d_name[0] = '\0';
5141
    } else {
5142
      mg_free(dir);
5143
      dir = NULL;
5144
    }
5145
  }
5146
5147
  return dir;
5148
}
5149
5150
5151
FUNCTION_MAY_BE_UNUSED
5152
static int
5153
mg_closedir(DIR *dir)
5154
{
5155
  int result = 0;
5156
5157
  if (dir != NULL) {
5158
    if (dir->handle != INVALID_HANDLE_VALUE)
5159
      result = FindClose(dir->handle) ? 0 : -1;
5160
5161
    mg_free(dir);
5162
  } else {
5163
    result = -1;
5164
    SetLastError(ERROR_BAD_ARGUMENTS);
5165
  }
5166
5167
  return result;
5168
}
5169
5170
5171
FUNCTION_MAY_BE_UNUSED
5172
static struct dirent *
5173
mg_readdir(DIR *dir)
5174
{
5175
  struct dirent *result = 0;
5176
5177
  if (dir) {
5178
    if (dir->handle != INVALID_HANDLE_VALUE) {
5179
      result = &dir->result;
5180
      (void)WideCharToMultiByte(CP_UTF8,
5181
                                0,
5182
                                dir->info.cFileName,
5183
                                -1,
5184
                                result->d_name,
5185
                                sizeof(result->d_name),
5186
                                NULL,
5187
                                NULL);
5188
5189
      if (!FindNextFileW(dir->handle, &dir->info)) {
5190
        (void)FindClose(dir->handle);
5191
        dir->handle = INVALID_HANDLE_VALUE;
5192
      }
5193
5194
    } else {
5195
      SetLastError(ERROR_FILE_NOT_FOUND);
5196
    }
5197
  } else {
5198
    SetLastError(ERROR_BAD_ARGUMENTS);
5199
  }
5200
5201
  return result;
5202
}
5203
5204
5205
#if !defined(HAVE_POLL)
5206
#undef POLLIN
5207
#undef POLLPRI
5208
#undef POLLOUT
5209
#undef POLLERR
5210
#define POLLIN (1)  /* Data ready - read will not block. */
5211
#define POLLPRI (2) /* Priority data ready. */
5212
#define POLLOUT (4) /* Send queue not full - write will not block. */
5213
#define POLLERR (8) /* Error event */
5214
5215
FUNCTION_MAY_BE_UNUSED
5216
static int
5217
poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
5218
{
5219
  struct timeval tv;
5220
  fd_set rset;
5221
  fd_set wset;
5222
  fd_set eset;
5223
  unsigned int i;
5224
  int result;
5225
  SOCKET maxfd = 0;
5226
5227
  memset(&tv, 0, sizeof(tv));
5228
  tv.tv_sec = milliseconds / 1000;
5229
  tv.tv_usec = (milliseconds % 1000) * 1000;
5230
  FD_ZERO(&rset);
5231
  FD_ZERO(&wset);
5232
  FD_ZERO(&eset);
5233
5234
  for (i = 0; i < n; i++) {
5235
    if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
5236
      if (pfd[i].events & POLLIN) {
5237
        FD_SET(pfd[i].fd, &rset);
5238
      }
5239
      if (pfd[i].events & POLLOUT) {
5240
        FD_SET(pfd[i].fd, &wset);
5241
      }
5242
      /* Check for errors for any FD in the set */
5243
      FD_SET(pfd[i].fd, &eset);
5244
    }
5245
    pfd[i].revents = 0;
5246
5247
    if (pfd[i].fd > maxfd) {
5248
      maxfd = pfd[i].fd;
5249
    }
5250
  }
5251
5252
  if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
5253
    for (i = 0; i < n; i++) {
5254
      if (FD_ISSET(pfd[i].fd, &rset)) {
5255
        pfd[i].revents |= POLLIN;
5256
      }
5257
      if (FD_ISSET(pfd[i].fd, &wset)) {
5258
        pfd[i].revents |= POLLOUT;
5259
      }
5260
      if (FD_ISSET(pfd[i].fd, &eset)) {
5261
        pfd[i].revents |= POLLERR;
5262
      }
5263
    }
5264
  }
5265
5266
  /* We should subtract the time used in select from remaining
5267
   * "milliseconds", in particular if called from mg_poll with a
5268
   * timeout quantum.
5269
   * Unfortunately, the remaining time is not stored in "tv" in all
5270
   * implementations, so the result in "tv" must be considered undefined.
5271
   * See http://man7.org/linux/man-pages/man2/select.2.html */
5272
5273
  return result;
5274
}
5275
#endif /* HAVE_POLL */
5276
5277
5278
#if defined(GCC_DIAGNOSTIC)
5279
/* Enable unused function warning again */
5280
#pragma GCC diagnostic pop
5281
#endif
5282
5283
5284
static void
5285
set_close_on_exec(SOCKET sock,
5286
                  const struct mg_connection *conn /* may be null */,
5287
                  struct mg_context *ctx /* may be null */)
5288
{
5289
  (void)conn; /* Unused. */
5290
  (void)ctx;
5291
5292
  (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5293
}
5294
5295
5296
CIVETWEB_API int
5297
mg_start_thread(mg_thread_func_t f, void *p)
5298
{
5299
#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5300
  /* Compile-time option to control stack size, e.g.
5301
   * -DUSE_STACK_SIZE=16384
5302
   */
5303
  return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
5304
           == ((uintptr_t)(-1L)))
5305
              ? -1
5306
              : 0);
5307
#else
5308
  return (
5309
      (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
5310
          ? -1
5311
          : 0);
5312
#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5313
}
5314
5315
5316
/* Start a thread storing the thread context. */
5317
static int
5318
mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
5319
                        void *p,
5320
                        pthread_t *threadidptr)
5321
{
5322
  uintptr_t uip;
5323
  HANDLE threadhandle;
5324
  int result = -1;
5325
5326
  uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
5327
  threadhandle = (HANDLE)uip;
5328
  if ((uip != 0) && (threadidptr != NULL)) {
5329
    *threadidptr = threadhandle;
5330
    result = 0;
5331
  }
5332
5333
  return result;
5334
}
5335
5336
5337
/* Wait for a thread to finish. */
5338
static int
5339
mg_join_thread(pthread_t threadid)
5340
{
5341
  int result;
5342
  DWORD dwevent;
5343
5344
  result = -1;
5345
  dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5346
  if (dwevent == WAIT_FAILED) {
5347
    DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
5348
  } else {
5349
    if (dwevent == WAIT_OBJECT_0) {
5350
      CloseHandle(threadid);
5351
      result = 0;
5352
    }
5353
  }
5354
5355
  return result;
5356
}
5357
5358
#if !defined(NO_SSL_DL) && !defined(NO_SSL)
5359
/* If SSL is loaded dynamically, dlopen/dlclose is required. */
5360
/* Create substitutes for POSIX functions in Win32. */
5361
5362
#if defined(GCC_DIAGNOSTIC)
5363
/* Show no warning in case system functions are not used. */
5364
#pragma GCC diagnostic push
5365
#pragma GCC diagnostic ignored "-Wunused-function"
5366
#endif
5367
5368
5369
FUNCTION_MAY_BE_UNUSED
5370
static HANDLE
5371
dlopen(const char *dll_name, int flags)
5372
{
5373
  wchar_t wbuf[UTF16_PATH_MAX];
5374
  (void)flags;
5375
  path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
5376
  return LoadLibraryW(wbuf);
5377
}
5378
5379
5380
FUNCTION_MAY_BE_UNUSED
5381
static int
5382
dlclose(void *handle)
5383
{
5384
  int result;
5385
5386
  if (FreeLibrary((HMODULE)handle) != 0) {
5387
    result = 0;
5388
  } else {
5389
    result = -1;
5390
  }
5391
5392
  return result;
5393
}
5394
5395
5396
#if defined(GCC_DIAGNOSTIC)
5397
/* Enable unused function warning again */
5398
#pragma GCC diagnostic pop
5399
#endif
5400
5401
#endif
5402
5403
5404
#if !defined(NO_CGI)
5405
#define SIGKILL (0)
5406
5407
5408
static int
5409
kill(pid_t pid, int sig_num)
5410
{
5411
  (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5412
  (void)CloseHandle((HANDLE)pid);
5413
  return 0;
5414
}
5415
5416
5417
#if !defined(WNOHANG)
5418
#define WNOHANG (1)
5419
#endif
5420
5421
5422
static pid_t
5423
waitpid(pid_t pid, int *status, int flags)
5424
{
5425
  DWORD timeout = INFINITE;
5426
  DWORD waitres;
5427
5428
  (void)status; /* Currently not used by any client here */
5429
5430
  if ((flags | WNOHANG) == WNOHANG) {
5431
    timeout = 0;
5432
  }
5433
5434
  waitres = WaitForSingleObject((HANDLE)pid, timeout);
5435
  if (waitres == WAIT_OBJECT_0) {
5436
    return pid;
5437
  }
5438
  if (waitres == WAIT_TIMEOUT) {
5439
    return 0;
5440
  }
5441
  return (pid_t)-1;
5442
}
5443
5444
5445
static void
5446
trim_trailing_whitespaces(char *s)
5447
{
5448
  char *e = s + strlen(s);
5449
  while ((e > s) && isspace((unsigned char)e[-1])) {
5450
    *(--e) = '\0';
5451
  }
5452
}
5453
5454
5455
static pid_t
5456
spawn_process(struct mg_connection *conn,
5457
              const char *prog,
5458
              char *envblk,
5459
              char *envp[],
5460
              int fdin[2],
5461
              int fdout[2],
5462
              int fderr[2],
5463
              const char *dir,
5464
              unsigned char cgi_config_idx)
5465
{
5466
  HANDLE me;
5467
  char *interp;
5468
  char *interp_arg = 0;
5469
  char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
5470
  int truncated;
5471
  struct mg_file file = STRUCT_FILE_INITIALIZER;
5472
  STARTUPINFOA si;
5473
  PROCESS_INFORMATION pi = {0};
5474
5475
  (void)envp;
5476
5477
  memset(&si, 0, sizeof(si));
5478
  si.cb = sizeof(si);
5479
5480
  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5481
  si.wShowWindow = SW_HIDE;
5482
5483
  me = GetCurrentProcess();
5484
  DuplicateHandle(me,
5485
                  (HANDLE)_get_osfhandle(fdin[0]),
5486
                  me,
5487
                  &si.hStdInput,
5488
                  0,
5489
                  TRUE,
5490
                  DUPLICATE_SAME_ACCESS);
5491
  DuplicateHandle(me,
5492
                  (HANDLE)_get_osfhandle(fdout[1]),
5493
                  me,
5494
                  &si.hStdOutput,
5495
                  0,
5496
                  TRUE,
5497
                  DUPLICATE_SAME_ACCESS);
5498
  DuplicateHandle(me,
5499
                  (HANDLE)_get_osfhandle(fderr[1]),
5500
                  me,
5501
                  &si.hStdError,
5502
                  0,
5503
                  TRUE,
5504
                  DUPLICATE_SAME_ACCESS);
5505
5506
  /* Mark handles that should not be inherited. See
5507
   * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
5508
   */
5509
  SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5510
                       HANDLE_FLAG_INHERIT,
5511
                       0);
5512
  SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5513
                       HANDLE_FLAG_INHERIT,
5514
                       0);
5515
  SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5516
                       HANDLE_FLAG_INHERIT,
5517
                       0);
5518
5519
  /* First check, if there is a CGI interpreter configured for all CGI
5520
   * scripts. */
5521
  interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
5522
  if (interp != NULL) {
5523
    /* If there is a configured interpreter, check for additional arguments
5524
     */
5525
    interp_arg =
5526
        conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
5527
  } else {
5528
    /* Otherwise, the interpreter must be stated in the first line of the
5529
     * CGI script file, after a #! (shebang) mark. */
5530
    buf[0] = buf[1] = '\0';
5531
5532
    /* Get the full script path */
5533
    mg_snprintf(
5534
        conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
5535
5536
    if (truncated) {
5537
      pi.hProcess = (pid_t)-1;
5538
      goto spawn_cleanup;
5539
    }
5540
5541
    /* Open the script file, to read the first line */
5542
    if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
5543
5544
      /* Read the first line of the script into the buffer */
5545
      mg_fgets(buf, sizeof(buf), &file);
5546
      (void)mg_fclose(&file.access); /* ignore error on read only file */
5547
      buf[sizeof(buf) - 1] = '\0';
5548
    }
5549
5550
    if ((buf[0] == '#') && (buf[1] == '!')) {
5551
      trim_trailing_whitespaces(buf + 2);
5552
    } else {
5553
      buf[2] = '\0';
5554
    }
5555
    interp = buf + 2;
5556
  }
5557
5558
  GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
5559
5560
  if (interp[0] != '\0') {
5561
    /* This is an interpreted script file. We must call the interpreter. */
5562
    if ((interp_arg != 0) && (interp_arg[0] != 0)) {
5563
      mg_snprintf(conn,
5564
                  &truncated,
5565
                  cmdline,
5566
                  sizeof(cmdline),
5567
                  "\"%s\" %s \"%s\\%s\"",
5568
                  interp,
5569
                  interp_arg,
5570
                  full_dir,
5571
                  prog);
5572
    } else {
5573
      mg_snprintf(conn,
5574
                  &truncated,
5575
                  cmdline,
5576
                  sizeof(cmdline),
5577
                  "\"%s\" \"%s\\%s\"",
5578
                  interp,
5579
                  full_dir,
5580
                  prog);
5581
    }
5582
  } else {
5583
    /* This is (probably) a compiled program. We call it directly. */
5584
    mg_snprintf(conn,
5585
                &truncated,
5586
                cmdline,
5587
                sizeof(cmdline),
5588
                "\"%s\\%s\"",
5589
                full_dir,
5590
                prog);
5591
  }
5592
5593
  if (truncated) {
5594
    pi.hProcess = (pid_t)-1;
5595
    goto spawn_cleanup;
5596
  }
5597
5598
  DEBUG_TRACE("Running [%s]", cmdline);
5599
  if (CreateProcessA(NULL,
5600
                     cmdline,
5601
                     NULL,
5602
                     NULL,
5603
                     TRUE,
5604
                     CREATE_NEW_PROCESS_GROUP,
5605
                     envblk,
5606
                     NULL,
5607
                     &si,
5608
                     &pi)
5609
      == 0) {
5610
    mg_cry_internal(
5611
        conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
5612
    pi.hProcess = (pid_t)-1;
5613
    /* goto spawn_cleanup; */
5614
  }
5615
5616
spawn_cleanup:
5617
  (void)CloseHandle(si.hStdOutput);
5618
  (void)CloseHandle(si.hStdError);
5619
  (void)CloseHandle(si.hStdInput);
5620
  if (pi.hThread != NULL) {
5621
    (void)CloseHandle(pi.hThread);
5622
  }
5623
5624
  return (pid_t)pi.hProcess;
5625
}
5626
#endif /* !NO_CGI */
5627
5628
5629
static int
5630
set_blocking_mode(SOCKET sock)
5631
{
5632
  unsigned long non_blocking = 0;
5633
  return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5634
}
5635
5636
5637
static int
5638
set_non_blocking_mode(SOCKET sock)
5639
{
5640
  unsigned long non_blocking = 1;
5641
  return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5642
}
5643
5644
5645
#else
5646
5647
5648
#if !defined(NO_FILESYSTEMS)
5649
static int
5650
mg_stat(const struct mg_connection *conn,
5651
        const char *path,
5652
        struct mg_file_stat *filep)
5653
0
{
5654
0
  struct stat st;
5655
0
  if (!filep) {
5656
0
    return 0;
5657
0
  }
5658
0
  memset(filep, 0, sizeof(*filep));
5659
5660
0
  if (mg_path_suspicious(conn, path)) {
5661
0
    return 0;
5662
0
  }
5663
5664
0
  if (0 == stat(path, &st)) {
5665
0
    filep->size = (uint64_t)(st.st_size);
5666
0
    filep->last_modified = st.st_mtime;
5667
0
    filep->is_directory = S_ISDIR(st.st_mode);
5668
0
    return 1;
5669
0
  }
5670
5671
0
  return 0;
5672
0
}
5673
#endif /* NO_FILESYSTEMS */
5674
5675
5676
static void
5677
set_close_on_exec(int fd,
5678
                  const struct mg_connection *conn /* may be null */,
5679
                  struct mg_context *ctx /* may be null */)
5680
36
{
5681
#if defined(__ZEPHYR__)
5682
  (void)fd;
5683
  (void)conn;
5684
  (void)ctx;
5685
#else
5686
36
  if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5687
0
    if (conn || ctx) {
5688
0
      struct mg_connection fc;
5689
0
      mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
5690
0
                      "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5691
0
                      __func__,
5692
0
                      strerror(ERRNO));
5693
0
    }
5694
0
  }
5695
36
#endif
5696
36
}
5697
5698
5699
CIVETWEB_API int
5700
mg_start_thread(mg_thread_func_t func, void *param)
5701
0
{
5702
0
  pthread_t thread_id;
5703
0
  pthread_attr_t attr;
5704
0
  int result;
5705
5706
0
  (void)pthread_attr_init(&attr);
5707
0
  (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
5708
5709
#if defined(__ZEPHYR__)
5710
  pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
5711
#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5712
  /* Compile-time option to control stack size,
5713
   * e.g. -DUSE_STACK_SIZE=16384 */
5714
0
  (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5715
0
#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5716
5717
0
  result = pthread_create(&thread_id, &attr, func, param);
5718
0
  pthread_attr_destroy(&attr);
5719
5720
0
  return result;
5721
0
}
5722
5723
5724
/* Start a thread storing the thread context. */
5725
static int
5726
mg_start_thread_with_id(mg_thread_func_t func,
5727
                        void *param,
5728
                        pthread_t *threadidptr)
5729
102
{
5730
102
  pthread_t thread_id;
5731
102
  pthread_attr_t attr;
5732
102
  int result;
5733
5734
102
  (void)pthread_attr_init(&attr);
5735
5736
#if defined(__ZEPHYR__)
5737
  pthread_attr_setstack(&attr,
5738
                        &civetweb_worker_stacks[zephyr_worker_stack_index++],
5739
                        ZEPHYR_STACK_SIZE);
5740
#elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5741
  /* Compile-time option to control stack size,
5742
   * e.g. -DUSE_STACK_SIZE=16384 */
5743
102
  (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5744
102
#endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
5745
5746
102
  result = pthread_create(&thread_id, &attr, func, param);
5747
102
  pthread_attr_destroy(&attr);
5748
102
  if ((result == 0) && (threadidptr != NULL)) {
5749
102
    *threadidptr = thread_id;
5750
102
  }
5751
102
  return result;
5752
102
}
5753
5754
5755
/* Wait for a thread to finish. */
5756
static int
5757
mg_join_thread(pthread_t threadid)
5758
102
{
5759
102
  int result;
5760
5761
102
  result = pthread_join(threadid, NULL);
5762
102
  return result;
5763
102
}
5764
5765
5766
#if !defined(NO_CGI)
5767
static pid_t
5768
spawn_process(struct mg_connection *conn,
5769
              const char *prog,
5770
              char *envblk,
5771
              char *envp[],
5772
              int fdin[2],
5773
              int fdout[2],
5774
              int fderr[2],
5775
              const char *dir,
5776
              unsigned char cgi_config_idx)
5777
0
{
5778
0
  pid_t pid;
5779
0
  const char *interp;
5780
5781
0
  (void)envblk;
5782
5783
0
  if ((pid = fork()) == -1) {
5784
    /* Parent */
5785
0
    mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
5786
0
  } else if (pid != 0) {
5787
    /* Make sure children close parent-side descriptors.
5788
     * The caller will close the child-side immediately. */
5789
0
    set_close_on_exec(fdin[1], conn, NULL);  /* stdin write */
5790
0
    set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
5791
0
    set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
5792
0
  } else {
5793
    /* Child */
5794
0
    if (chdir(dir) != 0) {
5795
0
      mg_cry_internal(
5796
0
          conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
5797
0
    } else if (dup2(fdin[0], 0) == -1) {
5798
0
      mg_cry_internal(conn,
5799
0
                      "%s: dup2(%d, 0): %s",
5800
0
                      __func__,
5801
0
                      fdin[0],
5802
0
                      strerror(ERRNO));
5803
0
    } else if (dup2(fdout[1], 1) == -1) {
5804
0
      mg_cry_internal(conn,
5805
0
                      "%s: dup2(%d, 1): %s",
5806
0
                      __func__,
5807
0
                      fdout[1],
5808
0
                      strerror(ERRNO));
5809
0
    } else if (dup2(fderr[1], 2) == -1) {
5810
0
      mg_cry_internal(conn,
5811
0
                      "%s: dup2(%d, 2): %s",
5812
0
                      __func__,
5813
0
                      fderr[1],
5814
0
                      strerror(ERRNO));
5815
0
    } else {
5816
0
      struct sigaction sa;
5817
5818
      /* Keep stderr and stdout in two different pipes.
5819
       * Stdout will be sent back to the client,
5820
       * stderr should go into a server error log. */
5821
0
      (void)close(fdin[0]);
5822
0
      (void)close(fdout[1]);
5823
0
      (void)close(fderr[1]);
5824
5825
      /* Close write end fdin and read end fdout and fderr */
5826
0
      (void)close(fdin[1]);
5827
0
      (void)close(fdout[0]);
5828
0
      (void)close(fderr[0]);
5829
5830
      /* After exec, all signal handlers are restored to their default
5831
       * values, with one exception of SIGCHLD. According to
5832
       * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
5833
       * will leave unchanged after exec if it was set to be ignored.
5834
       * Restore it to default action. */
5835
0
      memset(&sa, 0, sizeof(sa));
5836
0
      sa.sa_handler = SIG_DFL;
5837
0
      sigaction(SIGCHLD, &sa, NULL);
5838
5839
0
      interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
5840
0
      if (interp == NULL) {
5841
        /* no interpreter configured, call the program directly */
5842
0
        (void)execle(prog, prog, NULL, envp);
5843
0
        mg_cry_internal(conn,
5844
0
                        "%s: execle(%s): %s",
5845
0
                        __func__,
5846
0
                        prog,
5847
0
                        strerror(ERRNO));
5848
0
      } else {
5849
        /* call the configured interpreter */
5850
0
        const char *interp_args =
5851
0
            conn->dom_ctx
5852
0
                ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
5853
5854
0
        if ((interp_args != NULL) && (interp_args[0] != 0)) {
5855
0
          (void)execle(interp, interp, interp_args, prog, NULL, envp);
5856
0
        } else {
5857
0
          (void)execle(interp, interp, prog, NULL, envp);
5858
0
        }
5859
0
        mg_cry_internal(conn,
5860
0
                        "%s: execle(%s %s): %s",
5861
0
                        __func__,
5862
0
                        interp,
5863
0
                        prog,
5864
0
                        strerror(ERRNO));
5865
0
      }
5866
0
    }
5867
0
    exit(EXIT_FAILURE);
5868
0
  }
5869
5870
0
  return pid;
5871
0
}
5872
#endif /* !NO_CGI */
5873
5874
5875
static int
5876
set_non_blocking_mode(SOCKET sock)
5877
34
{
5878
34
  int flags = fcntl(sock, F_GETFL, 0);
5879
34
  if (flags < 0) {
5880
0
    return -1;
5881
0
  }
5882
5883
34
  if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
5884
0
    return -1;
5885
0
  }
5886
34
  return 0;
5887
34
}
5888
5889
static int
5890
set_blocking_mode(SOCKET sock)
5891
34
{
5892
34
  int flags = fcntl(sock, F_GETFL, 0);
5893
34
  if (flags < 0) {
5894
0
    return -1;
5895
0
  }
5896
5897
34
  if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
5898
0
    return -1;
5899
0
  }
5900
34
  return 0;
5901
34
}
5902
#endif /* _WIN32 / else */
5903
5904
/* End of initial operating system specific define block. */
5905
5906
5907
/* Get a random number (independent of C rand function) */
5908
static uint64_t
5909
get_random(void)
5910
2
{
5911
2
  static uint64_t lfsr = 0; /* Linear feedback shift register */
5912
2
  static uint64_t lcg = 0;  /* Linear congruential generator */
5913
2
  uint64_t now = mg_get_current_time_ns();
5914
5915
2
  if (lfsr == 0) {
5916
    /* lfsr will be only 0 if has not been initialized,
5917
     * so this code is called only once. */
5918
2
    lfsr = mg_get_current_time_ns();
5919
2
    lcg = mg_get_current_time_ns();
5920
2
  } else {
5921
    /* Get the next step of both random number generators. */
5922
0
    lfsr = (lfsr >> 1)
5923
0
           | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
5924
0
              << 63);
5925
0
    lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
5926
0
  }
5927
5928
  /* Combining two pseudo-random number generators and a high resolution
5929
   * part
5930
   * of the current server time will make it hard (impossible?) to guess
5931
   * the
5932
   * next number. */
5933
2
  return (lfsr ^ lcg ^ now);
5934
2
}
5935
5936
5937
static int
5938
mg_poll(struct mg_pollfd *pfd,
5939
        unsigned int n,
5940
        int milliseconds,
5941
        const stop_flag_t *stop_flag)
5942
84
{
5943
  /* Call poll, but only for a maximum time of a few seconds.
5944
   * This will allow to stop the server after some seconds, instead
5945
   * of having to wait for a long socket timeout. */
5946
84
  int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
5947
5948
84
  int check_pollerr = 0;
5949
84
  if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
5950
    /* If we wait for only one file descriptor, wait on error as well */
5951
84
    pfd[0].events |= POLLERR;
5952
84
    check_pollerr = 1;
5953
84
  }
5954
5955
84
  do {
5956
84
    int result;
5957
5958
84
    if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
5959
      /* Shut down signal */
5960
0
      return -2;
5961
0
    }
5962
5963
84
    if ((milliseconds >= 0) && (milliseconds < ms_now)) {
5964
44
      ms_now = milliseconds;
5965
44
    }
5966
5967
84
    result = poll(pfd, n, ms_now);
5968
84
    if (result != 0) {
5969
78
      int err = ERRNO;
5970
78
      if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
5971
        /* Poll returned either success (1) or error (-1).
5972
         * Forward both to the caller. */
5973
78
        if ((check_pollerr)
5974
78
            && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
5975
78
                == POLLERR)) {
5976
          /* One and only file descriptor returned error */
5977
0
          return -1;
5978
0
        }
5979
78
        return result;
5980
78
      }
5981
78
    }
5982
5983
    /* Poll returned timeout (0). */
5984
6
    if (milliseconds > 0) {
5985
6
      milliseconds -= ms_now;
5986
6
    }
5987
5988
6
  } while (milliseconds > 0);
5989
5990
  /* timeout: return 0 */
5991
6
  return 0;
5992
84
}
5993
5994
5995
/* Write data to the IO channel - opened file descriptor, socket or SSL
5996
 * descriptor.
5997
 * Return value:
5998
 *  >=0 .. number of bytes successfully written
5999
 *   -1 .. timeout
6000
 *   -2 .. error
6001
 */
6002
static int
6003
push_inner(struct mg_context *ctx,
6004
           FILE *fp,
6005
           SOCKET sock,
6006
           SSL *ssl,
6007
           const char *buf,
6008
           int len,
6009
           double timeout)
6010
34
{
6011
34
  uint64_t start = 0, now = 0, timeout_ns = 0;
6012
34
  int n, err;
6013
34
  unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
6014
6015
#if defined(_WIN32)
6016
  typedef int len_t;
6017
#else
6018
34
  typedef size_t len_t;
6019
34
#endif
6020
6021
34
  if (timeout > 0) {
6022
34
    now = mg_get_current_time_ns();
6023
34
    start = now;
6024
34
    timeout_ns = (uint64_t)(timeout * 1.0E9);
6025
34
  }
6026
6027
34
  if (ctx == NULL) {
6028
0
    return -2;
6029
0
  }
6030
6031
#if defined(NO_SSL) && !defined(USE_MBEDTLS)
6032
  if (ssl) {
6033
    return -2;
6034
  }
6035
#endif
6036
6037
  /* Try to read until it succeeds, fails, times out, or the server
6038
   * shuts down. */
6039
34
  for (;;) {
6040
6041
#if defined(USE_MBEDTLS)
6042
    if (ssl != NULL) {
6043
      n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
6044
      if (n <= 0) {
6045
        if ((n == MBEDTLS_ERR_SSL_WANT_READ)
6046
            || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
6047
            || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6048
          n = 0;
6049
        } else {
6050
          fprintf(stderr, "SSL write failed, error %d\n", n);
6051
          return -2;
6052
        }
6053
      } else {
6054
        err = 0;
6055
      }
6056
    } else
6057
#elif !defined(NO_SSL)
6058
34
    if (ssl != NULL) {
6059
0
      ERR_clear_error();
6060
0
      n = SSL_write(ssl, buf, len);
6061
0
      if (n <= 0) {
6062
0
        err = SSL_get_error(ssl, n);
6063
0
        if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
6064
0
          err = ERRNO;
6065
0
        } else if ((err == SSL_ERROR_WANT_READ)
6066
0
                   || (err == SSL_ERROR_WANT_WRITE)) {
6067
0
          n = 0;
6068
0
        } else {
6069
0
          DEBUG_TRACE("SSL_write() failed, error %d", err);
6070
0
          ERR_clear_error();
6071
0
          return -2;
6072
0
        }
6073
0
        ERR_clear_error();
6074
0
      } else {
6075
0
        err = 0;
6076
0
      }
6077
0
    } else
6078
34
#endif
6079
6080
34
        if (fp != NULL) {
6081
0
      n = (int)fwrite(buf, 1, (size_t)len, fp);
6082
0
      if (ferror(fp)) {
6083
0
        n = -1;
6084
0
        err = ERRNO;
6085
0
      } else {
6086
0
        err = 0;
6087
0
      }
6088
34
    } else {
6089
34
      n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
6090
34
      err = (n < 0) ? ERRNO : 0;
6091
34
      if (ERROR_TRY_AGAIN(err)) {
6092
0
        err = 0;
6093
0
        n = 0;
6094
0
      }
6095
34
      if (n < 0) {
6096
        /* shutdown of the socket at client side */
6097
0
        return -2;
6098
0
      }
6099
34
    }
6100
6101
34
    if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6102
0
      return -2;
6103
0
    }
6104
6105
34
    if ((n > 0) || ((n == 0) && (len == 0))) {
6106
      /* some data has been read, or no data was requested */
6107
34
      return n;
6108
34
    }
6109
0
    if (n < 0) {
6110
      /* socket error - check errno */
6111
0
      DEBUG_TRACE("send() failed, error %d", err);
6112
6113
      /* TODO (mid): error handling depending on the error code.
6114
       * These codes are different between Windows and Linux.
6115
       * Currently there is no problem with failing send calls,
6116
       * if there is a reproducible situation, it should be
6117
       * investigated in detail.
6118
       */
6119
0
      return -2;
6120
0
    }
6121
6122
    /* Only in case n=0 (timeout), repeat calling the write function */
6123
6124
    /* If send failed, wait before retry */
6125
0
    if (fp != NULL) {
6126
      /* For files, just wait a fixed time.
6127
       * Maybe it helps, maybe not. */
6128
0
      mg_sleep(5);
6129
0
    } else {
6130
      /* For sockets, wait for the socket using poll */
6131
0
      struct mg_pollfd pfd[1];
6132
0
      int pollres;
6133
6134
0
      pfd[0].fd = sock;
6135
0
      pfd[0].events = POLLOUT;
6136
0
      pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
6137
0
      if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6138
0
        return -2;
6139
0
      }
6140
0
      if (pollres > 0) {
6141
0
        continue;
6142
0
      }
6143
0
    }
6144
6145
0
    if (timeout > 0) {
6146
0
      now = mg_get_current_time_ns();
6147
0
      if ((now - start) > timeout_ns) {
6148
        /* Timeout */
6149
0
        break;
6150
0
      }
6151
0
    }
6152
0
  }
6153
6154
0
  (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
6155
             used */
6156
6157
0
  return -1;
6158
34
}
6159
6160
6161
static int
6162
push_all(struct mg_context *ctx,
6163
         FILE *fp,
6164
         SOCKET sock,
6165
         SSL *ssl,
6166
         const char *buf,
6167
         int len)
6168
34
{
6169
34
  double timeout = -1.0;
6170
34
  int n, nwritten = 0;
6171
6172
34
  if (ctx == NULL) {
6173
0
    return -1;
6174
0
  }
6175
6176
34
  if (ctx->dd.config[REQUEST_TIMEOUT]) {
6177
0
    timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
6178
0
  }
6179
34
  if (timeout <= 0.0) {
6180
34
    timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
6181
34
              / 1000.0;
6182
34
  }
6183
6184
68
  while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
6185
34
    n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
6186
34
    if (n < 0) {
6187
0
      if (nwritten == 0) {
6188
0
        nwritten = -1; /* Propagate the error */
6189
0
      }
6190
0
      break;
6191
34
    } else if (n == 0) {
6192
0
      break; /* No more data to write */
6193
34
    } else {
6194
34
      nwritten += n;
6195
34
      len -= n;
6196
34
    }
6197
34
  }
6198
6199
34
  return nwritten;
6200
34
}
6201
6202
6203
/* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
6204
 * Return value:
6205
 *  >=0 .. number of bytes successfully read
6206
 *   -1 .. timeout
6207
 *   -2 .. error
6208
 */
6209
static int
6210
pull_inner(FILE *fp,
6211
           struct mg_connection *conn,
6212
           char *buf,
6213
           int len,
6214
           double timeout)
6215
44
{
6216
44
  int nread, err = 0;
6217
6218
#if defined(_WIN32)
6219
  typedef int len_t;
6220
#else
6221
44
  typedef size_t len_t;
6222
44
#endif
6223
6224
  /* We need an additional wait loop around this, because in some cases
6225
   * with TLSwe may get data from the socket but not from SSL_read.
6226
   * In this case we need to repeat at least once.
6227
   */
6228
6229
44
  if (fp != NULL) {
6230
    /* Use read() instead of fread(), because if we're reading from the
6231
     * CGI pipe, fread() may block until IO buffer is filled up. We
6232
     * cannot afford to block and must pass all read bytes immediately
6233
     * to the client. */
6234
0
    nread = (int)read(fileno(fp), buf, (size_t)len);
6235
6236
0
    err = (nread < 0) ? ERRNO : 0;
6237
0
    if ((nread == 0) && (len > 0)) {
6238
      /* Should get data, but got EOL */
6239
0
      return -2;
6240
0
    }
6241
6242
#if defined(USE_MBEDTLS)
6243
  } else if (conn->ssl != NULL) {
6244
    struct mg_pollfd pfd[1];
6245
    int to_read;
6246
    int pollres;
6247
6248
    to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
6249
6250
    if (to_read > 0) {
6251
      /* We already know there is no more data buffered in conn->buf
6252
       * but there is more available in the SSL layer. So don't poll
6253
       * conn->client.sock yet. */
6254
6255
      pollres = 1;
6256
      if (to_read > len)
6257
        to_read = len;
6258
    } else {
6259
      pfd[0].fd = conn->client.sock;
6260
      pfd[0].events = POLLIN;
6261
6262
      to_read = len;
6263
6264
      pollres = mg_poll(pfd,
6265
                        1,
6266
                        (int)(timeout * 1000.0),
6267
                        &(conn->phys_ctx->stop_flag));
6268
6269
      if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6270
        return -2;
6271
      }
6272
    }
6273
6274
    if (pollres > 0) {
6275
      nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
6276
      if (nread <= 0) {
6277
        if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
6278
            || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
6279
            || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
6280
          nread = 0;
6281
        } else {
6282
          fprintf(stderr, "SSL read failed, error %d\n", nread);
6283
          return -2;
6284
        }
6285
      } else {
6286
        err = 0;
6287
      }
6288
6289
    } else if (pollres < 0) {
6290
      /* Error */
6291
      return -2;
6292
    } else {
6293
      /* pollres = 0 means timeout */
6294
      nread = 0;
6295
    }
6296
6297
#elif !defined(NO_SSL)
6298
44
  } else if (conn->ssl != NULL) {
6299
0
    int ssl_pending;
6300
0
    struct mg_pollfd pfd[1];
6301
0
    int pollres;
6302
6303
0
    if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
6304
      /* We already know there is no more data buffered in conn->buf
6305
       * but there is more available in the SSL layer. So don't poll
6306
       * conn->client.sock yet. */
6307
0
      if (ssl_pending > len) {
6308
0
        ssl_pending = len;
6309
0
      }
6310
0
      pollres = 1;
6311
0
    } else {
6312
0
      pfd[0].fd = conn->client.sock;
6313
0
      pfd[0].events = POLLIN;
6314
0
      pollres = mg_poll(pfd,
6315
0
                        1,
6316
0
                        (int)(timeout * 1000.0),
6317
0
                        &(conn->phys_ctx->stop_flag));
6318
0
      if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6319
0
        return -2;
6320
0
      }
6321
0
    }
6322
0
    if (pollres > 0) {
6323
0
      ERR_clear_error();
6324
0
      nread =
6325
0
          SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
6326
0
      if (nread <= 0) {
6327
0
        err = SSL_get_error(conn->ssl, nread);
6328
0
        if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
6329
0
          err = ERRNO;
6330
0
        } else if ((err == SSL_ERROR_WANT_READ)
6331
0
                   || (err == SSL_ERROR_WANT_WRITE)) {
6332
0
          nread = 0;
6333
0
        } else {
6334
          /* All errors should return -2 */
6335
0
          DEBUG_TRACE("SSL_read() failed, error %d", err);
6336
0
          ERR_clear_error();
6337
0
          return -2;
6338
0
        }
6339
0
        ERR_clear_error();
6340
0
      } else {
6341
0
        err = 0;
6342
0
      }
6343
0
    } else if (pollres < 0) {
6344
      /* Error */
6345
0
      return -2;
6346
0
    } else {
6347
      /* pollres = 0 means timeout */
6348
0
      nread = 0;
6349
0
    }
6350
0
#endif
6351
6352
44
  } else {
6353
44
    struct mg_pollfd pfd[1];
6354
44
    int pollres;
6355
6356
44
    pfd[0].fd = conn->client.sock;
6357
44
    pfd[0].events = POLLIN;
6358
44
    pollres = mg_poll(pfd,
6359
44
                      1,
6360
44
                      (int)(timeout * 1000.0),
6361
44
                      &(conn->phys_ctx->stop_flag));
6362
44
    if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6363
0
      return -2;
6364
0
    }
6365
44
    if (pollres > 0) {
6366
44
      nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
6367
44
      err = (nread < 0) ? ERRNO : 0;
6368
44
      if (nread <= 0) {
6369
        /* shutdown of the socket at client side */
6370
10
        return -2;
6371
10
      }
6372
44
    } else if (pollres < 0) {
6373
      /* error calling poll */
6374
0
      return -2;
6375
0
    } else {
6376
      /* pollres = 0 means timeout */
6377
0
      nread = 0;
6378
0
    }
6379
44
  }
6380
6381
34
  if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6382
0
    return -2;
6383
0
  }
6384
6385
34
  if ((nread > 0) || ((nread == 0) && (len == 0))) {
6386
    /* some data has been read, or no data was requested */
6387
34
    return nread;
6388
34
  }
6389
6390
0
  if (nread < 0) {
6391
    /* socket error - check errno */
6392
#if defined(_WIN32)
6393
    if (err == WSAEWOULDBLOCK) {
6394
      /* TODO (low): check if this is still required */
6395
      /* standard case if called from close_socket_gracefully */
6396
      return -2;
6397
    } else if (err == WSAETIMEDOUT) {
6398
      /* TODO (low): check if this is still required */
6399
      /* timeout is handled by the while loop  */
6400
      return 0;
6401
    } else if (err == WSAECONNABORTED) {
6402
      /* See https://www.chilkatsoft.com/p/p_299.asp */
6403
      return -2;
6404
    } else {
6405
      DEBUG_TRACE("recv() failed, error %d", err);
6406
      return -2;
6407
    }
6408
#else
6409
    /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
6410
     * if the timeout is reached and if the socket was set to non-
6411
     * blocking in close_socket_gracefully, so we can not distinguish
6412
     * here. We have to wait for the timeout in both cases for now.
6413
     */
6414
0
    if (ERROR_TRY_AGAIN(err)) {
6415
      /* TODO (low): check if this is still required */
6416
      /* EAGAIN/EWOULDBLOCK:
6417
       * standard case if called from close_socket_gracefully
6418
       * => should return -1 */
6419
      /* or timeout occurred
6420
       * => the code must stay in the while loop */
6421
6422
      /* EINTR can be generated on a socket with a timeout set even
6423
       * when SA_RESTART is effective for all relevant signals
6424
       * (see signal(7)).
6425
       * => stay in the while loop */
6426
0
    } else {
6427
0
      DEBUG_TRACE("recv() failed, error %d", err);
6428
0
      return -2;
6429
0
    }
6430
0
#endif
6431
0
  }
6432
6433
  /* Timeout occurred, but no data available. */
6434
0
  return -1;
6435
0
}
6436
6437
6438
static int
6439
pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
6440
0
{
6441
0
  int n, nread = 0;
6442
0
  double timeout = -1.0;
6443
0
  uint64_t start_time = 0, now = 0, timeout_ns = 0;
6444
6445
0
  if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
6446
0
    timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
6447
0
  }
6448
0
  if (timeout <= 0.0) {
6449
0
    timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
6450
0
              / 1000.0;
6451
0
  }
6452
0
  start_time = mg_get_current_time_ns();
6453
0
  timeout_ns = (uint64_t)(timeout * 1.0E9);
6454
6455
0
  while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6456
0
    n = pull_inner(fp, conn, buf + nread, len, timeout);
6457
0
    if (n == -2) {
6458
0
      if (nread == 0) {
6459
0
        nread = -1; /* Propagate the error */
6460
0
      }
6461
0
      break;
6462
0
    } else if (n == -1) {
6463
      /* timeout */
6464
0
      if (timeout >= 0.0) {
6465
0
        now = mg_get_current_time_ns();
6466
0
        if ((now - start_time) <= timeout_ns) {
6467
0
          continue;
6468
0
        }
6469
0
      }
6470
0
      break;
6471
0
    } else if (n == 0) {
6472
0
      break; /* No more data to read */
6473
0
    } else {
6474
0
      nread += n;
6475
0
      len -= n;
6476
0
    }
6477
0
  }
6478
6479
0
  return nread;
6480
0
}
6481
6482
6483
static void
6484
discard_unread_request_data(struct mg_connection *conn)
6485
0
{
6486
0
  char buf[MG_BUF_LEN];
6487
6488
0
  while (mg_read(conn, buf, sizeof(buf)) > 0)
6489
0
    ;
6490
0
}
6491
6492
6493
static int
6494
mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
6495
0
{
6496
0
  int64_t content_len, n, buffered_len, nread;
6497
0
  int64_t len64 =
6498
0
      (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
6499
                                                   * int, we may not read more
6500
                                                   * bytes */
6501
0
  const char *body;
6502
6503
0
  if (conn == NULL) {
6504
0
    return 0;
6505
0
  }
6506
6507
  /* If Content-Length is not set for a response with body data,
6508
   * we do not know in advance how much data should be read. */
6509
0
  content_len = conn->content_len;
6510
0
  if (content_len < 0) {
6511
    /* The body data is completed when the connection is closed. */
6512
0
    content_len = INT64_MAX;
6513
0
  }
6514
6515
0
  nread = 0;
6516
0
  if (conn->consumed_content < content_len) {
6517
    /* Adjust number of bytes to read. */
6518
0
    int64_t left_to_read = content_len - conn->consumed_content;
6519
0
    if (left_to_read < len64) {
6520
      /* Do not read more than the total content length of the
6521
       * request.
6522
       */
6523
0
      len64 = left_to_read;
6524
0
    }
6525
6526
    /* Return buffered data */
6527
0
    buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
6528
0
                   - conn->consumed_content;
6529
0
    if (buffered_len > 0) {
6530
0
      if (len64 < buffered_len) {
6531
0
        buffered_len = len64;
6532
0
      }
6533
0
      body = conn->buf + conn->request_len + conn->consumed_content;
6534
0
      memcpy(buf, body, (size_t)buffered_len);
6535
0
      len64 -= buffered_len;
6536
0
      conn->consumed_content += buffered_len;
6537
0
      nread += buffered_len;
6538
0
      buf = (char *)buf + buffered_len;
6539
0
    }
6540
6541
    /* We have returned all buffered data. Read new data from the remote
6542
     * socket.
6543
     */
6544
0
    if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
6545
0
      conn->consumed_content += n;
6546
0
      nread += n;
6547
0
    } else {
6548
0
      nread = ((nread > 0) ? nread : n);
6549
0
    }
6550
0
  }
6551
0
  return (int)nread;
6552
0
}
6553
6554
6555
/* Forward declarations */
6556
static void handle_request(struct mg_connection *);
6557
static void log_access(const struct mg_connection *);
6558
6559
6560
/* Handle request, update statistics and call access log */
6561
static void
6562
handle_request_stat_log(struct mg_connection *conn)
6563
0
{
6564
#if defined(USE_SERVER_STATS)
6565
  struct timespec tnow;
6566
  conn->conn_state = 4; /* processing */
6567
#endif
6568
6569
0
  handle_request(conn);
6570
6571
6572
#if defined(USE_SERVER_STATS)
6573
  conn->conn_state = 5; /* processed */
6574
6575
  clock_gettime(CLOCK_MONOTONIC, &tnow);
6576
  conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
6577
6578
  mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
6579
  mg_atomic_add64(&(conn->phys_ctx->total_data_written),
6580
                  conn->num_bytes_sent);
6581
#endif
6582
6583
0
  DEBUG_TRACE("%s", "handle_request done");
6584
6585
0
  if (conn->phys_ctx->callbacks.end_request != NULL) {
6586
0
    conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
6587
0
    DEBUG_TRACE("%s", "end_request callback done");
6588
0
  }
6589
0
  log_access(conn);
6590
0
}
6591
6592
6593
#if defined(USE_HTTP2)
6594
#if defined(NO_SSL)
6595
#error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
6596
#endif
6597
#define USE_ALPN
6598
#include "http2.inl"
6599
/* Not supported with HTTP/2 */
6600
#define HTTP1_only                                                             \
6601
  {                                                                          \
6602
    if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {                      \
6603
      http2_must_use_http1(conn);                                        \
6604
      DEBUG_TRACE("%s", "must use HTTP/1.x");                            \
6605
      return;                                                            \
6606
    }                                                                      \
6607
  }
6608
#else
6609
#define HTTP1_only
6610
#endif
6611
6612
6613
CIVETWEB_API int
6614
mg_read(struct mg_connection *conn, void *buf, size_t len)
6615
0
{
6616
0
  if (len > INT_MAX) {
6617
0
    len = INT_MAX;
6618
0
  }
6619
6620
0
  if (conn == NULL) {
6621
0
    return 0;
6622
0
  }
6623
6624
0
  if (conn->is_chunked) {
6625
0
    size_t all_read = 0;
6626
6627
0
    while (len > 0) {
6628
0
      if (conn->is_chunked >= 3) {
6629
        /* No more data left to read */
6630
0
        return 0;
6631
0
      }
6632
0
      if (conn->is_chunked != 1) {
6633
        /* Has error */
6634
0
        return -1;
6635
0
      }
6636
6637
0
      if (conn->consumed_content != conn->content_len) {
6638
        /* copy from the current chunk */
6639
0
        int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
6640
6641
0
        if (read_ret < 1) {
6642
          /* read error */
6643
0
          conn->is_chunked = 2;
6644
0
          return -1;
6645
0
        }
6646
6647
0
        all_read += (size_t)read_ret;
6648
0
        len -= (size_t)read_ret;
6649
6650
0
        if (conn->consumed_content == conn->content_len) {
6651
          /* Add data bytes in the current chunk have been read,
6652
           * so we are expecting \r\n now. */
6653
0
          char x[2];
6654
0
          conn->content_len += 2;
6655
0
          if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
6656
0
              || (x[1] != '\n')) {
6657
            /* Protocol violation */
6658
0
            conn->is_chunked = 2;
6659
0
            return -1;
6660
0
          }
6661
0
        }
6662
6663
0
      } else {
6664
        /* fetch a new chunk */
6665
0
        size_t i;
6666
0
        char lenbuf[64];
6667
0
        char *end = NULL;
6668
0
        unsigned long chunkSize = 0;
6669
6670
0
        for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
6671
0
          conn->content_len++;
6672
0
          if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
6673
0
            lenbuf[i] = 0;
6674
0
          }
6675
0
          if ((i > 0) && (lenbuf[i] == ';'))
6676
0
          {
6677
            // chunk extension --> skip chars until next CR
6678
            //
6679
            // RFC 2616, 3.6.1 Chunked Transfer Coding
6680
              // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
6681
            //
6682
            // chunk          = chunk-size [ chunk-extension ] CRLF
6683
            //                  chunk-data CRLF
6684
            // ...
6685
            // chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
6686
0
            do
6687
0
              ++conn->content_len;
6688
0
            while (mg_read_inner(conn, lenbuf + i, 1) == 1 &&
6689
0
                 lenbuf[i] != '\r');
6690
0
          }
6691
0
          if ((i > 0) && (lenbuf[i] == '\r')
6692
0
              && (lenbuf[i - 1] != '\r')) {
6693
0
            continue;
6694
0
          }
6695
0
          if ((i > 1) && (lenbuf[i] == '\n')
6696
0
              && (lenbuf[i - 1] == '\r')) {
6697
0
            lenbuf[i + 1] = 0;
6698
0
            chunkSize = strtoul(lenbuf, &end, 16);
6699
0
            if (chunkSize == 0) {
6700
              /* regular end of content */
6701
0
              conn->is_chunked = 3;
6702
0
            }
6703
0
            break;
6704
0
          }
6705
0
          if (!isxdigit((unsigned char)lenbuf[i])) {
6706
            /* illegal character for chunk length */
6707
0
            conn->is_chunked = 2;
6708
0
            return -1;
6709
0
          }
6710
0
        }
6711
0
        if ((end == NULL) || (*end != '\r')) {
6712
          /* chunksize not set correctly */
6713
0
          conn->is_chunked = 2;
6714
0
          return -1;
6715
0
        }
6716
0
        if (conn->is_chunked == 3) {
6717
          /* try discarding trailer for keep-alive */
6718
6719
          // We found the last chunk (length 0) including the
6720
          // CRLF that terminates that chunk. Now follows a possibly
6721
          // empty trailer and a final CRLF.
6722
          //
6723
          // see RFC 2616, 3.6.1 Chunked Transfer Coding
6724
          // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
6725
          //
6726
          // Chunked-Body   = *chunk
6727
          //                  last-chunk
6728
          //                  trailer
6729
          //                  CRLF
6730
          // ...
6731
          // last-chunk     = 1*("0") [ chunk-extension ] CRLF
6732
          // ...
6733
          // trailer        = *(entity-header CRLF)
6734
6735
0
          int crlf_count = 2;  // one CRLF already determined
6736
6737
0
          while (crlf_count < 4 && conn->is_chunked == 3) {
6738
0
            ++conn->content_len;
6739
0
            if (mg_read_inner(conn, lenbuf, 1) == 1) {
6740
0
              if ((crlf_count == 0 || crlf_count == 2)) {
6741
0
                if (lenbuf[0] == '\r')
6742
0
                  ++crlf_count;
6743
0
                else
6744
0
                  crlf_count = 0;
6745
0
              }
6746
0
              else {
6747
                // previous character was a CR
6748
                // --> next character must be LF
6749
6750
0
                if (lenbuf[0] == '\n')
6751
0
                  ++crlf_count;
6752
0
                else
6753
0
                  conn->is_chunked = 2;
6754
0
              }
6755
0
            }
6756
0
            else
6757
              // premature end of trailer
6758
0
              conn->is_chunked = 2;
6759
0
          }
6760
6761
0
          if (conn->is_chunked == 2)
6762
0
            return -1;
6763
0
          else
6764
0
            conn->is_chunked = 4;
6765
6766
0
          break;
6767
0
        }
6768
6769
        /* append a new chunk */
6770
0
        conn->content_len += (int64_t)chunkSize;
6771
0
      }
6772
0
    }
6773
6774
0
    return (int)all_read;
6775
0
  }
6776
0
  return mg_read_inner(conn, buf, len);
6777
0
}
6778
6779
6780
CIVETWEB_API int
6781
mg_write(struct mg_connection *conn, const void *buf, size_t len)
6782
34
{
6783
34
  time_t now;
6784
34
  int n, total, allowed;
6785
6786
34
  if (conn == NULL) {
6787
0
    return 0;
6788
0
  }
6789
34
  if (len > INT_MAX) {
6790
0
    return -1;
6791
0
  }
6792
6793
  /* Mark connection as "data sent" */
6794
34
  conn->request_state = 10;
6795
#if defined(USE_HTTP2)
6796
  if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
6797
    http2_data_frame_head(conn, len, 0);
6798
  }
6799
#endif
6800
6801
34
  if (conn->throttle > 0) {
6802
0
    if ((now = time(NULL)) != conn->last_throttle_time) {
6803
0
      conn->last_throttle_time = now;
6804
0
      conn->last_throttle_bytes = 0;
6805
0
    }
6806
0
    allowed = conn->throttle - conn->last_throttle_bytes;
6807
0
    if (allowed > (int)len) {
6808
0
      allowed = (int)len;
6809
0
    }
6810
6811
0
    total = push_all(conn->phys_ctx,
6812
0
                     NULL,
6813
0
                     conn->client.sock,
6814
0
                     conn->ssl,
6815
0
                     (const char *)buf,
6816
0
                     allowed);
6817
6818
0
    if (total == allowed) {
6819
6820
0
      buf = (const char *)buf + total;
6821
0
      conn->last_throttle_bytes += total;
6822
0
      while ((total < (int)len)
6823
0
             && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
6824
0
        allowed = (conn->throttle > ((int)len - total))
6825
0
                      ? (int)len - total
6826
0
                      : conn->throttle;
6827
6828
0
        n = push_all(conn->phys_ctx,
6829
0
                     NULL,
6830
0
                     conn->client.sock,
6831
0
                     conn->ssl,
6832
0
                     (const char *)buf,
6833
0
                     allowed);
6834
6835
0
        if (n != allowed) {
6836
0
          break;
6837
0
        }
6838
0
        sleep(1);
6839
0
        conn->last_throttle_bytes = allowed;
6840
0
        conn->last_throttle_time = time(NULL);
6841
0
        buf = (const char *)buf + n;
6842
0
        total += n;
6843
0
      }
6844
0
    }
6845
34
  } else {
6846
34
    total = push_all(conn->phys_ctx,
6847
34
                     NULL,
6848
34
                     conn->client.sock,
6849
34
                     conn->ssl,
6850
34
                     (const char *)buf,
6851
34
                     (int)len);
6852
34
  }
6853
34
  if (total > 0) {
6854
34
    conn->num_bytes_sent += total;
6855
34
  }
6856
34
  return total;
6857
34
}
6858
6859
6860
/* Send a chunk, if "Transfer-Encoding: chunked" is used */
6861
CIVETWEB_API int
6862
mg_send_chunk(struct mg_connection *conn,
6863
              const char *chunk,
6864
              unsigned int chunk_len)
6865
0
{
6866
0
  char lenbuf[16];
6867
0
  size_t lenbuf_len;
6868
0
  int ret;
6869
0
  int t;
6870
6871
  /* First store the length information in a text buffer. */
6872
0
  sprintf(lenbuf, "%x\r\n", chunk_len);
6873
0
  lenbuf_len = strlen(lenbuf);
6874
6875
  /* Then send length information, chunk and terminating \r\n. */
6876
0
  ret = mg_write(conn, lenbuf, lenbuf_len);
6877
0
  if (ret != (int)lenbuf_len) {
6878
0
    return -1;
6879
0
  }
6880
0
  t = ret;
6881
6882
0
  ret = mg_write(conn, chunk, chunk_len);
6883
0
  if (ret != (int)chunk_len) {
6884
0
    return -1;
6885
0
  }
6886
0
  t += ret;
6887
6888
0
  ret = mg_write(conn, "\r\n", 2);
6889
0
  if (ret != 2) {
6890
0
    return -1;
6891
0
  }
6892
0
  t += ret;
6893
6894
0
  return t;
6895
0
}
6896
6897
6898
#if defined(GCC_DIAGNOSTIC)
6899
/* This block forwards format strings to printf implementations,
6900
 * so we need to disable the format-nonliteral warning. */
6901
#pragma GCC diagnostic push
6902
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
6903
#endif
6904
6905
6906
/* Alternative alloc_vprintf() for non-compliant C runtimes */
6907
static int
6908
alloc_vprintf2(char **buf, const char *fmt, va_list ap)
6909
0
{
6910
0
  va_list ap_copy;
6911
0
  size_t size = MG_BUF_LEN / 4;
6912
0
  int len = -1;
6913
6914
0
  *buf = NULL;
6915
0
  while (len < 0) {
6916
0
    if (*buf) {
6917
0
      mg_free(*buf);
6918
0
    }
6919
6920
0
    size *= 4;
6921
0
    *buf = (char *)mg_malloc(size);
6922
0
    if (!*buf) {
6923
0
      break;
6924
0
    }
6925
6926
0
    va_copy(ap_copy, ap);
6927
0
    len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
6928
0
    va_end(ap_copy);
6929
0
    (*buf)[size - 1] = 0;
6930
0
  }
6931
6932
0
  return len;
6933
0
}
6934
6935
6936
/* Print message to buffer. If buffer is large enough to hold the message,
6937
 * return buffer. If buffer is to small, allocate large enough buffer on
6938
 * heap,
6939
 * and return allocated buffer. */
6940
static int
6941
alloc_vprintf(char **out_buf,
6942
              char *prealloc_buf,
6943
              size_t prealloc_size,
6944
              const char *fmt,
6945
              va_list ap)
6946
34
{
6947
34
  va_list ap_copy;
6948
34
  int len;
6949
6950
  /* Windows is not standard-compliant, and vsnprintf() returns -1 if
6951
   * buffer is too small. Also, older versions of msvcrt.dll do not have
6952
   * _vscprintf().  However, if size is 0, vsnprintf() behaves correctly.
6953
   * Therefore, we make two passes: on first pass, get required message
6954
   * length.
6955
   * On second pass, actually print the message. */
6956
34
  va_copy(ap_copy, ap);
6957
34
  len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
6958
34
  va_end(ap_copy);
6959
6960
34
  if (len < 0) {
6961
    /* C runtime is not standard compliant, vsnprintf() returned -1.
6962
     * Switch to alternative code path that uses incremental
6963
     * allocations.
6964
     */
6965
0
    va_copy(ap_copy, ap);
6966
0
    len = alloc_vprintf2(out_buf, fmt, ap_copy);
6967
0
    va_end(ap_copy);
6968
6969
34
  } else if ((size_t)(len) >= prealloc_size) {
6970
    /* The pre-allocated buffer not large enough. */
6971
    /* Allocate a new buffer. */
6972
0
    *out_buf = (char *)mg_malloc((size_t)(len) + 1);
6973
0
    if (!*out_buf) {
6974
      /* Allocation failed. Return -1 as "out of memory" error. */
6975
0
      return -1;
6976
0
    }
6977
    /* Buffer allocation successful. Store the string there. */
6978
0
    va_copy(ap_copy, ap);
6979
0
    IGNORE_UNUSED_RESULT(
6980
0
        vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
6981
0
    va_end(ap_copy);
6982
6983
34
  } else {
6984
    /* The pre-allocated buffer is large enough.
6985
     * Use it to store the string and return the address. */
6986
34
    va_copy(ap_copy, ap);
6987
34
    IGNORE_UNUSED_RESULT(
6988
34
        vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
6989
34
    va_end(ap_copy);
6990
34
    *out_buf = prealloc_buf;
6991
34
  }
6992
6993
34
  return len;
6994
34
}
6995
6996
6997
static int
6998
alloc_printf(char **out_buf, const char *fmt, ...)
6999
0
{
7000
0
  va_list ap;
7001
0
  int result;
7002
0
7003
0
  va_start(ap, fmt);
7004
0
  result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
7005
0
  va_end(ap);
7006
0
7007
0
  return result;
7008
0
}
7009
7010
7011
#if defined(GCC_DIAGNOSTIC)
7012
/* Enable format-nonliteral warning again. */
7013
#pragma GCC diagnostic pop
7014
#endif
7015
7016
7017
static int
7018
mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
7019
34
{
7020
34
  char mem[MG_BUF_LEN];
7021
34
  char *buf = NULL;
7022
34
  int len;
7023
7024
34
  if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
7025
34
    len = mg_write(conn, buf, (size_t)len);
7026
34
  }
7027
34
  if (buf != mem) {
7028
0
    mg_free(buf);
7029
0
  }
7030
7031
34
  return len;
7032
34
}
7033
7034
7035
CIVETWEB_API int
7036
mg_printf(struct mg_connection *conn, const char *fmt, ...)
7037
34
{
7038
34
  va_list ap;
7039
34
  int result;
7040
7041
34
  va_start(ap, fmt);
7042
34
  result = mg_vprintf(conn, fmt, ap);
7043
34
  va_end(ap);
7044
7045
34
  return result;
7046
34
}
7047
7048
7049
CIVETWEB_API int
7050
mg_url_decode(const char *src,
7051
              int src_len,
7052
              char *dst,
7053
              int dst_len,
7054
              int is_form_url_encoded)
7055
0
{
7056
0
  int i, j, a, b;
7057
0
#define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
7058
7059
0
  for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
7060
0
    if ((i < src_len - 2) && (src[i] == '%')
7061
0
        && isxdigit((unsigned char)src[i + 1])
7062
0
        && isxdigit((unsigned char)src[i + 2])) {
7063
0
      a = tolower((unsigned char)src[i + 1]);
7064
0
      b = tolower((unsigned char)src[i + 2]);
7065
0
      dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
7066
0
      i += 2;
7067
0
    } else if (is_form_url_encoded && (src[i] == '+')) {
7068
0
      dst[j] = ' ';
7069
0
    } else {
7070
0
      dst[j] = src[i];
7071
0
    }
7072
0
  }
7073
7074
0
  dst[j] = '\0'; /* Null-terminate the destination */
7075
7076
0
  return (i >= src_len) ? j : -1;
7077
0
}
7078
7079
7080
/* form url decoding of an entire string */
7081
static void
7082
url_decode_in_place(char *buf)
7083
0
{
7084
0
  int len = (int)strlen(buf);
7085
0
  (void)mg_url_decode(buf, len, buf, len + 1, 1);
7086
0
}
7087
7088
7089
CIVETWEB_API int
7090
mg_get_var(const char *data,
7091
           size_t data_len,
7092
           const char *name,
7093
           char *dst,
7094
           size_t dst_len)
7095
0
{
7096
0
  return mg_get_var2(data, data_len, name, dst, dst_len, 0);
7097
0
}
7098
7099
7100
CIVETWEB_API int
7101
mg_get_var2(const char *data,
7102
            size_t data_len,
7103
            const char *name,
7104
            char *dst,
7105
            size_t dst_len,
7106
            size_t occurrence)
7107
0
{
7108
0
  const char *p, *e, *s;
7109
0
  size_t name_len;
7110
0
  int len;
7111
7112
0
  if ((dst == NULL) || (dst_len == 0)) {
7113
0
    len = -2;
7114
0
  } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
7115
0
    len = -1;
7116
0
    dst[0] = '\0';
7117
0
  } else {
7118
0
    name_len = strlen(name);
7119
0
    e = data + data_len;
7120
0
    len = -1;
7121
0
    dst[0] = '\0';
7122
7123
    /* data is "var1=val1&var2=val2...". Find variable first */
7124
0
    for (p = data; p + name_len < e; p++) {
7125
0
      if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
7126
0
          && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
7127
        /* Point p to variable value */
7128
0
        p += name_len + 1;
7129
7130
        /* Point s to the end of the value */
7131
0
        s = (const char *)memchr(p, '&', (size_t)(e - p));
7132
0
        if (s == NULL) {
7133
0
          s = e;
7134
0
        }
7135
0
        DEBUG_ASSERT(s >= p);
7136
0
        if (s < p) {
7137
0
          return -3;
7138
0
        }
7139
7140
        /* Decode variable into destination buffer */
7141
0
        len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
7142
7143
        /* Redirect error code from -1 to -2 (destination buffer too
7144
         * small). */
7145
0
        if (len == -1) {
7146
0
          len = -2;
7147
0
        }
7148
0
        break;
7149
0
      }
7150
0
    }
7151
0
  }
7152
7153
0
  return len;
7154
0
}
7155
7156
7157
/* split a string "key1=val1&key2=val2" into key/value pairs */
7158
CIVETWEB_API int
7159
mg_split_form_urlencoded(char *data,
7160
                         struct mg_header *form_fields,
7161
                         unsigned num_form_fields)
7162
0
{
7163
0
  char *b;
7164
0
  int i;
7165
0
  int num = 0;
7166
7167
0
  if (data == NULL) {
7168
    /* parameter error */
7169
0
    return -1;
7170
0
  }
7171
7172
0
  if ((form_fields == NULL) && (num_form_fields == 0)) {
7173
    /* determine the number of expected fields */
7174
0
    if (data[0] == 0) {
7175
0
      return 0;
7176
0
    }
7177
    /* count number of & to return the number of key-value-pairs */
7178
0
    num = 1;
7179
0
    while (*data) {
7180
0
      if (*data == '&') {
7181
0
        num++;
7182
0
      }
7183
0
      data++;
7184
0
    }
7185
0
    return num;
7186
0
  }
7187
7188
0
  if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
7189
    /* parameter error */
7190
0
    return -1;
7191
0
  }
7192
7193
0
  for (i = 0; i < (int)num_form_fields; i++) {
7194
    /* extract key-value pairs from input data */
7195
0
    while ((*data == ' ') || (*data == '\t')) {
7196
      /* skip initial spaces */
7197
0
      data++;
7198
0
    }
7199
0
    if (*data == 0) {
7200
      /* end of string reached */
7201
0
      break;
7202
0
    }
7203
0
    form_fields[num].name = data;
7204
7205
    /* find & or = */
7206
0
    b = data;
7207
0
    while ((*b != 0) && (*b != '&') && (*b != '=')) {
7208
0
      b++;
7209
0
    }
7210
7211
0
    if (*b == 0) {
7212
      /* last key without value */
7213
0
      form_fields[num].value = NULL;
7214
0
    } else if (*b == '&') {
7215
      /* mid key without value */
7216
0
      form_fields[num].value = NULL;
7217
0
    } else {
7218
      /* terminate string */
7219
0
      *b = 0;
7220
      /* value starts after '=' */
7221
0
      data = b + 1;
7222
0
      form_fields[num].value = data;
7223
0
    }
7224
7225
    /* new field is stored */
7226
0
    num++;
7227
7228
    /* find a next key */
7229
0
    b = strchr(data, '&');
7230
0
    if (b == 0) {
7231
      /* no more data */
7232
0
      break;
7233
0
    } else {
7234
      /* terminate value of last field at '&' */
7235
0
      *b = 0;
7236
      /* next key-value-pairs starts after '&' */
7237
0
      data = b + 1;
7238
0
    }
7239
0
  }
7240
7241
  /* Decode all values */
7242
0
  for (i = 0; i < num; i++) {
7243
0
    if (form_fields[i].name) {
7244
0
      url_decode_in_place((char *)form_fields[i].name);
7245
0
    }
7246
0
    if (form_fields[i].value) {
7247
0
      url_decode_in_place((char *)form_fields[i].value);
7248
0
    }
7249
0
  }
7250
7251
  /* return number of fields found */
7252
0
  return num;
7253
0
}
7254
7255
7256
/* HCP24: some changes to compare whole var_name */
7257
CIVETWEB_API int
7258
mg_get_cookie(const char *cookie_header,
7259
              const char *var_name,
7260
              char *dst,
7261
              size_t dst_size)
7262
0
{
7263
0
  const char *s, *p, *end;
7264
0
  int name_len, len = -1;
7265
7266
0
  if ((dst == NULL) || (dst_size == 0)) {
7267
0
    return -2;
7268
0
  }
7269
7270
0
  dst[0] = '\0';
7271
0
  if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
7272
0
    return -1;
7273
0
  }
7274
7275
0
  name_len = (int)strlen(var_name);
7276
0
  end = s + strlen(s);
7277
0
  for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
7278
0
    if (s[name_len] == '=') {
7279
      /* HCP24: now check is it a substring or a full cookie name */
7280
0
      if ((s == cookie_header) || (s[-1] == ' ')) {
7281
0
        s += name_len + 1;
7282
0
        if ((p = strchr(s, ' ')) == NULL) {
7283
0
          p = end;
7284
0
        }
7285
0
        if (p[-1] == ';') {
7286
0
          p--;
7287
0
        }
7288
0
        if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
7289
0
          s++;
7290
0
          p--;
7291
0
        }
7292
0
        if ((size_t)(p - s) < dst_size) {
7293
0
          len = (int)(p - s);
7294
0
          mg_strlcpy(dst, s, (size_t)len + 1);
7295
0
        } else {
7296
0
          len = -3;
7297
0
        }
7298
0
        break;
7299
0
      }
7300
0
    }
7301
0
  }
7302
0
  return len;
7303
0
}
7304
7305
7306
CIVETWEB_API int
7307
mg_base64_encode(const unsigned char *src,
7308
                 size_t src_len,
7309
                 char *dst,
7310
                 size_t *dst_len)
7311
0
{
7312
0
  static const char *b64 =
7313
0
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7314
0
  size_t i, j;
7315
0
  int a, b, c;
7316
7317
0
  if (dst_len != NULL) {
7318
    /* Expected length including 0 termination: */
7319
    /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
7320
     * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
7321
0
    size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
7322
0
    if (*dst_len < expected_len) {
7323
0
      if (*dst_len > 0) {
7324
0
        dst[0] = '\0';
7325
0
      }
7326
0
      *dst_len = expected_len;
7327
0
      return 0;
7328
0
    }
7329
0
  }
7330
7331
0
  for (i = j = 0; i < src_len; i += 3) {
7332
0
    a = src[i];
7333
0
    b = ((i + 1) >= src_len) ? 0 : src[i + 1];
7334
0
    c = ((i + 2) >= src_len) ? 0 : src[i + 2];
7335
7336
0
    dst[j++] = b64[a >> 2];
7337
0
    dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
7338
0
    if (i + 1 < src_len) {
7339
0
      dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
7340
0
    }
7341
0
    if (i + 2 < src_len) {
7342
0
      dst[j++] = b64[c & 63];
7343
0
    }
7344
0
  }
7345
0
  while (j % 4 != 0) {
7346
0
    dst[j++] = '=';
7347
0
  }
7348
0
  dst[j++] = '\0';
7349
7350
0
  if (dst_len != NULL) {
7351
0
    *dst_len = (size_t)j;
7352
0
  }
7353
7354
  /* Return -1 for "OK" */
7355
0
  return -1;
7356
0
}
7357
7358
7359
static unsigned char
7360
b64reverse(char letter)
7361
0
{
7362
0
  if ((letter >= 'A') && (letter <= 'Z')) {
7363
0
    return letter - 'A';
7364
0
  }
7365
0
  if ((letter >= 'a') && (letter <= 'z')) {
7366
0
    return letter - 'a' + 26;
7367
0
  }
7368
0
  if ((letter >= '0') && (letter <= '9')) {
7369
0
    return letter - '0' + 52;
7370
0
  }
7371
0
  if (letter == '+') {
7372
0
    return 62;
7373
0
  }
7374
0
  if (letter == '/') {
7375
0
    return 63;
7376
0
  }
7377
0
  if (letter == '=') {
7378
0
    return 255; /* normal end */
7379
0
  }
7380
0
  return 254; /* error */
7381
0
}
7382
7383
7384
CIVETWEB_API int
7385
mg_base64_decode(const char *src,
7386
                 size_t src_len,
7387
                 unsigned char *dst,
7388
                 size_t *dst_len)
7389
0
{
7390
0
  size_t i;
7391
0
  unsigned char a, b, c, d;
7392
0
  size_t dst_len_limit = (size_t)-1;
7393
0
  size_t dst_len_used = 0;
7394
7395
0
  if (dst_len != NULL) {
7396
0
    dst_len_limit = *dst_len;
7397
0
    *dst_len = 0;
7398
0
  }
7399
7400
0
  for (i = 0; i < src_len; i += 4) {
7401
    /* Read 4 characters from BASE64 string */
7402
0
    a = b64reverse(src[i]);
7403
0
    if (a >= 254) {
7404
0
      return (int)i;
7405
0
    }
7406
7407
0
    b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
7408
0
    if (b >= 254) {
7409
0
      return (int)i + 1;
7410
0
    }
7411
7412
0
    c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
7413
0
    if (c == 254) {
7414
0
      return (int)i + 2;
7415
0
    }
7416
7417
0
    d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
7418
0
    if (d == 254) {
7419
0
      return (int)i + 3;
7420
0
    }
7421
7422
    /* Add first (of 3) decoded character */
7423
0
    if (dst_len_used < dst_len_limit) {
7424
0
      dst[dst_len_used] = (a << 2) + (b >> 4);
7425
0
    }
7426
0
    dst_len_used++;
7427
7428
0
    if (c != 255) {
7429
0
      if (dst_len_used < dst_len_limit) {
7430
7431
0
        dst[dst_len_used] = (b << 4) + (c >> 2);
7432
0
      }
7433
0
      dst_len_used++;
7434
0
      if (d != 255) {
7435
0
        if (dst_len_used < dst_len_limit) {
7436
0
          dst[dst_len_used] = (c << 6) + d;
7437
0
        }
7438
0
        dst_len_used++;
7439
0
      }
7440
0
    }
7441
0
  }
7442
7443
  /* Add terminating zero */
7444
0
  if (dst_len_used < dst_len_limit) {
7445
0
    dst[dst_len_used] = '\0';
7446
0
  }
7447
0
  dst_len_used++;
7448
0
  if (dst_len != NULL) {
7449
0
    *dst_len = dst_len_used;
7450
0
  }
7451
7452
0
  if (dst_len_used > dst_len_limit) {
7453
    /* Out of memory */
7454
0
    return 0;
7455
0
  }
7456
7457
  /* Return -1 for "OK" */
7458
0
  return -1;
7459
0
}
7460
7461
7462
static int
7463
is_put_or_delete_method(const struct mg_connection *conn)
7464
0
{
7465
0
  if (conn) {
7466
0
    const char *s = conn->request_info.request_method;
7467
0
    if (s != NULL) {
7468
      /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
7469
0
      return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
7470
0
              || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
7471
0
              || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
7472
0
              || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
7473
0
              || !strcmp(s, "COPY"));
7474
0
    }
7475
0
  }
7476
0
  return 0;
7477
0
}
7478
7479
7480
static int
7481
is_civetweb_webdav_method(const struct mg_connection *conn)
7482
0
{
7483
  /* Note: Here we only have to identify the WebDav methods that need special
7484
   * handling in the CivetWeb code - not all methods used in WebDav. In
7485
   * particular, methods used on directories (when using Windows Explorer as
7486
   * WebDav client).
7487
   */
7488
0
  if (conn) {
7489
0
    const char *s = conn->request_info.request_method;
7490
0
    if (s != NULL) {
7491
      /* These are the civetweb builtin DAV methods */
7492
0
      return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
7493
0
              || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
7494
0
              || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
7495
0
    }
7496
0
  }
7497
0
  return 0;
7498
0
}
7499
7500
7501
#if !defined(NO_FILES)
7502
static int
7503
extention_matches_script(
7504
    struct mg_connection *conn, /* in: request (must be valid) */
7505
    const char *filename        /* in: filename  (must be valid) */
7506
)
7507
0
{
7508
0
#if !defined(NO_CGI)
7509
0
  unsigned char cgi_config_idx, inc, max;
7510
0
#endif
7511
7512
#if defined(USE_LUA)
7513
  if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
7514
                          filename)
7515
      > 0) {
7516
    return 1;
7517
  }
7518
#endif
7519
#if defined(USE_DUKTAPE)
7520
  if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
7521
                          filename)
7522
      > 0) {
7523
    return 1;
7524
  }
7525
#endif
7526
0
#if !defined(NO_CGI)
7527
0
  inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
7528
0
  max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
7529
0
  for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
7530
0
    if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
7531
0
        && (match_prefix_strlen(
7532
0
                conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
7533
0
                filename)
7534
0
            > 0)) {
7535
0
      return 1;
7536
0
    }
7537
0
  }
7538
0
#endif
7539
  /* filename and conn could be unused, if all preocessor conditions
7540
   * are false (no script language supported). */
7541
0
  (void)filename;
7542
0
  (void)conn;
7543
7544
0
  return 0;
7545
0
}
7546
7547
7548
static int
7549
extention_matches_template_text(
7550
    struct mg_connection *conn, /* in: request (must be valid) */
7551
    const char *filename        /* in: filename  (must be valid) */
7552
)
7553
0
{
7554
#if defined(USE_LUA)
7555
  if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
7556
                          filename)
7557
      > 0) {
7558
    return 1;
7559
  }
7560
#endif
7561
0
  if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
7562
0
      > 0) {
7563
0
    return 1;
7564
0
  }
7565
0
  return 0;
7566
0
}
7567
7568
7569
/* For given directory path, substitute it to valid index file.
7570
 * Return 1 if index file has been found, 0 if not found.
7571
 * If the file is found, it's stats is returned in stp. */
7572
static int
7573
substitute_index_file(struct mg_connection *conn,
7574
                      char *path,
7575
                      size_t path_len,
7576
                      struct mg_file_stat *filestat)
7577
0
{
7578
0
  const char *list = conn->dom_ctx->config[INDEX_FILES];
7579
0
  struct vec filename_vec;
7580
0
  size_t n = strlen(path);
7581
0
  int found = 0;
7582
7583
  /* The 'path' given to us points to the directory. Remove all trailing
7584
   * directory separator characters from the end of the path, and
7585
   * then append single directory separator character. */
7586
0
  while ((n > 0) && (path[n - 1] == '/')) {
7587
0
    n--;
7588
0
  }
7589
0
  path[n] = '/';
7590
7591
  /* Traverse index files list. For each entry, append it to the given
7592
   * path and see if the file exists. If it exists, break the loop */
7593
0
  while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
7594
    /* Ignore too long entries that may overflow path buffer */
7595
0
    if ((filename_vec.len + 1) > (path_len - (n + 1))) {
7596
0
      continue;
7597
0
    }
7598
7599
    /* Prepare full path to the index file */
7600
0
    mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
7601
7602
    /* Does it exist? */
7603
0
    if (mg_stat(conn, path, filestat)) {
7604
      /* Yes it does, break the loop */
7605
0
      found = 1;
7606
0
      break;
7607
0
    }
7608
0
  }
7609
7610
  /* If no index file exists, restore directory path */
7611
0
  if (!found) {
7612
0
    path[n] = '\0';
7613
0
  }
7614
7615
0
  return found;
7616
0
}
7617
#endif
7618
7619
7620
static void
7621
interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
7622
              char *filename,             /* out: filename */
7623
              size_t filename_buf_len,    /* in: size of filename buffer */
7624
              struct mg_file_stat *filestat, /* out: file status structure */
7625
              int *is_found,                 /* out: file found (directly) */
7626
              int *is_script_resource,       /* out: handled by a script? */
7627
              int *is_websocket_request,     /* out: websocket connection? */
7628
              int *is_put_or_delete_request, /* out: put/delete a file? */
7629
              int *is_webdav_request,        /* out: webdav request? */
7630
              int *is_template_text          /* out: SSI file or LSP file? */
7631
)
7632
0
{
7633
0
  char const *accept_encoding;
7634
7635
0
#if !defined(NO_FILES)
7636
0
  const char *uri = conn->request_info.local_uri;
7637
0
  const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
7638
0
  const char *rewrite;
7639
0
  struct vec a, b;
7640
0
  ptrdiff_t match_len;
7641
0
  char gz_path[UTF8_PATH_MAX];
7642
0
  int truncated;
7643
0
#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7644
0
  char *tmp_str;
7645
0
  size_t tmp_str_len, sep_pos;
7646
0
  int allow_substitute_script_subresources;
7647
0
#endif
7648
#else
7649
  (void)filename_buf_len; /* unused if NO_FILES is defined */
7650
#endif
7651
7652
  /* Step 1: Set all initially unknown outputs to zero */
7653
0
  memset(filestat, 0, sizeof(*filestat));
7654
0
  *filename = 0;
7655
0
  *is_found = 0;
7656
0
  *is_script_resource = 0;
7657
0
  *is_template_text = 0;
7658
7659
  /* Step 2: Classify the request method */
7660
  /* Step 2a: Check if the request attempts to modify the file system */
7661
0
  *is_put_or_delete_request = is_put_or_delete_method(conn);
7662
  /* Step 2b: Check if the request uses WebDav method that requires special
7663
   * handling */
7664
0
  *is_webdav_request = is_civetweb_webdav_method(conn);
7665
7666
  /* Step 3: Check if it is a websocket request, and modify the document
7667
   * root if required */
7668
#if defined(USE_WEBSOCKET)
7669
  *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
7670
#if !defined(NO_FILES)
7671
  if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
7672
    root = conn->dom_ctx->config[WEBSOCKET_ROOT];
7673
  }
7674
#endif /* !NO_FILES */
7675
#else  /* USE_WEBSOCKET */
7676
0
  *is_websocket_request = 0;
7677
0
#endif /* USE_WEBSOCKET */
7678
7679
  /* Step 4: Check if gzip encoded response is allowed */
7680
0
  conn->accept_gzip = 0;
7681
0
  if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
7682
0
    if (strstr(accept_encoding, "gzip") != NULL) {
7683
0
      conn->accept_gzip = 1;
7684
0
    }
7685
0
  }
7686
7687
0
#if !defined(NO_FILES)
7688
  /* Step 5: If there is no root directory, don't look for files. */
7689
  /* Note that root == NULL is a regular use case here. This occurs,
7690
   * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
7691
   * config is not required. */
7692
0
  if (root == NULL) {
7693
    /* all file related outputs have already been set to 0, just return
7694
     */
7695
0
    return;
7696
0
  }
7697
7698
  /* Step 6: Determine the local file path from the root path and the
7699
   * request uri. */
7700
  /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
7701
   * part of the path one byte on the right. */
7702
0
  truncated = 0;
7703
0
  mg_snprintf(
7704
0
      conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
7705
7706
0
  if (truncated) {
7707
0
    goto interpret_cleanup;
7708
0
  }
7709
7710
  /* Step 7: URI rewriting */
7711
0
  rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
7712
0
  while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
7713
0
    if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
7714
0
      mg_snprintf(conn,
7715
0
                  &truncated,
7716
0
                  filename,
7717
0
                  filename_buf_len - 1,
7718
0
                  "%.*s%s",
7719
0
                  (int)b.len,
7720
0
                  b.ptr,
7721
0
                  uri + match_len);
7722
0
      break;
7723
0
    }
7724
0
  }
7725
7726
0
  if (truncated) {
7727
0
    goto interpret_cleanup;
7728
0
  }
7729
7730
  /* Step 8: Check if the file exists at the server */
7731
  /* Local file path and name, corresponding to requested URI
7732
   * is now stored in "filename" variable. */
7733
0
  if (mg_stat(conn, filename, filestat)) {
7734
0
    int uri_len = (int)strlen(uri);
7735
0
    int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
7736
7737
    /* 8.1: File exists. */
7738
0
    *is_found = 1;
7739
7740
    /* 8.2: Check if it is a script type. */
7741
0
    if (extention_matches_script(conn, filename)) {
7742
      /* The request addresses a CGI resource, Lua script or
7743
       * server-side javascript.
7744
       * The URI corresponds to the script itself (like
7745
       * /path/script.cgi), and there is no additional resource
7746
       * path (like /path/script.cgi/something).
7747
       * Requests that modify (replace or delete) a resource, like
7748
       * PUT and DELETE requests, should replace/delete the script
7749
       * file.
7750
       * Requests that read or write from/to a resource, like GET and
7751
       * POST requests, should call the script and return the
7752
       * generated response. */
7753
0
      *is_script_resource = (!*is_put_or_delete_request);
7754
0
    }
7755
7756
    /* 8.3: Check for SSI and LSP files */
7757
0
    if (extention_matches_template_text(conn, filename)) {
7758
      /* Same as above, but for *.lsp and *.shtml files. */
7759
      /* A "template text" is a file delivered directly to the client,
7760
       * but with some text tags replaced by dynamic content.
7761
       * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
7762
       * (LP, LSP) file. */
7763
0
      *is_template_text = (!*is_put_or_delete_request);
7764
0
    }
7765
7766
    /* 8.4: If the request target is a directory, there could be
7767
     * a substitute file (index.html, index.cgi, ...). */
7768
    /* But do not substitute a directory for a WebDav request */
7769
0
    if (filestat->is_directory && is_uri_end_slash
7770
0
        && (!*is_webdav_request)) {
7771
      /* Use a local copy here, since substitute_index_file will
7772
       * change the content of the file status */
7773
0
      struct mg_file_stat tmp_filestat;
7774
0
      memset(&tmp_filestat, 0, sizeof(tmp_filestat));
7775
7776
0
      if (substitute_index_file(
7777
0
              conn, filename, filename_buf_len, &tmp_filestat)) {
7778
7779
        /* Substitute file found. Copy stat to the output, then
7780
         * check if the file is a script file */
7781
0
        *filestat = tmp_filestat;
7782
7783
0
        if (extention_matches_script(conn, filename)) {
7784
          /* Substitute file is a script file */
7785
0
          *is_script_resource = 1;
7786
0
        } else if (extention_matches_template_text(conn, filename)) {
7787
          /* Substitute file is a LSP or SSI file */
7788
0
          *is_template_text = 1;
7789
0
        } else {
7790
          /* Substitute file is a regular file */
7791
0
          *is_script_resource = 0;
7792
0
          *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
7793
0
        }
7794
0
      }
7795
      /* If there is no substitute file, the server could return
7796
       * a directory listing in a later step */
7797
0
    }
7798
0
    return;
7799
0
  }
7800
7801
  /* Step 9: Check for zipped files: */
7802
  /* If we can't find the actual file, look for the file
7803
   * with the same name but a .gz extension. If we find it,
7804
   * use that and set the gzipped flag in the file struct
7805
   * to indicate that the response need to have the content-
7806
   * encoding: gzip header.
7807
   * We can only do this if the browser declares support. */
7808
0
  if (conn->accept_gzip) {
7809
0
    mg_snprintf(
7810
0
        conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
7811
7812
0
    if (truncated) {
7813
0
      goto interpret_cleanup;
7814
0
    }
7815
7816
0
    if (mg_stat(conn, gz_path, filestat)) {
7817
0
      if (filestat) {
7818
0
        filestat->is_gzipped = 1;
7819
0
        *is_found = 1;
7820
0
      }
7821
      /* Currently gz files can not be scripts. */
7822
0
      return;
7823
0
    }
7824
0
  }
7825
7826
0
#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7827
  /* Step 10: Script resources may handle sub-resources */
7828
  /* Support PATH_INFO for CGI scripts. */
7829
0
  tmp_str_len = strlen(filename);
7830
0
  tmp_str =
7831
0
      (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
7832
0
  if (!tmp_str) {
7833
    /* Out of memory */
7834
0
    goto interpret_cleanup;
7835
0
  }
7836
0
  memcpy(tmp_str, filename, tmp_str_len + 1);
7837
7838
  /* Check config, if index scripts may have sub-resources */
7839
0
  allow_substitute_script_subresources =
7840
0
      !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
7841
0
                     "yes");
7842
0
  if (*is_webdav_request) {
7843
    /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
7844
     * PROPFIND for their subresources? */
7845
    /* allow_substitute_script_subresources = 0; */
7846
0
  }
7847
7848
0
  sep_pos = tmp_str_len;
7849
0
  while (sep_pos > 0) {
7850
0
    sep_pos--;
7851
0
    if (tmp_str[sep_pos] == '/') {
7852
0
      int is_script = 0, does_exist = 0;
7853
7854
0
      tmp_str[sep_pos] = 0;
7855
0
      if (tmp_str[0]) {
7856
0
        is_script = extention_matches_script(conn, tmp_str);
7857
0
        does_exist = mg_stat(conn, tmp_str, filestat);
7858
0
      }
7859
7860
0
      if (does_exist && is_script) {
7861
0
        filename[sep_pos] = 0;
7862
0
        memmove(filename + sep_pos + 2,
7863
0
                filename + sep_pos + 1,
7864
0
                strlen(filename + sep_pos + 1) + 1);
7865
0
        conn->path_info = filename + sep_pos + 1;
7866
0
        filename[sep_pos + 1] = '/';
7867
0
        *is_script_resource = 1;
7868
0
        *is_found = 1;
7869
0
        break;
7870
0
      }
7871
7872
0
      if (allow_substitute_script_subresources) {
7873
0
        if (substitute_index_file(
7874
0
                conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
7875
7876
          /* some intermediate directory has an index file */
7877
0
          if (extention_matches_script(conn, tmp_str)) {
7878
7879
0
            size_t script_name_len = strlen(tmp_str);
7880
7881
            /* subres_name read before this memory locatio will be
7882
            overwritten */
7883
0
            char *subres_name = filename + sep_pos;
7884
0
            size_t subres_name_len = strlen(subres_name);
7885
7886
0
            DEBUG_TRACE("Substitute script %s serving path %s",
7887
0
                        tmp_str,
7888
0
                        filename);
7889
7890
            /* this index file is a script */
7891
0
            if ((script_name_len + subres_name_len + 2)
7892
0
                >= filename_buf_len) {
7893
0
              mg_free(tmp_str);
7894
0
              goto interpret_cleanup;
7895
0
            }
7896
7897
0
            conn->path_info =
7898
0
                filename + script_name_len + 1; /* new target */
7899
0
            memmove(conn->path_info, subres_name, subres_name_len);
7900
0
            conn->path_info[subres_name_len] = 0;
7901
0
            memcpy(filename, tmp_str, script_name_len + 1);
7902
7903
0
            *is_script_resource = 1;
7904
0
            *is_found = 1;
7905
0
            break;
7906
7907
0
          } else {
7908
7909
0
            DEBUG_TRACE("Substitute file %s serving path %s",
7910
0
                        tmp_str,
7911
0
                        filename);
7912
7913
            /* non-script files will not have sub-resources */
7914
0
            filename[sep_pos] = 0;
7915
0
            conn->path_info = 0;
7916
0
            *is_script_resource = 0;
7917
0
            *is_found = 0;
7918
0
            break;
7919
0
          }
7920
0
        }
7921
0
      }
7922
7923
0
      tmp_str[sep_pos] = '/';
7924
0
    }
7925
0
  }
7926
7927
0
  mg_free(tmp_str);
7928
7929
0
#endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
7930
0
#endif /* !defined(NO_FILES) */
7931
0
  return;
7932
7933
0
#if !defined(NO_FILES)
7934
/* Reset all outputs */
7935
0
interpret_cleanup:
7936
0
  memset(filestat, 0, sizeof(*filestat));
7937
0
  *filename = 0;
7938
0
  *is_found = 0;
7939
0
  *is_script_resource = 0;
7940
0
  *is_websocket_request = 0;
7941
0
  *is_put_or_delete_request = 0;
7942
0
#endif /* !defined(NO_FILES) */
7943
0
}
7944
7945
7946
/* Check whether full request is buffered. Return:
7947
 * -1  if request or response is malformed
7948
 *  0  if request or response is not yet fully buffered
7949
 * >0  actual request length, including last \r\n\r\n */
7950
static int
7951
get_http_header_len(const char *buf, int buflen)
7952
82
{
7953
82
  int i;
7954
11.6k
  for (i = 0; i < buflen; i++) {
7955
    /* Do an unsigned comparison in some conditions below */
7956
11.6k
    const unsigned char c = (unsigned char)buf[i];
7957
7958
11.6k
    if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
7959
11.6k
        && !isprint(c)) {
7960
      /* abort scan as soon as one malformed character is found */
7961
11
      return -1;
7962
11
    }
7963
7964
11.6k
    if (i < buflen - 1) {
7965
11.6k
      if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
7966
        /* Two newline, no carriage return - not standard compliant,
7967
         * but it should be accepted */
7968
26
        return i + 2;
7969
26
      }
7970
11.6k
    }
7971
7972
11.6k
    if (i < buflen - 3) {
7973
11.5k
      if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
7974
11.5k
          && (buf[i + 3] == '\n')) {
7975
        /* Two \r\n - standard compliant */
7976
1
        return i + 4;
7977
1
      }
7978
11.5k
    }
7979
11.6k
  }
7980
7981
44
  return 0;
7982
82
}
7983
7984
7985
#if !defined(NO_CACHING)
7986
/* Convert month to the month number. Return -1 on error, or month number */
7987
static int
7988
get_month_index(const char *s)
7989
0
{
7990
0
  size_t i;
7991
7992
0
  for (i = 0; i < ARRAY_SIZE(month_names); i++) {
7993
0
    if (!strcmp(s, month_names[i])) {
7994
0
      return (int)i;
7995
0
    }
7996
0
  }
7997
7998
0
  return -1;
7999
0
}
8000
8001
8002
/* Parse UTC date-time string, and return the corresponding time_t value. */
8003
static time_t
8004
parse_date_string(const char *datetime)
8005
0
{
8006
0
  char month_str[32] = {0};
8007
0
  int second, minute, hour, day, month, year;
8008
0
  time_t result = (time_t)0;
8009
0
  struct tm tm;
8010
8011
0
  if ((sscanf(datetime,
8012
0
              "%d/%3s/%d %d:%d:%d",
8013
0
              &day,
8014
0
              month_str,
8015
0
              &year,
8016
0
              &hour,
8017
0
              &minute,
8018
0
              &second)
8019
0
       == 6)
8020
0
      || (sscanf(datetime,
8021
0
                 "%d %3s %d %d:%d:%d",
8022
0
                 &day,
8023
0
                 month_str,
8024
0
                 &year,
8025
0
                 &hour,
8026
0
                 &minute,
8027
0
                 &second)
8028
0
          == 6)
8029
0
      || (sscanf(datetime,
8030
0
                 "%*3s, %d %3s %d %d:%d:%d",
8031
0
                 &day,
8032
0
                 month_str,
8033
0
                 &year,
8034
0
                 &hour,
8035
0
                 &minute,
8036
0
                 &second)
8037
0
          == 6)
8038
0
      || (sscanf(datetime,
8039
0
                 "%d-%3s-%d %d:%d:%d",
8040
0
                 &day,
8041
0
                 month_str,
8042
0
                 &year,
8043
0
                 &hour,
8044
0
                 &minute,
8045
0
                 &second)
8046
0
          == 6)) {
8047
0
    month = get_month_index(month_str);
8048
0
    if ((month >= 0) && (year >= 1970)) {
8049
0
      memset(&tm, 0, sizeof(tm));
8050
0
      tm.tm_year = year - 1900;
8051
0
      tm.tm_mon = month;
8052
0
      tm.tm_mday = day;
8053
0
      tm.tm_hour = hour;
8054
0
      tm.tm_min = minute;
8055
0
      tm.tm_sec = second;
8056
0
      result = timegm(&tm);
8057
0
    }
8058
0
  }
8059
8060
0
  return result;
8061
0
}
8062
#endif /* !NO_CACHING */
8063
8064
8065
/* Pre-process URIs according to RFC + protect against directory disclosure
8066
 * attacks by removing '..', excessive '/' and '\' characters */
8067
static void
8068
remove_dot_segments(char *inout)
8069
0
{
8070
  /* Windows backend protection
8071
   * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
8072
   * in URI by slash */
8073
0
  char *out_end = inout;
8074
0
  char *in = inout;
8075
8076
0
  if (!in) {
8077
    /* Param error. */
8078
0
    return;
8079
0
  }
8080
8081
0
  while (*in) {
8082
0
    if (*in == '\\') {
8083
0
      *in = '/';
8084
0
    }
8085
0
    in++;
8086
0
  }
8087
8088
  /* Algorithm "remove_dot_segments" from
8089
   * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
8090
  /* Step 1:
8091
   * The input buffer is initialized.
8092
   * The output buffer is initialized to the empty string.
8093
   */
8094
0
  in = inout;
8095
8096
  /* Step 2:
8097
   * While the input buffer is not empty, loop as follows:
8098
   */
8099
  /* Less than out_end of the inout buffer is used as output, so keep
8100
   * condition: out_end <= in */
8101
0
  while (*in) {
8102
    /* Step 2a:
8103
     * If the input buffer begins with a prefix of "../" or "./",
8104
     * then remove that prefix from the input buffer;
8105
     */
8106
0
    if (!strncmp(in, "../", 3)) {
8107
0
      in += 3;
8108
0
    } else if (!strncmp(in, "./", 2)) {
8109
0
      in += 2;
8110
0
    }
8111
    /* otherwise */
8112
    /* Step 2b:
8113
     * if the input buffer begins with a prefix of "/./" or "/.",
8114
     * where "." is a complete path segment, then replace that
8115
     * prefix with "/" in the input buffer;
8116
     */
8117
0
    else if (!strncmp(in, "/./", 3)) {
8118
0
      in += 2;
8119
0
    } else if (!strcmp(in, "/.")) {
8120
0
      in[1] = 0;
8121
0
    }
8122
    /* otherwise */
8123
    /* Step 2c:
8124
     * if the input buffer begins with a prefix of "/../" or "/..",
8125
     * where ".." is a complete path segment, then replace that
8126
     * prefix with "/" in the input buffer and remove the last
8127
     * segment and its preceding "/" (if any) from the output
8128
     * buffer;
8129
     */
8130
0
    else if (!strncmp(in, "/../", 4)) {
8131
0
      in += 3;
8132
0
      if (inout != out_end) {
8133
        /* remove last segment */
8134
0
        do {
8135
0
          out_end--;
8136
0
        } while ((inout != out_end) && (*out_end != '/'));
8137
0
      }
8138
0
    } else if (!strcmp(in, "/..")) {
8139
0
      in[1] = 0;
8140
0
      if (inout != out_end) {
8141
        /* remove last segment */
8142
0
        do {
8143
0
          out_end--;
8144
0
        } while ((inout != out_end) && (*out_end != '/'));
8145
0
      }
8146
0
    }
8147
    /* otherwise */
8148
    /* Step 2d:
8149
     * if the input buffer consists only of "." or "..", then remove
8150
     * that from the input buffer;
8151
     */
8152
0
    else if (!strcmp(in, ".") || !strcmp(in, "..")) {
8153
0
      *in = 0;
8154
0
    }
8155
    /* otherwise */
8156
    /* Step 2e:
8157
     * move the first path segment in the input buffer to the end of
8158
     * the output buffer, including the initial "/" character (if
8159
     * any) and any subsequent characters up to, but not including,
8160
     * the next "/" character or the end of the input buffer.
8161
     */
8162
0
    else {
8163
0
      do {
8164
0
        *out_end = *in;
8165
0
        out_end++;
8166
0
        in++;
8167
0
      } while ((*in != 0) && (*in != '/'));
8168
0
    }
8169
0
  }
8170
8171
  /* Step 3:
8172
   * Finally, the output buffer is returned as the result of
8173
   * remove_dot_segments.
8174
   */
8175
  /* Terminate output */
8176
0
  *out_end = 0;
8177
8178
  /* For Windows, the files/folders "x" and "x." (with a dot but without
8179
   * extension) are identical. Replace all "./" by "/" and remove a "." at
8180
   * the end. Also replace all "//" by "/". Repeat until there is no "./"
8181
   * or "//" anymore.
8182
   */
8183
0
  out_end = in = inout;
8184
0
  while (*in) {
8185
0
    if (*in == '.') {
8186
      /* remove . at the end or preceding of / */
8187
0
      char *in_ahead = in;
8188
0
      do {
8189
0
        in_ahead++;
8190
0
      } while (*in_ahead == '.');
8191
0
      if (*in_ahead == '/') {
8192
0
        in = in_ahead;
8193
0
        if ((out_end != inout) && (out_end[-1] == '/')) {
8194
          /* remove generated // */
8195
0
          out_end--;
8196
0
        }
8197
0
      } else if (*in_ahead == 0) {
8198
0
        in = in_ahead;
8199
0
      } else {
8200
0
        do {
8201
0
          *out_end++ = '.';
8202
0
          in++;
8203
0
        } while (in != in_ahead);
8204
0
      }
8205
0
    } else if (*in == '/') {
8206
      /* replace // by / */
8207
0
      *out_end++ = '/';
8208
0
      do {
8209
0
        in++;
8210
0
      } while (*in == '/');
8211
0
    } else {
8212
0
      *out_end++ = *in;
8213
0
      in++;
8214
0
    }
8215
0
  }
8216
0
  *out_end = 0;
8217
0
}
8218
8219
8220
static const struct {
8221
  const char *extension;
8222
  size_t ext_len;
8223
  const char *mime_type;
8224
} builtin_mime_types[] = {
8225
    /* IANA registered MIME types
8226
     * (http://www.iana.org/assignments/media-types)
8227
     * application types */
8228
    {".bin", 4, "application/octet-stream"},
8229
    {".deb", 4, "application/octet-stream"},
8230
    {".dmg", 4, "application/octet-stream"},
8231
    {".dll", 4, "application/octet-stream"},
8232
    {".doc", 4, "application/msword"},
8233
    {".eps", 4, "application/postscript"},
8234
    {".exe", 4, "application/octet-stream"},
8235
    {".iso", 4, "application/octet-stream"},
8236
    {".js", 3, "application/javascript"},
8237
    {".json", 5, "application/json"},
8238
    {".msi", 4, "application/octet-stream"},
8239
    {".pdf", 4, "application/pdf"},
8240
    {".ps", 3, "application/postscript"},
8241
    {".rtf", 4, "application/rtf"},
8242
    {".xhtml", 6, "application/xhtml+xml"},
8243
    {".xsl", 4, "application/xml"},
8244
    {".xslt", 5, "application/xml"},
8245
8246
    /* fonts */
8247
    {".ttf", 4, "application/font-sfnt"},
8248
    {".cff", 4, "application/font-sfnt"},
8249
    {".otf", 4, "application/font-sfnt"},
8250
    {".aat", 4, "application/font-sfnt"},
8251
    {".sil", 4, "application/font-sfnt"},
8252
    {".pfr", 4, "application/font-tdpfr"},
8253
    {".woff", 5, "application/font-woff"},
8254
    {".woff2", 6, "application/font-woff2"},
8255
8256
    /* audio */
8257
    {".mp3", 4, "audio/mpeg"},
8258
    {".oga", 4, "audio/ogg"},
8259
    {".ogg", 4, "audio/ogg"},
8260
8261
    /* image */
8262
    {".gif", 4, "image/gif"},
8263
    {".ief", 4, "image/ief"},
8264
    {".jpeg", 5, "image/jpeg"},
8265
    {".jpg", 4, "image/jpeg"},
8266
    {".jpm", 4, "image/jpm"},
8267
    {".jpx", 4, "image/jpx"},
8268
    {".png", 4, "image/png"},
8269
    {".svg", 4, "image/svg+xml"},
8270
    {".tif", 4, "image/tiff"},
8271
    {".tiff", 5, "image/tiff"},
8272
8273
    /* model */
8274
    {".wrl", 4, "model/vrml"},
8275
8276
    /* text */
8277
    {".css", 4, "text/css"},
8278
    {".csv", 4, "text/csv"},
8279
    {".htm", 4, "text/html"},
8280
    {".html", 5, "text/html"},
8281
    {".sgm", 4, "text/sgml"},
8282
    {".shtm", 5, "text/html"},
8283
    {".shtml", 6, "text/html"},
8284
    {".txt", 4, "text/plain"},
8285
    {".xml", 4, "text/xml"},
8286
8287
    /* video */
8288
    {".mov", 4, "video/quicktime"},
8289
    {".mp4", 4, "video/mp4"},
8290
    {".mpeg", 5, "video/mpeg"},
8291
    {".mpg", 4, "video/mpeg"},
8292
    {".ogv", 4, "video/ogg"},
8293
    {".qt", 3, "video/quicktime"},
8294
8295
    /* not registered types
8296
     * (http://reference.sitepoint.com/html/mime-types-full,
8297
     * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
8298
    {".arj", 4, "application/x-arj-compressed"},
8299
    {".gz", 3, "application/x-gunzip"},
8300
    {".rar", 4, "application/x-arj-compressed"},
8301
    {".swf", 4, "application/x-shockwave-flash"},
8302
    {".tar", 4, "application/x-tar"},
8303
    {".tgz", 4, "application/x-tar-gz"},
8304
    {".torrent", 8, "application/x-bittorrent"},
8305
    {".ppt", 4, "application/x-mspowerpoint"},
8306
    {".xls", 4, "application/x-msexcel"},
8307
    {".zip", 4, "application/x-zip-compressed"},
8308
    {".aac",
8309
     4,
8310
     "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
8311
    {".flac", 5, "audio/flac"},
8312
    {".aif", 4, "audio/x-aif"},
8313
    {".m3u", 4, "audio/x-mpegurl"},
8314
    {".mid", 4, "audio/x-midi"},
8315
    {".ra", 3, "audio/x-pn-realaudio"},
8316
    {".ram", 4, "audio/x-pn-realaudio"},
8317
    {".wav", 4, "audio/x-wav"},
8318
    {".bmp", 4, "image/bmp"},
8319
    {".ico", 4, "image/x-icon"},
8320
    {".pct", 4, "image/x-pct"},
8321
    {".pict", 5, "image/pict"},
8322
    {".rgb", 4, "image/x-rgb"},
8323
    {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
8324
    {".asf", 4, "video/x-ms-asf"},
8325
    {".avi", 4, "video/x-msvideo"},
8326
    {".m4v", 4, "video/x-m4v"},
8327
    {NULL, 0, NULL}};
8328
8329
8330
CIVETWEB_API const char *
8331
mg_get_builtin_mime_type(const char *path)
8332
0
{
8333
0
  const char *ext;
8334
0
  size_t i, path_len;
8335
8336
0
  path_len = strlen(path);
8337
8338
0
  for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
8339
0
    ext = path + (path_len - builtin_mime_types[i].ext_len);
8340
0
    if ((path_len > builtin_mime_types[i].ext_len)
8341
0
        && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
8342
0
      return builtin_mime_types[i].mime_type;
8343
0
    }
8344
0
  }
8345
8346
0
  return "text/plain";
8347
0
}
8348
8349
8350
/* Look at the "path" extension and figure what mime type it has.
8351
 * Store mime type in the vector. */
8352
static void
8353
get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
8354
0
{
8355
0
  struct vec ext_vec, mime_vec;
8356
0
  const char *list, *ext;
8357
0
  size_t path_len;
8358
8359
0
  path_len = strlen(path);
8360
8361
0
  if ((conn == NULL) || (vec == NULL)) {
8362
0
    if (vec != NULL) {
8363
0
      memset(vec, '\0', sizeof(struct vec));
8364
0
    }
8365
0
    return;
8366
0
  }
8367
8368
  /* Scan user-defined mime types first, in case user wants to
8369
   * override default mime types. */
8370
0
  list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
8371
0
  while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
8372
    /* ext now points to the path suffix */
8373
0
    ext = path + path_len - ext_vec.len;
8374
0
    if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
8375
0
      *vec = mime_vec;
8376
0
      return;
8377
0
    }
8378
0
  }
8379
8380
0
  vec->ptr = mg_get_builtin_mime_type(path);
8381
0
  vec->len = strlen(vec->ptr);
8382
0
}
8383
8384
8385
/* Stringify binary data. Output buffer must be twice as big as input,
8386
 * because each byte takes 2 bytes in string representation */
8387
static void
8388
bin2str(char *to, const unsigned char *p, size_t len)
8389
0
{
8390
0
  static const char *hex = "0123456789abcdef";
8391
8392
0
  for (; len--; p++) {
8393
0
    *to++ = hex[p[0] >> 4];
8394
0
    *to++ = hex[p[0] & 0x0f];
8395
0
  }
8396
0
  *to = '\0';
8397
0
}
8398
8399
8400
/* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
8401
 */
8402
CIVETWEB_API char *
8403
mg_md5(char buf[33], ...)
8404
0
{
8405
0
  md5_byte_t hash[16];
8406
0
  const char *p;
8407
0
  va_list ap;
8408
0
  md5_state_t ctx;
8409
8410
0
  md5_init(&ctx);
8411
8412
0
  va_start(ap, buf);
8413
0
  while ((p = va_arg(ap, const char *)) != NULL) {
8414
0
    md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
8415
0
  }
8416
0
  va_end(ap);
8417
8418
0
  md5_finish(&ctx, hash);
8419
0
  bin2str(buf, hash, sizeof(hash));
8420
0
  return buf;
8421
0
}
8422
8423
8424
/* Check the user's password, return 1 if OK */
8425
static int
8426
check_password_digest(const char *method,
8427
                      const char *ha1,
8428
                      const char *uri,
8429
                      const char *nonce,
8430
                      const char *nc,
8431
                      const char *cnonce,
8432
                      const char *qop,
8433
                      const char *response)
8434
0
{
8435
0
  char ha2[32 + 1], expected_response[32 + 1];
8436
8437
  /* Some of the parameters may be NULL */
8438
0
  if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
8439
0
      || (qop == NULL) || (response == NULL)) {
8440
0
    return 0;
8441
0
  }
8442
8443
  /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
8444
0
  if (strlen(response) != 32) {
8445
0
    return 0;
8446
0
  }
8447
8448
0
  mg_md5(ha2, method, ":", uri, NULL);
8449
0
  mg_md5(expected_response,
8450
0
         ha1,
8451
0
         ":",
8452
0
         nonce,
8453
0
         ":",
8454
0
         nc,
8455
0
         ":",
8456
0
         cnonce,
8457
0
         ":",
8458
0
         qop,
8459
0
         ":",
8460
0
         ha2,
8461
0
         NULL);
8462
8463
0
  return mg_strcasecmp(response, expected_response) == 0;
8464
0
}
8465
8466
8467
#if !defined(NO_FILESYSTEMS)
8468
/* Use the global passwords file, if specified by auth_gpass option,
8469
 * or search for .htpasswd in the requested directory. */
8470
static void
8471
open_auth_file(struct mg_connection *conn,
8472
               const char *path,
8473
               struct mg_file *filep)
8474
0
{
8475
0
  if ((conn != NULL) && (conn->dom_ctx != NULL)) {
8476
0
    char name[UTF8_PATH_MAX];
8477
0
    const char *p, *e,
8478
0
        *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
8479
0
    int truncated;
8480
8481
0
    if (gpass != NULL) {
8482
      /* Use global passwords file */
8483
0
      if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
8484
#if defined(DEBUG)
8485
        /* Use mg_cry_internal here, since gpass has been
8486
         * configured. */
8487
        mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
8488
#endif
8489
0
      }
8490
      /* Important: using local struct mg_file to test path for
8491
       * is_directory flag. If filep is used, mg_stat() makes it
8492
       * appear as if auth file was opened.
8493
       * TODO(mid): Check if this is still required after rewriting
8494
       * mg_stat */
8495
0
    } else if (mg_stat(conn, path, &filep->stat)
8496
0
               && filep->stat.is_directory) {
8497
0
      mg_snprintf(conn,
8498
0
                  &truncated,
8499
0
                  name,
8500
0
                  sizeof(name),
8501
0
                  "%s/%s",
8502
0
                  path,
8503
0
                  PASSWORDS_FILE_NAME);
8504
8505
0
      if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8506
#if defined(DEBUG)
8507
        /* Don't use mg_cry_internal here, but only a trace, since
8508
         * this is a typical case. It will occur for every directory
8509
         * without a password file. */
8510
        DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8511
#endif
8512
0
      }
8513
0
    } else {
8514
      /* Try to find .htpasswd in requested directory. */
8515
0
      for (p = path, e = p + strlen(p) - 1; e > p; e--) {
8516
0
        if (e[0] == '/') {
8517
0
          break;
8518
0
        }
8519
0
      }
8520
0
      mg_snprintf(conn,
8521
0
                  &truncated,
8522
0
                  name,
8523
0
                  sizeof(name),
8524
0
                  "%.*s/%s",
8525
0
                  (int)(e - p),
8526
0
                  p,
8527
0
                  PASSWORDS_FILE_NAME);
8528
8529
0
      if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8530
#if defined(DEBUG)
8531
        /* Don't use mg_cry_internal here, but only a trace, since
8532
         * this is a typical case. It will occur for every directory
8533
         * without a password file. */
8534
        DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8535
#endif
8536
0
      }
8537
0
    }
8538
0
  }
8539
0
}
8540
#endif /* NO_FILESYSTEMS */
8541
8542
8543
/* Parsed Authorization header */
8544
struct ah {
8545
  char *user;
8546
  int type;             /* 1 = basic, 2 = digest */
8547
  char *plain_password; /* Basic only */
8548
  char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
8549
};
8550
8551
8552
/* Return 1 on success. Always initializes the ah structure. */
8553
static int
8554
parse_auth_header(struct mg_connection *conn,
8555
                  char *buf,
8556
                  size_t buf_size,
8557
                  struct ah *ah)
8558
0
{
8559
0
  char *name, *value, *s;
8560
0
  const char *auth_header;
8561
0
  uint64_t nonce;
8562
8563
0
  if (!ah || !conn) {
8564
0
    return 0;
8565
0
  }
8566
8567
0
  (void)memset(ah, 0, sizeof(*ah));
8568
0
  auth_header = mg_get_header(conn, "Authorization");
8569
8570
0
  if (auth_header == NULL) {
8571
    /* No Authorization header at all */
8572
0
    return 0;
8573
0
  }
8574
0
  if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
8575
    /* Basic Auth (we never asked for this, but some client may send it) */
8576
0
    char *split;
8577
0
    const char *userpw_b64 = auth_header + 6;
8578
0
    size_t userpw_b64_len = strlen(userpw_b64);
8579
0
    size_t buf_len_r = buf_size;
8580
0
    if (mg_base64_decode(
8581
0
            userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
8582
0
        != -1) {
8583
0
      return 0; /* decode error */
8584
0
    }
8585
0
    split = strchr(buf, ':');
8586
0
    if (!split) {
8587
0
      return 0; /* Format error */
8588
0
    }
8589
8590
    /* Separate string at ':' */
8591
0
    *split = 0;
8592
8593
    /* User name is before ':', Password is after ':'  */
8594
0
    ah->user = buf;
8595
0
    ah->type = 1;
8596
0
    ah->plain_password = split + 1;
8597
8598
0
    return 1;
8599
8600
0
  } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
8601
    /* Digest Auth ... implemented below */
8602
0
    ah->type = 2;
8603
8604
0
  } else {
8605
    /* Unknown or invalid Auth method */
8606
0
    return 0;
8607
0
  }
8608
8609
  /* Make modifiable copy of the auth header */
8610
0
  (void)mg_strlcpy(buf, auth_header + 7, buf_size);
8611
0
  s = buf;
8612
8613
  /* Parse authorization header */
8614
0
  for (;;) {
8615
    /* Gobble initial spaces */
8616
0
    while (isspace((unsigned char)*s)) {
8617
0
      s++;
8618
0
    }
8619
0
    name = skip_quoted(&s, "=", " ", 0);
8620
    /* Value is either quote-delimited, or ends at first comma or space.
8621
     */
8622
0
    if (s[0] == '\"') {
8623
0
      s++;
8624
0
      value = skip_quoted(&s, "\"", " ", '\\');
8625
0
      if (s[0] == ',') {
8626
0
        s++;
8627
0
      }
8628
0
    } else {
8629
0
      value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
8630
                                              * uses spaces */
8631
0
    }
8632
0
    if (*name == '\0') {
8633
0
      break;
8634
0
    }
8635
8636
0
    if (!strcmp(name, "username")) {
8637
0
      ah->user = value;
8638
0
    } else if (!strcmp(name, "cnonce")) {
8639
0
      ah->cnonce = value;
8640
0
    } else if (!strcmp(name, "response")) {
8641
0
      ah->response = value;
8642
0
    } else if (!strcmp(name, "uri")) {
8643
0
      ah->uri = value;
8644
0
    } else if (!strcmp(name, "qop")) {
8645
0
      ah->qop = value;
8646
0
    } else if (!strcmp(name, "nc")) {
8647
0
      ah->nc = value;
8648
0
    } else if (!strcmp(name, "nonce")) {
8649
0
      ah->nonce = value;
8650
0
    }
8651
0
  }
8652
8653
0
#if !defined(NO_NONCE_CHECK)
8654
  /* Read the nonce from the response. */
8655
0
  if (ah->nonce == NULL) {
8656
0
    return 0;
8657
0
  }
8658
0
  s = NULL;
8659
0
  nonce = strtoull(ah->nonce, &s, 10);
8660
0
  if ((s == NULL) || (*s != 0)) {
8661
0
    return 0;
8662
0
  }
8663
8664
  /* Convert the nonce from the client to a number. */
8665
0
  nonce ^= conn->dom_ctx->auth_nonce_mask;
8666
8667
  /* The converted number corresponds to the time the nounce has been
8668
   * created. This should not be earlier than the server start. */
8669
  /* Server side nonce check is valuable in all situations but one:
8670
   * if the server restarts frequently, but the client should not see
8671
   * that, so the server should accept nonces from previous starts. */
8672
  /* However, the reasonable default is to not accept a nonce from a
8673
   * previous start, so if anyone changed the access rights between
8674
   * two restarts, a new login is required. */
8675
0
  if (nonce < (uint64_t)conn->phys_ctx->start_time) {
8676
    /* nonce is from a previous start of the server and no longer valid
8677
     * (replay attack?) */
8678
0
    return 0;
8679
0
  }
8680
  /* Check if the nonce is too high, so it has not (yet) been used by the
8681
   * server. */
8682
0
  if (nonce >= ((uint64_t)conn->phys_ctx->start_time
8683
0
                + conn->dom_ctx->nonce_count)) {
8684
0
    return 0;
8685
0
  }
8686
#else
8687
  (void)nonce;
8688
#endif
8689
8690
0
  return (ah->user != NULL);
8691
0
}
8692
8693
8694
static const char *
8695
mg_fgets(char *buf, size_t size, struct mg_file *filep)
8696
0
{
8697
0
  if (!filep) {
8698
0
    return NULL;
8699
0
  }
8700
8701
0
  if (filep->access.fp != NULL) {
8702
0
    return fgets(buf, (int)size, filep->access.fp);
8703
0
  } else {
8704
0
    return NULL;
8705
0
  }
8706
0
}
8707
8708
/* Define the initial recursion depth for procesesing htpasswd files that
8709
 * include other htpasswd
8710
 * (or even the same) files.  It is not difficult to provide a file or files
8711
 * s.t. they force civetweb
8712
 * to infinitely recurse and then crash.
8713
 */
8714
0
#define INITIAL_DEPTH 9
8715
#if INITIAL_DEPTH <= 0
8716
#error Bad INITIAL_DEPTH for recursion, set to at least 1
8717
#endif
8718
8719
#if !defined(NO_FILESYSTEMS)
8720
struct read_auth_file_struct {
8721
  struct mg_connection *conn;
8722
  struct ah ah;
8723
  const char *domain;
8724
  char buf[256 + 256 + 40];
8725
  const char *f_user;
8726
  const char *f_domain;
8727
  const char *f_ha1;
8728
};
8729
8730
8731
static int
8732
read_auth_file(struct mg_file *filep,
8733
               struct read_auth_file_struct *workdata,
8734
               int depth)
8735
0
{
8736
0
  int is_authorized = 0;
8737
0
  struct mg_file fp;
8738
0
  size_t l;
8739
8740
0
  if (!filep || !workdata || (0 == depth)) {
8741
0
    return 0;
8742
0
  }
8743
8744
  /* Loop over passwords file */
8745
0
  while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
8746
0
    l = strlen(workdata->buf);
8747
0
    while (l > 0) {
8748
0
      if (isspace((unsigned char)workdata->buf[l - 1])
8749
0
          || iscntrl((unsigned char)workdata->buf[l - 1])) {
8750
0
        l--;
8751
0
        workdata->buf[l] = 0;
8752
0
      } else
8753
0
        break;
8754
0
    }
8755
0
    if (l < 1) {
8756
0
      continue;
8757
0
    }
8758
8759
0
    workdata->f_user = workdata->buf;
8760
8761
0
    if (workdata->f_user[0] == ':') {
8762
      /* user names may not contain a ':' and may not be empty,
8763
       * so lines starting with ':' may be used for a special purpose
8764
       */
8765
0
      if (workdata->f_user[1] == '#') {
8766
        /* :# is a comment */
8767
0
        continue;
8768
0
      } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
8769
0
        if (mg_fopen(workdata->conn,
8770
0
                     workdata->f_user + 9,
8771
0
                     MG_FOPEN_MODE_READ,
8772
0
                     &fp)) {
8773
0
          is_authorized = read_auth_file(&fp, workdata, depth - 1);
8774
0
          (void)mg_fclose(
8775
0
              &fp.access); /* ignore error on read only file */
8776
8777
          /* No need to continue processing files once we have a
8778
           * match, since nothing will reset it back
8779
           * to 0.
8780
           */
8781
0
          if (is_authorized) {
8782
0
            return is_authorized;
8783
0
          }
8784
0
        } else {
8785
0
          mg_cry_internal(workdata->conn,
8786
0
                          "%s: cannot open authorization file: %s",
8787
0
                          __func__,
8788
0
                          workdata->buf);
8789
0
        }
8790
0
        continue;
8791
0
      }
8792
      /* everything is invalid for the moment (might change in the
8793
       * future) */
8794
0
      mg_cry_internal(workdata->conn,
8795
0
                      "%s: syntax error in authorization file: %s",
8796
0
                      __func__,
8797
0
                      workdata->buf);
8798
0
      continue;
8799
0
    }
8800
8801
0
    workdata->f_domain = strchr(workdata->f_user, ':');
8802
0
    if (workdata->f_domain == NULL) {
8803
0
      mg_cry_internal(workdata->conn,
8804
0
                      "%s: syntax error in authorization file: %s",
8805
0
                      __func__,
8806
0
                      workdata->buf);
8807
0
      continue;
8808
0
    }
8809
0
    *(char *)(workdata->f_domain) = 0;
8810
0
    (workdata->f_domain)++;
8811
8812
0
    workdata->f_ha1 = strchr(workdata->f_domain, ':');
8813
0
    if (workdata->f_ha1 == NULL) {
8814
0
      mg_cry_internal(workdata->conn,
8815
0
                      "%s: syntax error in authorization file: %s",
8816
0
                      __func__,
8817
0
                      workdata->buf);
8818
0
      continue;
8819
0
    }
8820
0
    *(char *)(workdata->f_ha1) = 0;
8821
0
    (workdata->f_ha1)++;
8822
8823
0
    if (!strcmp(workdata->ah.user, workdata->f_user)
8824
0
        && !strcmp(workdata->domain, workdata->f_domain)) {
8825
0
      switch (workdata->ah.type) {
8826
0
      case 1: /* Basic */
8827
0
      {
8828
0
        char md5[33];
8829
0
        mg_md5(md5,
8830
0
               workdata->f_user,
8831
0
               ":",
8832
0
               workdata->domain,
8833
0
               ":",
8834
0
               workdata->ah.plain_password,
8835
0
               NULL);
8836
0
        return 0 == memcmp(workdata->f_ha1, md5, 33);
8837
0
      }
8838
0
      case 2: /* Digest */
8839
0
        return check_password_digest(
8840
0
            workdata->conn->request_info.request_method,
8841
0
            workdata->f_ha1,
8842
0
            workdata->ah.uri,
8843
0
            workdata->ah.nonce,
8844
0
            workdata->ah.nc,
8845
0
            workdata->ah.cnonce,
8846
0
            workdata->ah.qop,
8847
0
            workdata->ah.response);
8848
0
      default: /* None/Other/Unknown */
8849
0
        return 0;
8850
0
      }
8851
0
    }
8852
0
  }
8853
8854
0
  return is_authorized;
8855
0
}
8856
8857
8858
/* Authorize against the opened passwords file. Return 1 if authorized. */
8859
static int
8860
authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
8861
0
{
8862
0
  struct read_auth_file_struct workdata;
8863
0
  char buf[MG_BUF_LEN];
8864
8865
0
  if (!conn || !conn->dom_ctx) {
8866
0
    return 0;
8867
0
  }
8868
8869
0
  memset(&workdata, 0, sizeof(workdata));
8870
0
  workdata.conn = conn;
8871
8872
0
  if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
8873
0
    return 0;
8874
0
  }
8875
8876
  /* CGI needs it as REMOTE_USER */
8877
0
  conn->request_info.remote_user =
8878
0
      mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
8879
8880
0
  if (realm) {
8881
0
    workdata.domain = realm;
8882
0
  } else {
8883
0
    workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
8884
0
  }
8885
8886
0
  return read_auth_file(filep, &workdata, INITIAL_DEPTH);
8887
0
}
8888
8889
8890
/* Public function to check http digest authentication header */
8891
CIVETWEB_API int
8892
mg_check_digest_access_authentication(struct mg_connection *conn,
8893
                                      const char *realm,
8894
                                      const char *filename)
8895
0
{
8896
0
  struct mg_file file = STRUCT_FILE_INITIALIZER;
8897
0
  int auth;
8898
8899
0
  if (!conn || !filename) {
8900
0
    return -1;
8901
0
  }
8902
0
  if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
8903
0
    return -2;
8904
0
  }
8905
8906
0
  auth = authorize(conn, &file, realm);
8907
8908
0
  mg_fclose(&file.access);
8909
8910
0
  return auth;
8911
0
}
8912
#endif /* NO_FILESYSTEMS */
8913
8914
8915
/* Return 1 if request is authorised, 0 otherwise. */
8916
static int
8917
check_authorization(struct mg_connection *conn, const char *path)
8918
0
{
8919
0
#if !defined(NO_FILESYSTEMS)
8920
0
  char fname[UTF8_PATH_MAX];
8921
0
  struct vec uri_vec, filename_vec;
8922
0
  const char *list;
8923
0
  struct mg_file file = STRUCT_FILE_INITIALIZER;
8924
0
  int authorized = 1, truncated;
8925
8926
0
  if (!conn || !conn->dom_ctx) {
8927
0
    return 0;
8928
0
  }
8929
8930
0
  list = conn->dom_ctx->config[PROTECT_URI];
8931
0
  while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
8932
0
    if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
8933
0
      mg_snprintf(conn,
8934
0
                  &truncated,
8935
0
                  fname,
8936
0
                  sizeof(fname),
8937
0
                  "%.*s",
8938
0
                  (int)filename_vec.len,
8939
0
                  filename_vec.ptr);
8940
8941
0
      if (truncated
8942
0
          || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
8943
0
        mg_cry_internal(conn,
8944
0
                        "%s: cannot open %s: %s",
8945
0
                        __func__,
8946
0
                        fname,
8947
0
                        strerror(errno));
8948
0
      }
8949
0
      break;
8950
0
    }
8951
0
  }
8952
8953
0
  if (!is_file_opened(&file.access)) {
8954
0
    open_auth_file(conn, path, &file);
8955
0
  }
8956
8957
0
  if (is_file_opened(&file.access)) {
8958
0
    authorized = authorize(conn, &file, NULL);
8959
0
    (void)mg_fclose(&file.access); /* ignore error on read only file */
8960
0
  }
8961
8962
0
  return authorized;
8963
#else
8964
  (void)conn;
8965
  (void)path;
8966
  return 1;
8967
#endif /* NO_FILESYSTEMS */
8968
0
}
8969
8970
8971
/* Internal function. Assumes conn is valid */
8972
static void
8973
send_authorization_request(struct mg_connection *conn, const char *realm)
8974
0
{
8975
0
  uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
8976
0
  int trunc = 0;
8977
0
  char buf[128];
8978
8979
0
  if (!realm) {
8980
0
    realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
8981
0
  }
8982
8983
0
  mg_lock_context(conn->phys_ctx);
8984
0
  nonce += conn->dom_ctx->nonce_count;
8985
0
  ++conn->dom_ctx->nonce_count;
8986
0
  mg_unlock_context(conn->phys_ctx);
8987
8988
0
  nonce ^= conn->dom_ctx->auth_nonce_mask;
8989
0
  conn->must_close = 1;
8990
8991
  /* Create 401 response */
8992
0
  mg_response_header_start(conn, 401);
8993
0
  send_no_cache_header(conn);
8994
0
  send_additional_header(conn);
8995
0
  mg_response_header_add(conn, "Content-Length", "0", -1);
8996
8997
  /* Content for "WWW-Authenticate" header */
8998
0
  mg_snprintf(conn,
8999
0
              &trunc,
9000
0
              buf,
9001
0
              sizeof(buf),
9002
0
              "Digest qop=\"auth\", realm=\"%s\", "
9003
0
              "nonce=\"%" UINT64_FMT "\"",
9004
0
              realm,
9005
0
              nonce);
9006
9007
0
  if (!trunc) {
9008
    /* !trunc should always be true */
9009
0
    mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
9010
0
  }
9011
9012
  /* Send all headers */
9013
0
  mg_response_header_send(conn);
9014
0
}
9015
9016
9017
/* Interface function. Parameters are provided by the user, so do
9018
 * at least some basic checks.
9019
 */
9020
CIVETWEB_API int
9021
mg_send_digest_access_authentication_request(struct mg_connection *conn,
9022
                                             const char *realm)
9023
0
{
9024
0
  if (conn && conn->dom_ctx) {
9025
0
    send_authorization_request(conn, realm);
9026
0
    return 0;
9027
0
  }
9028
0
  return -1;
9029
0
}
9030
9031
9032
#if !defined(NO_FILES)
9033
static int
9034
is_authorized_for_put(struct mg_connection *conn)
9035
0
{
9036
0
  int ret = 0;
9037
9038
0
  if (conn) {
9039
0
    struct mg_file file = STRUCT_FILE_INITIALIZER;
9040
0
    const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
9041
9042
0
    if (passfile != NULL
9043
0
        && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
9044
0
      ret = authorize(conn, &file, NULL);
9045
0
      (void)mg_fclose(&file.access); /* ignore error on read only file */
9046
0
    }
9047
0
  }
9048
9049
0
  DEBUG_TRACE("file write authorization: %i", ret);
9050
0
  return ret;
9051
0
}
9052
#endif
9053
9054
9055
CIVETWEB_API int
9056
mg_modify_passwords_file_ha1(const char *fname,
9057
                             const char *domain,
9058
                             const char *user,
9059
                             const char *ha1)
9060
0
{
9061
0
  int found = 0, i, result = 1;
9062
0
  char line[512], u[256], d[256], h[256];
9063
0
  struct stat st = {0};
9064
0
  FILE *fp = NULL;
9065
0
  char *temp_file = NULL;
9066
0
  int temp_file_offs = 0;
9067
9068
  /* Regard empty password as no password - remove user record. */
9069
0
  if ((ha1 != NULL) && (ha1[0] == '\0')) {
9070
0
    ha1 = NULL;
9071
0
  }
9072
9073
  /* Other arguments must not be empty */
9074
0
  if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
9075
0
    return 0;
9076
0
  }
9077
9078
  /* Using the given file format, user name and domain must not contain
9079
   * the ':' character */
9080
0
  if (strchr(user, ':') != NULL) {
9081
0
    return 0;
9082
0
  }
9083
0
  if (strchr(domain, ':') != NULL) {
9084
0
    return 0;
9085
0
  }
9086
9087
  /* Do not allow control characters like newline in user name and domain.
9088
   * Do not allow excessively long names either. */
9089
0
  for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
9090
0
    if (iscntrl((unsigned char)user[i])) {
9091
0
      return 0;
9092
0
    }
9093
0
  }
9094
0
  if (user[i]) {
9095
0
    return 0; /* user name too long */
9096
0
  }
9097
0
  for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
9098
0
    if (iscntrl((unsigned char)domain[i])) {
9099
0
      return 0;
9100
0
    }
9101
0
  }
9102
0
  if (domain[i]) {
9103
0
    return 0; /* domain name too long */
9104
0
  }
9105
9106
  /* The maximum length of the path to the password file is limited */
9107
0
  if (strlen(fname) >= UTF8_PATH_MAX) {
9108
0
    return 0;
9109
0
  }
9110
9111
  /* Check if the file exists, and get file size */
9112
0
  if (0 == stat(fname, &st)) {
9113
0
    int temp_buf_len = (int)st.st_size + 1024;
9114
9115
    /* Allocate memory (instead of using a temporary file) */
9116
0
    temp_file = (char *)mg_calloc(temp_buf_len, 1);
9117
0
    if (!temp_file) {
9118
      /* Out of memory */
9119
0
      return 0;
9120
0
    }
9121
9122
    /* File exists. Read it into a memory buffer. */
9123
0
    fp = fopen(fname, "r");
9124
0
    if (fp == NULL) {
9125
      /* Cannot read file. No permission? */
9126
0
      mg_free(temp_file);
9127
0
      return 0;
9128
0
    }
9129
9130
    /* Read content and store in memory */
9131
0
    while ((fgets(line, sizeof(line), fp) != NULL)
9132
0
           && ((temp_file_offs + 600) < temp_buf_len)) {
9133
      /* file format is "user:domain:hash\n" */
9134
0
      if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
9135
0
        continue;
9136
0
      }
9137
0
      u[255] = 0;
9138
0
      d[255] = 0;
9139
0
      h[255] = 0;
9140
9141
0
      if (!strcmp(u, user) && !strcmp(d, domain)) {
9142
        /* Found the user: change the password hash or drop the user
9143
         */
9144
0
        if ((ha1 != NULL) && (!found)) {
9145
0
          i = sprintf(temp_file + temp_file_offs,
9146
0
                      "%s:%s:%s\n",
9147
0
                      user,
9148
0
                      domain,
9149
0
                      ha1);
9150
0
          if (i < 1) {
9151
0
            fclose(fp);
9152
0
            mg_free(temp_file);
9153
0
            return 0;
9154
0
          }
9155
0
          temp_file_offs += i;
9156
0
        }
9157
0
        found = 1;
9158
0
      } else {
9159
        /* Copy existing user, including password hash */
9160
0
        i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
9161
0
        if (i < 1) {
9162
0
          fclose(fp);
9163
0
          mg_free(temp_file);
9164
0
          return 0;
9165
0
        }
9166
0
        temp_file_offs += i;
9167
0
      }
9168
0
    }
9169
0
    fclose(fp);
9170
0
  }
9171
9172
  /* Create new file */
9173
0
  fp = fopen(fname, "w");
9174
0
  if (!fp) {
9175
0
    mg_free(temp_file);
9176
0
    return 0;
9177
0
  }
9178
9179
0
#if !defined(_WIN32)
9180
  /* On Linux & co., restrict file read/write permissions to the owner */
9181
0
  if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
9182
0
    result = 0;
9183
0
  }
9184
0
#endif
9185
9186
0
  if ((temp_file != NULL) && (temp_file_offs > 0)) {
9187
    /* Store buffered content of old file */
9188
0
    if (fwrite(temp_file, 1, temp_file_offs, fp)
9189
0
        != (size_t)temp_file_offs) {
9190
0
      result = 0;
9191
0
    }
9192
0
  }
9193
9194
  /* If new user, just add it */
9195
0
  if ((ha1 != NULL) && (!found)) {
9196
0
    if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
9197
0
      result = 0;
9198
0
    }
9199
0
  }
9200
9201
  /* All data written */
9202
0
  if (fclose(fp) != 0) {
9203
0
    result = 0;
9204
0
  }
9205
9206
0
  mg_free(temp_file);
9207
0
  return result;
9208
0
}
9209
9210
9211
CIVETWEB_API int
9212
mg_modify_passwords_file(const char *fname,
9213
                         const char *domain,
9214
                         const char *user,
9215
                         const char *pass)
9216
0
{
9217
0
  char ha1buf[33];
9218
0
  if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
9219
0
    return 0;
9220
0
  }
9221
0
  if ((pass == NULL) || (pass[0] == 0)) {
9222
0
    return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
9223
0
  }
9224
9225
0
  mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
9226
0
  return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
9227
0
}
9228
9229
9230
static int
9231
is_valid_port(unsigned long port)
9232
38
{
9233
38
  return (port <= 0xffff);
9234
38
}
9235
9236
9237
static int
9238
mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
9239
34
{
9240
34
  struct addrinfo hints, *res, *ressave;
9241
34
  int func_ret = 0;
9242
34
  int gai_ret;
9243
9244
34
  memset(&hints, 0, sizeof(struct addrinfo));
9245
34
  hints.ai_family = af;
9246
34
  if (!resolve_src) {
9247
0
    hints.ai_flags = AI_NUMERICHOST;
9248
0
  }
9249
9250
34
  gai_ret = getaddrinfo(src, NULL, &hints, &res);
9251
34
  if (gai_ret != 0) {
9252
    /* gai_strerror could be used to convert gai_ret to a string */
9253
    /* POSIX return values: see
9254
     * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
9255
     */
9256
    /* Windows return values: see
9257
     * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
9258
     */
9259
0
    return 0;
9260
0
  }
9261
9262
34
  ressave = res;
9263
9264
136
  while (res) {
9265
102
    if ((dstlen >= (size_t)res->ai_addrlen)
9266
102
        && (res->ai_addr->sa_family == af)) {
9267
102
      memcpy(dst, res->ai_addr, res->ai_addrlen);
9268
102
      func_ret = 1;
9269
102
    }
9270
102
    res = res->ai_next;
9271
102
  }
9272
9273
34
  freeaddrinfo(ressave);
9274
34
  return func_ret;
9275
34
}
9276
9277
9278
static int
9279
connect_socket(
9280
    struct mg_context *ctx /* may be NULL */,
9281
    const char *host,
9282
    int port,    /* 1..65535, or -99 for domain sockets (may be changed) */
9283
    int use_ssl, /* 0 or 1 */
9284
    struct mg_error_data *error,
9285
    SOCKET *sock /* output: socket, must not be NULL */,
9286
    union usa *sa /* output: socket address, must not be NULL  */
9287
)
9288
34
{
9289
34
  int ip_ver = 0;
9290
34
  int conn_ret = -1;
9291
34
  int sockerr = 0;
9292
34
  *sock = INVALID_SOCKET;
9293
34
  memset(sa, 0, sizeof(*sa));
9294
9295
34
  if (host == NULL) {
9296
0
    if (error != NULL) {
9297
0
      error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
9298
0
      mg_snprintf(NULL,
9299
0
                  NULL, /* No truncation check for ebuf */
9300
0
                  error->text,
9301
0
                  error->text_buffer_size,
9302
0
                  "%s",
9303
0
                  "NULL host");
9304
0
    }
9305
0
    return 0;
9306
0
  }
9307
9308
#if defined(USE_X_DOM_SOCKET)
9309
  if (port == -99) {
9310
    /* Unix domain socket */
9311
    size_t hostlen = strlen(host);
9312
    if (hostlen >= sizeof(sa->sun.sun_path)) {
9313
      if (error != NULL) {
9314
        error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
9315
        mg_snprintf(NULL,
9316
                    NULL, /* No truncation check for ebuf */
9317
                    error->text,
9318
                    error->text_buffer_size,
9319
                    "%s",
9320
                    "host length exceeds limit");
9321
      }
9322
      return 0;
9323
    }
9324
  } else
9325
#endif
9326
34
      if ((port <= 0) || !is_valid_port((unsigned)port)) {
9327
0
    if (error != NULL) {
9328
0
      error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
9329
0
      mg_snprintf(NULL,
9330
0
                  NULL, /* No truncation check for ebuf */
9331
0
                  error->text,
9332
0
                  error->text_buffer_size,
9333
0
                  "%s",
9334
0
                  "invalid port");
9335
0
    }
9336
0
    return 0;
9337
0
  }
9338
9339
34
#if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
9340
34
#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
9341
34
  if (use_ssl && (TLS_client_method == NULL)) {
9342
0
    if (error != NULL) {
9343
0
      error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
9344
0
      mg_snprintf(NULL,
9345
0
                  NULL, /* No truncation check for ebuf */
9346
0
                  error->text,
9347
0
                  error->text_buffer_size,
9348
0
                  "%s",
9349
0
                  "SSL is not initialized");
9350
0
    }
9351
0
    return 0;
9352
0
  }
9353
#else
9354
  if (use_ssl && (SSLv23_client_method == NULL)) {
9355
    if (error != 0) {
9356
      error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
9357
      mg_snprintf(NULL,
9358
                  NULL, /* No truncation check for ebuf */
9359
                  error->text,
9360
                  error->text_buffer_size,
9361
                  "%s",
9362
                  "SSL is not initialized");
9363
    }
9364
    return 0;
9365
  }
9366
#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
9367
#else
9368
  (void)use_ssl;
9369
#endif /* NO SSL */
9370
9371
#if defined(USE_X_DOM_SOCKET)
9372
  if (port == -99) {
9373
    size_t hostlen = strlen(host);
9374
    /* check (hostlen < sizeof(sun.sun_path)) already passed above */
9375
    ip_ver = -99;
9376
    sa->sun.sun_family = AF_UNIX;
9377
    memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
9378
    memcpy(sa->sun.sun_path, host, hostlen);
9379
  } else
9380
#endif
9381
34
      if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
9382
34
    sa->sin.sin_port = htons((uint16_t)port);
9383
34
    ip_ver = 4;
9384
#if defined(USE_IPV6)
9385
  } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
9386
    sa->sin6.sin6_port = htons((uint16_t)port);
9387
    ip_ver = 6;
9388
  } else if (host[0] == '[') {
9389
    /* While getaddrinfo on Windows will work with [::1],
9390
     * getaddrinfo on Linux only works with ::1 (without []). */
9391
    size_t l = strlen(host + 1);
9392
    char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
9393
    if (h) {
9394
      h[l - 1] = 0;
9395
      if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
9396
        sa->sin6.sin6_port = htons((uint16_t)port);
9397
        ip_ver = 6;
9398
      }
9399
      mg_free(h);
9400
    }
9401
#endif
9402
34
  }
9403
9404
34
  if (ip_ver == 0) {
9405
0
    if (error != NULL) {
9406
0
      error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
9407
0
      mg_snprintf(NULL,
9408
0
                  NULL, /* No truncation check for ebuf */
9409
0
                  error->text,
9410
0
                  error->text_buffer_size,
9411
0
                  "%s",
9412
0
                  "host not found");
9413
0
    }
9414
0
    return 0;
9415
0
  }
9416
9417
34
  if (ip_ver == 4) {
9418
34
    *sock = socket(PF_INET, SOCK_STREAM, 0);
9419
34
  }
9420
#if defined(USE_IPV6)
9421
  else if (ip_ver == 6) {
9422
    *sock = socket(PF_INET6, SOCK_STREAM, 0);
9423
  }
9424
#endif
9425
#if defined(USE_X_DOM_SOCKET)
9426
  else if (ip_ver == -99) {
9427
    *sock = socket(AF_UNIX, SOCK_STREAM, 0);
9428
  }
9429
#endif
9430
9431
34
  if (*sock == INVALID_SOCKET) {
9432
0
    if (error != NULL) {
9433
0
      error->code = MG_ERROR_DATA_CODE_OS_ERROR;
9434
0
      error->code_sub = ERRNO;
9435
0
      mg_snprintf(NULL,
9436
0
                  NULL, /* No truncation check for ebuf */
9437
0
                  error->text,
9438
0
                  error->text_buffer_size,
9439
0
                  "socket(): %s",
9440
0
                  strerror(ERRNO));
9441
0
    }
9442
0
    return 0;
9443
0
  }
9444
9445
34
  if (0 != set_non_blocking_mode(*sock)) {
9446
0
    if (error != NULL) {
9447
0
      error->code = MG_ERROR_DATA_CODE_OS_ERROR;
9448
0
      error->code_sub = ERRNO;
9449
0
      mg_snprintf(NULL,
9450
0
                  NULL, /* No truncation check for ebuf */
9451
0
                  error->text,
9452
0
                  error->text_buffer_size,
9453
0
                  "Cannot set socket to non-blocking: %s",
9454
0
                  strerror(ERRNO));
9455
0
    }
9456
0
    closesocket(*sock);
9457
0
    *sock = INVALID_SOCKET;
9458
0
    return 0;
9459
0
  }
9460
9461
34
  set_close_on_exec(*sock, NULL, ctx);
9462
9463
34
  if (ip_ver == 4) {
9464
    /* connected with IPv4 */
9465
34
    conn_ret = connect(*sock,
9466
34
                       (struct sockaddr *)((void *)&sa->sin),
9467
34
                       sizeof(sa->sin));
9468
34
  }
9469
#if defined(USE_IPV6)
9470
  else if (ip_ver == 6) {
9471
    /* connected with IPv6 */
9472
    conn_ret = connect(*sock,
9473
                       (struct sockaddr *)((void *)&sa->sin6),
9474
                       sizeof(sa->sin6));
9475
  }
9476
#endif
9477
#if defined(USE_X_DOM_SOCKET)
9478
  else if (ip_ver == -99) {
9479
    /* connected to domain socket */
9480
    conn_ret = connect(*sock,
9481
                       (struct sockaddr *)((void *)&sa->sun),
9482
                       sizeof(sa->sun));
9483
  }
9484
#endif
9485
9486
34
  if (conn_ret != 0) {
9487
34
    sockerr = ERRNO;
9488
34
  }
9489
9490
#if defined(_WIN32)
9491
  if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
9492
#else
9493
34
  if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
9494
34
#endif
9495
    /* Data for getsockopt */
9496
34
    void *psockerr = &sockerr;
9497
34
    int ret;
9498
9499
#if defined(_WIN32)
9500
    int len = (int)sizeof(sockerr);
9501
#else
9502
34
    socklen_t len = (socklen_t)sizeof(sockerr);
9503
34
#endif
9504
9505
    /* Data for poll */
9506
34
    struct mg_pollfd pfd[1];
9507
34
    int pollres;
9508
34
    int ms_wait = 10000; /* 10 second timeout */
9509
34
    stop_flag_t nonstop;
9510
34
    STOP_FLAG_ASSIGN(&nonstop, 0);
9511
9512
    /* For a non-blocking socket, the connect sequence is:
9513
     * 1) call connect (will not block)
9514
     * 2) wait until the socket is ready for writing (select or poll)
9515
     * 3) check connection state with getsockopt
9516
     */
9517
34
    pfd[0].fd = *sock;
9518
34
    pfd[0].events = POLLOUT;
9519
34
    pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
9520
9521
34
    if (pollres != 1) {
9522
      /* Not connected */
9523
0
      if (error != NULL) {
9524
0
        error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
9525
0
        mg_snprintf(NULL,
9526
0
                    NULL, /* No truncation check for ebuf */
9527
0
                    error->text,
9528
0
                    error->text_buffer_size,
9529
0
                    "connect(%s:%d): timeout",
9530
0
                    host,
9531
0
                    port);
9532
0
      }
9533
0
      closesocket(*sock);
9534
0
      *sock = INVALID_SOCKET;
9535
0
      return 0;
9536
0
    }
9537
9538
#if defined(_WIN32)
9539
    ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
9540
#else
9541
34
    ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
9542
34
#endif
9543
9544
34
    if ((ret == 0) && (sockerr == 0)) {
9545
34
      conn_ret = 0;
9546
34
    }
9547
34
  }
9548
9549
34
  if (conn_ret != 0) {
9550
    /* Not connected */
9551
0
    if (error != NULL) {
9552
0
      error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
9553
0
      error->code_sub = ERRNO;
9554
0
      mg_snprintf(NULL,
9555
0
                  NULL, /* No truncation check for ebuf */
9556
0
                  error->text,
9557
0
                  error->text_buffer_size,
9558
0
                  "connect(%s:%d): error %s",
9559
0
                  host,
9560
0
                  port,
9561
0
                  strerror(sockerr));
9562
0
    }
9563
0
    closesocket(*sock);
9564
0
    *sock = INVALID_SOCKET;
9565
0
    return 0;
9566
0
  }
9567
9568
34
  return 1;
9569
34
}
9570
9571
9572
CIVETWEB_API int
9573
mg_url_encode(const char *src, char *dst, size_t dst_len)
9574
0
{
9575
0
  static const char *dont_escape = "._-$,;~()";
9576
0
  static const char *hex = "0123456789abcdef";
9577
0
  char *pos = dst;
9578
0
  const char *end = dst + dst_len - 1;
9579
9580
0
  for (; ((*src != '\0') && (pos < end)); src++, pos++) {
9581
0
    if (isalnum((unsigned char)*src)
9582
0
        || (strchr(dont_escape, *src) != NULL)) {
9583
0
      *pos = *src;
9584
0
    } else if (pos + 2 < end) {
9585
0
      pos[0] = '%';
9586
0
      pos[1] = hex[(unsigned char)*src >> 4];
9587
0
      pos[2] = hex[(unsigned char)*src & 0xf];
9588
0
      pos += 2;
9589
0
    } else {
9590
0
      break;
9591
0
    }
9592
0
  }
9593
9594
0
  *pos = '\0';
9595
0
  return (*src == '\0') ? (int)(pos - dst) : -1;
9596
0
}
9597
9598
/* Return 0 on success, non-zero if an error occurs. */
9599
9600
static int
9601
print_dir_entry(struct mg_connection *conn, struct de *de)
9602
0
{
9603
0
  size_t namesize, escsize, i;
9604
0
  char *href, *esc, *p;
9605
0
  char size[64], mod[64];
9606
#if defined(REENTRANT_TIME)
9607
  struct tm _tm;
9608
  struct tm *tm = &_tm;
9609
#else
9610
0
  struct tm *tm;
9611
0
#endif
9612
9613
  /* Estimate worst case size for encoding and escaping */
9614
0
  namesize = strlen(de->file_name) + 1;
9615
0
  escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
9616
0
  href = (char *)mg_malloc(namesize * 3 + escsize);
9617
0
  if (href == NULL) {
9618
0
    return -1;
9619
0
  }
9620
0
  mg_url_encode(de->file_name, href, namesize * 3);
9621
0
  esc = NULL;
9622
0
  if (escsize > 0) {
9623
    /* HTML escaping needed */
9624
0
    esc = href + namesize * 3;
9625
0
    for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
9626
0
      mg_strlcpy(p, de->file_name + i, 2);
9627
0
      if (*p == '&') {
9628
0
        strcpy(p, "&amp;");
9629
0
      } else if (*p == '<') {
9630
0
        strcpy(p, "&lt;");
9631
0
      } else if (*p == '>') {
9632
0
        strcpy(p, "&gt;");
9633
0
      }
9634
0
    }
9635
0
  }
9636
9637
0
  if (de->file.is_directory) {
9638
0
    mg_snprintf(conn,
9639
0
                NULL, /* Buffer is big enough */
9640
0
                size,
9641
0
                sizeof(size),
9642
0
                "%s",
9643
0
                "[DIRECTORY]");
9644
0
  } else {
9645
    /* We use (signed) cast below because MSVC 6 compiler cannot
9646
     * convert unsigned __int64 to double. Sigh. */
9647
0
    if (de->file.size < 1024) {
9648
0
      mg_snprintf(conn,
9649
0
                  NULL, /* Buffer is big enough */
9650
0
                  size,
9651
0
                  sizeof(size),
9652
0
                  "%d",
9653
0
                  (int)de->file.size);
9654
0
    } else if (de->file.size < 0x100000) {
9655
0
      mg_snprintf(conn,
9656
0
                  NULL, /* Buffer is big enough */
9657
0
                  size,
9658
0
                  sizeof(size),
9659
0
                  "%.1fk",
9660
0
                  (double)de->file.size / 1024.0);
9661
0
    } else if (de->file.size < 0x40000000) {
9662
0
      mg_snprintf(conn,
9663
0
                  NULL, /* Buffer is big enough */
9664
0
                  size,
9665
0
                  sizeof(size),
9666
0
                  "%.1fM",
9667
0
                  (double)de->file.size / 1048576);
9668
0
    } else {
9669
0
      mg_snprintf(conn,
9670
0
                  NULL, /* Buffer is big enough */
9671
0
                  size,
9672
0
                  sizeof(size),
9673
0
                  "%.1fG",
9674
0
                  (double)de->file.size / 1073741824);
9675
0
    }
9676
0
  }
9677
9678
  /* Note: mg_snprintf will not cause a buffer overflow above.
9679
   * So, string truncation checks are not required here. */
9680
9681
#if defined(REENTRANT_TIME)
9682
  localtime_r(&de->file.last_modified, tm);
9683
#else
9684
0
  tm = localtime(&de->file.last_modified);
9685
0
#endif
9686
0
  if (tm != NULL) {
9687
0
    strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
9688
0
  } else {
9689
0
    mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
9690
0
  }
9691
0
  mg_printf(conn,
9692
0
            "<tr><td><a href=\"%s%s\">%s%s</a></td>"
9693
0
            "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
9694
0
            href,
9695
0
            de->file.is_directory ? "/" : "",
9696
0
            esc ? esc : de->file_name,
9697
0
            de->file.is_directory ? "/" : "",
9698
0
            mod,
9699
0
            size);
9700
0
  mg_free(href);
9701
0
  return 0;
9702
0
}
9703
9704
9705
/* This function is called from send_directory() and used for
9706
 * sorting directory entries by size, name, or modification time. */
9707
static int
9708
compare_dir_entries(const void *p1, const void *p2, void *arg)
9709
0
{
9710
0
  const char *query_string = (const char *)(arg != NULL ? arg : "");
9711
0
  if (p1 && p2) {
9712
0
    const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
9713
0
    int cmp_result = 0;
9714
9715
0
    if ((query_string == NULL) || (query_string[0] == '\0')) {
9716
0
      query_string = "n";
9717
0
    }
9718
9719
    /* Sort Directories vs Files */
9720
0
    if (a->file.is_directory && !b->file.is_directory) {
9721
0
      return -1; /* Always put directories on top */
9722
0
    } else if (!a->file.is_directory && b->file.is_directory) {
9723
0
      return 1; /* Always put directories on top */
9724
0
    }
9725
9726
    /* Sort by size or date */
9727
0
    if (*query_string == 's') {
9728
0
      cmp_result = (a->file.size == b->file.size)
9729
0
                       ? 0
9730
0
                       : ((a->file.size > b->file.size) ? 1 : -1);
9731
0
    } else if (*query_string == 'd') {
9732
0
      cmp_result =
9733
0
          (a->file.last_modified == b->file.last_modified)
9734
0
              ? 0
9735
0
              : ((a->file.last_modified > b->file.last_modified) ? 1
9736
0
                                                                 : -1);
9737
0
    }
9738
9739
    /* Sort by name:
9740
     * if (*query_string == 'n')  ...
9741
     * but also sort files of same size/date by name as secondary criterion.
9742
     */
9743
0
    if (cmp_result == 0) {
9744
0
      cmp_result = strcmp(a->file_name, b->file_name);
9745
0
    }
9746
9747
    /* For descending order, invert result */
9748
0
    return (query_string[1] == 'd') ? -cmp_result : cmp_result;
9749
0
  }
9750
0
  return 0;
9751
0
}
9752
9753
9754
static int
9755
must_hide_file(struct mg_connection *conn, const char *path)
9756
0
{
9757
0
  if (conn && conn->dom_ctx) {
9758
0
    const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
9759
0
    const char *pattern = conn->dom_ctx->config[HIDE_FILES];
9760
0
    return (match_prefix_strlen(pw_pattern, path) > 0)
9761
0
           || (match_prefix_strlen(pattern, path) > 0);
9762
0
  }
9763
0
  return 0;
9764
0
}
9765
9766
9767
#if !defined(NO_FILESYSTEMS)
9768
static int
9769
scan_directory(struct mg_connection *conn,
9770
               const char *dir,
9771
               void *data,
9772
               int (*cb)(struct de *, void *))
9773
0
{
9774
0
  char path[UTF8_PATH_MAX];
9775
0
  struct dirent *dp;
9776
0
  DIR *dirp;
9777
0
  struct de de;
9778
0
  int truncated;
9779
9780
0
  if ((dirp = mg_opendir(conn, dir)) == NULL) {
9781
0
    return 0;
9782
0
  } else {
9783
9784
0
    while ((dp = mg_readdir(dirp)) != NULL) {
9785
      /* Do not show current dir and hidden files */
9786
0
      if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
9787
0
          || must_hide_file(conn, dp->d_name)) {
9788
0
        continue;
9789
0
      }
9790
9791
0
      mg_snprintf(
9792
0
          conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9793
9794
      /* If we don't memset stat structure to zero, mtime will have
9795
       * garbage and strftime() will segfault later on in
9796
       * print_dir_entry(). memset is required only if mg_stat()
9797
       * fails. For more details, see
9798
       * http://code.google.com/p/mongoose/issues/detail?id=79 */
9799
0
      memset(&de.file, 0, sizeof(de.file));
9800
9801
0
      if (truncated) {
9802
        /* If the path is not complete, skip processing. */
9803
0
        continue;
9804
0
      }
9805
9806
0
      if (!mg_stat(conn, path, &de.file)) {
9807
0
        mg_cry_internal(conn,
9808
0
                        "%s: mg_stat(%s) failed: %s",
9809
0
                        __func__,
9810
0
                        path,
9811
0
                        strerror(ERRNO));
9812
0
      }
9813
0
      de.file_name = dp->d_name;
9814
0
      if (cb(&de, data)) {
9815
        /* stopped */
9816
0
        break;
9817
0
      }
9818
0
    }
9819
0
    (void)mg_closedir(dirp);
9820
0
  }
9821
0
  return 1;
9822
0
}
9823
#endif /* NO_FILESYSTEMS */
9824
9825
9826
#if !defined(NO_FILES)
9827
static int
9828
remove_directory(struct mg_connection *conn, const char *dir)
9829
0
{
9830
0
  char path[UTF8_PATH_MAX];
9831
0
  struct dirent *dp;
9832
0
  DIR *dirp;
9833
0
  struct de de;
9834
0
  int truncated;
9835
0
  int ok = 1;
9836
9837
0
  if ((dirp = mg_opendir(conn, dir)) == NULL) {
9838
0
    return 0;
9839
0
  } else {
9840
9841
0
    while ((dp = mg_readdir(dirp)) != NULL) {
9842
      /* Do not show current dir (but show hidden files as they will
9843
       * also be removed) */
9844
0
      if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
9845
0
        continue;
9846
0
      }
9847
9848
0
      mg_snprintf(
9849
0
          conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9850
9851
      /* If we don't memset stat structure to zero, mtime will have
9852
       * garbage and strftime() will segfault later on in
9853
       * print_dir_entry(). memset is required only if mg_stat()
9854
       * fails. For more details, see
9855
       * http://code.google.com/p/mongoose/issues/detail?id=79 */
9856
0
      memset(&de.file, 0, sizeof(de.file));
9857
9858
0
      if (truncated) {
9859
        /* Do not delete anything shorter */
9860
0
        ok = 0;
9861
0
        continue;
9862
0
      }
9863
9864
0
      if (!mg_stat(conn, path, &de.file)) {
9865
0
        mg_cry_internal(conn,
9866
0
                        "%s: mg_stat(%s) failed: %s",
9867
0
                        __func__,
9868
0
                        path,
9869
0
                        strerror(ERRNO));
9870
0
        ok = 0;
9871
0
      }
9872
9873
0
      if (de.file.is_directory) {
9874
0
        if (remove_directory(conn, path) == 0) {
9875
0
          ok = 0;
9876
0
        }
9877
0
      } else {
9878
        /* This will fail file is the file is in memory */
9879
0
        if (mg_remove(conn, path) == 0) {
9880
0
          ok = 0;
9881
0
        }
9882
0
      }
9883
0
    }
9884
0
    (void)mg_closedir(dirp);
9885
9886
0
    IGNORE_UNUSED_RESULT(rmdir(dir));
9887
0
  }
9888
9889
0
  return ok;
9890
0
}
9891
#endif
9892
9893
9894
struct dir_scan_data {
9895
  struct de *entries;
9896
  size_t num_entries;
9897
  size_t arr_size;
9898
};
9899
9900
9901
#if !defined(NO_FILESYSTEMS)
9902
static int
9903
dir_scan_callback(struct de *de, void *data)
9904
0
{
9905
0
  struct dir_scan_data *dsd = (struct dir_scan_data *)data;
9906
0
  struct de *entries = dsd->entries;
9907
9908
0
  if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
9909
    /* Here "entries" is a temporary pointer and can be replaced,
9910
     * "dsd->entries" is the original pointer */
9911
0
    entries =
9912
0
        (struct de *)mg_realloc(entries,
9913
0
                                dsd->arr_size * 2 * sizeof(entries[0]));
9914
0
    if (entries == NULL) {
9915
      /* stop scan */
9916
0
      return 1;
9917
0
    }
9918
0
    dsd->entries = entries;
9919
0
    dsd->arr_size *= 2;
9920
0
  }
9921
0
  entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
9922
0
  if (entries[dsd->num_entries].file_name == NULL) {
9923
    /* stop scan */
9924
0
    return 1;
9925
0
  }
9926
0
  entries[dsd->num_entries].file = de->file;
9927
0
  dsd->num_entries++;
9928
9929
0
  return 0;
9930
0
}
9931
9932
9933
static void
9934
handle_directory_request(struct mg_connection *conn, const char *dir)
9935
0
{
9936
0
  size_t i;
9937
0
  int sort_direction;
9938
0
  struct dir_scan_data data = {NULL, 0, 128};
9939
0
  char date[64], *esc, *p;
9940
0
  const char *title;
9941
0
  time_t curtime = time(NULL);
9942
9943
0
  if (!conn) {
9944
0
    return;
9945
0
  }
9946
9947
0
  if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
9948
0
    mg_send_http_error(conn,
9949
0
                       500,
9950
0
                       "Error: Cannot open directory\nopendir(%s): %s",
9951
0
                       dir,
9952
0
                       strerror(ERRNO));
9953
0
    return;
9954
0
  }
9955
9956
0
  gmt_time_string(date, sizeof(date), &curtime);
9957
9958
0
  esc = NULL;
9959
0
  title = conn->request_info.local_uri;
9960
0
  if (title[strcspn(title, "&<>")]) {
9961
    /* HTML escaping needed */
9962
0
    esc = (char *)mg_malloc(strlen(title) * 5 + 1);
9963
0
    if (esc) {
9964
0
      for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
9965
0
        mg_strlcpy(p, title + i, 2);
9966
0
        if (*p == '&') {
9967
0
          strcpy(p, "&amp;");
9968
0
        } else if (*p == '<') {
9969
0
          strcpy(p, "&lt;");
9970
0
        } else if (*p == '>') {
9971
0
          strcpy(p, "&gt;");
9972
0
        }
9973
0
      }
9974
0
    } else {
9975
0
      title = "";
9976
0
    }
9977
0
  }
9978
9979
0
  sort_direction = ((conn->request_info.query_string != NULL)
9980
0
                    && (conn->request_info.query_string[0] != '\0')
9981
0
                    && (conn->request_info.query_string[1] == 'd'))
9982
0
                       ? 'a'
9983
0
                       : 'd';
9984
9985
0
  conn->must_close = 1;
9986
9987
  /* Create 200 OK response */
9988
0
  mg_response_header_start(conn, 200);
9989
0
  send_static_cache_header(conn);
9990
0
  send_additional_header(conn);
9991
0
  mg_response_header_add(conn,
9992
0
                         "Content-Type",
9993
0
                         "text/html; charset=utf-8",
9994
0
                         -1);
9995
9996
  /* Send all headers */
9997
0
  mg_response_header_send(conn);
9998
9999
  /* Body */
10000
0
  mg_printf(conn,
10001
0
            "<html><head><title>Index of %s</title>"
10002
0
            "<style>th {text-align: left;}</style></head>"
10003
0
            "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
10004
0
            "<tr><th><a href=\"?n%c\">Name</a></th>"
10005
0
            "<th><a href=\"?d%c\">Modified</a></th>"
10006
0
            "<th><a href=\"?s%c\">Size</a></th></tr>"
10007
0
            "<tr><td colspan=\"3\"><hr></td></tr>",
10008
0
            esc ? esc : title,
10009
0
            esc ? esc : title,
10010
0
            sort_direction,
10011
0
            sort_direction,
10012
0
            sort_direction);
10013
0
  mg_free(esc);
10014
10015
  /* Print first entry - link to a parent directory */
10016
0
  mg_printf(conn,
10017
0
            "<tr><td><a href=\"%s\">%s</a></td>"
10018
0
            "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
10019
0
            "..",
10020
0
            "Parent directory",
10021
0
            "-",
10022
0
            "-");
10023
10024
  /* Sort and print directory entries */
10025
0
  if (data.entries != NULL) {
10026
0
    mg_sort(data.entries,
10027
0
            data.num_entries,
10028
0
            sizeof(data.entries[0]),
10029
0
            compare_dir_entries,
10030
0
            (void *)conn->request_info.query_string);
10031
0
    for (i = 0; i < data.num_entries; i++) {
10032
0
      print_dir_entry(conn, &data.entries[i]);
10033
0
      mg_free(data.entries[i].file_name);
10034
0
    }
10035
0
    mg_free(data.entries);
10036
0
  }
10037
10038
0
  mg_printf(conn, "%s", "</table></pre></body></html>");
10039
0
  conn->status_code = 200;
10040
0
}
10041
#endif /* NO_FILESYSTEMS */
10042
10043
10044
/* Send len bytes from the opened file to the client. */
10045
static void
10046
send_file_data(struct mg_connection *conn,
10047
               struct mg_file *filep,
10048
               int64_t offset,
10049
               int64_t len,
10050
               int no_buffering)
10051
0
{
10052
0
  char buf[MG_BUF_LEN];
10053
0
  int to_read, num_read, num_written;
10054
0
  int64_t size;
10055
10056
0
  if (!filep || !conn) {
10057
0
    return;
10058
0
  }
10059
10060
  /* Sanity check the offset */
10061
0
  size = (filep->stat.size > INT64_MAX) ? INT64_MAX
10062
0
                                        : (int64_t)(filep->stat.size);
10063
0
  offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
10064
10065
0
  if (len > 0 && filep->access.fp != NULL) {
10066
    /* file stored on disk */
10067
0
#if defined(__linux__)
10068
    /* sendfile is only available for Linux */
10069
0
    if ((conn->ssl == 0) && (conn->throttle == 0)
10070
0
        && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
10071
0
                           "yes"))) {
10072
0
      off_t sf_offs = (off_t)offset;
10073
0
      ssize_t sf_sent;
10074
0
      int sf_file = fileno(filep->access.fp);
10075
0
      int loop_cnt = 0;
10076
10077
0
      do {
10078
        /* 2147479552 (0x7FFFF000) is a limit found by experiment on
10079
         * 64 bit Linux (2^31 minus one memory page of 4k?). */
10080
0
        size_t sf_tosend =
10081
0
            (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
10082
0
        sf_sent =
10083
0
            sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
10084
0
        if (sf_sent > 0) {
10085
0
          len -= sf_sent;
10086
0
          offset += sf_sent;
10087
0
        } else if (loop_cnt == 0) {
10088
          /* This file can not be sent using sendfile.
10089
           * This might be the case for pseudo-files in the
10090
           * /sys/ and /proc/ file system.
10091
           * Use the regular user mode copy code instead. */
10092
0
          break;
10093
0
        } else if (sf_sent == 0) {
10094
          /* No error, but 0 bytes sent. May be EOF? */
10095
0
          return;
10096
0
        }
10097
0
        loop_cnt++;
10098
10099
0
      } while ((len > 0) && (sf_sent >= 0));
10100
10101
0
      if (sf_sent > 0) {
10102
0
        return; /* OK */
10103
0
      }
10104
10105
      /* sf_sent<0 means error, thus fall back to the classic way */
10106
      /* This is always the case, if sf_file is not a "normal" file,
10107
       * e.g., for sending data from the output of a CGI process. */
10108
0
      offset = (int64_t)sf_offs;
10109
0
    }
10110
0
#endif
10111
0
    if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
10112
0
      mg_cry_internal(conn,
10113
0
                      "%s: fseeko() failed: %s",
10114
0
                      __func__,
10115
0
                      strerror(ERRNO));
10116
0
      mg_send_http_error(
10117
0
          conn,
10118
0
          500,
10119
0
          "%s",
10120
0
          "Error: Unable to access file at requested position.");
10121
0
    } else {
10122
0
      while (len > 0) {
10123
        /* Calculate how much to read from the file into the buffer. */
10124
        /* If no_buffering is set, we should not wait until the
10125
         * CGI->Server buffer is filled, but send everything
10126
         * immediately. In theory buffering could be turned off using
10127
         * setbuf(filep->access.fp, NULL);
10128
         * setvbuf(filep->access.fp, NULL, _IONBF, 0);
10129
         * but in practice this does not work. A "Linux only" solution
10130
         * may be to use select(). The only portable way is to read byte
10131
         * by byte, but this is quite inefficient from a performance
10132
         * point of view. */
10133
0
        to_read = no_buffering ? 1 : sizeof(buf);
10134
0
        if ((int64_t)to_read > len) {
10135
0
          to_read = (int)len;
10136
0
        }
10137
10138
        /* Read from file, exit the loop on error */
10139
0
        if ((num_read =
10140
0
                 (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
10141
0
            <= 0) {
10142
0
          break;
10143
0
        }
10144
10145
        /* Send read bytes to the client, exit the loop on error */
10146
0
        if ((num_written = mg_write(conn, buf, (size_t)num_read))
10147
0
            != num_read) {
10148
0
          break;
10149
0
        }
10150
10151
        /* Both read and were successful, adjust counters */
10152
0
        len -= num_written;
10153
0
      }
10154
0
    }
10155
0
  }
10156
0
}
10157
10158
10159
static int
10160
parse_range_header(const char *header, int64_t *a, int64_t *b)
10161
0
{
10162
0
  return sscanf(header,
10163
0
                "bytes=%" INT64_FMT "-%" INT64_FMT,
10164
0
                a,
10165
0
                b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
10166
                    // to an integer value, but function will not report
10167
                    // conversion errors; consider using 'strtol' instead
10168
0
}
10169
10170
10171
static void
10172
construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
10173
0
{
10174
0
  if ((filestat != NULL) && (buf != NULL)) {
10175
0
    mg_snprintf(NULL,
10176
0
                NULL, /* All calls to construct_etag use 64 byte buffer */
10177
0
                buf,
10178
0
                buf_len,
10179
0
                "\"%lx.%" INT64_FMT "\"",
10180
0
                (unsigned long)filestat->last_modified,
10181
0
                filestat->size);
10182
0
  }
10183
0
}
10184
10185
10186
static void
10187
fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
10188
0
{
10189
0
  if (filep != NULL && filep->fp != NULL) {
10190
#if defined(_WIN32)
10191
    (void)conn; /* Unused. */
10192
#else
10193
0
    if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
10194
0
      mg_cry_internal(conn,
10195
0
                      "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
10196
0
                      __func__,
10197
0
                      strerror(ERRNO));
10198
0
    }
10199
0
#endif
10200
0
  }
10201
0
}
10202
10203
10204
#if defined(USE_ZLIB)
10205
#include "mod_zlib.inl"
10206
#endif
10207
10208
10209
#if !defined(NO_FILESYSTEMS)
10210
static void
10211
handle_static_file_request(struct mg_connection *conn,
10212
                           const char *path,
10213
                           struct mg_file *filep,
10214
                           const char *mime_type,
10215
                           const char *additional_headers)
10216
0
{
10217
0
  char lm[64], etag[64];
10218
0
  char range[128]; /* large enough, so there will be no overflow */
10219
0
  const char *range_hdr;
10220
0
  int64_t cl, r1, r2;
10221
0
  struct vec mime_vec;
10222
0
  int n, truncated;
10223
0
  char gz_path[UTF8_PATH_MAX];
10224
0
  const char *encoding = 0;
10225
0
  int is_head_request;
10226
10227
#if defined(USE_ZLIB)
10228
  /* Compression is allowed, unless there is a reason not to use
10229
   * compression. If the file is already compressed, too small or a
10230
   * "range" request was made, on the fly compression is not possible. */
10231
  int allow_on_the_fly_compression = 1;
10232
#endif
10233
10234
0
  if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
10235
0
    return;
10236
0
  }
10237
10238
0
  is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
10239
10240
0
  if (mime_type == NULL) {
10241
0
    get_mime_type(conn, path, &mime_vec);
10242
0
  } else {
10243
0
    mime_vec.ptr = mime_type;
10244
0
    mime_vec.len = strlen(mime_type);
10245
0
  }
10246
0
  if (filep->stat.size > INT64_MAX) {
10247
0
    mg_send_http_error(conn,
10248
0
                       500,
10249
0
                       "Error: File size is too large to send\n%" INT64_FMT,
10250
0
                       filep->stat.size);
10251
0
    return;
10252
0
  }
10253
0
  cl = (int64_t)filep->stat.size;
10254
0
  conn->status_code = 200;
10255
0
  range[0] = '\0';
10256
10257
#if defined(USE_ZLIB)
10258
  /* if this file is in fact a pre-gzipped file, rewrite its filename
10259
   * it's important to rewrite the filename after resolving
10260
   * the mime type from it, to preserve the actual file's type */
10261
  if (!conn->accept_gzip) {
10262
    allow_on_the_fly_compression = 0;
10263
  }
10264
#endif
10265
10266
  /* Check if there is a range header */
10267
0
  range_hdr = mg_get_header(conn, "Range");
10268
10269
  /* For gzipped files, add *.gz */
10270
0
  if (filep->stat.is_gzipped) {
10271
0
    mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
10272
10273
0
    if (truncated) {
10274
0
      mg_send_http_error(conn,
10275
0
                         500,
10276
0
                         "Error: Path of zipped file too long (%s)",
10277
0
                         path);
10278
0
      return;
10279
0
    }
10280
10281
0
    path = gz_path;
10282
0
    encoding = "gzip";
10283
10284
#if defined(USE_ZLIB)
10285
    /* File is already compressed. No "on the fly" compression. */
10286
    allow_on_the_fly_compression = 0;
10287
#endif
10288
0
  } else if ((conn->accept_gzip) && (range_hdr == NULL)
10289
0
             && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
10290
0
    struct mg_file_stat file_stat;
10291
10292
0
    mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
10293
10294
0
    if (!truncated && mg_stat(conn, gz_path, &file_stat)
10295
0
        && !file_stat.is_directory) {
10296
0
      file_stat.is_gzipped = 1;
10297
0
      filep->stat = file_stat;
10298
0
      cl = (int64_t)filep->stat.size;
10299
0
      path = gz_path;
10300
0
      encoding = "gzip";
10301
10302
#if defined(USE_ZLIB)
10303
      /* File is already compressed. No "on the fly" compression. */
10304
      allow_on_the_fly_compression = 0;
10305
#endif
10306
0
    }
10307
0
  }
10308
10309
0
  if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
10310
0
    mg_send_http_error(conn,
10311
0
                       500,
10312
0
                       "Error: Cannot open file\nfopen(%s): %s",
10313
0
                       path,
10314
0
                       strerror(ERRNO));
10315
0
    return;
10316
0
  }
10317
10318
0
  fclose_on_exec(&filep->access, conn);
10319
10320
  /* If "Range" request was made: parse header, send only selected part
10321
   * of the file. */
10322
0
  r1 = r2 = 0;
10323
0
  if ((range_hdr != NULL)
10324
0
      && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
10325
0
      && (r2 >= 0)) {
10326
    /* actually, range requests don't play well with a pre-gzipped
10327
     * file (since the range is specified in the uncompressed space) */
10328
0
    if (filep->stat.is_gzipped) {
10329
0
      mg_send_http_error(
10330
0
          conn,
10331
0
          416, /* 416 = Range Not Satisfiable */
10332
0
          "%s",
10333
0
          "Error: Range requests in gzipped files are not supported");
10334
0
      (void)mg_fclose(
10335
0
          &filep->access); /* ignore error on read only file */
10336
0
      return;
10337
0
    }
10338
0
    conn->status_code = 206;
10339
0
    cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
10340
0
    mg_snprintf(conn,
10341
0
                NULL, /* range buffer is big enough */
10342
0
                range,
10343
0
                sizeof(range),
10344
0
                "bytes "
10345
0
                "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
10346
0
                r1,
10347
0
                r1 + cl - 1,
10348
0
                filep->stat.size);
10349
10350
#if defined(USE_ZLIB)
10351
    /* Do not compress ranges. */
10352
    allow_on_the_fly_compression = 0;
10353
#endif
10354
0
  }
10355
10356
  /* Do not compress small files. Small files do not benefit from file
10357
   * compression, but there is still some overhead. */
10358
#if defined(USE_ZLIB)
10359
  if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
10360
    /* File is below the size limit. */
10361
    allow_on_the_fly_compression = 0;
10362
  }
10363
#endif
10364
10365
  /* Prepare Etag, and Last-Modified headers. */
10366
0
  gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
10367
0
  construct_etag(etag, sizeof(etag), &filep->stat);
10368
10369
  /* Create 2xx (200, 206) response */
10370
0
  mg_response_header_start(conn, conn->status_code);
10371
0
  send_static_cache_header(conn);
10372
0
  send_additional_header(conn);
10373
0
  send_cors_header(conn);
10374
0
  mg_response_header_add(conn,
10375
0
                         "Content-Type",
10376
0
                         mime_vec.ptr,
10377
0
                         (int)mime_vec.len);
10378
0
  mg_response_header_add(conn, "Last-Modified", lm, -1);
10379
0
  mg_response_header_add(conn, "Etag", etag, -1);
10380
10381
#if defined(USE_ZLIB)
10382
  /* On the fly compression allowed */
10383
  if (allow_on_the_fly_compression) {
10384
    /* For on the fly compression, we don't know the content size in
10385
     * advance, so we have to use chunked encoding */
10386
    encoding = "gzip";
10387
    if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
10388
      /* HTTP/2 is always using "chunks" (frames) */
10389
      mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
10390
    }
10391
10392
  } else
10393
#endif
10394
0
  {
10395
    /* Without on-the-fly compression, we know the content-length
10396
     * and we can use ranges (with on-the-fly compression we cannot).
10397
     * So we send these response headers only in this case. */
10398
0
    char len[32];
10399
0
    int trunc = 0;
10400
0
    mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
10401
10402
0
    if (!trunc) {
10403
0
      mg_response_header_add(conn, "Content-Length", len, -1);
10404
0
    }
10405
10406
0
    mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
10407
0
  }
10408
10409
0
  if (encoding) {
10410
0
    mg_response_header_add(conn, "Content-Encoding", encoding, -1);
10411
0
  }
10412
0
  if (range[0] != 0) {
10413
0
    mg_response_header_add(conn, "Content-Range", range, -1);
10414
0
  }
10415
10416
  /* The code above does not add any header starting with X- to make
10417
   * sure no one of the additional_headers is included twice */
10418
0
  if ((additional_headers != NULL) && (*additional_headers != 0)) {
10419
0
    mg_response_header_add_lines(conn, additional_headers);
10420
0
  }
10421
10422
  /* Send all headers */
10423
0
  mg_response_header_send(conn);
10424
10425
0
  if (!is_head_request) {
10426
#if defined(USE_ZLIB)
10427
    if (allow_on_the_fly_compression) {
10428
      /* Compress and send */
10429
      send_compressed_data(conn, filep);
10430
    } else
10431
#endif
10432
0
    {
10433
      /* Send file directly */
10434
0
      send_file_data(conn, filep, r1, cl, 0); /* send static file */
10435
0
    }
10436
0
  }
10437
0
  (void)mg_fclose(&filep->access); /* ignore error on read only file */
10438
0
}
10439
10440
10441
CIVETWEB_API int
10442
mg_send_file_body(struct mg_connection *conn, const char *path)
10443
0
{
10444
0
  struct mg_file file = STRUCT_FILE_INITIALIZER;
10445
0
  if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
10446
0
    return -1;
10447
0
  }
10448
0
  fclose_on_exec(&file.access, conn);
10449
0
  send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
10450
0
  (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
10451
0
  return 0;                      /* >= 0 for OK */
10452
0
}
10453
#endif /* NO_FILESYSTEMS */
10454
10455
10456
#if !defined(NO_CACHING)
10457
/* Return True if we should reply 304 Not Modified. */
10458
static int
10459
is_not_modified(const struct mg_connection *conn,
10460
                const struct mg_file_stat *filestat)
10461
0
{
10462
0
  char etag[64];
10463
0
  const char *ims = mg_get_header(conn, "If-Modified-Since");
10464
0
  const char *inm = mg_get_header(conn, "If-None-Match");
10465
0
  construct_etag(etag, sizeof(etag), filestat);
10466
10467
0
  return ((inm != NULL) && !mg_strcasecmp(etag, inm))
10468
0
         || ((ims != NULL)
10469
0
             && (filestat->last_modified <= parse_date_string(ims)));
10470
0
}
10471
10472
10473
static void
10474
handle_not_modified_static_file_request(struct mg_connection *conn,
10475
                                        struct mg_file *filep)
10476
0
{
10477
0
  char lm[64], etag[64];
10478
10479
0
  if ((conn == NULL) || (filep == NULL)) {
10480
0
    return;
10481
0
  }
10482
10483
0
  gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
10484
0
  construct_etag(etag, sizeof(etag), &filep->stat);
10485
10486
  /* Create 304 "not modified" response */
10487
0
  mg_response_header_start(conn, 304);
10488
0
  send_static_cache_header(conn);
10489
0
  send_additional_header(conn);
10490
0
  mg_response_header_add(conn, "Last-Modified", lm, -1);
10491
0
  mg_response_header_add(conn, "Etag", etag, -1);
10492
10493
  /* Send all headers */
10494
0
  mg_response_header_send(conn);
10495
0
}
10496
#endif
10497
10498
10499
#if !defined(NO_FILESYSTEMS)
10500
CIVETWEB_API void
10501
mg_send_file(struct mg_connection *conn, const char *path)
10502
0
{
10503
0
  mg_send_mime_file2(conn, path, NULL, NULL);
10504
0
}
10505
10506
10507
CIVETWEB_API void
10508
mg_send_mime_file(struct mg_connection *conn,
10509
                  const char *path,
10510
                  const char *mime_type)
10511
0
{
10512
0
  mg_send_mime_file2(conn, path, mime_type, NULL);
10513
0
}
10514
10515
10516
CIVETWEB_API void
10517
mg_send_mime_file2(struct mg_connection *conn,
10518
                   const char *path,
10519
                   const char *mime_type,
10520
                   const char *additional_headers)
10521
0
{
10522
0
  struct mg_file file = STRUCT_FILE_INITIALIZER;
10523
10524
0
  if (!conn) {
10525
    /* No conn */
10526
0
    return;
10527
0
  }
10528
10529
0
  if (mg_stat(conn, path, &file.stat)) {
10530
0
#if !defined(NO_CACHING)
10531
0
    if (is_not_modified(conn, &file.stat)) {
10532
      /* Send 304 "Not Modified" - this must not send any body data */
10533
0
      handle_not_modified_static_file_request(conn, &file);
10534
0
    } else
10535
0
#endif /* NO_CACHING */
10536
0
        if (file.stat.is_directory) {
10537
0
      if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
10538
0
                         "yes")) {
10539
0
        handle_directory_request(conn, path);
10540
0
      } else {
10541
0
        mg_send_http_error(conn,
10542
0
                           403,
10543
0
                           "%s",
10544
0
                           "Error: Directory listing denied");
10545
0
      }
10546
0
    } else {
10547
0
      handle_static_file_request(
10548
0
          conn, path, &file, mime_type, additional_headers);
10549
0
    }
10550
0
  } else {
10551
0
    mg_send_http_error(conn, 404, "%s", "Error: File not found");
10552
0
  }
10553
0
}
10554
10555
10556
/* For a given PUT path, create all intermediate subdirectories.
10557
 * Return  0  if the path itself is a directory.
10558
 * Return  1  if the path leads to a file.
10559
 * Return -1  for if the path is too long.
10560
 * Return -2  if path can not be created.
10561
 */
10562
static int
10563
put_dir(struct mg_connection *conn, const char *path)
10564
0
{
10565
0
  char buf[UTF8_PATH_MAX];
10566
0
  const char *s, *p;
10567
0
  struct mg_file file = STRUCT_FILE_INITIALIZER;
10568
0
  size_t len;
10569
0
  int res = 1;
10570
10571
0
  for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
10572
0
    len = (size_t)(p - path);
10573
0
    if (len >= sizeof(buf)) {
10574
      /* path too long */
10575
0
      res = -1;
10576
0
      break;
10577
0
    }
10578
0
    memcpy(buf, path, len);
10579
0
    buf[len] = '\0';
10580
10581
    /* Try to create intermediate directory */
10582
0
    DEBUG_TRACE("mkdir(%s)", buf);
10583
0
    if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
10584
      /* path does not exist and can not be created */
10585
0
      res = -2;
10586
0
      break;
10587
0
    }
10588
10589
    /* Is path itself a directory? */
10590
0
    if (p[1] == '\0') {
10591
0
      res = 0;
10592
0
    }
10593
0
  }
10594
10595
0
  return res;
10596
0
}
10597
10598
10599
static void
10600
remove_bad_file(const struct mg_connection *conn, const char *path)
10601
0
{
10602
0
  int r = mg_remove(conn, path);
10603
0
  if (r != 0) {
10604
0
    mg_cry_internal(conn,
10605
0
                    "%s: Cannot remove invalid file %s",
10606
0
                    __func__,
10607
0
                    path);
10608
0
  }
10609
0
}
10610
10611
10612
CIVETWEB_API long long
10613
mg_store_body(struct mg_connection *conn, const char *path)
10614
0
{
10615
0
  char buf[MG_BUF_LEN];
10616
0
  long long len = 0;
10617
0
  int ret, n;
10618
0
  struct mg_file fi;
10619
10620
0
  if (conn->consumed_content != 0) {
10621
0
    mg_cry_internal(conn, "%s: Contents already consumed", __func__);
10622
0
    return -11;
10623
0
  }
10624
10625
0
  ret = put_dir(conn, path);
10626
0
  if (ret < 0) {
10627
    /* -1 for path too long,
10628
     * -2 for path can not be created. */
10629
0
    return ret;
10630
0
  }
10631
0
  if (ret != 1) {
10632
    /* Return 0 means, path itself is a directory. */
10633
0
    return 0;
10634
0
  }
10635
10636
0
  if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
10637
0
    return -12;
10638
0
  }
10639
10640
0
  ret = mg_read(conn, buf, sizeof(buf));
10641
0
  while (ret > 0) {
10642
0
    n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
10643
0
    if (n != ret) {
10644
0
      (void)mg_fclose(
10645
0
          &fi.access); /* File is bad and will be removed anyway. */
10646
0
      remove_bad_file(conn, path);
10647
0
      return -13;
10648
0
    }
10649
0
    len += ret;
10650
0
    ret = mg_read(conn, buf, sizeof(buf));
10651
0
  }
10652
10653
  /* File is open for writing. If fclose fails, there was probably an
10654
   * error flushing the buffer to disk, so the file on disk might be
10655
   * broken. Delete it and return an error to the caller. */
10656
0
  if (mg_fclose(&fi.access) != 0) {
10657
0
    remove_bad_file(conn, path);
10658
0
    return -14;
10659
0
  }
10660
10661
0
  return len;
10662
0
}
10663
#endif /* NO_FILESYSTEMS */
10664
10665
10666
/* Parse a buffer:
10667
 * Forward the string pointer till the end of a word, then
10668
 * terminate it and forward till the begin of the next word.
10669
 */
10670
static int
10671
skip_to_end_of_word_and_terminate(char **ppw, int eol)
10672
10
{
10673
  /* Forward until a space is found - use isgraph here */
10674
  /* See http://www.cplusplus.com/reference/cctype/ */
10675
41
  while (isgraph((unsigned char)**ppw)) {
10676
41
    (*ppw)++;
10677
41
  }
10678
10679
  /* Check end of word */
10680
10
  if (eol) {
10681
    /* must be a end of line */
10682
0
    if ((**ppw != '\r') && (**ppw != '\n')) {
10683
0
      return -1;
10684
0
    }
10685
10
  } else {
10686
    /* must be a end of a word, but not a line */
10687
10
    if (**ppw != ' ') {
10688
0
      return -1;
10689
0
    }
10690
10
  }
10691
10692
  /* Terminate and forward to the next word */
10693
10
  do {
10694
10
    **ppw = 0;
10695
10
    (*ppw)++;
10696
10
  } while (isspace((unsigned char)**ppw));
10697
10698
  /* Check after term */
10699
10
  if (!eol) {
10700
    /* if it's not the end of line, there must be a next word */
10701
10
    if (!isgraph((unsigned char)**ppw)) {
10702
0
      return -1;
10703
0
    }
10704
10
  }
10705
10706
  /* ok */
10707
10
  return 1;
10708
10
}
10709
10710
10711
/* Parse HTTP headers from the given buffer, advance buf pointer
10712
 * to the point where parsing stopped.
10713
 * All parameters must be valid pointers (not NULL).
10714
 * Return <0 on error. */
10715
static int
10716
parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
10717
3
{
10718
3
  int i;
10719
3
  int num_headers = 0;
10720
10721
58
  for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
10722
58
    char *dp = *buf;
10723
10724
    /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
10725
246
    while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
10726
188
      dp++;
10727
188
    }
10728
58
    if (dp == *buf) {
10729
      /* End of headers reached. */
10730
1
      break;
10731
1
    }
10732
10733
    /* Drop all spaces after header name before : */
10734
173
    while (*dp == ' ') {
10735
116
      *dp = 0;
10736
116
      dp++;
10737
116
    }
10738
57
    if (*dp != ':') {
10739
      /* This is not a valid field. */
10740
2
      return -1;
10741
2
    }
10742
10743
    /* End of header key (*dp == ':') */
10744
    /* Truncate here and set the key name */
10745
55
    *dp = 0;
10746
55
    hdr[i].name = *buf;
10747
10748
    /* Skip all spaces */
10749
88
    do {
10750
88
      dp++;
10751
88
    } while ((*dp == ' ') || (*dp == '\t'));
10752
10753
    /* The rest of the line is the value */
10754
55
    hdr[i].value = dp;
10755
10756
    /* Find end of line */
10757
1.47k
    while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
10758
1.42k
      dp++;
10759
1.42k
    };
10760
10761
    /* eliminate \r */
10762
55
    if (*dp == '\r') {
10763
0
      *dp = 0;
10764
0
      dp++;
10765
0
      if (*dp != '\n') {
10766
        /* This is not a valid line. */
10767
0
        return -1;
10768
0
      }
10769
0
    }
10770
10771
    /* here *dp is either 0 or '\n' */
10772
    /* in any case, we have a new header */
10773
55
    num_headers = i + 1;
10774
10775
55
    if (*dp) {
10776
55
      *dp = 0;
10777
55
      dp++;
10778
55
      *buf = dp;
10779
10780
55
      if ((dp[0] == '\r') || (dp[0] == '\n')) {
10781
        /* This is the end of the header */
10782
0
        break;
10783
0
      }
10784
55
    } else {
10785
0
      *buf = dp;
10786
0
      break;
10787
0
    }
10788
55
  }
10789
1
  return num_headers;
10790
3
}
10791
10792
10793
struct mg_http_method_info {
10794
  const char *name;
10795
  int request_has_body;
10796
  int response_has_body;
10797
  int is_safe;
10798
  int is_idempotent;
10799
  int is_cacheable;
10800
};
10801
10802
10803
/* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
10804
static const struct mg_http_method_info http_methods[] = {
10805
    /* HTTP (RFC 2616) */
10806
    {"GET", 0, 1, 1, 1, 1},
10807
    {"POST", 1, 1, 0, 0, 0},
10808
    {"PUT", 1, 0, 0, 1, 0},
10809
    {"DELETE", 0, 0, 0, 1, 0},
10810
    {"HEAD", 0, 0, 1, 1, 1},
10811
    {"OPTIONS", 0, 0, 1, 1, 0},
10812
    {"CONNECT", 1, 1, 0, 0, 0},
10813
    /* TRACE method (RFC 2616) is not supported for security reasons */
10814
10815
    /* PATCH method (RFC 5789) */
10816
    {"PATCH", 1, 0, 0, 0, 0},
10817
    /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
10818
10819
    /* WEBDAV (RFC 2518) */
10820
    {"PROPFIND", 0, 1, 1, 1, 0},
10821
    /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10822
     * Some PROPFIND results MAY be cached, with care,
10823
     * as there is no cache validation mechanism for
10824
     * most properties. This method is both safe and
10825
     * idempotent (see Section 9.1 of [RFC2616]). */
10826
    {"MKCOL", 0, 0, 0, 1, 0},
10827
    /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10828
     * When MKCOL is invoked without a request body,
10829
     * the newly created collection SHOULD have no
10830
     * members. A MKCOL request message may contain
10831
     * a message body. The precise behavior of a MKCOL
10832
     * request when the body is present is undefined,
10833
     * ... ==> We do not support MKCOL with body data.
10834
     * This method is idempotent, but not safe (see
10835
     * Section 9.1 of [RFC2616]). Responses to this
10836
     * method MUST NOT be cached. */
10837
10838
    /* Methods for write access to files on WEBDAV (RFC 2518) */
10839
    {"LOCK", 1, 1, 0, 0, 0},
10840
    {"UNLOCK", 1, 0, 0, 0, 0},
10841
    {"PROPPATCH", 1, 1, 0, 0, 0},
10842
    {"COPY", 1, 0, 0, 0, 0},
10843
    {"MOVE", 1, 1, 0, 0, 0},
10844
10845
    /* Unsupported WEBDAV Methods: */
10846
    /* + 11 methods from RFC 3253 */
10847
    /* ORDERPATCH (RFC 3648) */
10848
    /* ACL (RFC 3744) */
10849
    /* SEARCH (RFC 5323) */
10850
    /* + MicroSoft extensions
10851
     * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
10852
10853
    /* REPORT method (RFC 3253) */
10854
    {"REPORT", 1, 1, 1, 1, 1},
10855
    /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
10856
    /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
10857
     * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
10858
     * to be useful for REST in case a "GET request with body" is
10859
     * required. */
10860
10861
    {NULL, 0, 0, 0, 0, 0}
10862
    /* end of list */
10863
};
10864
10865
10866
/* All method names */
10867
static char *all_methods = NULL; /* Built by mg_init_library */
10868
10869
10870
static const struct mg_http_method_info *
10871
get_http_method_info(const char *method)
10872
0
{
10873
  /* Check if the method is known to the server. The list of all known
10874
   * HTTP methods can be found here at
10875
   * http://www.iana.org/assignments/http-methods/http-methods.xhtml
10876
   */
10877
0
  const struct mg_http_method_info *m = http_methods;
10878
10879
0
  while (m->name) {
10880
0
    if (!strcmp(m->name, method)) {
10881
0
      return m;
10882
0
    }
10883
0
    m++;
10884
0
  }
10885
0
  return NULL;
10886
0
}
10887
10888
10889
static int
10890
is_valid_http_method(const char *method)
10891
0
{
10892
0
  return (get_http_method_info(method) != NULL);
10893
0
}
10894
10895
10896
/* Parse HTTP request, fill in mg_request_info structure.
10897
 * This function modifies the buffer by NUL-terminating
10898
 * HTTP request components, header names and header values.
10899
 * Parameters:
10900
 *   buf (in/out): pointer to the HTTP header to parse and split
10901
 *   len (in): length of HTTP header buffer
10902
 *   re (out): parsed header as mg_request_info
10903
 * buf and ri must be valid pointers (not NULL), len>0.
10904
 * Returns <0 on error. */
10905
static int
10906
parse_http_request(char *buf, int len, struct mg_request_info *ri)
10907
0
{
10908
0
  int request_length;
10909
0
  int init_skip = 0;
10910
10911
  /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
10912
   * remote_port */
10913
0
  ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
10914
0
      NULL;
10915
0
  ri->num_headers = 0;
10916
10917
  /* RFC says that all initial whitespaces should be ignored */
10918
  /* This included all leading \r and \n (isspace) */
10919
  /* See table: http://www.cplusplus.com/reference/cctype/ */
10920
0
  while ((len > 0) && isspace((unsigned char)*buf)) {
10921
0
    buf++;
10922
0
    len--;
10923
0
    init_skip++;
10924
0
  }
10925
10926
0
  if (len == 0) {
10927
    /* Incomplete request */
10928
0
    return 0;
10929
0
  }
10930
10931
  /* Control characters are not allowed, including zero */
10932
0
  if (iscntrl((unsigned char)*buf)) {
10933
0
    return -1;
10934
0
  }
10935
10936
  /* Find end of HTTP header */
10937
0
  request_length = get_http_header_len(buf, len);
10938
0
  if (request_length <= 0) {
10939
0
    return request_length;
10940
0
  }
10941
0
  buf[request_length - 1] = '\0';
10942
10943
0
  if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10944
0
    return -1;
10945
0
  }
10946
10947
  /* The first word has to be the HTTP method */
10948
0
  ri->request_method = buf;
10949
10950
0
  if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10951
0
    return -1;
10952
0
  }
10953
10954
  /* The second word is the URI */
10955
0
  ri->request_uri = buf;
10956
10957
0
  if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10958
0
    return -1;
10959
0
  }
10960
10961
  /* Next would be the HTTP version */
10962
0
  ri->http_version = buf;
10963
10964
0
  if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
10965
0
    return -1;
10966
0
  }
10967
10968
  /* Check for a valid HTTP version key */
10969
0
  if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
10970
    /* Invalid request */
10971
0
    return -1;
10972
0
  }
10973
0
  ri->http_version += 5;
10974
10975
  /* Check for a valid http method */
10976
0
  if (!is_valid_http_method(ri->request_method)) {
10977
0
    return -1;
10978
0
  }
10979
10980
  /* Parse all HTTP headers */
10981
0
  ri->num_headers = parse_http_headers(&buf, ri->http_headers);
10982
0
  if (ri->num_headers < 0) {
10983
    /* Error while parsing headers */
10984
0
    return -1;
10985
0
  }
10986
10987
0
  return request_length + init_skip;
10988
0
}
10989
10990
10991
static int
10992
parse_http_response(char *buf, int len, struct mg_response_info *ri)
10993
14
{
10994
14
  int response_length;
10995
14
  int init_skip = 0;
10996
14
  char *tmp, *tmp2;
10997
14
  long l;
10998
10999
  /* Initialize elements. */
11000
14
  ri->http_version = ri->status_text = NULL;
11001
14
  ri->num_headers = ri->status_code = 0;
11002
11003
  /* RFC says that all initial whitespaces should be ignored */
11004
  /* This included all leading \r and \n (isspace) */
11005
  /* See table: http://www.cplusplus.com/reference/cctype/ */
11006
1.22k
  while ((len > 0) && isspace((unsigned char)*buf)) {
11007
1.20k
    buf++;
11008
1.20k
    len--;
11009
1.20k
    init_skip++;
11010
1.20k
  }
11011
11012
14
  if (len == 0) {
11013
    /* Incomplete request */
11014
0
    return 0;
11015
0
  }
11016
11017
  /* Control characters are not allowed, including zero */
11018
14
  if (iscntrl((unsigned char)*buf)) {
11019
0
    return -1;
11020
0
  }
11021
11022
  /* Find end of HTTP header */
11023
14
  response_length = get_http_header_len(buf, len);
11024
14
  if (response_length <= 0) {
11025
1
    return response_length;
11026
1
  }
11027
13
  buf[response_length - 1] = '\0';
11028
11029
13
  if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
11030
0
    return -1;
11031
0
  }
11032
11033
  /* The first word is the HTTP version */
11034
  /* Check for a valid HTTP version key */
11035
13
  if (strncmp(buf, "HTTP/", 5) != 0) {
11036
    /* Invalid request */
11037
8
    return -1;
11038
8
  }
11039
5
  buf += 5;
11040
5
  if (!isgraph((unsigned char)buf[0])) {
11041
    /* Invalid request */
11042
0
    return -1;
11043
0
  }
11044
5
  ri->http_version = buf;
11045
11046
5
  if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
11047
0
    return -1;
11048
0
  }
11049
11050
  /* The second word is the status as a number */
11051
5
  tmp = buf;
11052
11053
5
  if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
11054
0
    return -1;
11055
0
  }
11056
11057
5
  l = strtol(tmp, &tmp2, 10);
11058
5
  if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
11059
    /* Everything else but a 3 digit code is invalid */
11060
1
    return -1;
11061
1
  }
11062
4
  ri->status_code = (int)l;
11063
11064
  /* The rest of the line is the status text */
11065
4
  ri->status_text = buf;
11066
11067
  /* Find end of status text */
11068
  /* isgraph or isspace = isprint */
11069
20
  while (isprint((unsigned char)*buf)) {
11070
20
    buf++;
11071
20
  }
11072
4
  if ((*buf != '\r') && (*buf != '\n')) {
11073
1
    return -1;
11074
1
  }
11075
  /* Terminate string and forward buf to next line */
11076
3
  do {
11077
3
    *buf = 0;
11078
3
    buf++;
11079
3
  } while (isspace((unsigned char)*buf));
11080
11081
  /* Parse all HTTP headers */
11082
3
  ri->num_headers = parse_http_headers(&buf, ri->http_headers);
11083
3
  if (ri->num_headers < 0) {
11084
    /* Error while parsing headers */
11085
2
    return -1;
11086
2
  }
11087
11088
1
  return response_length + init_skip;
11089
3
}
11090
11091
11092
/* Keep reading the input (either opened file descriptor fd, or socket sock,
11093
 * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
11094
 * buffer (which marks the end of HTTP request). Buffer buf may already
11095
 * have some data. The length of the data is stored in nread.
11096
 * Upon every read operation, increase nread by the number of bytes read. */
11097
static int
11098
read_message(FILE *fp,
11099
             struct mg_connection *conn,
11100
             char *buf,
11101
             int bufsiz,
11102
             int *nread)
11103
34
{
11104
34
  int request_len, n = 0;
11105
34
  struct timespec last_action_time;
11106
34
  double request_timeout;
11107
11108
34
  if (!conn) {
11109
0
    return 0;
11110
0
  }
11111
11112
34
  memset(&last_action_time, 0, sizeof(last_action_time));
11113
11114
34
  if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
11115
    /* value of request_timeout is in seconds, config in milliseconds */
11116
34
    request_timeout =
11117
34
        strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
11118
34
  } else {
11119
0
    request_timeout =
11120
0
        strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
11121
0
        / 1000.0;
11122
0
  }
11123
34
  if (conn->handled_requests > 0) {
11124
0
    if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
11125
0
      request_timeout =
11126
0
          strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
11127
0
          / 1000.0;
11128
0
    }
11129
0
  }
11130
11131
34
  request_len = get_http_header_len(buf, *nread);
11132
11133
68
  while (request_len == 0) {
11134
    /* Full request not yet received */
11135
44
    if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
11136
      /* Server is to be stopped. */
11137
0
      return -1;
11138
0
    }
11139
11140
44
    if (*nread >= bufsiz) {
11141
      /* Request too long */
11142
0
      return -2;
11143
0
    }
11144
11145
44
    n = pull_inner(
11146
44
        fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
11147
44
    if (n == -2) {
11148
      /* Receive error */
11149
10
      return -1;
11150
10
    }
11151
11152
    /* update clock after every read request */
11153
34
    clock_gettime(CLOCK_MONOTONIC, &last_action_time);
11154
11155
34
    if (n > 0) {
11156
34
      *nread += n;
11157
34
      request_len = get_http_header_len(buf, *nread);
11158
34
    }
11159
11160
34
    if ((request_len == 0) && (request_timeout >= 0)) {
11161
10
      if (mg_difftimespec(&last_action_time, &(conn->req_time))
11162
10
          > request_timeout) {
11163
        /* Timeout */
11164
0
        return -1;
11165
0
      }
11166
10
    }
11167
34
  }
11168
11169
24
  return request_len;
11170
34
}
11171
11172
11173
#if !defined(NO_CGI) || !defined(NO_FILES)
11174
static int
11175
forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
11176
0
{
11177
0
  const char *expect;
11178
0
  char buf[MG_BUF_LEN];
11179
0
  int success = 0;
11180
11181
0
  if (!conn) {
11182
0
    return 0;
11183
0
  }
11184
11185
0
  expect = mg_get_header(conn, "Expect");
11186
0
  DEBUG_ASSERT(fp != NULL);
11187
0
  if (!fp) {
11188
0
    mg_send_http_error(conn, 500, "%s", "Error: NULL File");
11189
0
    return 0;
11190
0
  }
11191
11192
0
  if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
11193
    /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
11194
     */
11195
0
    mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
11196
0
  } else {
11197
0
    if (expect != NULL) {
11198
0
      (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
11199
0
      conn->status_code = 100;
11200
0
    } else {
11201
0
      conn->status_code = 200;
11202
0
    }
11203
11204
0
    DEBUG_ASSERT(conn->consumed_content == 0);
11205
11206
0
    if (conn->consumed_content != 0) {
11207
0
      mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
11208
0
      return 0;
11209
0
    }
11210
11211
0
    for (;;) {
11212
0
      int nread = mg_read(conn, buf, sizeof(buf));
11213
0
      if (nread <= 0) {
11214
0
        success = (nread == 0);
11215
0
        break;
11216
0
      }
11217
0
      if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
11218
0
        break;
11219
0
      }
11220
0
    }
11221
11222
    /* Each error code path in this function must send an error */
11223
0
    if (!success) {
11224
      /* NOTE: Maybe some data has already been sent. */
11225
      /* TODO (low): If some data has been sent, a correct error
11226
       * reply can no longer be sent, so just close the connection */
11227
0
      mg_send_http_error(conn, 500, "%s", "");
11228
0
    }
11229
0
  }
11230
11231
0
  return success;
11232
0
}
11233
#endif
11234
11235
11236
#if defined(USE_TIMERS)
11237
11238
#define TIMER_API static
11239
#include "timer.inl"
11240
11241
#endif /* USE_TIMERS */
11242
11243
11244
#if !defined(NO_CGI)
11245
/* This structure helps to create an environment for the spawned CGI
11246
 * program.
11247
 * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
11248
 * last element must be NULL.
11249
 * However, on Windows there is a requirement that all these
11250
 * VARIABLE=VALUE\0
11251
 * strings must reside in a contiguous buffer. The end of the buffer is
11252
 * marked by two '\0' characters.
11253
 * We satisfy both worlds: we create an envp array (which is vars), all
11254
 * entries are actually pointers inside buf. */
11255
struct cgi_environment {
11256
  struct mg_connection *conn;
11257
  /* Data block */
11258
  char *buf;      /* Environment buffer */
11259
  size_t buflen;  /* Space available in buf */
11260
  size_t bufused; /* Space taken in buf */
11261
  /* Index block */
11262
  char **var;     /* char **envp */
11263
  size_t varlen;  /* Number of variables available in var */
11264
  size_t varused; /* Number of variables stored in var */
11265
};
11266
11267
11268
static void addenv(struct cgi_environment *env,
11269
                   PRINTF_FORMAT_STRING(const char *fmt),
11270
                   ...) PRINTF_ARGS(2, 3);
11271
11272
/* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
11273
 * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
11274
static void
11275
addenv(struct cgi_environment *env, const char *fmt, ...)
11276
0
{
11277
0
  size_t i, n, space;
11278
0
  int truncated = 0;
11279
0
  char *added;
11280
0
  va_list ap;
11281
11282
0
  if ((env->varlen - env->varused) < 2) {
11283
0
    mg_cry_internal(env->conn,
11284
0
                    "%s: Cannot register CGI variable [%s]",
11285
0
                    __func__,
11286
0
                    fmt);
11287
0
    return;
11288
0
  }
11289
11290
  /* Calculate how much space is left in the buffer */
11291
0
  space = (env->buflen - env->bufused);
11292
11293
0
  do {
11294
    /* Space for "\0\0" is always needed. */
11295
0
    if (space <= 2) {
11296
      /* Allocate new buffer */
11297
0
      n = env->buflen + CGI_ENVIRONMENT_SIZE;
11298
0
      added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
11299
0
      if (!added) {
11300
        /* Out of memory */
11301
0
        mg_cry_internal(
11302
0
            env->conn,
11303
0
            "%s: Cannot allocate memory for CGI variable [%s]",
11304
0
            __func__,
11305
0
            fmt);
11306
0
        return;
11307
0
      }
11308
      /* Retarget pointers */
11309
0
      env->buf = added;
11310
0
      env->buflen = n;
11311
0
      for (i = 0, n = 0; i < env->varused; i++) {
11312
0
        env->var[i] = added + n;
11313
0
        n += strlen(added + n) + 1;
11314
0
      }
11315
0
      space = (env->buflen - env->bufused);
11316
0
    }
11317
11318
    /* Make a pointer to the free space int the buffer */
11319
0
    added = env->buf + env->bufused;
11320
11321
    /* Copy VARIABLE=VALUE\0 string into the free space */
11322
0
    va_start(ap, fmt);
11323
0
    mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
11324
0
    va_end(ap);
11325
11326
    /* Do not add truncated strings to the environment */
11327
0
    if (truncated) {
11328
      /* Reallocate the buffer */
11329
0
      space = 0;
11330
0
    }
11331
0
  } while (truncated);
11332
11333
  /* Calculate number of bytes added to the environment */
11334
0
  n = strlen(added) + 1;
11335
0
  env->bufused += n;
11336
11337
  /* Append a pointer to the added string into the envp array */
11338
0
  env->var[env->varused] = added;
11339
0
  env->varused++;
11340
0
}
11341
11342
/* Return 0 on success, non-zero if an error occurs. */
11343
11344
static int
11345
prepare_cgi_environment(struct mg_connection *conn,
11346
                        const char *prog,
11347
                        struct cgi_environment *env,
11348
                        unsigned char cgi_config_idx)
11349
0
{
11350
0
  const char *s;
11351
0
  struct vec var_vec;
11352
0
  char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
11353
0
  int i, truncated, uri_len;
11354
11355
0
  if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
11356
0
    return -1;
11357
0
  }
11358
11359
0
  env->conn = conn;
11360
0
  env->buflen = CGI_ENVIRONMENT_SIZE;
11361
0
  env->bufused = 0;
11362
0
  env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
11363
0
  if (env->buf == NULL) {
11364
0
    mg_cry_internal(conn,
11365
0
                    "%s: Not enough memory for environmental buffer",
11366
0
                    __func__);
11367
0
    return -1;
11368
0
  }
11369
0
  env->varlen = MAX_CGI_ENVIR_VARS;
11370
0
  env->varused = 0;
11371
0
  env->var =
11372
0
      (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
11373
0
  if (env->var == NULL) {
11374
0
    mg_cry_internal(conn,
11375
0
                    "%s: Not enough memory for environmental variables",
11376
0
                    __func__);
11377
0
    mg_free(env->buf);
11378
0
    return -1;
11379
0
  }
11380
11381
0
  addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
11382
0
  addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11383
0
  addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11384
0
  addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
11385
11386
  /* Prepare the environment block */
11387
0
  addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
11388
0
  addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
11389
0
  addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
11390
11391
0
  addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
11392
11393
0
  sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
11394
0
  addenv(env, "REMOTE_ADDR=%s", src_addr);
11395
11396
0
  addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
11397
0
  addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
11398
11399
0
  addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
11400
0
  addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
11401
0
  addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
11402
11403
  /* SCRIPT_NAME */
11404
0
  uri_len = (int)strlen(conn->request_info.local_uri);
11405
0
  if (conn->path_info == NULL) {
11406
0
    if (conn->request_info.local_uri[uri_len - 1] != '/') {
11407
      /* URI: /path_to_script/script.cgi */
11408
0
      addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
11409
0
    } else {
11410
      /* URI: /path_to_script/ ... using index.cgi */
11411
0
      const char *index_file = strrchr(prog, '/');
11412
0
      if (index_file) {
11413
0
        addenv(env,
11414
0
               "SCRIPT_NAME=%s%s",
11415
0
               conn->request_info.local_uri,
11416
0
               index_file + 1);
11417
0
      }
11418
0
    }
11419
0
  } else {
11420
    /* URI: /path_to_script/script.cgi/path_info */
11421
0
    addenv(env,
11422
0
           "SCRIPT_NAME=%.*s",
11423
0
           uri_len - (int)strlen(conn->path_info),
11424
0
           conn->request_info.local_uri);
11425
0
  }
11426
11427
0
  addenv(env, "SCRIPT_FILENAME=%s", prog);
11428
0
  if (conn->path_info == NULL) {
11429
0
    addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
11430
0
  } else {
11431
0
    addenv(env,
11432
0
           "PATH_TRANSLATED=%s%s",
11433
0
           conn->dom_ctx->config[DOCUMENT_ROOT],
11434
0
           conn->path_info);
11435
0
  }
11436
11437
0
  addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
11438
11439
0
  if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
11440
0
    addenv(env, "CONTENT_TYPE=%s", s);
11441
0
  }
11442
0
  if (conn->request_info.query_string != NULL) {
11443
0
    addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
11444
0
  }
11445
0
  if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
11446
0
    addenv(env, "CONTENT_LENGTH=%s", s);
11447
0
  }
11448
0
  if ((s = getenv("PATH")) != NULL) {
11449
0
    addenv(env, "PATH=%s", s);
11450
0
  }
11451
0
  if (conn->path_info != NULL) {
11452
0
    addenv(env, "PATH_INFO=%s", conn->path_info);
11453
0
  }
11454
11455
0
  if (conn->status_code > 0) {
11456
    /* CGI error handler should show the status code */
11457
0
    addenv(env, "STATUS=%d", conn->status_code);
11458
0
  }
11459
11460
#if defined(_WIN32)
11461
  if ((s = getenv("COMSPEC")) != NULL) {
11462
    addenv(env, "COMSPEC=%s", s);
11463
  }
11464
  if ((s = getenv("SYSTEMROOT")) != NULL) {
11465
    addenv(env, "SYSTEMROOT=%s", s);
11466
  }
11467
  if ((s = getenv("SystemDrive")) != NULL) {
11468
    addenv(env, "SystemDrive=%s", s);
11469
  }
11470
  if ((s = getenv("ProgramFiles")) != NULL) {
11471
    addenv(env, "ProgramFiles=%s", s);
11472
  }
11473
  if ((s = getenv("ProgramFiles(x86)")) != NULL) {
11474
    addenv(env, "ProgramFiles(x86)=%s", s);
11475
  }
11476
#else
11477
0
  if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
11478
0
    addenv(env, "LD_LIBRARY_PATH=%s", s);
11479
0
  }
11480
0
#endif /* _WIN32 */
11481
11482
0
  if ((s = getenv("PERLLIB")) != NULL) {
11483
0
    addenv(env, "PERLLIB=%s", s);
11484
0
  }
11485
11486
0
  if (conn->request_info.remote_user != NULL) {
11487
0
    addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
11488
0
    addenv(env, "%s", "AUTH_TYPE=Digest");
11489
0
  }
11490
11491
  /* Add all headers as HTTP_* variables */
11492
0
  for (i = 0; i < conn->request_info.num_headers; i++) {
11493
11494
0
    (void)mg_snprintf(conn,
11495
0
                      &truncated,
11496
0
                      http_var_name,
11497
0
                      sizeof(http_var_name),
11498
0
                      "HTTP_%s",
11499
0
                      conn->request_info.http_headers[i].name);
11500
11501
0
    if (truncated) {
11502
0
      mg_cry_internal(conn,
11503
0
                      "%s: HTTP header variable too long [%s]",
11504
0
                      __func__,
11505
0
                      conn->request_info.http_headers[i].name);
11506
0
      continue;
11507
0
    }
11508
11509
    /* Convert variable name into uppercase, and change - to _ */
11510
0
    for (p = http_var_name; *p != '\0'; p++) {
11511
0
      if (*p == '-') {
11512
0
        *p = '_';
11513
0
      }
11514
0
      *p = (char)toupper((unsigned char)*p);
11515
0
    }
11516
11517
0
    addenv(env,
11518
0
           "%s=%s",
11519
0
           http_var_name,
11520
0
           conn->request_info.http_headers[i].value);
11521
0
  }
11522
11523
  /* Add user-specified variables */
11524
0
  s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
11525
0
  while ((s = next_option(s, &var_vec, NULL)) != NULL) {
11526
0
    addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
11527
0
  }
11528
11529
0
  env->var[env->varused] = NULL;
11530
0
  env->buf[env->bufused] = '\0';
11531
11532
0
  return 0;
11533
0
}
11534
11535
11536
/* Data for CGI process control: PID and number of references */
11537
struct process_control_data {
11538
  pid_t pid;
11539
  ptrdiff_t references;
11540
};
11541
11542
static int
11543
abort_cgi_process(void *data)
11544
0
{
11545
  /* Waitpid checks for child status and won't work for a pid that does
11546
   * not identify a child of the current process. Thus, if the pid is
11547
   * reused, we will not affect a different process. */
11548
0
  struct process_control_data *proc = (struct process_control_data *)data;
11549
0
  int status = 0;
11550
0
  ptrdiff_t refs;
11551
0
  pid_t ret_pid;
11552
11553
0
  ret_pid = waitpid(proc->pid, &status, WNOHANG);
11554
0
  if ((ret_pid != (pid_t)-1) && (status == 0)) {
11555
    /* Stop child process */
11556
0
    DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
11557
0
    kill(proc->pid, SIGABRT);
11558
11559
    /* Wait until process is terminated (don't leave zombies) */
11560
0
    while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
11561
0
      ;
11562
0
  } else {
11563
0
    DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
11564
0
  }
11565
  /* Dec reference counter */
11566
0
  refs = mg_atomic_dec(&proc->references);
11567
0
  if (refs == 0) {
11568
    /* no more references - free data */
11569
0
    mg_free(data);
11570
0
  }
11571
11572
0
  return 0;
11573
0
}
11574
11575
11576
/* Local (static) function assumes all arguments are valid. */
11577
static void
11578
handle_cgi_request(struct mg_connection *conn,
11579
                   const char *prog,
11580
                   unsigned char cgi_config_idx)
11581
0
{
11582
0
  char *buf;
11583
0
  size_t buflen;
11584
0
  int headers_len, data_len, i, truncated;
11585
0
  int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
11586
0
  const char *status, *status_text;
11587
0
  char *pbuf, dir[UTF8_PATH_MAX], *p;
11588
0
  struct mg_request_info ri;
11589
0
  struct cgi_environment blk;
11590
0
  FILE *in = NULL, *out = NULL, *err = NULL;
11591
0
  struct mg_file fout = STRUCT_FILE_INITIALIZER;
11592
0
  pid_t pid = (pid_t)-1;
11593
0
  struct process_control_data *proc = NULL;
11594
0
  char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
11595
0
  int no_buffering = 0;
11596
11597
#if defined(USE_TIMERS)
11598
  double cgi_timeout;
11599
  if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
11600
    /* Get timeout in seconds */
11601
    cgi_timeout =
11602
        atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
11603
  } else {
11604
    cgi_timeout =
11605
        atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
11606
  }
11607
#endif
11608
0
  if (cfg_buffering != NULL) {
11609
0
    if (!mg_strcasecmp(cfg_buffering, "no")) {
11610
0
      no_buffering = 1;
11611
0
    }
11612
0
  }
11613
11614
0
  buf = NULL;
11615
0
  buflen = conn->phys_ctx->max_request_size;
11616
0
  i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
11617
0
  if (i != 0) {
11618
0
    blk.buf = NULL;
11619
0
    blk.var = NULL;
11620
0
    goto done;
11621
0
  }
11622
11623
  /* CGI must be executed in its own directory. 'dir' must point to the
11624
   * directory containing executable program, 'p' must point to the
11625
   * executable program name relative to 'dir'. */
11626
0
  (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
11627
11628
0
  if (truncated) {
11629
0
    mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
11630
0
    mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
11631
0
    goto done;
11632
0
  }
11633
11634
0
  if ((p = strrchr(dir, '/')) != NULL) {
11635
0
    *p++ = '\0';
11636
0
  } else {
11637
0
    dir[0] = '.';
11638
0
    dir[1] = '\0';
11639
0
    p = (char *)prog;
11640
0
  }
11641
11642
0
  if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
11643
0
    status = strerror(ERRNO);
11644
0
    mg_cry_internal(
11645
0
        conn,
11646
0
        "Error: CGI program \"%s\": Can not create CGI pipes: %s",
11647
0
        prog,
11648
0
        status);
11649
0
    mg_send_http_error(conn,
11650
0
                       500,
11651
0
                       "Error: Cannot create CGI pipe: %s",
11652
0
                       status);
11653
0
    goto done;
11654
0
  }
11655
11656
0
  proc = (struct process_control_data *)
11657
0
      mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
11658
0
  if (proc == NULL) {
11659
0
    mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
11660
0
    mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
11661
0
    goto done;
11662
0
  }
11663
11664
0
  DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
11665
0
  pid = spawn_process(
11666
0
      conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
11667
11668
0
  if (pid == (pid_t)-1) {
11669
0
    status = strerror(ERRNO);
11670
0
    mg_cry_internal(
11671
0
        conn,
11672
0
        "Error: CGI program \"%s\": Can not spawn CGI process: %s",
11673
0
        prog,
11674
0
        status);
11675
0
    mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
11676
0
    mg_free(proc);
11677
0
    proc = NULL;
11678
0
    goto done;
11679
0
  }
11680
11681
  /* Store data in shared process_control_data */
11682
0
  proc->pid = pid;
11683
0
  proc->references = 1;
11684
11685
#if defined(USE_TIMERS)
11686
  if (cgi_timeout > 0.0) {
11687
    proc->references = 2;
11688
11689
    // Start a timer for CGI
11690
    timer_add(conn->phys_ctx,
11691
              cgi_timeout /* in seconds */,
11692
              0.0,
11693
              1,
11694
              abort_cgi_process,
11695
              (void *)proc,
11696
              NULL);
11697
  }
11698
#endif
11699
11700
  /* Parent closes only one side of the pipes.
11701
   * If we don't mark them as closed, close() attempt before
11702
   * return from this function throws an exception on Windows.
11703
   * Windows does not like when closed descriptor is closed again. */
11704
0
  (void)close(fdin[0]);
11705
0
  (void)close(fdout[1]);
11706
0
  (void)close(fderr[1]);
11707
0
  fdin[0] = fdout[1] = fderr[1] = -1;
11708
11709
0
  if (((in = fdopen(fdin[1], "wb")) == NULL)
11710
0
      || ((out = fdopen(fdout[0], "rb")) == NULL)
11711
0
      || ((err = fdopen(fderr[0], "rb")) == NULL)) {
11712
0
    status = strerror(ERRNO);
11713
0
    mg_cry_internal(conn,
11714
0
                    "Error: CGI program \"%s\": Can not open fd: %s",
11715
0
                    prog,
11716
0
                    status);
11717
0
    mg_send_http_error(conn,
11718
0
                       500,
11719
0
                       "Error: CGI can not open fd\nfdopen: %s",
11720
0
                       status);
11721
0
    goto done;
11722
0
  }
11723
11724
0
  setbuf(in, NULL);
11725
0
  setbuf(out, NULL);
11726
0
  setbuf(err, NULL);
11727
0
  fout.access.fp = out;
11728
11729
0
  if ((conn->content_len != 0) || (conn->is_chunked)) {
11730
0
    DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
11731
0
                conn->content_len);
11732
11733
    /* This is a POST/PUT request, or another request with body data. */
11734
0
    if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
11735
      /* Error sending the body data */
11736
0
      mg_cry_internal(
11737
0
          conn,
11738
0
          "Error: CGI program \"%s\": Forward body data failed",
11739
0
          prog);
11740
0
      goto done;
11741
0
    }
11742
0
  }
11743
11744
  /* Close so child gets an EOF. */
11745
0
  fclose(in);
11746
0
  in = NULL;
11747
0
  fdin[1] = -1;
11748
11749
  /* Now read CGI reply into a buffer. We need to set correct
11750
   * status code, thus we need to see all HTTP headers first.
11751
   * Do not send anything back to client, until we buffer in all
11752
   * HTTP headers. */
11753
0
  data_len = 0;
11754
0
  buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
11755
0
  if (buf == NULL) {
11756
0
    mg_send_http_error(conn,
11757
0
                       500,
11758
0
                       "Error: Not enough memory for CGI buffer (%u bytes)",
11759
0
                       (unsigned int)buflen);
11760
0
    mg_cry_internal(
11761
0
        conn,
11762
0
        "Error: CGI program \"%s\": Not enough memory for buffer (%u "
11763
0
        "bytes)",
11764
0
        prog,
11765
0
        (unsigned int)buflen);
11766
0
    goto done;
11767
0
  }
11768
11769
0
  DEBUG_TRACE("CGI: %s", "wait for response");
11770
0
  headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
11771
0
  DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
11772
11773
0
  if (headers_len <= 0) {
11774
11775
    /* Could not parse the CGI response. Check if some error message on
11776
     * stderr. */
11777
0
    i = pull_all(err, conn, buf, (int)buflen);
11778
0
    if (i > 0) {
11779
      /* CGI program explicitly sent an error */
11780
      /* Write the error message to the internal log */
11781
0
      mg_cry_internal(conn,
11782
0
                      "Error: CGI program \"%s\" sent error "
11783
0
                      "message: [%.*s]",
11784
0
                      prog,
11785
0
                      i,
11786
0
                      buf);
11787
      /* Don't send the error message back to the client */
11788
0
      mg_send_http_error(conn,
11789
0
                         500,
11790
0
                         "Error: CGI program \"%s\" failed.",
11791
0
                         prog);
11792
0
    } else {
11793
      /* CGI program did not explicitly send an error, but a broken
11794
       * respon header */
11795
0
      mg_cry_internal(conn,
11796
0
                      "Error: CGI program sent malformed or too big "
11797
0
                      "(>%u bytes) HTTP headers: [%.*s]",
11798
0
                      (unsigned)buflen,
11799
0
                      data_len,
11800
0
                      buf);
11801
11802
0
      mg_send_http_error(conn,
11803
0
                         500,
11804
0
                         "Error: CGI program sent malformed or too big "
11805
0
                         "(>%u bytes) HTTP headers: [%.*s]",
11806
0
                         (unsigned)buflen,
11807
0
                         data_len,
11808
0
                         buf);
11809
0
    }
11810
11811
    /* in both cases, abort processing CGI */
11812
0
    goto done;
11813
0
  }
11814
11815
0
  pbuf = buf;
11816
0
  buf[headers_len - 1] = '\0';
11817
0
  ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
11818
11819
  /* Make up and send the status line */
11820
0
  status_text = "OK";
11821
0
  if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
11822
0
      != NULL) {
11823
0
    conn->status_code = atoi(status);
11824
0
    status_text = status;
11825
0
    while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
11826
0
      status_text++;
11827
0
    }
11828
0
  } else if (get_header(ri.http_headers, ri.num_headers, "Location")
11829
0
             != NULL) {
11830
0
    conn->status_code = 307;
11831
0
  } else {
11832
0
    conn->status_code = 200;
11833
0
  }
11834
11835
0
  if (!should_keep_alive(conn)) {
11836
0
    conn->must_close = 1;
11837
0
  }
11838
11839
0
  DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
11840
11841
0
  (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
11842
11843
  /* Send headers */
11844
0
  for (i = 0; i < ri.num_headers; i++) {
11845
0
    DEBUG_TRACE("CGI header: %s: %s",
11846
0
                ri.http_headers[i].name,
11847
0
                ri.http_headers[i].value);
11848
0
    mg_printf(conn,
11849
0
              "%s: %s\r\n",
11850
0
              ri.http_headers[i].name,
11851
0
              ri.http_headers[i].value);
11852
0
  }
11853
0
  mg_write(conn, "\r\n", 2);
11854
11855
  /* Send chunk of data that may have been read after the headers */
11856
0
  mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
11857
11858
  /* Read the rest of CGI output and send to the client */
11859
0
  DEBUG_TRACE("CGI: %s", "forward all data");
11860
0
  send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
11861
0
  DEBUG_TRACE("CGI: %s", "all data sent");
11862
11863
0
done:
11864
0
  mg_free(blk.var);
11865
0
  mg_free(blk.buf);
11866
11867
0
  if (pid != (pid_t)-1) {
11868
0
    abort_cgi_process((void *)proc);
11869
0
  }
11870
11871
0
  if (fdin[0] != -1) {
11872
0
    close(fdin[0]);
11873
0
  }
11874
0
  if (fdout[1] != -1) {
11875
0
    close(fdout[1]);
11876
0
  }
11877
0
  if (fderr[1] != -1) {
11878
0
    close(fderr[1]);
11879
0
  }
11880
11881
0
  if (in != NULL) {
11882
0
    fclose(in);
11883
0
  } else if (fdin[1] != -1) {
11884
0
    close(fdin[1]);
11885
0
  }
11886
11887
0
  if (out != NULL) {
11888
0
    fclose(out);
11889
0
  } else if (fdout[0] != -1) {
11890
0
    close(fdout[0]);
11891
0
  }
11892
11893
0
  if (err != NULL) {
11894
0
    fclose(err);
11895
0
  } else if (fderr[0] != -1) {
11896
0
    close(fderr[0]);
11897
0
  }
11898
11899
0
  mg_free(buf);
11900
0
}
11901
#endif /* !NO_CGI */
11902
11903
11904
#if !defined(NO_FILES)
11905
static void
11906
dav_mkcol(struct mg_connection *conn, const char *path)
11907
0
{
11908
0
  int rc, body_len;
11909
0
  struct de de;
11910
11911
0
  if (conn == NULL) {
11912
0
    return;
11913
0
  }
11914
11915
  /* TODO (mid): Check the mg_send_http_error situations in this function
11916
   */
11917
11918
0
  memset(&de.file, 0, sizeof(de.file));
11919
0
  if (!mg_stat(conn, path, &de.file)) {
11920
0
    mg_cry_internal(conn,
11921
0
                    "%s: mg_stat(%s) failed: %s",
11922
0
                    __func__,
11923
0
                    path,
11924
0
                    strerror(ERRNO));
11925
0
  }
11926
11927
0
  if (de.file.last_modified) {
11928
    /* TODO (mid): This check does not seem to make any sense ! */
11929
    /* TODO (mid): Add a webdav unit test first, before changing
11930
     * anything here. */
11931
0
    mg_send_http_error(
11932
0
        conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11933
0
    return;
11934
0
  }
11935
11936
0
  body_len = conn->data_len - conn->request_len;
11937
0
  if (body_len > 0) {
11938
0
    mg_send_http_error(
11939
0
        conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11940
0
    return;
11941
0
  }
11942
11943
0
  rc = mg_mkdir(conn, path, 0755);
11944
0
  DEBUG_TRACE("mkdir %s: %i", path, rc);
11945
0
  if (rc == 0) {
11946
    /* Create 201 "Created" response */
11947
0
    mg_response_header_start(conn, 201);
11948
0
    send_static_cache_header(conn);
11949
0
    send_additional_header(conn);
11950
0
    mg_response_header_add(conn, "Content-Length", "0", -1);
11951
11952
    /* Send all headers - there is no body */
11953
0
    mg_response_header_send(conn);
11954
0
  } else {
11955
0
    int http_status = 500;
11956
0
    switch (errno) {
11957
0
    case EEXIST:
11958
0
      http_status = 405;
11959
0
      break;
11960
0
    case EACCES:
11961
0
      http_status = 403;
11962
0
      break;
11963
0
    case ENOENT:
11964
0
      http_status = 409;
11965
0
      break;
11966
0
    }
11967
11968
0
    mg_send_http_error(conn,
11969
0
                       http_status,
11970
0
                       "Error processing %s: %s",
11971
0
                       path,
11972
0
                       strerror(ERRNO));
11973
0
  }
11974
0
}
11975
11976
11977
/* Forward decrlaration */
11978
static int get_uri_type(const char *uri);
11979
static const char *
11980
get_rel_url_at_current_server(const char *uri,
11981
                              const struct mg_connection *conn);
11982
11983
11984
static void
11985
dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
11986
0
{
11987
0
  const char *overwrite_hdr;
11988
0
  const char *destination_hdr;
11989
0
  const char *root;
11990
0
  int rc, dest_uri_type;
11991
0
  int http_status = 400;
11992
0
  int do_overwrite = 0;
11993
0
  int destination_ok = 0;
11994
0
  char dest_path[UTF8_PATH_MAX];
11995
0
  struct mg_file_stat ignored;
11996
11997
0
  if (conn == NULL) {
11998
0
    return;
11999
0
  }
12000
12001
0
  root = conn->dom_ctx->config[DOCUMENT_ROOT];
12002
0
  overwrite_hdr = mg_get_header(conn, "Overwrite");
12003
0
  destination_hdr = mg_get_header(conn, "Destination");
12004
0
  if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
12005
0
    do_overwrite = 1;
12006
0
  }
12007
12008
0
  if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
12009
0
    mg_send_http_error(conn, 400, "%s", "Missing destination");
12010
0
    return;
12011
0
  }
12012
12013
0
  if (root != NULL) {
12014
0
    char *local_dest = NULL;
12015
0
    dest_uri_type = get_uri_type(destination_hdr);
12016
0
    if (dest_uri_type == 2) {
12017
0
      local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
12018
0
    } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
12019
0
      const char *h =
12020
0
          get_rel_url_at_current_server(destination_hdr, conn);
12021
0
      if (h) {
12022
0
        int len = (int)strlen(h);
12023
0
        local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
12024
0
        mg_url_decode(h, len, local_dest, len + 1, 0);
12025
0
      }
12026
0
    }
12027
0
    if (local_dest != NULL) {
12028
0
      remove_dot_segments(local_dest);
12029
0
      if (local_dest[0] == '/') {
12030
0
        int trunc_check = 0;
12031
0
        mg_snprintf(conn,
12032
0
                    &trunc_check,
12033
0
                    dest_path,
12034
0
                    sizeof(dest_path),
12035
0
                    "%s/%s",
12036
0
                    root,
12037
0
                    local_dest);
12038
0
        if (trunc_check == 0) {
12039
0
          destination_ok = 1;
12040
0
        }
12041
0
      }
12042
0
      mg_free(local_dest);
12043
0
    }
12044
0
  }
12045
12046
0
  if (!destination_ok) {
12047
0
    mg_send_http_error(conn, 502, "%s", "Illegal destination");
12048
0
    return;
12049
0
  }
12050
12051
  /* Check now if this file exists */
12052
0
  if (mg_stat(conn, dest_path, &ignored)) {
12053
    /* File exists */
12054
0
    if (do_overwrite) {
12055
      /* Overwrite allowed: delete the file first */
12056
0
      if (0 != remove(dest_path)) {
12057
        /* No overwrite: return error */
12058
0
        mg_send_http_error(conn,
12059
0
                           403,
12060
0
                           "Cannot overwrite file: %s",
12061
0
                           dest_path);
12062
0
        return;
12063
0
      }
12064
0
    } else {
12065
      /* No overwrite: return error */
12066
0
      mg_send_http_error(conn,
12067
0
                         412,
12068
0
                         "Destination already exists: %s",
12069
0
                         dest_path);
12070
0
      return;
12071
0
    }
12072
0
  }
12073
12074
  /* Copy / Move / Rename operation. */
12075
0
  DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
12076
#if defined(_WIN32)
12077
  {
12078
    /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
12079
    wchar_t wSource[UTF16_PATH_MAX];
12080
    wchar_t wDest[UTF16_PATH_MAX];
12081
    BOOL ok;
12082
12083
    path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
12084
    path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
12085
    if (do_copy) {
12086
      ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
12087
    } else {
12088
      ok = MoveFileExW(wSource,
12089
                       wDest,
12090
                       do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
12091
    }
12092
    if (ok) {
12093
      rc = 0;
12094
    } else {
12095
      DWORD lastErr = GetLastError();
12096
      if (lastErr == ERROR_ALREADY_EXISTS) {
12097
        mg_send_http_error(conn,
12098
                           412,
12099
                           "Destination already exists: %s",
12100
                           dest_path);
12101
        return;
12102
      }
12103
      rc = -1;
12104
      http_status = 400;
12105
    }
12106
  }
12107
12108
#else
12109
0
  {
12110
    /* Linux uses already UTF-8, we don't need to convert file names. */
12111
12112
0
    if (do_copy) {
12113
      /* TODO: COPY for Linux. */
12114
0
      mg_send_http_error(conn, 403, "%s", "COPY forbidden");
12115
0
      return;
12116
0
    }
12117
12118
0
    rc = rename(path, dest_path);
12119
0
    if (rc) {
12120
0
      switch (errno) {
12121
0
      case EEXIST:
12122
0
        http_status = 412;
12123
0
        break;
12124
0
      case EACCES:
12125
0
        http_status = 403;
12126
0
        break;
12127
0
      case ENOENT:
12128
0
        http_status = 409;
12129
0
        break;
12130
0
      }
12131
0
    }
12132
0
  }
12133
0
#endif
12134
12135
0
  if (rc == 0) {
12136
    /* Create 204 "No Content" response */
12137
0
    mg_response_header_start(conn, 204);
12138
0
    mg_response_header_add(conn, "Content-Length", "0", -1);
12139
12140
    /* Send all headers - there is no body */
12141
0
    mg_response_header_send(conn);
12142
0
  } else {
12143
0
    mg_send_http_error(conn, http_status, "Operation failed");
12144
0
  }
12145
0
}
12146
12147
12148
static void
12149
put_file(struct mg_connection *conn, const char *path)
12150
0
{
12151
0
  struct mg_file file = STRUCT_FILE_INITIALIZER;
12152
0
  const char *range;
12153
0
  int64_t r1, r2;
12154
0
  int rc;
12155
12156
0
  if (conn == NULL) {
12157
0
    return;
12158
0
  }
12159
12160
0
  DEBUG_TRACE("store %s", path);
12161
12162
0
  if (mg_stat(conn, path, &file.stat)) {
12163
    /* File already exists */
12164
0
    conn->status_code = 200;
12165
12166
0
    if (file.stat.is_directory) {
12167
      /* This is an already existing directory,
12168
       * so there is nothing to do for the server. */
12169
0
      rc = 0;
12170
12171
0
    } else {
12172
      /* File exists and is not a directory. */
12173
      /* Can it be replaced? */
12174
12175
      /* Check if the server may write this file */
12176
0
      if (access(path, W_OK) == 0) {
12177
        /* Access granted */
12178
0
        rc = 1;
12179
0
      } else {
12180
0
        mg_send_http_error(
12181
0
            conn,
12182
0
            403,
12183
0
            "Error: Put not possible\nReplacing %s is not allowed",
12184
0
            path);
12185
0
        return;
12186
0
      }
12187
0
    }
12188
0
  } else {
12189
    /* File should be created */
12190
0
    conn->status_code = 201;
12191
0
    rc = put_dir(conn, path);
12192
0
  }
12193
12194
0
  if (rc == 0) {
12195
    /* put_dir returns 0 if path is a directory */
12196
12197
    /* Create response */
12198
0
    mg_response_header_start(conn, conn->status_code);
12199
0
    send_no_cache_header(conn);
12200
0
    send_additional_header(conn);
12201
0
    mg_response_header_add(conn, "Content-Length", "0", -1);
12202
12203
    /* Send all headers - there is no body */
12204
0
    mg_response_header_send(conn);
12205
12206
    /* Request to create a directory has been fulfilled successfully.
12207
     * No need to put a file. */
12208
0
    return;
12209
0
  }
12210
12211
0
  if (rc == -1) {
12212
    /* put_dir returns -1 if the path is too long */
12213
0
    mg_send_http_error(conn,
12214
0
                       414,
12215
0
                       "Error: Path too long\nput_dir(%s): %s",
12216
0
                       path,
12217
0
                       strerror(ERRNO));
12218
0
    return;
12219
0
  }
12220
12221
0
  if (rc == -2) {
12222
    /* put_dir returns -2 if the directory can not be created */
12223
0
    mg_send_http_error(conn,
12224
0
                       500,
12225
0
                       "Error: Can not create directory\nput_dir(%s): %s",
12226
0
                       path,
12227
0
                       strerror(ERRNO));
12228
0
    return;
12229
0
  }
12230
12231
  /* A file should be created or overwritten. */
12232
  /* Currently CivetWeb does not need read+write access. */
12233
0
  if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
12234
0
      || file.access.fp == NULL) {
12235
0
    (void)mg_fclose(&file.access);
12236
0
    mg_send_http_error(conn,
12237
0
                       500,
12238
0
                       "Error: Can not create file\nfopen(%s): %s",
12239
0
                       path,
12240
0
                       strerror(ERRNO));
12241
0
    return;
12242
0
  }
12243
12244
0
  fclose_on_exec(&file.access, conn);
12245
0
  range = mg_get_header(conn, "Content-Range");
12246
0
  r1 = r2 = 0;
12247
0
  if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
12248
0
    conn->status_code = 206; /* Partial content */
12249
0
    if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
12250
0
      mg_send_http_error(conn,
12251
0
                         500,
12252
0
                         "Error: Internal error processing file %s",
12253
0
                         path);
12254
0
      return;
12255
0
    }
12256
0
  }
12257
12258
0
  if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
12259
    /* forward_body_data failed.
12260
     * The error code has already been sent to the client,
12261
     * and conn->status_code is already set. */
12262
0
    (void)mg_fclose(&file.access);
12263
0
    return;
12264
0
  }
12265
12266
0
  if (mg_fclose(&file.access) != 0) {
12267
    /* fclose failed. This might have different reasons, but a likely
12268
     * one is "no space on disk", http 507. */
12269
0
    conn->status_code = 507;
12270
0
  }
12271
12272
  /* Create response (status_code has been set before) */
12273
0
  mg_response_header_start(conn, conn->status_code);
12274
0
  send_no_cache_header(conn);
12275
0
  send_additional_header(conn);
12276
0
  mg_response_header_add(conn, "Content-Length", "0", -1);
12277
12278
  /* Send all headers - there is no body */
12279
0
  mg_response_header_send(conn);
12280
0
}
12281
12282
12283
static void
12284
delete_file(struct mg_connection *conn, const char *path)
12285
0
{
12286
0
  struct de de;
12287
0
  memset(&de.file, 0, sizeof(de.file));
12288
0
  if (!mg_stat(conn, path, &de.file)) {
12289
    /* mg_stat returns 0 if the file does not exist */
12290
0
    mg_send_http_error(conn,
12291
0
                       404,
12292
0
                       "Error: Cannot delete file\nFile %s not found",
12293
0
                       path);
12294
0
    return;
12295
0
  }
12296
12297
0
  DEBUG_TRACE("delete %s", path);
12298
12299
0
  if (de.file.is_directory) {
12300
0
    if (remove_directory(conn, path)) {
12301
      /* Delete is successful: Return 204 without content. */
12302
0
      mg_send_http_error(conn, 204, "%s", "");
12303
0
    } else {
12304
      /* Delete is not successful: Return 500 (Server error). */
12305
0
      mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
12306
0
    }
12307
0
    return;
12308
0
  }
12309
12310
  /* This is an existing file (not a directory).
12311
   * Check if write permission is granted. */
12312
0
  if (access(path, W_OK) != 0) {
12313
    /* File is read only */
12314
0
    mg_send_http_error(
12315
0
        conn,
12316
0
        403,
12317
0
        "Error: Delete not possible\nDeleting %s is not allowed",
12318
0
        path);
12319
0
    return;
12320
0
  }
12321
12322
  /* Try to delete it. */
12323
0
  if (mg_remove(conn, path) == 0) {
12324
    /* Delete was successful: Return 204 without content. */
12325
0
    mg_response_header_start(conn, 204);
12326
0
    send_no_cache_header(conn);
12327
0
    send_additional_header(conn);
12328
0
    mg_response_header_add(conn, "Content-Length", "0", -1);
12329
0
    mg_response_header_send(conn);
12330
12331
0
  } else {
12332
    /* Delete not successful (file locked). */
12333
0
    mg_send_http_error(conn,
12334
0
                       423,
12335
0
                       "Error: Cannot delete file\nremove(%s): %s",
12336
0
                       path,
12337
0
                       strerror(ERRNO));
12338
0
  }
12339
0
}
12340
#endif /* !NO_FILES */
12341
12342
12343
#if !defined(NO_FILESYSTEMS)
12344
static void
12345
send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
12346
12347
12348
static void
12349
do_ssi_include(struct mg_connection *conn,
12350
               const char *ssi,
12351
               char *tag,
12352
               int include_level)
12353
0
{
12354
0
  char file_name[MG_BUF_LEN], path[512], *p;
12355
0
  struct mg_file file = STRUCT_FILE_INITIALIZER;
12356
0
  size_t len;
12357
0
  int truncated = 0;
12358
12359
0
  if (conn == NULL) {
12360
0
    return;
12361
0
  }
12362
12363
  /* sscanf() is safe here, since send_ssi_file() also uses buffer
12364
   * of size MG_BUF_LEN to get the tag. So strlen(tag) is
12365
   * always < MG_BUF_LEN. */
12366
0
  if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
12367
    /* File name is relative to the webserver root */
12368
0
    file_name[511] = 0;
12369
0
    (void)mg_snprintf(conn,
12370
0
                      &truncated,
12371
0
                      path,
12372
0
                      sizeof(path),
12373
0
                      "%s/%s",
12374
0
                      conn->dom_ctx->config[DOCUMENT_ROOT],
12375
0
                      file_name);
12376
12377
0
  } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
12378
    /* File name is relative to the webserver working directory
12379
     * or it is absolute system path */
12380
0
    file_name[511] = 0;
12381
0
    (void)
12382
0
        mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
12383
12384
0
  } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
12385
0
             || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
12386
    /* File name is relative to the current document */
12387
0
    file_name[511] = 0;
12388
0
    (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
12389
12390
0
    if (!truncated) {
12391
0
      if ((p = strrchr(path, '/')) != NULL) {
12392
0
        p[1] = '\0';
12393
0
      }
12394
0
      len = strlen(path);
12395
0
      (void)mg_snprintf(conn,
12396
0
                        &truncated,
12397
0
                        path + len,
12398
0
                        sizeof(path) - len,
12399
0
                        "%s",
12400
0
                        file_name);
12401
0
    }
12402
12403
0
  } else {
12404
0
    mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
12405
0
    return;
12406
0
  }
12407
12408
0
  if (truncated) {
12409
0
    mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
12410
0
    return;
12411
0
  }
12412
12413
0
  if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
12414
0
    mg_cry_internal(conn,
12415
0
                    "Cannot open SSI #include: [%s]: fopen(%s): %s",
12416
0
                    tag,
12417
0
                    path,
12418
0
                    strerror(ERRNO));
12419
0
  } else {
12420
0
    fclose_on_exec(&file.access, conn);
12421
0
    if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
12422
0
        > 0) {
12423
0
      send_ssi_file(conn, path, &file, include_level + 1);
12424
0
    } else {
12425
0
      send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
12426
0
    }
12427
0
    (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
12428
0
  }
12429
0
}
12430
12431
12432
#if !defined(NO_POPEN)
12433
static void
12434
do_ssi_exec(struct mg_connection *conn, char *tag)
12435
0
{
12436
0
  char cmd[1024] = "";
12437
0
  struct mg_file file = STRUCT_FILE_INITIALIZER;
12438
12439
0
  if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
12440
0
    mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
12441
0
  } else {
12442
0
    cmd[1023] = 0;
12443
0
    if ((file.access.fp = popen(cmd, "r")) == NULL) {
12444
0
      mg_cry_internal(conn,
12445
0
                      "Cannot SSI #exec: [%s]: %s",
12446
0
                      cmd,
12447
0
                      strerror(ERRNO));
12448
0
    } else {
12449
0
      send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
12450
0
      pclose(file.access.fp);
12451
0
    }
12452
0
  }
12453
0
}
12454
#endif /* !NO_POPEN */
12455
12456
12457
static int
12458
mg_fgetc(struct mg_file *filep)
12459
0
{
12460
0
  if (filep == NULL) {
12461
0
    return EOF;
12462
0
  }
12463
12464
0
  if (filep->access.fp != NULL) {
12465
0
    return fgetc(filep->access.fp);
12466
0
  } else {
12467
0
    return EOF;
12468
0
  }
12469
0
}
12470
12471
12472
static void
12473
send_ssi_file(struct mg_connection *conn,
12474
              const char *path,
12475
              struct mg_file *filep,
12476
              int include_level)
12477
0
{
12478
0
  char buf[MG_BUF_LEN];
12479
0
  int ch, len, in_tag, in_ssi_tag;
12480
12481
0
  if (include_level > 10) {
12482
0
    mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
12483
0
    return;
12484
0
  }
12485
12486
0
  in_tag = in_ssi_tag = len = 0;
12487
12488
  /* Read file, byte by byte, and look for SSI include tags */
12489
0
  while ((ch = mg_fgetc(filep)) != EOF) {
12490
12491
0
    if (in_tag) {
12492
      /* We are in a tag, either SSI tag or html tag */
12493
12494
0
      if (ch == '>') {
12495
        /* Tag is closing */
12496
0
        buf[len++] = '>';
12497
12498
0
        if (in_ssi_tag) {
12499
          /* Handle SSI tag */
12500
0
          buf[len] = 0;
12501
12502
0
          if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
12503
0
            do_ssi_include(conn, path, buf + 12, include_level + 1);
12504
0
#if !defined(NO_POPEN)
12505
0
          } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
12506
0
            do_ssi_exec(conn, buf + 9);
12507
0
#endif /* !NO_POPEN */
12508
0
          } else {
12509
0
            mg_cry_internal(conn,
12510
0
                            "%s: unknown SSI "
12511
0
                            "command: \"%s\"",
12512
0
                            path,
12513
0
                            buf);
12514
0
          }
12515
0
          len = 0;
12516
0
          in_ssi_tag = in_tag = 0;
12517
12518
0
        } else {
12519
          /* Not an SSI tag */
12520
          /* Flush buffer */
12521
0
          (void)mg_write(conn, buf, (size_t)len);
12522
0
          len = 0;
12523
0
          in_tag = 0;
12524
0
        }
12525
12526
0
      } else {
12527
        /* Tag is still open */
12528
0
        buf[len++] = (char)(ch & 0xff);
12529
12530
0
        if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
12531
          /* All SSI tags start with <!--# */
12532
0
          in_ssi_tag = 1;
12533
0
        }
12534
12535
0
        if ((len + 2) > (int)sizeof(buf)) {
12536
          /* Tag to long for buffer */
12537
0
          mg_cry_internal(conn, "%s: tag is too large", path);
12538
0
          return;
12539
0
        }
12540
0
      }
12541
12542
0
    } else {
12543
12544
      /* We are not in a tag yet. */
12545
0
      if (ch == '<') {
12546
        /* Tag is opening */
12547
0
        in_tag = 1;
12548
12549
0
        if (len > 0) {
12550
          /* Flush current buffer.
12551
           * Buffer is filled with "len" bytes. */
12552
0
          (void)mg_write(conn, buf, (size_t)len);
12553
0
        }
12554
        /* Store the < */
12555
0
        len = 1;
12556
0
        buf[0] = '<';
12557
12558
0
      } else {
12559
        /* No Tag */
12560
        /* Add data to buffer */
12561
0
        buf[len++] = (char)(ch & 0xff);
12562
        /* Flush if buffer is full */
12563
0
        if (len == (int)sizeof(buf)) {
12564
0
          mg_write(conn, buf, (size_t)len);
12565
0
          len = 0;
12566
0
        }
12567
0
      }
12568
0
    }
12569
0
  }
12570
12571
  /* Send the rest of buffered data */
12572
0
  if (len > 0) {
12573
0
    mg_write(conn, buf, (size_t)len);
12574
0
  }
12575
0
}
12576
12577
12578
static void
12579
handle_ssi_file_request(struct mg_connection *conn,
12580
                        const char *path,
12581
                        struct mg_file *filep)
12582
0
{
12583
0
  char date[64];
12584
0
  time_t curtime = time(NULL);
12585
12586
0
  if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
12587
0
    return;
12588
0
  }
12589
12590
0
  if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
12591
    /* File exists (precondition for calling this function),
12592
     * but can not be opened by the server. */
12593
0
    mg_send_http_error(conn,
12594
0
                       500,
12595
0
                       "Error: Cannot read file\nfopen(%s): %s",
12596
0
                       path,
12597
0
                       strerror(ERRNO));
12598
0
  } else {
12599
    /* Set "must_close" for HTTP/1.x, since we do not know the
12600
     * content length */
12601
0
    conn->must_close = 1;
12602
0
    gmt_time_string(date, sizeof(date), &curtime);
12603
0
    fclose_on_exec(&filep->access, conn);
12604
12605
    /* 200 OK response */
12606
0
    mg_response_header_start(conn, 200);
12607
0
    send_no_cache_header(conn);
12608
0
    send_additional_header(conn);
12609
0
    send_cors_header(conn);
12610
0
    mg_response_header_add(conn, "Content-Type", "text/html", -1);
12611
0
    mg_response_header_send(conn);
12612
12613
    /* Header sent, now send body */
12614
0
    send_ssi_file(conn, path, filep, 0);
12615
0
    (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
12616
0
  }
12617
0
}
12618
#endif /* NO_FILESYSTEMS */
12619
12620
12621
#if !defined(NO_FILES)
12622
static void
12623
send_options(struct mg_connection *conn)
12624
0
{
12625
0
  if (!conn || !all_methods) {
12626
0
    return;
12627
0
  }
12628
12629
  /* We do not set a "Cache-Control" header here, but leave the default.
12630
   * Since browsers do not send an OPTIONS request, we can not test the
12631
   * effect anyway. */
12632
12633
0
  mg_response_header_start(conn, 200);
12634
0
  mg_response_header_add(conn, "Content-Type", "text/html", -1);
12635
12636
0
  if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
12637
    /* Use the same as before */
12638
0
    mg_response_header_add(conn, "Allow", all_methods, -1);
12639
0
    mg_response_header_add(conn, "DAV", "1", -1);
12640
0
  } else {
12641
    /* TODO: Check this later for HTTP/2 */
12642
0
    mg_response_header_add(conn, "Allow", "GET, POST", -1);
12643
0
  }
12644
0
  send_additional_header(conn);
12645
0
  mg_response_header_send(conn);
12646
0
}
12647
12648
12649
/* Writes PROPFIND properties for a collection element */
12650
static int
12651
print_props(struct mg_connection *conn,
12652
            const char *uri,
12653
            const char *name,
12654
            struct mg_file_stat *filep)
12655
0
{
12656
0
  size_t i;
12657
0
  char mtime[64];
12658
0
  char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
12659
0
  char *link_concat;
12660
0
  size_t link_concat_len;
12661
12662
0
  if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
12663
0
    return 0;
12664
0
  }
12665
12666
0
  link_concat_len = strlen(uri) + strlen(name) + 1;
12667
0
  link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
12668
0
  if (!link_concat) {
12669
0
    return 0;
12670
0
  }
12671
0
  strcpy(link_concat, uri);
12672
0
  strcat(link_concat, name);
12673
12674
  /* Get full link used in request */
12675
0
  mg_construct_local_link(
12676
0
      conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
12677
12678
  /*
12679
  OutputDebugStringA("print_props:\n  uri: ");
12680
  OutputDebugStringA(uri);
12681
  OutputDebugStringA("\n  name: ");
12682
  OutputDebugStringA(name);
12683
  OutputDebugStringA("\n  link: ");
12684
  OutputDebugStringA(link_buf);
12685
  OutputDebugStringA("\n");
12686
  */
12687
12688
0
  gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
12689
0
  mg_printf(conn,
12690
0
            "<d:response>"
12691
0
            "<d:href>%s</d:href>"
12692
0
            "<d:propstat>"
12693
0
            "<d:prop>"
12694
0
            "<d:resourcetype>%s</d:resourcetype>"
12695
0
            "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
12696
0
            "<d:getlastmodified>%s</d:getlastmodified>"
12697
0
            "<d:lockdiscovery>",
12698
0
            link_buf,
12699
0
            filep->is_directory ? "<d:collection/>" : "",
12700
0
            filep->size,
12701
0
            mtime);
12702
12703
0
  for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
12704
0
    struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
12705
0
    if (!strcmp(dav_lock[i].path, link_buf)) {
12706
0
      mg_printf(conn,
12707
0
                "<d:activelock>"
12708
0
                "<d:locktype><d:write/></d:locktype>"
12709
0
                "<d:lockscope><d:exclusive/></d:lockscope>"
12710
0
                "<d:depth>0</d:depth>"
12711
0
                "<d:owner>%s</d:owner>"
12712
0
                "<d:timeout>Second-%u</d:timeout>"
12713
0
                "<d:locktoken>"
12714
0
                "<d:href>%s</d:href>"
12715
0
                "</d:locktoken>"
12716
0
                "</d:activelock>\n",
12717
0
                dav_lock[i].user,
12718
0
                (unsigned)LOCK_DURATION_S,
12719
0
                dav_lock[i].token);
12720
0
    }
12721
0
  }
12722
12723
0
  mg_printf(conn,
12724
0
            "</d:lockdiscovery>"
12725
0
            "</d:prop>"
12726
0
            "<d:status>HTTP/1.1 200 OK</d:status>"
12727
0
            "</d:propstat>"
12728
0
            "</d:response>\n");
12729
12730
0
  mg_free(link_concat);
12731
0
  return 1;
12732
0
}
12733
12734
12735
static int
12736
print_dav_dir_entry(struct de *de, void *data)
12737
0
{
12738
0
  struct mg_connection *conn = (struct mg_connection *)data;
12739
0
  if (!de || !conn
12740
0
      || !print_props(
12741
0
             conn, conn->request_info.local_uri, de->file_name, &de->file)) {
12742
    /* stop scan */
12743
0
    return 1;
12744
0
  }
12745
0
  return 0;
12746
0
}
12747
12748
12749
static void
12750
handle_propfind(struct mg_connection *conn,
12751
                const char *path,
12752
                struct mg_file_stat *filep)
12753
0
{
12754
0
  const char *depth = mg_get_header(conn, "Depth");
12755
12756
0
  if (!conn || !path || !filep || !conn->dom_ctx) {
12757
0
    return;
12758
0
  }
12759
12760
  /* return 207 "Multi-Status" */
12761
0
  conn->must_close = 1;
12762
0
  mg_response_header_start(conn, 207);
12763
0
  send_static_cache_header(conn);
12764
0
  send_additional_header(conn);
12765
0
  mg_response_header_add(conn,
12766
0
                         "Content-Type",
12767
0
                         "application/xml; charset=utf-8",
12768
0
                         -1);
12769
0
  mg_response_header_send(conn);
12770
12771
  /* Content */
12772
0
  mg_printf(conn,
12773
0
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12774
0
            "<d:multistatus xmlns:d='DAV:'>\n");
12775
12776
  /* Print properties for the requested resource itself */
12777
0
  print_props(conn, conn->request_info.local_uri, "", filep);
12778
12779
  /* If it is a directory, print directory entries too if Depth is not 0
12780
   */
12781
0
  if (filep->is_directory
12782
0
      && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
12783
0
                        "yes")
12784
0
      && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
12785
0
    scan_directory(conn, path, conn, &print_dav_dir_entry);
12786
0
  }
12787
12788
0
  mg_printf(conn, "%s\n", "</d:multistatus>");
12789
0
}
12790
12791
12792
static void
12793
dav_lock_file(struct mg_connection *conn, const char *path)
12794
0
{
12795
  /* internal function - therefore conn is assumed to be valid */
12796
0
  char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
12797
0
  uint64_t new_locktime;
12798
0
  int lock_index = -1;
12799
0
  int i;
12800
0
  uint64_t LOCK_DURATION_NS =
12801
0
      (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
12802
0
  struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
12803
12804
0
  if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
12805
0
    return;
12806
0
  }
12807
0
  mg_get_request_link(conn, link_buf, sizeof(link_buf));
12808
12809
  /* const char *refresh = mg_get_header(conn, "If"); */
12810
  /* Link refresh should have an "If" header:
12811
   * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
12812
   * But it seems Windows Explorer does not send them.
12813
   */
12814
12815
0
  mg_lock_context(conn->phys_ctx);
12816
0
  new_locktime = mg_get_current_time_ns();
12817
12818
  /* Find a slot for a lock */
12819
0
  while (lock_index < 0) {
12820
    /* find existing lock */
12821
0
    for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
12822
0
      if (!strcmp(dav_lock[i].path, link_buf)) {
12823
0
        if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
12824
          /* locked by the same user */
12825
0
          dav_lock[i].locktime = new_locktime;
12826
0
          lock_index = i;
12827
0
          break;
12828
0
        } else {
12829
          /* already locked by someone else */
12830
0
          if (new_locktime
12831
0
              > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
12832
            /* Lock expired */
12833
0
            dav_lock[i].path[0] = 0;
12834
0
          } else {
12835
            /* Lock still valid */
12836
0
            mg_unlock_context(conn->phys_ctx);
12837
0
            mg_send_http_error(conn, 423, "%s", "Already locked");
12838
0
            return;
12839
0
          }
12840
0
        }
12841
0
      }
12842
0
    }
12843
12844
    /* create new lock token */
12845
0
    for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
12846
0
      if (dav_lock[i].path[0] == 0) {
12847
0
        char s[32];
12848
0
        dav_lock[i].locktime = mg_get_current_time_ns();
12849
0
        sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
12850
0
        mg_md5(dav_lock[i].token,
12851
0
               link_buf,
12852
0
               "\x01",
12853
0
               s,
12854
0
               "\x01",
12855
0
               conn->request_info.remote_user,
12856
0
               NULL);
12857
0
        mg_strlcpy(dav_lock[i].path,
12858
0
                   link_buf,
12859
0
                   sizeof(dav_lock[i].path));
12860
0
        mg_strlcpy(dav_lock[i].user,
12861
0
                   conn->request_info.remote_user,
12862
0
                   sizeof(dav_lock[i].user));
12863
0
        lock_index = i;
12864
0
        break;
12865
0
      }
12866
0
    }
12867
0
    if (lock_index < 0) {
12868
      /* too many locks. Find oldest lock */
12869
0
      uint64_t oldest_locktime = dav_lock[0].locktime;
12870
0
      lock_index = 0;
12871
0
      for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
12872
0
        if (dav_lock[i].locktime < oldest_locktime) {
12873
0
          oldest_locktime = dav_lock[i].locktime;
12874
0
          lock_index = i;
12875
0
        }
12876
0
      }
12877
      /* invalidate oldest lock */
12878
0
      dav_lock[lock_index].path[0] = 0;
12879
0
    }
12880
0
  }
12881
0
  mg_unlock_context(conn->phys_ctx);
12882
12883
  /* return 200 "OK" */
12884
0
  conn->must_close = 1;
12885
0
  mg_response_header_start(conn, 200);
12886
0
  send_static_cache_header(conn);
12887
0
  send_additional_header(conn);
12888
0
  mg_response_header_add(conn,
12889
0
                         "Content-Type",
12890
0
                         "application/xml; charset=utf-8",
12891
0
                         -1);
12892
0
  mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
12893
0
  mg_response_header_send(conn);
12894
12895
  /* Content */
12896
0
  mg_printf(conn,
12897
0
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12898
0
            "<d:prop xmlns:d=\"DAV:\">\n"
12899
0
            "     <d:lockdiscovery>\n"
12900
0
            "       <d:activelock>\n"
12901
0
            "         <d:lockscope><d:exclusive/></d:lockscope>\n"
12902
0
            "         <d:locktype><d:write/></d:locktype>\n"
12903
0
            "         <d:owner>\n"
12904
0
            "           <d:href>%s</d:href>\n"
12905
0
            "         </d:owner>\n"
12906
0
            "         <d:timeout>Second-%u</d:timeout>\n"
12907
0
            "         <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
12908
0
            "         <d:lockroot>\n"
12909
0
            "           <d:href>%s</d:href>\n"
12910
0
            "         </d:lockroot>\n"
12911
0
            "       </d:activelock>\n"
12912
0
            "     </d:lockdiscovery>\n"
12913
0
            "   </d:prop>\n",
12914
0
            dav_lock[lock_index].user,
12915
0
            (LOCK_DURATION_S),
12916
0
            dav_lock[lock_index].token,
12917
0
            dav_lock[lock_index].path);
12918
0
}
12919
12920
12921
static void
12922
dav_unlock_file(struct mg_connection *conn, const char *path)
12923
0
{
12924
  /* internal function - therefore conn is assumed to be valid */
12925
0
  char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
12926
0
  struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
12927
0
  int lock_index;
12928
12929
0
  if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
12930
0
    return;
12931
0
  }
12932
12933
0
  mg_get_request_link(conn, link_buf, sizeof(link_buf));
12934
12935
0
  mg_lock_context(conn->phys_ctx);
12936
  /* find existing lock */
12937
0
  for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
12938
0
    if (!strcmp(dav_lock[lock_index].path, link_buf)) {
12939
      /* Success: return 204 "No Content" */
12940
0
      mg_unlock_context(conn->phys_ctx);
12941
0
      conn->must_close = 1;
12942
0
      mg_response_header_start(conn, 204);
12943
0
      mg_response_header_send(conn);
12944
0
      return;
12945
0
    }
12946
0
  }
12947
0
  mg_unlock_context(conn->phys_ctx);
12948
12949
  /* Error: Cannot unlock a resource that is not locked */
12950
0
  mg_send_http_error(conn, 423, "%s", "Lock not found");
12951
0
}
12952
12953
12954
static void
12955
dav_proppatch(struct mg_connection *conn, const char *path)
12956
0
{
12957
0
  char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
12958
12959
0
  if (!conn || !path || !conn->dom_ctx) {
12960
0
    return;
12961
0
  }
12962
12963
  /* return 207 "Multi-Status" */
12964
0
  conn->must_close = 1;
12965
0
  mg_response_header_start(conn, 207);
12966
0
  send_static_cache_header(conn);
12967
0
  send_additional_header(conn);
12968
0
  mg_response_header_add(conn,
12969
0
                         "Content-Type",
12970
0
                         "application/xml; charset=utf-8",
12971
0
                         -1);
12972
0
  mg_response_header_send(conn);
12973
12974
0
  mg_get_request_link(conn, link_buf, sizeof(link_buf));
12975
12976
  /* Content */
12977
0
  mg_printf(conn,
12978
0
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12979
0
            "<d:multistatus xmlns:d='DAV:'>\n"
12980
0
            "<d:response>\n<d:href>%s</d:href>\n",
12981
0
            link_buf);
12982
0
  mg_printf(conn,
12983
0
            "<d:propstat><d:status>HTTP/1.1 403 "
12984
0
            "Forbidden</d:status></d:propstat>\n");
12985
0
  mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
12986
0
}
12987
#endif
12988
12989
12990
CIVETWEB_API void
12991
mg_lock_connection(struct mg_connection *conn)
12992
34
{
12993
34
  if (conn) {
12994
34
    (void)pthread_mutex_lock(&conn->mutex);
12995
34
  }
12996
34
}
12997
12998
12999
CIVETWEB_API void
13000
mg_unlock_connection(struct mg_connection *conn)
13001
34
{
13002
34
  if (conn) {
13003
34
    (void)pthread_mutex_unlock(&conn->mutex);
13004
34
  }
13005
34
}
13006
13007
13008
CIVETWEB_API void
13009
mg_lock_context(struct mg_context *ctx)
13010
0
{
13011
0
  if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
13012
0
    (void)pthread_mutex_lock(&ctx->nonce_mutex);
13013
0
  }
13014
0
}
13015
13016
13017
CIVETWEB_API void
13018
mg_unlock_context(struct mg_context *ctx)
13019
0
{
13020
0
  if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
13021
0
    (void)pthread_mutex_unlock(&ctx->nonce_mutex);
13022
0
  }
13023
0
}
13024
13025
13026
#if defined(USE_LUA)
13027
#include "mod_lua.inl"
13028
#endif /* USE_LUA */
13029
13030
#if defined(USE_DUKTAPE)
13031
#include "mod_duktape.inl"
13032
#endif /* USE_DUKTAPE */
13033
13034
#if defined(USE_WEBSOCKET)
13035
13036
#if !defined(NO_SSL_DL)
13037
#if !defined(OPENSSL_API_3_0)
13038
#define SHA_API static
13039
#include "sha1.inl"
13040
#endif
13041
#endif
13042
13043
static int
13044
send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
13045
{
13046
  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
13047
  char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
13048
  size_t dst_len = sizeof(b64_sha);
13049
#if !defined(OPENSSL_API_3_0)
13050
  SHA_CTX sha_ctx;
13051
#endif
13052
  int truncated;
13053
13054
  /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
13055
  mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
13056
  if (truncated) {
13057
    conn->must_close = 1;
13058
    return 0;
13059
  }
13060
13061
  DEBUG_TRACE("%s", "Send websocket handshake");
13062
13063
#if defined(OPENSSL_API_3_0)
13064
  EVP_Digest((unsigned char *)buf,
13065
             (uint32_t)strlen(buf),
13066
             (unsigned char *)sha,
13067
             NULL,
13068
             EVP_get_digestbyname("sha1"),
13069
             NULL);
13070
#else
13071
  SHA1_Init(&sha_ctx);
13072
  SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
13073
  SHA1_Final((unsigned char *)sha, &sha_ctx);
13074
#endif
13075
  mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
13076
  mg_printf(conn,
13077
            "HTTP/1.1 101 Switching Protocols\r\n"
13078
            "Upgrade: websocket\r\n"
13079
            "Connection: Upgrade\r\n"
13080
            "Sec-WebSocket-Accept: %s\r\n",
13081
            b64_sha);
13082
13083
#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13084
  // Send negotiated compression extension parameters
13085
  websocket_deflate_response(conn);
13086
#endif
13087
13088
  if (conn->request_info.acceptedWebSocketSubprotocol) {
13089
    mg_printf(conn,
13090
              "Sec-WebSocket-Protocol: %s\r\n\r\n",
13091
              conn->request_info.acceptedWebSocketSubprotocol);
13092
  } else {
13093
    mg_printf(conn, "%s", "\r\n");
13094
  }
13095
13096
  return 1;
13097
}
13098
13099
13100
#if !defined(MG_MAX_UNANSWERED_PING)
13101
/* Configuration of the maximum number of websocket PINGs that might
13102
 * stay unanswered before the connection is considered broken.
13103
 * Note: The name of this define may still change (until it is
13104
 * defined as a compile parameter in a documentation).
13105
 */
13106
#define MG_MAX_UNANSWERED_PING (5)
13107
#endif
13108
13109
13110
static void
13111
read_websocket(struct mg_connection *conn,
13112
               mg_websocket_data_handler ws_data_handler,
13113
               void *callback_data)
13114
{
13115
  /* Pointer to the beginning of the portion of the incoming websocket
13116
   * message queue.
13117
   * The original websocket upgrade request is never removed, so the queue
13118
   * begins after it. */
13119
  unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
13120
  int n, error, exit_by_callback;
13121
  int ret;
13122
13123
  /* body_len is the length of the entire queue in bytes
13124
   * len is the length of the current message
13125
   * data_len is the length of the current message's data payload
13126
   * header_len is the length of the current message's header */
13127
  size_t i, len, mask_len = 0, header_len, body_len;
13128
  uint64_t data_len = 0;
13129
13130
  /* "The masking key is a 32-bit value chosen at random by the client."
13131
   * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
13132
   */
13133
  unsigned char mask[4];
13134
13135
  /* data points to the place where the message is stored when passed to
13136
   * the websocket_data callback.  This is either mem on the stack, or a
13137
   * dynamically allocated buffer if it is too large. */
13138
  unsigned char mem[4096];
13139
  unsigned char mop; /* mask flag and opcode */
13140
13141
  /* Variables used for connection monitoring */
13142
  double timeout = -1.0;
13143
  int enable_ping_pong = 0;
13144
  int ping_count = 0;
13145
13146
  if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
13147
    enable_ping_pong =
13148
        !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
13149
                       "yes");
13150
  }
13151
13152
  if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
13153
    timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
13154
  }
13155
  if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
13156
    timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
13157
  }
13158
  if (timeout <= 0.0) {
13159
    timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
13160
  }
13161
13162
  /* Enter data processing loop */
13163
  DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
13164
              conn->request_info.remote_addr,
13165
              conn->request_info.remote_port);
13166
  conn->in_websocket_handling = 1;
13167
  mg_set_thread_name("wsock");
13168
13169
  /* Loop continuously, reading messages from the socket, invoking the
13170
   * callback, and waiting repeatedly until an error occurs. */
13171
  while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
13172
         && (!conn->must_close)) {
13173
    header_len = 0;
13174
    DEBUG_ASSERT(conn->data_len >= conn->request_len);
13175
    if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
13176
      len = buf[1] & 127;
13177
      mask_len = (buf[1] & 128) ? 4 : 0;
13178
      if ((len < 126) && (body_len >= mask_len)) {
13179
        /* inline 7-bit length field */
13180
        data_len = len;
13181
        header_len = 2 + mask_len;
13182
      } else if ((len == 126) && (body_len >= (4 + mask_len))) {
13183
        /* 16-bit length field */
13184
        header_len = 4 + mask_len;
13185
        data_len = ((((size_t)buf[2]) << 8) + buf[3]);
13186
      } else if (body_len >= (10 + mask_len)) {
13187
        /* 64-bit length field */
13188
        uint32_t l1, l2;
13189
        memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
13190
        memcpy(&l2, &buf[6], 4);
13191
        header_len = 10 + mask_len;
13192
        data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
13193
13194
        if (data_len > (uint64_t)0x7FFF0000ul) {
13195
          /* no can do */
13196
          mg_cry_internal(
13197
              conn,
13198
              "%s",
13199
              "websocket out of memory; closing connection");
13200
          break;
13201
        }
13202
      }
13203
    }
13204
13205
    if ((header_len > 0) && (body_len >= header_len)) {
13206
      /* Allocate space to hold websocket payload */
13207
      unsigned char *data = mem;
13208
13209
      if ((size_t)data_len > (size_t)sizeof(mem)) {
13210
        data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
13211
                                              conn->phys_ctx);
13212
        if (data == NULL) {
13213
          /* Allocation failed, exit the loop and then close the
13214
           * connection */
13215
          mg_cry_internal(
13216
              conn,
13217
              "%s",
13218
              "websocket out of memory; closing connection");
13219
          break;
13220
        }
13221
      }
13222
13223
      /* Copy the mask before we shift the queue and destroy it */
13224
      if (mask_len > 0) {
13225
        memcpy(mask, buf + header_len - mask_len, sizeof(mask));
13226
      } else {
13227
        memset(mask, 0, sizeof(mask));
13228
      }
13229
13230
      /* Read frame payload from the first message in the queue into
13231
       * data and advance the queue by moving the memory in place. */
13232
      DEBUG_ASSERT(body_len >= header_len);
13233
      if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
13234
        mop = buf[0]; /* current mask and opcode */
13235
                      /* Overflow case */
13236
        len = body_len - header_len;
13237
        memcpy(data, buf + header_len, len);
13238
        error = 0;
13239
        while ((uint64_t)len < data_len) {
13240
          n = pull_inner(NULL,
13241
                         conn,
13242
                         (char *)(data + len),
13243
                         (int)(data_len - len),
13244
                         timeout);
13245
          if (n <= -2) {
13246
            error = 1;
13247
            break;
13248
          } else if (n > 0) {
13249
            len += (size_t)n;
13250
          } else {
13251
            /* Timeout: should retry */
13252
            /* TODO: retry condition */
13253
          }
13254
        }
13255
        if (error) {
13256
          mg_cry_internal(
13257
              conn,
13258
              "%s",
13259
              "Websocket pull failed; closing connection");
13260
          if (data != mem) {
13261
            mg_free(data);
13262
          }
13263
          break;
13264
        }
13265
13266
        conn->data_len = conn->request_len;
13267
13268
      } else {
13269
13270
        mop = buf[0]; /* current mask and opcode, overwritten by
13271
                       * memmove() */
13272
13273
        /* Length of the message being read at the front of the
13274
         * queue. Cast to 31 bit is OK, since we limited
13275
         * data_len before. */
13276
        len = (size_t)data_len + header_len;
13277
13278
        /* Copy the data payload into the data pointer for the
13279
         * callback. Cast to 31 bit is OK, since we
13280
         * limited data_len */
13281
        memcpy(data, buf + header_len, (size_t)data_len);
13282
13283
        /* Move the queue forward len bytes */
13284
        memmove(buf, buf + len, body_len - len);
13285
13286
        /* Mark the queue as advanced */
13287
        conn->data_len -= (int)len;
13288
      }
13289
13290
      /* Apply mask if necessary */
13291
      if (mask_len > 0) {
13292
        for (i = 0; i < (size_t)data_len; i++) {
13293
          data[i] ^= mask[i & 3];
13294
        }
13295
      }
13296
13297
      exit_by_callback = 0;
13298
      if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
13299
        /* filter PONG messages */
13300
        DEBUG_TRACE("PONG from %s:%u",
13301
                    conn->request_info.remote_addr,
13302
                    conn->request_info.remote_port);
13303
        /* No unanwered PINGs left */
13304
        ping_count = 0;
13305
      } else if (enable_ping_pong
13306
                 && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
13307
        /* reply PING messages */
13308
        DEBUG_TRACE("Reply PING from %s:%u",
13309
                    conn->request_info.remote_addr,
13310
                    conn->request_info.remote_port);
13311
        ret = mg_websocket_write(conn,
13312
                                 MG_WEBSOCKET_OPCODE_PONG,
13313
                                 (char *)data,
13314
                                 (size_t)data_len);
13315
        if (ret <= 0) {
13316
          /* Error: send failed */
13317
          DEBUG_TRACE("Reply PONG failed (%i)", ret);
13318
          break;
13319
        }
13320
13321
      } else {
13322
        /* Exit the loop if callback signals to exit (server side),
13323
         * or "connection close" opcode received (client side). */
13324
        if (ws_data_handler != NULL) {
13325
#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13326
          if (mop & 0x40) {
13327
            /* Inflate the data received if bit RSV1 is set. */
13328
            if (!conn->websocket_deflate_initialized) {
13329
              if (websocket_deflate_initialize(conn, 1) != Z_OK)
13330
                exit_by_callback = 1;
13331
            }
13332
            if (!exit_by_callback) {
13333
              size_t inflate_buf_size_old = 0;
13334
              size_t inflate_buf_size =
13335
                  data_len
13336
                  * 4; // Initial guess of the inflated message
13337
                       // size. We double the memory when needed.
13338
              Bytef *inflated = NULL;
13339
              Bytef *new_mem = NULL;
13340
              conn->websocket_inflate_state.avail_in =
13341
                  (uInt)(data_len + 4);
13342
              conn->websocket_inflate_state.next_in = data;
13343
              // Add trailing 0x00 0x00 0xff 0xff bytes
13344
              data[data_len] = '\x00';
13345
              data[data_len + 1] = '\x00';
13346
              data[data_len + 2] = '\xff';
13347
              data[data_len + 3] = '\xff';
13348
              do {
13349
                if (inflate_buf_size_old == 0) {
13350
                  new_mem =
13351
                      (Bytef *)mg_calloc(inflate_buf_size,
13352
                                         sizeof(Bytef));
13353
                } else {
13354
                  inflate_buf_size *= 2;
13355
                  new_mem =
13356
                      (Bytef *)mg_realloc(inflated,
13357
                                          inflate_buf_size);
13358
                }
13359
                if (new_mem == NULL) {
13360
                  mg_cry_internal(
13361
                      conn,
13362
                      "Out of memory: Cannot allocate "
13363
                      "inflate buffer of %lu bytes",
13364
                      (unsigned long)inflate_buf_size);
13365
                  exit_by_callback = 1;
13366
                  break;
13367
                }
13368
                inflated = new_mem;
13369
                conn->websocket_inflate_state.avail_out =
13370
                    (uInt)(inflate_buf_size
13371
                           - inflate_buf_size_old);
13372
                conn->websocket_inflate_state.next_out =
13373
                    inflated + inflate_buf_size_old;
13374
                ret = inflate(&conn->websocket_inflate_state,
13375
                              Z_SYNC_FLUSH);
13376
                if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
13377
                    || ret == Z_MEM_ERROR) {
13378
                  mg_cry_internal(
13379
                      conn,
13380
                      "ZLIB inflate error: %i %s",
13381
                      ret,
13382
                      (conn->websocket_inflate_state.msg
13383
                           ? conn->websocket_inflate_state.msg
13384
                           : "<no error message>"));
13385
                  exit_by_callback = 1;
13386
                  break;
13387
                }
13388
                inflate_buf_size_old = inflate_buf_size;
13389
13390
              } while (conn->websocket_inflate_state.avail_out
13391
                       == 0);
13392
              inflate_buf_size -=
13393
                  conn->websocket_inflate_state.avail_out;
13394
              if (!ws_data_handler(conn,
13395
                                   mop,
13396
                                   (char *)inflated,
13397
                                   inflate_buf_size,
13398
                                   callback_data)) {
13399
                exit_by_callback = 1;
13400
              }
13401
              mg_free(inflated);
13402
            }
13403
          } else
13404
#endif
13405
              if (!ws_data_handler(conn,
13406
                                   mop,
13407
                                   (char *)data,
13408
                                   (size_t)data_len,
13409
                                   callback_data)) {
13410
            exit_by_callback = 1;
13411
          }
13412
        }
13413
      }
13414
13415
      /* It a buffer has been allocated, free it again */
13416
      if (data != mem) {
13417
        mg_free(data);
13418
      }
13419
13420
      if (exit_by_callback) {
13421
        DEBUG_TRACE("Callback requests to close connection from %s:%u",
13422
                    conn->request_info.remote_addr,
13423
                    conn->request_info.remote_port);
13424
        break;
13425
      }
13426
      if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
13427
        /* Opcode == 8, connection close */
13428
        DEBUG_TRACE("Message requests to close connection from %s:%u",
13429
                    conn->request_info.remote_addr,
13430
                    conn->request_info.remote_port);
13431
        break;
13432
      }
13433
13434
      /* Not breaking the loop, process next websocket frame. */
13435
    } else {
13436
      /* Read from the socket into the next available location in the
13437
       * message queue. */
13438
      n = pull_inner(NULL,
13439
                     conn,
13440
                     conn->buf + conn->data_len,
13441
                     conn->buf_size - conn->data_len,
13442
                     timeout);
13443
      if (n <= -2) {
13444
        /* Error, no bytes read */
13445
        DEBUG_TRACE("PULL from %s:%u failed",
13446
                    conn->request_info.remote_addr,
13447
                    conn->request_info.remote_port);
13448
        break;
13449
      }
13450
      if (n > 0) {
13451
        conn->data_len += n;
13452
        /* Reset open PING count */
13453
        ping_count = 0;
13454
      } else {
13455
        if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
13456
            && (!conn->must_close)) {
13457
          if (ping_count > MG_MAX_UNANSWERED_PING) {
13458
            /* Stop sending PING */
13459
            DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
13460
                        "- closing connection",
13461
                        ping_count,
13462
                        conn->request_info.remote_addr,
13463
                        conn->request_info.remote_port);
13464
            break;
13465
          }
13466
          if (enable_ping_pong) {
13467
            /* Send Websocket PING message */
13468
            DEBUG_TRACE("PING to %s:%u",
13469
                        conn->request_info.remote_addr,
13470
                        conn->request_info.remote_port);
13471
            ret = mg_websocket_write(conn,
13472
                                     MG_WEBSOCKET_OPCODE_PING,
13473
                                     NULL,
13474
                                     0);
13475
13476
            if (ret <= 0) {
13477
              /* Error: send failed */
13478
              DEBUG_TRACE("Send PING failed (%i)", ret);
13479
              break;
13480
            }
13481
            ping_count++;
13482
          }
13483
        }
13484
        /* Timeout: should retry */
13485
        /* TODO: get timeout def */
13486
      }
13487
    }
13488
  }
13489
13490
  /* Leave data processing loop */
13491
  mg_set_thread_name("worker");
13492
  conn->in_websocket_handling = 0;
13493
  DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
13494
              conn->request_info.remote_addr,
13495
              conn->request_info.remote_port);
13496
}
13497
13498
13499
static int
13500
mg_websocket_write_exec(struct mg_connection *conn,
13501
                        int opcode,
13502
                        const char *data,
13503
                        size_t dataLen,
13504
                        uint32_t masking_key)
13505
{
13506
  unsigned char header[14];
13507
  size_t headerLen;
13508
  int retval;
13509
13510
#if defined(GCC_DIAGNOSTIC)
13511
  /* Disable spurious conversion warning for GCC */
13512
#pragma GCC diagnostic push
13513
#pragma GCC diagnostic ignored "-Wconversion"
13514
#endif
13515
13516
  /* Note that POSIX/Winsock's send() is threadsafe
13517
   * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
13518
   * but mongoose's mg_printf/mg_write is not (because of the loop in
13519
   * push(), although that is only a problem if the packet is large or
13520
   * outgoing buffer is full). */
13521
13522
  /* TODO: Check if this lock should be moved to user land.
13523
   * Currently the server sets this lock for websockets, but
13524
   * not for any other connection. It must be set for every
13525
   * conn read/written by more than one thread, no matter if
13526
   * it is a websocket or regular connection. */
13527
  (void)mg_lock_connection(conn);
13528
13529
#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13530
  size_t deflated_size = 0;
13531
  Bytef *deflated = 0;
13532
  // Deflate websocket messages over 100kb
13533
  int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
13534
13535
  if (use_deflate) {
13536
    if (!conn->websocket_deflate_initialized) {
13537
      if (websocket_deflate_initialize(conn, 1) != Z_OK)
13538
        return 0;
13539
    }
13540
13541
    // Deflating the message
13542
    header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
13543
    conn->websocket_deflate_state.avail_in = (uInt)dataLen;
13544
    conn->websocket_deflate_state.next_in = (unsigned char *)data;
13545
    deflated_size = (size_t)compressBound((uLong)dataLen);
13546
    deflated = mg_calloc(deflated_size, sizeof(Bytef));
13547
    if (deflated == NULL) {
13548
      mg_cry_internal(
13549
          conn,
13550
          "Out of memory: Cannot allocate deflate buffer of %lu bytes",
13551
          (unsigned long)deflated_size);
13552
      mg_unlock_connection(conn);
13553
      return -1;
13554
    }
13555
    conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
13556
    conn->websocket_deflate_state.next_out = deflated;
13557
    deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
13558
    dataLen = deflated_size - conn->websocket_deflate_state.avail_out
13559
              - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
13560
  } else
13561
#endif
13562
    header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
13563
13564
#if defined(GCC_DIAGNOSTIC)
13565
#pragma GCC diagnostic pop
13566
#endif
13567
13568
  /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
13569
  if (dataLen < 126) {
13570
    /* inline 7-bit length field */
13571
    header[1] = (unsigned char)dataLen;
13572
    headerLen = 2;
13573
  } else if (dataLen <= 0xFFFF) {
13574
    /* 16-bit length field */
13575
    uint16_t len = htons((uint16_t)dataLen);
13576
    header[1] = 126;
13577
    memcpy(header + 2, &len, 2);
13578
    headerLen = 4;
13579
  } else {
13580
    /* 64-bit length field */
13581
    uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
13582
    uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
13583
    header[1] = 127;
13584
    memcpy(header + 2, &len1, 4);
13585
    memcpy(header + 6, &len2, 4);
13586
    headerLen = 10;
13587
  }
13588
13589
  if (masking_key) {
13590
    /* add mask */
13591
    header[1] |= 0x80;
13592
    memcpy(header + headerLen, &masking_key, 4);
13593
    headerLen += 4;
13594
  }
13595
13596
  retval = mg_write(conn, header, headerLen);
13597
  if (retval != (int)headerLen) {
13598
    /* Did not send complete header */
13599
    retval = -1;
13600
  } else {
13601
    if (dataLen > 0) {
13602
#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13603
      if (use_deflate) {
13604
        retval = mg_write(conn, deflated, dataLen);
13605
        mg_free(deflated);
13606
      } else
13607
#endif
13608
        retval = mg_write(conn, data, dataLen);
13609
    }
13610
    /* if dataLen == 0, the header length (2) is returned */
13611
  }
13612
13613
  /* TODO: Remove this unlock as well, when lock is removed. */
13614
  mg_unlock_connection(conn);
13615
13616
  return retval;
13617
}
13618
13619
13620
CIVETWEB_API int
13621
mg_websocket_write(struct mg_connection *conn,
13622
                   int opcode,
13623
                   const char *data,
13624
                   size_t dataLen)
13625
{
13626
  return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
13627
}
13628
13629
13630
static void
13631
mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
13632
{
13633
  size_t i = 0;
13634
13635
  i = 0;
13636
  if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
13637
    /* Convert in 32 bit words, if data is 4 byte aligned */
13638
    while (i < (in_len - 3)) {
13639
      *(uint32_t *)(void *)(out + i) =
13640
          *(uint32_t *)(void *)(in + i) ^ masking_key;
13641
      i += 4;
13642
    }
13643
  }
13644
  if (i != in_len) {
13645
    /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
13646
    while (i < in_len) {
13647
      *(uint8_t *)(void *)(out + i) =
13648
          *(uint8_t *)(void *)(in + i)
13649
          ^ *(((uint8_t *)&masking_key) + (i % 4));
13650
      i++;
13651
    }
13652
  }
13653
}
13654
13655
13656
CIVETWEB_API int
13657
mg_websocket_client_write(struct mg_connection *conn,
13658
                          int opcode,
13659
                          const char *data,
13660
                          size_t dataLen)
13661
{
13662
  int retval = -1;
13663
  char *masked_data =
13664
      (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
13665
  uint32_t masking_key = 0;
13666
13667
  if (masked_data == NULL) {
13668
    /* Return -1 in an error case */
13669
    mg_cry_internal(conn,
13670
                    "%s",
13671
                    "Cannot allocate buffer for masked websocket response: "
13672
                    "Out of memory");
13673
    return -1;
13674
  }
13675
13676
  do {
13677
    /* Get a masking key - but not 0 */
13678
    masking_key = (uint32_t)get_random();
13679
  } while (masking_key == 0);
13680
13681
  mask_data(data, dataLen, masking_key, masked_data);
13682
13683
  retval = mg_websocket_write_exec(
13684
      conn, opcode, masked_data, dataLen, masking_key);
13685
  mg_free(masked_data);
13686
13687
  return retval;
13688
}
13689
13690
13691
static void
13692
handle_websocket_request(struct mg_connection *conn,
13693
                         const char *path,
13694
                         int is_callback_resource,
13695
                         struct mg_websocket_subprotocols *subprotocols,
13696
                         mg_websocket_connect_handler ws_connect_handler,
13697
                         mg_websocket_ready_handler ws_ready_handler,
13698
                         mg_websocket_data_handler ws_data_handler,
13699
                         mg_websocket_close_handler ws_close_handler,
13700
                         void *cbData)
13701
{
13702
  const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
13703
  const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
13704
  ptrdiff_t lua_websock = 0;
13705
13706
#if !defined(USE_LUA)
13707
  (void)path;
13708
#endif
13709
13710
  /* Step 1: Check websocket protocol version. */
13711
  /* Step 1.1: Check Sec-WebSocket-Key. */
13712
  if (!websock_key) {
13713
    /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
13714
     * requires a Sec-WebSocket-Key header.
13715
     */
13716
    /* It could be the hixie draft version
13717
     * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
13718
     */
13719
    const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
13720
    const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
13721
    char key3[8];
13722
13723
    if ((key1 != NULL) && (key2 != NULL)) {
13724
      /* This version uses 8 byte body data in a GET request */
13725
      conn->content_len = 8;
13726
      if (8 == mg_read(conn, key3, 8)) {
13727
        /* This is the hixie version */
13728
        mg_send_http_error(conn,
13729
                           426,
13730
                           "%s",
13731
                           "Protocol upgrade to RFC 6455 required");
13732
        return;
13733
      }
13734
    }
13735
    /* This is an unknown version */
13736
    mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
13737
    return;
13738
  }
13739
13740
  /* Step 1.2: Check websocket protocol version. */
13741
  /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
13742
  if ((version == NULL) || (strcmp(version, "13") != 0)) {
13743
    /* Reject wrong versions */
13744
    mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
13745
    return;
13746
  }
13747
13748
  /* Step 1.3: Could check for "Host", but we do not really need this
13749
   * value for anything, so just ignore it. */
13750
13751
  /* Step 2: If a callback is responsible, call it. */
13752
  if (is_callback_resource) {
13753
    /* Step 2.1 check and select subprotocol */
13754
    const char *protocols[64]; // max 64 headers
13755
    int nbSubprotocolHeader = get_req_headers(&conn->request_info,
13756
                                              "Sec-WebSocket-Protocol",
13757
                                              protocols,
13758
                                              64);
13759
13760
    if ((nbSubprotocolHeader > 0) && subprotocols) {
13761
13762
      int headerNo, idx;
13763
      size_t len;
13764
      const char *sep, *curSubProtocol,
13765
          *acceptedWebSocketSubprotocol = NULL;
13766
13767
      /* look for matching subprotocol */
13768
      for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
13769
        /* There might be multiple headers ... */
13770
        const char *protocol = protocols[headerNo];
13771
        curSubProtocol = protocol;
13772
13773
        /* ... and in every header there might be a , separated list */
13774
        while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
13775
13776
          while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
13777
            curSubProtocol++;
13778
          sep = strchr(curSubProtocol, ',');
13779
          if (sep) {
13780
            len = (size_t)(sep - curSubProtocol);
13781
          } else {
13782
            len = strlen(curSubProtocol);
13783
          }
13784
13785
          for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
13786
            // COMPARE: curSubProtocol ==
13787
            // subprotocols->subprotocols[idx]
13788
            if ((strlen(subprotocols->subprotocols[idx]) == len)
13789
                && (strncmp(curSubProtocol,
13790
                            subprotocols->subprotocols[idx],
13791
                            len)
13792
                    == 0)) {
13793
              acceptedWebSocketSubprotocol =
13794
                  subprotocols->subprotocols[idx];
13795
              break;
13796
            }
13797
          }
13798
          curSubProtocol += len;
13799
        }
13800
      }
13801
13802
      conn->request_info.acceptedWebSocketSubprotocol =
13803
          acceptedWebSocketSubprotocol;
13804
    }
13805
13806
#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13807
    websocket_deflate_negotiate(conn);
13808
#endif
13809
13810
    if ((ws_connect_handler != NULL)
13811
        && (ws_connect_handler(conn, cbData) != 0)) {
13812
      /* C callback has returned non-zero, do not proceed with
13813
       * handshake.
13814
       */
13815
      /* Note that C callbacks are no longer called when Lua is
13816
       * responsible, so C can no longer filter callbacks for Lua. */
13817
      return;
13818
    }
13819
  }
13820
13821
#if defined(USE_LUA)
13822
  /* Step 3: No callback. Check if Lua is responsible. */
13823
  else {
13824
    /* Step 3.1: Check if Lua is responsible. */
13825
    if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
13826
      lua_websock = match_prefix_strlen(
13827
          conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
13828
    }
13829
13830
    if (lua_websock > 0) {
13831
      /* Step 3.2: Lua is responsible: call it. */
13832
      conn->lua_websocket_state = lua_websocket_new(path, conn);
13833
      if (!conn->lua_websocket_state) {
13834
        /* Lua rejected the new client */
13835
        return;
13836
      }
13837
    }
13838
  }
13839
#endif
13840
13841
  /* Step 4: Check if there is a responsible websocket handler. */
13842
  if (!is_callback_resource && !lua_websock) {
13843
    /* There is no callback, and Lua is not responsible either. */
13844
    /* Reply with a 404 Not Found. We are still at a standard
13845
     * HTTP request here, before the websocket handshake, so
13846
     * we can still send standard HTTP error replies. */
13847
    mg_send_http_error(conn, 404, "%s", "Not found");
13848
    return;
13849
  }
13850
13851
  /* Step 5: The websocket connection has been accepted */
13852
  if (!send_websocket_handshake(conn, websock_key)) {
13853
    mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
13854
    return;
13855
  }
13856
13857
  /* Step 6: Call the ready handler */
13858
  if (is_callback_resource) {
13859
    if (ws_ready_handler != NULL) {
13860
      ws_ready_handler(conn, cbData);
13861
    }
13862
#if defined(USE_LUA)
13863
  } else if (lua_websock) {
13864
    if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
13865
      /* the ready handler returned false */
13866
      return;
13867
    }
13868
#endif
13869
  }
13870
13871
  /* Step 7: Enter the read loop */
13872
  if (is_callback_resource) {
13873
    read_websocket(conn, ws_data_handler, cbData);
13874
#if defined(USE_LUA)
13875
  } else if (lua_websock) {
13876
    read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
13877
#endif
13878
  }
13879
13880
#if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
13881
  /* Step 8: Close the deflate & inflate buffers */
13882
  if (conn->websocket_deflate_initialized) {
13883
    deflateEnd(&conn->websocket_deflate_state);
13884
    inflateEnd(&conn->websocket_inflate_state);
13885
  }
13886
#endif
13887
13888
  /* Step 9: Call the close handler */
13889
  if (ws_close_handler) {
13890
    ws_close_handler(conn, cbData);
13891
  }
13892
}
13893
#endif /* !USE_WEBSOCKET */
13894
13895
13896
/* Is upgrade request:
13897
 *   0 = regular HTTP/1.0 or HTTP/1.1 request
13898
 *   1 = upgrade to websocket
13899
 *   2 = upgrade to HTTP/2
13900
 * -1 = upgrade to unknown protocol
13901
 */
13902
static int
13903
should_switch_to_protocol(const struct mg_connection *conn)
13904
0
{
13905
0
  const char *connection_headers[8];
13906
0
  const char *upgrade_to;
13907
0
  int connection_header_count, i, should_upgrade;
13908
13909
  /* A websocket protocol has the following HTTP headers:
13910
   *
13911
   * Connection: Upgrade
13912
   * Upgrade: Websocket
13913
   *
13914
   * It seems some clients use multiple headers:
13915
   * see https://github.com/civetweb/civetweb/issues/1083
13916
   */
13917
0
  connection_header_count = get_req_headers(&conn->request_info,
13918
0
                                            "Connection",
13919
0
                                            connection_headers,
13920
0
                                            8);
13921
0
  should_upgrade = 0;
13922
0
  for (i = 0; i < connection_header_count; i++) {
13923
0
    if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
13924
0
      should_upgrade = 1;
13925
0
    }
13926
0
  }
13927
0
  if (!should_upgrade) {
13928
0
    return PROTOCOL_TYPE_HTTP1;
13929
0
  }
13930
13931
0
  upgrade_to = mg_get_header(conn, "Upgrade");
13932
0
  if (upgrade_to == NULL) {
13933
    /* "Connection: Upgrade" without "Upgrade" Header --> Error */
13934
0
    return -1;
13935
0
  }
13936
13937
  /* Upgrade to ... */
13938
0
  if (0 != mg_strcasestr(upgrade_to, "websocket")) {
13939
    /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
13940
     * "Sec-WebSocket-Version" are also required.
13941
     * Don't check them here, since even an unsupported websocket protocol
13942
     * request still IS a websocket request (in contrast to a standard HTTP
13943
     * request). It will fail later in handle_websocket_request.
13944
     */
13945
0
    return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
13946
0
  }
13947
0
  if (0 != mg_strcasestr(upgrade_to, "h2")) {
13948
0
    return PROTOCOL_TYPE_HTTP2; /* Websocket */
13949
0
  }
13950
13951
  /* Upgrade to another protocol */
13952
0
  return -1;
13953
0
}
13954
13955
13956
static int
13957
parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
13958
0
{
13959
0
  int n;
13960
0
  unsigned int a, b, c, d, slash;
13961
13962
0
  if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
13963
0
      != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
13964
            // integer value, but function will not report conversion
13965
            // errors; consider using 'strtol' instead
13966
0
    slash = 32;
13967
0
    if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
13968
0
        != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
13969
              // an integer value, but function will not report conversion
13970
              // errors; consider using 'strtol' instead
13971
0
      n = 0;
13972
0
    }
13973
0
  }
13974
13975
0
  if ((n > 0) && ((size_t)n == vec->len)) {
13976
0
    if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
13977
      /* IPv4 format */
13978
0
      if (sa->sa.sa_family == AF_INET) {
13979
0
        uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
13980
0
        uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
13981
0
                       | ((uint32_t)c << 8) | (uint32_t)d;
13982
0
        uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
13983
0
        return (ip & mask) == net;
13984
0
      }
13985
0
      return 0;
13986
0
    }
13987
0
  }
13988
#if defined(USE_IPV6)
13989
  else {
13990
    char ad[50];
13991
    const char *p;
13992
13993
    if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
13994
      slash = 128;
13995
      if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
13996
        n = 0;
13997
      }
13998
    }
13999
14000
    if ((n <= 0) && no_strict) {
14001
      /* no square brackets? */
14002
      p = strchr(vec->ptr, '/');
14003
      if (p && (p < (vec->ptr + vec->len))) {
14004
        if (((size_t)(p - vec->ptr) < sizeof(ad))
14005
            && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
14006
          n += (int)(p - vec->ptr);
14007
          mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
14008
        } else {
14009
          n = 0;
14010
        }
14011
      } else if (vec->len < sizeof(ad)) {
14012
        n = (int)vec->len;
14013
        slash = 128;
14014
        mg_strlcpy(ad, vec->ptr, vec->len + 1);
14015
      }
14016
    }
14017
14018
    if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
14019
      p = ad;
14020
      c = 0;
14021
      /* zone indexes are unsupported, at least two colons are needed */
14022
      while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
14023
        if (*(p++) == ':') {
14024
          c++;
14025
        }
14026
      }
14027
      if ((*p == '\0') && (c >= 2)) {
14028
        struct sockaddr_in6 sin6;
14029
        unsigned int i;
14030
14031
        /* for strict validation, an actual IPv6 argument is needed */
14032
        if (sa->sa.sa_family != AF_INET6) {
14033
          return 0;
14034
        }
14035
        if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
14036
          /* IPv6 format */
14037
          for (i = 0; i < 16; i++) {
14038
            uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
14039
            uint8_t net = sin6.sin6_addr.s6_addr[i];
14040
            uint8_t mask = 0;
14041
14042
            if (8 * i + 8 < slash) {
14043
              mask = 0xFFu;
14044
            } else if (8 * i < slash) {
14045
              mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
14046
            }
14047
            if ((ip & mask) != net) {
14048
              return 0;
14049
            }
14050
          }
14051
          return 1;
14052
        }
14053
      }
14054
    }
14055
  }
14056
#else
14057
0
  (void)no_strict;
14058
0
#endif
14059
14060
  /* malformed */
14061
0
  return -1;
14062
0
}
14063
14064
14065
static int
14066
set_throttle(const char *spec, const union usa *rsa, const char *uri)
14067
0
{
14068
0
  int throttle = 0;
14069
0
  struct vec vec, val;
14070
0
  char mult;
14071
0
  double v;
14072
14073
0
  while ((spec = next_option(spec, &vec, &val)) != NULL) {
14074
0
    mult = ',';
14075
0
    if ((val.ptr == NULL)
14076
0
        || (sscanf(val.ptr, "%lf%c", &v, &mult)
14077
0
            < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
14078
                 // to an integer value, but function will not report
14079
                 // conversion errors; consider using 'strtol' instead
14080
0
        || (v < 0)
14081
0
        || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
14082
0
            && (mult != ','))) {
14083
0
      continue;
14084
0
    }
14085
0
    v *= (lowercase(&mult) == 'k')
14086
0
             ? 1024
14087
0
             : ((lowercase(&mult) == 'm') ? 1048576 : 1);
14088
0
    if (vec.len == 1 && vec.ptr[0] == '*') {
14089
0
      throttle = (int)v;
14090
0
    } else {
14091
0
      int matched = parse_match_net(&vec, rsa, 0);
14092
0
      if (matched >= 0) {
14093
        /* a valid IP subnet */
14094
0
        if (matched) {
14095
0
          throttle = (int)v;
14096
0
        }
14097
0
      } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
14098
0
        throttle = (int)v;
14099
0
      }
14100
0
    }
14101
0
  }
14102
14103
0
  return throttle;
14104
0
}
14105
14106
14107
/* The mg_upload function is superseded by mg_handle_form_request. */
14108
#include "handle_form.inl"
14109
14110
14111
static int
14112
get_first_ssl_listener_index(const struct mg_context *ctx)
14113
0
{
14114
0
  unsigned int i;
14115
0
  int idx = -1;
14116
0
  if (ctx) {
14117
0
    for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
14118
0
      idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
14119
0
    }
14120
0
  }
14121
0
  return idx;
14122
0
}
14123
14124
14125
/* Return host (without port) */
14126
static void
14127
get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
14128
0
{
14129
0
  const char *host_header =
14130
0
      get_header(ri->http_headers, ri->num_headers, "Host");
14131
14132
0
  host->ptr = NULL;
14133
0
  host->len = 0;
14134
14135
0
  if (host_header != NULL) {
14136
0
    const char *pos;
14137
14138
    /* If the "Host" is an IPv6 address, like [::1], parse until ]
14139
     * is found. */
14140
0
    if (*host_header == '[') {
14141
0
      pos = strchr(host_header, ']');
14142
0
      if (!pos) {
14143
        /* Malformed hostname starts with '[', but no ']' found */
14144
0
        DEBUG_TRACE("%s", "Host name format error '[' without ']'");
14145
0
        return;
14146
0
      }
14147
      /* terminate after ']' */
14148
0
      host->ptr = host_header;
14149
0
      host->len = (size_t)(pos + 1 - host_header);
14150
0
    } else {
14151
      /* Otherwise, a ':' separates hostname and port number */
14152
0
      pos = strchr(host_header, ':');
14153
0
      if (pos != NULL) {
14154
0
        host->len = (size_t)(pos - host_header);
14155
0
      } else {
14156
0
        host->len = strlen(host_header);
14157
0
      }
14158
0
      host->ptr = host_header;
14159
0
    }
14160
0
  }
14161
0
}
14162
14163
14164
static int
14165
switch_domain_context(struct mg_connection *conn)
14166
0
{
14167
0
  struct vec host;
14168
14169
0
  get_host_from_request_info(&host, &conn->request_info);
14170
14171
0
  if (host.ptr) {
14172
0
    if (conn->ssl) {
14173
      /* This is a HTTPS connection, maybe we have a hostname
14174
       * from SNI (set in ssl_servername_callback). */
14175
0
      const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
14176
0
      if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
14177
        /* We are not using the default domain */
14178
0
        if ((strlen(sslhost) != host.len)
14179
0
            || mg_strncasecmp(host.ptr, sslhost, host.len)) {
14180
          /* Mismatch between SNI domain and HTTP domain */
14181
0
          DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
14182
0
                      sslhost,
14183
0
                      (int)host.len,
14184
0
                      host.ptr);
14185
0
          return 0;
14186
0
        }
14187
0
      }
14188
14189
0
    } else {
14190
0
      struct mg_domain_context *dom = &(conn->phys_ctx->dd);
14191
0
      while (dom) {
14192
0
        const char *domName = dom->config[AUTHENTICATION_DOMAIN];
14193
0
        size_t domNameLen = strlen(domName);
14194
0
        if ((domNameLen == host.len)
14195
0
            && !mg_strncasecmp(host.ptr, domName, host.len)) {
14196
14197
          /* Found matching domain */
14198
0
          DEBUG_TRACE("HTTP domain %s found",
14199
0
                      dom->config[AUTHENTICATION_DOMAIN]);
14200
14201
          /* TODO: Check if this is a HTTP or HTTPS domain */
14202
0
          conn->dom_ctx = dom;
14203
0
          break;
14204
0
        }
14205
0
        mg_lock_context(conn->phys_ctx);
14206
0
        dom = dom->next;
14207
0
        mg_unlock_context(conn->phys_ctx);
14208
0
      }
14209
0
    }
14210
14211
0
    DEBUG_TRACE("HTTP%s Host: %.*s",
14212
0
                conn->ssl ? "S" : "",
14213
0
                (int)host.len,
14214
0
                host.ptr);
14215
14216
0
  } else {
14217
0
    DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
14218
0
    return 1;
14219
0
  }
14220
14221
0
  return 1;
14222
0
}
14223
14224
14225
static void
14226
redirect_to_https_port(struct mg_connection *conn, int port)
14227
0
{
14228
0
  char target_url[MG_BUF_LEN];
14229
0
  int truncated = 0;
14230
0
  const char *expect_proto =
14231
0
      (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
14232
14233
  /* Use "308 Permanent Redirect" */
14234
0
  int redirect_code = 308;
14235
14236
  /* In any case, close the current connection */
14237
0
  conn->must_close = 1;
14238
14239
  /* Send host, port, uri and (if it exists) ?query_string */
14240
0
  if (mg_construct_local_link(
14241
0
          conn, target_url, sizeof(target_url), expect_proto, port, NULL)
14242
0
      < 0) {
14243
0
    truncated = 1;
14244
0
  } else if (conn->request_info.query_string != NULL) {
14245
0
    size_t slen1 = strlen(target_url);
14246
0
    size_t slen2 = strlen(conn->request_info.query_string);
14247
0
    if ((slen1 + slen2 + 2) < sizeof(target_url)) {
14248
0
      target_url[slen1] = '?';
14249
0
      memcpy(target_url + slen1 + 1,
14250
0
             conn->request_info.query_string,
14251
0
             slen2);
14252
0
      target_url[slen1 + slen2 + 1] = 0;
14253
0
    } else {
14254
0
      truncated = 1;
14255
0
    }
14256
0
  }
14257
14258
  /* Check overflow in location buffer (will not occur if MG_BUF_LEN
14259
   * is used as buffer size) */
14260
0
  if (truncated) {
14261
0
    mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
14262
0
    return;
14263
0
  }
14264
14265
  /* Use redirect helper function */
14266
0
  mg_send_http_redirect(conn, target_url, redirect_code);
14267
0
}
14268
14269
14270
static void
14271
mg_set_handler_type(struct mg_context *phys_ctx,
14272
                    struct mg_domain_context *dom_ctx,
14273
                    const char *uri,
14274
                    int handler_type,
14275
                    int is_delete_request,
14276
                    mg_request_handler handler,
14277
                    struct mg_websocket_subprotocols *subprotocols,
14278
                    mg_websocket_connect_handler connect_handler,
14279
                    mg_websocket_ready_handler ready_handler,
14280
                    mg_websocket_data_handler data_handler,
14281
                    mg_websocket_close_handler close_handler,
14282
                    mg_authorization_handler auth_handler,
14283
                    void *cbdata)
14284
0
{
14285
0
  struct mg_handler_info *tmp_rh, **lastref;
14286
0
  size_t urilen = strlen(uri);
14287
14288
0
  if (handler_type == WEBSOCKET_HANDLER) {
14289
0
    DEBUG_ASSERT(handler == NULL);
14290
0
    DEBUG_ASSERT(is_delete_request || connect_handler != NULL
14291
0
                 || ready_handler != NULL || data_handler != NULL
14292
0
                 || close_handler != NULL);
14293
14294
0
    DEBUG_ASSERT(auth_handler == NULL);
14295
0
    if (handler != NULL) {
14296
0
      return;
14297
0
    }
14298
0
    if (!is_delete_request && (connect_handler == NULL)
14299
0
        && (ready_handler == NULL) && (data_handler == NULL)
14300
0
        && (close_handler == NULL)) {
14301
0
      return;
14302
0
    }
14303
0
    if (auth_handler != NULL) {
14304
0
      return;
14305
0
    }
14306
14307
0
  } else if (handler_type == REQUEST_HANDLER) {
14308
0
    DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
14309
0
                 && data_handler == NULL && close_handler == NULL);
14310
0
    DEBUG_ASSERT(is_delete_request || (handler != NULL));
14311
0
    DEBUG_ASSERT(auth_handler == NULL);
14312
14313
0
    if ((connect_handler != NULL) || (ready_handler != NULL)
14314
0
        || (data_handler != NULL) || (close_handler != NULL)) {
14315
0
      return;
14316
0
    }
14317
0
    if (!is_delete_request && (handler == NULL)) {
14318
0
      return;
14319
0
    }
14320
0
    if (auth_handler != NULL) {
14321
0
      return;
14322
0
    }
14323
14324
0
  } else if (handler_type == AUTH_HANDLER) {
14325
0
    DEBUG_ASSERT(handler == NULL);
14326
0
    DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
14327
0
                 && data_handler == NULL && close_handler == NULL);
14328
0
    DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
14329
0
    if (handler != NULL) {
14330
0
      return;
14331
0
    }
14332
0
    if ((connect_handler != NULL) || (ready_handler != NULL)
14333
0
        || (data_handler != NULL) || (close_handler != NULL)) {
14334
0
      return;
14335
0
    }
14336
0
    if (!is_delete_request && (auth_handler == NULL)) {
14337
0
      return;
14338
0
    }
14339
0
  } else {
14340
    /* Unknown handler type. */
14341
0
    return;
14342
0
  }
14343
14344
0
  if (!phys_ctx || !dom_ctx) {
14345
    /* no context available */
14346
0
    return;
14347
0
  }
14348
14349
0
  mg_lock_context(phys_ctx);
14350
14351
  /* first try to find an existing handler */
14352
0
  do {
14353
0
    lastref = &(dom_ctx->handlers);
14354
0
    for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
14355
0
         tmp_rh = tmp_rh->next) {
14356
0
      if (tmp_rh->handler_type == handler_type
14357
0
          && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
14358
0
        if (!is_delete_request) {
14359
          /* update existing handler */
14360
0
          if (handler_type == REQUEST_HANDLER) {
14361
            /* Wait for end of use before updating */
14362
0
            if (tmp_rh->refcount) {
14363
0
              mg_unlock_context(phys_ctx);
14364
0
              mg_sleep(1);
14365
0
              mg_lock_context(phys_ctx);
14366
              /* tmp_rh might have been freed, search again. */
14367
0
              break;
14368
0
            }
14369
            /* Ok, the handler is no more use -> Update it */
14370
0
            tmp_rh->handler = handler;
14371
0
          } else if (handler_type == WEBSOCKET_HANDLER) {
14372
0
            tmp_rh->subprotocols = subprotocols;
14373
0
            tmp_rh->connect_handler = connect_handler;
14374
0
            tmp_rh->ready_handler = ready_handler;
14375
0
            tmp_rh->data_handler = data_handler;
14376
0
            tmp_rh->close_handler = close_handler;
14377
0
          } else { /* AUTH_HANDLER */
14378
0
            tmp_rh->auth_handler = auth_handler;
14379
0
          }
14380
0
          tmp_rh->cbdata = cbdata;
14381
0
        } else {
14382
          /* remove existing handler */
14383
0
          if (handler_type == REQUEST_HANDLER) {
14384
            /* Wait for end of use before removing */
14385
0
            if (tmp_rh->refcount) {
14386
0
              tmp_rh->removing = 1;
14387
0
              mg_unlock_context(phys_ctx);
14388
0
              mg_sleep(1);
14389
0
              mg_lock_context(phys_ctx);
14390
              /* tmp_rh might have been freed, search again. */
14391
0
              break;
14392
0
            }
14393
            /* Ok, the handler is no more used */
14394
0
          }
14395
0
          *lastref = tmp_rh->next;
14396
0
          mg_free(tmp_rh->uri);
14397
0
          mg_free(tmp_rh);
14398
0
        }
14399
0
        mg_unlock_context(phys_ctx);
14400
0
        return;
14401
0
      }
14402
0
      lastref = &(tmp_rh->next);
14403
0
    }
14404
0
  } while (tmp_rh != NULL);
14405
14406
0
  if (is_delete_request) {
14407
    /* no handler to set, this was a remove request to a non-existing
14408
     * handler */
14409
0
    mg_unlock_context(phys_ctx);
14410
0
    return;
14411
0
  }
14412
14413
0
  tmp_rh =
14414
0
      (struct mg_handler_info *)mg_calloc_ctx(1,
14415
0
                                              sizeof(struct mg_handler_info),
14416
0
                                              phys_ctx);
14417
0
  if (tmp_rh == NULL) {
14418
0
    mg_unlock_context(phys_ctx);
14419
0
    mg_cry_ctx_internal(phys_ctx,
14420
0
                        "%s",
14421
0
                        "Cannot create new request handler struct, OOM");
14422
0
    return;
14423
0
  }
14424
0
  tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
14425
0
  if (!tmp_rh->uri) {
14426
0
    mg_unlock_context(phys_ctx);
14427
0
    mg_free(tmp_rh);
14428
0
    mg_cry_ctx_internal(phys_ctx,
14429
0
                        "%s",
14430
0
                        "Cannot create new request handler struct, OOM");
14431
0
    return;
14432
0
  }
14433
0
  tmp_rh->uri_len = urilen;
14434
0
  if (handler_type == REQUEST_HANDLER) {
14435
0
    tmp_rh->refcount = 0;
14436
0
    tmp_rh->removing = 0;
14437
0
    tmp_rh->handler = handler;
14438
0
  } else if (handler_type == WEBSOCKET_HANDLER) {
14439
0
    tmp_rh->subprotocols = subprotocols;
14440
0
    tmp_rh->connect_handler = connect_handler;
14441
0
    tmp_rh->ready_handler = ready_handler;
14442
0
    tmp_rh->data_handler = data_handler;
14443
0
    tmp_rh->close_handler = close_handler;
14444
0
  } else { /* AUTH_HANDLER */
14445
0
    tmp_rh->auth_handler = auth_handler;
14446
0
  }
14447
0
  tmp_rh->cbdata = cbdata;
14448
0
  tmp_rh->handler_type = handler_type;
14449
0
  tmp_rh->next = NULL;
14450
14451
0
  *lastref = tmp_rh;
14452
0
  mg_unlock_context(phys_ctx);
14453
0
}
14454
14455
14456
CIVETWEB_API void
14457
mg_set_request_handler(struct mg_context *ctx,
14458
                       const char *uri,
14459
                       mg_request_handler handler,
14460
                       void *cbdata)
14461
0
{
14462
0
  mg_set_handler_type(ctx,
14463
0
                      &(ctx->dd),
14464
0
                      uri,
14465
0
                      REQUEST_HANDLER,
14466
0
                      handler == NULL,
14467
0
                      handler,
14468
0
                      NULL,
14469
0
                      NULL,
14470
0
                      NULL,
14471
0
                      NULL,
14472
0
                      NULL,
14473
0
                      NULL,
14474
0
                      cbdata);
14475
0
}
14476
14477
14478
CIVETWEB_API void
14479
mg_set_websocket_handler(struct mg_context *ctx,
14480
                         const char *uri,
14481
                         mg_websocket_connect_handler connect_handler,
14482
                         mg_websocket_ready_handler ready_handler,
14483
                         mg_websocket_data_handler data_handler,
14484
                         mg_websocket_close_handler close_handler,
14485
                         void *cbdata)
14486
0
{
14487
0
  mg_set_websocket_handler_with_subprotocols(ctx,
14488
0
                                             uri,
14489
0
                                             NULL,
14490
0
                                             connect_handler,
14491
0
                                             ready_handler,
14492
0
                                             data_handler,
14493
0
                                             close_handler,
14494
0
                                             cbdata);
14495
0
}
14496
14497
14498
CIVETWEB_API void
14499
mg_set_websocket_handler_with_subprotocols(
14500
    struct mg_context *ctx,
14501
    const char *uri,
14502
    struct mg_websocket_subprotocols *subprotocols,
14503
    mg_websocket_connect_handler connect_handler,
14504
    mg_websocket_ready_handler ready_handler,
14505
    mg_websocket_data_handler data_handler,
14506
    mg_websocket_close_handler close_handler,
14507
    void *cbdata)
14508
0
{
14509
0
  int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
14510
0
                          && (data_handler == NULL)
14511
0
                          && (close_handler == NULL);
14512
0
  mg_set_handler_type(ctx,
14513
0
                      &(ctx->dd),
14514
0
                      uri,
14515
0
                      WEBSOCKET_HANDLER,
14516
0
                      is_delete_request,
14517
0
                      NULL,
14518
0
                      subprotocols,
14519
0
                      connect_handler,
14520
0
                      ready_handler,
14521
0
                      data_handler,
14522
0
                      close_handler,
14523
0
                      NULL,
14524
0
                      cbdata);
14525
0
}
14526
14527
14528
CIVETWEB_API void
14529
mg_set_auth_handler(struct mg_context *ctx,
14530
                    const char *uri,
14531
                    mg_authorization_handler handler,
14532
                    void *cbdata)
14533
0
{
14534
0
  mg_set_handler_type(ctx,
14535
0
                      &(ctx->dd),
14536
0
                      uri,
14537
0
                      AUTH_HANDLER,
14538
0
                      handler == NULL,
14539
0
                      NULL,
14540
0
                      NULL,
14541
0
                      NULL,
14542
0
                      NULL,
14543
0
                      NULL,
14544
0
                      NULL,
14545
0
                      handler,
14546
0
                      cbdata);
14547
0
}
14548
14549
14550
static int
14551
get_request_handler(struct mg_connection *conn,
14552
                    int handler_type,
14553
                    mg_request_handler *handler,
14554
                    struct mg_websocket_subprotocols **subprotocols,
14555
                    mg_websocket_connect_handler *connect_handler,
14556
                    mg_websocket_ready_handler *ready_handler,
14557
                    mg_websocket_data_handler *data_handler,
14558
                    mg_websocket_close_handler *close_handler,
14559
                    mg_authorization_handler *auth_handler,
14560
                    void **cbdata,
14561
                    struct mg_handler_info **handler_info)
14562
0
{
14563
0
  const struct mg_request_info *request_info = mg_get_request_info(conn);
14564
0
  if (request_info) {
14565
0
    const char *uri = request_info->local_uri;
14566
0
    size_t urilen = strlen(uri);
14567
0
    struct mg_handler_info *tmp_rh;
14568
0
    int step, matched;
14569
14570
0
    if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
14571
0
      return 0;
14572
0
    }
14573
14574
0
    mg_lock_context(conn->phys_ctx);
14575
14576
0
    for (step = 0; step < 3; step++) {
14577
0
      for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
14578
0
           tmp_rh = tmp_rh->next) {
14579
0
        if (tmp_rh->handler_type != handler_type) {
14580
0
          continue;
14581
0
        }
14582
0
        if (step == 0) {
14583
          /* first try for an exact match */
14584
0
          matched = (tmp_rh->uri_len == urilen)
14585
0
                    && (strcmp(tmp_rh->uri, uri) == 0);
14586
0
        } else if (step == 1) {
14587
          /* next try for a partial match, we will accept
14588
          uri/something */
14589
0
          matched =
14590
0
              (tmp_rh->uri_len < urilen)
14591
0
              && (uri[tmp_rh->uri_len] == '/')
14592
0
              && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
14593
0
        } else {
14594
          /* finally try for pattern match */
14595
0
          matched =
14596
0
              match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
14597
0
        }
14598
0
        if (matched) {
14599
0
          if (handler_type == WEBSOCKET_HANDLER) {
14600
0
            *subprotocols = tmp_rh->subprotocols;
14601
0
            *connect_handler = tmp_rh->connect_handler;
14602
0
            *ready_handler = tmp_rh->ready_handler;
14603
0
            *data_handler = tmp_rh->data_handler;
14604
0
            *close_handler = tmp_rh->close_handler;
14605
0
          } else if (handler_type == REQUEST_HANDLER) {
14606
0
            if (tmp_rh->removing) {
14607
              /* Treat as none found */
14608
0
              step = 2;
14609
0
              break;
14610
0
            }
14611
0
            *handler = tmp_rh->handler;
14612
            /* Acquire handler and give it back */
14613
0
            tmp_rh->refcount++;
14614
0
            *handler_info = tmp_rh;
14615
0
          } else { /* AUTH_HANDLER */
14616
0
            *auth_handler = tmp_rh->auth_handler;
14617
0
          }
14618
0
          *cbdata = tmp_rh->cbdata;
14619
0
          mg_unlock_context(conn->phys_ctx);
14620
0
          return 1;
14621
0
        }
14622
0
      }
14623
0
    }
14624
14625
0
    mg_unlock_context(conn->phys_ctx);
14626
0
  }
14627
0
  return 0; /* none found */
14628
0
}
14629
14630
14631
/* Check if the script file is in a path, allowed for script files.
14632
 * This can be used if uploading files is possible not only for the server
14633
 * admin, and the upload mechanism does not check the file extension.
14634
 */
14635
static int
14636
is_in_script_path(const struct mg_connection *conn, const char *path)
14637
0
{
14638
  /* TODO (Feature): Add config value for allowed script path.
14639
   * Default: All allowed. */
14640
0
  (void)conn;
14641
0
  (void)path;
14642
0
  return 1;
14643
0
}
14644
14645
14646
#if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
14647
static int
14648
experimental_websocket_client_data_wrapper(struct mg_connection *conn,
14649
                                           int bits,
14650
                                           char *data,
14651
                                           size_t len,
14652
                                           void *cbdata)
14653
{
14654
  struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
14655
  if (pcallbacks->websocket_data) {
14656
    return pcallbacks->websocket_data(conn, bits, data, len);
14657
  }
14658
  /* No handler set - assume "OK" */
14659
  return 1;
14660
}
14661
14662
14663
static void
14664
experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
14665
                                            void *cbdata)
14666
{
14667
  struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
14668
  if (pcallbacks->connection_close) {
14669
    pcallbacks->connection_close(conn);
14670
  }
14671
}
14672
#endif
14673
14674
14675
/* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
14676
 */
14677
static void
14678
release_handler_ref(struct mg_connection *conn,
14679
                    struct mg_handler_info *handler_info)
14680
0
{
14681
0
  if (handler_info != NULL) {
14682
    /* Use context lock for ref counter */
14683
0
    mg_lock_context(conn->phys_ctx);
14684
0
    handler_info->refcount--;
14685
0
    mg_unlock_context(conn->phys_ctx);
14686
0
  }
14687
0
}
14688
14689
14690
/* This is the heart of the Civetweb's logic.
14691
 * This function is called when the request is read, parsed and validated,
14692
 * and Civetweb must decide what action to take: serve a file, or
14693
 * a directory, or call embedded function, etcetera. */
14694
static void
14695
handle_request(struct mg_connection *conn)
14696
0
{
14697
0
  struct mg_request_info *ri = &conn->request_info;
14698
0
  char path[UTF8_PATH_MAX];
14699
0
  int uri_len, ssl_index;
14700
0
  int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
14701
0
      is_put_or_delete_request = 0, is_callback_resource = 0,
14702
0
      is_template_text_file = 0, is_webdav_request = 0;
14703
0
  int i;
14704
0
  struct mg_file file = STRUCT_FILE_INITIALIZER;
14705
0
  mg_request_handler callback_handler = NULL;
14706
0
  struct mg_handler_info *handler_info = NULL;
14707
0
  struct mg_websocket_subprotocols *subprotocols;
14708
0
  mg_websocket_connect_handler ws_connect_handler = NULL;
14709
0
  mg_websocket_ready_handler ws_ready_handler = NULL;
14710
0
  mg_websocket_data_handler ws_data_handler = NULL;
14711
0
  mg_websocket_close_handler ws_close_handler = NULL;
14712
0
  void *callback_data = NULL;
14713
0
  mg_authorization_handler auth_handler = NULL;
14714
0
  void *auth_callback_data = NULL;
14715
0
  int handler_type;
14716
0
  time_t curtime = time(NULL);
14717
0
  char date[64];
14718
0
  char *tmp;
14719
14720
0
  path[0] = 0;
14721
14722
  /* 0. Reset internal state (required for HTTP/2 proxy) */
14723
0
  conn->request_state = 0;
14724
14725
  /* 1. get the request url */
14726
  /* 1.1. split into url and query string */
14727
0
  if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
14728
0
      != NULL) {
14729
0
    *((char *)conn->request_info.query_string++) = '\0';
14730
0
  }
14731
14732
  /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
14733
0
  if (!conn->client.is_ssl && conn->client.ssl_redir) {
14734
0
    ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
14735
0
    if (ssl_index >= 0) {
14736
0
      int port = (int)ntohs(USA_IN_PORT_UNSAFE(
14737
0
          &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
14738
0
      redirect_to_https_port(conn, port);
14739
0
    } else {
14740
      /* A http to https forward port has been specified,
14741
       * but no https port to forward to. */
14742
0
      mg_send_http_error(conn,
14743
0
                         503,
14744
0
                         "%s",
14745
0
                         "Error: SSL forward not configured properly");
14746
0
      mg_cry_internal(conn,
14747
0
                      "%s",
14748
0
                      "Can not redirect to SSL, no SSL port available");
14749
0
    }
14750
0
    return;
14751
0
  }
14752
0
  uri_len = (int)strlen(ri->local_uri);
14753
14754
  /* 1.3. decode url (if config says so) */
14755
0
  if (should_decode_url(conn)) {
14756
0
    url_decode_in_place((char *)ri->local_uri);
14757
0
  }
14758
14759
  /* URL decode the query-string only if explicitly set in the configuration
14760
   */
14761
0
  if (conn->request_info.query_string) {
14762
0
    if (should_decode_query_string(conn)) {
14763
0
      url_decode_in_place((char *)conn->request_info.query_string);
14764
0
    }
14765
0
  }
14766
14767
  /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
14768
   * possible. The fact that we cleaned the URI is stored in that the
14769
   * pointer to ri->local_ur and ri->local_uri_raw are now different.
14770
   * ri->local_uri_raw still points to memory allocated in
14771
   * worker_thread_run(). ri->local_uri is private to the request so we
14772
   * don't have to use preallocated memory here. */
14773
0
  tmp = mg_strdup(ri->local_uri_raw);
14774
0
  if (!tmp) {
14775
    /* Out of memory. We cannot do anything reasonable here. */
14776
0
    return;
14777
0
  }
14778
0
  remove_dot_segments(tmp);
14779
0
  ri->local_uri = tmp;
14780
14781
  /* step 1. completed, the url is known now */
14782
0
  DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
14783
14784
  /* 2. if this ip has limited speed, set it for this connection */
14785
0
  conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
14786
0
                                &conn->client.rsa,
14787
0
                                ri->local_uri);
14788
14789
  /* 3. call a "handle everything" callback, if registered */
14790
0
  if (conn->phys_ctx->callbacks.begin_request != NULL) {
14791
    /* Note that since V1.7 the "begin_request" function is called
14792
     * before an authorization check. If an authorization check is
14793
     * required, use a request_handler instead. */
14794
0
    i = conn->phys_ctx->callbacks.begin_request(conn);
14795
0
    if (i > 0) {
14796
      /* callback already processed the request. Store the
14797
      return value as a status code for the access log. */
14798
0
      conn->status_code = i;
14799
0
      if (!conn->must_close) {
14800
0
        discard_unread_request_data(conn);
14801
0
      }
14802
0
      DEBUG_TRACE("%s", "begin_request handled request");
14803
0
      return;
14804
0
    } else if (i == 0) {
14805
      /* civetweb should process the request */
14806
0
    } else {
14807
      /* unspecified - may change with the next version */
14808
0
      DEBUG_TRACE("%s", "done (undocumented behavior)");
14809
0
      return;
14810
0
    }
14811
0
  }
14812
14813
  /* request not yet handled by a handler or redirect, so the request
14814
   * is processed here */
14815
14816
  /* 4. Check for CORS preflight requests and handle them (if configured).
14817
   * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
14818
   */
14819
0
  if (!strcmp(ri->request_method, "OPTIONS")) {
14820
    /* Send a response to CORS preflights only if
14821
     * access_control_allow_methods is not NULL and not an empty string.
14822
     * In this case, scripts can still handle CORS. */
14823
0
    const char *cors_meth_cfg =
14824
0
        conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
14825
0
    const char *cors_orig_cfg =
14826
0
        conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
14827
0
    const char *cors_origin =
14828
0
        get_header(ri->http_headers, ri->num_headers, "Origin");
14829
0
    const char *cors_acrm = get_header(ri->http_headers,
14830
0
                                       ri->num_headers,
14831
0
                                       "Access-Control-Request-Method");
14832
14833
    /* Todo: check if cors_origin is in cors_orig_cfg.
14834
     * Or, let the client check this. */
14835
14836
0
    if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
14837
0
        && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
14838
0
        && (cors_origin != NULL) && (cors_acrm != NULL)) {
14839
      /* This is a valid CORS preflight, and the server is configured
14840
       * to handle it automatically. */
14841
0
      const char *cors_acrh =
14842
0
          get_header(ri->http_headers,
14843
0
                     ri->num_headers,
14844
0
                     "Access-Control-Request-Headers");
14845
14846
0
      gmt_time_string(date, sizeof(date), &curtime);
14847
0
      mg_printf(conn,
14848
0
                "HTTP/1.1 200 OK\r\n"
14849
0
                "Date: %s\r\n"
14850
0
                "Access-Control-Allow-Origin: %s\r\n"
14851
0
                "Access-Control-Allow-Methods: %s\r\n"
14852
0
                "Content-Length: 0\r\n"
14853
0
                "Connection: %s\r\n",
14854
0
                date,
14855
0
                cors_orig_cfg,
14856
0
                ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
14857
0
                suggest_connection_header(conn));
14858
14859
0
      if (cors_acrh != NULL) {
14860
        /* CORS request is asking for additional headers */
14861
0
        const char *cors_hdr_cfg =
14862
0
            conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
14863
14864
0
        if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
14865
          /* Allow only if access_control_allow_headers is
14866
           * not NULL and not an empty string. If this
14867
           * configuration is set to *, allow everything.
14868
           * Otherwise this configuration must be a list
14869
           * of allowed HTTP header names. */
14870
0
          mg_printf(conn,
14871
0
                    "Access-Control-Allow-Headers: %s\r\n",
14872
0
                    ((cors_hdr_cfg[0] == '*') ? cors_acrh
14873
0
                                              : cors_hdr_cfg));
14874
0
        }
14875
0
      }
14876
0
      mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
14877
0
      mg_printf(conn, "\r\n");
14878
0
      DEBUG_TRACE("%s", "OPTIONS done");
14879
0
      return;
14880
0
    }
14881
0
  }
14882
14883
  /* 5. interpret the url to find out how the request must be handled
14884
   */
14885
  /* 5.1. first test, if the request targets the regular http(s)://
14886
   * protocol namespace or the websocket ws(s):// protocol namespace.
14887
   */
14888
0
  is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
14889
#if defined(USE_WEBSOCKET)
14890
  handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
14891
#else
14892
0
  handler_type = REQUEST_HANDLER;
14893
0
#endif /* defined(USE_WEBSOCKET) */
14894
14895
0
  if (is_websocket_request) {
14896
0
    HTTP1_only;
14897
0
  }
14898
14899
  /* 5.2. check if the request will be handled by a callback */
14900
0
  if (get_request_handler(conn,
14901
0
                          handler_type,
14902
0
                          &callback_handler,
14903
0
                          &subprotocols,
14904
0
                          &ws_connect_handler,
14905
0
                          &ws_ready_handler,
14906
0
                          &ws_data_handler,
14907
0
                          &ws_close_handler,
14908
0
                          NULL,
14909
0
                          &callback_data,
14910
0
                          &handler_info)) {
14911
    /* 5.2.1. A callback will handle this request. All requests
14912
     * handled by a callback have to be considered as requests
14913
     * to a script resource. */
14914
0
    is_callback_resource = 1;
14915
0
    is_script_resource = 1;
14916
0
    is_put_or_delete_request = is_put_or_delete_method(conn);
14917
    /* Never handle a C callback according to File WebDav rules,
14918
     * even if it is a webdav method */
14919
0
    is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
14920
0
  } else {
14921
0
  no_callback_resource:
14922
14923
    /* 5.2.2. No callback is responsible for this request. The URI
14924
     * addresses a file based resource (static content or Lua/cgi
14925
     * scripts in the file system). */
14926
0
    is_callback_resource = 0;
14927
0
    interpret_uri(conn,
14928
0
                  path,
14929
0
                  sizeof(path),
14930
0
                  &file.stat,
14931
0
                  &is_found,
14932
0
                  &is_script_resource,
14933
0
                  &is_websocket_request,
14934
0
                  &is_put_or_delete_request,
14935
0
                  &is_webdav_request,
14936
0
                  &is_template_text_file);
14937
0
  }
14938
14939
  /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
14940
0
  if (is_webdav_request) {
14941
    /* TODO: Do we need a config option? */
14942
0
    const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
14943
0
    if (webdav_enable[0] != 'y') {
14944
0
      mg_send_http_error(conn,
14945
0
                         405,
14946
0
                         "%s method not allowed",
14947
0
                         conn->request_info.request_method);
14948
0
      DEBUG_TRACE("%s", "webdav rejected");
14949
0
      return;
14950
0
    }
14951
0
  }
14952
14953
  /* 6. authorization check */
14954
  /* 6.1. a custom authorization handler is installed */
14955
0
  if (get_request_handler(conn,
14956
0
                          AUTH_HANDLER,
14957
0
                          NULL,
14958
0
                          NULL,
14959
0
                          NULL,
14960
0
                          NULL,
14961
0
                          NULL,
14962
0
                          NULL,
14963
0
                          &auth_handler,
14964
0
                          &auth_callback_data,
14965
0
                          NULL)) {
14966
0
    if (!auth_handler(conn, auth_callback_data)) {
14967
14968
      /* Callback handler will not be used anymore. Release it */
14969
0
      release_handler_ref(conn, handler_info);
14970
0
      DEBUG_TRACE("%s", "auth handler rejected request");
14971
0
      return;
14972
0
    }
14973
0
  } else if (is_put_or_delete_request && !is_script_resource
14974
0
             && !is_callback_resource) {
14975
0
    HTTP1_only;
14976
    /* 6.2. this request is a PUT/DELETE to a real file */
14977
    /* 6.2.1. thus, the server must have real files */
14978
#if defined(NO_FILES)
14979
    if (1) {
14980
#else
14981
0
    if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
14982
0
        || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
14983
0
#endif
14984
      /* This code path will not be called for request handlers */
14985
0
      DEBUG_ASSERT(handler_info == NULL);
14986
14987
      /* This server does not have any real files, thus the
14988
       * PUT/DELETE methods are not valid. */
14989
0
      mg_send_http_error(conn,
14990
0
                         405,
14991
0
                         "%s method not allowed",
14992
0
                         conn->request_info.request_method);
14993
0
      DEBUG_TRACE("%s", "all file based put/delete requests rejected");
14994
0
      return;
14995
0
    }
14996
14997
0
#if !defined(NO_FILES)
14998
    /* 6.2.2. Check if put authorization for static files is
14999
     * available.
15000
     */
15001
0
    if (!is_authorized_for_put(conn)) {
15002
0
      send_authorization_request(conn, NULL);
15003
0
      DEBUG_TRACE("%s", "file write needs authorization");
15004
0
      return;
15005
0
    }
15006
0
#endif
15007
15008
0
  } else {
15009
    /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
15010
     * or it is a PUT or DELETE request to a resource that does not
15011
     * correspond to a file. Check authorization. */
15012
0
    if (!check_authorization(conn, path)) {
15013
0
      send_authorization_request(conn, NULL);
15014
15015
      /* Callback handler will not be used anymore. Release it */
15016
0
      release_handler_ref(conn, handler_info);
15017
0
      DEBUG_TRACE("%s", "access authorization required");
15018
0
      return;
15019
0
    }
15020
0
  }
15021
15022
  /* request is authorized or does not need authorization */
15023
15024
  /* 7. check if there are request handlers for this uri */
15025
0
  if (is_callback_resource) {
15026
0
    HTTP1_only;
15027
0
    if (!is_websocket_request) {
15028
0
      i = callback_handler(conn, callback_data);
15029
15030
      /* Callback handler will not be used anymore. Release it */
15031
0
      release_handler_ref(conn, handler_info);
15032
15033
0
      if (i > 0) {
15034
        /* Do nothing, callback has served the request. Store
15035
         * then return value as status code for the log and discard
15036
         * all data from the client not used by the callback. */
15037
0
        conn->status_code = i;
15038
0
        if (!conn->must_close) {
15039
0
          discard_unread_request_data(conn);
15040
0
        }
15041
0
      } else {
15042
        /* The handler did NOT handle the request. */
15043
        /* Some proper reactions would be:
15044
         * a) close the connections without sending anything
15045
         * b) send a 404 not found
15046
         * c) try if there is a file matching the URI
15047
         * It would be possible to do a, b or c in the callback
15048
         * implementation, and return 1 - we cannot do anything
15049
         * here, that is not possible in the callback.
15050
         *
15051
         * TODO: What would be the best reaction here?
15052
         * (Note: The reaction may change, if there is a better
15053
         * idea.)
15054
         */
15055
15056
        /* For the moment, use option c: We look for a proper file,
15057
         * but since a file request is not always a script resource,
15058
         * the authorization check might be different. */
15059
0
        callback_handler = NULL;
15060
15061
        /* Here we are at a dead end:
15062
         * According to URI matching, a callback should be
15063
         * responsible for handling the request,
15064
         * we called it, but the callback declared itself
15065
         * not responsible.
15066
         * We use a goto here, to get out of this dead end,
15067
         * and continue with the default handling.
15068
         * A goto here is simpler and better to understand
15069
         * than some curious loop. */
15070
0
        goto no_callback_resource;
15071
0
      }
15072
0
    } else {
15073
#if defined(USE_WEBSOCKET)
15074
      handle_websocket_request(conn,
15075
                               path,
15076
                               is_callback_resource,
15077
                               subprotocols,
15078
                               ws_connect_handler,
15079
                               ws_ready_handler,
15080
                               ws_data_handler,
15081
                               ws_close_handler,
15082
                               callback_data);
15083
#endif
15084
0
    }
15085
0
    DEBUG_TRACE("%s", "websocket handling done");
15086
0
    return;
15087
0
  }
15088
15089
  /* 8. handle websocket requests */
15090
#if defined(USE_WEBSOCKET)
15091
  if (is_websocket_request) {
15092
    HTTP1_only;
15093
    if (is_script_resource) {
15094
15095
      if (is_in_script_path(conn, path)) {
15096
        /* Websocket Lua script */
15097
        handle_websocket_request(conn,
15098
                                 path,
15099
                                 0 /* Lua Script */,
15100
                                 NULL,
15101
                                 NULL,
15102
                                 NULL,
15103
                                 NULL,
15104
                                 NULL,
15105
                                 conn->phys_ctx->user_data);
15106
      } else {
15107
        /* Script was in an illegal path */
15108
        mg_send_http_error(conn, 403, "%s", "Forbidden");
15109
      }
15110
    } else {
15111
      mg_send_http_error(conn, 404, "%s", "Not found");
15112
    }
15113
    DEBUG_TRACE("%s", "websocket script done");
15114
    return;
15115
  } else
15116
#endif
15117
15118
#if defined(NO_FILES)
15119
    /* 9a. In case the server uses only callbacks, this uri is
15120
     * unknown.
15121
     * Then, all request handling ends here. */
15122
    mg_send_http_error(conn, 404, "%s", "Not Found");
15123
15124
#else
15125
  /* 9b. This request is either for a static file or resource handled
15126
   * by a script file. Thus, a DOCUMENT_ROOT must exist. */
15127
0
  if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
15128
0
    mg_send_http_error(conn, 404, "%s", "Not Found");
15129
0
    DEBUG_TRACE("%s", "no document root available");
15130
0
    return;
15131
0
  }
15132
15133
  /* 10. Request is handled by a script */
15134
0
  if (is_script_resource) {
15135
0
    HTTP1_only;
15136
0
    handle_file_based_request(conn, path, &file);
15137
0
    DEBUG_TRACE("%s", "script handling done");
15138
0
    return;
15139
0
  }
15140
15141
  /* Request was not handled by a callback or script. It will be
15142
   * handled by a server internal method. */
15143
15144
  /* 11. Handle put/delete/mkcol requests */
15145
0
  if (is_put_or_delete_request) {
15146
0
    HTTP1_only;
15147
    /* 11.1. PUT method */
15148
0
    if (!strcmp(ri->request_method, "PUT")) {
15149
0
      put_file(conn, path);
15150
0
      DEBUG_TRACE("handling %s request to %s done",
15151
0
                  ri->request_method,
15152
0
                  path);
15153
0
      return;
15154
0
    }
15155
    /* 11.2. DELETE method */
15156
0
    if (!strcmp(ri->request_method, "DELETE")) {
15157
0
      delete_file(conn, path);
15158
0
      DEBUG_TRACE("handling %s request to %s done",
15159
0
                  ri->request_method,
15160
0
                  path);
15161
0
      return;
15162
0
    }
15163
    /* 11.3. MKCOL method */
15164
0
    if (!strcmp(ri->request_method, "MKCOL")) {
15165
0
      dav_mkcol(conn, path);
15166
0
      DEBUG_TRACE("handling %s request to %s done",
15167
0
                  ri->request_method,
15168
0
                  path);
15169
0
      return;
15170
0
    }
15171
    /* 11.4. MOVE method */
15172
0
    if (!strcmp(ri->request_method, "MOVE")) {
15173
0
      dav_move_file(conn, path, 0);
15174
0
      DEBUG_TRACE("handling %s request to %s done",
15175
0
                  ri->request_method,
15176
0
                  path);
15177
0
      return;
15178
0
    }
15179
0
    if (!strcmp(ri->request_method, "COPY")) {
15180
0
      dav_move_file(conn, path, 1);
15181
0
      DEBUG_TRACE("handling %s request to %s done",
15182
0
                  ri->request_method,
15183
0
                  path);
15184
0
      return;
15185
0
    }
15186
    /* 11.5. LOCK method */
15187
0
    if (!strcmp(ri->request_method, "LOCK")) {
15188
0
      dav_lock_file(conn, path);
15189
0
      DEBUG_TRACE("handling %s request to %s done",
15190
0
                  ri->request_method,
15191
0
                  path);
15192
0
      return;
15193
0
    }
15194
    /* 11.6. UNLOCK method */
15195
0
    if (!strcmp(ri->request_method, "UNLOCK")) {
15196
0
      dav_unlock_file(conn, path);
15197
0
      DEBUG_TRACE("handling %s request to %s done",
15198
0
                  ri->request_method,
15199
0
                  path);
15200
0
      return;
15201
0
    }
15202
    /* 11.7. PROPPATCH method */
15203
0
    if (!strcmp(ri->request_method, "PROPPATCH")) {
15204
0
      dav_proppatch(conn, path);
15205
0
      DEBUG_TRACE("handling %s request to %s done",
15206
0
                  ri->request_method,
15207
0
                  path);
15208
0
      return;
15209
0
    }
15210
    /* 11.8. Other methods, e.g.: PATCH
15211
     * This method is not supported for static resources,
15212
     * only for scripts (Lua, CGI) and callbacks. */
15213
0
    mg_send_http_error(conn,
15214
0
                       405,
15215
0
                       "%s method not allowed",
15216
0
                       conn->request_info.request_method);
15217
0
    DEBUG_TRACE("method %s on %s is not supported",
15218
0
                ri->request_method,
15219
0
                path);
15220
0
    return;
15221
0
  }
15222
15223
  /* 11. File does not exist, or it was configured that it should be
15224
   * hidden */
15225
0
  if (!is_found || (must_hide_file(conn, path))) {
15226
0
    mg_send_http_error(conn, 404, "%s", "Not found");
15227
0
    DEBUG_TRACE("handling %s request to %s: file not found",
15228
0
                ri->request_method,
15229
0
                path);
15230
0
    return;
15231
0
  }
15232
15233
  /* 12. Directory uris should end with a slash */
15234
0
  if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
15235
0
      && (ri->local_uri[uri_len - 1] != '/')) {
15236
15237
    /* Path + server root */
15238
0
    size_t buflen = UTF8_PATH_MAX * 2 + 2;
15239
0
    char *new_path;
15240
15241
0
    if (ri->query_string) {
15242
0
      buflen += strlen(ri->query_string);
15243
0
    }
15244
0
    new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
15245
0
    if (!new_path) {
15246
0
      mg_send_http_error(conn, 500, "out or memory");
15247
0
    } else {
15248
0
      mg_get_request_link(conn, new_path, buflen - 1);
15249
0
      strcat(new_path, "/");
15250
0
      if (ri->query_string) {
15251
        /* Append ? and query string */
15252
0
        strcat(new_path, "?");
15253
0
        strcat(new_path, ri->query_string);
15254
0
      }
15255
0
      mg_send_http_redirect(conn, new_path, 301);
15256
0
      mg_free(new_path);
15257
0
    }
15258
0
    DEBUG_TRACE("%s request to %s: directory redirection sent",
15259
0
                ri->request_method,
15260
0
                path);
15261
0
    return;
15262
0
  }
15263
15264
  /* 13. Handle other methods than GET/HEAD */
15265
  /* 13.1. Handle PROPFIND */
15266
0
  if (!strcmp(ri->request_method, "PROPFIND")) {
15267
0
    handle_propfind(conn, path, &file.stat);
15268
0
    DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
15269
0
    return;
15270
0
  }
15271
  /* 13.2. Handle OPTIONS for files */
15272
0
  if (!strcmp(ri->request_method, "OPTIONS")) {
15273
    /* This standard handler is only used for real files.
15274
     * Scripts should support the OPTIONS method themselves, to allow a
15275
     * maximum flexibility.
15276
     * Lua and CGI scripts may fully support CORS this way (including
15277
     * preflights). */
15278
0
    send_options(conn);
15279
0
    DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
15280
0
    return;
15281
0
  }
15282
  /* 13.3. everything but GET and HEAD (e.g. POST) */
15283
0
  if ((0 != strcmp(ri->request_method, "GET"))
15284
0
      && (0 != strcmp(ri->request_method, "HEAD"))) {
15285
0
    mg_send_http_error(conn,
15286
0
                       405,
15287
0
                       "%s method not allowed",
15288
0
                       conn->request_info.request_method);
15289
0
    DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
15290
0
    return;
15291
0
  }
15292
15293
  /* 14. directories */
15294
0
  if (file.stat.is_directory) {
15295
    /* Substitute files have already been handled above. */
15296
    /* Here we can either generate and send a directory listing,
15297
     * or send an "access denied" error. */
15298
0
    if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
15299
0
                       "yes")) {
15300
0
      handle_directory_request(conn, path);
15301
0
    } else {
15302
0
      mg_send_http_error(conn,
15303
0
                         403,
15304
0
                         "%s",
15305
0
                         "Error: Directory listing denied");
15306
0
    }
15307
0
    DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
15308
0
    return;
15309
0
  }
15310
15311
  /* 15. Files with search/replace patterns: LSP and SSI */
15312
0
  if (is_template_text_file) {
15313
0
    HTTP1_only;
15314
0
    handle_file_based_request(conn, path, &file);
15315
0
    DEBUG_TRACE("handling %s request to %s done (template)",
15316
0
                ri->request_method,
15317
0
                path);
15318
0
    return;
15319
0
  }
15320
15321
  /* 16. Static file - maybe cached */
15322
0
#if !defined(NO_CACHING)
15323
0
  if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
15324
    /* Send 304 "Not Modified" - this must not send any body data */
15325
0
    handle_not_modified_static_file_request(conn, &file);
15326
0
    DEBUG_TRACE("handling %s request to %s done (not modified)",
15327
0
                ri->request_method,
15328
0
                path);
15329
0
    return;
15330
0
  }
15331
0
#endif /* !NO_CACHING */
15332
15333
  /* 17. Static file - not cached */
15334
0
  handle_static_file_request(conn, path, &file, NULL, NULL);
15335
0
  DEBUG_TRACE("handling %s request to %s done (static)",
15336
0
              ri->request_method,
15337
0
              path);
15338
15339
0
#endif /* !defined(NO_FILES) */
15340
0
}
15341
15342
15343
#if !defined(NO_FILESYSTEMS)
15344
static void
15345
handle_file_based_request(struct mg_connection *conn,
15346
                          const char *path,
15347
                          struct mg_file *file)
15348
0
{
15349
0
#if !defined(NO_CGI)
15350
0
  unsigned char cgi_config_idx, inc, max;
15351
0
#endif
15352
15353
0
  if (!conn || !conn->dom_ctx) {
15354
0
    return;
15355
0
  }
15356
15357
#if defined(USE_LUA)
15358
  if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
15359
                          path)
15360
      > 0) {
15361
    if (is_in_script_path(conn, path)) {
15362
      /* Lua server page: an SSI like page containing mostly plain
15363
       * html code plus some tags with server generated contents. */
15364
      handle_lsp_request(conn, path, file, NULL);
15365
    } else {
15366
      /* Script was in an illegal path */
15367
      mg_send_http_error(conn, 403, "%s", "Forbidden");
15368
    }
15369
    return;
15370
  }
15371
15372
  if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
15373
      > 0) {
15374
    if (is_in_script_path(conn, path)) {
15375
      /* Lua in-server module script: a CGI like script used to
15376
       * generate the entire reply. */
15377
      mg_exec_lua_script(conn, path, NULL);
15378
    } else {
15379
      /* Script was in an illegal path */
15380
      mg_send_http_error(conn, 403, "%s", "Forbidden");
15381
    }
15382
    return;
15383
  }
15384
#endif
15385
15386
#if defined(USE_DUKTAPE)
15387
  if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
15388
                          path)
15389
      > 0) {
15390
    if (is_in_script_path(conn, path)) {
15391
      /* Call duktape to generate the page */
15392
      mg_exec_duktape_script(conn, path);
15393
    } else {
15394
      /* Script was in an illegal path */
15395
      mg_send_http_error(conn, 403, "%s", "Forbidden");
15396
    }
15397
    return;
15398
  }
15399
#endif
15400
15401
0
#if !defined(NO_CGI)
15402
0
  inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
15403
0
  max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
15404
0
  for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
15405
0
    if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
15406
0
      if (match_prefix_strlen(
15407
0
              conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
15408
0
              path)
15409
0
          > 0) {
15410
0
        if (is_in_script_path(conn, path)) {
15411
          /* CGI scripts may support all HTTP methods */
15412
0
          handle_cgi_request(conn, path, cgi_config_idx);
15413
0
        } else {
15414
          /* Script was in an illegal path */
15415
0
          mg_send_http_error(conn, 403, "%s", "Forbidden");
15416
0
        }
15417
0
        return;
15418
0
      }
15419
0
    }
15420
0
  }
15421
0
#endif /* !NO_CGI */
15422
15423
0
  if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
15424
0
    if (is_in_script_path(conn, path)) {
15425
0
      handle_ssi_file_request(conn, path, file);
15426
0
    } else {
15427
      /* Script was in an illegal path */
15428
0
      mg_send_http_error(conn, 403, "%s", "Forbidden");
15429
0
    }
15430
0
    return;
15431
0
  }
15432
15433
0
#if !defined(NO_CACHING)
15434
0
  if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
15435
    /* Send 304 "Not Modified" - this must not send any body data */
15436
0
    handle_not_modified_static_file_request(conn, file);
15437
0
    return;
15438
0
  }
15439
0
#endif /* !NO_CACHING */
15440
15441
0
  handle_static_file_request(conn, path, file, NULL, NULL);
15442
0
}
15443
#endif /* NO_FILESYSTEMS */
15444
15445
15446
static void
15447
close_all_listening_sockets(struct mg_context *ctx)
15448
2
{
15449
2
  unsigned int i;
15450
2
  if (!ctx) {
15451
0
    return;
15452
0
  }
15453
15454
4
  for (i = 0; i < ctx->num_listening_sockets; i++) {
15455
2
    closesocket(ctx->listening_sockets[i].sock);
15456
#if defined(USE_X_DOM_SOCKET)
15457
    /* For unix domain sockets, the socket name represents a file that has
15458
     * to be deleted. */
15459
    /* See
15460
     * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
15461
     */
15462
    if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
15463
        && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
15464
      IGNORE_UNUSED_RESULT(
15465
          remove(ctx->listening_sockets[i].lsa.sun.sun_path));
15466
    }
15467
#endif
15468
2
    ctx->listening_sockets[i].sock = INVALID_SOCKET;
15469
2
  }
15470
2
  mg_free(ctx->listening_sockets);
15471
2
  ctx->listening_sockets = NULL;
15472
2
  mg_free(ctx->listening_socket_fds);
15473
2
  ctx->listening_socket_fds = NULL;
15474
2
}
15475
15476
15477
/* Valid listening port specification is: [ip_address:]port[s]
15478
 * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
15479
 * Examples for IPv6: [::]:80, [::1]:80,
15480
 *   [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
15481
 *   see https://tools.ietf.org/html/rfc3513#section-2.2
15482
 * In order to bind to both, IPv4 and IPv6, you can either add
15483
 * both ports using 8080,[::]:8080, or the short form +8080.
15484
 * Both forms differ in detail: 8080,[::]:8080 create two sockets,
15485
 * one only accepting IPv4 the other only IPv6. +8080 creates
15486
 * one socket accepting IPv4 and IPv6. Depending on the IPv6
15487
 * environment, they might work differently, or might not work
15488
 * at all - it must be tested what options work best in the
15489
 * relevant network environment.
15490
 */
15491
static int
15492
parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
15493
2
{
15494
2
  unsigned int a, b, c, d;
15495
2
  unsigned port;
15496
2
  unsigned long portUL;
15497
2
  int ch, len;
15498
2
  const char *cb;
15499
2
  char *endptr;
15500
#if defined(USE_IPV6)
15501
  char buf[100] = {0};
15502
#endif
15503
15504
  /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
15505
   * Also, all-zeroes in the socket address means binding to all addresses
15506
   * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
15507
2
  memset(so, 0, sizeof(*so));
15508
2
  so->lsa.sin.sin_family = AF_INET;
15509
2
  *ip_version = 0;
15510
15511
  /* Initialize len as invalid. */
15512
2
  port = 0;
15513
2
  len = 0;
15514
15515
  /* Test for different ways to format this string */
15516
2
  if (sscanf(vec->ptr,
15517
2
             "%u.%u.%u.%u:%u%n",
15518
2
             &a,
15519
2
             &b,
15520
2
             &c,
15521
2
             &d,
15522
2
             &port,
15523
2
             &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
15524
                   // to an integer value, but function will not report
15525
                   // conversion errors; consider using 'strtol' instead
15526
2
      == 5) {
15527
    /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
15528
0
    so->lsa.sin.sin_addr.s_addr =
15529
0
        htonl((a << 24) | (b << 16) | (c << 8) | d);
15530
0
    so->lsa.sin.sin_port = htons((uint16_t)port);
15531
0
    *ip_version = 4;
15532
15533
#if defined(USE_IPV6)
15534
  } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
15535
             && ((size_t)len <= vec->len)
15536
             && mg_inet_pton(
15537
                    AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
15538
    /* IPv6 address, examples: see above */
15539
    /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
15540
     */
15541
    so->lsa.sin6.sin6_port = htons((uint16_t)port);
15542
    *ip_version = 6;
15543
#endif
15544
15545
2
  } else if ((vec->ptr[0] == '+')
15546
2
             && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
15547
0
                 == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
15548
                        // string to an integer value, but function will not
15549
                        // report conversion errors; consider using 'strtol'
15550
                        // instead
15551
15552
    /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
15553
    /* Add 1 to len for the + character we skipped before */
15554
0
    len++;
15555
15556
#if defined(USE_IPV6)
15557
    /* Set socket family to IPv6, do not use IPV6_V6ONLY */
15558
    so->lsa.sin6.sin6_family = AF_INET6;
15559
    so->lsa.sin6.sin6_port = htons((uint16_t)port);
15560
    *ip_version = 4 + 6;
15561
#else
15562
    /* Bind to IPv4 only, since IPv6 is not built in. */
15563
0
    so->lsa.sin.sin_port = htons((uint16_t)port);
15564
0
    *ip_version = 4;
15565
0
#endif
15566
15567
2
  } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
15568
2
             && (vec->ptr != endptr)) {
15569
2
    len = (int)(endptr - vec->ptr);
15570
2
    port = (uint16_t)portUL;
15571
    /* If only port is specified, bind to IPv4, INADDR_ANY */
15572
2
    so->lsa.sin.sin_port = htons((uint16_t)port);
15573
2
    *ip_version = 4;
15574
15575
2
  } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
15576
    /* String could be a hostname. This check algorithm
15577
     * will only work for RFC 952 compliant hostnames,
15578
     * starting with a letter, containing only letters,
15579
     * digits and hyphen ('-'). Newer specs may allow
15580
     * more, but this is not guaranteed here, since it
15581
     * may interfere with rules for port option lists. */
15582
15583
    /* According to RFC 1035, hostnames are restricted to 255 characters
15584
     * in total (63 between two dots). */
15585
0
    char hostname[256];
15586
0
    size_t hostnlen = (size_t)(cb - vec->ptr);
15587
15588
0
    if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
15589
      /* This would be invalid in any case */
15590
0
      *ip_version = 0;
15591
0
      return 0;
15592
0
    }
15593
15594
0
    mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
15595
15596
0
    if (mg_inet_pton(
15597
0
            AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
15598
0
      if (sscanf(cb + 1, "%u%n", &port, &len)
15599
0
          == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
15600
                // string to an integer value, but function will not
15601
                // report conversion errors; consider using 'strtol'
15602
                // instead
15603
0
        *ip_version = 4;
15604
0
        so->lsa.sin.sin_port = htons((uint16_t)port);
15605
0
        len += (int)(hostnlen + 1);
15606
0
      } else {
15607
0
        len = 0;
15608
0
      }
15609
#if defined(USE_IPV6)
15610
    } else if (mg_inet_pton(AF_INET6,
15611
                            hostname,
15612
                            &so->lsa.sin6,
15613
                            sizeof(so->lsa.sin6),
15614
                            1)) {
15615
      if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
15616
        *ip_version = 6;
15617
        so->lsa.sin6.sin6_port = htons((uint16_t)port);
15618
        len += (int)(hostnlen + 1);
15619
      } else {
15620
        len = 0;
15621
      }
15622
#endif
15623
0
    } else {
15624
0
      len = 0;
15625
0
    }
15626
15627
#if defined(USE_X_DOM_SOCKET)
15628
15629
  } else if (vec->ptr[0] == 'x') {
15630
    /* unix (linux) domain socket */
15631
    if (vec->len < sizeof(so->lsa.sun.sun_path)) {
15632
      len = vec->len;
15633
      so->lsa.sun.sun_family = AF_UNIX;
15634
      memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
15635
      memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
15636
      port = 0;
15637
      *ip_version = 99;
15638
    } else {
15639
      /* String too long */
15640
      len = 0;
15641
    }
15642
#endif
15643
15644
0
  } else {
15645
    /* Parsing failure. */
15646
0
    len = 0;
15647
0
  }
15648
15649
  /* sscanf and the option splitting code ensure the following condition
15650
   * Make sure the port is valid and vector ends with the port, 's' or 'r' */
15651
2
  if ((len > 0) && is_valid_port(port)
15652
2
      && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
15653
    /* Next character after the port number */
15654
2
    ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
15655
2
    so->is_ssl = (ch == 's');
15656
2
    so->ssl_redir = (ch == 'r');
15657
2
    if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
15658
2
      return 1;
15659
2
    }
15660
2
  }
15661
15662
  /* Reset ip_version to 0 if there is an error */
15663
0
  *ip_version = 0;
15664
0
  return 0;
15665
2
}
15666
15667
15668
/* Is there any SSL port in use? */
15669
static int
15670
is_ssl_port_used(const char *ports)
15671
4
{
15672
4
  if (ports) {
15673
    /* There are several different allowed syntax variants:
15674
     * - "80" for a single port using every network interface
15675
     * - "localhost:80" for a single port using only localhost
15676
     * - "80,localhost:8080" for two ports, one bound to localhost
15677
     * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
15678
     *   to IPv4 localhost, one to IPv6 localhost
15679
     * - "+80" use port 80 for IPv4 and IPv6
15680
     * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
15681
     *   for both: IPv4 and IPv4
15682
     * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
15683
     *   additionally port 8080 bound to localhost connections
15684
     *
15685
     * If we just look for 's' anywhere in the string, "localhost:80"
15686
     * will be detected as SSL (false positive).
15687
     * Looking for 's' after a digit may cause false positives in
15688
     * "my24service:8080".
15689
     * Looking from 's' backward if there are only ':' and numbers
15690
     * before will not work for "24service:8080" (non SSL, port 8080)
15691
     * or "24s" (SSL, port 24).
15692
     *
15693
     * Remark: Initially hostnames were not allowed to start with a
15694
     * digit (according to RFC 952), this was allowed later (RFC 1123,
15695
     * Section 2.1).
15696
     *
15697
     * To get this correct, the entire string must be parsed as a whole,
15698
     * reading it as a list element for element and parsing with an
15699
     * algorithm equivalent to parse_port_string.
15700
     *
15701
     * In fact, we use local interface names here, not arbitrary
15702
     * hostnames, so in most cases the only name will be "localhost".
15703
     *
15704
     * So, for now, we use this simple algorithm, that may still return
15705
     * a false positive in bizarre cases.
15706
     */
15707
4
    int i;
15708
4
    int portslen = (int)strlen(ports);
15709
4
    char prevIsNumber = 0;
15710
15711
8
    for (i = 0; i < portslen; i++) {
15712
4
      if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
15713
0
        return 1;
15714
0
      }
15715
4
      if (ports[i] >= '0' && ports[i] <= '9') {
15716
4
        prevIsNumber = 1;
15717
4
      } else {
15718
0
        prevIsNumber = 0;
15719
0
      }
15720
4
    }
15721
4
  }
15722
4
  return 0;
15723
4
}
15724
15725
15726
static int
15727
set_ports_option(struct mg_context *phys_ctx)
15728
2
{
15729
2
  const char *list;
15730
2
  int on = 1;
15731
#if defined(USE_IPV6)
15732
  int off = 0;
15733
#endif
15734
2
  struct vec vec;
15735
2
  struct socket so, *ptr;
15736
15737
2
  struct mg_pollfd *pfd;
15738
2
  union usa usa;
15739
2
  socklen_t len;
15740
2
  int ip_version;
15741
15742
2
  int portsTotal = 0;
15743
2
  int portsOk = 0;
15744
15745
2
  const char *opt_txt;
15746
2
  long opt_listen_backlog;
15747
15748
2
  if (!phys_ctx) {
15749
0
    return 0;
15750
0
  }
15751
15752
2
  memset(&so, 0, sizeof(so));
15753
2
  memset(&usa, 0, sizeof(usa));
15754
2
  len = sizeof(usa);
15755
2
  list = phys_ctx->dd.config[LISTENING_PORTS];
15756
15757
4
  while ((list = next_option(list, &vec, NULL)) != NULL) {
15758
15759
2
    portsTotal++;
15760
15761
2
    if (!parse_port_string(&vec, &so, &ip_version)) {
15762
0
      mg_cry_ctx_internal(
15763
0
          phys_ctx,
15764
0
          "%.*s: invalid port spec (entry %i). Expecting list of: %s",
15765
0
          (int)vec.len,
15766
0
          vec.ptr,
15767
0
          portsTotal,
15768
0
          "[IP_ADDRESS:]PORT[s|r]");
15769
0
      continue;
15770
0
    }
15771
15772
2
#if !defined(NO_SSL)
15773
2
    if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
15774
15775
0
      mg_cry_ctx_internal(phys_ctx,
15776
0
                          "Cannot add SSL socket (entry %i)",
15777
0
                          portsTotal);
15778
0
      continue;
15779
0
    }
15780
2
#endif
15781
    /* Create socket. */
15782
    /* For a list of protocol numbers (e.g., TCP==6) see:
15783
     * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
15784
     */
15785
2
    if ((so.sock =
15786
2
             socket(so.lsa.sa.sa_family,
15787
2
                    SOCK_STREAM,
15788
2
                    (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
15789
2
        == INVALID_SOCKET) {
15790
15791
0
      mg_cry_ctx_internal(phys_ctx,
15792
0
                          "cannot create socket (entry %i)",
15793
0
                          portsTotal);
15794
0
      continue;
15795
0
    }
15796
15797
#if defined(_WIN32)
15798
    /* Windows SO_REUSEADDR lets many procs binds to a
15799
     * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
15800
     * if someone already has the socket -- DTL */
15801
    /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
15802
     * Windows might need a few seconds before
15803
     * the same port can be used again in the
15804
     * same process, so a short Sleep may be
15805
     * required between mg_stop and mg_start.
15806
     */
15807
    if (setsockopt(so.sock,
15808
                   SOL_SOCKET,
15809
                   SO_EXCLUSIVEADDRUSE,
15810
                   (SOCK_OPT_TYPE)&on,
15811
                   sizeof(on))
15812
        != 0) {
15813
15814
      /* Set reuse option, but don't abort on errors. */
15815
      mg_cry_ctx_internal(
15816
          phys_ctx,
15817
          "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
15818
          portsTotal);
15819
    }
15820
#else
15821
2
    if (setsockopt(so.sock,
15822
2
                   SOL_SOCKET,
15823
2
                   SO_REUSEADDR,
15824
2
                   (SOCK_OPT_TYPE)&on,
15825
2
                   sizeof(on))
15826
2
        != 0) {
15827
15828
      /* Set reuse option, but don't abort on errors. */
15829
0
      mg_cry_ctx_internal(
15830
0
          phys_ctx,
15831
0
          "cannot set socket option SO_REUSEADDR (entry %i)",
15832
0
          portsTotal);
15833
0
    }
15834
2
#endif
15835
15836
#if defined(USE_X_DOM_SOCKET)
15837
    if (ip_version == 99) {
15838
      /* Unix domain socket */
15839
    } else
15840
#endif
15841
15842
2
        if (ip_version > 4) {
15843
      /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
15844
#if defined(USE_IPV6)
15845
      if (ip_version > 6) {
15846
        if (so.lsa.sa.sa_family == AF_INET6
15847
            && setsockopt(so.sock,
15848
                          IPPROTO_IPV6,
15849
                          IPV6_V6ONLY,
15850
                          (void *)&off,
15851
                          sizeof(off))
15852
                   != 0) {
15853
15854
          /* Set IPv6 only option, but don't abort on errors. */
15855
          mg_cry_ctx_internal(phys_ctx,
15856
                              "cannot set socket option "
15857
                              "IPV6_V6ONLY=off (entry %i)",
15858
                              portsTotal);
15859
        }
15860
      } else {
15861
        if (so.lsa.sa.sa_family == AF_INET6
15862
            && setsockopt(so.sock,
15863
                          IPPROTO_IPV6,
15864
                          IPV6_V6ONLY,
15865
                          (void *)&on,
15866
                          sizeof(on))
15867
                   != 0) {
15868
15869
          /* Set IPv6 only option, but don't abort on errors. */
15870
          mg_cry_ctx_internal(phys_ctx,
15871
                              "cannot set socket option "
15872
                              "IPV6_V6ONLY=on (entry %i)",
15873
                              portsTotal);
15874
        }
15875
      }
15876
#else
15877
0
      mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
15878
0
      closesocket(so.sock);
15879
0
      so.sock = INVALID_SOCKET;
15880
0
      continue;
15881
0
#endif
15882
0
    }
15883
15884
2
    if (so.lsa.sa.sa_family == AF_INET) {
15885
15886
2
      len = sizeof(so.lsa.sin);
15887
2
      if (bind(so.sock, &so.lsa.sa, len) != 0) {
15888
0
        mg_cry_ctx_internal(phys_ctx,
15889
0
                            "cannot bind to %.*s: %d (%s)",
15890
0
                            (int)vec.len,
15891
0
                            vec.ptr,
15892
0
                            (int)ERRNO,
15893
0
                            strerror(errno));
15894
0
        closesocket(so.sock);
15895
0
        so.sock = INVALID_SOCKET;
15896
0
        continue;
15897
0
      }
15898
2
    }
15899
#if defined(USE_IPV6)
15900
    else if (so.lsa.sa.sa_family == AF_INET6) {
15901
15902
      len = sizeof(so.lsa.sin6);
15903
      if (bind(so.sock, &so.lsa.sa, len) != 0) {
15904
        mg_cry_ctx_internal(phys_ctx,
15905
                            "cannot bind to IPv6 %.*s: %d (%s)",
15906
                            (int)vec.len,
15907
                            vec.ptr,
15908
                            (int)ERRNO,
15909
                            strerror(errno));
15910
        closesocket(so.sock);
15911
        so.sock = INVALID_SOCKET;
15912
        continue;
15913
      }
15914
    }
15915
#endif
15916
#if defined(USE_X_DOM_SOCKET)
15917
    else if (so.lsa.sa.sa_family == AF_UNIX) {
15918
15919
      len = sizeof(so.lsa.sun);
15920
      if (bind(so.sock, &so.lsa.sa, len) != 0) {
15921
        mg_cry_ctx_internal(phys_ctx,
15922
                            "cannot bind to unix socket %s: %d (%s)",
15923
                            so.lsa.sun.sun_path,
15924
                            (int)ERRNO,
15925
                            strerror(errno));
15926
        closesocket(so.sock);
15927
        so.sock = INVALID_SOCKET;
15928
        continue;
15929
      }
15930
    }
15931
#endif
15932
0
    else {
15933
0
      mg_cry_ctx_internal(
15934
0
          phys_ctx,
15935
0
          "cannot bind: address family not supported (entry %i)",
15936
0
          portsTotal);
15937
0
      closesocket(so.sock);
15938
0
      so.sock = INVALID_SOCKET;
15939
0
      continue;
15940
0
    }
15941
15942
2
    opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
15943
2
    opt_listen_backlog = strtol(opt_txt, NULL, 10);
15944
2
    if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
15945
0
      mg_cry_ctx_internal(phys_ctx,
15946
0
                          "%s value \"%s\" is invalid",
15947
0
                          config_options[LISTEN_BACKLOG_SIZE].name,
15948
0
                          opt_txt);
15949
0
      closesocket(so.sock);
15950
0
      so.sock = INVALID_SOCKET;
15951
0
      continue;
15952
0
    }
15953
15954
2
    if (listen(so.sock, (int)opt_listen_backlog) != 0) {
15955
15956
0
      mg_cry_ctx_internal(phys_ctx,
15957
0
                          "cannot listen to %.*s: %d (%s)",
15958
0
                          (int)vec.len,
15959
0
                          vec.ptr,
15960
0
                          (int)ERRNO,
15961
0
                          strerror(errno));
15962
0
      closesocket(so.sock);
15963
0
      so.sock = INVALID_SOCKET;
15964
0
      continue;
15965
0
    }
15966
15967
2
    if ((getsockname(so.sock, &(usa.sa), &len) != 0)
15968
2
        || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
15969
15970
0
      int err = (int)ERRNO;
15971
0
      mg_cry_ctx_internal(phys_ctx,
15972
0
                          "call to getsockname failed %.*s: %d (%s)",
15973
0
                          (int)vec.len,
15974
0
                          vec.ptr,
15975
0
                          err,
15976
0
                          strerror(errno));
15977
0
      closesocket(so.sock);
15978
0
      so.sock = INVALID_SOCKET;
15979
0
      continue;
15980
0
    }
15981
15982
    /* Update lsa port in case of random free ports */
15983
#if defined(USE_IPV6)
15984
    if (so.lsa.sa.sa_family == AF_INET6) {
15985
      so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
15986
    } else
15987
#endif
15988
2
    {
15989
2
      so.lsa.sin.sin_port = usa.sin.sin_port;
15990
2
    }
15991
15992
2
    if ((ptr = (struct socket *)
15993
2
             mg_realloc_ctx(phys_ctx->listening_sockets,
15994
2
                            (phys_ctx->num_listening_sockets + 1)
15995
2
                                * sizeof(phys_ctx->listening_sockets[0]),
15996
2
                            phys_ctx))
15997
2
        == NULL) {
15998
15999
0
      mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
16000
0
      closesocket(so.sock);
16001
0
      so.sock = INVALID_SOCKET;
16002
0
      continue;
16003
0
    }
16004
16005
2
    if ((pfd = (struct mg_pollfd *)
16006
2
             mg_realloc_ctx(phys_ctx->listening_socket_fds,
16007
2
                            (phys_ctx->num_listening_sockets + 1)
16008
2
                                * sizeof(phys_ctx->listening_socket_fds[0]),
16009
2
                            phys_ctx))
16010
2
        == NULL) {
16011
16012
0
      mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
16013
0
      closesocket(so.sock);
16014
0
      so.sock = INVALID_SOCKET;
16015
0
      mg_free(ptr);
16016
0
      continue;
16017
0
    }
16018
16019
2
    set_close_on_exec(so.sock, NULL, phys_ctx);
16020
2
    phys_ctx->listening_sockets = ptr;
16021
2
    phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
16022
2
    phys_ctx->listening_socket_fds = pfd;
16023
2
    phys_ctx->num_listening_sockets++;
16024
2
    portsOk++;
16025
2
  }
16026
16027
2
  if (portsOk != portsTotal) {
16028
0
    close_all_listening_sockets(phys_ctx);
16029
0
    portsOk = 0;
16030
0
  }
16031
16032
2
  return portsOk;
16033
2
}
16034
16035
16036
static const char *
16037
header_val(const struct mg_connection *conn, const char *header)
16038
0
{
16039
0
  const char *header_value;
16040
16041
0
  if ((header_value = mg_get_header(conn, header)) == NULL) {
16042
0
    return "-";
16043
0
  } else {
16044
0
    return header_value;
16045
0
  }
16046
0
}
16047
16048
16049
#if defined(MG_EXTERNAL_FUNCTION_log_access)
16050
#include "external_log_access.inl"
16051
#elif !defined(NO_FILESYSTEMS)
16052
16053
static void
16054
log_access(const struct mg_connection *conn)
16055
0
{
16056
0
  const struct mg_request_info *ri;
16057
0
  struct mg_file fi;
16058
0
  char date[64], src_addr[IP_ADDR_STR_LEN];
16059
#if defined(REENTRANT_TIME)
16060
  struct tm _tm;
16061
  struct tm *tm = &_tm;
16062
#else
16063
0
  struct tm *tm;
16064
0
#endif
16065
16066
0
  const char *referer;
16067
0
  const char *user_agent;
16068
16069
0
  char log_buf[4096];
16070
16071
0
  if (!conn || !conn->dom_ctx) {
16072
0
    return;
16073
0
  }
16074
16075
  /* Set log message to "empty" */
16076
0
  log_buf[0] = 0;
16077
16078
#if defined(USE_LUA)
16079
  if (conn->phys_ctx->lua_bg_log_available) {
16080
    int ret;
16081
    struct mg_context *ctx = conn->phys_ctx;
16082
    lua_State *lstate = (lua_State *)ctx->lua_background_state;
16083
    pthread_mutex_lock(&ctx->lua_bg_mutex);
16084
    /* call "log()" in Lua */
16085
    lua_getglobal(lstate, "log");
16086
    prepare_lua_request_info_inner(conn, lstate);
16087
    push_lua_response_log_data(conn, lstate);
16088
16089
    ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
16090
    if (ret == 0) {
16091
      int t = lua_type(lstate, -1);
16092
      if (t == LUA_TBOOLEAN) {
16093
        if (lua_toboolean(lstate, -1) == 0) {
16094
          /* log() returned false: do not log */
16095
          pthread_mutex_unlock(&ctx->lua_bg_mutex);
16096
          return;
16097
        }
16098
        /* log returned true: continue logging */
16099
      } else if (t == LUA_TSTRING) {
16100
        size_t len;
16101
        const char *txt = lua_tolstring(lstate, -1, &len);
16102
        if ((len == 0) || (*txt == 0)) {
16103
          /* log() returned empty string: do not log */
16104
          pthread_mutex_unlock(&ctx->lua_bg_mutex);
16105
          return;
16106
        }
16107
        /* Copy test from Lua into log_buf */
16108
        if (len >= sizeof(log_buf)) {
16109
          len = sizeof(log_buf) - 1;
16110
        }
16111
        memcpy(log_buf, txt, len);
16112
        log_buf[len] = 0;
16113
      }
16114
    } else {
16115
      lua_cry(conn, ret, lstate, "lua_background_script", "log");
16116
    }
16117
    pthread_mutex_unlock(&ctx->lua_bg_mutex);
16118
  }
16119
#endif
16120
16121
0
  if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
16122
0
    if (mg_fopen(conn,
16123
0
                 conn->dom_ctx->config[ACCESS_LOG_FILE],
16124
0
                 MG_FOPEN_MODE_APPEND,
16125
0
                 &fi)
16126
0
        == 0) {
16127
0
      fi.access.fp = NULL;
16128
0
    }
16129
0
  } else {
16130
0
    fi.access.fp = NULL;
16131
0
  }
16132
16133
  /* Log is written to a file and/or a callback. If both are not set,
16134
   * executing the rest of the function is pointless. */
16135
0
  if ((fi.access.fp == NULL)
16136
0
      && (conn->phys_ctx->callbacks.log_access == NULL)) {
16137
0
    return;
16138
0
  }
16139
16140
  /* If we did not get a log message from Lua, create it here. */
16141
0
  if (!log_buf[0]) {
16142
#if defined(REENTRANT_TIME)
16143
    localtime_r(&conn->conn_birth_time, tm);
16144
#else
16145
0
    tm = localtime(&conn->conn_birth_time);
16146
0
#endif
16147
0
    if (tm != NULL) {
16148
0
      strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
16149
0
    } else {
16150
0
      mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
16151
0
    }
16152
16153
0
    ri = &conn->request_info;
16154
16155
0
    sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
16156
0
    referer = header_val(conn, "Referer");
16157
0
    user_agent = header_val(conn, "User-Agent");
16158
16159
0
    mg_snprintf(conn,
16160
0
                NULL, /* Ignore truncation in access log */
16161
0
                log_buf,
16162
0
                sizeof(log_buf),
16163
0
                "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
16164
0
                " %s %s",
16165
0
                src_addr,
16166
0
                (ri->remote_user == NULL) ? "-" : ri->remote_user,
16167
0
                date,
16168
0
                ri->request_method ? ri->request_method : "-",
16169
0
                ri->request_uri ? ri->request_uri : "-",
16170
0
                ri->query_string ? "?" : "",
16171
0
                ri->query_string ? ri->query_string : "",
16172
0
                ri->http_version,
16173
0
                conn->status_code,
16174
0
                conn->num_bytes_sent,
16175
0
                referer,
16176
0
                user_agent);
16177
0
  }
16178
16179
  /* Here we have a log message in log_buf. Call the callback */
16180
0
  if (conn->phys_ctx->callbacks.log_access) {
16181
0
    if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
16182
      /* do not log if callback returns non-zero */
16183
0
      if (fi.access.fp) {
16184
0
        mg_fclose(&fi.access);
16185
0
      }
16186
0
      return;
16187
0
    }
16188
0
  }
16189
16190
  /* Store in file */
16191
0
  if (fi.access.fp) {
16192
0
    int ok = 1;
16193
0
    flockfile(fi.access.fp);
16194
0
    if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
16195
0
      ok = 0;
16196
0
    }
16197
0
    if (fflush(fi.access.fp) != 0) {
16198
0
      ok = 0;
16199
0
    }
16200
0
    funlockfile(fi.access.fp);
16201
0
    if (mg_fclose(&fi.access) != 0) {
16202
0
      ok = 0;
16203
0
    }
16204
0
    if (!ok) {
16205
0
      mg_cry_internal(conn,
16206
0
                      "Error writing log file %s",
16207
0
                      conn->dom_ctx->config[ACCESS_LOG_FILE]);
16208
0
    }
16209
0
  }
16210
0
}
16211
#else
16212
#error "Either enable filesystems or provide a custom log_access implementation"
16213
#endif /* Externally provided function */
16214
16215
16216
/* Verify given socket address against the ACL.
16217
 * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
16218
 */
16219
static int
16220
check_acl(struct mg_context *phys_ctx, const union usa *sa)
16221
2
{
16222
2
  int allowed, flag, matched;
16223
2
  struct vec vec;
16224
16225
2
  if (phys_ctx) {
16226
2
    const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
16227
16228
    /* If any ACL is set, deny by default */
16229
2
    allowed = (list == NULL) ? '+' : '-';
16230
16231
2
    while ((list = next_option(list, &vec, NULL)) != NULL) {
16232
0
      flag = vec.ptr[0];
16233
0
      matched = -1;
16234
0
      if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
16235
0
        vec.ptr++;
16236
0
        vec.len--;
16237
0
        matched = parse_match_net(&vec, sa, 1);
16238
0
      }
16239
0
      if (matched < 0) {
16240
0
        mg_cry_ctx_internal(phys_ctx,
16241
0
                            "%s: subnet must be [+|-]IP-addr[/x]",
16242
0
                            __func__);
16243
0
        return -1;
16244
0
      }
16245
0
      if (matched) {
16246
0
        allowed = flag;
16247
0
      }
16248
0
    }
16249
16250
2
    return allowed == '+';
16251
2
  }
16252
0
  return -1;
16253
2
}
16254
16255
16256
#if !defined(_WIN32) && !defined(__ZEPHYR__)
16257
static int
16258
set_uid_option(struct mg_context *phys_ctx)
16259
2
{
16260
2
  int success = 0;
16261
16262
2
  if (phys_ctx) {
16263
    /* We are currently running as curr_uid. */
16264
2
    const uid_t curr_uid = getuid();
16265
    /* If set, we want to run as run_as_user. */
16266
2
    const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
16267
2
    const struct passwd *to_pw = NULL;
16268
16269
2
    if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
16270
      /* run_as_user does not exist on the system. We can't proceed
16271
       * further. */
16272
0
      mg_cry_ctx_internal(phys_ctx,
16273
0
                          "%s: unknown user [%s]",
16274
0
                          __func__,
16275
0
                          run_as_user);
16276
2
    } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
16277
      /* There was either no request to change user, or we're already
16278
       * running as run_as_user. Nothing else to do.
16279
       */
16280
2
      success = 1;
16281
2
    } else {
16282
      /* Valid change request.  */
16283
0
      if (setgid(to_pw->pw_gid) == -1) {
16284
0
        mg_cry_ctx_internal(phys_ctx,
16285
0
                            "%s: setgid(%s): %s",
16286
0
                            __func__,
16287
0
                            run_as_user,
16288
0
                            strerror(errno));
16289
0
      } else if (setgroups(0, NULL) == -1) {
16290
0
        mg_cry_ctx_internal(phys_ctx,
16291
0
                            "%s: setgroups(): %s",
16292
0
                            __func__,
16293
0
                            strerror(errno));
16294
0
      } else if (setuid(to_pw->pw_uid) == -1) {
16295
0
        mg_cry_ctx_internal(phys_ctx,
16296
0
                            "%s: setuid(%s): %s",
16297
0
                            __func__,
16298
0
                            run_as_user,
16299
0
                            strerror(errno));
16300
0
      } else {
16301
0
        success = 1;
16302
0
      }
16303
0
    }
16304
2
  }
16305
16306
2
  return success;
16307
2
}
16308
#endif /* !_WIN32 */
16309
16310
16311
static void
16312
tls_dtor(void *key)
16313
0
{
16314
0
  struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
16315
  /* key == pthread_getspecific(sTlsKey); */
16316
16317
0
  if (tls) {
16318
0
    if (tls->is_master == 2) {
16319
0
      tls->is_master = -3; /* Mark memory as dead */
16320
0
      mg_free(tls);
16321
0
    }
16322
0
  }
16323
0
  pthread_setspecific(sTlsKey, NULL);
16324
0
}
16325
16326
16327
#if defined(USE_MBEDTLS)
16328
/* Check if SSL is required.
16329
 * If so, set up ctx->ssl_ctx pointer. */
16330
static int
16331
mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16332
{
16333
  if (!phys_ctx) {
16334
    return 0;
16335
  }
16336
16337
  if (!dom_ctx) {
16338
    dom_ctx = &(phys_ctx->dd);
16339
  }
16340
16341
  if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
16342
    /* No SSL port is set. No need to setup SSL. */
16343
    return 1;
16344
  }
16345
16346
  dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
16347
  if (dom_ctx->ssl_ctx == NULL) {
16348
    fprintf(stderr, "ssl_ctx malloc failed\n");
16349
    return 0;
16350
  }
16351
16352
  return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
16353
                 == 0
16354
             ? 1
16355
             : 0;
16356
}
16357
16358
#elif !defined(NO_SSL)
16359
16360
static int ssl_use_pem_file(struct mg_context *phys_ctx,
16361
                            struct mg_domain_context *dom_ctx,
16362
                            const char *pem,
16363
                            const char *chain);
16364
static const char *ssl_error(void);
16365
16366
16367
static int
16368
refresh_trust(struct mg_connection *conn)
16369
0
{
16370
0
  struct stat cert_buf;
16371
0
  int64_t t = 0;
16372
0
  const char *pem;
16373
0
  const char *chain;
16374
0
  int should_verify_peer;
16375
16376
0
  if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
16377
    /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
16378
     * refresh_trust still can not work. */
16379
0
    return 0;
16380
0
  }
16381
0
  chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
16382
0
  if (chain == NULL) {
16383
    /* pem is not NULL here */
16384
0
    chain = pem;
16385
0
  }
16386
0
  if (*chain == 0) {
16387
0
    chain = NULL;
16388
0
  }
16389
16390
0
  if (stat(pem, &cert_buf) != -1) {
16391
0
    t = (int64_t)cert_buf.st_mtime;
16392
0
  }
16393
16394
0
  mg_lock_context(conn->phys_ctx);
16395
0
  if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
16396
0
    conn->dom_ctx->ssl_cert_last_mtime = t;
16397
16398
0
    should_verify_peer = 0;
16399
0
    if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
16400
0
      if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
16401
0
          == 0) {
16402
0
        should_verify_peer = 1;
16403
0
      } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
16404
0
                               "optional")
16405
0
                 == 0) {
16406
0
        should_verify_peer = 1;
16407
0
      }
16408
0
    }
16409
16410
0
    if (should_verify_peer) {
16411
0
      char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
16412
0
      char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
16413
0
      if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
16414
0
                                        ca_file,
16415
0
                                        ca_path)
16416
0
          != 1) {
16417
0
        mg_unlock_context(conn->phys_ctx);
16418
0
        mg_cry_ctx_internal(
16419
0
            conn->phys_ctx,
16420
0
            "SSL_CTX_load_verify_locations error: %s "
16421
0
            "ssl_verify_peer requires setting "
16422
0
            "either ssl_ca_path or ssl_ca_file. Is any of them "
16423
0
            "present in "
16424
0
            "the .conf file?",
16425
0
            ssl_error());
16426
0
        return 0;
16427
0
      }
16428
0
    }
16429
16430
0
    if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
16431
0
      mg_unlock_context(conn->phys_ctx);
16432
0
      return 0;
16433
0
    }
16434
0
  }
16435
0
  mg_unlock_context(conn->phys_ctx);
16436
16437
0
  return 1;
16438
0
}
16439
16440
#if defined(OPENSSL_API_1_1)
16441
#else
16442
static pthread_mutex_t *ssl_mutexes;
16443
#endif /* OPENSSL_API_1_1 */
16444
16445
static int
16446
sslize(struct mg_connection *conn,
16447
       int (*func)(SSL *),
16448
       const struct mg_client_options *client_options)
16449
0
{
16450
0
  int ret, err;
16451
0
  int short_trust;
16452
0
  unsigned timeout = 1024;
16453
0
  unsigned i;
16454
16455
0
  if (!conn) {
16456
0
    return 0;
16457
0
  }
16458
16459
0
  short_trust =
16460
0
      (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
16461
0
      && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
16462
16463
0
  if (short_trust) {
16464
0
    int trust_ret = refresh_trust(conn);
16465
0
    if (!trust_ret) {
16466
0
      return trust_ret;
16467
0
    }
16468
0
  }
16469
16470
0
  mg_lock_context(conn->phys_ctx);
16471
0
  conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
16472
0
  mg_unlock_context(conn->phys_ctx);
16473
0
  if (conn->ssl == NULL) {
16474
0
    mg_cry_internal(conn, "sslize error: %s", ssl_error());
16475
0
    OPENSSL_REMOVE_THREAD_STATE();
16476
0
    return 0;
16477
0
  }
16478
0
  SSL_set_app_data(conn->ssl, (char *)conn);
16479
16480
0
  ret = SSL_set_fd(conn->ssl, conn->client.sock);
16481
0
  if (ret != 1) {
16482
0
    mg_cry_internal(conn, "sslize error: %s", ssl_error());
16483
0
    SSL_free(conn->ssl);
16484
0
    conn->ssl = NULL;
16485
0
    OPENSSL_REMOVE_THREAD_STATE();
16486
0
    return 0;
16487
0
  }
16488
16489
0
  if (client_options) {
16490
0
    if (client_options->host_name) {
16491
0
      SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
16492
0
    }
16493
0
  }
16494
16495
  /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout  */
16496
0
  if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
16497
    /* NOTE: The loop below acts as a back-off, so we can end
16498
     * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
16499
0
    int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
16500
0
    if (to >= 0) {
16501
0
      timeout = (unsigned)to;
16502
0
    }
16503
0
  }
16504
16505
  /* SSL functions may fail and require to be called again:
16506
   * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
16507
   * Here "func" could be SSL_connect or SSL_accept. */
16508
0
  for (i = 0; i <= timeout; i += 50) {
16509
0
    ERR_clear_error();
16510
    /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
16511
0
    ret = func(conn->ssl);
16512
0
    if (ret != 1) {
16513
0
      err = SSL_get_error(conn->ssl, ret);
16514
0
      if ((err == SSL_ERROR_WANT_CONNECT)
16515
0
          || (err == SSL_ERROR_WANT_ACCEPT)
16516
0
          || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
16517
0
          || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
16518
0
        if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
16519
          /* Don't wait if the server is going to be stopped. */
16520
0
          break;
16521
0
        }
16522
0
        if (err == SSL_ERROR_WANT_X509_LOOKUP) {
16523
          /* Simply retry the function call. */
16524
0
          mg_sleep(50);
16525
0
        } else {
16526
          /* Need to retry the function call "later".
16527
           * See https://linux.die.net/man/3/ssl_get_error
16528
           * This is typical for non-blocking sockets. */
16529
0
          struct mg_pollfd pfd;
16530
0
          int pollres;
16531
0
          pfd.fd = conn->client.sock;
16532
0
          pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
16533
0
                        || (err == SSL_ERROR_WANT_WRITE))
16534
0
                           ? POLLOUT
16535
0
                           : POLLIN;
16536
0
          pollres =
16537
0
              mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
16538
0
          if (pollres < 0) {
16539
            /* Break if error occurred (-1)
16540
             * or server shutdown (-2) */
16541
0
            break;
16542
0
          }
16543
0
        }
16544
16545
0
      } else if (err == SSL_ERROR_SYSCALL) {
16546
        /* This is an IO error. Look at errno. */
16547
0
        mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
16548
0
        break;
16549
16550
0
      } else {
16551
        /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
16552
0
        mg_cry_internal(conn, "sslize error: %s", ssl_error());
16553
0
        break;
16554
0
      }
16555
16556
0
    } else {
16557
      /* success */
16558
0
      break;
16559
0
    }
16560
0
  }
16561
0
  ERR_clear_error();
16562
16563
0
  if (ret != 1) {
16564
0
    SSL_free(conn->ssl);
16565
0
    conn->ssl = NULL;
16566
0
    OPENSSL_REMOVE_THREAD_STATE();
16567
0
    return 0;
16568
0
  }
16569
16570
0
  return 1;
16571
0
}
16572
16573
16574
/* Return OpenSSL error message (from CRYPTO lib) */
16575
static const char *
16576
ssl_error(void)
16577
0
{
16578
0
  unsigned long err;
16579
0
  err = ERR_get_error();
16580
0
  return ((err == 0) ? "" : ERR_error_string(err, NULL));
16581
0
}
16582
16583
16584
static int
16585
hexdump2string(void *mem, int memlen, char *buf, int buflen)
16586
0
{
16587
0
  int i;
16588
0
  const char hexdigit[] = "0123456789abcdef";
16589
16590
0
  if ((memlen <= 0) || (buflen <= 0)) {
16591
0
    return 0;
16592
0
  }
16593
0
  if (buflen < (3 * memlen)) {
16594
0
    return 0;
16595
0
  }
16596
16597
0
  for (i = 0; i < memlen; i++) {
16598
0
    if (i > 0) {
16599
0
      buf[3 * i - 1] = ' ';
16600
0
    }
16601
0
    buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
16602
0
    buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
16603
0
  }
16604
0
  buf[3 * memlen - 1] = 0;
16605
16606
0
  return 1;
16607
0
}
16608
16609
16610
static int
16611
ssl_get_client_cert_info(const struct mg_connection *conn,
16612
                         struct mg_client_cert *client_cert)
16613
0
{
16614
0
  X509 *cert = SSL_get_peer_certificate(conn->ssl);
16615
0
  if (cert) {
16616
0
    char str_buf[1024];
16617
0
    unsigned char buf[256];
16618
0
    char *str_serial = NULL;
16619
0
    unsigned int ulen;
16620
0
    int ilen;
16621
0
    unsigned char *tmp_buf;
16622
0
    unsigned char *tmp_p;
16623
16624
    /* Handle to algorithm used for fingerprint */
16625
0
    const EVP_MD *digest = EVP_get_digestbyname("sha1");
16626
16627
    /* Get Subject and issuer */
16628
0
    X509_NAME *subj = X509_get_subject_name(cert);
16629
0
    X509_NAME *iss = X509_get_issuer_name(cert);
16630
16631
    /* Get serial number */
16632
0
    ASN1_INTEGER *serial = X509_get_serialNumber(cert);
16633
16634
    /* Translate serial number to a hex string */
16635
0
    BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
16636
0
    if (serial_bn) {
16637
0
      str_serial = BN_bn2hex(serial_bn);
16638
0
      BN_free(serial_bn);
16639
0
    }
16640
0
    client_cert->serial =
16641
0
        str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
16642
16643
    /* Translate subject and issuer to a string */
16644
0
    (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
16645
0
    client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
16646
0
    (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
16647
0
    client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
16648
16649
    /* Calculate SHA1 fingerprint and store as a hex string */
16650
0
    ulen = 0;
16651
16652
    /* ASN1_digest is deprecated. Do the calculation manually,
16653
     * using EVP_Digest. */
16654
0
    ilen = i2d_X509(cert, NULL);
16655
0
    tmp_buf = (ilen > 0)
16656
0
                  ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
16657
0
                                                   conn->phys_ctx)
16658
0
                  : NULL;
16659
0
    if (tmp_buf) {
16660
0
      tmp_p = tmp_buf;
16661
0
      (void)i2d_X509(cert, &tmp_p);
16662
0
      if (!EVP_Digest(
16663
0
              tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
16664
0
        ulen = 0;
16665
0
      }
16666
0
      mg_free(tmp_buf);
16667
0
    }
16668
16669
0
    if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
16670
0
      *str_buf = 0;
16671
0
    }
16672
0
    client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
16673
16674
0
    client_cert->peer_cert = (void *)cert;
16675
16676
    /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
16677
     * see https://linux.die.net/man/3/bn_bn2hex */
16678
0
    OPENSSL_free(str_serial);
16679
0
    return 1;
16680
0
  }
16681
0
  return 0;
16682
0
}
16683
16684
16685
#if defined(OPENSSL_API_1_1)
16686
#else
16687
static void
16688
ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
16689
{
16690
  (void)line;
16691
  (void)file;
16692
16693
  if (mode & 1) {
16694
    /* 1 is CRYPTO_LOCK */
16695
    (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
16696
  } else {
16697
    (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
16698
  }
16699
}
16700
#endif /* OPENSSL_API_1_1 */
16701
16702
16703
#if !defined(NO_SSL_DL)
16704
/* Load a DLL/Shared Object with a TLS/SSL implementation. */
16705
static void *
16706
load_tls_dll(char *ebuf,
16707
             size_t ebuf_len,
16708
             const char *dll_name,
16709
             struct ssl_func *sw,
16710
             int *feature_missing)
16711
0
{
16712
0
  union {
16713
0
    void *p;
16714
0
    void (*fp)(void);
16715
0
  } u;
16716
0
  void *dll_handle;
16717
0
  struct ssl_func *fp;
16718
0
  int ok;
16719
0
  int truncated = 0;
16720
16721
0
  if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
16722
0
    mg_snprintf(NULL,
16723
0
                NULL, /* No truncation check for ebuf */
16724
0
                ebuf,
16725
0
                ebuf_len,
16726
0
                "%s: cannot load %s",
16727
0
                __func__,
16728
0
                dll_name);
16729
0
    return NULL;
16730
0
  }
16731
16732
0
  ok = 1;
16733
0
  for (fp = sw; fp->name != NULL; fp++) {
16734
#if defined(_WIN32)
16735
    /* GetProcAddress() returns pointer to function */
16736
    u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
16737
#else
16738
    /* dlsym() on UNIX returns void *. ISO C forbids casts of data
16739
     * pointers to function pointers. We need to use a union to make a
16740
     * cast. */
16741
0
    u.p = dlsym(dll_handle, fp->name);
16742
0
#endif /* _WIN32 */
16743
16744
    /* Set pointer (might be NULL) */
16745
0
    fp->ptr = u.fp;
16746
16747
0
    if (u.fp == NULL) {
16748
0
      DEBUG_TRACE("Missing function: %s\n", fp->name);
16749
0
      if (feature_missing) {
16750
0
        feature_missing[fp->required]++;
16751
0
      }
16752
0
      if (fp->required == TLS_Mandatory) {
16753
        /* Mandatory function is missing */
16754
0
        if (ok) {
16755
          /* This is the first missing function.
16756
           * Create a new error message. */
16757
0
          mg_snprintf(NULL,
16758
0
                      &truncated,
16759
0
                      ebuf,
16760
0
                      ebuf_len,
16761
0
                      "%s: %s: cannot find %s",
16762
0
                      __func__,
16763
0
                      dll_name,
16764
0
                      fp->name);
16765
0
          ok = 0;
16766
0
        } else {
16767
          /* This is yet anothermissing function.
16768
           * Append existing error message. */
16769
0
          size_t cur_len = strlen(ebuf);
16770
0
          if (!truncated && ((ebuf_len - cur_len) > 3)) {
16771
0
            mg_snprintf(NULL,
16772
0
                        &truncated,
16773
0
                        ebuf + cur_len,
16774
0
                        ebuf_len - cur_len - 3,
16775
0
                        ", %s",
16776
0
                        fp->name);
16777
0
            if (truncated) {
16778
              /* If truncated, add "..." */
16779
0
              strcat(ebuf, "...");
16780
0
            }
16781
0
          }
16782
0
        }
16783
0
      }
16784
0
    }
16785
0
  }
16786
16787
0
  if (!ok) {
16788
0
    (void)dlclose(dll_handle);
16789
0
    return NULL;
16790
0
  }
16791
16792
0
  return dll_handle;
16793
0
}
16794
16795
16796
static void *ssllib_dll_handle;    /* Store the ssl library handle. */
16797
static void *cryptolib_dll_handle; /* Store the crypto library handle. */
16798
16799
#endif /* NO_SSL_DL */
16800
16801
16802
#if defined(SSL_ALREADY_INITIALIZED)
16803
static volatile ptrdiff_t cryptolib_users =
16804
    1; /* Reference counter for crypto library. */
16805
#else
16806
static volatile ptrdiff_t cryptolib_users =
16807
    0; /* Reference counter for crypto library. */
16808
#endif
16809
16810
16811
static int
16812
initialize_openssl(char *ebuf, size_t ebuf_len)
16813
0
{
16814
#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16815
  int i, num_locks;
16816
  size_t size;
16817
#endif
16818
16819
0
  if (ebuf_len > 0) {
16820
0
    ebuf[0] = 0;
16821
0
  }
16822
16823
0
#if !defined(NO_SSL_DL)
16824
0
  if (!cryptolib_dll_handle) {
16825
0
    memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
16826
0
    cryptolib_dll_handle = load_tls_dll(
16827
0
        ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
16828
0
    if (!cryptolib_dll_handle) {
16829
0
      mg_snprintf(NULL,
16830
0
                  NULL, /* No truncation check for ebuf */
16831
0
                  ebuf,
16832
0
                  ebuf_len,
16833
0
                  "%s: error loading library %s",
16834
0
                  __func__,
16835
0
                  CRYPTO_LIB);
16836
0
      DEBUG_TRACE("%s", ebuf);
16837
0
      return 0;
16838
0
    }
16839
0
  }
16840
0
#endif /* NO_SSL_DL */
16841
16842
0
  if (mg_atomic_inc(&cryptolib_users) > 1) {
16843
0
    return 1;
16844
0
  }
16845
16846
#if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
16847
  /* Initialize locking callbacks, needed for thread safety.
16848
   * http://www.openssl.org/support/faq.html#PROG1
16849
   */
16850
  num_locks = CRYPTO_num_locks();
16851
  if (num_locks < 0) {
16852
    num_locks = 0;
16853
  }
16854
  size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
16855
16856
  /* allocate mutex array, if required */
16857
  if (num_locks == 0) {
16858
    /* No mutex array required */
16859
    ssl_mutexes = NULL;
16860
  } else {
16861
    /* Mutex array required - allocate it */
16862
    ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
16863
16864
    /* Check OOM */
16865
    if (ssl_mutexes == NULL) {
16866
      mg_snprintf(NULL,
16867
                  NULL, /* No truncation check for ebuf */
16868
                  ebuf,
16869
                  ebuf_len,
16870
                  "%s: cannot allocate mutexes: %s",
16871
                  __func__,
16872
                  ssl_error());
16873
      DEBUG_TRACE("%s", ebuf);
16874
      return 0;
16875
    }
16876
16877
    /* initialize mutex array */
16878
    for (i = 0; i < num_locks; i++) {
16879
      if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
16880
        mg_snprintf(NULL,
16881
                    NULL, /* No truncation check for ebuf */
16882
                    ebuf,
16883
                    ebuf_len,
16884
                    "%s: error initializing mutex %i of %i",
16885
                    __func__,
16886
                    i,
16887
                    num_locks);
16888
        DEBUG_TRACE("%s", ebuf);
16889
        mg_free(ssl_mutexes);
16890
        return 0;
16891
      }
16892
    }
16893
  }
16894
16895
  CRYPTO_set_locking_callback(&ssl_locking_callback);
16896
  CRYPTO_set_id_callback(&mg_current_thread_id);
16897
#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
16898
16899
0
#if !defined(NO_SSL_DL)
16900
0
  if (!ssllib_dll_handle) {
16901
0
    ssllib_dll_handle =
16902
0
        load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
16903
0
    if (!ssllib_dll_handle) {
16904
#if !defined(OPENSSL_API_1_1)
16905
      mg_free(ssl_mutexes);
16906
#endif
16907
0
      DEBUG_TRACE("%s", ebuf);
16908
0
      return 0;
16909
0
    }
16910
0
  }
16911
0
#endif /* NO_SSL_DL */
16912
16913
0
#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0))                     \
16914
0
    && !defined(NO_SSL_DL)
16915
  /* Initialize SSL library */
16916
0
  OPENSSL_init_ssl(0, NULL);
16917
0
  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
16918
0
                       | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
16919
0
                   NULL);
16920
#else
16921
  /* Initialize SSL library */
16922
  SSL_library_init();
16923
  SSL_load_error_strings();
16924
#endif
16925
16926
0
  return 1;
16927
0
}
16928
16929
16930
static int
16931
ssl_use_pem_file(struct mg_context *phys_ctx,
16932
                 struct mg_domain_context *dom_ctx,
16933
                 const char *pem,
16934
                 const char *chain)
16935
0
{
16936
0
  if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
16937
0
    mg_cry_ctx_internal(phys_ctx,
16938
0
                        "%s: cannot open certificate file %s: %s",
16939
0
                        __func__,
16940
0
                        pem,
16941
0
                        ssl_error());
16942
0
    return 0;
16943
0
  }
16944
16945
  /* could use SSL_CTX_set_default_passwd_cb_userdata */
16946
0
  if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
16947
0
    mg_cry_ctx_internal(phys_ctx,
16948
0
                        "%s: cannot open private key file %s: %s",
16949
0
                        __func__,
16950
0
                        pem,
16951
0
                        ssl_error());
16952
0
    return 0;
16953
0
  }
16954
16955
0
  if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
16956
0
    mg_cry_ctx_internal(phys_ctx,
16957
0
                        "%s: certificate and private key do not match: %s",
16958
0
                        __func__,
16959
0
                        pem);
16960
0
    return 0;
16961
0
  }
16962
16963
  /* In contrast to OpenSSL, wolfSSL does not support certificate
16964
   * chain files that contain private keys and certificates in
16965
   * SSL_CTX_use_certificate_chain_file.
16966
   * The CivetWeb-Server used pem-Files that contained both information.
16967
   * In order to make wolfSSL work, it is split in two files.
16968
   * One file that contains key and certificate used by the server and
16969
   * an optional chain file for the ssl stack.
16970
   */
16971
0
  if (chain) {
16972
0
    if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
16973
0
      mg_cry_ctx_internal(phys_ctx,
16974
0
                          "%s: cannot use certificate chain file %s: %s",
16975
0
                          __func__,
16976
0
                          chain,
16977
0
                          ssl_error());
16978
0
      return 0;
16979
0
    }
16980
0
  }
16981
0
  return 1;
16982
0
}
16983
16984
16985
#if defined(OPENSSL_API_1_1)
16986
static unsigned long
16987
ssl_get_protocol(int version_id)
16988
0
{
16989
0
  long unsigned ret = (long unsigned)SSL_OP_ALL;
16990
0
  if (version_id > 0)
16991
0
    ret |= SSL_OP_NO_SSLv2;
16992
0
  if (version_id > 1)
16993
0
    ret |= SSL_OP_NO_SSLv3;
16994
0
  if (version_id > 2)
16995
0
    ret |= SSL_OP_NO_TLSv1;
16996
0
  if (version_id > 3)
16997
0
    ret |= SSL_OP_NO_TLSv1_1;
16998
0
  if (version_id > 4)
16999
0
    ret |= SSL_OP_NO_TLSv1_2;
17000
0
#if defined(SSL_OP_NO_TLSv1_3)
17001
0
  if (version_id > 5)
17002
0
    ret |= SSL_OP_NO_TLSv1_3;
17003
0
#endif
17004
0
  return ret;
17005
0
}
17006
#else
17007
static long
17008
ssl_get_protocol(int version_id)
17009
{
17010
  unsigned long ret = (unsigned long)SSL_OP_ALL;
17011
  if (version_id > 0)
17012
    ret |= SSL_OP_NO_SSLv2;
17013
  if (version_id > 1)
17014
    ret |= SSL_OP_NO_SSLv3;
17015
  if (version_id > 2)
17016
    ret |= SSL_OP_NO_TLSv1;
17017
  if (version_id > 3)
17018
    ret |= SSL_OP_NO_TLSv1_1;
17019
  if (version_id > 4)
17020
    ret |= SSL_OP_NO_TLSv1_2;
17021
#if defined(SSL_OP_NO_TLSv1_3)
17022
  if (version_id > 5)
17023
    ret |= SSL_OP_NO_TLSv1_3;
17024
#endif
17025
  return (long)ret;
17026
}
17027
#endif /* OPENSSL_API_1_1 */
17028
17029
17030
/* SSL callback documentation:
17031
 * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
17032
 * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
17033
 * https://linux.die.net/man/3/ssl_set_info_callback */
17034
/* Note: There is no "const" for the first argument in the documentation
17035
 * examples, however some (maybe most, but not all) headers of OpenSSL
17036
 * versions / OpenSSL compatibility layers have it. Having a different
17037
 * definition will cause a warning in C and an error in C++. Use "const SSL
17038
 * *", while automatic conversion from "SSL *" works for all compilers,
17039
 * but not other way around */
17040
static void
17041
ssl_info_callback(const SSL *ssl, int what, int ret)
17042
0
{
17043
0
  (void)ret;
17044
17045
0
  if (what & SSL_CB_HANDSHAKE_START) {
17046
0
    SSL_get_app_data(ssl);
17047
0
  }
17048
0
  if (what & SSL_CB_HANDSHAKE_DONE) {
17049
    /* TODO: check for openSSL 1.1 */
17050
    //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
17051
    // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
17052
0
  }
17053
0
}
17054
17055
17056
static int
17057
ssl_servername_callback(SSL *ssl, int *ad, void *arg)
17058
0
{
17059
#if defined(GCC_DIAGNOSTIC)
17060
#pragma GCC diagnostic push
17061
#pragma GCC diagnostic ignored "-Wcast-align"
17062
#endif /* defined(GCC_DIAGNOSTIC) */
17063
17064
  /* We used an aligned pointer in SSL_set_app_data */
17065
0
  struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
17066
17067
#if defined(GCC_DIAGNOSTIC)
17068
#pragma GCC diagnostic pop
17069
#endif /* defined(GCC_DIAGNOSTIC) */
17070
17071
0
  const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
17072
17073
0
  (void)ad;
17074
0
  (void)arg;
17075
17076
0
  if ((conn == NULL) || (conn->phys_ctx == NULL)) {
17077
0
    DEBUG_ASSERT(0);
17078
0
    return SSL_TLSEXT_ERR_NOACK;
17079
0
  }
17080
0
  conn->dom_ctx = &(conn->phys_ctx->dd);
17081
17082
  /* Old clients (Win XP) will not support SNI. Then, there
17083
   * is no server name available in the request - we can
17084
   * only work with the default certificate.
17085
   * Multiple HTTPS hosts on one IP+port are only possible
17086
   * with a certificate containing all alternative names.
17087
   */
17088
0
  if ((servername == NULL) || (*servername == 0)) {
17089
0
    DEBUG_TRACE("%s", "SSL connection not supporting SNI");
17090
0
    mg_lock_context(conn->phys_ctx);
17091
0
    SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
17092
0
    mg_unlock_context(conn->phys_ctx);
17093
0
    return SSL_TLSEXT_ERR_NOACK;
17094
0
  }
17095
17096
0
  DEBUG_TRACE("TLS connection to host %s", servername);
17097
17098
0
  while (conn->dom_ctx) {
17099
0
    if (!mg_strcasecmp(servername,
17100
0
                       conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
17101
      /* Found matching domain */
17102
0
      DEBUG_TRACE("TLS domain %s found",
17103
0
                  conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
17104
0
      break;
17105
0
    }
17106
0
    mg_lock_context(conn->phys_ctx);
17107
0
    conn->dom_ctx = conn->dom_ctx->next;
17108
0
    mg_unlock_context(conn->phys_ctx);
17109
0
  }
17110
17111
0
  if (conn->dom_ctx == NULL) {
17112
    /* Default domain */
17113
0
    DEBUG_TRACE("TLS default domain %s used",
17114
0
                conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
17115
0
    conn->dom_ctx = &(conn->phys_ctx->dd);
17116
0
  }
17117
0
  mg_lock_context(conn->phys_ctx);
17118
0
  SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
17119
0
  mg_unlock_context(conn->phys_ctx);
17120
0
  return SSL_TLSEXT_ERR_OK;
17121
0
}
17122
17123
17124
#if defined(USE_ALPN)
17125
static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
17126
static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
17127
                                               alpn_proto_list + 3 + 8,
17128
                                               NULL};
17129
#if defined(USE_HTTP2)
17130
static const char *alpn_proto_order_http2[] = {alpn_proto_list,
17131
                                               alpn_proto_list + 3,
17132
                                               alpn_proto_list + 3 + 8,
17133
                                               NULL};
17134
#endif
17135
17136
static int
17137
alpn_select_cb(SSL *ssl,
17138
               const unsigned char **out,
17139
               unsigned char *outlen,
17140
               const unsigned char *in,
17141
               unsigned int inlen,
17142
               void *arg)
17143
{
17144
  struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
17145
  unsigned int i, j, enable_http2 = 0;
17146
  const char **alpn_proto_order = alpn_proto_order_http1;
17147
17148
  struct mg_workerTLS *tls =
17149
      (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
17150
17151
  (void)ssl;
17152
17153
  if (tls == NULL) {
17154
    /* Need to store protocol in Thread Local Storage */
17155
    /* If there is no Thread Local Storage, don't use ALPN */
17156
    return SSL_TLSEXT_ERR_NOACK;
17157
  }
17158
17159
#if defined(USE_HTTP2)
17160
  enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
17161
  if (enable_http2) {
17162
    alpn_proto_order = alpn_proto_order_http2;
17163
  }
17164
#endif
17165
17166
  for (j = 0; alpn_proto_order[j] != NULL; j++) {
17167
    /* check all accepted protocols in this order */
17168
    const char *alpn_proto = alpn_proto_order[j];
17169
    /* search input for matching protocol */
17170
    for (i = 0; i < inlen; i++) {
17171
      if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
17172
        *out = in + i + 1;
17173
        *outlen = in[i];
17174
        tls->alpn_proto = alpn_proto;
17175
        return SSL_TLSEXT_ERR_OK;
17176
      }
17177
    }
17178
  }
17179
17180
  /* Nothing found */
17181
  return SSL_TLSEXT_ERR_NOACK;
17182
}
17183
17184
17185
static int
17186
next_protos_advertised_cb(SSL *ssl,
17187
                          const unsigned char **data,
17188
                          unsigned int *len,
17189
                          void *arg)
17190
{
17191
  struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
17192
  *data = (const unsigned char *)alpn_proto_list;
17193
  *len = (unsigned int)strlen((const char *)data);
17194
17195
  (void)ssl;
17196
  (void)dom_ctx;
17197
17198
  return SSL_TLSEXT_ERR_OK;
17199
}
17200
17201
17202
static int
17203
init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
17204
{
17205
  unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
17206
  int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
17207
                                    (const unsigned char *)alpn_proto_list,
17208
                                    alpn_len);
17209
  if (ret != 0) {
17210
    mg_cry_ctx_internal(phys_ctx,
17211
                        "SSL_CTX_set_alpn_protos error: %s",
17212
                        ssl_error());
17213
  }
17214
17215
  SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
17216
                             alpn_select_cb,
17217
                             (void *)dom_ctx);
17218
17219
  SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
17220
                                        next_protos_advertised_cb,
17221
                                        (void *)dom_ctx);
17222
17223
  return ret;
17224
}
17225
#endif
17226
17227
17228
/* Setup SSL CTX as required by CivetWeb */
17229
static int
17230
init_ssl_ctx_impl(struct mg_context *phys_ctx,
17231
                  struct mg_domain_context *dom_ctx,
17232
                  const char *pem,
17233
                  const char *chain)
17234
0
{
17235
0
  int callback_ret;
17236
0
  int should_verify_peer;
17237
0
  int peer_certificate_optional;
17238
0
  const char *ca_path;
17239
0
  const char *ca_file;
17240
0
  int use_default_verify_paths;
17241
0
  int verify_depth;
17242
0
  struct timespec now_mt;
17243
0
  md5_byte_t ssl_context_id[16];
17244
0
  md5_state_t md5state;
17245
0
  int protocol_ver;
17246
0
  int ssl_cache_timeout;
17247
17248
0
#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0))                     \
17249
0
    && !defined(NO_SSL_DL)
17250
0
  if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
17251
0
    mg_cry_ctx_internal(phys_ctx,
17252
0
                        "SSL_CTX_new (server) error: %s",
17253
0
                        ssl_error());
17254
0
    return 0;
17255
0
  }
17256
#else
17257
  if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
17258
    mg_cry_ctx_internal(phys_ctx,
17259
                        "SSL_CTX_new (server) error: %s",
17260
                        ssl_error());
17261
    return 0;
17262
  }
17263
#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
17264
17265
0
#if defined(SSL_OP_NO_TLSv1_3)
17266
0
  SSL_CTX_clear_options(dom_ctx->ssl_ctx,
17267
0
                        SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
17268
0
                            | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
17269
0
                            | SSL_OP_NO_TLSv1_3);
17270
#else
17271
  SSL_CTX_clear_options(dom_ctx->ssl_ctx,
17272
                        SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
17273
                            | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
17274
#endif
17275
17276
0
  protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
17277
0
  SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
17278
0
  SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
17279
0
  SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
17280
0
  SSL_CTX_set_options(dom_ctx->ssl_ctx,
17281
0
                      SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
17282
0
  SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
17283
17284
0
#if defined(SSL_OP_NO_RENEGOTIATION)
17285
0
  SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
17286
0
#endif
17287
17288
0
#if !defined(NO_SSL_DL)
17289
0
  SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
17290
0
#endif /* NO_SSL_DL */
17291
17292
  /* In SSL documentation examples callback defined without const
17293
   * specifier 'void (*)(SSL *, int, int)'   See:
17294
   * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
17295
   * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
17296
   * But in the source code const SSL is used:
17297
   * 'void (*)(const SSL *, int, int)' See:
17298
   * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
17299
   * Problem about wrong documentation described, but not resolved:
17300
   * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
17301
   * Wrong const cast ignored on C or can be suppressed by compiler flags.
17302
   * But when compiled with modern C++ compiler, correct const should be
17303
   * provided
17304
   */
17305
0
  SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
17306
17307
0
  SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
17308
0
                                         ssl_servername_callback);
17309
17310
  /* If a callback has been specified, call it. */
17311
0
  callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
17312
0
                     ? 0
17313
0
                     : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
17314
0
                                                     phys_ctx->user_data));
17315
17316
  /* If callback returns 0, civetweb sets up the SSL certificate.
17317
   * If it returns 1, civetweb assumes the callback already did this.
17318
   * If it returns -1, initializing ssl fails. */
17319
0
  if (callback_ret < 0) {
17320
0
    mg_cry_ctx_internal(phys_ctx,
17321
0
                        "SSL callback returned error: %i",
17322
0
                        callback_ret);
17323
0
    return 0;
17324
0
  }
17325
0
  if (callback_ret > 0) {
17326
    /* Callback did everything. */
17327
0
    return 1;
17328
0
  }
17329
17330
  /* If a domain callback has been specified, call it. */
17331
0
  callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
17332
0
                     ? 0
17333
0
                     : (phys_ctx->callbacks.init_ssl_domain(
17334
0
                           dom_ctx->config[AUTHENTICATION_DOMAIN],
17335
0
                           dom_ctx->ssl_ctx,
17336
0
                           phys_ctx->user_data));
17337
17338
  /* If domain callback returns 0, civetweb sets up the SSL certificate.
17339
   * If it returns 1, civetweb assumes the callback already did this.
17340
   * If it returns -1, initializing ssl fails. */
17341
0
  if (callback_ret < 0) {
17342
0
    mg_cry_ctx_internal(phys_ctx,
17343
0
                        "Domain SSL callback returned error: %i",
17344
0
                        callback_ret);
17345
0
    return 0;
17346
0
  }
17347
0
  if (callback_ret > 0) {
17348
    /* Domain callback did everything. */
17349
0
    return 1;
17350
0
  }
17351
17352
  /* Use some combination of start time, domain and port as a SSL
17353
   * context ID. This should be unique on the current machine. */
17354
0
  md5_init(&md5state);
17355
0
  clock_gettime(CLOCK_MONOTONIC, &now_mt);
17356
0
  md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
17357
0
  md5_append(&md5state,
17358
0
             (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
17359
0
             strlen(phys_ctx->dd.config[LISTENING_PORTS]));
17360
0
  md5_append(&md5state,
17361
0
             (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
17362
0
             strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
17363
0
  md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
17364
0
  md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
17365
0
  md5_finish(&md5state, ssl_context_id);
17366
17367
0
  SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
17368
0
                                 (unsigned char *)ssl_context_id,
17369
0
                                 sizeof(ssl_context_id));
17370
17371
0
  if (pem != NULL) {
17372
0
    if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
17373
0
      return 0;
17374
0
    }
17375
0
  }
17376
17377
  /* Should we support client certificates? */
17378
  /* Default is "no". */
17379
0
  should_verify_peer = 0;
17380
0
  peer_certificate_optional = 0;
17381
0
  if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
17382
0
    if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
17383
      /* Yes, they are mandatory */
17384
0
      should_verify_peer = 1;
17385
0
    } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
17386
0
                             "optional")
17387
0
               == 0) {
17388
      /* Yes, they are optional */
17389
0
      should_verify_peer = 1;
17390
0
      peer_certificate_optional = 1;
17391
0
    }
17392
0
  }
17393
17394
0
  use_default_verify_paths =
17395
0
      (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
17396
0
      && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
17397
0
          == 0);
17398
17399
0
  if (should_verify_peer) {
17400
0
    ca_path = dom_ctx->config[SSL_CA_PATH];
17401
0
    ca_file = dom_ctx->config[SSL_CA_FILE];
17402
0
    if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
17403
0
        != 1) {
17404
0
      mg_cry_ctx_internal(phys_ctx,
17405
0
                          "SSL_CTX_load_verify_locations error: %s "
17406
0
                          "ssl_verify_peer requires setting "
17407
0
                          "either ssl_ca_path or ssl_ca_file. "
17408
0
                          "Is any of them present in the "
17409
0
                          ".conf file?",
17410
0
                          ssl_error());
17411
0
      return 0;
17412
0
    }
17413
17414
0
    if (peer_certificate_optional) {
17415
0
      SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
17416
0
    } else {
17417
0
      SSL_CTX_set_verify(dom_ctx->ssl_ctx,
17418
0
                         SSL_VERIFY_PEER
17419
0
                             | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
17420
0
                         NULL);
17421
0
    }
17422
17423
0
    if (use_default_verify_paths
17424
0
        && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
17425
0
      mg_cry_ctx_internal(phys_ctx,
17426
0
                          "SSL_CTX_set_default_verify_paths error: %s",
17427
0
                          ssl_error());
17428
0
      return 0;
17429
0
    }
17430
17431
0
    if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
17432
0
      verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
17433
0
      SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
17434
0
    }
17435
0
  }
17436
17437
0
  if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
17438
0
    if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
17439
0
                                dom_ctx->config[SSL_CIPHER_LIST])
17440
0
        != 1) {
17441
0
      mg_cry_ctx_internal(phys_ctx,
17442
0
                          "SSL_CTX_set_cipher_list error: %s",
17443
0
                          ssl_error());
17444
0
    }
17445
0
  }
17446
17447
  /* SSL session caching */
17448
0
  ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
17449
0
                           ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
17450
0
                           : 0);
17451
0
  if (ssl_cache_timeout > 0) {
17452
0
    SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
17453
    /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000);  ... use
17454
     * default */
17455
0
    SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
17456
0
  }
17457
17458
#if defined(USE_ALPN)
17459
  /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
17460
#if !defined(NO_SSL_DL)
17461
  if (!tls_feature_missing[TLS_ALPN])
17462
#endif
17463
  {
17464
    init_alpn(phys_ctx, dom_ctx);
17465
  }
17466
#endif
17467
17468
0
  return 1;
17469
0
}
17470
17471
17472
/* Check if SSL is required.
17473
 * If so, dynamically load SSL library
17474
 * and set up ctx->ssl_ctx pointer. */
17475
static int
17476
init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
17477
2
{
17478
2
  void *ssl_ctx = 0;
17479
2
  int callback_ret;
17480
2
  const char *pem;
17481
2
  const char *chain;
17482
2
  char ebuf[128];
17483
17484
2
  if (!phys_ctx) {
17485
0
    return 0;
17486
0
  }
17487
17488
2
  if (!dom_ctx) {
17489
2
    dom_ctx = &(phys_ctx->dd);
17490
2
  }
17491
17492
2
  if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
17493
    /* No SSL port is set. No need to setup SSL. */
17494
2
    return 1;
17495
2
  }
17496
17497
  /* Check for external SSL_CTX */
17498
0
  callback_ret =
17499
0
      (phys_ctx->callbacks.external_ssl_ctx == NULL)
17500
0
          ? 0
17501
0
          : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
17502
0
                                                  phys_ctx->user_data));
17503
17504
0
  if (callback_ret < 0) {
17505
    /* Callback exists and returns <0: Initializing failed. */
17506
0
    mg_cry_ctx_internal(phys_ctx,
17507
0
                        "external_ssl_ctx callback returned error: %i",
17508
0
                        callback_ret);
17509
0
    return 0;
17510
0
  } else if (callback_ret > 0) {
17511
    /* Callback exists and returns >0: Initializing complete,
17512
     * civetweb should not modify the SSL context. */
17513
0
    dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
17514
0
    if (!initialize_openssl(ebuf, sizeof(ebuf))) {
17515
0
      mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
17516
0
      return 0;
17517
0
    }
17518
0
    return 1;
17519
0
  }
17520
  /* If the callback does not exist or return 0, civetweb must initialize
17521
   * the SSL context. Handle "domain" callback next. */
17522
17523
  /* Check for external domain SSL_CTX callback. */
17524
0
  callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
17525
0
                     ? 0
17526
0
                     : (phys_ctx->callbacks.external_ssl_ctx_domain(
17527
0
                           dom_ctx->config[AUTHENTICATION_DOMAIN],
17528
0
                           &ssl_ctx,
17529
0
                           phys_ctx->user_data));
17530
17531
0
  if (callback_ret < 0) {
17532
    /* Callback < 0: Error. Abort init. */
17533
0
    mg_cry_ctx_internal(
17534
0
        phys_ctx,
17535
0
        "external_ssl_ctx_domain callback returned error: %i",
17536
0
        callback_ret);
17537
0
    return 0;
17538
0
  } else if (callback_ret > 0) {
17539
    /* Callback > 0: Consider init done. */
17540
0
    dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
17541
0
    if (!initialize_openssl(ebuf, sizeof(ebuf))) {
17542
0
      mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
17543
0
      return 0;
17544
0
    }
17545
0
    return 1;
17546
0
  }
17547
  /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
17548
   * 0, CivetWeb should continue initializing SSL */
17549
17550
  /* If PEM file is not specified and the init_ssl callbacks
17551
   * are not specified, setup will fail. */
17552
0
  if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
17553
0
      && (phys_ctx->callbacks.init_ssl == NULL)
17554
0
      && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
17555
    /* No certificate and no init_ssl callbacks:
17556
     * Essential data to set up TLS is missing.
17557
     */
17558
0
    mg_cry_ctx_internal(phys_ctx,
17559
0
                        "Initializing SSL failed: -%s is not set",
17560
0
                        config_options[SSL_CERTIFICATE].name);
17561
0
    return 0;
17562
0
  }
17563
17564
  /* If a certificate chain is configured, use it. */
17565
0
  chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
17566
0
  if (chain == NULL) {
17567
    /* Default: certificate chain in PEM file */
17568
0
    chain = pem;
17569
0
  }
17570
0
  if ((chain != NULL) && (*chain == 0)) {
17571
    /* If the chain is an empty string, don't use it. */
17572
0
    chain = NULL;
17573
0
  }
17574
17575
0
  if (!initialize_openssl(ebuf, sizeof(ebuf))) {
17576
0
    mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
17577
0
    return 0;
17578
0
  }
17579
17580
0
  return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
17581
0
}
17582
17583
17584
static void
17585
uninitialize_openssl(void)
17586
0
{
17587
0
#if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
17588
17589
0
  if (mg_atomic_dec(&cryptolib_users) == 0) {
17590
17591
    /* Shutdown according to
17592
     * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
17593
     * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
17594
     */
17595
0
    CONF_modules_unload(1);
17596
#else
17597
  int i;
17598
17599
  if (mg_atomic_dec(&cryptolib_users) == 0) {
17600
17601
    /* Shutdown according to
17602
     * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
17603
     * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
17604
     */
17605
    CRYPTO_set_locking_callback(NULL);
17606
    CRYPTO_set_id_callback(NULL);
17607
    ENGINE_cleanup();
17608
    CONF_modules_unload(1);
17609
    ERR_free_strings();
17610
    EVP_cleanup();
17611
    CRYPTO_cleanup_all_ex_data();
17612
    OPENSSL_REMOVE_THREAD_STATE();
17613
17614
    for (i = 0; i < CRYPTO_num_locks(); i++) {
17615
      pthread_mutex_destroy(&ssl_mutexes[i]);
17616
    }
17617
    mg_free(ssl_mutexes);
17618
    ssl_mutexes = NULL;
17619
#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
17620
0
  }
17621
0
}
17622
#endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
17623
17624
17625
#if !defined(NO_FILESYSTEMS)
17626
static int
17627
set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
17628
2
{
17629
2
  if (phys_ctx) {
17630
2
    struct mg_file file = STRUCT_FILE_INITIALIZER;
17631
2
    const char *path;
17632
2
    struct mg_connection fc;
17633
2
    if (!dom_ctx) {
17634
2
      dom_ctx = &(phys_ctx->dd);
17635
2
    }
17636
2
    path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
17637
2
    if ((path != NULL)
17638
2
        && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
17639
0
      mg_cry_ctx_internal(phys_ctx,
17640
0
                          "Cannot open %s: %s",
17641
0
                          path,
17642
0
                          strerror(ERRNO));
17643
0
      return 0;
17644
0
    }
17645
2
    return 1;
17646
2
  }
17647
0
  return 0;
17648
2
}
17649
#endif /* NO_FILESYSTEMS */
17650
17651
17652
static int
17653
set_acl_option(struct mg_context *phys_ctx)
17654
2
{
17655
2
  union usa sa;
17656
2
  memset(&sa, 0, sizeof(sa));
17657
#if defined(USE_IPV6)
17658
  sa.sin6.sin6_family = AF_INET6;
17659
#else
17660
2
  sa.sin.sin_family = AF_INET;
17661
2
#endif
17662
2
  return check_acl(phys_ctx, &sa) != -1;
17663
2
}
17664
17665
17666
static void
17667
reset_per_request_attributes(struct mg_connection *conn)
17668
34
{
17669
34
  if (!conn) {
17670
0
    return;
17671
0
  }
17672
17673
34
  conn->num_bytes_sent = conn->consumed_content = 0;
17674
17675
34
  conn->path_info = NULL;
17676
34
  conn->status_code = -1;
17677
34
  conn->content_len = -1;
17678
34
  conn->is_chunked = 0;
17679
34
  conn->must_close = 0;
17680
34
  conn->request_len = 0;
17681
34
  conn->request_state = 0;
17682
34
  conn->throttle = 0;
17683
34
  conn->accept_gzip = 0;
17684
17685
34
  conn->response_info.content_length = conn->request_info.content_length = -1;
17686
34
  conn->response_info.http_version = conn->request_info.http_version = NULL;
17687
34
  conn->response_info.num_headers = conn->request_info.num_headers = 0;
17688
34
  conn->response_info.status_text = NULL;
17689
34
  conn->response_info.status_code = 0;
17690
17691
34
  conn->request_info.remote_user = NULL;
17692
34
  conn->request_info.request_method = NULL;
17693
34
  conn->request_info.request_uri = NULL;
17694
17695
  /* Free cleaned local URI (if any) */
17696
34
  if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
17697
0
    mg_free((void *)conn->request_info.local_uri);
17698
0
    conn->request_info.local_uri = NULL;
17699
0
  }
17700
34
  conn->request_info.local_uri = NULL;
17701
17702
#if defined(USE_SERVER_STATS)
17703
  conn->processing_time = 0;
17704
#endif
17705
34
}
17706
17707
17708
static int
17709
set_tcp_nodelay(const struct socket *so, int nodelay_on)
17710
0
{
17711
0
  if ((so->lsa.sa.sa_family == AF_INET)
17712
0
      || (so->lsa.sa.sa_family == AF_INET6)) {
17713
    /* Only for TCP sockets */
17714
0
    if (setsockopt(so->sock,
17715
0
                   IPPROTO_TCP,
17716
0
                   TCP_NODELAY,
17717
0
                   (SOCK_OPT_TYPE)&nodelay_on,
17718
0
                   sizeof(nodelay_on))
17719
0
        != 0) {
17720
      /* Error */
17721
0
      return 1;
17722
0
    }
17723
0
  }
17724
  /* OK */
17725
0
  return 0;
17726
0
}
17727
17728
17729
#if !defined(__ZEPHYR__)
17730
static void
17731
close_socket_gracefully(struct mg_connection *conn)
17732
34
{
17733
#if defined(_WIN32)
17734
  char buf[MG_BUF_LEN];
17735
  int n;
17736
#endif
17737
34
  struct linger linger;
17738
34
  int error_code = 0;
17739
34
  int linger_timeout = -2;
17740
34
  socklen_t opt_len = sizeof(error_code);
17741
17742
34
  if (!conn) {
17743
0
    return;
17744
0
  }
17745
17746
  /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
17747
   * "Note that enabling a nonzero timeout on a nonblocking socket
17748
   * is not recommended.", so set it to blocking now */
17749
34
  set_blocking_mode(conn->client.sock);
17750
17751
  /* Send FIN to the client */
17752
34
  shutdown(conn->client.sock, SHUTDOWN_WR);
17753
17754
#if defined(_WIN32)
17755
  /* Read and discard pending incoming data. If we do not do that and
17756
   * close
17757
   * the socket, the data in the send buffer may be discarded. This
17758
   * behaviour is seen on Windows, when client keeps sending data
17759
   * when server decides to close the connection; then when client
17760
   * does recv() it gets no data back. */
17761
  do {
17762
    n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
17763
  } while (n > 0);
17764
#endif
17765
17766
34
  if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
17767
0
    linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
17768
0
  }
17769
17770
  /* Set linger option according to configuration */
17771
34
  if (linger_timeout >= 0) {
17772
    /* Set linger option to avoid socket hanging out after close. This
17773
     * prevent ephemeral port exhaust problem under high QPS. */
17774
0
    linger.l_onoff = 1;
17775
17776
#if defined(_MSC_VER)
17777
#pragma warning(push)
17778
#pragma warning(disable : 4244)
17779
#endif
17780
#if defined(GCC_DIAGNOSTIC)
17781
#pragma GCC diagnostic push
17782
#pragma GCC diagnostic ignored "-Wconversion"
17783
#endif
17784
    /* Data type of linger structure elements may differ,
17785
     * so we don't know what cast we need here.
17786
     * Disable type conversion warnings. */
17787
17788
0
    linger.l_linger = (linger_timeout + 999) / 1000;
17789
17790
#if defined(GCC_DIAGNOSTIC)
17791
#pragma GCC diagnostic pop
17792
#endif
17793
#if defined(_MSC_VER)
17794
#pragma warning(pop)
17795
#endif
17796
17797
34
  } else {
17798
34
    linger.l_onoff = 0;
17799
34
    linger.l_linger = 0;
17800
34
  }
17801
17802
34
  if (linger_timeout < -1) {
17803
    /* Default: don't configure any linger */
17804
34
  } else if (getsockopt(conn->client.sock,
17805
0
                        SOL_SOCKET,
17806
0
                        SO_ERROR,
17807
#if defined(_WIN32) /* WinSock uses different data type here */
17808
                        (char *)&error_code,
17809
#else
17810
0
                        &error_code,
17811
0
#endif
17812
0
                        &opt_len)
17813
0
             != 0) {
17814
    /* Cannot determine if socket is already closed. This should
17815
     * not occur and never did in a test. Log an error message
17816
     * and continue. */
17817
0
    mg_cry_internal(conn,
17818
0
                    "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
17819
0
                    __func__,
17820
0
                    strerror(ERRNO));
17821
#if defined(_WIN32)
17822
  } else if (error_code == WSAECONNRESET) {
17823
#else
17824
0
  } else if (error_code == ECONNRESET) {
17825
0
#endif
17826
    /* Socket already closed by client/peer, close socket without linger
17827
     */
17828
0
  } else {
17829
17830
    /* Set linger timeout */
17831
0
    if (setsockopt(conn->client.sock,
17832
0
                   SOL_SOCKET,
17833
0
                   SO_LINGER,
17834
0
                   (char *)&linger,
17835
0
                   sizeof(linger))
17836
0
        != 0) {
17837
0
      mg_cry_internal(
17838
0
          conn,
17839
0
          "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
17840
0
          __func__,
17841
0
          linger.l_onoff,
17842
0
          linger.l_linger,
17843
0
          strerror(ERRNO));
17844
0
    }
17845
0
  }
17846
17847
  /* Now we know that our FIN is ACK-ed, safe to close */
17848
34
  closesocket(conn->client.sock);
17849
34
  conn->client.sock = INVALID_SOCKET;
17850
34
}
17851
#endif
17852
17853
17854
static void
17855
close_connection(struct mg_connection *conn)
17856
34
{
17857
#if defined(USE_SERVER_STATS)
17858
  conn->conn_state = 6; /* to close */
17859
#endif
17860
17861
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
17862
  if (conn->lua_websocket_state) {
17863
    lua_websocket_close(conn, conn->lua_websocket_state);
17864
    conn->lua_websocket_state = NULL;
17865
  }
17866
#endif
17867
17868
34
  mg_lock_connection(conn);
17869
17870
  /* Set close flag, so keep-alive loops will stop */
17871
34
  conn->must_close = 1;
17872
17873
  /* call the connection_close callback if assigned */
17874
34
  if (conn->phys_ctx->callbacks.connection_close != NULL) {
17875
0
    if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17876
0
      conn->phys_ctx->callbacks.connection_close(conn);
17877
0
    }
17878
0
  }
17879
17880
  /* Reset user data, after close callback is called.
17881
   * Do not reuse it. If the user needs a destructor,
17882
   * it must be done in the connection_close callback. */
17883
34
  mg_set_user_connection_data(conn, NULL);
17884
17885
#if defined(USE_SERVER_STATS)
17886
  conn->conn_state = 7; /* closing */
17887
#endif
17888
17889
#if defined(USE_MBEDTLS)
17890
  if (conn->ssl != NULL) {
17891
    mbed_ssl_close(conn->ssl);
17892
    conn->ssl = NULL;
17893
  }
17894
#elif !defined(NO_SSL)
17895
34
  if (conn->ssl != NULL) {
17896
    /* Run SSL_shutdown twice to ensure completely close SSL connection
17897
     */
17898
0
    SSL_shutdown(conn->ssl);
17899
0
    SSL_free(conn->ssl);
17900
0
    OPENSSL_REMOVE_THREAD_STATE();
17901
0
    conn->ssl = NULL;
17902
0
  }
17903
34
#endif
17904
34
  if (conn->client.sock != INVALID_SOCKET) {
17905
#if defined(__ZEPHYR__)
17906
    closesocket(conn->client.sock);
17907
#else
17908
34
    close_socket_gracefully(conn);
17909
34
#endif
17910
34
    conn->client.sock = INVALID_SOCKET;
17911
34
  }
17912
17913
  /* call the connection_closed callback if assigned */
17914
34
  if (conn->phys_ctx->callbacks.connection_closed != NULL) {
17915
0
    if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17916
0
      conn->phys_ctx->callbacks.connection_closed(conn);
17917
0
    }
17918
0
  }
17919
17920
34
  mg_unlock_connection(conn);
17921
17922
#if defined(USE_SERVER_STATS)
17923
  conn->conn_state = 8; /* closed */
17924
#endif
17925
34
}
17926
17927
17928
CIVETWEB_API void
17929
mg_close_connection(struct mg_connection *conn)
17930
34
{
17931
34
  if ((conn == NULL) || (conn->phys_ctx == NULL)) {
17932
0
    return;
17933
0
  }
17934
17935
#if defined(USE_WEBSOCKET)
17936
  if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17937
    if (conn->in_websocket_handling) {
17938
      /* Set close flag, so the server thread can exit. */
17939
      conn->must_close = 1;
17940
      return;
17941
    }
17942
  }
17943
  if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
17944
17945
    unsigned int i;
17946
17947
    /* client context: loops must end */
17948
    STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
17949
    conn->must_close = 1;
17950
17951
    /* We need to get the client thread out of the select/recv call
17952
     * here. */
17953
    /* Since we use a sleep quantum of some seconds to check for recv
17954
     * timeouts, we will just wait a few seconds in mg_join_thread. */
17955
17956
    /* join worker thread */
17957
    for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
17958
      mg_join_thread(conn->phys_ctx->worker_threadids[i]);
17959
    }
17960
  }
17961
#endif /* defined(USE_WEBSOCKET) */
17962
17963
34
  close_connection(conn);
17964
17965
34
#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
17966
34
  if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
17967
34
       || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
17968
34
      && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
17969
0
    SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
17970
0
  }
17971
34
#endif
17972
17973
#if defined(USE_WEBSOCKET)
17974
  if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
17975
    mg_free(conn->phys_ctx->worker_threadids);
17976
    (void)pthread_mutex_destroy(&conn->mutex);
17977
    mg_free(conn);
17978
  } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
17979
    (void)pthread_mutex_destroy(&conn->mutex);
17980
    mg_free(conn);
17981
  }
17982
#else
17983
34
  if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
17984
34
    (void)pthread_mutex_destroy(&conn->mutex);
17985
34
    mg_free(conn);
17986
34
  }
17987
34
#endif /* defined(USE_WEBSOCKET) */
17988
34
}
17989
17990
17991
static struct mg_connection *
17992
mg_connect_client_impl(const struct mg_client_options *client_options,
17993
                       int use_ssl,
17994
                       struct mg_init_data *init,
17995
                       struct mg_error_data *error)
17996
34
{
17997
34
  struct mg_connection *conn = NULL;
17998
34
  SOCKET sock;
17999
34
  union usa sa;
18000
34
  struct sockaddr *psa;
18001
34
  socklen_t len;
18002
18003
34
  unsigned max_req_size =
18004
34
      (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
18005
18006
  /* Size of structures, aligned to 8 bytes */
18007
34
  size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
18008
34
  size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
18009
34
  size_t alloc_size = conn_size + ctx_size + max_req_size;
18010
18011
34
  (void)init; /* TODO: Implement required options */
18012
18013
34
  conn = (struct mg_connection *)mg_calloc(1, alloc_size);
18014
18015
34
  if (error != NULL) {
18016
34
    error->code = MG_ERROR_DATA_CODE_OK;
18017
34
    error->code_sub = 0;
18018
34
    if (error->text_buffer_size > 0) {
18019
34
      error->text[0] = 0;
18020
34
    }
18021
34
  }
18022
18023
34
  if (conn == NULL) {
18024
0
    if (error != NULL) {
18025
0
      error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
18026
0
      error->code_sub = (unsigned)alloc_size;
18027
0
      mg_snprintf(NULL,
18028
0
                  NULL, /* No truncation check for ebuf */
18029
0
                  error->text,
18030
0
                  error->text_buffer_size,
18031
0
                  "calloc(): %s",
18032
0
                  strerror(ERRNO));
18033
0
    }
18034
0
    return NULL;
18035
0
  }
18036
18037
#if defined(GCC_DIAGNOSTIC)
18038
#pragma GCC diagnostic push
18039
#pragma GCC diagnostic ignored "-Wcast-align"
18040
#endif /* defined(GCC_DIAGNOSTIC) */
18041
  /* conn_size is aligned to 8 bytes */
18042
18043
34
  conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
18044
18045
#if defined(GCC_DIAGNOSTIC)
18046
#pragma GCC diagnostic pop
18047
#endif /* defined(GCC_DIAGNOSTIC) */
18048
18049
34
  conn->buf = (((char *)conn) + conn_size + ctx_size);
18050
34
  conn->buf_size = (int)max_req_size;
18051
34
  conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
18052
34
  conn->dom_ctx = &(conn->phys_ctx->dd);
18053
18054
34
  if (!connect_socket(conn->phys_ctx,
18055
34
                      client_options->host,
18056
34
                      client_options->port,
18057
34
                      use_ssl,
18058
34
                      error,
18059
34
                      &sock,
18060
34
                      &sa)) {
18061
    /* "error" will be set by connect_socket. */
18062
    /* free all memory and return NULL; */
18063
0
    mg_free(conn);
18064
0
    return NULL;
18065
0
  }
18066
18067
34
#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
18068
34
#if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0))                     \
18069
34
    && !defined(NO_SSL_DL)
18070
18071
34
  if (use_ssl
18072
34
      && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
18073
0
             == NULL) {
18074
0
    if (error != NULL) {
18075
0
      error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
18076
0
      mg_snprintf(NULL,
18077
0
                  NULL, /* No truncation check for ebuf */
18078
0
                  error->text,
18079
0
                  error->text_buffer_size,
18080
0
                  "SSL_CTX_new error: %s",
18081
0
                  ssl_error());
18082
0
    }
18083
18084
0
    closesocket(sock);
18085
0
    mg_free(conn);
18086
0
    return NULL;
18087
0
  }
18088
18089
#else
18090
18091
  if (use_ssl
18092
      && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
18093
             == NULL) {
18094
    if (error != NULL) {
18095
      error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
18096
      mg_snprintf(NULL,
18097
                  NULL, /* No truncation check for ebuf */
18098
                  error->text,
18099
                  error->text_buffer_size,
18100
                  "SSL_CTX_new error: %s",
18101
                  ssl_error());
18102
    }
18103
18104
    closesocket(sock);
18105
    mg_free(conn);
18106
    return NULL;
18107
  }
18108
18109
#endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
18110
34
#endif /* NO_SSL */
18111
18112
#if defined(USE_IPV6)
18113
  len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
18114
                                     : sizeof(conn->client.rsa.sin6);
18115
  psa = (sa.sa.sa_family == AF_INET)
18116
            ? (struct sockaddr *)&(conn->client.rsa.sin)
18117
            : (struct sockaddr *)&(conn->client.rsa.sin6);
18118
#else
18119
34
  len = sizeof(conn->client.rsa.sin);
18120
34
  psa = (struct sockaddr *)&(conn->client.rsa.sin);
18121
34
#endif
18122
18123
34
  conn->client.sock = sock;
18124
34
  conn->client.lsa = sa;
18125
18126
34
  if (getsockname(sock, psa, &len) != 0) {
18127
0
    mg_cry_internal(conn,
18128
0
                    "%s: getsockname() failed: %s",
18129
0
                    __func__,
18130
0
                    strerror(ERRNO));
18131
0
  }
18132
18133
34
  conn->client.is_ssl = use_ssl ? 1 : 0;
18134
34
  if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
18135
0
    if (error != NULL) {
18136
0
      error->code = MG_ERROR_DATA_CODE_OS_ERROR;
18137
0
      error->code_sub = (unsigned)ERRNO;
18138
0
      mg_snprintf(NULL,
18139
0
                  NULL, /* No truncation check for ebuf */
18140
0
                  error->text,
18141
0
                  error->text_buffer_size,
18142
0
                  "Can not create mutex");
18143
0
    }
18144
0
#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
18145
0
    SSL_CTX_free(conn->dom_ctx->ssl_ctx);
18146
0
#endif
18147
0
    closesocket(sock);
18148
0
    mg_free(conn);
18149
0
    return NULL;
18150
0
  }
18151
18152
34
#if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
18153
34
  if (use_ssl) {
18154
    /* TODO: Check ssl_verify_peer and ssl_ca_path here.
18155
     * SSL_CTX_set_verify call is needed to switch off server
18156
     * certificate checking, which is off by default in OpenSSL and
18157
     * on in yaSSL. */
18158
    /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
18159
     * SSL_VERIFY_PEER, verify_ssl_server); */
18160
18161
0
    if (client_options->client_cert) {
18162
0
      if (!ssl_use_pem_file(conn->phys_ctx,
18163
0
                            conn->dom_ctx,
18164
0
                            client_options->client_cert,
18165
0
                            NULL)) {
18166
0
        if (error != NULL) {
18167
0
          error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
18168
0
          mg_snprintf(NULL,
18169
0
                      NULL, /* No truncation check for ebuf */
18170
0
                      error->text,
18171
0
                      error->text_buffer_size,
18172
0
                      "Can not use SSL client certificate");
18173
0
        }
18174
18175
0
        SSL_CTX_free(conn->dom_ctx->ssl_ctx);
18176
0
        closesocket(sock);
18177
0
        mg_free(conn);
18178
0
        return NULL;
18179
0
      }
18180
0
    }
18181
18182
0
    if (client_options->server_cert) {
18183
0
      if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
18184
0
                                        client_options->server_cert,
18185
0
                                        NULL)
18186
0
          != 1) {
18187
0
        if (error != NULL) {
18188
0
          error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
18189
0
          mg_snprintf(NULL,
18190
0
                      NULL, /* No truncation check for ebuf */
18191
0
                      error->text,
18192
0
                      error->text_buffer_size,
18193
0
                      "SSL_CTX_load_verify_locations error: %s",
18194
0
                      ssl_error());
18195
0
        }
18196
0
        SSL_CTX_free(conn->dom_ctx->ssl_ctx);
18197
0
        closesocket(sock);
18198
0
        mg_free(conn);
18199
0
        return NULL;
18200
0
      }
18201
0
      SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
18202
0
    } else {
18203
0
      SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
18204
0
    }
18205
18206
0
    if (!sslize(conn, SSL_connect, client_options)) {
18207
0
      if (error != NULL) {
18208
0
        error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
18209
0
        mg_snprintf(NULL,
18210
0
                    NULL, /* No truncation check for ebuf */
18211
0
                    error->text,
18212
0
                    error->text_buffer_size,
18213
0
                    "SSL connection error");
18214
0
      }
18215
0
      SSL_CTX_free(conn->dom_ctx->ssl_ctx);
18216
0
      closesocket(sock);
18217
0
      mg_free(conn);
18218
0
      return NULL;
18219
0
    }
18220
0
  }
18221
34
#endif
18222
18223
34
  return conn;
18224
34
}
18225
18226
18227
CIVETWEB_API struct mg_connection *
18228
mg_connect_client_secure(const struct mg_client_options *client_options,
18229
                         char *error_buffer,
18230
                         size_t error_buffer_size)
18231
0
{
18232
0
  struct mg_init_data init;
18233
0
  struct mg_error_data error;
18234
18235
0
  memset(&init, 0, sizeof(init));
18236
0
  memset(&error, 0, sizeof(error));
18237
0
  error.text_buffer_size = error_buffer_size;
18238
0
  error.text = error_buffer;
18239
0
  return mg_connect_client_impl(client_options, 1, &init, &error);
18240
0
}
18241
18242
18243
CIVETWEB_API struct mg_connection *
18244
mg_connect_client(const char *host,
18245
                  int port,
18246
                  int use_ssl,
18247
                  char *error_buffer,
18248
                  size_t error_buffer_size)
18249
34
{
18250
34
  struct mg_client_options opts;
18251
34
  struct mg_init_data init;
18252
34
  struct mg_error_data error;
18253
18254
34
  memset(&init, 0, sizeof(init));
18255
18256
34
  memset(&error, 0, sizeof(error));
18257
34
  error.text_buffer_size = error_buffer_size;
18258
34
  error.text = error_buffer;
18259
18260
34
  memset(&opts, 0, sizeof(opts));
18261
34
  opts.host = host;
18262
34
  opts.port = port;
18263
34
  if (use_ssl) {
18264
0
    opts.host_name = host;
18265
0
  }
18266
18267
34
  return mg_connect_client_impl(&opts, use_ssl, &init, &error);
18268
34
}
18269
18270
18271
#if defined(MG_EXPERIMENTAL_INTERFACES)
18272
CIVETWEB_API struct mg_connection *
18273
mg_connect_client2(const char *host,
18274
                   const char *protocol,
18275
                   int port,
18276
                   const char *path,
18277
                   struct mg_init_data *init,
18278
                   struct mg_error_data *error)
18279
{
18280
  (void)path;
18281
18282
  int is_ssl, is_ws;
18283
  /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
18284
18285
  if (error != NULL) {
18286
    error->code = MG_ERROR_DATA_CODE_OK;
18287
    error->code_sub = 0;
18288
    if (error->text_buffer_size > 0) {
18289
      *error->text = 0;
18290
    }
18291
  }
18292
18293
  if ((host == NULL) || (protocol == NULL)) {
18294
    if (error != NULL) {
18295
      error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
18296
      mg_snprintf(NULL,
18297
                  NULL, /* No truncation check for error buffers */
18298
                  error->text,
18299
                  error->text_buffer_size,
18300
                  "%s",
18301
                  "Invalid parameters");
18302
    }
18303
    return NULL;
18304
  }
18305
18306
  /* check all known protocols */
18307
  if (!mg_strcasecmp(protocol, "http")) {
18308
    is_ssl = 0;
18309
    is_ws = 0;
18310
  } else if (!mg_strcasecmp(protocol, "https")) {
18311
    is_ssl = 1;
18312
    is_ws = 0;
18313
#if defined(USE_WEBSOCKET)
18314
  } else if (!mg_strcasecmp(protocol, "ws")) {
18315
    is_ssl = 0;
18316
    is_ws = 1;
18317
  } else if (!mg_strcasecmp(protocol, "wss")) {
18318
    is_ssl = 1;
18319
    is_ws = 1;
18320
#endif
18321
  } else {
18322
    if (error != NULL) {
18323
      error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
18324
      mg_snprintf(NULL,
18325
                  NULL, /* No truncation check for error buffers */
18326
                  error->text,
18327
                  error->text_buffer_size,
18328
                  "Protocol %s not supported",
18329
                  protocol);
18330
    }
18331
    return NULL;
18332
  }
18333
18334
  /* TODO: The current implementation here just calls the old
18335
   * implementations, without using any new options. This is just a first
18336
   * step to test the new interfaces. */
18337
#if defined(USE_WEBSOCKET)
18338
  if (is_ws) {
18339
    /* TODO: implement all options */
18340
    return mg_connect_websocket_client(
18341
        host,
18342
        port,
18343
        is_ssl,
18344
        ((error != NULL) ? error->text : NULL),
18345
        ((error != NULL) ? error->text_buffer_size : 0),
18346
        (path ? path : ""),
18347
        NULL /* TODO: origin */,
18348
        experimental_websocket_client_data_wrapper,
18349
        experimental_websocket_client_close_wrapper,
18350
        (void *)init->callbacks);
18351
  }
18352
#else
18353
  (void)is_ws;
18354
#endif
18355
18356
  /* TODO: all additional options */
18357
  struct mg_client_options opts;
18358
18359
  memset(&opts, 0, sizeof(opts));
18360
  opts.host = host;
18361
  opts.port = port;
18362
18363
  return mg_connect_client_impl(&opts, is_ssl, init, error);
18364
}
18365
#endif
18366
18367
18368
static const struct {
18369
  const char *proto;
18370
  size_t proto_len;
18371
  unsigned default_port;
18372
} abs_uri_protocols[] = {{"http://", 7, 80},
18373
                         {"https://", 8, 443},
18374
                         {"ws://", 5, 80},
18375
                         {"wss://", 6, 443},
18376
                         {NULL, 0, 0}};
18377
18378
18379
/* Check if the uri is valid.
18380
 * return 0 for invalid uri,
18381
 * return 1 for *,
18382
 * return 2 for relative uri,
18383
 * return 3 for absolute uri without port,
18384
 * return 4 for absolute uri with port */
18385
static int
18386
get_uri_type(const char *uri)
18387
0
{
18388
0
  int i;
18389
0
  const char *hostend, *portbegin;
18390
0
  char *portend;
18391
0
  unsigned long port;
18392
18393
  /* According to the HTTP standard
18394
   * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
18395
   * URI can be an asterisk (*) or should start with slash (relative uri),
18396
   * or it should start with the protocol (absolute uri). */
18397
0
  if ((uri[0] == '*') && (uri[1] == '\0')) {
18398
    /* asterisk */
18399
0
    return 1;
18400
0
  }
18401
18402
  /* Valid URIs according to RFC 3986
18403
   * (https://www.ietf.org/rfc/rfc3986.txt)
18404
   * must only contain reserved characters :/?#[]@!$&'()*+,;=
18405
   * and unreserved characters A-Z a-z 0-9 and -._~
18406
   * and % encoded symbols.
18407
   */
18408
0
  for (i = 0; uri[i] != 0; i++) {
18409
0
    if (uri[i] < 33) {
18410
      /* control characters and spaces are invalid */
18411
0
      return 0;
18412
0
    }
18413
    /* Allow everything else here (See #894) */
18414
0
  }
18415
18416
  /* A relative uri starts with a / character */
18417
0
  if (uri[0] == '/') {
18418
    /* relative uri */
18419
0
    return 2;
18420
0
  }
18421
18422
  /* It could be an absolute uri: */
18423
  /* This function only checks if the uri is valid, not if it is
18424
   * addressing the current server. So civetweb can also be used
18425
   * as a proxy server. */
18426
0
  for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
18427
0
    if (mg_strncasecmp(uri,
18428
0
                       abs_uri_protocols[i].proto,
18429
0
                       abs_uri_protocols[i].proto_len)
18430
0
        == 0) {
18431
18432
0
      hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
18433
0
      if (!hostend) {
18434
0
        return 0;
18435
0
      }
18436
0
      portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
18437
0
      if (!portbegin) {
18438
0
        return 3;
18439
0
      }
18440
18441
0
      port = strtoul(portbegin + 1, &portend, 10);
18442
0
      if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
18443
0
        return 0;
18444
0
      }
18445
18446
0
      return 4;
18447
0
    }
18448
0
  }
18449
18450
0
  return 0;
18451
0
}
18452
18453
18454
/* Return NULL or the relative uri at the current server */
18455
static const char *
18456
get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
18457
0
{
18458
0
  const char *server_domain;
18459
0
  size_t server_domain_len;
18460
0
  size_t request_domain_len = 0;
18461
0
  unsigned long port = 0;
18462
0
  int i, auth_domain_check_enabled;
18463
0
  const char *hostbegin = NULL;
18464
0
  const char *hostend = NULL;
18465
0
  const char *portbegin;
18466
0
  char *portend;
18467
18468
0
  auth_domain_check_enabled =
18469
0
      !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
18470
18471
  /* DNS is case insensitive, so use case insensitive string compare here
18472
   */
18473
0
  for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
18474
0
    if (mg_strncasecmp(uri,
18475
0
                       abs_uri_protocols[i].proto,
18476
0
                       abs_uri_protocols[i].proto_len)
18477
0
        == 0) {
18478
18479
0
      hostbegin = uri + abs_uri_protocols[i].proto_len;
18480
0
      hostend = strchr(hostbegin, '/');
18481
0
      if (!hostend) {
18482
0
        return 0;
18483
0
      }
18484
0
      portbegin = strchr(hostbegin, ':');
18485
0
      if ((!portbegin) || (portbegin > hostend)) {
18486
0
        port = abs_uri_protocols[i].default_port;
18487
0
        request_domain_len = (size_t)(hostend - hostbegin);
18488
0
      } else {
18489
0
        port = strtoul(portbegin + 1, &portend, 10);
18490
0
        if ((portend != hostend) || (port <= 0)
18491
0
            || !is_valid_port(port)) {
18492
0
          return 0;
18493
0
        }
18494
0
        request_domain_len = (size_t)(portbegin - hostbegin);
18495
0
      }
18496
      /* protocol found, port set */
18497
0
      break;
18498
0
    }
18499
0
  }
18500
18501
0
  if (!port) {
18502
    /* port remains 0 if the protocol is not found */
18503
0
    return 0;
18504
0
  }
18505
18506
  /* Check if the request is directed to a different server. */
18507
  /* First check if the port is the same. */
18508
0
  if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
18509
    /* Request is directed to a different port */
18510
0
    return 0;
18511
0
  }
18512
18513
  /* Finally check if the server corresponds to the authentication
18514
   * domain of the server (the server domain).
18515
   * Allow full matches (like http://mydomain.com/path/file.ext), and
18516
   * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
18517
   * but do not allow substrings (like
18518
   * http://notmydomain.com/path/file.ext
18519
   * or http://mydomain.com.fake/path/file.ext).
18520
   */
18521
0
  if (auth_domain_check_enabled) {
18522
0
    server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
18523
0
    server_domain_len = strlen(server_domain);
18524
0
    if ((server_domain_len == 0) || (hostbegin == NULL)) {
18525
0
      return 0;
18526
0
    }
18527
0
    if ((request_domain_len == server_domain_len)
18528
0
        && (!memcmp(server_domain, hostbegin, server_domain_len))) {
18529
      /* Request is directed to this server - full name match. */
18530
0
    } else {
18531
0
      if (request_domain_len < (server_domain_len + 2)) {
18532
        /* Request is directed to another server: The server name
18533
         * is longer than the request name.
18534
         * Drop this case here to avoid overflows in the
18535
         * following checks. */
18536
0
        return 0;
18537
0
      }
18538
0
      if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
18539
        /* Request is directed to another server: It could be a
18540
         * substring
18541
         * like notmyserver.com */
18542
0
        return 0;
18543
0
      }
18544
0
      if (0
18545
0
          != memcmp(server_domain,
18546
0
                    hostbegin + request_domain_len - server_domain_len,
18547
0
                    server_domain_len)) {
18548
        /* Request is directed to another server:
18549
         * The server name is different. */
18550
0
        return 0;
18551
0
      }
18552
0
    }
18553
0
  }
18554
18555
0
  return hostend;
18556
0
}
18557
18558
18559
static int
18560
get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
18561
34
{
18562
34
  if (ebuf_len > 0) {
18563
34
    ebuf[0] = '\0';
18564
34
  }
18565
34
  *err = 0;
18566
18567
34
  reset_per_request_attributes(conn);
18568
18569
34
  if (!conn) {
18570
0
    mg_snprintf(conn,
18571
0
                NULL, /* No truncation check for ebuf */
18572
0
                ebuf,
18573
0
                ebuf_len,
18574
0
                "%s",
18575
0
                "Internal error");
18576
0
    *err = 500;
18577
0
    return 0;
18578
0
  }
18579
18580
  /* Set the time the request was received. This value should be used for
18581
   * timeouts. */
18582
34
  clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
18583
18584
34
  conn->request_len =
18585
34
      read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
18586
34
  DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
18587
34
  if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
18588
0
    mg_snprintf(conn,
18589
0
                NULL, /* No truncation check for ebuf */
18590
0
                ebuf,
18591
0
                ebuf_len,
18592
0
                "%s",
18593
0
                "Invalid message size");
18594
0
    *err = 500;
18595
0
    return 0;
18596
0
  }
18597
18598
34
  if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
18599
0
    mg_snprintf(conn,
18600
0
                NULL, /* No truncation check for ebuf */
18601
0
                ebuf,
18602
0
                ebuf_len,
18603
0
                "%s",
18604
0
                "Message too large");
18605
0
    *err = 413;
18606
0
    return 0;
18607
0
  }
18608
18609
34
  if (conn->request_len <= 0) {
18610
20
    if (conn->data_len > 0) {
18611
20
      mg_snprintf(conn,
18612
20
                  NULL, /* No truncation check for ebuf */
18613
20
                  ebuf,
18614
20
                  ebuf_len,
18615
20
                  "%s",
18616
20
                  "Malformed message");
18617
20
      *err = 400;
18618
20
    } else {
18619
      /* Server did not recv anything -> just close the connection */
18620
0
      conn->must_close = 1;
18621
0
      mg_snprintf(conn,
18622
0
                  NULL, /* No truncation check for ebuf */
18623
0
                  ebuf,
18624
0
                  ebuf_len,
18625
0
                  "%s",
18626
0
                  "No data received");
18627
0
      *err = 0;
18628
0
    }
18629
20
    return 0;
18630
20
  }
18631
14
  return 1;
18632
34
}
18633
18634
18635
static int
18636
get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
18637
0
{
18638
0
  const char *cl;
18639
18640
0
  conn->connection_type =
18641
0
      CONNECTION_TYPE_REQUEST; /* request (valid of not) */
18642
18643
0
  if (!get_message(conn, ebuf, ebuf_len, err)) {
18644
0
    return 0;
18645
0
  }
18646
18647
0
  if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
18648
0
      <= 0) {
18649
0
    mg_snprintf(conn,
18650
0
                NULL, /* No truncation check for ebuf */
18651
0
                ebuf,
18652
0
                ebuf_len,
18653
0
                "%s",
18654
0
                "Bad request");
18655
0
    *err = 400;
18656
0
    return 0;
18657
0
  }
18658
18659
  /* Message is a valid request */
18660
18661
0
  if (!switch_domain_context(conn)) {
18662
0
    mg_snprintf(conn,
18663
0
                NULL, /* No truncation check for ebuf */
18664
0
                ebuf,
18665
0
                ebuf_len,
18666
0
                "%s",
18667
0
                "Bad request: Host mismatch");
18668
0
    *err = 400;
18669
0
    return 0;
18670
0
  }
18671
18672
#if USE_ZLIB
18673
  if (((cl = get_header(conn->request_info.http_headers,
18674
                        conn->request_info.num_headers,
18675
                        "Accept-Encoding"))
18676
       != NULL)
18677
      && strstr(cl, "gzip")) {
18678
    conn->accept_gzip = 1;
18679
  }
18680
#endif
18681
0
  if (((cl = get_header(conn->request_info.http_headers,
18682
0
                        conn->request_info.num_headers,
18683
0
                        "Transfer-Encoding"))
18684
0
       != NULL)
18685
0
      && mg_strcasecmp(cl, "identity")) {
18686
0
    if (mg_strcasecmp(cl, "chunked")) {
18687
0
      mg_snprintf(conn,
18688
0
                  NULL, /* No truncation check for ebuf */
18689
0
                  ebuf,
18690
0
                  ebuf_len,
18691
0
                  "%s",
18692
0
                  "Bad request");
18693
0
      *err = 400;
18694
0
      return 0;
18695
0
    }
18696
0
    conn->is_chunked = 1;
18697
0
    conn->content_len = 0; /* not yet read */
18698
0
  } else if ((cl = get_header(conn->request_info.http_headers,
18699
0
                              conn->request_info.num_headers,
18700
0
                              "Content-Length"))
18701
0
             != NULL) {
18702
    /* Request has content length set */
18703
0
    char *endptr = NULL;
18704
0
    conn->content_len = strtoll(cl, &endptr, 10);
18705
0
    if ((endptr == cl) || (conn->content_len < 0)) {
18706
0
      mg_snprintf(conn,
18707
0
                  NULL, /* No truncation check for ebuf */
18708
0
                  ebuf,
18709
0
                  ebuf_len,
18710
0
                  "%s",
18711
0
                  "Bad request");
18712
0
      *err = 411;
18713
0
      return 0;
18714
0
    }
18715
    /* Publish the content length back to the request info. */
18716
0
    conn->request_info.content_length = conn->content_len;
18717
0
  } else {
18718
    /* There is no exception, see RFC7230. */
18719
0
    conn->content_len = 0;
18720
0
  }
18721
18722
0
  return 1;
18723
0
}
18724
18725
18726
/* conn is assumed to be valid in this internal function */
18727
static int
18728
get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
18729
34
{
18730
34
  const char *cl;
18731
18732
34
  conn->connection_type =
18733
34
      CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
18734
18735
34
  if (!get_message(conn, ebuf, ebuf_len, err)) {
18736
20
    return 0;
18737
20
  }
18738
18739
14
  if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
18740
14
      <= 0) {
18741
13
    mg_snprintf(conn,
18742
13
                NULL, /* No truncation check for ebuf */
18743
13
                ebuf,
18744
13
                ebuf_len,
18745
13
                "%s",
18746
13
                "Bad response");
18747
13
    *err = 400;
18748
13
    return 0;
18749
13
  }
18750
18751
  /* Message is a valid response */
18752
18753
1
  if (((cl = get_header(conn->response_info.http_headers,
18754
1
                        conn->response_info.num_headers,
18755
1
                        "Transfer-Encoding"))
18756
1
       != NULL)
18757
1
      && mg_strcasecmp(cl, "identity")) {
18758
0
    if (mg_strcasecmp(cl, "chunked")) {
18759
0
      mg_snprintf(conn,
18760
0
                  NULL, /* No truncation check for ebuf */
18761
0
                  ebuf,
18762
0
                  ebuf_len,
18763
0
                  "%s",
18764
0
                  "Bad request");
18765
0
      *err = 400;
18766
0
      return 0;
18767
0
    }
18768
0
    conn->is_chunked = 1;
18769
0
    conn->content_len = 0; /* not yet read */
18770
1
  } else if ((cl = get_header(conn->response_info.http_headers,
18771
1
                              conn->response_info.num_headers,
18772
1
                              "Content-Length"))
18773
1
             != NULL) {
18774
0
    char *endptr = NULL;
18775
0
    conn->content_len = strtoll(cl, &endptr, 10);
18776
0
    if ((endptr == cl) || (conn->content_len < 0)) {
18777
0
      mg_snprintf(conn,
18778
0
                  NULL, /* No truncation check for ebuf */
18779
0
                  ebuf,
18780
0
                  ebuf_len,
18781
0
                  "%s",
18782
0
                  "Bad request");
18783
0
      *err = 411;
18784
0
      return 0;
18785
0
    }
18786
    /* Publish the content length back to the response info. */
18787
0
    conn->response_info.content_length = conn->content_len;
18788
18789
    /* TODO: check if it is still used in response_info */
18790
0
    conn->request_info.content_length = conn->content_len;
18791
18792
    /* TODO: we should also consider HEAD method */
18793
0
    if (conn->response_info.status_code == 304) {
18794
0
      conn->content_len = 0;
18795
0
    }
18796
1
  } else {
18797
    /* TODO: we should also consider HEAD method */
18798
1
    if (((conn->response_info.status_code >= 100)
18799
1
         && (conn->response_info.status_code <= 199))
18800
1
        || (conn->response_info.status_code == 204)
18801
1
        || (conn->response_info.status_code == 304)) {
18802
0
      conn->content_len = 0;
18803
1
    } else {
18804
1
      conn->content_len = -1; /* unknown content length */
18805
1
    }
18806
1
  }
18807
18808
1
  return 1;
18809
1
}
18810
18811
18812
CIVETWEB_API int
18813
mg_get_response(struct mg_connection *conn,
18814
                char *ebuf,
18815
                size_t ebuf_len,
18816
                int timeout)
18817
34
{
18818
34
  int err, ret;
18819
34
  char txt[32]; /* will not overflow */
18820
34
  char *save_timeout;
18821
34
  char *new_timeout;
18822
18823
34
  if (ebuf_len > 0) {
18824
34
    ebuf[0] = '\0';
18825
34
  }
18826
18827
34
  if (!conn) {
18828
0
    mg_snprintf(conn,
18829
0
                NULL, /* No truncation check for ebuf */
18830
0
                ebuf,
18831
0
                ebuf_len,
18832
0
                "%s",
18833
0
                "Parameter error");
18834
0
    return -1;
18835
0
  }
18836
18837
  /* Reset the previous responses */
18838
34
  conn->data_len = 0;
18839
18840
  /* Implementation of API function for HTTP clients */
18841
34
  save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
18842
18843
34
  if (timeout >= 0) {
18844
34
    mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
18845
34
    new_timeout = txt;
18846
34
  } else {
18847
0
    new_timeout = NULL;
18848
0
  }
18849
18850
34
  conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
18851
34
  ret = get_response(conn, ebuf, ebuf_len, &err);
18852
34
  conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
18853
18854
  /* TODO: here, the URI is the http response code */
18855
34
  conn->request_info.local_uri_raw = conn->request_info.request_uri;
18856
34
  conn->request_info.local_uri = conn->request_info.local_uri_raw;
18857
18858
  /* TODO (mid): Define proper return values - maybe return length?
18859
   * For the first test use <0 for error and >0 for OK */
18860
34
  return (ret == 0) ? -1 : +1;
18861
34
}
18862
18863
18864
CIVETWEB_API struct mg_connection *
18865
mg_download(const char *host,
18866
            int port,
18867
            int use_ssl,
18868
            char *ebuf,
18869
            size_t ebuf_len,
18870
            const char *fmt,
18871
            ...)
18872
0
{
18873
0
  struct mg_connection *conn;
18874
0
  va_list ap;
18875
0
  int i;
18876
0
  int reqerr;
18877
18878
0
  if (ebuf_len > 0) {
18879
0
    ebuf[0] = '\0';
18880
0
  }
18881
18882
0
  va_start(ap, fmt);
18883
18884
  /* open a connection */
18885
0
  conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
18886
18887
0
  if (conn != NULL) {
18888
0
    i = mg_vprintf(conn, fmt, ap);
18889
0
    if (i <= 0) {
18890
0
      mg_snprintf(conn,
18891
0
                  NULL, /* No truncation check for ebuf */
18892
0
                  ebuf,
18893
0
                  ebuf_len,
18894
0
                  "%s",
18895
0
                  "Error sending request");
18896
0
    } else {
18897
      /* make sure the buffer is clear */
18898
0
      conn->data_len = 0;
18899
0
      get_response(conn, ebuf, ebuf_len, &reqerr);
18900
18901
      /* TODO: here, the URI is the http response code */
18902
0
      conn->request_info.local_uri = conn->request_info.request_uri;
18903
0
    }
18904
0
  }
18905
18906
  /* if an error occurred, close the connection */
18907
0
  if ((ebuf[0] != '\0') && (conn != NULL)) {
18908
0
    mg_close_connection(conn);
18909
0
    conn = NULL;
18910
0
  }
18911
18912
0
  va_end(ap);
18913
0
  return conn;
18914
0
}
18915
18916
18917
struct websocket_client_thread_data {
18918
  struct mg_connection *conn;
18919
  mg_websocket_data_handler data_handler;
18920
  mg_websocket_close_handler close_handler;
18921
  void *callback_data;
18922
};
18923
18924
18925
#if defined(USE_WEBSOCKET)
18926
#if defined(_WIN32)
18927
static unsigned __stdcall websocket_client_thread(void *data)
18928
#else
18929
static void *
18930
websocket_client_thread(void *data)
18931
#endif
18932
{
18933
  struct websocket_client_thread_data *cdata =
18934
      (struct websocket_client_thread_data *)data;
18935
18936
  void *user_thread_ptr = NULL;
18937
18938
#if !defined(_WIN32) && !defined(__ZEPHYR__)
18939
  struct sigaction sa;
18940
18941
  /* Ignore SIGPIPE */
18942
  memset(&sa, 0, sizeof(sa));
18943
  sa.sa_handler = SIG_IGN;
18944
  sigaction(SIGPIPE, &sa, NULL);
18945
#endif
18946
18947
  mg_set_thread_name("ws-clnt");
18948
18949
  if (cdata->conn->phys_ctx) {
18950
    if (cdata->conn->phys_ctx->callbacks.init_thread) {
18951
      /* 3 indicates a websocket client thread */
18952
      /* TODO: check if conn->phys_ctx can be set */
18953
      user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
18954
          cdata->conn->phys_ctx, 3);
18955
    }
18956
  }
18957
18958
  read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
18959
18960
  DEBUG_TRACE("%s", "Websocket client thread exited\n");
18961
18962
  if (cdata->close_handler != NULL) {
18963
    cdata->close_handler(cdata->conn, cdata->callback_data);
18964
  }
18965
18966
  /* The websocket_client context has only this thread. If it runs out,
18967
  set the stop_flag to 2 (= "stopped"). */
18968
  STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
18969
18970
  if (cdata->conn->phys_ctx->callbacks.exit_thread) {
18971
    cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
18972
                                                 3,
18973
                                                 user_thread_ptr);
18974
  }
18975
18976
  mg_free((void *)cdata);
18977
18978
#if defined(_WIN32)
18979
  return 0;
18980
#else
18981
  return NULL;
18982
#endif
18983
}
18984
#endif
18985
18986
18987
static struct mg_connection *
18988
mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
18989
                                 int use_ssl,
18990
                                 char *error_buffer,
18991
                                 size_t error_buffer_size,
18992
                                 const char *path,
18993
                                 const char *origin,
18994
                                 const char *extensions,
18995
                                 mg_websocket_data_handler data_func,
18996
                                 mg_websocket_close_handler close_func,
18997
                                 void *user_data)
18998
0
{
18999
0
  struct mg_connection *conn = NULL;
19000
19001
#if defined(USE_WEBSOCKET)
19002
  struct websocket_client_thread_data *thread_data;
19003
  static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
19004
19005
  const char *host = client_options->host;
19006
  int i;
19007
19008
  struct mg_init_data init;
19009
  struct mg_error_data error;
19010
19011
  memset(&init, 0, sizeof(init));
19012
  memset(&error, 0, sizeof(error));
19013
  error.text_buffer_size = error_buffer_size;
19014
  error.text = error_buffer;
19015
19016
#if defined(__clang__)
19017
#pragma clang diagnostic push
19018
#pragma clang diagnostic ignored "-Wformat-nonliteral"
19019
#endif
19020
19021
  /* Establish the client connection and request upgrade */
19022
  conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
19023
19024
  /* Connection object will be null if something goes wrong */
19025
  if (conn == NULL) {
19026
    /* error_buffer should be already filled ... */
19027
    if (!error_buffer[0]) {
19028
      /* ... if not add an error message */
19029
      mg_snprintf(conn,
19030
                  NULL, /* No truncation check for ebuf */
19031
                  error_buffer,
19032
                  error_buffer_size,
19033
                  "Unexpected error");
19034
    }
19035
    return NULL;
19036
  }
19037
19038
  if (origin != NULL) {
19039
    if (extensions != NULL) {
19040
      i = mg_printf(conn,
19041
                    "GET %s HTTP/1.1\r\n"
19042
                    "Host: %s\r\n"
19043
                    "Upgrade: websocket\r\n"
19044
                    "Connection: Upgrade\r\n"
19045
                    "Sec-WebSocket-Key: %s\r\n"
19046
                    "Sec-WebSocket-Version: 13\r\n"
19047
                    "Sec-WebSocket-Extensions: %s\r\n"
19048
                    "Origin: %s\r\n"
19049
                    "\r\n",
19050
                    path,
19051
                    host,
19052
                    magic,
19053
                    extensions,
19054
                    origin);
19055
    } else {
19056
      i = mg_printf(conn,
19057
                    "GET %s HTTP/1.1\r\n"
19058
                    "Host: %s\r\n"
19059
                    "Upgrade: websocket\r\n"
19060
                    "Connection: Upgrade\r\n"
19061
                    "Sec-WebSocket-Key: %s\r\n"
19062
                    "Sec-WebSocket-Version: 13\r\n"
19063
                    "Origin: %s\r\n"
19064
                    "\r\n",
19065
                    path,
19066
                    host,
19067
                    magic,
19068
                    origin);
19069
    }
19070
  } else {
19071
19072
    if (extensions != NULL) {
19073
      i = mg_printf(conn,
19074
                    "GET %s HTTP/1.1\r\n"
19075
                    "Host: %s\r\n"
19076
                    "Upgrade: websocket\r\n"
19077
                    "Connection: Upgrade\r\n"
19078
                    "Sec-WebSocket-Key: %s\r\n"
19079
                    "Sec-WebSocket-Version: 13\r\n"
19080
                    "Sec-WebSocket-Extensions: %s\r\n"
19081
                    "\r\n",
19082
                    path,
19083
                    host,
19084
                    magic,
19085
                    extensions);
19086
    } else {
19087
      i = mg_printf(conn,
19088
                    "GET %s HTTP/1.1\r\n"
19089
                    "Host: %s\r\n"
19090
                    "Upgrade: websocket\r\n"
19091
                    "Connection: Upgrade\r\n"
19092
                    "Sec-WebSocket-Key: %s\r\n"
19093
                    "Sec-WebSocket-Version: 13\r\n"
19094
                    "\r\n",
19095
                    path,
19096
                    host,
19097
                    magic);
19098
    }
19099
  }
19100
  if (i <= 0) {
19101
    mg_snprintf(conn,
19102
                NULL, /* No truncation check for ebuf */
19103
                error_buffer,
19104
                error_buffer_size,
19105
                "%s",
19106
                "Error sending request");
19107
    mg_close_connection(conn);
19108
    return NULL;
19109
  }
19110
19111
  conn->data_len = 0;
19112
  if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
19113
    mg_close_connection(conn);
19114
    return NULL;
19115
  }
19116
  conn->request_info.local_uri_raw = conn->request_info.request_uri;
19117
  conn->request_info.local_uri = conn->request_info.local_uri_raw;
19118
19119
#if defined(__clang__)
19120
#pragma clang diagnostic pop
19121
#endif
19122
19123
  if (conn->response_info.status_code != 101) {
19124
    /* We sent an "upgrade" request. For a correct websocket
19125
     * protocol handshake, we expect a "101 Continue" response.
19126
     * Otherwise it is a protocol violation. Maybe the HTTP
19127
     * Server does not know websockets. */
19128
    if (!*error_buffer) {
19129
      /* set an error, if not yet set */
19130
      mg_snprintf(conn,
19131
                  NULL, /* No truncation check for ebuf */
19132
                  error_buffer,
19133
                  error_buffer_size,
19134
                  "Unexpected server reply");
19135
    }
19136
19137
    DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
19138
    mg_close_connection(conn);
19139
    return NULL;
19140
  }
19141
19142
  thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
19143
      1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
19144
  if (!thread_data) {
19145
    DEBUG_TRACE("%s\r\n", "Out of memory");
19146
    mg_close_connection(conn);
19147
    return NULL;
19148
  }
19149
19150
  thread_data->conn = conn;
19151
  thread_data->data_handler = data_func;
19152
  thread_data->close_handler = close_func;
19153
  thread_data->callback_data = user_data;
19154
19155
  conn->phys_ctx->worker_threadids =
19156
      (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
19157
  if (!conn->phys_ctx->worker_threadids) {
19158
    DEBUG_TRACE("%s\r\n", "Out of memory");
19159
    mg_free(thread_data);
19160
    mg_close_connection(conn);
19161
    return NULL;
19162
  }
19163
19164
  /* Now upgrade to ws/wss client context */
19165
  conn->phys_ctx->user_data = user_data;
19166
  conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
19167
  conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
19168
19169
  /* Start a thread to read the websocket client connection
19170
   * This thread will automatically stop when mg_disconnect is
19171
   * called on the client connection */
19172
  if (mg_start_thread_with_id(websocket_client_thread,
19173
                              thread_data,
19174
                              conn->phys_ctx->worker_threadids)
19175
      != 0) {
19176
    conn->phys_ctx->cfg_worker_threads = 0;
19177
    mg_free(thread_data);
19178
    mg_close_connection(conn);
19179
    conn = NULL;
19180
    DEBUG_TRACE("%s",
19181
                "Websocket client connect thread could not be started\r\n");
19182
  }
19183
19184
#else
19185
  /* Appease "unused parameter" warnings */
19186
0
  (void)client_options;
19187
0
  (void)use_ssl;
19188
0
  (void)error_buffer;
19189
0
  (void)error_buffer_size;
19190
0
  (void)path;
19191
0
  (void)origin;
19192
0
  (void)extensions;
19193
0
  (void)user_data;
19194
0
  (void)data_func;
19195
0
  (void)close_func;
19196
0
#endif
19197
19198
0
  return conn;
19199
0
}
19200
19201
19202
CIVETWEB_API struct mg_connection *
19203
mg_connect_websocket_client(const char *host,
19204
                            int port,
19205
                            int use_ssl,
19206
                            char *error_buffer,
19207
                            size_t error_buffer_size,
19208
                            const char *path,
19209
                            const char *origin,
19210
                            mg_websocket_data_handler data_func,
19211
                            mg_websocket_close_handler close_func,
19212
                            void *user_data)
19213
0
{
19214
0
  struct mg_client_options client_options;
19215
0
  memset(&client_options, 0, sizeof(client_options));
19216
0
  client_options.host = host;
19217
0
  client_options.port = port;
19218
19219
0
  return mg_connect_websocket_client_impl(&client_options,
19220
0
                                          use_ssl,
19221
0
                                          error_buffer,
19222
0
                                          error_buffer_size,
19223
0
                                          path,
19224
0
                                          origin,
19225
0
                                          NULL,
19226
0
                                          data_func,
19227
0
                                          close_func,
19228
0
                                          user_data);
19229
0
}
19230
19231
19232
CIVETWEB_API struct mg_connection *
19233
mg_connect_websocket_client_secure(
19234
    const struct mg_client_options *client_options,
19235
    char *error_buffer,
19236
    size_t error_buffer_size,
19237
    const char *path,
19238
    const char *origin,
19239
    mg_websocket_data_handler data_func,
19240
    mg_websocket_close_handler close_func,
19241
    void *user_data)
19242
0
{
19243
0
  if (!client_options) {
19244
0
    return NULL;
19245
0
  }
19246
0
  return mg_connect_websocket_client_impl(client_options,
19247
0
                                          1,
19248
0
                                          error_buffer,
19249
0
                                          error_buffer_size,
19250
0
                                          path,
19251
0
                                          origin,
19252
0
                                          NULL,
19253
0
                                          data_func,
19254
0
                                          close_func,
19255
0
                                          user_data);
19256
0
}
19257
19258
19259
CIVETWEB_API struct mg_connection *
19260
mg_connect_websocket_client_extensions(const char *host,
19261
                                       int port,
19262
                                       int use_ssl,
19263
                                       char *error_buffer,
19264
                                       size_t error_buffer_size,
19265
                                       const char *path,
19266
                                       const char *origin,
19267
                                       const char *extensions,
19268
                                       mg_websocket_data_handler data_func,
19269
                                       mg_websocket_close_handler close_func,
19270
                                       void *user_data)
19271
0
{
19272
0
  struct mg_client_options client_options;
19273
0
  memset(&client_options, 0, sizeof(client_options));
19274
0
  client_options.host = host;
19275
0
  client_options.port = port;
19276
19277
0
  return mg_connect_websocket_client_impl(&client_options,
19278
0
                                          use_ssl,
19279
0
                                          error_buffer,
19280
0
                                          error_buffer_size,
19281
0
                                          path,
19282
0
                                          origin,
19283
0
                                          extensions,
19284
0
                                          data_func,
19285
0
                                          close_func,
19286
0
                                          user_data);
19287
0
}
19288
19289
19290
CIVETWEB_API struct mg_connection *
19291
mg_connect_websocket_client_secure_extensions(
19292
    const struct mg_client_options *client_options,
19293
    char *error_buffer,
19294
    size_t error_buffer_size,
19295
    const char *path,
19296
    const char *origin,
19297
    const char *extensions,
19298
    mg_websocket_data_handler data_func,
19299
    mg_websocket_close_handler close_func,
19300
    void *user_data)
19301
0
{
19302
0
  if (!client_options) {
19303
0
    return NULL;
19304
0
  }
19305
0
  return mg_connect_websocket_client_impl(client_options,
19306
0
                                          1,
19307
0
                                          error_buffer,
19308
0
                                          error_buffer_size,
19309
0
                                          path,
19310
0
                                          origin,
19311
0
                                          extensions,
19312
0
                                          data_func,
19313
0
                                          close_func,
19314
0
                                          user_data);
19315
0
}
19316
19317
19318
/* Prepare connection data structure */
19319
static void
19320
init_connection(struct mg_connection *conn)
19321
0
{
19322
  /* Is keep alive allowed by the server */
19323
0
  int keep_alive_enabled =
19324
0
      !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
19325
19326
0
  if (!keep_alive_enabled) {
19327
0
    conn->must_close = 1;
19328
0
  }
19329
19330
  /* Important: on new connection, reset the receiving buffer. Credit
19331
   * goes to crule42. */
19332
0
  conn->data_len = 0;
19333
0
  conn->handled_requests = 0;
19334
0
  conn->connection_type = CONNECTION_TYPE_INVALID;
19335
0
  conn->request_info.acceptedWebSocketSubprotocol = NULL;
19336
0
  mg_set_user_connection_data(conn, NULL);
19337
19338
#if defined(USE_SERVER_STATS)
19339
  conn->conn_state = 2; /* init */
19340
#endif
19341
19342
  /* call the init_connection callback if assigned */
19343
0
  if (conn->phys_ctx->callbacks.init_connection != NULL) {
19344
0
    if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
19345
0
      void *conn_data = NULL;
19346
0
      conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
19347
0
      mg_set_user_connection_data(conn, conn_data);
19348
0
    }
19349
0
  }
19350
0
}
19351
19352
19353
/* Process a connection - may handle multiple requests
19354
 * using the same connection.
19355
 * Must be called with a valid connection (conn  and
19356
 * conn->phys_ctx must be valid).
19357
 */
19358
static void
19359
process_new_connection(struct mg_connection *conn)
19360
0
{
19361
0
  struct mg_request_info *ri = &conn->request_info;
19362
0
  int keep_alive, discard_len;
19363
0
  char ebuf[100];
19364
0
  const char *hostend;
19365
0
  int reqerr, uri_type;
19366
19367
#if defined(USE_SERVER_STATS)
19368
  ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
19369
  mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
19370
  mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
19371
#endif
19372
19373
0
  DEBUG_TRACE("Start processing connection from %s",
19374
0
              conn->request_info.remote_addr);
19375
19376
  /* Loop over multiple requests sent using the same connection
19377
   * (while "keep alive"). */
19378
0
  do {
19379
0
    DEBUG_TRACE("calling get_request (%i times for this connection)",
19380
0
                conn->handled_requests + 1);
19381
19382
#if defined(USE_SERVER_STATS)
19383
    conn->conn_state = 3; /* ready */
19384
#endif
19385
19386
0
    if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
19387
      /* The request sent by the client could not be understood by
19388
       * the server, or it was incomplete or a timeout. Send an
19389
       * error message and close the connection. */
19390
0
      if (reqerr > 0) {
19391
0
        DEBUG_ASSERT(ebuf[0] != '\0');
19392
0
        mg_send_http_error(conn, reqerr, "%s", ebuf);
19393
0
      }
19394
19395
0
    } else if (strcmp(ri->http_version, "1.0")
19396
0
               && strcmp(ri->http_version, "1.1")) {
19397
      /* HTTP/2 is not allowed here */
19398
0
      mg_snprintf(conn,
19399
0
                  NULL, /* No truncation check for ebuf */
19400
0
                  ebuf,
19401
0
                  sizeof(ebuf),
19402
0
                  "Bad HTTP version: [%s]",
19403
0
                  ri->http_version);
19404
0
      mg_send_http_error(conn, 505, "%s", ebuf);
19405
0
    }
19406
19407
0
    if (ebuf[0] == '\0') {
19408
0
      uri_type = get_uri_type(conn->request_info.request_uri);
19409
0
      switch (uri_type) {
19410
0
      case 1:
19411
        /* Asterisk */
19412
0
        conn->request_info.local_uri_raw = 0;
19413
        /* TODO: Deal with '*'. */
19414
0
        break;
19415
0
      case 2:
19416
        /* relative uri */
19417
0
        conn->request_info.local_uri_raw =
19418
0
            conn->request_info.request_uri;
19419
0
        break;
19420
0
      case 3:
19421
0
      case 4:
19422
        /* absolute uri (with/without port) */
19423
0
        hostend = get_rel_url_at_current_server(
19424
0
            conn->request_info.request_uri, conn);
19425
0
        if (hostend) {
19426
0
          conn->request_info.local_uri_raw = hostend;
19427
0
        } else {
19428
0
          conn->request_info.local_uri_raw = NULL;
19429
0
        }
19430
0
        break;
19431
0
      default:
19432
0
        mg_snprintf(conn,
19433
0
                    NULL, /* No truncation check for ebuf */
19434
0
                    ebuf,
19435
0
                    sizeof(ebuf),
19436
0
                    "Invalid URI");
19437
0
        mg_send_http_error(conn, 400, "%s", ebuf);
19438
0
        conn->request_info.local_uri_raw = NULL;
19439
0
        break;
19440
0
      }
19441
0
      conn->request_info.local_uri =
19442
0
          (char *)conn->request_info.local_uri_raw;
19443
0
    }
19444
19445
0
    if (ebuf[0] != '\0') {
19446
0
      conn->protocol_type = -1;
19447
19448
0
    } else {
19449
      /* HTTP/1 allows protocol upgrade */
19450
0
      conn->protocol_type = should_switch_to_protocol(conn);
19451
19452
0
      if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
19453
        /* This will occur, if a HTTP/1.1 request should be upgraded
19454
         * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
19455
         * Since most (all?) major browsers only support HTTP/2 using
19456
         * ALPN, this is hard to test and very low priority.
19457
         * Deactivate it (at least for now).
19458
         */
19459
0
        conn->protocol_type = PROTOCOL_TYPE_HTTP1;
19460
0
      }
19461
0
    }
19462
19463
0
    DEBUG_TRACE("http: %s, error: %s",
19464
0
                (ri->http_version ? ri->http_version : "none"),
19465
0
                (ebuf[0] ? ebuf : "none"));
19466
19467
0
    if (ebuf[0] == '\0') {
19468
0
      if (conn->request_info.local_uri) {
19469
19470
        /* handle request to local server */
19471
0
        handle_request_stat_log(conn);
19472
19473
0
      } else {
19474
        /* TODO: handle non-local request (PROXY) */
19475
0
        conn->must_close = 1;
19476
0
      }
19477
0
    } else {
19478
0
      conn->must_close = 1;
19479
0
    }
19480
19481
    /* Response complete. Free header buffer */
19482
0
    free_buffered_response_header_list(conn);
19483
19484
0
    if (ri->remote_user != NULL) {
19485
0
      mg_free((void *)ri->remote_user);
19486
      /* Important! When having connections with and without auth
19487
       * would cause double free and then crash */
19488
0
      ri->remote_user = NULL;
19489
0
    }
19490
19491
    /* NOTE(lsm): order is important here. should_keep_alive() call
19492
     * is using parsed request, which will be invalid after
19493
     * memmove's below.
19494
     * Therefore, memorize should_keep_alive() result now for later
19495
     * use in loop exit condition. */
19496
    /* Enable it only if this request is completely discardable. */
19497
0
    keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
19498
0
                 && should_keep_alive(conn) && (conn->content_len >= 0)
19499
0
                 && (conn->request_len > 0)
19500
0
                 && ((conn->is_chunked == 4)
19501
0
                     || (!conn->is_chunked
19502
0
                         && ((conn->consumed_content == conn->content_len)
19503
0
                             || ((conn->request_len + conn->content_len)
19504
0
                                 <= conn->data_len))))
19505
0
                 && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
19506
19507
0
    if (keep_alive) {
19508
      /* Discard all buffered data for this request */
19509
0
      discard_len =
19510
0
          ((conn->request_len + conn->content_len) < conn->data_len)
19511
0
              ? (int)(conn->request_len + conn->content_len)
19512
0
              : conn->data_len;
19513
0
      conn->data_len -= discard_len;
19514
19515
0
      if (conn->data_len > 0) {
19516
0
        DEBUG_TRACE("discard_len = %d", discard_len);
19517
0
        memmove(conn->buf,
19518
0
                conn->buf + discard_len,
19519
0
                (size_t)conn->data_len);
19520
0
      }
19521
0
    }
19522
19523
0
    DEBUG_ASSERT(conn->data_len >= 0);
19524
0
    DEBUG_ASSERT(conn->data_len <= conn->buf_size);
19525
19526
0
    if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
19527
0
      DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
19528
0
                  (long int)conn->data_len,
19529
0
                  (long int)conn->buf_size);
19530
0
      break;
19531
0
    }
19532
0
    conn->handled_requests++;
19533
0
  } while (keep_alive);
19534
19535
0
  DEBUG_TRACE("Done processing connection from %s (%f sec)",
19536
0
              conn->request_info.remote_addr,
19537
0
              difftime(time(NULL), conn->conn_birth_time));
19538
19539
0
  close_connection(conn);
19540
19541
#if defined(USE_SERVER_STATS)
19542
  mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
19543
  mg_atomic_dec(&(conn->phys_ctx->active_connections));
19544
#endif
19545
0
}
19546
19547
19548
#if defined(ALTERNATIVE_QUEUE)
19549
19550
static void
19551
produce_socket(struct mg_context *ctx, const struct socket *sp)
19552
{
19553
  unsigned int i;
19554
19555
  while (!ctx->stop_flag) {
19556
    for (i = 0; i < ctx->cfg_worker_threads; i++) {
19557
      /* find a free worker slot and signal it */
19558
      if (ctx->client_socks[i].in_use == 2) {
19559
        (void)pthread_mutex_lock(&ctx->thread_mutex);
19560
        if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
19561
          ctx->client_socks[i] = *sp;
19562
          ctx->client_socks[i].in_use = 1;
19563
          /* socket has been moved to the consumer */
19564
          (void)pthread_mutex_unlock(&ctx->thread_mutex);
19565
          (void)event_signal(ctx->client_wait_events[i]);
19566
          return;
19567
        }
19568
        (void)pthread_mutex_unlock(&ctx->thread_mutex);
19569
      }
19570
    }
19571
    /* queue is full */
19572
    mg_sleep(1);
19573
  }
19574
  /* must consume */
19575
  set_blocking_mode(sp->sock);
19576
  closesocket(sp->sock);
19577
}
19578
19579
19580
static int
19581
consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
19582
{
19583
  DEBUG_TRACE("%s", "going idle");
19584
  (void)pthread_mutex_lock(&ctx->thread_mutex);
19585
  ctx->client_socks[thread_index].in_use = 2;
19586
  (void)pthread_mutex_unlock(&ctx->thread_mutex);
19587
19588
  event_wait(ctx->client_wait_events[thread_index]);
19589
19590
  (void)pthread_mutex_lock(&ctx->thread_mutex);
19591
  *sp = ctx->client_socks[thread_index];
19592
  if (ctx->stop_flag) {
19593
    (void)pthread_mutex_unlock(&ctx->thread_mutex);
19594
    if (sp->in_use == 1) {
19595
      /* must consume */
19596
      set_blocking_mode(sp->sock);
19597
      closesocket(sp->sock);
19598
    }
19599
    return 0;
19600
  }
19601
  (void)pthread_mutex_unlock(&ctx->thread_mutex);
19602
  if (sp->in_use == 1) {
19603
    DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
19604
    return 1;
19605
  }
19606
  /* must not reach here */
19607
  DEBUG_ASSERT(0);
19608
  return 0;
19609
}
19610
19611
#else /* ALTERNATIVE_QUEUE */
19612
19613
/* Worker threads take accepted socket from the queue */
19614
static int
19615
consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
19616
100
{
19617
100
  (void)thread_index;
19618
19619
100
  (void)pthread_mutex_lock(&ctx->thread_mutex);
19620
100
  DEBUG_TRACE("%s", "going idle");
19621
19622
  /* If the queue is empty, wait. We're idle at this point. */
19623
200
  while ((ctx->sq_head == ctx->sq_tail)
19624
200
         && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
19625
100
    pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
19626
100
  }
19627
19628
  /* If we're stopping, sq_head may be equal to sq_tail. */
19629
100
  if (ctx->sq_head > ctx->sq_tail) {
19630
    /* Copy socket from the queue and increment tail */
19631
0
    *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
19632
0
    ctx->sq_tail++;
19633
19634
0
    DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
19635
19636
    /* Wrap pointers if needed */
19637
0
    while (ctx->sq_tail > ctx->sq_size) {
19638
0
      ctx->sq_tail -= ctx->sq_size;
19639
0
      ctx->sq_head -= ctx->sq_size;
19640
0
    }
19641
0
  }
19642
19643
100
  (void)pthread_cond_signal(&ctx->sq_empty);
19644
100
  (void)pthread_mutex_unlock(&ctx->thread_mutex);
19645
19646
100
  return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
19647
100
}
19648
19649
19650
/* Master thread adds accepted socket to a queue */
19651
static void
19652
produce_socket(struct mg_context *ctx, const struct socket *sp)
19653
0
{
19654
0
  int queue_filled;
19655
19656
0
  (void)pthread_mutex_lock(&ctx->thread_mutex);
19657
19658
0
  queue_filled = ctx->sq_head - ctx->sq_tail;
19659
19660
  /* If the queue is full, wait */
19661
0
  while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
19662
0
         && (queue_filled >= ctx->sq_size)) {
19663
0
    ctx->sq_blocked = 1; /* Status information: All threads busy */
19664
#if defined(USE_SERVER_STATS)
19665
    if (queue_filled > ctx->sq_max_fill) {
19666
      ctx->sq_max_fill = queue_filled;
19667
    }
19668
#endif
19669
0
    (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
19670
0
    ctx->sq_blocked = 0; /* Not blocked now */
19671
0
    queue_filled = ctx->sq_head - ctx->sq_tail;
19672
0
  }
19673
19674
0
  if (queue_filled < ctx->sq_size) {
19675
    /* Copy socket to the queue and increment head */
19676
0
    ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
19677
0
    ctx->sq_head++;
19678
0
    DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
19679
0
  }
19680
19681
0
  queue_filled = ctx->sq_head - ctx->sq_tail;
19682
#if defined(USE_SERVER_STATS)
19683
  if (queue_filled > ctx->sq_max_fill) {
19684
    ctx->sq_max_fill = queue_filled;
19685
  }
19686
#endif
19687
19688
0
  (void)pthread_cond_signal(&ctx->sq_full);
19689
0
  (void)pthread_mutex_unlock(&ctx->thread_mutex);
19690
0
}
19691
#endif /* ALTERNATIVE_QUEUE */
19692
19693
19694
static void
19695
worker_thread_run(struct mg_connection *conn)
19696
100
{
19697
100
  struct mg_context *ctx = conn->phys_ctx;
19698
100
  int thread_index;
19699
100
  struct mg_workerTLS tls;
19700
19701
100
  mg_set_thread_name("worker");
19702
19703
100
  tls.is_master = 0;
19704
100
  tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
19705
#if defined(_WIN32)
19706
  tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
19707
#endif
19708
19709
  /* Initialize thread local storage before calling any callback */
19710
100
  pthread_setspecific(sTlsKey, &tls);
19711
19712
  /* Check if there is a user callback */
19713
100
  if (ctx->callbacks.init_thread) {
19714
    /* call init_thread for a worker thread (type 1), and store the
19715
     * return value */
19716
0
    tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
19717
100
  } else {
19718
    /* No callback: set user pointer to NULL */
19719
100
    tls.user_ptr = NULL;
19720
100
  }
19721
19722
  /* Connection structure has been pre-allocated */
19723
100
  thread_index = (int)(conn - ctx->worker_connections);
19724
100
  if ((thread_index < 0)
19725
100
      || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
19726
0
    mg_cry_ctx_internal(ctx,
19727
0
                        "Internal error: Invalid worker index %i",
19728
0
                        thread_index);
19729
0
    return;
19730
0
  }
19731
19732
  /* Request buffers are not pre-allocated. They are private to the
19733
   * request and do not contain any state information that might be
19734
   * of interest to anyone observing a server status.  */
19735
100
  conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
19736
100
  if (conn->buf == NULL) {
19737
0
    mg_cry_ctx_internal(
19738
0
        ctx,
19739
0
        "Out of memory: Cannot allocate buffer for worker %i",
19740
0
        thread_index);
19741
0
    return;
19742
0
  }
19743
100
  conn->buf_size = (int)ctx->max_request_size;
19744
19745
100
  conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
19746
19747
100
  conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
19748
19749
100
  conn->request_info.user_data = ctx->user_data;
19750
  /* Allocate a mutex for this connection to allow communication both
19751
   * within the request handler and from elsewhere in the application
19752
   */
19753
100
  if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
19754
0
    mg_free(conn->buf);
19755
0
    mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
19756
0
    return;
19757
0
  }
19758
19759
#if defined(USE_SERVER_STATS)
19760
  conn->conn_state = 1; /* not consumed */
19761
#endif
19762
19763
  /* Call consume_socket() even when ctx->stop_flag > 0, to let it
19764
   * signal sq_empty condvar to wake up the master waiting in
19765
   * produce_socket() */
19766
100
  while (consume_socket(ctx, &conn->client, thread_index)) {
19767
19768
    /* New connections must start with new protocol negotiation */
19769
0
    tls.alpn_proto = NULL;
19770
19771
#if defined(USE_SERVER_STATS)
19772
    conn->conn_close_time = 0;
19773
#endif
19774
0
    conn->conn_birth_time = time(NULL);
19775
19776
    /* Fill in IP, port info early so even if SSL setup below fails,
19777
     * error handler would have the corresponding info.
19778
     * Thanks to Johannes Winkelmann for the patch.
19779
     */
19780
0
    conn->request_info.remote_port =
19781
0
        ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
19782
19783
0
    conn->request_info.server_port =
19784
0
        ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
19785
19786
0
    sockaddr_to_string(conn->request_info.remote_addr,
19787
0
                       sizeof(conn->request_info.remote_addr),
19788
0
                       &conn->client.rsa);
19789
19790
0
    DEBUG_TRACE("Incoming %sconnection from %s",
19791
0
                (conn->client.is_ssl ? "SSL " : ""),
19792
0
                conn->request_info.remote_addr);
19793
19794
0
    conn->request_info.is_ssl = conn->client.is_ssl;
19795
19796
0
    if (conn->client.is_ssl) {
19797
19798
#if defined(USE_MBEDTLS)
19799
      /* HTTPS connection */
19800
      if (mbed_ssl_accept(&(conn->ssl),
19801
                          conn->dom_ctx->ssl_ctx,
19802
                          (int *)&(conn->client.sock),
19803
                          conn->phys_ctx)
19804
          == 0) {
19805
        /* conn->dom_ctx is set in get_request */
19806
        /* process HTTPS connection */
19807
        init_connection(conn);
19808
        conn->connection_type = CONNECTION_TYPE_REQUEST;
19809
        conn->protocol_type = PROTOCOL_TYPE_HTTP1;
19810
        process_new_connection(conn);
19811
      } else {
19812
        /* make sure the connection is cleaned up on SSL failure */
19813
        close_connection(conn);
19814
      }
19815
19816
#elif !defined(NO_SSL)
19817
      /* HTTPS connection */
19818
0
      if (sslize(conn, SSL_accept, NULL)) {
19819
        /* conn->dom_ctx is set in get_request */
19820
19821
        /* Get SSL client certificate information (if set) */
19822
0
        struct mg_client_cert client_cert;
19823
0
        if (ssl_get_client_cert_info(conn, &client_cert)) {
19824
0
          conn->request_info.client_cert = &client_cert;
19825
0
        }
19826
19827
        /* process HTTPS connection */
19828
#if defined(USE_HTTP2)
19829
        if ((tls.alpn_proto != NULL)
19830
            && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
19831
          /* process HTTPS/2 connection */
19832
          init_connection(conn);
19833
          conn->connection_type = CONNECTION_TYPE_REQUEST;
19834
          conn->protocol_type = PROTOCOL_TYPE_HTTP2;
19835
          conn->content_len =
19836
              -1;               /* content length is not predefined */
19837
          conn->is_chunked = 0; /* HTTP2 is never chunked */
19838
          process_new_http2_connection(conn);
19839
        } else
19840
#endif
19841
0
        {
19842
          /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
19843
0
          init_connection(conn);
19844
0
          conn->connection_type = CONNECTION_TYPE_REQUEST;
19845
          /* Start with HTTP, WS will be an "upgrade" request later */
19846
0
          conn->protocol_type = PROTOCOL_TYPE_HTTP1;
19847
0
          process_new_connection(conn);
19848
0
        }
19849
19850
        /* Free client certificate info */
19851
0
        if (conn->request_info.client_cert) {
19852
0
          mg_free((void *)(conn->request_info.client_cert->subject));
19853
0
          mg_free((void *)(conn->request_info.client_cert->issuer));
19854
0
          mg_free((void *)(conn->request_info.client_cert->serial));
19855
0
          mg_free((void *)(conn->request_info.client_cert->finger));
19856
          /* Free certificate memory */
19857
0
          X509_free(
19858
0
              (X509 *)conn->request_info.client_cert->peer_cert);
19859
0
          conn->request_info.client_cert->peer_cert = 0;
19860
0
          conn->request_info.client_cert->subject = 0;
19861
0
          conn->request_info.client_cert->issuer = 0;
19862
0
          conn->request_info.client_cert->serial = 0;
19863
0
          conn->request_info.client_cert->finger = 0;
19864
0
          conn->request_info.client_cert = 0;
19865
0
        }
19866
0
      } else {
19867
        /* make sure the connection is cleaned up on SSL failure */
19868
0
        close_connection(conn);
19869
0
      }
19870
0
#endif
19871
19872
0
    } else {
19873
      /* process HTTP connection */
19874
0
      init_connection(conn);
19875
0
      conn->connection_type = CONNECTION_TYPE_REQUEST;
19876
      /* Start with HTTP, WS will be an "upgrade" request later */
19877
0
      conn->protocol_type = PROTOCOL_TYPE_HTTP1;
19878
0
      process_new_connection(conn);
19879
0
    }
19880
19881
0
    DEBUG_TRACE("%s", "Connection closed");
19882
19883
#if defined(USE_SERVER_STATS)
19884
    conn->conn_close_time = time(NULL);
19885
#endif
19886
0
  }
19887
19888
  /* Call exit thread user callback */
19889
100
  if (ctx->callbacks.exit_thread) {
19890
0
    ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
19891
0
  }
19892
19893
  /* delete thread local storage objects */
19894
100
  pthread_setspecific(sTlsKey, NULL);
19895
#if defined(_WIN32)
19896
  CloseHandle(tls.pthread_cond_helper_mutex);
19897
#endif
19898
100
  pthread_mutex_destroy(&conn->mutex);
19899
19900
  /* Free the request buffer. */
19901
100
  conn->buf_size = 0;
19902
100
  mg_free(conn->buf);
19903
100
  conn->buf = NULL;
19904
19905
  /* Free cleaned URI (if any) */
19906
100
  if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
19907
0
    mg_free((void *)conn->request_info.local_uri);
19908
0
    conn->request_info.local_uri = NULL;
19909
0
  }
19910
19911
#if defined(USE_SERVER_STATS)
19912
  conn->conn_state = 9; /* done */
19913
#endif
19914
19915
100
  DEBUG_TRACE("%s", "exiting");
19916
100
}
19917
19918
19919
/* Threads have different return types on Windows and Unix. */
19920
#if defined(_WIN32)
19921
static unsigned __stdcall worker_thread(void *thread_func_param)
19922
{
19923
  worker_thread_run((struct mg_connection *)thread_func_param);
19924
  return 0;
19925
}
19926
#else
19927
static void *
19928
worker_thread(void *thread_func_param)
19929
100
{
19930
100
#if !defined(__ZEPHYR__)
19931
100
  struct sigaction sa;
19932
19933
  /* Ignore SIGPIPE */
19934
100
  memset(&sa, 0, sizeof(sa));
19935
100
  sa.sa_handler = SIG_IGN;
19936
100
  sigaction(SIGPIPE, &sa, NULL);
19937
100
#endif
19938
19939
100
  worker_thread_run((struct mg_connection *)thread_func_param);
19940
100
  return NULL;
19941
100
}
19942
#endif /* _WIN32 */
19943
19944
19945
/* This is an internal function, thus all arguments are expected to be
19946
 * valid - a NULL check is not required. */
19947
static void
19948
accept_new_connection(const struct socket *listener, struct mg_context *ctx)
19949
0
{
19950
0
  struct socket so;
19951
0
  char src_addr[IP_ADDR_STR_LEN];
19952
0
  socklen_t len = sizeof(so.rsa);
19953
0
#if !defined(__ZEPHYR__)
19954
0
  int on = 1;
19955
0
#endif
19956
0
  memset(&so, 0, sizeof(so));
19957
19958
0
  if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
19959
0
      == INVALID_SOCKET) {
19960
0
  } else if (check_acl(ctx, &so.rsa) != 1) {
19961
0
    sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
19962
0
    mg_cry_ctx_internal(ctx,
19963
0
                        "%s: %s is not allowed to connect",
19964
0
                        __func__,
19965
0
                        src_addr);
19966
0
    closesocket(so.sock);
19967
0
  } else {
19968
    /* Put so socket structure into the queue */
19969
0
    DEBUG_TRACE("Accepted socket %d", (int)so.sock);
19970
0
    set_close_on_exec(so.sock, NULL, ctx);
19971
0
    so.is_ssl = listener->is_ssl;
19972
0
    so.ssl_redir = listener->ssl_redir;
19973
0
    if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
19974
0
      mg_cry_ctx_internal(ctx,
19975
0
                          "%s: getsockname() failed: %s",
19976
0
                          __func__,
19977
0
                          strerror(ERRNO));
19978
0
    }
19979
19980
0
#if !defined(__ZEPHYR__)
19981
0
    if ((so.lsa.sa.sa_family == AF_INET)
19982
0
        || (so.lsa.sa.sa_family == AF_INET6)) {
19983
      /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
19984
       * This is needed because if HTTP-level keep-alive
19985
       * is enabled, and client resets the connection, server won't get
19986
       * TCP FIN or RST and will keep the connection open forever. With
19987
       * TCP keep-alive, next keep-alive handshake will figure out that
19988
       * the client is down and will close the server end.
19989
       * Thanks to Igor Klopov who suggested the patch. */
19990
0
      if (setsockopt(so.sock,
19991
0
                     SOL_SOCKET,
19992
0
                     SO_KEEPALIVE,
19993
0
                     (SOCK_OPT_TYPE)&on,
19994
0
                     sizeof(on))
19995
0
          != 0) {
19996
0
        mg_cry_ctx_internal(
19997
0
            ctx,
19998
0
            "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
19999
0
            __func__,
20000
0
            strerror(ERRNO));
20001
0
      }
20002
0
    }
20003
0
#endif
20004
20005
    /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
20006
     * to effectively fill up the underlying IP packet payload and
20007
     * reduce the overhead of sending lots of small buffers. However
20008
     * this hurts the server's throughput (ie. operations per second)
20009
     * when HTTP 1.1 persistent connections are used and the responses
20010
     * are relatively small (eg. less than 1400 bytes).
20011
     */
20012
0
    if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
20013
0
        && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
20014
0
      if (set_tcp_nodelay(&so, 1) != 0) {
20015
0
        mg_cry_ctx_internal(
20016
0
            ctx,
20017
0
            "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
20018
0
            __func__,
20019
0
            strerror(ERRNO));
20020
0
      }
20021
0
    }
20022
20023
    /* The "non blocking" property should already be
20024
     * inherited from the parent socket. Set it for
20025
     * non-compliant socket implementations. */
20026
0
    set_non_blocking_mode(so.sock);
20027
20028
0
    so.in_use = 0;
20029
0
    produce_socket(ctx, &so);
20030
0
  }
20031
0
}
20032
20033
20034
static void
20035
master_thread_run(struct mg_context *ctx)
20036
2
{
20037
2
  struct mg_workerTLS tls;
20038
2
  struct mg_pollfd *pfd;
20039
2
  unsigned int i;
20040
2
  unsigned int workerthreadcount;
20041
20042
2
  if (!ctx) {
20043
0
    return;
20044
0
  }
20045
20046
2
  mg_set_thread_name("master");
20047
20048
  /* Increase priority of the master thread */
20049
#if defined(_WIN32)
20050
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
20051
#elif defined(USE_MASTER_THREAD_PRIORITY)
20052
  int min_prio = sched_get_priority_min(SCHED_RR);
20053
  int max_prio = sched_get_priority_max(SCHED_RR);
20054
  if ((min_prio >= 0) && (max_prio >= 0)
20055
      && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
20056
      && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
20057
    struct sched_param sched_param = {0};
20058
    sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
20059
    pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
20060
  }
20061
#endif
20062
20063
  /* Initialize thread local storage */
20064
#if defined(_WIN32)
20065
  tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
20066
#endif
20067
2
  tls.is_master = 1;
20068
2
  pthread_setspecific(sTlsKey, &tls);
20069
20070
2
  if (ctx->callbacks.init_thread) {
20071
    /* Callback for the master thread (type 0) */
20072
0
    tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
20073
2
  } else {
20074
2
    tls.user_ptr = NULL;
20075
2
  }
20076
20077
  /* Lua background script "start" event */
20078
#if defined(USE_LUA)
20079
  if (ctx->lua_background_state) {
20080
    lua_State *lstate = (lua_State *)ctx->lua_background_state;
20081
    pthread_mutex_lock(&ctx->lua_bg_mutex);
20082
20083
    /* call "start()" in Lua */
20084
    lua_getglobal(lstate, "start");
20085
    if (lua_type(lstate, -1) == LUA_TFUNCTION) {
20086
      int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
20087
      if (ret != 0) {
20088
        struct mg_connection fc;
20089
        lua_cry(fake_connection(&fc, ctx),
20090
                ret,
20091
                lstate,
20092
                "lua_background_script",
20093
                "start");
20094
      }
20095
    } else {
20096
      lua_pop(lstate, 1);
20097
    }
20098
20099
    /* determine if there is a "log()" function in Lua background script */
20100
    lua_getglobal(lstate, "log");
20101
    if (lua_type(lstate, -1) == LUA_TFUNCTION) {
20102
      ctx->lua_bg_log_available = 1;
20103
    }
20104
    lua_pop(lstate, 1);
20105
20106
    pthread_mutex_unlock(&ctx->lua_bg_mutex);
20107
  }
20108
#endif
20109
20110
  /* Server starts *now* */
20111
2
  ctx->start_time = time(NULL);
20112
20113
  /* Server accept loop */
20114
2
  pfd = ctx->listening_socket_fds;
20115
8
  while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
20116
12
    for (i = 0; i < ctx->num_listening_sockets; i++) {
20117
6
      pfd[i].fd = ctx->listening_sockets[i].sock;
20118
6
      pfd[i].events = POLLIN;
20119
6
    }
20120
20121
6
    if (mg_poll(pfd,
20122
6
                ctx->num_listening_sockets,
20123
6
                SOCKET_TIMEOUT_QUANTUM,
20124
6
                &(ctx->stop_flag))
20125
6
        > 0) {
20126
0
      for (i = 0; i < ctx->num_listening_sockets; i++) {
20127
        /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
20128
         * successful poll, and POLLIN is defined as
20129
         * (POLLRDNORM | POLLRDBAND)
20130
         * Therefore, we're checking pfd[i].revents & POLLIN, not
20131
         * pfd[i].revents == POLLIN. */
20132
0
        if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
20133
0
            && (pfd[i].revents & POLLIN)) {
20134
0
          accept_new_connection(&ctx->listening_sockets[i], ctx);
20135
0
        }
20136
0
      }
20137
0
    }
20138
6
  }
20139
20140
  /* Here stop_flag is 1 - Initiate shutdown. */
20141
2
  DEBUG_TRACE("%s", "stopping workers");
20142
20143
  /* Stop signal received: somebody called mg_stop. Quit. */
20144
2
  close_all_listening_sockets(ctx);
20145
20146
  /* Wakeup workers that are waiting for connections to handle. */
20147
#if defined(ALTERNATIVE_QUEUE)
20148
  for (i = 0; i < ctx->cfg_worker_threads; i++) {
20149
    event_signal(ctx->client_wait_events[i]);
20150
  }
20151
#else
20152
2
  (void)pthread_mutex_lock(&ctx->thread_mutex);
20153
2
  pthread_cond_broadcast(&ctx->sq_full);
20154
2
  (void)pthread_mutex_unlock(&ctx->thread_mutex);
20155
2
#endif
20156
20157
  /* Join all worker threads to avoid leaking threads. */
20158
2
  workerthreadcount = ctx->cfg_worker_threads;
20159
102
  for (i = 0; i < workerthreadcount; i++) {
20160
100
    if (ctx->worker_threadids[i] != 0) {
20161
100
      mg_join_thread(ctx->worker_threadids[i]);
20162
100
    }
20163
100
  }
20164
20165
#if defined(USE_LUA)
20166
  /* Free Lua state of lua background task */
20167
  if (ctx->lua_background_state) {
20168
    lua_State *lstate = (lua_State *)ctx->lua_background_state;
20169
    ctx->lua_bg_log_available = 0;
20170
20171
    /* call "stop()" in Lua */
20172
    pthread_mutex_lock(&ctx->lua_bg_mutex);
20173
    lua_getglobal(lstate, "stop");
20174
    if (lua_type(lstate, -1) == LUA_TFUNCTION) {
20175
      int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
20176
      if (ret != 0) {
20177
        struct mg_connection fc;
20178
        lua_cry(fake_connection(&fc, ctx),
20179
                ret,
20180
                lstate,
20181
                "lua_background_script",
20182
                "stop");
20183
      }
20184
    }
20185
    DEBUG_TRACE("Close Lua background state %p", lstate);
20186
    lua_close(lstate);
20187
20188
    ctx->lua_background_state = 0;
20189
    pthread_mutex_unlock(&ctx->lua_bg_mutex);
20190
  }
20191
#endif
20192
20193
2
  DEBUG_TRACE("%s", "exiting");
20194
20195
  /* call exit thread callback */
20196
2
  if (ctx->callbacks.exit_thread) {
20197
    /* Callback for the master thread (type 0) */
20198
0
    ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
20199
0
  }
20200
20201
#if defined(_WIN32)
20202
  CloseHandle(tls.pthread_cond_helper_mutex);
20203
#endif
20204
2
  pthread_setspecific(sTlsKey, NULL);
20205
20206
  /* Signal mg_stop() that we're done.
20207
   * WARNING: This must be the very last thing this
20208
   * thread does, as ctx becomes invalid after this line. */
20209
2
  STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
20210
2
}
20211
20212
20213
/* Threads have different return types on Windows and Unix. */
20214
#if defined(_WIN32)
20215
static unsigned __stdcall master_thread(void *thread_func_param)
20216
{
20217
  master_thread_run((struct mg_context *)thread_func_param);
20218
  return 0;
20219
}
20220
#else
20221
static void *
20222
master_thread(void *thread_func_param)
20223
2
{
20224
2
#if !defined(__ZEPHYR__)
20225
2
  struct sigaction sa;
20226
20227
  /* Ignore SIGPIPE */
20228
2
  memset(&sa, 0, sizeof(sa));
20229
2
  sa.sa_handler = SIG_IGN;
20230
2
  sigaction(SIGPIPE, &sa, NULL);
20231
2
#endif
20232
20233
2
  master_thread_run((struct mg_context *)thread_func_param);
20234
2
  return NULL;
20235
2
}
20236
#endif /* _WIN32 */
20237
20238
20239
static void
20240
free_context(struct mg_context *ctx)
20241
2
{
20242
2
  int i;
20243
2
  struct mg_handler_info *tmp_rh;
20244
20245
2
  if (ctx == NULL) {
20246
0
    return;
20247
0
  }
20248
20249
  /* Call user callback */
20250
2
  if (ctx->callbacks.exit_context) {
20251
0
    ctx->callbacks.exit_context(ctx);
20252
0
  }
20253
20254
  /* All threads exited, no sync is needed. Destroy thread mutex and
20255
   * condvars
20256
   */
20257
2
  (void)pthread_mutex_destroy(&ctx->thread_mutex);
20258
20259
#if defined(ALTERNATIVE_QUEUE)
20260
  mg_free(ctx->client_socks);
20261
  if (ctx->client_wait_events != NULL) {
20262
    for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
20263
      event_destroy(ctx->client_wait_events[i]);
20264
    }
20265
    mg_free(ctx->client_wait_events);
20266
  }
20267
#else
20268
2
  (void)pthread_cond_destroy(&ctx->sq_empty);
20269
2
  (void)pthread_cond_destroy(&ctx->sq_full);
20270
2
  mg_free(ctx->squeue);
20271
2
#endif
20272
20273
  /* Destroy other context global data structures mutex */
20274
2
  (void)pthread_mutex_destroy(&ctx->nonce_mutex);
20275
20276
#if defined(USE_LUA)
20277
  (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
20278
#endif
20279
20280
  /* Deallocate config parameters */
20281
124
  for (i = 0; i < NUM_OPTIONS; i++) {
20282
122
    if (ctx->dd.config[i] != NULL) {
20283
#if defined(_MSC_VER)
20284
#pragma warning(suppress : 6001)
20285
#endif
20286
66
      mg_free(ctx->dd.config[i]);
20287
66
    }
20288
122
  }
20289
20290
  /* Deallocate request handlers */
20291
2
  while (ctx->dd.handlers) {
20292
0
    tmp_rh = ctx->dd.handlers;
20293
0
    ctx->dd.handlers = tmp_rh->next;
20294
0
    mg_free(tmp_rh->uri);
20295
0
    mg_free(tmp_rh);
20296
0
  }
20297
20298
#if defined(USE_MBEDTLS)
20299
  if (ctx->dd.ssl_ctx != NULL) {
20300
    mbed_sslctx_uninit(ctx->dd.ssl_ctx);
20301
    mg_free(ctx->dd.ssl_ctx);
20302
    ctx->dd.ssl_ctx = NULL;
20303
  }
20304
20305
#elif !defined(NO_SSL)
20306
  /* Deallocate SSL context */
20307
2
  if (ctx->dd.ssl_ctx != NULL) {
20308
0
    void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
20309
0
    int callback_ret =
20310
0
        (ctx->callbacks.external_ssl_ctx == NULL)
20311
0
            ? 0
20312
0
            : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
20313
20314
0
    if (callback_ret == 0) {
20315
0
      SSL_CTX_free(ctx->dd.ssl_ctx);
20316
0
    }
20317
    /* else: ignore error and omit SSL_CTX_free in case
20318
     * callback_ret is 1 */
20319
0
  }
20320
2
#endif /* !NO_SSL */
20321
20322
  /* Deallocate worker thread ID array */
20323
2
  mg_free(ctx->worker_threadids);
20324
20325
  /* Deallocate worker thread ID array */
20326
2
  mg_free(ctx->worker_connections);
20327
20328
  /* deallocate system name string */
20329
2
  mg_free(ctx->systemName);
20330
20331
  /* Deallocate context itself */
20332
2
  mg_free(ctx);
20333
2
}
20334
20335
20336
CIVETWEB_API void
20337
mg_stop(struct mg_context *ctx)
20338
2
{
20339
2
  pthread_t mt;
20340
2
  if (!ctx) {
20341
0
    return;
20342
0
  }
20343
20344
  /* We don't use a lock here. Calling mg_stop with the same ctx from
20345
   * two threads is not allowed. */
20346
2
  mt = ctx->masterthreadid;
20347
2
  if (mt == 0) {
20348
0
    return;
20349
0
  }
20350
20351
2
  ctx->masterthreadid = 0;
20352
20353
  /* Set stop flag, so all threads know they have to exit. */
20354
2
  STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
20355
20356
  /* Join timer thread */
20357
#if defined(USE_TIMERS)
20358
  timers_exit(ctx);
20359
#endif
20360
20361
  /* Wait until everything has stopped. */
20362
200
  while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
20363
198
    (void)mg_sleep(10);
20364
198
  }
20365
20366
  /* Wait to stop master thread */
20367
2
  mg_join_thread(mt);
20368
20369
  /* Close remaining Lua states */
20370
#if defined(USE_LUA)
20371
  lua_ctx_exit(ctx);
20372
#endif
20373
20374
  /* Free memory */
20375
2
  free_context(ctx);
20376
2
}
20377
20378
20379
static void
20380
get_system_name(char **sysName)
20381
2
{
20382
#if defined(_WIN32)
20383
  char name[128];
20384
  DWORD dwVersion = 0;
20385
  DWORD dwMajorVersion = 0;
20386
  DWORD dwMinorVersion = 0;
20387
  DWORD dwBuild = 0;
20388
  BOOL wowRet, isWoW = FALSE;
20389
20390
#if defined(_MSC_VER)
20391
#pragma warning(push)
20392
  /* GetVersion was declared deprecated */
20393
#pragma warning(disable : 4996)
20394
#endif
20395
  dwVersion = GetVersion();
20396
#if defined(_MSC_VER)
20397
#pragma warning(pop)
20398
#endif
20399
20400
  dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
20401
  dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
20402
  dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
20403
  (void)dwBuild;
20404
20405
  wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
20406
20407
  sprintf(name,
20408
          "Windows %u.%u%s",
20409
          (unsigned)dwMajorVersion,
20410
          (unsigned)dwMinorVersion,
20411
          (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
20412
20413
  *sysName = mg_strdup(name);
20414
20415
#elif defined(__ZEPHYR__)
20416
  *sysName = mg_strdup("Zephyr OS");
20417
#else
20418
2
  struct utsname name;
20419
2
  memset(&name, 0, sizeof(name));
20420
2
  uname(&name);
20421
2
  *sysName = mg_strdup(name.sysname);
20422
2
#endif
20423
2
}
20424
20425
20426
static void
20427
legacy_init(const char **options)
20428
2
{
20429
2
  const char *ports_option = config_options[LISTENING_PORTS].default_value;
20430
20431
2
  if (options) {
20432
2
    const char **run_options = options;
20433
2
    const char *optname = config_options[LISTENING_PORTS].name;
20434
20435
    /* Try to find the "listening_ports" option */
20436
6
    while (*run_options) {
20437
4
      if (!strcmp(*run_options, optname)) {
20438
2
        ports_option = run_options[1];
20439
2
      }
20440
4
      run_options += 2;
20441
4
    }
20442
2
  }
20443
20444
2
  if (is_ssl_port_used(ports_option)) {
20445
    /* Initialize with SSL support */
20446
0
    mg_init_library(MG_FEATURES_TLS);
20447
2
  } else {
20448
    /* Initialize without SSL support */
20449
2
    mg_init_library(MG_FEATURES_DEFAULT);
20450
2
  }
20451
2
}
20452
20453
20454
CIVETWEB_API struct mg_context *
20455
mg_start2(struct mg_init_data *init, struct mg_error_data *error)
20456
2
{
20457
2
  struct mg_context *ctx;
20458
2
  const char *name, *value, *default_value;
20459
2
  int idx, ok, workerthreadcount;
20460
2
  unsigned int i;
20461
2
  int itmp;
20462
2
  void (*exit_callback)(const struct mg_context *ctx) = 0;
20463
2
  const char **options =
20464
2
      ((init != NULL) ? (init->configuration_options) : (NULL));
20465
20466
2
  struct mg_workerTLS tls;
20467
20468
2
  if (error != NULL) {
20469
0
    error->code = MG_ERROR_DATA_CODE_OK;
20470
0
    error->code_sub = 0;
20471
0
    if (error->text_buffer_size > 0) {
20472
0
      *error->text = 0;
20473
0
    }
20474
0
  }
20475
20476
2
  if (mg_init_library_called == 0) {
20477
    /* Legacy INIT, if mg_start is called without mg_init_library.
20478
     * Note: This will cause a memory leak when unloading the library.
20479
     */
20480
2
    legacy_init(options);
20481
2
  }
20482
2
  if (mg_init_library_called == 0) {
20483
0
    if (error != NULL) {
20484
0
      error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
20485
0
      mg_snprintf(NULL,
20486
0
                  NULL, /* No truncation check for error buffers */
20487
0
                  error->text,
20488
0
                  error->text_buffer_size,
20489
0
                  "%s",
20490
0
                  "Library uninitialized");
20491
0
    }
20492
0
    return NULL;
20493
0
  }
20494
20495
  /* Allocate context and initialize reasonable general case defaults. */
20496
2
  ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
20497
2
  if (ctx == NULL) {
20498
0
    if (error != NULL) {
20499
0
      error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
20500
0
      error->code_sub = (unsigned)sizeof(*ctx);
20501
0
      mg_snprintf(NULL,
20502
0
                  NULL, /* No truncation check for error buffers */
20503
0
                  error->text,
20504
0
                  error->text_buffer_size,
20505
0
                  "%s",
20506
0
                  "Out of memory");
20507
0
    }
20508
0
    return NULL;
20509
0
  }
20510
20511
  /* Random number generator will initialize at the first call */
20512
2
  ctx->dd.auth_nonce_mask =
20513
2
      (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
20514
20515
  /* Save started thread index to reuse in other external API calls
20516
   * For the sake of thread synchronization all non-civetweb threads
20517
   * can be considered as single external thread */
20518
2
  ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
20519
2
  tls.is_master = -1; /* Thread calling mg_start */
20520
2
  tls.thread_idx = ctx->starter_thread_idx;
20521
#if defined(_WIN32)
20522
  tls.pthread_cond_helper_mutex = NULL;
20523
#endif
20524
2
  pthread_setspecific(sTlsKey, &tls);
20525
20526
2
  ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
20527
2
#if !defined(ALTERNATIVE_QUEUE)
20528
2
  ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
20529
2
  ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
20530
2
  ctx->sq_blocked = 0;
20531
2
#endif
20532
2
  ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
20533
#if defined(USE_LUA)
20534
  ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
20535
#endif
20536
2
  if (!ok) {
20537
0
    unsigned error_id = (unsigned)ERRNO;
20538
0
    const char *err_msg =
20539
0
        "Cannot initialize thread synchronization objects";
20540
    /* Fatal error - abort start. However, this situation should never
20541
     * occur in practice. */
20542
20543
0
    mg_cry_ctx_internal(ctx, "%s", err_msg);
20544
0
    if (error != NULL) {
20545
0
      error->code = MG_ERROR_DATA_CODE_OS_ERROR;
20546
0
      error->code_sub = error_id;
20547
0
      mg_snprintf(NULL,
20548
0
                  NULL, /* No truncation check for error buffers */
20549
0
                  error->text,
20550
0
                  error->text_buffer_size,
20551
0
                  "%s",
20552
0
                  err_msg);
20553
0
    }
20554
20555
0
    mg_free(ctx);
20556
0
    pthread_setspecific(sTlsKey, NULL);
20557
0
    return NULL;
20558
0
  }
20559
20560
2
  if ((init != NULL) && (init->callbacks != NULL)) {
20561
    /* Set all callbacks except exit_context. */
20562
2
    ctx->callbacks = *init->callbacks;
20563
2
    exit_callback = init->callbacks->exit_context;
20564
    /* The exit callback is activated once the context is successfully
20565
     * created. It should not be called, if an incomplete context object
20566
     * is deleted during a failed initialization. */
20567
2
    ctx->callbacks.exit_context = 0;
20568
2
  }
20569
2
  ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
20570
2
  ctx->dd.handlers = NULL;
20571
2
  ctx->dd.next = NULL;
20572
20573
#if defined(USE_LUA)
20574
  lua_ctx_init(ctx);
20575
#endif
20576
20577
  /* Store options */
20578
6
  while (options && (name = *options++) != NULL) {
20579
4
    idx = get_option_index(name);
20580
4
    if (idx == -1) {
20581
0
      mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
20582
0
      if (error != NULL) {
20583
0
        error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
20584
0
        error->code_sub = (unsigned)-1;
20585
0
        mg_snprintf(NULL,
20586
0
                    NULL, /* No truncation check for error buffers */
20587
0
                    error->text,
20588
0
                    error->text_buffer_size,
20589
0
                    "Invalid configuration option: %s",
20590
0
                    name);
20591
0
      }
20592
20593
0
      free_context(ctx);
20594
0
      pthread_setspecific(sTlsKey, NULL);
20595
0
      return NULL;
20596
20597
4
    } else if ((value = *options++) == NULL) {
20598
0
      mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
20599
0
      if (error != NULL) {
20600
0
        error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
20601
0
        error->code_sub = (unsigned)idx;
20602
0
        mg_snprintf(NULL,
20603
0
                    NULL, /* No truncation check for error buffers */
20604
0
                    error->text,
20605
0
                    error->text_buffer_size,
20606
0
                    "Invalid configuration option value: %s",
20607
0
                    name);
20608
0
      }
20609
20610
0
      free_context(ctx);
20611
0
      pthread_setspecific(sTlsKey, NULL);
20612
0
      return NULL;
20613
0
    }
20614
4
    if (ctx->dd.config[idx] != NULL) {
20615
      /* A duplicate configuration option is not an error - the last
20616
       * option value will be used. */
20617
0
      mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
20618
0
      mg_free(ctx->dd.config[idx]);
20619
0
    }
20620
4
    ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
20621
4
    DEBUG_TRACE("[%s] -> [%s]", name, value);
20622
4
  }
20623
20624
  /* Set default value if needed */
20625
124
  for (i = 0; config_options[i].name != NULL; i++) {
20626
122
    default_value = config_options[i].default_value;
20627
122
    if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
20628
62
      ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
20629
62
    }
20630
122
  }
20631
20632
  /* Request size option */
20633
2
  itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
20634
2
  if (itmp < 1024) {
20635
0
    mg_cry_ctx_internal(ctx,
20636
0
                        "%s too small",
20637
0
                        config_options[MAX_REQUEST_SIZE].name);
20638
0
    if (error != NULL) {
20639
0
      error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
20640
0
      error->code_sub = (unsigned)MAX_REQUEST_SIZE;
20641
0
      mg_snprintf(NULL,
20642
0
                  NULL, /* No truncation check for error buffers */
20643
0
                  error->text,
20644
0
                  error->text_buffer_size,
20645
0
                  "Invalid configuration option value: %s",
20646
0
                  config_options[MAX_REQUEST_SIZE].name);
20647
0
    }
20648
20649
0
    free_context(ctx);
20650
0
    pthread_setspecific(sTlsKey, NULL);
20651
0
    return NULL;
20652
0
  }
20653
2
  ctx->max_request_size = (unsigned)itmp;
20654
20655
  /* Queue length */
20656
2
#if !defined(ALTERNATIVE_QUEUE)
20657
2
  itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
20658
2
  if (itmp < 1) {
20659
0
    mg_cry_ctx_internal(ctx,
20660
0
                        "%s too small",
20661
0
                        config_options[CONNECTION_QUEUE_SIZE].name);
20662
0
    if (error != NULL) {
20663
0
      error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
20664
0
      error->code_sub = CONNECTION_QUEUE_SIZE;
20665
0
      mg_snprintf(NULL,
20666
0
                  NULL, /* No truncation check for error buffers */
20667
0
                  error->text,
20668
0
                  error->text_buffer_size,
20669
0
                  "Invalid configuration option value: %s",
20670
0
                  config_options[CONNECTION_QUEUE_SIZE].name);
20671
0
    }
20672
20673
0
    free_context(ctx);
20674
0
    pthread_setspecific(sTlsKey, NULL);
20675
0
    return NULL;
20676
0
  }
20677
2
  ctx->squeue =
20678
2
      (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
20679
2
  if (ctx->squeue == NULL) {
20680
0
    mg_cry_ctx_internal(ctx,
20681
0
                        "Out of memory: Cannot allocate %s",
20682
0
                        config_options[CONNECTION_QUEUE_SIZE].name);
20683
0
    if (error != NULL) {
20684
0
      error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
20685
0
      error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
20686
0
      mg_snprintf(NULL,
20687
0
                  NULL, /* No truncation check for error buffers */
20688
0
                  error->text,
20689
0
                  error->text_buffer_size,
20690
0
                  "Out of memory: Cannot allocate %s",
20691
0
                  config_options[CONNECTION_QUEUE_SIZE].name);
20692
0
    }
20693
20694
0
    free_context(ctx);
20695
0
    pthread_setspecific(sTlsKey, NULL);
20696
0
    return NULL;
20697
0
  }
20698
2
  ctx->sq_size = itmp;
20699
2
#endif
20700
20701
  /* Worker thread count option */
20702
2
  workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
20703
20704
2
  if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
20705
0
    if (workerthreadcount <= 0) {
20706
0
      mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
20707
0
    } else {
20708
0
      mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
20709
0
    }
20710
0
    if (error != NULL) {
20711
0
      error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
20712
0
      error->code_sub = NUM_THREADS;
20713
0
      mg_snprintf(NULL,
20714
0
                  NULL, /* No truncation check for error buffers */
20715
0
                  error->text,
20716
0
                  error->text_buffer_size,
20717
0
                  "Invalid configuration option value: %s",
20718
0
                  config_options[NUM_THREADS].name);
20719
0
    }
20720
20721
0
    free_context(ctx);
20722
0
    pthread_setspecific(sTlsKey, NULL);
20723
0
    return NULL;
20724
0
  }
20725
20726
  /* Document root */
20727
#if defined(NO_FILES)
20728
  if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
20729
    mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
20730
    if (error != NULL) {
20731
      error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
20732
      error->code_sub = (unsigned)DOCUMENT_ROOT;
20733
      mg_snprintf(NULL,
20734
                  NULL, /* No truncation check for error buffers */
20735
                  error->text,
20736
                  error->text_buffer_size,
20737
                  "Invalid configuration option value: %s",
20738
                  config_options[DOCUMENT_ROOT].name);
20739
    }
20740
20741
    free_context(ctx);
20742
    pthread_setspecific(sTlsKey, NULL);
20743
    return NULL;
20744
  }
20745
#endif
20746
20747
2
  get_system_name(&ctx->systemName);
20748
20749
#if defined(USE_LUA)
20750
  /* If a Lua background script has been configured, start it. */
20751
  ctx->lua_bg_log_available = 0;
20752
  if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
20753
    char ebuf[256];
20754
    struct vec opt_vec;
20755
    struct vec eq_vec;
20756
    const char *sparams;
20757
20758
    memset(ebuf, 0, sizeof(ebuf));
20759
    pthread_mutex_lock(&ctx->lua_bg_mutex);
20760
20761
    /* Create a Lua state, load all standard libraries and the mg table */
20762
    lua_State *state = mg_lua_context_script_prepare(
20763
        ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
20764
    if (!state) {
20765
      mg_cry_ctx_internal(ctx,
20766
                          "lua_background_script load error: %s",
20767
                          ebuf);
20768
      if (error != NULL) {
20769
        error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
20770
        mg_snprintf(NULL,
20771
                    NULL, /* No truncation check for error buffers */
20772
                    error->text,
20773
                    error->text_buffer_size,
20774
                    "Error in script %s: %s",
20775
                    config_options[LUA_BACKGROUND_SCRIPT].name,
20776
                    ebuf);
20777
      }
20778
20779
      pthread_mutex_unlock(&ctx->lua_bg_mutex);
20780
20781
      free_context(ctx);
20782
      pthread_setspecific(sTlsKey, NULL);
20783
      return NULL;
20784
    }
20785
20786
    /* Add a table with parameters into mg.params */
20787
    sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
20788
    if (sparams && sparams[0]) {
20789
      lua_getglobal(state, "mg");
20790
      lua_pushstring(state, "params");
20791
      lua_newtable(state);
20792
20793
      while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
20794
             != NULL) {
20795
        reg_llstring(
20796
            state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
20797
        if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
20798
          break;
20799
      }
20800
      lua_rawset(state, -3);
20801
      lua_pop(state, 1);
20802
    }
20803
20804
    /* Call script */
20805
    state = mg_lua_context_script_run(state,
20806
                                      ctx->dd.config[LUA_BACKGROUND_SCRIPT],
20807
                                      ctx,
20808
                                      ebuf,
20809
                                      sizeof(ebuf));
20810
    if (!state) {
20811
      mg_cry_ctx_internal(ctx,
20812
                          "lua_background_script start error: %s",
20813
                          ebuf);
20814
      if (error != NULL) {
20815
        error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
20816
        mg_snprintf(NULL,
20817
                    NULL, /* No truncation check for error buffers */
20818
                    error->text,
20819
                    error->text_buffer_size,
20820
                    "Error in script %s: %s",
20821
                    config_options[DOCUMENT_ROOT].name,
20822
                    ebuf);
20823
      }
20824
      pthread_mutex_unlock(&ctx->lua_bg_mutex);
20825
20826
      free_context(ctx);
20827
      pthread_setspecific(sTlsKey, NULL);
20828
      return NULL;
20829
    }
20830
20831
    /* state remains valid */
20832
    ctx->lua_background_state = (void *)state;
20833
    pthread_mutex_unlock(&ctx->lua_bg_mutex);
20834
20835
  } else {
20836
    ctx->lua_background_state = 0;
20837
  }
20838
#endif
20839
20840
  /* Step by step initialization of ctx - depending on build options */
20841
2
#if !defined(NO_FILESYSTEMS)
20842
2
  if (!set_gpass_option(ctx, NULL)) {
20843
0
    const char *err_msg = "Invalid global password file";
20844
    /* Fatal error - abort start. */
20845
0
    mg_cry_ctx_internal(ctx, "%s", err_msg);
20846
20847
0
    if (error != NULL) {
20848
0
      error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
20849
0
      mg_snprintf(NULL,
20850
0
                  NULL, /* No truncation check for error buffers */
20851
0
                  error->text,
20852
0
                  error->text_buffer_size,
20853
0
                  "%s",
20854
0
                  err_msg);
20855
0
    }
20856
0
    free_context(ctx);
20857
0
    pthread_setspecific(sTlsKey, NULL);
20858
0
    return NULL;
20859
0
  }
20860
2
#endif
20861
20862
#if defined(USE_MBEDTLS)
20863
  if (!mg_sslctx_init(ctx, NULL)) {
20864
    const char *err_msg = "Error initializing SSL context";
20865
    /* Fatal error - abort start. */
20866
    mg_cry_ctx_internal(ctx, "%s", err_msg);
20867
20868
    if (error != NULL) {
20869
      error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
20870
      mg_snprintf(NULL,
20871
                  NULL, /* No truncation check for error buffers */
20872
                  error->text,
20873
                  error->text_buffer_size,
20874
                  "%s",
20875
                  err_msg);
20876
    }
20877
20878
    free_context(ctx);
20879
    pthread_setspecific(sTlsKey, NULL);
20880
    return NULL;
20881
  }
20882
20883
#elif !defined(NO_SSL)
20884
2
  if (!init_ssl_ctx(ctx, NULL)) {
20885
0
    const char *err_msg = "Error initializing SSL context";
20886
    /* Fatal error - abort start. */
20887
0
    mg_cry_ctx_internal(ctx, "%s", err_msg);
20888
20889
0
    if (error != NULL) {
20890
0
      error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
20891
0
      mg_snprintf(NULL,
20892
0
                  NULL, /* No truncation check for error buffers */
20893
0
                  error->text,
20894
0
                  error->text_buffer_size,
20895
0
                  "%s",
20896
0
                  err_msg);
20897
0
    }
20898
20899
0
    free_context(ctx);
20900
0
    pthread_setspecific(sTlsKey, NULL);
20901
0
    return NULL;
20902
0
  }
20903
2
#endif
20904
20905
2
  if (!set_ports_option(ctx)) {
20906
0
    const char *err_msg = "Failed to setup server ports";
20907
    /* Fatal error - abort start. */
20908
0
    mg_cry_ctx_internal(ctx, "%s", err_msg);
20909
20910
0
    if (error != NULL) {
20911
0
      error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
20912
0
      mg_snprintf(NULL,
20913
0
                  NULL, /* No truncation check for error buffers */
20914
0
                  error->text,
20915
0
                  error->text_buffer_size,
20916
0
                  "%s",
20917
0
                  err_msg);
20918
0
    }
20919
20920
0
    free_context(ctx);
20921
0
    pthread_setspecific(sTlsKey, NULL);
20922
0
    return NULL;
20923
0
  }
20924
20925
2
#if !defined(_WIN32) && !defined(__ZEPHYR__)
20926
2
  if (!set_uid_option(ctx)) {
20927
0
    const char *err_msg = "Failed to run as configured user";
20928
    /* Fatal error - abort start. */
20929
0
    mg_cry_ctx_internal(ctx, "%s", err_msg);
20930
20931
0
    if (error != NULL) {
20932
0
      error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
20933
0
      mg_snprintf(NULL,
20934
0
                  NULL, /* No truncation check for error buffers */
20935
0
                  error->text,
20936
0
                  error->text_buffer_size,
20937
0
                  "%s",
20938
0
                  err_msg);
20939
0
    }
20940
20941
0
    free_context(ctx);
20942
0
    pthread_setspecific(sTlsKey, NULL);
20943
0
    return NULL;
20944
0
  }
20945
2
#endif
20946
20947
2
  if (!set_acl_option(ctx)) {
20948
0
    const char *err_msg = "Failed to setup access control list";
20949
    /* Fatal error - abort start. */
20950
0
    mg_cry_ctx_internal(ctx, "%s", err_msg);
20951
20952
0
    if (error != NULL) {
20953
0
      error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
20954
0
      mg_snprintf(NULL,
20955
0
                  NULL, /* No truncation check for error buffers */
20956
0
                  error->text,
20957
0
                  error->text_buffer_size,
20958
0
                  "%s",
20959
0
                  err_msg);
20960
0
    }
20961
20962
0
    free_context(ctx);
20963
0
    pthread_setspecific(sTlsKey, NULL);
20964
0
    return NULL;
20965
0
  }
20966
20967
2
  ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
20968
2
  ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
20969
2
                                                     sizeof(pthread_t),
20970
2
                                                     ctx);
20971
20972
2
  if (ctx->worker_threadids == NULL) {
20973
0
    const char *err_msg = "Not enough memory for worker thread ID array";
20974
0
    mg_cry_ctx_internal(ctx, "%s", err_msg);
20975
20976
0
    if (error != NULL) {
20977
0
      error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
20978
0
      error->code_sub =
20979
0
          (unsigned)ctx->cfg_worker_threads * (unsigned)sizeof(pthread_t);
20980
0
      mg_snprintf(NULL,
20981
0
                  NULL, /* No truncation check for error buffers */
20982
0
                  error->text,
20983
0
                  error->text_buffer_size,
20984
0
                  "%s",
20985
0
                  err_msg);
20986
0
    }
20987
20988
0
    free_context(ctx);
20989
0
    pthread_setspecific(sTlsKey, NULL);
20990
0
    return NULL;
20991
0
  }
20992
2
  ctx->worker_connections =
20993
2
      (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
20994
2
                                            sizeof(struct mg_connection),
20995
2
                                            ctx);
20996
2
  if (ctx->worker_connections == NULL) {
20997
0
    const char *err_msg =
20998
0
        "Not enough memory for worker thread connection array";
20999
0
    mg_cry_ctx_internal(ctx, "%s", err_msg);
21000
21001
0
    if (error != NULL) {
21002
0
      error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
21003
0
      error->code_sub = (unsigned)ctx->cfg_worker_threads
21004
0
                        * (unsigned)sizeof(struct mg_connection);
21005
0
      mg_snprintf(NULL,
21006
0
                  NULL, /* No truncation check for error buffers */
21007
0
                  error->text,
21008
0
                  error->text_buffer_size,
21009
0
                  "%s",
21010
0
                  err_msg);
21011
0
    }
21012
21013
0
    free_context(ctx);
21014
0
    pthread_setspecific(sTlsKey, NULL);
21015
0
    return NULL;
21016
0
  }
21017
21018
#if defined(ALTERNATIVE_QUEUE)
21019
  ctx->client_wait_events =
21020
      (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
21021
                             sizeof(ctx->client_wait_events[0]),
21022
                             ctx);
21023
  if (ctx->client_wait_events == NULL) {
21024
    const char *err_msg = "Not enough memory for worker event array";
21025
    mg_cry_ctx_internal(ctx, "%s", err_msg);
21026
    mg_free(ctx->worker_threadids);
21027
21028
    if (error != NULL) {
21029
      error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
21030
      error->code_sub = (unsigned)ctx->cfg_worker_threads
21031
                        * (unsigned)sizeof(ctx->client_wait_events[0]);
21032
      mg_snprintf(NULL,
21033
                  NULL, /* No truncation check for error buffers */
21034
                  error->text,
21035
                  error->text_buffer_size,
21036
                  "%s",
21037
                  err_msg);
21038
    }
21039
21040
    free_context(ctx);
21041
    pthread_setspecific(sTlsKey, NULL);
21042
    return NULL;
21043
  }
21044
21045
  ctx->client_socks =
21046
      (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
21047
                                     sizeof(ctx->client_socks[0]),
21048
                                     ctx);
21049
  if (ctx->client_socks == NULL) {
21050
    const char *err_msg = "Not enough memory for worker socket array";
21051
    mg_cry_ctx_internal(ctx, "%s", err_msg);
21052
    mg_free(ctx->client_wait_events);
21053
    mg_free(ctx->worker_threadids);
21054
21055
    if (error != NULL) {
21056
      error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
21057
      error->code_sub = (unsigned)ctx->cfg_worker_threads
21058
                        * (unsigned)sizeof(ctx->client_socks[0]);
21059
      mg_snprintf(NULL,
21060
                  NULL, /* No truncation check for error buffers */
21061
                  error->text,
21062
                  error->text_buffer_size,
21063
                  "%s",
21064
                  err_msg);
21065
    }
21066
21067
    free_context(ctx);
21068
    pthread_setspecific(sTlsKey, NULL);
21069
    return NULL;
21070
  }
21071
21072
  for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
21073
    ctx->client_wait_events[i] = event_create();
21074
    if (ctx->client_wait_events[i] == 0) {
21075
      const char *err_msg = "Error creating worker event %i";
21076
      mg_cry_ctx_internal(ctx, err_msg, i);
21077
      while (i > 0) {
21078
        i--;
21079
        event_destroy(ctx->client_wait_events[i]);
21080
      }
21081
      mg_free(ctx->client_socks);
21082
      mg_free(ctx->client_wait_events);
21083
      mg_free(ctx->worker_threadids);
21084
21085
      if (error != NULL) {
21086
        error->code = MG_ERROR_DATA_CODE_OS_ERROR;
21087
        error->code_sub = ERRNO;
21088
        mg_snprintf(NULL,
21089
                    NULL, /* No truncation check for error buffers */
21090
                    error->text,
21091
                    error->text_buffer_size,
21092
                    err_msg,
21093
                    i);
21094
      }
21095
21096
      free_context(ctx);
21097
      pthread_setspecific(sTlsKey, NULL);
21098
      return NULL;
21099
    }
21100
  }
21101
#endif
21102
21103
#if defined(USE_TIMERS)
21104
  if (timers_init(ctx) != 0) {
21105
    const char *err_msg = "Error creating timers";
21106
    mg_cry_ctx_internal(ctx, "%s", err_msg);
21107
21108
    if (error != NULL) {
21109
      error->code = MG_ERROR_DATA_CODE_OS_ERROR;
21110
      error->code_sub = ERRNO;
21111
      mg_snprintf(NULL,
21112
                  NULL, /* No truncation check for error buffers */
21113
                  error->text,
21114
                  error->text_buffer_size,
21115
                  "%s",
21116
                  err_msg);
21117
    }
21118
21119
    free_context(ctx);
21120
    pthread_setspecific(sTlsKey, NULL);
21121
    return NULL;
21122
  }
21123
#endif
21124
21125
  /* Context has been created - init user libraries */
21126
2
  if (ctx->callbacks.init_context) {
21127
0
    ctx->callbacks.init_context(ctx);
21128
0
  }
21129
21130
  /* From now, the context is successfully created.
21131
   * When it is destroyed, the exit callback should be called. */
21132
2
  ctx->callbacks.exit_context = exit_callback;
21133
2
  ctx->context_type = CONTEXT_SERVER; /* server context */
21134
21135
  /* Start worker threads */
21136
102
  for (i = 0; i < ctx->cfg_worker_threads; i++) {
21137
    /* worker_thread sets up the other fields */
21138
100
    ctx->worker_connections[i].phys_ctx = ctx;
21139
100
    if (mg_start_thread_with_id(worker_thread,
21140
100
                                &ctx->worker_connections[i],
21141
100
                                &ctx->worker_threadids[i])
21142
100
        != 0) {
21143
21144
0
      long error_no = (long)ERRNO;
21145
21146
      /* thread was not created */
21147
0
      if (i > 0) {
21148
        /* If the second, third, ... thread cannot be created, set a
21149
         * warning, but keep running. */
21150
0
        mg_cry_ctx_internal(ctx,
21151
0
                            "Cannot start worker thread %i: error %ld",
21152
0
                            i + 1,
21153
0
                            error_no);
21154
21155
        /* If the server initialization should stop here, all
21156
         * threads that have already been created must be stopped
21157
         * first, before any free_context(ctx) call.
21158
         */
21159
21160
0
      } else {
21161
        /* If the first worker thread cannot be created, stop
21162
         * initialization and free the entire server context. */
21163
0
        mg_cry_ctx_internal(ctx,
21164
0
                            "Cannot create threads: error %ld",
21165
0
                            error_no);
21166
21167
0
        if (error != NULL) {
21168
0
          error->code = MG_ERROR_DATA_CODE_OS_ERROR;
21169
0
          error->code_sub = (unsigned)error_no;
21170
0
          mg_snprintf(
21171
0
              NULL,
21172
0
              NULL, /* No truncation check for error buffers */
21173
0
              error->text,
21174
0
              error->text_buffer_size,
21175
0
              "Cannot create first worker thread: error %ld",
21176
0
              error_no);
21177
0
        }
21178
21179
0
        free_context(ctx);
21180
0
        pthread_setspecific(sTlsKey, NULL);
21181
0
        return NULL;
21182
0
      }
21183
0
      break;
21184
0
    }
21185
100
  }
21186
21187
  /* Start master (listening) thread */
21188
2
  mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
21189
21190
2
  pthread_setspecific(sTlsKey, NULL);
21191
2
  return ctx;
21192
2
}
21193
21194
21195
CIVETWEB_API struct mg_context *
21196
mg_start(const struct mg_callbacks *callbacks,
21197
         void *user_data,
21198
         const char **options)
21199
2
{
21200
2
  struct mg_init_data init = {0};
21201
2
  init.callbacks = callbacks;
21202
2
  init.user_data = user_data;
21203
2
  init.configuration_options = options;
21204
21205
2
  return mg_start2(&init, NULL);
21206
2
}
21207
21208
21209
/* Add an additional domain to an already running web server. */
21210
CIVETWEB_API int
21211
mg_start_domain2(struct mg_context *ctx,
21212
                 const char **options,
21213
                 struct mg_error_data *error)
21214
0
{
21215
0
  const char *name;
21216
0
  const char *value;
21217
0
  const char *default_value;
21218
0
  struct mg_domain_context *new_dom;
21219
0
  struct mg_domain_context *dom;
21220
0
  int idx, i;
21221
21222
0
  if (error != NULL) {
21223
0
    error->code = MG_ERROR_DATA_CODE_OK;
21224
0
    error->code_sub = 0;
21225
0
    if (error->text_buffer_size > 0) {
21226
0
      *error->text = 0;
21227
0
    }
21228
0
  }
21229
21230
0
  if ((ctx == NULL) || (options == NULL)) {
21231
0
    if (error != NULL) {
21232
0
      error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
21233
0
      mg_snprintf(NULL,
21234
0
                  NULL, /* No truncation check for error buffers */
21235
0
                  error->text,
21236
0
                  error->text_buffer_size,
21237
0
                  "%s",
21238
0
                  "Invalid parameters");
21239
0
    }
21240
0
    return -1;
21241
0
  }
21242
21243
0
  if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
21244
0
    if (error != NULL) {
21245
0
      error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
21246
0
      mg_snprintf(NULL,
21247
0
                  NULL, /* No truncation check for error buffers */
21248
0
                  error->text,
21249
0
                  error->text_buffer_size,
21250
0
                  "%s",
21251
0
                  "Server already stopped");
21252
0
    }
21253
0
    return -7;
21254
0
  }
21255
21256
0
  new_dom = (struct mg_domain_context *)
21257
0
      mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
21258
21259
0
  if (!new_dom) {
21260
    /* Out of memory */
21261
0
    if (error != NULL) {
21262
0
      error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
21263
0
      error->code_sub = (unsigned)sizeof(struct mg_domain_context);
21264
0
      mg_snprintf(NULL,
21265
0
                  NULL, /* No truncation check for error buffers */
21266
0
                  error->text,
21267
0
                  error->text_buffer_size,
21268
0
                  "%s",
21269
0
                  "Out or memory");
21270
0
    }
21271
0
    return -6;
21272
0
  }
21273
21274
  /* Store options - TODO: unite duplicate code */
21275
0
  while (options && (name = *options++) != NULL) {
21276
0
    idx = get_option_index(name);
21277
0
    if (idx == -1) {
21278
0
      mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
21279
0
      if (error != NULL) {
21280
0
        error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
21281
0
        error->code_sub = (unsigned)-1;
21282
0
        mg_snprintf(NULL,
21283
0
                    NULL, /* No truncation check for error buffers */
21284
0
                    error->text,
21285
0
                    error->text_buffer_size,
21286
0
                    "Invalid option: %s",
21287
0
                    name);
21288
0
      }
21289
0
      mg_free(new_dom);
21290
0
      return -2;
21291
0
    } else if ((value = *options++) == NULL) {
21292
0
      mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
21293
0
      if (error != NULL) {
21294
0
        error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
21295
0
        error->code_sub = idx;
21296
0
        mg_snprintf(NULL,
21297
0
                    NULL, /* No truncation check for error buffers */
21298
0
                    error->text,
21299
0
                    error->text_buffer_size,
21300
0
                    "Invalid option value: %s",
21301
0
                    name);
21302
0
      }
21303
0
      mg_free(new_dom);
21304
0
      return -2;
21305
0
    }
21306
0
    if (new_dom->config[idx] != NULL) {
21307
      /* Duplicate option: Later values overwrite earlier ones. */
21308
0
      mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
21309
0
      mg_free(new_dom->config[idx]);
21310
0
    }
21311
0
    new_dom->config[idx] = mg_strdup_ctx(value, ctx);
21312
0
    DEBUG_TRACE("[%s] -> [%s]", name, value);
21313
0
  }
21314
21315
  /* Authentication domain is mandatory */
21316
  /* TODO: Maybe use a new option hostname? */
21317
0
  if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
21318
0
    mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
21319
0
    if (error != NULL) {
21320
0
      error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
21321
0
      error->code_sub = AUTHENTICATION_DOMAIN;
21322
0
      mg_snprintf(NULL,
21323
0
                  NULL, /* No truncation check for error buffers */
21324
0
                  error->text,
21325
0
                  error->text_buffer_size,
21326
0
                  "Mandatory option %s missing",
21327
0
                  config_options[AUTHENTICATION_DOMAIN].name);
21328
0
    }
21329
0
    mg_free(new_dom);
21330
0
    return -4;
21331
0
  }
21332
21333
  /* Set default value if needed. Take the config value from
21334
   * ctx as a default value. */
21335
0
  for (i = 0; config_options[i].name != NULL; i++) {
21336
0
    default_value = ctx->dd.config[i];
21337
0
    if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
21338
0
      new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
21339
0
    }
21340
0
  }
21341
21342
0
  new_dom->handlers = NULL;
21343
0
  new_dom->next = NULL;
21344
0
  new_dom->nonce_count = 0;
21345
0
  new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
21346
21347
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
21348
  new_dom->shared_lua_websockets = NULL;
21349
#endif
21350
21351
0
#if !defined(NO_SSL) && !defined(USE_MBEDTLS)
21352
0
  if (!init_ssl_ctx(ctx, new_dom)) {
21353
    /* Init SSL failed */
21354
0
    if (error != NULL) {
21355
0
      error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
21356
0
      mg_snprintf(NULL,
21357
0
                  NULL, /* No truncation check for error buffers */
21358
0
                  error->text,
21359
0
                  error->text_buffer_size,
21360
0
                  "%s",
21361
0
                  "Initializing SSL context failed");
21362
0
    }
21363
0
    mg_free(new_dom);
21364
0
    return -3;
21365
0
  }
21366
0
#endif
21367
21368
  /* Add element to linked list. */
21369
0
  mg_lock_context(ctx);
21370
21371
0
  idx = 0;
21372
0
  dom = &(ctx->dd);
21373
0
  for (;;) {
21374
0
    if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
21375
0
                       dom->config[AUTHENTICATION_DOMAIN])) {
21376
      /* Domain collision */
21377
0
      mg_cry_ctx_internal(ctx,
21378
0
                          "domain %s already in use",
21379
0
                          new_dom->config[AUTHENTICATION_DOMAIN]);
21380
0
      if (error != NULL) {
21381
0
        error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
21382
0
        mg_snprintf(NULL,
21383
0
                    NULL, /* No truncation check for error buffers */
21384
0
                    error->text,
21385
0
                    error->text_buffer_size,
21386
0
                    "Domain %s specified by %s is already in use",
21387
0
                    new_dom->config[AUTHENTICATION_DOMAIN],
21388
0
                    config_options[AUTHENTICATION_DOMAIN].name);
21389
0
      }
21390
0
      mg_free(new_dom);
21391
0
      mg_unlock_context(ctx);
21392
0
      return -5;
21393
0
    }
21394
21395
    /* Count number of domains */
21396
0
    idx++;
21397
21398
0
    if (dom->next == NULL) {
21399
0
      dom->next = new_dom;
21400
0
      break;
21401
0
    }
21402
0
    dom = dom->next;
21403
0
  }
21404
21405
0
  mg_unlock_context(ctx);
21406
21407
  /* Return domain number */
21408
0
  return idx;
21409
0
}
21410
21411
21412
CIVETWEB_API int
21413
mg_start_domain(struct mg_context *ctx, const char **options)
21414
0
{
21415
0
  return mg_start_domain2(ctx, options, NULL);
21416
0
}
21417
21418
21419
/* Feature check API function */
21420
CIVETWEB_API unsigned
21421
mg_check_feature(unsigned feature)
21422
2
{
21423
2
  static const unsigned feature_set = 0
21424
  /* Set bits for available features according to API documentation.
21425
   * This bit mask is created at compile time, according to the active
21426
   * preprocessor defines. It is a single const value at runtime. */
21427
2
#if !defined(NO_FILES)
21428
2
                                      | MG_FEATURES_FILES
21429
2
#endif
21430
2
#if !defined(NO_SSL) || defined(USE_MBEDTLS)
21431
2
                                      | MG_FEATURES_SSL
21432
2
#endif
21433
2
#if !defined(NO_CGI)
21434
2
                                      | MG_FEATURES_CGI
21435
2
#endif
21436
#if defined(USE_IPV6)
21437
                                      | MG_FEATURES_IPV6
21438
#endif
21439
#if defined(USE_WEBSOCKET)
21440
                                      | MG_FEATURES_WEBSOCKET
21441
#endif
21442
#if defined(USE_LUA)
21443
                                      | MG_FEATURES_LUA
21444
#endif
21445
#if defined(USE_DUKTAPE)
21446
                                      | MG_FEATURES_SSJS
21447
#endif
21448
2
#if !defined(NO_CACHING)
21449
2
                                      | MG_FEATURES_CACHE
21450
2
#endif
21451
#if defined(USE_SERVER_STATS)
21452
                                      | MG_FEATURES_STATS
21453
#endif
21454
#if defined(USE_ZLIB)
21455
                                      | MG_FEATURES_COMPRESSION
21456
#endif
21457
#if defined(USE_HTTP2)
21458
                                      | MG_FEATURES_HTTP2
21459
#endif
21460
#if defined(USE_X_DOM_SOCKET)
21461
                                      | MG_FEATURES_X_DOMAIN_SOCKET
21462
#endif
21463
21464
  /* Set some extra bits not defined in the API documentation.
21465
   * These bits may change without further notice. */
21466
#if defined(MG_LEGACY_INTERFACE)
21467
                                      | 0x80000000u
21468
#endif
21469
#if defined(MG_EXPERIMENTAL_INTERFACES)
21470
                                      | 0x40000000u
21471
#endif
21472
2
#if !defined(NO_RESPONSE_BUFFERING)
21473
2
                                      | 0x20000000u
21474
2
#endif
21475
#if defined(MEMORY_DEBUGGING)
21476
                                      | 0x10000000u
21477
#endif
21478
2
      ;
21479
2
  return (feature & feature_set);
21480
2
}
21481
21482
21483
static size_t
21484
mg_str_append(char **dst, char *end, const char *src)
21485
0
{
21486
0
  size_t len = strlen(src);
21487
0
  if (*dst != end) {
21488
    /* Append src if enough space, or close dst. */
21489
0
    if ((size_t)(end - *dst) > len) {
21490
0
      strcpy(*dst, src);
21491
0
      *dst += len;
21492
0
    } else {
21493
0
      *dst = end;
21494
0
    }
21495
0
  }
21496
0
  return len;
21497
0
}
21498
21499
21500
/* Get system information. It can be printed or stored by the caller.
21501
 * Return the size of available information. */
21502
CIVETWEB_API int
21503
mg_get_system_info(char *buffer, int buflen)
21504
0
{
21505
0
  char *end, *append_eoobj = NULL, block[256];
21506
0
  size_t system_info_length = 0;
21507
21508
#if defined(_WIN32)
21509
  static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
21510
#else
21511
0
  static const char eol[] = "\n", eoobj[] = "\n}\n";
21512
0
#endif
21513
21514
0
  if ((buffer == NULL) || (buflen < 1)) {
21515
0
    buflen = 0;
21516
0
    end = buffer;
21517
0
  } else {
21518
0
    *buffer = 0;
21519
0
    end = buffer + buflen;
21520
0
  }
21521
0
  if (buflen > (int)(sizeof(eoobj) - 1)) {
21522
    /* has enough space to append eoobj */
21523
0
    append_eoobj = buffer;
21524
0
    if (end) {
21525
0
      end -= sizeof(eoobj) - 1;
21526
0
    }
21527
0
  }
21528
21529
0
  system_info_length += mg_str_append(&buffer, end, "{");
21530
21531
  /* Server version */
21532
0
  {
21533
0
    const char *version = mg_version();
21534
0
    mg_snprintf(NULL,
21535
0
                NULL,
21536
0
                block,
21537
0
                sizeof(block),
21538
0
                "%s\"version\" : \"%s\"",
21539
0
                eol,
21540
0
                version);
21541
0
    system_info_length += mg_str_append(&buffer, end, block);
21542
0
  }
21543
21544
  /* System info */
21545
0
  {
21546
#if defined(_WIN32)
21547
    DWORD dwVersion = 0;
21548
    DWORD dwMajorVersion = 0;
21549
    DWORD dwMinorVersion = 0;
21550
    SYSTEM_INFO si;
21551
21552
    GetSystemInfo(&si);
21553
21554
#if defined(_MSC_VER)
21555
#pragma warning(push)
21556
    /* GetVersion was declared deprecated */
21557
#pragma warning(disable : 4996)
21558
#endif
21559
    dwVersion = GetVersion();
21560
#if defined(_MSC_VER)
21561
#pragma warning(pop)
21562
#endif
21563
21564
    dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
21565
    dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
21566
21567
    mg_snprintf(NULL,
21568
                NULL,
21569
                block,
21570
                sizeof(block),
21571
                ",%s\"os\" : \"Windows %u.%u\"",
21572
                eol,
21573
                (unsigned)dwMajorVersion,
21574
                (unsigned)dwMinorVersion);
21575
    system_info_length += mg_str_append(&buffer, end, block);
21576
21577
    mg_snprintf(NULL,
21578
                NULL,
21579
                block,
21580
                sizeof(block),
21581
                ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
21582
                eol,
21583
                (unsigned)si.wProcessorArchitecture,
21584
                (unsigned)si.dwNumberOfProcessors,
21585
                (unsigned)si.dwActiveProcessorMask);
21586
    system_info_length += mg_str_append(&buffer, end, block);
21587
#elif defined(__ZEPHYR__)
21588
    mg_snprintf(NULL,
21589
                NULL,
21590
                block,
21591
                sizeof(block),
21592
                ",%s\"os\" : \"%s %s\"",
21593
                eol,
21594
                "Zephyr OS",
21595
                ZEPHYR_VERSION);
21596
    system_info_length += mg_str_append(&buffer, end, block);
21597
#else
21598
0
    struct utsname name;
21599
0
    memset(&name, 0, sizeof(name));
21600
0
    uname(&name);
21601
21602
0
    mg_snprintf(NULL,
21603
0
                NULL,
21604
0
                block,
21605
0
                sizeof(block),
21606
0
                ",%s\"os\" : \"%s %s (%s) - %s\"",
21607
0
                eol,
21608
0
                name.sysname,
21609
0
                name.version,
21610
0
                name.release,
21611
0
                name.machine);
21612
0
    system_info_length += mg_str_append(&buffer, end, block);
21613
0
#endif
21614
0
  }
21615
21616
  /* Features */
21617
0
  {
21618
0
    mg_snprintf(NULL,
21619
0
                NULL,
21620
0
                block,
21621
0
                sizeof(block),
21622
0
                ",%s\"features\" : %lu"
21623
0
                ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
21624
0
                eol,
21625
0
                (unsigned long)mg_check_feature(0xFFFFFFFFu),
21626
0
                eol,
21627
0
                mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
21628
0
                mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
21629
0
                mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
21630
0
                mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
21631
0
                mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
21632
0
                                                        : "",
21633
0
                mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
21634
0
                mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
21635
0
                mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
21636
0
                mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
21637
0
    system_info_length += mg_str_append(&buffer, end, block);
21638
21639
#if defined(USE_LUA)
21640
    mg_snprintf(NULL,
21641
                NULL,
21642
                block,
21643
                sizeof(block),
21644
                ",%s\"lua_version\" : \"%u (%s)\"",
21645
                eol,
21646
                (unsigned)LUA_VERSION_NUM,
21647
                LUA_RELEASE);
21648
    system_info_length += mg_str_append(&buffer, end, block);
21649
#endif
21650
#if defined(USE_DUKTAPE)
21651
    mg_snprintf(NULL,
21652
                NULL,
21653
                block,
21654
                sizeof(block),
21655
                ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
21656
                eol,
21657
                (unsigned)DUK_VERSION / 10000,
21658
                ((unsigned)DUK_VERSION / 100) % 100,
21659
                (unsigned)DUK_VERSION % 100);
21660
    system_info_length += mg_str_append(&buffer, end, block);
21661
#endif
21662
0
  }
21663
21664
  /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
21665
0
  {
21666
#if defined(BUILD_DATE)
21667
    const char *bd = BUILD_DATE;
21668
#else
21669
#if defined(GCC_DIAGNOSTIC)
21670
#if GCC_VERSION >= 40900
21671
#pragma GCC diagnostic push
21672
    /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
21673
     * does not work in some versions. If "BUILD_DATE" is defined to some
21674
     * string, it is used instead of __DATE__. */
21675
#pragma GCC diagnostic ignored "-Wdate-time"
21676
#endif
21677
#endif
21678
0
    const char *bd = __DATE__;
21679
#if defined(GCC_DIAGNOSTIC)
21680
#if GCC_VERSION >= 40900
21681
#pragma GCC diagnostic pop
21682
#endif
21683
#endif
21684
0
#endif
21685
21686
0
    mg_snprintf(
21687
0
        NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
21688
21689
0
    system_info_length += mg_str_append(&buffer, end, block);
21690
0
  }
21691
21692
  /* Compiler information */
21693
  /* http://sourceforge.net/p/predef/wiki/Compilers/ */
21694
0
  {
21695
#if defined(_MSC_VER)
21696
    mg_snprintf(NULL,
21697
                NULL,
21698
                block,
21699
                sizeof(block),
21700
                ",%s\"compiler\" : \"MSC: %u (%u)\"",
21701
                eol,
21702
                (unsigned)_MSC_VER,
21703
                (unsigned)_MSC_FULL_VER);
21704
    system_info_length += mg_str_append(&buffer, end, block);
21705
#elif defined(__MINGW64__)
21706
    mg_snprintf(NULL,
21707
                NULL,
21708
                block,
21709
                sizeof(block),
21710
                ",%s\"compiler\" : \"MinGW64: %u.%u\"",
21711
                eol,
21712
                (unsigned)__MINGW64_VERSION_MAJOR,
21713
                (unsigned)__MINGW64_VERSION_MINOR);
21714
    system_info_length += mg_str_append(&buffer, end, block);
21715
    mg_snprintf(NULL,
21716
                NULL,
21717
                block,
21718
                sizeof(block),
21719
                ",%s\"compiler\" : \"MinGW32: %u.%u\"",
21720
                eol,
21721
                (unsigned)__MINGW32_MAJOR_VERSION,
21722
                (unsigned)__MINGW32_MINOR_VERSION);
21723
    system_info_length += mg_str_append(&buffer, end, block);
21724
#elif defined(__MINGW32__)
21725
    mg_snprintf(NULL,
21726
                NULL,
21727
                block,
21728
                sizeof(block),
21729
                ",%s\"compiler\" : \"MinGW32: %u.%u\"",
21730
                eol,
21731
                (unsigned)__MINGW32_MAJOR_VERSION,
21732
                (unsigned)__MINGW32_MINOR_VERSION);
21733
    system_info_length += mg_str_append(&buffer, end, block);
21734
#elif defined(__clang__)
21735
0
    mg_snprintf(NULL,
21736
0
                NULL,
21737
0
                block,
21738
0
                sizeof(block),
21739
0
                ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
21740
0
                eol,
21741
0
                __clang_major__,
21742
0
                __clang_minor__,
21743
0
                __clang_patchlevel__,
21744
0
                __clang_version__);
21745
0
    system_info_length += mg_str_append(&buffer, end, block);
21746
#elif defined(__GNUC__)
21747
    mg_snprintf(NULL,
21748
                NULL,
21749
                block,
21750
                sizeof(block),
21751
                ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
21752
                eol,
21753
                (unsigned)__GNUC__,
21754
                (unsigned)__GNUC_MINOR__,
21755
                (unsigned)__GNUC_PATCHLEVEL__);
21756
    system_info_length += mg_str_append(&buffer, end, block);
21757
#elif defined(__INTEL_COMPILER)
21758
    mg_snprintf(NULL,
21759
                NULL,
21760
                block,
21761
                sizeof(block),
21762
                ",%s\"compiler\" : \"Intel C/C++: %u\"",
21763
                eol,
21764
                (unsigned)__INTEL_COMPILER);
21765
    system_info_length += mg_str_append(&buffer, end, block);
21766
#elif defined(__BORLANDC__)
21767
    mg_snprintf(NULL,
21768
                NULL,
21769
                block,
21770
                sizeof(block),
21771
                ",%s\"compiler\" : \"Borland C: 0x%x\"",
21772
                eol,
21773
                (unsigned)__BORLANDC__);
21774
    system_info_length += mg_str_append(&buffer, end, block);
21775
#elif defined(__SUNPRO_C)
21776
    mg_snprintf(NULL,
21777
                NULL,
21778
                block,
21779
                sizeof(block),
21780
                ",%s\"compiler\" : \"Solaris: 0x%x\"",
21781
                eol,
21782
                (unsigned)__SUNPRO_C);
21783
    system_info_length += mg_str_append(&buffer, end, block);
21784
#else
21785
    mg_snprintf(NULL,
21786
                NULL,
21787
                block,
21788
                sizeof(block),
21789
                ",%s\"compiler\" : \"other\"",
21790
                eol);
21791
    system_info_length += mg_str_append(&buffer, end, block);
21792
#endif
21793
0
  }
21794
21795
  /* Determine 32/64 bit data mode.
21796
   * see https://en.wikipedia.org/wiki/64-bit_computing */
21797
0
  {
21798
0
    mg_snprintf(NULL,
21799
0
                NULL,
21800
0
                block,
21801
0
                sizeof(block),
21802
0
                ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
21803
0
                "char:%u/%u, "
21804
0
                "ptr:%u, size:%u, time:%u\"",
21805
0
                eol,
21806
0
                (unsigned)sizeof(short),
21807
0
                (unsigned)sizeof(int),
21808
0
                (unsigned)sizeof(long),
21809
0
                (unsigned)sizeof(long long),
21810
0
                (unsigned)sizeof(float),
21811
0
                (unsigned)sizeof(double),
21812
0
                (unsigned)sizeof(long double),
21813
0
                (unsigned)sizeof(char),
21814
0
                (unsigned)sizeof(wchar_t),
21815
0
                (unsigned)sizeof(void *),
21816
0
                (unsigned)sizeof(size_t),
21817
0
                (unsigned)sizeof(time_t));
21818
0
    system_info_length += mg_str_append(&buffer, end, block);
21819
0
  }
21820
21821
  /* Terminate string */
21822
0
  if (append_eoobj) {
21823
0
    strcat(append_eoobj, eoobj);
21824
0
  }
21825
0
  system_info_length += sizeof(eoobj) - 1;
21826
21827
0
  return (int)system_info_length;
21828
0
}
21829
21830
21831
/* Get context information. It can be printed or stored by the caller.
21832
 * Return the size of available information. */
21833
CIVETWEB_API int
21834
mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
21835
0
{
21836
#if defined(USE_SERVER_STATS)
21837
  char *end, *append_eoobj = NULL, block[256];
21838
  size_t context_info_length = 0;
21839
21840
#if defined(_WIN32)
21841
  static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
21842
#else
21843
  static const char eol[] = "\n", eoobj[] = "\n}\n";
21844
#endif
21845
  struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
21846
21847
  if ((buffer == NULL) || (buflen < 1)) {
21848
    buflen = 0;
21849
    end = buffer;
21850
  } else {
21851
    *buffer = 0;
21852
    end = buffer + buflen;
21853
  }
21854
  if (buflen > (int)(sizeof(eoobj) - 1)) {
21855
    /* has enough space to append eoobj */
21856
    append_eoobj = buffer;
21857
    end -= sizeof(eoobj) - 1;
21858
  }
21859
21860
  context_info_length += mg_str_append(&buffer, end, "{");
21861
21862
  if (ms) { /* <-- should be always true */
21863
          /* Memory information */
21864
    int blockCount = (int)ms->blockCount;
21865
    int64_t totalMemUsed = ms->totalMemUsed;
21866
    int64_t maxMemUsed = ms->maxMemUsed;
21867
    if (totalMemUsed > maxMemUsed) {
21868
      maxMemUsed = totalMemUsed;
21869
    }
21870
21871
    mg_snprintf(NULL,
21872
                NULL,
21873
                block,
21874
                sizeof(block),
21875
                "%s\"memory\" : {%s"
21876
                "\"blocks\" : %i,%s"
21877
                "\"used\" : %" INT64_FMT ",%s"
21878
                "\"maxUsed\" : %" INT64_FMT "%s"
21879
                "}",
21880
                eol,
21881
                eol,
21882
                blockCount,
21883
                eol,
21884
                totalMemUsed,
21885
                eol,
21886
                maxMemUsed,
21887
                eol);
21888
    context_info_length += mg_str_append(&buffer, end, block);
21889
  }
21890
21891
  if (ctx) {
21892
    /* Declare all variables at begin of the block, to comply
21893
     * with old C standards. */
21894
    char start_time_str[64] = {0};
21895
    char now_str[64] = {0};
21896
    time_t start_time = ctx->start_time;
21897
    time_t now = time(NULL);
21898
    int64_t total_data_read, total_data_written;
21899
    int active_connections = (int)ctx->active_connections;
21900
    int max_active_connections = (int)ctx->max_active_connections;
21901
    int total_connections = (int)ctx->total_connections;
21902
    if (active_connections > max_active_connections) {
21903
      max_active_connections = active_connections;
21904
    }
21905
    if (active_connections > total_connections) {
21906
      total_connections = active_connections;
21907
    }
21908
21909
    /* Connections information */
21910
    mg_snprintf(NULL,
21911
                NULL,
21912
                block,
21913
                sizeof(block),
21914
                ",%s\"connections\" : {%s"
21915
                "\"active\" : %i,%s"
21916
                "\"maxActive\" : %i,%s"
21917
                "\"total\" : %i%s"
21918
                "}",
21919
                eol,
21920
                eol,
21921
                active_connections,
21922
                eol,
21923
                max_active_connections,
21924
                eol,
21925
                total_connections,
21926
                eol);
21927
    context_info_length += mg_str_append(&buffer, end, block);
21928
21929
    /* Queue information */
21930
#if !defined(ALTERNATIVE_QUEUE)
21931
    mg_snprintf(NULL,
21932
                NULL,
21933
                block,
21934
                sizeof(block),
21935
                ",%s\"queue\" : {%s"
21936
                "\"length\" : %i,%s"
21937
                "\"filled\" : %i,%s"
21938
                "\"maxFilled\" : %i,%s"
21939
                "\"full\" : %s%s"
21940
                "}",
21941
                eol,
21942
                eol,
21943
                ctx->sq_size,
21944
                eol,
21945
                ctx->sq_head - ctx->sq_tail,
21946
                eol,
21947
                ctx->sq_max_fill,
21948
                eol,
21949
                (ctx->sq_blocked ? "true" : "false"),
21950
                eol);
21951
    context_info_length += mg_str_append(&buffer, end, block);
21952
#endif
21953
21954
    /* Requests information */
21955
    mg_snprintf(NULL,
21956
                NULL,
21957
                block,
21958
                sizeof(block),
21959
                ",%s\"requests\" : {%s"
21960
                "\"total\" : %lu%s"
21961
                "}",
21962
                eol,
21963
                eol,
21964
                (unsigned long)ctx->total_requests,
21965
                eol);
21966
    context_info_length += mg_str_append(&buffer, end, block);
21967
21968
    /* Data information */
21969
    total_data_read =
21970
        mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
21971
    total_data_written =
21972
        mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
21973
    mg_snprintf(NULL,
21974
                NULL,
21975
                block,
21976
                sizeof(block),
21977
                ",%s\"data\" : {%s"
21978
                "\"read\" : %" INT64_FMT ",%s"
21979
                "\"written\" : %" INT64_FMT "%s"
21980
                "}",
21981
                eol,
21982
                eol,
21983
                total_data_read,
21984
                eol,
21985
                total_data_written,
21986
                eol);
21987
    context_info_length += mg_str_append(&buffer, end, block);
21988
21989
    /* Execution time information */
21990
    gmt_time_string(start_time_str,
21991
                    sizeof(start_time_str) - 1,
21992
                    &start_time);
21993
    gmt_time_string(now_str, sizeof(now_str) - 1, &now);
21994
21995
    mg_snprintf(NULL,
21996
                NULL,
21997
                block,
21998
                sizeof(block),
21999
                ",%s\"time\" : {%s"
22000
                "\"uptime\" : %.0f,%s"
22001
                "\"start\" : \"%s\",%s"
22002
                "\"now\" : \"%s\"%s"
22003
                "}",
22004
                eol,
22005
                eol,
22006
                difftime(now, start_time),
22007
                eol,
22008
                start_time_str,
22009
                eol,
22010
                now_str,
22011
                eol);
22012
    context_info_length += mg_str_append(&buffer, end, block);
22013
  }
22014
22015
  /* Terminate string */
22016
  if (append_eoobj) {
22017
    strcat(append_eoobj, eoobj);
22018
  }
22019
  context_info_length += sizeof(eoobj) - 1;
22020
22021
  return (int)context_info_length;
22022
#else
22023
0
  (void)ctx;
22024
0
  if ((buffer != NULL) && (buflen > 0)) {
22025
0
    *buffer = 0;
22026
0
  }
22027
0
  return 0;
22028
0
#endif
22029
0
}
22030
22031
22032
CIVETWEB_API void
22033
mg_disable_connection_keep_alive(struct mg_connection *conn)
22034
0
{
22035
  /* https://github.com/civetweb/civetweb/issues/727 */
22036
0
  if (conn != NULL) {
22037
0
    conn->must_close = 1;
22038
0
  }
22039
0
}
22040
22041
22042
#if defined(MG_EXPERIMENTAL_INTERFACES)
22043
/* Get connection information. It can be printed or stored by the caller.
22044
 * Return the size of available information. */
22045
CIVETWEB_API int
22046
mg_get_connection_info(const struct mg_context *ctx,
22047
                       int idx,
22048
                       char *buffer,
22049
                       int buflen)
22050
{
22051
  const struct mg_connection *conn;
22052
  const struct mg_request_info *ri;
22053
  char *end, *append_eoobj = NULL, block[256];
22054
  size_t connection_info_length = 0;
22055
  int state = 0;
22056
  const char *state_str = "unknown";
22057
22058
#if defined(_WIN32)
22059
  static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
22060
#else
22061
  static const char eol[] = "\n", eoobj[] = "\n}\n";
22062
#endif
22063
22064
  if ((buffer == NULL) || (buflen < 1)) {
22065
    buflen = 0;
22066
    end = buffer;
22067
  } else {
22068
    *buffer = 0;
22069
    end = buffer + buflen;
22070
  }
22071
  if (buflen > (int)(sizeof(eoobj) - 1)) {
22072
    /* has enough space to append eoobj */
22073
    append_eoobj = buffer;
22074
    end -= sizeof(eoobj) - 1;
22075
  }
22076
22077
  if ((ctx == NULL) || (idx < 0)) {
22078
    /* Parameter error */
22079
    return 0;
22080
  }
22081
22082
  if ((unsigned)idx >= ctx->cfg_worker_threads) {
22083
    /* Out of range */
22084
    return 0;
22085
  }
22086
22087
  /* Take connection [idx]. This connection is not locked in
22088
   * any way, so some other thread might use it. */
22089
  conn = (ctx->worker_connections) + idx;
22090
22091
  /* Initialize output string */
22092
  connection_info_length += mg_str_append(&buffer, end, "{");
22093
22094
  /* Init variables */
22095
  ri = &(conn->request_info);
22096
22097
#if defined(USE_SERVER_STATS)
22098
  state = conn->conn_state;
22099
22100
  /* State as string */
22101
  switch (state) {
22102
  case 0:
22103
    state_str = "undefined";
22104
    break;
22105
  case 1:
22106
    state_str = "not used";
22107
    break;
22108
  case 2:
22109
    state_str = "init";
22110
    break;
22111
  case 3:
22112
    state_str = "ready";
22113
    break;
22114
  case 4:
22115
    state_str = "processing";
22116
    break;
22117
  case 5:
22118
    state_str = "processed";
22119
    break;
22120
  case 6:
22121
    state_str = "to close";
22122
    break;
22123
  case 7:
22124
    state_str = "closing";
22125
    break;
22126
  case 8:
22127
    state_str = "closed";
22128
    break;
22129
  case 9:
22130
    state_str = "done";
22131
    break;
22132
  }
22133
#endif
22134
22135
  /* Connection info */
22136
  if ((state >= 3) && (state < 9)) {
22137
    mg_snprintf(NULL,
22138
                NULL,
22139
                block,
22140
                sizeof(block),
22141
                "%s\"connection\" : {%s"
22142
                "\"remote\" : {%s"
22143
                "\"protocol\" : \"%s\",%s"
22144
                "\"addr\" : \"%s\",%s"
22145
                "\"port\" : %u%s"
22146
                "},%s"
22147
                "\"handled_requests\" : %u%s"
22148
                "}",
22149
                eol,
22150
                eol,
22151
                eol,
22152
                get_proto_name(conn),
22153
                eol,
22154
                ri->remote_addr,
22155
                eol,
22156
                ri->remote_port,
22157
                eol,
22158
                eol,
22159
                conn->handled_requests,
22160
                eol);
22161
    connection_info_length += mg_str_append(&buffer, end, block);
22162
  }
22163
22164
  /* Request info */
22165
  if ((state >= 4) && (state < 6)) {
22166
    mg_snprintf(NULL,
22167
                NULL,
22168
                block,
22169
                sizeof(block),
22170
                "%s%s\"request_info\" : {%s"
22171
                "\"method\" : \"%s\",%s"
22172
                "\"uri\" : \"%s\",%s"
22173
                "\"query\" : %s%s%s%s"
22174
                "}",
22175
                (connection_info_length > 1 ? "," : ""),
22176
                eol,
22177
                eol,
22178
                ri->request_method,
22179
                eol,
22180
                ri->request_uri,
22181
                eol,
22182
                ri->query_string ? "\"" : "",
22183
                ri->query_string ? ri->query_string : "null",
22184
                ri->query_string ? "\"" : "",
22185
                eol);
22186
    connection_info_length += mg_str_append(&buffer, end, block);
22187
  }
22188
22189
  /* Execution time information */
22190
  if ((state >= 2) && (state < 9)) {
22191
    char start_time_str[64] = {0};
22192
    char close_time_str[64] = {0};
22193
    time_t start_time = conn->conn_birth_time;
22194
    time_t close_time = 0;
22195
    double time_diff;
22196
22197
    gmt_time_string(start_time_str,
22198
                    sizeof(start_time_str) - 1,
22199
                    &start_time);
22200
#if defined(USE_SERVER_STATS)
22201
    close_time = conn->conn_close_time;
22202
#endif
22203
    if (close_time != 0) {
22204
      time_diff = difftime(close_time, start_time);
22205
      gmt_time_string(close_time_str,
22206
                      sizeof(close_time_str) - 1,
22207
                      &close_time);
22208
    } else {
22209
      time_t now = time(NULL);
22210
      time_diff = difftime(now, start_time);
22211
      close_time_str[0] = 0; /* or use "now" ? */
22212
    }
22213
22214
    mg_snprintf(NULL,
22215
                NULL,
22216
                block,
22217
                sizeof(block),
22218
                "%s%s\"time\" : {%s"
22219
                "\"uptime\" : %.0f,%s"
22220
                "\"start\" : \"%s\",%s"
22221
                "\"closed\" : \"%s\"%s"
22222
                "}",
22223
                (connection_info_length > 1 ? "," : ""),
22224
                eol,
22225
                eol,
22226
                time_diff,
22227
                eol,
22228
                start_time_str,
22229
                eol,
22230
                close_time_str,
22231
                eol);
22232
    connection_info_length += mg_str_append(&buffer, end, block);
22233
  }
22234
22235
  /* Remote user name */
22236
  if ((ri->remote_user) && (state < 9)) {
22237
    mg_snprintf(NULL,
22238
                NULL,
22239
                block,
22240
                sizeof(block),
22241
                "%s%s\"user\" : {%s"
22242
                "\"name\" : \"%s\",%s"
22243
                "}",
22244
                (connection_info_length > 1 ? "," : ""),
22245
                eol,
22246
                eol,
22247
                ri->remote_user,
22248
                eol);
22249
    connection_info_length += mg_str_append(&buffer, end, block);
22250
  }
22251
22252
  /* Data block */
22253
  if (state >= 3) {
22254
    mg_snprintf(NULL,
22255
                NULL,
22256
                block,
22257
                sizeof(block),
22258
                "%s%s\"data\" : {%s"
22259
                "\"read\" : %" INT64_FMT ",%s"
22260
                "\"written\" : %" INT64_FMT "%s"
22261
                "}",
22262
                (connection_info_length > 1 ? "," : ""),
22263
                eol,
22264
                eol,
22265
                conn->consumed_content,
22266
                eol,
22267
                conn->num_bytes_sent,
22268
                eol);
22269
    connection_info_length += mg_str_append(&buffer, end, block);
22270
  }
22271
22272
  /* State */
22273
  mg_snprintf(NULL,
22274
              NULL,
22275
              block,
22276
              sizeof(block),
22277
              "%s%s\"state\" : \"%s\"",
22278
              (connection_info_length > 1 ? "," : ""),
22279
              eol,
22280
              state_str);
22281
  connection_info_length += mg_str_append(&buffer, end, block);
22282
22283
  /* Terminate string */
22284
  if (append_eoobj) {
22285
    strcat(append_eoobj, eoobj);
22286
  }
22287
  connection_info_length += sizeof(eoobj) - 1;
22288
22289
  return (int)connection_info_length;
22290
}
22291
22292
#if 0
22293
/* Get handler information. It can be printed or stored by the caller.
22294
 * Return the size of available information. */
22295
CIVETWEB_API int
22296
mg_get_handler_info(struct mg_context *ctx,
22297
                       char *buffer,
22298
                       int buflen)
22299
{
22300
    int handler_info_len = 0;
22301
    struct mg_handler_info *tmp_rh;
22302
    mg_lock_context(ctx);
22303
22304
    for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
22305
22306
        if (buflen > handler_info_len+ tmp_rh->uri_len) {
22307
        memcpy(buffer+handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
22308
        }
22309
        handler_info_len += tmp_rh->uri_len;
22310
22311
        switch (tmp_rh->handler_type) {
22312
            case REQUEST_HANDLER:
22313
                (void)tmp_rh->handler;
22314
            break;
22315
            case WEBSOCKET_HANDLER:
22316
        (void)tmp_rh->connect_handler;
22317
       (void) tmp_rh->ready_handler;
22318
       (void) tmp_rh->data_handler;
22319
       (void) tmp_rh->close_handler;
22320
            break;
22321
            case AUTH_HANDLER:
22322
             (void) tmp_rh->auth_handler;
22323
            break;
22324
        }
22325
        (void)cbdata;
22326
    }
22327
22328
    mg_unlock_context(ctx);
22329
    return handler_info_len;
22330
}
22331
#endif
22332
#endif
22333
22334
22335
/* Initialize this library. This function does not need to be thread safe.
22336
 */
22337
CIVETWEB_API unsigned
22338
mg_init_library(unsigned features)
22339
2
{
22340
2
  unsigned features_to_init = mg_check_feature(features & 0xFFu);
22341
2
  unsigned features_inited = features_to_init;
22342
22343
2
  if (mg_init_library_called <= 0) {
22344
    /* Not initialized yet */
22345
2
    if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
22346
0
      return 0;
22347
0
    }
22348
2
  }
22349
22350
2
  mg_global_lock();
22351
22352
2
  if (mg_init_library_called <= 0) {
22353
2
    int i, len;
22354
22355
#if defined(_WIN32)
22356
    int file_mutex_init = 1;
22357
    int wsa = 1;
22358
#else
22359
2
    int mutexattr_init = 1;
22360
2
#endif
22361
2
    int failed = 1;
22362
2
    int key_create = pthread_key_create(&sTlsKey, tls_dtor);
22363
22364
2
    if (key_create == 0) {
22365
#if defined(_WIN32)
22366
      file_mutex_init =
22367
          pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
22368
      if (file_mutex_init == 0) {
22369
        /* Start WinSock */
22370
        WSADATA data;
22371
        failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
22372
      }
22373
#else
22374
2
      mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
22375
2
      if (mutexattr_init == 0) {
22376
2
        failed = pthread_mutexattr_settype(&pthread_mutex_attr,
22377
2
                                           PTHREAD_MUTEX_RECURSIVE);
22378
2
      }
22379
2
#endif
22380
2
    }
22381
22382
2
    if (failed) {
22383
#if defined(_WIN32)
22384
      if (wsa == 0) {
22385
        (void)WSACleanup();
22386
      }
22387
      if (file_mutex_init == 0) {
22388
        (void)pthread_mutex_destroy(&global_log_file_lock);
22389
      }
22390
#else
22391
0
      if (mutexattr_init == 0) {
22392
0
        (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
22393
0
      }
22394
0
#endif
22395
0
      if (key_create == 0) {
22396
0
        (void)pthread_key_delete(sTlsKey);
22397
0
      }
22398
0
      mg_global_unlock();
22399
0
      (void)pthread_mutex_destroy(&global_lock_mutex);
22400
0
      return 0;
22401
0
    }
22402
22403
2
    len = 1;
22404
34
    for (i = 0; http_methods[i].name != NULL; i++) {
22405
32
      size_t sl = strlen(http_methods[i].name);
22406
32
      len += (int)sl;
22407
32
      if (i > 0) {
22408
30
        len += 2;
22409
30
      }
22410
32
    }
22411
2
    all_methods = (char *)mg_malloc(len);
22412
2
    if (!all_methods) {
22413
      /* Must never happen */
22414
0
      mg_global_unlock();
22415
0
      (void)pthread_mutex_destroy(&global_lock_mutex);
22416
0
      return 0;
22417
0
    }
22418
2
    all_methods[0] = 0;
22419
34
    for (i = 0; http_methods[i].name != NULL; i++) {
22420
32
      if (i > 0) {
22421
30
        strcat(all_methods, ", ");
22422
30
        strcat(all_methods, http_methods[i].name);
22423
30
      } else {
22424
2
        strcpy(all_methods, http_methods[i].name);
22425
2
      }
22426
32
    }
22427
2
  }
22428
22429
#if defined(USE_LUA)
22430
  lua_init_optional_libraries();
22431
#endif
22432
22433
2
#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)                      \
22434
2
     || defined(OPENSSL_API_3_0))                                              \
22435
2
    && !defined(NO_SSL)
22436
22437
2
  if (features_to_init & MG_FEATURES_SSL) {
22438
0
    if (!mg_openssl_initialized) {
22439
0
      char ebuf[128];
22440
0
      if (initialize_openssl(ebuf, sizeof(ebuf))) {
22441
0
        mg_openssl_initialized = 1;
22442
0
      } else {
22443
0
        (void)ebuf;
22444
0
        DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
22445
0
        features_inited &= ~((unsigned)(MG_FEATURES_SSL));
22446
0
      }
22447
0
    } else {
22448
      /* ssl already initialized */
22449
0
    }
22450
0
  }
22451
22452
2
#endif
22453
22454
2
  if (mg_init_library_called <= 0) {
22455
2
    mg_init_library_called = 1;
22456
2
  } else {
22457
0
    mg_init_library_called++;
22458
0
  }
22459
2
  mg_global_unlock();
22460
22461
2
  return features_inited;
22462
2
}
22463
22464
22465
/* Un-initialize this library. */
22466
CIVETWEB_API unsigned
22467
mg_exit_library(void)
22468
0
{
22469
0
  if (mg_init_library_called <= 0) {
22470
0
    return 0;
22471
0
  }
22472
22473
0
  mg_global_lock();
22474
22475
0
  mg_init_library_called--;
22476
0
  if (mg_init_library_called == 0) {
22477
0
#if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
22478
0
    if (mg_openssl_initialized) {
22479
0
      uninitialize_openssl();
22480
0
      mg_openssl_initialized = 0;
22481
0
    }
22482
0
#endif
22483
22484
#if defined(_WIN32)
22485
    (void)WSACleanup();
22486
    (void)pthread_mutex_destroy(&global_log_file_lock);
22487
#else
22488
0
    (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
22489
0
#endif
22490
22491
0
    (void)pthread_key_delete(sTlsKey);
22492
22493
#if defined(USE_LUA)
22494
    lua_exit_optional_libraries();
22495
#endif
22496
0
    mg_free(all_methods);
22497
0
    all_methods = NULL;
22498
22499
0
    mg_global_unlock();
22500
0
    (void)pthread_mutex_destroy(&global_lock_mutex);
22501
0
    return 1;
22502
0
  }
22503
22504
0
  mg_global_unlock();
22505
0
  return 1;
22506
0
}
22507
22508
22509
/* End of civetweb.c */