1 /* Copyright (c) 2013-2018 the Civetweb developers
2 * Copyright (c) 2004-2013 Sergey Lyubka
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23 #if defined(__GNUC__) || defined(__MINGW32__)
24 #define GCC_VERSION \
25 (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
26 #if GCC_VERSION >= 40500
27 /* gcc diagnostic pragmas available */
28 #define GCC_DIAGNOSTIC
29 #endif
30 #endif
31
32 #if defined(GCC_DIAGNOSTIC)
33 /* Disable unused macros warnings - not all defines are required
34 * for all systems and all compilers. */
35 #pragma GCC diagnostic ignored "-Wunused-macros"
36 /* A padding warning is just plain useless */
37 #pragma GCC diagnostic ignored "-Wpadded"
38 #endif
39
40 #if defined(__clang__) /* GCC does not (yet) support this pragma */
41 /* We must set some flags for the headers we include. These flags
42 * are reserved ids according to C99, so we need to disable a
43 * warning for that. */
44 #pragma GCC diagnostic push
45 #pragma GCC diagnostic ignored "-Wreserved-id-macro"
46 #endif
47
48 #if defined(_WIN32)
49 #if !defined(_CRT_SECURE_NO_WARNINGS)
50 #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
51 #endif
52 #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
53 #define _WIN32_WINNT 0x0501
54 #endif
55 #else
56 #if !defined(_GNU_SOURCE)
57 #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
58 #endif
59 #if defined(__linux__) && !defined(_XOPEN_SOURCE)
60 #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
61 #endif
62 #if defined(__LSB_VERSION__)
63 #define NEED_TIMEGM
64 #define NO_THREAD_NAME
65 #endif
66 #if !defined(_LARGEFILE_SOURCE)
67 #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
68 #endif
69 #if !defined(_FILE_OFFSET_BITS)
70 #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
71 #endif
72 #if !defined(__STDC_FORMAT_MACROS)
73 #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
74 #endif
75 #if !defined(__STDC_LIMIT_MACROS)
76 #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
77 #endif
78 #if !defined(_DARWIN_UNLIMITED_SELECT)
79 #define _DARWIN_UNLIMITED_SELECT
80 #endif
81 #if defined(__sun)
82 #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
83 #define __inline inline /* not recognized on older compiler versions */
84 #endif
85 #endif
86
87 #if defined(__clang__)
88 /* Enable reserved-id-macro warning again. */
89 #pragma GCC diagnostic pop
90 #endif
91
92
93 #if defined(USE_LUA)
94 #define USE_TIMERS
95 #endif
96
97 #if defined(_MSC_VER)
98 /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
99 #pragma warning(disable : 4306)
100 /* conditional expression is constant: introduced by FD_SET(..) */
101 #pragma warning(disable : 4127)
102 /* non-constant aggregate initializer: issued due to missing C99 support */
103 #pragma warning(disable : 4204)
104 /* padding added after data member */
105 #pragma warning(disable : 4820)
106 /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
107 #pragma warning(disable : 4668)
108 /* no function prototype given: converting '()' to '(void)' */
109 #pragma warning(disable : 4255)
110 /* function has been selected for automatic inline expansion */
111 #pragma warning(disable : 4711)
112 #endif
113
114
115 /* This code uses static_assert to check some conditions.
116 * Unfortunately some compilers still do not support it, so we have a
117 * replacement function here. */
118 #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
119 #define mg_static_assert _Static_assert
120 #elif defined(__cplusplus) && __cplusplus >= 201103L
121 #define mg_static_assert static_assert
122 #else
123 char static_assert_replacement[1];
124 #define mg_static_assert(cond, txt) \
125 extern char static_assert_replacement[(cond) ? 1 : -1]
126 #endif
127
128 mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
129 "int data type size check");
130 mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
131 "pointer data type size check");
132 mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
133
134
135 /* Alternative queue is well tested and should be the new default */
136 #if defined(NO_ALTERNATIVE_QUEUE)
137 #if defined(ALTERNATIVE_QUEUE)
138 #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
139 #endif
140 #else
141 #define ALTERNATIVE_QUEUE
142 #endif
143
144 #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
145 #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
146 #endif
147
148 /* DTL -- including winsock2.h works better if lean and mean */
149 #if !defined(WIN32_LEAN_AND_MEAN)
150 #define WIN32_LEAN_AND_MEAN
151 #endif
152
153 #if defined(__SYMBIAN32__)
154 /* According to https://en.wikipedia.org/wiki/Symbian#History,
155 * Symbian is no longer maintained since 2014-01-01.
156 * Recent versions of CivetWeb are no longer tested for Symbian.
157 * It makes no sense, to support an abandoned operating system.
158 */
159 #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
160 #define NO_SSL /* SSL is not supported */
161 #define NO_CGI /* CGI is not supported */
162 #define PATH_MAX FILENAME_MAX
163 #endif /* __SYMBIAN32__ */
164
165 #if defined(__ZEPHYR__)
166 #include <time.h>
167
168 #include <ctype.h>
169 #include <net/socket.h>
170 #include <posix/pthread.h>
171 #include <posix/time.h>
172 #include <stdio.h>
173 #include <stdlib.h>
174 #include <string.h>
175 #include <zephyr.h>
176
177 #include <fcntl.h>
178
179 #include <libc_extensions.h>
180
181 /* Max worker threads is the max of pthreads minus the main application thread
182 * and minus the main civetweb thread, thus -2
183 */
184 #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
185
186 #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
187 #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
188 #else
189 #define ZEPHYR_STACK_SIZE 8096
190 #endif
191
192 K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
193 K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
194 MAX_WORKER_THREADS,
195 ZEPHYR_STACK_SIZE);
196
197 static int zephyr_worker_stack_index;
198
199 #endif
200
201 #if !defined(CIVETWEB_HEADER_INCLUDED)
202 /* Include the header file here, so the CivetWeb interface is defined for the
203 * entire implementation, including the following forward definitions. */
204 #include "civetweb.h"
205 #endif
206
207 #if !defined(DEBUG_TRACE)
208 #if defined(DEBUG)
209 static void DEBUG_TRACE_FUNC(const char *func,
210 unsigned line,
211 PRINTF_FORMAT_STRING(const char *fmt),
212 ...) PRINTF_ARGS(3, 4);
213
214 #define DEBUG_TRACE(fmt, ...) \
215 DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
216
217 #define NEED_DEBUG_TRACE_FUNC
218
219 #else
220 #define DEBUG_TRACE(fmt, ...) \
221 do { \
222 } while (0)
223 #endif /* DEBUG */
224 #endif /* DEBUG_TRACE */
225
226
227 #if !defined(DEBUG_ASSERT)
228 #if defined(DEBUG)
229 #define DEBUG_ASSERT(cond) \
230 do { \
231 if (!(cond)) { \
232 DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
233 exit(2); /* Exit with error */ \
234 } \
235 } while (0)
236 #else
237 #define DEBUG_ASSERT(cond)
238 #endif /* DEBUG */
239 #endif
240
241
242 #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
243 void __cyg_profile_func_enter(void *this_fn, void *call_site)
244 __attribute__((no_instrument_function));
245
246 void __cyg_profile_func_exit(void *this_fn, void *call_site)
247 __attribute__((no_instrument_function));
248
249 void
__cyg_profile_func_enter(void * this_fn,void * call_site)250 __cyg_profile_func_enter(void *this_fn, void *call_site)
251 {
252 if ((void *)this_fn != (void *)printf) {
253 printf("E %p %p\n", this_fn, call_site);
254 }
255 }
256
257 void
__cyg_profile_func_exit(void * this_fn,void * call_site)258 __cyg_profile_func_exit(void *this_fn, void *call_site)
259 {
260 if ((void *)this_fn != (void *)printf) {
261 printf("X %p %p\n", this_fn, call_site);
262 }
263 }
264 #endif
265
266
267 #if !defined(IGNORE_UNUSED_RESULT)
268 #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
269 #endif
270
271
272 #if defined(__GNUC__) || defined(__MINGW32__)
273
274 /* GCC unused function attribute seems fundamentally broken.
275 * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
276 * OR UNUSED" for individual functions failed.
277 * Either the compiler creates an "unused-function" warning if a
278 * function is not marked with __attribute__((unused)).
279 * On the other hand, if the function is marked with this attribute,
280 * but is used, the compiler raises a completely idiotic
281 * "used-but-marked-unused" warning - and
282 * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
283 * raises error: unknown option after "#pragma GCC diagnostic".
284 * Disable this warning completely, until the GCC guys sober up
285 * again.
286 */
287
288 #pragma GCC diagnostic ignored "-Wunused-function"
289
290 #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
291
292 #else
293 #define FUNCTION_MAY_BE_UNUSED
294 #endif
295
296
297 /* Some ANSI #includes are not available on Windows CE */
298 #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
299 #include <errno.h>
300 #include <fcntl.h>
301 #include <signal.h>
302 #include <stdlib.h>
303 #include <sys/stat.h>
304 #include <sys/types.h>
305 #endif /* !_WIN32_WCE */
306
307
308 #if defined(__clang__)
309 /* When using -Weverything, clang does not accept it's own headers
310 * in a release build configuration. Disable what is too much in
311 * -Weverything. */
312 #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
313 #endif
314
315 #if defined(__GNUC__) || defined(__MINGW32__)
316 /* Who on earth came to the conclusion, using __DATE__ should rise
317 * an "expansion of date or time macro is not reproducible"
318 * warning. That's exactly what was intended by using this macro.
319 * Just disable this nonsense warning. */
320
321 /* And disabling them does not work either:
322 * #pragma clang diagnostic ignored "-Wno-error=date-time"
323 * #pragma clang diagnostic ignored "-Wdate-time"
324 * So we just have to disable ALL warnings for some lines
325 * of code.
326 * This seems to be a known GCC bug, not resolved since 2012:
327 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
328 */
329 #endif
330
331
332 #if defined(__MACH__) /* Apple OSX section */
333
334 #if defined(__clang__)
335 #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
336 /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
337 #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
338 #pragma clang diagnostic ignored "-Wno-keyword-macro"
339 #endif
340 #endif
341
342 #define CLOCK_MONOTONIC (1)
343 #define CLOCK_REALTIME (2)
344
345 #include <mach/clock.h>
346 #include <mach/mach.h>
347 #include <mach/mach_time.h>
348 #include <sys/errno.h>
349 #include <sys/time.h>
350
351 /* clock_gettime is not implemented on OSX prior to 10.12 */
352 static int
_civet_clock_gettime(int clk_id,struct timespec * t)353 _civet_clock_gettime(int clk_id, struct timespec *t)
354 {
355 memset(t, 0, sizeof(*t));
356 if (clk_id == CLOCK_REALTIME) {
357 struct timeval now;
358 int rv = gettimeofday(&now, NULL);
359 if (rv) {
360 return rv;
361 }
362 t->tv_sec = now.tv_sec;
363 t->tv_nsec = now.tv_usec * 1000;
364 return 0;
365
366 } else if (clk_id == CLOCK_MONOTONIC) {
367 static uint64_t clock_start_time = 0;
368 static mach_timebase_info_data_t timebase_ifo = {0, 0};
369
370 uint64_t now = mach_absolute_time();
371
372 if (clock_start_time == 0) {
373 kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
374 DEBUG_ASSERT(mach_status == KERN_SUCCESS);
375
376 /* appease "unused variable" warning for release builds */
377 (void)mach_status;
378
379 clock_start_time = now;
380 }
381
382 now = (uint64_t)((double)(now - clock_start_time)
383 * (double)timebase_ifo.numer
384 / (double)timebase_ifo.denom);
385
386 t->tv_sec = now / 1000000000;
387 t->tv_nsec = now % 1000000000;
388 return 0;
389 }
390 return -1; /* EINVAL - Clock ID is unknown */
391 }
392
393 /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
394 #if defined(__CLOCK_AVAILABILITY)
395 /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
396 * declared but it may be NULL at runtime. So we need to check before using
397 * it. */
398 static int
_civet_safe_clock_gettime(int clk_id,struct timespec * t)399 _civet_safe_clock_gettime(int clk_id, struct timespec *t)
400 {
401 if (clock_gettime) {
402 return clock_gettime(clk_id, t);
403 }
404 return _civet_clock_gettime(clk_id, t);
405 }
406 #define clock_gettime _civet_safe_clock_gettime
407 #else
408 #define clock_gettime _civet_clock_gettime
409 #endif
410
411 #endif
412
413
414 /********************************************************************/
415 /* CivetWeb configuration defines */
416 /********************************************************************/
417
418 /* Maximum number of threads that can be configured.
419 * The number of threads actually created depends on the "num_threads"
420 * configuration parameter, but this is the upper limit. */
421 #if !defined(MAX_WORKER_THREADS)
422 #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
423 #endif
424
425 /* Timeout interval for select/poll calls.
426 * The timeouts depend on "*_timeout_ms" configuration values, but long
427 * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
428 * This reduces the time required to stop the server. */
429 #if !defined(SOCKET_TIMEOUT_QUANTUM)
430 #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
431 #endif
432
433 /* Do not try to compress files smaller than this limit. */
434 #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
435 #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
436 #endif
437
438 #if !defined(PASSWORDS_FILE_NAME)
439 #define PASSWORDS_FILE_NAME ".htpasswd"
440 #endif
441
442 /* Initial buffer size for all CGI environment variables. In case there is
443 * not enough space, another block is allocated. */
444 #if !defined(CGI_ENVIRONMENT_SIZE)
445 #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
446 #endif
447
448 /* Maximum number of environment variables. */
449 #if !defined(MAX_CGI_ENVIR_VARS)
450 #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
451 #endif
452
453 /* General purpose buffer size. */
454 #if !defined(MG_BUF_LEN) /* in bytes */
455 #define MG_BUF_LEN (1024 * 8)
456 #endif
457
458 /* Size of the accepted socket queue (in case the old queue implementation
459 * is used). */
460 #if !defined(MGSQLEN)
461 #define MGSQLEN (20) /* count */
462 #endif
463
464
465 /********************************************************************/
466
467 /* Helper makros */
468 #if !defined(ARRAY_SIZE)
469 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
470 #endif
471
472 #include <stdint.h>
473
474 /* Standard defines */
475 #if !defined(INT64_MAX)
476 #define INT64_MAX (9223372036854775807)
477 #endif
478
479 #define SHUTDOWN_RD (0)
480 #define SHUTDOWN_WR (1)
481 #define SHUTDOWN_BOTH (2)
482
483 mg_static_assert(MAX_WORKER_THREADS >= 1,
484 "worker threads must be a positive number");
485
486 mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
487 "size_t data type size check");
488
489
490 #if defined(_WIN32) /* WINDOWS include block */
491 #include <malloc.h> /* *alloc( */
492 #include <stdlib.h> /* *alloc( */
493 #include <time.h> /* struct timespec */
494 #include <windows.h>
495 #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
496 #include <ws2tcpip.h>
497
498 typedef const char *SOCK_OPT_TYPE;
499
500 #if !defined(PATH_MAX)
501 #define W_PATH_MAX (MAX_PATH)
502 /* at most three UTF-8 chars per wchar_t */
503 #define PATH_MAX (W_PATH_MAX * 3)
504 #else
505 #define W_PATH_MAX ((PATH_MAX + 2) / 3)
506 #endif
507
508 mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
509
510 #if !defined(_IN_PORT_T)
511 #if !defined(in_port_t)
512 #define in_port_t u_short
513 #endif
514 #endif
515
516 #if !defined(_WIN32_WCE)
517 #include <direct.h>
518 #include <io.h>
519 #include <process.h>
520 #else /* _WIN32_WCE */
521 #define NO_CGI /* WinCE has no pipes */
522 #define NO_POPEN /* WinCE has no popen */
523
524 typedef long off_t;
525
526 #define errno ((int)(GetLastError()))
527 #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
528 #endif /* _WIN32_WCE */
529
530 #define MAKEUQUAD(lo, hi) \
531 ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
532 #define RATE_DIFF (10000000) /* 100 nsecs */
533 #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
534 #define SYS2UNIX_TIME(lo, hi) \
535 ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
536
537 /* Visual Studio 6 does not know __func__ or __FUNCTION__
538 * The rest of MS compilers use __FUNCTION__, not C99 __func__
539 * Also use _strtoui64 on modern M$ compilers */
540 #if defined(_MSC_VER)
541 #if (_MSC_VER < 1300)
542 #define STRX(x) #x
543 #define STR(x) STRX(x)
544 #define __func__ __FILE__ ":" STR(__LINE__)
545 #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
546 #define strtoll(x, y, z) (_atoi64(x))
547 #else
548 #define __func__ __FUNCTION__
549 #define strtoull(x, y, z) (_strtoui64(x, y, z))
550 #define strtoll(x, y, z) (_strtoi64(x, y, z))
551 #endif
552 #endif /* _MSC_VER */
553
554 #define ERRNO ((int)(GetLastError()))
555 #define NO_SOCKLEN_T
556
557 #if defined(_WIN64) || defined(__MINGW64__)
558 #if !defined(SSL_LIB)
559 #define SSL_LIB "ssleay64.dll"
560 #endif
561 #if !defined(CRYPTO_LIB)
562 #define CRYPTO_LIB "libeay64.dll"
563 #endif
564 #else
565 #if !defined(SSL_LIB)
566 #define SSL_LIB "ssleay32.dll"
567 #endif
568 #if !defined(CRYPTO_LIB)
569 #define CRYPTO_LIB "libeay32.dll"
570 #endif
571 #endif
572
573 #define O_NONBLOCK (0)
574 #if !defined(W_OK)
575 #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
576 #endif
577 #define _POSIX_
578 #define INT64_FMT "I64d"
579 #define UINT64_FMT "I64u"
580
581 #define WINCDECL __cdecl
582 #define vsnprintf_impl _vsnprintf
583 #define access _access
584 #define mg_sleep(x) (Sleep(x))
585
586 #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
587 #if !defined(popen)
588 #define popen(x, y) (_popen(x, y))
589 #endif
590 #if !defined(pclose)
591 #define pclose(x) (_pclose(x))
592 #endif
593 #define close(x) (_close(x))
594 #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
595 #define RTLD_LAZY (0)
596 #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
597 #define fdopen(x, y) (_fdopen((x), (y)))
598 #define write(x, y, z) (_write((x), (y), (unsigned)z))
599 #define read(x, y, z) (_read((x), (y), (unsigned)z))
600 #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
601 #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
602 #define sleep(x) (Sleep((x)*1000))
603 #define rmdir(x) (_rmdir(x))
604 #if defined(_WIN64) || !defined(__MINGW32__)
605 /* Only MinGW 32 bit is missing this function */
606 #define timegm(x) (_mkgmtime(x))
607 #else
608 time_t timegm(struct tm *tm);
609 #define NEED_TIMEGM
610 #endif
611
612
613 #if !defined(fileno)
614 #define fileno(x) (_fileno(x))
615 #endif /* !fileno MINGW #defines fileno */
616
617 typedef struct {
618 CRITICAL_SECTION sec; /* Immovable */
619 } pthread_mutex_t;
620 typedef DWORD pthread_key_t;
621 typedef HANDLE pthread_t;
622 typedef struct {
623 pthread_mutex_t threadIdSec;
624 struct mg_workerTLS *waiting_thread; /* The chain of threads */
625 } pthread_cond_t;
626
627 #if !defined(__clockid_t_defined)
628 typedef DWORD clockid_t;
629 #endif
630 #if !defined(CLOCK_MONOTONIC)
631 #define CLOCK_MONOTONIC (1)
632 #endif
633 #if !defined(CLOCK_REALTIME)
634 #define CLOCK_REALTIME (2)
635 #endif
636 #if !defined(CLOCK_THREAD)
637 #define CLOCK_THREAD (3)
638 #endif
639 #if !defined(CLOCK_PROCESS)
640 #define CLOCK_PROCESS (4)
641 #endif
642
643
644 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
645 #define _TIMESPEC_DEFINED
646 #endif
647 #if !defined(_TIMESPEC_DEFINED)
648 struct timespec {
649 time_t tv_sec; /* seconds */
650 long tv_nsec; /* nanoseconds */
651 };
652 #endif
653
654 #if !defined(WIN_PTHREADS_TIME_H)
655 #define MUST_IMPLEMENT_CLOCK_GETTIME
656 #endif
657
658 #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
659 #define clock_gettime mg_clock_gettime
660 static int
clock_gettime(clockid_t clk_id,struct timespec * tp)661 clock_gettime(clockid_t clk_id, struct timespec *tp)
662 {
663 FILETIME ft;
664 ULARGE_INTEGER li, li2;
665 BOOL ok = FALSE;
666 double d;
667 static double perfcnt_per_sec = 0.0;
668 static BOOL initialized = FALSE;
669
670 if (!initialized) {
671 QueryPerformanceFrequency((LARGE_INTEGER *)&li);
672 perfcnt_per_sec = 1.0 / li.QuadPart;
673 initialized = TRUE;
674 }
675
676 if (tp) {
677 memset(tp, 0, sizeof(*tp));
678
679 if (clk_id == CLOCK_REALTIME) {
680
681 /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
682 GetSystemTimeAsFileTime(&ft);
683 li.LowPart = ft.dwLowDateTime;
684 li.HighPart = ft.dwHighDateTime;
685 li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
686 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
687 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
688 ok = TRUE;
689 /* END: CLOCK_REALTIME */
690
691 } else if (clk_id == CLOCK_MONOTONIC) {
692
693 /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
694 QueryPerformanceCounter((LARGE_INTEGER *)&li);
695 d = li.QuadPart * perfcnt_per_sec;
696 tp->tv_sec = (time_t)d;
697 d -= (double)tp->tv_sec;
698 tp->tv_nsec = (long)(d * 1.0E9);
699 ok = TRUE;
700 /* END: CLOCK_MONOTONIC */
701
702 } else if (clk_id == CLOCK_THREAD) {
703
704 /* BEGIN: CLOCK_THREAD = CPU usage of thread */
705 FILETIME t_create, t_exit, t_kernel, t_user;
706 if (GetThreadTimes(GetCurrentThread(),
707 &t_create,
708 &t_exit,
709 &t_kernel,
710 &t_user)) {
711 li.LowPart = t_user.dwLowDateTime;
712 li.HighPart = t_user.dwHighDateTime;
713 li2.LowPart = t_kernel.dwLowDateTime;
714 li2.HighPart = t_kernel.dwHighDateTime;
715 li.QuadPart += li2.QuadPart;
716 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
717 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
718 ok = TRUE;
719 }
720 /* END: CLOCK_THREAD */
721
722 } else if (clk_id == CLOCK_PROCESS) {
723
724 /* BEGIN: CLOCK_PROCESS = CPU usage of process */
725 FILETIME t_create, t_exit, t_kernel, t_user;
726 if (GetProcessTimes(GetCurrentProcess(),
727 &t_create,
728 &t_exit,
729 &t_kernel,
730 &t_user)) {
731 li.LowPart = t_user.dwLowDateTime;
732 li.HighPart = t_user.dwHighDateTime;
733 li2.LowPart = t_kernel.dwLowDateTime;
734 li2.HighPart = t_kernel.dwHighDateTime;
735 li.QuadPart += li2.QuadPart;
736 tp->tv_sec = (time_t)(li.QuadPart / 10000000);
737 tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
738 ok = TRUE;
739 }
740 /* END: CLOCK_PROCESS */
741
742 } else {
743
744 /* BEGIN: unknown clock */
745 /* ok = FALSE; already set by init */
746 /* END: unknown clock */
747 }
748 }
749
750 return ok ? 0 : -1;
751 }
752 #endif
753
754
755 #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
756
757 static int pthread_mutex_lock(pthread_mutex_t *);
758 static int pthread_mutex_unlock(pthread_mutex_t *);
759 static void path_to_unicode(const struct mg_connection *conn,
760 const char *path,
761 wchar_t *wbuf,
762 size_t wbuf_len);
763
764 /* All file operations need to be rewritten to solve #246. */
765
766 struct mg_file;
767
768 static const char *
769 mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
770
771
772 /* POSIX dirent interface */
773 struct dirent {
774 char d_name[PATH_MAX];
775 };
776
777 typedef struct DIR {
778 HANDLE handle;
779 WIN32_FIND_DATAW info;
780 struct dirent result;
781 } DIR;
782
783 #if defined(HAVE_POLL)
784 #define mg_pollfd pollfd
785 #else
786 struct mg_pollfd {
787 SOCKET fd;
788 short events;
789 short revents;
790 };
791 #endif
792
793 /* Mark required libraries */
794 #if defined(_MSC_VER)
795 #pragma comment(lib, "Ws2_32.lib")
796 #endif
797
798 #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
799
800 #include <inttypes.h>
801
802 typedef const void *SOCK_OPT_TYPE;
803
804 #if defined(ANDROID)
805 typedef unsigned short int in_port_t;
806 #endif
807
808 #if !defined(__ZEPHYR__)
809 #include <arpa/inet.h>
810 #include <ctype.h>
811 #include <dirent.h>
812 #include <grp.h>
813 #include <limits.h>
814 #include <netdb.h>
815 #include <netinet/in.h>
816 #include <netinet/tcp.h>
817 #include <pthread.h>
818 #include <pwd.h>
819 #include <stdarg.h>
820 #include <stddef.h>
821 #include <stdio.h>
822 #include <stdlib.h>
823 #include <string.h>
824 #include <sys/poll.h>
825 #include <sys/socket.h>
826 #include <sys/time.h>
827 #include <sys/utsname.h>
828 #include <sys/wait.h>
829 #include <time.h>
830 #include <unistd.h>
831 #endif
832
833 #define vsnprintf_impl vsnprintf
834
835 #if !defined(NO_SSL_DL) && !defined(NO_SSL)
836 #include <dlfcn.h>
837 #endif
838
839 #if defined(__MACH__)
840 #define SSL_LIB "libssl.dylib"
841 #define CRYPTO_LIB "libcrypto.dylib"
842 #else
843 #if !defined(SSL_LIB)
844 #define SSL_LIB "libssl.so"
845 #endif
846 #if !defined(CRYPTO_LIB)
847 #define CRYPTO_LIB "libcrypto.so"
848 #endif
849 #endif
850 #if !defined(O_BINARY)
851 #define O_BINARY (0)
852 #endif /* O_BINARY */
853 #define closesocket(a) (close(a))
854 #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
855 #define mg_remove(conn, x) (remove(x))
856 #define mg_sleep(x) (usleep((x)*1000))
857 #define mg_opendir(conn, x) (opendir(x))
858 #define mg_closedir(x) (closedir(x))
859 #define mg_readdir(x) (readdir(x))
860 #define ERRNO (errno)
861 #define INVALID_SOCKET (-1)
862 #define INT64_FMT PRId64
863 #define UINT64_FMT PRIu64
864 typedef int SOCKET;
865 #define WINCDECL
866
867 #if defined(__hpux)
868 /* HPUX 11 does not have monotonic, fall back to realtime */
869 #if !defined(CLOCK_MONOTONIC)
870 #define CLOCK_MONOTONIC CLOCK_REALTIME
871 #endif
872
873 /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
874 * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
875 * the prototypes use int* rather than socklen_t* which matches the
876 * actual library expectation. When called with the wrong size arg
877 * accept() returns a zero client inet addr and check_acl() always
878 * fails. Since socklen_t is widely used below, just force replace
879 * their typedef with int. - DTL
880 */
881 #define socklen_t int
882 #endif /* hpux */
883
884 #define mg_pollfd pollfd
885
886 #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
887
888 /* In case our C library is missing "timegm", provide an implementation */
889 #if defined(NEED_TIMEGM)
890 static inline int
is_leap(int y)891 is_leap(int y)
892 {
893 return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
894 }
895
896 static inline int
count_leap(int y)897 count_leap(int y)
898 {
899 return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
900 }
901
902 time_t
timegm(struct tm * tm)903 timegm(struct tm *tm)
904 {
905 static const unsigned short ydays[] = {
906 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
907 int year = tm->tm_year + 1900;
908 int mon = tm->tm_mon;
909 int mday = tm->tm_mday - 1;
910 int hour = tm->tm_hour;
911 int min = tm->tm_min;
912 int sec = tm->tm_sec;
913
914 if (year < 1970 || mon < 0 || mon > 11 || mday < 0
915 || (mday >= ydays[mon + 1] - ydays[mon]
916 + (mon == 1 && is_leap(year) ? 1 : 0))
917 || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
918 return -1;
919
920 time_t res = year - 1970;
921 res *= 365;
922 res += mday;
923 res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
924 res += count_leap(year);
925
926 res *= 24;
927 res += hour;
928 res *= 60;
929 res += min;
930 res *= 60;
931 res += sec;
932 return res;
933 }
934 #endif /* NEED_TIMEGM */
935
936
937 /* va_copy should always be a macro, C99 and C++11 - DTL */
938 #if !defined(va_copy)
939 #define va_copy(x, y) ((x) = (y))
940 #endif
941
942
943 #if defined(_WIN32)
944 /* Create substitutes for POSIX functions in Win32. */
945
946 #if defined(GCC_DIAGNOSTIC)
947 /* Show no warning in case system functions are not used. */
948 #pragma GCC diagnostic push
949 #pragma GCC diagnostic ignored "-Wunused-function"
950 #endif
951
952
953 static pthread_mutex_t global_log_file_lock;
954
955 FUNCTION_MAY_BE_UNUSED
956 static DWORD
pthread_self(void)957 pthread_self(void)
958 {
959 return GetCurrentThreadId();
960 }
961
962
963 FUNCTION_MAY_BE_UNUSED
964 static int
pthread_key_create(pthread_key_t * key,void (* _ignored)(void *))965 pthread_key_create(
966 pthread_key_t *key,
967 void (*_ignored)(void *) /* destructor not supported for Windows */
968 )
969 {
970 (void)_ignored;
971
972 if ((key != 0)) {
973 *key = TlsAlloc();
974 return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
975 }
976 return -2;
977 }
978
979
980 FUNCTION_MAY_BE_UNUSED
981 static int
pthread_key_delete(pthread_key_t key)982 pthread_key_delete(pthread_key_t key)
983 {
984 return TlsFree(key) ? 0 : 1;
985 }
986
987
988 FUNCTION_MAY_BE_UNUSED
989 static int
pthread_setspecific(pthread_key_t key,void * value)990 pthread_setspecific(pthread_key_t key, void *value)
991 {
992 return TlsSetValue(key, value) ? 0 : 1;
993 }
994
995
996 FUNCTION_MAY_BE_UNUSED
997 static void *
pthread_getspecific(pthread_key_t key)998 pthread_getspecific(pthread_key_t key)
999 {
1000 return TlsGetValue(key);
1001 }
1002
1003 #if defined(GCC_DIAGNOSTIC)
1004 /* Enable unused function warning again */
1005 #pragma GCC diagnostic pop
1006 #endif
1007
1008 static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
1009 #else
1010 static pthread_mutexattr_t pthread_mutex_attr;
1011 #endif /* _WIN32 */
1012
1013
1014 #if defined(_WIN32_WCE)
1015 /* Create substitutes for POSIX functions in Win32. */
1016
1017 #if defined(GCC_DIAGNOSTIC)
1018 /* Show no warning in case system functions are not used. */
1019 #pragma GCC diagnostic push
1020 #pragma GCC diagnostic ignored "-Wunused-function"
1021 #endif
1022
1023
1024 FUNCTION_MAY_BE_UNUSED
1025 static time_t
time(time_t * ptime)1026 time(time_t *ptime)
1027 {
1028 time_t t;
1029 SYSTEMTIME st;
1030 FILETIME ft;
1031
1032 GetSystemTime(&st);
1033 SystemTimeToFileTime(&st, &ft);
1034 t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
1035
1036 if (ptime != NULL) {
1037 *ptime = t;
1038 }
1039
1040 return t;
1041 }
1042
1043
1044 FUNCTION_MAY_BE_UNUSED
1045 static struct tm *
localtime_s(const time_t * ptime,struct tm * ptm)1046 localtime_s(const time_t *ptime, struct tm *ptm)
1047 {
1048 int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
1049 FILETIME ft, lft;
1050 SYSTEMTIME st;
1051 TIME_ZONE_INFORMATION tzinfo;
1052
1053 if (ptm == NULL) {
1054 return NULL;
1055 }
1056
1057 *(int64_t *)&ft = t;
1058 FileTimeToLocalFileTime(&ft, &lft);
1059 FileTimeToSystemTime(&lft, &st);
1060 ptm->tm_year = st.wYear - 1900;
1061 ptm->tm_mon = st.wMonth - 1;
1062 ptm->tm_wday = st.wDayOfWeek;
1063 ptm->tm_mday = st.wDay;
1064 ptm->tm_hour = st.wHour;
1065 ptm->tm_min = st.wMinute;
1066 ptm->tm_sec = st.wSecond;
1067 ptm->tm_yday = 0; /* hope nobody uses this */
1068 ptm->tm_isdst =
1069 (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
1070
1071 return ptm;
1072 }
1073
1074
1075 FUNCTION_MAY_BE_UNUSED
1076 static struct tm *
gmtime_s(const time_t * ptime,struct tm * ptm)1077 gmtime_s(const time_t *ptime, struct tm *ptm)
1078 {
1079 /* FIXME(lsm): fix this. */
1080 return localtime_s(ptime, ptm);
1081 }
1082
1083
1084 static int mg_atomic_inc(volatile int *addr);
1085 static struct tm tm_array[MAX_WORKER_THREADS];
1086 static int tm_index = 0;
1087
1088
1089 FUNCTION_MAY_BE_UNUSED
1090 static struct tm *
localtime(const time_t * ptime)1091 localtime(const time_t *ptime)
1092 {
1093 int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
1094 return localtime_s(ptime, tm_array + i);
1095 }
1096
1097
1098 FUNCTION_MAY_BE_UNUSED
1099 static struct tm *
gmtime(const time_t * ptime)1100 gmtime(const time_t *ptime)
1101 {
1102 int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
1103 return gmtime_s(ptime, tm_array + i);
1104 }
1105
1106
1107 FUNCTION_MAY_BE_UNUSED
1108 static size_t
strftime(char * dst,size_t dst_size,const char * fmt,const struct tm * tm)1109 strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
1110 {
1111 /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
1112 * for WinCE"); */
1113 return 0;
1114 }
1115
1116 #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
1117 (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
1118
1119 #define remove(f) mg_remove(NULL, f)
1120
1121
1122 FUNCTION_MAY_BE_UNUSED
1123 static int
rename(const char * a,const char * b)1124 rename(const char *a, const char *b)
1125 {
1126 wchar_t wa[W_PATH_MAX];
1127 wchar_t wb[W_PATH_MAX];
1128 path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
1129 path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
1130
1131 return MoveFileW(wa, wb) ? 0 : -1;
1132 }
1133
1134
1135 struct stat {
1136 int64_t st_size;
1137 time_t st_mtime;
1138 };
1139
1140
1141 FUNCTION_MAY_BE_UNUSED
1142 static int
stat(const char * name,struct stat * st)1143 stat(const char *name, struct stat *st)
1144 {
1145 wchar_t wbuf[W_PATH_MAX];
1146 WIN32_FILE_ATTRIBUTE_DATA attr;
1147 time_t creation_time, write_time;
1148
1149 path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
1150 memset(&attr, 0, sizeof(attr));
1151
1152 GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
1153 st->st_size =
1154 (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
1155
1156 write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
1157 attr.ftLastWriteTime.dwHighDateTime);
1158 creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
1159 attr.ftCreationTime.dwHighDateTime);
1160
1161 if (creation_time > write_time) {
1162 st->st_mtime = creation_time;
1163 } else {
1164 st->st_mtime = write_time;
1165 }
1166 return 0;
1167 }
1168
1169 #define access(x, a) 1 /* not required anyway */
1170
1171 /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
1172 /* Values from errno.h in Windows SDK (Visual Studio). */
1173 #define EEXIST 17
1174 #define EACCES 13
1175 #define ENOENT 2
1176
1177 #if defined(GCC_DIAGNOSTIC)
1178 /* Enable unused function warning again */
1179 #pragma GCC diagnostic pop
1180 #endif
1181
1182 #endif /* defined(_WIN32_WCE) */
1183
1184
1185 #if defined(GCC_DIAGNOSTIC)
1186 /* Show no warning in case system functions are not used. */
1187 #pragma GCC diagnostic push
1188 #pragma GCC diagnostic ignored "-Wunused-function"
1189 #endif /* defined(GCC_DIAGNOSTIC) */
1190 #if defined(__clang__)
1191 /* Show no warning in case system functions are not used. */
1192 #pragma clang diagnostic push
1193 #pragma clang diagnostic ignored "-Wunused-function"
1194 #endif
1195
1196 static pthread_mutex_t global_lock_mutex;
1197
1198
1199 FUNCTION_MAY_BE_UNUSED
1200 static void
mg_global_lock(void)1201 mg_global_lock(void)
1202 {
1203 (void)pthread_mutex_lock(&global_lock_mutex);
1204 }
1205
1206
1207 FUNCTION_MAY_BE_UNUSED
1208 static void
mg_global_unlock(void)1209 mg_global_unlock(void)
1210 {
1211 (void)pthread_mutex_unlock(&global_lock_mutex);
1212 }
1213
1214
1215 FUNCTION_MAY_BE_UNUSED
1216 static int
mg_atomic_inc(volatile int * addr)1217 mg_atomic_inc(volatile int *addr)
1218 {
1219 int ret;
1220 #if defined(_WIN32) && !defined(NO_ATOMICS)
1221 /* Depending on the SDK, this function uses either
1222 * (volatile unsigned int *) or (volatile LONG *),
1223 * so whatever you use, the other SDK is likely to raise a warning. */
1224 ret = InterlockedIncrement((volatile long *)addr);
1225 #elif defined(__GNUC__) \
1226 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1227 && !defined(NO_ATOMICS)
1228 ret = __sync_add_and_fetch(addr, 1);
1229 #else
1230 mg_global_lock();
1231 ret = (++(*addr));
1232 mg_global_unlock();
1233 #endif
1234 return ret;
1235 }
1236
1237
1238 FUNCTION_MAY_BE_UNUSED
1239 static int
mg_atomic_dec(volatile int * addr)1240 mg_atomic_dec(volatile int *addr)
1241 {
1242 int ret;
1243 #if defined(_WIN32) && !defined(NO_ATOMICS)
1244 /* Depending on the SDK, this function uses either
1245 * (volatile unsigned int *) or (volatile LONG *),
1246 * so whatever you use, the other SDK is likely to raise a warning. */
1247 ret = InterlockedDecrement((volatile long *)addr);
1248 #elif defined(__GNUC__) \
1249 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1250 && !defined(NO_ATOMICS)
1251 ret = __sync_sub_and_fetch(addr, 1);
1252 #else
1253 mg_global_lock();
1254 ret = (--(*addr));
1255 mg_global_unlock();
1256 #endif
1257 return ret;
1258 }
1259
1260
1261 #if defined(USE_SERVER_STATS)
1262 static int64_t
mg_atomic_add(volatile int64_t * addr,int64_t value)1263 mg_atomic_add(volatile int64_t *addr, int64_t value)
1264 {
1265 int64_t ret;
1266 #if defined(_WIN64) && !defined(NO_ATOMICS)
1267 ret = InterlockedAdd64(addr, value);
1268 #elif defined(__GNUC__) \
1269 && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1270 && !defined(NO_ATOMICS)
1271 ret = __sync_add_and_fetch(addr, value);
1272 #else
1273 mg_global_lock();
1274 *addr += value;
1275 ret = (*addr);
1276 mg_global_unlock();
1277 #endif
1278 return ret;
1279 }
1280 #endif
1281
1282
1283 #if defined(GCC_DIAGNOSTIC)
1284 /* Show no warning in case system functions are not used. */
1285 #pragma GCC diagnostic pop
1286 #endif /* defined(GCC_DIAGNOSTIC) */
1287 #if defined(__clang__)
1288 /* Show no warning in case system functions are not used. */
1289 #pragma clang diagnostic pop
1290 #endif
1291
1292
1293 #if defined(USE_SERVER_STATS)
1294
1295 struct mg_memory_stat {
1296 volatile int64_t totalMemUsed;
1297 volatile int64_t maxMemUsed;
1298 volatile int blockCount;
1299 };
1300
1301
1302 static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
1303
1304
1305 static void *
mg_malloc_ex(size_t size,struct mg_context * ctx,const char * file,unsigned line)1306 mg_malloc_ex(size_t size,
1307 struct mg_context *ctx,
1308 const char *file,
1309 unsigned line)
1310 {
1311 void *data = malloc(size + 2 * sizeof(uintptr_t));
1312 void *memory = 0;
1313 struct mg_memory_stat *mstat = get_memory_stat(ctx);
1314
1315 #if defined(MEMORY_DEBUGGING)
1316 char mallocStr[256];
1317 #else
1318 (void)file;
1319 (void)line;
1320 #endif
1321
1322 if (data) {
1323 int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
1324 if (mmem > mstat->maxMemUsed) {
1325 /* could use atomic compare exchange, but this
1326 * seems overkill for statistics data */
1327 mstat->maxMemUsed = mmem;
1328 }
1329
1330 mg_atomic_inc(&mstat->blockCount);
1331 ((uintptr_t *)data)[0] = size;
1332 ((uintptr_t *)data)[1] = (uintptr_t)mstat;
1333 memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1334 }
1335
1336 #if defined(MEMORY_DEBUGGING)
1337 sprintf(mallocStr,
1338 "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
1339 memory,
1340 (unsigned long)size,
1341 (unsigned long)mstat->totalMemUsed,
1342 (unsigned long)mstat->blockCount,
1343 file,
1344 line);
1345 #if defined(_WIN32)
1346 OutputDebugStringA(mallocStr);
1347 #else
1348 DEBUG_TRACE("%s", mallocStr);
1349 #endif
1350 #endif
1351
1352 return memory;
1353 }
1354
1355
1356 static void *
mg_calloc_ex(size_t count,size_t size,struct mg_context * ctx,const char * file,unsigned line)1357 mg_calloc_ex(size_t count,
1358 size_t size,
1359 struct mg_context *ctx,
1360 const char *file,
1361 unsigned line)
1362 {
1363 void *data = mg_malloc_ex(size * count, ctx, file, line);
1364
1365 if (data) {
1366 memset(data, 0, size * count);
1367 }
1368 return data;
1369 }
1370
1371
1372 static void
mg_free_ex(void * memory,const char * file,unsigned line)1373 mg_free_ex(void *memory, const char *file, unsigned line)
1374 {
1375 void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1376
1377
1378 #if defined(MEMORY_DEBUGGING)
1379 char mallocStr[256];
1380 #else
1381 (void)file;
1382 (void)line;
1383 #endif
1384
1385 if (memory) {
1386 uintptr_t size = ((uintptr_t *)data)[0];
1387 struct mg_memory_stat *mstat =
1388 (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
1389 mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
1390 mg_atomic_dec(&mstat->blockCount);
1391 #if defined(MEMORY_DEBUGGING)
1392 sprintf(mallocStr,
1393 "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
1394 memory,
1395 (unsigned long)size,
1396 (unsigned long)mstat->totalMemUsed,
1397 (unsigned long)mstat->blockCount,
1398 file,
1399 line);
1400 #if defined(_WIN32)
1401 OutputDebugStringA(mallocStr);
1402 #else
1403 DEBUG_TRACE("%s", mallocStr);
1404 #endif
1405 #endif
1406 free(data);
1407 }
1408 }
1409
1410
1411 static void *
mg_realloc_ex(void * memory,size_t newsize,struct mg_context * ctx,const char * file,unsigned line)1412 mg_realloc_ex(void *memory,
1413 size_t newsize,
1414 struct mg_context *ctx,
1415 const char *file,
1416 unsigned line)
1417 {
1418 void *data;
1419 void *_realloc;
1420 uintptr_t oldsize;
1421
1422 #if defined(MEMORY_DEBUGGING)
1423 char mallocStr[256];
1424 #else
1425 (void)file;
1426 (void)line;
1427 #endif
1428
1429 if (newsize) {
1430 if (memory) {
1431 /* Reallocate existing block */
1432 struct mg_memory_stat *mstat;
1433 data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1434 oldsize = ((uintptr_t *)data)[0];
1435 mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
1436 _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
1437 if (_realloc) {
1438 data = _realloc;
1439 mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
1440 #if defined(MEMORY_DEBUGGING)
1441 sprintf(mallocStr,
1442 "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
1443 memory,
1444 (unsigned long)oldsize,
1445 (unsigned long)mstat->totalMemUsed,
1446 (unsigned long)mstat->blockCount,
1447 file,
1448 line);
1449 #if defined(_WIN32)
1450 OutputDebugStringA(mallocStr);
1451 #else
1452 DEBUG_TRACE("%s", mallocStr);
1453 #endif
1454 #endif
1455 mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
1456 #if defined(MEMORY_DEBUGGING)
1457 sprintf(mallocStr,
1458 "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
1459 memory,
1460 (unsigned long)newsize,
1461 (unsigned long)mstat->totalMemUsed,
1462 (unsigned long)mstat->blockCount,
1463 file,
1464 line);
1465 #if defined(_WIN32)
1466 OutputDebugStringA(mallocStr);
1467 #else
1468 DEBUG_TRACE("%s", mallocStr);
1469 #endif
1470 #endif
1471 *(uintptr_t *)data = newsize;
1472 data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1473 } else {
1474 #if defined(MEMORY_DEBUGGING)
1475 #if defined(_WIN32)
1476 OutputDebugStringA("MEM: realloc failed\n");
1477 #else
1478 DEBUG_TRACE("%s", "MEM: realloc failed\n");
1479 #endif
1480 #endif
1481 return _realloc;
1482 }
1483 } else {
1484 /* Allocate new block */
1485 data = mg_malloc_ex(newsize, ctx, file, line);
1486 }
1487 } else {
1488 /* Free existing block */
1489 data = 0;
1490 mg_free_ex(memory, file, line);
1491 }
1492
1493 return data;
1494 }
1495
1496 #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
1497 #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
1498 #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
1499 #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
1500
1501 #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
1502 #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
1503 #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
1504
1505 #else /* USE_SERVER_STATS */
1506
1507 static __inline void *
mg_malloc(size_t a)1508 mg_malloc(size_t a)
1509 {
1510 return malloc(a);
1511 }
1512
1513 static __inline void *
mg_calloc(size_t a,size_t b)1514 mg_calloc(size_t a, size_t b)
1515 {
1516 return calloc(a, b);
1517 }
1518
1519 static __inline void *
mg_realloc(void * a,size_t b)1520 mg_realloc(void *a, size_t b)
1521 {
1522 return realloc(a, b);
1523 }
1524
1525 static __inline void
mg_free(void * a)1526 mg_free(void *a)
1527 {
1528 free(a);
1529 }
1530
1531 #define mg_malloc_ctx(a, c) mg_malloc(a)
1532 #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
1533 #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
1534 #define mg_free_ctx(a, c) mg_free(a)
1535
1536 #endif /* USE_SERVER_STATS */
1537
1538
1539 static void mg_vsnprintf(const struct mg_connection *conn,
1540 int *truncated,
1541 char *buf,
1542 size_t buflen,
1543 const char *fmt,
1544 va_list ap);
1545
1546 static void mg_snprintf(const struct mg_connection *conn,
1547 int *truncated,
1548 char *buf,
1549 size_t buflen,
1550 PRINTF_FORMAT_STRING(const char *fmt),
1551 ...) PRINTF_ARGS(5, 6);
1552
1553 /* This following lines are just meant as a reminder to use the mg-functions
1554 * for memory management */
1555 #if defined(malloc)
1556 #undef malloc
1557 #endif
1558 #if defined(calloc)
1559 #undef calloc
1560 #endif
1561 #if defined(realloc)
1562 #undef realloc
1563 #endif
1564 #if defined(free)
1565 #undef free
1566 #endif
1567 #if defined(snprintf)
1568 #undef snprintf
1569 #endif
1570 #if defined(vsnprintf)
1571 #undef vsnprintf
1572 #endif
1573 #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
1574 #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
1575 #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
1576 #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
1577 #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
1578 #if defined(_WIN32)
1579 /* vsnprintf must not be used in any system,
1580 * but this define only works well for Windows. */
1581 #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
1582 #endif
1583
1584
1585 /* mg_init_library counter */
1586 static int mg_init_library_called = 0;
1587
1588 #if !defined(NO_SSL)
1589 static int mg_ssl_initialized = 0;
1590 #endif
1591
1592 static pthread_key_t sTlsKey; /* Thread local storage index */
1593 static int thread_idx_max = 0;
1594
1595 #if defined(MG_LEGACY_INTERFACE)
1596 #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
1597 #endif
1598
1599 struct mg_workerTLS {
1600 int is_master;
1601 unsigned long thread_idx;
1602 void *user_ptr;
1603 #if defined(_WIN32)
1604 HANDLE pthread_cond_helper_mutex;
1605 struct mg_workerTLS *next_waiting_thread;
1606 #endif
1607 #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
1608 char txtbuf[4];
1609 #endif
1610 };
1611
1612
1613 #if defined(GCC_DIAGNOSTIC)
1614 /* Show no warning in case system functions are not used. */
1615 #pragma GCC diagnostic push
1616 #pragma GCC diagnostic ignored "-Wunused-function"
1617 #endif /* defined(GCC_DIAGNOSTIC) */
1618 #if defined(__clang__)
1619 /* Show no warning in case system functions are not used. */
1620 #pragma clang diagnostic push
1621 #pragma clang diagnostic ignored "-Wunused-function"
1622 #endif
1623
1624
1625 /* Get a unique thread ID as unsigned long, independent from the data type
1626 * of thread IDs defined by the operating system API.
1627 * If two calls to mg_current_thread_id return the same value, they calls
1628 * are done from the same thread. If they return different values, they are
1629 * done from different threads. (Provided this function is used in the same
1630 * process context and threads are not repeatedly created and deleted, but
1631 * CivetWeb does not do that).
1632 * This function must match the signature required for SSL id callbacks:
1633 * CRYPTO_set_id_callback
1634 */
1635 FUNCTION_MAY_BE_UNUSED
1636 static unsigned long
mg_current_thread_id(void)1637 mg_current_thread_id(void)
1638 {
1639 #if defined(_WIN32)
1640 return GetCurrentThreadId();
1641 #else
1642
1643 #if defined(__clang__)
1644 #pragma clang diagnostic push
1645 #pragma clang diagnostic ignored "-Wunreachable-code"
1646 /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
1647 * or not, so one of the two conditions will be unreachable by construction.
1648 * Unfortunately the C standard does not define a way to check this at
1649 * compile time, since the #if preprocessor conditions can not use the sizeof
1650 * operator as an argument. */
1651 #endif
1652
1653 if (sizeof(pthread_t) > sizeof(unsigned long)) {
1654 /* This is the problematic case for CRYPTO_set_id_callback:
1655 * The OS pthread_t can not be cast to unsigned long. */
1656 struct mg_workerTLS *tls =
1657 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
1658 if (tls == NULL) {
1659 /* SSL called from an unknown thread: Create some thread index.
1660 */
1661 tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
1662 tls->is_master = -2; /* -2 means "3rd party thread" */
1663 tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
1664 pthread_setspecific(sTlsKey, tls);
1665 }
1666 return tls->thread_idx;
1667 } else {
1668 /* pthread_t may be any data type, so a simple cast to unsigned long
1669 * can rise a warning/error, depending on the platform.
1670 * Here memcpy is used as an anything-to-anything cast. */
1671 unsigned long ret = 0;
1672 pthread_t t = pthread_self();
1673 memcpy(&ret, &t, sizeof(pthread_t));
1674 return ret;
1675 }
1676
1677 #if defined(__clang__)
1678 #pragma clang diagnostic pop
1679 #endif
1680
1681 #endif
1682 }
1683
1684
1685 FUNCTION_MAY_BE_UNUSED
1686 static uint64_t
mg_get_current_time_ns(void)1687 mg_get_current_time_ns(void)
1688 {
1689 struct timespec tsnow;
1690 clock_gettime(CLOCK_REALTIME, &tsnow);
1691 return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
1692 }
1693
1694
1695 #if defined(GCC_DIAGNOSTIC)
1696 /* Show no warning in case system functions are not used. */
1697 #pragma GCC diagnostic pop
1698 #endif /* defined(GCC_DIAGNOSTIC) */
1699 #if defined(__clang__)
1700 /* Show no warning in case system functions are not used. */
1701 #pragma clang diagnostic pop
1702 #endif
1703
1704
1705 #if defined(NEED_DEBUG_TRACE_FUNC)
1706 static void
DEBUG_TRACE_FUNC(const char * func,unsigned line,const char * fmt,...)1707 DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
1708 {
1709 va_list args;
1710 uint64_t nsnow;
1711 static uint64_t nslast;
1712 struct timespec tsnow;
1713
1714 /* Get some operating system independent thread id */
1715 unsigned long thread_id = mg_current_thread_id();
1716
1717 clock_gettime(CLOCK_REALTIME, &tsnow);
1718 nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
1719 + ((uint64_t)tsnow.tv_nsec);
1720
1721 if (!nslast) {
1722 nslast = nsnow;
1723 }
1724
1725 flockfile(stdout);
1726 printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
1727 (unsigned long)tsnow.tv_sec,
1728 (unsigned long)tsnow.tv_nsec,
1729 nsnow - nslast,
1730 thread_id,
1731 func,
1732 line);
1733 va_start(args, fmt);
1734 vprintf(fmt, args);
1735 va_end(args);
1736 putchar('\n');
1737 fflush(stdout);
1738 funlockfile(stdout);
1739 nslast = nsnow;
1740 }
1741 #endif /* NEED_DEBUG_TRACE_FUNC */
1742
1743
1744 #define MD5_STATIC static
1745 #include "md5.inl"
1746
1747 /* Darwin prior to 7.0 and Win32 do not have socklen_t */
1748 #if defined(NO_SOCKLEN_T)
1749 typedef int socklen_t;
1750 #endif /* NO_SOCKLEN_T */
1751
1752 #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
1753
1754 #if !defined(MSG_NOSIGNAL)
1755 #define MSG_NOSIGNAL (0)
1756 #endif
1757
1758
1759 #if defined(NO_SSL)
1760 typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
1761 typedef struct SSL_CTX SSL_CTX;
1762 #else
1763 #if defined(NO_SSL_DL)
1764 #include <openssl/bn.h>
1765 #include <openssl/conf.h>
1766 #include <openssl/crypto.h>
1767 #include <openssl/dh.h>
1768 #include <openssl/engine.h>
1769 #include <openssl/err.h>
1770 #include <openssl/opensslv.h>
1771 #include <openssl/pem.h>
1772 #include <openssl/ssl.h>
1773 #include <openssl/tls1.h>
1774 #include <openssl/x509.h>
1775
1776 #if defined(WOLFSSL_VERSION)
1777 /* Additional defines for WolfSSL, see
1778 * https://github.com/civetweb/civetweb/issues/583 */
1779 #include "wolfssl_extras.inl"
1780 #endif
1781
1782 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1783 /* If OpenSSL headers are included, automatically select the API version */
1784 #if !defined(OPENSSL_API_1_1)
1785 #define OPENSSL_API_1_1
1786 #endif
1787 #define OPENSSL_REMOVE_THREAD_STATE()
1788 #else
1789 #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
1790 #endif
1791
1792 #else
1793
1794 /* SSL loaded dynamically from DLL.
1795 * I put the prototypes here to be independent from OpenSSL source
1796 * installation. */
1797
1798 typedef struct ssl_st SSL;
1799 typedef struct ssl_method_st SSL_METHOD;
1800 typedef struct ssl_ctx_st SSL_CTX;
1801 typedef struct x509_store_ctx_st X509_STORE_CTX;
1802 typedef struct x509_name X509_NAME;
1803 typedef struct asn1_integer ASN1_INTEGER;
1804 typedef struct bignum BIGNUM;
1805 typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
1806 typedef struct evp_md EVP_MD;
1807 typedef struct x509 X509;
1808
1809
1810 #define SSL_CTRL_OPTIONS (32)
1811 #define SSL_CTRL_CLEAR_OPTIONS (77)
1812 #define SSL_CTRL_SET_ECDH_AUTO (94)
1813
1814 #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
1815 #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
1816 #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
1817
1818 #define SSL_VERIFY_NONE (0)
1819 #define SSL_VERIFY_PEER (1)
1820 #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
1821 #define SSL_VERIFY_CLIENT_ONCE (4)
1822
1823 #define SSL_OP_ALL (0x80000BFFul)
1824
1825 #define SSL_OP_NO_SSLv2 (0x01000000ul)
1826 #define SSL_OP_NO_SSLv3 (0x02000000ul)
1827 #define SSL_OP_NO_TLSv1 (0x04000000ul)
1828 #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
1829 #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
1830 #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
1831 #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
1832 #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
1833 #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
1834 #define SSL_OP_NO_COMPRESSION (0x00020000ul)
1835 #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
1836
1837 #define SSL_CB_HANDSHAKE_START (0x10)
1838 #define SSL_CB_HANDSHAKE_DONE (0x20)
1839
1840 #define SSL_ERROR_NONE (0)
1841 #define SSL_ERROR_SSL (1)
1842 #define SSL_ERROR_WANT_READ (2)
1843 #define SSL_ERROR_WANT_WRITE (3)
1844 #define SSL_ERROR_WANT_X509_LOOKUP (4)
1845 #define SSL_ERROR_SYSCALL (5) /* see errno */
1846 #define SSL_ERROR_ZERO_RETURN (6)
1847 #define SSL_ERROR_WANT_CONNECT (7)
1848 #define SSL_ERROR_WANT_ACCEPT (8)
1849
1850 #define TLSEXT_TYPE_server_name (0)
1851 #define TLSEXT_NAMETYPE_host_name (0)
1852 #define SSL_TLSEXT_ERR_OK (0)
1853 #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
1854 #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
1855 #define SSL_TLSEXT_ERR_NOACK (3)
1856
1857 struct ssl_func {
1858 const char *name; /* SSL function name */
1859 void (*ptr)(void); /* Function pointer */
1860 };
1861
1862
1863 #if defined(OPENSSL_API_1_1)
1864
1865 #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
1866 #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
1867 #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
1868 #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
1869 #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
1870 #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
1871 #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
1872 #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
1873 #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
1874 #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
1875 #define OPENSSL_init_ssl \
1876 (*(int (*)(uint64_t opts, \
1877 const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
1878 .ptr)
1879 #define SSL_CTX_use_PrivateKey_file \
1880 (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
1881 #define SSL_CTX_use_certificate_file \
1882 (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
1883 #define SSL_CTX_set_default_passwd_cb \
1884 (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
1885 #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
1886 #define SSL_CTX_use_certificate_chain_file \
1887 (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
1888 #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
1889 #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
1890 #define SSL_CTX_set_verify \
1891 (*(void (*)(SSL_CTX *, \
1892 int, \
1893 int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
1894 .ptr)
1895 #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
1896 #define SSL_CTX_load_verify_locations \
1897 (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
1898 #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
1899 #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
1900 #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
1901 #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
1902 #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
1903 #define SSL_CIPHER_get_name \
1904 (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
1905 #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
1906 #define SSL_CTX_set_session_id_context \
1907 (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
1908 #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
1909 #define SSL_CTX_set_cipher_list \
1910 (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
1911 #define SSL_CTX_set_options \
1912 (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
1913 #define SSL_CTX_set_info_callback \
1914 (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
1915 ssl_sw[32] \
1916 .ptr)
1917 #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
1918 #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
1919 #define SSL_CTX_callback_ctrl \
1920 (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
1921 #define SSL_get_servername \
1922 (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
1923 #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
1924 #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
1925
1926 #define SSL_CTX_clear_options(ctx, op) \
1927 SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
1928 #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
1929 SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
1930
1931 #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
1932 #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
1933 #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
1934 #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
1935 SSL_CTX_callback_ctrl(ctx, \
1936 SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
1937 (void (*)(void))cb)
1938 #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
1939 SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
1940 #define SSL_set_tlsext_host_name(ctx, arg) \
1941 SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
1942
1943 #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
1944 #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
1945
1946 #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
1947 #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
1948
1949 #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
1950 #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
1951 #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
1952 #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
1953 #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
1954 #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
1955 #define X509_NAME_oneline \
1956 (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
1957 #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
1958 #define EVP_get_digestbyname \
1959 (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
1960 #define EVP_Digest \
1961 (*(int (*)( \
1962 const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
1963 crypto_sw[9] \
1964 .ptr)
1965 #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
1966 #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
1967 #define ASN1_INTEGER_to_BN \
1968 (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
1969 #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
1970 #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
1971 #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
1972
1973 #define OPENSSL_free(a) CRYPTO_free(a)
1974
1975 #define OPENSSL_REMOVE_THREAD_STATE()
1976
1977 /* init_ssl_ctx() function updates this array.
1978 * It loads SSL library dynamically and changes NULLs to the actual addresses
1979 * of respective functions. The macros above (like SSL_connect()) are really
1980 * just calling these functions indirectly via the pointer. */
1981 static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
1982 {"SSL_accept", NULL},
1983 {"SSL_connect", NULL},
1984 {"SSL_read", NULL},
1985 {"SSL_write", NULL},
1986 {"SSL_get_error", NULL},
1987 {"SSL_set_fd", NULL},
1988 {"SSL_new", NULL},
1989 {"SSL_CTX_new", NULL},
1990 {"TLS_server_method", NULL},
1991 {"OPENSSL_init_ssl", NULL},
1992 {"SSL_CTX_use_PrivateKey_file", NULL},
1993 {"SSL_CTX_use_certificate_file", NULL},
1994 {"SSL_CTX_set_default_passwd_cb", NULL},
1995 {"SSL_CTX_free", NULL},
1996 {"SSL_CTX_use_certificate_chain_file", NULL},
1997 {"TLS_client_method", NULL},
1998 {"SSL_pending", NULL},
1999 {"SSL_CTX_set_verify", NULL},
2000 {"SSL_shutdown", NULL},
2001 {"SSL_CTX_load_verify_locations", NULL},
2002 {"SSL_CTX_set_default_verify_paths", NULL},
2003 {"SSL_CTX_set_verify_depth", NULL},
2004 {"SSL_get_peer_certificate", NULL},
2005 {"SSL_get_version", NULL},
2006 {"SSL_get_current_cipher", NULL},
2007 {"SSL_CIPHER_get_name", NULL},
2008 {"SSL_CTX_check_private_key", NULL},
2009 {"SSL_CTX_set_session_id_context", NULL},
2010 {"SSL_CTX_ctrl", NULL},
2011 {"SSL_CTX_set_cipher_list", NULL},
2012 {"SSL_CTX_set_options", NULL},
2013 {"SSL_CTX_set_info_callback", NULL},
2014 {"SSL_get_ex_data", NULL},
2015 {"SSL_set_ex_data", NULL},
2016 {"SSL_CTX_callback_ctrl", NULL},
2017 {"SSL_get_servername", NULL},
2018 {"SSL_set_SSL_CTX", NULL},
2019 {"SSL_ctrl", NULL},
2020 {NULL, NULL}};
2021
2022
2023 /* Similar array as ssl_sw. These functions could be located in different
2024 * lib. */
2025 static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
2026 {"ERR_error_string", NULL},
2027 {"CONF_modules_unload", NULL},
2028 {"X509_free", NULL},
2029 {"X509_get_subject_name", NULL},
2030 {"X509_get_issuer_name", NULL},
2031 {"X509_NAME_oneline", NULL},
2032 {"X509_get_serialNumber", NULL},
2033 {"EVP_get_digestbyname", NULL},
2034 {"EVP_Digest", NULL},
2035 {"i2d_X509", NULL},
2036 {"BN_bn2hex", NULL},
2037 {"ASN1_INTEGER_to_BN", NULL},
2038 {"BN_free", NULL},
2039 {"CRYPTO_free", NULL},
2040 {"ERR_clear_error", NULL},
2041 {NULL, NULL}};
2042 #else
2043
2044 #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
2045 #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
2046 #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
2047 #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
2048 #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
2049 #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
2050 #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
2051 #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
2052 #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
2053 #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
2054 #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
2055 #define SSL_CTX_use_PrivateKey_file \
2056 (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
2057 #define SSL_CTX_use_certificate_file \
2058 (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
2059 #define SSL_CTX_set_default_passwd_cb \
2060 (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
2061 #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
2062 #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
2063 #define SSL_CTX_use_certificate_chain_file \
2064 (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
2065 #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
2066 #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
2067 #define SSL_CTX_set_verify \
2068 (*(void (*)(SSL_CTX *, \
2069 int, \
2070 int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
2071 .ptr)
2072 #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
2073 #define SSL_CTX_load_verify_locations \
2074 (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
2075 #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
2076 #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
2077 #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
2078 #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
2079 #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
2080 #define SSL_CIPHER_get_name \
2081 (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
2082 #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
2083 #define SSL_CTX_set_session_id_context \
2084 (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
2085 #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
2086 #define SSL_CTX_set_cipher_list \
2087 (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
2088 #define SSL_CTX_set_info_callback \
2089 (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
2090 .ptr)
2091 #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
2092 #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
2093 #define SSL_CTX_callback_ctrl \
2094 (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
2095 #define SSL_get_servername \
2096 (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
2097 #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
2098 #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
2099
2100 #define SSL_CTX_set_options(ctx, op) \
2101 SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
2102 #define SSL_CTX_clear_options(ctx, op) \
2103 SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
2104 #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
2105 SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
2106
2107 #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
2108 #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
2109 #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
2110 #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
2111 SSL_CTX_callback_ctrl(ctx, \
2112 SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
2113 (void (*)(void))cb)
2114 #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
2115 SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
2116 #define SSL_set_tlsext_host_name(ctx, arg) \
2117 SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
2118
2119 #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
2120 #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
2121
2122 #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
2123 #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
2124
2125 #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
2126 #define CRYPTO_set_locking_callback \
2127 (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
2128 #define CRYPTO_set_id_callback \
2129 (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
2130 #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
2131 #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
2132 #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
2133 #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
2134 #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
2135 #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
2136 #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
2137 #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
2138 #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
2139 #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
2140 #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
2141 #define X509_NAME_oneline \
2142 (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
2143 #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
2144 #define i2c_ASN1_INTEGER \
2145 (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
2146 #define EVP_get_digestbyname \
2147 (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
2148 #define EVP_Digest \
2149 (*(int (*)( \
2150 const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
2151 crypto_sw[18] \
2152 .ptr)
2153 #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
2154 #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
2155 #define ASN1_INTEGER_to_BN \
2156 (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
2157 #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
2158 #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
2159 #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
2160
2161 #define OPENSSL_free(a) CRYPTO_free(a)
2162
2163 /* use here ERR_remove_state,
2164 * while on some platforms function is not included into library due to
2165 * deprication */
2166 #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
2167
2168 /* init_ssl_ctx() function updates this array.
2169 * It loads SSL library dynamically and changes NULLs to the actual addresses
2170 * of respective functions. The macros above (like SSL_connect()) are really
2171 * just calling these functions indirectly via the pointer. */
2172 static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
2173 {"SSL_accept", NULL},
2174 {"SSL_connect", NULL},
2175 {"SSL_read", NULL},
2176 {"SSL_write", NULL},
2177 {"SSL_get_error", NULL},
2178 {"SSL_set_fd", NULL},
2179 {"SSL_new", NULL},
2180 {"SSL_CTX_new", NULL},
2181 {"SSLv23_server_method", NULL},
2182 {"SSL_library_init", NULL},
2183 {"SSL_CTX_use_PrivateKey_file", NULL},
2184 {"SSL_CTX_use_certificate_file", NULL},
2185 {"SSL_CTX_set_default_passwd_cb", NULL},
2186 {"SSL_CTX_free", NULL},
2187 {"SSL_load_error_strings", NULL},
2188 {"SSL_CTX_use_certificate_chain_file", NULL},
2189 {"SSLv23_client_method", NULL},
2190 {"SSL_pending", NULL},
2191 {"SSL_CTX_set_verify", NULL},
2192 {"SSL_shutdown", NULL},
2193 {"SSL_CTX_load_verify_locations", NULL},
2194 {"SSL_CTX_set_default_verify_paths", NULL},
2195 {"SSL_CTX_set_verify_depth", NULL},
2196 {"SSL_get_peer_certificate", NULL},
2197 {"SSL_get_version", NULL},
2198 {"SSL_get_current_cipher", NULL},
2199 {"SSL_CIPHER_get_name", NULL},
2200 {"SSL_CTX_check_private_key", NULL},
2201 {"SSL_CTX_set_session_id_context", NULL},
2202 {"SSL_CTX_ctrl", NULL},
2203 {"SSL_CTX_set_cipher_list", NULL},
2204 {"SSL_CTX_set_info_callback", NULL},
2205 {"SSL_get_ex_data", NULL},
2206 {"SSL_set_ex_data", NULL},
2207 {"SSL_CTX_callback_ctrl", NULL},
2208 {"SSL_get_servername", NULL},
2209 {"SSL_set_SSL_CTX", NULL},
2210 {"SSL_ctrl", NULL},
2211 {NULL, NULL}};
2212
2213
2214 /* Similar array as ssl_sw. These functions could be located in different
2215 * lib. */
2216 static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
2217 {"CRYPTO_set_locking_callback", NULL},
2218 {"CRYPTO_set_id_callback", NULL},
2219 {"ERR_get_error", NULL},
2220 {"ERR_error_string", NULL},
2221 {"ERR_remove_state", NULL},
2222 {"ERR_free_strings", NULL},
2223 {"ENGINE_cleanup", NULL},
2224 {"CONF_modules_unload", NULL},
2225 {"CRYPTO_cleanup_all_ex_data", NULL},
2226 {"EVP_cleanup", NULL},
2227 {"X509_free", NULL},
2228 {"X509_get_subject_name", NULL},
2229 {"X509_get_issuer_name", NULL},
2230 {"X509_NAME_oneline", NULL},
2231 {"X509_get_serialNumber", NULL},
2232 {"i2c_ASN1_INTEGER", NULL},
2233 {"EVP_get_digestbyname", NULL},
2234 {"EVP_Digest", NULL},
2235 {"i2d_X509", NULL},
2236 {"BN_bn2hex", NULL},
2237 {"ASN1_INTEGER_to_BN", NULL},
2238 {"BN_free", NULL},
2239 {"CRYPTO_free", NULL},
2240 {"ERR_clear_error", NULL},
2241 {NULL, NULL}};
2242 #endif /* OPENSSL_API_1_1 */
2243 #endif /* NO_SSL_DL */
2244 #endif /* NO_SSL */
2245
2246
2247 #if !defined(NO_CACHING)
2248 static const char month_names[][4] = {"Jan",
2249 "Feb",
2250 "Mar",
2251 "Apr",
2252 "May",
2253 "Jun",
2254 "Jul",
2255 "Aug",
2256 "Sep",
2257 "Oct",
2258 "Nov",
2259 "Dec"};
2260 #endif /* !NO_CACHING */
2261
2262 /* Unified socket address. For IPv6 support, add IPv6 address structure in
2263 * the
2264 * union u. */
2265 union usa {
2266 struct sockaddr sa;
2267 struct sockaddr_in sin;
2268 #if defined(USE_IPV6)
2269 struct sockaddr_in6 sin6;
2270 #endif
2271 };
2272
2273 /* Describes a string (chunk of memory). */
2274 struct vec {
2275 const char *ptr;
2276 size_t len;
2277 };
2278
2279 struct mg_file_stat {
2280 /* File properties filled by mg_stat: */
2281 uint64_t size;
2282 time_t last_modified;
2283 int is_directory; /* Set to 1 if mg_stat is called for a directory */
2284 int is_gzipped; /* Set to 1 if the content is gzipped, in which
2285 * case we need a "Content-Eencoding: gzip" header */
2286 int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
2287 };
2288
2289 struct mg_file_in_memory {
2290 char *p;
2291 uint32_t pos;
2292 char mode;
2293 };
2294
2295 struct mg_file_access {
2296 /* File properties filled by mg_fopen: */
2297 FILE *fp;
2298 #if defined(MG_USE_OPEN_FILE)
2299 /* TODO (low): Remove obsolete "file in memory" implementation.
2300 * In an "early 2017" discussion at Google groups
2301 * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
2302 * we decided to get rid of this feature (after some fade-out
2303 * phase). */
2304 const char *membuf;
2305 #endif
2306 };
2307
2308 struct mg_file {
2309 struct mg_file_stat stat;
2310 struct mg_file_access access;
2311 };
2312
2313 #if defined(MG_USE_OPEN_FILE)
2314
2315 #define STRUCT_FILE_INITIALIZER \
2316 { \
2317 {(uint64_t)0, (time_t)0, 0, 0, 0}, \
2318 { \
2319 (FILE *)NULL, (const char *)NULL \
2320 } \
2321 }
2322
2323 #else
2324
2325 #define STRUCT_FILE_INITIALIZER \
2326 { \
2327 {(uint64_t)0, (time_t)0, 0, 0, 0}, \
2328 { \
2329 (FILE *)NULL \
2330 } \
2331 }
2332
2333 #endif
2334
2335
2336 /* Describes listening socket, or socket which was accept()-ed by the master
2337 * thread and queued for future handling by the worker thread. */
2338 struct socket {
2339 SOCKET sock; /* Listening socket */
2340 union usa lsa; /* Local socket address */
2341 union usa rsa; /* Remote socket address */
2342 unsigned char is_ssl; /* Is port SSL-ed */
2343 unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
2344 * port */
2345 unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
2346 };
2347
2348
2349 /* Enum const for all options must be in sync with
2350 * static struct mg_option config_options[]
2351 * This is tested in the unit test (test/private.c)
2352 * "Private Config Options"
2353 */
2354 enum {
2355 /* Once for each server */
2356 LISTENING_PORTS,
2357 NUM_THREADS,
2358 RUN_AS_USER,
2359 CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
2360 * socket option typedef TCP_NODELAY. */
2361 MAX_REQUEST_SIZE,
2362 LINGER_TIMEOUT,
2363 MAX_CONNECTIONS,
2364 #if defined(__linux__)
2365 ALLOW_SENDFILE_CALL,
2366 #endif
2367 #if defined(_WIN32)
2368 CASE_SENSITIVE_FILES,
2369 #endif
2370 THROTTLE,
2371 ACCESS_LOG_FILE,
2372 ERROR_LOG_FILE,
2373 ENABLE_KEEP_ALIVE,
2374 REQUEST_TIMEOUT,
2375 KEEP_ALIVE_TIMEOUT,
2376 #if defined(USE_WEBSOCKET)
2377 WEBSOCKET_TIMEOUT,
2378 ENABLE_WEBSOCKET_PING_PONG,
2379 #endif
2380 DECODE_URL,
2381 #if defined(USE_LUA)
2382 LUA_BACKGROUND_SCRIPT,
2383 LUA_BACKGROUND_SCRIPT_PARAMS,
2384 #endif
2385 #if defined(USE_TIMERS)
2386 CGI_TIMEOUT,
2387 #endif
2388
2389 /* Once for each domain */
2390 DOCUMENT_ROOT,
2391 CGI_EXTENSIONS,
2392 CGI_ENVIRONMENT,
2393 PUT_DELETE_PASSWORDS_FILE,
2394 CGI_INTERPRETER,
2395 PROTECT_URI,
2396 AUTHENTICATION_DOMAIN,
2397 ENABLE_AUTH_DOMAIN_CHECK,
2398 SSI_EXTENSIONS,
2399 ENABLE_DIRECTORY_LISTING,
2400 GLOBAL_PASSWORDS_FILE,
2401 INDEX_FILES,
2402 ACCESS_CONTROL_LIST,
2403 EXTRA_MIME_TYPES,
2404 SSL_CERTIFICATE,
2405 SSL_CERTIFICATE_CHAIN,
2406 URL_REWRITE_PATTERN,
2407 HIDE_FILES,
2408 SSL_DO_VERIFY_PEER,
2409 SSL_CA_PATH,
2410 SSL_CA_FILE,
2411 SSL_VERIFY_DEPTH,
2412 SSL_DEFAULT_VERIFY_PATHS,
2413 SSL_CIPHER_LIST,
2414 SSL_PROTOCOL_VERSION,
2415 SSL_SHORT_TRUST,
2416
2417 #if defined(USE_LUA)
2418 LUA_PRELOAD_FILE,
2419 LUA_SCRIPT_EXTENSIONS,
2420 LUA_SERVER_PAGE_EXTENSIONS,
2421 #if defined(MG_EXPERIMENTAL_INTERFACES)
2422 LUA_DEBUG_PARAMS,
2423 #endif
2424 #endif
2425 #if defined(USE_DUKTAPE)
2426 DUKTAPE_SCRIPT_EXTENSIONS,
2427 #endif
2428
2429 #if defined(USE_WEBSOCKET)
2430 WEBSOCKET_ROOT,
2431 #endif
2432 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
2433 LUA_WEBSOCKET_EXTENSIONS,
2434 #endif
2435
2436 ACCESS_CONTROL_ALLOW_ORIGIN,
2437 ACCESS_CONTROL_ALLOW_METHODS,
2438 ACCESS_CONTROL_ALLOW_HEADERS,
2439 ERROR_PAGES,
2440 #if !defined(NO_CACHING)
2441 STATIC_FILE_MAX_AGE,
2442 #endif
2443 #if !defined(NO_SSL)
2444 STRICT_HTTPS_MAX_AGE,
2445 #endif
2446 ADDITIONAL_HEADER,
2447 ALLOW_INDEX_SCRIPT_SUB_RES,
2448 #if defined(DAEMONIZE)
2449 ENABLE_DAEMONIZE,
2450 #endif
2451
2452 NUM_OPTIONS
2453 };
2454
2455
2456 /* Config option name, config types, default value.
2457 * Must be in the same order as the enum const above.
2458 */
2459 static const struct mg_option config_options[] = {
2460
2461 /* Once for each server */
2462 {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
2463 {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
2464 {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
2465 {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
2466 {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
2467 {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2468 {"max_connections", MG_CONFIG_TYPE_NUMBER, "100"},
2469 #if defined(__linux__)
2470 {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2471 #endif
2472 #if defined(_WIN32)
2473 {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2474 #endif
2475 {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
2476 {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
2477 {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
2478 {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2479 {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
2480 {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
2481 #if defined(USE_WEBSOCKET)
2482 {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2483 {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
2484 #endif
2485 {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2486 #if defined(USE_LUA)
2487 {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
2488 {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
2489 #endif
2490 #if defined(USE_TIMERS)
2491 {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2492 #endif
2493
2494 /* Once for each domain */
2495 {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2496 {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
2497 {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2498 {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2499 {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2500 {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
2501 {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
2502 {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2503 {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
2504 {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2505 {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2506 {"index_files",
2507 MG_CONFIG_TYPE_STRING_LIST,
2508 #if defined(USE_LUA)
2509 "index.xhtml,index.html,index.htm,"
2510 "index.lp,index.lsp,index.lua,index.cgi,"
2511 "index.shtml,index.php"},
2512 #else
2513 "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
2514 #endif
2515 {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
2516 {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
2517 {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
2518 {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
2519 {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
2520 {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2521
2522 {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
2523
2524 {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
2525 {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
2526 {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
2527 {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2528 {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
2529 {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
2530 {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
2531
2532 #if defined(USE_LUA)
2533 {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
2534 {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2535 {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
2536 #if defined(MG_EXPERIMENTAL_INTERFACES)
2537 {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
2538 #endif
2539 #endif
2540 #if defined(USE_DUKTAPE)
2541 /* The support for duktape is still in alpha version state.
2542 * The name of this config option might change. */
2543 {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
2544 #endif
2545
2546 #if defined(USE_WEBSOCKET)
2547 {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2548 #endif
2549 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
2550 {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2551 #endif
2552 {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
2553 {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
2554 {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
2555 {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
2556 #if !defined(NO_CACHING)
2557 {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
2558 #endif
2559 #if !defined(NO_SSL)
2560 {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
2561 #endif
2562 {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
2563 {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
2564 #if defined(DAEMONIZE)
2565 {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
2566 #endif
2567
2568 {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
2569
2570
2571 /* Check if the config_options and the corresponding enum have compatible
2572 * sizes. */
2573 mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
2574 == (NUM_OPTIONS + 1),
2575 "config_options and enum not sync");
2576
2577
2578 enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
2579
2580
2581 struct mg_handler_info {
2582 /* Name/Pattern of the URI. */
2583 char *uri;
2584 size_t uri_len;
2585
2586 /* handler type */
2587 int handler_type;
2588
2589 /* Handler for http/https or authorization requests. */
2590 mg_request_handler handler;
2591 unsigned int refcount;
2592 pthread_mutex_t refcount_mutex; /* Protects refcount */
2593 pthread_cond_t
2594 refcount_cond; /* Signaled when handler refcount is decremented */
2595
2596 /* Handler for ws/wss (websocket) requests. */
2597 mg_websocket_connect_handler connect_handler;
2598 mg_websocket_ready_handler ready_handler;
2599 mg_websocket_data_handler data_handler;
2600 mg_websocket_close_handler close_handler;
2601
2602 /* accepted subprotocols for ws/wss requests. */
2603 struct mg_websocket_subprotocols *subprotocols;
2604
2605 /* Handler for authorization requests */
2606 mg_authorization_handler auth_handler;
2607
2608 /* User supplied argument for the handler function. */
2609 void *cbdata;
2610
2611 /* next handler in a linked list */
2612 struct mg_handler_info *next;
2613 };
2614
2615
2616 enum {
2617 CONTEXT_INVALID,
2618 CONTEXT_SERVER,
2619 CONTEXT_HTTP_CLIENT,
2620 CONTEXT_WS_CLIENT
2621 };
2622
2623
2624 struct mg_domain_context {
2625 SSL_CTX *ssl_ctx; /* SSL context */
2626 char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
2627 struct mg_handler_info *handlers; /* linked list of uri handlers */
2628
2629 /* Server nonce */
2630 uint64_t auth_nonce_mask; /* Mask for all nonce values */
2631 unsigned long nonce_count; /* Used nonces, used for authentication */
2632
2633 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
2634 /* linked list of shared lua websockets */
2635 struct mg_shared_lua_websocket_list *shared_lua_websockets;
2636 #endif
2637
2638 /* Linked list of domains */
2639 struct mg_domain_context *next;
2640 };
2641
2642
2643 struct mg_context {
2644
2645 /* Part 1 - Physical context:
2646 * This holds threads, ports, timeouts, ...
2647 * set for the entire server, independent from the
2648 * addressed hostname.
2649 */
2650
2651 /* Connection related */
2652 int context_type; /* See CONTEXT_* above */
2653
2654 struct socket *listening_sockets;
2655 struct mg_pollfd *listening_socket_fds;
2656 unsigned int num_listening_sockets;
2657
2658 struct mg_connection *worker_connections; /* The connection struct, pre-
2659 * allocated for each worker */
2660
2661 #if defined(USE_SERVER_STATS)
2662 int active_connections;
2663 int max_connections;
2664 int64_t total_connections;
2665 int64_t total_requests;
2666 int64_t total_data_read;
2667 int64_t total_data_written;
2668 #endif
2669
2670 /* Thread related */
2671 volatile int stop_flag; /* Should we stop event loop */
2672 pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
2673
2674 pthread_t masterthreadid; /* The master thread ID */
2675 unsigned int
2676 cfg_worker_threads; /* The number of configured worker threads. */
2677 pthread_t *worker_threadids; /* The worker thread IDs */
2678
2679 /* Connection to thread dispatching */
2680 #if defined(ALTERNATIVE_QUEUE)
2681 struct socket *client_socks;
2682 void **client_wait_events;
2683 #else
2684 struct socket queue[MGSQLEN]; /* Accepted sockets */
2685 volatile int sq_head; /* Head of the socket queue */
2686 volatile int sq_tail; /* Tail of the socket queue */
2687 pthread_cond_t sq_full; /* Signaled when socket is produced */
2688 pthread_cond_t sq_empty; /* Signaled when socket is consumed */
2689 #endif
2690
2691 /* Memory related */
2692 unsigned int max_request_size; /* The max request size */
2693
2694 #if defined(USE_SERVER_STATS)
2695 struct mg_memory_stat ctx_memory;
2696 #endif
2697
2698 /* Operating system related */
2699 char *systemName; /* What operating system is running */
2700 time_t start_time; /* Server start time, used for authentication
2701 * and for diagnstics. */
2702
2703 #if defined(USE_TIMERS)
2704 struct ttimers *timers;
2705 #endif
2706
2707 /* Lua specific: Background operations and shared websockets */
2708 #if defined(USE_LUA)
2709 void *lua_background_state;
2710 #endif
2711
2712 /* Server nonce */
2713 pthread_mutex_t nonce_mutex; /* Protects nonce_count */
2714
2715 /* Server callbacks */
2716 struct mg_callbacks callbacks; /* User-defined callback function */
2717 void *user_data; /* User-defined data */
2718
2719 /* Part 2 - Logical domain:
2720 * This holds hostname, TLS certificate, document root, ...
2721 * set for a domain hosted at the server.
2722 * There may be multiple domains hosted at one physical server.
2723 * The default domain "dd" is the first element of a list of
2724 * domains.
2725 */
2726 struct mg_domain_context dd; /* default domain */
2727 };
2728
2729
2730 #if defined(USE_SERVER_STATS)
2731 static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2732
2733 static struct mg_memory_stat *
get_memory_stat(struct mg_context * ctx)2734 get_memory_stat(struct mg_context *ctx)
2735 {
2736 if (ctx) {
2737 return &(ctx->ctx_memory);
2738 }
2739 return &mg_common_memory;
2740 }
2741 #endif
2742
2743 enum {
2744 CONNECTION_TYPE_INVALID,
2745 CONNECTION_TYPE_REQUEST,
2746 CONNECTION_TYPE_RESPONSE
2747 };
2748
2749 struct mg_connection {
2750 int connection_type; /* see CONNECTION_TYPE_* above */
2751
2752 struct mg_request_info request_info;
2753 struct mg_response_info response_info;
2754
2755 struct mg_context *phys_ctx;
2756 struct mg_domain_context *dom_ctx;
2757
2758 #if defined(USE_SERVER_STATS)
2759 int conn_state; /* 0 = undef, numerical value may change in different
2760 * versions. For the current definition, see
2761 * mg_get_connection_info_impl */
2762 #endif
2763
2764 const char *host; /* Host (HTTP/1.1 header or SNI) */
2765 SSL *ssl; /* SSL descriptor */
2766 struct socket client; /* Connected client */
2767 time_t conn_birth_time; /* Time (wall clock) when connection was
2768 * established */
2769 struct timespec req_time; /* Time (since system start) when the request
2770 * was received */
2771 int64_t num_bytes_sent; /* Total bytes sent to client */
2772 int64_t content_len; /* How many bytes of content can be read
2773 * !is_chunked: Content-Length header value
2774 * or -1 (until connection closed,
2775 * not allowed for a request)
2776 * is_chunked: >= 0, appended gradually
2777 */
2778 int64_t consumed_content; /* How many bytes of content have been read */
2779 int is_chunked; /* Transfer-Encoding is chunked:
2780 * 0 = not chunked,
2781 * 1 = chunked, not yet, or some data read,
2782 * 2 = chunked, has error,
2783 * 3 = chunked, all data read except trailer,
2784 * 4 = chunked, all data read
2785 */
2786 char *buf; /* Buffer for received data */
2787 char *path_info; /* PATH_INFO part of the URL */
2788
2789 int must_close; /* 1 if connection must be closed */
2790 int accept_gzip; /* 1 if gzip encoding is accepted */
2791 int in_error_handler; /* 1 if in handler for user defined error
2792 * pages */
2793 #if defined(USE_WEBSOCKET)
2794 int in_websocket_handling; /* 1 if in read_websocket */
2795 #endif
2796 int handled_requests; /* Number of requests handled by this connection
2797 */
2798 int buf_size; /* Buffer size */
2799 int request_len; /* Size of the request + headers in a buffer */
2800 int data_len; /* Total size of data in a buffer */
2801 int status_code; /* HTTP reply status code, e.g. 200 */
2802 int throttle; /* Throttling, bytes/sec. <= 0 means no
2803 * throttle */
2804
2805 time_t last_throttle_time; /* Last time throttled data was sent */
2806 int last_throttle_bytes; /* Bytes sent this second */
2807 pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
2808 * atomic transmissions for websockets */
2809 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
2810 void *lua_websocket_state; /* Lua_State for a websocket connection */
2811 #endif
2812
2813 void *tls_user_ptr; /* User defined pointer in thread local storage,
2814 * for quick access */
2815 };
2816
2817
2818 /* Directory entry */
2819 struct de {
2820 struct mg_connection *conn;
2821 char *file_name;
2822 struct mg_file_stat file;
2823 };
2824
2825
2826 #if defined(USE_WEBSOCKET)
2827 static int is_websocket_protocol(const struct mg_connection *conn);
2828 #else
2829 #define is_websocket_protocol(conn) (0)
2830 #endif
2831
2832
2833 #define mg_cry_internal(conn, fmt, ...) \
2834 mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
2835
2836 #define mg_cry_ctx_internal(ctx, fmt, ...) \
2837 mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
2838
2839 static void mg_cry_internal_wrap(const struct mg_connection *conn,
2840 struct mg_context *ctx,
2841 const char *func,
2842 unsigned line,
2843 const char *fmt,
2844 ...) PRINTF_ARGS(5, 6);
2845
2846
2847 #if !defined(NO_THREAD_NAME)
2848 #if defined(_WIN32) && defined(_MSC_VER)
2849 /* Set the thread name for debugging purposes in Visual Studio
2850 * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
2851 */
2852 #pragma pack(push, 8)
2853 typedef struct tagTHREADNAME_INFO {
2854 DWORD dwType; /* Must be 0x1000. */
2855 LPCSTR szName; /* Pointer to name (in user addr space). */
2856 DWORD dwThreadID; /* Thread ID (-1=caller thread). */
2857 DWORD dwFlags; /* Reserved for future use, must be zero. */
2858 } THREADNAME_INFO;
2859 #pragma pack(pop)
2860
2861 #elif defined(__linux__)
2862
2863 #include <sys/prctl.h>
2864 #include <sys/sendfile.h>
2865 #if defined(ALTERNATIVE_QUEUE)
2866 #include <sys/eventfd.h>
2867 #endif /* ALTERNATIVE_QUEUE */
2868
2869
2870 #if defined(ALTERNATIVE_QUEUE)
2871
2872 static void *
event_create(void)2873 event_create(void)
2874 {
2875 int evhdl = eventfd(0, EFD_CLOEXEC);
2876 int *ret;
2877
2878 if (evhdl == -1) {
2879 /* Linux uses -1 on error, Windows NULL. */
2880 /* However, Linux does not return 0 on success either. */
2881 return 0;
2882 }
2883
2884 ret = (int *)mg_malloc(sizeof(int));
2885 if (ret) {
2886 *ret = evhdl;
2887 } else {
2888 (void)close(evhdl);
2889 }
2890
2891 return (void *)ret;
2892 }
2893
2894
2895 static int
event_wait(void * eventhdl)2896 event_wait(void *eventhdl)
2897 {
2898 uint64_t u;
2899 int evhdl, s;
2900
2901 if (!eventhdl) {
2902 /* error */
2903 return 0;
2904 }
2905 evhdl = *(int *)eventhdl;
2906
2907 s = (int)read(evhdl, &u, sizeof(u));
2908 if (s != sizeof(u)) {
2909 /* error */
2910 return 0;
2911 }
2912 (void)u; /* the value is not required */
2913 return 1;
2914 }
2915
2916
2917 static int
event_signal(void * eventhdl)2918 event_signal(void *eventhdl)
2919 {
2920 uint64_t u = 1;
2921 int evhdl, s;
2922
2923 if (!eventhdl) {
2924 /* error */
2925 return 0;
2926 }
2927 evhdl = *(int *)eventhdl;
2928
2929 s = (int)write(evhdl, &u, sizeof(u));
2930 if (s != sizeof(u)) {
2931 /* error */
2932 return 0;
2933 }
2934 return 1;
2935 }
2936
2937
2938 static void
event_destroy(void * eventhdl)2939 event_destroy(void *eventhdl)
2940 {
2941 int evhdl;
2942
2943 if (!eventhdl) {
2944 /* error */
2945 return;
2946 }
2947 evhdl = *(int *)eventhdl;
2948
2949 close(evhdl);
2950 mg_free(eventhdl);
2951 }
2952
2953
2954 #endif
2955
2956 #endif
2957
2958
2959 #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2960
2961 struct posix_event {
2962 pthread_mutex_t mutex;
2963 pthread_cond_t cond;
2964 int signaled;
2965 };
2966
2967
2968 static void *
event_create(void)2969 event_create(void)
2970 {
2971 struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
2972 if (ret == 0) {
2973 /* out of memory */
2974 return 0;
2975 }
2976 if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2977 /* pthread mutex not available */
2978 mg_free(ret);
2979 return 0;
2980 }
2981 if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2982 /* pthread cond not available */
2983 pthread_mutex_destroy(&(ret->mutex));
2984 mg_free(ret);
2985 return 0;
2986 }
2987 ret->signaled = 0;
2988 return (void *)ret;
2989 }
2990
2991
2992 static int
event_wait(void * eventhdl)2993 event_wait(void *eventhdl)
2994 {
2995 struct posix_event *ev = (struct posix_event *)eventhdl;
2996 pthread_mutex_lock(&(ev->mutex));
2997 while (!ev->signaled) {
2998 pthread_cond_wait(&(ev->cond), &(ev->mutex));
2999 }
3000 ev->signaled = 0;
3001 pthread_mutex_unlock(&(ev->mutex));
3002 return 1;
3003 }
3004
3005
3006 static int
event_signal(void * eventhdl)3007 event_signal(void *eventhdl)
3008 {
3009 struct posix_event *ev = (struct posix_event *)eventhdl;
3010 pthread_mutex_lock(&(ev->mutex));
3011 pthread_cond_signal(&(ev->cond));
3012 ev->signaled = 1;
3013 pthread_mutex_unlock(&(ev->mutex));
3014 return 1;
3015 }
3016
3017
3018 static void
event_destroy(void * eventhdl)3019 event_destroy(void *eventhdl)
3020 {
3021 struct posix_event *ev = (struct posix_event *)eventhdl;
3022 pthread_cond_destroy(&(ev->cond));
3023 pthread_mutex_destroy(&(ev->mutex));
3024 mg_free(ev);
3025 }
3026 #endif
3027
3028
3029 static void
mg_set_thread_name(const char * name)3030 mg_set_thread_name(const char *name)
3031 {
3032 char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
3033
3034 mg_snprintf(
3035 NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
3036
3037 #if defined(_WIN32)
3038 #if defined(_MSC_VER)
3039 /* Windows and Visual Studio Compiler */
3040 __try {
3041 THREADNAME_INFO info;
3042 info.dwType = 0x1000;
3043 info.szName = threadName;
3044 info.dwThreadID = ~0U;
3045 info.dwFlags = 0;
3046
3047 RaiseException(0x406D1388,
3048 0,
3049 sizeof(info) / sizeof(ULONG_PTR),
3050 (ULONG_PTR *)&info);
3051 } __except (EXCEPTION_EXECUTE_HANDLER) {
3052 }
3053 #elif defined(__MINGW32__)
3054 /* No option known to set thread name for MinGW */
3055 #endif
3056 #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
3057 && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
3058 /* pthread_setname_np first appeared in glibc in version 2.12*/
3059 #if defined(__MACH__)
3060 /* OS X only current thread name can be changed */
3061 (void)pthread_setname_np(threadName);
3062 #else
3063 (void)pthread_setname_np(pthread_self(), threadName);
3064 #endif
3065 #elif defined(__linux__)
3066 /* on linux we can use the old prctl function */
3067 (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
3068 #endif
3069 }
3070 #else /* !defined(NO_THREAD_NAME) */
3071 void
mg_set_thread_name(const char * threadName)3072 mg_set_thread_name(const char *threadName)
3073 {
3074 }
3075 #endif
3076
3077
3078 #if defined(MG_LEGACY_INTERFACE)
3079 const char **
mg_get_valid_option_names(void)3080 mg_get_valid_option_names(void)
3081 {
3082 /* This function is deprecated. Use mg_get_valid_options instead. */
3083 static const char
3084 *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
3085 int i;
3086
3087 for (i = 0; config_options[i].name != NULL; i++) {
3088 data[i * 2] = config_options[i].name;
3089 data[i * 2 + 1] = config_options[i].default_value;
3090 }
3091
3092 return data;
3093 }
3094 #endif
3095
3096
3097 const struct mg_option *
mg_get_valid_options(void)3098 mg_get_valid_options(void)
3099 {
3100 return config_options;
3101 }
3102
3103
3104 /* Do not open file (used in is_file_in_memory) */
3105 #define MG_FOPEN_MODE_NONE (0)
3106
3107 /* Open file for read only access */
3108 #define MG_FOPEN_MODE_READ (1)
3109
3110 /* Open file for writing, create and overwrite */
3111 #define MG_FOPEN_MODE_WRITE (2)
3112
3113 /* Open file for writing, create and append */
3114 #define MG_FOPEN_MODE_APPEND (4)
3115
3116
3117 /* If a file is in memory, set all "stat" members and the membuf pointer of
3118 * output filep and return 1, otherwise return 0 and don't modify anything.
3119 */
3120 static int
open_file_in_memory(const struct mg_connection * conn,const char * path,struct mg_file * filep,int mode)3121 open_file_in_memory(const struct mg_connection *conn,
3122 const char *path,
3123 struct mg_file *filep,
3124 int mode)
3125 {
3126 #if defined(MG_USE_OPEN_FILE)
3127
3128 size_t size = 0;
3129 const char *buf = NULL;
3130 if (!conn) {
3131 return 0;
3132 }
3133
3134 if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
3135 return 0;
3136 }
3137
3138 if (conn->phys_ctx->callbacks.open_file) {
3139 buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
3140 if (buf != NULL) {
3141 if (filep == NULL) {
3142 /* This is a file in memory, but we cannot store the
3143 * properties
3144 * now.
3145 * Called from "is_file_in_memory" function. */
3146 return 1;
3147 }
3148
3149 /* NOTE: override filep->size only on success. Otherwise, it
3150 * might
3151 * break constructs like if (!mg_stat() || !mg_fopen()) ... */
3152 filep->access.membuf = buf;
3153 filep->access.fp = NULL;
3154
3155 /* Size was set by the callback */
3156 filep->stat.size = size;
3157
3158 /* Assume the data may change during runtime by setting
3159 * last_modified = now */
3160 filep->stat.last_modified = time(NULL);
3161
3162 filep->stat.is_directory = 0;
3163 filep->stat.is_gzipped = 0;
3164 }
3165 }
3166
3167 return (buf != NULL);
3168
3169 #else
3170 (void)conn;
3171 (void)path;
3172 (void)filep;
3173 (void)mode;
3174
3175 return 0;
3176
3177 #endif
3178 }
3179
3180
3181 static int
is_file_in_memory(const struct mg_connection * conn,const char * path)3182 is_file_in_memory(const struct mg_connection *conn, const char *path)
3183 {
3184 return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
3185 }
3186
3187
3188 static int
is_file_opened(const struct mg_file_access * fileacc)3189 is_file_opened(const struct mg_file_access *fileacc)
3190 {
3191 if (!fileacc) {
3192 return 0;
3193 }
3194
3195 #if defined(MG_USE_OPEN_FILE)
3196 return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
3197 #else
3198 return (fileacc->fp != NULL);
3199 #endif
3200 }
3201
3202
3203 #if !defined(NO_FILESYSTEMS)
3204 static int mg_stat(const struct mg_connection *conn,
3205 const char *path,
3206 struct mg_file_stat *filep);
3207
3208
3209 /* mg_fopen will open a file either in memory or on the disk.
3210 * The input parameter path is a string in UTF-8 encoding.
3211 * The input parameter mode is MG_FOPEN_MODE_*
3212 * On success, either fp or membuf will be set in the output
3213 * struct file. All status members will also be set.
3214 * The function returns 1 on success, 0 on error. */
3215 static int
mg_fopen(const struct mg_connection * conn,const char * path,int mode,struct mg_file * filep)3216 mg_fopen(const struct mg_connection *conn,
3217 const char *path,
3218 int mode,
3219 struct mg_file *filep)
3220 {
3221 int found;
3222
3223 if (!filep) {
3224 return 0;
3225 }
3226 filep->access.fp = NULL;
3227 #if defined(MG_USE_OPEN_FILE)
3228 filep->access.membuf = NULL;
3229 #endif
3230
3231 if (!is_file_in_memory(conn, path)) {
3232
3233 /* filep is initialized in mg_stat: all fields with memset to,
3234 * some fields like size and modification date with values */
3235 found = mg_stat(conn, path, &(filep->stat));
3236
3237 if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
3238 /* file does not exist and will not be created */
3239 return 0;
3240 }
3241
3242 #if defined(_WIN32)
3243 {
3244 wchar_t wbuf[W_PATH_MAX];
3245 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
3246 switch (mode) {
3247 case MG_FOPEN_MODE_READ:
3248 filep->access.fp = _wfopen(wbuf, L"rb");
3249 break;
3250 case MG_FOPEN_MODE_WRITE:
3251 filep->access.fp = _wfopen(wbuf, L"wb");
3252 break;
3253 case MG_FOPEN_MODE_APPEND:
3254 filep->access.fp = _wfopen(wbuf, L"ab");
3255 break;
3256 }
3257 }
3258 #else
3259 /* Linux et al already use unicode. No need to convert. */
3260 switch (mode) {
3261 case MG_FOPEN_MODE_READ:
3262 filep->access.fp = fopen(path, "r");
3263 break;
3264 case MG_FOPEN_MODE_WRITE:
3265 filep->access.fp = fopen(path, "w");
3266 break;
3267 case MG_FOPEN_MODE_APPEND:
3268 filep->access.fp = fopen(path, "a");
3269 break;
3270 }
3271
3272 #endif
3273 if (!found) {
3274 /* File did not exist before fopen was called.
3275 * Maybe it has been created now. Get stat info
3276 * like creation time now. */
3277 found = mg_stat(conn, path, &(filep->stat));
3278 (void)found;
3279 }
3280
3281 /* file is on disk */
3282 return (filep->access.fp != NULL);
3283
3284 } else {
3285 #if defined(MG_USE_OPEN_FILE)
3286 /* is_file_in_memory returned true */
3287 if (open_file_in_memory(conn, path, filep, mode)) {
3288 /* file is in memory */
3289 return (filep->access.membuf != NULL);
3290 }
3291 #endif
3292 }
3293
3294 /* Open failed */
3295 return 0;
3296 }
3297
3298
3299 /* return 0 on success, just like fclose */
3300 static int
mg_fclose(struct mg_file_access * fileacc)3301 mg_fclose(struct mg_file_access *fileacc)
3302 {
3303 int ret = -1;
3304 if (fileacc != NULL) {
3305 if (fileacc->fp != NULL) {
3306 ret = fclose(fileacc->fp);
3307 #if defined(MG_USE_OPEN_FILE)
3308 } else if (fileacc->membuf != NULL) {
3309 ret = 0;
3310 #endif
3311 }
3312 /* reset all members of fileacc */
3313 memset(fileacc, 0, sizeof(*fileacc));
3314 }
3315 return ret;
3316 }
3317 #endif /* NO_FILESYSTEMS */
3318
3319
3320 static void
mg_strlcpy(register char * dst,register const char * src,size_t n)3321 mg_strlcpy(register char *dst, register const char *src, size_t n)
3322 {
3323 for (; *src != '\0' && n > 1; n--) {
3324 *dst++ = *src++;
3325 }
3326 *dst = '\0';
3327 }
3328
3329
3330 static int
lowercase(const char * s)3331 lowercase(const char *s)
3332 {
3333 return tolower((unsigned char)*s);
3334 }
3335
3336
3337 int
mg_strncasecmp(const char * s1,const char * s2,size_t len)3338 mg_strncasecmp(const char *s1, const char *s2, size_t len)
3339 {
3340 int diff = 0;
3341
3342 if (len > 0) {
3343 do {
3344 diff = lowercase(s1++) - lowercase(s2++);
3345 } while (diff == 0 && s1[-1] != '\0' && --len > 0);
3346 }
3347
3348 return diff;
3349 }
3350
3351
3352 int
mg_strcasecmp(const char * s1,const char * s2)3353 mg_strcasecmp(const char *s1, const char *s2)
3354 {
3355 int diff;
3356
3357 do {
3358 diff = lowercase(s1++) - lowercase(s2++);
3359 } while (diff == 0 && s1[-1] != '\0');
3360
3361 return diff;
3362 }
3363
3364
3365 static char *
mg_strndup_ctx(const char * ptr,size_t len,struct mg_context * ctx)3366 mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
3367 {
3368 char *p;
3369 (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
3370 * defined */
3371
3372 if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
3373 mg_strlcpy(p, ptr, len + 1);
3374 }
3375
3376 return p;
3377 }
3378
3379
3380 static char *
mg_strdup_ctx(const char * str,struct mg_context * ctx)3381 mg_strdup_ctx(const char *str, struct mg_context *ctx)
3382 {
3383 return mg_strndup_ctx(str, strlen(str), ctx);
3384 }
3385
3386 static char *
mg_strdup(const char * str)3387 mg_strdup(const char *str)
3388 {
3389 return mg_strndup_ctx(str, strlen(str), NULL);
3390 }
3391
3392
3393 static const char *
mg_strcasestr(const char * big_str,const char * small_str)3394 mg_strcasestr(const char *big_str, const char *small_str)
3395 {
3396 size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3397
3398 if (big_len >= small_len) {
3399 for (i = 0; i <= (big_len - small_len); i++) {
3400 if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
3401 return big_str + i;
3402 }
3403 }
3404 }
3405
3406 return NULL;
3407 }
3408
3409
3410 /* Return null terminated string of given maximum length.
3411 * Report errors if length is exceeded. */
3412 static void
mg_vsnprintf(const struct mg_connection * conn,int * truncated,char * buf,size_t buflen,const char * fmt,va_list ap)3413 mg_vsnprintf(const struct mg_connection *conn,
3414 int *truncated,
3415 char *buf,
3416 size_t buflen,
3417 const char *fmt,
3418 va_list ap)
3419 {
3420 int n, ok;
3421
3422 if (buflen == 0) {
3423 if (truncated) {
3424 *truncated = 1;
3425 }
3426 return;
3427 }
3428
3429 #if defined(__clang__)
3430 #pragma clang diagnostic push
3431 #pragma clang diagnostic ignored "-Wformat-nonliteral"
3432 /* Using fmt as a non-literal is intended here, since it is mostly called
3433 * indirectly by mg_snprintf */
3434 #endif
3435
3436 n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
3437 ok = (n >= 0) && ((size_t)n < buflen);
3438
3439 #if defined(__clang__)
3440 #pragma clang diagnostic pop
3441 #endif
3442
3443 if (ok) {
3444 if (truncated) {
3445 *truncated = 0;
3446 }
3447 } else {
3448 if (truncated) {
3449 *truncated = 1;
3450 }
3451 mg_cry_internal(conn,
3452 "truncating vsnprintf buffer: [%.*s]",
3453 (int)((buflen > 200) ? 200 : (buflen - 1)),
3454 buf);
3455 n = (int)buflen - 1;
3456 }
3457 buf[n] = '\0';
3458 }
3459
3460
3461 static void
mg_snprintf(const struct mg_connection * conn,int * truncated,char * buf,size_t buflen,const char * fmt,...)3462 mg_snprintf(const struct mg_connection *conn,
3463 int *truncated,
3464 char *buf,
3465 size_t buflen,
3466 const char *fmt,
3467 ...)
3468 {
3469 va_list ap;
3470
3471 va_start(ap, fmt);
3472 mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
3473 va_end(ap);
3474 }
3475
3476
3477 static int
get_option_index(const char * name)3478 get_option_index(const char *name)
3479 {
3480 int i;
3481
3482 for (i = 0; config_options[i].name != NULL; i++) {
3483 if (strcmp(config_options[i].name, name) == 0) {
3484 return i;
3485 }
3486 }
3487 return -1;
3488 }
3489
3490
3491 const char *
mg_get_option(const struct mg_context * ctx,const char * name)3492 mg_get_option(const struct mg_context *ctx, const char *name)
3493 {
3494 int i;
3495 if ((i = get_option_index(name)) == -1) {
3496 return NULL;
3497 } else if (!ctx || ctx->dd.config[i] == NULL) {
3498 return "";
3499 } else {
3500 return ctx->dd.config[i];
3501 }
3502 }
3503
3504 #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3505
3506 struct mg_context *
mg_get_context(const struct mg_connection * conn)3507 mg_get_context(const struct mg_connection *conn)
3508 {
3509 return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
3510 }
3511
3512
3513 void *
mg_get_user_data(const struct mg_context * ctx)3514 mg_get_user_data(const struct mg_context *ctx)
3515 {
3516 return (ctx == NULL) ? NULL : ctx->user_data;
3517 }
3518
3519
3520 void *
mg_get_thread_pointer(const struct mg_connection * conn)3521 mg_get_thread_pointer(const struct mg_connection *conn)
3522 {
3523 /* both methods should return the same pointer */
3524 if (conn) {
3525 /* quick access, in case conn is known */
3526 return conn->tls_user_ptr;
3527 } else {
3528 /* otherwise get pointer from thread local storage (TLS) */
3529 struct mg_workerTLS *tls =
3530 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3531 return tls->user_ptr;
3532 }
3533 }
3534
3535
3536 void
mg_set_user_connection_data(struct mg_connection * conn,void * data)3537 mg_set_user_connection_data(struct mg_connection *conn, void *data)
3538 {
3539 if (conn != NULL) {
3540 conn->request_info.conn_data = data;
3541 }
3542 }
3543
3544
3545 void *
mg_get_user_connection_data(const struct mg_connection * conn)3546 mg_get_user_connection_data(const struct mg_connection *conn)
3547 {
3548 if (conn != NULL) {
3549 return conn->request_info.conn_data;
3550 }
3551 return NULL;
3552 }
3553
3554
3555 #if defined(MG_LEGACY_INTERFACE)
3556 /* Deprecated: Use mg_get_server_ports instead. */
3557 size_t
mg_get_ports(const struct mg_context * ctx,size_t size,int * ports,int * ssl)3558 mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
3559 {
3560 size_t i;
3561 if (!ctx) {
3562 return 0;
3563 }
3564 for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
3565 ssl[i] = ctx->listening_sockets[i].is_ssl;
3566 ports[i] =
3567 #if defined(USE_IPV6)
3568 (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
3569 ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
3570 :
3571 #endif
3572 ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
3573 }
3574 return i;
3575 }
3576 #endif
3577
3578
3579 int
mg_get_server_ports(const struct mg_context * ctx,int size,struct mg_server_port * ports)3580 mg_get_server_ports(const struct mg_context *ctx,
3581 int size,
3582 struct mg_server_port *ports)
3583 {
3584 int i, cnt = 0;
3585
3586 if (size <= 0) {
3587 return -1;
3588 }
3589 memset(ports, 0, sizeof(*ports) * (size_t)size);
3590 if (!ctx) {
3591 return -1;
3592 }
3593 if (!ctx->listening_sockets) {
3594 return -1;
3595 }
3596
3597 for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
3598
3599 ports[cnt].port =
3600 #if defined(USE_IPV6)
3601 (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
3602 ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
3603 :
3604 #endif
3605 ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
3606 ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
3607 ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
3608
3609 if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
3610 /* IPv4 */
3611 ports[cnt].protocol = 1;
3612 cnt++;
3613 } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
3614 /* IPv6 */
3615 ports[cnt].protocol = 3;
3616 cnt++;
3617 }
3618 }
3619
3620 return cnt;
3621 }
3622
3623
3624 static void
sockaddr_to_string(char * buf,size_t len,const union usa * usa)3625 sockaddr_to_string(char *buf, size_t len, const union usa *usa)
3626 {
3627 buf[0] = '\0';
3628
3629 if (!usa) {
3630 return;
3631 }
3632
3633 if (usa->sa.sa_family == AF_INET) {
3634 getnameinfo(&usa->sa,
3635 sizeof(usa->sin),
3636 buf,
3637 (unsigned)len,
3638 NULL,
3639 0,
3640 NI_NUMERICHOST);
3641 }
3642 #if defined(USE_IPV6)
3643 else if (usa->sa.sa_family == AF_INET6) {
3644 getnameinfo(&usa->sa,
3645 sizeof(usa->sin6),
3646 buf,
3647 (unsigned)len,
3648 NULL,
3649 0,
3650 NI_NUMERICHOST);
3651 }
3652 #endif
3653 }
3654
3655
3656 /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
3657 * included in all responses other than 100, 101, 5xx. */
3658 static void
gmt_time_string(char * buf,size_t buf_len,time_t * t)3659 gmt_time_string(char *buf, size_t buf_len, time_t *t)
3660 {
3661 #if !defined(REENTRANT_TIME)
3662 struct tm *tm;
3663
3664 tm = ((t != NULL) ? gmtime(t) : NULL);
3665 if (tm != NULL) {
3666 #else
3667 struct tm _tm;
3668 struct tm *tm = &_tm;
3669
3670 if (t != NULL) {
3671 gmtime_r(t, tm);
3672 #endif
3673 strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
3674 } else {
3675 mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3676 buf[buf_len - 1] = '\0';
3677 }
3678 }
3679
3680
3681 /* difftime for struct timespec. Return value is in seconds. */
3682 static double
3683 mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
3684 {
3685 return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3686 + (double)(ts_now->tv_sec - ts_before->tv_sec);
3687 }
3688
3689
3690 #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3691 static void mg_cry_internal_impl(const struct mg_connection *conn,
3692 const char *func,
3693 unsigned line,
3694 const char *fmt,
3695 va_list ap);
3696 #include "external_mg_cry_internal_impl.inl"
3697 #elif !defined(NO_FILESYSTEMS)
3698
3699 /* Print error message to the opened error log stream. */
3700 static void
3701 mg_cry_internal_impl(const struct mg_connection *conn,
3702 const char *func,
3703 unsigned line,
3704 const char *fmt,
3705 va_list ap)
3706 {
3707 char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
3708 struct mg_file fi;
3709 time_t timestamp;
3710
3711 /* Unused, in the RELEASE build */
3712 (void)func;
3713 (void)line;
3714
3715 #if defined(GCC_DIAGNOSTIC)
3716 #pragma GCC diagnostic push
3717 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
3718 #endif
3719
3720 IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
3721
3722 #if defined(GCC_DIAGNOSTIC)
3723 #pragma GCC diagnostic pop
3724 #endif
3725
3726 buf[sizeof(buf) - 1] = 0;
3727
3728 DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
3729
3730 if (!conn) {
3731 puts(buf);
3732 return;
3733 }
3734
3735 /* Do not lock when getting the callback value, here and below.
3736 * I suppose this is fine, since function cannot disappear in the
3737 * same way string option can. */
3738 if ((conn->phys_ctx->callbacks.log_message == NULL)
3739 || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
3740
3741 if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
3742 if (mg_fopen(conn,
3743 conn->dom_ctx->config[ERROR_LOG_FILE],
3744 MG_FOPEN_MODE_APPEND,
3745 &fi)
3746 == 0) {
3747 fi.access.fp = NULL;
3748 }
3749 } else {
3750 fi.access.fp = NULL;
3751 }
3752
3753 if (fi.access.fp != NULL) {
3754 flockfile(fi.access.fp);
3755 timestamp = time(NULL);
3756
3757 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
3758 fprintf(fi.access.fp,
3759 "[%010lu] [error] [client %s] ",
3760 (unsigned long)timestamp,
3761 src_addr);
3762
3763 if (conn->request_info.request_method != NULL) {
3764 fprintf(fi.access.fp,
3765 "%s %s: ",
3766 conn->request_info.request_method,
3767 conn->request_info.request_uri
3768 ? conn->request_info.request_uri
3769 : "");
3770 }
3771
3772 fprintf(fi.access.fp, "%s", buf);
3773 fputc('\n', fi.access.fp);
3774 fflush(fi.access.fp);
3775 funlockfile(fi.access.fp);
3776 (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
3777 * mg_cry here anyway ;-) */
3778 }
3779 }
3780 }
3781 #else
3782 #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
3783 #endif /* Externally provided function */
3784
3785
3786 /* Construct fake connection structure. Used for logging, if connection
3787 * is not applicable at the moment of logging. */
3788 static struct mg_connection *
3789 fake_connection(struct mg_connection *fc, struct mg_context *ctx)
3790 {
3791 static const struct mg_connection conn_zero = {0};
3792 *fc = conn_zero;
3793 fc->phys_ctx = ctx;
3794 fc->dom_ctx = &(ctx->dd);
3795 return fc;
3796 }
3797
3798
3799 static void
3800 mg_cry_internal_wrap(const struct mg_connection *conn,
3801 struct mg_context *ctx,
3802 const char *func,
3803 unsigned line,
3804 const char *fmt,
3805 ...)
3806 {
3807 va_list ap;
3808 va_start(ap, fmt);
3809 if (!conn && ctx) {
3810 struct mg_connection fc;
3811 mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
3812 } else {
3813 mg_cry_internal_impl(conn, func, line, fmt, ap);
3814 }
3815 va_end(ap);
3816 }
3817
3818
3819 void
3820 mg_cry(const struct mg_connection *conn, const char *fmt, ...)
3821 {
3822 va_list ap;
3823 va_start(ap, fmt);
3824 mg_cry_internal_impl(conn, "user", 0, fmt, ap);
3825 va_end(ap);
3826 }
3827
3828
3829 #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3830
3831
3832 const char *
3833 mg_version(void)
3834 {
3835 return CIVETWEB_VERSION;
3836 }
3837
3838
3839 const struct mg_request_info *
3840 mg_get_request_info(const struct mg_connection *conn)
3841 {
3842 if (!conn) {
3843 return NULL;
3844 }
3845 #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3846 if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
3847 char txt[16];
3848 struct mg_workerTLS *tls =
3849 (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3850
3851 sprintf(txt, "%03i", conn->response_info.status_code);
3852 if (strlen(txt) == 3) {
3853 memcpy(tls->txtbuf, txt, 4);
3854 } else {
3855 strcpy(tls->txtbuf, "ERR");
3856 }
3857
3858 ((struct mg_connection *)conn)->request_info.local_uri =
3859 ((struct mg_connection *)conn)->request_info.request_uri =
3860 tls->txtbuf; /* use thread safe buffer */
3861
3862 ((struct mg_connection *)conn)->request_info.num_headers =
3863 conn->response_info.num_headers;
3864 memcpy(((struct mg_connection *)conn)->request_info.http_headers,
3865 conn->response_info.http_headers,
3866 sizeof(conn->response_info.http_headers));
3867 } else
3868 #endif
3869 if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
3870 return NULL;
3871 }
3872 return &conn->request_info;
3873 }
3874
3875
3876 const struct mg_response_info *
3877 mg_get_response_info(const struct mg_connection *conn)
3878 {
3879 if (!conn) {
3880 return NULL;
3881 }
3882 if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
3883 return NULL;
3884 }
3885 return &conn->response_info;
3886 }
3887
3888
3889 static const char *
3890 get_proto_name(const struct mg_connection *conn)
3891 {
3892 #if defined(__clang__)
3893 #pragma clang diagnostic push
3894 #pragma clang diagnostic ignored "-Wunreachable-code"
3895 /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
3896 * not supported. Clang raises an "unreachable code" warning for parts of ?:
3897 * unreachable, but splitting into four different #ifdef clauses here is more
3898 * complicated.
3899 */
3900 #endif
3901
3902 const struct mg_request_info *ri = &conn->request_info;
3903
3904 const char *proto =
3905 (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
3906 : (ri->is_ssl ? "https" : "http"));
3907
3908 return proto;
3909
3910 #if defined(__clang__)
3911 #pragma clang diagnostic pop
3912 #endif
3913 }
3914
3915
3916 int
3917 mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
3918 {
3919 if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3920 return -1;
3921 } else {
3922
3923 int truncated = 0;
3924 const struct mg_request_info *ri = &conn->request_info;
3925
3926 const char *proto = get_proto_name(conn);
3927
3928 if (ri->local_uri == NULL) {
3929 return -1;
3930 }
3931
3932 if ((ri->request_uri != NULL)
3933 && (0 != strcmp(ri->local_uri, ri->request_uri))) {
3934 /* The request uri is different from the local uri.
3935 * This is usually if an absolute URI, including server
3936 * name has been provided. */
3937 mg_snprintf(conn,
3938 &truncated,
3939 buf,
3940 buflen,
3941 "%s://%s",
3942 proto,
3943 ri->request_uri);
3944 if (truncated) {
3945 return -1;
3946 }
3947 return 0;
3948
3949 } else {
3950
3951 /* The common case is a relative URI, so we have to
3952 * construct an absolute URI from server name and port */
3953
3954 #if defined(USE_IPV6)
3955 int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
3956 int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
3957 : htons(conn->client.lsa.sin.sin_port);
3958 #else
3959 int port = htons(conn->client.lsa.sin.sin_port);
3960 #endif
3961 int def_port = ri->is_ssl ? 443 : 80;
3962 int auth_domain_check_enabled =
3963 conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
3964 && (!mg_strcasecmp(
3965 conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
3966 const char *server_domain =
3967 conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
3968
3969 char portstr[16];
3970 char server_ip[48];
3971
3972 if (port != def_port) {
3973 sprintf(portstr, ":%u", (unsigned)port);
3974 } else {
3975 portstr[0] = 0;
3976 }
3977
3978 if (!auth_domain_check_enabled || !server_domain) {
3979
3980 sockaddr_to_string(server_ip,
3981 sizeof(server_ip),
3982 &conn->client.lsa);
3983
3984 server_domain = server_ip;
3985 }
3986
3987 mg_snprintf(conn,
3988 &truncated,
3989 buf,
3990 buflen,
3991 "%s://%s%s%s",
3992 proto,
3993 server_domain,
3994 portstr,
3995 ri->local_uri);
3996 if (truncated) {
3997 return -1;
3998 }
3999 return 0;
4000 }
4001 }
4002 }
4003
4004 /* Skip the characters until one of the delimiters characters found.
4005 * 0-terminate resulting word. Skip the delimiter and following whitespaces.
4006 * Advance pointer to buffer to the next word. Return found 0-terminated
4007 * word.
4008 * Delimiters can be quoted with quotechar. */
4009 static char *
4010 skip_quoted(char **buf,
4011 const char *delimiters,
4012 const char *whitespace,
4013 char quotechar)
4014 {
4015 char *p, *begin_word, *end_word, *end_whitespace;
4016
4017 begin_word = *buf;
4018 end_word = begin_word + strcspn(begin_word, delimiters);
4019
4020 /* Check for quotechar */
4021 if (end_word > begin_word) {
4022 p = end_word - 1;
4023 while (*p == quotechar) {
4024 /* While the delimiter is quoted, look for the next delimiter.
4025 */
4026 /* This happens, e.g., in calls from parse_auth_header,
4027 * if the user name contains a " character. */
4028
4029 /* If there is anything beyond end_word, copy it. */
4030 if (*end_word != '\0') {
4031 size_t end_off = strcspn(end_word + 1, delimiters);
4032 memmove(p, end_word, end_off + 1);
4033 p += end_off; /* p must correspond to end_word - 1 */
4034 end_word += end_off + 1;
4035 } else {
4036 *p = '\0';
4037 break;
4038 }
4039 }
4040 for (p++; p < end_word; p++) {
4041 *p = '\0';
4042 }
4043 }
4044
4045 if (*end_word == '\0') {
4046 *buf = end_word;
4047 } else {
4048
4049 #if defined(GCC_DIAGNOSTIC)
4050 /* Disable spurious conversion warning for GCC */
4051 #pragma GCC diagnostic push
4052 #pragma GCC diagnostic ignored "-Wsign-conversion"
4053 #endif /* defined(GCC_DIAGNOSTIC) */
4054
4055 end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
4056
4057 #if defined(GCC_DIAGNOSTIC)
4058 #pragma GCC diagnostic pop
4059 #endif /* defined(GCC_DIAGNOSTIC) */
4060
4061 for (p = end_word; p < end_whitespace; p++) {
4062 *p = '\0';
4063 }
4064
4065 *buf = end_whitespace;
4066 }
4067
4068 return begin_word;
4069 }
4070
4071
4072 /* Return HTTP header value, or NULL if not found. */
4073 static const char *
4074 get_header(const struct mg_header *hdr, int num_hdr, const char *name)
4075 {
4076 int i;
4077 for (i = 0; i < num_hdr; i++) {
4078 if (!mg_strcasecmp(name, hdr[i].name)) {
4079 return hdr[i].value;
4080 }
4081 }
4082
4083 return NULL;
4084 }
4085
4086
4087 #if defined(USE_WEBSOCKET)
4088 /* Retrieve requested HTTP header multiple values, and return the number of
4089 * found occurrences */
4090 static int
4091 get_req_headers(const struct mg_request_info *ri,
4092 const char *name,
4093 const char **output,
4094 int output_max_size)
4095 {
4096 int i;
4097 int cnt = 0;
4098 if (ri) {
4099 for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
4100 if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
4101 output[cnt++] = ri->http_headers[i].value;
4102 }
4103 }
4104 }
4105 return cnt;
4106 }
4107 #endif
4108
4109
4110 const char *
4111 mg_get_header(const struct mg_connection *conn, const char *name)
4112 {
4113 if (!conn) {
4114 return NULL;
4115 }
4116
4117 if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
4118 return get_header(conn->request_info.http_headers,
4119 conn->request_info.num_headers,
4120 name);
4121 }
4122 if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
4123 return get_header(conn->response_info.http_headers,
4124 conn->response_info.num_headers,
4125 name);
4126 }
4127 return NULL;
4128 }
4129
4130
4131 static const char *
4132 get_http_version(const struct mg_connection *conn)
4133 {
4134 if (!conn) {
4135 return NULL;
4136 }
4137
4138 if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
4139 return conn->request_info.http_version;
4140 }
4141 if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
4142 return conn->response_info.http_version;
4143 }
4144 return NULL;
4145 }
4146
4147
4148 /* A helper function for traversing a comma separated list of values.
4149 * It returns a list pointer shifted to the next value, or NULL if the end
4150 * of the list found.
4151 * Value is stored in val vector. If value has form "x=y", then eq_val
4152 * vector is initialized to point to the "y" part, and val vector length
4153 * is adjusted to point only to "x". */
4154 static const char *
4155 next_option(const char *list, struct vec *val, struct vec *eq_val)
4156 {
4157 int end;
4158
4159 reparse:
4160 if (val == NULL || list == NULL || *list == '\0') {
4161 /* End of the list */
4162 return NULL;
4163 }
4164
4165 /* Skip over leading LWS */
4166 while (*list == ' ' || *list == '\t')
4167 list++;
4168
4169 val->ptr = list;
4170 if ((list = strchr(val->ptr, ',')) != NULL) {
4171 /* Comma found. Store length and shift the list ptr */
4172 val->len = ((size_t)(list - val->ptr));
4173 list++;
4174 } else {
4175 /* This value is the last one */
4176 list = val->ptr + strlen(val->ptr);
4177 val->len = ((size_t)(list - val->ptr));
4178 }
4179
4180 /* Adjust length for trailing LWS */
4181 end = (int)val->len - 1;
4182 while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
4183 end--;
4184 val->len = (size_t)(end) + (size_t)(1);
4185
4186 if (val->len == 0) {
4187 /* Ignore any empty entries. */
4188 goto reparse;
4189 }
4190
4191 if (eq_val != NULL) {
4192 /* Value has form "x=y", adjust pointers and lengths
4193 * so that val points to "x", and eq_val points to "y". */
4194 eq_val->len = 0;
4195 eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
4196 if (eq_val->ptr != NULL) {
4197 eq_val->ptr++; /* Skip over '=' character */
4198 eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
4199 val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
4200 }
4201 }
4202
4203 return list;
4204 }
4205
4206
4207 /* A helper function for checking if a comma separated list of values
4208 * contains
4209 * the given option (case insensitvely).
4210 * 'header' can be NULL, in which case false is returned. */
4211 static int
4212 header_has_option(const char *header, const char *option)
4213 {
4214 struct vec opt_vec;
4215 struct vec eq_vec;
4216
4217 DEBUG_ASSERT(option != NULL);
4218 DEBUG_ASSERT(option[0] != '\0');
4219
4220 while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
4221 if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
4222 return 1;
4223 }
4224
4225 return 0;
4226 }
4227
4228
4229 /* Perform case-insensitive match of string against pattern */
4230 static ptrdiff_t
4231 match_prefix(const char *pattern, size_t pattern_len, const char *str)
4232 {
4233 const char *or_str;
4234 ptrdiff_t i, j, len, res;
4235
4236 if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
4237 res = match_prefix(pattern, (size_t)(or_str - pattern), str);
4238 return (res > 0) ? res
4239 : match_prefix(or_str + 1,
4240 (size_t)((pattern + pattern_len)
4241 - (or_str + 1)),
4242 str);
4243 }
4244
4245 for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
4246 if ((pattern[i] == '?') && (str[j] != '\0')) {
4247 continue;
4248 } else if (pattern[i] == '$') {
4249 return (str[j] == '\0') ? j : -1;
4250 } else if (pattern[i] == '*') {
4251 i++;
4252 if (pattern[i] == '*') {
4253 i++;
4254 len = strlen(str + j);
4255 } else {
4256 len = strcspn(str + j, "/");
4257 }
4258 if (i == (ptrdiff_t)pattern_len) {
4259 return j + len;
4260 }
4261 do {
4262 res = match_prefix(pattern + i, pattern_len - i, str + j + len);
4263 } while (res == -1 && len-- > 0);
4264 return (res == -1) ? -1 : j + res + len;
4265 } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
4266 return -1;
4267 }
4268 }
4269 return (ptrdiff_t)j;
4270 }
4271
4272
4273 /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
4274 * This function must tolerate situations when connection info is not
4275 * set up, for example if request parsing failed. */
4276 static int
4277 should_keep_alive(const struct mg_connection *conn)
4278 {
4279 const char *http_version;
4280 const char *header;
4281
4282 /* First satisfy needs of the server */
4283 if ((conn == NULL) || conn->must_close) {
4284 /* Close, if civetweb framework needs to close */
4285 return 0;
4286 }
4287
4288 if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
4289 /* Close, if keep alive is not enabled */
4290 return 0;
4291 }
4292
4293 /* Check explicit wish of the client */
4294 header = mg_get_header(conn, "Connection");
4295 if (header) {
4296 /* If there is a connection header from the client, obey */
4297 if (header_has_option(header, "keep-alive")) {
4298 return 1;
4299 }
4300 return 0;
4301 }
4302
4303 /* Use default of the standard */
4304 http_version = get_http_version(conn);
4305 if (http_version && (0 == strcmp(http_version, "1.1"))) {
4306 /* HTTP 1.1 default is keep alive */
4307 return 1;
4308 }
4309
4310 /* HTTP 1.0 (and earlier) default is to close the connection */
4311 return 0;
4312 }
4313
4314
4315 static int
4316 should_decode_url(const struct mg_connection *conn)
4317 {
4318 if (!conn || !conn->dom_ctx) {
4319 return 0;
4320 }
4321
4322 return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
4323 }
4324
4325
4326 static const char *
4327 suggest_connection_header(const struct mg_connection *conn)
4328 {
4329 return should_keep_alive(conn) ? "keep-alive" : "close";
4330 }
4331
4332
4333 static int
4334 send_no_cache_header(struct mg_connection *conn)
4335 {
4336 /* Send all current and obsolete cache opt-out directives. */
4337 return mg_printf(conn,
4338 "Cache-Control: no-cache, no-store, "
4339 "must-revalidate, private, max-age=0\r\n"
4340 "Pragma: no-cache\r\n"
4341 "Expires: 0\r\n");
4342 }
4343
4344
4345 static int
4346 send_static_cache_header(struct mg_connection *conn)
4347 {
4348 #if !defined(NO_CACHING)
4349 /* Read the server config to check how long a file may be cached.
4350 * The configuration is in seconds. */
4351 int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
4352 if (max_age <= 0) {
4353 /* 0 means "do not cache". All values <0 are reserved
4354 * and may be used differently in the future. */
4355 /* If a file should not be cached, do not only send
4356 * max-age=0, but also pragmas and Expires headers. */
4357 return send_no_cache_header(conn);
4358 }
4359
4360 /* Use "Cache-Control: max-age" instead of "Expires" header.
4361 * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
4362 /* See also https://www.mnot.net/cache_docs/ */
4363 /* According to RFC 2616, Section 14.21, caching times should not exceed
4364 * one year. A year with 365 days corresponds to 31536000 seconds, a
4365 * leap
4366 * year to 31622400 seconds. For the moment, we just send whatever has
4367 * been configured, still the behavior for >1 year should be considered
4368 * as undefined. */
4369 return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
4370 #else /* NO_CACHING */
4371 return send_no_cache_header(conn);
4372 #endif /* !NO_CACHING */
4373 }
4374
4375
4376 static int
4377 send_additional_header(struct mg_connection *conn)
4378 {
4379 int i = 0;
4380 const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
4381
4382 #if !defined(NO_SSL)
4383 if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
4384 int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
4385 if (max_age >= 0) {
4386 i += mg_printf(conn,
4387 "Strict-Transport-Security: max-age=%u\r\n",
4388 (unsigned)max_age);
4389 }
4390 }
4391 #endif
4392
4393 if (header && header[0]) {
4394 i += mg_printf(conn, "%s\r\n", header);
4395 }
4396
4397 return i;
4398 }
4399
4400
4401 #if !defined(NO_FILESYSTEMS)
4402 static void handle_file_based_request(struct mg_connection *conn,
4403 const char *path,
4404 struct mg_file *filep);
4405 #endif /* NO_FILESYSTEMS */
4406
4407
4408 const char *
4409 mg_get_response_code_text(const struct mg_connection *conn, int response_code)
4410 {
4411 /* See IANA HTTP status code assignment:
4412 * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
4413 */
4414
4415 switch (response_code) {
4416 /* RFC2616 Section 10.1 - Informational 1xx */
4417 case 100:
4418 return "Continue"; /* RFC2616 Section 10.1.1 */
4419 case 101:
4420 return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
4421 case 102:
4422 return "Processing"; /* RFC2518 Section 10.1 */
4423
4424 /* RFC2616 Section 10.2 - Successful 2xx */
4425 case 200:
4426 return "OK"; /* RFC2616 Section 10.2.1 */
4427 case 201:
4428 return "Created"; /* RFC2616 Section 10.2.2 */
4429 case 202:
4430 return "Accepted"; /* RFC2616 Section 10.2.3 */
4431 case 203:
4432 return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
4433 case 204:
4434 return "No Content"; /* RFC2616 Section 10.2.5 */
4435 case 205:
4436 return "Reset Content"; /* RFC2616 Section 10.2.6 */
4437 case 206:
4438 return "Partial Content"; /* RFC2616 Section 10.2.7 */
4439 case 207:
4440 return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
4441 */
4442 case 208:
4443 return "Already Reported"; /* RFC5842 Section 7.1 */
4444
4445 case 226:
4446 return "IM used"; /* RFC3229 Section 10.4.1 */
4447
4448 /* RFC2616 Section 10.3 - Redirection 3xx */
4449 case 300:
4450 return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
4451 case 301:
4452 return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
4453 case 302:
4454 return "Found"; /* RFC2616 Section 10.3.3 */
4455 case 303:
4456 return "See Other"; /* RFC2616 Section 10.3.4 */
4457 case 304:
4458 return "Not Modified"; /* RFC2616 Section 10.3.5 */
4459 case 305:
4460 return "Use Proxy"; /* RFC2616 Section 10.3.6 */
4461 case 307:
4462 return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
4463 case 308:
4464 return "Permanent Redirect"; /* RFC7238 Section 3 */
4465
4466 /* RFC2616 Section 10.4 - Client Error 4xx */
4467 case 400:
4468 return "Bad Request"; /* RFC2616 Section 10.4.1 */
4469 case 401:
4470 return "Unauthorized"; /* RFC2616 Section 10.4.2 */
4471 case 402:
4472 return "Payment Required"; /* RFC2616 Section 10.4.3 */
4473 case 403:
4474 return "Forbidden"; /* RFC2616 Section 10.4.4 */
4475 case 404:
4476 return "Not Found"; /* RFC2616 Section 10.4.5 */
4477 case 405:
4478 return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
4479 case 406:
4480 return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
4481 case 407:
4482 return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
4483 case 408:
4484 return "Request Time-out"; /* RFC2616 Section 10.4.9 */
4485 case 409:
4486 return "Conflict"; /* RFC2616 Section 10.4.10 */
4487 case 410:
4488 return "Gone"; /* RFC2616 Section 10.4.11 */
4489 case 411:
4490 return "Length Required"; /* RFC2616 Section 10.4.12 */
4491 case 412:
4492 return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
4493 case 413:
4494 return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
4495 case 414:
4496 return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
4497 case 415:
4498 return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
4499 case 416:
4500 return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
4501 */
4502 case 417:
4503 return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
4504
4505 case 421:
4506 return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
4507 case 422:
4508 return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
4509 * Section 11.2 */
4510 case 423:
4511 return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
4512 case 424:
4513 return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
4514 * Section 11.4 */
4515
4516 case 426:
4517 return "Upgrade Required"; /* RFC 2817 Section 4 */
4518
4519 case 428:
4520 return "Precondition Required"; /* RFC 6585, Section 3 */
4521 case 429:
4522 return "Too Many Requests"; /* RFC 6585, Section 4 */
4523
4524 case 431:
4525 return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
4526
4527 case 451:
4528 return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
4529 * Section 3 */
4530
4531 /* RFC2616 Section 10.5 - Server Error 5xx */
4532 case 500:
4533 return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
4534 case 501:
4535 return "Not Implemented"; /* RFC2616 Section 10.5.2 */
4536 case 502:
4537 return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
4538 case 503:
4539 return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
4540 case 504:
4541 return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
4542 case 505:
4543 return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
4544 case 506:
4545 return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
4546 case 507:
4547 return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
4548 * Section 11.5 */
4549 case 508:
4550 return "Loop Detected"; /* RFC5842 Section 7.1 */
4551
4552 case 510:
4553 return "Not Extended"; /* RFC 2774, Section 7 */
4554 case 511:
4555 return "Network Authentication Required"; /* RFC 6585, Section 6 */
4556
4557 /* Other status codes, not shown in the IANA HTTP status code
4558 * assignment.
4559 * E.g., "de facto" standards due to common use, ... */
4560 case 418:
4561 return "I am a teapot"; /* RFC2324 Section 2.3.2 */
4562 case 419:
4563 return "Authentication Timeout"; /* common use */
4564 case 420:
4565 return "Enhance Your Calm"; /* common use */
4566 case 440:
4567 return "Login Timeout"; /* common use */
4568 case 509:
4569 return "Bandwidth Limit Exceeded"; /* common use */
4570
4571 default:
4572 /* This error code is unknown. This should not happen. */
4573 if (conn) {
4574 mg_cry_internal(conn,
4575 "Unknown HTTP response code: %u",
4576 response_code);
4577 }
4578
4579 /* Return at least a category according to RFC 2616 Section 10. */
4580 if (response_code >= 100 && response_code < 200) {
4581 /* Unknown informational status code */
4582 return "Information";
4583 }
4584 if (response_code >= 200 && response_code < 300) {
4585 /* Unknown success code */
4586 return "Success";
4587 }
4588 if (response_code >= 300 && response_code < 400) {
4589 /* Unknown redirection code */
4590 return "Redirection";
4591 }
4592 if (response_code >= 400 && response_code < 500) {
4593 /* Unknown request error code */
4594 return "Client Error";
4595 }
4596 if (response_code >= 500 && response_code < 600) {
4597 /* Unknown server error code */
4598 return "Server Error";
4599 }
4600
4601 /* Response code not even within reasonable range */
4602 return "";
4603 }
4604 }
4605
4606
4607 static int
4608 mg_send_http_error_impl(struct mg_connection *conn,
4609 int status,
4610 const char *fmt,
4611 va_list args)
4612 {
4613 char errmsg_buf[MG_BUF_LEN];
4614 va_list ap;
4615 int has_body;
4616 char date[64];
4617 time_t curtime = time(NULL);
4618 #if !defined(NO_FILESYSTEMS)
4619 char path_buf[PATH_MAX];
4620 int len, i, page_handler_found, scope, truncated;
4621 const char *error_handler = NULL;
4622 struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
4623 const char *error_page_file_ext, *tstr;
4624 #endif /* NO_FILESYSTEMS */
4625 int handled_by_callback = 0;
4626
4627 const char *status_text = mg_get_response_code_text(conn, status);
4628
4629 if ((conn == NULL) || (fmt == NULL)) {
4630 return -2;
4631 }
4632
4633 /* Set status (for log) */
4634 conn->status_code = status;
4635
4636 /* Errors 1xx, 204 and 304 MUST NOT send a body */
4637 has_body = ((status > 199) && (status != 204) && (status != 304));
4638
4639 /* Prepare message in buf, if required */
4640 if (has_body
4641 || (!conn->in_error_handler
4642 && (conn->phys_ctx->callbacks.http_error != NULL))) {
4643 /* Store error message in errmsg_buf */
4644 va_copy(ap, args);
4645 mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
4646 va_end(ap);
4647 /* In a debug build, print all html errors */
4648 DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
4649 }
4650
4651 /* If there is a http_error callback, call it.
4652 * But don't do it recursively, if callback calls mg_send_http_error again.
4653 */
4654 if (!conn->in_error_handler
4655 && (conn->phys_ctx->callbacks.http_error != NULL)) {
4656 /* Mark in_error_handler to avoid recursion and call user callback. */
4657 conn->in_error_handler = 1;
4658 handled_by_callback =
4659 (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
4660 == 0);
4661 conn->in_error_handler = 0;
4662 }
4663
4664 if (!handled_by_callback) {
4665 /* Check for recursion */
4666 if (conn->in_error_handler) {
4667 DEBUG_TRACE(
4668 "Recursion when handling error %u - fall back to default",
4669 status);
4670 #if !defined(NO_FILESYSTEMS)
4671 } else {
4672 /* Send user defined error pages, if defined */
4673 error_handler = conn->dom_ctx->config[ERROR_PAGES];
4674 error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
4675 page_handler_found = 0;
4676
4677 if (error_handler != NULL) {
4678 for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4679 switch (scope) {
4680 case 1: /* Handler for specific error, e.g. 404 error */
4681 mg_snprintf(conn,
4682 &truncated,
4683 path_buf,
4684 sizeof(path_buf) - 32,
4685 "%serror%03u.",
4686 error_handler,
4687 status);
4688 break;
4689 case 2: /* Handler for error group, e.g., 5xx error
4690 * handler
4691 * for all server errors (500-599) */
4692 mg_snprintf(conn,
4693 &truncated,
4694 path_buf,
4695 sizeof(path_buf) - 32,
4696 "%serror%01uxx.",
4697 error_handler,
4698 status / 100);
4699 break;
4700 default: /* Handler for all errors */
4701 mg_snprintf(conn,
4702 &truncated,
4703 path_buf,
4704 sizeof(path_buf) - 32,
4705 "%serror.",
4706 error_handler);
4707 break;
4708 }
4709
4710 /* String truncation in buf may only occur if
4711 * error_handler is too long. This string is
4712 * from the config, not from a client. */
4713 (void)truncated;
4714
4715 len = (int)strlen(path_buf);
4716
4717 tstr = strchr(error_page_file_ext, '.');
4718
4719 while (tstr) {
4720 for (i = 1;
4721 (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
4722 i++) {
4723 /* buffer overrun is not possible here, since
4724 * (i < 32) && (len < sizeof(path_buf) - 32)
4725 * ==> (i + len) < sizeof(path_buf) */
4726 path_buf[len + i - 1] = tstr[i];
4727 }
4728 /* buffer overrun is not possible here, since
4729 * (i <= 32) && (len < sizeof(path_buf) - 32)
4730 * ==> (i + len) <= sizeof(path_buf) */
4731 path_buf[len + i - 1] = 0;
4732
4733 if (mg_stat(conn, path_buf, &error_page_file.stat)) {
4734 DEBUG_TRACE("Check error page %s - found",
4735 path_buf);
4736 page_handler_found = 1;
4737 break;
4738 }
4739 DEBUG_TRACE("Check error page %s - not found",
4740 path_buf);
4741
4742 tstr = strchr(tstr + i, '.');
4743 }
4744 }
4745 }
4746
4747 if (page_handler_found) {
4748 conn->in_error_handler = 1;
4749 handle_file_based_request(conn, path_buf, &error_page_file);
4750 conn->in_error_handler = 0;
4751 return 0;
4752 }
4753 #endif /* NO_FILESYSTEMS */
4754 }
4755
4756 /* No custom error page. Send default error page. */
4757 gmt_time_string(date, sizeof(date), &curtime);
4758
4759 conn->must_close = 1;
4760 mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
4761 send_no_cache_header(conn);
4762 send_additional_header(conn);
4763 if (has_body) {
4764 mg_printf(conn,
4765 "%s",
4766 "Content-Type: text/plain; charset=utf-8\r\n");
4767 }
4768 mg_printf(conn,
4769 "Date: %s\r\n"
4770 "Connection: close\r\n\r\n",
4771 date);
4772
4773 /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
4774 if (has_body) {
4775 /* For other errors, send a generic error message. */
4776 mg_printf(conn, "Error %d: %s\n", status, status_text);
4777 mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4778
4779 } else {
4780 /* No body allowed. Close the connection. */
4781 DEBUG_TRACE("Error %i", status);
4782 }
4783 }
4784 return 0;
4785 }
4786
4787
4788 int
4789 mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
4790 {
4791 va_list ap;
4792 int ret;
4793
4794 va_start(ap, fmt);
4795 ret = mg_send_http_error_impl(conn, status, fmt, ap);
4796 va_end(ap);
4797
4798 return ret;
4799 }
4800
4801
4802 int
4803 mg_send_http_ok(struct mg_connection *conn,
4804 const char *mime_type,
4805 long long content_length)
4806 {
4807 char date[64];
4808 time_t curtime = time(NULL);
4809
4810 if ((mime_type == NULL) || (*mime_type == 0)) {
4811 /* Parameter error */
4812 return -2;
4813 }
4814
4815 gmt_time_string(date, sizeof(date), &curtime);
4816
4817 mg_printf(conn,
4818 "HTTP/1.1 200 OK\r\n"
4819 "Content-Type: %s\r\n"
4820 "Date: %s\r\n"
4821 "Connection: %s\r\n",
4822 mime_type,
4823 date,
4824 suggest_connection_header(conn));
4825
4826 send_no_cache_header(conn);
4827 send_additional_header(conn);
4828 if (content_length < 0) {
4829 mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
4830 } else {
4831 mg_printf(conn,
4832 "Content-Length: %" UINT64_FMT "\r\n\r\n",
4833 (uint64_t)content_length);
4834 }
4835
4836 return 0;
4837 }
4838
4839
4840 int
4841 mg_send_http_redirect(struct mg_connection *conn,
4842 const char *target_url,
4843 int redirect_code)
4844 {
4845 /* Send a 30x redirect response.
4846 *
4847 * Redirect types (status codes):
4848 *
4849 * Status | Perm/Temp | Method | Version
4850 * 301 | permanent | POST->GET undefined | HTTP/1.0
4851 * 302 | temporary | POST->GET undefined | HTTP/1.0
4852 * 303 | temporary | always use GET | HTTP/1.1
4853 * 307 | temporary | always keep method | HTTP/1.1
4854 * 308 | permanent | always keep method | HTTP/1.1
4855 */
4856 const char *redirect_text;
4857 int ret;
4858 size_t content_len = 0;
4859 char reply[MG_BUF_LEN];
4860
4861 /* In case redirect_code=0, use 307. */
4862 if (redirect_code == 0) {
4863 redirect_code = 307;
4864 }
4865
4866 /* In case redirect_code is none of the above, return error. */
4867 if ((redirect_code != 301) && (redirect_code != 302)
4868 && (redirect_code != 303) && (redirect_code != 307)
4869 && (redirect_code != 308)) {
4870 /* Parameter error */
4871 return -2;
4872 }
4873
4874 /* Get proper text for response code */
4875 redirect_text = mg_get_response_code_text(conn, redirect_code);
4876
4877 /* If target_url is not defined, redirect to "/". */
4878 if ((target_url == NULL) || (*target_url == 0)) {
4879 target_url = "/";
4880 }
4881
4882 #if defined(MG_SEND_REDIRECT_BODY)
4883 /* TODO: condition name? */
4884
4885 /* Prepare a response body with a hyperlink.
4886 *
4887 * According to RFC2616 (and RFC1945 before):
4888 * Unless the request method was HEAD, the entity of the
4889 * response SHOULD contain a short hypertext note with a hyperlink to
4890 * the new URI(s).
4891 *
4892 * However, this response body is not useful in M2M communication.
4893 * Probably the original reason in the RFC was, clients not supporting
4894 * a 30x HTTP redirect could still show the HTML page and let the user
4895 * press the link. Since current browsers support 30x HTTP, the additional
4896 * HTML body does not seem to make sense anymore.
4897 *
4898 * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
4899 * but it only notes:
4900 * The server's response payload usually contains a short
4901 * hypertext note with a hyperlink to the new URI(s).
4902 *
4903 * Deactivated by default. If you need the 30x body, set the define.
4904 */
4905 mg_snprintf(
4906 conn,
4907 NULL /* ignore truncation */,
4908 reply,
4909 sizeof(reply),
4910 "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4911 redirect_text,
4912 target_url,
4913 target_url);
4914 content_len = strlen(reply);
4915 #else
4916 reply[0] = 0;
4917 #endif
4918
4919 /* Do not send any additional header. For all other options,
4920 * including caching, there are suitable defaults. */
4921 ret = mg_printf(conn,
4922 "HTTP/1.1 %i %s\r\n"
4923 "Location: %s\r\n"
4924 "Content-Length: %u\r\n"
4925 "Connection: %s\r\n\r\n",
4926 redirect_code,
4927 redirect_text,
4928 target_url,
4929 (unsigned int)content_len,
4930 suggest_connection_header(conn));
4931
4932 /* Send response body */
4933 if (ret > 0) {
4934 /* ... unless it is a HEAD request */
4935 if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
4936 ret = mg_write(conn, reply, content_len);
4937 }
4938 }
4939
4940 return (ret > 0) ? ret : -1;
4941 }
4942
4943
4944 #if defined(_WIN32)
4945 /* Create substitutes for POSIX functions in Win32. */
4946
4947 #if defined(GCC_DIAGNOSTIC)
4948 /* Show no warning in case system functions are not used. */
4949 #pragma GCC diagnostic push
4950 #pragma GCC diagnostic ignored "-Wunused-function"
4951 #endif
4952
4953
4954 static int
4955 pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
4956 {
4957 (void)unused;
4958 /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
4959 InitializeCriticalSection(&mutex->sec);
4960 return 0;
4961 }
4962
4963
4964 static int
4965 pthread_mutex_destroy(pthread_mutex_t *mutex)
4966 {
4967 DeleteCriticalSection(&mutex->sec);
4968 return 0;
4969 }
4970
4971
4972 static int
4973 pthread_mutex_lock(pthread_mutex_t *mutex)
4974 {
4975 EnterCriticalSection(&mutex->sec);
4976 return 0;
4977 }
4978
4979
4980 static int
4981 pthread_mutex_unlock(pthread_mutex_t *mutex)
4982 {
4983 LeaveCriticalSection(&mutex->sec);
4984 return 0;
4985 }
4986
4987
4988 FUNCTION_MAY_BE_UNUSED
4989 static int
4990 pthread_cond_init(pthread_cond_t *cv, const void *unused)
4991 {
4992 (void)unused;
4993 (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
4994 cv->waiting_thread = NULL;
4995 return 0;
4996 }
4997
4998
4999 FUNCTION_MAY_BE_UNUSED
5000 static int
5001 pthread_cond_timedwait(pthread_cond_t *cv,
5002 pthread_mutex_t *mutex,
5003 FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
5004 {
5005 struct mg_workerTLS **ptls,
5006 *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
5007 int ok;
5008 int64_t nsnow, nswaitabs, nswaitrel;
5009 DWORD mswaitrel;
5010
5011 pthread_mutex_lock(&cv->threadIdSec);
5012 /* Add this thread to cv's waiting list */
5013 ptls = &cv->waiting_thread;
5014 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
5015 ;
5016 tls->next_waiting_thread = NULL;
5017 *ptls = tls;
5018 pthread_mutex_unlock(&cv->threadIdSec);
5019
5020 if (abstime) {
5021 nsnow = mg_get_current_time_ns();
5022 nswaitabs =
5023 (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
5024 nswaitrel = nswaitabs - nsnow;
5025 if (nswaitrel < 0) {
5026 nswaitrel = 0;
5027 }
5028 mswaitrel = (DWORD)(nswaitrel / 1000000);
5029 } else {
5030 mswaitrel = (DWORD)INFINITE;
5031 }
5032
5033 pthread_mutex_unlock(mutex);
5034 ok = (WAIT_OBJECT_0
5035 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
5036 if (!ok) {
5037 ok = 1;
5038 pthread_mutex_lock(&cv->threadIdSec);
5039 ptls = &cv->waiting_thread;
5040 for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
5041 if (*ptls == tls) {
5042 *ptls = tls->next_waiting_thread;
5043 ok = 0;
5044 break;
5045 }
5046 }
5047 pthread_mutex_unlock(&cv->threadIdSec);
5048 if (ok) {
5049 WaitForSingleObject(tls->pthread_cond_helper_mutex,
5050 (DWORD)INFINITE);
5051 }
5052 }
5053 /* This thread has been removed from cv's waiting list */
5054 pthread_mutex_lock(mutex);
5055
5056 return ok ? 0 : -1;
5057 }
5058
5059
5060 FUNCTION_MAY_BE_UNUSED
5061 static int
5062 pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
5063 {
5064 return pthread_cond_timedwait(cv, mutex, NULL);
5065 }
5066
5067
5068 FUNCTION_MAY_BE_UNUSED
5069 static int
5070 pthread_cond_signal(pthread_cond_t *cv)
5071 {
5072 HANDLE wkup = NULL;
5073 BOOL ok = FALSE;
5074
5075 pthread_mutex_lock(&cv->threadIdSec);
5076 if (cv->waiting_thread) {
5077 wkup = cv->waiting_thread->pthread_cond_helper_mutex;
5078 cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
5079
5080 ok = SetEvent(wkup);
5081 DEBUG_ASSERT(ok);
5082 }
5083 pthread_mutex_unlock(&cv->threadIdSec);
5084
5085 return ok ? 0 : 1;
5086 }
5087
5088
5089 FUNCTION_MAY_BE_UNUSED
5090 static int
5091 pthread_cond_broadcast(pthread_cond_t *cv)
5092 {
5093 pthread_mutex_lock(&cv->threadIdSec);
5094 while (cv->waiting_thread) {
5095 pthread_cond_signal(cv);
5096 }
5097 pthread_mutex_unlock(&cv->threadIdSec);
5098
5099 return 0;
5100 }
5101
5102
5103 FUNCTION_MAY_BE_UNUSED
5104 static int
5105 pthread_cond_destroy(pthread_cond_t *cv)
5106 {
5107 pthread_mutex_lock(&cv->threadIdSec);
5108 DEBUG_ASSERT(cv->waiting_thread == NULL);
5109 pthread_mutex_unlock(&cv->threadIdSec);
5110 pthread_mutex_destroy(&cv->threadIdSec);
5111
5112 return 0;
5113 }
5114
5115
5116 #if defined(ALTERNATIVE_QUEUE)
5117 FUNCTION_MAY_BE_UNUSED
5118 static void *
5119 event_create(void)
5120 {
5121 return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
5122 }
5123
5124
5125 FUNCTION_MAY_BE_UNUSED
5126 static int
5127 event_wait(void *eventhdl)
5128 {
5129 int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
5130 return (res == WAIT_OBJECT_0);
5131 }
5132
5133
5134 FUNCTION_MAY_BE_UNUSED
5135 static int
5136 event_signal(void *eventhdl)
5137 {
5138 return (int)SetEvent((HANDLE)eventhdl);
5139 }
5140
5141
5142 FUNCTION_MAY_BE_UNUSED
5143 static void
5144 event_destroy(void *eventhdl)
5145 {
5146 CloseHandle((HANDLE)eventhdl);
5147 }
5148 #endif
5149
5150
5151 #if defined(GCC_DIAGNOSTIC)
5152 /* Enable unused function warning again */
5153 #pragma GCC diagnostic pop
5154 #endif
5155
5156
5157 /* For Windows, change all slashes to backslashes in path names. */
5158 static void
5159 change_slashes_to_backslashes(char *path)
5160 {
5161 int i;
5162
5163 for (i = 0; path[i] != '\0'; i++) {
5164 if (path[i] == '/') {
5165 path[i] = '\\';
5166 }
5167
5168 /* remove double backslash (check i > 0 to preserve UNC paths,
5169 * like \\server\file.txt) */
5170 if ((path[i] == '\\') && (i > 0)) {
5171 while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
5172 (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
5173 }
5174 }
5175 }
5176 }
5177
5178
5179 static int
5180 mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
5181 {
5182 int diff;
5183
5184 do {
5185 diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
5186 - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
5187 s1++;
5188 s2++;
5189 } while ((diff == 0) && (s1[-1] != L'\0'));
5190
5191 return diff;
5192 }
5193
5194
5195 /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
5196 * wbuf and wbuf_len is a target buffer and its length. */
5197 static void
5198 path_to_unicode(const struct mg_connection *conn,
5199 const char *path,
5200 wchar_t *wbuf,
5201 size_t wbuf_len)
5202 {
5203 char buf[PATH_MAX], buf2[PATH_MAX];
5204 wchar_t wbuf2[W_PATH_MAX + 1];
5205 DWORD long_len, err;
5206 int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
5207
5208 mg_strlcpy(buf, path, sizeof(buf));
5209 change_slashes_to_backslashes(buf);
5210
5211 /* Convert to Unicode and back. If doubly-converted string does not
5212 * match the original, something is fishy, reject. */
5213 memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
5214 MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
5215 WideCharToMultiByte(
5216 CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
5217 if (strcmp(buf, buf2) != 0) {
5218 wbuf[0] = L'\0';
5219 }
5220
5221 /* Windows file systems are not case sensitive, but you can still use
5222 * uppercase and lowercase letters (on all modern file systems).
5223 * The server can check if the URI uses the same upper/lowercase
5224 * letters an the file system, effectively making Windows servers
5225 * case sensitive (like Linux servers are). It is still not possible
5226 * to use two files with the same name in different cases on Windows
5227 * (like /a and /A) - this would be possible in Linux.
5228 * As a default, Windows is not case sensitive, but the case sensitive
5229 * file name check can be activated by an additional configuration. */
5230 if (conn) {
5231 if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
5232 && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
5233 "yes")) {
5234 /* Use case sensitive compare function */
5235 fcompare = wcscmp;
5236 }
5237 }
5238 (void)conn; /* conn is currently unused */
5239
5240 #if !defined(_WIN32_WCE)
5241 /* Only accept a full file path, not a Windows short (8.3) path. */
5242 memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
5243 long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
5244 if (long_len == 0) {
5245 err = GetLastError();
5246 if (err == ERROR_FILE_NOT_FOUND) {
5247 /* File does not exist. This is not always a problem here. */
5248 return;
5249 }
5250 }
5251 if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5252 /* Short name is used. */
5253 wbuf[0] = L'\0';
5254 }
5255 #else
5256 (void)long_len;
5257 (void)wbuf2;
5258 (void)err;
5259
5260 if (strchr(path, '~')) {
5261 wbuf[0] = L'\0';
5262 }
5263 #endif
5264 }
5265
5266
5267 #if !defined(NO_FILESYSTEMS)
5268 static int
5269 mg_stat(const struct mg_connection *conn,
5270 const char *path,
5271 struct mg_file_stat *filep)
5272 {
5273 wchar_t wbuf[W_PATH_MAX];
5274 WIN32_FILE_ATTRIBUTE_DATA info;
5275 time_t creation_time;
5276 size_t len;
5277
5278 if (!filep) {
5279 return 0;
5280 }
5281 memset(filep, 0, sizeof(*filep));
5282
5283 if (conn && is_file_in_memory(conn, path)) {
5284 /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
5285 * memset */
5286
5287 /* Quick fix (for 1.9.x): */
5288 /* mg_stat must fill all fields, also for files in memory */
5289 struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
5290 open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
5291 filep->size = tmp_file.stat.size;
5292 filep->location = 2;
5293 /* TODO: for 1.10: restructure how files in memory are handled */
5294
5295 /* The "file in memory" feature is a candidate for deletion.
5296 * Please join the discussion at
5297 * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
5298 */
5299
5300 filep->last_modified = time(NULL); /* TODO */
5301 /* last_modified = now ... assumes the file may change during
5302 * runtime,
5303 * so every mg_fopen call may return different data */
5304 /* last_modified = conn->phys_ctx.start_time;
5305 * May be used it the data does not change during runtime. This
5306 * allows
5307 * browser caching. Since we do not know, we have to assume the file
5308 * in memory may change. */
5309 return 1;
5310 }
5311
5312 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5313 /* Windows happily opens files with some garbage at the end of file name.
5314 * For example, fopen("a.cgi ", "r") on Windows successfully opens
5315 * "a.cgi", despite one would expect an error back. */
5316 len = strlen(path);
5317 if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
5318 && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
5319 filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5320 filep->last_modified =
5321 SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5322 info.ftLastWriteTime.dwHighDateTime);
5323
5324 /* On Windows, the file creation time can be higher than the
5325 * modification time, e.g. when a file is copied.
5326 * Since the Last-Modified timestamp is used for caching
5327 * it should be based on the most recent timestamp. */
5328 creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5329 info.ftCreationTime.dwHighDateTime);
5330 if (creation_time > filep->last_modified) {
5331 filep->last_modified = creation_time;
5332 }
5333
5334 filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5335 return 1;
5336 }
5337
5338 return 0;
5339 }
5340 #endif
5341
5342
5343 static int
5344 mg_remove(const struct mg_connection *conn, const char *path)
5345 {
5346 wchar_t wbuf[W_PATH_MAX];
5347 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5348 return DeleteFileW(wbuf) ? 0 : -1;
5349 }
5350
5351
5352 static int
5353 mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
5354 {
5355 wchar_t wbuf[W_PATH_MAX];
5356 (void)mode;
5357 path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5358 return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5359 }
5360
5361
5362 /* Create substitutes for POSIX functions in Win32. */
5363
5364 #if defined(GCC_DIAGNOSTIC)
5365 /* Show no warning in case system functions are not used. */
5366 #pragma GCC diagnostic push
5367 #pragma GCC diagnostic ignored "-Wunused-function"
5368 #endif
5369
5370
5371 /* Implementation of POSIX opendir/closedir/readdir for Windows. */
5372 FUNCTION_MAY_BE_UNUSED
5373 static DIR *
5374 mg_opendir(const struct mg_connection *conn, const char *name)
5375 {
5376 DIR *dir = NULL;
5377 wchar_t wpath[W_PATH_MAX];
5378 DWORD attrs;
5379
5380 if (name == NULL) {
5381 SetLastError(ERROR_BAD_ARGUMENTS);
5382 } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
5383 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5384 } else {
5385 path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
5386 attrs = GetFileAttributesW(wpath);
5387 if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5388 && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5389 (void)wcscat(wpath, L"\\*");
5390 dir->handle = FindFirstFileW(wpath, &dir->info);
5391 dir->result.d_name[0] = '\0';
5392 } else {
5393 mg_free(dir);
5394 dir = NULL;
5395 }
5396 }
5397
5398 return dir;
5399 }
5400
5401
5402 FUNCTION_MAY_BE_UNUSED
5403 static int
5404 mg_closedir(DIR *dir)
5405 {
5406 int result = 0;
5407
5408 if (dir != NULL) {
5409 if (dir->handle != INVALID_HANDLE_VALUE)
5410 result = FindClose(dir->handle) ? 0 : -1;
5411
5412 mg_free(dir);
5413 } else {
5414 result = -1;
5415 SetLastError(ERROR_BAD_ARGUMENTS);
5416 }
5417
5418 return result;
5419 }
5420
5421
5422 FUNCTION_MAY_BE_UNUSED
5423 static struct dirent *
5424 mg_readdir(DIR *dir)
5425 {
5426 struct dirent *result = 0;
5427
5428 if (dir) {
5429 if (dir->handle != INVALID_HANDLE_VALUE) {
5430 result = &dir->result;
5431 (void)WideCharToMultiByte(CP_UTF8,
5432 0,
5433 dir->info.cFileName,
5434 -1,
5435 result->d_name,
5436 sizeof(result->d_name),
5437 NULL,
5438 NULL);
5439
5440 if (!FindNextFileW(dir->handle, &dir->info)) {
5441 (void)FindClose(dir->handle);
5442 dir->handle = INVALID_HANDLE_VALUE;
5443 }
5444
5445 } else {
5446 SetLastError(ERROR_FILE_NOT_FOUND);
5447 }
5448 } else {
5449 SetLastError(ERROR_BAD_ARGUMENTS);
5450 }
5451
5452 return result;
5453 }
5454
5455
5456 #if !defined(HAVE_POLL)
5457 #undef POLLIN
5458 #undef POLLPRI
5459 #undef POLLOUT
5460 #define POLLIN (1) /* Data ready - read will not block. */
5461 #define POLLPRI (2) /* Priority data ready. */
5462 #define POLLOUT (4) /* Send queue not full - write will not block. */
5463
5464 FUNCTION_MAY_BE_UNUSED
5465 static int
5466 poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
5467 {
5468 struct timeval tv;
5469 fd_set rset;
5470 fd_set wset;
5471 unsigned int i;
5472 int result;
5473 SOCKET maxfd = 0;
5474
5475 memset(&tv, 0, sizeof(tv));
5476 tv.tv_sec = milliseconds / 1000;
5477 tv.tv_usec = (milliseconds % 1000) * 1000;
5478 FD_ZERO(&rset);
5479 FD_ZERO(&wset);
5480
5481 for (i = 0; i < n; i++) {
5482 if (pfd[i].events & POLLIN) {
5483 FD_SET(pfd[i].fd, &rset);
5484 }
5485 if (pfd[i].events & POLLOUT) {
5486 FD_SET(pfd[i].fd, &wset);
5487 }
5488 pfd[i].revents = 0;
5489
5490 if (pfd[i].fd > maxfd) {
5491 maxfd = pfd[i].fd;
5492 }
5493 }
5494
5495 if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
5496 for (i = 0; i < n; i++) {
5497 if (FD_ISSET(pfd[i].fd, &rset)) {
5498 pfd[i].revents |= POLLIN;
5499 }
5500 if (FD_ISSET(pfd[i].fd, &wset)) {
5501 pfd[i].revents |= POLLOUT;
5502 }
5503 }
5504 }
5505
5506 /* We should subtract the time used in select from remaining
5507 * "milliseconds", in particular if called from mg_poll with a
5508 * timeout quantum.
5509 * Unfortunately, the remaining time is not stored in "tv" in all
5510 * implementations, so the result in "tv" must be considered undefined.
5511 * See http://man7.org/linux/man-pages/man2/select.2.html */
5512
5513 return result;
5514 }
5515 #endif /* HAVE_POLL */
5516
5517
5518 #if defined(GCC_DIAGNOSTIC)
5519 /* Enable unused function warning again */
5520 #pragma GCC diagnostic pop
5521 #endif
5522
5523
5524 static void
5525 set_close_on_exec(SOCKET sock,
5526 const struct mg_connection *conn /* may be null */,
5527 struct mg_context *ctx /* may be null */)
5528 {
5529 (void)conn; /* Unused. */
5530 (void)ctx;
5531 #if defined(_WIN32_WCE)
5532 (void)sock;
5533 #else
5534 (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5535 #endif
5536 }
5537
5538
5539 int
5540 mg_start_thread(mg_thread_func_t f, void *p)
5541 {
5542 #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5543 /* Compile-time option to control stack size, e.g.
5544 * -DUSE_STACK_SIZE=16384
5545 */
5546 return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
5547 == ((uintptr_t)(-1L)))
5548 ? -1
5549 : 0);
5550 #else
5551 return (
5552 (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
5553 ? -1
5554 : 0);
5555 #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5556 }
5557
5558
5559 /* Start a thread storing the thread context. */
5560 static int
5561 mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
5562 void *p,
5563 pthread_t *threadidptr)
5564 {
5565 uintptr_t uip;
5566 HANDLE threadhandle;
5567 int result = -1;
5568
5569 uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
5570 threadhandle = (HANDLE)uip;
5571 if ((uip != 0) && (threadidptr != NULL)) {
5572 *threadidptr = threadhandle;
5573 result = 0;
5574 }
5575
5576 return result;
5577 }
5578
5579
5580 /* Wait for a thread to finish. */
5581 static int
5582 mg_join_thread(pthread_t threadid)
5583 {
5584 int result;
5585 DWORD dwevent;
5586
5587 result = -1;
5588 dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5589 if (dwevent == WAIT_FAILED) {
5590 DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
5591 } else {
5592 if (dwevent == WAIT_OBJECT_0) {
5593 CloseHandle(threadid);
5594 result = 0;
5595 }
5596 }
5597
5598 return result;
5599 }
5600
5601 #if !defined(NO_SSL_DL) && !defined(NO_SSL)
5602 /* If SSL is loaded dynamically, dlopen/dlclose is required. */
5603 /* Create substitutes for POSIX functions in Win32. */
5604
5605 #if defined(GCC_DIAGNOSTIC)
5606 /* Show no warning in case system functions are not used. */
5607 #pragma GCC diagnostic push
5608 #pragma GCC diagnostic ignored "-Wunused-function"
5609 #endif
5610
5611
5612 FUNCTION_MAY_BE_UNUSED
5613 static HANDLE
5614 dlopen(const char *dll_name, int flags)
5615 {
5616 wchar_t wbuf[W_PATH_MAX];
5617 (void)flags;
5618 path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
5619 return LoadLibraryW(wbuf);
5620 }
5621
5622
5623 FUNCTION_MAY_BE_UNUSED
5624 static int
5625 dlclose(void *handle)
5626 {
5627 int result;
5628
5629 if (FreeLibrary((HMODULE)handle) != 0) {
5630 result = 0;
5631 } else {
5632 result = -1;
5633 }
5634
5635 return result;
5636 }
5637
5638
5639 #if defined(GCC_DIAGNOSTIC)
5640 /* Enable unused function warning again */
5641 #pragma GCC diagnostic pop
5642 #endif
5643
5644 #endif
5645
5646
5647 #if !defined(NO_CGI)
5648 #define SIGKILL (0)
5649
5650
5651 static int
5652 kill(pid_t pid, int sig_num)
5653 {
5654 (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5655 (void)CloseHandle((HANDLE)pid);
5656 return 0;
5657 }
5658
5659
5660 #if !defined(WNOHANG)
5661 #define WNOHANG (1)
5662 #endif
5663
5664
5665 static pid_t
5666 waitpid(pid_t pid, int *status, int flags)
5667 {
5668 DWORD timeout = INFINITE;
5669 DWORD waitres;
5670
5671 (void)status; /* Currently not used by any client here */
5672
5673 if ((flags | WNOHANG) == WNOHANG) {
5674 timeout = 0;
5675 }
5676
5677 waitres = WaitForSingleObject((HANDLE)pid, timeout);
5678 if (waitres == WAIT_OBJECT_0) {
5679 return pid;
5680 }
5681 if (waitres == WAIT_TIMEOUT) {
5682 return 0;
5683 }
5684 return (pid_t)-1;
5685 }
5686
5687
5688 static void
5689 trim_trailing_whitespaces(char *s)
5690 {
5691 char *e = s + strlen(s);
5692 while ((e > s) && isspace((unsigned char)e[-1])) {
5693 *(--e) = '\0';
5694 }
5695 }
5696
5697
5698 static pid_t
5699 spawn_process(struct mg_connection *conn,
5700 const char *prog,
5701 char *envblk,
5702 char *envp[],
5703 int fdin[2],
5704 int fdout[2],
5705 int fderr[2],
5706 const char *dir)
5707 {
5708 HANDLE me;
5709 char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
5710 cmdline[PATH_MAX], buf[PATH_MAX];
5711 int truncated;
5712 struct mg_file file = STRUCT_FILE_INITIALIZER;
5713 STARTUPINFOA si;
5714 PROCESS_INFORMATION pi = {0};
5715
5716 (void)envp;
5717
5718 memset(&si, 0, sizeof(si));
5719 si.cb = sizeof(si);
5720
5721 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5722 si.wShowWindow = SW_HIDE;
5723
5724 me = GetCurrentProcess();
5725 DuplicateHandle(me,
5726 (HANDLE)_get_osfhandle(fdin[0]),
5727 me,
5728 &si.hStdInput,
5729 0,
5730 TRUE,
5731 DUPLICATE_SAME_ACCESS);
5732 DuplicateHandle(me,
5733 (HANDLE)_get_osfhandle(fdout[1]),
5734 me,
5735 &si.hStdOutput,
5736 0,
5737 TRUE,
5738 DUPLICATE_SAME_ACCESS);
5739 DuplicateHandle(me,
5740 (HANDLE)_get_osfhandle(fderr[1]),
5741 me,
5742 &si.hStdError,
5743 0,
5744 TRUE,
5745 DUPLICATE_SAME_ACCESS);
5746
5747 /* Mark handles that should not be inherited. See
5748 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
5749 */
5750 SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5751 HANDLE_FLAG_INHERIT,
5752 0);
5753 SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5754 HANDLE_FLAG_INHERIT,
5755 0);
5756 SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5757 HANDLE_FLAG_INHERIT,
5758 0);
5759
5760 /* If CGI file is a script, try to read the interpreter line */
5761 interp = conn->dom_ctx->config[CGI_INTERPRETER];
5762 if (interp == NULL) {
5763 buf[0] = buf[1] = '\0';
5764
5765 /* Read the first line of the script into the buffer */
5766 mg_snprintf(
5767 conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
5768
5769 if (truncated) {
5770 pi.hProcess = (pid_t)-1;
5771 goto spawn_cleanup;
5772 }
5773
5774 if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
5775 #if defined(MG_USE_OPEN_FILE)
5776 p = (char *)file.access.membuf;
5777 #else
5778 p = (char *)NULL;
5779 #endif
5780 mg_fgets(buf, sizeof(buf), &file, &p);
5781 (void)mg_fclose(&file.access); /* ignore error on read only file */
5782 buf[sizeof(buf) - 1] = '\0';
5783 }
5784
5785 if ((buf[0] == '#') && (buf[1] == '!')) {
5786 trim_trailing_whitespaces(buf + 2);
5787 } else {
5788 buf[2] = '\0';
5789 }
5790 interp = buf + 2;
5791 }
5792
5793 if (interp[0] != '\0') {
5794 GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
5795 interp = full_interp;
5796 }
5797 GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
5798
5799 if (interp[0] != '\0') {
5800 mg_snprintf(conn,
5801 &truncated,
5802 cmdline,
5803 sizeof(cmdline),
5804 "\"%s\" \"%s\\%s\"",
5805 interp,
5806 full_dir,
5807 prog);
5808 } else {
5809 mg_snprintf(conn,
5810 &truncated,
5811 cmdline,
5812 sizeof(cmdline),
5813 "\"%s\\%s\"",
5814 full_dir,
5815 prog);
5816 }
5817
5818 if (truncated) {
5819 pi.hProcess = (pid_t)-1;
5820 goto spawn_cleanup;
5821 }
5822
5823 DEBUG_TRACE("Running [%s]", cmdline);
5824 if (CreateProcessA(NULL,
5825 cmdline,
5826 NULL,
5827 NULL,
5828 TRUE,
5829 CREATE_NEW_PROCESS_GROUP,
5830 envblk,
5831 NULL,
5832 &si,
5833 &pi)
5834 == 0) {
5835 mg_cry_internal(
5836 conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
5837 pi.hProcess = (pid_t)-1;
5838 /* goto spawn_cleanup; */
5839 }
5840
5841 spawn_cleanup:
5842 (void)CloseHandle(si.hStdOutput);
5843 (void)CloseHandle(si.hStdError);
5844 (void)CloseHandle(si.hStdInput);
5845 if (pi.hThread != NULL) {
5846 (void)CloseHandle(pi.hThread);
5847 }
5848
5849 return (pid_t)pi.hProcess;
5850 }
5851 #endif /* !NO_CGI */
5852
5853
5854 static int
5855 set_blocking_mode(SOCKET sock)
5856 {
5857 unsigned long non_blocking = 0;
5858 return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5859 }
5860
5861 static int
5862 set_non_blocking_mode(SOCKET sock)
5863 {
5864 unsigned long non_blocking = 1;
5865 return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5866 }
5867
5868 #else
5869
5870 #if !defined(NO_FILESYSTEMS)
5871 static int
5872 mg_stat(const struct mg_connection *conn,
5873 const char *path,
5874 struct mg_file_stat *filep)
5875 {
5876 struct stat st;
5877 if (!filep) {
5878 return 0;
5879 }
5880 memset(filep, 0, sizeof(*filep));
5881
5882 if (conn && is_file_in_memory(conn, path)) {
5883
5884 /* Quick fix (for 1.9.x): */
5885 /* mg_stat must fill all fields, also for files in memory */
5886 struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
5887 open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
5888 filep->size = tmp_file.stat.size;
5889 filep->last_modified = time(NULL);
5890 filep->location = 2;
5891 /* TODO: remove legacy "files in memory" feature */
5892
5893 return 1;
5894 }
5895
5896 if (0 == stat(path, &st)) {
5897 filep->size = (uint64_t)(st.st_size);
5898 filep->last_modified = st.st_mtime;
5899 filep->is_directory = S_ISDIR(st.st_mode);
5900 return 1;
5901 }
5902
5903 return 0;
5904 }
5905 #endif /* NO_FILESYSTEMS */
5906
5907
5908 static void
5909 set_close_on_exec(int fd,
5910 const struct mg_connection *conn /* may be null */,
5911 struct mg_context *ctx /* may be null */)
5912 {
5913 #if defined(__ZEPHYR__)
5914 (void)fd;
5915 (void)conn;
5916 (void)ctx;
5917 #else
5918 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5919 if (conn || ctx) {
5920 struct mg_connection fc;
5921 mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
5922 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5923 __func__,
5924 strerror(ERRNO));
5925 }
5926 }
5927 #endif
5928 }
5929
5930
5931 int
5932 mg_start_thread(mg_thread_func_t func, void *param)
5933 {
5934 pthread_t thread_id;
5935 pthread_attr_t attr;
5936 int result;
5937
5938 (void)pthread_attr_init(&attr);
5939 (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
5940
5941 #if defined(__ZEPHYR__)
5942 pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
5943 #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5944 /* Compile-time option to control stack size,
5945 * e.g. -DUSE_STACK_SIZE=16384 */
5946 (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5947 #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5948
5949 result = pthread_create(&thread_id, &attr, func, param);
5950 pthread_attr_destroy(&attr);
5951
5952 return result;
5953 }
5954
5955
5956 /* Start a thread storing the thread context. */
5957 static int
5958 mg_start_thread_with_id(mg_thread_func_t func,
5959 void *param,
5960 pthread_t *threadidptr)
5961 {
5962 pthread_t thread_id;
5963 pthread_attr_t attr;
5964 int result;
5965
5966 (void)pthread_attr_init(&attr);
5967
5968 #if defined(__ZEPHYR__)
5969 pthread_attr_setstack(&attr,
5970 &civetweb_worker_stacks[zephyr_worker_stack_index++],
5971 ZEPHYR_STACK_SIZE);
5972 #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5973 /* Compile-time option to control stack size,
5974 * e.g. -DUSE_STACK_SIZE=16384 */
5975 (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5976 #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
5977
5978 result = pthread_create(&thread_id, &attr, func, param);
5979 pthread_attr_destroy(&attr);
5980 if ((result == 0) && (threadidptr != NULL)) {
5981 *threadidptr = thread_id;
5982 }
5983 return result;
5984 }
5985
5986
5987 /* Wait for a thread to finish. */
5988 static int
5989 mg_join_thread(pthread_t threadid)
5990 {
5991 int result;
5992
5993 result = pthread_join(threadid, NULL);
5994 return result;
5995 }
5996
5997
5998 #if !defined(NO_CGI)
5999 static pid_t
6000 spawn_process(struct mg_connection *conn,
6001 const char *prog,
6002 char *envblk,
6003 char *envp[],
6004 int fdin[2],
6005 int fdout[2],
6006 int fderr[2],
6007 const char *dir)
6008 {
6009 pid_t pid;
6010 const char *interp;
6011
6012 (void)envblk;
6013
6014 if ((pid = fork()) == -1) {
6015 /* Parent */
6016 mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
6017 } else if (pid != 0) {
6018 /* Make sure children close parent-side descriptors.
6019 * The caller will close the child-side immediately. */
6020 set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
6021 set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
6022 set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
6023 } else {
6024 /* Child */
6025 if (chdir(dir) != 0) {
6026 mg_cry_internal(
6027 conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
6028 } else if (dup2(fdin[0], 0) == -1) {
6029 mg_cry_internal(conn,
6030 "%s: dup2(%d, 0): %s",
6031 __func__,
6032 fdin[0],
6033 strerror(ERRNO));
6034 } else if (dup2(fdout[1], 1) == -1) {
6035 mg_cry_internal(conn,
6036 "%s: dup2(%d, 1): %s",
6037 __func__,
6038 fdout[1],
6039 strerror(ERRNO));
6040 } else if (dup2(fderr[1], 2) == -1) {
6041 mg_cry_internal(conn,
6042 "%s: dup2(%d, 2): %s",
6043 __func__,
6044 fderr[1],
6045 strerror(ERRNO));
6046 } else {
6047 struct sigaction sa;
6048
6049 /* Keep stderr and stdout in two different pipes.
6050 * Stdout will be sent back to the client,
6051 * stderr should go into a server error log. */
6052 (void)close(fdin[0]);
6053 (void)close(fdout[1]);
6054 (void)close(fderr[1]);
6055
6056 /* Close write end fdin and read end fdout and fderr */
6057 (void)close(fdin[1]);
6058 (void)close(fdout[0]);
6059 (void)close(fderr[0]);
6060
6061 /* After exec, all signal handlers are restored to their default
6062 * values, with one exception of SIGCHLD. According to
6063 * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
6064 * will leave unchanged after exec if it was set to be ignored.
6065 * Restore it to default action. */
6066 memset(&sa, 0, sizeof(sa));
6067 sa.sa_handler = SIG_DFL;
6068 sigaction(SIGCHLD, &sa, NULL);
6069
6070 interp = conn->dom_ctx->config[CGI_INTERPRETER];
6071 if (interp == NULL) {
6072 (void)execle(prog, prog, NULL, envp);
6073 mg_cry_internal(conn,
6074 "%s: execle(%s): %s",
6075 __func__,
6076 prog,
6077 strerror(ERRNO));
6078 } else {
6079 (void)execle(interp, interp, prog, NULL, envp);
6080 mg_cry_internal(conn,
6081 "%s: execle(%s %s): %s",
6082 __func__,
6083 interp,
6084 prog,
6085 strerror(ERRNO));
6086 }
6087 }
6088 exit(EXIT_FAILURE);
6089 }
6090
6091 return pid;
6092 }
6093 #endif /* !NO_CGI */
6094
6095
6096 static int
6097 set_non_blocking_mode(SOCKET sock)
6098 {
6099 int flags = fcntl(sock, F_GETFL, 0);
6100 if (flags < 0) {
6101 return -1;
6102 }
6103
6104 if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
6105 return -1;
6106 }
6107 return 0;
6108 }
6109
6110 static int
6111 set_blocking_mode(SOCKET sock)
6112 {
6113 int flags = fcntl(sock, F_GETFL, 0);
6114 if (flags < 0) {
6115 return -1;
6116 }
6117
6118 if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
6119 return -1;
6120 }
6121 return 0;
6122 }
6123 #endif /* _WIN32 / else */
6124
6125 /* End of initial operating system specific define block. */
6126
6127
6128 /* Get a random number (independent of C rand function) */
6129 static uint64_t
6130 get_random(void)
6131 {
6132 static uint64_t lfsr = 0; /* Linear feedback shift register */
6133 static uint64_t lcg = 0; /* Linear congruential generator */
6134 uint64_t now = mg_get_current_time_ns();
6135
6136 if (lfsr == 0) {
6137 /* lfsr will be only 0 if has not been initialized,
6138 * so this code is called only once. */
6139 lfsr = mg_get_current_time_ns();
6140 lcg = mg_get_current_time_ns();
6141 } else {
6142 /* Get the next step of both random number generators. */
6143 lfsr = (lfsr >> 1)
6144 | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
6145 << 63);
6146 lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
6147 }
6148
6149 /* Combining two pseudo-random number generators and a high resolution
6150 * part
6151 * of the current server time will make it hard (impossible?) to guess
6152 * the
6153 * next number. */
6154 return (lfsr ^ lcg ^ now);
6155 }
6156
6157
6158 static int
6159 mg_poll(struct mg_pollfd *pfd,
6160 unsigned int n,
6161 int milliseconds,
6162 volatile int *stop_server)
6163 {
6164 /* Call poll, but only for a maximum time of a few seconds.
6165 * This will allow to stop the server after some seconds, instead
6166 * of having to wait for a long socket timeout. */
6167 int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
6168
6169 do {
6170 int result;
6171
6172 if (*stop_server) {
6173 /* Shut down signal */
6174 return -2;
6175 }
6176
6177 if ((milliseconds >= 0) && (milliseconds < ms_now)) {
6178 ms_now = milliseconds;
6179 }
6180
6181 result = poll(pfd, n, ms_now);
6182 if (result != 0) {
6183 /* Poll returned either success (1) or error (-1).
6184 * Forward both to the caller. */
6185 return result;
6186 }
6187
6188 /* Poll returned timeout (0). */
6189 if (milliseconds > 0) {
6190 milliseconds -= ms_now;
6191 }
6192
6193 } while (milliseconds != 0);
6194
6195 /* timeout: return 0 */
6196 return 0;
6197 }
6198
6199
6200 /* Write data to the IO channel - opened file descriptor, socket or SSL
6201 * descriptor.
6202 * Return value:
6203 * >=0 .. number of bytes successfully written
6204 * -1 .. timeout
6205 * -2 .. error
6206 */
6207 static int
6208 push_inner(struct mg_context *ctx,
6209 FILE *fp,
6210 SOCKET sock,
6211 SSL *ssl,
6212 const char *buf,
6213 int len,
6214 double timeout)
6215 {
6216 uint64_t start = 0, now = 0, timeout_ns = 0;
6217 int n, err;
6218 unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
6219
6220 #if defined(_WIN32)
6221 typedef int len_t;
6222 #else
6223 typedef size_t len_t;
6224 #endif
6225
6226 if (timeout > 0) {
6227 now = mg_get_current_time_ns();
6228 start = now;
6229 timeout_ns = (uint64_t)(timeout * 1.0E9);
6230 }
6231
6232 if (ctx == NULL) {
6233 return -2;
6234 }
6235
6236 #if defined(NO_SSL)
6237 if (ssl) {
6238 return -2;
6239 }
6240 #endif
6241
6242 /* Try to read until it succeeds, fails, times out, or the server
6243 * shuts down. */
6244 for (;;) {
6245
6246 #if !defined(NO_SSL)
6247 if (ssl != NULL) {
6248 n = SSL_write(ssl, buf, len);
6249 if (n <= 0) {
6250 err = SSL_get_error(ssl, n);
6251 if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
6252 err = ERRNO;
6253 } else if ((err == SSL_ERROR_WANT_READ)
6254 || (err == SSL_ERROR_WANT_WRITE)) {
6255 n = 0;
6256 } else {
6257 DEBUG_TRACE("SSL_write() failed, error %d", err);
6258 return -2;
6259 }
6260 } else {
6261 err = 0;
6262 }
6263 } else
6264 #endif
6265 if (fp != NULL) {
6266 n = (int)fwrite(buf, 1, (size_t)len, fp);
6267 if (ferror(fp)) {
6268 n = -1;
6269 err = ERRNO;
6270 } else {
6271 err = 0;
6272 }
6273 } else {
6274 n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
6275 err = (n < 0) ? ERRNO : 0;
6276 #if defined(_WIN32)
6277 if (err == WSAEWOULDBLOCK) {
6278 err = 0;
6279 n = 0;
6280 }
6281 #else
6282 if (err == EWOULDBLOCK) {
6283 err = 0;
6284 n = 0;
6285 }
6286 #endif
6287 if (n < 0) {
6288 /* shutdown of the socket at client side */
6289 return -2;
6290 }
6291 }
6292
6293 if (ctx->stop_flag) {
6294 return -2;
6295 }
6296
6297 if ((n > 0) || ((n == 0) && (len == 0))) {
6298 /* some data has been read, or no data was requested */
6299 return n;
6300 }
6301 if (n < 0) {
6302 /* socket error - check errno */
6303 DEBUG_TRACE("send() failed, error %d", err);
6304
6305 /* TODO (mid): error handling depending on the error code.
6306 * These codes are different between Windows and Linux.
6307 * Currently there is no problem with failing send calls,
6308 * if there is a reproducible situation, it should be
6309 * investigated in detail.
6310 */
6311 return -2;
6312 }
6313
6314 /* Only in case n=0 (timeout), repeat calling the write function */
6315
6316 /* If send failed, wait before retry */
6317 if (fp != NULL) {
6318 /* For files, just wait a fixed time.
6319 * Maybe it helps, maybe not. */
6320 mg_sleep(5);
6321 } else {
6322 /* For sockets, wait for the socket using poll */
6323 struct mg_pollfd pfd[1];
6324 int pollres;
6325
6326 pfd[0].fd = sock;
6327 pfd[0].events = POLLOUT;
6328 pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
6329 if (ctx->stop_flag) {
6330 return -2;
6331 }
6332 if (pollres > 0) {
6333 continue;
6334 }
6335 }
6336
6337 if (timeout > 0) {
6338 now = mg_get_current_time_ns();
6339 if ((now - start) > timeout_ns) {
6340 /* Timeout */
6341 break;
6342 }
6343 }
6344 }
6345
6346 (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
6347 used */
6348
6349 return -1;
6350 }
6351
6352
6353 static int
6354 push_all(struct mg_context *ctx,
6355 FILE *fp,
6356 SOCKET sock,
6357 SSL *ssl,
6358 const char *buf,
6359 int len)
6360 {
6361 double timeout = -1.0;
6362 int n, nwritten = 0;
6363
6364 if (ctx == NULL) {
6365 return -1;
6366 }
6367
6368 if (ctx->dd.config[REQUEST_TIMEOUT]) {
6369 timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
6370 }
6371
6372 while ((len > 0) && (ctx->stop_flag == 0)) {
6373 n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
6374 if (n < 0) {
6375 if (nwritten == 0) {
6376 nwritten = -1; /* Propagate the error */
6377 }
6378 break;
6379 } else if (n == 0) {
6380 break; /* No more data to write */
6381 } else {
6382 nwritten += n;
6383 len -= n;
6384 }
6385 }
6386
6387 return nwritten;
6388 }
6389
6390
6391 /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
6392 * Return value:
6393 * >=0 .. number of bytes successfully read
6394 * -1 .. timeout
6395 * -2 .. error
6396 */
6397 static int
6398 pull_inner(FILE *fp,
6399 struct mg_connection *conn,
6400 char *buf,
6401 int len,
6402 double timeout)
6403 {
6404 int nread, err = 0;
6405
6406 #if defined(_WIN32)
6407 typedef int len_t;
6408 #else
6409 typedef size_t len_t;
6410 #endif
6411 #if !defined(NO_SSL)
6412 int ssl_pending;
6413 #endif
6414
6415 /* We need an additional wait loop around this, because in some cases
6416 * with TLSwe may get data from the socket but not from SSL_read.
6417 * In this case we need to repeat at least once.
6418 */
6419
6420 if (fp != NULL) {
6421 #if !defined(_WIN32_WCE)
6422 /* Use read() instead of fread(), because if we're reading from the
6423 * CGI pipe, fread() may block until IO buffer is filled up. We
6424 * cannot afford to block and must pass all read bytes immediately
6425 * to the client. */
6426 nread = (int)read(fileno(fp), buf, (size_t)len);
6427 #else
6428 /* WinCE does not support CGI pipes */
6429 nread = (int)fread(buf, 1, (size_t)len, fp);
6430 #endif
6431 err = (nread < 0) ? ERRNO : 0;
6432 if ((nread == 0) && (len > 0)) {
6433 /* Should get data, but got EOL */
6434 return -2;
6435 }
6436
6437 #if !defined(NO_SSL)
6438 } else if ((conn->ssl != NULL)
6439 && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
6440 /* We already know there is no more data buffered in conn->buf
6441 * but there is more available in the SSL layer. So don't poll
6442 * conn->client.sock yet. */
6443 if (ssl_pending > len) {
6444 ssl_pending = len;
6445 }
6446 nread = SSL_read(conn->ssl, buf, ssl_pending);
6447 if (nread <= 0) {
6448 err = SSL_get_error(conn->ssl, nread);
6449 if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
6450 err = ERRNO;
6451 } else if ((err == SSL_ERROR_WANT_READ)
6452 || (err == SSL_ERROR_WANT_WRITE)) {
6453 nread = 0;
6454 } else {
6455 /* All errors should return -2 */
6456 DEBUG_TRACE("SSL_read() failed, error %d", err);
6457 return -2;
6458 }
6459
6460 ERR_clear_error();
6461 } else {
6462 err = 0;
6463 }
6464
6465 } else if (conn->ssl != NULL) {
6466
6467 struct mg_pollfd pfd[1];
6468 int pollres;
6469
6470 pfd[0].fd = conn->client.sock;
6471 pfd[0].events = POLLIN;
6472 pollres = mg_poll(pfd,
6473 1,
6474 (int)(timeout * 1000.0),
6475 &(conn->phys_ctx->stop_flag));
6476 if (conn->phys_ctx->stop_flag) {
6477 return -2;
6478 }
6479 if (pollres > 0) {
6480 nread = SSL_read(conn->ssl, buf, len);
6481 if (nread <= 0) {
6482 err = SSL_get_error(conn->ssl, nread);
6483 if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
6484 err = ERRNO;
6485 } else if ((err == SSL_ERROR_WANT_READ)
6486 || (err == SSL_ERROR_WANT_WRITE)) {
6487 nread = 0;
6488 } else {
6489 DEBUG_TRACE("SSL_read() failed, error %d", err);
6490 return -2;
6491 }
6492 } else {
6493 err = 0;
6494 }
6495 ERR_clear_error();
6496 } else if (pollres < 0) {
6497 /* Error */
6498 return -2;
6499 } else {
6500 /* pollres = 0 means timeout */
6501 nread = 0;
6502 }
6503 #endif
6504
6505 } else {
6506 struct mg_pollfd pfd[1];
6507 int pollres;
6508
6509 pfd[0].fd = conn->client.sock;
6510 pfd[0].events = POLLIN;
6511 pollres = mg_poll(pfd,
6512 1,
6513 (int)(timeout * 1000.0),
6514 &(conn->phys_ctx->stop_flag));
6515 if (conn->phys_ctx->stop_flag) {
6516 return -2;
6517 }
6518 if (pollres > 0) {
6519 nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
6520 err = (nread < 0) ? ERRNO : 0;
6521 if (nread <= 0) {
6522 /* shutdown of the socket at client side */
6523 return -2;
6524 }
6525 } else if (pollres < 0) {
6526 /* error callint poll */
6527 return -2;
6528 } else {
6529 /* pollres = 0 means timeout */
6530 nread = 0;
6531 }
6532 }
6533
6534 if (conn->phys_ctx->stop_flag) {
6535 return -2;
6536 }
6537
6538 if ((nread > 0) || ((nread == 0) && (len == 0))) {
6539 /* some data has been read, or no data was requested */
6540 return nread;
6541 }
6542
6543 if (nread < 0) {
6544 /* socket error - check errno */
6545 #if defined(_WIN32)
6546 if (err == WSAEWOULDBLOCK) {
6547 /* TODO (low): check if this is still required */
6548 /* standard case if called from close_socket_gracefully */
6549 return -2;
6550 } else if (err == WSAETIMEDOUT) {
6551 /* TODO (low): check if this is still required */
6552 /* timeout is handled by the while loop */
6553 return 0;
6554 } else if (err == WSAECONNABORTED) {
6555 /* See https://www.chilkatsoft.com/p/p_299.asp */
6556 return -2;
6557 } else {
6558 DEBUG_TRACE("recv() failed, error %d", err);
6559 return -2;
6560 }
6561 #else
6562 /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
6563 * if the timeout is reached and if the socket was set to non-
6564 * blocking in close_socket_gracefully, so we can not distinguish
6565 * here. We have to wait for the timeout in both cases for now.
6566 */
6567 if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
6568 /* TODO (low): check if this is still required */
6569 /* EAGAIN/EWOULDBLOCK:
6570 * standard case if called from close_socket_gracefully
6571 * => should return -1 */
6572 /* or timeout occurred
6573 * => the code must stay in the while loop */
6574
6575 /* EINTR can be generated on a socket with a timeout set even
6576 * when SA_RESTART is effective for all relevant signals
6577 * (see signal(7)).
6578 * => stay in the while loop */
6579 } else {
6580 DEBUG_TRACE("recv() failed, error %d", err);
6581 return -2;
6582 }
6583 #endif
6584 }
6585
6586 /* Timeout occurred, but no data available. */
6587 return -1;
6588 }
6589
6590
6591 static int
6592 pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
6593 {
6594 int n, nread = 0;
6595 double timeout = -1.0;
6596 uint64_t start_time = 0, now = 0, timeout_ns = 0;
6597
6598 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
6599 timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
6600 }
6601 if (timeout >= 0.0) {
6602 start_time = mg_get_current_time_ns();
6603 timeout_ns = (uint64_t)(timeout * 1.0E9);
6604 }
6605
6606 while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
6607 n = pull_inner(fp, conn, buf + nread, len, timeout);
6608 if (n == -2) {
6609 if (nread == 0) {
6610 nread = -1; /* Propagate the error */
6611 }
6612 break;
6613 } else if (n == -1) {
6614 /* timeout */
6615 if (timeout >= 0.0) {
6616 now = mg_get_current_time_ns();
6617 if ((now - start_time) <= timeout_ns) {
6618 continue;
6619 }
6620 }
6621 break;
6622 } else if (n == 0) {
6623 break; /* No more data to read */
6624 } else {
6625 nread += n;
6626 len -= n;
6627 }
6628 }
6629
6630 return nread;
6631 }
6632
6633
6634 static void
6635 discard_unread_request_data(struct mg_connection *conn)
6636 {
6637 char buf[MG_BUF_LEN];
6638
6639 while (mg_read(conn, buf, sizeof(buf)) > 0)
6640 ;
6641 }
6642
6643
6644 static int
6645 mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
6646 {
6647 int64_t content_len, n, buffered_len, nread;
6648 int64_t len64 =
6649 (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
6650 * int, we may not read more
6651 * bytes */
6652 const char *body;
6653
6654 if (conn == NULL) {
6655 return 0;
6656 }
6657
6658 /* If Content-Length is not set for a response with body data,
6659 * we do not know in advance how much data should be read. */
6660 content_len = conn->content_len;
6661 if (content_len < 0) {
6662 /* The body data is completed when the connection is closed. */
6663 content_len = INT64_MAX;
6664 }
6665
6666 nread = 0;
6667 if (conn->consumed_content < content_len) {
6668 /* Adjust number of bytes to read. */
6669 int64_t left_to_read = content_len - conn->consumed_content;
6670 if (left_to_read < len64) {
6671 /* Do not read more than the total content length of the
6672 * request.
6673 */
6674 len64 = left_to_read;
6675 }
6676
6677 /* Return buffered data */
6678 buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
6679 - conn->consumed_content;
6680 if (buffered_len > 0) {
6681 if (len64 < buffered_len) {
6682 buffered_len = len64;
6683 }
6684 body = conn->buf + conn->request_len + conn->consumed_content;
6685 memcpy(buf, body, (size_t)buffered_len);
6686 len64 -= buffered_len;
6687 conn->consumed_content += buffered_len;
6688 nread += buffered_len;
6689 buf = (char *)buf + buffered_len;
6690 }
6691
6692 /* We have returned all buffered data. Read new data from the remote
6693 * socket.
6694 */
6695 if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
6696 conn->consumed_content += n;
6697 nread += n;
6698 } else {
6699 nread = ((nread > 0) ? nread : n);
6700 }
6701 }
6702 return (int)nread;
6703 }
6704
6705
6706 int
6707 mg_read(struct mg_connection *conn, void *buf, size_t len)
6708 {
6709 if (len > INT_MAX) {
6710 len = INT_MAX;
6711 }
6712
6713 if (conn == NULL) {
6714 return 0;
6715 }
6716
6717 if (conn->is_chunked) {
6718 size_t all_read = 0;
6719
6720 while (len > 0) {
6721 if (conn->is_chunked >= 3) {
6722 /* No more data left to read */
6723 return 0;
6724 }
6725 if (conn->is_chunked != 1) {
6726 /* Has error */
6727 return -1;
6728 }
6729
6730 if (conn->consumed_content != conn->content_len) {
6731 /* copy from the current chunk */
6732 int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
6733
6734 if (read_ret < 1) {
6735 /* read error */
6736 conn->is_chunked = 2;
6737 return -1;
6738 }
6739
6740 all_read += (size_t)read_ret;
6741 len -= (size_t)read_ret;
6742
6743 if (conn->consumed_content == conn->content_len) {
6744 /* Add data bytes in the current chunk have been read,
6745 * so we are expecting \r\n now. */
6746 char x[2];
6747 conn->content_len += 2;
6748 if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
6749 || (x[1] != '\n')) {
6750 /* Protocol violation */
6751 conn->is_chunked = 2;
6752 return -1;
6753 }
6754 }
6755
6756 } else {
6757 /* fetch a new chunk */
6758 size_t i;
6759 char lenbuf[64];
6760 char *end = NULL;
6761 unsigned long chunkSize = 0;
6762
6763 for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
6764 conn->content_len++;
6765 if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
6766 lenbuf[i] = 0;
6767 }
6768 if ((i > 0) && (lenbuf[i] == '\r')
6769 && (lenbuf[i - 1] != '\r')) {
6770 continue;
6771 }
6772 if ((i > 1) && (lenbuf[i] == '\n')
6773 && (lenbuf[i - 1] == '\r')) {
6774 lenbuf[i + 1] = 0;
6775 chunkSize = strtoul(lenbuf, &end, 16);
6776 if (chunkSize == 0) {
6777 /* regular end of content */
6778 conn->is_chunked = 3;
6779 }
6780 break;
6781 }
6782 if (!isxdigit((unsigned char)lenbuf[i])) {
6783 /* illegal character for chunk length */
6784 conn->is_chunked = 2;
6785 return -1;
6786 }
6787 }
6788 if ((end == NULL) || (*end != '\r')) {
6789 /* chunksize not set correctly */
6790 conn->is_chunked = 2;
6791 return -1;
6792 }
6793 if (chunkSize == 0) {
6794 /* try discarding trailer for keep-alive */
6795 conn->content_len += 2;
6796 if ((mg_read_inner(conn, lenbuf, 2) == 2)
6797 && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
6798 conn->is_chunked = 4;
6799 }
6800 break;
6801 }
6802
6803 /* append a new chunk */
6804 conn->content_len += chunkSize;
6805 }
6806 }
6807
6808 return (int)all_read;
6809 }
6810 return mg_read_inner(conn, buf, len);
6811 }
6812
6813
6814 int
6815 mg_write(struct mg_connection *conn, const void *buf, size_t len)
6816 {
6817 time_t now;
6818 int n, total, allowed;
6819
6820 if (conn == NULL) {
6821 return 0;
6822 }
6823 if (len > INT_MAX) {
6824 return -1;
6825 }
6826
6827 if (conn->throttle > 0) {
6828 if ((now = time(NULL)) != conn->last_throttle_time) {
6829 conn->last_throttle_time = now;
6830 conn->last_throttle_bytes = 0;
6831 }
6832 allowed = conn->throttle - conn->last_throttle_bytes;
6833 if (allowed > (int)len) {
6834 allowed = (int)len;
6835 }
6836 if ((total = push_all(conn->phys_ctx,
6837 NULL,
6838 conn->client.sock,
6839 conn->ssl,
6840 (const char *)buf,
6841 allowed))
6842 == allowed) {
6843 buf = (const char *)buf + total;
6844 conn->last_throttle_bytes += total;
6845 while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
6846 allowed = (conn->throttle > ((int)len - total))
6847 ? (int)len - total
6848 : conn->throttle;
6849 if ((n = push_all(conn->phys_ctx,
6850 NULL,
6851 conn->client.sock,
6852 conn->ssl,
6853 (const char *)buf,
6854 allowed))
6855 != allowed) {
6856 break;
6857 }
6858 sleep(1);
6859 conn->last_throttle_bytes = allowed;
6860 conn->last_throttle_time = time(NULL);
6861 buf = (const char *)buf + n;
6862 total += n;
6863 }
6864 }
6865 } else {
6866 total = push_all(conn->phys_ctx,
6867 NULL,
6868 conn->client.sock,
6869 conn->ssl,
6870 (const char *)buf,
6871 (int)len);
6872 }
6873 if (total > 0) {
6874 conn->num_bytes_sent += total;
6875 }
6876 return total;
6877 }
6878
6879
6880 /* Send a chunk, if "Transfer-Encoding: chunked" is used */
6881 int
6882 mg_send_chunk(struct mg_connection *conn,
6883 const char *chunk,
6884 unsigned int chunk_len)
6885 {
6886 char lenbuf[16];
6887 size_t lenbuf_len;
6888 int ret;
6889 int t;
6890
6891 /* First store the length information in a text buffer. */
6892 sprintf(lenbuf, "%x\r\n", chunk_len);
6893 lenbuf_len = strlen(lenbuf);
6894
6895 /* Then send length information, chunk and terminating \r\n. */
6896 ret = mg_write(conn, lenbuf, lenbuf_len);
6897 if (ret != (int)lenbuf_len) {
6898 return -1;
6899 }
6900 t = ret;
6901
6902 ret = mg_write(conn, chunk, chunk_len);
6903 if (ret != (int)chunk_len) {
6904 return -1;
6905 }
6906 t += ret;
6907
6908 ret = mg_write(conn, "\r\n", 2);
6909 if (ret != 2) {
6910 return -1;
6911 }
6912 t += ret;
6913
6914 return t;
6915 }
6916
6917
6918 #if defined(GCC_DIAGNOSTIC)
6919 /* This block forwards format strings to printf implementations,
6920 * so we need to disable the format-nonliteral warning. */
6921 #pragma GCC diagnostic push
6922 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
6923 #endif
6924
6925
6926 /* Alternative alloc_vprintf() for non-compliant C runtimes */
6927 static int
6928 alloc_vprintf2(char **buf, const char *fmt, va_list ap)
6929 {
6930 va_list ap_copy;
6931 size_t size = MG_BUF_LEN / 4;
6932 int len = -1;
6933
6934 *buf = NULL;
6935 while (len < 0) {
6936 if (*buf) {
6937 mg_free(*buf);
6938 }
6939
6940 size *= 4;
6941 *buf = (char *)mg_malloc(size);
6942 if (!*buf) {
6943 break;
6944 }
6945
6946 va_copy(ap_copy, ap);
6947 len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
6948 va_end(ap_copy);
6949 (*buf)[size - 1] = 0;
6950 }
6951
6952 return len;
6953 }
6954
6955
6956 /* Print message to buffer. If buffer is large enough to hold the message,
6957 * return buffer. If buffer is to small, allocate large enough buffer on
6958 * heap,
6959 * and return allocated buffer. */
6960 static int
6961 alloc_vprintf(char **out_buf,
6962 char *prealloc_buf,
6963 size_t prealloc_size,
6964 const char *fmt,
6965 va_list ap)
6966 {
6967 va_list ap_copy;
6968 int len;
6969
6970 /* Windows is not standard-compliant, and vsnprintf() returns -1 if
6971 * buffer is too small. Also, older versions of msvcrt.dll do not have
6972 * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
6973 * Therefore, we make two passes: on first pass, get required message
6974 * length.
6975 * On second pass, actually print the message. */
6976 va_copy(ap_copy, ap);
6977 len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
6978 va_end(ap_copy);
6979
6980 if (len < 0) {
6981 /* C runtime is not standard compliant, vsnprintf() returned -1.
6982 * Switch to alternative code path that uses incremental
6983 * allocations.
6984 */
6985 va_copy(ap_copy, ap);
6986 len = alloc_vprintf2(out_buf, fmt, ap_copy);
6987 va_end(ap_copy);
6988
6989 } else if ((size_t)(len) >= prealloc_size) {
6990 /* The pre-allocated buffer not large enough. */
6991 /* Allocate a new buffer. */
6992 *out_buf = (char *)mg_malloc((size_t)(len) + 1);
6993 if (!*out_buf) {
6994 /* Allocation failed. Return -1 as "out of memory" error. */
6995 return -1;
6996 }
6997 /* Buffer allocation successful. Store the string there. */
6998 va_copy(ap_copy, ap);
6999 IGNORE_UNUSED_RESULT(
7000 vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
7001 va_end(ap_copy);
7002
7003 } else {
7004 /* The pre-allocated buffer is large enough.
7005 * Use it to store the string and return the address. */
7006 va_copy(ap_copy, ap);
7007 IGNORE_UNUSED_RESULT(
7008 vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
7009 va_end(ap_copy);
7010 *out_buf = prealloc_buf;
7011 }
7012
7013 return len;
7014 }
7015
7016
7017 #if defined(GCC_DIAGNOSTIC)
7018 /* Enable format-nonliteral warning again. */
7019 #pragma GCC diagnostic pop
7020 #endif
7021
7022
7023 static int
7024 mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
7025 {
7026 char mem[MG_BUF_LEN];
7027 char *buf = NULL;
7028 int len;
7029
7030 if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
7031 len = mg_write(conn, buf, (size_t)len);
7032 }
7033 if (buf != mem) {
7034 mg_free(buf);
7035 }
7036
7037 return len;
7038 }
7039
7040
7041 int
7042 mg_printf(struct mg_connection *conn, const char *fmt, ...)
7043 {
7044 va_list ap;
7045 int result;
7046
7047 va_start(ap, fmt);
7048 result = mg_vprintf(conn, fmt, ap);
7049 va_end(ap);
7050
7051 return result;
7052 }
7053
7054
7055 int
7056 mg_url_decode(const char *src,
7057 int src_len,
7058 char *dst,
7059 int dst_len,
7060 int is_form_url_encoded)
7061 {
7062 int i, j, a, b;
7063 #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
7064
7065 for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
7066 if ((i < src_len - 2) && (src[i] == '%')
7067 && isxdigit((unsigned char)src[i + 1])
7068 && isxdigit((unsigned char)src[i + 2])) {
7069 a = tolower((unsigned char)src[i + 1]);
7070 b = tolower((unsigned char)src[i + 2]);
7071 dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
7072 i += 2;
7073 } else if (is_form_url_encoded && (src[i] == '+')) {
7074 dst[j] = ' ';
7075 } else {
7076 dst[j] = src[i];
7077 }
7078 }
7079
7080 dst[j] = '\0'; /* Null-terminate the destination */
7081
7082 return (i >= src_len) ? j : -1;
7083 }
7084
7085
7086 int
7087 mg_get_var(const char *data,
7088 size_t data_len,
7089 const char *name,
7090 char *dst,
7091 size_t dst_len)
7092 {
7093 return mg_get_var2(data, data_len, name, dst, dst_len, 0);
7094 }
7095
7096
7097 int
7098 mg_get_var2(const char *data,
7099 size_t data_len,
7100 const char *name,
7101 char *dst,
7102 size_t dst_len,
7103 size_t occurrence)
7104 {
7105 const char *p, *e, *s;
7106 size_t name_len;
7107 int len;
7108
7109 if ((dst == NULL) || (dst_len == 0)) {
7110 len = -2;
7111 } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
7112 len = -1;
7113 dst[0] = '\0';
7114 } else {
7115 name_len = strlen(name);
7116 e = data + data_len;
7117 len = -1;
7118 dst[0] = '\0';
7119
7120 /* data is "var1=val1&var2=val2...". Find variable first */
7121 for (p = data; p + name_len < e; p++) {
7122 if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
7123 && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
7124 /* Point p to variable value */
7125 p += name_len + 1;
7126
7127 /* Point s to the end of the value */
7128 s = (const char *)memchr(p, '&', (size_t)(e - p));
7129 if (s == NULL) {
7130 s = e;
7131 }
7132 DEBUG_ASSERT(s >= p);
7133 if (s < p) {
7134 return -3;
7135 }
7136
7137 /* Decode variable into destination buffer */
7138 len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
7139
7140 /* Redirect error code from -1 to -2 (destination buffer too
7141 * small). */
7142 if (len == -1) {
7143 len = -2;
7144 }
7145 break;
7146 }
7147 }
7148 }
7149
7150 return len;
7151 }
7152
7153
7154 /* HCP24: some changes to compare hole var_name */
7155 int
7156 mg_get_cookie(const char *cookie_header,
7157 const char *var_name,
7158 char *dst,
7159 size_t dst_size)
7160 {
7161 const char *s, *p, *end;
7162 int name_len, len = -1;
7163
7164 if ((dst == NULL) || (dst_size == 0)) {
7165 return -2;
7166 }
7167
7168 dst[0] = '\0';
7169 if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
7170 return -1;
7171 }
7172
7173 name_len = (int)strlen(var_name);
7174 end = s + strlen(s);
7175 for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
7176 if (s[name_len] == '=') {
7177 /* HCP24: now check is it a substring or a full cookie name */
7178 if ((s == cookie_header) || (s[-1] == ' ')) {
7179 s += name_len + 1;
7180 if ((p = strchr(s, ' ')) == NULL) {
7181 p = end;
7182 }
7183 if (p[-1] == ';') {
7184 p--;
7185 }
7186 if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
7187 s++;
7188 p--;
7189 }
7190 if ((size_t)(p - s) < dst_size) {
7191 len = (int)(p - s);
7192 mg_strlcpy(dst, s, (size_t)len + 1);
7193 } else {
7194 len = -3;
7195 }
7196 break;
7197 }
7198 }
7199 }
7200 return len;
7201 }
7202
7203
7204 #if defined(USE_WEBSOCKET) || defined(USE_LUA)
7205 static void
7206 base64_encode(const unsigned char *src, int src_len, char *dst)
7207 {
7208 static const char *b64 =
7209 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7210 int i, j, a, b, c;
7211
7212 for (i = j = 0; i < src_len; i += 3) {
7213 a = src[i];
7214 b = ((i + 1) >= src_len) ? 0 : src[i + 1];
7215 c = ((i + 2) >= src_len) ? 0 : src[i + 2];
7216
7217 dst[j++] = b64[a >> 2];
7218 dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
7219 if (i + 1 < src_len) {
7220 dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
7221 }
7222 if (i + 2 < src_len) {
7223 dst[j++] = b64[c & 63];
7224 }
7225 }
7226 while (j % 4 != 0) {
7227 dst[j++] = '=';
7228 }
7229 dst[j++] = '\0';
7230 }
7231 #endif
7232
7233
7234 #if defined(USE_LUA)
7235 static unsigned char
7236 b64reverse(char letter)
7237 {
7238 if ((letter >= 'A') && (letter <= 'Z')) {
7239 return letter - 'A';
7240 }
7241 if ((letter >= 'a') && (letter <= 'z')) {
7242 return letter - 'a' + 26;
7243 }
7244 if ((letter >= '0') && (letter <= '9')) {
7245 return letter - '0' + 52;
7246 }
7247 if (letter == '+') {
7248 return 62;
7249 }
7250 if (letter == '/') {
7251 return 63;
7252 }
7253 if (letter == '=') {
7254 return 255; /* normal end */
7255 }
7256 return 254; /* error */
7257 }
7258
7259
7260 static int
7261 base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
7262 {
7263 int i;
7264 unsigned char a, b, c, d;
7265
7266 *dst_len = 0;
7267
7268 for (i = 0; i < src_len; i += 4) {
7269 a = b64reverse(src[i]);
7270 if (a >= 254) {
7271 return i;
7272 }
7273
7274 b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
7275 if (b >= 254) {
7276 return i + 1;
7277 }
7278
7279 c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
7280 if (c == 254) {
7281 return i + 2;
7282 }
7283
7284 d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
7285 if (d == 254) {
7286 return i + 3;
7287 }
7288
7289 dst[(*dst_len)++] = (a << 2) + (b >> 4);
7290 if (c != 255) {
7291 dst[(*dst_len)++] = (b << 4) + (c >> 2);
7292 if (d != 255) {
7293 dst[(*dst_len)++] = (c << 6) + d;
7294 }
7295 }
7296 }
7297 return -1;
7298 }
7299 #endif
7300
7301
7302 static int
7303 is_put_or_delete_method(const struct mg_connection *conn)
7304 {
7305 if (conn) {
7306 const char *s = conn->request_info.request_method;
7307 return (s != NULL)
7308 && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
7309 || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
7310 }
7311 return 0;
7312 }
7313
7314
7315 #if !defined(NO_FILES)
7316 static int
7317 extention_matches_script(
7318 struct mg_connection *conn, /* in: request (must be valid) */
7319 const char *filename /* in: filename (must be valid) */
7320 )
7321 {
7322 #if !defined(NO_CGI)
7323 if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
7324 strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
7325 filename)
7326 > 0) {
7327 return 1;
7328 }
7329 #endif
7330 #if defined(USE_LUA)
7331 if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
7332 strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
7333 filename)
7334 > 0) {
7335 return 1;
7336 }
7337 #endif
7338 #if defined(USE_DUKTAPE)
7339 if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
7340 strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
7341 filename)
7342 > 0) {
7343 return 1;
7344 }
7345 #endif
7346 /* filename and conn could be unused, if all preocessor conditions
7347 * are false (no script language supported). */
7348 (void)filename;
7349 (void)conn;
7350
7351 return 0;
7352 }
7353
7354
7355 /* For given directory path, substitute it to valid index file.
7356 * Return 1 if index file has been found, 0 if not found.
7357 * If the file is found, it's stats is returned in stp. */
7358 static int
7359 substitute_index_file(struct mg_connection *conn,
7360 char *path,
7361 size_t path_len,
7362 struct mg_file_stat *filestat)
7363 {
7364 const char *list = conn->dom_ctx->config[INDEX_FILES];
7365 struct vec filename_vec;
7366 size_t n = strlen(path);
7367 int found = 0;
7368
7369 /* The 'path' given to us points to the directory. Remove all trailing
7370 * directory separator characters from the end of the path, and
7371 * then append single directory separator character. */
7372 while ((n > 0) && (path[n - 1] == '/')) {
7373 n--;
7374 }
7375 path[n] = '/';
7376
7377 /* Traverse index files list. For each entry, append it to the given
7378 * path and see if the file exists. If it exists, break the loop */
7379 while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
7380 /* Ignore too long entries that may overflow path buffer */
7381 if ((filename_vec.len + 1) > (path_len - (n + 1))) {
7382 continue;
7383 }
7384
7385 /* Prepare full path to the index file */
7386 mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
7387
7388 /* Does it exist? */
7389 if (mg_stat(conn, path, filestat)) {
7390 /* Yes it does, break the loop */
7391 found = 1;
7392 break;
7393 }
7394 }
7395
7396 /* If no index file exists, restore directory path */
7397 if (!found) {
7398 path[n] = '\0';
7399 }
7400
7401 return found;
7402 }
7403 #endif
7404
7405
7406 static void
7407 interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
7408 char *filename, /* out: filename */
7409 size_t filename_buf_len, /* in: size of filename buffer */
7410 struct mg_file_stat *filestat, /* out: file status structure */
7411 int *is_found, /* out: file found (directly) */
7412 int *is_script_resource, /* out: handled by a script? */
7413 int *is_websocket_request, /* out: websocket connetion? */
7414 int *is_put_or_delete_request /* out: put/delete a file? */
7415 )
7416 {
7417 char const *accept_encoding;
7418
7419 #if !defined(NO_FILES)
7420 const char *uri = conn->request_info.local_uri;
7421 const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
7422 const char *rewrite;
7423 struct vec a, b;
7424 ptrdiff_t match_len;
7425 char gz_path[PATH_MAX];
7426 int truncated;
7427 #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7428 char *tmp_str;
7429 size_t tmp_str_len, sep_pos;
7430 int allow_substitute_script_subresources;
7431 #endif
7432 #else
7433 (void)filename_buf_len; /* unused if NO_FILES is defined */
7434 #endif
7435
7436 /* Step 1: Set all initially unknown outputs to zero */
7437 memset(filestat, 0, sizeof(*filestat));
7438 *filename = 0;
7439 *is_found = 0;
7440 *is_script_resource = 0;
7441
7442 /* Step 2: Check if the request attempts to modify the file system */
7443 *is_put_or_delete_request = is_put_or_delete_method(conn);
7444
7445 /* Step 3: Check if it is a websocket request, and modify the document
7446 * root if required */
7447 #if defined(USE_WEBSOCKET)
7448 *is_websocket_request = is_websocket_protocol(conn);
7449 #if !defined(NO_FILES)
7450 if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
7451 root = conn->dom_ctx->config[WEBSOCKET_ROOT];
7452 }
7453 #endif /* !NO_FILES */
7454 #else /* USE_WEBSOCKET */
7455 *is_websocket_request = 0;
7456 #endif /* USE_WEBSOCKET */
7457
7458 /* Step 4: Check if gzip encoded response is allowed */
7459 conn->accept_gzip = 0;
7460 if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
7461 if (strstr(accept_encoding, "gzip") != NULL) {
7462 conn->accept_gzip = 1;
7463 }
7464 }
7465
7466 #if !defined(NO_FILES)
7467 /* Step 5: If there is no root directory, don't look for files. */
7468 /* Note that root == NULL is a regular use case here. This occurs,
7469 * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
7470 * config is not required. */
7471 if (root == NULL) {
7472 /* all file related outputs have already been set to 0, just return
7473 */
7474 return;
7475 }
7476
7477 /* Step 6: Determine the local file path from the root path and the
7478 * request uri. */
7479 /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
7480 * part of the path one byte on the right. */
7481 mg_snprintf(
7482 conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
7483
7484 if (truncated) {
7485 goto interpret_cleanup;
7486 }
7487
7488 /* Step 7: URI rewriting */
7489 rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
7490 while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
7491 if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
7492 mg_snprintf(conn,
7493 &truncated,
7494 filename,
7495 filename_buf_len - 1,
7496 "%.*s%s",
7497 (int)b.len,
7498 b.ptr,
7499 uri + match_len);
7500 break;
7501 }
7502 }
7503
7504 if (truncated) {
7505 goto interpret_cleanup;
7506 }
7507
7508 /* Step 8: Check if the file exists at the server */
7509 /* Local file path and name, corresponding to requested URI
7510 * is now stored in "filename" variable. */
7511 if (mg_stat(conn, filename, filestat)) {
7512 int uri_len = (int)strlen(uri);
7513 int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
7514
7515 /* 8.1: File exists. */
7516 *is_found = 1;
7517
7518 /* 8.2: Check if it is a script type. */
7519 if (extention_matches_script(conn, filename)) {
7520 /* The request addresses a CGI resource, Lua script or
7521 * server-side javascript.
7522 * The URI corresponds to the script itself (like
7523 * /path/script.cgi), and there is no additional resource
7524 * path (like /path/script.cgi/something).
7525 * Requests that modify (replace or delete) a resource, like
7526 * PUT and DELETE requests, should replace/delete the script
7527 * file.
7528 * Requests that read or write from/to a resource, like GET and
7529 * POST requests, should call the script and return the
7530 * generated response. */
7531 *is_script_resource = (!*is_put_or_delete_request);
7532 }
7533
7534 /* 8.3: If the request target is a directory, there could be
7535 * a substitute file (index.html, index.cgi, ...). */
7536 if (filestat->is_directory && is_uri_end_slash) {
7537 /* Use a local copy here, since substitute_index_file will
7538 * change the content of the file status */
7539 struct mg_file_stat tmp_filestat;
7540 memset(&tmp_filestat, 0, sizeof(tmp_filestat));
7541
7542 if (substitute_index_file(
7543 conn, filename, filename_buf_len, &tmp_filestat)) {
7544
7545 /* Substitute file found. Copy stat to the output, then
7546 * check if the file is a script file */
7547 *filestat = tmp_filestat;
7548
7549 if (extention_matches_script(conn, filename)) {
7550 /* Substitute file is a script file */
7551 *is_script_resource = 1;
7552 } else {
7553 /* Substitute file is a regular file */
7554 *is_script_resource = 0;
7555 *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
7556 }
7557 }
7558 /* If there is no substitute file, the server could return
7559 * a directory listing in a later step */
7560 }
7561 return;
7562 }
7563
7564 /* Step 9: Check for zipped files: */
7565 /* If we can't find the actual file, look for the file
7566 * with the same name but a .gz extension. If we find it,
7567 * use that and set the gzipped flag in the file struct
7568 * to indicate that the response need to have the content-
7569 * encoding: gzip header.
7570 * We can only do this if the browser declares support. */
7571 if (conn->accept_gzip) {
7572 mg_snprintf(
7573 conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
7574
7575 if (truncated) {
7576 goto interpret_cleanup;
7577 }
7578
7579 if (mg_stat(conn, gz_path, filestat)) {
7580 if (filestat) {
7581 filestat->is_gzipped = 1;
7582 *is_found = 1;
7583 }
7584 /* Currently gz files can not be scripts. */
7585 return;
7586 }
7587 }
7588
7589 #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7590 /* Step 10: Script resources may handle sub-resources */
7591 /* Support PATH_INFO for CGI scripts. */
7592 tmp_str_len = strlen(filename);
7593 tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
7594 if (!tmp_str) {
7595 /* Out of memory */
7596 goto interpret_cleanup;
7597 }
7598 memcpy(tmp_str, filename, tmp_str_len + 1);
7599
7600 /* Check config, if index scripts may have sub-resources */
7601 allow_substitute_script_subresources =
7602 !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
7603 "yes");
7604
7605 sep_pos = tmp_str_len;
7606 while (sep_pos > 0) {
7607 sep_pos--;
7608 if (tmp_str[sep_pos] == '/') {
7609 int is_script = 0, does_exist = 0;
7610
7611 tmp_str[sep_pos] = 0;
7612 if (tmp_str[0]) {
7613 is_script = extention_matches_script(conn, tmp_str);
7614 does_exist = mg_stat(conn, tmp_str, filestat);
7615 }
7616
7617 if (does_exist && is_script) {
7618 filename[sep_pos] = 0;
7619 memmove(filename + sep_pos + 2,
7620 filename + sep_pos + 1,
7621 strlen(filename + sep_pos + 1) + 1);
7622 conn->path_info = filename + sep_pos + 1;
7623 filename[sep_pos + 1] = '/';
7624 *is_script_resource = 1;
7625 *is_found = 1;
7626 break;
7627 }
7628
7629 if (allow_substitute_script_subresources) {
7630 if (substitute_index_file(
7631 conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
7632
7633 /* some intermediate directory has an index file */
7634 if (extention_matches_script(conn, tmp_str)) {
7635
7636 char *tmp_str2;
7637
7638 DEBUG_TRACE("Substitute script %s serving path %s",
7639 tmp_str,
7640 filename);
7641
7642 /* this index file is a script */
7643 tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
7644 conn->phys_ctx);
7645 mg_snprintf(conn,
7646 &truncated,
7647 filename,
7648 filename_buf_len,
7649 "%s//%s",
7650 tmp_str,
7651 tmp_str2);
7652 mg_free(tmp_str2);
7653
7654 if (truncated) {
7655 mg_free(tmp_str);
7656 goto interpret_cleanup;
7657 }
7658 sep_pos = strlen(tmp_str);
7659 filename[sep_pos] = 0;
7660 conn->path_info = filename + sep_pos + 1;
7661 *is_script_resource = 1;
7662 *is_found = 1;
7663 break;
7664
7665 } else {
7666
7667 DEBUG_TRACE("Substitute file %s serving path %s",
7668 tmp_str,
7669 filename);
7670
7671 /* non-script files will not have sub-resources */
7672 filename[sep_pos] = 0;
7673 conn->path_info = 0;
7674 *is_script_resource = 0;
7675 *is_found = 0;
7676 break;
7677 }
7678 }
7679 }
7680
7681 tmp_str[sep_pos] = '/';
7682 }
7683 }
7684
7685 mg_free(tmp_str);
7686
7687 #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
7688 #endif /* !defined(NO_FILES) */
7689 return;
7690
7691 #if !defined(NO_FILES)
7692 /* Reset all outputs */
7693 interpret_cleanup:
7694 memset(filestat, 0, sizeof(*filestat));
7695 *filename = 0;
7696 *is_found = 0;
7697 *is_script_resource = 0;
7698 *is_websocket_request = 0;
7699 *is_put_or_delete_request = 0;
7700 #endif /* !defined(NO_FILES) */
7701 }
7702
7703
7704 /* Check whether full request is buffered. Return:
7705 * -1 if request or response is malformed
7706 * 0 if request or response is not yet fully buffered
7707 * >0 actual request length, including last \r\n\r\n */
7708 static int
7709 get_http_header_len(const char *buf, int buflen)
7710 {
7711 int i;
7712 for (i = 0; i < buflen; i++) {
7713 /* Do an unsigned comparison in some conditions below */
7714 const unsigned char c = (unsigned char)buf[i];
7715
7716 if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
7717 && !isprint(c)) {
7718 /* abort scan as soon as one malformed character is found */
7719 return -1;
7720 }
7721
7722 if (i < buflen - 1) {
7723 if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
7724 /* Two newline, no carriage return - not standard compliant,
7725 * but
7726 * it
7727 * should be accepted */
7728 return i + 2;
7729 }
7730 }
7731
7732 if (i < buflen - 3) {
7733 if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
7734 && (buf[i + 3] == '\n')) {
7735 /* Two \r\n - standard compliant */
7736 return i + 4;
7737 }
7738 }
7739 }
7740
7741 return 0;
7742 }
7743
7744
7745 #if !defined(NO_CACHING)
7746 /* Convert month to the month number. Return -1 on error, or month number */
7747 static int
7748 get_month_index(const char *s)
7749 {
7750 size_t i;
7751
7752 for (i = 0; i < ARRAY_SIZE(month_names); i++) {
7753 if (!strcmp(s, month_names[i])) {
7754 return (int)i;
7755 }
7756 }
7757
7758 return -1;
7759 }
7760
7761
7762 /* Parse UTC date-time string, and return the corresponding time_t value. */
7763 static time_t
7764 parse_date_string(const char *datetime)
7765 {
7766 char month_str[32] = {0};
7767 int second, minute, hour, day, month, year;
7768 time_t result = (time_t)0;
7769 struct tm tm;
7770
7771 if ((sscanf(datetime,
7772 "%d/%3s/%d %d:%d:%d",
7773 &day,
7774 month_str,
7775 &year,
7776 &hour,
7777 &minute,
7778 &second)
7779 == 6)
7780 || (sscanf(datetime,
7781 "%d %3s %d %d:%d:%d",
7782 &day,
7783 month_str,
7784 &year,
7785 &hour,
7786 &minute,
7787 &second)
7788 == 6)
7789 || (sscanf(datetime,
7790 "%*3s, %d %3s %d %d:%d:%d",
7791 &day,
7792 month_str,
7793 &year,
7794 &hour,
7795 &minute,
7796 &second)
7797 == 6)
7798 || (sscanf(datetime,
7799 "%d-%3s-%d %d:%d:%d",
7800 &day,
7801 month_str,
7802 &year,
7803 &hour,
7804 &minute,
7805 &second)
7806 == 6)) {
7807 month = get_month_index(month_str);
7808 if ((month >= 0) && (year >= 1970)) {
7809 memset(&tm, 0, sizeof(tm));
7810 tm.tm_year = year - 1900;
7811 tm.tm_mon = month;
7812 tm.tm_mday = day;
7813 tm.tm_hour = hour;
7814 tm.tm_min = minute;
7815 tm.tm_sec = second;
7816 result = timegm(&tm);
7817 }
7818 }
7819
7820 return result;
7821 }
7822 #endif /* !NO_CACHING */
7823
7824
7825 /* Protect against directory disclosure attack by removing '..',
7826 * excessive '/' and '\' characters */
7827 static void
7828 remove_double_dots_and_double_slashes(char *s)
7829 {
7830 char *p = s;
7831
7832 while ((s[0] == '.') && (s[1] == '.')) {
7833 s++;
7834 }
7835
7836 while (*s != '\0') {
7837 *p++ = *s++;
7838 if ((s[-1] == '/') || (s[-1] == '\\')) {
7839 /* Skip all following slashes, backslashes and double-dots */
7840 while (s[0] != '\0') {
7841 if ((s[0] == '/') || (s[0] == '\\')) {
7842 s++;
7843 } else if ((s[0] == '.') && (s[1] == '.')) {
7844 s += 2;
7845 } else {
7846 break;
7847 }
7848 }
7849 }
7850 }
7851 *p = '\0';
7852 }
7853
7854
7855 static const struct {
7856 const char *extension;
7857 size_t ext_len;
7858 const char *mime_type;
7859 } builtin_mime_types[] = {
7860 /* IANA registered MIME types
7861 * (http://www.iana.org/assignments/media-types)
7862 * application types */
7863 {".doc", 4, "application/msword"},
7864 {".eps", 4, "application/postscript"},
7865 {".exe", 4, "application/octet-stream"},
7866 {".js", 3, "application/javascript"},
7867 {".json", 5, "application/json"},
7868 {".pdf", 4, "application/pdf"},
7869 {".ps", 3, "application/postscript"},
7870 {".rtf", 4, "application/rtf"},
7871 {".xhtml", 6, "application/xhtml+xml"},
7872 {".xsl", 4, "application/xml"},
7873 {".xslt", 5, "application/xml"},
7874
7875 /* fonts */
7876 {".ttf", 4, "application/font-sfnt"},
7877 {".cff", 4, "application/font-sfnt"},
7878 {".otf", 4, "application/font-sfnt"},
7879 {".aat", 4, "application/font-sfnt"},
7880 {".sil", 4, "application/font-sfnt"},
7881 {".pfr", 4, "application/font-tdpfr"},
7882 {".woff", 5, "application/font-woff"},
7883
7884 /* audio */
7885 {".mp3", 4, "audio/mpeg"},
7886 {".oga", 4, "audio/ogg"},
7887 {".ogg", 4, "audio/ogg"},
7888
7889 /* image */
7890 {".gif", 4, "image/gif"},
7891 {".ief", 4, "image/ief"},
7892 {".jpeg", 5, "image/jpeg"},
7893 {".jpg", 4, "image/jpeg"},
7894 {".jpm", 4, "image/jpm"},
7895 {".jpx", 4, "image/jpx"},
7896 {".png", 4, "image/png"},
7897 {".svg", 4, "image/svg+xml"},
7898 {".tif", 4, "image/tiff"},
7899 {".tiff", 5, "image/tiff"},
7900
7901 /* model */
7902 {".wrl", 4, "model/vrml"},
7903
7904 /* text */
7905 {".css", 4, "text/css"},
7906 {".csv", 4, "text/csv"},
7907 {".htm", 4, "text/html"},
7908 {".html", 5, "text/html"},
7909 {".sgm", 4, "text/sgml"},
7910 {".shtm", 5, "text/html"},
7911 {".shtml", 6, "text/html"},
7912 {".txt", 4, "text/plain"},
7913 {".xml", 4, "text/xml"},
7914
7915 /* video */
7916 {".mov", 4, "video/quicktime"},
7917 {".mp4", 4, "video/mp4"},
7918 {".mpeg", 5, "video/mpeg"},
7919 {".mpg", 4, "video/mpeg"},
7920 {".ogv", 4, "video/ogg"},
7921 {".qt", 3, "video/quicktime"},
7922
7923 /* not registered types
7924 * (http://reference.sitepoint.com/html/mime-types-full,
7925 * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
7926 {".arj", 4, "application/x-arj-compressed"},
7927 {".gz", 3, "application/x-gunzip"},
7928 {".rar", 4, "application/x-arj-compressed"},
7929 {".swf", 4, "application/x-shockwave-flash"},
7930 {".tar", 4, "application/x-tar"},
7931 {".tgz", 4, "application/x-tar-gz"},
7932 {".torrent", 8, "application/x-bittorrent"},
7933 {".ppt", 4, "application/x-mspowerpoint"},
7934 {".xls", 4, "application/x-msexcel"},
7935 {".zip", 4, "application/x-zip-compressed"},
7936 {".aac",
7937 4,
7938 "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
7939 {".aif", 4, "audio/x-aif"},
7940 {".m3u", 4, "audio/x-mpegurl"},
7941 {".mid", 4, "audio/x-midi"},
7942 {".ra", 3, "audio/x-pn-realaudio"},
7943 {".ram", 4, "audio/x-pn-realaudio"},
7944 {".wav", 4, "audio/x-wav"},
7945 {".bmp", 4, "image/bmp"},
7946 {".ico", 4, "image/x-icon"},
7947 {".pct", 4, "image/x-pct"},
7948 {".pict", 5, "image/pict"},
7949 {".rgb", 4, "image/x-rgb"},
7950 {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
7951 {".asf", 4, "video/x-ms-asf"},
7952 {".avi", 4, "video/x-msvideo"},
7953 {".m4v", 4, "video/x-m4v"},
7954 {NULL, 0, NULL}};
7955
7956
7957 const char *
7958 mg_get_builtin_mime_type(const char *path)
7959 {
7960 const char *ext;
7961 size_t i, path_len;
7962
7963 path_len = strlen(path);
7964
7965 for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
7966 ext = path + (path_len - builtin_mime_types[i].ext_len);
7967 if ((path_len > builtin_mime_types[i].ext_len)
7968 && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
7969 return builtin_mime_types[i].mime_type;
7970 }
7971 }
7972
7973 return "text/plain";
7974 }
7975
7976
7977 /* Look at the "path" extension and figure what mime type it has.
7978 * Store mime type in the vector. */
7979 static void
7980 get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
7981 {
7982 struct vec ext_vec, mime_vec;
7983 const char *list, *ext;
7984 size_t path_len;
7985
7986 path_len = strlen(path);
7987
7988 if ((conn == NULL) || (vec == NULL)) {
7989 if (vec != NULL) {
7990 memset(vec, '\0', sizeof(struct vec));
7991 }
7992 return;
7993 }
7994
7995 /* Scan user-defined mime types first, in case user wants to
7996 * override default mime types. */
7997 list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
7998 while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
7999 /* ext now points to the path suffix */
8000 ext = path + path_len - ext_vec.len;
8001 if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
8002 *vec = mime_vec;
8003 return;
8004 }
8005 }
8006
8007 vec->ptr = mg_get_builtin_mime_type(path);
8008 vec->len = strlen(vec->ptr);
8009 }
8010
8011
8012 /* Stringify binary data. Output buffer must be twice as big as input,
8013 * because each byte takes 2 bytes in string representation */
8014 static void
8015 bin2str(char *to, const unsigned char *p, size_t len)
8016 {
8017 static const char *hex = "0123456789abcdef";
8018
8019 for (; len--; p++) {
8020 *to++ = hex[p[0] >> 4];
8021 *to++ = hex[p[0] & 0x0f];
8022 }
8023 *to = '\0';
8024 }
8025
8026
8027 /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
8028 */
8029 char *
8030 mg_md5(char buf[33], ...)
8031 {
8032 md5_byte_t hash[16];
8033 const char *p;
8034 va_list ap;
8035 md5_state_t ctx;
8036
8037 md5_init(&ctx);
8038
8039 va_start(ap, buf);
8040 while ((p = va_arg(ap, const char *)) != NULL) {
8041 md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
8042 }
8043 va_end(ap);
8044
8045 md5_finish(&ctx, hash);
8046 bin2str(buf, hash, sizeof(hash));
8047 return buf;
8048 }
8049
8050
8051 /* Check the user's password, return 1 if OK */
8052 static int
8053 check_password(const char *method,
8054 const char *ha1,
8055 const char *uri,
8056 const char *nonce,
8057 const char *nc,
8058 const char *cnonce,
8059 const char *qop,
8060 const char *response)
8061 {
8062 char ha2[32 + 1], expected_response[32 + 1];
8063
8064 /* Some of the parameters may be NULL */
8065 if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
8066 || (qop == NULL) || (response == NULL)) {
8067 return 0;
8068 }
8069
8070 /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
8071 if (strlen(response) != 32) {
8072 return 0;
8073 }
8074
8075 mg_md5(ha2, method, ":", uri, NULL);
8076 mg_md5(expected_response,
8077 ha1,
8078 ":",
8079 nonce,
8080 ":",
8081 nc,
8082 ":",
8083 cnonce,
8084 ":",
8085 qop,
8086 ":",
8087 ha2,
8088 NULL);
8089
8090 return mg_strcasecmp(response, expected_response) == 0;
8091 }
8092
8093
8094 #if !defined(NO_FILESYSTEMS)
8095 /* Use the global passwords file, if specified by auth_gpass option,
8096 * or search for .htpasswd in the requested directory. */
8097 static void
8098 open_auth_file(struct mg_connection *conn,
8099 const char *path,
8100 struct mg_file *filep)
8101 {
8102 if ((conn != NULL) && (conn->dom_ctx != NULL)) {
8103 char name[PATH_MAX];
8104 const char *p, *e,
8105 *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
8106 int truncated;
8107
8108 if (gpass != NULL) {
8109 /* Use global passwords file */
8110 if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
8111 #if defined(DEBUG)
8112 /* Use mg_cry_internal here, since gpass has been configured. */
8113 mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
8114 #endif
8115 }
8116 /* Important: using local struct mg_file to test path for
8117 * is_directory flag. If filep is used, mg_stat() makes it
8118 * appear as if auth file was opened.
8119 * TODO(mid): Check if this is still required after rewriting
8120 * mg_stat */
8121 } else if (mg_stat(conn, path, &filep->stat)
8122 && filep->stat.is_directory) {
8123 mg_snprintf(conn,
8124 &truncated,
8125 name,
8126 sizeof(name),
8127 "%s/%s",
8128 path,
8129 PASSWORDS_FILE_NAME);
8130
8131 if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8132 #if defined(DEBUG)
8133 /* Don't use mg_cry_internal here, but only a trace, since this
8134 * is
8135 * a typical case. It will occur for every directory
8136 * without a password file. */
8137 DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8138 #endif
8139 }
8140 } else {
8141 /* Try to find .htpasswd in requested directory. */
8142 for (p = path, e = p + strlen(p) - 1; e > p; e--) {
8143 if (e[0] == '/') {
8144 break;
8145 }
8146 }
8147 mg_snprintf(conn,
8148 &truncated,
8149 name,
8150 sizeof(name),
8151 "%.*s/%s",
8152 (int)(e - p),
8153 p,
8154 PASSWORDS_FILE_NAME);
8155
8156 if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8157 #if defined(DEBUG)
8158 /* Don't use mg_cry_internal here, but only a trace, since this
8159 * is
8160 * a typical case. It will occur for every directory
8161 * without a password file. */
8162 DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8163 #endif
8164 }
8165 }
8166 }
8167 }
8168 #endif /* NO_FILESYSTEMS */
8169
8170
8171 /* Parsed Authorization header */
8172 struct ah {
8173 char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
8174 };
8175
8176
8177 /* Return 1 on success. Always initializes the ah structure. */
8178 static int
8179 parse_auth_header(struct mg_connection *conn,
8180 char *buf,
8181 size_t buf_size,
8182 struct ah *ah)
8183 {
8184 char *name, *value, *s;
8185 const char *auth_header;
8186 uint64_t nonce;
8187
8188 if (!ah || !conn) {
8189 return 0;
8190 }
8191
8192 (void)memset(ah, 0, sizeof(*ah));
8193 if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
8194 || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
8195 return 0;
8196 }
8197
8198 /* Make modifiable copy of the auth header */
8199 (void)mg_strlcpy(buf, auth_header + 7, buf_size);
8200 s = buf;
8201
8202 /* Parse authorization header */
8203 for (;;) {
8204 /* Gobble initial spaces */
8205 while (isspace((unsigned char)*s)) {
8206 s++;
8207 }
8208 name = skip_quoted(&s, "=", " ", 0);
8209 /* Value is either quote-delimited, or ends at first comma or space.
8210 */
8211 if (s[0] == '\"') {
8212 s++;
8213 value = skip_quoted(&s, "\"", " ", '\\');
8214 if (s[0] == ',') {
8215 s++;
8216 }
8217 } else {
8218 value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
8219 * spaces */
8220 }
8221 if (*name == '\0') {
8222 break;
8223 }
8224
8225 if (!strcmp(name, "username")) {
8226 ah->user = value;
8227 } else if (!strcmp(name, "cnonce")) {
8228 ah->cnonce = value;
8229 } else if (!strcmp(name, "response")) {
8230 ah->response = value;
8231 } else if (!strcmp(name, "uri")) {
8232 ah->uri = value;
8233 } else if (!strcmp(name, "qop")) {
8234 ah->qop = value;
8235 } else if (!strcmp(name, "nc")) {
8236 ah->nc = value;
8237 } else if (!strcmp(name, "nonce")) {
8238 ah->nonce = value;
8239 }
8240 }
8241
8242 #if !defined(NO_NONCE_CHECK)
8243 /* Read the nonce from the response. */
8244 if (ah->nonce == NULL) {
8245 return 0;
8246 }
8247 s = NULL;
8248 nonce = strtoull(ah->nonce, &s, 10);
8249 if ((s == NULL) || (*s != 0)) {
8250 return 0;
8251 }
8252
8253 /* Convert the nonce from the client to a number. */
8254 nonce ^= conn->dom_ctx->auth_nonce_mask;
8255
8256 /* The converted number corresponds to the time the nounce has been
8257 * created. This should not be earlier than the server start. */
8258 /* Server side nonce check is valuable in all situations but one:
8259 * if the server restarts frequently, but the client should not see
8260 * that, so the server should accept nonces from previous starts. */
8261 /* However, the reasonable default is to not accept a nonce from a
8262 * previous start, so if anyone changed the access rights between
8263 * two restarts, a new login is required. */
8264 if (nonce < (uint64_t)conn->phys_ctx->start_time) {
8265 /* nonce is from a previous start of the server and no longer valid
8266 * (replay attack?) */
8267 return 0;
8268 }
8269 /* Check if the nonce is too high, so it has not (yet) been used by the
8270 * server. */
8271 if (nonce >= ((uint64_t)conn->phys_ctx->start_time
8272 + conn->dom_ctx->nonce_count)) {
8273 return 0;
8274 }
8275 #else
8276 (void)nonce;
8277 #endif
8278
8279 /* CGI needs it as REMOTE_USER */
8280 if (ah->user != NULL) {
8281 conn->request_info.remote_user =
8282 mg_strdup_ctx(ah->user, conn->phys_ctx);
8283 } else {
8284 return 0;
8285 }
8286
8287 return 1;
8288 }
8289
8290
8291 static const char *
8292 mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
8293 {
8294 #if defined(MG_USE_OPEN_FILE)
8295 const char *eof;
8296 size_t len;
8297 const char *memend;
8298 #else
8299 (void)p; /* parameter is unused */
8300 #endif
8301
8302 if (!filep) {
8303 return NULL;
8304 }
8305
8306 #if defined(MG_USE_OPEN_FILE)
8307 if ((filep->access.membuf != NULL) && (*p != NULL)) {
8308 memend = (const char *)&filep->access.membuf[filep->stat.size];
8309 /* Search for \n from p till the end of stream */
8310 eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
8311 if (eof != NULL) {
8312 eof += 1; /* Include \n */
8313 } else {
8314 eof = memend; /* Copy remaining data */
8315 }
8316 len =
8317 ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
8318 memcpy(buf, *p, len);
8319 buf[len] = '\0';
8320 *p += len;
8321 return len ? eof : NULL;
8322 } else /* filep->access.fp block below */
8323 #endif
8324 if (filep->access.fp != NULL) {
8325 return fgets(buf, (int)size, filep->access.fp);
8326 } else {
8327 return NULL;
8328 }
8329 }
8330
8331 /* Define the initial recursion depth for procesesing htpasswd files that
8332 * include other htpasswd
8333 * (or even the same) files. It is not difficult to provide a file or files
8334 * s.t. they force civetweb
8335 * to infinitely recurse and then crash.
8336 */
8337 #define INITIAL_DEPTH 9
8338 #if INITIAL_DEPTH <= 0
8339 #error Bad INITIAL_DEPTH for recursion, set to at least 1
8340 #endif
8341
8342 #if !defined(NO_FILESYSTEMS)
8343 struct read_auth_file_struct {
8344 struct mg_connection *conn;
8345 struct ah ah;
8346 const char *domain;
8347 char buf[256 + 256 + 40];
8348 const char *f_user;
8349 const char *f_domain;
8350 const char *f_ha1;
8351 };
8352
8353
8354 static int
8355 read_auth_file(struct mg_file *filep,
8356 struct read_auth_file_struct *workdata,
8357 int depth)
8358 {
8359 char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
8360 int is_authorized = 0;
8361 struct mg_file fp;
8362 size_t l;
8363
8364 if (!filep || !workdata || (0 == depth)) {
8365 return 0;
8366 }
8367
8368 /* Loop over passwords file */
8369 #if defined(MG_USE_OPEN_FILE)
8370 p = (char *)filep->access.membuf;
8371 #endif
8372 while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
8373 l = strlen(workdata->buf);
8374 while (l > 0) {
8375 if (isspace((unsigned char)workdata->buf[l - 1])
8376 || iscntrl((unsigned char)workdata->buf[l - 1])) {
8377 l--;
8378 workdata->buf[l] = 0;
8379 } else
8380 break;
8381 }
8382 if (l < 1) {
8383 continue;
8384 }
8385
8386 workdata->f_user = workdata->buf;
8387
8388 if (workdata->f_user[0] == ':') {
8389 /* user names may not contain a ':' and may not be empty,
8390 * so lines starting with ':' may be used for a special purpose
8391 */
8392 if (workdata->f_user[1] == '#') {
8393 /* :# is a comment */
8394 continue;
8395 } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
8396 if (mg_fopen(workdata->conn,
8397 workdata->f_user + 9,
8398 MG_FOPEN_MODE_READ,
8399 &fp)) {
8400 is_authorized = read_auth_file(&fp, workdata, depth - 1);
8401 (void)mg_fclose(
8402 &fp.access); /* ignore error on read only file */
8403
8404 /* No need to continue processing files once we have a
8405 * match, since nothing will reset it back
8406 * to 0.
8407 */
8408 if (is_authorized) {
8409 return is_authorized;
8410 }
8411 } else {
8412 mg_cry_internal(workdata->conn,
8413 "%s: cannot open authorization file: %s",
8414 __func__,
8415 workdata->buf);
8416 }
8417 continue;
8418 }
8419 /* everything is invalid for the moment (might change in the
8420 * future) */
8421 mg_cry_internal(workdata->conn,
8422 "%s: syntax error in authorization file: %s",
8423 __func__,
8424 workdata->buf);
8425 continue;
8426 }
8427
8428 workdata->f_domain = strchr(workdata->f_user, ':');
8429 if (workdata->f_domain == NULL) {
8430 mg_cry_internal(workdata->conn,
8431 "%s: syntax error in authorization file: %s",
8432 __func__,
8433 workdata->buf);
8434 continue;
8435 }
8436 *(char *)(workdata->f_domain) = 0;
8437 (workdata->f_domain)++;
8438
8439 workdata->f_ha1 = strchr(workdata->f_domain, ':');
8440 if (workdata->f_ha1 == NULL) {
8441 mg_cry_internal(workdata->conn,
8442 "%s: syntax error in authorization file: %s",
8443 __func__,
8444 workdata->buf);
8445 continue;
8446 }
8447 *(char *)(workdata->f_ha1) = 0;
8448 (workdata->f_ha1)++;
8449
8450 if (!strcmp(workdata->ah.user, workdata->f_user)
8451 && !strcmp(workdata->domain, workdata->f_domain)) {
8452 return check_password(workdata->conn->request_info.request_method,
8453 workdata->f_ha1,
8454 workdata->ah.uri,
8455 workdata->ah.nonce,
8456 workdata->ah.nc,
8457 workdata->ah.cnonce,
8458 workdata->ah.qop,
8459 workdata->ah.response);
8460 }
8461 }
8462
8463 return is_authorized;
8464 }
8465
8466
8467 /* Authorize against the opened passwords file. Return 1 if authorized. */
8468 static int
8469 authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
8470 {
8471 struct read_auth_file_struct workdata;
8472 char buf[MG_BUF_LEN];
8473
8474 if (!conn || !conn->dom_ctx) {
8475 return 0;
8476 }
8477
8478 memset(&workdata, 0, sizeof(workdata));
8479 workdata.conn = conn;
8480
8481 if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
8482 return 0;
8483 }
8484
8485 if (realm) {
8486 workdata.domain = realm;
8487 } else {
8488 workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
8489 }
8490
8491 return read_auth_file(filep, &workdata, INITIAL_DEPTH);
8492 }
8493
8494
8495 /* Public function to check http digest authentication header */
8496 int
8497 mg_check_digest_access_authentication(struct mg_connection *conn,
8498 const char *realm,
8499 const char *filename)
8500 {
8501 struct mg_file file = STRUCT_FILE_INITIALIZER;
8502 int auth;
8503
8504 if (!conn || !filename) {
8505 return -1;
8506 }
8507 if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
8508 return -2;
8509 }
8510
8511 auth = authorize(conn, &file, realm);
8512
8513 mg_fclose(&file.access);
8514
8515 return auth;
8516 }
8517 #endif /* NO_FILESYSTEMS */
8518
8519
8520 /* Return 1 if request is authorised, 0 otherwise. */
8521 static int
8522 check_authorization(struct mg_connection *conn, const char *path)
8523 {
8524 #if !defined(NO_FILESYSTEMS)
8525 char fname[PATH_MAX];
8526 struct vec uri_vec, filename_vec;
8527 const char *list;
8528 struct mg_file file = STRUCT_FILE_INITIALIZER;
8529 int authorized = 1, truncated;
8530
8531 if (!conn || !conn->dom_ctx) {
8532 return 0;
8533 }
8534
8535 list = conn->dom_ctx->config[PROTECT_URI];
8536 while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
8537 if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
8538 mg_snprintf(conn,
8539 &truncated,
8540 fname,
8541 sizeof(fname),
8542 "%.*s",
8543 (int)filename_vec.len,
8544 filename_vec.ptr);
8545
8546 if (truncated
8547 || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
8548 mg_cry_internal(conn,
8549 "%s: cannot open %s: %s",
8550 __func__,
8551 fname,
8552 strerror(errno));
8553 }
8554 break;
8555 }
8556 }
8557
8558 if (!is_file_opened(&file.access)) {
8559 open_auth_file(conn, path, &file);
8560 }
8561
8562 if (is_file_opened(&file.access)) {
8563 authorized = authorize(conn, &file, NULL);
8564 (void)mg_fclose(&file.access); /* ignore error on read only file */
8565 }
8566
8567 return authorized;
8568 #else
8569 (void)conn;
8570 (void)path;
8571 return 1;
8572 #endif /* NO_FILESYSTEMS */
8573 }
8574
8575
8576 /* Internal function. Assumes conn is valid */
8577 static void
8578 send_authorization_request(struct mg_connection *conn, const char *realm)
8579 {
8580 char date[64];
8581 time_t curtime = time(NULL);
8582 uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
8583
8584 if (!realm) {
8585 realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
8586 }
8587
8588 (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
8589 nonce += conn->dom_ctx->nonce_count;
8590 ++conn->dom_ctx->nonce_count;
8591 (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
8592
8593 nonce ^= conn->dom_ctx->auth_nonce_mask;
8594 conn->status_code = 401;
8595 conn->must_close = 1;
8596
8597 gmt_time_string(date, sizeof(date), &curtime);
8598
8599 mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
8600 send_no_cache_header(conn);
8601 send_additional_header(conn);
8602 mg_printf(conn,
8603 "Date: %s\r\n"
8604 "Connection: %s\r\n"
8605 "Content-Length: 0\r\n"
8606 "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
8607 "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
8608 date,
8609 suggest_connection_header(conn),
8610 realm,
8611 nonce);
8612 }
8613
8614
8615 /* Interface function. Parameters are provided by the user, so do
8616 * at least some basic checks.
8617 */
8618 int
8619 mg_send_digest_access_authentication_request(struct mg_connection *conn,
8620 const char *realm)
8621 {
8622 if (conn && conn->dom_ctx) {
8623 send_authorization_request(conn, realm);
8624 return 0;
8625 }
8626 return -1;
8627 }
8628
8629
8630 #if !defined(NO_FILES)
8631 static int
8632 is_authorized_for_put(struct mg_connection *conn)
8633 {
8634 if (conn) {
8635 struct mg_file file = STRUCT_FILE_INITIALIZER;
8636 const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
8637 int ret = 0;
8638
8639 if (passfile != NULL
8640 && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
8641 ret = authorize(conn, &file, NULL);
8642 (void)mg_fclose(&file.access); /* ignore error on read only file */
8643 }
8644
8645 return ret;
8646 }
8647 return 0;
8648 }
8649 #endif
8650
8651
8652 int
8653 mg_modify_passwords_file(const char *fname,
8654 const char *domain,
8655 const char *user,
8656 const char *pass)
8657 {
8658 int found, i;
8659 char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
8660 FILE *fp, *fp2;
8661
8662 found = 0;
8663 fp = fp2 = NULL;
8664
8665 /* Regard empty password as no password - remove user record. */
8666 if ((pass != NULL) && (pass[0] == '\0')) {
8667 pass = NULL;
8668 }
8669
8670 /* Other arguments must not be empty */
8671 if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
8672 return 0;
8673 }
8674
8675 /* Using the given file format, user name and domain must not contain
8676 * ':'
8677 */
8678 if (strchr(user, ':') != NULL) {
8679 return 0;
8680 }
8681 if (strchr(domain, ':') != NULL) {
8682 return 0;
8683 }
8684
8685 /* Do not allow control characters like newline in user name and domain.
8686 * Do not allow excessively long names either. */
8687 for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
8688 if (iscntrl((unsigned char)user[i])) {
8689 return 0;
8690 }
8691 }
8692 if (user[i]) {
8693 return 0;
8694 }
8695 for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
8696 if (iscntrl((unsigned char)domain[i])) {
8697 return 0;
8698 }
8699 }
8700 if (domain[i]) {
8701 return 0;
8702 }
8703
8704 /* The maximum length of the path to the password file is limited */
8705 if ((strlen(fname) + 4) >= PATH_MAX) {
8706 return 0;
8707 }
8708
8709 /* Create a temporary file name. Length has been checked before. */
8710 strcpy(tmp, fname);
8711 strcat(tmp, ".tmp");
8712
8713 /* Create the file if does not exist */
8714 /* Use of fopen here is OK, since fname is only ASCII */
8715 if ((fp = fopen(fname, "a+")) != NULL) {
8716 (void)fclose(fp);
8717 }
8718
8719 /* Open the given file and temporary file */
8720 if ((fp = fopen(fname, "r")) == NULL) {
8721 return 0;
8722 } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
8723 fclose(fp);
8724 return 0;
8725 }
8726
8727 /* Copy the stuff to temporary file */
8728 while (fgets(line, sizeof(line), fp) != NULL) {
8729 if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
8730 continue;
8731 }
8732 u[255] = 0;
8733 d[255] = 0;
8734
8735 if (!strcmp(u, user) && !strcmp(d, domain)) {
8736 found++;
8737 if (pass != NULL) {
8738 mg_md5(ha1, user, ":", domain, ":", pass, NULL);
8739 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8740 }
8741 } else {
8742 fprintf(fp2, "%s", line);
8743 }
8744 }
8745
8746 /* If new user, just add it */
8747 if (!found && (pass != NULL)) {
8748 mg_md5(ha1, user, ":", domain, ":", pass, NULL);
8749 fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8750 }
8751
8752 /* Close files */
8753 fclose(fp);
8754 fclose(fp2);
8755
8756 /* Put the temp file in place of real file */
8757 IGNORE_UNUSED_RESULT(remove(fname));
8758 IGNORE_UNUSED_RESULT(rename(tmp, fname));
8759
8760 return 1;
8761 }
8762
8763
8764 static int
8765 is_valid_port(unsigned long port)
8766 {
8767 return (port <= 0xffff);
8768 }
8769
8770
8771 static int
8772 mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
8773 {
8774 struct addrinfo hints, *res, *ressave;
8775 int func_ret = 0;
8776 int gai_ret;
8777
8778 memset(&hints, 0, sizeof(struct addrinfo));
8779 hints.ai_family = af;
8780
8781 gai_ret = getaddrinfo(src, NULL, &hints, &res);
8782 if (gai_ret != 0) {
8783 /* gai_strerror could be used to convert gai_ret to a string */
8784 /* POSIX return values: see
8785 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
8786 */
8787 /* Windows return values: see
8788 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
8789 */
8790 return 0;
8791 }
8792
8793 ressave = res;
8794
8795 while (res) {
8796 if (dstlen >= (size_t)res->ai_addrlen) {
8797 memcpy(dst, res->ai_addr, res->ai_addrlen);
8798 func_ret = 1;
8799 }
8800 res = res->ai_next;
8801 }
8802
8803 freeaddrinfo(ressave);
8804 return func_ret;
8805 }
8806
8807
8808 static int
8809 connect_socket(struct mg_context *ctx /* may be NULL */,
8810 const char *host,
8811 int port,
8812 int use_ssl,
8813 char *ebuf,
8814 size_t ebuf_len,
8815 SOCKET *sock /* output: socket, must not be NULL */,
8816 union usa *sa /* output: socket address, must not be NULL */
8817 )
8818 {
8819 int ip_ver = 0;
8820 int conn_ret = -1;
8821 int sockerr = 0;
8822 *sock = INVALID_SOCKET;
8823 memset(sa, 0, sizeof(*sa));
8824
8825 if (ebuf_len > 0) {
8826 *ebuf = 0;
8827 }
8828
8829 if (host == NULL) {
8830 mg_snprintf(NULL,
8831 NULL, /* No truncation check for ebuf */
8832 ebuf,
8833 ebuf_len,
8834 "%s",
8835 "NULL host");
8836 return 0;
8837 }
8838
8839 if ((port <= 0) || !is_valid_port((unsigned)port)) {
8840 mg_snprintf(NULL,
8841 NULL, /* No truncation check for ebuf */
8842 ebuf,
8843 ebuf_len,
8844 "%s",
8845 "invalid port");
8846 return 0;
8847 }
8848
8849 #if !defined(NO_SSL)
8850 #if !defined(NO_SSL_DL)
8851 #if defined(OPENSSL_API_1_1)
8852 if (use_ssl && (TLS_client_method == NULL)) {
8853 mg_snprintf(NULL,
8854 NULL, /* No truncation check for ebuf */
8855 ebuf,
8856 ebuf_len,
8857 "%s",
8858 "SSL is not initialized");
8859 return 0;
8860 }
8861 #else
8862 if (use_ssl && (SSLv23_client_method == NULL)) {
8863 mg_snprintf(NULL,
8864 NULL, /* No truncation check for ebuf */
8865 ebuf,
8866 ebuf_len,
8867 "%s",
8868 "SSL is not initialized");
8869 return 0;
8870 }
8871
8872 #endif /* OPENSSL_API_1_1 */
8873 #else
8874 (void)use_ssl;
8875 #endif /* NO_SSL_DL */
8876 #else
8877 (void)use_ssl;
8878 #endif /* !defined(NO_SSL) */
8879
8880 if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
8881 sa->sin.sin_family = AF_INET;
8882 sa->sin.sin_port = htons((uint16_t)port);
8883 ip_ver = 4;
8884 #if defined(USE_IPV6)
8885 } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
8886 sa->sin6.sin6_family = AF_INET6;
8887 sa->sin6.sin6_port = htons((uint16_t)port);
8888 ip_ver = 6;
8889 } else if (host[0] == '[') {
8890 /* While getaddrinfo on Windows will work with [::1],
8891 * getaddrinfo on Linux only works with ::1 (without []). */
8892 size_t l = strlen(host + 1);
8893 char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
8894 if (h) {
8895 h[l - 1] = 0;
8896 if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
8897 sa->sin6.sin6_family = AF_INET6;
8898 sa->sin6.sin6_port = htons((uint16_t)port);
8899 ip_ver = 6;
8900 }
8901 mg_free(h);
8902 }
8903 #endif
8904 }
8905
8906 if (ip_ver == 0) {
8907 mg_snprintf(NULL,
8908 NULL, /* No truncation check for ebuf */
8909 ebuf,
8910 ebuf_len,
8911 "%s",
8912 "host not found");
8913 return 0;
8914 }
8915
8916 if (ip_ver == 4) {
8917 *sock = socket(PF_INET, SOCK_STREAM, 0);
8918 }
8919 #if defined(USE_IPV6)
8920 else if (ip_ver == 6) {
8921 *sock = socket(PF_INET6, SOCK_STREAM, 0);
8922 }
8923 #endif
8924
8925 if (*sock == INVALID_SOCKET) {
8926 mg_snprintf(NULL,
8927 NULL, /* No truncation check for ebuf */
8928 ebuf,
8929 ebuf_len,
8930 "socket(): %s",
8931 strerror(ERRNO));
8932 return 0;
8933 }
8934
8935 if (0 != set_non_blocking_mode(*sock)) {
8936 mg_snprintf(NULL,
8937 NULL, /* No truncation check for ebuf */
8938 ebuf,
8939 ebuf_len,
8940 "Cannot set socket to non-blocking: %s",
8941 strerror(ERRNO));
8942 closesocket(*sock);
8943 *sock = INVALID_SOCKET;
8944 return 0;
8945 }
8946
8947 set_close_on_exec(*sock, NULL, ctx);
8948
8949 if (ip_ver == 4) {
8950 /* connected with IPv4 */
8951 conn_ret = connect(*sock,
8952 (struct sockaddr *)((void *)&sa->sin),
8953 sizeof(sa->sin));
8954 }
8955 #if defined(USE_IPV6)
8956 else if (ip_ver == 6) {
8957 /* connected with IPv6 */
8958 conn_ret = connect(*sock,
8959 (struct sockaddr *)((void *)&sa->sin6),
8960 sizeof(sa->sin6));
8961 }
8962 #endif
8963
8964 if (conn_ret != 0) {
8965 sockerr = ERRNO;
8966 }
8967
8968 #if defined(_WIN32)
8969 if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
8970 #else
8971 if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
8972 #endif
8973 /* Data for getsockopt */
8974 void *psockerr = &sockerr;
8975 int ret;
8976
8977 #if defined(_WIN32)
8978 int len = (int)sizeof(sockerr);
8979 #else
8980 socklen_t len = (socklen_t)sizeof(sockerr);
8981 #endif
8982
8983 /* Data for poll */
8984 struct mg_pollfd pfd[1];
8985 int pollres;
8986 int ms_wait = 10000; /* 10 second timeout */
8987 int nonstop = 0;
8988
8989 /* For a non-blocking socket, the connect sequence is:
8990 * 1) call connect (will not block)
8991 * 2) wait until the socket is ready for writing (select or poll)
8992 * 3) check connection state with getsockopt
8993 */
8994 pfd[0].fd = *sock;
8995 pfd[0].events = POLLOUT;
8996 pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
8997
8998 if (pollres != 1) {
8999 /* Not connected */
9000 mg_snprintf(NULL,
9001 NULL, /* No truncation check for ebuf */
9002 ebuf,
9003 ebuf_len,
9004 "connect(%s:%d): timeout",
9005 host,
9006 port);
9007 closesocket(*sock);
9008 *sock = INVALID_SOCKET;
9009 return 0;
9010 }
9011
9012 #if defined(_WIN32)
9013 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
9014 #else
9015 ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
9016 #endif
9017
9018 if ((ret == 0) && (sockerr == 0)) {
9019 conn_ret = 0;
9020 }
9021 }
9022
9023 if (conn_ret != 0) {
9024 /* Not connected */
9025 mg_snprintf(NULL,
9026 NULL, /* No truncation check for ebuf */
9027 ebuf,
9028 ebuf_len,
9029 "connect(%s:%d): error %s",
9030 host,
9031 port,
9032 strerror(sockerr));
9033 closesocket(*sock);
9034 *sock = INVALID_SOCKET;
9035 return 0;
9036 }
9037
9038 return 1;
9039 }
9040
9041
9042 int
9043 mg_url_encode(const char *src, char *dst, size_t dst_len)
9044 {
9045 static const char *dont_escape = "._-$,;~()";
9046 static const char *hex = "0123456789abcdef";
9047 char *pos = dst;
9048 const char *end = dst + dst_len - 1;
9049
9050 for (; ((*src != '\0') && (pos < end)); src++, pos++) {
9051 if (isalnum((unsigned char)*src)
9052 || (strchr(dont_escape, *src) != NULL)) {
9053 *pos = *src;
9054 } else if (pos + 2 < end) {
9055 pos[0] = '%';
9056 pos[1] = hex[(unsigned char)*src >> 4];
9057 pos[2] = hex[(unsigned char)*src & 0xf];
9058 pos += 2;
9059 } else {
9060 break;
9061 }
9062 }
9063
9064 *pos = '\0';
9065 return (*src == '\0') ? (int)(pos - dst) : -1;
9066 }
9067
9068 /* Return 0 on success, non-zero if an error occurs. */
9069
9070 static int
9071 print_dir_entry(struct de *de)
9072 {
9073 size_t namesize, escsize, i;
9074 char *href, *esc, *p;
9075 char size[64], mod[64];
9076 #if defined(REENTRANT_TIME)
9077 struct tm _tm;
9078 struct tm *tm = &_tm;
9079 #else
9080 struct tm *tm;
9081 #endif
9082
9083 /* Estimate worst case size for encoding and escaping */
9084 namesize = strlen(de->file_name) + 1;
9085 escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
9086 href = (char *)mg_malloc(namesize * 3 + escsize);
9087 if (href == NULL) {
9088 return -1;
9089 }
9090 mg_url_encode(de->file_name, href, namesize * 3);
9091 esc = NULL;
9092 if (escsize > 0) {
9093 /* HTML escaping needed */
9094 esc = href + namesize * 3;
9095 for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
9096 mg_strlcpy(p, de->file_name + i, 2);
9097 if (*p == '&') {
9098 strcpy(p, "&");
9099 } else if (*p == '<') {
9100 strcpy(p, "<");
9101 } else if (*p == '>') {
9102 strcpy(p, ">");
9103 }
9104 }
9105 }
9106
9107 if (de->file.is_directory) {
9108 mg_snprintf(de->conn,
9109 NULL, /* Buffer is big enough */
9110 size,
9111 sizeof(size),
9112 "%s",
9113 "[DIRECTORY]");
9114 } else {
9115 /* We use (signed) cast below because MSVC 6 compiler cannot
9116 * convert unsigned __int64 to double. Sigh. */
9117 if (de->file.size < 1024) {
9118 mg_snprintf(de->conn,
9119 NULL, /* Buffer is big enough */
9120 size,
9121 sizeof(size),
9122 "%d",
9123 (int)de->file.size);
9124 } else if (de->file.size < 0x100000) {
9125 mg_snprintf(de->conn,
9126 NULL, /* Buffer is big enough */
9127 size,
9128 sizeof(size),
9129 "%.1fk",
9130 (double)de->file.size / 1024.0);
9131 } else if (de->file.size < 0x40000000) {
9132 mg_snprintf(de->conn,
9133 NULL, /* Buffer is big enough */
9134 size,
9135 sizeof(size),
9136 "%.1fM",
9137 (double)de->file.size / 1048576);
9138 } else {
9139 mg_snprintf(de->conn,
9140 NULL, /* Buffer is big enough */
9141 size,
9142 sizeof(size),
9143 "%.1fG",
9144 (double)de->file.size / 1073741824);
9145 }
9146 }
9147
9148 /* Note: mg_snprintf will not cause a buffer overflow above.
9149 * So, string truncation checks are not required here. */
9150
9151 #if defined(REENTRANT_TIME)
9152 localtime_r(&de->file.last_modified, tm);
9153 #else
9154 tm = localtime(&de->file.last_modified);
9155 #endif
9156 if (tm != NULL) {
9157 strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
9158 } else {
9159 mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
9160 mod[sizeof(mod) - 1] = '\0';
9161 }
9162 mg_printf(de->conn,
9163 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
9164 "<td> %s</td><td> %s</td></tr>\n",
9165 href,
9166 de->file.is_directory ? "/" : "",
9167 esc ? esc : de->file_name,
9168 de->file.is_directory ? "/" : "",
9169 mod,
9170 size);
9171 mg_free(href);
9172 return 0;
9173 }
9174
9175
9176 /* This function is called from send_directory() and used for
9177 * sorting directory entries by size, or name, or modification time.
9178 * On windows, __cdecl specification is needed in case if project is built
9179 * with __stdcall convention. qsort always requires __cdels callback. */
9180 static int WINCDECL
9181 compare_dir_entries(const void *p1, const void *p2)
9182 {
9183 if (p1 && p2) {
9184 const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
9185 const char *query_string = a->conn->request_info.query_string;
9186 int cmp_result = 0;
9187
9188 if ((query_string == NULL) || (query_string[0] == '\0')) {
9189 query_string = "n";
9190 }
9191
9192 if (a->file.is_directory && !b->file.is_directory) {
9193 return -1; /* Always put directories on top */
9194 } else if (!a->file.is_directory && b->file.is_directory) {
9195 return 1; /* Always put directories on top */
9196 } else if (*query_string == 'n') {
9197 cmp_result = strcmp(a->file_name, b->file_name);
9198 } else if (*query_string == 's') {
9199 cmp_result = (a->file.size == b->file.size)
9200 ? 0
9201 : ((a->file.size > b->file.size) ? 1 : -1);
9202 } else if (*query_string == 'd') {
9203 cmp_result =
9204 (a->file.last_modified == b->file.last_modified)
9205 ? 0
9206 : ((a->file.last_modified > b->file.last_modified) ? 1
9207 : -1);
9208 }
9209
9210 return (query_string[1] == 'd') ? -cmp_result : cmp_result;
9211 }
9212 return 0;
9213 }
9214
9215
9216 static int
9217 must_hide_file(struct mg_connection *conn, const char *path)
9218 {
9219 if (conn && conn->dom_ctx) {
9220 const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
9221 const char *pattern = conn->dom_ctx->config[HIDE_FILES];
9222 return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
9223 || ((pattern != NULL)
9224 && (match_prefix(pattern, strlen(pattern), path) > 0));
9225 }
9226 return 0;
9227 }
9228
9229
9230 #if !defined(NO_FILESYSTEMS)
9231 static int
9232 scan_directory(struct mg_connection *conn,
9233 const char *dir,
9234 void *data,
9235 int (*cb)(struct de *, void *))
9236 {
9237 char path[PATH_MAX];
9238 struct dirent *dp;
9239 DIR *dirp;
9240 struct de de;
9241 int truncated;
9242
9243 if ((dirp = mg_opendir(conn, dir)) == NULL) {
9244 return 0;
9245 } else {
9246 de.conn = conn;
9247
9248 while ((dp = mg_readdir(dirp)) != NULL) {
9249 /* Do not show current dir and hidden files */
9250 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
9251 || must_hide_file(conn, dp->d_name)) {
9252 continue;
9253 }
9254
9255 mg_snprintf(
9256 conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9257
9258 /* If we don't memset stat structure to zero, mtime will have
9259 * garbage and strftime() will segfault later on in
9260 * print_dir_entry(). memset is required only if mg_stat()
9261 * fails. For more details, see
9262 * http://code.google.com/p/mongoose/issues/detail?id=79 */
9263 memset(&de.file, 0, sizeof(de.file));
9264
9265 if (truncated) {
9266 /* If the path is not complete, skip processing. */
9267 continue;
9268 }
9269
9270 if (!mg_stat(conn, path, &de.file)) {
9271 mg_cry_internal(conn,
9272 "%s: mg_stat(%s) failed: %s",
9273 __func__,
9274 path,
9275 strerror(ERRNO));
9276 }
9277 de.file_name = dp->d_name;
9278 cb(&de, data);
9279 }
9280 (void)mg_closedir(dirp);
9281 }
9282 return 1;
9283 }
9284 #endif /* NO_FILESYSTEMS */
9285
9286
9287 #if !defined(NO_FILES)
9288 static int
9289 remove_directory(struct mg_connection *conn, const char *dir)
9290 {
9291 char path[PATH_MAX];
9292 struct dirent *dp;
9293 DIR *dirp;
9294 struct de de;
9295 int truncated;
9296 int ok = 1;
9297
9298 if ((dirp = mg_opendir(conn, dir)) == NULL) {
9299 return 0;
9300 } else {
9301 de.conn = conn;
9302
9303 while ((dp = mg_readdir(dirp)) != NULL) {
9304 /* Do not show current dir (but show hidden files as they will
9305 * also be removed) */
9306 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
9307 continue;
9308 }
9309
9310 mg_snprintf(
9311 conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9312
9313 /* If we don't memset stat structure to zero, mtime will have
9314 * garbage and strftime() will segfault later on in
9315 * print_dir_entry(). memset is required only if mg_stat()
9316 * fails. For more details, see
9317 * http://code.google.com/p/mongoose/issues/detail?id=79 */
9318 memset(&de.file, 0, sizeof(de.file));
9319
9320 if (truncated) {
9321 /* Do not delete anything shorter */
9322 ok = 0;
9323 continue;
9324 }
9325
9326 if (!mg_stat(conn, path, &de.file)) {
9327 mg_cry_internal(conn,
9328 "%s: mg_stat(%s) failed: %s",
9329 __func__,
9330 path,
9331 strerror(ERRNO));
9332 ok = 0;
9333 }
9334
9335 if (de.file.is_directory) {
9336 if (remove_directory(conn, path) == 0) {
9337 ok = 0;
9338 }
9339 } else {
9340 /* This will fail file is the file is in memory */
9341 if (mg_remove(conn, path) == 0) {
9342 ok = 0;
9343 }
9344 }
9345 }
9346 (void)mg_closedir(dirp);
9347
9348 IGNORE_UNUSED_RESULT(rmdir(dir));
9349 }
9350
9351 return ok;
9352 }
9353 #endif
9354
9355
9356 struct dir_scan_data {
9357 struct de *entries;
9358 unsigned int num_entries;
9359 unsigned int arr_size;
9360 };
9361
9362
9363 /* Behaves like realloc(), but frees original pointer on failure */
9364 static void *
9365 realloc2(void *ptr, size_t size)
9366 {
9367 void *new_ptr = mg_realloc(ptr, size);
9368 if (new_ptr == NULL) {
9369 mg_free(ptr);
9370 }
9371 return new_ptr;
9372 }
9373
9374
9375 #if !defined(NO_FILESYSTEMS)
9376 static int
9377 dir_scan_callback(struct de *de, void *data)
9378 {
9379 struct dir_scan_data *dsd = (struct dir_scan_data *)data;
9380
9381 if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
9382 dsd->arr_size *= 2;
9383 dsd->entries =
9384 (struct de *)realloc2(dsd->entries,
9385 dsd->arr_size * sizeof(dsd->entries[0]));
9386 }
9387 if (dsd->entries == NULL) {
9388 /* TODO(lsm, low): propagate an error to the caller */
9389 dsd->num_entries = 0;
9390 } else {
9391 dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
9392 dsd->entries[dsd->num_entries].file = de->file;
9393 dsd->entries[dsd->num_entries].conn = de->conn;
9394 dsd->num_entries++;
9395 }
9396
9397 return 0;
9398 }
9399
9400
9401 static void
9402 handle_directory_request(struct mg_connection *conn, const char *dir)
9403 {
9404 unsigned int i;
9405 int sort_direction;
9406 struct dir_scan_data data = {NULL, 0, 128};
9407 char date[64], *esc, *p;
9408 const char *title;
9409 time_t curtime = time(NULL);
9410
9411 if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
9412 mg_send_http_error(conn,
9413 500,
9414 "Error: Cannot open directory\nopendir(%s): %s",
9415 dir,
9416 strerror(ERRNO));
9417 return;
9418 }
9419
9420 gmt_time_string(date, sizeof(date), &curtime);
9421
9422 if (!conn) {
9423 return;
9424 }
9425
9426 esc = NULL;
9427 title = conn->request_info.local_uri;
9428 if (title[strcspn(title, "&<>")]) {
9429 /* HTML escaping needed */
9430 esc = (char *)mg_malloc(strlen(title) * 5 + 1);
9431 if (esc) {
9432 for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
9433 mg_strlcpy(p, title + i, 2);
9434 if (*p == '&') {
9435 strcpy(p, "&");
9436 } else if (*p == '<') {
9437 strcpy(p, "<");
9438 } else if (*p == '>') {
9439 strcpy(p, ">");
9440 }
9441 }
9442 } else {
9443 title = "";
9444 }
9445 }
9446
9447 sort_direction = ((conn->request_info.query_string != NULL)
9448 && (conn->request_info.query_string[0] != '\0')
9449 && (conn->request_info.query_string[1] == 'd'))
9450 ? 'a'
9451 : 'd';
9452
9453 conn->must_close = 1;
9454 mg_printf(conn, "HTTP/1.1 200 OK\r\n");
9455 send_static_cache_header(conn);
9456 send_additional_header(conn);
9457 mg_printf(conn,
9458 "Date: %s\r\n"
9459 "Connection: close\r\n"
9460 "Content-Type: text/html; charset=utf-8\r\n\r\n",
9461 date);
9462 mg_printf(conn,
9463 "<html><head><title>Index of %s</title>"
9464 "<style>th {text-align: left;}</style></head>"
9465 "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
9466 "<tr><th><a href=\"?n%c\">Name</a></th>"
9467 "<th><a href=\"?d%c\">Modified</a></th>"
9468 "<th><a href=\"?s%c\">Size</a></th></tr>"
9469 "<tr><td colspan=\"3\"><hr></td></tr>",
9470 esc ? esc : title,
9471 esc ? esc : title,
9472 sort_direction,
9473 sort_direction,
9474 sort_direction);
9475 mg_free(esc);
9476
9477 /* Print first entry - link to a parent directory */
9478 mg_printf(conn,
9479 "<tr><td><a href=\"%s\">%s</a></td>"
9480 "<td> %s</td><td> %s</td></tr>\n",
9481 "..",
9482 "Parent directory",
9483 "-",
9484 "-");
9485
9486 /* Sort and print directory entries */
9487 if (data.entries != NULL) {
9488 qsort(data.entries,
9489 (size_t)data.num_entries,
9490 sizeof(data.entries[0]),
9491 compare_dir_entries);
9492 for (i = 0; i < data.num_entries; i++) {
9493 print_dir_entry(&data.entries[i]);
9494 mg_free(data.entries[i].file_name);
9495 }
9496 mg_free(data.entries);
9497 }
9498
9499 mg_printf(conn, "%s", "</table></pre></body></html>");
9500 conn->status_code = 200;
9501 }
9502 #endif /* NO_FILESYSTEMS */
9503
9504
9505 /* Send len bytes from the opened file to the client. */
9506 static void
9507 send_file_data(struct mg_connection *conn,
9508 struct mg_file *filep,
9509 int64_t offset,
9510 int64_t len)
9511 {
9512 char buf[MG_BUF_LEN];
9513 int to_read, num_read, num_written;
9514 int64_t size;
9515
9516 if (!filep || !conn) {
9517 return;
9518 }
9519
9520 /* Sanity check the offset */
9521 size = (filep->stat.size > INT64_MAX) ? INT64_MAX
9522 : (int64_t)(filep->stat.size);
9523 offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
9524
9525 #if defined(MG_USE_OPEN_FILE)
9526 if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
9527 /* file stored in memory */
9528 if (len > size - offset) {
9529 len = size - offset;
9530 }
9531 mg_write(conn, filep->access.membuf + offset, (size_t)len);
9532 } else /* else block below */
9533 #endif
9534 if (len > 0 && filep->access.fp != NULL) {
9535 /* file stored on disk */
9536 #if defined(__linux__)
9537 /* sendfile is only available for Linux */
9538 if ((conn->ssl == 0) && (conn->throttle == 0)
9539 && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
9540 "yes"))) {
9541 off_t sf_offs = (off_t)offset;
9542 ssize_t sf_sent;
9543 int sf_file = fileno(filep->access.fp);
9544 int loop_cnt = 0;
9545
9546 do {
9547 /* 2147479552 (0x7FFFF000) is a limit found by experiment on
9548 * 64 bit Linux (2^31 minus one memory page of 4k?). */
9549 size_t sf_tosend =
9550 (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
9551 sf_sent =
9552 sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
9553 if (sf_sent > 0) {
9554 len -= sf_sent;
9555 offset += sf_sent;
9556 } else if (loop_cnt == 0) {
9557 /* This file can not be sent using sendfile.
9558 * This might be the case for pseudo-files in the
9559 * /sys/ and /proc/ file system.
9560 * Use the regular user mode copy code instead. */
9561 break;
9562 } else if (sf_sent == 0) {
9563 /* No error, but 0 bytes sent. May be EOF? */
9564 return;
9565 }
9566 loop_cnt++;
9567
9568 } while ((len > 0) && (sf_sent >= 0));
9569
9570 if (sf_sent > 0) {
9571 return; /* OK */
9572 }
9573
9574 /* sf_sent<0 means error, thus fall back to the classic way */
9575 /* This is always the case, if sf_file is not a "normal" file,
9576 * e.g., for sending data from the output of a CGI process. */
9577 offset = (int64_t)sf_offs;
9578 }
9579 #endif
9580 if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
9581 mg_cry_internal(conn,
9582 "%s: fseeko() failed: %s",
9583 __func__,
9584 strerror(ERRNO));
9585 mg_send_http_error(
9586 conn,
9587 500,
9588 "%s",
9589 "Error: Unable to access file at requested position.");
9590 } else {
9591 while (len > 0) {
9592 /* Calculate how much to read from the file in the buffer */
9593 to_read = sizeof(buf);
9594 if ((int64_t)to_read > len) {
9595 to_read = (int)len;
9596 }
9597
9598 /* Read from file, exit the loop on error */
9599 if ((num_read =
9600 (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
9601 <= 0) {
9602 break;
9603 }
9604
9605 /* Send read bytes to the client, exit the loop on error */
9606 if ((num_written = mg_write(conn, buf, (size_t)num_read))
9607 != num_read) {
9608 break;
9609 }
9610
9611 /* Both read and were successful, adjust counters */
9612 len -= num_written;
9613 }
9614 }
9615 }
9616 }
9617
9618
9619 static int
9620 parse_range_header(const char *header, int64_t *a, int64_t *b)
9621 {
9622 return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
9623 }
9624
9625
9626 static void
9627 construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
9628 {
9629 if ((filestat != NULL) && (buf != NULL)) {
9630 mg_snprintf(NULL,
9631 NULL, /* All calls to construct_etag use 64 byte buffer */
9632 buf,
9633 buf_len,
9634 "\"%lx.%" INT64_FMT "\"",
9635 (unsigned long)filestat->last_modified,
9636 filestat->size);
9637 }
9638 }
9639
9640
9641 static void
9642 fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
9643 {
9644 if (filep != NULL && filep->fp != NULL) {
9645 #if defined(_WIN32)
9646 (void)conn; /* Unused. */
9647 #else
9648 if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
9649 mg_cry_internal(conn,
9650 "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
9651 __func__,
9652 strerror(ERRNO));
9653 }
9654 #endif
9655 }
9656 }
9657
9658
9659 #if defined(USE_ZLIB)
9660 #include "mod_zlib.inl"
9661 #endif
9662
9663
9664 #if !defined(NO_FILESYSTEMS)
9665 static void
9666 handle_static_file_request(struct mg_connection *conn,
9667 const char *path,
9668 struct mg_file *filep,
9669 const char *mime_type,
9670 const char *additional_headers)
9671 {
9672 char date[64], lm[64], etag[64];
9673 char range[128]; /* large enough, so there will be no overflow */
9674 const char *msg = "OK";
9675 const char *range_hdr;
9676 time_t curtime = time(NULL);
9677 int64_t cl, r1, r2;
9678 struct vec mime_vec;
9679 int n, truncated;
9680 char gz_path[PATH_MAX];
9681 const char *encoding = "";
9682 const char *origin_hdr;
9683 const char *cors_orig_cfg;
9684 const char *cors1, *cors2, *cors3;
9685 int is_head_request;
9686
9687 #if defined(USE_ZLIB)
9688 /* Compression is allowed, unless there is a reason not to use compression.
9689 * If the file is already compressed, too small or a "range" request was
9690 * made, on the fly compression is not possible. */
9691 int allow_on_the_fly_compression = 1;
9692 #endif
9693
9694 if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
9695 return;
9696 }
9697
9698 is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
9699
9700 if (mime_type == NULL) {
9701 get_mime_type(conn, path, &mime_vec);
9702 } else {
9703 mime_vec.ptr = mime_type;
9704 mime_vec.len = strlen(mime_type);
9705 }
9706 if (filep->stat.size > INT64_MAX) {
9707 mg_send_http_error(conn,
9708 500,
9709 "Error: File size is too large to send\n%" INT64_FMT,
9710 filep->stat.size);
9711 return;
9712 }
9713 cl = (int64_t)filep->stat.size;
9714 conn->status_code = 200;
9715 range[0] = '\0';
9716
9717 #if defined(USE_ZLIB)
9718 /* if this file is in fact a pre-gzipped file, rewrite its filename
9719 * it's important to rewrite the filename after resolving
9720 * the mime type from it, to preserve the actual file's type */
9721 if (!conn->accept_gzip) {
9722 allow_on_the_fly_compression = 0;
9723 }
9724 #endif
9725
9726 /* Check if there is a range header */
9727 range_hdr = mg_get_header(conn, "Range");
9728
9729 /* For gzipped files, add *.gz */
9730 if (filep->stat.is_gzipped) {
9731 mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
9732
9733 if (truncated) {
9734 mg_send_http_error(conn,
9735 500,
9736 "Error: Path of zipped file too long (%s)",
9737 path);
9738 return;
9739 }
9740
9741 path = gz_path;
9742 encoding = "Content-Encoding: gzip\r\n";
9743
9744 #if defined(USE_ZLIB)
9745 /* File is already compressed. No "on the fly" compression. */
9746 allow_on_the_fly_compression = 0;
9747 #endif
9748 } else if ((conn->accept_gzip) && (range_hdr == NULL)
9749 && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
9750 struct mg_file_stat file_stat;
9751
9752 mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
9753
9754 if (!truncated && mg_stat(conn, gz_path, &file_stat)
9755 && !file_stat.is_directory) {
9756 file_stat.is_gzipped = 1;
9757 filep->stat = file_stat;
9758 cl = (int64_t)filep->stat.size;
9759 path = gz_path;
9760 encoding = "Content-Encoding: gzip\r\n";
9761
9762 #if defined(USE_ZLIB)
9763 /* File is already compressed. No "on the fly" compression. */
9764 allow_on_the_fly_compression = 0;
9765 #endif
9766 }
9767 }
9768
9769 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
9770 mg_send_http_error(conn,
9771 500,
9772 "Error: Cannot open file\nfopen(%s): %s",
9773 path,
9774 strerror(ERRNO));
9775 return;
9776 }
9777
9778 fclose_on_exec(&filep->access, conn);
9779
9780 /* If "Range" request was made: parse header, send only selected part
9781 * of the file. */
9782 r1 = r2 = 0;
9783 if ((range_hdr != NULL)
9784 && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
9785 && (r2 >= 0)) {
9786 /* actually, range requests don't play well with a pre-gzipped
9787 * file (since the range is specified in the uncompressed space) */
9788 if (filep->stat.is_gzipped) {
9789 mg_send_http_error(
9790 conn,
9791 416, /* 416 = Range Not Satisfiable */
9792 "%s",
9793 "Error: Range requests in gzipped files are not supported");
9794 (void)mg_fclose(
9795 &filep->access); /* ignore error on read only file */
9796 return;
9797 }
9798 conn->status_code = 206;
9799 cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
9800 mg_snprintf(conn,
9801 NULL, /* range buffer is big enough */
9802 range,
9803 sizeof(range),
9804 "Content-Range: bytes "
9805 "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
9806 r1,
9807 r1 + cl - 1,
9808 filep->stat.size);
9809 msg = "Partial Content";
9810
9811 #if defined(USE_ZLIB)
9812 /* Do not compress ranges. */
9813 allow_on_the_fly_compression = 0;
9814 #endif
9815 }
9816
9817 /* Do not compress small files. Small files do not benefit from file
9818 * compression, but there is still some overhead. */
9819 #if defined(USE_ZLIB)
9820 if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
9821 /* File is below the size limit. */
9822 allow_on_the_fly_compression = 0;
9823 }
9824 #endif
9825
9826 /* Standard CORS header */
9827 cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
9828 origin_hdr = mg_get_header(conn, "Origin");
9829 if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
9830 /* Cross-origin resource sharing (CORS), see
9831 * http://www.html5rocks.com/en/tutorials/cors/,
9832 * http://www.html5rocks.com/static/images/cors_server_flowchart.png
9833 * -
9834 * preflight is not supported for files. */
9835 cors1 = "Access-Control-Allow-Origin: ";
9836 cors2 = cors_orig_cfg;
9837 cors3 = "\r\n";
9838 } else {
9839 cors1 = cors2 = cors3 = "";
9840 }
9841
9842 /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
9843 * according to
9844 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
9845 gmt_time_string(date, sizeof(date), &curtime);
9846 gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
9847 construct_etag(etag, sizeof(etag), &filep->stat);
9848
9849 /* Send header */
9850 (void)mg_printf(conn,
9851 "HTTP/1.1 %d %s\r\n"
9852 "%s%s%s" /* CORS */
9853 "Date: %s\r\n"
9854 "Last-Modified: %s\r\n"
9855 "Etag: %s\r\n"
9856 "Content-Type: %.*s\r\n"
9857 "Connection: %s\r\n",
9858 conn->status_code,
9859 msg,
9860 cors1,
9861 cors2,
9862 cors3,
9863 date,
9864 lm,
9865 etag,
9866 (int)mime_vec.len,
9867 mime_vec.ptr,
9868 suggest_connection_header(conn));
9869 send_static_cache_header(conn);
9870 send_additional_header(conn);
9871
9872 #if defined(USE_ZLIB)
9873 /* On the fly compression allowed */
9874 if (allow_on_the_fly_compression) {
9875 /* For on the fly compression, we don't know the content size in
9876 * advance, so we have to use chunked encoding */
9877 (void)mg_printf(conn,
9878 "Content-Encoding: gzip\r\n"
9879 "Transfer-Encoding: chunked\r\n");
9880 } else
9881 #endif
9882 {
9883 /* Without on-the-fly compression, we know the content-length
9884 * and we can use ranges (with on-the-fly compression we cannot).
9885 * So we send these response headers only in this case. */
9886 (void)mg_printf(conn,
9887 "Content-Length: %" INT64_FMT "\r\n"
9888 "Accept-Ranges: bytes\r\n"
9889 "%s" /* range */
9890 "%s" /* encoding */,
9891 cl,
9892 range,
9893 encoding);
9894 }
9895
9896 /* The previous code must not add any header starting with X- to make
9897 * sure no one of the additional_headers is included twice */
9898 if (additional_headers != NULL) {
9899 (void)mg_printf(conn,
9900 "%.*s\r\n\r\n",
9901 (int)strlen(additional_headers),
9902 additional_headers);
9903 } else {
9904 (void)mg_printf(conn, "\r\n");
9905 }
9906
9907 if (!is_head_request) {
9908 #if defined(USE_ZLIB)
9909 if (allow_on_the_fly_compression) {
9910 /* Compress and send */
9911 send_compressed_data(conn, filep);
9912 } else
9913 #endif
9914 {
9915 /* Send file directly */
9916 send_file_data(conn, filep, r1, cl);
9917 }
9918 }
9919 (void)mg_fclose(&filep->access); /* ignore error on read only file */
9920 }
9921
9922
9923 int
9924 mg_send_file_body(struct mg_connection *conn, const char *path)
9925 {
9926 struct mg_file file = STRUCT_FILE_INITIALIZER;
9927 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
9928 return -1;
9929 }
9930 fclose_on_exec(&file.access, conn);
9931 send_file_data(conn, &file, 0, INT64_MAX);
9932 (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
9933 return 0; /* >= 0 for OK */
9934 }
9935 #endif /* NO_FILESYSTEMS */
9936
9937
9938 #if !defined(NO_CACHING)
9939 /* Return True if we should reply 304 Not Modified. */
9940 static int
9941 is_not_modified(const struct mg_connection *conn,
9942 const struct mg_file_stat *filestat)
9943 {
9944 char etag[64];
9945 const char *ims = mg_get_header(conn, "If-Modified-Since");
9946 const char *inm = mg_get_header(conn, "If-None-Match");
9947 construct_etag(etag, sizeof(etag), filestat);
9948
9949 return ((inm != NULL) && !mg_strcasecmp(etag, inm))
9950 || ((ims != NULL)
9951 && (filestat->last_modified <= parse_date_string(ims)));
9952 }
9953
9954 static void
9955 handle_not_modified_static_file_request(struct mg_connection *conn,
9956 struct mg_file *filep)
9957 {
9958 char date[64], lm[64], etag[64];
9959 time_t curtime = time(NULL);
9960
9961 if ((conn == NULL) || (filep == NULL)) {
9962 return;
9963 }
9964 conn->status_code = 304;
9965 gmt_time_string(date, sizeof(date), &curtime);
9966 gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
9967 construct_etag(etag, sizeof(etag), &filep->stat);
9968
9969 (void)mg_printf(conn,
9970 "HTTP/1.1 %d %s\r\n"
9971 "Date: %s\r\n",
9972 conn->status_code,
9973 mg_get_response_code_text(conn, conn->status_code),
9974 date);
9975 send_static_cache_header(conn);
9976 send_additional_header(conn);
9977 (void)mg_printf(conn,
9978 "Last-Modified: %s\r\n"
9979 "Etag: %s\r\n"
9980 "Connection: %s\r\n"
9981 "\r\n",
9982 lm,
9983 etag,
9984 suggest_connection_header(conn));
9985 }
9986 #endif
9987
9988
9989 #if !defined(NO_FILESYSTEMS)
9990 void
9991 mg_send_file(struct mg_connection *conn, const char *path)
9992 {
9993 mg_send_mime_file2(conn, path, NULL, NULL);
9994 }
9995
9996
9997 void
9998 mg_send_mime_file(struct mg_connection *conn,
9999 const char *path,
10000 const char *mime_type)
10001 {
10002 mg_send_mime_file2(conn, path, mime_type, NULL);
10003 }
10004
10005
10006 void
10007 mg_send_mime_file2(struct mg_connection *conn,
10008 const char *path,
10009 const char *mime_type,
10010 const char *additional_headers)
10011 {
10012 struct mg_file file = STRUCT_FILE_INITIALIZER;
10013
10014 if (!conn) {
10015 /* No conn */
10016 return;
10017 }
10018
10019 if (mg_stat(conn, path, &file.stat)) {
10020 #if !defined(NO_CACHING)
10021 if (is_not_modified(conn, &file.stat)) {
10022 /* Send 304 "Not Modified" - this must not send any body data */
10023 handle_not_modified_static_file_request(conn, &file);
10024 } else
10025 #endif /* NO_CACHING */
10026 if (file.stat.is_directory) {
10027 if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
10028 "yes")) {
10029 handle_directory_request(conn, path);
10030 } else {
10031 mg_send_http_error(conn,
10032 403,
10033 "%s",
10034 "Error: Directory listing denied");
10035 }
10036 } else {
10037 handle_static_file_request(
10038 conn, path, &file, mime_type, additional_headers);
10039 }
10040 } else {
10041 mg_send_http_error(conn, 404, "%s", "Error: File not found");
10042 }
10043 }
10044
10045
10046 /* For a given PUT path, create all intermediate subdirectories.
10047 * Return 0 if the path itself is a directory.
10048 * Return 1 if the path leads to a file.
10049 * Return -1 for if the path is too long.
10050 * Return -2 if path can not be created.
10051 */
10052 static int
10053 put_dir(struct mg_connection *conn, const char *path)
10054 {
10055 char buf[PATH_MAX];
10056 const char *s, *p;
10057 struct mg_file file = STRUCT_FILE_INITIALIZER;
10058 size_t len;
10059 int res = 1;
10060
10061 for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
10062 len = (size_t)(p - path);
10063 if (len >= sizeof(buf)) {
10064 /* path too long */
10065 res = -1;
10066 break;
10067 }
10068 memcpy(buf, path, len);
10069 buf[len] = '\0';
10070
10071 /* Try to create intermediate directory */
10072 DEBUG_TRACE("mkdir(%s)", buf);
10073 if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
10074 /* path does not exixt and can not be created */
10075 res = -2;
10076 break;
10077 }
10078
10079 /* Is path itself a directory? */
10080 if (p[1] == '\0') {
10081 res = 0;
10082 }
10083 }
10084
10085 return res;
10086 }
10087
10088
10089 static void
10090 remove_bad_file(const struct mg_connection *conn, const char *path)
10091 {
10092 int r = mg_remove(conn, path);
10093 if (r != 0) {
10094 mg_cry_internal(conn,
10095 "%s: Cannot remove invalid file %s",
10096 __func__,
10097 path);
10098 }
10099 }
10100
10101
10102 long long
10103 mg_store_body(struct mg_connection *conn, const char *path)
10104 {
10105 char buf[MG_BUF_LEN];
10106 long long len = 0;
10107 int ret, n;
10108 struct mg_file fi;
10109
10110 if (conn->consumed_content != 0) {
10111 mg_cry_internal(conn, "%s: Contents already consumed", __func__);
10112 return -11;
10113 }
10114
10115 ret = put_dir(conn, path);
10116 if (ret < 0) {
10117 /* -1 for path too long,
10118 * -2 for path can not be created. */
10119 return ret;
10120 }
10121 if (ret != 1) {
10122 /* Return 0 means, path itself is a directory. */
10123 return 0;
10124 }
10125
10126 if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
10127 return -12;
10128 }
10129
10130 ret = mg_read(conn, buf, sizeof(buf));
10131 while (ret > 0) {
10132 n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
10133 if (n != ret) {
10134 (void)mg_fclose(
10135 &fi.access); /* File is bad and will be removed anyway. */
10136 remove_bad_file(conn, path);
10137 return -13;
10138 }
10139 len += ret;
10140 ret = mg_read(conn, buf, sizeof(buf));
10141 }
10142
10143 /* File is open for writing. If fclose fails, there was probably an
10144 * error flushing the buffer to disk, so the file on disk might be
10145 * broken. Delete it and return an error to the caller. */
10146 if (mg_fclose(&fi.access) != 0) {
10147 remove_bad_file(conn, path);
10148 return -14;
10149 }
10150
10151 return len;
10152 }
10153 #endif /* NO_FILESYSTEMS */
10154
10155
10156 /* Parse a buffer:
10157 * Forward the string pointer till the end of a word, then
10158 * terminate it and forward till the begin of the next word.
10159 */
10160 static int
10161 skip_to_end_of_word_and_terminate(char **ppw, int eol)
10162 {
10163 /* Forward until a space is found - use isgraph here */
10164 /* See http://www.cplusplus.com/reference/cctype/ */
10165 while (isgraph((unsigned char)**ppw)) {
10166 (*ppw)++;
10167 }
10168
10169 /* Check end of word */
10170 if (eol) {
10171 /* must be a end of line */
10172 if ((**ppw != '\r') && (**ppw != '\n')) {
10173 return -1;
10174 }
10175 } else {
10176 /* must be a end of a word, but not a line */
10177 if (**ppw != ' ') {
10178 return -1;
10179 }
10180 }
10181
10182 /* Terminate and forward to the next word */
10183 do {
10184 **ppw = 0;
10185 (*ppw)++;
10186 } while (isspace((unsigned char)**ppw));
10187
10188 /* Check after term */
10189 if (!eol) {
10190 /* if it's not the end of line, there must be a next word */
10191 if (!isgraph((unsigned char)**ppw)) {
10192 return -1;
10193 }
10194 }
10195
10196 /* ok */
10197 return 1;
10198 }
10199
10200
10201 /* Parse HTTP headers from the given buffer, advance buf pointer
10202 * to the point where parsing stopped.
10203 * All parameters must be valid pointers (not NULL).
10204 * Return <0 on error. */
10205 static int
10206 parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
10207 {
10208 int i;
10209 int num_headers = 0;
10210
10211 for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
10212 char *dp = *buf;
10213
10214 /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
10215 while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
10216 dp++;
10217 }
10218 if (dp == *buf) {
10219 /* End of headers reached. */
10220 break;
10221 }
10222 if (*dp != ':') {
10223 /* This is not a valid field. */
10224 return -1;
10225 }
10226
10227 /* End of header key (*dp == ':') */
10228 /* Truncate here and set the key name */
10229 *dp = 0;
10230 hdr[i].name = *buf;
10231
10232 /* Skip all spaces */
10233 do {
10234 dp++;
10235 } while ((*dp == ' ') || (*dp == '\t'));
10236
10237 /* The rest of the line is the value */
10238 hdr[i].value = dp;
10239
10240 /* Find end of line */
10241 while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
10242 dp++;
10243 };
10244
10245 /* eliminate \r */
10246 if (*dp == '\r') {
10247 *dp = 0;
10248 dp++;
10249 if (*dp != '\n') {
10250 /* This is not a valid line. */
10251 return -1;
10252 }
10253 }
10254
10255 /* here *dp is either 0 or '\n' */
10256 /* in any case, we have a new header */
10257 num_headers = i + 1;
10258
10259 if (*dp) {
10260 *dp = 0;
10261 dp++;
10262 *buf = dp;
10263
10264 if ((dp[0] == '\r') || (dp[0] == '\n')) {
10265 /* This is the end of the header */
10266 break;
10267 }
10268 } else {
10269 *buf = dp;
10270 break;
10271 }
10272 }
10273 return num_headers;
10274 }
10275
10276
10277 struct mg_http_method_info {
10278 const char *name;
10279 int request_has_body;
10280 int response_has_body;
10281 int is_safe;
10282 int is_idempotent;
10283 int is_cacheable;
10284 };
10285
10286
10287 /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
10288 static struct mg_http_method_info http_methods[] = {
10289 /* HTTP (RFC 2616) */
10290 {"GET", 0, 1, 1, 1, 1},
10291 {"POST", 1, 1, 0, 0, 0},
10292 {"PUT", 1, 0, 0, 1, 0},
10293 {"DELETE", 0, 0, 0, 1, 0},
10294 {"HEAD", 0, 0, 1, 1, 1},
10295 {"OPTIONS", 0, 0, 1, 1, 0},
10296 {"CONNECT", 1, 1, 0, 0, 0},
10297 /* TRACE method (RFC 2616) is not supported for security reasons */
10298
10299 /* PATCH method (RFC 5789) */
10300 {"PATCH", 1, 0, 0, 0, 0},
10301 /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
10302
10303 /* WEBDAV (RFC 2518) */
10304 {"PROPFIND", 0, 1, 1, 1, 0},
10305 /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10306 * Some PROPFIND results MAY be cached, with care,
10307 * as there is no cache validation mechanism for
10308 * most properties. This method is both safe and
10309 * idempotent (see Section 9.1 of [RFC2616]). */
10310 {"MKCOL", 0, 0, 0, 1, 0},
10311 /* http://www.webdav.org/specs/rfc4918.html, 9.1:
10312 * When MKCOL is invoked without a request body,
10313 * the newly created collection SHOULD have no
10314 * members. A MKCOL request message may contain
10315 * a message body. The precise behavior of a MKCOL
10316 * request when the body is present is undefined,
10317 * ... ==> We do not support MKCOL with body data.
10318 * This method is idempotent, but not safe (see
10319 * Section 9.1 of [RFC2616]). Responses to this
10320 * method MUST NOT be cached. */
10321
10322 /* Unsupported WEBDAV Methods: */
10323 /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
10324 /* + 11 methods from RFC 3253 */
10325 /* ORDERPATCH (RFC 3648) */
10326 /* ACL (RFC 3744) */
10327 /* SEARCH (RFC 5323) */
10328 /* + MicroSoft extensions
10329 * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
10330
10331 /* REPORT method (RFC 3253) */
10332 {"REPORT", 1, 1, 1, 1, 1},
10333 /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
10334 /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
10335 * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
10336 * to be useful for REST in case a "GET request with body" is
10337 * required. */
10338
10339 {NULL, 0, 0, 0, 0, 0}
10340 /* end of list */
10341 };
10342
10343
10344 static const struct mg_http_method_info *
10345 get_http_method_info(const char *method)
10346 {
10347 /* Check if the method is known to the server. The list of all known
10348 * HTTP methods can be found here at
10349 * http://www.iana.org/assignments/http-methods/http-methods.xhtml
10350 */
10351 const struct mg_http_method_info *m = http_methods;
10352
10353 while (m->name) {
10354 if (!strcmp(m->name, method)) {
10355 return m;
10356 }
10357 m++;
10358 }
10359 return NULL;
10360 }
10361
10362
10363 static int
10364 is_valid_http_method(const char *method)
10365 {
10366 return (get_http_method_info(method) != NULL);
10367 }
10368
10369
10370 /* Parse HTTP request, fill in mg_request_info structure.
10371 * This function modifies the buffer by NUL-terminating
10372 * HTTP request components, header names and header values.
10373 * Parameters:
10374 * buf (in/out): pointer to the HTTP header to parse and split
10375 * len (in): length of HTTP header buffer
10376 * re (out): parsed header as mg_request_info
10377 * buf and ri must be valid pointers (not NULL), len>0.
10378 * Returns <0 on error. */
10379 static int
10380 parse_http_request(char *buf, int len, struct mg_request_info *ri)
10381 {
10382 int request_length;
10383 int init_skip = 0;
10384
10385 /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
10386 * remote_port */
10387 ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
10388 NULL;
10389 ri->num_headers = 0;
10390
10391 /* RFC says that all initial whitespaces should be ingored */
10392 /* This included all leading \r and \n (isspace) */
10393 /* See table: http://www.cplusplus.com/reference/cctype/ */
10394 while ((len > 0) && isspace((unsigned char)*buf)) {
10395 buf++;
10396 len--;
10397 init_skip++;
10398 }
10399
10400 if (len == 0) {
10401 /* Incomplete request */
10402 return 0;
10403 }
10404
10405 /* Control characters are not allowed, including zero */
10406 if (iscntrl((unsigned char)*buf)) {
10407 return -1;
10408 }
10409
10410 /* Find end of HTTP header */
10411 request_length = get_http_header_len(buf, len);
10412 if (request_length <= 0) {
10413 return request_length;
10414 }
10415 buf[request_length - 1] = '\0';
10416
10417 if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10418 return -1;
10419 }
10420
10421 /* The first word has to be the HTTP method */
10422 ri->request_method = buf;
10423
10424 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10425 return -1;
10426 }
10427
10428 /* Check for a valid http method */
10429 if (!is_valid_http_method(ri->request_method)) {
10430 return -1;
10431 }
10432
10433 /* The second word is the URI */
10434 ri->request_uri = buf;
10435
10436 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10437 return -1;
10438 }
10439
10440 /* Next would be the HTTP version */
10441 ri->http_version = buf;
10442
10443 if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
10444 return -1;
10445 }
10446
10447 /* Check for a valid HTTP version key */
10448 if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
10449 /* Invalid request */
10450 return -1;
10451 }
10452 ri->http_version += 5;
10453
10454
10455 /* Parse all HTTP headers */
10456 ri->num_headers = parse_http_headers(&buf, ri->http_headers);
10457 if (ri->num_headers < 0) {
10458 /* Error while parsing headers */
10459 return -1;
10460 }
10461
10462 return request_length + init_skip;
10463 }
10464
10465
10466 static int
10467 parse_http_response(char *buf, int len, struct mg_response_info *ri)
10468 {
10469 int response_length;
10470 int init_skip = 0;
10471 char *tmp, *tmp2;
10472 long l;
10473
10474 /* Initialize elements. */
10475 ri->http_version = ri->status_text = NULL;
10476 ri->num_headers = ri->status_code = 0;
10477
10478 /* RFC says that all initial whitespaces should be ingored */
10479 /* This included all leading \r and \n (isspace) */
10480 /* See table: http://www.cplusplus.com/reference/cctype/ */
10481 while ((len > 0) && isspace((unsigned char)*buf)) {
10482 buf++;
10483 len--;
10484 init_skip++;
10485 }
10486
10487 if (len == 0) {
10488 /* Incomplete request */
10489 return 0;
10490 }
10491
10492 /* Control characters are not allowed, including zero */
10493 if (iscntrl((unsigned char)*buf)) {
10494 return -1;
10495 }
10496
10497 /* Find end of HTTP header */
10498 response_length = get_http_header_len(buf, len);
10499 if (response_length <= 0) {
10500 return response_length;
10501 }
10502 buf[response_length - 1] = '\0';
10503
10504 if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10505 return -1;
10506 }
10507
10508 /* The first word is the HTTP version */
10509 /* Check for a valid HTTP version key */
10510 if (strncmp(buf, "HTTP/", 5) != 0) {
10511 /* Invalid request */
10512 return -1;
10513 }
10514 buf += 5;
10515 if (!isgraph((unsigned char)buf[0])) {
10516 /* Invalid request */
10517 return -1;
10518 }
10519 ri->http_version = buf;
10520
10521 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10522 return -1;
10523 }
10524
10525 /* The second word is the status as a number */
10526 tmp = buf;
10527
10528 if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10529 return -1;
10530 }
10531
10532 l = strtol(tmp, &tmp2, 10);
10533 if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
10534 /* Everything else but a 3 digit code is invalid */
10535 return -1;
10536 }
10537 ri->status_code = (int)l;
10538
10539 /* The rest of the line is the status text */
10540 ri->status_text = buf;
10541
10542 /* Find end of status text */
10543 /* isgraph or isspace = isprint */
10544 while (isprint((unsigned char)*buf)) {
10545 buf++;
10546 }
10547 if ((*buf != '\r') && (*buf != '\n')) {
10548 return -1;
10549 }
10550 /* Terminate string and forward buf to next line */
10551 do {
10552 *buf = 0;
10553 buf++;
10554 } while (isspace((unsigned char)*buf));
10555
10556
10557 /* Parse all HTTP headers */
10558 ri->num_headers = parse_http_headers(&buf, ri->http_headers);
10559 if (ri->num_headers < 0) {
10560 /* Error while parsing headers */
10561 return -1;
10562 }
10563
10564 return response_length + init_skip;
10565 }
10566
10567
10568 /* Keep reading the input (either opened file descriptor fd, or socket sock,
10569 * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
10570 * buffer (which marks the end of HTTP request). Buffer buf may already
10571 * have some data. The length of the data is stored in nread.
10572 * Upon every read operation, increase nread by the number of bytes read. */
10573 static int
10574 read_message(FILE *fp,
10575 struct mg_connection *conn,
10576 char *buf,
10577 int bufsiz,
10578 int *nread)
10579 {
10580 int request_len, n = 0;
10581 struct timespec last_action_time;
10582 double request_timeout;
10583
10584 if (!conn) {
10585 return 0;
10586 }
10587
10588 memset(&last_action_time, 0, sizeof(last_action_time));
10589
10590 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
10591 /* value of request_timeout is in seconds, config in milliseconds */
10592 request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
10593 } else {
10594 request_timeout = -1.0;
10595 }
10596 if (conn->handled_requests > 0) {
10597 if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
10598 request_timeout =
10599 atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
10600 }
10601 }
10602
10603 request_len = get_http_header_len(buf, *nread);
10604
10605 while (request_len == 0) {
10606 /* Full request not yet received */
10607 if (conn->phys_ctx->stop_flag != 0) {
10608 /* Server is to be stopped. */
10609 return -1;
10610 }
10611
10612 if (*nread >= bufsiz) {
10613 /* Request too long */
10614 return -2;
10615 }
10616
10617 n = pull_inner(
10618 fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
10619 if (n == -2) {
10620 /* Receive error */
10621 return -1;
10622 }
10623
10624 /* update clock after every read request */
10625 clock_gettime(CLOCK_MONOTONIC, &last_action_time);
10626
10627 if (n > 0) {
10628 *nread += n;
10629 request_len = get_http_header_len(buf, *nread);
10630 } else {
10631 request_len = 0;
10632 }
10633
10634 if ((request_len == 0) && (request_timeout >= 0)) {
10635 if (mg_difftimespec(&last_action_time, &(conn->req_time))
10636 > request_timeout) {
10637 /* Timeout */
10638 return -1;
10639 }
10640 }
10641 }
10642
10643 return request_len;
10644 }
10645
10646
10647 #if !defined(NO_CGI) || !defined(NO_FILES)
10648 static int
10649 forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
10650 {
10651 const char *expect;
10652 char buf[MG_BUF_LEN];
10653 int success = 0;
10654
10655 if (!conn) {
10656 return 0;
10657 }
10658
10659 expect = mg_get_header(conn, "Expect");
10660 DEBUG_ASSERT(fp != NULL);
10661 if (!fp) {
10662 mg_send_http_error(conn, 500, "%s", "Error: NULL File");
10663 return 0;
10664 }
10665
10666 if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
10667 /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
10668 */
10669 mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
10670 } else {
10671 if (expect != NULL) {
10672 (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
10673 conn->status_code = 100;
10674 } else {
10675 conn->status_code = 200;
10676 }
10677
10678 DEBUG_ASSERT(conn->consumed_content == 0);
10679
10680 if (conn->consumed_content != 0) {
10681 mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
10682 return 0;
10683 }
10684
10685 for (;;) {
10686 int nread = mg_read(conn, buf, sizeof(buf));
10687 if (nread <= 0) {
10688 success = (nread == 0);
10689 break;
10690 }
10691 if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
10692 break;
10693 }
10694 }
10695
10696 /* Each error code path in this function must send an error */
10697 if (!success) {
10698 /* NOTE: Maybe some data has already been sent. */
10699 /* TODO (low): If some data has been sent, a correct error
10700 * reply can no longer be sent, so just close the connection */
10701 mg_send_http_error(conn, 500, "%s", "");
10702 }
10703 }
10704
10705 return success;
10706 }
10707 #endif
10708
10709
10710 #if defined(USE_TIMERS)
10711
10712 #define TIMER_API static
10713 #include "timer.inl"
10714
10715 #endif /* USE_TIMERS */
10716
10717
10718 #if !defined(NO_CGI)
10719 /* This structure helps to create an environment for the spawned CGI
10720 * program.
10721 * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
10722 * last element must be NULL.
10723 * However, on Windows there is a requirement that all these
10724 * VARIABLE=VALUE\0
10725 * strings must reside in a contiguous buffer. The end of the buffer is
10726 * marked by two '\0' characters.
10727 * We satisfy both worlds: we create an envp array (which is vars), all
10728 * entries are actually pointers inside buf. */
10729 struct cgi_environment {
10730 struct mg_connection *conn;
10731 /* Data block */
10732 char *buf; /* Environment buffer */
10733 size_t buflen; /* Space available in buf */
10734 size_t bufused; /* Space taken in buf */
10735 /* Index block */
10736 char **var; /* char **envp */
10737 size_t varlen; /* Number of variables available in var */
10738 size_t varused; /* Number of variables stored in var */
10739 };
10740
10741
10742 static void addenv(struct cgi_environment *env,
10743 PRINTF_FORMAT_STRING(const char *fmt),
10744 ...) PRINTF_ARGS(2, 3);
10745
10746 /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
10747 * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
10748 static void
10749 addenv(struct cgi_environment *env, const char *fmt, ...)
10750 {
10751 size_t i, n, space;
10752 int truncated = 0;
10753 char *added;
10754 va_list ap;
10755
10756 if ((env->varlen - env->varused) < 2) {
10757 mg_cry_internal(env->conn,
10758 "%s: Cannot register CGI variable [%s]",
10759 __func__,
10760 fmt);
10761 return;
10762 }
10763
10764 /* Calculate how much space is left in the buffer */
10765 space = (env->buflen - env->bufused);
10766
10767 do {
10768 /* Space for "\0\0" is always needed. */
10769 if (space <= 2) {
10770 /* Allocate new buffer */
10771 n = env->buflen + CGI_ENVIRONMENT_SIZE;
10772 added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
10773 if (!added) {
10774 /* Out of memory */
10775 mg_cry_internal(
10776 env->conn,
10777 "%s: Cannot allocate memory for CGI variable [%s]",
10778 __func__,
10779 fmt);
10780 return;
10781 }
10782 /* Retarget pointers */
10783 env->buf = added;
10784 env->buflen = n;
10785 for (i = 0, n = 0; i < env->varused; i++) {
10786 env->var[i] = added + n;
10787 n += strlen(added + n) + 1;
10788 }
10789 space = (env->buflen - env->bufused);
10790 }
10791
10792 /* Make a pointer to the free space int the buffer */
10793 added = env->buf + env->bufused;
10794
10795 /* Copy VARIABLE=VALUE\0 string into the free space */
10796 va_start(ap, fmt);
10797 mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
10798 va_end(ap);
10799
10800 /* Do not add truncated strings to the environment */
10801 if (truncated) {
10802 /* Reallocate the buffer */
10803 space = 0;
10804 }
10805 } while (truncated);
10806
10807 /* Calculate number of bytes added to the environment */
10808 n = strlen(added) + 1;
10809 env->bufused += n;
10810
10811 /* Append a pointer to the added string into the envp array */
10812 env->var[env->varused] = added;
10813 env->varused++;
10814 }
10815
10816 /* Return 0 on success, non-zero if an error occurs. */
10817
10818 static int
10819 prepare_cgi_environment(struct mg_connection *conn,
10820 const char *prog,
10821 struct cgi_environment *env)
10822 {
10823 const char *s;
10824 struct vec var_vec;
10825 char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
10826 int i, truncated, uri_len;
10827
10828 if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
10829 return -1;
10830 }
10831
10832 env->conn = conn;
10833 env->buflen = CGI_ENVIRONMENT_SIZE;
10834 env->bufused = 0;
10835 env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
10836 if (env->buf == NULL) {
10837 mg_cry_internal(conn,
10838 "%s: Not enough memory for environmental buffer",
10839 __func__);
10840 return -1;
10841 }
10842 env->varlen = MAX_CGI_ENVIR_VARS;
10843 env->varused = 0;
10844 env->var =
10845 (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
10846 if (env->var == NULL) {
10847 mg_cry_internal(conn,
10848 "%s: Not enough memory for environmental variables",
10849 __func__);
10850 mg_free(env->buf);
10851 return -1;
10852 }
10853
10854 addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
10855 addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
10856 addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
10857 addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
10858
10859 /* Prepare the environment block */
10860 addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
10861 addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
10862 addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
10863
10864 #if defined(USE_IPV6)
10865 if (conn->client.lsa.sa.sa_family == AF_INET6) {
10866 addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
10867 } else
10868 #endif
10869 {
10870 addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
10871 }
10872
10873 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
10874 addenv(env, "REMOTE_ADDR=%s", src_addr);
10875
10876 addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
10877 addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
10878
10879 addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
10880 addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
10881
10882 /* SCRIPT_NAME */
10883 uri_len = (int)strlen(conn->request_info.local_uri);
10884 if (conn->path_info == NULL) {
10885 if (conn->request_info.local_uri[uri_len - 1] != '/') {
10886 /* URI: /path_to_script/script.cgi */
10887 addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
10888 } else {
10889 /* URI: /path_to_script/ ... using index.cgi */
10890 const char *index_file = strrchr(prog, '/');
10891 if (index_file) {
10892 addenv(env,
10893 "SCRIPT_NAME=%s%s",
10894 conn->request_info.local_uri,
10895 index_file + 1);
10896 }
10897 }
10898 } else {
10899 /* URI: /path_to_script/script.cgi/path_info */
10900 addenv(env,
10901 "SCRIPT_NAME=%.*s",
10902 uri_len - (int)strlen(conn->path_info),
10903 conn->request_info.local_uri);
10904 }
10905
10906 addenv(env, "SCRIPT_FILENAME=%s", prog);
10907 if (conn->path_info == NULL) {
10908 addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
10909 } else {
10910 addenv(env,
10911 "PATH_TRANSLATED=%s%s",
10912 conn->dom_ctx->config[DOCUMENT_ROOT],
10913 conn->path_info);
10914 }
10915
10916 addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
10917
10918 if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
10919 addenv(env, "CONTENT_TYPE=%s", s);
10920 }
10921 if (conn->request_info.query_string != NULL) {
10922 addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
10923 }
10924 if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
10925 addenv(env, "CONTENT_LENGTH=%s", s);
10926 }
10927 if ((s = getenv("PATH")) != NULL) {
10928 addenv(env, "PATH=%s", s);
10929 }
10930 if (conn->path_info != NULL) {
10931 addenv(env, "PATH_INFO=%s", conn->path_info);
10932 }
10933
10934 if (conn->status_code > 0) {
10935 /* CGI error handler should show the status code */
10936 addenv(env, "STATUS=%d", conn->status_code);
10937 }
10938
10939 #if defined(_WIN32)
10940 if ((s = getenv("COMSPEC")) != NULL) {
10941 addenv(env, "COMSPEC=%s", s);
10942 }
10943 if ((s = getenv("SYSTEMROOT")) != NULL) {
10944 addenv(env, "SYSTEMROOT=%s", s);
10945 }
10946 if ((s = getenv("SystemDrive")) != NULL) {
10947 addenv(env, "SystemDrive=%s", s);
10948 }
10949 if ((s = getenv("ProgramFiles")) != NULL) {
10950 addenv(env, "ProgramFiles=%s", s);
10951 }
10952 if ((s = getenv("ProgramFiles(x86)")) != NULL) {
10953 addenv(env, "ProgramFiles(x86)=%s", s);
10954 }
10955 #else
10956 if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
10957 addenv(env, "LD_LIBRARY_PATH=%s", s);
10958 }
10959 #endif /* _WIN32 */
10960
10961 if ((s = getenv("PERLLIB")) != NULL) {
10962 addenv(env, "PERLLIB=%s", s);
10963 }
10964
10965 if (conn->request_info.remote_user != NULL) {
10966 addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
10967 addenv(env, "%s", "AUTH_TYPE=Digest");
10968 }
10969
10970 /* Add all headers as HTTP_* variables */
10971 for (i = 0; i < conn->request_info.num_headers; i++) {
10972
10973 (void)mg_snprintf(conn,
10974 &truncated,
10975 http_var_name,
10976 sizeof(http_var_name),
10977 "HTTP_%s",
10978 conn->request_info.http_headers[i].name);
10979
10980 if (truncated) {
10981 mg_cry_internal(conn,
10982 "%s: HTTP header variable too long [%s]",
10983 __func__,
10984 conn->request_info.http_headers[i].name);
10985 continue;
10986 }
10987
10988 /* Convert variable name into uppercase, and change - to _ */
10989 for (p = http_var_name; *p != '\0'; p++) {
10990 if (*p == '-') {
10991 *p = '_';
10992 }
10993 *p = (char)toupper((unsigned char)*p);
10994 }
10995
10996 addenv(env,
10997 "%s=%s",
10998 http_var_name,
10999 conn->request_info.http_headers[i].value);
11000 }
11001
11002 /* Add user-specified variables */
11003 s = conn->dom_ctx->config[CGI_ENVIRONMENT];
11004 while ((s = next_option(s, &var_vec, NULL)) != NULL) {
11005 addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
11006 }
11007
11008 env->var[env->varused] = NULL;
11009 env->buf[env->bufused] = '\0';
11010
11011 return 0;
11012 }
11013
11014
11015 /* Data for CGI process control: PID and number of references */
11016 struct process_control_data {
11017 pid_t pid;
11018 int references;
11019 };
11020
11021 static int
11022 abort_process(void *data)
11023 {
11024 /* Waitpid checks for child status and won't work for a pid that does not
11025 * identify a child of the current process. Thus, if the pid is reused,
11026 * we will not affect a different process. */
11027 struct process_control_data *proc = (struct process_control_data *)data;
11028 int status = 0;
11029 int refs;
11030 pid_t ret_pid;
11031
11032 ret_pid = waitpid(proc->pid, &status, WNOHANG);
11033 if ((ret_pid != (pid_t)-1) && (status == 0)) {
11034 /* Stop child process */
11035 DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
11036 kill(proc->pid, SIGABRT);
11037
11038 /* Wait until process is terminated (don't leave zombies) */
11039 while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
11040 ;
11041 } else {
11042 DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
11043 }
11044 /* Dec reference counter */
11045 refs = mg_atomic_dec(&proc->references);
11046 if (refs == 0) {
11047 /* no more references - free data */
11048 mg_free(data);
11049 }
11050
11051 return 0;
11052 }
11053
11054
11055 /* Local (static) function assumes all arguments are valid. */
11056 static void
11057 handle_cgi_request(struct mg_connection *conn, const char *prog)
11058 {
11059 char *buf;
11060 size_t buflen;
11061 int headers_len, data_len, i, truncated;
11062 int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
11063 const char *status, *status_text, *connection_state;
11064 char *pbuf, dir[PATH_MAX], *p;
11065 struct mg_request_info ri;
11066 struct cgi_environment blk;
11067 FILE *in = NULL, *out = NULL, *err = NULL;
11068 struct mg_file fout = STRUCT_FILE_INITIALIZER;
11069 pid_t pid = (pid_t)-1;
11070 struct process_control_data *proc = NULL;
11071
11072 #if defined(USE_TIMERS)
11073 double cgi_timeout = -1.0;
11074 if (conn->dom_ctx->config[CGI_TIMEOUT]) {
11075 /* Get timeout in seconds */
11076 cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
11077 }
11078 #endif
11079
11080 buf = NULL;
11081 buflen = conn->phys_ctx->max_request_size;
11082 i = prepare_cgi_environment(conn, prog, &blk);
11083 if (i != 0) {
11084 blk.buf = NULL;
11085 blk.var = NULL;
11086 goto done;
11087 }
11088
11089 /* CGI must be executed in its own directory. 'dir' must point to the
11090 * directory containing executable program, 'p' must point to the
11091 * executable program name relative to 'dir'. */
11092 (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
11093
11094 if (truncated) {
11095 mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
11096 mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
11097 goto done;
11098 }
11099
11100 if ((p = strrchr(dir, '/')) != NULL) {
11101 *p++ = '\0';
11102 } else {
11103 dir[0] = '.';
11104 dir[1] = '\0';
11105 p = (char *)prog;
11106 }
11107
11108 if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
11109 status = strerror(ERRNO);
11110 mg_cry_internal(
11111 conn,
11112 "Error: CGI program \"%s\": Can not create CGI pipes: %s",
11113 prog,
11114 status);
11115 mg_send_http_error(conn,
11116 500,
11117 "Error: Cannot create CGI pipe: %s",
11118 status);
11119 goto done;
11120 }
11121
11122 proc = (struct process_control_data *)
11123 mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
11124 if (proc == NULL) {
11125 mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
11126 mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
11127 goto done;
11128 }
11129
11130 DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
11131 pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
11132
11133 if (pid == (pid_t)-1) {
11134 status = strerror(ERRNO);
11135 mg_cry_internal(
11136 conn,
11137 "Error: CGI program \"%s\": Can not spawn CGI process: %s",
11138 prog,
11139 status);
11140 mg_send_http_error(conn,
11141 500,
11142 "Error: Cannot spawn CGI process [%s]: %s",
11143 prog,
11144 status);
11145 mg_free(proc);
11146 proc = NULL;
11147 goto done;
11148 }
11149
11150 /* Store data in shared process_control_data */
11151 proc->pid = pid;
11152 proc->references = 1;
11153
11154 #if defined(USE_TIMERS)
11155 if (cgi_timeout > 0.0) {
11156 proc->references = 2;
11157
11158 // Start a timer for CGI
11159 timer_add(conn->phys_ctx,
11160 cgi_timeout /* in seconds */,
11161 0.0,
11162 1,
11163 abort_process,
11164 (void *)proc);
11165 }
11166 #endif
11167
11168 /* Parent closes only one side of the pipes.
11169 * If we don't mark them as closed, close() attempt before
11170 * return from this function throws an exception on Windows.
11171 * Windows does not like when closed descriptor is closed again. */
11172 (void)close(fdin[0]);
11173 (void)close(fdout[1]);
11174 (void)close(fderr[1]);
11175 fdin[0] = fdout[1] = fderr[1] = -1;
11176
11177 if (((in = fdopen(fdin[1], "wb")) == NULL)
11178 || ((out = fdopen(fdout[0], "rb")) == NULL)
11179 || ((err = fdopen(fderr[0], "rb")) == NULL)) {
11180 status = strerror(ERRNO);
11181 mg_cry_internal(conn,
11182 "Error: CGI program \"%s\": Can not open fd: %s",
11183 prog,
11184 status);
11185 mg_send_http_error(conn,
11186 500,
11187 "Error: CGI can not open fd\nfdopen: %s",
11188 status);
11189 goto done;
11190 }
11191
11192 setbuf(in, NULL);
11193 setbuf(out, NULL);
11194 setbuf(err, NULL);
11195 fout.access.fp = out;
11196
11197 if ((conn->content_len != 0) || (conn->is_chunked)) {
11198 DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
11199 conn->content_len);
11200
11201 /* This is a POST/PUT request, or another request with body data. */
11202 if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
11203 /* Error sending the body data */
11204 mg_cry_internal(
11205 conn,
11206 "Error: CGI program \"%s\": Forward body data failed",
11207 prog);
11208 goto done;
11209 }
11210 }
11211
11212 /* Close so child gets an EOF. */
11213 fclose(in);
11214 in = NULL;
11215 fdin[1] = -1;
11216
11217 /* Now read CGI reply into a buffer. We need to set correct
11218 * status code, thus we need to see all HTTP headers first.
11219 * Do not send anything back to client, until we buffer in all
11220 * HTTP headers. */
11221 data_len = 0;
11222 buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
11223 if (buf == NULL) {
11224 mg_send_http_error(conn,
11225 500,
11226 "Error: Not enough memory for CGI buffer (%u bytes)",
11227 (unsigned int)buflen);
11228 mg_cry_internal(
11229 conn,
11230 "Error: CGI program \"%s\": Not enough memory for buffer (%u "
11231 "bytes)",
11232 prog,
11233 (unsigned int)buflen);
11234 goto done;
11235 }
11236
11237 DEBUG_TRACE("CGI: %s", "wait for response");
11238 headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
11239 DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
11240
11241 if (headers_len <= 0) {
11242
11243 /* Could not parse the CGI response. Check if some error message on
11244 * stderr. */
11245 i = pull_all(err, conn, buf, (int)buflen);
11246 if (i > 0) {
11247 /* CGI program explicitly sent an error */
11248 /* Write the error message to the internal log */
11249 mg_cry_internal(conn,
11250 "Error: CGI program \"%s\" sent error "
11251 "message: [%.*s]",
11252 prog,
11253 i,
11254 buf);
11255 /* Don't send the error message back to the client */
11256 mg_send_http_error(conn,
11257 500,
11258 "Error: CGI program \"%s\" failed.",
11259 prog);
11260 } else {
11261 /* CGI program did not explicitly send an error, but a broken
11262 * respon header */
11263 mg_cry_internal(conn,
11264 "Error: CGI program sent malformed or too big "
11265 "(>%u bytes) HTTP headers: [%.*s]",
11266 (unsigned)buflen,
11267 data_len,
11268 buf);
11269
11270 mg_send_http_error(conn,
11271 500,
11272 "Error: CGI program sent malformed or too big "
11273 "(>%u bytes) HTTP headers: [%.*s]",
11274 (unsigned)buflen,
11275 data_len,
11276 buf);
11277 }
11278
11279 /* in both cases, abort processing CGI */
11280 goto done;
11281 }
11282
11283 pbuf = buf;
11284 buf[headers_len - 1] = '\0';
11285 ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
11286
11287 /* Make up and send the status line */
11288 status_text = "OK";
11289 if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
11290 != NULL) {
11291 conn->status_code = atoi(status);
11292 status_text = status;
11293 while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
11294 status_text++;
11295 }
11296 } else if (get_header(ri.http_headers, ri.num_headers, "Location")
11297 != NULL) {
11298 conn->status_code = 307;
11299 } else {
11300 conn->status_code = 200;
11301 }
11302 connection_state =
11303 get_header(ri.http_headers, ri.num_headers, "Connection");
11304 if (!header_has_option(connection_state, "keep-alive")) {
11305 conn->must_close = 1;
11306 }
11307
11308 DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
11309
11310 (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
11311
11312 /* Send headers */
11313 for (i = 0; i < ri.num_headers; i++) {
11314 DEBUG_TRACE("CGI header: %s: %s",
11315 ri.http_headers[i].name,
11316 ri.http_headers[i].value);
11317 mg_printf(conn,
11318 "%s: %s\r\n",
11319 ri.http_headers[i].name,
11320 ri.http_headers[i].value);
11321 }
11322 mg_write(conn, "\r\n", 2);
11323
11324 /* Send chunk of data that may have been read after the headers */
11325 mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
11326
11327 /* Read the rest of CGI output and send to the client */
11328 DEBUG_TRACE("CGI: %s", "forward all data");
11329 send_file_data(conn, &fout, 0, INT64_MAX);
11330 DEBUG_TRACE("CGI: %s", "all data sent");
11331
11332 done:
11333 mg_free(blk.var);
11334 mg_free(blk.buf);
11335
11336 if (pid != (pid_t)-1) {
11337 abort_process((void *)proc);
11338 }
11339
11340 if (fdin[0] != -1) {
11341 close(fdin[0]);
11342 }
11343 if (fdout[1] != -1) {
11344 close(fdout[1]);
11345 }
11346 if (fderr[1] != -1) {
11347 close(fderr[1]);
11348 }
11349
11350 if (in != NULL) {
11351 fclose(in);
11352 } else if (fdin[1] != -1) {
11353 close(fdin[1]);
11354 }
11355
11356 if (out != NULL) {
11357 fclose(out);
11358 } else if (fdout[0] != -1) {
11359 close(fdout[0]);
11360 }
11361
11362 if (err != NULL) {
11363 fclose(err);
11364 } else if (fderr[0] != -1) {
11365 close(fderr[0]);
11366 }
11367
11368 mg_free(buf);
11369 }
11370 #endif /* !NO_CGI */
11371
11372
11373 #if !defined(NO_FILES)
11374 static void
11375 mkcol(struct mg_connection *conn, const char *path)
11376 {
11377 int rc, body_len;
11378 struct de de;
11379 char date[64];
11380 time_t curtime = time(NULL);
11381
11382 if (conn == NULL) {
11383 return;
11384 }
11385
11386 /* TODO (mid): Check the mg_send_http_error situations in this function
11387 */
11388
11389 memset(&de.file, 0, sizeof(de.file));
11390 if (!mg_stat(conn, path, &de.file)) {
11391 mg_cry_internal(conn,
11392 "%s: mg_stat(%s) failed: %s",
11393 __func__,
11394 path,
11395 strerror(ERRNO));
11396 }
11397
11398 if (de.file.last_modified) {
11399 /* TODO (mid): This check does not seem to make any sense ! */
11400 /* TODO (mid): Add a webdav unit test first, before changing
11401 * anything here. */
11402 mg_send_http_error(
11403 conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11404 return;
11405 }
11406
11407 body_len = conn->data_len - conn->request_len;
11408 if (body_len > 0) {
11409 mg_send_http_error(
11410 conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11411 return;
11412 }
11413
11414 rc = mg_mkdir(conn, path, 0755);
11415
11416 if (rc == 0) {
11417 conn->status_code = 201;
11418 gmt_time_string(date, sizeof(date), &curtime);
11419 mg_printf(conn,
11420 "HTTP/1.1 %d Created\r\n"
11421 "Date: %s\r\n",
11422 conn->status_code,
11423 date);
11424 send_static_cache_header(conn);
11425 send_additional_header(conn);
11426 mg_printf(conn,
11427 "Content-Length: 0\r\n"
11428 "Connection: %s\r\n\r\n",
11429 suggest_connection_header(conn));
11430 } else {
11431 if (errno == EEXIST) {
11432 mg_send_http_error(
11433 conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11434 } else if (errno == EACCES) {
11435 mg_send_http_error(
11436 conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11437 } else if (errno == ENOENT) {
11438 mg_send_http_error(
11439 conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11440 } else {
11441 mg_send_http_error(
11442 conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
11443 }
11444 }
11445 }
11446
11447
11448 static void
11449 put_file(struct mg_connection *conn, const char *path)
11450 {
11451 struct mg_file file = STRUCT_FILE_INITIALIZER;
11452 const char *range;
11453 int64_t r1, r2;
11454 int rc;
11455 char date[64];
11456 time_t curtime = time(NULL);
11457
11458 if (conn == NULL) {
11459 return;
11460 }
11461
11462 if (mg_stat(conn, path, &file.stat)) {
11463 /* File already exists */
11464 conn->status_code = 200;
11465
11466 if (file.stat.is_directory) {
11467 /* This is an already existing directory,
11468 * so there is nothing to do for the server. */
11469 rc = 0;
11470
11471 } else {
11472 /* File exists and is not a directory. */
11473 /* Can it be replaced? */
11474
11475 #if defined(MG_USE_OPEN_FILE)
11476 if (file.access.membuf != NULL) {
11477 /* This is an "in-memory" file, that can not be replaced */
11478 mg_send_http_error(conn,
11479 405,
11480 "Error: Put not possible\nReplacing %s "
11481 "is not supported",
11482 path);
11483 return;
11484 }
11485 #endif
11486
11487 /* Check if the server may write this file */
11488 if (access(path, W_OK) == 0) {
11489 /* Access granted */
11490 conn->status_code = 200;
11491 rc = 1;
11492 } else {
11493 mg_send_http_error(
11494 conn,
11495 403,
11496 "Error: Put not possible\nReplacing %s is not allowed",
11497 path);
11498 return;
11499 }
11500 }
11501 } else {
11502 /* File should be created */
11503 conn->status_code = 201;
11504 rc = put_dir(conn, path);
11505 }
11506
11507 if (rc == 0) {
11508 /* put_dir returns 0 if path is a directory */
11509 gmt_time_string(date, sizeof(date), &curtime);
11510 mg_printf(conn,
11511 "HTTP/1.1 %d %s\r\n",
11512 conn->status_code,
11513 mg_get_response_code_text(NULL, conn->status_code));
11514 send_no_cache_header(conn);
11515 send_additional_header(conn);
11516 mg_printf(conn,
11517 "Date: %s\r\n"
11518 "Content-Length: 0\r\n"
11519 "Connection: %s\r\n\r\n",
11520 date,
11521 suggest_connection_header(conn));
11522
11523 /* Request to create a directory has been fulfilled successfully.
11524 * No need to put a file. */
11525 return;
11526 }
11527
11528 if (rc == -1) {
11529 /* put_dir returns -1 if the path is too long */
11530 mg_send_http_error(conn,
11531 414,
11532 "Error: Path too long\nput_dir(%s): %s",
11533 path,
11534 strerror(ERRNO));
11535 return;
11536 }
11537
11538 if (rc == -2) {
11539 /* put_dir returns -2 if the directory can not be created */
11540 mg_send_http_error(conn,
11541 500,
11542 "Error: Can not create directory\nput_dir(%s): %s",
11543 path,
11544 strerror(ERRNO));
11545 return;
11546 }
11547
11548 /* A file should be created or overwritten. */
11549 /* Currently CivetWeb does not nead read+write access. */
11550 if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
11551 || file.access.fp == NULL) {
11552 (void)mg_fclose(&file.access);
11553 mg_send_http_error(conn,
11554 500,
11555 "Error: Can not create file\nfopen(%s): %s",
11556 path,
11557 strerror(ERRNO));
11558 return;
11559 }
11560
11561 fclose_on_exec(&file.access, conn);
11562 range = mg_get_header(conn, "Content-Range");
11563 r1 = r2 = 0;
11564 if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
11565 conn->status_code = 206; /* Partial content */
11566 fseeko(file.access.fp, r1, SEEK_SET);
11567 }
11568
11569 if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
11570 /* forward_body_data failed.
11571 * The error code has already been sent to the client,
11572 * and conn->status_code is already set. */
11573 (void)mg_fclose(&file.access);
11574 return;
11575 }
11576
11577 if (mg_fclose(&file.access) != 0) {
11578 /* fclose failed. This might have different reasons, but a likely
11579 * one is "no space on disk", http 507. */
11580 conn->status_code = 507;
11581 }
11582
11583 gmt_time_string(date, sizeof(date), &curtime);
11584 mg_printf(conn,
11585 "HTTP/1.1 %d %s\r\n",
11586 conn->status_code,
11587 mg_get_response_code_text(NULL, conn->status_code));
11588 send_no_cache_header(conn);
11589 send_additional_header(conn);
11590 mg_printf(conn,
11591 "Date: %s\r\n"
11592 "Content-Length: 0\r\n"
11593 "Connection: %s\r\n\r\n",
11594 date,
11595 suggest_connection_header(conn));
11596 }
11597
11598
11599 static void
11600 delete_file(struct mg_connection *conn, const char *path)
11601 {
11602 struct de de;
11603 memset(&de.file, 0, sizeof(de.file));
11604 if (!mg_stat(conn, path, &de.file)) {
11605 /* mg_stat returns 0 if the file does not exist */
11606 mg_send_http_error(conn,
11607 404,
11608 "Error: Cannot delete file\nFile %s not found",
11609 path);
11610 return;
11611 }
11612
11613 #if 0 /* Ignore if a file in memory is inside a folder */
11614 if (de.access.membuf != NULL) {
11615 /* the file is cached in memory */
11616 mg_send_http_error(
11617 conn,
11618 405,
11619 "Error: Delete not possible\nDeleting %s is not supported",
11620 path);
11621 return;
11622 }
11623 #endif
11624
11625 if (de.file.is_directory) {
11626 if (remove_directory(conn, path)) {
11627 /* Delete is successful: Return 204 without content. */
11628 mg_send_http_error(conn, 204, "%s", "");
11629 } else {
11630 /* Delete is not successful: Return 500 (Server error). */
11631 mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
11632 }
11633 return;
11634 }
11635
11636 /* This is an existing file (not a directory).
11637 * Check if write permission is granted. */
11638 if (access(path, W_OK) != 0) {
11639 /* File is read only */
11640 mg_send_http_error(
11641 conn,
11642 403,
11643 "Error: Delete not possible\nDeleting %s is not allowed",
11644 path);
11645 return;
11646 }
11647
11648 /* Try to delete it. */
11649 if (mg_remove(conn, path) == 0) {
11650 /* Delete was successful: Return 204 without content. */
11651 mg_send_http_error(conn, 204, "%s", "");
11652 } else {
11653 /* Delete not successful (file locked). */
11654 mg_send_http_error(conn,
11655 423,
11656 "Error: Cannot delete file\nremove(%s): %s",
11657 path,
11658 strerror(ERRNO));
11659 }
11660 }
11661 #endif /* !NO_FILES */
11662
11663
11664 #if !defined(NO_FILESYSTEMS)
11665 static void
11666 send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
11667
11668
11669 static void
11670 do_ssi_include(struct mg_connection *conn,
11671 const char *ssi,
11672 char *tag,
11673 int include_level)
11674 {
11675 char file_name[MG_BUF_LEN], path[512], *p;
11676 struct mg_file file = STRUCT_FILE_INITIALIZER;
11677 size_t len;
11678 int truncated = 0;
11679
11680 if (conn == NULL) {
11681 return;
11682 }
11683
11684 /* sscanf() is safe here, since send_ssi_file() also uses buffer
11685 * of size MG_BUF_LEN to get the tag. So strlen(tag) is
11686 * always < MG_BUF_LEN. */
11687 if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
11688 /* File name is relative to the webserver root */
11689 file_name[511] = 0;
11690 (void)mg_snprintf(conn,
11691 &truncated,
11692 path,
11693 sizeof(path),
11694 "%s/%s",
11695 conn->dom_ctx->config[DOCUMENT_ROOT],
11696 file_name);
11697
11698 } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
11699 /* File name is relative to the webserver working directory
11700 * or it is absolute system path */
11701 file_name[511] = 0;
11702 (void)
11703 mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
11704
11705 } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
11706 || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
11707 /* File name is relative to the currect document */
11708 file_name[511] = 0;
11709 (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
11710
11711 if (!truncated) {
11712 if ((p = strrchr(path, '/')) != NULL) {
11713 p[1] = '\0';
11714 }
11715 len = strlen(path);
11716 (void)mg_snprintf(conn,
11717 &truncated,
11718 path + len,
11719 sizeof(path) - len,
11720 "%s",
11721 file_name);
11722 }
11723
11724 } else {
11725 mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
11726 return;
11727 }
11728
11729 if (truncated) {
11730 mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
11731 return;
11732 }
11733
11734 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
11735 mg_cry_internal(conn,
11736 "Cannot open SSI #include: [%s]: fopen(%s): %s",
11737 tag,
11738 path,
11739 strerror(ERRNO));
11740 } else {
11741 fclose_on_exec(&file.access, conn);
11742 if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
11743 strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
11744 path)
11745 > 0) {
11746 send_ssi_file(conn, path, &file, include_level + 1);
11747 } else {
11748 send_file_data(conn, &file, 0, INT64_MAX);
11749 }
11750 (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
11751 }
11752 }
11753
11754
11755 #if !defined(NO_POPEN)
11756 static void
11757 do_ssi_exec(struct mg_connection *conn, char *tag)
11758 {
11759 char cmd[1024] = "";
11760 struct mg_file file = STRUCT_FILE_INITIALIZER;
11761
11762 if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
11763 mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
11764 } else {
11765 cmd[1023] = 0;
11766 if ((file.access.fp = popen(cmd, "r")) == NULL) {
11767 mg_cry_internal(conn,
11768 "Cannot SSI #exec: [%s]: %s",
11769 cmd,
11770 strerror(ERRNO));
11771 } else {
11772 send_file_data(conn, &file, 0, INT64_MAX);
11773 pclose(file.access.fp);
11774 }
11775 }
11776 }
11777 #endif /* !NO_POPEN */
11778
11779
11780 static int
11781 mg_fgetc(struct mg_file *filep, int offset)
11782 {
11783 (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
11784
11785 if (filep == NULL) {
11786 return EOF;
11787 }
11788 #if defined(MG_USE_OPEN_FILE)
11789 if ((filep->access.membuf != NULL) && (offset >= 0)
11790 && (((unsigned int)(offset)) < filep->stat.size)) {
11791 return ((const unsigned char *)filep->access.membuf)[offset];
11792 } else /* else block below */
11793 #endif
11794 if (filep->access.fp != NULL) {
11795 return fgetc(filep->access.fp);
11796 } else {
11797 return EOF;
11798 }
11799 }
11800
11801
11802 static void
11803 send_ssi_file(struct mg_connection *conn,
11804 const char *path,
11805 struct mg_file *filep,
11806 int include_level)
11807 {
11808 char buf[MG_BUF_LEN];
11809 int ch, offset, len, in_tag, in_ssi_tag;
11810
11811 if (include_level > 10) {
11812 mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
11813 return;
11814 }
11815
11816 in_tag = in_ssi_tag = len = offset = 0;
11817
11818 /* Read file, byte by byte, and look for SSI include tags */
11819 while ((ch = mg_fgetc(filep, offset++)) != EOF) {
11820
11821 if (in_tag) {
11822 /* We are in a tag, either SSI tag or html tag */
11823
11824 if (ch == '>') {
11825 /* Tag is closing */
11826 buf[len++] = '>';
11827
11828 if (in_ssi_tag) {
11829 /* Handle SSI tag */
11830 buf[len] = 0;
11831
11832 if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
11833 do_ssi_include(conn, path, buf + 12, include_level + 1);
11834 #if !defined(NO_POPEN)
11835 } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
11836 do_ssi_exec(conn, buf + 9);
11837 #endif /* !NO_POPEN */
11838 } else {
11839 mg_cry_internal(conn,
11840 "%s: unknown SSI "
11841 "command: \"%s\"",
11842 path,
11843 buf);
11844 }
11845 len = 0;
11846 in_ssi_tag = in_tag = 0;
11847
11848 } else {
11849 /* Not an SSI tag */
11850 /* Flush buffer */
11851 (void)mg_write(conn, buf, (size_t)len);
11852 len = 0;
11853 in_tag = 0;
11854 }
11855
11856 } else {
11857 /* Tag is still open */
11858 buf[len++] = (char)(ch & 0xff);
11859
11860 if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
11861 /* All SSI tags start with <!--# */
11862 in_ssi_tag = 1;
11863 }
11864
11865 if ((len + 2) > (int)sizeof(buf)) {
11866 /* Tag to long for buffer */
11867 mg_cry_internal(conn, "%s: tag is too large", path);
11868 return;
11869 }
11870 }
11871
11872 } else {
11873
11874 /* We are not in a tag yet. */
11875 if (ch == '<') {
11876 /* Tag is opening */
11877 in_tag = 1;
11878
11879 if (len > 0) {
11880 /* Flush current buffer.
11881 * Buffer is filled with "len" bytes. */
11882 (void)mg_write(conn, buf, (size_t)len);
11883 }
11884 /* Store the < */
11885 len = 1;
11886 buf[0] = '<';
11887
11888 } else {
11889 /* No Tag */
11890 /* Add data to buffer */
11891 buf[len++] = (char)(ch & 0xff);
11892 /* Flush if buffer is full */
11893 if (len == (int)sizeof(buf)) {
11894 mg_write(conn, buf, (size_t)len);
11895 len = 0;
11896 }
11897 }
11898 }
11899 }
11900
11901 /* Send the rest of buffered data */
11902 if (len > 0) {
11903 mg_write(conn, buf, (size_t)len);
11904 }
11905 }
11906
11907
11908 static void
11909 handle_ssi_file_request(struct mg_connection *conn,
11910 const char *path,
11911 struct mg_file *filep)
11912 {
11913 char date[64];
11914 time_t curtime = time(NULL);
11915 const char *cors_orig_cfg;
11916 const char *cors1, *cors2, *cors3;
11917
11918 if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
11919 return;
11920 }
11921
11922 cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
11923 if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
11924 /* Cross-origin resource sharing (CORS). */
11925 cors1 = "Access-Control-Allow-Origin: ";
11926 cors2 = cors_orig_cfg;
11927 cors3 = "\r\n";
11928 } else {
11929 cors1 = cors2 = cors3 = "";
11930 }
11931
11932 if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
11933 /* File exists (precondition for calling this function),
11934 * but can not be opened by the server. */
11935 mg_send_http_error(conn,
11936 500,
11937 "Error: Cannot read file\nfopen(%s): %s",
11938 path,
11939 strerror(ERRNO));
11940 } else {
11941 conn->must_close = 1;
11942 gmt_time_string(date, sizeof(date), &curtime);
11943 fclose_on_exec(&filep->access, conn);
11944 mg_printf(conn, "HTTP/1.1 200 OK\r\n");
11945 send_no_cache_header(conn);
11946 send_additional_header(conn);
11947 mg_printf(conn,
11948 "%s%s%s"
11949 "Date: %s\r\n"
11950 "Content-Type: text/html\r\n"
11951 "Connection: %s\r\n\r\n",
11952 cors1,
11953 cors2,
11954 cors3,
11955 date,
11956 suggest_connection_header(conn));
11957 send_ssi_file(conn, path, filep, 0);
11958 (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
11959 }
11960 }
11961 #endif /* NO_FILESYSTEMS */
11962
11963
11964 #if !defined(NO_FILES)
11965 static void
11966 send_options(struct mg_connection *conn)
11967 {
11968 char date[64];
11969 time_t curtime = time(NULL);
11970
11971 if (!conn) {
11972 return;
11973 }
11974
11975 conn->status_code = 200;
11976 conn->must_close = 1;
11977 gmt_time_string(date, sizeof(date), &curtime);
11978
11979 /* We do not set a "Cache-Control" header here, but leave the default.
11980 * Since browsers do not send an OPTIONS request, we can not test the
11981 * effect anyway. */
11982 mg_printf(conn,
11983 "HTTP/1.1 200 OK\r\n"
11984 "Date: %s\r\n"
11985 "Connection: %s\r\n"
11986 "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
11987 "PROPFIND, MKCOL\r\n"
11988 "DAV: 1\r\n",
11989 date,
11990 suggest_connection_header(conn));
11991 send_additional_header(conn);
11992 mg_printf(conn, "\r\n");
11993 }
11994
11995
11996 /* Writes PROPFIND properties for a collection element */
11997 static int
11998 print_props(struct mg_connection *conn,
11999 const char *uri,
12000 const char *name,
12001 struct mg_file_stat *filep)
12002 {
12003 size_t href_size, i, j;
12004 int len;
12005 char *href, mtime[64];
12006
12007 if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
12008 return 0;
12009 }
12010 /* Estimate worst case size for encoding */
12011 href_size = (strlen(uri) + strlen(name)) * 3 + 1;
12012 href = (char *)mg_malloc(href_size);
12013 if (href == NULL) {
12014 return 0;
12015 }
12016 len = mg_url_encode(uri, href, href_size);
12017 if (len >= 0) {
12018 /* Append an extra string */
12019 mg_url_encode(name, href + len, href_size - (size_t)len);
12020 }
12021 /* Directory separator should be preserved. */
12022 for (i = j = 0; href[i]; j++) {
12023 if (!strncmp(href + i, "%2f", 3)) {
12024 href[j] = '/';
12025 i += 3;
12026 } else {
12027 href[j] = href[i++];
12028 }
12029 }
12030 href[j] = '\0';
12031
12032 gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
12033 mg_printf(conn,
12034 "<d:response>"
12035 "<d:href>%s</d:href>"
12036 "<d:propstat>"
12037 "<d:prop>"
12038 "<d:resourcetype>%s</d:resourcetype>"
12039 "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
12040 "<d:getlastmodified>%s</d:getlastmodified>"
12041 "</d:prop>"
12042 "<d:status>HTTP/1.1 200 OK</d:status>"
12043 "</d:propstat>"
12044 "</d:response>\n",
12045 href,
12046 filep->is_directory ? "<d:collection/>" : "",
12047 filep->size,
12048 mtime);
12049 mg_free(href);
12050 return 1;
12051 }
12052
12053
12054 static int
12055 print_dav_dir_entry(struct de *de, void *data)
12056 {
12057 struct mg_connection *conn = (struct mg_connection *)data;
12058 if (!de || !conn
12059 || !print_props(
12060 conn, conn->request_info.local_uri, de->file_name, &de->file)) {
12061 return -1;
12062 }
12063 return 0;
12064 }
12065
12066
12067 static void
12068 handle_propfind(struct mg_connection *conn,
12069 const char *path,
12070 struct mg_file_stat *filep)
12071 {
12072 const char *depth = mg_get_header(conn, "Depth");
12073 char date[64];
12074 time_t curtime = time(NULL);
12075
12076 gmt_time_string(date, sizeof(date), &curtime);
12077
12078 if (!conn || !path || !filep || !conn->dom_ctx) {
12079 return;
12080 }
12081
12082 conn->must_close = 1;
12083 conn->status_code = 207;
12084 mg_printf(conn,
12085 "HTTP/1.1 207 Multi-Status\r\n"
12086 "Date: %s\r\n",
12087 date);
12088 send_static_cache_header(conn);
12089 send_additional_header(conn);
12090 mg_printf(conn,
12091 "Connection: %s\r\n"
12092 "Content-Type: text/xml; charset=utf-8\r\n\r\n",
12093 suggest_connection_header(conn));
12094
12095 mg_printf(conn,
12096 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
12097 "<d:multistatus xmlns:d='DAV:'>\n");
12098
12099 /* Print properties for the requested resource itself */
12100 print_props(conn, conn->request_info.local_uri, "", filep);
12101
12102 /* If it is a directory, print directory entries too if Depth is not 0
12103 */
12104 if (filep->is_directory
12105 && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
12106 "yes")
12107 && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
12108 scan_directory(conn, path, conn, &print_dav_dir_entry);
12109 }
12110
12111 mg_printf(conn, "%s\n", "</d:multistatus>");
12112 }
12113 #endif
12114
12115 void
12116 mg_lock_connection(struct mg_connection *conn)
12117 {
12118 if (conn) {
12119 (void)pthread_mutex_lock(&conn->mutex);
12120 }
12121 }
12122
12123 void
12124 mg_unlock_connection(struct mg_connection *conn)
12125 {
12126 if (conn) {
12127 (void)pthread_mutex_unlock(&conn->mutex);
12128 }
12129 }
12130
12131 void
12132 mg_lock_context(struct mg_context *ctx)
12133 {
12134 if (ctx) {
12135 (void)pthread_mutex_lock(&ctx->nonce_mutex);
12136 }
12137 }
12138
12139 void
12140 mg_unlock_context(struct mg_context *ctx)
12141 {
12142 if (ctx) {
12143 (void)pthread_mutex_unlock(&ctx->nonce_mutex);
12144 }
12145 }
12146
12147
12148 #if defined(USE_LUA)
12149 #include "mod_lua.inl"
12150 #endif /* USE_LUA */
12151
12152 #if defined(USE_DUKTAPE)
12153 #include "mod_duktape.inl"
12154 #endif /* USE_DUKTAPE */
12155
12156 #if defined(USE_WEBSOCKET)
12157
12158 #if !defined(NO_SSL_DL)
12159 #define SHA_API static
12160 #include "sha1.inl"
12161 #endif
12162
12163 static int
12164 send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
12165 {
12166 static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
12167 char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
12168 SHA_CTX sha_ctx;
12169 int truncated;
12170
12171 /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
12172 mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
12173 if (truncated) {
12174 conn->must_close = 1;
12175 return 0;
12176 }
12177
12178 DEBUG_TRACE("%s", "Send websocket handshake");
12179
12180 SHA1_Init(&sha_ctx);
12181 SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
12182 SHA1_Final((unsigned char *)sha, &sha_ctx);
12183 base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
12184 mg_printf(conn,
12185 "HTTP/1.1 101 Switching Protocols\r\n"
12186 "Upgrade: websocket\r\n"
12187 "Connection: Upgrade\r\n"
12188 "Sec-WebSocket-Accept: %s\r\n",
12189 b64_sha);
12190 if (conn->request_info.acceptedWebSocketSubprotocol) {
12191 mg_printf(conn,
12192 "Sec-WebSocket-Protocol: %s\r\n\r\n",
12193 conn->request_info.acceptedWebSocketSubprotocol);
12194 } else {
12195 mg_printf(conn, "%s", "\r\n");
12196 }
12197
12198 return 1;
12199 }
12200
12201
12202 #if !defined(MG_MAX_UNANSWERED_PING)
12203 /* Configuration of the maximum number of websocket PINGs that might
12204 * stay unanswered before the connection is considered broken.
12205 * Note: The name of this define may still change (until it is
12206 * defined as a compile parameter in a documentation).
12207 */
12208 #define MG_MAX_UNANSWERED_PING (5)
12209 #endif
12210
12211
12212 static void
12213 read_websocket(struct mg_connection *conn,
12214 mg_websocket_data_handler ws_data_handler,
12215 void *callback_data)
12216 {
12217 /* Pointer to the beginning of the portion of the incoming websocket
12218 * message queue.
12219 * The original websocket upgrade request is never removed, so the queue
12220 * begins after it. */
12221 unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
12222 int n, error, exit_by_callback;
12223 int ret;
12224
12225 /* body_len is the length of the entire queue in bytes
12226 * len is the length of the current message
12227 * data_len is the length of the current message's data payload
12228 * header_len is the length of the current message's header */
12229 size_t i, len, mask_len = 0, header_len, body_len;
12230 uint64_t data_len = 0;
12231
12232 /* "The masking key is a 32-bit value chosen at random by the client."
12233 * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
12234 */
12235 unsigned char mask[4];
12236
12237 /* data points to the place where the message is stored when passed to
12238 * the websocket_data callback. This is either mem on the stack, or a
12239 * dynamically allocated buffer if it is too large. */
12240 unsigned char mem[4096];
12241 unsigned char mop; /* mask flag and opcode */
12242
12243
12244 /* Variables used for connection monitoring */
12245 double timeout = -1.0;
12246 int enable_ping_pong = 0;
12247 int ping_count = 0;
12248
12249 if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
12250 enable_ping_pong =
12251 !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
12252 "yes");
12253 }
12254
12255 if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
12256 timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
12257 }
12258 if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
12259 timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
12260 }
12261
12262 /* Enter data processing loop */
12263 DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
12264 conn->request_info.remote_addr,
12265 conn->request_info.remote_port);
12266 conn->in_websocket_handling = 1;
12267 mg_set_thread_name("wsock");
12268
12269 /* Loop continuously, reading messages from the socket, invoking the
12270 * callback, and waiting repeatedly until an error occurs. */
12271 while (!conn->phys_ctx->stop_flag && !conn->must_close) {
12272 header_len = 0;
12273 DEBUG_ASSERT(conn->data_len >= conn->request_len);
12274 if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
12275 len = buf[1] & 127;
12276 mask_len = (buf[1] & 128) ? 4 : 0;
12277 if ((len < 126) && (body_len >= mask_len)) {
12278 /* inline 7-bit length field */
12279 data_len = len;
12280 header_len = 2 + mask_len;
12281 } else if ((len == 126) && (body_len >= (4 + mask_len))) {
12282 /* 16-bit length field */
12283 header_len = 4 + mask_len;
12284 data_len = ((((size_t)buf[2]) << 8) + buf[3]);
12285 } else if (body_len >= (10 + mask_len)) {
12286 /* 64-bit length field */
12287 uint32_t l1, l2;
12288 memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
12289 memcpy(&l2, &buf[6], 4);
12290 header_len = 10 + mask_len;
12291 data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
12292
12293 if (data_len > (uint64_t)0x7FFF0000ul) {
12294 /* no can do */
12295 mg_cry_internal(
12296 conn,
12297 "%s",
12298 "websocket out of memory; closing connection");
12299 break;
12300 }
12301 }
12302 }
12303
12304 if ((header_len > 0) && (body_len >= header_len)) {
12305 /* Allocate space to hold websocket payload */
12306 unsigned char *data = mem;
12307
12308 if ((size_t)data_len > (size_t)sizeof(mem)) {
12309 data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
12310 conn->phys_ctx);
12311 if (data == NULL) {
12312 /* Allocation failed, exit the loop and then close the
12313 * connection */
12314 mg_cry_internal(
12315 conn,
12316 "%s",
12317 "websocket out of memory; closing connection");
12318 break;
12319 }
12320 }
12321
12322 /* Copy the mask before we shift the queue and destroy it */
12323 if (mask_len > 0) {
12324 memcpy(mask, buf + header_len - mask_len, sizeof(mask));
12325 } else {
12326 memset(mask, 0, sizeof(mask));
12327 }
12328
12329 /* Read frame payload from the first message in the queue into
12330 * data and advance the queue by moving the memory in place. */
12331 DEBUG_ASSERT(body_len >= header_len);
12332 if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
12333 mop = buf[0]; /* current mask and opcode */
12334 /* Overflow case */
12335 len = body_len - header_len;
12336 memcpy(data, buf + header_len, len);
12337 error = 0;
12338 while ((uint64_t)len < data_len) {
12339 n = pull_inner(NULL,
12340 conn,
12341 (char *)(data + len),
12342 (int)(data_len - len),
12343 timeout);
12344 if (n <= -2) {
12345 error = 1;
12346 break;
12347 } else if (n > 0) {
12348 len += (size_t)n;
12349 } else {
12350 /* Timeout: should retry */
12351 /* TODO: retry condition */
12352 }
12353 }
12354 if (error) {
12355 mg_cry_internal(
12356 conn,
12357 "%s",
12358 "Websocket pull failed; closing connection");
12359 if (data != mem) {
12360 mg_free(data);
12361 }
12362 break;
12363 }
12364
12365 conn->data_len = conn->request_len;
12366
12367 } else {
12368
12369 mop = buf[0]; /* current mask and opcode, overwritten by
12370 * memmove() */
12371
12372 /* Length of the message being read at the front of the
12373 * queue. Cast to 31 bit is OK, since we limited
12374 * data_len before. */
12375 len = (size_t)data_len + header_len;
12376
12377 /* Copy the data payload into the data pointer for the
12378 * callback. Cast to 31 bit is OK, since we
12379 * limited data_len */
12380 memcpy(data, buf + header_len, (size_t)data_len);
12381
12382 /* Move the queue forward len bytes */
12383 memmove(buf, buf + len, body_len - len);
12384
12385 /* Mark the queue as advanced */
12386 conn->data_len -= (int)len;
12387 }
12388
12389 /* Apply mask if necessary */
12390 if (mask_len > 0) {
12391 for (i = 0; i < (size_t)data_len; i++) {
12392 data[i] ^= mask[i & 3];
12393 }
12394 }
12395
12396 exit_by_callback = 0;
12397 if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
12398 /* filter PONG messages */
12399 DEBUG_TRACE("PONG from %s:%u",
12400 conn->request_info.remote_addr,
12401 conn->request_info.remote_port);
12402 /* No unanwered PINGs left */
12403 ping_count = 0;
12404 } else if (enable_ping_pong
12405 && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
12406 /* reply PING messages */
12407 DEBUG_TRACE("Reply PING from %s:%u",
12408 conn->request_info.remote_addr,
12409 conn->request_info.remote_port);
12410 ret = mg_websocket_write(conn,
12411 MG_WEBSOCKET_OPCODE_PONG,
12412 (char *)data,
12413 (size_t)data_len);
12414 if (ret <= 0) {
12415 /* Error: send failed */
12416 DEBUG_TRACE("Reply PONG failed (%i)", ret);
12417 break;
12418 }
12419
12420
12421 } else {
12422 /* Exit the loop if callback signals to exit (server side),
12423 * or "connection close" opcode received (client side). */
12424 if ((ws_data_handler != NULL)
12425 && !ws_data_handler(conn,
12426 mop,
12427 (char *)data,
12428 (size_t)data_len,
12429 callback_data)) {
12430 exit_by_callback = 1;
12431 }
12432 }
12433
12434 /* It a buffer has been allocated, free it again */
12435 if (data != mem) {
12436 mg_free(data);
12437 }
12438
12439 if (exit_by_callback) {
12440 DEBUG_TRACE("Callback requests to close connection from %s:%u",
12441 conn->request_info.remote_addr,
12442 conn->request_info.remote_port);
12443 break;
12444 }
12445 if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
12446 /* Opcode == 8, connection close */
12447 DEBUG_TRACE("Message requests to close connection from %s:%u",
12448 conn->request_info.remote_addr,
12449 conn->request_info.remote_port);
12450 break;
12451 }
12452
12453 /* Not breaking the loop, process next websocket frame. */
12454 } else {
12455 /* Read from the socket into the next available location in the
12456 * message queue. */
12457 n = pull_inner(NULL,
12458 conn,
12459 conn->buf + conn->data_len,
12460 conn->buf_size - conn->data_len,
12461 timeout);
12462 if (n <= -2) {
12463 /* Error, no bytes read */
12464 DEBUG_TRACE("PULL from %s:%u failed",
12465 conn->request_info.remote_addr,
12466 conn->request_info.remote_port);
12467 break;
12468 }
12469 if (n > 0) {
12470 conn->data_len += n;
12471 /* Reset open PING count */
12472 ping_count = 0;
12473 } else {
12474 if (!conn->phys_ctx->stop_flag && !conn->must_close) {
12475 if (ping_count > MG_MAX_UNANSWERED_PING) {
12476 /* Stop sending PING */
12477 DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
12478 "- closing connection",
12479 ping_count,
12480 conn->request_info.remote_addr,
12481 conn->request_info.remote_port);
12482 break;
12483 }
12484 if (enable_ping_pong) {
12485 /* Send Websocket PING message */
12486 DEBUG_TRACE("PING to %s:%u",
12487 conn->request_info.remote_addr,
12488 conn->request_info.remote_port);
12489 ret = mg_websocket_write(conn,
12490 MG_WEBSOCKET_OPCODE_PING,
12491 NULL,
12492 0);
12493
12494 if (ret <= 0) {
12495 /* Error: send failed */
12496 DEBUG_TRACE("Send PING failed (%i)", ret);
12497 break;
12498 }
12499 ping_count++;
12500 }
12501 }
12502 /* Timeout: should retry */
12503 /* TODO: get timeout def */
12504 }
12505 }
12506 }
12507
12508 /* Leave data processing loop */
12509 mg_set_thread_name("worker");
12510 conn->in_websocket_handling = 0;
12511 DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
12512 conn->request_info.remote_addr,
12513 conn->request_info.remote_port);
12514 }
12515
12516
12517 static int
12518 mg_websocket_write_exec(struct mg_connection *conn,
12519 int opcode,
12520 const char *data,
12521 size_t dataLen,
12522 uint32_t masking_key)
12523 {
12524 unsigned char header[14];
12525 size_t headerLen;
12526 int retval;
12527
12528 #if defined(GCC_DIAGNOSTIC)
12529 /* Disable spurious conversion warning for GCC */
12530 #pragma GCC diagnostic push
12531 #pragma GCC diagnostic ignored "-Wconversion"
12532 #endif
12533
12534 header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
12535
12536 #if defined(GCC_DIAGNOSTIC)
12537 #pragma GCC diagnostic pop
12538 #endif
12539
12540 /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
12541 if (dataLen < 126) {
12542 /* inline 7-bit length field */
12543 header[1] = (unsigned char)dataLen;
12544 headerLen = 2;
12545 } else if (dataLen <= 0xFFFF) {
12546 /* 16-bit length field */
12547 uint16_t len = htons((uint16_t)dataLen);
12548 header[1] = 126;
12549 memcpy(header + 2, &len, 2);
12550 headerLen = 4;
12551 } else {
12552 /* 64-bit length field */
12553 uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
12554 uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
12555 header[1] = 127;
12556 memcpy(header + 2, &len1, 4);
12557 memcpy(header + 6, &len2, 4);
12558 headerLen = 10;
12559 }
12560
12561 if (masking_key) {
12562 /* add mask */
12563 header[1] |= 0x80;
12564 memcpy(header + headerLen, &masking_key, 4);
12565 headerLen += 4;
12566 }
12567
12568 /* Note that POSIX/Winsock's send() is threadsafe
12569 * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
12570 * but mongoose's mg_printf/mg_write is not (because of the loop in
12571 * push(), although that is only a problem if the packet is large or
12572 * outgoing buffer is full). */
12573
12574 /* TODO: Check if this lock should be moved to user land.
12575 * Currently the server sets this lock for websockets, but
12576 * not for any other connection. It must be set for every
12577 * conn read/written by more than one thread, no matter if
12578 * it is a websocket or regular connection. */
12579 (void)mg_lock_connection(conn);
12580
12581 retval = mg_write(conn, header, headerLen);
12582 if (retval != (int)headerLen) {
12583 /* Did not send complete header */
12584 retval = -1;
12585 } else {
12586 if (dataLen > 0) {
12587 retval = mg_write(conn, data, dataLen);
12588 }
12589 /* if dataLen == 0, the header length (2) is returned */
12590 }
12591
12592 /* TODO: Remove this unlock as well, when lock is removed. */
12593 mg_unlock_connection(conn);
12594
12595 return retval;
12596 }
12597
12598 int
12599 mg_websocket_write(struct mg_connection *conn,
12600 int opcode,
12601 const char *data,
12602 size_t dataLen)
12603 {
12604 return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
12605 }
12606
12607
12608 static void
12609 mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
12610 {
12611 size_t i = 0;
12612
12613 i = 0;
12614 if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
12615 /* Convert in 32 bit words, if data is 4 byte aligned */
12616 while (i < (in_len - 3)) {
12617 *(uint32_t *)(void *)(out + i) =
12618 *(uint32_t *)(void *)(in + i) ^ masking_key;
12619 i += 4;
12620 }
12621 }
12622 if (i != in_len) {
12623 /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
12624 while (i < in_len) {
12625 *(uint8_t *)(void *)(out + i) =
12626 *(uint8_t *)(void *)(in + i)
12627 ^ *(((uint8_t *)&masking_key) + (i % 4));
12628 i++;
12629 }
12630 }
12631 }
12632
12633
12634 int
12635 mg_websocket_client_write(struct mg_connection *conn,
12636 int opcode,
12637 const char *data,
12638 size_t dataLen)
12639 {
12640 int retval = -1;
12641 char *masked_data =
12642 (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
12643 uint32_t masking_key = 0;
12644
12645 if (masked_data == NULL) {
12646 /* Return -1 in an error case */
12647 mg_cry_internal(conn,
12648 "%s",
12649 "Cannot allocate buffer for masked websocket response: "
12650 "Out of memory");
12651 return -1;
12652 }
12653
12654 do {
12655 /* Get a masking key - but not 0 */
12656 masking_key = (uint32_t)get_random();
12657 } while (masking_key == 0);
12658
12659 mask_data(data, dataLen, masking_key, masked_data);
12660
12661 retval = mg_websocket_write_exec(
12662 conn, opcode, masked_data, dataLen, masking_key);
12663 mg_free(masked_data);
12664
12665 return retval;
12666 }
12667
12668
12669 static void
12670 handle_websocket_request(struct mg_connection *conn,
12671 const char *path,
12672 int is_callback_resource,
12673 struct mg_websocket_subprotocols *subprotocols,
12674 mg_websocket_connect_handler ws_connect_handler,
12675 mg_websocket_ready_handler ws_ready_handler,
12676 mg_websocket_data_handler ws_data_handler,
12677 mg_websocket_close_handler ws_close_handler,
12678 void *cbData)
12679 {
12680 const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
12681 const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
12682 ptrdiff_t lua_websock = 0;
12683
12684 #if !defined(USE_LUA)
12685 (void)path;
12686 #endif
12687
12688 /* Step 1: Check websocket protocol version. */
12689 /* Step 1.1: Check Sec-WebSocket-Key. */
12690 if (!websock_key) {
12691 /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
12692 * requires a Sec-WebSocket-Key header.
12693 */
12694 /* It could be the hixie draft version
12695 * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
12696 */
12697 const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
12698 const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
12699 char key3[8];
12700
12701 if ((key1 != NULL) && (key2 != NULL)) {
12702 /* This version uses 8 byte body data in a GET request */
12703 conn->content_len = 8;
12704 if (8 == mg_read(conn, key3, 8)) {
12705 /* This is the hixie version */
12706 mg_send_http_error(conn,
12707 426,
12708 "%s",
12709 "Protocol upgrade to RFC 6455 required");
12710 return;
12711 }
12712 }
12713 /* This is an unknown version */
12714 mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
12715 return;
12716 }
12717
12718 /* Step 1.2: Check websocket protocol version. */
12719 /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
12720 if ((version == NULL) || (strcmp(version, "13") != 0)) {
12721 /* Reject wrong versions */
12722 mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
12723 return;
12724 }
12725
12726 /* Step 1.3: Could check for "Host", but we do not really nead this
12727 * value for anything, so just ignore it. */
12728
12729 /* Step 2: If a callback is responsible, call it. */
12730 if (is_callback_resource) {
12731 /* Step 2.1 check and select subprotocol */
12732 const char *protocols[64]; // max 64 headers
12733 int nbSubprotocolHeader = get_req_headers(&conn->request_info,
12734 "Sec-WebSocket-Protocol",
12735 protocols,
12736 64);
12737 if ((nbSubprotocolHeader > 0) && subprotocols) {
12738 int cnt = 0;
12739 int idx;
12740 unsigned long len;
12741 const char *sep, *curSubProtocol,
12742 *acceptedWebSocketSubprotocol = NULL;
12743
12744
12745 /* look for matching subprotocol */
12746 do {
12747 const char *protocol = protocols[cnt];
12748
12749 do {
12750 sep = strchr(protocol, ',');
12751 curSubProtocol = protocol;
12752 len = sep ? (unsigned long)(sep - protocol)
12753 : (unsigned long)strlen(protocol);
12754 while (sep && isspace((unsigned char)*++sep))
12755 ; // ignore leading whitespaces
12756 protocol = sep;
12757
12758
12759 for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
12760 if ((strlen(subprotocols->subprotocols[idx]) == len)
12761 && (strncmp(curSubProtocol,
12762 subprotocols->subprotocols[idx],
12763 len)
12764 == 0)) {
12765 acceptedWebSocketSubprotocol =
12766 subprotocols->subprotocols[idx];
12767 break;
12768 }
12769 }
12770 } while (sep && !acceptedWebSocketSubprotocol);
12771 } while (++cnt < nbSubprotocolHeader
12772 && !acceptedWebSocketSubprotocol);
12773
12774 conn->request_info.acceptedWebSocketSubprotocol =
12775 acceptedWebSocketSubprotocol;
12776
12777 } else if (nbSubprotocolHeader > 0) {
12778 /* keep legacy behavior */
12779 const char *protocol = protocols[0];
12780
12781 /* The protocol is a comma separated list of names. */
12782 /* The server must only return one value from this list. */
12783 /* First check if it is a list or just a single value. */
12784 const char *sep = strrchr(protocol, ',');
12785 if (sep == NULL) {
12786 /* Just a single protocol -> accept it. */
12787 conn->request_info.acceptedWebSocketSubprotocol = protocol;
12788 } else {
12789 /* Multiple protocols -> accept the last one. */
12790 /* This is just a quick fix if the client offers multiple
12791 * protocols. The handler should have a list of accepted
12792 * protocols on his own
12793 * and use it to select one protocol among those the client
12794 * has
12795 * offered.
12796 */
12797 while (isspace((unsigned char)*++sep)) {
12798 ; /* ignore leading whitespaces */
12799 }
12800 conn->request_info.acceptedWebSocketSubprotocol = sep;
12801 }
12802 }
12803
12804 if ((ws_connect_handler != NULL)
12805 && (ws_connect_handler(conn, cbData) != 0)) {
12806 /* C callback has returned non-zero, do not proceed with
12807 * handshake.
12808 */
12809 /* Note that C callbacks are no longer called when Lua is
12810 * responsible, so C can no longer filter callbacks for Lua. */
12811 return;
12812 }
12813 }
12814
12815 #if defined(USE_LUA)
12816 /* Step 3: No callback. Check if Lua is responsible. */
12817 else {
12818 /* Step 3.1: Check if Lua is responsible. */
12819 if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
12820 lua_websock = match_prefix(
12821 conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
12822 strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
12823 path);
12824 }
12825
12826 if (lua_websock) {
12827 /* Step 3.2: Lua is responsible: call it. */
12828 conn->lua_websocket_state = lua_websocket_new(path, conn);
12829 if (!conn->lua_websocket_state) {
12830 /* Lua rejected the new client */
12831 return;
12832 }
12833 }
12834 }
12835 #endif
12836
12837 /* Step 4: Check if there is a responsible websocket handler. */
12838 if (!is_callback_resource && !lua_websock) {
12839 /* There is no callback, and Lua is not responsible either. */
12840 /* Reply with a 404 Not Found. We are still at a standard
12841 * HTTP request here, before the websocket handshake, so
12842 * we can still send standard HTTP error replies. */
12843 mg_send_http_error(conn, 404, "%s", "Not found");
12844 return;
12845 }
12846
12847 /* Step 5: The websocket connection has been accepted */
12848 if (!send_websocket_handshake(conn, websock_key)) {
12849 mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
12850 return;
12851 }
12852
12853 /* Step 6: Call the ready handler */
12854 if (is_callback_resource) {
12855 if (ws_ready_handler != NULL) {
12856 ws_ready_handler(conn, cbData);
12857 }
12858 #if defined(USE_LUA)
12859 } else if (lua_websock) {
12860 if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
12861 /* the ready handler returned false */
12862 return;
12863 }
12864 #endif
12865 }
12866
12867 /* Step 7: Enter the read loop */
12868 if (is_callback_resource) {
12869 read_websocket(conn, ws_data_handler, cbData);
12870 #if defined(USE_LUA)
12871 } else if (lua_websock) {
12872 read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
12873 #endif
12874 }
12875
12876 /* Step 8: Call the close handler */
12877 if (ws_close_handler) {
12878 ws_close_handler(conn, cbData);
12879 }
12880 }
12881
12882
12883 static int
12884 is_websocket_protocol(const struct mg_connection *conn)
12885 {
12886 const char *upgrade, *connection;
12887
12888 /* A websocket protocoll has the following HTTP headers:
12889 *
12890 * Connection: Upgrade
12891 * Upgrade: Websocket
12892 */
12893
12894 upgrade = mg_get_header(conn, "Upgrade");
12895 if (upgrade == NULL) {
12896 return 0; /* fail early, don't waste time checking other header
12897 * fields
12898 */
12899 }
12900 DEBUG_TRACE("Upgrade: %s", upgrade);
12901 if (!mg_strcasestr(upgrade, "websocket")) {
12902 return 0;
12903 }
12904
12905 connection = mg_get_header(conn, "Connection");
12906 if (connection == NULL) {
12907 return 0;
12908 }
12909 if (!mg_strcasestr(connection, "upgrade")) {
12910 return 0;
12911 }
12912
12913 /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
12914 * "Sec-WebSocket-Version" are also required.
12915 * Don't check them here, since even an unsupported websocket protocol
12916 * request still IS a websocket request (in contrast to a standard HTTP
12917 * request). It will fail later in handle_websocket_request.
12918 */
12919
12920 return 1;
12921 }
12922 #endif /* !USE_WEBSOCKET */
12923
12924
12925 static int
12926 isbyte(int n)
12927 {
12928 return (n >= 0) && (n <= 255);
12929 }
12930
12931
12932 static int
12933 parse_net(const char *spec, uint32_t *net, uint32_t *mask)
12934 {
12935 int n, a, b, c, d, slash = 32, len = 0;
12936
12937 if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
12938 || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
12939 && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
12940 && (slash < 33)) {
12941 len = n;
12942 *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
12943 | (uint32_t)d;
12944 *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
12945 }
12946
12947 return len;
12948 }
12949
12950
12951 static int
12952 set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
12953 {
12954 int throttle = 0;
12955 struct vec vec, val;
12956 uint32_t net, mask;
12957 char mult;
12958 double v;
12959
12960 while ((spec = next_option(spec, &vec, &val)) != NULL) {
12961 mult = ',';
12962 if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
12963 || (v < 0)
12964 || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
12965 && (mult != ','))) {
12966 continue;
12967 }
12968 v *= (lowercase(&mult) == 'k')
12969 ? 1024
12970 : ((lowercase(&mult) == 'm') ? 1048576 : 1);
12971 if (vec.len == 1 && vec.ptr[0] == '*') {
12972 throttle = (int)v;
12973 } else if (parse_net(vec.ptr, &net, &mask) > 0) {
12974 if ((remote_ip & mask) == net) {
12975 throttle = (int)v;
12976 }
12977 } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
12978 throttle = (int)v;
12979 }
12980 }
12981
12982 return throttle;
12983 }
12984
12985
12986 static uint32_t
12987 get_remote_ip(const struct mg_connection *conn)
12988 {
12989 if (!conn) {
12990 return 0;
12991 }
12992 return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
12993 }
12994
12995
12996 /* The mg_upload function is superseeded by mg_handle_form_request. */
12997 #include "handle_form.inl"
12998
12999
13000 #if defined(MG_LEGACY_INTERFACE)
13001 /* Implement the deprecated mg_upload function by calling the new
13002 * mg_handle_form_request function. While mg_upload could only handle
13003 * HTML forms sent as POST request in multipart/form-data format
13004 * containing only file input elements, mg_handle_form_request can
13005 * handle all form input elements and all standard request methods. */
13006 struct mg_upload_user_data {
13007 struct mg_connection *conn;
13008 const char *destination_dir;
13009 int num_uploaded_files;
13010 };
13011
13012
13013 /* Helper function for deprecated mg_upload. */
13014 static int
13015 mg_upload_field_found(const char *key,
13016 const char *filename,
13017 char *path,
13018 size_t pathlen,
13019 void *user_data)
13020 {
13021 int truncated = 0;
13022 struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
13023 (void)key;
13024
13025 if (!filename) {
13026 mg_cry_internal(fud->conn, "%s: No filename set", __func__);
13027 return FORM_FIELD_STORAGE_ABORT;
13028 }
13029 mg_snprintf(fud->conn,
13030 &truncated,
13031 path,
13032 pathlen - 1,
13033 "%s/%s",
13034 fud->destination_dir,
13035 filename);
13036 if (truncated) {
13037 mg_cry_internal(fud->conn, "%s: File path too long", __func__);
13038 return FORM_FIELD_STORAGE_ABORT;
13039 }
13040 return FORM_FIELD_STORAGE_STORE;
13041 }
13042
13043
13044 /* Helper function for deprecated mg_upload. */
13045 static int
13046 mg_upload_field_get(const char *key,
13047 const char *value,
13048 size_t value_size,
13049 void *user_data)
13050 {
13051 /* Function should never be called */
13052 (void)key;
13053 (void)value;
13054 (void)value_size;
13055 (void)user_data;
13056
13057 return 0;
13058 }
13059
13060
13061 /* Helper function for deprecated mg_upload. */
13062 static int
13063 mg_upload_field_stored(const char *path, long long file_size, void *user_data)
13064 {
13065 struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
13066 (void)file_size;
13067
13068 fud->num_uploaded_files++;
13069 fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
13070
13071 return 0;
13072 }
13073
13074
13075 /* Deprecated function mg_upload - use mg_handle_form_request instead. */
13076 int
13077 mg_upload(struct mg_connection *conn, const char *destination_dir)
13078 {
13079 struct mg_upload_user_data fud = {conn, destination_dir, 0};
13080 struct mg_form_data_handler fdh = {mg_upload_field_found,
13081 mg_upload_field_get,
13082 mg_upload_field_stored,
13083 0};
13084 int ret;
13085
13086 fdh.user_data = (void *)&fud;
13087 ret = mg_handle_form_request(conn, &fdh);
13088
13089 if (ret < 0) {
13090 mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
13091 }
13092
13093 return fud.num_uploaded_files;
13094 }
13095 #endif
13096
13097
13098 static int
13099 get_first_ssl_listener_index(const struct mg_context *ctx)
13100 {
13101 unsigned int i;
13102 int idx = -1;
13103 if (ctx) {
13104 for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
13105 idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
13106 }
13107 }
13108 return idx;
13109 }
13110
13111
13112 /* Return host (without port) */
13113 /* Use mg_free to free the result */
13114 static const char *
13115 alloc_get_host(struct mg_connection *conn)
13116 {
13117 char buf[1025];
13118 size_t buflen = sizeof(buf);
13119 const char *host_header = get_header(conn->request_info.http_headers,
13120 conn->request_info.num_headers,
13121 "Host");
13122 char *host;
13123
13124 if (host_header != NULL) {
13125 char *pos;
13126
13127 /* Create a local copy of the "Host" header, since it might be
13128 * modified here. */
13129 mg_strlcpy(buf, host_header, buflen);
13130 buf[buflen - 1] = '\0';
13131 host = buf;
13132 while (isspace((unsigned char)*host)) {
13133 host++;
13134 }
13135
13136 /* If the "Host" is an IPv6 address, like [::1], parse until ]
13137 * is found. */
13138 if (*host == '[') {
13139 pos = strchr(host, ']');
13140 if (!pos) {
13141 /* Malformed hostname starts with '[', but no ']' found */
13142 DEBUG_TRACE("%s", "Host name format error '[' without ']'");
13143 return NULL;
13144 }
13145 /* terminate after ']' */
13146 pos[1] = 0;
13147 } else {
13148 /* Otherwise, a ':' separates hostname and port number */
13149 pos = strchr(host, ':');
13150 if (pos != NULL) {
13151 *pos = '\0';
13152 }
13153 }
13154
13155 if (conn->ssl) {
13156 /* This is a HTTPS connection, maybe we have a hostname
13157 * from SNI (set in ssl_servername_callback). */
13158 const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
13159 if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
13160 /* We are not using the default domain */
13161 if (mg_strcasecmp(host, sslhost)) {
13162 /* Mismatch between SNI domain and HTTP domain */
13163 DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
13164 sslhost,
13165 host);
13166 return NULL;
13167 }
13168 }
13169 DEBUG_TRACE("HTTPS Host: %s", host);
13170
13171 } else {
13172 struct mg_domain_context *dom = &(conn->phys_ctx->dd);
13173 while (dom) {
13174 if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
13175
13176 /* Found matching domain */
13177 DEBUG_TRACE("HTTP domain %s found",
13178 dom->config[AUTHENTICATION_DOMAIN]);
13179
13180 /* TODO: Check if this is a HTTP or HTTPS domain */
13181 conn->dom_ctx = dom;
13182 break;
13183 }
13184 dom = dom->next;
13185 }
13186
13187 DEBUG_TRACE("HTTP Host: %s", host);
13188 }
13189
13190 } else {
13191 sockaddr_to_string(buf, buflen, &conn->client.lsa);
13192 host = buf;
13193
13194 DEBUG_TRACE("IP: %s", host);
13195 }
13196
13197 return mg_strdup_ctx(host, conn->phys_ctx);
13198 }
13199
13200
13201 static void
13202 redirect_to_https_port(struct mg_connection *conn, int ssl_index)
13203 {
13204 char target_url[MG_BUF_LEN];
13205 int truncated = 0;
13206
13207 conn->must_close = 1;
13208
13209 /* Send host, port, uri and (if it exists) ?query_string */
13210 if (conn->host) {
13211
13212 /* Use "308 Permanent Redirect" */
13213 int redirect_code = 308;
13214
13215 /* Create target URL */
13216 mg_snprintf(
13217 conn,
13218 &truncated,
13219 target_url,
13220 sizeof(target_url),
13221 "https://%s:%d%s%s%s",
13222
13223 conn->host,
13224 #if defined(USE_IPV6)
13225 (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
13226 == AF_INET6)
13227 ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
13228 .lsa.sin6.sin6_port)
13229 :
13230 #endif
13231 (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
13232 .lsa.sin.sin_port),
13233 conn->request_info.local_uri,
13234 (conn->request_info.query_string == NULL) ? "" : "?",
13235 (conn->request_info.query_string == NULL)
13236 ? ""
13237 : conn->request_info.query_string);
13238
13239 /* Check overflow in location buffer (will not occur if MG_BUF_LEN
13240 * is used as buffer size) */
13241 if (truncated) {
13242 mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
13243 return;
13244 }
13245
13246 /* Use redirect helper function */
13247 mg_send_http_redirect(conn, target_url, redirect_code);
13248 }
13249 }
13250
13251
13252 static void
13253 handler_info_acquire(struct mg_handler_info *handler_info)
13254 {
13255 pthread_mutex_lock(&handler_info->refcount_mutex);
13256 handler_info->refcount++;
13257 pthread_mutex_unlock(&handler_info->refcount_mutex);
13258 }
13259
13260
13261 static void
13262 handler_info_release(struct mg_handler_info *handler_info)
13263 {
13264 pthread_mutex_lock(&handler_info->refcount_mutex);
13265 handler_info->refcount--;
13266 pthread_cond_signal(&handler_info->refcount_cond);
13267 pthread_mutex_unlock(&handler_info->refcount_mutex);
13268 }
13269
13270
13271 static void
13272 handler_info_wait_unused(struct mg_handler_info *handler_info)
13273 {
13274 pthread_mutex_lock(&handler_info->refcount_mutex);
13275 while (handler_info->refcount) {
13276 pthread_cond_wait(&handler_info->refcount_cond,
13277 &handler_info->refcount_mutex);
13278 }
13279 pthread_mutex_unlock(&handler_info->refcount_mutex);
13280 }
13281
13282
13283 static void
13284 mg_set_handler_type(struct mg_context *phys_ctx,
13285 struct mg_domain_context *dom_ctx,
13286 const char *uri,
13287 int handler_type,
13288 int is_delete_request,
13289 mg_request_handler handler,
13290 struct mg_websocket_subprotocols *subprotocols,
13291 mg_websocket_connect_handler connect_handler,
13292 mg_websocket_ready_handler ready_handler,
13293 mg_websocket_data_handler data_handler,
13294 mg_websocket_close_handler close_handler,
13295 mg_authorization_handler auth_handler,
13296 void *cbdata)
13297 {
13298 struct mg_handler_info *tmp_rh, **lastref;
13299 size_t urilen = strlen(uri);
13300
13301 if (handler_type == WEBSOCKET_HANDLER) {
13302 DEBUG_ASSERT(handler == NULL);
13303 DEBUG_ASSERT(is_delete_request || connect_handler != NULL
13304 || ready_handler != NULL || data_handler != NULL
13305 || close_handler != NULL);
13306
13307 DEBUG_ASSERT(auth_handler == NULL);
13308 if (handler != NULL) {
13309 return;
13310 }
13311 if (!is_delete_request && (connect_handler == NULL)
13312 && (ready_handler == NULL) && (data_handler == NULL)
13313 && (close_handler == NULL)) {
13314 return;
13315 }
13316 if (auth_handler != NULL) {
13317 return;
13318 }
13319 } else if (handler_type == REQUEST_HANDLER) {
13320 DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13321 && data_handler == NULL && close_handler == NULL);
13322 DEBUG_ASSERT(is_delete_request || (handler != NULL));
13323 DEBUG_ASSERT(auth_handler == NULL);
13324
13325 if ((connect_handler != NULL) || (ready_handler != NULL)
13326 || (data_handler != NULL) || (close_handler != NULL)) {
13327 return;
13328 }
13329 if (!is_delete_request && (handler == NULL)) {
13330 return;
13331 }
13332 if (auth_handler != NULL) {
13333 return;
13334 }
13335 } else { /* AUTH_HANDLER */
13336 DEBUG_ASSERT(handler == NULL);
13337 DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13338 && data_handler == NULL && close_handler == NULL);
13339 DEBUG_ASSERT(auth_handler != NULL);
13340 if (handler != NULL) {
13341 return;
13342 }
13343 if ((connect_handler != NULL) || (ready_handler != NULL)
13344 || (data_handler != NULL) || (close_handler != NULL)) {
13345 return;
13346 }
13347 if (!is_delete_request && (auth_handler == NULL)) {
13348 return;
13349 }
13350 }
13351
13352 if (!phys_ctx || !dom_ctx) {
13353 return;
13354 }
13355
13356 mg_lock_context(phys_ctx);
13357
13358 /* first try to find an existing handler */
13359 lastref = &(dom_ctx->handlers);
13360 for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
13361 if (tmp_rh->handler_type == handler_type) {
13362 if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
13363 if (!is_delete_request) {
13364 /* update existing handler */
13365 if (handler_type == REQUEST_HANDLER) {
13366 /* Wait for end of use before updating */
13367 handler_info_wait_unused(tmp_rh);
13368
13369 /* Ok, the handler is no more use -> Update it */
13370 tmp_rh->handler = handler;
13371 } else if (handler_type == WEBSOCKET_HANDLER) {
13372 tmp_rh->subprotocols = subprotocols;
13373 tmp_rh->connect_handler = connect_handler;
13374 tmp_rh->ready_handler = ready_handler;
13375 tmp_rh->data_handler = data_handler;
13376 tmp_rh->close_handler = close_handler;
13377 } else { /* AUTH_HANDLER */
13378 tmp_rh->auth_handler = auth_handler;
13379 }
13380 tmp_rh->cbdata = cbdata;
13381 } else {
13382 /* remove existing handler */
13383 if (handler_type == REQUEST_HANDLER) {
13384 /* Wait for end of use before removing */
13385 handler_info_wait_unused(tmp_rh);
13386
13387 /* Ok, the handler is no more used -> Destroy resources
13388 */
13389 pthread_cond_destroy(&tmp_rh->refcount_cond);
13390 pthread_mutex_destroy(&tmp_rh->refcount_mutex);
13391 }
13392 *lastref = tmp_rh->next;
13393 mg_free(tmp_rh->uri);
13394 mg_free(tmp_rh);
13395 }
13396 mg_unlock_context(phys_ctx);
13397 return;
13398 }
13399 }
13400 lastref = &(tmp_rh->next);
13401 }
13402
13403 if (is_delete_request) {
13404 /* no handler to set, this was a remove request to a non-existing
13405 * handler */
13406 mg_unlock_context(phys_ctx);
13407 return;
13408 }
13409
13410 tmp_rh =
13411 (struct mg_handler_info *)mg_calloc_ctx(1,
13412 sizeof(struct mg_handler_info),
13413 phys_ctx);
13414 if (tmp_rh == NULL) {
13415 mg_unlock_context(phys_ctx);
13416 mg_cry_ctx_internal(phys_ctx,
13417 "%s",
13418 "Cannot create new request handler struct, OOM");
13419 return;
13420 }
13421 tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
13422 if (!tmp_rh->uri) {
13423 mg_unlock_context(phys_ctx);
13424 mg_free(tmp_rh);
13425 mg_cry_ctx_internal(phys_ctx,
13426 "%s",
13427 "Cannot create new request handler struct, OOM");
13428 return;
13429 }
13430 tmp_rh->uri_len = urilen;
13431 if (handler_type == REQUEST_HANDLER) {
13432 /* Init refcount mutex and condition */
13433 if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
13434 mg_unlock_context(phys_ctx);
13435 mg_free(tmp_rh);
13436 mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
13437 return;
13438 }
13439 if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
13440 mg_unlock_context(phys_ctx);
13441 pthread_mutex_destroy(&tmp_rh->refcount_mutex);
13442 mg_free(tmp_rh);
13443 mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
13444 return;
13445 }
13446 tmp_rh->refcount = 0;
13447 tmp_rh->handler = handler;
13448 } else if (handler_type == WEBSOCKET_HANDLER) {
13449 tmp_rh->subprotocols = subprotocols;
13450 tmp_rh->connect_handler = connect_handler;
13451 tmp_rh->ready_handler = ready_handler;
13452 tmp_rh->data_handler = data_handler;
13453 tmp_rh->close_handler = close_handler;
13454 } else { /* AUTH_HANDLER */
13455 tmp_rh->auth_handler = auth_handler;
13456 }
13457 tmp_rh->cbdata = cbdata;
13458 tmp_rh->handler_type = handler_type;
13459 tmp_rh->next = NULL;
13460
13461 *lastref = tmp_rh;
13462 mg_unlock_context(phys_ctx);
13463 }
13464
13465
13466 void
13467 mg_set_request_handler(struct mg_context *ctx,
13468 const char *uri,
13469 mg_request_handler handler,
13470 void *cbdata)
13471 {
13472 mg_set_handler_type(ctx,
13473 &(ctx->dd),
13474 uri,
13475 REQUEST_HANDLER,
13476 handler == NULL,
13477 handler,
13478 NULL,
13479 NULL,
13480 NULL,
13481 NULL,
13482 NULL,
13483 NULL,
13484 cbdata);
13485 }
13486
13487
13488 void
13489 mg_set_websocket_handler(struct mg_context *ctx,
13490 const char *uri,
13491 mg_websocket_connect_handler connect_handler,
13492 mg_websocket_ready_handler ready_handler,
13493 mg_websocket_data_handler data_handler,
13494 mg_websocket_close_handler close_handler,
13495 void *cbdata)
13496 {
13497 mg_set_websocket_handler_with_subprotocols(ctx,
13498 uri,
13499 NULL,
13500 connect_handler,
13501 ready_handler,
13502 data_handler,
13503 close_handler,
13504 cbdata);
13505 }
13506
13507
13508 void
13509 mg_set_websocket_handler_with_subprotocols(
13510 struct mg_context *ctx,
13511 const char *uri,
13512 struct mg_websocket_subprotocols *subprotocols,
13513 mg_websocket_connect_handler connect_handler,
13514 mg_websocket_ready_handler ready_handler,
13515 mg_websocket_data_handler data_handler,
13516 mg_websocket_close_handler close_handler,
13517 void *cbdata)
13518 {
13519 int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
13520 && (data_handler == NULL)
13521 && (close_handler == NULL);
13522 mg_set_handler_type(ctx,
13523 &(ctx->dd),
13524 uri,
13525 WEBSOCKET_HANDLER,
13526 is_delete_request,
13527 NULL,
13528 subprotocols,
13529 connect_handler,
13530 ready_handler,
13531 data_handler,
13532 close_handler,
13533 NULL,
13534 cbdata);
13535 }
13536
13537
13538 void
13539 mg_set_auth_handler(struct mg_context *ctx,
13540 const char *uri,
13541 mg_authorization_handler handler,
13542 void *cbdata)
13543 {
13544 mg_set_handler_type(ctx,
13545 &(ctx->dd),
13546 uri,
13547 AUTH_HANDLER,
13548 handler == NULL,
13549 NULL,
13550 NULL,
13551 NULL,
13552 NULL,
13553 NULL,
13554 NULL,
13555 handler,
13556 cbdata);
13557 }
13558
13559
13560 static int
13561 get_request_handler(struct mg_connection *conn,
13562 int handler_type,
13563 mg_request_handler *handler,
13564 struct mg_websocket_subprotocols **subprotocols,
13565 mg_websocket_connect_handler *connect_handler,
13566 mg_websocket_ready_handler *ready_handler,
13567 mg_websocket_data_handler *data_handler,
13568 mg_websocket_close_handler *close_handler,
13569 mg_authorization_handler *auth_handler,
13570 void **cbdata,
13571 struct mg_handler_info **handler_info)
13572 {
13573 const struct mg_request_info *request_info = mg_get_request_info(conn);
13574 if (request_info) {
13575 const char *uri = request_info->local_uri;
13576 size_t urilen = strlen(uri);
13577 struct mg_handler_info *tmp_rh;
13578
13579 if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
13580 return 0;
13581 }
13582
13583 mg_lock_context(conn->phys_ctx);
13584
13585 /* first try for an exact match */
13586 for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
13587 tmp_rh = tmp_rh->next) {
13588 if (tmp_rh->handler_type == handler_type) {
13589 if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
13590 if (handler_type == WEBSOCKET_HANDLER) {
13591 *subprotocols = tmp_rh->subprotocols;
13592 *connect_handler = tmp_rh->connect_handler;
13593 *ready_handler = tmp_rh->ready_handler;
13594 *data_handler = tmp_rh->data_handler;
13595 *close_handler = tmp_rh->close_handler;
13596 } else if (handler_type == REQUEST_HANDLER) {
13597 *handler = tmp_rh->handler;
13598 /* Acquire handler and give it back */
13599 handler_info_acquire(tmp_rh);
13600 *handler_info = tmp_rh;
13601 } else { /* AUTH_HANDLER */
13602 *auth_handler = tmp_rh->auth_handler;
13603 }
13604 *cbdata = tmp_rh->cbdata;
13605 mg_unlock_context(conn->phys_ctx);
13606 return 1;
13607 }
13608 }
13609 }
13610
13611 /* next try for a partial match, we will accept uri/something */
13612 for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
13613 tmp_rh = tmp_rh->next) {
13614 if (tmp_rh->handler_type == handler_type) {
13615 if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
13616 && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
13617 if (handler_type == WEBSOCKET_HANDLER) {
13618 *subprotocols = tmp_rh->subprotocols;
13619 *connect_handler = tmp_rh->connect_handler;
13620 *ready_handler = tmp_rh->ready_handler;
13621 *data_handler = tmp_rh->data_handler;
13622 *close_handler = tmp_rh->close_handler;
13623 } else if (handler_type == REQUEST_HANDLER) {
13624 *handler = tmp_rh->handler;
13625 /* Acquire handler and give it back */
13626 handler_info_acquire(tmp_rh);
13627 *handler_info = tmp_rh;
13628 } else { /* AUTH_HANDLER */
13629 *auth_handler = tmp_rh->auth_handler;
13630 }
13631 *cbdata = tmp_rh->cbdata;
13632 mg_unlock_context(conn->phys_ctx);
13633 return 1;
13634 }
13635 }
13636 }
13637
13638 /* finally try for pattern match */
13639 for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
13640 tmp_rh = tmp_rh->next) {
13641 if (tmp_rh->handler_type == handler_type) {
13642 if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
13643 if (handler_type == WEBSOCKET_HANDLER) {
13644 *subprotocols = tmp_rh->subprotocols;
13645 *connect_handler = tmp_rh->connect_handler;
13646 *ready_handler = tmp_rh->ready_handler;
13647 *data_handler = tmp_rh->data_handler;
13648 *close_handler = tmp_rh->close_handler;
13649 } else if (handler_type == REQUEST_HANDLER) {
13650 *handler = tmp_rh->handler;
13651 /* Acquire handler and give it back */
13652 handler_info_acquire(tmp_rh);
13653 *handler_info = tmp_rh;
13654 } else { /* AUTH_HANDLER */
13655 *auth_handler = tmp_rh->auth_handler;
13656 }
13657 *cbdata = tmp_rh->cbdata;
13658 mg_unlock_context(conn->phys_ctx);
13659 return 1;
13660 }
13661 }
13662 }
13663
13664 mg_unlock_context(conn->phys_ctx);
13665 }
13666 return 0; /* none found */
13667 }
13668
13669
13670 /* Check if the script file is in a path, allowed for script files.
13671 * This can be used if uploading files is possible not only for the server
13672 * admin, and the upload mechanism does not check the file extension.
13673 */
13674 static int
13675 is_in_script_path(const struct mg_connection *conn, const char *path)
13676 {
13677 /* TODO (Feature): Add config value for allowed script path.
13678 * Default: All allowed. */
13679 (void)conn;
13680 (void)path;
13681 return 1;
13682 }
13683
13684
13685 #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
13686 static int
13687 deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
13688 void *cbdata)
13689 {
13690 struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13691 if (pcallbacks->websocket_connect) {
13692 return pcallbacks->websocket_connect(conn);
13693 }
13694 /* No handler set - assume "OK" */
13695 return 0;
13696 }
13697
13698
13699 static void
13700 deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
13701 {
13702 struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13703 if (pcallbacks->websocket_ready) {
13704 pcallbacks->websocket_ready(conn);
13705 }
13706 }
13707
13708
13709 static int
13710 deprecated_websocket_data_wrapper(struct mg_connection *conn,
13711 int bits,
13712 char *data,
13713 size_t len,
13714 void *cbdata)
13715 {
13716 struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13717 if (pcallbacks->websocket_data) {
13718 return pcallbacks->websocket_data(conn, bits, data, len);
13719 }
13720 /* No handler set - assume "OK" */
13721 return 1;
13722 }
13723 #endif
13724
13725
13726 /* This is the heart of the Civetweb's logic.
13727 * This function is called when the request is read, parsed and validated,
13728 * and Civetweb must decide what action to take: serve a file, or
13729 * a directory, or call embedded function, etcetera. */
13730 static void
13731 handle_request(struct mg_connection *conn)
13732 {
13733 struct mg_request_info *ri = &conn->request_info;
13734 char path[PATH_MAX];
13735 int uri_len, ssl_index;
13736 int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
13737 is_put_or_delete_request = 0, is_callback_resource = 0;
13738 int i;
13739 struct mg_file file = STRUCT_FILE_INITIALIZER;
13740 mg_request_handler callback_handler = NULL;
13741 struct mg_handler_info *handler_info = NULL;
13742 struct mg_websocket_subprotocols *subprotocols;
13743 mg_websocket_connect_handler ws_connect_handler = NULL;
13744 mg_websocket_ready_handler ws_ready_handler = NULL;
13745 mg_websocket_data_handler ws_data_handler = NULL;
13746 mg_websocket_close_handler ws_close_handler = NULL;
13747 void *callback_data = NULL;
13748 mg_authorization_handler auth_handler = NULL;
13749 void *auth_callback_data = NULL;
13750 int handler_type;
13751 time_t curtime = time(NULL);
13752 char date[64];
13753
13754 path[0] = 0;
13755
13756 /* 1. get the request url */
13757 /* 1.1. split into url and query string */
13758 if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
13759 != NULL) {
13760 *((char *)conn->request_info.query_string++) = '\0';
13761 }
13762
13763 /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
13764 if (!conn->client.is_ssl && conn->client.ssl_redir) {
13765 ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
13766 if (ssl_index >= 0) {
13767 redirect_to_https_port(conn, ssl_index);
13768 } else {
13769 /* A http to https forward port has been specified,
13770 * but no https port to forward to. */
13771 mg_send_http_error(conn,
13772 503,
13773 "%s",
13774 "Error: SSL forward not configured properly");
13775 mg_cry_internal(conn,
13776 "%s",
13777 "Can not redirect to SSL, no SSL port available");
13778 }
13779 return;
13780 }
13781 uri_len = (int)strlen(ri->local_uri);
13782
13783 /* 1.3. decode url (if config says so) */
13784 if (should_decode_url(conn)) {
13785 mg_url_decode(
13786 ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
13787 }
13788
13789 /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
13790 * not possible */
13791 remove_double_dots_and_double_slashes((char *)ri->local_uri);
13792
13793 /* step 1. completed, the url is known now */
13794 uri_len = (int)strlen(ri->local_uri);
13795 DEBUG_TRACE("URL: %s", ri->local_uri);
13796
13797 /* 2. if this ip has limited speed, set it for this connection */
13798 conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
13799 get_remote_ip(conn),
13800 ri->local_uri);
13801
13802 /* 3. call a "handle everything" callback, if registered */
13803 if (conn->phys_ctx->callbacks.begin_request != NULL) {
13804 /* Note that since V1.7 the "begin_request" function is called
13805 * before an authorization check. If an authorization check is
13806 * required, use a request_handler instead. */
13807 i = conn->phys_ctx->callbacks.begin_request(conn);
13808 if (i > 0) {
13809 /* callback already processed the request. Store the
13810 return value as a status code for the access log. */
13811 conn->status_code = i;
13812 discard_unread_request_data(conn);
13813 return;
13814 } else if (i == 0) {
13815 /* civetweb should process the request */
13816 } else {
13817 /* unspecified - may change with the next version */
13818 return;
13819 }
13820 }
13821
13822 /* request not yet handled by a handler or redirect, so the request
13823 * is processed here */
13824
13825 /* 4. Check for CORS preflight requests and handle them (if configured).
13826 * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
13827 */
13828 if (!strcmp(ri->request_method, "OPTIONS")) {
13829 /* Send a response to CORS preflights only if
13830 * access_control_allow_methods is not NULL and not an empty string.
13831 * In this case, scripts can still handle CORS. */
13832 const char *cors_meth_cfg =
13833 conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
13834 const char *cors_orig_cfg =
13835 conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
13836 const char *cors_origin =
13837 get_header(ri->http_headers, ri->num_headers, "Origin");
13838 const char *cors_acrm = get_header(ri->http_headers,
13839 ri->num_headers,
13840 "Access-Control-Request-Method");
13841
13842 /* Todo: check if cors_origin is in cors_orig_cfg.
13843 * Or, let the client check this. */
13844
13845 if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
13846 && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
13847 && (cors_origin != NULL) && (cors_acrm != NULL)) {
13848 /* This is a valid CORS preflight, and the server is configured
13849 * to
13850 * handle it automatically. */
13851 const char *cors_acrh =
13852 get_header(ri->http_headers,
13853 ri->num_headers,
13854 "Access-Control-Request-Headers");
13855
13856 gmt_time_string(date, sizeof(date), &curtime);
13857 mg_printf(conn,
13858 "HTTP/1.1 200 OK\r\n"
13859 "Date: %s\r\n"
13860 "Access-Control-Allow-Origin: %s\r\n"
13861 "Access-Control-Allow-Methods: %s\r\n"
13862 "Content-Length: 0\r\n"
13863 "Connection: %s\r\n",
13864 date,
13865 cors_orig_cfg,
13866 ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
13867 suggest_connection_header(conn));
13868
13869 if (cors_acrh != NULL) {
13870 /* CORS request is asking for additional headers */
13871 const char *cors_hdr_cfg =
13872 conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
13873
13874 if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
13875 /* Allow only if access_control_allow_headers is
13876 * not NULL and not an empty string. If this
13877 * configuration is set to *, allow everything.
13878 * Otherwise this configuration must be a list
13879 * of allowed HTTP header names. */
13880 mg_printf(conn,
13881 "Access-Control-Allow-Headers: %s\r\n",
13882 ((cors_hdr_cfg[0] == '*') ? cors_acrh
13883 : cors_hdr_cfg));
13884 }
13885 }
13886 mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
13887
13888 mg_printf(conn, "\r\n");
13889 return;
13890 }
13891 }
13892
13893 /* 5. interpret the url to find out how the request must be handled
13894 */
13895 /* 5.1. first test, if the request targets the regular http(s)://
13896 * protocol namespace or the websocket ws(s):// protocol namespace.
13897 */
13898 is_websocket_request = is_websocket_protocol(conn);
13899 #if defined(USE_WEBSOCKET)
13900 handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
13901 #else
13902 handler_type = REQUEST_HANDLER;
13903 #endif /* defined(USE_WEBSOCKET) */
13904 /* 5.2. check if the request will be handled by a callback */
13905 if (get_request_handler(conn,
13906 handler_type,
13907 &callback_handler,
13908 &subprotocols,
13909 &ws_connect_handler,
13910 &ws_ready_handler,
13911 &ws_data_handler,
13912 &ws_close_handler,
13913 NULL,
13914 &callback_data,
13915 &handler_info)) {
13916 /* 5.2.1. A callback will handle this request. All requests
13917 * handled
13918 * by a callback have to be considered as requests to a script
13919 * resource. */
13920 is_callback_resource = 1;
13921 is_script_resource = 1;
13922 is_put_or_delete_request = is_put_or_delete_method(conn);
13923 } else {
13924 no_callback_resource:
13925
13926 /* 5.2.2. No callback is responsible for this request. The URI
13927 * addresses a file based resource (static content or Lua/cgi
13928 * scripts in the file system). */
13929 is_callback_resource = 0;
13930 interpret_uri(conn,
13931 path,
13932 sizeof(path),
13933 &file.stat,
13934 &is_found,
13935 &is_script_resource,
13936 &is_websocket_request,
13937 &is_put_or_delete_request);
13938 }
13939
13940 /* 6. authorization check */
13941 /* 6.1. a custom authorization handler is installed */
13942 if (get_request_handler(conn,
13943 AUTH_HANDLER,
13944 NULL,
13945 NULL,
13946 NULL,
13947 NULL,
13948 NULL,
13949 NULL,
13950 &auth_handler,
13951 &auth_callback_data,
13952 NULL)) {
13953 if (!auth_handler(conn, auth_callback_data)) {
13954 return;
13955 }
13956 } else if (is_put_or_delete_request && !is_script_resource
13957 && !is_callback_resource) {
13958 /* 6.2. this request is a PUT/DELETE to a real file */
13959 /* 6.2.1. thus, the server must have real files */
13960 #if defined(NO_FILES)
13961 if (1) {
13962 #else
13963 if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
13964 #endif
13965 /* This server does not have any real files, thus the
13966 * PUT/DELETE methods are not valid. */
13967 mg_send_http_error(conn,
13968 405,
13969 "%s method not allowed",
13970 conn->request_info.request_method);
13971 return;
13972 }
13973
13974 #if !defined(NO_FILES)
13975 /* 6.2.2. Check if put authorization for static files is
13976 * available.
13977 */
13978 if (!is_authorized_for_put(conn)) {
13979 send_authorization_request(conn, NULL);
13980 return;
13981 }
13982 #endif
13983
13984 } else {
13985 /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
13986 * or it is a PUT or DELETE request to a resource that does not
13987 * correspond to a file. Check authorization. */
13988 if (!check_authorization(conn, path)) {
13989 send_authorization_request(conn, NULL);
13990 return;
13991 }
13992 }
13993
13994 /* request is authorized or does not need authorization */
13995
13996 /* 7. check if there are request handlers for this uri */
13997 if (is_callback_resource) {
13998 if (!is_websocket_request) {
13999 i = callback_handler(conn, callback_data);
14000
14001 /* Callback handler will not be used anymore. Release it */
14002 handler_info_release(handler_info);
14003
14004 if (i > 0) {
14005 /* Do nothing, callback has served the request. Store
14006 * then return value as status code for the log and discard
14007 * all data from the client not used by the callback. */
14008 conn->status_code = i;
14009 discard_unread_request_data(conn);
14010 } else {
14011 /* The handler did NOT handle the request. */
14012 /* Some proper reactions would be:
14013 * a) close the connections without sending anything
14014 * b) send a 404 not found
14015 * c) try if there is a file matching the URI
14016 * It would be possible to do a, b or c in the callback
14017 * implementation, and return 1 - we cannot do anything
14018 * here, that is not possible in the callback.
14019 *
14020 * TODO: What would be the best reaction here?
14021 * (Note: The reaction may change, if there is a better
14022 *idea.)
14023 */
14024
14025 /* For the moment, use option c: We look for a proper file,
14026 * but since a file request is not always a script resource,
14027 * the authorization check might be different. */
14028 interpret_uri(conn,
14029 path,
14030 sizeof(path),
14031 &file.stat,
14032 &is_found,
14033 &is_script_resource,
14034 &is_websocket_request,
14035 &is_put_or_delete_request);
14036 callback_handler = NULL;
14037
14038 /* Here we are at a dead end:
14039 * According to URI matching, a callback should be
14040 * responsible for handling the request,
14041 * we called it, but the callback declared itself
14042 * not responsible.
14043 * We use a goto here, to get out of this dead end,
14044 * and continue with the default handling.
14045 * A goto here is simpler and better to understand
14046 * than some curious loop. */
14047 goto no_callback_resource;
14048 }
14049 } else {
14050 #if defined(USE_WEBSOCKET)
14051 handle_websocket_request(conn,
14052 path,
14053 is_callback_resource,
14054 subprotocols,
14055 ws_connect_handler,
14056 ws_ready_handler,
14057 ws_data_handler,
14058 ws_close_handler,
14059 callback_data);
14060 #endif
14061 }
14062 return;
14063 }
14064
14065 /* 8. handle websocket requests */
14066 #if defined(USE_WEBSOCKET)
14067 if (is_websocket_request) {
14068 if (is_script_resource) {
14069
14070 if (is_in_script_path(conn, path)) {
14071 /* Websocket Lua script */
14072 handle_websocket_request(conn,
14073 path,
14074 0 /* Lua Script */,
14075 NULL,
14076 NULL,
14077 NULL,
14078 NULL,
14079 NULL,
14080 conn->phys_ctx->user_data);
14081 } else {
14082 /* Script was in an illegal path */
14083 mg_send_http_error(conn, 403, "%s", "Forbidden");
14084 }
14085 } else {
14086 #if defined(MG_LEGACY_INTERFACE)
14087 handle_websocket_request(
14088 conn,
14089 path,
14090 !is_script_resource /* could be deprecated global callback */,
14091 NULL,
14092 deprecated_websocket_connect_wrapper,
14093 deprecated_websocket_ready_wrapper,
14094 deprecated_websocket_data_wrapper,
14095 NULL,
14096 conn->phys_ctx->user_data);
14097 #else
14098 mg_send_http_error(conn, 404, "%s", "Not found");
14099 #endif
14100 }
14101 return;
14102 } else
14103 #endif
14104
14105 #if defined(NO_FILES)
14106 /* 9a. In case the server uses only callbacks, this uri is
14107 * unknown.
14108 * Then, all request handling ends here. */
14109 mg_send_http_error(conn, 404, "%s", "Not Found");
14110
14111 #else
14112 /* 9b. This request is either for a static file or resource handled
14113 * by a script file. Thus, a DOCUMENT_ROOT must exist. */
14114 if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
14115 mg_send_http_error(conn, 404, "%s", "Not Found");
14116 return;
14117 }
14118
14119 /* 10. Request is handled by a script */
14120 if (is_script_resource) {
14121 handle_file_based_request(conn, path, &file);
14122 return;
14123 }
14124
14125 /* 11. Handle put/delete/mkcol requests */
14126 if (is_put_or_delete_request) {
14127 /* 11.1. PUT method */
14128 if (!strcmp(ri->request_method, "PUT")) {
14129 put_file(conn, path);
14130 return;
14131 }
14132 /* 11.2. DELETE method */
14133 if (!strcmp(ri->request_method, "DELETE")) {
14134 delete_file(conn, path);
14135 return;
14136 }
14137 /* 11.3. MKCOL method */
14138 if (!strcmp(ri->request_method, "MKCOL")) {
14139 mkcol(conn, path);
14140 return;
14141 }
14142 /* 11.4. PATCH method
14143 * This method is not supported for static resources,
14144 * only for scripts (Lua, CGI) and callbacks. */
14145 mg_send_http_error(conn,
14146 405,
14147 "%s method not allowed",
14148 conn->request_info.request_method);
14149 return;
14150 }
14151
14152 /* 11. File does not exist, or it was configured that it should be
14153 * hidden */
14154 if (!is_found || (must_hide_file(conn, path))) {
14155 mg_send_http_error(conn, 404, "%s", "Not found");
14156 return;
14157 }
14158
14159 /* 12. Directory uris should end with a slash */
14160 if (file.stat.is_directory && (uri_len > 0)
14161 && (ri->local_uri[uri_len - 1] != '/')) {
14162 gmt_time_string(date, sizeof(date), &curtime);
14163 mg_printf(conn,
14164 "HTTP/1.1 301 Moved Permanently\r\n"
14165 "Location: %s/\r\n"
14166 "Date: %s\r\n"
14167 /* "Cache-Control: private\r\n" (= default) */
14168 "Content-Length: 0\r\n"
14169 "Connection: %s\r\n",
14170 ri->request_uri,
14171 date,
14172 suggest_connection_header(conn));
14173 send_additional_header(conn);
14174 mg_printf(conn, "\r\n");
14175 return;
14176 }
14177
14178 /* 13. Handle other methods than GET/HEAD */
14179 /* 13.1. Handle PROPFIND */
14180 if (!strcmp(ri->request_method, "PROPFIND")) {
14181 handle_propfind(conn, path, &file.stat);
14182 return;
14183 }
14184 /* 13.2. Handle OPTIONS for files */
14185 if (!strcmp(ri->request_method, "OPTIONS")) {
14186 /* This standard handler is only used for real files.
14187 * Scripts should support the OPTIONS method themselves, to allow a
14188 * maximum flexibility.
14189 * Lua and CGI scripts may fully support CORS this way (including
14190 * preflights). */
14191 send_options(conn);
14192 return;
14193 }
14194 /* 13.3. everything but GET and HEAD (e.g. POST) */
14195 if ((0 != strcmp(ri->request_method, "GET"))
14196 && (0 != strcmp(ri->request_method, "HEAD"))) {
14197 mg_send_http_error(conn,
14198 405,
14199 "%s method not allowed",
14200 conn->request_info.request_method);
14201 return;
14202 }
14203
14204 /* 14. directories */
14205 if (file.stat.is_directory) {
14206 /* Substitute files have already been handled above. */
14207 /* Here we can either generate and send a directory listing,
14208 * or send an "access denied" error. */
14209 if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
14210 "yes")) {
14211 handle_directory_request(conn, path);
14212 } else {
14213 mg_send_http_error(conn,
14214 403,
14215 "%s",
14216 "Error: Directory listing denied");
14217 }
14218 return;
14219 }
14220
14221 /* 15. read a normal file with GET or HEAD */
14222 handle_file_based_request(conn, path, &file);
14223 #endif /* !defined(NO_FILES) */
14224 }
14225
14226
14227 #if !defined(NO_FILESYSTEMS)
14228 static void
14229 handle_file_based_request(struct mg_connection *conn,
14230 const char *path,
14231 struct mg_file *file)
14232 {
14233 if (!conn || !conn->dom_ctx) {
14234 return;
14235 }
14236
14237 if (0) {
14238 #if defined(USE_LUA)
14239 } else if (match_prefix(
14240 conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
14241 strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
14242 path)
14243 > 0) {
14244 if (is_in_script_path(conn, path)) {
14245 /* Lua server page: an SSI like page containing mostly plain
14246 * html
14247 * code
14248 * plus some tags with server generated contents. */
14249 handle_lsp_request(conn, path, file, NULL);
14250 } else {
14251 /* Script was in an illegal path */
14252 mg_send_http_error(conn, 403, "%s", "Forbidden");
14253 }
14254
14255 } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
14256 strlen(
14257 conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
14258 path)
14259 > 0) {
14260 if (is_in_script_path(conn, path)) {
14261 /* Lua in-server module script: a CGI like script used to
14262 * generate
14263 * the
14264 * entire reply. */
14265 mg_exec_lua_script(conn, path, NULL);
14266 } else {
14267 /* Script was in an illegal path */
14268 mg_send_http_error(conn, 403, "%s", "Forbidden");
14269 }
14270 #endif
14271 #if defined(USE_DUKTAPE)
14272 } else if (match_prefix(
14273 conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
14274 strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
14275 path)
14276 > 0) {
14277 if (is_in_script_path(conn, path)) {
14278 /* Call duktape to generate the page */
14279 mg_exec_duktape_script(conn, path);
14280 } else {
14281 /* Script was in an illegal path */
14282 mg_send_http_error(conn, 403, "%s", "Forbidden");
14283 }
14284 #endif
14285 #if !defined(NO_CGI)
14286 } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
14287 strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
14288 path)
14289 > 0) {
14290 if (is_in_script_path(conn, path)) {
14291 /* CGI scripts may support all HTTP methods */
14292 handle_cgi_request(conn, path);
14293 } else {
14294 /* Script was in an illegal path */
14295 mg_send_http_error(conn, 403, "%s", "Forbidden");
14296 }
14297 #endif /* !NO_CGI */
14298 } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
14299 strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
14300 path)
14301 > 0) {
14302 if (is_in_script_path(conn, path)) {
14303 handle_ssi_file_request(conn, path, file);
14304 } else {
14305 /* Script was in an illegal path */
14306 mg_send_http_error(conn, 403, "%s", "Forbidden");
14307 }
14308 #if !defined(NO_CACHING)
14309 } else if ((!conn->in_error_handler)
14310 && is_not_modified(conn, &file->stat)) {
14311 /* Send 304 "Not Modified" - this must not send any body data */
14312 handle_not_modified_static_file_request(conn, file);
14313 #endif /* !NO_CACHING */
14314 } else {
14315 handle_static_file_request(conn, path, file, NULL, NULL);
14316 }
14317 }
14318 #endif /* NO_FILESYSTEMS */
14319
14320
14321 static void
14322 close_all_listening_sockets(struct mg_context *ctx)
14323 {
14324 unsigned int i;
14325 if (!ctx) {
14326 return;
14327 }
14328
14329 for (i = 0; i < ctx->num_listening_sockets; i++) {
14330 closesocket(ctx->listening_sockets[i].sock);
14331 ctx->listening_sockets[i].sock = INVALID_SOCKET;
14332 }
14333 mg_free(ctx->listening_sockets);
14334 ctx->listening_sockets = NULL;
14335 mg_free(ctx->listening_socket_fds);
14336 ctx->listening_socket_fds = NULL;
14337 }
14338
14339
14340 /* Valid listening port specification is: [ip_address:]port[s]
14341 * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
14342 * Examples for IPv6: [::]:80, [::1]:80,
14343 * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
14344 * see https://tools.ietf.org/html/rfc3513#section-2.2
14345 * In order to bind to both, IPv4 and IPv6, you can either add
14346 * both ports using 8080,[::]:8080, or the short form +8080.
14347 * Both forms differ in detail: 8080,[::]:8080 create two sockets,
14348 * one only accepting IPv4 the other only IPv6. +8080 creates
14349 * one socket accepting IPv4 and IPv6. Depending on the IPv6
14350 * environment, they might work differently, or might not work
14351 * at all - it must be tested what options work best in the
14352 * relevant network environment.
14353 */
14354 static int
14355 parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
14356 {
14357 unsigned int a, b, c, d, port;
14358 int ch, len;
14359 const char *cb;
14360 char *endptr;
14361 #if defined(USE_IPV6)
14362 char buf[100] = {0};
14363 #endif
14364
14365 /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
14366 * Also, all-zeroes in the socket address means binding to all addresses
14367 * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
14368 memset(so, 0, sizeof(*so));
14369 so->lsa.sin.sin_family = AF_INET;
14370 *ip_version = 0;
14371
14372 /* Initialize port and len as invalid. */
14373 port = 0;
14374 len = 0;
14375
14376 /* Test for different ways to format this string */
14377 if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
14378 == 5) {
14379 /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
14380 so->lsa.sin.sin_addr.s_addr =
14381 htonl((a << 24) | (b << 16) | (c << 8) | d);
14382 so->lsa.sin.sin_port = htons((uint16_t)port);
14383 *ip_version = 4;
14384
14385 #if defined(USE_IPV6)
14386 } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
14387 && mg_inet_pton(
14388 AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
14389 /* IPv6 address, examples: see above */
14390 /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
14391 */
14392 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14393 *ip_version = 6;
14394 #endif
14395
14396 } else if ((vec->ptr[0] == '+')
14397 && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
14398
14399 /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
14400 /* Add 1 to len for the + character we skipped before */
14401 len++;
14402
14403 #if defined(USE_IPV6)
14404 /* Set socket family to IPv6, do not use IPV6_V6ONLY */
14405 so->lsa.sin6.sin6_family = AF_INET6;
14406 so->lsa.sin6.sin6_port = htons((uint16_t)port);
14407 *ip_version = 4 + 6;
14408 #else
14409 /* Bind to IPv4 only, since IPv6 is not built in. */
14410 so->lsa.sin.sin_port = htons((uint16_t)port);
14411 *ip_version = 4;
14412 #endif
14413
14414 } else if (is_valid_port(port = strtoul(vec->ptr, &endptr, 0))
14415 && vec->ptr != endptr) {
14416 len = endptr - vec->ptr;
14417 /* If only port is specified, bind to IPv4, INADDR_ANY */
14418 so->lsa.sin.sin_port = htons((uint16_t)port);
14419 *ip_version = 4;
14420
14421 } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
14422 /* String could be a hostname. This check algotithm
14423 * will only work for RFC 952 compliant hostnames,
14424 * starting with a letter, containing only letters,
14425 * digits and hyphen ('-'). Newer specs may allow
14426 * more, but this is not guaranteed here, since it
14427 * may interfere with rules for port option lists. */
14428
14429 /* According to RFC 1035, hostnames are restricted to 255 characters
14430 * in total (63 between two dots). */
14431 char hostname[256];
14432 size_t hostnlen = (size_t)(cb - vec->ptr);
14433
14434 if (hostnlen >= sizeof(hostname)) {
14435 /* This would be invalid in any case */
14436 *ip_version = 0;
14437 return 0;
14438 }
14439
14440 memcpy(hostname, vec->ptr, hostnlen);
14441 hostname[hostnlen] = 0;
14442
14443 if (mg_inet_pton(
14444 AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
14445 if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
14446 *ip_version = 4;
14447 so->lsa.sin.sin_family = AF_INET;
14448 so->lsa.sin.sin_port = htons((uint16_t)port);
14449 len += (int)(hostnlen + 1);
14450 } else {
14451 port = 0;
14452 len = 0;
14453 }
14454 #if defined(USE_IPV6)
14455 } else if (mg_inet_pton(AF_INET6,
14456 vec->ptr,
14457 &so->lsa.sin6,
14458 sizeof(so->lsa.sin6))) {
14459 if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
14460 *ip_version = 6;
14461 so->lsa.sin6.sin6_family = AF_INET6;
14462 so->lsa.sin.sin_port = htons((uint16_t)port);
14463 len += (int)(hostnlen + 1);
14464 } else {
14465 port = 0;
14466 len = 0;
14467 }
14468 #endif
14469 }
14470
14471
14472 } else {
14473 /* Parsing failure. */
14474 }
14475
14476 /* sscanf and the option splitting code ensure the following condition
14477 */
14478 if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
14479 *ip_version = 0;
14480 return 0;
14481 }
14482 ch = vec->ptr[len]; /* Next character after the port number */
14483 so->is_ssl = (ch == 's');
14484 so->ssl_redir = (ch == 'r');
14485
14486 /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
14487 if (is_valid_port(port)
14488 && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
14489 return 1;
14490 }
14491
14492 /* Reset ip_version to 0 if there is an error */
14493 *ip_version = 0;
14494 return 0;
14495 }
14496
14497
14498 /* Is there any SSL port in use? */
14499 static int
14500 is_ssl_port_used(const char *ports)
14501 {
14502 if (ports) {
14503 /* There are several different allowed syntax variants:
14504 * - "80" for a single port using every network interface
14505 * - "localhost:80" for a single port using only localhost
14506 * - "80,localhost:8080" for two ports, one bound to localhost
14507 * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
14508 * to IPv4 localhost, one to IPv6 localhost
14509 * - "+80" use port 80 for IPv4 and IPv6
14510 * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
14511 * for both: IPv4 and IPv4
14512 * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
14513 * additionally port 8080 bound to localhost connections
14514 *
14515 * If we just look for 's' anywhere in the string, "localhost:80"
14516 * will be detected as SSL (false positive).
14517 * Looking for 's' after a digit may cause false positives in
14518 * "my24service:8080".
14519 * Looking from 's' backward if there are only ':' and numbers
14520 * before will not work for "24service:8080" (non SSL, port 8080)
14521 * or "24s" (SSL, port 24).
14522 *
14523 * Remark: Initially hostnames were not allowed to start with a
14524 * digit (according to RFC 952), this was allowed later (RFC 1123,
14525 * Section 2.1).
14526 *
14527 * To get this correct, the entire string must be parsed as a whole,
14528 * reading it as a list element for element and parsing with an
14529 * algorithm equivalent to parse_port_string.
14530 *
14531 * In fact, we use local interface names here, not arbitrary hostnames,
14532 * so in most cases the only name will be "localhost".
14533 *
14534 * So, for now, we use this simple algorithm, that may still return
14535 * a false positive in bizarre cases.
14536 */
14537 int i;
14538 int portslen = (int)strlen(ports);
14539 char prevIsNumber = 0;
14540
14541 for (i = 0; i < portslen; i++) {
14542 if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
14543 return 1;
14544 }
14545 if (ports[i] >= '0' && ports[i] <= '9') {
14546 prevIsNumber = 1;
14547 } else {
14548 prevIsNumber = 0;
14549 }
14550 }
14551 }
14552 return 0;
14553 }
14554
14555
14556 static int
14557 set_ports_option(struct mg_context *phys_ctx)
14558 {
14559 const char *list;
14560 int on = 1;
14561 #if defined(USE_IPV6)
14562 int off = 0;
14563 #endif
14564 struct vec vec;
14565 struct socket so, *ptr;
14566
14567 struct mg_pollfd *pfd;
14568 union usa usa;
14569 socklen_t len;
14570 int ip_version;
14571
14572 int portsTotal = 0;
14573 int portsOk = 0;
14574
14575 const char *opt_txt;
14576 long opt_max_connections;
14577
14578 if (!phys_ctx) {
14579 return 0;
14580 }
14581
14582 memset(&so, 0, sizeof(so));
14583 memset(&usa, 0, sizeof(usa));
14584 len = sizeof(usa);
14585 list = phys_ctx->dd.config[LISTENING_PORTS];
14586
14587 while ((list = next_option(list, &vec, NULL)) != NULL) {
14588
14589 portsTotal++;
14590
14591 if (!parse_port_string(&vec, &so, &ip_version)) {
14592 mg_cry_ctx_internal(
14593 phys_ctx,
14594 "%.*s: invalid port spec (entry %i). Expecting list of: %s",
14595 (int)vec.len,
14596 vec.ptr,
14597 portsTotal,
14598 "[IP_ADDRESS:]PORT[s|r]");
14599 continue;
14600 }
14601
14602 #if !defined(NO_SSL)
14603 if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
14604
14605 mg_cry_ctx_internal(phys_ctx,
14606 "Cannot add SSL socket (entry %i)",
14607 portsTotal);
14608 continue;
14609 }
14610 #endif
14611
14612 if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
14613 == INVALID_SOCKET) {
14614
14615 mg_cry_ctx_internal(phys_ctx,
14616 "cannot create socket (entry %i)",
14617 portsTotal);
14618 continue;
14619 }
14620
14621 #if defined(_WIN32)
14622 /* Windows SO_REUSEADDR lets many procs binds to a
14623 * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
14624 * if someone already has the socket -- DTL */
14625 /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
14626 * Windows might need a few seconds before
14627 * the same port can be used again in the
14628 * same process, so a short Sleep may be
14629 * required between mg_stop and mg_start.
14630 */
14631 if (setsockopt(so.sock,
14632 SOL_SOCKET,
14633 SO_EXCLUSIVEADDRUSE,
14634 (SOCK_OPT_TYPE)&on,
14635 sizeof(on))
14636 != 0) {
14637
14638 /* Set reuse option, but don't abort on errors. */
14639 mg_cry_ctx_internal(
14640 phys_ctx,
14641 "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
14642 portsTotal);
14643 }
14644 #else
14645 if (setsockopt(so.sock,
14646 SOL_SOCKET,
14647 SO_REUSEADDR,
14648 (SOCK_OPT_TYPE)&on,
14649 sizeof(on))
14650 != 0) {
14651
14652 /* Set reuse option, but don't abort on errors. */
14653 mg_cry_ctx_internal(
14654 phys_ctx,
14655 "cannot set socket option SO_REUSEADDR (entry %i)",
14656 portsTotal);
14657 }
14658 #endif
14659
14660 if (ip_version > 4) {
14661 /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
14662 #if defined(USE_IPV6)
14663 if (ip_version > 6) {
14664 if (so.lsa.sa.sa_family == AF_INET6
14665 && setsockopt(so.sock,
14666 IPPROTO_IPV6,
14667 IPV6_V6ONLY,
14668 (void *)&off,
14669 sizeof(off))
14670 != 0) {
14671
14672 /* Set IPv6 only option, but don't abort on errors. */
14673 mg_cry_ctx_internal(
14674 phys_ctx,
14675 "cannot set socket option IPV6_V6ONLY=off (entry %i)",
14676 portsTotal);
14677 }
14678 } else {
14679 if (so.lsa.sa.sa_family == AF_INET6
14680 && setsockopt(so.sock,
14681 IPPROTO_IPV6,
14682 IPV6_V6ONLY,
14683 (void *)&on,
14684 sizeof(on))
14685 != 0) {
14686
14687 /* Set IPv6 only option, but don't abort on errors. */
14688 mg_cry_ctx_internal(
14689 phys_ctx,
14690 "cannot set socket option IPV6_V6ONLY=on (entry %i)",
14691 portsTotal);
14692 }
14693 }
14694 #else
14695 mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
14696 closesocket(so.sock);
14697 so.sock = INVALID_SOCKET;
14698 continue;
14699 #endif
14700 }
14701
14702 if (so.lsa.sa.sa_family == AF_INET) {
14703
14704 len = sizeof(so.lsa.sin);
14705 if (bind(so.sock, &so.lsa.sa, len) != 0) {
14706 mg_cry_ctx_internal(phys_ctx,
14707 "cannot bind to %.*s: %d (%s)",
14708 (int)vec.len,
14709 vec.ptr,
14710 (int)ERRNO,
14711 strerror(errno));
14712 closesocket(so.sock);
14713 so.sock = INVALID_SOCKET;
14714 continue;
14715 }
14716 }
14717 #if defined(USE_IPV6)
14718 else if (so.lsa.sa.sa_family == AF_INET6) {
14719
14720 len = sizeof(so.lsa.sin6);
14721 if (bind(so.sock, &so.lsa.sa, len) != 0) {
14722 mg_cry_ctx_internal(phys_ctx,
14723 "cannot bind to IPv6 %.*s: %d (%s)",
14724 (int)vec.len,
14725 vec.ptr,
14726 (int)ERRNO,
14727 strerror(errno));
14728 closesocket(so.sock);
14729 so.sock = INVALID_SOCKET;
14730 continue;
14731 }
14732 }
14733 #endif
14734 else {
14735 mg_cry_ctx_internal(
14736 phys_ctx,
14737 "cannot bind: address family not supported (entry %i)",
14738 portsTotal);
14739 closesocket(so.sock);
14740 so.sock = INVALID_SOCKET;
14741 continue;
14742 }
14743
14744 opt_txt = phys_ctx->dd.config[MAX_CONNECTIONS];
14745 opt_max_connections = strtol(opt_txt, NULL, 10);
14746 if ((opt_max_connections > INT_MAX) || (opt_max_connections < 1)) {
14747 mg_cry_ctx_internal(phys_ctx,
14748 "max_connections value \"%s\" is invalid",
14749 opt_txt);
14750 continue;
14751 }
14752
14753 if (listen(so.sock, (int)opt_max_connections) != 0) {
14754
14755 mg_cry_ctx_internal(phys_ctx,
14756 "cannot listen to %.*s: %d (%s)",
14757 (int)vec.len,
14758 vec.ptr,
14759 (int)ERRNO,
14760 strerror(errno));
14761 closesocket(so.sock);
14762 so.sock = INVALID_SOCKET;
14763 continue;
14764 }
14765
14766 if ((getsockname(so.sock, &(usa.sa), &len) != 0)
14767 || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
14768
14769 int err = (int)ERRNO;
14770 mg_cry_ctx_internal(phys_ctx,
14771 "call to getsockname failed %.*s: %d (%s)",
14772 (int)vec.len,
14773 vec.ptr,
14774 err,
14775 strerror(errno));
14776 closesocket(so.sock);
14777 so.sock = INVALID_SOCKET;
14778 continue;
14779 }
14780
14781 /* Update lsa port in case of random free ports */
14782 #if defined(USE_IPV6)
14783 if (so.lsa.sa.sa_family == AF_INET6) {
14784 so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
14785 } else
14786 #endif
14787 {
14788 so.lsa.sin.sin_port = usa.sin.sin_port;
14789 }
14790
14791 if ((ptr = (struct socket *)
14792 mg_realloc_ctx(phys_ctx->listening_sockets,
14793 (phys_ctx->num_listening_sockets + 1)
14794 * sizeof(phys_ctx->listening_sockets[0]),
14795 phys_ctx))
14796 == NULL) {
14797
14798 mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
14799 closesocket(so.sock);
14800 so.sock = INVALID_SOCKET;
14801 continue;
14802 }
14803
14804 if ((pfd = (struct mg_pollfd *)
14805 mg_realloc_ctx(phys_ctx->listening_socket_fds,
14806 (phys_ctx->num_listening_sockets + 1)
14807 * sizeof(phys_ctx->listening_socket_fds[0]),
14808 phys_ctx))
14809 == NULL) {
14810
14811 mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
14812 closesocket(so.sock);
14813 so.sock = INVALID_SOCKET;
14814 mg_free(ptr);
14815 continue;
14816 }
14817
14818 set_close_on_exec(so.sock, NULL, phys_ctx);
14819 phys_ctx->listening_sockets = ptr;
14820 phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
14821 phys_ctx->listening_socket_fds = pfd;
14822 phys_ctx->num_listening_sockets++;
14823 portsOk++;
14824 }
14825
14826 if (portsOk != portsTotal) {
14827 close_all_listening_sockets(phys_ctx);
14828 portsOk = 0;
14829 }
14830
14831 return portsOk;
14832 }
14833
14834
14835 static const char *
14836 header_val(const struct mg_connection *conn, const char *header)
14837 {
14838 const char *header_value;
14839
14840 if ((header_value = mg_get_header(conn, header)) == NULL) {
14841 return "-";
14842 } else {
14843 return header_value;
14844 }
14845 }
14846
14847
14848 #if defined(MG_EXTERNAL_FUNCTION_log_access)
14849 static void log_access(const struct mg_connection *conn);
14850 #include "external_log_access.inl"
14851 #elif !defined(NO_FILESYSTEMS)
14852
14853 static void
14854 log_access(const struct mg_connection *conn)
14855 {
14856 const struct mg_request_info *ri;
14857 struct mg_file fi;
14858 char date[64], src_addr[IP_ADDR_STR_LEN];
14859 struct tm *tm;
14860
14861 const char *referer;
14862 const char *user_agent;
14863
14864 char buf[4096];
14865
14866 if (!conn || !conn->dom_ctx) {
14867 return;
14868 }
14869
14870 if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
14871 if (mg_fopen(conn,
14872 conn->dom_ctx->config[ACCESS_LOG_FILE],
14873 MG_FOPEN_MODE_APPEND,
14874 &fi)
14875 == 0) {
14876 fi.access.fp = NULL;
14877 }
14878 } else {
14879 fi.access.fp = NULL;
14880 }
14881
14882 /* Log is written to a file and/or a callback. If both are not set,
14883 * executing the rest of the function is pointless. */
14884 if ((fi.access.fp == NULL)
14885 && (conn->phys_ctx->callbacks.log_access == NULL)) {
14886 return;
14887 }
14888
14889 tm = localtime(&conn->conn_birth_time);
14890 if (tm != NULL) {
14891 strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
14892 } else {
14893 mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
14894 date[sizeof(date) - 1] = '\0';
14895 }
14896
14897 ri = &conn->request_info;
14898
14899 sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
14900 referer = header_val(conn, "Referer");
14901 user_agent = header_val(conn, "User-Agent");
14902
14903 mg_snprintf(conn,
14904 NULL, /* Ignore truncation in access log */
14905 buf,
14906 sizeof(buf),
14907 "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
14908 src_addr,
14909 (ri->remote_user == NULL) ? "-" : ri->remote_user,
14910 date,
14911 ri->request_method ? ri->request_method : "-",
14912 ri->request_uri ? ri->request_uri : "-",
14913 ri->query_string ? "?" : "",
14914 ri->query_string ? ri->query_string : "",
14915 ri->http_version,
14916 conn->status_code,
14917 conn->num_bytes_sent,
14918 referer,
14919 user_agent);
14920
14921 if (conn->phys_ctx->callbacks.log_access) {
14922 conn->phys_ctx->callbacks.log_access(conn, buf);
14923 }
14924
14925 if (fi.access.fp) {
14926 int ok = 1;
14927 flockfile(fi.access.fp);
14928 if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
14929 ok = 0;
14930 }
14931 if (fflush(fi.access.fp) != 0) {
14932 ok = 0;
14933 }
14934 funlockfile(fi.access.fp);
14935 if (mg_fclose(&fi.access) != 0) {
14936 ok = 0;
14937 }
14938 if (!ok) {
14939 mg_cry_internal(conn,
14940 "Error writing log file %s",
14941 conn->dom_ctx->config[ACCESS_LOG_FILE]);
14942 }
14943 }
14944 }
14945 #else
14946 #error Must either enable filesystems or provide a custom log_access implementation
14947 #endif /* Externally provided function */
14948
14949
14950 /* Verify given socket address against the ACL.
14951 * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
14952 */
14953 static int
14954 check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
14955 {
14956 int allowed, flag;
14957 uint32_t net, mask;
14958 struct vec vec;
14959
14960 if (phys_ctx) {
14961 const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
14962
14963 /* If any ACL is set, deny by default */
14964 allowed = (list == NULL) ? '+' : '-';
14965
14966 while ((list = next_option(list, &vec, NULL)) != NULL) {
14967 flag = vec.ptr[0];
14968 if ((flag != '+' && flag != '-')
14969 || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
14970 mg_cry_ctx_internal(phys_ctx,
14971 "%s: subnet must be [+|-]x.x.x.x[/x]",
14972 __func__);
14973 return -1;
14974 }
14975
14976 if (net == (remote_ip & mask)) {
14977 allowed = flag;
14978 }
14979 }
14980
14981 return allowed == '+';
14982 }
14983 return -1;
14984 }
14985
14986
14987 #if !defined(_WIN32) && !defined(__ZEPHYR__)
14988 static int
14989 set_uid_option(struct mg_context *phys_ctx)
14990 {
14991 int success = 0;
14992
14993 if (phys_ctx) {
14994 /* We are currently running as curr_uid. */
14995 const uid_t curr_uid = getuid();
14996 /* If set, we want to run as run_as_user. */
14997 const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
14998 const struct passwd *to_pw = NULL;
14999
15000 if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
15001 /* run_as_user does not exist on the system. We can't proceed
15002 * further. */
15003 mg_cry_ctx_internal(phys_ctx,
15004 "%s: unknown user [%s]",
15005 __func__,
15006 run_as_user);
15007 } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
15008 /* There was either no request to change user, or we're already
15009 * running as run_as_user. Nothing else to do.
15010 */
15011 success = 1;
15012 } else {
15013 /* Valid change request. */
15014 if (setgid(to_pw->pw_gid) == -1) {
15015 mg_cry_ctx_internal(phys_ctx,
15016 "%s: setgid(%s): %s",
15017 __func__,
15018 run_as_user,
15019 strerror(errno));
15020 } else if (setgroups(0, NULL) == -1) {
15021 mg_cry_ctx_internal(phys_ctx,
15022 "%s: setgroups(): %s",
15023 __func__,
15024 strerror(errno));
15025 } else if (setuid(to_pw->pw_uid) == -1) {
15026 mg_cry_ctx_internal(phys_ctx,
15027 "%s: setuid(%s): %s",
15028 __func__,
15029 run_as_user,
15030 strerror(errno));
15031 } else {
15032 success = 1;
15033 }
15034 }
15035 }
15036
15037 return success;
15038 }
15039 #endif /* !_WIN32 */
15040
15041
15042 static void
15043 tls_dtor(void *key)
15044 {
15045 struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
15046 /* key == pthread_getspecific(sTlsKey); */
15047
15048 if (tls) {
15049 if (tls->is_master == 2) {
15050 tls->is_master = -3; /* Mark memory as dead */
15051 mg_free(tls);
15052 }
15053 }
15054 pthread_setspecific(sTlsKey, NULL);
15055 }
15056
15057
15058 #if !defined(NO_SSL)
15059
15060 static int ssl_use_pem_file(struct mg_context *phys_ctx,
15061 struct mg_domain_context *dom_ctx,
15062 const char *pem,
15063 const char *chain);
15064 static const char *ssl_error(void);
15065
15066
15067 static int
15068 refresh_trust(struct mg_connection *conn)
15069 {
15070 static int reload_lock = 0;
15071 static long int data_check = 0;
15072 volatile int *p_reload_lock = (volatile int *)&reload_lock;
15073
15074 struct stat cert_buf;
15075 long int t;
15076 const char *pem;
15077 const char *chain;
15078 int should_verify_peer;
15079
15080 if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
15081 /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
15082 * refresh_trust still can not work. */
15083 return 0;
15084 }
15085 chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
15086 if (chain == NULL) {
15087 /* pem is not NULL here */
15088 chain = pem;
15089 }
15090 if (*chain == 0) {
15091 chain = NULL;
15092 }
15093
15094 t = data_check;
15095 if (stat(pem, &cert_buf) != -1) {
15096 t = (long int)cert_buf.st_mtime;
15097 }
15098
15099 if (data_check != t) {
15100 data_check = t;
15101
15102 should_verify_peer = 0;
15103 if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
15104 if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
15105 == 0) {
15106 should_verify_peer = 1;
15107 } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
15108 "optional")
15109 == 0) {
15110 should_verify_peer = 1;
15111 }
15112 }
15113
15114 if (should_verify_peer) {
15115 char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
15116 char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
15117 if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
15118 ca_file,
15119 ca_path)
15120 != 1) {
15121 mg_cry_ctx_internal(
15122 conn->phys_ctx,
15123 "SSL_CTX_load_verify_locations error: %s "
15124 "ssl_verify_peer requires setting "
15125 "either ssl_ca_path or ssl_ca_file. Is any of them "
15126 "present in "
15127 "the .conf file?",
15128 ssl_error());
15129 return 0;
15130 }
15131 }
15132
15133 if (1 == mg_atomic_inc(p_reload_lock)) {
15134 if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
15135 == 0) {
15136 return 0;
15137 }
15138 *p_reload_lock = 0;
15139 }
15140 }
15141 /* lock while cert is reloading */
15142 while (*p_reload_lock) {
15143 sleep(1);
15144 }
15145
15146 return 1;
15147 }
15148
15149 #if defined(OPENSSL_API_1_1)
15150 #else
15151 static pthread_mutex_t *ssl_mutexes;
15152 #endif /* OPENSSL_API_1_1 */
15153
15154 static int
15155 sslize(struct mg_connection *conn,
15156 SSL_CTX *s,
15157 int (*func)(SSL *),
15158 volatile int *stop_server,
15159 const struct mg_client_options *client_options)
15160 {
15161 int ret, err;
15162 int short_trust;
15163 unsigned timeout = 1024;
15164 unsigned i;
15165
15166 if (!conn) {
15167 return 0;
15168 }
15169
15170 short_trust =
15171 (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
15172 && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
15173
15174 if (short_trust) {
15175 int trust_ret = refresh_trust(conn);
15176 if (!trust_ret) {
15177 return trust_ret;
15178 }
15179 }
15180
15181 conn->ssl = SSL_new(s);
15182 if (conn->ssl == NULL) {
15183 return 0;
15184 }
15185 SSL_set_app_data(conn->ssl, (char *)conn);
15186
15187 ret = SSL_set_fd(conn->ssl, conn->client.sock);
15188 if (ret != 1) {
15189 err = SSL_get_error(conn->ssl, ret);
15190 mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
15191 SSL_free(conn->ssl);
15192 conn->ssl = NULL;
15193 OPENSSL_REMOVE_THREAD_STATE();
15194 return 0;
15195 }
15196
15197 if (client_options) {
15198 if (client_options->host_name) {
15199 SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
15200 }
15201 }
15202
15203 /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
15204 if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
15205 /* NOTE: The loop below acts as a back-off, so we can end
15206 * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
15207 timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
15208 }
15209
15210 /* SSL functions may fail and require to be called again:
15211 * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
15212 * Here "func" could be SSL_connect or SSL_accept. */
15213 for (i = 0; i <= timeout; i += 50) {
15214 ret = func(conn->ssl);
15215 if (ret != 1) {
15216 err = SSL_get_error(conn->ssl, ret);
15217 if ((err == SSL_ERROR_WANT_CONNECT)
15218 || (err == SSL_ERROR_WANT_ACCEPT)
15219 || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
15220 || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
15221 if (*stop_server) {
15222 /* Don't wait if the server is going to be stopped. */
15223 break;
15224 }
15225 if (err == SSL_ERROR_WANT_X509_LOOKUP) {
15226 /* Simply retry the function call. */
15227 mg_sleep(50);
15228 } else {
15229 /* Need to retry the function call "later".
15230 * See https://linux.die.net/man/3/ssl_get_error
15231 * This is typical for non-blocking sockets. */
15232 struct mg_pollfd pfd;
15233 int pollres;
15234 pfd.fd = conn->client.sock;
15235 pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
15236 || (err == SSL_ERROR_WANT_WRITE))
15237 ? POLLOUT
15238 : POLLIN;
15239 pollres = mg_poll(&pfd, 1, 50, stop_server);
15240 if (pollres < 0) {
15241 /* Break if error occured (-1)
15242 * or server shutdown (-2) */
15243 break;
15244 }
15245 }
15246
15247 } else if (err == SSL_ERROR_SYSCALL) {
15248 /* This is an IO error. Look at errno. */
15249 err = errno;
15250 mg_cry_internal(conn, "SSL syscall error %i", err);
15251 break;
15252
15253 } else {
15254 /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
15255 mg_cry_internal(conn, "sslize error: %s", ssl_error());
15256 break;
15257 }
15258 ERR_clear_error();
15259
15260 } else {
15261 /* success */
15262 break;
15263 }
15264 }
15265
15266 if (ret != 1) {
15267 SSL_free(conn->ssl);
15268 conn->ssl = NULL;
15269 OPENSSL_REMOVE_THREAD_STATE();
15270 return 0;
15271 }
15272
15273 return 1;
15274 }
15275
15276
15277 /* Return OpenSSL error message (from CRYPTO lib) */
15278 static const char *
15279 ssl_error(void)
15280 {
15281 unsigned long err;
15282 err = ERR_get_error();
15283 return ((err == 0) ? "" : ERR_error_string(err, NULL));
15284 }
15285
15286
15287 static int
15288 hexdump2string(void *mem, int memlen, char *buf, int buflen)
15289 {
15290 int i;
15291 const char hexdigit[] = "0123456789abcdef";
15292
15293 if ((memlen <= 0) || (buflen <= 0)) {
15294 return 0;
15295 }
15296 if (buflen < (3 * memlen)) {
15297 return 0;
15298 }
15299
15300 for (i = 0; i < memlen; i++) {
15301 if (i > 0) {
15302 buf[3 * i - 1] = ' ';
15303 }
15304 buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
15305 buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
15306 }
15307 buf[3 * memlen - 1] = 0;
15308
15309 return 1;
15310 }
15311
15312
15313 static void
15314 ssl_get_client_cert_info(struct mg_connection *conn)
15315 {
15316 X509 *cert = SSL_get_peer_certificate(conn->ssl);
15317 if (cert) {
15318 char str_subject[1024];
15319 char str_issuer[1024];
15320 char str_finger[1024];
15321 unsigned char buf[256];
15322 char *str_serial = NULL;
15323 unsigned int ulen;
15324 int ilen;
15325 unsigned char *tmp_buf;
15326 unsigned char *tmp_p;
15327
15328 /* Handle to algorithm used for fingerprint */
15329 const EVP_MD *digest = EVP_get_digestbyname("sha1");
15330
15331 /* Get Subject and issuer */
15332 X509_NAME *subj = X509_get_subject_name(cert);
15333 X509_NAME *iss = X509_get_issuer_name(cert);
15334
15335 /* Get serial number */
15336 ASN1_INTEGER *serial = X509_get_serialNumber(cert);
15337
15338 /* Translate serial number to a hex string */
15339 BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
15340 str_serial = BN_bn2hex(serial_bn);
15341 BN_free(serial_bn);
15342
15343 /* Translate subject and issuer to a string */
15344 (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
15345 (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
15346
15347 /* Calculate SHA1 fingerprint and store as a hex string */
15348 ulen = 0;
15349
15350 /* ASN1_digest is deprecated. Do the calculation manually,
15351 * using EVP_Digest. */
15352 ilen = i2d_X509(cert, NULL);
15353 tmp_buf = (ilen > 0)
15354 ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
15355 conn->phys_ctx)
15356 : NULL;
15357 if (tmp_buf) {
15358 tmp_p = tmp_buf;
15359 (void)i2d_X509(cert, &tmp_p);
15360 if (!EVP_Digest(
15361 tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
15362 ulen = 0;
15363 }
15364 mg_free(tmp_buf);
15365 }
15366
15367 if (!hexdump2string(
15368 buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
15369 *str_finger = 0;
15370 }
15371
15372 conn->request_info.client_cert = (struct mg_client_cert *)
15373 mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
15374 if (conn->request_info.client_cert) {
15375 conn->request_info.client_cert->peer_cert = (void *)cert;
15376 conn->request_info.client_cert->subject =
15377 mg_strdup_ctx(str_subject, conn->phys_ctx);
15378 conn->request_info.client_cert->issuer =
15379 mg_strdup_ctx(str_issuer, conn->phys_ctx);
15380 conn->request_info.client_cert->serial =
15381 mg_strdup_ctx(str_serial, conn->phys_ctx);
15382 conn->request_info.client_cert->finger =
15383 mg_strdup_ctx(str_finger, conn->phys_ctx);
15384 } else {
15385 mg_cry_internal(conn,
15386 "%s",
15387 "Out of memory: Cannot allocate memory for client "
15388 "certificate");
15389 }
15390
15391 /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
15392 * see https://linux.die.net/man/3/bn_bn2hex */
15393 OPENSSL_free(str_serial);
15394 }
15395 }
15396
15397
15398 #if defined(OPENSSL_API_1_1)
15399 #else
15400 static void
15401 ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
15402 {
15403 (void)line;
15404 (void)file;
15405
15406 if (mode & 1) {
15407 /* 1 is CRYPTO_LOCK */
15408 (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
15409 } else {
15410 (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
15411 }
15412 }
15413 #endif /* OPENSSL_API_1_1 */
15414
15415
15416 #if !defined(NO_SSL_DL)
15417 static void *
15418 load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
15419 {
15420 union {
15421 void *p;
15422 void (*fp)(void);
15423 } u;
15424 void *dll_handle;
15425 struct ssl_func *fp;
15426 int ok;
15427 int truncated = 0;
15428
15429 if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
15430 mg_snprintf(NULL,
15431 NULL, /* No truncation check for ebuf */
15432 ebuf,
15433 ebuf_len,
15434 "%s: cannot load %s",
15435 __func__,
15436 dll_name);
15437 return NULL;
15438 }
15439
15440 ok = 1;
15441 for (fp = sw; fp->name != NULL; fp++) {
15442 #if defined(_WIN32)
15443 /* GetProcAddress() returns pointer to function */
15444 u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
15445 #else
15446 /* dlsym() on UNIX returns void *. ISO C forbids casts of data
15447 * pointers to function pointers. We need to use a union to make a
15448 * cast. */
15449 u.p = dlsym(dll_handle, fp->name);
15450 #endif /* _WIN32 */
15451 if (u.fp == NULL) {
15452 if (ok) {
15453 mg_snprintf(NULL,
15454 &truncated,
15455 ebuf,
15456 ebuf_len,
15457 "%s: %s: cannot find %s",
15458 __func__,
15459 dll_name,
15460 fp->name);
15461 ok = 0;
15462 } else {
15463 size_t cur_len = strlen(ebuf);
15464 if (!truncated) {
15465 mg_snprintf(NULL,
15466 &truncated,
15467 ebuf + cur_len,
15468 ebuf_len - cur_len - 3,
15469 ", %s",
15470 fp->name);
15471 if (truncated) {
15472 /* If truncated, add "..." */
15473 strcat(ebuf, "...");
15474 }
15475 }
15476 }
15477 /* Debug:
15478 * printf("Missing function: %s\n", fp->name); */
15479 } else {
15480 fp->ptr = u.fp;
15481 }
15482 }
15483
15484 if (!ok) {
15485 (void)dlclose(dll_handle);
15486 return NULL;
15487 }
15488
15489 return dll_handle;
15490 }
15491
15492
15493 static void *ssllib_dll_handle; /* Store the ssl library handle. */
15494 static void *cryptolib_dll_handle; /* Store the crypto library handle. */
15495
15496 #endif /* NO_SSL_DL */
15497
15498
15499 #if defined(SSL_ALREADY_INITIALIZED)
15500 static int cryptolib_users = 1; /* Reference counter for crypto library. */
15501 #else
15502 static int cryptolib_users = 0; /* Reference counter for crypto library. */
15503 #endif
15504
15505
15506 static int
15507 initialize_ssl(char *ebuf, size_t ebuf_len)
15508 {
15509 #if defined(OPENSSL_API_1_1)
15510 if (ebuf_len > 0) {
15511 ebuf[0] = 0;
15512 }
15513
15514 #if !defined(NO_SSL_DL)
15515 if (!cryptolib_dll_handle) {
15516 cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
15517 if (!cryptolib_dll_handle) {
15518 mg_snprintf(NULL,
15519 NULL, /* No truncation check for ebuf */
15520 ebuf,
15521 ebuf_len,
15522 "%s: error loading library %s",
15523 __func__,
15524 CRYPTO_LIB);
15525 DEBUG_TRACE("%s", ebuf);
15526 return 0;
15527 }
15528 }
15529 #endif /* NO_SSL_DL */
15530
15531 if (mg_atomic_inc(&cryptolib_users) > 1) {
15532 return 1;
15533 }
15534
15535 #else /* not OPENSSL_API_1_1 */
15536 int i, num_locks;
15537 size_t size;
15538
15539 if (ebuf_len > 0) {
15540 ebuf[0] = 0;
15541 }
15542
15543 #if !defined(NO_SSL_DL)
15544 if (!cryptolib_dll_handle) {
15545 cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
15546 if (!cryptolib_dll_handle) {
15547 mg_snprintf(NULL,
15548 NULL, /* No truncation check for ebuf */
15549 ebuf,
15550 ebuf_len,
15551 "%s: error loading library %s",
15552 __func__,
15553 CRYPTO_LIB);
15554 DEBUG_TRACE("%s", ebuf);
15555 return 0;
15556 }
15557 }
15558 #endif /* NO_SSL_DL */
15559
15560 if (mg_atomic_inc(&cryptolib_users) > 1) {
15561 return 1;
15562 }
15563
15564 /* Initialize locking callbacks, needed for thread safety.
15565 * http://www.openssl.org/support/faq.html#PROG1
15566 */
15567 num_locks = CRYPTO_num_locks();
15568 if (num_locks < 0) {
15569 num_locks = 0;
15570 }
15571 size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
15572
15573 /* allocate mutex array, if required */
15574 if (num_locks == 0) {
15575 /* No mutex array required */
15576 ssl_mutexes = NULL;
15577 } else {
15578 /* Mutex array required - allocate it */
15579 ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
15580
15581 /* Check OOM */
15582 if (ssl_mutexes == NULL) {
15583 mg_snprintf(NULL,
15584 NULL, /* No truncation check for ebuf */
15585 ebuf,
15586 ebuf_len,
15587 "%s: cannot allocate mutexes: %s",
15588 __func__,
15589 ssl_error());
15590 DEBUG_TRACE("%s", ebuf);
15591 return 0;
15592 }
15593
15594 /* initialize mutex array */
15595 for (i = 0; i < num_locks; i++) {
15596 if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
15597 mg_snprintf(NULL,
15598 NULL, /* No truncation check for ebuf */
15599 ebuf,
15600 ebuf_len,
15601 "%s: error initializing mutex %i of %i",
15602 __func__,
15603 i,
15604 num_locks);
15605 DEBUG_TRACE("%s", ebuf);
15606 mg_free(ssl_mutexes);
15607 return 0;
15608 }
15609 }
15610 }
15611
15612 CRYPTO_set_locking_callback(&ssl_locking_callback);
15613 CRYPTO_set_id_callback(&mg_current_thread_id);
15614 #endif /* OPENSSL_API_1_1 */
15615
15616 #if !defined(NO_SSL_DL)
15617 if (!ssllib_dll_handle) {
15618 ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
15619 if (!ssllib_dll_handle) {
15620 #if !defined(OPENSSL_API_1_1)
15621 mg_free(ssl_mutexes);
15622 #endif
15623 DEBUG_TRACE("%s", ebuf);
15624 return 0;
15625 }
15626 }
15627 #endif /* NO_SSL_DL */
15628
15629 #if defined(OPENSSL_API_1_1)
15630 /* Initialize SSL library */
15631 OPENSSL_init_ssl(0, NULL);
15632 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
15633 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
15634 NULL);
15635 #else
15636 /* Initialize SSL library */
15637 SSL_library_init();
15638 SSL_load_error_strings();
15639 #endif
15640
15641 return 1;
15642 }
15643
15644
15645 static int
15646 ssl_use_pem_file(struct mg_context *phys_ctx,
15647 struct mg_domain_context *dom_ctx,
15648 const char *pem,
15649 const char *chain)
15650 {
15651 if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
15652 mg_cry_ctx_internal(phys_ctx,
15653 "%s: cannot open certificate file %s: %s",
15654 __func__,
15655 pem,
15656 ssl_error());
15657 return 0;
15658 }
15659
15660 /* could use SSL_CTX_set_default_passwd_cb_userdata */
15661 if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
15662 mg_cry_ctx_internal(phys_ctx,
15663 "%s: cannot open private key file %s: %s",
15664 __func__,
15665 pem,
15666 ssl_error());
15667 return 0;
15668 }
15669
15670 if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
15671 mg_cry_ctx_internal(phys_ctx,
15672 "%s: certificate and private key do not match: %s",
15673 __func__,
15674 pem);
15675 return 0;
15676 }
15677
15678 /* In contrast to OpenSSL, wolfSSL does not support certificate
15679 * chain files that contain private keys and certificates in
15680 * SSL_CTX_use_certificate_chain_file.
15681 * The CivetWeb-Server used pem-Files that contained both information.
15682 * In order to make wolfSSL work, it is split in two files.
15683 * One file that contains key and certificate used by the server and
15684 * an optional chain file for the ssl stack.
15685 */
15686 if (chain) {
15687 if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
15688 mg_cry_ctx_internal(phys_ctx,
15689 "%s: cannot use certificate chain file %s: %s",
15690 __func__,
15691 chain,
15692 ssl_error());
15693 return 0;
15694 }
15695 }
15696 return 1;
15697 }
15698
15699
15700 #if defined(OPENSSL_API_1_1)
15701 static unsigned long
15702 ssl_get_protocol(int version_id)
15703 {
15704 long unsigned ret = (long unsigned)SSL_OP_ALL;
15705 if (version_id > 0)
15706 ret |= SSL_OP_NO_SSLv2;
15707 if (version_id > 1)
15708 ret |= SSL_OP_NO_SSLv3;
15709 if (version_id > 2)
15710 ret |= SSL_OP_NO_TLSv1;
15711 if (version_id > 3)
15712 ret |= SSL_OP_NO_TLSv1_1;
15713 if (version_id > 4)
15714 ret |= SSL_OP_NO_TLSv1_2;
15715 #if defined(SSL_OP_NO_TLSv1_3)
15716 if (version_id > 5)
15717 ret |= SSL_OP_NO_TLSv1_3;
15718 #endif
15719 return ret;
15720 }
15721 #else
15722 static long
15723 ssl_get_protocol(int version_id)
15724 {
15725 long ret = (long)SSL_OP_ALL;
15726 if (version_id > 0)
15727 ret |= SSL_OP_NO_SSLv2;
15728 if (version_id > 1)
15729 ret |= SSL_OP_NO_SSLv3;
15730 if (version_id > 2)
15731 ret |= SSL_OP_NO_TLSv1;
15732 if (version_id > 3)
15733 ret |= SSL_OP_NO_TLSv1_1;
15734 if (version_id > 4)
15735 ret |= SSL_OP_NO_TLSv1_2;
15736 #if defined(SSL_OP_NO_TLSv1_3)
15737 if (version_id > 5)
15738 ret |= SSL_OP_NO_TLSv1_3;
15739 #endif
15740 return ret;
15741 }
15742 #endif /* OPENSSL_API_1_1 */
15743
15744
15745 /* SSL callback documentation:
15746 * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
15747 * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
15748 * https://linux.die.net/man/3/ssl_set_info_callback */
15749 /* Note: There is no "const" for the first argument in the documentation
15750 * examples, however some (maybe most, but not all) headers of OpenSSL versions
15751 * / OpenSSL compatibility layers have it. Having a different definition will
15752 * cause a warning in C and an error in C++. Use "const SSL *", while
15753 * automatical conversion from "SSL *" works for all compilers, but not other
15754 * way around */
15755 static void
15756 ssl_info_callback(const SSL *ssl, int what, int ret)
15757 {
15758 (void)ret;
15759
15760 if (what & SSL_CB_HANDSHAKE_START) {
15761 SSL_get_app_data(ssl);
15762 }
15763 if (what & SSL_CB_HANDSHAKE_DONE) {
15764 /* TODO: check for openSSL 1.1 */
15765 //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
15766 // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
15767 }
15768 }
15769
15770
15771 static int
15772 ssl_servername_callback(SSL *ssl, int *ad, void *arg)
15773 {
15774 struct mg_context *ctx = (struct mg_context *)arg;
15775 struct mg_domain_context *dom =
15776 (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
15777
15778 #if defined(GCC_DIAGNOSTIC)
15779 #pragma GCC diagnostic push
15780 #pragma GCC diagnostic ignored "-Wcast-align"
15781 #endif /* defined(GCC_DIAGNOSTIC) */
15782
15783 /* We used an aligned pointer in SSL_set_app_data */
15784 struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
15785
15786 #if defined(GCC_DIAGNOSTIC)
15787 #pragma GCC diagnostic pop
15788 #endif /* defined(GCC_DIAGNOSTIC) */
15789
15790 const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
15791
15792 (void)ad;
15793
15794 if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
15795 DEBUG_TRACE("%s", "internal error - assertion failed");
15796 return SSL_TLSEXT_ERR_NOACK;
15797 }
15798
15799 /* Old clients (Win XP) will not support SNI. Then, there
15800 * is no server name available in the request - we can
15801 * only work with the default certificate.
15802 * Multiple HTTPS hosts on one IP+port are only possible
15803 * with a certificate containing all alternative names.
15804 */
15805 if ((servername == NULL) || (*servername == 0)) {
15806 DEBUG_TRACE("%s", "SSL connection not supporting SNI");
15807 conn->dom_ctx = &(ctx->dd);
15808 SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
15809 return SSL_TLSEXT_ERR_NOACK;
15810 }
15811
15812 DEBUG_TRACE("TLS connection to host %s", servername);
15813
15814 while (dom) {
15815 if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
15816
15817 /* Found matching domain */
15818 DEBUG_TRACE("TLS domain %s found",
15819 dom->config[AUTHENTICATION_DOMAIN]);
15820 SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
15821 conn->dom_ctx = dom;
15822 return SSL_TLSEXT_ERR_OK;
15823 }
15824 dom = dom->next;
15825 }
15826
15827 /* Default domain */
15828 DEBUG_TRACE("TLS default domain %s used",
15829 ctx->dd.config[AUTHENTICATION_DOMAIN]);
15830 conn->dom_ctx = &(ctx->dd);
15831 SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
15832 return SSL_TLSEXT_ERR_OK;
15833 }
15834
15835
15836 /* Setup SSL CTX as required by CivetWeb */
15837 static int
15838 init_ssl_ctx_impl(struct mg_context *phys_ctx,
15839 struct mg_domain_context *dom_ctx,
15840 const char *pem,
15841 const char *chain)
15842 {
15843 int callback_ret;
15844 int should_verify_peer;
15845 int peer_certificate_optional;
15846 const char *ca_path;
15847 const char *ca_file;
15848 int use_default_verify_paths;
15849 int verify_depth;
15850 struct timespec now_mt;
15851 md5_byte_t ssl_context_id[16];
15852 md5_state_t md5state;
15853 int protocol_ver;
15854
15855 #if defined(OPENSSL_API_1_1)
15856 if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
15857 mg_cry_ctx_internal(phys_ctx,
15858 "SSL_CTX_new (server) error: %s",
15859 ssl_error());
15860 return 0;
15861 }
15862 #else
15863 if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
15864 mg_cry_ctx_internal(phys_ctx,
15865 "SSL_CTX_new (server) error: %s",
15866 ssl_error());
15867 return 0;
15868 }
15869 #endif /* OPENSSL_API_1_1 */
15870
15871 SSL_CTX_clear_options(dom_ctx->ssl_ctx,
15872 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
15873 | SSL_OP_NO_TLSv1_1);
15874 protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
15875 SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
15876 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
15877 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
15878 SSL_CTX_set_options(dom_ctx->ssl_ctx,
15879 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
15880 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
15881
15882 #if defined(SSL_OP_NO_RENEGOTIATION)
15883 SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
15884 #endif
15885
15886 #if !defined(NO_SSL_DL)
15887 SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
15888 #endif /* NO_SSL_DL */
15889
15890 /* In SSL documentation examples callback defined without const specifier
15891 * 'void (*)(SSL *, int, int)' See:
15892 * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
15893 * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
15894 * But in the source code const SSL is used:
15895 * 'void (*)(const SSL *, int, int)' See:
15896 * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
15897 * Problem about wrong documentation described, but not resolved:
15898 * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
15899 * Wrong const cast ignored on C or can be suppressed by compiler flags.
15900 * But when compiled with modern C++ compiler, correct const should be
15901 * provided
15902 */
15903 SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
15904
15905 SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
15906 ssl_servername_callback);
15907 SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
15908
15909 /* If a callback has been specified, call it. */
15910 callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
15911 ? 0
15912 : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
15913 phys_ctx->user_data));
15914
15915 /* If callback returns 0, civetweb sets up the SSL certificate.
15916 * If it returns 1, civetweb assumes the calback already did this.
15917 * If it returns -1, initializing ssl fails. */
15918 if (callback_ret < 0) {
15919 mg_cry_ctx_internal(phys_ctx,
15920 "SSL callback returned error: %i",
15921 callback_ret);
15922 return 0;
15923 }
15924 if (callback_ret > 0) {
15925 /* Callback did everything. */
15926 return 1;
15927 }
15928
15929 /* Use some combination of start time, domain and port as a SSL
15930 * context ID. This should be unique on the current machine. */
15931 md5_init(&md5state);
15932 clock_gettime(CLOCK_MONOTONIC, &now_mt);
15933 md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
15934 md5_append(&md5state,
15935 (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
15936 strlen(phys_ctx->dd.config[LISTENING_PORTS]));
15937 md5_append(&md5state,
15938 (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
15939 strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
15940 md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
15941 md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
15942 md5_finish(&md5state, ssl_context_id);
15943
15944 SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
15945 (unsigned char *)ssl_context_id,
15946 sizeof(ssl_context_id));
15947
15948 if (pem != NULL) {
15949 if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
15950 return 0;
15951 }
15952 }
15953
15954 /* Should we support client certificates? */
15955 /* Default is "no". */
15956 should_verify_peer = 0;
15957 peer_certificate_optional = 0;
15958 if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
15959 if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
15960 /* Yes, they are mandatory */
15961 should_verify_peer = 1;
15962 peer_certificate_optional = 0;
15963 } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
15964 "optional")
15965 == 0) {
15966 /* Yes, they are optional */
15967 should_verify_peer = 1;
15968 peer_certificate_optional = 1;
15969 }
15970 }
15971
15972 use_default_verify_paths =
15973 (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
15974 && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
15975 == 0);
15976
15977 if (should_verify_peer) {
15978 ca_path = dom_ctx->config[SSL_CA_PATH];
15979 ca_file = dom_ctx->config[SSL_CA_FILE];
15980 if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
15981 != 1) {
15982 mg_cry_ctx_internal(phys_ctx,
15983 "SSL_CTX_load_verify_locations error: %s "
15984 "ssl_verify_peer requires setting "
15985 "either ssl_ca_path or ssl_ca_file. "
15986 "Is any of them present in the "
15987 ".conf file?",
15988 ssl_error());
15989 return 0;
15990 }
15991
15992 if (peer_certificate_optional) {
15993 SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
15994 } else {
15995 SSL_CTX_set_verify(dom_ctx->ssl_ctx,
15996 SSL_VERIFY_PEER
15997 | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
15998 NULL);
15999 }
16000
16001 if (use_default_verify_paths
16002 && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
16003 mg_cry_ctx_internal(phys_ctx,
16004 "SSL_CTX_set_default_verify_paths error: %s",
16005 ssl_error());
16006 return 0;
16007 }
16008
16009 if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
16010 verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
16011 SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
16012 }
16013 }
16014
16015 if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
16016 if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
16017 dom_ctx->config[SSL_CIPHER_LIST])
16018 != 1) {
16019 mg_cry_ctx_internal(phys_ctx,
16020 "SSL_CTX_set_cipher_list error: %s",
16021 ssl_error());
16022 }
16023 }
16024
16025 return 1;
16026 }
16027
16028
16029 /* Check if SSL is required.
16030 * If so, dynamically load SSL library
16031 * and set up ctx->ssl_ctx pointer. */
16032 static int
16033 init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16034 {
16035 void *ssl_ctx = 0;
16036 int callback_ret;
16037 const char *pem;
16038 const char *chain;
16039 char ebuf[128];
16040
16041 if (!phys_ctx) {
16042 return 0;
16043 }
16044
16045 if (!dom_ctx) {
16046 dom_ctx = &(phys_ctx->dd);
16047 }
16048
16049 if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
16050 /* No SSL port is set. No need to setup SSL. */
16051 return 1;
16052 }
16053
16054 /* Check for external SSL_CTX */
16055 callback_ret =
16056 (phys_ctx->callbacks.external_ssl_ctx == NULL)
16057 ? 0
16058 : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
16059 phys_ctx->user_data));
16060
16061 if (callback_ret < 0) {
16062 mg_cry_ctx_internal(phys_ctx,
16063 "external_ssl_ctx callback returned error: %i",
16064 callback_ret);
16065 return 0;
16066 } else if (callback_ret > 0) {
16067 dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
16068 if (!initialize_ssl(ebuf, sizeof(ebuf))) {
16069 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16070 return 0;
16071 }
16072 return 1;
16073 }
16074 /* else: external_ssl_ctx does not exist or returns 0,
16075 * CivetWeb should continue initializing SSL */
16076
16077 /* If PEM file is not specified and the init_ssl callback
16078 * is not specified, setup will fail. */
16079 if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
16080 && (phys_ctx->callbacks.init_ssl == NULL)) {
16081 /* No certificate and no callback:
16082 * Essential data to set up TLS is missing.
16083 */
16084 mg_cry_ctx_internal(phys_ctx,
16085 "Initializing SSL failed: -%s is not set",
16086 config_options[SSL_CERTIFICATE].name);
16087 return 0;
16088 }
16089
16090 chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
16091 if (chain == NULL) {
16092 chain = pem;
16093 }
16094 if ((chain != NULL) && (*chain == 0)) {
16095 chain = NULL;
16096 }
16097
16098 if (!initialize_ssl(ebuf, sizeof(ebuf))) {
16099 mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
16100 return 0;
16101 }
16102
16103 return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
16104 }
16105
16106
16107 static void
16108 uninitialize_ssl(void)
16109 {
16110 #if defined(OPENSSL_API_1_1)
16111
16112 if (mg_atomic_dec(&cryptolib_users) == 0) {
16113
16114 /* Shutdown according to
16115 * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
16116 * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
16117 */
16118 CONF_modules_unload(1);
16119 #else
16120 int i;
16121
16122 if (mg_atomic_dec(&cryptolib_users) == 0) {
16123
16124 /* Shutdown according to
16125 * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
16126 * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
16127 */
16128 CRYPTO_set_locking_callback(NULL);
16129 CRYPTO_set_id_callback(NULL);
16130 ENGINE_cleanup();
16131 CONF_modules_unload(1);
16132 ERR_free_strings();
16133 EVP_cleanup();
16134 CRYPTO_cleanup_all_ex_data();
16135 OPENSSL_REMOVE_THREAD_STATE();
16136
16137 for (i = 0; i < CRYPTO_num_locks(); i++) {
16138 pthread_mutex_destroy(&ssl_mutexes[i]);
16139 }
16140 mg_free(ssl_mutexes);
16141 ssl_mutexes = NULL;
16142 #endif /* OPENSSL_API_1_1 */
16143 }
16144 }
16145 #endif /* !NO_SSL */
16146
16147
16148 #if !defined(NO_FILESYSTEMS)
16149 static int
16150 set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
16151 {
16152 if (phys_ctx) {
16153 struct mg_file file = STRUCT_FILE_INITIALIZER;
16154 const char *path;
16155 struct mg_connection fc;
16156 if (!dom_ctx) {
16157 dom_ctx = &(phys_ctx->dd);
16158 }
16159 path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
16160 if ((path != NULL)
16161 && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
16162 mg_cry_ctx_internal(phys_ctx,
16163 "Cannot open %s: %s",
16164 path,
16165 strerror(ERRNO));
16166 return 0;
16167 }
16168 return 1;
16169 }
16170 return 0;
16171 }
16172 #endif /* NO_FILESYSTEMS */
16173
16174
16175 static int
16176 set_acl_option(struct mg_context *phys_ctx)
16177 {
16178 return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
16179 }
16180
16181
16182 static void
16183 reset_per_request_attributes(struct mg_connection *conn)
16184 {
16185 if (!conn) {
16186 return;
16187 }
16188 conn->connection_type =
16189 CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
16190
16191 conn->num_bytes_sent = conn->consumed_content = 0;
16192
16193 conn->path_info = NULL;
16194 conn->status_code = -1;
16195 conn->content_len = -1;
16196 conn->is_chunked = 0;
16197 conn->must_close = 0;
16198 conn->request_len = 0;
16199 conn->throttle = 0;
16200 conn->accept_gzip = 0;
16201
16202 conn->response_info.content_length = conn->request_info.content_length = -1;
16203 conn->response_info.http_version = conn->request_info.http_version = NULL;
16204 conn->response_info.num_headers = conn->request_info.num_headers = 0;
16205 conn->response_info.status_text = NULL;
16206 conn->response_info.status_code = 0;
16207
16208 conn->request_info.remote_user = NULL;
16209 conn->request_info.request_method = NULL;
16210 conn->request_info.request_uri = NULL;
16211 conn->request_info.local_uri = NULL;
16212
16213 #if defined(MG_LEGACY_INTERFACE)
16214 /* Legacy before split into local_uri and request_uri */
16215 conn->request_info.uri = NULL;
16216 #endif
16217 }
16218
16219
16220 static int
16221 set_tcp_nodelay(SOCKET sock, int nodelay_on)
16222 {
16223 if (setsockopt(sock,
16224 IPPROTO_TCP,
16225 TCP_NODELAY,
16226 (SOCK_OPT_TYPE)&nodelay_on,
16227 sizeof(nodelay_on))
16228 != 0) {
16229 /* Error */
16230 return 1;
16231 }
16232 /* OK */
16233 return 0;
16234 }
16235
16236
16237 #if !defined(__ZEPHYR__)
16238 static void
16239 close_socket_gracefully(struct mg_connection *conn)
16240 {
16241 #if defined(_WIN32)
16242 char buf[MG_BUF_LEN];
16243 int n;
16244 #endif
16245 struct linger linger;
16246 int error_code = 0;
16247 int linger_timeout = -2;
16248 socklen_t opt_len = sizeof(error_code);
16249
16250 if (!conn) {
16251 return;
16252 }
16253
16254 /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
16255 * "Note that enabling a nonzero timeout on a nonblocking socket
16256 * is not recommended.", so set it to blocking now */
16257 set_blocking_mode(conn->client.sock);
16258
16259 /* Send FIN to the client */
16260 shutdown(conn->client.sock, SHUTDOWN_WR);
16261
16262
16263 #if defined(_WIN32)
16264 /* Read and discard pending incoming data. If we do not do that and
16265 * close
16266 * the socket, the data in the send buffer may be discarded. This
16267 * behaviour is seen on Windows, when client keeps sending data
16268 * when server decides to close the connection; then when client
16269 * does recv() it gets no data back. */
16270 do {
16271 n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
16272 } while (n > 0);
16273 #endif
16274
16275 if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
16276 linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
16277 }
16278
16279 /* Set linger option according to configuration */
16280 if (linger_timeout >= 0) {
16281 /* Set linger option to avoid socket hanging out after close. This
16282 * prevent ephemeral port exhaust problem under high QPS. */
16283 linger.l_onoff = 1;
16284
16285 #if defined(_MSC_VER)
16286 #pragma warning(push)
16287 #pragma warning(disable : 4244)
16288 #endif
16289 #if defined(GCC_DIAGNOSTIC)
16290 #pragma GCC diagnostic push
16291 #pragma GCC diagnostic ignored "-Wconversion"
16292 #endif
16293 /* Data type of linger structure elements may differ,
16294 * so we don't know what cast we need here.
16295 * Disable type conversion warnings. */
16296
16297 linger.l_linger = (linger_timeout + 999) / 1000;
16298
16299 #if defined(GCC_DIAGNOSTIC)
16300 #pragma GCC diagnostic pop
16301 #endif
16302 #if defined(_MSC_VER)
16303 #pragma warning(pop)
16304 #endif
16305
16306 } else {
16307 linger.l_onoff = 0;
16308 linger.l_linger = 0;
16309 }
16310
16311 if (linger_timeout < -1) {
16312 /* Default: don't configure any linger */
16313 } else if (getsockopt(conn->client.sock,
16314 SOL_SOCKET,
16315 SO_ERROR,
16316 #if defined(_WIN32) /* WinSock uses different data type here */
16317 (char *)&error_code,
16318 #else
16319 &error_code,
16320 #endif
16321 &opt_len)
16322 != 0) {
16323 /* Cannot determine if socket is already closed. This should
16324 * not occur and never did in a test. Log an error message
16325 * and continue. */
16326 mg_cry_internal(conn,
16327 "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
16328 __func__,
16329 strerror(ERRNO));
16330 #if defined(_WIN32)
16331 } else if (error_code == WSAECONNRESET) {
16332 #else
16333 } else if (error_code == ECONNRESET) {
16334 #endif
16335 /* Socket already closed by client/peer, close socket without linger
16336 */
16337 } else {
16338
16339 /* Set linger timeout */
16340 if (setsockopt(conn->client.sock,
16341 SOL_SOCKET,
16342 SO_LINGER,
16343 (char *)&linger,
16344 sizeof(linger))
16345 != 0) {
16346 mg_cry_internal(
16347 conn,
16348 "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
16349 __func__,
16350 linger.l_onoff,
16351 linger.l_linger,
16352 strerror(ERRNO));
16353 }
16354 }
16355
16356 /* Now we know that our FIN is ACK-ed, safe to close */
16357 closesocket(conn->client.sock);
16358 conn->client.sock = INVALID_SOCKET;
16359 }
16360 #endif
16361
16362
16363 static void
16364 close_connection(struct mg_connection *conn)
16365 {
16366 #if defined(USE_SERVER_STATS)
16367 conn->conn_state = 6; /* to close */
16368 #endif
16369
16370 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
16371 if (conn->lua_websocket_state) {
16372 lua_websocket_close(conn, conn->lua_websocket_state);
16373 conn->lua_websocket_state = NULL;
16374 }
16375 #endif
16376
16377 mg_lock_connection(conn);
16378
16379 /* Set close flag, so keep-alive loops will stop */
16380 conn->must_close = 1;
16381
16382 /* call the connection_close callback if assigned */
16383 if (conn->phys_ctx->callbacks.connection_close != NULL) {
16384 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
16385 conn->phys_ctx->callbacks.connection_close(conn);
16386 }
16387 }
16388
16389 /* Reset user data, after close callback is called.
16390 * Do not reuse it. If the user needs a destructor,
16391 * it must be done in the connection_close callback. */
16392 mg_set_user_connection_data(conn, NULL);
16393
16394
16395 #if defined(USE_SERVER_STATS)
16396 conn->conn_state = 7; /* closing */
16397 #endif
16398
16399 #if !defined(NO_SSL)
16400 if (conn->ssl != NULL) {
16401 /* Run SSL_shutdown twice to ensure completely close SSL connection
16402 */
16403 SSL_shutdown(conn->ssl);
16404 SSL_free(conn->ssl);
16405 OPENSSL_REMOVE_THREAD_STATE();
16406 conn->ssl = NULL;
16407 }
16408 #endif
16409 if (conn->client.sock != INVALID_SOCKET) {
16410 #if defined(__ZEPHYR__)
16411 closesocket(conn->client.sock);
16412 #else
16413 close_socket_gracefully(conn);
16414 #endif
16415 conn->client.sock = INVALID_SOCKET;
16416 }
16417
16418 if (conn->host) {
16419 mg_free((void *)conn->host);
16420 conn->host = NULL;
16421 }
16422
16423 mg_unlock_connection(conn);
16424
16425 #if defined(USE_SERVER_STATS)
16426 conn->conn_state = 8; /* closed */
16427 #endif
16428 }
16429
16430
16431 void
16432 mg_close_connection(struct mg_connection *conn)
16433 {
16434 if ((conn == NULL) || (conn->phys_ctx == NULL)) {
16435 return;
16436 }
16437
16438 #if defined(USE_WEBSOCKET)
16439 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
16440 if (conn->in_websocket_handling) {
16441 /* Set close flag, so the server thread can exit. */
16442 conn->must_close = 1;
16443 return;
16444 }
16445 }
16446 if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
16447
16448 unsigned int i;
16449
16450 /* client context: loops must end */
16451 conn->phys_ctx->stop_flag = 1;
16452 conn->must_close = 1;
16453
16454 /* We need to get the client thread out of the select/recv call
16455 * here. */
16456 /* Since we use a sleep quantum of some seconds to check for recv
16457 * timeouts, we will just wait a few seconds in mg_join_thread. */
16458
16459 /* join worker thread */
16460 for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
16461 mg_join_thread(conn->phys_ctx->worker_threadids[i]);
16462 }
16463 }
16464 #endif /* defined(USE_WEBSOCKET) */
16465
16466 close_connection(conn);
16467
16468 #if !defined(NO_SSL)
16469 if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
16470 || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
16471 && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
16472 SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
16473 }
16474 #endif
16475
16476 #if defined(USE_WEBSOCKET)
16477 if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
16478 mg_free(conn->phys_ctx->worker_threadids);
16479 (void)pthread_mutex_destroy(&conn->mutex);
16480 mg_free(conn);
16481 } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
16482 mg_free(conn);
16483 }
16484 #else
16485 if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
16486 mg_free(conn);
16487 }
16488 #endif /* defined(USE_WEBSOCKET) */
16489 }
16490
16491
16492 static struct mg_connection *
16493 mg_connect_client_impl(const struct mg_client_options *client_options,
16494 int use_ssl,
16495 char *ebuf,
16496 size_t ebuf_len)
16497 {
16498 struct mg_connection *conn = NULL;
16499 SOCKET sock;
16500 union usa sa;
16501 struct sockaddr *psa;
16502 socklen_t len;
16503
16504 unsigned max_req_size =
16505 (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
16506
16507 /* Size of structures, aligned to 8 bytes */
16508 size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
16509 size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
16510
16511 conn =
16512 (struct mg_connection *)mg_calloc(1,
16513 conn_size + ctx_size + max_req_size);
16514
16515 if (conn == NULL) {
16516 mg_snprintf(NULL,
16517 NULL, /* No truncation check for ebuf */
16518 ebuf,
16519 ebuf_len,
16520 "calloc(): %s",
16521 strerror(ERRNO));
16522 return NULL;
16523 }
16524
16525 #if defined(GCC_DIAGNOSTIC)
16526 #pragma GCC diagnostic push
16527 #pragma GCC diagnostic ignored "-Wcast-align"
16528 #endif /* defined(GCC_DIAGNOSTIC) */
16529 /* conn_size is aligned to 8 bytes */
16530
16531 conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
16532
16533 #if defined(GCC_DIAGNOSTIC)
16534 #pragma GCC diagnostic pop
16535 #endif /* defined(GCC_DIAGNOSTIC) */
16536
16537 conn->buf = (((char *)conn) + conn_size + ctx_size);
16538 conn->buf_size = (int)max_req_size;
16539 conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
16540 conn->dom_ctx = &(conn->phys_ctx->dd);
16541
16542 if (!connect_socket(conn->phys_ctx,
16543 client_options->host,
16544 client_options->port,
16545 use_ssl,
16546 ebuf,
16547 ebuf_len,
16548 &sock,
16549 &sa)) {
16550 /* ebuf is set by connect_socket,
16551 * free all memory and return NULL; */
16552 mg_free(conn);
16553 return NULL;
16554 }
16555
16556 #if !defined(NO_SSL)
16557 #if defined(OPENSSL_API_1_1)
16558 if (use_ssl
16559 && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
16560 == NULL) {
16561 mg_snprintf(NULL,
16562 NULL, /* No truncation check for ebuf */
16563 ebuf,
16564 ebuf_len,
16565 "SSL_CTX_new error: %s",
16566 ssl_error());
16567 closesocket(sock);
16568 mg_free(conn);
16569 return NULL;
16570 }
16571 #else
16572 if (use_ssl
16573 && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
16574 == NULL) {
16575 mg_snprintf(NULL,
16576 NULL, /* No truncation check for ebuf */
16577 ebuf,
16578 ebuf_len,
16579 "SSL_CTX_new error: %s",
16580 ssl_error());
16581 closesocket(sock);
16582 mg_free(conn);
16583 return NULL;
16584 }
16585 #endif /* OPENSSL_API_1_1 */
16586 #endif /* NO_SSL */
16587
16588
16589 #if defined(USE_IPV6)
16590 len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
16591 : sizeof(conn->client.rsa.sin6);
16592 psa = (sa.sa.sa_family == AF_INET)
16593 ? (struct sockaddr *)&(conn->client.rsa.sin)
16594 : (struct sockaddr *)&(conn->client.rsa.sin6);
16595 #else
16596 len = sizeof(conn->client.rsa.sin);
16597 psa = (struct sockaddr *)&(conn->client.rsa.sin);
16598 #endif
16599
16600 conn->client.sock = sock;
16601 conn->client.lsa = sa;
16602
16603 if (getsockname(sock, psa, &len) != 0) {
16604 mg_cry_internal(conn,
16605 "%s: getsockname() failed: %s",
16606 __func__,
16607 strerror(ERRNO));
16608 }
16609
16610 conn->client.is_ssl = use_ssl ? 1 : 0;
16611 if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
16612 mg_snprintf(NULL,
16613 NULL, /* No truncation check for ebuf */
16614 ebuf,
16615 ebuf_len,
16616 "Can not create mutex");
16617 #if !defined(NO_SSL)
16618 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
16619 #endif
16620 closesocket(sock);
16621 mg_free(conn);
16622 return NULL;
16623 }
16624
16625
16626 #if !defined(NO_SSL)
16627 if (use_ssl) {
16628 /* TODO: Check ssl_verify_peer and ssl_ca_path here.
16629 * SSL_CTX_set_verify call is needed to switch off server
16630 * certificate checking, which is off by default in OpenSSL and
16631 * on in yaSSL. */
16632 /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
16633 * SSL_VERIFY_PEER, verify_ssl_server); */
16634
16635 if (client_options->client_cert) {
16636 if (!ssl_use_pem_file(conn->phys_ctx,
16637 conn->dom_ctx,
16638 client_options->client_cert,
16639 NULL)) {
16640 mg_snprintf(NULL,
16641 NULL, /* No truncation check for ebuf */
16642 ebuf,
16643 ebuf_len,
16644 "Can not use SSL client certificate");
16645 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
16646 closesocket(sock);
16647 mg_free(conn);
16648 return NULL;
16649 }
16650 }
16651
16652 if (client_options->server_cert) {
16653 if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
16654 client_options->server_cert,
16655 NULL)
16656 != 1) {
16657 mg_cry_internal(conn,
16658 "SSL_CTX_load_verify_locations error: %s ",
16659 ssl_error());
16660 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
16661 closesocket(sock);
16662 mg_free(conn);
16663 return NULL;
16664 }
16665 SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
16666 } else {
16667 SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
16668 }
16669
16670 if (!sslize(conn,
16671 conn->dom_ctx->ssl_ctx,
16672 SSL_connect,
16673 &(conn->phys_ctx->stop_flag),
16674 client_options)) {
16675 mg_snprintf(NULL,
16676 NULL, /* No truncation check for ebuf */
16677 ebuf,
16678 ebuf_len,
16679 "SSL connection error");
16680 SSL_CTX_free(conn->dom_ctx->ssl_ctx);
16681 closesocket(sock);
16682 mg_free(conn);
16683 return NULL;
16684 }
16685 }
16686 #endif
16687
16688 return conn;
16689 }
16690
16691
16692 CIVETWEB_API struct mg_connection *
16693 mg_connect_client_secure(const struct mg_client_options *client_options,
16694 char *error_buffer,
16695 size_t error_buffer_size)
16696 {
16697 return mg_connect_client_impl(client_options,
16698 1,
16699 error_buffer,
16700 error_buffer_size);
16701 }
16702
16703
16704 struct mg_connection *
16705 mg_connect_client(const char *host,
16706 int port,
16707 int use_ssl,
16708 char *error_buffer,
16709 size_t error_buffer_size)
16710 {
16711 struct mg_client_options opts;
16712 memset(&opts, 0, sizeof(opts));
16713 opts.host = host;
16714 opts.port = port;
16715 return mg_connect_client_impl(&opts,
16716 use_ssl,
16717 error_buffer,
16718 error_buffer_size);
16719 }
16720
16721
16722 static const struct {
16723 const char *proto;
16724 size_t proto_len;
16725 unsigned default_port;
16726 } abs_uri_protocols[] = {{"http://", 7, 80},
16727 {"https://", 8, 443},
16728 {"ws://", 5, 80},
16729 {"wss://", 6, 443},
16730 {NULL, 0, 0}};
16731
16732
16733 /* Check if the uri is valid.
16734 * return 0 for invalid uri,
16735 * return 1 for *,
16736 * return 2 for relative uri,
16737 * return 3 for absolute uri without port,
16738 * return 4 for absolute uri with port */
16739 static int
16740 get_uri_type(const char *uri)
16741 {
16742 int i;
16743 const char *hostend, *portbegin;
16744 char *portend;
16745 unsigned long port;
16746
16747 /* According to the HTTP standard
16748 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
16749 * URI can be an asterisk (*) or should start with slash (relative uri),
16750 * or it should start with the protocol (absolute uri). */
16751 if ((uri[0] == '*') && (uri[1] == '\0')) {
16752 /* asterisk */
16753 return 1;
16754 }
16755
16756 /* Valid URIs according to RFC 3986
16757 * (https://www.ietf.org/rfc/rfc3986.txt)
16758 * must only contain reserved characters :/?#[]@!$&'()*+,;=
16759 * and unreserved characters A-Z a-z 0-9 and -._~
16760 * and % encoded symbols.
16761 */
16762 for (i = 0; uri[i] != 0; i++) {
16763 if (uri[i] < 33) {
16764 /* control characters and spaces are invalid */
16765 return 0;
16766 }
16767 if (uri[i] > 126) {
16768 /* non-ascii characters must be % encoded */
16769 return 0;
16770 } else {
16771 switch (uri[i]) {
16772 case '"': /* 34 */
16773 case '<': /* 60 */
16774 case '>': /* 62 */
16775 case '\\': /* 92 */
16776 case '^': /* 94 */
16777 case '`': /* 96 */
16778 case '{': /* 123 */
16779 case '|': /* 124 */
16780 case '}': /* 125 */
16781 return 0;
16782 default:
16783 /* character is ok */
16784 break;
16785 }
16786 }
16787 }
16788
16789 /* A relative uri starts with a / character */
16790 if (uri[0] == '/') {
16791 /* relative uri */
16792 return 2;
16793 }
16794
16795 /* It could be an absolute uri: */
16796 /* This function only checks if the uri is valid, not if it is
16797 * addressing the current server. So civetweb can also be used
16798 * as a proxy server. */
16799 for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
16800 if (mg_strncasecmp(uri,
16801 abs_uri_protocols[i].proto,
16802 abs_uri_protocols[i].proto_len)
16803 == 0) {
16804
16805 hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
16806 if (!hostend) {
16807 return 0;
16808 }
16809 portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
16810 if (!portbegin) {
16811 return 3;
16812 }
16813
16814 port = strtoul(portbegin + 1, &portend, 10);
16815 if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
16816 return 0;
16817 }
16818
16819 return 4;
16820 }
16821 }
16822
16823 return 0;
16824 }
16825
16826
16827 /* Return NULL or the relative uri at the current server */
16828 static const char *
16829 get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
16830 {
16831 const char *server_domain;
16832 size_t server_domain_len;
16833 size_t request_domain_len = 0;
16834 unsigned long port = 0;
16835 int i, auth_domain_check_enabled;
16836 const char *hostbegin = NULL;
16837 const char *hostend = NULL;
16838 const char *portbegin;
16839 char *portend;
16840
16841 auth_domain_check_enabled =
16842 !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
16843
16844 /* DNS is case insensitive, so use case insensitive string compare here
16845 */
16846 for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
16847 if (mg_strncasecmp(uri,
16848 abs_uri_protocols[i].proto,
16849 abs_uri_protocols[i].proto_len)
16850 == 0) {
16851
16852 hostbegin = uri + abs_uri_protocols[i].proto_len;
16853 hostend = strchr(hostbegin, '/');
16854 if (!hostend) {
16855 return 0;
16856 }
16857 portbegin = strchr(hostbegin, ':');
16858 if ((!portbegin) || (portbegin > hostend)) {
16859 port = abs_uri_protocols[i].default_port;
16860 request_domain_len = (size_t)(hostend - hostbegin);
16861 } else {
16862 port = strtoul(portbegin + 1, &portend, 10);
16863 if ((portend != hostend) || (port <= 0)
16864 || !is_valid_port(port)) {
16865 return 0;
16866 }
16867 request_domain_len = (size_t)(portbegin - hostbegin);
16868 }
16869 /* protocol found, port set */
16870 break;
16871 }
16872 }
16873
16874 if (!port) {
16875 /* port remains 0 if the protocol is not found */
16876 return 0;
16877 }
16878
16879 /* Check if the request is directed to a different server. */
16880 /* First check if the port is the same (IPv4 and IPv6). */
16881 #if defined(USE_IPV6)
16882 if (conn->client.lsa.sa.sa_family == AF_INET6) {
16883 if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
16884 /* Request is directed to a different port */
16885 return 0;
16886 }
16887 } else
16888 #endif
16889 {
16890 if (ntohs(conn->client.lsa.sin.sin_port) != port) {
16891 /* Request is directed to a different port */
16892 return 0;
16893 }
16894 }
16895
16896 /* Finally check if the server corresponds to the authentication
16897 * domain of the server (the server domain).
16898 * Allow full matches (like http://mydomain.com/path/file.ext), and
16899 * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
16900 * but do not allow substrings (like
16901 * http://notmydomain.com/path/file.ext
16902 * or http://mydomain.com.fake/path/file.ext).
16903 */
16904 if (auth_domain_check_enabled) {
16905 server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
16906 server_domain_len = strlen(server_domain);
16907 if ((server_domain_len == 0) || (hostbegin == NULL)) {
16908 return 0;
16909 }
16910 if ((request_domain_len == server_domain_len)
16911 && (!memcmp(server_domain, hostbegin, server_domain_len))) {
16912 /* Request is directed to this server - full name match. */
16913 } else {
16914 if (request_domain_len < (server_domain_len + 2)) {
16915 /* Request is directed to another server: The server name
16916 * is longer than the request name.
16917 * Drop this case here to avoid overflows in the
16918 * following checks. */
16919 return 0;
16920 }
16921 if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
16922 /* Request is directed to another server: It could be a
16923 * substring
16924 * like notmyserver.com */
16925 return 0;
16926 }
16927 if (0
16928 != memcmp(server_domain,
16929 hostbegin + request_domain_len - server_domain_len,
16930 server_domain_len)) {
16931 /* Request is directed to another server:
16932 * The server name is different. */
16933 return 0;
16934 }
16935 }
16936 }
16937
16938 return hostend;
16939 }
16940
16941
16942 static int
16943 get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
16944 {
16945 if (ebuf_len > 0) {
16946 ebuf[0] = '\0';
16947 }
16948 *err = 0;
16949
16950 reset_per_request_attributes(conn);
16951
16952 if (!conn) {
16953 mg_snprintf(conn,
16954 NULL, /* No truncation check for ebuf */
16955 ebuf,
16956 ebuf_len,
16957 "%s",
16958 "Internal error");
16959 *err = 500;
16960 return 0;
16961 }
16962 /* Set the time the request was received. This value should be used for
16963 * timeouts. */
16964 clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
16965
16966 conn->request_len =
16967 read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
16968 DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
16969 if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
16970 mg_snprintf(conn,
16971 NULL, /* No truncation check for ebuf */
16972 ebuf,
16973 ebuf_len,
16974 "%s",
16975 "Invalid message size");
16976 *err = 500;
16977 return 0;
16978 }
16979
16980 if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
16981 mg_snprintf(conn,
16982 NULL, /* No truncation check for ebuf */
16983 ebuf,
16984 ebuf_len,
16985 "%s",
16986 "Message too large");
16987 *err = 413;
16988 return 0;
16989 }
16990
16991 if (conn->request_len <= 0) {
16992 if (conn->data_len > 0) {
16993 mg_snprintf(conn,
16994 NULL, /* No truncation check for ebuf */
16995 ebuf,
16996 ebuf_len,
16997 "%s",
16998 "Malformed message");
16999 *err = 400;
17000 } else {
17001 /* Server did not recv anything -> just close the connection */
17002 conn->must_close = 1;
17003 mg_snprintf(conn,
17004 NULL, /* No truncation check for ebuf */
17005 ebuf,
17006 ebuf_len,
17007 "%s",
17008 "No data received");
17009 *err = 0;
17010 }
17011 return 0;
17012 }
17013 return 1;
17014 }
17015
17016
17017 static int
17018 get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17019 {
17020 const char *cl;
17021 if (!get_message(conn, ebuf, ebuf_len, err)) {
17022 return 0;
17023 }
17024
17025 if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
17026 <= 0) {
17027 mg_snprintf(conn,
17028 NULL, /* No truncation check for ebuf */
17029 ebuf,
17030 ebuf_len,
17031 "%s",
17032 "Bad request");
17033 *err = 400;
17034 return 0;
17035 }
17036
17037 /* Message is a valid request */
17038
17039 /* Is there a "host" ? */
17040 if (conn->host != NULL) {
17041 mg_free((void *)conn->host);
17042 }
17043 conn->host = alloc_get_host(conn);
17044 if (!conn->host) {
17045 mg_snprintf(conn,
17046 NULL, /* No truncation check for ebuf */
17047 ebuf,
17048 ebuf_len,
17049 "%s",
17050 "Bad request: Host mismatch");
17051 *err = 400;
17052 return 0;
17053 }
17054
17055 if (((cl = get_header(conn->request_info.http_headers,
17056 conn->request_info.num_headers,
17057 "Transfer-Encoding"))
17058 != NULL)
17059 && mg_strcasecmp(cl, "identity")) {
17060 if (mg_strcasecmp(cl, "chunked")) {
17061 mg_snprintf(conn,
17062 NULL, /* No truncation check for ebuf */
17063 ebuf,
17064 ebuf_len,
17065 "%s",
17066 "Bad request");
17067 *err = 400;
17068 return 0;
17069 }
17070 conn->is_chunked = 1;
17071 conn->content_len = 0; /* not yet read */
17072 } else if ((cl = get_header(conn->request_info.http_headers,
17073 conn->request_info.num_headers,
17074 "Content-Length"))
17075 != NULL) {
17076 /* Request has content length set */
17077 char *endptr = NULL;
17078 conn->content_len = strtoll(cl, &endptr, 10);
17079 if ((endptr == cl) || (conn->content_len < 0)) {
17080 mg_snprintf(conn,
17081 NULL, /* No truncation check for ebuf */
17082 ebuf,
17083 ebuf_len,
17084 "%s",
17085 "Bad request");
17086 *err = 411;
17087 return 0;
17088 }
17089 /* Publish the content length back to the request info. */
17090 conn->request_info.content_length = conn->content_len;
17091 } else {
17092 /* There is no exception, see RFC7230. */
17093 conn->content_len = 0;
17094 }
17095
17096 conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
17097 return 1;
17098 }
17099
17100
17101 /* conn is assumed to be valid in this internal function */
17102 static int
17103 get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
17104 {
17105 const char *cl;
17106 if (!get_message(conn, ebuf, ebuf_len, err)) {
17107 return 0;
17108 }
17109
17110 if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
17111 <= 0) {
17112 mg_snprintf(conn,
17113 NULL, /* No truncation check for ebuf */
17114 ebuf,
17115 ebuf_len,
17116 "%s",
17117 "Bad response");
17118 *err = 400;
17119 return 0;
17120 }
17121
17122 /* Message is a valid response */
17123
17124 if (((cl = get_header(conn->response_info.http_headers,
17125 conn->response_info.num_headers,
17126 "Transfer-Encoding"))
17127 != NULL)
17128 && mg_strcasecmp(cl, "identity")) {
17129 if (mg_strcasecmp(cl, "chunked")) {
17130 mg_snprintf(conn,
17131 NULL, /* No truncation check for ebuf */
17132 ebuf,
17133 ebuf_len,
17134 "%s",
17135 "Bad request");
17136 *err = 400;
17137 return 0;
17138 }
17139 conn->is_chunked = 1;
17140 conn->content_len = 0; /* not yet read */
17141 } else if ((cl = get_header(conn->response_info.http_headers,
17142 conn->response_info.num_headers,
17143 "Content-Length"))
17144 != NULL) {
17145 char *endptr = NULL;
17146 conn->content_len = strtoll(cl, &endptr, 10);
17147 if ((endptr == cl) || (conn->content_len < 0)) {
17148 mg_snprintf(conn,
17149 NULL, /* No truncation check for ebuf */
17150 ebuf,
17151 ebuf_len,
17152 "%s",
17153 "Bad request");
17154 *err = 411;
17155 return 0;
17156 }
17157 /* Publish the content length back to the response info. */
17158 conn->response_info.content_length = conn->content_len;
17159
17160 /* TODO: check if it is still used in response_info */
17161 conn->request_info.content_length = conn->content_len;
17162
17163 /* TODO: we should also consider HEAD method */
17164 if (conn->response_info.status_code == 304) {
17165 conn->content_len = 0;
17166 }
17167 } else {
17168 /* TODO: we should also consider HEAD method */
17169 if (((conn->response_info.status_code >= 100)
17170 && (conn->response_info.status_code <= 199))
17171 || (conn->response_info.status_code == 204)
17172 || (conn->response_info.status_code == 304)) {
17173 conn->content_len = 0;
17174 } else {
17175 conn->content_len = -1; /* unknown content length */
17176 }
17177 }
17178
17179 conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
17180 return 1;
17181 }
17182
17183
17184 int
17185 mg_get_response(struct mg_connection *conn,
17186 char *ebuf,
17187 size_t ebuf_len,
17188 int timeout)
17189 {
17190 int err, ret;
17191 char txt[32]; /* will not overflow */
17192 char *save_timeout;
17193 char *new_timeout;
17194
17195 if (ebuf_len > 0) {
17196 ebuf[0] = '\0';
17197 }
17198
17199 if (!conn) {
17200 mg_snprintf(conn,
17201 NULL, /* No truncation check for ebuf */
17202 ebuf,
17203 ebuf_len,
17204 "%s",
17205 "Parameter error");
17206 return -1;
17207 }
17208
17209 /* Reset the previous responses */
17210 conn->data_len = 0;
17211
17212 /* Implementation of API function for HTTP clients */
17213 save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
17214
17215 if (timeout >= 0) {
17216 mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
17217 new_timeout = txt;
17218 } else {
17219 new_timeout = NULL;
17220 }
17221
17222 conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
17223 ret = get_response(conn, ebuf, ebuf_len, &err);
17224 conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
17225
17226 #if defined(MG_LEGACY_INTERFACE)
17227 /* TODO: 1) uri is deprecated;
17228 * 2) here, ri.uri is the http response code */
17229 conn->request_info.uri = conn->request_info.request_uri;
17230 #endif
17231 conn->request_info.local_uri = conn->request_info.request_uri;
17232
17233 /* TODO (mid): Define proper return values - maybe return length?
17234 * For the first test use <0 for error and >0 for OK */
17235 return (ret == 0) ? -1 : +1;
17236 }
17237
17238
17239 struct mg_connection *
17240 mg_download(const char *host,
17241 int port,
17242 int use_ssl,
17243 char *ebuf,
17244 size_t ebuf_len,
17245 const char *fmt,
17246 ...)
17247 {
17248 struct mg_connection *conn;
17249 va_list ap;
17250 int i;
17251 int reqerr;
17252
17253 if (ebuf_len > 0) {
17254 ebuf[0] = '\0';
17255 }
17256
17257 va_start(ap, fmt);
17258
17259 /* open a connection */
17260 conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
17261
17262 if (conn != NULL) {
17263 i = mg_vprintf(conn, fmt, ap);
17264 if (i <= 0) {
17265 mg_snprintf(conn,
17266 NULL, /* No truncation check for ebuf */
17267 ebuf,
17268 ebuf_len,
17269 "%s",
17270 "Error sending request");
17271 } else {
17272 /* make sure the buffer is clear */
17273 conn->data_len = 0;
17274 get_response(conn, ebuf, ebuf_len, &reqerr);
17275
17276 #if defined(MG_LEGACY_INTERFACE)
17277 /* TODO: 1) uri is deprecated;
17278 * 2) here, ri.uri is the http response code */
17279 conn->request_info.uri = conn->request_info.request_uri;
17280 #endif
17281 conn->request_info.local_uri = conn->request_info.request_uri;
17282 }
17283 }
17284
17285 /* if an error occurred, close the connection */
17286 if ((ebuf[0] != '\0') && (conn != NULL)) {
17287 mg_close_connection(conn);
17288 conn = NULL;
17289 }
17290
17291 va_end(ap);
17292 return conn;
17293 }
17294
17295
17296 struct websocket_client_thread_data {
17297 struct mg_connection *conn;
17298 mg_websocket_data_handler data_handler;
17299 mg_websocket_close_handler close_handler;
17300 void *callback_data;
17301 };
17302
17303
17304 #if defined(USE_WEBSOCKET)
17305 #if defined(_WIN32)
17306 static unsigned __stdcall websocket_client_thread(void *data)
17307 #else
17308 static void *
17309 websocket_client_thread(void *data)
17310 #endif
17311 {
17312 struct websocket_client_thread_data *cdata =
17313 (struct websocket_client_thread_data *)data;
17314
17315 void *user_thread_ptr = NULL;
17316
17317 #if !defined(_WIN32) && !defined(__ZEPHYR__)
17318 struct sigaction sa;
17319
17320 /* Ignore SIGPIPE */
17321 memset(&sa, 0, sizeof(sa));
17322 sa.sa_handler = SIG_IGN;
17323 sigaction(SIGPIPE, &sa, NULL);
17324 #endif
17325
17326 mg_set_thread_name("ws-clnt");
17327
17328 if (cdata->conn->phys_ctx) {
17329 if (cdata->conn->phys_ctx->callbacks.init_thread) {
17330 /* 3 indicates a websocket client thread */
17331 /* TODO: check if conn->phys_ctx can be set */
17332 user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
17333 cdata->conn->phys_ctx, 3);
17334 }
17335 }
17336
17337 read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
17338
17339 DEBUG_TRACE("%s", "Websocket client thread exited\n");
17340
17341 if (cdata->close_handler != NULL) {
17342 cdata->close_handler(cdata->conn, cdata->callback_data);
17343 }
17344
17345 /* The websocket_client context has only this thread. If it runs out,
17346 set the stop_flag to 2 (= "stopped"). */
17347 cdata->conn->phys_ctx->stop_flag = 2;
17348
17349 if (cdata->conn->phys_ctx->callbacks.exit_thread) {
17350 cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
17351 3,
17352 user_thread_ptr);
17353 }
17354
17355 mg_free((void *)cdata);
17356
17357 #if defined(_WIN32)
17358 return 0;
17359 #else
17360 return NULL;
17361 #endif
17362 }
17363 #endif
17364
17365
17366 struct mg_connection *
17367 mg_connect_websocket_client(const char *host,
17368 int port,
17369 int use_ssl,
17370 char *error_buffer,
17371 size_t error_buffer_size,
17372 const char *path,
17373 const char *origin,
17374 mg_websocket_data_handler data_func,
17375 mg_websocket_close_handler close_func,
17376 void *user_data)
17377 {
17378 struct mg_connection *conn = NULL;
17379
17380 #if defined(USE_WEBSOCKET)
17381 struct websocket_client_thread_data *thread_data;
17382 static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
17383 static const char *handshake_req;
17384
17385 if (origin != NULL) {
17386 handshake_req = "GET %s HTTP/1.1\r\n"
17387 "Host: %s\r\n"
17388 "Upgrade: websocket\r\n"
17389 "Connection: Upgrade\r\n"
17390 "Sec-WebSocket-Key: %s\r\n"
17391 "Sec-WebSocket-Version: 13\r\n"
17392 "Origin: %s\r\n"
17393 "\r\n";
17394 } else {
17395 handshake_req = "GET %s HTTP/1.1\r\n"
17396 "Host: %s\r\n"
17397 "Upgrade: websocket\r\n"
17398 "Connection: Upgrade\r\n"
17399 "Sec-WebSocket-Key: %s\r\n"
17400 "Sec-WebSocket-Version: 13\r\n"
17401 "\r\n";
17402 }
17403
17404 #if defined(__clang__)
17405 #pragma clang diagnostic push
17406 #pragma clang diagnostic ignored "-Wformat-nonliteral"
17407 #endif
17408
17409 /* Establish the client connection and request upgrade */
17410 conn = mg_download(host,
17411 port,
17412 use_ssl,
17413 error_buffer,
17414 error_buffer_size,
17415 handshake_req,
17416 path,
17417 host,
17418 magic,
17419 origin);
17420
17421 #if defined(__clang__)
17422 #pragma clang diagnostic pop
17423 #endif
17424
17425 /* Connection object will be null if something goes wrong */
17426 if (conn == NULL) {
17427 if (!*error_buffer) {
17428 /* There should be already an error message */
17429 mg_snprintf(conn,
17430 NULL, /* No truncation check for ebuf */
17431 error_buffer,
17432 error_buffer_size,
17433 "Unexpected error");
17434 }
17435 return NULL;
17436 }
17437
17438 if (conn->response_info.status_code != 101) {
17439 /* We sent an "upgrade" request. For a correct websocket
17440 * protocol handshake, we expect a "101 Continue" response.
17441 * Otherwise it is a protocol violation. Maybe the HTTP
17442 * Server does not know websockets. */
17443 if (!*error_buffer) {
17444 /* set an error, if not yet set */
17445 mg_snprintf(conn,
17446 NULL, /* No truncation check for ebuf */
17447 error_buffer,
17448 error_buffer_size,
17449 "Unexpected server reply");
17450 }
17451
17452 DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
17453 mg_close_connection(conn);
17454 return NULL;
17455 }
17456
17457 thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
17458 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
17459 if (!thread_data) {
17460 DEBUG_TRACE("%s\r\n", "Out of memory");
17461 mg_close_connection(conn);
17462 return NULL;
17463 }
17464
17465 thread_data->conn = conn;
17466 thread_data->data_handler = data_func;
17467 thread_data->close_handler = close_func;
17468 thread_data->callback_data = user_data;
17469
17470 conn->phys_ctx->worker_threadids =
17471 (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
17472 if (!conn->phys_ctx->worker_threadids) {
17473 DEBUG_TRACE("%s\r\n", "Out of memory");
17474 mg_free(thread_data);
17475 mg_close_connection(conn);
17476 return NULL;
17477 }
17478
17479 /* Now upgrade to ws/wss client context */
17480 conn->phys_ctx->user_data = user_data;
17481 conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
17482 conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
17483
17484 /* Start a thread to read the websocket client connection
17485 * This thread will automatically stop when mg_disconnect is
17486 * called on the client connection */
17487 if (mg_start_thread_with_id(websocket_client_thread,
17488 thread_data,
17489 conn->phys_ctx->worker_threadids)
17490 != 0) {
17491 conn->phys_ctx->cfg_worker_threads = 0;
17492 mg_free(thread_data);
17493 mg_close_connection(conn);
17494 conn = NULL;
17495 DEBUG_TRACE("%s",
17496 "Websocket client connect thread could not be started\r\n");
17497 }
17498
17499 #else
17500 /* Appease "unused parameter" warnings */
17501 (void)host;
17502 (void)port;
17503 (void)use_ssl;
17504 (void)error_buffer;
17505 (void)error_buffer_size;
17506 (void)path;
17507 (void)origin;
17508 (void)user_data;
17509 (void)data_func;
17510 (void)close_func;
17511 #endif
17512
17513 return conn;
17514 }
17515
17516
17517 /* Prepare connection data structure */
17518 static void
17519 init_connection(struct mg_connection *conn)
17520 {
17521 /* Is keep alive allowed by the server */
17522 int keep_alive_enabled =
17523 !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
17524
17525 if (!keep_alive_enabled) {
17526 conn->must_close = 1;
17527 }
17528
17529 /* Important: on new connection, reset the receiving buffer. Credit
17530 * goes to crule42. */
17531 conn->data_len = 0;
17532 conn->handled_requests = 0;
17533 mg_set_user_connection_data(conn, NULL);
17534
17535 #if defined(USE_SERVER_STATS)
17536 conn->conn_state = 2; /* init */
17537 #endif
17538
17539 /* call the init_connection callback if assigned */
17540 if (conn->phys_ctx->callbacks.init_connection != NULL) {
17541 if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17542 void *conn_data = NULL;
17543 conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
17544 mg_set_user_connection_data(conn, conn_data);
17545 }
17546 }
17547 }
17548
17549
17550 /* Process a connection - may handle multiple requests
17551 * using the same connection.
17552 * Must be called with a valid connection (conn and
17553 * conn->phys_ctx must be valid).
17554 */
17555 static void
17556 process_new_connection(struct mg_connection *conn)
17557 {
17558 struct mg_request_info *ri = &conn->request_info;
17559 int keep_alive, discard_len;
17560 char ebuf[100];
17561 const char *hostend;
17562 int reqerr, uri_type;
17563
17564 #if defined(USE_SERVER_STATS)
17565 int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
17566 mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
17567 if (mcon > (conn->phys_ctx->max_connections)) {
17568 /* could use atomic compare exchange, but this
17569 * seems overkill for statistics data */
17570 conn->phys_ctx->max_connections = mcon;
17571 }
17572 #endif
17573
17574 init_connection(conn);
17575
17576 DEBUG_TRACE("Start processing connection from %s",
17577 conn->request_info.remote_addr);
17578
17579 /* Loop over multiple requests sent using the same connection
17580 * (while "keep alive"). */
17581 do {
17582
17583 DEBUG_TRACE("calling get_request (%i times for this connection)",
17584 conn->handled_requests + 1);
17585
17586 #if defined(USE_SERVER_STATS)
17587 conn->conn_state = 3; /* ready */
17588 #endif
17589
17590 if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
17591 /* The request sent by the client could not be understood by
17592 * the server, or it was incomplete or a timeout. Send an
17593 * error message and close the connection. */
17594 if (reqerr > 0) {
17595 DEBUG_ASSERT(ebuf[0] != '\0');
17596 mg_send_http_error(conn, reqerr, "%s", ebuf);
17597 }
17598 } else if (strcmp(ri->http_version, "1.0")
17599 && strcmp(ri->http_version, "1.1")) {
17600 mg_snprintf(conn,
17601 NULL, /* No truncation check for ebuf */
17602 ebuf,
17603 sizeof(ebuf),
17604 "Bad HTTP version: [%s]",
17605 ri->http_version);
17606 mg_send_http_error(conn, 505, "%s", ebuf);
17607 }
17608
17609 if (ebuf[0] == '\0') {
17610 uri_type = get_uri_type(conn->request_info.request_uri);
17611 switch (uri_type) {
17612 case 1:
17613 /* Asterisk */
17614 conn->request_info.local_uri = NULL;
17615 break;
17616 case 2:
17617 /* relative uri */
17618 conn->request_info.local_uri = conn->request_info.request_uri;
17619 break;
17620 case 3:
17621 case 4:
17622 /* absolute uri (with/without port) */
17623 hostend = get_rel_url_at_current_server(
17624 conn->request_info.request_uri, conn);
17625 if (hostend) {
17626 conn->request_info.local_uri = hostend;
17627 } else {
17628 conn->request_info.local_uri = NULL;
17629 }
17630 break;
17631 default:
17632 mg_snprintf(conn,
17633 NULL, /* No truncation check for ebuf */
17634 ebuf,
17635 sizeof(ebuf),
17636 "Invalid URI");
17637 mg_send_http_error(conn, 400, "%s", ebuf);
17638 conn->request_info.local_uri = NULL;
17639 break;
17640 }
17641
17642 #if defined(MG_LEGACY_INTERFACE)
17643 /* Legacy before split into local_uri and request_uri */
17644 conn->request_info.uri = conn->request_info.local_uri;
17645 #endif
17646 }
17647
17648 DEBUG_TRACE("http: %s, error: %s",
17649 (ri->http_version ? ri->http_version : "none"),
17650 (ebuf[0] ? ebuf : "none"));
17651
17652 if (ebuf[0] == '\0') {
17653 if (conn->request_info.local_uri) {
17654
17655 /* handle request to local server */
17656 #if defined(USE_SERVER_STATS)
17657 conn->conn_state = 4; /* processing */
17658 #endif
17659 handle_request(conn);
17660
17661 #if defined(USE_SERVER_STATS)
17662 conn->conn_state = 5; /* processed */
17663
17664 mg_atomic_add(&(conn->phys_ctx->total_data_read),
17665 conn->consumed_content);
17666 mg_atomic_add(&(conn->phys_ctx->total_data_written),
17667 conn->num_bytes_sent);
17668 #endif
17669
17670 DEBUG_TRACE("%s", "handle_request done");
17671
17672 if (conn->phys_ctx->callbacks.end_request != NULL) {
17673 conn->phys_ctx->callbacks.end_request(conn,
17674 conn->status_code);
17675 DEBUG_TRACE("%s", "end_request callback done");
17676 }
17677 log_access(conn);
17678 } else {
17679 /* TODO: handle non-local request (PROXY) */
17680 conn->must_close = 1;
17681 }
17682 } else {
17683 conn->must_close = 1;
17684 }
17685
17686 if (ri->remote_user != NULL) {
17687 mg_free((void *)ri->remote_user);
17688 /* Important! When having connections with and without auth
17689 * would cause double free and then crash */
17690 ri->remote_user = NULL;
17691 }
17692
17693 /* NOTE(lsm): order is important here. should_keep_alive() call
17694 * is using parsed request, which will be invalid after
17695 * memmove's below.
17696 * Therefore, memorize should_keep_alive() result now for later
17697 * use in loop exit condition. */
17698 /* Enable it only if this request is completely discardable. */
17699 keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
17700 && (conn->content_len >= 0) && (conn->request_len > 0)
17701 && ((conn->is_chunked == 4)
17702 || (!conn->is_chunked
17703 && ((conn->consumed_content == conn->content_len)
17704 || ((conn->request_len + conn->content_len)
17705 <= conn->data_len))));
17706
17707 if (keep_alive) {
17708 /* Discard all buffered data for this request */
17709 discard_len =
17710 ((conn->request_len + conn->content_len) < conn->data_len)
17711 ? (int)(conn->request_len + conn->content_len)
17712 : conn->data_len;
17713 conn->data_len -= discard_len;
17714 if (conn->data_len > 0) {
17715 DEBUG_TRACE("discard_len = %d", discard_len);
17716 memmove(conn->buf,
17717 conn->buf + discard_len,
17718 (size_t)conn->data_len);
17719 }
17720 }
17721
17722 DEBUG_ASSERT(conn->data_len >= 0);
17723 DEBUG_ASSERT(conn->data_len <= conn->buf_size);
17724
17725 if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
17726 DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
17727 (long int)conn->data_len,
17728 (long int)conn->buf_size);
17729 break;
17730 }
17731
17732 conn->handled_requests++;
17733
17734 } while (keep_alive);
17735
17736 DEBUG_TRACE("Done processing connection from %s (%f sec)",
17737 conn->request_info.remote_addr,
17738 difftime(time(NULL), conn->conn_birth_time));
17739
17740 close_connection(conn);
17741
17742 #if defined(USE_SERVER_STATS)
17743 mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
17744 mg_atomic_dec(&(conn->phys_ctx->active_connections));
17745 #endif
17746 }
17747
17748
17749 #if defined(ALTERNATIVE_QUEUE)
17750
17751 static void
17752 produce_socket(struct mg_context *ctx, const struct socket *sp)
17753 {
17754 unsigned int i;
17755
17756 while (!ctx->stop_flag) {
17757 for (i = 0; i < ctx->cfg_worker_threads; i++) {
17758 /* find a free worker slot and signal it */
17759 if (ctx->client_socks[i].in_use == 2) {
17760 (void)pthread_mutex_lock(&ctx->thread_mutex);
17761 if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
17762 ctx->client_socks[i] = *sp;
17763 ctx->client_socks[i].in_use = 1;
17764 /* socket has been moved to the consumer */
17765 (void)pthread_mutex_unlock(&ctx->thread_mutex);
17766 (void)event_signal(ctx->client_wait_events[i]);
17767 return;
17768 }
17769 (void)pthread_mutex_unlock(&ctx->thread_mutex);
17770 }
17771 }
17772 /* queue is full */
17773 mg_sleep(1);
17774 }
17775 /* must consume */
17776 set_blocking_mode(sp->sock);
17777 closesocket(sp->sock);
17778 }
17779
17780
17781 static int
17782 consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
17783 {
17784 DEBUG_TRACE("%s", "going idle");
17785 (void)pthread_mutex_lock(&ctx->thread_mutex);
17786 ctx->client_socks[thread_index].in_use = 2;
17787 (void)pthread_mutex_unlock(&ctx->thread_mutex);
17788
17789 event_wait(ctx->client_wait_events[thread_index]);
17790
17791 (void)pthread_mutex_lock(&ctx->thread_mutex);
17792 *sp = ctx->client_socks[thread_index];
17793 if (ctx->stop_flag) {
17794 (void)pthread_mutex_unlock(&ctx->thread_mutex);
17795 if (sp->in_use == 1) {
17796 /* must consume */
17797 set_blocking_mode(sp->sock);
17798 closesocket(sp->sock);
17799 }
17800 return 0;
17801 }
17802 (void)pthread_mutex_unlock(&ctx->thread_mutex);
17803 if (sp->in_use == 1) {
17804 DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
17805 return 1;
17806 }
17807 /* must not reach here */
17808 DEBUG_ASSERT(0);
17809 return 0;
17810 }
17811
17812 #else /* ALTERNATIVE_QUEUE */
17813
17814 /* Worker threads take accepted socket from the queue */
17815 static int
17816 consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
17817 {
17818 #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
17819
17820 (void)thread_index;
17821
17822 (void)pthread_mutex_lock(&ctx->thread_mutex);
17823 DEBUG_TRACE("%s", "going idle");
17824
17825 /* If the queue is empty, wait. We're idle at this point. */
17826 while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
17827 pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
17828 }
17829
17830 /* If we're stopping, sq_head may be equal to sq_tail. */
17831 if (ctx->sq_head > ctx->sq_tail) {
17832 /* Copy socket from the queue and increment tail */
17833 *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
17834 ctx->sq_tail++;
17835
17836 DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
17837
17838 /* Wrap pointers if needed */
17839 while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
17840 ctx->sq_tail -= QUEUE_SIZE(ctx);
17841 ctx->sq_head -= QUEUE_SIZE(ctx);
17842 }
17843 }
17844
17845 (void)pthread_cond_signal(&ctx->sq_empty);
17846 (void)pthread_mutex_unlock(&ctx->thread_mutex);
17847
17848 return !ctx->stop_flag;
17849 #undef QUEUE_SIZE
17850 }
17851
17852
17853 /* Master thread adds accepted socket to a queue */
17854 static void
17855 produce_socket(struct mg_context *ctx, const struct socket *sp)
17856 {
17857 #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
17858 if (!ctx) {
17859 return;
17860 }
17861 (void)pthread_mutex_lock(&ctx->thread_mutex);
17862
17863 /* If the queue is full, wait */
17864 while ((ctx->stop_flag == 0)
17865 && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
17866 (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
17867 }
17868
17869 if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
17870 /* Copy socket to the queue and increment head */
17871 ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
17872 ctx->sq_head++;
17873 DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
17874 }
17875
17876 (void)pthread_cond_signal(&ctx->sq_full);
17877 (void)pthread_mutex_unlock(&ctx->thread_mutex);
17878 #undef QUEUE_SIZE
17879 }
17880 #endif /* ALTERNATIVE_QUEUE */
17881
17882
17883 static void
17884 worker_thread_run(struct mg_connection *conn)
17885 {
17886 struct mg_context *ctx = conn->phys_ctx;
17887 int thread_index;
17888 struct mg_workerTLS tls;
17889
17890 #if defined(MG_LEGACY_INTERFACE)
17891 uint32_t addr;
17892 #endif
17893
17894 mg_set_thread_name("worker");
17895
17896 tls.is_master = 0;
17897 tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
17898 #if defined(_WIN32)
17899 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
17900 #endif
17901
17902 /* Initialize thread local storage before calling any callback */
17903 pthread_setspecific(sTlsKey, &tls);
17904
17905 /* Check if there is a user callback */
17906 if (ctx->callbacks.init_thread) {
17907 /* call init_thread for a worker thread (type 1), and store the return
17908 * value */
17909 tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
17910 } else {
17911 /* No callback: set user pointer to NULL */
17912 tls.user_ptr = NULL;
17913 }
17914
17915 /* Connection structure has been pre-allocated */
17916 thread_index = (int)(conn - ctx->worker_connections);
17917 if ((thread_index < 0)
17918 || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
17919 mg_cry_ctx_internal(ctx,
17920 "Internal error: Invalid worker index %i",
17921 thread_index);
17922 return;
17923 }
17924
17925 /* Request buffers are not pre-allocated. They are private to the
17926 * request and do not contain any state information that might be
17927 * of interest to anyone observing a server status. */
17928 conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
17929 if (conn->buf == NULL) {
17930 mg_cry_ctx_internal(
17931 ctx,
17932 "Out of memory: Cannot allocate buffer for worker %i",
17933 thread_index);
17934 return;
17935 }
17936 conn->buf_size = (int)ctx->max_request_size;
17937
17938 conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
17939 conn->host = NULL; /* until we have more information. */
17940
17941 conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
17942
17943 conn->request_info.user_data = ctx->user_data;
17944 /* Allocate a mutex for this connection to allow communication both
17945 * within the request handler and from elsewhere in the application
17946 */
17947 if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
17948 mg_free(conn->buf);
17949 mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
17950 return;
17951 }
17952
17953 #if defined(USE_SERVER_STATS)
17954 conn->conn_state = 1; /* not consumed */
17955 #endif
17956
17957 /* Call consume_socket() even when ctx->stop_flag > 0, to let it
17958 * signal sq_empty condvar to wake up the master waiting in
17959 * produce_socket() */
17960 while (consume_socket(ctx, &conn->client, thread_index)) {
17961
17962 conn->conn_birth_time = time(NULL);
17963
17964 /* Fill in IP, port info early so even if SSL setup below fails,
17965 * error handler would have the corresponding info.
17966 * Thanks to Johannes Winkelmann for the patch.
17967 */
17968 #if defined(USE_IPV6)
17969 if (conn->client.rsa.sa.sa_family == AF_INET6) {
17970 conn->request_info.remote_port =
17971 ntohs(conn->client.rsa.sin6.sin6_port);
17972 } else
17973 #endif
17974 {
17975 conn->request_info.remote_port =
17976 ntohs(conn->client.rsa.sin.sin_port);
17977 }
17978
17979 sockaddr_to_string(conn->request_info.remote_addr,
17980 sizeof(conn->request_info.remote_addr),
17981 &conn->client.rsa);
17982
17983 DEBUG_TRACE("Start processing connection from %s",
17984 conn->request_info.remote_addr);
17985
17986 conn->request_info.is_ssl = conn->client.is_ssl;
17987
17988 if (conn->client.is_ssl) {
17989 #if !defined(NO_SSL)
17990 /* HTTPS connection */
17991 if (sslize(conn,
17992 conn->dom_ctx->ssl_ctx,
17993 SSL_accept,
17994 &(conn->phys_ctx->stop_flag),
17995 NULL)) {
17996 /* conn->dom_ctx is set in get_request */
17997
17998 /* Get SSL client certificate information (if set) */
17999 ssl_get_client_cert_info(conn);
18000
18001 /* process HTTPS connection */
18002 process_new_connection(conn);
18003
18004 /* Free client certificate info */
18005 if (conn->request_info.client_cert) {
18006 mg_free((void *)(conn->request_info.client_cert->subject));
18007 mg_free((void *)(conn->request_info.client_cert->issuer));
18008 mg_free((void *)(conn->request_info.client_cert->serial));
18009 mg_free((void *)(conn->request_info.client_cert->finger));
18010 /* Free certificate memory */
18011 X509_free(
18012 (X509 *)conn->request_info.client_cert->peer_cert);
18013 conn->request_info.client_cert->peer_cert = 0;
18014 conn->request_info.client_cert->subject = 0;
18015 conn->request_info.client_cert->issuer = 0;
18016 conn->request_info.client_cert->serial = 0;
18017 conn->request_info.client_cert->finger = 0;
18018 mg_free(conn->request_info.client_cert);
18019 conn->request_info.client_cert = 0;
18020 }
18021 } else {
18022 /* make sure the connection is cleaned up on SSL failure */
18023 close_connection(conn);
18024 }
18025 #endif
18026 } else {
18027 /* process HTTP connection */
18028 process_new_connection(conn);
18029 }
18030
18031 DEBUG_TRACE("%s", "Connection closed");
18032 }
18033
18034
18035 /* Call exit thread user callback */
18036 if (ctx->callbacks.exit_thread) {
18037 ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
18038 }
18039
18040 /* delete thread local storage objects */
18041 pthread_setspecific(sTlsKey, NULL);
18042 #if defined(_WIN32)
18043 CloseHandle(tls.pthread_cond_helper_mutex);
18044 #endif
18045 pthread_mutex_destroy(&conn->mutex);
18046
18047 /* Free the request buffer. */
18048 conn->buf_size = 0;
18049 mg_free(conn->buf);
18050 conn->buf = NULL;
18051
18052 #if defined(USE_SERVER_STATS)
18053 conn->conn_state = 9; /* done */
18054 #endif
18055
18056 DEBUG_TRACE("%s", "exiting");
18057 }
18058
18059
18060 /* Threads have different return types on Windows and Unix. */
18061 #if defined(_WIN32)
18062 static unsigned __stdcall worker_thread(void *thread_func_param)
18063 {
18064 worker_thread_run((struct mg_connection *)thread_func_param);
18065 return 0;
18066 }
18067 #else
18068 static void *
18069 worker_thread(void *thread_func_param)
18070 {
18071 #if !defined(__ZEPHYR__)
18072 struct sigaction sa;
18073
18074 /* Ignore SIGPIPE */
18075 memset(&sa, 0, sizeof(sa));
18076 sa.sa_handler = SIG_IGN;
18077 sigaction(SIGPIPE, &sa, NULL);
18078 #endif
18079
18080 worker_thread_run((struct mg_connection *)thread_func_param);
18081 return NULL;
18082 }
18083 #endif /* _WIN32 */
18084
18085
18086 /* This is an internal function, thus all arguments are expected to be
18087 * valid - a NULL check is not required. */
18088 static void
18089 accept_new_connection(const struct socket *listener, struct mg_context *ctx)
18090 {
18091 struct socket so;
18092 char src_addr[IP_ADDR_STR_LEN];
18093 socklen_t len = sizeof(so.rsa);
18094 #if !defined(__ZEPHYR__)
18095 int on = 1;
18096 #endif
18097
18098 if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
18099 == INVALID_SOCKET) {
18100 } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
18101 sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
18102 mg_cry_ctx_internal(ctx,
18103 "%s: %s is not allowed to connect",
18104 __func__,
18105 src_addr);
18106 closesocket(so.sock);
18107 } else {
18108 /* Put so socket structure into the queue */
18109 DEBUG_TRACE("Accepted socket %d", (int)so.sock);
18110 set_close_on_exec(so.sock, NULL, ctx);
18111 so.is_ssl = listener->is_ssl;
18112 so.ssl_redir = listener->ssl_redir;
18113 if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
18114 mg_cry_ctx_internal(ctx,
18115 "%s: getsockname() failed: %s",
18116 __func__,
18117 strerror(ERRNO));
18118 }
18119
18120 #if !defined(__ZEPHYR__)
18121 /* Set TCP keep-alive. This is needed because if HTTP-level
18122 * keep-alive
18123 * is enabled, and client resets the connection, server won't get
18124 * TCP FIN or RST and will keep the connection open forever. With
18125 * TCP keep-alive, next keep-alive handshake will figure out that
18126 * the client is down and will close the server end.
18127 * Thanks to Igor Klopov who suggested the patch. */
18128 if (setsockopt(so.sock,
18129 SOL_SOCKET,
18130 SO_KEEPALIVE,
18131 (SOCK_OPT_TYPE)&on,
18132 sizeof(on))
18133 != 0) {
18134 mg_cry_ctx_internal(
18135 ctx,
18136 "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
18137 __func__,
18138 strerror(ERRNO));
18139 }
18140 #endif
18141
18142 /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
18143 * to effectively fill up the underlying IP packet payload and
18144 * reduce the overhead of sending lots of small buffers. However
18145 * this hurts the server's throughput (ie. operations per second)
18146 * when HTTP 1.1 persistent connections are used and the responses
18147 * are relatively small (eg. less than 1400 bytes).
18148 */
18149 if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
18150 && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
18151 if (set_tcp_nodelay(so.sock, 1) != 0) {
18152 mg_cry_ctx_internal(
18153 ctx,
18154 "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
18155 __func__,
18156 strerror(ERRNO));
18157 }
18158 }
18159
18160 /* The "non blocking" property should already be
18161 * inherited from the parent socket. Set it for
18162 * non-compliant socket implementations. */
18163 set_non_blocking_mode(so.sock);
18164
18165 so.in_use = 0;
18166 produce_socket(ctx, &so);
18167 }
18168 }
18169
18170
18171 static void
18172 master_thread_run(struct mg_context *ctx)
18173 {
18174 struct mg_workerTLS tls;
18175 struct mg_pollfd *pfd;
18176 unsigned int i;
18177 unsigned int workerthreadcount;
18178
18179 if (!ctx) {
18180 return;
18181 }
18182
18183 mg_set_thread_name("master");
18184
18185 /* Increase priority of the master thread */
18186 #if defined(_WIN32)
18187 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
18188 #elif defined(USE_MASTER_THREAD_PRIORITY)
18189 int min_prio = sched_get_priority_min(SCHED_RR);
18190 int max_prio = sched_get_priority_max(SCHED_RR);
18191 if ((min_prio >= 0) && (max_prio >= 0)
18192 && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
18193 && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
18194 struct sched_param sched_param = {0};
18195 sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
18196 pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
18197 }
18198 #endif
18199
18200 /* Initialize thread local storage */
18201 #if defined(_WIN32)
18202 tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
18203 #endif
18204 tls.is_master = 1;
18205 pthread_setspecific(sTlsKey, &tls);
18206
18207 if (ctx->callbacks.init_thread) {
18208 /* Callback for the master thread (type 0) */
18209 tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
18210 } else {
18211 tls.user_ptr = NULL;
18212 }
18213
18214 /* Server starts *now* */
18215 ctx->start_time = time(NULL);
18216
18217 /* Start the server */
18218 pfd = ctx->listening_socket_fds;
18219 while (ctx->stop_flag == 0) {
18220 for (i = 0; i < ctx->num_listening_sockets; i++) {
18221 pfd[i].fd = ctx->listening_sockets[i].sock;
18222 pfd[i].events = POLLIN;
18223 }
18224
18225 if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
18226 for (i = 0; i < ctx->num_listening_sockets; i++) {
18227 /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
18228 * successful poll, and POLLIN is defined as
18229 * (POLLRDNORM | POLLRDBAND)
18230 * Therefore, we're checking pfd[i].revents & POLLIN, not
18231 * pfd[i].revents == POLLIN. */
18232 if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
18233 accept_new_connection(&ctx->listening_sockets[i], ctx);
18234 }
18235 }
18236 }
18237 }
18238
18239 /* Here stop_flag is 1 - Initiate shutdown. */
18240 DEBUG_TRACE("%s", "stopping workers");
18241
18242 /* Stop signal received: somebody called mg_stop. Quit. */
18243 close_all_listening_sockets(ctx);
18244
18245 /* Wakeup workers that are waiting for connections to handle. */
18246 #if defined(ALTERNATIVE_QUEUE)
18247 for (i = 0; i < ctx->cfg_worker_threads; i++) {
18248 event_signal(ctx->client_wait_events[i]);
18249 }
18250 #else
18251 (void)pthread_mutex_lock(&ctx->thread_mutex);
18252 pthread_cond_broadcast(&ctx->sq_full);
18253 (void)pthread_mutex_unlock(&ctx->thread_mutex);
18254 #endif
18255
18256 /* Join all worker threads to avoid leaking threads. */
18257 workerthreadcount = ctx->cfg_worker_threads;
18258 for (i = 0; i < workerthreadcount; i++) {
18259 if (ctx->worker_threadids[i] != 0) {
18260 mg_join_thread(ctx->worker_threadids[i]);
18261 }
18262 }
18263
18264 #if defined(USE_LUA)
18265 /* Free Lua state of lua background task */
18266 if (ctx->lua_background_state) {
18267 lua_State *lstate = (lua_State *)ctx->lua_background_state;
18268 lua_getglobal(lstate, LUABACKGROUNDPARAMS);
18269 if (lua_istable(lstate, -1)) {
18270 reg_boolean(lstate, "shutdown", 1);
18271 lua_pop(lstate, 1);
18272 mg_sleep(2);
18273 }
18274 lua_close(lstate);
18275 ctx->lua_background_state = 0;
18276 }
18277 #endif
18278
18279 DEBUG_TRACE("%s", "exiting");
18280
18281 /* call exit thread callback */
18282 if (ctx->callbacks.exit_thread) {
18283 /* Callback for the master thread (type 0) */
18284 ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
18285 }
18286
18287 #if defined(_WIN32)
18288 CloseHandle(tls.pthread_cond_helper_mutex);
18289 #endif
18290 pthread_setspecific(sTlsKey, NULL);
18291
18292 /* Signal mg_stop() that we're done.
18293 * WARNING: This must be the very last thing this
18294 * thread does, as ctx becomes invalid after this line. */
18295 ctx->stop_flag = 2;
18296 }
18297
18298
18299 /* Threads have different return types on Windows and Unix. */
18300 #if defined(_WIN32)
18301 static unsigned __stdcall master_thread(void *thread_func_param)
18302 {
18303 master_thread_run((struct mg_context *)thread_func_param);
18304 return 0;
18305 }
18306 #else
18307 static void *
18308 master_thread(void *thread_func_param)
18309 {
18310 #if !defined(__ZEPHYR__)
18311 struct sigaction sa;
18312
18313 /* Ignore SIGPIPE */
18314 memset(&sa, 0, sizeof(sa));
18315 sa.sa_handler = SIG_IGN;
18316 sigaction(SIGPIPE, &sa, NULL);
18317 #endif
18318
18319 master_thread_run((struct mg_context *)thread_func_param);
18320 return NULL;
18321 }
18322 #endif /* _WIN32 */
18323
18324
18325 static void
18326 free_context(struct mg_context *ctx)
18327 {
18328 int i;
18329 struct mg_handler_info *tmp_rh;
18330
18331 if (ctx == NULL) {
18332 return;
18333 }
18334
18335 if (ctx->callbacks.exit_context) {
18336 ctx->callbacks.exit_context(ctx);
18337 }
18338
18339 /* All threads exited, no sync is needed. Destroy thread mutex and
18340 * condvars
18341 */
18342 (void)pthread_mutex_destroy(&ctx->thread_mutex);
18343 #if defined(ALTERNATIVE_QUEUE)
18344 mg_free(ctx->client_socks);
18345 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
18346 event_destroy(ctx->client_wait_events[i]);
18347 }
18348 mg_free(ctx->client_wait_events);
18349 #else
18350 (void)pthread_cond_destroy(&ctx->sq_empty);
18351 (void)pthread_cond_destroy(&ctx->sq_full);
18352 #endif
18353
18354 /* Destroy other context global data structures mutex */
18355 (void)pthread_mutex_destroy(&ctx->nonce_mutex);
18356
18357 #if defined(USE_TIMERS)
18358 timers_exit(ctx);
18359 #endif
18360
18361 /* Deallocate config parameters */
18362 for (i = 0; i < NUM_OPTIONS; i++) {
18363 if (ctx->dd.config[i] != NULL) {
18364 #if defined(_MSC_VER)
18365 #pragma warning(suppress : 6001)
18366 #endif
18367 mg_free(ctx->dd.config[i]);
18368 }
18369 }
18370
18371 /* Deallocate request handlers */
18372 while (ctx->dd.handlers) {
18373 tmp_rh = ctx->dd.handlers;
18374 ctx->dd.handlers = tmp_rh->next;
18375 if (tmp_rh->handler_type == REQUEST_HANDLER) {
18376 pthread_cond_destroy(&tmp_rh->refcount_cond);
18377 pthread_mutex_destroy(&tmp_rh->refcount_mutex);
18378 }
18379 mg_free(tmp_rh->uri);
18380 mg_free(tmp_rh);
18381 }
18382
18383 #if !defined(NO_SSL)
18384 /* Deallocate SSL context */
18385 if (ctx->dd.ssl_ctx != NULL) {
18386 void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
18387 int callback_ret =
18388 (ctx->callbacks.external_ssl_ctx == NULL)
18389 ? 0
18390 : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
18391
18392 if (callback_ret == 0) {
18393 SSL_CTX_free(ctx->dd.ssl_ctx);
18394 }
18395 /* else: ignore error and ommit SSL_CTX_free in case
18396 * callback_ret is 1 */
18397 }
18398 #endif /* !NO_SSL */
18399
18400 /* Deallocate worker thread ID array */
18401 mg_free(ctx->worker_threadids);
18402
18403 /* Deallocate worker thread ID array */
18404 mg_free(ctx->worker_connections);
18405
18406 /* deallocate system name string */
18407 mg_free(ctx->systemName);
18408
18409 /* Deallocate context itself */
18410 mg_free(ctx);
18411 }
18412
18413
18414 void
18415 mg_stop(struct mg_context *ctx)
18416 {
18417 pthread_t mt;
18418 if (!ctx) {
18419 return;
18420 }
18421
18422 /* We don't use a lock here. Calling mg_stop with the same ctx from
18423 * two threads is not allowed. */
18424 mt = ctx->masterthreadid;
18425 if (mt == 0) {
18426 return;
18427 }
18428
18429 ctx->masterthreadid = 0;
18430
18431 /* Set stop flag, so all threads know they have to exit. */
18432 ctx->stop_flag = 1;
18433
18434 /* Wait until everything has stopped. */
18435 while (ctx->stop_flag != 2) {
18436 (void)mg_sleep(10);
18437 }
18438
18439 mg_join_thread(mt);
18440 free_context(ctx);
18441
18442 #if defined(_WIN32)
18443 (void)WSACleanup();
18444 #endif /* _WIN32 */
18445 }
18446
18447
18448 static void
18449 get_system_name(char **sysName)
18450 {
18451 #if defined(_WIN32)
18452 #if !defined(__SYMBIAN32__)
18453 #if defined(_WIN32_WCE)
18454 *sysName = mg_strdup("WinCE");
18455 #else
18456 char name[128];
18457 DWORD dwVersion = 0;
18458 DWORD dwMajorVersion = 0;
18459 DWORD dwMinorVersion = 0;
18460 DWORD dwBuild = 0;
18461 BOOL wowRet, isWoW = FALSE;
18462
18463 #if defined(_MSC_VER)
18464 #pragma warning(push)
18465 /* GetVersion was declared deprecated */
18466 #pragma warning(disable : 4996)
18467 #endif
18468 dwVersion = GetVersion();
18469 #if defined(_MSC_VER)
18470 #pragma warning(pop)
18471 #endif
18472
18473 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
18474 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
18475 dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
18476 (void)dwBuild;
18477
18478 wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
18479
18480 sprintf(name,
18481 "Windows %u.%u%s",
18482 (unsigned)dwMajorVersion,
18483 (unsigned)dwMinorVersion,
18484 (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
18485
18486 *sysName = mg_strdup(name);
18487 #endif
18488 #else
18489 *sysName = mg_strdup("Symbian");
18490 #endif
18491 #elif defined(__ZEPHYR__)
18492 *sysName = mg_strdup("Zephyr OS");
18493 #else
18494 struct utsname name;
18495 memset(&name, 0, sizeof(name));
18496 uname(&name);
18497 *sysName = mg_strdup(name.sysname);
18498 #endif
18499 }
18500
18501
18502 static void legacy_init(const char **options) {
18503 const char *ports_option =
18504 config_options[LISTENING_PORTS].default_value;
18505
18506 if (options) {
18507 const char **run_options = options;
18508 const char *optname = config_options[LISTENING_PORTS].name;
18509
18510 /* Try to find the "listening_ports" option */
18511 while (*run_options) {
18512 if (!strcmp(*run_options, optname)) {
18513 ports_option = run_options[1];
18514 }
18515 run_options += 2;
18516 }
18517 }
18518
18519 if (is_ssl_port_used(ports_option)) {
18520 /* Initialize with SSL support */
18521 mg_init_library(MG_FEATURES_TLS);
18522 }
18523 else {
18524 /* Initialize without SSL support */
18525 mg_init_library(MG_FEATURES_DEFAULT);
18526 }
18527 }
18528
18529 struct mg_context *
18530 mg_start(const struct mg_callbacks *callbacks,
18531 void *user_data,
18532 const char **options)
18533 {
18534 struct mg_context *ctx;
18535 const char *name, *value, *default_value;
18536 int idx, ok, workerthreadcount;
18537 unsigned int i;
18538 int itmp;
18539 void (*exit_callback)(const struct mg_context *ctx) = 0;
18540
18541 struct mg_workerTLS tls;
18542
18543 #if defined(_WIN32)
18544 WSADATA data;
18545 WSAStartup(MAKEWORD(2, 2), &data);
18546 #endif /* _WIN32 */
18547
18548 if (mg_init_library_called == 0) {
18549 /* Legacy INIT, if mg_start is called without mg_init_library.
18550 * Note: This will cause a memory leak when unloading the library. */
18551 legacy_init(options);
18552 }
18553
18554 /* Allocate context and initialize reasonable general case defaults. */
18555 if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
18556 return NULL;
18557 }
18558
18559 /* Random number generator will initialize at the first call */
18560 ctx->dd.auth_nonce_mask =
18561 (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
18562
18563 tls.is_master = -1;
18564 tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
18565 #if defined(_WIN32)
18566 tls.pthread_cond_helper_mutex = NULL;
18567 #endif
18568 pthread_setspecific(sTlsKey, &tls);
18569
18570 ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
18571 #if !defined(ALTERNATIVE_QUEUE)
18572 ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
18573 ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
18574 #endif
18575 ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
18576 if (!ok) {
18577 /* Fatal error - abort start. However, this situation should never
18578 * occur in practice. */
18579 mg_cry_ctx_internal(ctx,
18580 "%s",
18581 "Cannot initialize thread synchronization objects");
18582 mg_free(ctx);
18583 pthread_setspecific(sTlsKey, NULL);
18584 return NULL;
18585 }
18586
18587 if (callbacks) {
18588 ctx->callbacks = *callbacks;
18589 exit_callback = callbacks->exit_context;
18590 ctx->callbacks.exit_context = 0;
18591 }
18592 ctx->user_data = user_data;
18593 ctx->dd.handlers = NULL;
18594 ctx->dd.next = NULL;
18595
18596 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
18597 ctx->dd.shared_lua_websockets = NULL;
18598 #endif
18599
18600 /* Store options */
18601 while (options && (name = *options++) != NULL) {
18602 if ((idx = get_option_index(name)) == -1) {
18603 mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
18604 free_context(ctx);
18605 pthread_setspecific(sTlsKey, NULL);
18606 return NULL;
18607 } else if ((value = *options++) == NULL) {
18608 mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
18609 free_context(ctx);
18610 pthread_setspecific(sTlsKey, NULL);
18611 return NULL;
18612 }
18613 if (ctx->dd.config[idx] != NULL) {
18614 mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
18615 mg_free(ctx->dd.config[idx]);
18616 }
18617 ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
18618 DEBUG_TRACE("[%s] -> [%s]", name, value);
18619 }
18620
18621 /* Set default value if needed */
18622 for (i = 0; config_options[i].name != NULL; i++) {
18623 default_value = config_options[i].default_value;
18624 if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
18625 ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
18626 }
18627 }
18628
18629 /* Request size option */
18630 itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
18631 if (itmp < 1024) {
18632 mg_cry_ctx_internal(ctx, "%s", "max_request_size too small");
18633 free_context(ctx);
18634 pthread_setspecific(sTlsKey, NULL);
18635 return NULL;
18636 }
18637 ctx->max_request_size = (unsigned)itmp;
18638
18639 /* Worker thread count option */
18640 workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
18641
18642 if (workerthreadcount > MAX_WORKER_THREADS) {
18643 mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
18644 free_context(ctx);
18645 pthread_setspecific(sTlsKey, NULL);
18646 return NULL;
18647 }
18648
18649 if (workerthreadcount <= 0) {
18650 mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
18651 free_context(ctx);
18652 pthread_setspecific(sTlsKey, NULL);
18653 return NULL;
18654 }
18655
18656 /* Document root */
18657 #if defined(NO_FILES)
18658 if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
18659 mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
18660 free_context(ctx);
18661 pthread_setspecific(sTlsKey, NULL);
18662 return NULL;
18663 }
18664 #endif
18665
18666 get_system_name(&ctx->systemName);
18667
18668 #if defined(USE_LUA)
18669 /* If a Lua background script has been configured, start it. */
18670 if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
18671 char ebuf[256];
18672 struct vec opt_vec;
18673 struct vec eq_vec;
18674 const char *sparams;
18675 lua_State *state = mg_prepare_lua_context_script(
18676 ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
18677 if (!state) {
18678 mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
18679 free_context(ctx);
18680 pthread_setspecific(sTlsKey, NULL);
18681 return NULL;
18682 }
18683 ctx->lua_background_state = (void *)state;
18684
18685 lua_newtable(state);
18686 reg_boolean(state, "shutdown", 0);
18687
18688 sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
18689
18690 while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
18691 reg_llstring(
18692 state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
18693 if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
18694 break;
18695 }
18696 lua_setglobal(state, LUABACKGROUNDPARAMS);
18697
18698 } else {
18699 ctx->lua_background_state = 0;
18700 }
18701 #endif
18702
18703 /* NOTE(lsm): order is important here. SSL certificates must
18704 * be initialized before listening ports. UID must be set last. */
18705 if (
18706 #if !defined(NO_FILESYSTEMS)
18707 !set_gpass_option(ctx, NULL) ||
18708 #endif
18709 #if !defined(NO_SSL)
18710 !init_ssl_ctx(ctx, NULL) ||
18711 #endif
18712 !set_ports_option(ctx) ||
18713 #if !defined(_WIN32) && !defined(__ZEPHYR__)
18714 !set_uid_option(ctx) ||
18715 #endif
18716 !set_acl_option(ctx)) {
18717 free_context(ctx);
18718 pthread_setspecific(sTlsKey, NULL);
18719 return NULL;
18720 }
18721
18722 ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
18723 ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
18724 sizeof(pthread_t),
18725 ctx);
18726
18727 if (ctx->worker_threadids == NULL) {
18728 mg_cry_ctx_internal(ctx,
18729 "%s",
18730 "Not enough memory for worker thread ID array");
18731 free_context(ctx);
18732 pthread_setspecific(sTlsKey, NULL);
18733 return NULL;
18734 }
18735 ctx->worker_connections =
18736 (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
18737 sizeof(struct mg_connection),
18738 ctx);
18739 if (ctx->worker_connections == NULL) {
18740 mg_cry_ctx_internal(
18741 ctx, "%s", "Not enough memory for worker thread connection array");
18742 free_context(ctx);
18743 pthread_setspecific(sTlsKey, NULL);
18744 return NULL;
18745 }
18746
18747
18748 #if defined(ALTERNATIVE_QUEUE)
18749 ctx->client_wait_events =
18750 (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
18751 sizeof(ctx->client_wait_events[0]),
18752 ctx);
18753 if (ctx->client_wait_events == NULL) {
18754 mg_cry_ctx_internal(ctx,
18755 "%s",
18756 "Not enough memory for worker event array");
18757 mg_free(ctx->worker_threadids);
18758 free_context(ctx);
18759 pthread_setspecific(sTlsKey, NULL);
18760 return NULL;
18761 }
18762
18763 ctx->client_socks =
18764 (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
18765 sizeof(ctx->client_socks[0]),
18766 ctx);
18767 if (ctx->client_socks == NULL) {
18768 mg_cry_ctx_internal(ctx,
18769 "%s",
18770 "Not enough memory for worker socket array");
18771 mg_free(ctx->client_wait_events);
18772 mg_free(ctx->worker_threadids);
18773 free_context(ctx);
18774 pthread_setspecific(sTlsKey, NULL);
18775 return NULL;
18776 }
18777
18778 for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
18779 ctx->client_wait_events[i] = event_create();
18780 if (ctx->client_wait_events[i] == 0) {
18781 mg_cry_ctx_internal(ctx, "Error creating worker event %i", i);
18782 while (i > 0) {
18783 i--;
18784 event_destroy(ctx->client_wait_events[i]);
18785 }
18786 mg_free(ctx->client_socks);
18787 mg_free(ctx->client_wait_events);
18788 mg_free(ctx->worker_threadids);
18789 free_context(ctx);
18790 pthread_setspecific(sTlsKey, NULL);
18791 return NULL;
18792 }
18793 }
18794 #endif
18795
18796
18797 #if defined(USE_TIMERS)
18798 if (timers_init(ctx) != 0) {
18799 mg_cry_ctx_internal(ctx, "%s", "Error creating timers");
18800 free_context(ctx);
18801 pthread_setspecific(sTlsKey, NULL);
18802 return NULL;
18803 }
18804 #endif
18805
18806 /* Context has been created - init user libraries */
18807 if (ctx->callbacks.init_context) {
18808 ctx->callbacks.init_context(ctx);
18809 }
18810 ctx->callbacks.exit_context = exit_callback;
18811 ctx->context_type = CONTEXT_SERVER; /* server context */
18812
18813 /* Start master (listening) thread */
18814 mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
18815
18816 /* Start worker threads */
18817 for (i = 0; i < ctx->cfg_worker_threads; i++) {
18818 /* worker_thread sets up the other fields */
18819 ctx->worker_connections[i].phys_ctx = ctx;
18820 if (mg_start_thread_with_id(worker_thread,
18821 &ctx->worker_connections[i],
18822 &ctx->worker_threadids[i])
18823 != 0) {
18824
18825 /* thread was not created */
18826 if (i > 0) {
18827 mg_cry_ctx_internal(ctx,
18828 "Cannot start worker thread %i: error %ld",
18829 i + 1,
18830 (long)ERRNO);
18831 } else {
18832 mg_cry_ctx_internal(ctx,
18833 "Cannot create threads: error %ld",
18834 (long)ERRNO);
18835 free_context(ctx);
18836 pthread_setspecific(sTlsKey, NULL);
18837 return NULL;
18838 }
18839 break;
18840 }
18841 }
18842
18843 pthread_setspecific(sTlsKey, NULL);
18844 return ctx;
18845 }
18846
18847
18848 #if defined(MG_EXPERIMENTAL_INTERFACES)
18849 /* Add an additional domain to an already running web server. */
18850 int
18851 mg_start_domain(struct mg_context *ctx, const char **options)
18852 {
18853 const char *name;
18854 const char *value;
18855 const char *default_value;
18856 struct mg_domain_context *new_dom;
18857 struct mg_domain_context *dom;
18858 int idx, i;
18859
18860 if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
18861 return -1;
18862 }
18863
18864 new_dom = (struct mg_domain_context *)
18865 mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
18866
18867 if (!new_dom) {
18868 /* Out of memory */
18869 return -6;
18870 }
18871
18872 /* Store options - TODO: unite duplicate code */
18873 while (options && (name = *options++) != NULL) {
18874 if ((idx = get_option_index(name)) == -1) {
18875 mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
18876 mg_free(new_dom);
18877 return -2;
18878 } else if ((value = *options++) == NULL) {
18879 mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
18880 mg_free(new_dom);
18881 return -2;
18882 }
18883 if (new_dom->config[idx] != NULL) {
18884 mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
18885 mg_free(new_dom->config[idx]);
18886 }
18887 new_dom->config[idx] = mg_strdup_ctx(value, ctx);
18888 DEBUG_TRACE("[%s] -> [%s]", name, value);
18889 }
18890
18891 /* Authentication domain is mandatory */
18892 /* TODO: Maybe use a new option hostname? */
18893 if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
18894 mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
18895 mg_free(new_dom);
18896 return -4;
18897 }
18898
18899 /* Set default value if needed. Take the config value from
18900 * ctx as a default value. */
18901 for (i = 0; config_options[i].name != NULL; i++) {
18902 default_value = ctx->dd.config[i];
18903 if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
18904 new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
18905 }
18906 }
18907
18908 new_dom->handlers = NULL;
18909 new_dom->next = NULL;
18910 new_dom->nonce_count = 0;
18911 new_dom->auth_nonce_mask =
18912 (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
18913
18914 #if defined(USE_LUA) && defined(USE_WEBSOCKET)
18915 new_dom->shared_lua_websockets = NULL;
18916 #endif
18917
18918 if (!init_ssl_ctx(ctx, new_dom)) {
18919 /* Init SSL failed */
18920 mg_free(new_dom);
18921 return -3;
18922 }
18923
18924 /* Add element to linked list. */
18925 mg_lock_context(ctx);
18926
18927 idx = 0;
18928 dom = &(ctx->dd);
18929 for (;;) {
18930 if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
18931 dom->config[AUTHENTICATION_DOMAIN])) {
18932 /* Domain collision */
18933 mg_cry_ctx_internal(ctx,
18934 "domain %s already in use",
18935 new_dom->config[AUTHENTICATION_DOMAIN]);
18936 mg_free(new_dom);
18937 return -5;
18938 }
18939
18940 /* Count number of domains */
18941 idx++;
18942
18943 if (dom->next == NULL) {
18944 dom->next = new_dom;
18945 break;
18946 }
18947 dom = dom->next;
18948 }
18949
18950 mg_unlock_context(ctx);
18951
18952 /* Return domain number */
18953 return idx;
18954 }
18955 #endif
18956
18957
18958 /* Feature check API function */
18959 unsigned
18960 mg_check_feature(unsigned feature)
18961 {
18962 static const unsigned feature_set = 0
18963 /* Set bits for available features according to API documentation.
18964 * This bit mask is created at compile time, according to the active
18965 * preprocessor defines. It is a single const value at runtime. */
18966 #if !defined(NO_FILES)
18967 | MG_FEATURES_FILES
18968 #endif
18969 #if !defined(NO_SSL)
18970 | MG_FEATURES_SSL
18971 #endif
18972 #if !defined(NO_CGI)
18973 | MG_FEATURES_CGI
18974 #endif
18975 #if defined(USE_IPV6)
18976 | MG_FEATURES_IPV6
18977 #endif
18978 #if defined(USE_WEBSOCKET)
18979 | MG_FEATURES_WEBSOCKET
18980 #endif
18981 #if defined(USE_LUA)
18982 | MG_FEATURES_LUA
18983 #endif
18984 #if defined(USE_DUKTAPE)
18985 | MG_FEATURES_SSJS
18986 #endif
18987 #if !defined(NO_CACHING)
18988 | MG_FEATURES_CACHE
18989 #endif
18990 #if defined(USE_SERVER_STATS)
18991 | MG_FEATURES_STATS
18992 #endif
18993 #if defined(USE_ZLIB)
18994 | MG_FEATURES_COMPRESSION
18995 #endif
18996
18997 /* Set some extra bits not defined in the API documentation.
18998 * These bits may change without further notice. */
18999 #if defined(MG_LEGACY_INTERFACE)
19000 | 0x00008000u
19001 #endif
19002 #if defined(MG_EXPERIMENTAL_INTERFACES)
19003 | 0x00004000u
19004 #endif
19005 #if defined(MEMORY_DEBUGGING)
19006 | 0x00001000u
19007 #endif
19008 #if defined(USE_TIMERS)
19009 | 0x00020000u
19010 #endif
19011 #if !defined(NO_NONCE_CHECK)
19012 | 0x00040000u
19013 #endif
19014 #if !defined(NO_POPEN)
19015 | 0x00080000u
19016 #endif
19017 ;
19018 return (feature & feature_set);
19019 }
19020
19021
19022 static size_t
19023 mg_str_append(char **dst, char *end, const char *src)
19024 {
19025 size_t len = strlen(src);
19026 if (*dst != end) {
19027 /* Append src if enough space, or close dst. */
19028 if ((size_t)(end - *dst) > len) {
19029 strcpy(*dst, src);
19030 *dst += len;
19031 } else {
19032 *dst = end;
19033 }
19034 }
19035 return len;
19036 }
19037
19038
19039 /* Get system information. It can be printed or stored by the caller.
19040 * Return the size of available information. */
19041 int
19042 mg_get_system_info(char *buffer, int buflen)
19043 {
19044 char *end, *append_eoobj = NULL, block[256];
19045 size_t system_info_length = 0;
19046
19047 #if defined(_WIN32)
19048 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
19049 #else
19050 static const char eol[] = "\n", eoobj[] = "\n}\n";
19051 #endif
19052
19053 if ((buffer == NULL) || (buflen < 1)) {
19054 buflen = 0;
19055 end = buffer;
19056 } else {
19057 *buffer = 0;
19058 end = buffer + buflen;
19059 }
19060 if (buflen > (int)(sizeof(eoobj) - 1)) {
19061 /* has enough space to append eoobj */
19062 append_eoobj = buffer;
19063 end -= sizeof(eoobj) - 1;
19064 }
19065
19066 system_info_length += mg_str_append(&buffer, end, "{");
19067
19068 /* Server version */
19069 {
19070 const char *version = mg_version();
19071 mg_snprintf(NULL,
19072 NULL,
19073 block,
19074 sizeof(block),
19075 "%s\"version\" : \"%s\"",
19076 eol,
19077 version);
19078 system_info_length += mg_str_append(&buffer, end, block);
19079 }
19080
19081 /* System info */
19082 {
19083 #if defined(_WIN32)
19084 DWORD dwVersion = 0;
19085 DWORD dwMajorVersion = 0;
19086 DWORD dwMinorVersion = 0;
19087 SYSTEM_INFO si;
19088
19089 GetSystemInfo(&si);
19090
19091 #if defined(_MSC_VER)
19092 #pragma warning(push)
19093 /* GetVersion was declared deprecated */
19094 #pragma warning(disable : 4996)
19095 #endif
19096 dwVersion = GetVersion();
19097 #if defined(_MSC_VER)
19098 #pragma warning(pop)
19099 #endif
19100
19101 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
19102 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
19103
19104 mg_snprintf(NULL,
19105 NULL,
19106 block,
19107 sizeof(block),
19108 ",%s\"os\" : \"Windows %u.%u\"",
19109 eol,
19110 (unsigned)dwMajorVersion,
19111 (unsigned)dwMinorVersion);
19112 system_info_length += mg_str_append(&buffer, end, block);
19113
19114 mg_snprintf(NULL,
19115 NULL,
19116 block,
19117 sizeof(block),
19118 ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
19119 eol,
19120 (unsigned)si.wProcessorArchitecture,
19121 (unsigned)si.dwNumberOfProcessors,
19122 (unsigned)si.dwActiveProcessorMask);
19123 system_info_length += mg_str_append(&buffer, end, block);
19124 #elif defined(__ZEPHYR__)
19125 mg_snprintf(NULL,
19126 NULL,
19127 block,
19128 sizeof(block),
19129 ",%s\"os\" : \"%s %s\"",
19130 eol,
19131 "Zephyr OS",
19132 ZEPHYR_VERSION);
19133 system_info_length += mg_str_append(&buffer, end, block);
19134 #else
19135 struct utsname name;
19136 memset(&name, 0, sizeof(name));
19137 uname(&name);
19138
19139 mg_snprintf(NULL,
19140 NULL,
19141 block,
19142 sizeof(block),
19143 ",%s\"os\" : \"%s %s (%s) - %s\"",
19144 eol,
19145 name.sysname,
19146 name.version,
19147 name.release,
19148 name.machine);
19149 system_info_length += mg_str_append(&buffer, end, block);
19150 #endif
19151 }
19152
19153 /* Features */
19154 {
19155 mg_snprintf(NULL,
19156 NULL,
19157 block,
19158 sizeof(block),
19159 ",%s\"features\" : %lu"
19160 ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
19161 eol,
19162 (unsigned long)mg_check_feature(0xFFFFFFFFu),
19163 eol,
19164 mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
19165 mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
19166 mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
19167 mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
19168 mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
19169 : "",
19170 mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
19171 mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
19172 mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
19173 mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
19174 system_info_length += mg_str_append(&buffer, end, block);
19175
19176 #if defined(USE_LUA)
19177 mg_snprintf(NULL,
19178 NULL,
19179 block,
19180 sizeof(block),
19181 ",%s\"lua_version\" : \"%u (%s)\"",
19182 eol,
19183 (unsigned)LUA_VERSION_NUM,
19184 LUA_RELEASE);
19185 system_info_length += mg_str_append(&buffer, end, block);
19186 #endif
19187 #if defined(USE_DUKTAPE)
19188 mg_snprintf(NULL,
19189 NULL,
19190 block,
19191 sizeof(block),
19192 ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
19193 eol,
19194 (unsigned)DUK_VERSION / 10000,
19195 ((unsigned)DUK_VERSION / 100) % 100,
19196 (unsigned)DUK_VERSION % 100);
19197 system_info_length += mg_str_append(&buffer, end, block);
19198 #endif
19199 }
19200
19201 /* Build date */
19202 {
19203 #if defined(GCC_DIAGNOSTIC)
19204 #if GCC_VERSION >= 40900
19205 #pragma GCC diagnostic push
19206 /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
19207 #pragma GCC diagnostic ignored "-Wdate-time"
19208 #endif
19209 #endif
19210 mg_snprintf(NULL,
19211 NULL,
19212 block,
19213 sizeof(block),
19214 ",%s\"build\" : \"%s\"",
19215 eol,
19216 __DATE__);
19217
19218 #if defined(GCC_DIAGNOSTIC)
19219 #if GCC_VERSION >= 40900
19220 #pragma GCC diagnostic pop
19221 #endif
19222 #endif
19223
19224 system_info_length += mg_str_append(&buffer, end, block);
19225 }
19226
19227
19228 /* Compiler information */
19229 /* http://sourceforge.net/p/predef/wiki/Compilers/ */
19230 {
19231 #if defined(_MSC_VER)
19232 mg_snprintf(NULL,
19233 NULL,
19234 block,
19235 sizeof(block),
19236 ",%s\"compiler\" : \"MSC: %u (%u)\"",
19237 eol,
19238 (unsigned)_MSC_VER,
19239 (unsigned)_MSC_FULL_VER);
19240 system_info_length += mg_str_append(&buffer, end, block);
19241 #elif defined(__MINGW64__)
19242 mg_snprintf(NULL,
19243 NULL,
19244 block,
19245 sizeof(block),
19246 ",%s\"compiler\" : \"MinGW64: %u.%u\"",
19247 eol,
19248 (unsigned)__MINGW64_VERSION_MAJOR,
19249 (unsigned)__MINGW64_VERSION_MINOR);
19250 system_info_length += mg_str_append(&buffer, end, block);
19251 mg_snprintf(NULL,
19252 NULL,
19253 block,
19254 sizeof(block),
19255 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
19256 eol,
19257 (unsigned)__MINGW32_MAJOR_VERSION,
19258 (unsigned)__MINGW32_MINOR_VERSION);
19259 system_info_length += mg_str_append(&buffer, end, block);
19260 #elif defined(__MINGW32__)
19261 mg_snprintf(NULL,
19262 NULL,
19263 block,
19264 sizeof(block),
19265 ",%s\"compiler\" : \"MinGW32: %u.%u\"",
19266 eol,
19267 (unsigned)__MINGW32_MAJOR_VERSION,
19268 (unsigned)__MINGW32_MINOR_VERSION);
19269 system_info_length += mg_str_append(&buffer, end, block);
19270 #elif defined(__clang__)
19271 mg_snprintf(NULL,
19272 NULL,
19273 block,
19274 sizeof(block),
19275 ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
19276 eol,
19277 __clang_major__,
19278 __clang_minor__,
19279 __clang_patchlevel__,
19280 __clang_version__);
19281 system_info_length += mg_str_append(&buffer, end, block);
19282 #elif defined(__GNUC__)
19283 mg_snprintf(NULL,
19284 NULL,
19285 block,
19286 sizeof(block),
19287 ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
19288 eol,
19289 (unsigned)__GNUC__,
19290 (unsigned)__GNUC_MINOR__,
19291 (unsigned)__GNUC_PATCHLEVEL__);
19292 system_info_length += mg_str_append(&buffer, end, block);
19293 #elif defined(__INTEL_COMPILER)
19294 mg_snprintf(NULL,
19295 NULL,
19296 block,
19297 sizeof(block),
19298 ",%s\"compiler\" : \"Intel C/C++: %u\"",
19299 eol,
19300 (unsigned)__INTEL_COMPILER);
19301 system_info_length += mg_str_append(&buffer, end, block);
19302 #elif defined(__BORLANDC__)
19303 mg_snprintf(NULL,
19304 NULL,
19305 block,
19306 sizeof(block),
19307 ",%s\"compiler\" : \"Borland C: 0x%x\"",
19308 eol,
19309 (unsigned)__BORLANDC__);
19310 system_info_length += mg_str_append(&buffer, end, block);
19311 #elif defined(__SUNPRO_C)
19312 mg_snprintf(NULL,
19313 NULL,
19314 block,
19315 sizeof(block),
19316 ",%s\"compiler\" : \"Solaris: 0x%x\"",
19317 eol,
19318 (unsigned)__SUNPRO_C);
19319 system_info_length += mg_str_append(&buffer, end, block);
19320 #else
19321 mg_snprintf(NULL,
19322 NULL,
19323 block,
19324 sizeof(block),
19325 ",%s\"compiler\" : \"other\"",
19326 eol);
19327 system_info_length += mg_str_append(&buffer, end, block);
19328 #endif
19329 }
19330
19331 /* Determine 32/64 bit data mode.
19332 * see https://en.wikipedia.org/wiki/64-bit_computing */
19333 {
19334 mg_snprintf(NULL,
19335 NULL,
19336 block,
19337 sizeof(block),
19338 ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
19339 "char:%u/%u, "
19340 "ptr:%u, size:%u, time:%u\"",
19341 eol,
19342 (unsigned)sizeof(short),
19343 (unsigned)sizeof(int),
19344 (unsigned)sizeof(long),
19345 (unsigned)sizeof(long long),
19346 (unsigned)sizeof(float),
19347 (unsigned)sizeof(double),
19348 (unsigned)sizeof(long double),
19349 (unsigned)sizeof(char),
19350 (unsigned)sizeof(wchar_t),
19351 (unsigned)sizeof(void *),
19352 (unsigned)sizeof(size_t),
19353 (unsigned)sizeof(time_t));
19354 system_info_length += mg_str_append(&buffer, end, block);
19355 }
19356
19357 /* Terminate string */
19358 if (append_eoobj) {
19359 strcat(append_eoobj, eoobj);
19360 }
19361 system_info_length += sizeof(eoobj) - 1;
19362
19363 return (int)system_info_length;
19364 }
19365
19366
19367 /* Get context information. It can be printed or stored by the caller.
19368 * Return the size of available information. */
19369 int
19370 mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
19371 {
19372 #if defined(USE_SERVER_STATS)
19373 char *end, *append_eoobj = NULL, block[256];
19374 size_t context_info_length = 0;
19375
19376 #if defined(_WIN32)
19377 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
19378 #else
19379 static const char eol[] = "\n", eoobj[] = "\n}\n";
19380 #endif
19381 struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
19382
19383 if ((buffer == NULL) || (buflen < 1)) {
19384 buflen = 0;
19385 end = buffer;
19386 } else {
19387 *buffer = 0;
19388 end = buffer + buflen;
19389 }
19390 if (buflen > (int)(sizeof(eoobj) - 1)) {
19391 /* has enough space to append eoobj */
19392 append_eoobj = buffer;
19393 end -= sizeof(eoobj) - 1;
19394 }
19395
19396 context_info_length += mg_str_append(&buffer, end, "{");
19397
19398 if (ms) { /* <-- should be always true */
19399 /* Memory information */
19400 mg_snprintf(NULL,
19401 NULL,
19402 block,
19403 sizeof(block),
19404 "%s\"memory\" : {%s"
19405 "\"blocks\" : %i,%s"
19406 "\"used\" : %" INT64_FMT ",%s"
19407 "\"maxUsed\" : %" INT64_FMT "%s"
19408 "}",
19409 eol,
19410 eol,
19411 ms->blockCount,
19412 eol,
19413 ms->totalMemUsed,
19414 eol,
19415 ms->maxMemUsed,
19416 eol);
19417 context_info_length += mg_str_append(&buffer, end, block);
19418 }
19419
19420 if (ctx) {
19421 /* Declare all variables at begin of the block, to comply
19422 * with old C standards. */
19423 char start_time_str[64] = {0};
19424 char now_str[64] = {0};
19425 time_t start_time = ctx->start_time;
19426 time_t now = time(NULL);
19427
19428 /* Connections information */
19429 mg_snprintf(NULL,
19430 NULL,
19431 block,
19432 sizeof(block),
19433 ",%s\"connections\" : {%s"
19434 "\"active\" : %i,%s"
19435 "\"maxActive\" : %i,%s"
19436 "\"total\" : %" INT64_FMT "%s"
19437 "}",
19438 eol,
19439 eol,
19440 ctx->active_connections,
19441 eol,
19442 ctx->max_connections,
19443 eol,
19444 ctx->total_connections,
19445 eol);
19446 context_info_length += mg_str_append(&buffer, end, block);
19447
19448 /* Requests information */
19449 mg_snprintf(NULL,
19450 NULL,
19451 block,
19452 sizeof(block),
19453 ",%s\"requests\" : {%s"
19454 "\"total\" : %" INT64_FMT "%s"
19455 "}",
19456 eol,
19457 eol,
19458 ctx->total_requests,
19459 eol);
19460 context_info_length += mg_str_append(&buffer, end, block);
19461
19462 /* Data information */
19463 mg_snprintf(NULL,
19464 NULL,
19465 block,
19466 sizeof(block),
19467 ",%s\"data\" : {%s"
19468 "\"read\" : %" INT64_FMT ",%s"
19469 "\"written\" : %" INT64_FMT "%s"
19470 "}",
19471 eol,
19472 eol,
19473 ctx->total_data_read,
19474 eol,
19475 ctx->total_data_written,
19476 eol);
19477 context_info_length += mg_str_append(&buffer, end, block);
19478
19479 /* Execution time information */
19480 gmt_time_string(start_time_str,
19481 sizeof(start_time_str) - 1,
19482 &start_time);
19483 gmt_time_string(now_str, sizeof(now_str) - 1, &now);
19484
19485 mg_snprintf(NULL,
19486 NULL,
19487 block,
19488 sizeof(block),
19489 ",%s\"time\" : {%s"
19490 "\"uptime\" : %.0f,%s"
19491 "\"start\" : \"%s\",%s"
19492 "\"now\" : \"%s\"%s"
19493 "}",
19494 eol,
19495 eol,
19496 difftime(now, start_time),
19497 eol,
19498 start_time_str,
19499 eol,
19500 now_str,
19501 eol);
19502 context_info_length += mg_str_append(&buffer, end, block);
19503 }
19504
19505 /* Terminate string */
19506 if (append_eoobj) {
19507 strcat(append_eoobj, eoobj);
19508 }
19509 context_info_length += sizeof(eoobj) - 1;
19510
19511 return (int)context_info_length;
19512 #else
19513 (void)ctx;
19514 if ((buffer != NULL) && (buflen > 0)) {
19515 *buffer = 0;
19516 }
19517 return 0;
19518 #endif
19519 }
19520
19521
19522 #if defined(MG_EXPERIMENTAL_INTERFACES)
19523 /* Get connection information. It can be printed or stored by the caller.
19524 * Return the size of available information. */
19525 int
19526 mg_get_connection_info(const struct mg_context *ctx,
19527 int idx,
19528 char *buffer,
19529 int buflen)
19530 {
19531 const struct mg_connection *conn;
19532 const struct mg_request_info *ri;
19533 char *end, *append_eoobj = NULL, block[256];
19534 size_t connection_info_length = 0;
19535 int state = 0;
19536 const char *state_str = "unknown";
19537
19538 #if defined(_WIN32)
19539 static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
19540 #else
19541 static const char eol[] = "\n", eoobj[] = "\n}\n";
19542 #endif
19543
19544 if ((buffer == NULL) || (buflen < 1)) {
19545 buflen = 0;
19546 end = buffer;
19547 } else {
19548 *buffer = 0;
19549 end = buffer + buflen;
19550 }
19551 if (buflen > (int)(sizeof(eoobj) - 1)) {
19552 /* has enough space to append eoobj */
19553 append_eoobj = buffer;
19554 end -= sizeof(eoobj) - 1;
19555 }
19556
19557 if ((ctx == NULL) || (idx < 0)) {
19558 /* Parameter error */
19559 return 0;
19560 }
19561
19562 if ((unsigned)idx >= ctx->cfg_worker_threads) {
19563 /* Out of range */
19564 return 0;
19565 }
19566
19567 /* Take connection [idx]. This connection is not locked in
19568 * any way, so some other thread might use it. */
19569 conn = (ctx->worker_connections) + idx;
19570
19571 /* Initialize output string */
19572 connection_info_length += mg_str_append(&buffer, end, "{");
19573
19574 /* Init variables */
19575 ri = &(conn->request_info);
19576
19577 #if defined(USE_SERVER_STATS)
19578 state = conn->conn_state;
19579
19580 /* State as string */
19581 switch (state) {
19582 case 0:
19583 state_str = "undefined";
19584 break;
19585 case 1:
19586 state_str = "not used";
19587 break;
19588 case 2:
19589 state_str = "init";
19590 break;
19591 case 3:
19592 state_str = "ready";
19593 break;
19594 case 4:
19595 state_str = "processing";
19596 break;
19597 case 5:
19598 state_str = "processed";
19599 break;
19600 case 6:
19601 state_str = "to close";
19602 break;
19603 case 7:
19604 state_str = "closing";
19605 break;
19606 case 8:
19607 state_str = "closed";
19608 break;
19609 case 9:
19610 state_str = "done";
19611 break;
19612 }
19613 #endif
19614
19615 /* Connection info */
19616 if ((state >= 3) && (state < 9)) {
19617 mg_snprintf(NULL,
19618 NULL,
19619 block,
19620 sizeof(block),
19621 "%s\"connection\" : {%s"
19622 "\"remote\" : {%s"
19623 "\"protocol\" : \"%s\",%s"
19624 "\"addr\" : \"%s\",%s"
19625 "\"port\" : %u%s"
19626 "},%s"
19627 "\"handled_requests\" : %u%s"
19628 "}",
19629 eol,
19630 eol,
19631 eol,
19632 get_proto_name(conn),
19633 eol,
19634 ri->remote_addr,
19635 eol,
19636 ri->remote_port,
19637 eol,
19638 eol,
19639 conn->handled_requests,
19640 eol);
19641 connection_info_length += mg_str_append(&buffer, end, block);
19642 }
19643
19644 /* Request info */
19645 if ((state >= 4) && (state < 6)) {
19646 mg_snprintf(NULL,
19647 NULL,
19648 block,
19649 sizeof(block),
19650 "%s%s\"request_info\" : {%s"
19651 "\"method\" : \"%s\",%s"
19652 "\"uri\" : \"%s\",%s"
19653 "\"query\" : %s%s%s%s"
19654 "}",
19655 (connection_info_length > 1 ? "," : ""),
19656 eol,
19657 eol,
19658 ri->request_method,
19659 eol,
19660 ri->request_uri,
19661 eol,
19662 ri->query_string ? "\"" : "",
19663 ri->query_string ? ri->query_string : "null",
19664 ri->query_string ? "\"" : "",
19665 eol);
19666 connection_info_length += mg_str_append(&buffer, end, block);
19667 }
19668
19669 /* Execution time information */
19670 if ((state >= 2) && (state < 9)) {
19671 char start_time_str[64] = {0};
19672 char now_str[64] = {0};
19673 time_t start_time = conn->conn_birth_time;
19674 time_t now = time(NULL);
19675
19676 gmt_time_string(start_time_str,
19677 sizeof(start_time_str) - 1,
19678 &start_time);
19679 gmt_time_string(now_str, sizeof(now_str) - 1, &now);
19680
19681 mg_snprintf(NULL,
19682 NULL,
19683 block,
19684 sizeof(block),
19685 "%s%s\"time\" : {%s"
19686 "\"uptime\" : %.0f,%s"
19687 "\"start\" : \"%s\",%s"
19688 "\"now\" : \"%s\"%s"
19689 "}",
19690 (connection_info_length > 1 ? "," : ""),
19691 eol,
19692 eol,
19693 difftime(now, start_time),
19694 eol,
19695 start_time_str,
19696 eol,
19697 now_str,
19698 eol);
19699 connection_info_length += mg_str_append(&buffer, end, block);
19700 }
19701
19702 /* Remote user name */
19703 if ((ri->remote_user) && (state < 9)) {
19704 mg_snprintf(NULL,
19705 NULL,
19706 block,
19707 sizeof(block),
19708 "%s%s\"user\" : {%s"
19709 "\"name\" : \"%s\",%s"
19710 "}",
19711 (connection_info_length > 1 ? "," : ""),
19712 eol,
19713 eol,
19714 ri->remote_user,
19715 eol);
19716 connection_info_length += mg_str_append(&buffer, end, block);
19717 }
19718
19719 /* Data block */
19720 if (state >= 3) {
19721 mg_snprintf(NULL,
19722 NULL,
19723 block,
19724 sizeof(block),
19725 "%s%s\"data\" : {%s"
19726 "\"read\" : %" INT64_FMT ",%s"
19727 "\"written\" : %" INT64_FMT "%s"
19728 "}",
19729 (connection_info_length > 1 ? "," : ""),
19730 eol,
19731 eol,
19732 conn->consumed_content,
19733 eol,
19734 conn->num_bytes_sent,
19735 eol);
19736 connection_info_length += mg_str_append(&buffer, end, block);
19737 }
19738
19739 /* State */
19740 mg_snprintf(NULL,
19741 NULL,
19742 block,
19743 sizeof(block),
19744 "%s%s\"state\" : \"%s\"",
19745 (connection_info_length > 1 ? "," : ""),
19746 eol,
19747 state_str);
19748 connection_info_length += mg_str_append(&buffer, end, block);
19749
19750 /* Terminate string */
19751 if (append_eoobj) {
19752 strcat(append_eoobj, eoobj);
19753 }
19754 connection_info_length += sizeof(eoobj) - 1;
19755
19756 return (int)connection_info_length;
19757 }
19758 #endif
19759
19760
19761 /* Initialize this library. This function does not need to be thread safe.
19762 */
19763 unsigned
19764 mg_init_library(unsigned features)
19765 {
19766 #if !defined(NO_SSL)
19767 char ebuf[128];
19768 #endif
19769
19770 unsigned features_to_init = mg_check_feature(features & 0xFFu);
19771 unsigned features_inited = features_to_init;
19772
19773 if (mg_init_library_called <= 0) {
19774 /* Not initialized yet */
19775 if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
19776 return 0;
19777 }
19778 }
19779
19780 mg_global_lock();
19781
19782 if (mg_init_library_called <= 0) {
19783 if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
19784 /* Fatal error - abort start. However, this situation should
19785 * never occur in practice. */
19786 mg_global_unlock();
19787 return 0;
19788 }
19789
19790 #if defined(_WIN32)
19791 (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
19792 #else
19793 pthread_mutexattr_init(&pthread_mutex_attr);
19794 pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
19795 #endif
19796
19797 #if defined(USE_LUA)
19798 lua_init_optional_libraries();
19799 #endif
19800 }
19801
19802 mg_global_unlock();
19803
19804 #if !defined(NO_SSL)
19805 if (features_to_init & MG_FEATURES_SSL) {
19806 if (!mg_ssl_initialized) {
19807 if (initialize_ssl(ebuf, sizeof(ebuf))) {
19808 mg_ssl_initialized = 1;
19809 } else {
19810 (void)ebuf;
19811 DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
19812 features_inited &= ~((unsigned)(MG_FEATURES_SSL));
19813 }
19814 } else {
19815 /* ssl already initialized */
19816 }
19817 }
19818 #endif
19819
19820 /* Start WinSock for Windows */
19821 mg_global_lock();
19822 if (mg_init_library_called <= 0) {
19823 #if defined(_WIN32)
19824 WSADATA data;
19825 WSAStartup(MAKEWORD(2, 2), &data);
19826 #endif /* _WIN32 */
19827 mg_init_library_called = 1;
19828 } else {
19829 mg_init_library_called++;
19830 }
19831 mg_global_unlock();
19832
19833 return features_inited;
19834 }
19835
19836
19837 /* Un-initialize this library. */
19838 unsigned
19839 mg_exit_library(void)
19840 {
19841 if (mg_init_library_called <= 0) {
19842 return 0;
19843 }
19844
19845 mg_global_lock();
19846
19847 mg_init_library_called--;
19848 if (mg_init_library_called == 0) {
19849 #if defined(_WIN32)
19850 (void)WSACleanup();
19851 #endif /* _WIN32 */
19852 #if !defined(NO_SSL)
19853 if (mg_ssl_initialized) {
19854 uninitialize_ssl();
19855 mg_ssl_initialized = 0;
19856 }
19857 #endif
19858
19859 #if defined(_WIN32)
19860 (void)pthread_mutex_destroy(&global_log_file_lock);
19861 #else
19862 (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
19863 #endif
19864
19865 (void)pthread_key_delete(sTlsKey);
19866
19867 #if defined(USE_LUA)
19868 lua_exit_optional_libraries();
19869 #endif
19870
19871 mg_global_unlock();
19872 (void)pthread_mutex_destroy(&global_lock_mutex);
19873 return 1;
19874 }
19875
19876 mg_global_unlock();
19877 return 1;
19878 }
19879
19880
19881 /* End of civetweb.c */
19882