Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
seleniumhq
GitHub Repository: seleniumhq/selenium
Path: blob/trunk/third_party/cpp/civetweb/civetweb.c
2868 views
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(_LARGEFILE_SOURCE)
63
#define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
64
#endif
65
#if !defined(_FILE_OFFSET_BITS)
66
#define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
67
#endif
68
#if !defined(__STDC_FORMAT_MACROS)
69
#define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
70
#endif
71
#if !defined(__STDC_LIMIT_MACROS)
72
#define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
73
#endif
74
#if !defined(_DARWIN_UNLIMITED_SELECT)
75
#define _DARWIN_UNLIMITED_SELECT
76
#endif
77
#if defined(__sun)
78
#define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
79
#define __inline inline /* not recognized on older compiler versions */
80
#endif
81
#endif
82
83
#if defined(__clang__)
84
/* Enable reserved-id-macro warning again. */
85
#pragma GCC diagnostic pop
86
#endif
87
88
89
#if defined(USE_LUA)
90
#define USE_TIMERS
91
#endif
92
93
#if defined(_MSC_VER)
94
/* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
95
#pragma warning(disable : 4306)
96
/* conditional expression is constant: introduced by FD_SET(..) */
97
#pragma warning(disable : 4127)
98
/* non-constant aggregate initializer: issued due to missing C99 support */
99
#pragma warning(disable : 4204)
100
/* padding added after data member */
101
#pragma warning(disable : 4820)
102
/* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
103
#pragma warning(disable : 4668)
104
/* no function prototype given: converting '()' to '(void)' */
105
#pragma warning(disable : 4255)
106
/* function has been selected for automatic inline expansion */
107
#pragma warning(disable : 4711)
108
#endif
109
110
111
/* This code uses static_assert to check some conditions.
112
* Unfortunately some compilers still do not support it, so we have a
113
* replacement function here. */
114
#if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
115
#define mg_static_assert _Static_assert
116
#elif defined(__cplusplus) && __cplusplus >= 201103L
117
#define mg_static_assert static_assert
118
#else
119
char static_assert_replacement[1];
120
#define mg_static_assert(cond, txt) \
121
extern char static_assert_replacement[(cond) ? 1 : -1]
122
#endif
123
124
mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
125
"int data type size check");
126
mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
127
"pointer data type size check");
128
mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
129
130
131
/* Alternative queue is well tested and should be the new default */
132
#if defined(NO_ALTERNATIVE_QUEUE)
133
#if defined(ALTERNATIVE_QUEUE)
134
#error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
135
#endif
136
#else
137
#define ALTERNATIVE_QUEUE
138
#endif
139
140
141
/* DTL -- including winsock2.h works better if lean and mean */
142
#if !defined(WIN32_LEAN_AND_MEAN)
143
#define WIN32_LEAN_AND_MEAN
144
#endif
145
146
#if defined(__SYMBIAN32__)
147
/* According to https://en.wikipedia.org/wiki/Symbian#History,
148
* Symbian is no longer maintained since 2014-01-01.
149
* Recent versions of CivetWeb are no longer tested for Symbian.
150
* It makes no sense, to support an abandoned operating system.
151
*/
152
#error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
153
#define NO_SSL /* SSL is not supported */
154
#define NO_CGI /* CGI is not supported */
155
#define PATH_MAX FILENAME_MAX
156
#endif /* __SYMBIAN32__ */
157
158
159
#if !defined(CIVETWEB_HEADER_INCLUDED)
160
/* Include the header file here, so the CivetWeb interface is defined for the
161
* entire implementation, including the following forward definitions. */
162
#include "civetweb.h"
163
#endif
164
165
#if !defined(DEBUG_TRACE)
166
#if defined(DEBUG)
167
static void DEBUG_TRACE_FUNC(const char *func,
168
unsigned line,
169
PRINTF_FORMAT_STRING(const char *fmt),
170
...) PRINTF_ARGS(3, 4);
171
172
#define DEBUG_TRACE(fmt, ...) \
173
DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
174
175
#define NEED_DEBUG_TRACE_FUNC
176
177
#else
178
#define DEBUG_TRACE(fmt, ...) \
179
do { \
180
} while (0)
181
#endif /* DEBUG */
182
#endif /* DEBUG_TRACE */
183
184
185
#if !defined(DEBUG_ASSERT)
186
#if defined(DEBUG)
187
#define DEBUG_ASSERT(cond) \
188
do { \
189
if (!(cond)) { \
190
DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
191
exit(2); /* Exit with error */ \
192
} \
193
} while (0)
194
#else
195
#define DEBUG_ASSERT(cond)
196
#endif /* DEBUG */
197
#endif
198
199
200
#if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
201
void __cyg_profile_func_enter(void *this_fn, void *call_site)
202
__attribute__((no_instrument_function));
203
204
void __cyg_profile_func_exit(void *this_fn, void *call_site)
205
__attribute__((no_instrument_function));
206
207
void
208
__cyg_profile_func_enter(void *this_fn, void *call_site)
209
{
210
if ((void *)this_fn != (void *)printf) {
211
printf("E %p %p\n", this_fn, call_site);
212
}
213
}
214
215
void
216
__cyg_profile_func_exit(void *this_fn, void *call_site)
217
{
218
if ((void *)this_fn != (void *)printf) {
219
printf("X %p %p\n", this_fn, call_site);
220
}
221
}
222
#endif
223
224
225
#if !defined(IGNORE_UNUSED_RESULT)
226
#define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
227
#endif
228
229
230
#if defined(__GNUC__) || defined(__MINGW32__)
231
232
/* GCC unused function attribute seems fundamentally broken.
233
* Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
234
* OR UNUSED" for individual functions failed.
235
* Either the compiler creates an "unused-function" warning if a
236
* function is not marked with __attribute__((unused)).
237
* On the other hand, if the function is marked with this attribute,
238
* but is used, the compiler raises a completely idiotic
239
* "used-but-marked-unused" warning - and
240
* #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
241
* raises error: unknown option after "#pragma GCC diagnostic".
242
* Disable this warning completely, until the GCC guys sober up
243
* again.
244
*/
245
246
#pragma GCC diagnostic ignored "-Wunused-function"
247
248
#define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
249
250
#else
251
#define FUNCTION_MAY_BE_UNUSED
252
#endif
253
254
255
/* Some ANSI #includes are not available on Windows CE */
256
#if !defined(_WIN32_WCE)
257
#include <errno.h>
258
#include <fcntl.h>
259
#include <signal.h>
260
#include <sys/stat.h>
261
#include <sys/types.h>
262
#endif /* !_WIN32_WCE */
263
264
265
#if defined(__clang__)
266
/* When using -Weverything, clang does not accept it's own headers
267
* in a release build configuration. Disable what is too much in
268
* -Weverything. */
269
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
270
#endif
271
272
#if defined(__GNUC__) || defined(__MINGW32__)
273
/* Who on earth came to the conclusion, using __DATE__ should rise
274
* an "expansion of date or time macro is not reproducible"
275
* warning. That's exactly what was intended by using this macro.
276
* Just disable this nonsense warning. */
277
278
/* And disabling them does not work either:
279
* #pragma clang diagnostic ignored "-Wno-error=date-time"
280
* #pragma clang diagnostic ignored "-Wdate-time"
281
* So we just have to disable ALL warnings for some lines
282
* of code.
283
* This seems to be a known GCC bug, not resolved since 2012:
284
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
285
*/
286
#endif
287
288
289
#if defined(__MACH__) /* Apple OSX section */
290
291
#if defined(__clang__)
292
#if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
293
/* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
294
#pragma clang diagnostic ignored "-Wno-reserved-id-macro"
295
#pragma clang diagnostic ignored "-Wno-keyword-macro"
296
#endif
297
#endif
298
299
#define CLOCK_MONOTONIC (1)
300
#define CLOCK_REALTIME (2)
301
302
#include <mach/clock.h>
303
#include <mach/mach.h>
304
#include <mach/mach_time.h>
305
#include <sys/errno.h>
306
#include <sys/time.h>
307
308
/* clock_gettime is not implemented on OSX prior to 10.12 */
309
static int
310
_civet_clock_gettime(int clk_id, struct timespec *t)
311
{
312
memset(t, 0, sizeof(*t));
313
if (clk_id == CLOCK_REALTIME) {
314
struct timeval now;
315
int rv = gettimeofday(&now, NULL);
316
if (rv) {
317
return rv;
318
}
319
t->tv_sec = now.tv_sec;
320
t->tv_nsec = now.tv_usec * 1000;
321
return 0;
322
323
} else if (clk_id == CLOCK_MONOTONIC) {
324
static uint64_t clock_start_time = 0;
325
static mach_timebase_info_data_t timebase_ifo = {0, 0};
326
327
uint64_t now = mach_absolute_time();
328
329
if (clock_start_time == 0) {
330
kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
331
DEBUG_ASSERT(mach_status == KERN_SUCCESS);
332
333
/* appease "unused variable" warning for release builds */
334
(void)mach_status;
335
336
clock_start_time = now;
337
}
338
339
now = (uint64_t)((double)(now - clock_start_time)
340
* (double)timebase_ifo.numer
341
/ (double)timebase_ifo.denom);
342
343
t->tv_sec = now / 1000000000;
344
t->tv_nsec = now % 1000000000;
345
return 0;
346
}
347
return -1; /* EINVAL - Clock ID is unknown */
348
}
349
350
/* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
351
#if defined(__CLOCK_AVAILABILITY)
352
/* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
353
* declared but it may be NULL at runtime. So we need to check before using
354
* it. */
355
static int
356
_civet_safe_clock_gettime(int clk_id, struct timespec *t)
357
{
358
if (clock_gettime) {
359
return clock_gettime(clk_id, t);
360
}
361
return _civet_clock_gettime(clk_id, t);
362
}
363
#define clock_gettime _civet_safe_clock_gettime
364
#else
365
#define clock_gettime _civet_clock_gettime
366
#endif
367
368
#endif
369
370
371
#include <ctype.h>
372
#include <limits.h>
373
#include <stdarg.h>
374
#include <stddef.h>
375
#include <stdint.h>
376
#include <stdio.h>
377
#include <stdlib.h>
378
#include <string.h>
379
#include <time.h>
380
381
/********************************************************************/
382
/* CivetWeb configuration defines */
383
/********************************************************************/
384
385
/* Maximum number of threads that can be configured.
386
* The number of threads actually created depends on the "num_threads"
387
* configuration parameter, but this is the upper limit. */
388
#if !defined(MAX_WORKER_THREADS)
389
#define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
390
#endif
391
392
/* Timeout interval for select/poll calls.
393
* The timeouts depend on "*_timeout_ms" configuration values, but long
394
* timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
395
* This reduces the time required to stop the server. */
396
#if !defined(SOCKET_TIMEOUT_QUANTUM)
397
#define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
398
#endif
399
400
/* Do not try to compress files smaller than this limit. */
401
#if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
402
#define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
403
#endif
404
405
#if !defined(PASSWORDS_FILE_NAME)
406
#define PASSWORDS_FILE_NAME ".htpasswd"
407
#endif
408
409
/* Initial buffer size for all CGI environment variables. In case there is
410
* not enough space, another block is allocated. */
411
#if !defined(CGI_ENVIRONMENT_SIZE)
412
#define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
413
#endif
414
415
/* Maximum number of environment variables. */
416
#if !defined(MAX_CGI_ENVIR_VARS)
417
#define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
418
#endif
419
420
/* General purpose buffer size. */
421
#if !defined(MG_BUF_LEN) /* in bytes */
422
#define MG_BUF_LEN (1024 * 8)
423
#endif
424
425
/* Size of the accepted socket queue (in case the old queue implementation
426
* is used). */
427
#if !defined(MGSQLEN)
428
#define MGSQLEN (20) /* count */
429
#endif
430
431
432
/********************************************************************/
433
434
/* Helper makros */
435
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
436
437
/* Standard defines */
438
#if !defined(INT64_MAX)
439
#define INT64_MAX (9223372036854775807)
440
#endif
441
442
#define SHUTDOWN_RD (0)
443
#define SHUTDOWN_WR (1)
444
#define SHUTDOWN_BOTH (2)
445
446
mg_static_assert(MAX_WORKER_THREADS >= 1,
447
"worker threads must be a positive number");
448
449
mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
450
"size_t data type size check");
451
452
#if defined(_WIN32) /* WINDOWS include block */
453
#include <windows.h>
454
#include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
455
#include <ws2tcpip.h>
456
457
typedef const char *SOCK_OPT_TYPE;
458
459
#if !defined(PATH_MAX)
460
#define W_PATH_MAX (MAX_PATH)
461
/* at most three UTF-8 chars per wchar_t */
462
#define PATH_MAX (W_PATH_MAX * 3)
463
#else
464
#define W_PATH_MAX ((PATH_MAX + 2) / 3)
465
#endif
466
467
mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
468
469
#if !defined(_IN_PORT_T)
470
#if !defined(in_port_t)
471
#define in_port_t u_short
472
#endif
473
#endif
474
475
#if !defined(_WIN32_WCE)
476
#include <direct.h>
477
#include <io.h>
478
#include <process.h>
479
#else /* _WIN32_WCE */
480
#define NO_CGI /* WinCE has no pipes */
481
#define NO_POPEN /* WinCE has no popen */
482
483
typedef long off_t;
484
485
#define errno ((int)(GetLastError()))
486
#define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
487
#endif /* _WIN32_WCE */
488
489
#define MAKEUQUAD(lo, hi) \
490
((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
491
#define RATE_DIFF (10000000) /* 100 nsecs */
492
#define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
493
#define SYS2UNIX_TIME(lo, hi) \
494
((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
495
496
/* Visual Studio 6 does not know __func__ or __FUNCTION__
497
* The rest of MS compilers use __FUNCTION__, not C99 __func__
498
* Also use _strtoui64 on modern M$ compilers */
499
#if defined(_MSC_VER)
500
#if (_MSC_VER < 1300)
501
#define STRX(x) #x
502
#define STR(x) STRX(x)
503
#define __func__ __FILE__ ":" STR(__LINE__)
504
#define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
505
#define strtoll(x, y, z) (_atoi64(x))
506
#else
507
#define __func__ __FUNCTION__
508
#define strtoull(x, y, z) (_strtoui64(x, y, z))
509
#define strtoll(x, y, z) (_strtoi64(x, y, z))
510
#endif
511
#endif /* _MSC_VER */
512
513
#define ERRNO ((int)(GetLastError()))
514
#define NO_SOCKLEN_T
515
516
#if defined(_WIN64) || defined(__MINGW64__)
517
#if !defined(SSL_LIB)
518
#define SSL_LIB "ssleay64.dll"
519
#endif
520
#if !defined(CRYPTO_LIB)
521
#define CRYPTO_LIB "libeay64.dll"
522
#endif
523
#else
524
#if !defined(SSL_LIB)
525
#define SSL_LIB "ssleay32.dll"
526
#endif
527
#if !defined(CRYPTO_LIB)
528
#define CRYPTO_LIB "libeay32.dll"
529
#endif
530
#endif
531
532
#define O_NONBLOCK (0)
533
#if !defined(W_OK)
534
#define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
535
#endif
536
#if !defined(EWOULDBLOCK)
537
#define EWOULDBLOCK WSAEWOULDBLOCK
538
#endif /* !EWOULDBLOCK */
539
#define _POSIX_
540
#define INT64_FMT "I64d"
541
#define UINT64_FMT "I64u"
542
543
#define WINCDECL __cdecl
544
#define vsnprintf_impl _vsnprintf
545
#define access _access
546
#define mg_sleep(x) (Sleep(x))
547
548
#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
549
#if !defined(popen)
550
#define popen(x, y) (_popen(x, y))
551
#endif
552
#if !defined(pclose)
553
#define pclose(x) (_pclose(x))
554
#endif
555
#define close(x) (_close(x))
556
#define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
557
#define RTLD_LAZY (0)
558
#define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
559
#define fdopen(x, y) (_fdopen((x), (y)))
560
#define write(x, y, z) (_write((x), (y), (unsigned)z))
561
#define read(x, y, z) (_read((x), (y), (unsigned)z))
562
#define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
563
#define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
564
#define sleep(x) (Sleep((x)*1000))
565
#define rmdir(x) (_rmdir(x))
566
#if defined(_WIN64) || !defined(__MINGW32__)
567
/* Only MinGW 32 bit is missing this function */
568
#define timegm(x) (_mkgmtime(x))
569
#else
570
time_t timegm(struct tm *tm);
571
#define NEED_TIMEGM
572
#endif
573
574
575
#if !defined(fileno)
576
#define fileno(x) (_fileno(x))
577
#endif /* !fileno MINGW #defines fileno */
578
579
typedef HANDLE pthread_mutex_t;
580
typedef DWORD pthread_key_t;
581
typedef HANDLE pthread_t;
582
typedef struct {
583
CRITICAL_SECTION threadIdSec;
584
struct mg_workerTLS *waiting_thread; /* The chain of threads */
585
} pthread_cond_t;
586
587
#if !defined(__clockid_t_defined)
588
typedef DWORD clockid_t;
589
#endif
590
#if !defined(CLOCK_MONOTONIC)
591
#define CLOCK_MONOTONIC (1)
592
#endif
593
#if !defined(CLOCK_REALTIME)
594
#define CLOCK_REALTIME (2)
595
#endif
596
#if !defined(CLOCK_THREAD)
597
#define CLOCK_THREAD (3)
598
#endif
599
#if !defined(CLOCK_PROCESS)
600
#define CLOCK_PROCESS (4)
601
#endif
602
603
604
#if defined(_MSC_VER) && (_MSC_VER >= 1900)
605
#define _TIMESPEC_DEFINED
606
#endif
607
#if !defined(_TIMESPEC_DEFINED)
608
struct timespec {
609
time_t tv_sec; /* seconds */
610
long tv_nsec; /* nanoseconds */
611
};
612
#endif
613
614
#if !defined(WIN_PTHREADS_TIME_H)
615
#define MUST_IMPLEMENT_CLOCK_GETTIME
616
#endif
617
618
#if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
619
#define clock_gettime mg_clock_gettime
620
static int
621
clock_gettime(clockid_t clk_id, struct timespec *tp)
622
{
623
FILETIME ft;
624
ULARGE_INTEGER li, li2;
625
BOOL ok = FALSE;
626
double d;
627
static double perfcnt_per_sec = 0.0;
628
static BOOL initialized = FALSE;
629
630
if (!initialized) {
631
QueryPerformanceFrequency((LARGE_INTEGER *)&li);
632
perfcnt_per_sec = 1.0 / li.QuadPart;
633
initialized = TRUE;
634
}
635
636
if (tp) {
637
memset(tp, 0, sizeof(*tp));
638
639
if (clk_id == CLOCK_REALTIME) {
640
641
/* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
642
GetSystemTimeAsFileTime(&ft);
643
li.LowPart = ft.dwLowDateTime;
644
li.HighPart = ft.dwHighDateTime;
645
li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
646
tp->tv_sec = (time_t)(li.QuadPart / 10000000);
647
tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
648
ok = TRUE;
649
/* END: CLOCK_REALTIME */
650
651
} else if (clk_id == CLOCK_MONOTONIC) {
652
653
/* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
654
QueryPerformanceCounter((LARGE_INTEGER *)&li);
655
d = li.QuadPart * perfcnt_per_sec;
656
tp->tv_sec = (time_t)d;
657
d -= (double)tp->tv_sec;
658
tp->tv_nsec = (long)(d * 1.0E9);
659
ok = TRUE;
660
/* END: CLOCK_MONOTONIC */
661
662
} else if (clk_id == CLOCK_THREAD) {
663
664
/* BEGIN: CLOCK_THREAD = CPU usage of thread */
665
FILETIME t_create, t_exit, t_kernel, t_user;
666
if (GetThreadTimes(GetCurrentThread(),
667
&t_create,
668
&t_exit,
669
&t_kernel,
670
&t_user)) {
671
li.LowPart = t_user.dwLowDateTime;
672
li.HighPart = t_user.dwHighDateTime;
673
li2.LowPart = t_kernel.dwLowDateTime;
674
li2.HighPart = t_kernel.dwHighDateTime;
675
li.QuadPart += li2.QuadPart;
676
tp->tv_sec = (time_t)(li.QuadPart / 10000000);
677
tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
678
ok = TRUE;
679
}
680
/* END: CLOCK_THREAD */
681
682
} else if (clk_id == CLOCK_PROCESS) {
683
684
/* BEGIN: CLOCK_PROCESS = CPU usage of process */
685
FILETIME t_create, t_exit, t_kernel, t_user;
686
if (GetProcessTimes(GetCurrentProcess(),
687
&t_create,
688
&t_exit,
689
&t_kernel,
690
&t_user)) {
691
li.LowPart = t_user.dwLowDateTime;
692
li.HighPart = t_user.dwHighDateTime;
693
li2.LowPart = t_kernel.dwLowDateTime;
694
li2.HighPart = t_kernel.dwHighDateTime;
695
li.QuadPart += li2.QuadPart;
696
tp->tv_sec = (time_t)(li.QuadPart / 10000000);
697
tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
698
ok = TRUE;
699
}
700
/* END: CLOCK_PROCESS */
701
702
} else {
703
704
/* BEGIN: unknown clock */
705
/* ok = FALSE; already set by init */
706
/* END: unknown clock */
707
}
708
}
709
710
return ok ? 0 : -1;
711
}
712
#endif
713
714
715
#define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
716
717
static int pthread_mutex_lock(pthread_mutex_t *);
718
static int pthread_mutex_unlock(pthread_mutex_t *);
719
static void path_to_unicode(const struct mg_connection *conn,
720
const char *path,
721
wchar_t *wbuf,
722
size_t wbuf_len);
723
724
/* All file operations need to be rewritten to solve #246. */
725
726
struct mg_file;
727
728
static const char *
729
mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
730
731
732
/* POSIX dirent interface */
733
struct dirent {
734
char d_name[PATH_MAX];
735
};
736
737
typedef struct DIR {
738
HANDLE handle;
739
WIN32_FIND_DATAW info;
740
struct dirent result;
741
} DIR;
742
743
#if defined(_WIN32)
744
#if !defined(HAVE_POLL)
745
struct pollfd {
746
SOCKET fd;
747
short events;
748
short revents;
749
};
750
#endif
751
#endif
752
753
/* Mark required libraries */
754
#if defined(_MSC_VER)
755
#pragma comment(lib, "Ws2_32.lib")
756
#endif
757
758
#else /* defined(_WIN32) - WINDOWS vs UNIX include block */
759
760
#include <arpa/inet.h>
761
#include <inttypes.h>
762
#include <netdb.h>
763
#include <netinet/in.h>
764
#include <netinet/tcp.h>
765
#include <stdint.h>
766
#include <sys/poll.h>
767
#include <sys/socket.h>
768
#include <sys/time.h>
769
#include <sys/utsname.h>
770
#include <sys/wait.h>
771
typedef const void *SOCK_OPT_TYPE;
772
773
#if defined(ANDROID)
774
typedef unsigned short int in_port_t;
775
#endif
776
777
#include <dirent.h>
778
#include <grp.h>
779
#include <pwd.h>
780
#include <unistd.h>
781
#define vsnprintf_impl vsnprintf
782
783
#if !defined(NO_SSL_DL) && !defined(NO_SSL)
784
#include <dlfcn.h>
785
#endif
786
#include <pthread.h>
787
#if defined(__MACH__)
788
#define SSL_LIB "libssl.dylib"
789
#define CRYPTO_LIB "libcrypto.dylib"
790
#else
791
#if !defined(SSL_LIB)
792
#define SSL_LIB "libssl.so"
793
#endif
794
#if !defined(CRYPTO_LIB)
795
#define CRYPTO_LIB "libcrypto.so"
796
#endif
797
#endif
798
#if !defined(O_BINARY)
799
#define O_BINARY (0)
800
#endif /* O_BINARY */
801
#define closesocket(a) (close(a))
802
#define mg_mkdir(conn, path, mode) (mkdir(path, mode))
803
#define mg_remove(conn, x) (remove(x))
804
#define mg_sleep(x) (usleep((x)*1000))
805
#define mg_opendir(conn, x) (opendir(x))
806
#define mg_closedir(x) (closedir(x))
807
#define mg_readdir(x) (readdir(x))
808
#define ERRNO (errno)
809
#define INVALID_SOCKET (-1)
810
#define INT64_FMT PRId64
811
#define UINT64_FMT PRIu64
812
typedef int SOCKET;
813
#define WINCDECL
814
815
#if defined(__hpux)
816
/* HPUX 11 does not have monotonic, fall back to realtime */
817
#if !defined(CLOCK_MONOTONIC)
818
#define CLOCK_MONOTONIC CLOCK_REALTIME
819
#endif
820
821
/* HPUX defines socklen_t incorrectly as size_t which is 64bit on
822
* Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
823
* the prototypes use int* rather than socklen_t* which matches the
824
* actual library expectation. When called with the wrong size arg
825
* accept() returns a zero client inet addr and check_acl() always
826
* fails. Since socklen_t is widely used below, just force replace
827
* their typedef with int. - DTL
828
*/
829
#define socklen_t int
830
#endif /* hpux */
831
832
#endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
833
834
/* Maximum queue length for pending connections. This value is passed as
835
* parameter to the "listen" socket call. */
836
#if !defined(SOMAXCONN)
837
/* This symbol may be defined in winsock2.h so this must after that include */
838
#define SOMAXCONN (100) /* in pending connections (count) */
839
#endif
840
841
/* In case our C library is missing "timegm", provide an implementation */
842
#if defined(NEED_TIMEGM)
843
static inline int
844
is_leap(int y)
845
{
846
return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
847
}
848
849
static inline int
850
count_leap(int y)
851
{
852
return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
853
}
854
855
time_t
856
timegm(struct tm *tm)
857
{
858
static const unsigned short ydays[] = {
859
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
860
int year = tm->tm_year + 1900;
861
int mon = tm->tm_mon;
862
int mday = tm->tm_mday - 1;
863
int hour = tm->tm_hour;
864
int min = tm->tm_min;
865
int sec = tm->tm_sec;
866
867
if (year < 1970 || mon < 0 || mon > 11 || mday < 0
868
|| (mday >= ydays[mon + 1] - ydays[mon]
869
+ (mon == 1 && is_leap(year) ? 1 : 0))
870
|| hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
871
return -1;
872
873
time_t res = year - 1970;
874
res *= 365;
875
res += mday;
876
res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
877
res += count_leap(year);
878
879
res *= 24;
880
res += hour;
881
res *= 60;
882
res += min;
883
res *= 60;
884
res += sec;
885
return res;
886
}
887
#endif /* NEED_TIMEGM */
888
889
890
/* va_copy should always be a macro, C99 and C++11 - DTL */
891
#if !defined(va_copy)
892
#define va_copy(x, y) ((x) = (y))
893
#endif
894
895
896
#if defined(_WIN32)
897
/* Create substitutes for POSIX functions in Win32. */
898
899
#if defined(GCC_DIAGNOSTIC)
900
/* Show no warning in case system functions are not used. */
901
#pragma GCC diagnostic push
902
#pragma GCC diagnostic ignored "-Wunused-function"
903
#endif
904
905
906
static CRITICAL_SECTION global_log_file_lock;
907
908
FUNCTION_MAY_BE_UNUSED
909
static DWORD
910
pthread_self(void)
911
{
912
return GetCurrentThreadId();
913
}
914
915
916
FUNCTION_MAY_BE_UNUSED
917
static int
918
pthread_key_create(
919
pthread_key_t *key,
920
void (*_ignored)(void *) /* destructor not supported for Windows */
921
)
922
{
923
(void)_ignored;
924
925
if ((key != 0)) {
926
*key = TlsAlloc();
927
return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
928
}
929
return -2;
930
}
931
932
933
FUNCTION_MAY_BE_UNUSED
934
static int
935
pthread_key_delete(pthread_key_t key)
936
{
937
return TlsFree(key) ? 0 : 1;
938
}
939
940
941
FUNCTION_MAY_BE_UNUSED
942
static int
943
pthread_setspecific(pthread_key_t key, void *value)
944
{
945
return TlsSetValue(key, value) ? 0 : 1;
946
}
947
948
949
FUNCTION_MAY_BE_UNUSED
950
static void *
951
pthread_getspecific(pthread_key_t key)
952
{
953
return TlsGetValue(key);
954
}
955
956
#if defined(GCC_DIAGNOSTIC)
957
/* Enable unused function warning again */
958
#pragma GCC diagnostic pop
959
#endif
960
961
static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
962
#else
963
static pthread_mutexattr_t pthread_mutex_attr;
964
#endif /* _WIN32 */
965
966
967
#if defined(_WIN32_WCE)
968
/* Create substitutes for POSIX functions in Win32. */
969
970
#if defined(GCC_DIAGNOSTIC)
971
/* Show no warning in case system functions are not used. */
972
#pragma GCC diagnostic push
973
#pragma GCC diagnostic ignored "-Wunused-function"
974
#endif
975
976
977
FUNCTION_MAY_BE_UNUSED
978
static time_t
979
time(time_t *ptime)
980
{
981
time_t t;
982
SYSTEMTIME st;
983
FILETIME ft;
984
985
GetSystemTime(&st);
986
SystemTimeToFileTime(&st, &ft);
987
t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
988
989
if (ptime != NULL) {
990
*ptime = t;
991
}
992
993
return t;
994
}
995
996
997
FUNCTION_MAY_BE_UNUSED
998
static struct tm *
999
localtime_s(const time_t *ptime, struct tm *ptm)
1000
{
1001
int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
1002
FILETIME ft, lft;
1003
SYSTEMTIME st;
1004
TIME_ZONE_INFORMATION tzinfo;
1005
1006
if (ptm == NULL) {
1007
return NULL;
1008
}
1009
1010
*(int64_t *)&ft = t;
1011
FileTimeToLocalFileTime(&ft, &lft);
1012
FileTimeToSystemTime(&lft, &st);
1013
ptm->tm_year = st.wYear - 1900;
1014
ptm->tm_mon = st.wMonth - 1;
1015
ptm->tm_wday = st.wDayOfWeek;
1016
ptm->tm_mday = st.wDay;
1017
ptm->tm_hour = st.wHour;
1018
ptm->tm_min = st.wMinute;
1019
ptm->tm_sec = st.wSecond;
1020
ptm->tm_yday = 0; /* hope nobody uses this */
1021
ptm->tm_isdst =
1022
(GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
1023
1024
return ptm;
1025
}
1026
1027
1028
FUNCTION_MAY_BE_UNUSED
1029
static struct tm *
1030
gmtime_s(const time_t *ptime, struct tm *ptm)
1031
{
1032
/* FIXME(lsm): fix this. */
1033
return localtime_s(ptime, ptm);
1034
}
1035
1036
1037
static int mg_atomic_inc(volatile int *addr);
1038
static struct tm tm_array[MAX_WORKER_THREADS];
1039
static int tm_index = 0;
1040
1041
1042
FUNCTION_MAY_BE_UNUSED
1043
static struct tm *
1044
localtime(const time_t *ptime)
1045
{
1046
int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
1047
return localtime_s(ptime, tm_array + i);
1048
}
1049
1050
1051
FUNCTION_MAY_BE_UNUSED
1052
static struct tm *
1053
gmtime(const time_t *ptime)
1054
{
1055
int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
1056
return gmtime_s(ptime, tm_array + i);
1057
}
1058
1059
1060
FUNCTION_MAY_BE_UNUSED
1061
static size_t
1062
strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
1063
{
1064
/* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
1065
* for WinCE"); */
1066
return 0;
1067
}
1068
1069
#define _beginthreadex(psec, stack, func, prm, flags, ptid) \
1070
(uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
1071
1072
#define remove(f) mg_remove(NULL, f)
1073
1074
1075
FUNCTION_MAY_BE_UNUSED
1076
static int
1077
rename(const char *a, const char *b)
1078
{
1079
wchar_t wa[W_PATH_MAX];
1080
wchar_t wb[W_PATH_MAX];
1081
path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
1082
path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
1083
1084
return MoveFileW(wa, wb) ? 0 : -1;
1085
}
1086
1087
1088
struct stat {
1089
int64_t st_size;
1090
time_t st_mtime;
1091
};
1092
1093
1094
FUNCTION_MAY_BE_UNUSED
1095
static int
1096
stat(const char *name, struct stat *st)
1097
{
1098
wchar_t wbuf[W_PATH_MAX];
1099
WIN32_FILE_ATTRIBUTE_DATA attr;
1100
time_t creation_time, write_time;
1101
1102
path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
1103
memset(&attr, 0, sizeof(attr));
1104
1105
GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
1106
st->st_size =
1107
(((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
1108
1109
write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
1110
attr.ftLastWriteTime.dwHighDateTime);
1111
creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
1112
attr.ftCreationTime.dwHighDateTime);
1113
1114
if (creation_time > write_time) {
1115
st->st_mtime = creation_time;
1116
} else {
1117
st->st_mtime = write_time;
1118
}
1119
return 0;
1120
}
1121
1122
#define access(x, a) 1 /* not required anyway */
1123
1124
/* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
1125
/* Values from errno.h in Windows SDK (Visual Studio). */
1126
#define EEXIST 17
1127
#define EACCES 13
1128
#define ENOENT 2
1129
1130
#if defined(GCC_DIAGNOSTIC)
1131
/* Enable unused function warning again */
1132
#pragma GCC diagnostic pop
1133
#endif
1134
1135
#endif /* defined(_WIN32_WCE) */
1136
1137
1138
#if defined(GCC_DIAGNOSTIC)
1139
/* Show no warning in case system functions are not used. */
1140
#pragma GCC diagnostic push
1141
#pragma GCC diagnostic ignored "-Wunused-function"
1142
#endif /* defined(GCC_DIAGNOSTIC) */
1143
#if defined(__clang__)
1144
/* Show no warning in case system functions are not used. */
1145
#pragma clang diagnostic push
1146
#pragma clang diagnostic ignored "-Wunused-function"
1147
#endif
1148
1149
static pthread_mutex_t global_lock_mutex;
1150
1151
1152
#if defined(_WIN32)
1153
/* Forward declaration for Windows */
1154
FUNCTION_MAY_BE_UNUSED
1155
static int pthread_mutex_lock(pthread_mutex_t *mutex);
1156
1157
FUNCTION_MAY_BE_UNUSED
1158
static int pthread_mutex_unlock(pthread_mutex_t *mutex);
1159
#endif
1160
1161
1162
FUNCTION_MAY_BE_UNUSED
1163
static void
1164
mg_global_lock(void)
1165
{
1166
(void)pthread_mutex_lock(&global_lock_mutex);
1167
}
1168
1169
1170
FUNCTION_MAY_BE_UNUSED
1171
static void
1172
mg_global_unlock(void)
1173
{
1174
(void)pthread_mutex_unlock(&global_lock_mutex);
1175
}
1176
1177
1178
FUNCTION_MAY_BE_UNUSED
1179
static int
1180
mg_atomic_inc(volatile int *addr)
1181
{
1182
int ret;
1183
#if defined(_WIN32) && !defined(NO_ATOMICS)
1184
/* Depending on the SDK, this function uses either
1185
* (volatile unsigned int *) or (volatile LONG *),
1186
* so whatever you use, the other SDK is likely to raise a warning. */
1187
ret = InterlockedIncrement((volatile long *)addr);
1188
#elif defined(__GNUC__) \
1189
&& ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1190
&& !defined(NO_ATOMICS)
1191
ret = __sync_add_and_fetch(addr, 1);
1192
#else
1193
mg_global_lock();
1194
ret = (++(*addr));
1195
mg_global_unlock();
1196
#endif
1197
return ret;
1198
}
1199
1200
1201
FUNCTION_MAY_BE_UNUSED
1202
static int
1203
mg_atomic_dec(volatile int *addr)
1204
{
1205
int ret;
1206
#if defined(_WIN32) && !defined(NO_ATOMICS)
1207
/* Depending on the SDK, this function uses either
1208
* (volatile unsigned int *) or (volatile LONG *),
1209
* so whatever you use, the other SDK is likely to raise a warning. */
1210
ret = InterlockedDecrement((volatile long *)addr);
1211
#elif defined(__GNUC__) \
1212
&& ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1213
&& !defined(NO_ATOMICS)
1214
ret = __sync_sub_and_fetch(addr, 1);
1215
#else
1216
mg_global_lock();
1217
ret = (--(*addr));
1218
mg_global_unlock();
1219
#endif
1220
return ret;
1221
}
1222
1223
1224
#if defined(USE_SERVER_STATS)
1225
static int64_t
1226
mg_atomic_add(volatile int64_t *addr, int64_t value)
1227
{
1228
int64_t ret;
1229
#if defined(_WIN64) && !defined(NO_ATOMICS)
1230
ret = InterlockedAdd64(addr, value);
1231
#elif defined(__GNUC__) \
1232
&& ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
1233
&& !defined(NO_ATOMICS)
1234
ret = __sync_add_and_fetch(addr, value);
1235
#else
1236
mg_global_lock();
1237
*addr += value;
1238
ret = (*addr);
1239
mg_global_unlock();
1240
#endif
1241
return ret;
1242
}
1243
#endif
1244
1245
1246
#if defined(GCC_DIAGNOSTIC)
1247
/* Show no warning in case system functions are not used. */
1248
#pragma GCC diagnostic pop
1249
#endif /* defined(GCC_DIAGNOSTIC) */
1250
#if defined(__clang__)
1251
/* Show no warning in case system functions are not used. */
1252
#pragma clang diagnostic pop
1253
#endif
1254
1255
1256
#if defined(USE_SERVER_STATS)
1257
1258
struct mg_memory_stat {
1259
volatile int64_t totalMemUsed;
1260
volatile int64_t maxMemUsed;
1261
volatile int blockCount;
1262
};
1263
1264
1265
static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
1266
1267
1268
static void *
1269
mg_malloc_ex(size_t size,
1270
struct mg_context *ctx,
1271
const char *file,
1272
unsigned line)
1273
{
1274
void *data = malloc(size + 2 * sizeof(uintptr_t));
1275
void *memory = 0;
1276
struct mg_memory_stat *mstat = get_memory_stat(ctx);
1277
1278
#if defined(MEMORY_DEBUGGING)
1279
char mallocStr[256];
1280
#else
1281
(void)file;
1282
(void)line;
1283
#endif
1284
1285
if (data) {
1286
int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
1287
if (mmem > mstat->maxMemUsed) {
1288
/* could use atomic compare exchange, but this
1289
* seems overkill for statistics data */
1290
mstat->maxMemUsed = mmem;
1291
}
1292
1293
mg_atomic_inc(&mstat->blockCount);
1294
((uintptr_t *)data)[0] = size;
1295
((uintptr_t *)data)[1] = (uintptr_t)mstat;
1296
memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1297
}
1298
1299
#if defined(MEMORY_DEBUGGING)
1300
sprintf(mallocStr,
1301
"MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
1302
memory,
1303
(unsigned long)size,
1304
(unsigned long)mstat->totalMemUsed,
1305
(unsigned long)mstat->blockCount,
1306
file,
1307
line);
1308
#if defined(_WIN32)
1309
OutputDebugStringA(mallocStr);
1310
#else
1311
DEBUG_TRACE("%s", mallocStr);
1312
#endif
1313
#endif
1314
1315
return memory;
1316
}
1317
1318
1319
static void *
1320
mg_calloc_ex(size_t count,
1321
size_t size,
1322
struct mg_context *ctx,
1323
const char *file,
1324
unsigned line)
1325
{
1326
void *data = mg_malloc_ex(size * count, ctx, file, line);
1327
1328
if (data) {
1329
memset(data, 0, size * count);
1330
}
1331
return data;
1332
}
1333
1334
1335
static void
1336
mg_free_ex(void *memory, const char *file, unsigned line)
1337
{
1338
void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1339
1340
1341
#if defined(MEMORY_DEBUGGING)
1342
char mallocStr[256];
1343
#else
1344
(void)file;
1345
(void)line;
1346
#endif
1347
1348
if (memory) {
1349
uintptr_t size = ((uintptr_t *)data)[0];
1350
struct mg_memory_stat *mstat =
1351
(struct mg_memory_stat *)(((uintptr_t *)data)[1]);
1352
mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
1353
mg_atomic_dec(&mstat->blockCount);
1354
#if defined(MEMORY_DEBUGGING)
1355
sprintf(mallocStr,
1356
"MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
1357
memory,
1358
(unsigned long)size,
1359
(unsigned long)mstat->totalMemUsed,
1360
(unsigned long)mstat->blockCount,
1361
file,
1362
line);
1363
#if defined(_WIN32)
1364
OutputDebugStringA(mallocStr);
1365
#else
1366
DEBUG_TRACE("%s", mallocStr);
1367
#endif
1368
#endif
1369
free(data);
1370
}
1371
}
1372
1373
1374
static void *
1375
mg_realloc_ex(void *memory,
1376
size_t newsize,
1377
struct mg_context *ctx,
1378
const char *file,
1379
unsigned line)
1380
{
1381
void *data;
1382
void *_realloc;
1383
uintptr_t oldsize;
1384
1385
#if defined(MEMORY_DEBUGGING)
1386
char mallocStr[256];
1387
#else
1388
(void)file;
1389
(void)line;
1390
#endif
1391
1392
if (newsize) {
1393
if (memory) {
1394
/* Reallocate existing block */
1395
struct mg_memory_stat *mstat;
1396
data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
1397
oldsize = ((uintptr_t *)data)[0];
1398
mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
1399
_realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
1400
if (_realloc) {
1401
data = _realloc;
1402
mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
1403
#if defined(MEMORY_DEBUGGING)
1404
sprintf(mallocStr,
1405
"MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
1406
memory,
1407
(unsigned long)oldsize,
1408
(unsigned long)mstat->totalMemUsed,
1409
(unsigned long)mstat->blockCount,
1410
file,
1411
line);
1412
#if defined(_WIN32)
1413
OutputDebugStringA(mallocStr);
1414
#else
1415
DEBUG_TRACE("%s", mallocStr);
1416
#endif
1417
#endif
1418
mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
1419
#if defined(MEMORY_DEBUGGING)
1420
sprintf(mallocStr,
1421
"MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
1422
memory,
1423
(unsigned long)newsize,
1424
(unsigned long)mstat->totalMemUsed,
1425
(unsigned long)mstat->blockCount,
1426
file,
1427
line);
1428
#if defined(_WIN32)
1429
OutputDebugStringA(mallocStr);
1430
#else
1431
DEBUG_TRACE("%s", mallocStr);
1432
#endif
1433
#endif
1434
*(uintptr_t *)data = newsize;
1435
data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
1436
} else {
1437
#if defined(MEMORY_DEBUGGING)
1438
#if defined(_WIN32)
1439
OutputDebugStringA("MEM: realloc failed\n");
1440
#else
1441
DEBUG_TRACE("%s", "MEM: realloc failed\n");
1442
#endif
1443
#endif
1444
return _realloc;
1445
}
1446
} else {
1447
/* Allocate new block */
1448
data = mg_malloc_ex(newsize, ctx, file, line);
1449
}
1450
} else {
1451
/* Free existing block */
1452
data = 0;
1453
mg_free_ex(memory, file, line);
1454
}
1455
1456
return data;
1457
}
1458
1459
#define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
1460
#define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
1461
#define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
1462
#define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
1463
1464
#define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
1465
#define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
1466
#define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
1467
1468
#else /* USE_SERVER_STATS */
1469
1470
static __inline void *
1471
mg_malloc(size_t a)
1472
{
1473
return malloc(a);
1474
}
1475
1476
static __inline void *
1477
mg_calloc(size_t a, size_t b)
1478
{
1479
return calloc(a, b);
1480
}
1481
1482
static __inline void *
1483
mg_realloc(void *a, size_t b)
1484
{
1485
return realloc(a, b);
1486
}
1487
1488
static __inline void
1489
mg_free(void *a)
1490
{
1491
free(a);
1492
}
1493
1494
#define mg_malloc_ctx(a, c) mg_malloc(a)
1495
#define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
1496
#define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
1497
#define mg_free_ctx(a, c) mg_free(a)
1498
1499
#endif /* USE_SERVER_STATS */
1500
1501
1502
static void mg_vsnprintf(const struct mg_connection *conn,
1503
int *truncated,
1504
char *buf,
1505
size_t buflen,
1506
const char *fmt,
1507
va_list ap);
1508
1509
static void mg_snprintf(const struct mg_connection *conn,
1510
int *truncated,
1511
char *buf,
1512
size_t buflen,
1513
PRINTF_FORMAT_STRING(const char *fmt),
1514
...) PRINTF_ARGS(5, 6);
1515
1516
/* This following lines are just meant as a reminder to use the mg-functions
1517
* for memory management */
1518
#if defined(malloc)
1519
#undef malloc
1520
#endif
1521
#if defined(calloc)
1522
#undef calloc
1523
#endif
1524
#if defined(realloc)
1525
#undef realloc
1526
#endif
1527
#if defined(free)
1528
#undef free
1529
#endif
1530
#if defined(snprintf)
1531
#undef snprintf
1532
#endif
1533
#if defined(vsnprintf)
1534
#undef vsnprintf
1535
#endif
1536
#define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
1537
#define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
1538
#define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
1539
#define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
1540
#define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
1541
#if defined(_WIN32)
1542
/* vsnprintf must not be used in any system,
1543
* but this define only works well for Windows. */
1544
#define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
1545
#endif
1546
1547
1548
/* mg_init_library counter */
1549
static int mg_init_library_called = 0;
1550
1551
#if !defined(NO_SSL)
1552
static int mg_ssl_initialized = 0;
1553
#endif
1554
1555
static pthread_key_t sTlsKey; /* Thread local storage index */
1556
static int thread_idx_max = 0;
1557
1558
#if defined(MG_LEGACY_INTERFACE)
1559
#define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
1560
#endif
1561
1562
struct mg_workerTLS {
1563
int is_master;
1564
unsigned long thread_idx;
1565
#if defined(_WIN32)
1566
HANDLE pthread_cond_helper_mutex;
1567
struct mg_workerTLS *next_waiting_thread;
1568
#endif
1569
#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
1570
char txtbuf[4];
1571
#endif
1572
};
1573
1574
1575
#if defined(GCC_DIAGNOSTIC)
1576
/* Show no warning in case system functions are not used. */
1577
#pragma GCC diagnostic push
1578
#pragma GCC diagnostic ignored "-Wunused-function"
1579
#endif /* defined(GCC_DIAGNOSTIC) */
1580
#if defined(__clang__)
1581
/* Show no warning in case system functions are not used. */
1582
#pragma clang diagnostic push
1583
#pragma clang diagnostic ignored "-Wunused-function"
1584
#endif
1585
1586
1587
/* Get a unique thread ID as unsigned long, independent from the data type
1588
* of thread IDs defined by the operating system API.
1589
* If two calls to mg_current_thread_id return the same value, they calls
1590
* are done from the same thread. If they return different values, they are
1591
* done from different threads. (Provided this function is used in the same
1592
* process context and threads are not repeatedly created and deleted, but
1593
* CivetWeb does not do that).
1594
* This function must match the signature required for SSL id callbacks:
1595
* CRYPTO_set_id_callback
1596
*/
1597
FUNCTION_MAY_BE_UNUSED
1598
static unsigned long
1599
mg_current_thread_id(void)
1600
{
1601
#if defined(_WIN32)
1602
return GetCurrentThreadId();
1603
#else
1604
1605
#if defined(__clang__)
1606
#pragma clang diagnostic push
1607
#pragma clang diagnostic ignored "-Wunreachable-code"
1608
/* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
1609
* or not, so one of the two conditions will be unreachable by construction.
1610
* Unfortunately the C standard does not define a way to check this at
1611
* compile time, since the #if preprocessor conditions can not use the sizeof
1612
* operator as an argument. */
1613
#endif
1614
1615
if (sizeof(pthread_t) > sizeof(unsigned long)) {
1616
/* This is the problematic case for CRYPTO_set_id_callback:
1617
* The OS pthread_t can not be cast to unsigned long. */
1618
struct mg_workerTLS *tls =
1619
(struct mg_workerTLS *)pthread_getspecific(sTlsKey);
1620
if (tls == NULL) {
1621
/* SSL called from an unknown thread: Create some thread index.
1622
*/
1623
tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
1624
tls->is_master = -2; /* -2 means "3rd party thread" */
1625
tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
1626
pthread_setspecific(sTlsKey, tls);
1627
}
1628
return tls->thread_idx;
1629
} else {
1630
/* pthread_t may be any data type, so a simple cast to unsigned long
1631
* can rise a warning/error, depending on the platform.
1632
* Here memcpy is used as an anything-to-anything cast. */
1633
unsigned long ret = 0;
1634
pthread_t t = pthread_self();
1635
memcpy(&ret, &t, sizeof(pthread_t));
1636
return ret;
1637
}
1638
1639
#if defined(__clang__)
1640
#pragma clang diagnostic pop
1641
#endif
1642
1643
#endif
1644
}
1645
1646
1647
FUNCTION_MAY_BE_UNUSED
1648
static uint64_t
1649
mg_get_current_time_ns(void)
1650
{
1651
struct timespec tsnow;
1652
clock_gettime(CLOCK_REALTIME, &tsnow);
1653
return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
1654
}
1655
1656
1657
#if defined(GCC_DIAGNOSTIC)
1658
/* Show no warning in case system functions are not used. */
1659
#pragma GCC diagnostic pop
1660
#endif /* defined(GCC_DIAGNOSTIC) */
1661
#if defined(__clang__)
1662
/* Show no warning in case system functions are not used. */
1663
#pragma clang diagnostic pop
1664
#endif
1665
1666
1667
#if defined(NEED_DEBUG_TRACE_FUNC)
1668
static void
1669
DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
1670
{
1671
va_list args;
1672
uint64_t nsnow;
1673
static uint64_t nslast;
1674
struct timespec tsnow;
1675
1676
/* Get some operating system independent thread id */
1677
unsigned long thread_id = mg_current_thread_id();
1678
1679
clock_gettime(CLOCK_REALTIME, &tsnow);
1680
nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
1681
+ ((uint64_t)tsnow.tv_nsec);
1682
1683
if (!nslast) {
1684
nslast = nsnow;
1685
}
1686
1687
flockfile(stdout);
1688
printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
1689
(unsigned long)tsnow.tv_sec,
1690
(unsigned long)tsnow.tv_nsec,
1691
nsnow - nslast,
1692
thread_id,
1693
func,
1694
line);
1695
va_start(args, fmt);
1696
vprintf(fmt, args);
1697
va_end(args);
1698
putchar('\n');
1699
fflush(stdout);
1700
funlockfile(stdout);
1701
nslast = nsnow;
1702
}
1703
#endif /* NEED_DEBUG_TRACE_FUNC */
1704
1705
1706
#define MD5_STATIC static
1707
#include "md5.inl"
1708
1709
/* Darwin prior to 7.0 and Win32 do not have socklen_t */
1710
#if defined(NO_SOCKLEN_T)
1711
typedef int socklen_t;
1712
#endif /* NO_SOCKLEN_T */
1713
1714
#define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
1715
1716
#if !defined(MSG_NOSIGNAL)
1717
#define MSG_NOSIGNAL (0)
1718
#endif
1719
1720
1721
#if defined(NO_SSL)
1722
typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
1723
typedef struct SSL_CTX SSL_CTX;
1724
#else
1725
#if defined(NO_SSL_DL)
1726
#include <openssl/bn.h>
1727
#include <openssl/conf.h>
1728
#include <openssl/crypto.h>
1729
#include <openssl/dh.h>
1730
#include <openssl/engine.h>
1731
#include <openssl/err.h>
1732
#include <openssl/opensslv.h>
1733
#include <openssl/pem.h>
1734
#include <openssl/ssl.h>
1735
#include <openssl/x509.h>
1736
1737
#if defined(WOLFSSL_VERSION)
1738
/* Additional defines for WolfSSL, see
1739
* https://github.com/civetweb/civetweb/issues/583 */
1740
#include "wolfssl_extras.inl"
1741
#endif
1742
1743
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
1744
/* If OpenSSL headers are included, automatically select the API version */
1745
#if !defined(OPENSSL_API_1_1)
1746
#define OPENSSL_API_1_1
1747
#endif
1748
#endif
1749
1750
1751
#else
1752
1753
/* SSL loaded dynamically from DLL.
1754
* I put the prototypes here to be independent from OpenSSL source
1755
* installation. */
1756
1757
typedef struct ssl_st SSL;
1758
typedef struct ssl_method_st SSL_METHOD;
1759
typedef struct ssl_ctx_st SSL_CTX;
1760
typedef struct x509_store_ctx_st X509_STORE_CTX;
1761
typedef struct x509_name X509_NAME;
1762
typedef struct asn1_integer ASN1_INTEGER;
1763
typedef struct bignum BIGNUM;
1764
typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
1765
typedef struct evp_md EVP_MD;
1766
typedef struct x509 X509;
1767
1768
1769
#define SSL_CTRL_OPTIONS (32)
1770
#define SSL_CTRL_CLEAR_OPTIONS (77)
1771
#define SSL_CTRL_SET_ECDH_AUTO (94)
1772
1773
#define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
1774
#define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
1775
#define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
1776
1777
#define SSL_VERIFY_NONE (0)
1778
#define SSL_VERIFY_PEER (1)
1779
#define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
1780
#define SSL_VERIFY_CLIENT_ONCE (4)
1781
#define SSL_OP_ALL ((long)(0x80000BFFUL))
1782
#define SSL_OP_NO_SSLv2 (0x01000000L)
1783
#define SSL_OP_NO_SSLv3 (0x02000000L)
1784
#define SSL_OP_NO_TLSv1 (0x04000000L)
1785
#define SSL_OP_NO_TLSv1_2 (0x08000000L)
1786
#define SSL_OP_NO_TLSv1_1 (0x10000000L)
1787
#define SSL_OP_SINGLE_DH_USE (0x00100000L)
1788
#define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
1789
#define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
1790
#define SSL_OP_NO_COMPRESSION (0x00020000L)
1791
1792
#define SSL_CB_HANDSHAKE_START (0x10)
1793
#define SSL_CB_HANDSHAKE_DONE (0x20)
1794
1795
#define SSL_ERROR_NONE (0)
1796
#define SSL_ERROR_SSL (1)
1797
#define SSL_ERROR_WANT_READ (2)
1798
#define SSL_ERROR_WANT_WRITE (3)
1799
#define SSL_ERROR_WANT_X509_LOOKUP (4)
1800
#define SSL_ERROR_SYSCALL (5) /* see errno */
1801
#define SSL_ERROR_ZERO_RETURN (6)
1802
#define SSL_ERROR_WANT_CONNECT (7)
1803
#define SSL_ERROR_WANT_ACCEPT (8)
1804
1805
#define TLSEXT_TYPE_server_name (0)
1806
#define TLSEXT_NAMETYPE_host_name (0)
1807
#define SSL_TLSEXT_ERR_OK (0)
1808
#define SSL_TLSEXT_ERR_ALERT_WARNING (1)
1809
#define SSL_TLSEXT_ERR_ALERT_FATAL (2)
1810
#define SSL_TLSEXT_ERR_NOACK (3)
1811
1812
struct ssl_func {
1813
const char *name; /* SSL function name */
1814
void (*ptr)(void); /* Function pointer */
1815
};
1816
1817
1818
#if defined(OPENSSL_API_1_1)
1819
1820
#define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
1821
#define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
1822
#define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
1823
#define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
1824
#define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
1825
#define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
1826
#define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
1827
#define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
1828
#define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
1829
#define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
1830
#define OPENSSL_init_ssl \
1831
(*(int (*)(uint64_t opts, \
1832
const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
1833
.ptr)
1834
#define SSL_CTX_use_PrivateKey_file \
1835
(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
1836
#define SSL_CTX_use_certificate_file \
1837
(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
1838
#define SSL_CTX_set_default_passwd_cb \
1839
(*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
1840
#define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
1841
#define SSL_CTX_use_certificate_chain_file \
1842
(*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
1843
#define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
1844
#define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
1845
#define SSL_CTX_set_verify \
1846
(*(void (*)(SSL_CTX *, \
1847
int, \
1848
int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
1849
.ptr)
1850
#define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
1851
#define SSL_CTX_load_verify_locations \
1852
(*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
1853
#define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
1854
#define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
1855
#define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
1856
#define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
1857
#define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
1858
#define SSL_CIPHER_get_name \
1859
(*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
1860
#define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
1861
#define SSL_CTX_set_session_id_context \
1862
(*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
1863
#define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
1864
#define SSL_CTX_set_cipher_list \
1865
(*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
1866
#define SSL_CTX_set_options \
1867
(*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
1868
#define SSL_CTX_set_info_callback \
1869
(*(void (*)(SSL_CTX * ctx, void (*callback)(SSL * s, int, int))) \
1870
ssl_sw[32] \
1871
.ptr)
1872
#define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
1873
#define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
1874
#define SSL_CTX_callback_ctrl \
1875
(*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
1876
#define SSL_get_servername \
1877
(*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
1878
#define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
1879
1880
#define SSL_CTX_clear_options(ctx, op) \
1881
SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
1882
#define SSL_CTX_set_ecdh_auto(ctx, onoff) \
1883
SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
1884
1885
#define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
1886
#define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
1887
#define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
1888
SSL_CTX_callback_ctrl(ctx, \
1889
SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
1890
(void (*)(void))cb)
1891
#define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
1892
SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
1893
1894
#define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
1895
#define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
1896
1897
#define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
1898
#define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
1899
1900
#define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
1901
#define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
1902
#define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
1903
#define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
1904
#define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
1905
#define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
1906
#define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[6].ptr)
1907
#define X509_NAME_oneline \
1908
(*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
1909
#define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[8].ptr)
1910
#define EVP_get_digestbyname \
1911
(*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
1912
#define EVP_Digest \
1913
(*(int (*)( \
1914
const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
1915
crypto_sw[10] \
1916
.ptr)
1917
#define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
1918
#define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
1919
#define ASN1_INTEGER_to_BN \
1920
(*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[13].ptr)
1921
#define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
1922
#define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
1923
1924
#define OPENSSL_free(a) CRYPTO_free(a)
1925
1926
1927
/* init_ssl_ctx() function updates this array.
1928
* It loads SSL library dynamically and changes NULLs to the actual addresses
1929
* of respective functions. The macros above (like SSL_connect()) are really
1930
* just calling these functions indirectly via the pointer. */
1931
static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
1932
{"SSL_accept", NULL},
1933
{"SSL_connect", NULL},
1934
{"SSL_read", NULL},
1935
{"SSL_write", NULL},
1936
{"SSL_get_error", NULL},
1937
{"SSL_set_fd", NULL},
1938
{"SSL_new", NULL},
1939
{"SSL_CTX_new", NULL},
1940
{"TLS_server_method", NULL},
1941
{"OPENSSL_init_ssl", NULL},
1942
{"SSL_CTX_use_PrivateKey_file", NULL},
1943
{"SSL_CTX_use_certificate_file", NULL},
1944
{"SSL_CTX_set_default_passwd_cb", NULL},
1945
{"SSL_CTX_free", NULL},
1946
{"SSL_CTX_use_certificate_chain_file", NULL},
1947
{"TLS_client_method", NULL},
1948
{"SSL_pending", NULL},
1949
{"SSL_CTX_set_verify", NULL},
1950
{"SSL_shutdown", NULL},
1951
{"SSL_CTX_load_verify_locations", NULL},
1952
{"SSL_CTX_set_default_verify_paths", NULL},
1953
{"SSL_CTX_set_verify_depth", NULL},
1954
{"SSL_get_peer_certificate", NULL},
1955
{"SSL_get_version", NULL},
1956
{"SSL_get_current_cipher", NULL},
1957
{"SSL_CIPHER_get_name", NULL},
1958
{"SSL_CTX_check_private_key", NULL},
1959
{"SSL_CTX_set_session_id_context", NULL},
1960
{"SSL_CTX_ctrl", NULL},
1961
{"SSL_CTX_set_cipher_list", NULL},
1962
{"SSL_CTX_set_options", NULL},
1963
{"SSL_CTX_set_info_callback", NULL},
1964
{"SSL_get_ex_data", NULL},
1965
{"SSL_set_ex_data", NULL},
1966
{"SSL_CTX_callback_ctrl", NULL},
1967
{"SSL_get_servername", NULL},
1968
{"SSL_set_SSL_CTX", NULL},
1969
{NULL, NULL}};
1970
1971
1972
/* Similar array as ssl_sw. These functions could be located in different
1973
* lib. */
1974
static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
1975
{"ERR_error_string", NULL},
1976
{"ERR_remove_state", NULL},
1977
{"CONF_modules_unload", NULL},
1978
{"X509_free", NULL},
1979
{"X509_get_subject_name", NULL},
1980
{"X509_get_issuer_name", NULL},
1981
{"X509_NAME_oneline", NULL},
1982
{"X509_get_serialNumber", NULL},
1983
{"EVP_get_digestbyname", NULL},
1984
{"EVP_Digest", NULL},
1985
{"i2d_X509", NULL},
1986
{"BN_bn2hex", NULL},
1987
{"ASN1_INTEGER_to_BN", NULL},
1988
{"BN_free", NULL},
1989
{"CRYPTO_free", NULL},
1990
{NULL, NULL}};
1991
#else
1992
1993
#define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
1994
#define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
1995
#define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
1996
#define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
1997
#define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
1998
#define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
1999
#define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
2000
#define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
2001
#define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
2002
#define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
2003
#define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
2004
#define SSL_CTX_use_PrivateKey_file \
2005
(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
2006
#define SSL_CTX_use_certificate_file \
2007
(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
2008
#define SSL_CTX_set_default_passwd_cb \
2009
(*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
2010
#define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
2011
#define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
2012
#define SSL_CTX_use_certificate_chain_file \
2013
(*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
2014
#define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
2015
#define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
2016
#define SSL_CTX_set_verify \
2017
(*(void (*)(SSL_CTX *, \
2018
int, \
2019
int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
2020
.ptr)
2021
#define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
2022
#define SSL_CTX_load_verify_locations \
2023
(*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
2024
#define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
2025
#define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
2026
#define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
2027
#define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
2028
#define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
2029
#define SSL_CIPHER_get_name \
2030
(*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
2031
#define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
2032
#define SSL_CTX_set_session_id_context \
2033
(*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
2034
#define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
2035
#define SSL_CTX_set_cipher_list \
2036
(*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
2037
#define SSL_CTX_set_info_callback \
2038
(*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int))) ssl_sw[32].ptr)
2039
#define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
2040
#define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
2041
#define SSL_CTX_callback_ctrl \
2042
(*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
2043
#define SSL_get_servername \
2044
(*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
2045
#define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
2046
2047
#define SSL_CTX_set_options(ctx, op) \
2048
SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
2049
#define SSL_CTX_clear_options(ctx, op) \
2050
SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
2051
#define SSL_CTX_set_ecdh_auto(ctx, onoff) \
2052
SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
2053
2054
#define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
2055
#define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
2056
#define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
2057
SSL_CTX_callback_ctrl(ctx, \
2058
SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
2059
(void (*)(void))cb)
2060
#define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
2061
SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
2062
2063
#define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
2064
#define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
2065
2066
#define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
2067
#define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
2068
2069
#define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
2070
#define CRYPTO_set_locking_callback \
2071
(*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
2072
#define CRYPTO_set_id_callback \
2073
(*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
2074
#define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
2075
#define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
2076
#define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
2077
#define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
2078
#define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
2079
#define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
2080
#define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
2081
#define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
2082
#define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
2083
#define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
2084
#define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
2085
#define X509_NAME_oneline \
2086
(*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
2087
#define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
2088
#define i2c_ASN1_INTEGER \
2089
(*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
2090
#define EVP_get_digestbyname \
2091
(*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
2092
#define EVP_Digest \
2093
(*(int (*)( \
2094
const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
2095
crypto_sw[18] \
2096
.ptr)
2097
#define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
2098
#define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
2099
#define ASN1_INTEGER_to_BN \
2100
(*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
2101
#define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
2102
#define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
2103
2104
#define OPENSSL_free(a) CRYPTO_free(a)
2105
2106
/* init_ssl_ctx() function updates this array.
2107
* It loads SSL library dynamically and changes NULLs to the actual addresses
2108
* of respective functions. The macros above (like SSL_connect()) are really
2109
* just calling these functions indirectly via the pointer. */
2110
static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
2111
{"SSL_accept", NULL},
2112
{"SSL_connect", NULL},
2113
{"SSL_read", NULL},
2114
{"SSL_write", NULL},
2115
{"SSL_get_error", NULL},
2116
{"SSL_set_fd", NULL},
2117
{"SSL_new", NULL},
2118
{"SSL_CTX_new", NULL},
2119
{"SSLv23_server_method", NULL},
2120
{"SSL_library_init", NULL},
2121
{"SSL_CTX_use_PrivateKey_file", NULL},
2122
{"SSL_CTX_use_certificate_file", NULL},
2123
{"SSL_CTX_set_default_passwd_cb", NULL},
2124
{"SSL_CTX_free", NULL},
2125
{"SSL_load_error_strings", NULL},
2126
{"SSL_CTX_use_certificate_chain_file", NULL},
2127
{"SSLv23_client_method", NULL},
2128
{"SSL_pending", NULL},
2129
{"SSL_CTX_set_verify", NULL},
2130
{"SSL_shutdown", NULL},
2131
{"SSL_CTX_load_verify_locations", NULL},
2132
{"SSL_CTX_set_default_verify_paths", NULL},
2133
{"SSL_CTX_set_verify_depth", NULL},
2134
{"SSL_get_peer_certificate", NULL},
2135
{"SSL_get_version", NULL},
2136
{"SSL_get_current_cipher", NULL},
2137
{"SSL_CIPHER_get_name", NULL},
2138
{"SSL_CTX_check_private_key", NULL},
2139
{"SSL_CTX_set_session_id_context", NULL},
2140
{"SSL_CTX_ctrl", NULL},
2141
{"SSL_CTX_set_cipher_list", NULL},
2142
{"SSL_CTX_set_info_callback", NULL},
2143
{"SSL_get_ex_data", NULL},
2144
{"SSL_set_ex_data", NULL},
2145
{"SSL_CTX_callback_ctrl", NULL},
2146
{"SSL_get_servername", NULL},
2147
{"SSL_set_SSL_CTX", NULL},
2148
{NULL, NULL}};
2149
2150
2151
/* Similar array as ssl_sw. These functions could be located in different
2152
* lib. */
2153
static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
2154
{"CRYPTO_set_locking_callback", NULL},
2155
{"CRYPTO_set_id_callback", NULL},
2156
{"ERR_get_error", NULL},
2157
{"ERR_error_string", NULL},
2158
{"ERR_remove_state", NULL},
2159
{"ERR_free_strings", NULL},
2160
{"ENGINE_cleanup", NULL},
2161
{"CONF_modules_unload", NULL},
2162
{"CRYPTO_cleanup_all_ex_data", NULL},
2163
{"EVP_cleanup", NULL},
2164
{"X509_free", NULL},
2165
{"X509_get_subject_name", NULL},
2166
{"X509_get_issuer_name", NULL},
2167
{"X509_NAME_oneline", NULL},
2168
{"X509_get_serialNumber", NULL},
2169
{"i2c_ASN1_INTEGER", NULL},
2170
{"EVP_get_digestbyname", NULL},
2171
{"EVP_Digest", NULL},
2172
{"i2d_X509", NULL},
2173
{"BN_bn2hex", NULL},
2174
{"ASN1_INTEGER_to_BN", NULL},
2175
{"BN_free", NULL},
2176
{"CRYPTO_free", NULL},
2177
{NULL, NULL}};
2178
#endif /* OPENSSL_API_1_1 */
2179
#endif /* NO_SSL_DL */
2180
#endif /* NO_SSL */
2181
2182
2183
#if !defined(NO_CACHING)
2184
static const char *month_names[] = {"Jan",
2185
"Feb",
2186
"Mar",
2187
"Apr",
2188
"May",
2189
"Jun",
2190
"Jul",
2191
"Aug",
2192
"Sep",
2193
"Oct",
2194
"Nov",
2195
"Dec"};
2196
#endif /* !NO_CACHING */
2197
2198
/* Unified socket address. For IPv6 support, add IPv6 address structure in
2199
* the
2200
* union u. */
2201
union usa {
2202
struct sockaddr sa;
2203
struct sockaddr_in sin;
2204
#if defined(USE_IPV6)
2205
struct sockaddr_in6 sin6;
2206
#endif
2207
};
2208
2209
/* Describes a string (chunk of memory). */
2210
struct vec {
2211
const char *ptr;
2212
size_t len;
2213
};
2214
2215
struct mg_file_stat {
2216
/* File properties filled by mg_stat: */
2217
uint64_t size;
2218
time_t last_modified;
2219
int is_directory; /* Set to 1 if mg_stat is called for a directory */
2220
int is_gzipped; /* Set to 1 if the content is gzipped, in which
2221
* case we need a "Content-Eencoding: gzip" header */
2222
int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
2223
};
2224
2225
struct mg_file_in_memory {
2226
char *p;
2227
uint32_t pos;
2228
char mode;
2229
};
2230
2231
struct mg_file_access {
2232
/* File properties filled by mg_fopen: */
2233
FILE *fp;
2234
#if defined(MG_USE_OPEN_FILE)
2235
/* TODO (low): Remove obsolete "file in memory" implementation.
2236
* In an "early 2017" discussion at Google groups
2237
* https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
2238
* we decided to get rid of this feature (after some fade-out
2239
* phase). */
2240
const char *membuf;
2241
#endif
2242
};
2243
2244
struct mg_file {
2245
struct mg_file_stat stat;
2246
struct mg_file_access access;
2247
};
2248
2249
#if defined(MG_USE_OPEN_FILE)
2250
2251
#define STRUCT_FILE_INITIALIZER \
2252
{ \
2253
{(uint64_t)0, (time_t)0, 0, 0, 0}, \
2254
{ \
2255
(FILE *)NULL, (const char *)NULL \
2256
} \
2257
}
2258
2259
#else
2260
2261
#define STRUCT_FILE_INITIALIZER \
2262
{ \
2263
{(uint64_t)0, (time_t)0, 0, 0, 0}, \
2264
{ \
2265
(FILE *)NULL \
2266
} \
2267
}
2268
2269
#endif
2270
2271
2272
/* Describes listening socket, or socket which was accept()-ed by the master
2273
* thread and queued for future handling by the worker thread. */
2274
struct socket {
2275
SOCKET sock; /* Listening socket */
2276
union usa lsa; /* Local socket address */
2277
union usa rsa; /* Remote socket address */
2278
unsigned char is_ssl; /* Is port SSL-ed */
2279
unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
2280
* port */
2281
unsigned char in_use; /* Is valid */
2282
};
2283
2284
2285
/* Enum const for all options must be in sync with
2286
* static struct mg_option config_options[]
2287
* This is tested in the unit test (test/private.c)
2288
* "Private Config Options"
2289
*/
2290
enum {
2291
/* Once for each server */
2292
LISTENING_PORTS,
2293
NUM_THREADS,
2294
RUN_AS_USER,
2295
CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
2296
* socket option typedef TCP_NODELAY. */
2297
MAX_REQUEST_SIZE,
2298
LINGER_TIMEOUT,
2299
#if defined(__linux__)
2300
ALLOW_SENDFILE_CALL,
2301
#endif
2302
#if defined(_WIN32)
2303
CASE_SENSITIVE_FILES,
2304
#endif
2305
THROTTLE,
2306
ACCESS_LOG_FILE,
2307
ERROR_LOG_FILE,
2308
ENABLE_KEEP_ALIVE,
2309
REQUEST_TIMEOUT,
2310
KEEP_ALIVE_TIMEOUT,
2311
#if defined(USE_WEBSOCKET)
2312
WEBSOCKET_TIMEOUT,
2313
ENABLE_WEBSOCKET_PING_PONG,
2314
#endif
2315
DECODE_URL,
2316
#if defined(USE_LUA)
2317
LUA_BACKGROUND_SCRIPT,
2318
LUA_BACKGROUND_SCRIPT_PARAMS,
2319
#endif
2320
#if defined(USE_TIMERS)
2321
CGI_TIMEOUT,
2322
#endif
2323
2324
/* Once for each domain */
2325
DOCUMENT_ROOT,
2326
CGI_EXTENSIONS,
2327
CGI_ENVIRONMENT,
2328
PUT_DELETE_PASSWORDS_FILE,
2329
CGI_INTERPRETER,
2330
PROTECT_URI,
2331
AUTHENTICATION_DOMAIN,
2332
ENABLE_AUTH_DOMAIN_CHECK,
2333
SSI_EXTENSIONS,
2334
ENABLE_DIRECTORY_LISTING,
2335
GLOBAL_PASSWORDS_FILE,
2336
INDEX_FILES,
2337
ACCESS_CONTROL_LIST,
2338
EXTRA_MIME_TYPES,
2339
SSL_CERTIFICATE,
2340
SSL_CERTIFICATE_CHAIN,
2341
URL_REWRITE_PATTERN,
2342
HIDE_FILES,
2343
SSL_DO_VERIFY_PEER,
2344
SSL_CA_PATH,
2345
SSL_CA_FILE,
2346
SSL_VERIFY_DEPTH,
2347
SSL_DEFAULT_VERIFY_PATHS,
2348
SSL_CIPHER_LIST,
2349
SSL_PROTOCOL_VERSION,
2350
SSL_SHORT_TRUST,
2351
2352
#if defined(USE_LUA)
2353
LUA_PRELOAD_FILE,
2354
LUA_SCRIPT_EXTENSIONS,
2355
LUA_SERVER_PAGE_EXTENSIONS,
2356
#if defined(MG_EXPERIMENTAL_INTERFACES)
2357
LUA_DEBUG_PARAMS,
2358
#endif
2359
#endif
2360
#if defined(USE_DUKTAPE)
2361
DUKTAPE_SCRIPT_EXTENSIONS,
2362
#endif
2363
2364
#if defined(USE_WEBSOCKET)
2365
WEBSOCKET_ROOT,
2366
#endif
2367
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2368
LUA_WEBSOCKET_EXTENSIONS,
2369
#endif
2370
2371
ACCESS_CONTROL_ALLOW_ORIGIN,
2372
ACCESS_CONTROL_ALLOW_METHODS,
2373
ACCESS_CONTROL_ALLOW_HEADERS,
2374
ERROR_PAGES,
2375
#if !defined(NO_CACHING)
2376
STATIC_FILE_MAX_AGE,
2377
#endif
2378
#if !defined(NO_SSL)
2379
STRICT_HTTPS_MAX_AGE,
2380
#endif
2381
ADDITIONAL_HEADER,
2382
ALLOW_INDEX_SCRIPT_SUB_RES,
2383
2384
NUM_OPTIONS
2385
};
2386
2387
2388
/* Config option name, config types, default value.
2389
* Must be in the same order as the enum const above.
2390
*/
2391
static const struct mg_option config_options[] = {
2392
2393
/* Once for each server */
2394
{"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
2395
{"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
2396
{"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
2397
{"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
2398
{"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
2399
{"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2400
#if defined(__linux__)
2401
{"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2402
#endif
2403
#if defined(_WIN32)
2404
{"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2405
#endif
2406
{"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
2407
{"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
2408
{"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
2409
{"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
2410
{"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
2411
{"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
2412
#if defined(USE_WEBSOCKET)
2413
{"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2414
{"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
2415
#endif
2416
{"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2417
#if defined(USE_LUA)
2418
{"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
2419
{"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
2420
#endif
2421
#if defined(USE_TIMERS)
2422
{"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
2423
#endif
2424
2425
/* Once for each domain */
2426
{"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2427
{"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
2428
{"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
2429
{"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2430
{"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
2431
{"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
2432
{"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
2433
{"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2434
{"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
2435
{"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2436
{"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
2437
{"index_files",
2438
MG_CONFIG_TYPE_STRING_LIST,
2439
#if defined(USE_LUA)
2440
"index.xhtml,index.html,index.htm,"
2441
"index.lp,index.lsp,index.lua,index.cgi,"
2442
"index.shtml,index.php"},
2443
#else
2444
"index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
2445
#endif
2446
{"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
2447
{"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
2448
{"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
2449
{"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
2450
{"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
2451
{"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
2452
2453
{"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
2454
2455
{"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
2456
{"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
2457
{"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
2458
{"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
2459
{"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
2460
{"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
2461
{"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
2462
2463
#if defined(USE_LUA)
2464
{"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
2465
{"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2466
{"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
2467
#if defined(MG_EXPERIMENTAL_INTERFACES)
2468
{"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
2469
#endif
2470
#endif
2471
#if defined(USE_DUKTAPE)
2472
/* The support for duktape is still in alpha version state.
2473
* The name of this config option might change. */
2474
{"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
2475
#endif
2476
2477
#if defined(USE_WEBSOCKET)
2478
{"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
2479
#endif
2480
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2481
{"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
2482
#endif
2483
{"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
2484
{"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
2485
{"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
2486
{"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
2487
#if !defined(NO_CACHING)
2488
{"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
2489
#endif
2490
#if !defined(NO_SSL)
2491
{"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
2492
#endif
2493
{"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
2494
{"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
2495
2496
{NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
2497
2498
2499
/* Check if the config_options and the corresponding enum have compatible
2500
* sizes. */
2501
mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
2502
== (NUM_OPTIONS + 1),
2503
"config_options and enum not sync");
2504
2505
2506
enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
2507
2508
2509
struct mg_handler_info {
2510
/* Name/Pattern of the URI. */
2511
char *uri;
2512
size_t uri_len;
2513
2514
/* handler type */
2515
int handler_type;
2516
2517
/* Handler for http/https or authorization requests. */
2518
mg_request_handler handler;
2519
unsigned int refcount;
2520
pthread_mutex_t refcount_mutex; /* Protects refcount */
2521
pthread_cond_t
2522
refcount_cond; /* Signaled when handler refcount is decremented */
2523
2524
/* Handler for ws/wss (websocket) requests. */
2525
mg_websocket_connect_handler connect_handler;
2526
mg_websocket_ready_handler ready_handler;
2527
mg_websocket_data_handler data_handler;
2528
mg_websocket_close_handler close_handler;
2529
2530
/* accepted subprotocols for ws/wss requests. */
2531
struct mg_websocket_subprotocols *subprotocols;
2532
2533
/* Handler for authorization requests */
2534
mg_authorization_handler auth_handler;
2535
2536
/* User supplied argument for the handler function. */
2537
void *cbdata;
2538
2539
/* next handler in a linked list */
2540
struct mg_handler_info *next;
2541
};
2542
2543
2544
enum {
2545
CONTEXT_INVALID,
2546
CONTEXT_SERVER,
2547
CONTEXT_HTTP_CLIENT,
2548
CONTEXT_WS_CLIENT
2549
};
2550
2551
2552
struct mg_domain_context {
2553
SSL_CTX *ssl_ctx; /* SSL context */
2554
char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
2555
struct mg_handler_info *handlers; /* linked list of uri handlers */
2556
2557
/* Server nonce */
2558
uint64_t auth_nonce_mask; /* Mask for all nonce values */
2559
unsigned long nonce_count; /* Used nonces, used for authentication */
2560
2561
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2562
/* linked list of shared lua websockets */
2563
struct mg_shared_lua_websocket_list *shared_lua_websockets;
2564
#endif
2565
2566
/* Linked list of domains */
2567
struct mg_domain_context *next;
2568
};
2569
2570
2571
struct mg_context {
2572
2573
/* Part 1 - Physical context:
2574
* This holds threads, ports, timeouts, ...
2575
* set for the entire server, independent from the
2576
* addressed hostname.
2577
*/
2578
2579
/* Connection related */
2580
int context_type; /* See CONTEXT_* above */
2581
2582
struct socket *listening_sockets;
2583
struct pollfd *listening_socket_fds;
2584
unsigned int num_listening_sockets;
2585
2586
struct mg_connection *worker_connections; /* The connection struct, pre-
2587
* allocated for each worker */
2588
2589
#if defined(USE_SERVER_STATS)
2590
int active_connections;
2591
int max_connections;
2592
int64_t total_connections;
2593
int64_t total_requests;
2594
int64_t total_data_read;
2595
int64_t total_data_written;
2596
#endif
2597
2598
/* Thread related */
2599
volatile int stop_flag; /* Should we stop event loop */
2600
pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
2601
2602
pthread_t masterthreadid; /* The master thread ID */
2603
unsigned int
2604
cfg_worker_threads; /* The number of configured worker threads. */
2605
pthread_t *worker_threadids; /* The worker thread IDs */
2606
2607
/* Connection to thread dispatching */
2608
#if defined(ALTERNATIVE_QUEUE)
2609
struct socket *client_socks;
2610
void **client_wait_events;
2611
#else
2612
struct socket queue[MGSQLEN]; /* Accepted sockets */
2613
volatile int sq_head; /* Head of the socket queue */
2614
volatile int sq_tail; /* Tail of the socket queue */
2615
pthread_cond_t sq_full; /* Signaled when socket is produced */
2616
pthread_cond_t sq_empty; /* Signaled when socket is consumed */
2617
#endif
2618
2619
/* Memory related */
2620
unsigned int max_request_size; /* The max request size */
2621
2622
#if defined(USE_SERVER_STATS)
2623
struct mg_memory_stat ctx_memory;
2624
#endif
2625
2626
/* Operating system related */
2627
char *systemName; /* What operating system is running */
2628
time_t start_time; /* Server start time, used for authentication
2629
* and for diagnstics. */
2630
2631
#if defined(USE_TIMERS)
2632
struct ttimers *timers;
2633
#endif
2634
2635
/* Lua specific: Background operations and shared websockets */
2636
#if defined(USE_LUA)
2637
void *lua_background_state;
2638
#endif
2639
2640
/* Server nonce */
2641
pthread_mutex_t nonce_mutex; /* Protects nonce_count */
2642
2643
/* Server callbacks */
2644
struct mg_callbacks callbacks; /* User-defined callback function */
2645
void *user_data; /* User-defined data */
2646
2647
/* Part 2 - Logical domain:
2648
* This holds hostname, TLS certificate, document root, ...
2649
* set for a domain hosted at the server.
2650
* There may be multiple domains hosted at one physical server.
2651
* The default domain "dd" is the first element of a list of
2652
* domains.
2653
*/
2654
struct mg_domain_context dd; /* default domain */
2655
};
2656
2657
2658
#if defined(USE_SERVER_STATS)
2659
static struct mg_memory_stat mg_common_memory = {0, 0, 0};
2660
2661
static struct mg_memory_stat *
2662
get_memory_stat(struct mg_context *ctx)
2663
{
2664
if (ctx) {
2665
return &(ctx->ctx_memory);
2666
}
2667
return &mg_common_memory;
2668
}
2669
#endif
2670
2671
enum {
2672
CONNECTION_TYPE_INVALID,
2673
CONNECTION_TYPE_REQUEST,
2674
CONNECTION_TYPE_RESPONSE
2675
};
2676
2677
struct mg_connection {
2678
int connection_type; /* see CONNECTION_TYPE_* above */
2679
2680
struct mg_request_info request_info;
2681
struct mg_response_info response_info;
2682
2683
struct mg_context *phys_ctx;
2684
struct mg_domain_context *dom_ctx;
2685
2686
#if defined(USE_SERVER_STATS)
2687
int conn_state; /* 0 = undef, numerical value may change in different
2688
* versions. For the current definition, see
2689
* mg_get_connection_info_impl */
2690
#endif
2691
2692
const char *host; /* Host (HTTP/1.1 header or SNI) */
2693
SSL *ssl; /* SSL descriptor */
2694
SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
2695
struct socket client; /* Connected client */
2696
time_t conn_birth_time; /* Time (wall clock) when connection was
2697
* established */
2698
struct timespec req_time; /* Time (since system start) when the request
2699
* was received */
2700
int64_t num_bytes_sent; /* Total bytes sent to client */
2701
int64_t content_len; /* Content-Length header value */
2702
int64_t consumed_content; /* How many bytes of content have been read */
2703
int is_chunked; /* Transfer-Encoding is chunked:
2704
* 0 = not chunked,
2705
* 1 = chunked, do data read yet,
2706
* 2 = chunked, some data read,
2707
* 3 = chunked, all data read
2708
*/
2709
size_t chunk_remainder; /* Unread data from the last chunk */
2710
char *buf; /* Buffer for received data */
2711
char *path_info; /* PATH_INFO part of the URL */
2712
2713
int must_close; /* 1 if connection must be closed */
2714
int accept_gzip; /* 1 if gzip encoding is accepted */
2715
int in_error_handler; /* 1 if in handler for user defined error
2716
* pages */
2717
#if defined(USE_WEBSOCKET)
2718
int in_websocket_handling; /* 1 if in read_websocket */
2719
#endif
2720
int handled_requests; /* Number of requests handled by this connection
2721
*/
2722
int buf_size; /* Buffer size */
2723
int request_len; /* Size of the request + headers in a buffer */
2724
int data_len; /* Total size of data in a buffer */
2725
int status_code; /* HTTP reply status code, e.g. 200 */
2726
int throttle; /* Throttling, bytes/sec. <= 0 means no
2727
* throttle */
2728
2729
time_t last_throttle_time; /* Last time throttled data was sent */
2730
int64_t last_throttle_bytes; /* Bytes sent this second */
2731
pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
2732
* atomic transmissions for websockets */
2733
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
2734
void *lua_websocket_state; /* Lua_State for a websocket connection */
2735
#endif
2736
2737
int thread_index; /* Thread index within ctx */
2738
};
2739
2740
2741
/* Directory entry */
2742
struct de {
2743
struct mg_connection *conn;
2744
char *file_name;
2745
struct mg_file_stat file;
2746
};
2747
2748
2749
#if defined(USE_WEBSOCKET)
2750
static int is_websocket_protocol(const struct mg_connection *conn);
2751
#else
2752
#define is_websocket_protocol(conn) (0)
2753
#endif
2754
2755
2756
#define mg_cry_internal(conn, fmt, ...) \
2757
mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
2758
2759
static void mg_cry_internal_wrap(const struct mg_connection *conn,
2760
const char *func,
2761
unsigned line,
2762
const char *fmt,
2763
...) PRINTF_ARGS(4, 5);
2764
2765
2766
#if !defined(NO_THREAD_NAME)
2767
#if defined(_WIN32) && defined(_MSC_VER)
2768
/* Set the thread name for debugging purposes in Visual Studio
2769
* http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
2770
*/
2771
#pragma pack(push, 8)
2772
typedef struct tagTHREADNAME_INFO {
2773
DWORD dwType; /* Must be 0x1000. */
2774
LPCSTR szName; /* Pointer to name (in user addr space). */
2775
DWORD dwThreadID; /* Thread ID (-1=caller thread). */
2776
DWORD dwFlags; /* Reserved for future use, must be zero. */
2777
} THREADNAME_INFO;
2778
#pragma pack(pop)
2779
2780
#elif defined(__linux__)
2781
2782
#include <sys/prctl.h>
2783
#include <sys/sendfile.h>
2784
#if defined(ALTERNATIVE_QUEUE)
2785
#include <sys/eventfd.h>
2786
#endif /* ALTERNATIVE_QUEUE */
2787
2788
2789
#if defined(ALTERNATIVE_QUEUE)
2790
2791
static void *
2792
event_create(void)
2793
{
2794
int evhdl = eventfd(0, EFD_CLOEXEC);
2795
int *ret;
2796
2797
if (evhdl == -1) {
2798
/* Linux uses -1 on error, Windows NULL. */
2799
/* However, Linux does not return 0 on success either. */
2800
return 0;
2801
}
2802
2803
ret = (int *)mg_malloc(sizeof(int));
2804
if (ret) {
2805
*ret = evhdl;
2806
} else {
2807
(void)close(evhdl);
2808
}
2809
2810
return (void *)ret;
2811
}
2812
2813
2814
static int
2815
event_wait(void *eventhdl)
2816
{
2817
uint64_t u;
2818
int evhdl, s;
2819
2820
if (!eventhdl) {
2821
/* error */
2822
return 0;
2823
}
2824
evhdl = *(int *)eventhdl;
2825
2826
s = (int)read(evhdl, &u, sizeof(u));
2827
if (s != sizeof(u)) {
2828
/* error */
2829
return 0;
2830
}
2831
(void)u; /* the value is not required */
2832
return 1;
2833
}
2834
2835
2836
static int
2837
event_signal(void *eventhdl)
2838
{
2839
uint64_t u = 1;
2840
int evhdl, s;
2841
2842
if (!eventhdl) {
2843
/* error */
2844
return 0;
2845
}
2846
evhdl = *(int *)eventhdl;
2847
2848
s = (int)write(evhdl, &u, sizeof(u));
2849
if (s != sizeof(u)) {
2850
/* error */
2851
return 0;
2852
}
2853
return 1;
2854
}
2855
2856
2857
static void
2858
event_destroy(void *eventhdl)
2859
{
2860
int evhdl;
2861
2862
if (!eventhdl) {
2863
/* error */
2864
return;
2865
}
2866
evhdl = *(int *)eventhdl;
2867
2868
close(evhdl);
2869
mg_free(eventhdl);
2870
}
2871
2872
2873
#endif
2874
2875
#endif
2876
2877
2878
#if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
2879
2880
struct posix_event {
2881
pthread_mutex_t mutex;
2882
pthread_cond_t cond;
2883
};
2884
2885
2886
static void *
2887
event_create(void)
2888
{
2889
struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
2890
if (ret == 0) {
2891
/* out of memory */
2892
return 0;
2893
}
2894
if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
2895
/* pthread mutex not available */
2896
mg_free(ret);
2897
return 0;
2898
}
2899
if (0 != pthread_cond_init(&(ret->cond), NULL)) {
2900
/* pthread cond not available */
2901
pthread_mutex_destroy(&(ret->mutex));
2902
mg_free(ret);
2903
return 0;
2904
}
2905
return (void *)ret;
2906
}
2907
2908
2909
static int
2910
event_wait(void *eventhdl)
2911
{
2912
struct posix_event *ev = (struct posix_event *)eventhdl;
2913
pthread_mutex_lock(&(ev->mutex));
2914
pthread_cond_wait(&(ev->cond), &(ev->mutex));
2915
pthread_mutex_unlock(&(ev->mutex));
2916
return 1;
2917
}
2918
2919
2920
static int
2921
event_signal(void *eventhdl)
2922
{
2923
struct posix_event *ev = (struct posix_event *)eventhdl;
2924
pthread_mutex_lock(&(ev->mutex));
2925
pthread_cond_signal(&(ev->cond));
2926
pthread_mutex_unlock(&(ev->mutex));
2927
return 1;
2928
}
2929
2930
2931
static void
2932
event_destroy(void *eventhdl)
2933
{
2934
struct posix_event *ev = (struct posix_event *)eventhdl;
2935
pthread_cond_destroy(&(ev->cond));
2936
pthread_mutex_destroy(&(ev->mutex));
2937
mg_free(ev);
2938
}
2939
#endif
2940
2941
2942
static void
2943
mg_set_thread_name(const char *name)
2944
{
2945
char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
2946
2947
mg_snprintf(
2948
NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
2949
2950
#if defined(_WIN32)
2951
#if defined(_MSC_VER)
2952
/* Windows and Visual Studio Compiler */
2953
__try {
2954
THREADNAME_INFO info;
2955
info.dwType = 0x1000;
2956
info.szName = threadName;
2957
info.dwThreadID = ~0U;
2958
info.dwFlags = 0;
2959
2960
RaiseException(0x406D1388,
2961
0,
2962
sizeof(info) / sizeof(ULONG_PTR),
2963
(ULONG_PTR *)&info);
2964
} __except (EXCEPTION_EXECUTE_HANDLER) {
2965
}
2966
#elif defined(__MINGW32__)
2967
/* No option known to set thread name for MinGW */
2968
#endif
2969
#elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
2970
&& ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
2971
/* pthread_setname_np first appeared in glibc in version 2.12*/
2972
#if defined(__MACH__)
2973
/* OS X only current thread name can be changed */
2974
(void)pthread_setname_np(threadName);
2975
#else
2976
(void)pthread_setname_np(pthread_self(), threadName);
2977
#endif
2978
#elif defined(__linux__)
2979
/* on linux we can use the old prctl function */
2980
(void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
2981
#endif
2982
}
2983
#else /* !defined(NO_THREAD_NAME) */
2984
void
2985
mg_set_thread_name(const char *threadName)
2986
{
2987
}
2988
#endif
2989
2990
2991
#if defined(MG_LEGACY_INTERFACE)
2992
const char **
2993
mg_get_valid_option_names(void)
2994
{
2995
/* This function is deprecated. Use mg_get_valid_options instead. */
2996
static const char
2997
*data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
2998
int i;
2999
3000
for (i = 0; config_options[i].name != NULL; i++) {
3001
data[i * 2] = config_options[i].name;
3002
data[i * 2 + 1] = config_options[i].default_value;
3003
}
3004
3005
return data;
3006
}
3007
#endif
3008
3009
3010
const struct mg_option *
3011
mg_get_valid_options(void)
3012
{
3013
return config_options;
3014
}
3015
3016
3017
/* Do not open file (used in is_file_in_memory) */
3018
#define MG_FOPEN_MODE_NONE (0)
3019
3020
/* Open file for read only access */
3021
#define MG_FOPEN_MODE_READ (1)
3022
3023
/* Open file for writing, create and overwrite */
3024
#define MG_FOPEN_MODE_WRITE (2)
3025
3026
/* Open file for writing, create and append */
3027
#define MG_FOPEN_MODE_APPEND (4)
3028
3029
3030
/* If a file is in memory, set all "stat" members and the membuf pointer of
3031
* output filep and return 1, otherwise return 0 and don't modify anything.
3032
*/
3033
static int
3034
open_file_in_memory(const struct mg_connection *conn,
3035
const char *path,
3036
struct mg_file *filep,
3037
int mode)
3038
{
3039
#if defined(MG_USE_OPEN_FILE)
3040
3041
size_t size = 0;
3042
const char *buf = NULL;
3043
if (!conn) {
3044
return 0;
3045
}
3046
3047
if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
3048
return 0;
3049
}
3050
3051
if (conn->phys_ctx->callbacks.open_file) {
3052
buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
3053
if (buf != NULL) {
3054
if (filep == NULL) {
3055
/* This is a file in memory, but we cannot store the
3056
* properties
3057
* now.
3058
* Called from "is_file_in_memory" function. */
3059
return 1;
3060
}
3061
3062
/* NOTE: override filep->size only on success. Otherwise, it
3063
* might
3064
* break constructs like if (!mg_stat() || !mg_fopen()) ... */
3065
filep->access.membuf = buf;
3066
filep->access.fp = NULL;
3067
3068
/* Size was set by the callback */
3069
filep->stat.size = size;
3070
3071
/* Assume the data may change during runtime by setting
3072
* last_modified = now */
3073
filep->stat.last_modified = time(NULL);
3074
3075
filep->stat.is_directory = 0;
3076
filep->stat.is_gzipped = 0;
3077
}
3078
}
3079
3080
return (buf != NULL);
3081
3082
#else
3083
(void)conn;
3084
(void)path;
3085
(void)filep;
3086
(void)mode;
3087
3088
return 0;
3089
3090
#endif
3091
}
3092
3093
3094
static int
3095
is_file_in_memory(const struct mg_connection *conn, const char *path)
3096
{
3097
return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
3098
}
3099
3100
3101
static int
3102
is_file_opened(const struct mg_file_access *fileacc)
3103
{
3104
if (!fileacc) {
3105
return 0;
3106
}
3107
3108
#if defined(MG_USE_OPEN_FILE)
3109
return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
3110
#else
3111
return (fileacc->fp != NULL);
3112
#endif
3113
}
3114
3115
3116
static int mg_stat(const struct mg_connection *conn,
3117
const char *path,
3118
struct mg_file_stat *filep);
3119
3120
3121
/* mg_fopen will open a file either in memory or on the disk.
3122
* The input parameter path is a string in UTF-8 encoding.
3123
* The input parameter mode is MG_FOPEN_MODE_*
3124
* On success, either fp or membuf will be set in the output
3125
* struct file. All status members will also be set.
3126
* The function returns 1 on success, 0 on error. */
3127
static int
3128
mg_fopen(const struct mg_connection *conn,
3129
const char *path,
3130
int mode,
3131
struct mg_file *filep)
3132
{
3133
int found;
3134
3135
if (!filep) {
3136
return 0;
3137
}
3138
filep->access.fp = NULL;
3139
#if defined(MG_USE_OPEN_FILE)
3140
filep->access.membuf = NULL;
3141
#endif
3142
3143
if (!is_file_in_memory(conn, path)) {
3144
3145
/* filep is initialized in mg_stat: all fields with memset to,
3146
* some fields like size and modification date with values */
3147
found = mg_stat(conn, path, &(filep->stat));
3148
3149
if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
3150
/* file does not exist and will not be created */
3151
return 0;
3152
}
3153
3154
#if defined(_WIN32)
3155
{
3156
wchar_t wbuf[W_PATH_MAX];
3157
path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
3158
switch (mode) {
3159
case MG_FOPEN_MODE_READ:
3160
filep->access.fp = _wfopen(wbuf, L"rb");
3161
break;
3162
case MG_FOPEN_MODE_WRITE:
3163
filep->access.fp = _wfopen(wbuf, L"wb");
3164
break;
3165
case MG_FOPEN_MODE_APPEND:
3166
filep->access.fp = _wfopen(wbuf, L"ab");
3167
break;
3168
}
3169
}
3170
#else
3171
/* Linux et al already use unicode. No need to convert. */
3172
switch (mode) {
3173
case MG_FOPEN_MODE_READ:
3174
filep->access.fp = fopen(path, "r");
3175
break;
3176
case MG_FOPEN_MODE_WRITE:
3177
filep->access.fp = fopen(path, "w");
3178
break;
3179
case MG_FOPEN_MODE_APPEND:
3180
filep->access.fp = fopen(path, "a");
3181
break;
3182
}
3183
3184
#endif
3185
if (!found) {
3186
/* File did not exist before fopen was called.
3187
* Maybe it has been created now. Get stat info
3188
* like creation time now. */
3189
found = mg_stat(conn, path, &(filep->stat));
3190
(void)found;
3191
}
3192
3193
/* file is on disk */
3194
return (filep->access.fp != NULL);
3195
3196
} else {
3197
#if defined(MG_USE_OPEN_FILE)
3198
/* is_file_in_memory returned true */
3199
if (open_file_in_memory(conn, path, filep, mode)) {
3200
/* file is in memory */
3201
return (filep->access.membuf != NULL);
3202
}
3203
#endif
3204
}
3205
3206
/* Open failed */
3207
return 0;
3208
}
3209
3210
3211
/* return 0 on success, just like fclose */
3212
static int
3213
mg_fclose(struct mg_file_access *fileacc)
3214
{
3215
int ret = -1;
3216
if (fileacc != NULL) {
3217
if (fileacc->fp != NULL) {
3218
ret = fclose(fileacc->fp);
3219
#if defined(MG_USE_OPEN_FILE)
3220
} else if (fileacc->membuf != NULL) {
3221
ret = 0;
3222
#endif
3223
}
3224
/* reset all members of fileacc */
3225
memset(fileacc, 0, sizeof(*fileacc));
3226
}
3227
return ret;
3228
}
3229
3230
3231
static void
3232
mg_strlcpy(register char *dst, register const char *src, size_t n)
3233
{
3234
for (; *src != '\0' && n > 1; n--) {
3235
*dst++ = *src++;
3236
}
3237
*dst = '\0';
3238
}
3239
3240
3241
static int
3242
lowercase(const char *s)
3243
{
3244
return tolower(*(const unsigned char *)s);
3245
}
3246
3247
3248
int
3249
mg_strncasecmp(const char *s1, const char *s2, size_t len)
3250
{
3251
int diff = 0;
3252
3253
if (len > 0) {
3254
do {
3255
diff = lowercase(s1++) - lowercase(s2++);
3256
} while (diff == 0 && s1[-1] != '\0' && --len > 0);
3257
}
3258
3259
return diff;
3260
}
3261
3262
3263
int
3264
mg_strcasecmp(const char *s1, const char *s2)
3265
{
3266
int diff;
3267
3268
do {
3269
diff = lowercase(s1++) - lowercase(s2++);
3270
} while (diff == 0 && s1[-1] != '\0');
3271
3272
return diff;
3273
}
3274
3275
3276
static char *
3277
mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
3278
{
3279
char *p;
3280
(void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
3281
* defined */
3282
3283
if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
3284
mg_strlcpy(p, ptr, len + 1);
3285
}
3286
3287
return p;
3288
}
3289
3290
3291
static char *
3292
mg_strdup_ctx(const char *str, struct mg_context *ctx)
3293
{
3294
return mg_strndup_ctx(str, strlen(str), ctx);
3295
}
3296
3297
static char *
3298
mg_strdup(const char *str)
3299
{
3300
return mg_strndup_ctx(str, strlen(str), NULL);
3301
}
3302
3303
3304
static const char *
3305
mg_strcasestr(const char *big_str, const char *small_str)
3306
{
3307
size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
3308
3309
if (big_len >= small_len) {
3310
for (i = 0; i <= (big_len - small_len); i++) {
3311
if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
3312
return big_str + i;
3313
}
3314
}
3315
}
3316
3317
return NULL;
3318
}
3319
3320
3321
/* Return null terminated string of given maximum length.
3322
* Report errors if length is exceeded. */
3323
static void
3324
mg_vsnprintf(const struct mg_connection *conn,
3325
int *truncated,
3326
char *buf,
3327
size_t buflen,
3328
const char *fmt,
3329
va_list ap)
3330
{
3331
int n, ok;
3332
3333
if (buflen == 0) {
3334
if (truncated) {
3335
*truncated = 1;
3336
}
3337
return;
3338
}
3339
3340
#if defined(__clang__)
3341
#pragma clang diagnostic push
3342
#pragma clang diagnostic ignored "-Wformat-nonliteral"
3343
/* Using fmt as a non-literal is intended here, since it is mostly called
3344
* indirectly by mg_snprintf */
3345
#endif
3346
3347
n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
3348
ok = (n >= 0) && ((size_t)n < buflen);
3349
3350
#if defined(__clang__)
3351
#pragma clang diagnostic pop
3352
#endif
3353
3354
if (ok) {
3355
if (truncated) {
3356
*truncated = 0;
3357
}
3358
} else {
3359
if (truncated) {
3360
*truncated = 1;
3361
}
3362
mg_cry_internal(conn,
3363
"truncating vsnprintf buffer: [%.*s]",
3364
(int)((buflen > 200) ? 200 : (buflen - 1)),
3365
buf);
3366
n = (int)buflen - 1;
3367
}
3368
buf[n] = '\0';
3369
}
3370
3371
3372
static void
3373
mg_snprintf(const struct mg_connection *conn,
3374
int *truncated,
3375
char *buf,
3376
size_t buflen,
3377
const char *fmt,
3378
...)
3379
{
3380
va_list ap;
3381
3382
va_start(ap, fmt);
3383
mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
3384
va_end(ap);
3385
}
3386
3387
3388
static int
3389
get_option_index(const char *name)
3390
{
3391
int i;
3392
3393
for (i = 0; config_options[i].name != NULL; i++) {
3394
if (strcmp(config_options[i].name, name) == 0) {
3395
return i;
3396
}
3397
}
3398
return -1;
3399
}
3400
3401
3402
const char *
3403
mg_get_option(const struct mg_context *ctx, const char *name)
3404
{
3405
int i;
3406
if ((i = get_option_index(name)) == -1) {
3407
return NULL;
3408
} else if (!ctx || ctx->dd.config[i] == NULL) {
3409
return "";
3410
} else {
3411
return ctx->dd.config[i];
3412
}
3413
}
3414
3415
#define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
3416
3417
struct mg_context *
3418
mg_get_context(const struct mg_connection *conn)
3419
{
3420
return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
3421
}
3422
3423
3424
void *
3425
mg_get_user_data(const struct mg_context *ctx)
3426
{
3427
return (ctx == NULL) ? NULL : ctx->user_data;
3428
}
3429
3430
3431
void
3432
mg_set_user_connection_data(struct mg_connection *conn, void *data)
3433
{
3434
if (conn != NULL) {
3435
conn->request_info.conn_data = data;
3436
}
3437
}
3438
3439
3440
void *
3441
mg_get_user_connection_data(const struct mg_connection *conn)
3442
{
3443
if (conn != NULL) {
3444
return conn->request_info.conn_data;
3445
}
3446
return NULL;
3447
}
3448
3449
3450
#if defined(MG_LEGACY_INTERFACE)
3451
/* Deprecated: Use mg_get_server_ports instead. */
3452
size_t
3453
mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
3454
{
3455
size_t i;
3456
if (!ctx) {
3457
return 0;
3458
}
3459
for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
3460
ssl[i] = ctx->listening_sockets[i].is_ssl;
3461
ports[i] =
3462
#if defined(USE_IPV6)
3463
(ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
3464
? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
3465
:
3466
#endif
3467
ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
3468
}
3469
return i;
3470
}
3471
#endif
3472
3473
3474
int
3475
mg_get_server_ports(const struct mg_context *ctx,
3476
int size,
3477
struct mg_server_ports *ports)
3478
{
3479
int i, cnt = 0;
3480
3481
if (size <= 0) {
3482
return -1;
3483
}
3484
memset(ports, 0, sizeof(*ports) * (size_t)size);
3485
if (!ctx) {
3486
return -1;
3487
}
3488
if (!ctx->listening_sockets) {
3489
return -1;
3490
}
3491
3492
for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
3493
3494
ports[cnt].port =
3495
#if defined(USE_IPV6)
3496
(ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
3497
? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
3498
:
3499
#endif
3500
ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
3501
ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
3502
ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
3503
3504
if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
3505
/* IPv4 */
3506
ports[cnt].protocol = 1;
3507
cnt++;
3508
} else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
3509
/* IPv6 */
3510
ports[cnt].protocol = 3;
3511
cnt++;
3512
}
3513
}
3514
3515
return cnt;
3516
}
3517
3518
3519
static void
3520
sockaddr_to_string(char *buf, size_t len, const union usa *usa)
3521
{
3522
buf[0] = '\0';
3523
3524
if (!usa) {
3525
return;
3526
}
3527
3528
if (usa->sa.sa_family == AF_INET) {
3529
getnameinfo(&usa->sa,
3530
sizeof(usa->sin),
3531
buf,
3532
(unsigned)len,
3533
NULL,
3534
0,
3535
NI_NUMERICHOST);
3536
}
3537
#if defined(USE_IPV6)
3538
else if (usa->sa.sa_family == AF_INET6) {
3539
getnameinfo(&usa->sa,
3540
sizeof(usa->sin6),
3541
buf,
3542
(unsigned)len,
3543
NULL,
3544
0,
3545
NI_NUMERICHOST);
3546
}
3547
#endif
3548
}
3549
3550
3551
/* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
3552
* included in all responses other than 100, 101, 5xx. */
3553
static void
3554
gmt_time_string(char *buf, size_t buf_len, time_t *t)
3555
{
3556
#if !defined(REENTRANT_TIME)
3557
struct tm *tm;
3558
3559
tm = ((t != NULL) ? gmtime(t) : NULL);
3560
if (tm != NULL) {
3561
#else
3562
struct tm _tm;
3563
struct tm *tm = &_tm;
3564
3565
if (t != NULL) {
3566
gmtime_r(t, tm);
3567
#endif
3568
strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
3569
} else {
3570
mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
3571
buf[buf_len - 1] = '\0';
3572
}
3573
}
3574
3575
3576
/* difftime for struct timespec. Return value is in seconds. */
3577
static double
3578
mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
3579
{
3580
return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
3581
+ (double)(ts_now->tv_sec - ts_before->tv_sec);
3582
}
3583
3584
3585
#if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
3586
static void mg_cry_internal_impl(const struct mg_connection *conn,
3587
const char *func,
3588
unsigned line,
3589
const char *fmt,
3590
va_list ap);
3591
#include "external_mg_cry_internal_impl.inl"
3592
#else
3593
3594
/* Print error message to the opened error log stream. */
3595
static void
3596
mg_cry_internal_impl(const struct mg_connection *conn,
3597
const char *func,
3598
unsigned line,
3599
const char *fmt,
3600
va_list ap)
3601
{
3602
char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
3603
struct mg_file fi;
3604
time_t timestamp;
3605
3606
/* Unused, in the RELEASE build */
3607
(void)func;
3608
(void)line;
3609
3610
#if defined(GCC_DIAGNOSTIC)
3611
#pragma GCC diagnostic push
3612
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
3613
#endif
3614
3615
IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
3616
3617
#if defined(GCC_DIAGNOSTIC)
3618
#pragma GCC diagnostic pop
3619
#endif
3620
3621
buf[sizeof(buf) - 1] = 0;
3622
3623
DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
3624
3625
if (!conn) {
3626
puts(buf);
3627
return;
3628
}
3629
3630
/* Do not lock when getting the callback value, here and below.
3631
* I suppose this is fine, since function cannot disappear in the
3632
* same way string option can. */
3633
if ((conn->phys_ctx->callbacks.log_message == NULL)
3634
|| (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
3635
3636
if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
3637
if (mg_fopen(conn,
3638
conn->dom_ctx->config[ERROR_LOG_FILE],
3639
MG_FOPEN_MODE_APPEND,
3640
&fi)
3641
== 0) {
3642
fi.access.fp = NULL;
3643
}
3644
} else {
3645
fi.access.fp = NULL;
3646
}
3647
3648
if (fi.access.fp != NULL) {
3649
flockfile(fi.access.fp);
3650
timestamp = time(NULL);
3651
3652
sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
3653
fprintf(fi.access.fp,
3654
"[%010lu] [error] [client %s] ",
3655
(unsigned long)timestamp,
3656
src_addr);
3657
3658
if (conn->request_info.request_method != NULL) {
3659
fprintf(fi.access.fp,
3660
"%s %s: ",
3661
conn->request_info.request_method,
3662
conn->request_info.request_uri
3663
? conn->request_info.request_uri
3664
: "");
3665
}
3666
3667
fprintf(fi.access.fp, "%s", buf);
3668
fputc('\n', fi.access.fp);
3669
fflush(fi.access.fp);
3670
funlockfile(fi.access.fp);
3671
(void)mg_fclose(&fi.access); /* Ignore errors. We can't call
3672
* mg_cry here anyway ;-) */
3673
}
3674
}
3675
}
3676
3677
#endif /* Externally provided function */
3678
3679
3680
static void
3681
mg_cry_internal_wrap(const struct mg_connection *conn,
3682
const char *func,
3683
unsigned line,
3684
const char *fmt,
3685
...)
3686
{
3687
va_list ap;
3688
va_start(ap, fmt);
3689
mg_cry_internal_impl(conn, func, line, fmt, ap);
3690
va_end(ap);
3691
}
3692
3693
3694
void
3695
mg_cry(const struct mg_connection *conn, const char *fmt, ...)
3696
{
3697
va_list ap;
3698
va_start(ap, fmt);
3699
mg_cry_internal_impl(conn, "user", 0, fmt, ap);
3700
va_end(ap);
3701
}
3702
3703
3704
#define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
3705
3706
3707
/* Return fake connection structure. Used for logging, if connection
3708
* is not applicable at the moment of logging. */
3709
static struct mg_connection *
3710
fc(struct mg_context *ctx)
3711
{
3712
static struct mg_connection fake_connection;
3713
fake_connection.phys_ctx = ctx;
3714
fake_connection.dom_ctx = &(ctx->dd);
3715
return &fake_connection;
3716
}
3717
3718
3719
const char *
3720
mg_version(void)
3721
{
3722
return CIVETWEB_VERSION;
3723
}
3724
3725
3726
const struct mg_request_info *
3727
mg_get_request_info(const struct mg_connection *conn)
3728
{
3729
if (!conn) {
3730
return NULL;
3731
}
3732
#if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
3733
if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
3734
char txt[16];
3735
struct mg_workerTLS *tls =
3736
(struct mg_workerTLS *)pthread_getspecific(sTlsKey);
3737
3738
sprintf(txt, "%03i", conn->response_info.status_code);
3739
if (strlen(txt) == 3) {
3740
memcpy(tls->txtbuf, txt, 4);
3741
} else {
3742
strcpy(tls->txtbuf, "ERR");
3743
}
3744
3745
((struct mg_connection *)conn)->request_info.local_uri =
3746
((struct mg_connection *)conn)->request_info.request_uri =
3747
tls->txtbuf; /* use thread safe buffer */
3748
3749
((struct mg_connection *)conn)->request_info.num_headers =
3750
conn->response_info.num_headers;
3751
memcpy(((struct mg_connection *)conn)->request_info.http_headers,
3752
conn->response_info.http_headers,
3753
sizeof(conn->response_info.http_headers));
3754
} else
3755
#endif
3756
if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
3757
return NULL;
3758
}
3759
return &conn->request_info;
3760
}
3761
3762
3763
const struct mg_response_info *
3764
mg_get_response_info(const struct mg_connection *conn)
3765
{
3766
if (!conn) {
3767
return NULL;
3768
}
3769
if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
3770
return NULL;
3771
}
3772
return &conn->response_info;
3773
}
3774
3775
3776
static const char *
3777
get_proto_name(const struct mg_connection *conn)
3778
{
3779
#if defined(__clang__)
3780
#pragma clang diagnostic push
3781
#pragma clang diagnostic ignored "-Wunreachable-code"
3782
/* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
3783
* not supported. Clang raises an "unreachable code" warning for parts of ?:
3784
* unreachable, but splitting into four different #ifdef clauses here is more
3785
* complicated.
3786
*/
3787
#endif
3788
3789
const struct mg_request_info *ri = &conn->request_info;
3790
3791
const char *proto =
3792
(is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
3793
: (ri->is_ssl ? "https" : "http"));
3794
3795
return proto;
3796
3797
#if defined(__clang__)
3798
#pragma clang diagnostic pop
3799
#endif
3800
}
3801
3802
3803
int
3804
mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
3805
{
3806
if ((buflen < 1) || (buf == 0) || (conn == 0)) {
3807
return -1;
3808
} else {
3809
3810
int truncated = 0;
3811
const struct mg_request_info *ri = &conn->request_info;
3812
3813
const char *proto = get_proto_name(conn);
3814
3815
if (ri->local_uri == NULL) {
3816
return -1;
3817
}
3818
3819
if ((ri->request_uri != NULL)
3820
&& (0 != strcmp(ri->local_uri, ri->request_uri))) {
3821
/* The request uri is different from the local uri.
3822
* This is usually if an absolute URI, including server
3823
* name has been provided. */
3824
mg_snprintf(conn,
3825
&truncated,
3826
buf,
3827
buflen,
3828
"%s://%s",
3829
proto,
3830
ri->request_uri);
3831
if (truncated) {
3832
return -1;
3833
}
3834
return 0;
3835
3836
} else {
3837
3838
/* The common case is a relative URI, so we have to
3839
* construct an absolute URI from server name and port */
3840
3841
#if defined(USE_IPV6)
3842
int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
3843
int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
3844
: htons(conn->client.lsa.sin.sin_port);
3845
#else
3846
int port = htons(conn->client.lsa.sin.sin_port);
3847
#endif
3848
int def_port = ri->is_ssl ? 443 : 80;
3849
int auth_domain_check_enabled =
3850
conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
3851
&& (!mg_strcasecmp(
3852
conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
3853
const char *server_domain =
3854
conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
3855
3856
char portstr[16];
3857
char server_ip[48];
3858
3859
if (port != def_port) {
3860
sprintf(portstr, ":%u", (unsigned)port);
3861
} else {
3862
portstr[0] = 0;
3863
}
3864
3865
if (!auth_domain_check_enabled || !server_domain) {
3866
3867
sockaddr_to_string(server_ip,
3868
sizeof(server_ip),
3869
&conn->client.lsa);
3870
3871
server_domain = server_ip;
3872
}
3873
3874
mg_snprintf(conn,
3875
&truncated,
3876
buf,
3877
buflen,
3878
"%s://%s%s%s",
3879
proto,
3880
server_domain,
3881
portstr,
3882
ri->local_uri);
3883
if (truncated) {
3884
return -1;
3885
}
3886
return 0;
3887
}
3888
}
3889
}
3890
3891
/* Skip the characters until one of the delimiters characters found.
3892
* 0-terminate resulting word. Skip the delimiter and following whitespaces.
3893
* Advance pointer to buffer to the next word. Return found 0-terminated
3894
* word.
3895
* Delimiters can be quoted with quotechar. */
3896
static char *
3897
skip_quoted(char **buf,
3898
const char *delimiters,
3899
const char *whitespace,
3900
char quotechar)
3901
{
3902
char *p, *begin_word, *end_word, *end_whitespace;
3903
3904
begin_word = *buf;
3905
end_word = begin_word + strcspn(begin_word, delimiters);
3906
3907
/* Check for quotechar */
3908
if (end_word > begin_word) {
3909
p = end_word - 1;
3910
while (*p == quotechar) {
3911
/* While the delimiter is quoted, look for the next delimiter.
3912
*/
3913
/* This happens, e.g., in calls from parse_auth_header,
3914
* if the user name contains a " character. */
3915
3916
/* If there is anything beyond end_word, copy it. */
3917
if (*end_word != '\0') {
3918
size_t end_off = strcspn(end_word + 1, delimiters);
3919
memmove(p, end_word, end_off + 1);
3920
p += end_off; /* p must correspond to end_word - 1 */
3921
end_word += end_off + 1;
3922
} else {
3923
*p = '\0';
3924
break;
3925
}
3926
}
3927
for (p++; p < end_word; p++) {
3928
*p = '\0';
3929
}
3930
}
3931
3932
if (*end_word == '\0') {
3933
*buf = end_word;
3934
} else {
3935
3936
#if defined(GCC_DIAGNOSTIC)
3937
/* Disable spurious conversion warning for GCC */
3938
#pragma GCC diagnostic push
3939
#pragma GCC diagnostic ignored "-Wsign-conversion"
3940
#endif /* defined(GCC_DIAGNOSTIC) */
3941
3942
end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
3943
3944
#if defined(GCC_DIAGNOSTIC)
3945
#pragma GCC diagnostic pop
3946
#endif /* defined(GCC_DIAGNOSTIC) */
3947
3948
for (p = end_word; p < end_whitespace; p++) {
3949
*p = '\0';
3950
}
3951
3952
*buf = end_whitespace;
3953
}
3954
3955
return begin_word;
3956
}
3957
3958
3959
/* Return HTTP header value, or NULL if not found. */
3960
static const char *
3961
get_header(const struct mg_header *hdr, int num_hdr, const char *name)
3962
{
3963
int i;
3964
for (i = 0; i < num_hdr; i++) {
3965
if (!mg_strcasecmp(name, hdr[i].name)) {
3966
return hdr[i].value;
3967
}
3968
}
3969
3970
return NULL;
3971
}
3972
3973
3974
#if defined(USE_WEBSOCKET)
3975
/* Retrieve requested HTTP header multiple values, and return the number of
3976
* found occurrences */
3977
static int
3978
get_req_headers(const struct mg_request_info *ri,
3979
const char *name,
3980
const char **output,
3981
int output_max_size)
3982
{
3983
int i;
3984
int cnt = 0;
3985
if (ri) {
3986
for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
3987
if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
3988
output[cnt++] = ri->http_headers[i].value;
3989
}
3990
}
3991
}
3992
return cnt;
3993
}
3994
#endif
3995
3996
3997
const char *
3998
mg_get_header(const struct mg_connection *conn, const char *name)
3999
{
4000
if (!conn) {
4001
return NULL;
4002
}
4003
4004
if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
4005
return get_header(conn->request_info.http_headers,
4006
conn->request_info.num_headers,
4007
name);
4008
}
4009
if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
4010
return get_header(conn->response_info.http_headers,
4011
conn->response_info.num_headers,
4012
name);
4013
}
4014
return NULL;
4015
}
4016
4017
4018
static const char *
4019
get_http_version(const struct mg_connection *conn)
4020
{
4021
if (!conn) {
4022
return NULL;
4023
}
4024
4025
if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
4026
return conn->request_info.http_version;
4027
}
4028
if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
4029
return conn->response_info.http_version;
4030
}
4031
return NULL;
4032
}
4033
4034
4035
/* A helper function for traversing a comma separated list of values.
4036
* It returns a list pointer shifted to the next value, or NULL if the end
4037
* of the list found.
4038
* Value is stored in val vector. If value has form "x=y", then eq_val
4039
* vector is initialized to point to the "y" part, and val vector length
4040
* is adjusted to point only to "x". */
4041
static const char *
4042
next_option(const char *list, struct vec *val, struct vec *eq_val)
4043
{
4044
int end;
4045
4046
reparse:
4047
if (val == NULL || list == NULL || *list == '\0') {
4048
/* End of the list */
4049
return NULL;
4050
}
4051
4052
/* Skip over leading LWS */
4053
while (*list == ' ' || *list == '\t')
4054
list++;
4055
4056
val->ptr = list;
4057
if ((list = strchr(val->ptr, ',')) != NULL) {
4058
/* Comma found. Store length and shift the list ptr */
4059
val->len = ((size_t)(list - val->ptr));
4060
list++;
4061
} else {
4062
/* This value is the last one */
4063
list = val->ptr + strlen(val->ptr);
4064
val->len = ((size_t)(list - val->ptr));
4065
}
4066
4067
/* Adjust length for trailing LWS */
4068
end = (int)val->len - 1;
4069
while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
4070
end--;
4071
val->len = (size_t)(end + 1);
4072
4073
if (val->len == 0) {
4074
/* Ignore any empty entries. */
4075
goto reparse;
4076
}
4077
4078
if (eq_val != NULL) {
4079
/* Value has form "x=y", adjust pointers and lengths
4080
* so that val points to "x", and eq_val points to "y". */
4081
eq_val->len = 0;
4082
eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
4083
if (eq_val->ptr != NULL) {
4084
eq_val->ptr++; /* Skip over '=' character */
4085
eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
4086
val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
4087
}
4088
}
4089
4090
return list;
4091
}
4092
4093
4094
/* A helper function for checking if a comma separated list of values
4095
* contains
4096
* the given option (case insensitvely).
4097
* 'header' can be NULL, in which case false is returned. */
4098
static int
4099
header_has_option(const char *header, const char *option)
4100
{
4101
struct vec opt_vec;
4102
struct vec eq_vec;
4103
4104
DEBUG_ASSERT(option != NULL);
4105
DEBUG_ASSERT(option[0] != '\0');
4106
4107
while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
4108
if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
4109
return 1;
4110
}
4111
4112
return 0;
4113
}
4114
4115
4116
/* Perform case-insensitive match of string against pattern */
4117
static ptrdiff_t
4118
match_prefix(const char *pattern, size_t pattern_len, const char *str)
4119
{
4120
const char *or_str;
4121
ptrdiff_t i, j, len, res;
4122
4123
if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
4124
res = match_prefix(pattern, (size_t)(or_str - pattern), str);
4125
return (res > 0) ? res
4126
: match_prefix(or_str + 1,
4127
(size_t)((pattern + pattern_len)
4128
- (or_str + 1)),
4129
str);
4130
}
4131
4132
for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
4133
if ((pattern[i] == '?') && (str[j] != '\0')) {
4134
continue;
4135
} else if (pattern[i] == '$') {
4136
return (str[j] == '\0') ? j : -1;
4137
} else if (pattern[i] == '*') {
4138
i++;
4139
if (pattern[i] == '*') {
4140
i++;
4141
len = strlen(str + j);
4142
} else {
4143
len = strcspn(str + j, "/");
4144
}
4145
if (i == (ptrdiff_t)pattern_len) {
4146
return j + len;
4147
}
4148
do {
4149
res = match_prefix(pattern + i, pattern_len - i, str + j + len);
4150
} while (res == -1 && len-- > 0);
4151
return (res == -1) ? -1 : j + res + len;
4152
} else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
4153
return -1;
4154
}
4155
}
4156
return (ptrdiff_t)j;
4157
}
4158
4159
4160
/* HTTP 1.1 assumes keep alive if "Connection:" header is not set
4161
* This function must tolerate situations when connection info is not
4162
* set up, for example if request parsing failed. */
4163
static int
4164
should_keep_alive(const struct mg_connection *conn)
4165
{
4166
const char *http_version;
4167
const char *header;
4168
4169
/* First satisfy needs of the server */
4170
if ((conn == NULL) || conn->must_close) {
4171
/* Close, if civetweb framework needs to close */
4172
return 0;
4173
}
4174
4175
if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
4176
/* Close, if keep alive is not enabled */
4177
return 0;
4178
}
4179
4180
/* Check explicit wish of the client */
4181
header = mg_get_header(conn, "Connection");
4182
if (header) {
4183
/* If there is a connection header from the client, obey */
4184
if (header_has_option(header, "keep-alive")) {
4185
return 1;
4186
}
4187
return 0;
4188
}
4189
4190
/* Use default of the standard */
4191
http_version = get_http_version(conn);
4192
if (http_version && (0 == strcmp(http_version, "1.1"))) {
4193
/* HTTP 1.1 default is keep alive */
4194
return 1;
4195
}
4196
4197
/* HTTP 1.0 (and earlier) default is to close the connection */
4198
return 0;
4199
}
4200
4201
4202
static int
4203
should_decode_url(const struct mg_connection *conn)
4204
{
4205
if (!conn || !conn->dom_ctx) {
4206
return 0;
4207
}
4208
4209
return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
4210
}
4211
4212
4213
static const char *
4214
suggest_connection_header(const struct mg_connection *conn)
4215
{
4216
return should_keep_alive(conn) ? "keep-alive" : "close";
4217
}
4218
4219
4220
static int
4221
send_no_cache_header(struct mg_connection *conn)
4222
{
4223
/* Send all current and obsolete cache opt-out directives. */
4224
return mg_printf(conn,
4225
"Cache-Control: no-cache, no-store, "
4226
"must-revalidate, private, max-age=0\r\n"
4227
"Pragma: no-cache\r\n"
4228
"Expires: 0\r\n");
4229
}
4230
4231
4232
static int
4233
send_static_cache_header(struct mg_connection *conn)
4234
{
4235
#if !defined(NO_CACHING)
4236
/* Read the server config to check how long a file may be cached.
4237
* The configuration is in seconds. */
4238
int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
4239
if (max_age <= 0) {
4240
/* 0 means "do not cache". All values <0 are reserved
4241
* and may be used differently in the future. */
4242
/* If a file should not be cached, do not only send
4243
* max-age=0, but also pragmas and Expires headers. */
4244
return send_no_cache_header(conn);
4245
}
4246
4247
/* Use "Cache-Control: max-age" instead of "Expires" header.
4248
* Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
4249
/* See also https://www.mnot.net/cache_docs/ */
4250
/* According to RFC 2616, Section 14.21, caching times should not exceed
4251
* one year. A year with 365 days corresponds to 31536000 seconds, a
4252
* leap
4253
* year to 31622400 seconds. For the moment, we just send whatever has
4254
* been configured, still the behavior for >1 year should be considered
4255
* as undefined. */
4256
return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
4257
#else /* NO_CACHING */
4258
return send_no_cache_header(conn);
4259
#endif /* !NO_CACHING */
4260
}
4261
4262
4263
static int
4264
send_additional_header(struct mg_connection *conn)
4265
{
4266
int i = 0;
4267
const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
4268
4269
#if !defined(NO_SSL)
4270
if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
4271
int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
4272
if (max_age >= 0) {
4273
i += mg_printf(conn,
4274
"Strict-Transport-Security: max-age=%u\r\n",
4275
(unsigned)max_age);
4276
}
4277
}
4278
#endif
4279
4280
if (header && header[0]) {
4281
i += mg_printf(conn, "%s\r\n", header);
4282
}
4283
4284
return i;
4285
}
4286
4287
4288
static void handle_file_based_request(struct mg_connection *conn,
4289
const char *path,
4290
struct mg_file *filep);
4291
4292
4293
const char *
4294
mg_get_response_code_text(const struct mg_connection *conn, int response_code)
4295
{
4296
/* See IANA HTTP status code assignment:
4297
* http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
4298
*/
4299
4300
switch (response_code) {
4301
/* RFC2616 Section 10.1 - Informational 1xx */
4302
case 100:
4303
return "Continue"; /* RFC2616 Section 10.1.1 */
4304
case 101:
4305
return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
4306
case 102:
4307
return "Processing"; /* RFC2518 Section 10.1 */
4308
4309
/* RFC2616 Section 10.2 - Successful 2xx */
4310
case 200:
4311
return "OK"; /* RFC2616 Section 10.2.1 */
4312
case 201:
4313
return "Created"; /* RFC2616 Section 10.2.2 */
4314
case 202:
4315
return "Accepted"; /* RFC2616 Section 10.2.3 */
4316
case 203:
4317
return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
4318
case 204:
4319
return "No Content"; /* RFC2616 Section 10.2.5 */
4320
case 205:
4321
return "Reset Content"; /* RFC2616 Section 10.2.6 */
4322
case 206:
4323
return "Partial Content"; /* RFC2616 Section 10.2.7 */
4324
case 207:
4325
return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
4326
*/
4327
case 208:
4328
return "Already Reported"; /* RFC5842 Section 7.1 */
4329
4330
case 226:
4331
return "IM used"; /* RFC3229 Section 10.4.1 */
4332
4333
/* RFC2616 Section 10.3 - Redirection 3xx */
4334
case 300:
4335
return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
4336
case 301:
4337
return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
4338
case 302:
4339
return "Found"; /* RFC2616 Section 10.3.3 */
4340
case 303:
4341
return "See Other"; /* RFC2616 Section 10.3.4 */
4342
case 304:
4343
return "Not Modified"; /* RFC2616 Section 10.3.5 */
4344
case 305:
4345
return "Use Proxy"; /* RFC2616 Section 10.3.6 */
4346
case 307:
4347
return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
4348
case 308:
4349
return "Permanent Redirect"; /* RFC7238 Section 3 */
4350
4351
/* RFC2616 Section 10.4 - Client Error 4xx */
4352
case 400:
4353
return "Bad Request"; /* RFC2616 Section 10.4.1 */
4354
case 401:
4355
return "Unauthorized"; /* RFC2616 Section 10.4.2 */
4356
case 402:
4357
return "Payment Required"; /* RFC2616 Section 10.4.3 */
4358
case 403:
4359
return "Forbidden"; /* RFC2616 Section 10.4.4 */
4360
case 404:
4361
return "Not Found"; /* RFC2616 Section 10.4.5 */
4362
case 405:
4363
return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
4364
case 406:
4365
return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
4366
case 407:
4367
return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
4368
case 408:
4369
return "Request Time-out"; /* RFC2616 Section 10.4.9 */
4370
case 409:
4371
return "Conflict"; /* RFC2616 Section 10.4.10 */
4372
case 410:
4373
return "Gone"; /* RFC2616 Section 10.4.11 */
4374
case 411:
4375
return "Length Required"; /* RFC2616 Section 10.4.12 */
4376
case 412:
4377
return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
4378
case 413:
4379
return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
4380
case 414:
4381
return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
4382
case 415:
4383
return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
4384
case 416:
4385
return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
4386
*/
4387
case 417:
4388
return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
4389
4390
case 421:
4391
return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
4392
case 422:
4393
return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
4394
* Section 11.2 */
4395
case 423:
4396
return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
4397
case 424:
4398
return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
4399
* Section 11.4 */
4400
4401
case 426:
4402
return "Upgrade Required"; /* RFC 2817 Section 4 */
4403
4404
case 428:
4405
return "Precondition Required"; /* RFC 6585, Section 3 */
4406
case 429:
4407
return "Too Many Requests"; /* RFC 6585, Section 4 */
4408
4409
case 431:
4410
return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
4411
4412
case 451:
4413
return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
4414
* Section 3 */
4415
4416
/* RFC2616 Section 10.5 - Server Error 5xx */
4417
case 500:
4418
return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
4419
case 501:
4420
return "Not Implemented"; /* RFC2616 Section 10.5.2 */
4421
case 502:
4422
return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
4423
case 503:
4424
return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
4425
case 504:
4426
return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
4427
case 505:
4428
return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
4429
case 506:
4430
return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
4431
case 507:
4432
return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
4433
* Section 11.5 */
4434
case 508:
4435
return "Loop Detected"; /* RFC5842 Section 7.1 */
4436
4437
case 510:
4438
return "Not Extended"; /* RFC 2774, Section 7 */
4439
case 511:
4440
return "Network Authentication Required"; /* RFC 6585, Section 6 */
4441
4442
/* Other status codes, not shown in the IANA HTTP status code
4443
* assignment.
4444
* E.g., "de facto" standards due to common use, ... */
4445
case 418:
4446
return "I am a teapot"; /* RFC2324 Section 2.3.2 */
4447
case 419:
4448
return "Authentication Timeout"; /* common use */
4449
case 420:
4450
return "Enhance Your Calm"; /* common use */
4451
case 440:
4452
return "Login Timeout"; /* common use */
4453
case 509:
4454
return "Bandwidth Limit Exceeded"; /* common use */
4455
4456
default:
4457
/* This error code is unknown. This should not happen. */
4458
if (conn) {
4459
mg_cry_internal(conn,
4460
"Unknown HTTP response code: %u",
4461
response_code);
4462
}
4463
4464
/* Return at least a category according to RFC 2616 Section 10. */
4465
if (response_code >= 100 && response_code < 200) {
4466
/* Unknown informational status code */
4467
return "Information";
4468
}
4469
if (response_code >= 200 && response_code < 300) {
4470
/* Unknown success code */
4471
return "Success";
4472
}
4473
if (response_code >= 300 && response_code < 400) {
4474
/* Unknown redirection code */
4475
return "Redirection";
4476
}
4477
if (response_code >= 400 && response_code < 500) {
4478
/* Unknown request error code */
4479
return "Client Error";
4480
}
4481
if (response_code >= 500 && response_code < 600) {
4482
/* Unknown server error code */
4483
return "Server Error";
4484
}
4485
4486
/* Response code not even within reasonable range */
4487
return "";
4488
}
4489
}
4490
4491
4492
static int
4493
mg_send_http_error_impl(struct mg_connection *conn,
4494
int status,
4495
const char *fmt,
4496
va_list args)
4497
{
4498
char errmsg_buf[MG_BUF_LEN];
4499
char path_buf[PATH_MAX];
4500
va_list ap;
4501
int len, i, page_handler_found, scope, truncated, has_body;
4502
char date[64];
4503
time_t curtime = time(NULL);
4504
const char *error_handler = NULL;
4505
struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
4506
const char *error_page_file_ext, *tstr;
4507
int handled_by_callback = 0;
4508
4509
const char *status_text = mg_get_response_code_text(conn, status);
4510
4511
if ((conn == NULL) || (fmt == NULL)) {
4512
return -2;
4513
}
4514
4515
/* Set status (for log) */
4516
conn->status_code = status;
4517
4518
/* Errors 1xx, 204 and 304 MUST NOT send a body */
4519
has_body = ((status > 199) && (status != 204) && (status != 304));
4520
4521
/* Prepare message in buf, if required */
4522
if (has_body
4523
|| (!conn->in_error_handler
4524
&& (conn->phys_ctx->callbacks.http_error != NULL))) {
4525
/* Store error message in errmsg_buf */
4526
va_copy(ap, args);
4527
mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
4528
va_end(ap);
4529
/* In a debug build, print all html errors */
4530
DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
4531
}
4532
4533
/* If there is a http_error callback, call it.
4534
* But don't do it recursively, if callback calls mg_send_http_error again.
4535
*/
4536
if (!conn->in_error_handler
4537
&& (conn->phys_ctx->callbacks.http_error != NULL)) {
4538
/* Mark in_error_handler to avoid recursion and call user callback. */
4539
conn->in_error_handler = 1;
4540
handled_by_callback =
4541
(conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
4542
== 0);
4543
conn->in_error_handler = 0;
4544
}
4545
4546
if (!handled_by_callback) {
4547
/* Check for recursion */
4548
if (conn->in_error_handler) {
4549
DEBUG_TRACE(
4550
"Recursion when handling error %u - fall back to default",
4551
status);
4552
} else {
4553
/* Send user defined error pages, if defined */
4554
error_handler = conn->dom_ctx->config[ERROR_PAGES];
4555
error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
4556
page_handler_found = 0;
4557
4558
if (error_handler != NULL) {
4559
for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
4560
switch (scope) {
4561
case 1: /* Handler for specific error, e.g. 404 error */
4562
mg_snprintf(conn,
4563
&truncated,
4564
path_buf,
4565
sizeof(path_buf) - 32,
4566
"%serror%03u.",
4567
error_handler,
4568
status);
4569
break;
4570
case 2: /* Handler for error group, e.g., 5xx error
4571
* handler
4572
* for all server errors (500-599) */
4573
mg_snprintf(conn,
4574
&truncated,
4575
path_buf,
4576
sizeof(path_buf) - 32,
4577
"%serror%01uxx.",
4578
error_handler,
4579
status / 100);
4580
break;
4581
default: /* Handler for all errors */
4582
mg_snprintf(conn,
4583
&truncated,
4584
path_buf,
4585
sizeof(path_buf) - 32,
4586
"%serror.",
4587
error_handler);
4588
break;
4589
}
4590
4591
/* String truncation in buf may only occur if
4592
* error_handler is too long. This string is
4593
* from the config, not from a client. */
4594
(void)truncated;
4595
4596
len = (int)strlen(path_buf);
4597
4598
tstr = strchr(error_page_file_ext, '.');
4599
4600
while (tstr) {
4601
for (i = 1;
4602
(i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
4603
i++) {
4604
/* buffer overrun is not possible here, since
4605
* (i < 32) && (len < sizeof(path_buf) - 32)
4606
* ==> (i + len) < sizeof(path_buf) */
4607
path_buf[len + i - 1] = tstr[i];
4608
}
4609
/* buffer overrun is not possible here, since
4610
* (i <= 32) && (len < sizeof(path_buf) - 32)
4611
* ==> (i + len) <= sizeof(path_buf) */
4612
path_buf[len + i - 1] = 0;
4613
4614
if (mg_stat(conn, path_buf, &error_page_file.stat)) {
4615
DEBUG_TRACE("Check error page %s - found",
4616
path_buf);
4617
page_handler_found = 1;
4618
break;
4619
}
4620
DEBUG_TRACE("Check error page %s - not found",
4621
path_buf);
4622
4623
tstr = strchr(tstr + i, '.');
4624
}
4625
}
4626
}
4627
4628
if (page_handler_found) {
4629
conn->in_error_handler = 1;
4630
handle_file_based_request(conn, path_buf, &error_page_file);
4631
conn->in_error_handler = 0;
4632
return 0;
4633
}
4634
}
4635
4636
/* No custom error page. Send default error page. */
4637
gmt_time_string(date, sizeof(date), &curtime);
4638
4639
conn->must_close = 1;
4640
mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
4641
send_no_cache_header(conn);
4642
send_additional_header(conn);
4643
if (has_body) {
4644
mg_printf(conn,
4645
"%s",
4646
"Content-Type: text/plain; charset=utf-8\r\n");
4647
}
4648
mg_printf(conn,
4649
"Date: %s\r\n"
4650
"Connection: close\r\n\r\n",
4651
date);
4652
4653
/* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
4654
if (has_body) {
4655
/* For other errors, send a generic error message. */
4656
mg_printf(conn, "Error %d: %s\n", status, status_text);
4657
mg_write(conn, errmsg_buf, strlen(errmsg_buf));
4658
4659
} else {
4660
/* No body allowed. Close the connection. */
4661
DEBUG_TRACE("Error %i", status);
4662
}
4663
}
4664
return 0;
4665
}
4666
4667
4668
int
4669
mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
4670
{
4671
va_list ap;
4672
int ret;
4673
4674
va_start(ap, fmt);
4675
ret = mg_send_http_error_impl(conn, status, fmt, ap);
4676
va_end(ap);
4677
4678
return ret;
4679
}
4680
4681
4682
int
4683
mg_send_http_ok(struct mg_connection *conn,
4684
const char *mime_type,
4685
long long content_length)
4686
{
4687
char date[64];
4688
time_t curtime = time(NULL);
4689
4690
if ((mime_type == NULL) || (*mime_type == 0)) {
4691
/* Parameter error */
4692
return -2;
4693
}
4694
4695
gmt_time_string(date, sizeof(date), &curtime);
4696
4697
mg_printf(conn,
4698
"HTTP/1.1 200 OK\r\n"
4699
"Content-Type: %s\r\n"
4700
"Date: %s\r\n"
4701
"Connection: %s\r\n",
4702
mime_type,
4703
date,
4704
suggest_connection_header(conn));
4705
4706
send_no_cache_header(conn);
4707
send_additional_header(conn);
4708
if (content_length < 0) {
4709
mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
4710
} else {
4711
mg_printf(conn,
4712
"Content-Length: %" UINT64_FMT "\r\n\r\n",
4713
(uint64_t)content_length);
4714
}
4715
4716
return 0;
4717
}
4718
4719
4720
int
4721
mg_send_http_redirect(struct mg_connection *conn,
4722
const char *target_url,
4723
int redirect_code)
4724
{
4725
/* Send a 30x redirect response.
4726
*
4727
* Redirect types (status codes):
4728
*
4729
* Status | Perm/Temp | Method | Version
4730
* 301 | permanent | POST->GET undefined | HTTP/1.0
4731
* 302 | temporary | POST->GET undefined | HTTP/1.0
4732
* 303 | temporary | always use GET | HTTP/1.1
4733
* 307 | temporary | always keep method | HTTP/1.1
4734
* 308 | permanent | always keep method | HTTP/1.1
4735
*/
4736
const char *redirect_text;
4737
int ret;
4738
size_t content_len = 0;
4739
char reply[MG_BUF_LEN];
4740
4741
/* In case redirect_code=0, use 307. */
4742
if (redirect_code == 0) {
4743
redirect_code = 307;
4744
}
4745
4746
/* In case redirect_code is none of the above, return error. */
4747
if ((redirect_code != 301) && (redirect_code != 302)
4748
&& (redirect_code != 303) && (redirect_code != 307)
4749
&& (redirect_code != 308)) {
4750
/* Parameter error */
4751
return -2;
4752
}
4753
4754
/* Get proper text for response code */
4755
redirect_text = mg_get_response_code_text(conn, redirect_code);
4756
4757
/* If target_url is not defined, redirect to "/". */
4758
if ((target_url == NULL) || (*target_url == 0)) {
4759
target_url = "/";
4760
}
4761
4762
#if defined(MG_SEND_REDIRECT_BODY)
4763
/* TODO: condition name? */
4764
4765
/* Prepare a response body with a hyperlink.
4766
*
4767
* According to RFC2616 (and RFC1945 before):
4768
* Unless the request method was HEAD, the entity of the
4769
* response SHOULD contain a short hypertext note with a hyperlink to
4770
* the new URI(s).
4771
*
4772
* However, this response body is not useful in M2M communication.
4773
* Probably the original reason in the RFC was, clients not supporting
4774
* a 30x HTTP redirect could still show the HTML page and let the user
4775
* press the link. Since current browsers support 30x HTTP, the additional
4776
* HTML body does not seem to make sense anymore.
4777
*
4778
* The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
4779
* but it only notes:
4780
* The server's response payload usually contains a short
4781
* hypertext note with a hyperlink to the new URI(s).
4782
*
4783
* Deactivated by default. If you need the 30x body, set the define.
4784
*/
4785
mg_snprintf(
4786
conn,
4787
NULL /* ignore truncation */,
4788
reply,
4789
sizeof(reply),
4790
"<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
4791
redirect_text,
4792
target_url,
4793
target_url);
4794
content_len = strlen(reply);
4795
#else
4796
reply[0] = 0;
4797
#endif
4798
4799
/* Do not send any additional header. For all other options,
4800
* including caching, there are suitable defaults. */
4801
ret = mg_printf(conn,
4802
"HTTP/1.1 %i %s\r\n"
4803
"Location: %s\r\n"
4804
"Content-Length: %u\r\n"
4805
"Connection: %s\r\n\r\n",
4806
redirect_code,
4807
redirect_text,
4808
target_url,
4809
(unsigned int)content_len,
4810
suggest_connection_header(conn));
4811
4812
/* Send response body */
4813
if (ret > 0) {
4814
/* ... unless it is a HEAD request */
4815
if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
4816
ret = mg_write(conn, reply, content_len);
4817
}
4818
}
4819
4820
return (ret > 0) ? ret : -1;
4821
}
4822
4823
4824
#if defined(_WIN32)
4825
/* Create substitutes for POSIX functions in Win32. */
4826
4827
#if defined(GCC_DIAGNOSTIC)
4828
/* Show no warning in case system functions are not used. */
4829
#pragma GCC diagnostic push
4830
#pragma GCC diagnostic ignored "-Wunused-function"
4831
#endif
4832
4833
4834
FUNCTION_MAY_BE_UNUSED
4835
static int
4836
pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
4837
{
4838
(void)unused;
4839
*mutex = CreateMutex(NULL, FALSE, NULL);
4840
return (*mutex == NULL) ? -1 : 0;
4841
}
4842
4843
FUNCTION_MAY_BE_UNUSED
4844
static int
4845
pthread_mutex_destroy(pthread_mutex_t *mutex)
4846
{
4847
return (CloseHandle(*mutex) == 0) ? -1 : 0;
4848
}
4849
4850
4851
FUNCTION_MAY_BE_UNUSED
4852
static int
4853
pthread_mutex_lock(pthread_mutex_t *mutex)
4854
{
4855
return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
4856
: -1;
4857
}
4858
4859
4860
#if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
4861
FUNCTION_MAY_BE_UNUSED
4862
static int
4863
pthread_mutex_trylock(pthread_mutex_t *mutex)
4864
{
4865
switch (WaitForSingleObject(*mutex, 0)) {
4866
case WAIT_OBJECT_0:
4867
return 0;
4868
case WAIT_TIMEOUT:
4869
return -2; /* EBUSY */
4870
}
4871
return -1;
4872
}
4873
#endif
4874
4875
4876
FUNCTION_MAY_BE_UNUSED
4877
static int
4878
pthread_mutex_unlock(pthread_mutex_t *mutex)
4879
{
4880
return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
4881
}
4882
4883
4884
FUNCTION_MAY_BE_UNUSED
4885
static int
4886
pthread_cond_init(pthread_cond_t *cv, const void *unused)
4887
{
4888
(void)unused;
4889
InitializeCriticalSection(&cv->threadIdSec);
4890
cv->waiting_thread = NULL;
4891
return 0;
4892
}
4893
4894
4895
FUNCTION_MAY_BE_UNUSED
4896
static int
4897
pthread_cond_timedwait(pthread_cond_t *cv,
4898
pthread_mutex_t *mutex,
4899
FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
4900
{
4901
struct mg_workerTLS **ptls,
4902
*tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
4903
int ok;
4904
int64_t nsnow, nswaitabs, nswaitrel;
4905
DWORD mswaitrel;
4906
4907
EnterCriticalSection(&cv->threadIdSec);
4908
/* Add this thread to cv's waiting list */
4909
ptls = &cv->waiting_thread;
4910
for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
4911
;
4912
tls->next_waiting_thread = NULL;
4913
*ptls = tls;
4914
LeaveCriticalSection(&cv->threadIdSec);
4915
4916
if (abstime) {
4917
nsnow = mg_get_current_time_ns();
4918
nswaitabs =
4919
(((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
4920
nswaitrel = nswaitabs - nsnow;
4921
if (nswaitrel < 0) {
4922
nswaitrel = 0;
4923
}
4924
mswaitrel = (DWORD)(nswaitrel / 1000000);
4925
} else {
4926
mswaitrel = (DWORD)INFINITE;
4927
}
4928
4929
pthread_mutex_unlock(mutex);
4930
ok = (WAIT_OBJECT_0
4931
== WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
4932
if (!ok) {
4933
ok = 1;
4934
EnterCriticalSection(&cv->threadIdSec);
4935
ptls = &cv->waiting_thread;
4936
for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
4937
if (*ptls == tls) {
4938
*ptls = tls->next_waiting_thread;
4939
ok = 0;
4940
break;
4941
}
4942
}
4943
LeaveCriticalSection(&cv->threadIdSec);
4944
if (ok) {
4945
WaitForSingleObject(tls->pthread_cond_helper_mutex,
4946
(DWORD)INFINITE);
4947
}
4948
}
4949
/* This thread has been removed from cv's waiting list */
4950
pthread_mutex_lock(mutex);
4951
4952
return ok ? 0 : -1;
4953
}
4954
4955
4956
FUNCTION_MAY_BE_UNUSED
4957
static int
4958
pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
4959
{
4960
return pthread_cond_timedwait(cv, mutex, NULL);
4961
}
4962
4963
4964
FUNCTION_MAY_BE_UNUSED
4965
static int
4966
pthread_cond_signal(pthread_cond_t *cv)
4967
{
4968
HANDLE wkup = NULL;
4969
BOOL ok = FALSE;
4970
4971
EnterCriticalSection(&cv->threadIdSec);
4972
if (cv->waiting_thread) {
4973
wkup = cv->waiting_thread->pthread_cond_helper_mutex;
4974
cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
4975
4976
ok = SetEvent(wkup);
4977
DEBUG_ASSERT(ok);
4978
}
4979
LeaveCriticalSection(&cv->threadIdSec);
4980
4981
return ok ? 0 : 1;
4982
}
4983
4984
4985
FUNCTION_MAY_BE_UNUSED
4986
static int
4987
pthread_cond_broadcast(pthread_cond_t *cv)
4988
{
4989
EnterCriticalSection(&cv->threadIdSec);
4990
while (cv->waiting_thread) {
4991
pthread_cond_signal(cv);
4992
}
4993
LeaveCriticalSection(&cv->threadIdSec);
4994
4995
return 0;
4996
}
4997
4998
4999
FUNCTION_MAY_BE_UNUSED
5000
static int
5001
pthread_cond_destroy(pthread_cond_t *cv)
5002
{
5003
EnterCriticalSection(&cv->threadIdSec);
5004
DEBUG_ASSERT(cv->waiting_thread == NULL);
5005
LeaveCriticalSection(&cv->threadIdSec);
5006
DeleteCriticalSection(&cv->threadIdSec);
5007
5008
return 0;
5009
}
5010
5011
5012
#if defined(ALTERNATIVE_QUEUE)
5013
FUNCTION_MAY_BE_UNUSED
5014
static void *
5015
event_create(void)
5016
{
5017
return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
5018
}
5019
5020
5021
FUNCTION_MAY_BE_UNUSED
5022
static int
5023
event_wait(void *eventhdl)
5024
{
5025
int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
5026
return (res == WAIT_OBJECT_0);
5027
}
5028
5029
5030
FUNCTION_MAY_BE_UNUSED
5031
static int
5032
event_signal(void *eventhdl)
5033
{
5034
return (int)SetEvent((HANDLE)eventhdl);
5035
}
5036
5037
5038
FUNCTION_MAY_BE_UNUSED
5039
static void
5040
event_destroy(void *eventhdl)
5041
{
5042
CloseHandle((HANDLE)eventhdl);
5043
}
5044
#endif
5045
5046
5047
#if defined(GCC_DIAGNOSTIC)
5048
/* Enable unused function warning again */
5049
#pragma GCC diagnostic pop
5050
#endif
5051
5052
5053
/* For Windows, change all slashes to backslashes in path names. */
5054
static void
5055
change_slashes_to_backslashes(char *path)
5056
{
5057
int i;
5058
5059
for (i = 0; path[i] != '\0'; i++) {
5060
if (path[i] == '/') {
5061
path[i] = '\\';
5062
}
5063
5064
/* remove double backslash (check i > 0 to preserve UNC paths,
5065
* like \\server\file.txt) */
5066
if ((path[i] == '\\') && (i > 0)) {
5067
while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
5068
(void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
5069
}
5070
}
5071
}
5072
}
5073
5074
5075
static int
5076
mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
5077
{
5078
int diff;
5079
5080
do {
5081
diff = tolower(*s1) - tolower(*s2);
5082
s1++;
5083
s2++;
5084
} while ((diff == 0) && (s1[-1] != '\0'));
5085
5086
return diff;
5087
}
5088
5089
5090
/* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
5091
* wbuf and wbuf_len is a target buffer and its length. */
5092
static void
5093
path_to_unicode(const struct mg_connection *conn,
5094
const char *path,
5095
wchar_t *wbuf,
5096
size_t wbuf_len)
5097
{
5098
char buf[PATH_MAX], buf2[PATH_MAX];
5099
wchar_t wbuf2[W_PATH_MAX + 1];
5100
DWORD long_len, err;
5101
int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
5102
5103
mg_strlcpy(buf, path, sizeof(buf));
5104
change_slashes_to_backslashes(buf);
5105
5106
/* Convert to Unicode and back. If doubly-converted string does not
5107
* match the original, something is fishy, reject. */
5108
memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
5109
MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
5110
WideCharToMultiByte(
5111
CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
5112
if (strcmp(buf, buf2) != 0) {
5113
wbuf[0] = L'\0';
5114
}
5115
5116
/* Windows file systems are not case sensitive, but you can still use
5117
* uppercase and lowercase letters (on all modern file systems).
5118
* The server can check if the URI uses the same upper/lowercase
5119
* letters an the file system, effectively making Windows servers
5120
* case sensitive (like Linux servers are). It is still not possible
5121
* to use two files with the same name in different cases on Windows
5122
* (like /a and /A) - this would be possible in Linux.
5123
* As a default, Windows is not case sensitive, but the case sensitive
5124
* file name check can be activated by an additional configuration. */
5125
if (conn) {
5126
if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
5127
&& !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
5128
"yes")) {
5129
/* Use case sensitive compare function */
5130
fcompare = wcscmp;
5131
}
5132
}
5133
(void)conn; /* conn is currently unused */
5134
5135
#if !defined(_WIN32_WCE)
5136
/* Only accept a full file path, not a Windows short (8.3) path. */
5137
memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
5138
long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
5139
if (long_len == 0) {
5140
err = GetLastError();
5141
if (err == ERROR_FILE_NOT_FOUND) {
5142
/* File does not exist. This is not always a problem here. */
5143
return;
5144
}
5145
}
5146
if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
5147
/* Short name is used. */
5148
wbuf[0] = L'\0';
5149
}
5150
#else
5151
(void)long_len;
5152
(void)wbuf2;
5153
(void)err;
5154
5155
if (strchr(path, '~')) {
5156
wbuf[0] = L'\0';
5157
}
5158
#endif
5159
}
5160
5161
5162
/* Windows happily opens files with some garbage at the end of file name.
5163
* For example, fopen("a.cgi ", "r") on Windows successfully opens
5164
* "a.cgi", despite one would expect an error back.
5165
* This function returns non-0 if path ends with some garbage. */
5166
static int
5167
path_cannot_disclose_cgi(const char *path)
5168
{
5169
static const char *allowed_last_characters = "_-";
5170
int last = path[strlen(path) - 1];
5171
return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
5172
}
5173
5174
5175
static int
5176
mg_stat(const struct mg_connection *conn,
5177
const char *path,
5178
struct mg_file_stat *filep)
5179
{
5180
wchar_t wbuf[W_PATH_MAX];
5181
WIN32_FILE_ATTRIBUTE_DATA info;
5182
time_t creation_time;
5183
5184
if (!filep) {
5185
return 0;
5186
}
5187
memset(filep, 0, sizeof(*filep));
5188
5189
if (conn && is_file_in_memory(conn, path)) {
5190
/* filep->is_directory = 0; filep->gzipped = 0; .. already done by
5191
* memset */
5192
5193
/* Quick fix (for 1.9.x): */
5194
/* mg_stat must fill all fields, also for files in memory */
5195
struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
5196
open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
5197
filep->size = tmp_file.stat.size;
5198
filep->location = 2;
5199
/* TODO: for 1.10: restructure how files in memory are handled */
5200
5201
/* The "file in memory" feature is a candidate for deletion.
5202
* Please join the discussion at
5203
* https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
5204
*/
5205
5206
filep->last_modified = time(NULL); /* TODO */
5207
/* last_modified = now ... assumes the file may change during
5208
* runtime,
5209
* so every mg_fopen call may return different data */
5210
/* last_modified = conn->phys_ctx.start_time;
5211
* May be used it the data does not change during runtime. This
5212
* allows
5213
* browser caching. Since we do not know, we have to assume the file
5214
* in memory may change. */
5215
return 1;
5216
}
5217
5218
path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5219
if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
5220
filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
5221
filep->last_modified =
5222
SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
5223
info.ftLastWriteTime.dwHighDateTime);
5224
5225
/* On Windows, the file creation time can be higher than the
5226
* modification time, e.g. when a file is copied.
5227
* Since the Last-Modified timestamp is used for caching
5228
* it should be based on the most recent timestamp. */
5229
creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
5230
info.ftCreationTime.dwHighDateTime);
5231
if (creation_time > filep->last_modified) {
5232
filep->last_modified = creation_time;
5233
}
5234
5235
filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
5236
/* If file name is fishy, reset the file structure and return
5237
* error.
5238
* Note it is important to reset, not just return the error, cause
5239
* functions like is_file_opened() check the struct. */
5240
if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
5241
memset(filep, 0, sizeof(*filep));
5242
return 0;
5243
}
5244
5245
return 1;
5246
}
5247
5248
return 0;
5249
}
5250
5251
5252
static int
5253
mg_remove(const struct mg_connection *conn, const char *path)
5254
{
5255
wchar_t wbuf[W_PATH_MAX];
5256
path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5257
return DeleteFileW(wbuf) ? 0 : -1;
5258
}
5259
5260
5261
static int
5262
mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
5263
{
5264
wchar_t wbuf[W_PATH_MAX];
5265
(void)mode;
5266
path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
5267
return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
5268
}
5269
5270
5271
/* Create substitutes for POSIX functions in Win32. */
5272
5273
#if defined(GCC_DIAGNOSTIC)
5274
/* Show no warning in case system functions are not used. */
5275
#pragma GCC diagnostic push
5276
#pragma GCC diagnostic ignored "-Wunused-function"
5277
#endif
5278
5279
5280
/* Implementation of POSIX opendir/closedir/readdir for Windows. */
5281
FUNCTION_MAY_BE_UNUSED
5282
static DIR *
5283
mg_opendir(const struct mg_connection *conn, const char *name)
5284
{
5285
DIR *dir = NULL;
5286
wchar_t wpath[W_PATH_MAX];
5287
DWORD attrs;
5288
5289
if (name == NULL) {
5290
SetLastError(ERROR_BAD_ARGUMENTS);
5291
} else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
5292
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
5293
} else {
5294
path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
5295
attrs = GetFileAttributesW(wpath);
5296
if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
5297
&& ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
5298
(void)wcscat(wpath, L"\\*");
5299
dir->handle = FindFirstFileW(wpath, &dir->info);
5300
dir->result.d_name[0] = '\0';
5301
} else {
5302
mg_free(dir);
5303
dir = NULL;
5304
}
5305
}
5306
5307
return dir;
5308
}
5309
5310
5311
FUNCTION_MAY_BE_UNUSED
5312
static int
5313
mg_closedir(DIR *dir)
5314
{
5315
int result = 0;
5316
5317
if (dir != NULL) {
5318
if (dir->handle != INVALID_HANDLE_VALUE)
5319
result = FindClose(dir->handle) ? 0 : -1;
5320
5321
mg_free(dir);
5322
} else {
5323
result = -1;
5324
SetLastError(ERROR_BAD_ARGUMENTS);
5325
}
5326
5327
return result;
5328
}
5329
5330
5331
FUNCTION_MAY_BE_UNUSED
5332
static struct dirent *
5333
mg_readdir(DIR *dir)
5334
{
5335
struct dirent *result = 0;
5336
5337
if (dir) {
5338
if (dir->handle != INVALID_HANDLE_VALUE) {
5339
result = &dir->result;
5340
(void)WideCharToMultiByte(CP_UTF8,
5341
0,
5342
dir->info.cFileName,
5343
-1,
5344
result->d_name,
5345
sizeof(result->d_name),
5346
NULL,
5347
NULL);
5348
5349
if (!FindNextFileW(dir->handle, &dir->info)) {
5350
(void)FindClose(dir->handle);
5351
dir->handle = INVALID_HANDLE_VALUE;
5352
}
5353
5354
} else {
5355
SetLastError(ERROR_FILE_NOT_FOUND);
5356
}
5357
} else {
5358
SetLastError(ERROR_BAD_ARGUMENTS);
5359
}
5360
5361
return result;
5362
}
5363
5364
5365
#if !defined(HAVE_POLL)
5366
#define POLLIN (1) /* Data ready - read will not block. */
5367
#define POLLPRI (2) /* Priority data ready. */
5368
#define POLLOUT (4) /* Send queue not full - write will not block. */
5369
5370
FUNCTION_MAY_BE_UNUSED
5371
static int
5372
poll(struct pollfd *pfd, unsigned int n, int milliseconds)
5373
{
5374
struct timeval tv;
5375
fd_set rset;
5376
fd_set wset;
5377
unsigned int i;
5378
int result;
5379
SOCKET maxfd = 0;
5380
5381
memset(&tv, 0, sizeof(tv));
5382
tv.tv_sec = milliseconds / 1000;
5383
tv.tv_usec = (milliseconds % 1000) * 1000;
5384
FD_ZERO(&rset);
5385
FD_ZERO(&wset);
5386
5387
for (i = 0; i < n; i++) {
5388
if (pfd[i].events & POLLIN) {
5389
FD_SET((SOCKET)pfd[i].fd, &rset);
5390
} else if (pfd[i].events & POLLOUT) {
5391
FD_SET((SOCKET)pfd[i].fd, &wset);
5392
}
5393
pfd[i].revents = 0;
5394
5395
if (pfd[i].fd > maxfd) {
5396
maxfd = pfd[i].fd;
5397
}
5398
}
5399
5400
if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
5401
for (i = 0; i < n; i++) {
5402
if (FD_ISSET(pfd[i].fd, &rset)) {
5403
pfd[i].revents |= POLLIN;
5404
}
5405
if (FD_ISSET(pfd[i].fd, &wset)) {
5406
pfd[i].revents |= POLLOUT;
5407
}
5408
}
5409
}
5410
5411
/* We should subtract the time used in select from remaining
5412
* "milliseconds", in particular if called from mg_poll with a
5413
* timeout quantum.
5414
* Unfortunately, the remaining time is not stored in "tv" in all
5415
* implementations, so the result in "tv" must be considered undefined.
5416
* See http://man7.org/linux/man-pages/man2/select.2.html */
5417
5418
return result;
5419
}
5420
#endif /* HAVE_POLL */
5421
5422
5423
#if defined(GCC_DIAGNOSTIC)
5424
/* Enable unused function warning again */
5425
#pragma GCC diagnostic pop
5426
#endif
5427
5428
5429
static void
5430
set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
5431
{
5432
(void)conn; /* Unused. */
5433
#if defined(_WIN32_WCE)
5434
(void)sock;
5435
#else
5436
(void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
5437
#endif
5438
}
5439
5440
5441
int
5442
mg_start_thread(mg_thread_func_t f, void *p)
5443
{
5444
#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5445
/* Compile-time option to control stack size, e.g.
5446
* -DUSE_STACK_SIZE=16384
5447
*/
5448
return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
5449
== ((uintptr_t)(-1L)))
5450
? -1
5451
: 0);
5452
#else
5453
return (
5454
(_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
5455
? -1
5456
: 0);
5457
#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5458
}
5459
5460
5461
/* Start a thread storing the thread context. */
5462
static int
5463
mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
5464
void *p,
5465
pthread_t *threadidptr)
5466
{
5467
uintptr_t uip;
5468
HANDLE threadhandle;
5469
int result = -1;
5470
5471
uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
5472
threadhandle = (HANDLE)uip;
5473
if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
5474
*threadidptr = threadhandle;
5475
result = 0;
5476
}
5477
5478
return result;
5479
}
5480
5481
5482
/* Wait for a thread to finish. */
5483
static int
5484
mg_join_thread(pthread_t threadid)
5485
{
5486
int result;
5487
DWORD dwevent;
5488
5489
result = -1;
5490
dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
5491
if (dwevent == WAIT_FAILED) {
5492
DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
5493
} else {
5494
if (dwevent == WAIT_OBJECT_0) {
5495
CloseHandle(threadid);
5496
result = 0;
5497
}
5498
}
5499
5500
return result;
5501
}
5502
5503
#if !defined(NO_SSL_DL) && !defined(NO_SSL)
5504
/* If SSL is loaded dynamically, dlopen/dlclose is required. */
5505
/* Create substitutes for POSIX functions in Win32. */
5506
5507
#if defined(GCC_DIAGNOSTIC)
5508
/* Show no warning in case system functions are not used. */
5509
#pragma GCC diagnostic push
5510
#pragma GCC diagnostic ignored "-Wunused-function"
5511
#endif
5512
5513
5514
FUNCTION_MAY_BE_UNUSED
5515
static HANDLE
5516
dlopen(const char *dll_name, int flags)
5517
{
5518
wchar_t wbuf[W_PATH_MAX];
5519
(void)flags;
5520
path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
5521
return LoadLibraryW(wbuf);
5522
}
5523
5524
5525
FUNCTION_MAY_BE_UNUSED
5526
static int
5527
dlclose(void *handle)
5528
{
5529
int result;
5530
5531
if (FreeLibrary((HMODULE)handle) != 0) {
5532
result = 0;
5533
} else {
5534
result = -1;
5535
}
5536
5537
return result;
5538
}
5539
5540
5541
#if defined(GCC_DIAGNOSTIC)
5542
/* Enable unused function warning again */
5543
#pragma GCC diagnostic pop
5544
#endif
5545
5546
#endif
5547
5548
5549
#if !defined(NO_CGI)
5550
#define SIGKILL (0)
5551
5552
5553
static int
5554
kill(pid_t pid, int sig_num)
5555
{
5556
(void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
5557
(void)CloseHandle((HANDLE)pid);
5558
return 0;
5559
}
5560
5561
5562
#if !defined(WNOHANG)
5563
#define WNOHANG (1)
5564
#endif
5565
5566
5567
static pid_t
5568
waitpid(pid_t pid, int *status, int flags)
5569
{
5570
DWORD timeout = INFINITE;
5571
DWORD waitres;
5572
5573
(void)status; /* Currently not used by any client here */
5574
5575
if ((flags | WNOHANG) == WNOHANG) {
5576
timeout = 0;
5577
}
5578
5579
waitres = WaitForSingleObject((HANDLE)pid, timeout);
5580
if (waitres == WAIT_OBJECT_0) {
5581
return pid;
5582
}
5583
if (waitres == WAIT_TIMEOUT) {
5584
return 0;
5585
}
5586
return (pid_t)-1;
5587
}
5588
5589
5590
static void
5591
trim_trailing_whitespaces(char *s)
5592
{
5593
char *e = s + strlen(s) - 1;
5594
while ((e > s) && isspace(*(unsigned char *)e)) {
5595
*e-- = '\0';
5596
}
5597
}
5598
5599
5600
static pid_t
5601
spawn_process(struct mg_connection *conn,
5602
const char *prog,
5603
char *envblk,
5604
char *envp[],
5605
int fdin[2],
5606
int fdout[2],
5607
int fderr[2],
5608
const char *dir)
5609
{
5610
HANDLE me;
5611
char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
5612
cmdline[PATH_MAX], buf[PATH_MAX];
5613
int truncated;
5614
struct mg_file file = STRUCT_FILE_INITIALIZER;
5615
STARTUPINFOA si;
5616
PROCESS_INFORMATION pi = {0};
5617
5618
(void)envp;
5619
5620
memset(&si, 0, sizeof(si));
5621
si.cb = sizeof(si);
5622
5623
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
5624
si.wShowWindow = SW_HIDE;
5625
5626
me = GetCurrentProcess();
5627
DuplicateHandle(me,
5628
(HANDLE)_get_osfhandle(fdin[0]),
5629
me,
5630
&si.hStdInput,
5631
0,
5632
TRUE,
5633
DUPLICATE_SAME_ACCESS);
5634
DuplicateHandle(me,
5635
(HANDLE)_get_osfhandle(fdout[1]),
5636
me,
5637
&si.hStdOutput,
5638
0,
5639
TRUE,
5640
DUPLICATE_SAME_ACCESS);
5641
DuplicateHandle(me,
5642
(HANDLE)_get_osfhandle(fderr[1]),
5643
me,
5644
&si.hStdError,
5645
0,
5646
TRUE,
5647
DUPLICATE_SAME_ACCESS);
5648
5649
/* Mark handles that should not be inherited. See
5650
* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
5651
*/
5652
SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
5653
HANDLE_FLAG_INHERIT,
5654
0);
5655
SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
5656
HANDLE_FLAG_INHERIT,
5657
0);
5658
SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
5659
HANDLE_FLAG_INHERIT,
5660
0);
5661
5662
/* If CGI file is a script, try to read the interpreter line */
5663
interp = conn->dom_ctx->config[CGI_INTERPRETER];
5664
if (interp == NULL) {
5665
buf[0] = buf[1] = '\0';
5666
5667
/* Read the first line of the script into the buffer */
5668
mg_snprintf(
5669
conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
5670
5671
if (truncated) {
5672
pi.hProcess = (pid_t)-1;
5673
goto spawn_cleanup;
5674
}
5675
5676
if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
5677
#if defined(MG_USE_OPEN_FILE)
5678
p = (char *)file.access.membuf;
5679
#else
5680
p = (char *)NULL;
5681
#endif
5682
mg_fgets(buf, sizeof(buf), &file, &p);
5683
(void)mg_fclose(&file.access); /* ignore error on read only file */
5684
buf[sizeof(buf) - 1] = '\0';
5685
}
5686
5687
if ((buf[0] == '#') && (buf[1] == '!')) {
5688
trim_trailing_whitespaces(buf + 2);
5689
} else {
5690
buf[2] = '\0';
5691
}
5692
interp = buf + 2;
5693
}
5694
5695
if (interp[0] != '\0') {
5696
GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
5697
interp = full_interp;
5698
}
5699
GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
5700
5701
if (interp[0] != '\0') {
5702
mg_snprintf(conn,
5703
&truncated,
5704
cmdline,
5705
sizeof(cmdline),
5706
"\"%s\" \"%s\\%s\"",
5707
interp,
5708
full_dir,
5709
prog);
5710
} else {
5711
mg_snprintf(conn,
5712
&truncated,
5713
cmdline,
5714
sizeof(cmdline),
5715
"\"%s\\%s\"",
5716
full_dir,
5717
prog);
5718
}
5719
5720
if (truncated) {
5721
pi.hProcess = (pid_t)-1;
5722
goto spawn_cleanup;
5723
}
5724
5725
DEBUG_TRACE("Running [%s]", cmdline);
5726
if (CreateProcessA(NULL,
5727
cmdline,
5728
NULL,
5729
NULL,
5730
TRUE,
5731
CREATE_NEW_PROCESS_GROUP,
5732
envblk,
5733
NULL,
5734
&si,
5735
&pi)
5736
== 0) {
5737
mg_cry_internal(
5738
conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
5739
pi.hProcess = (pid_t)-1;
5740
/* goto spawn_cleanup; */
5741
}
5742
5743
spawn_cleanup:
5744
(void)CloseHandle(si.hStdOutput);
5745
(void)CloseHandle(si.hStdError);
5746
(void)CloseHandle(si.hStdInput);
5747
if (pi.hThread != NULL) {
5748
(void)CloseHandle(pi.hThread);
5749
}
5750
5751
return (pid_t)pi.hProcess;
5752
}
5753
#endif /* !NO_CGI */
5754
5755
5756
static int
5757
set_blocking_mode(SOCKET sock)
5758
{
5759
unsigned long non_blocking = 0;
5760
return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5761
}
5762
5763
static int
5764
set_non_blocking_mode(SOCKET sock)
5765
{
5766
unsigned long non_blocking = 1;
5767
return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
5768
}
5769
5770
#else
5771
5772
static int
5773
mg_stat(const struct mg_connection *conn,
5774
const char *path,
5775
struct mg_file_stat *filep)
5776
{
5777
struct stat st;
5778
if (!filep) {
5779
return 0;
5780
}
5781
memset(filep, 0, sizeof(*filep));
5782
5783
if (conn && is_file_in_memory(conn, path)) {
5784
5785
/* Quick fix (for 1.9.x): */
5786
/* mg_stat must fill all fields, also for files in memory */
5787
struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
5788
open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
5789
filep->size = tmp_file.stat.size;
5790
filep->last_modified = time(NULL);
5791
filep->location = 2;
5792
/* TODO: remove legacy "files in memory" feature */
5793
5794
return 1;
5795
}
5796
5797
if (0 == stat(path, &st)) {
5798
filep->size = (uint64_t)(st.st_size);
5799
filep->last_modified = st.st_mtime;
5800
filep->is_directory = S_ISDIR(st.st_mode);
5801
return 1;
5802
}
5803
5804
return 0;
5805
}
5806
5807
5808
static void
5809
set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
5810
{
5811
if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
5812
if (conn) {
5813
mg_cry_internal(conn,
5814
"%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
5815
__func__,
5816
strerror(ERRNO));
5817
}
5818
}
5819
}
5820
5821
5822
int
5823
mg_start_thread(mg_thread_func_t func, void *param)
5824
{
5825
pthread_t thread_id;
5826
pthread_attr_t attr;
5827
int result;
5828
5829
(void)pthread_attr_init(&attr);
5830
(void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
5831
5832
#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5833
/* Compile-time option to control stack size,
5834
* e.g. -DUSE_STACK_SIZE=16384 */
5835
(void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5836
#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
5837
5838
result = pthread_create(&thread_id, &attr, func, param);
5839
pthread_attr_destroy(&attr);
5840
5841
return result;
5842
}
5843
5844
5845
/* Start a thread storing the thread context. */
5846
static int
5847
mg_start_thread_with_id(mg_thread_func_t func,
5848
void *param,
5849
pthread_t *threadidptr)
5850
{
5851
pthread_t thread_id;
5852
pthread_attr_t attr;
5853
int result;
5854
5855
(void)pthread_attr_init(&attr);
5856
5857
#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
5858
/* Compile-time option to control stack size,
5859
* e.g. -DUSE_STACK_SIZE=16384 */
5860
(void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
5861
#endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
5862
5863
result = pthread_create(&thread_id, &attr, func, param);
5864
pthread_attr_destroy(&attr);
5865
if ((result == 0) && (threadidptr != NULL)) {
5866
*threadidptr = thread_id;
5867
}
5868
return result;
5869
}
5870
5871
5872
/* Wait for a thread to finish. */
5873
static int
5874
mg_join_thread(pthread_t threadid)
5875
{
5876
int result;
5877
5878
result = pthread_join(threadid, NULL);
5879
return result;
5880
}
5881
5882
5883
#if !defined(NO_CGI)
5884
static pid_t
5885
spawn_process(struct mg_connection *conn,
5886
const char *prog,
5887
char *envblk,
5888
char *envp[],
5889
int fdin[2],
5890
int fdout[2],
5891
int fderr[2],
5892
const char *dir)
5893
{
5894
pid_t pid;
5895
const char *interp;
5896
5897
(void)envblk;
5898
5899
if (conn == NULL) {
5900
return 0;
5901
}
5902
5903
if ((pid = fork()) == -1) {
5904
/* Parent */
5905
mg_send_http_error(conn,
5906
500,
5907
"Error: Creating CGI process\nfork(): %s",
5908
strerror(ERRNO));
5909
} else if (pid == 0) {
5910
/* Child */
5911
if (chdir(dir) != 0) {
5912
mg_cry_internal(
5913
conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
5914
} else if (dup2(fdin[0], 0) == -1) {
5915
mg_cry_internal(conn,
5916
"%s: dup2(%d, 0): %s",
5917
__func__,
5918
fdin[0],
5919
strerror(ERRNO));
5920
} else if (dup2(fdout[1], 1) == -1) {
5921
mg_cry_internal(conn,
5922
"%s: dup2(%d, 1): %s",
5923
__func__,
5924
fdout[1],
5925
strerror(ERRNO));
5926
} else if (dup2(fderr[1], 2) == -1) {
5927
mg_cry_internal(conn,
5928
"%s: dup2(%d, 2): %s",
5929
__func__,
5930
fderr[1],
5931
strerror(ERRNO));
5932
} else {
5933
/* Keep stderr and stdout in two different pipes.
5934
* Stdout will be sent back to the client,
5935
* stderr should go into a server error log. */
5936
(void)close(fdin[0]);
5937
(void)close(fdout[1]);
5938
(void)close(fderr[1]);
5939
5940
/* Close write end fdin and read end fdout and fderr */
5941
(void)close(fdin[1]);
5942
(void)close(fdout[0]);
5943
(void)close(fderr[0]);
5944
5945
/* After exec, all signal handlers are restored to their default
5946
* values, with one exception of SIGCHLD. According to
5947
* POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
5948
* will leave unchanged after exec if it was set to be ignored.
5949
* Restore it to default action. */
5950
signal(SIGCHLD, SIG_DFL);
5951
5952
interp = conn->dom_ctx->config[CGI_INTERPRETER];
5953
if (interp == NULL) {
5954
(void)execle(prog, prog, NULL, envp);
5955
mg_cry_internal(conn,
5956
"%s: execle(%s): %s",
5957
__func__,
5958
prog,
5959
strerror(ERRNO));
5960
} else {
5961
(void)execle(interp, interp, prog, NULL, envp);
5962
mg_cry_internal(conn,
5963
"%s: execle(%s %s): %s",
5964
__func__,
5965
interp,
5966
prog,
5967
strerror(ERRNO));
5968
}
5969
}
5970
exit(EXIT_FAILURE);
5971
}
5972
5973
return pid;
5974
}
5975
#endif /* !NO_CGI */
5976
5977
5978
static int
5979
set_non_blocking_mode(SOCKET sock)
5980
{
5981
int flags = fcntl(sock, F_GETFL, 0);
5982
if (flags < 0) {
5983
return -1;
5984
}
5985
5986
if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
5987
return -1;
5988
}
5989
return 0;
5990
}
5991
5992
static int
5993
set_blocking_mode(SOCKET sock)
5994
{
5995
int flags = fcntl(sock, F_GETFL, 0);
5996
if (flags < 0) {
5997
return -1;
5998
}
5999
6000
if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
6001
return -1;
6002
}
6003
return 0;
6004
}
6005
#endif /* _WIN32 / else */
6006
6007
/* End of initial operating system specific define block. */
6008
6009
6010
/* Get a random number (independent of C rand function) */
6011
static uint64_t
6012
get_random(void)
6013
{
6014
static uint64_t lfsr = 0; /* Linear feedback shift register */
6015
static uint64_t lcg = 0; /* Linear congruential generator */
6016
uint64_t now = mg_get_current_time_ns();
6017
6018
if (lfsr == 0) {
6019
/* lfsr will be only 0 if has not been initialized,
6020
* so this code is called only once. */
6021
lfsr = mg_get_current_time_ns();
6022
lcg = mg_get_current_time_ns();
6023
} else {
6024
/* Get the next step of both random number generators. */
6025
lfsr = (lfsr >> 1)
6026
| ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
6027
<< 63);
6028
lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
6029
}
6030
6031
/* Combining two pseudo-random number generators and a high resolution
6032
* part
6033
* of the current server time will make it hard (impossible?) to guess
6034
* the
6035
* next number. */
6036
return (lfsr ^ lcg ^ now);
6037
}
6038
6039
6040
static int
6041
mg_poll(struct pollfd *pfd,
6042
unsigned int n,
6043
int milliseconds,
6044
volatile int *stop_server)
6045
{
6046
/* Call poll, but only for a maximum time of a few seconds.
6047
* This will allow to stop the server after some seconds, instead
6048
* of having to wait for a long socket timeout. */
6049
int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
6050
6051
do {
6052
int result;
6053
6054
if (*stop_server) {
6055
/* Shut down signal */
6056
return -2;
6057
}
6058
6059
if ((milliseconds >= 0) && (milliseconds < ms_now)) {
6060
ms_now = milliseconds;
6061
}
6062
6063
result = poll(pfd, n, ms_now);
6064
if (result != 0) {
6065
/* Poll returned either success (1) or error (-1).
6066
* Forward both to the caller. */
6067
return result;
6068
}
6069
6070
/* Poll returned timeout (0). */
6071
if (milliseconds > 0) {
6072
milliseconds -= ms_now;
6073
}
6074
6075
} while (milliseconds != 0);
6076
6077
/* timeout: return 0 */
6078
return 0;
6079
}
6080
6081
6082
/* Write data to the IO channel - opened file descriptor, socket or SSL
6083
* descriptor.
6084
* Return value:
6085
* >=0 .. number of bytes successfully written
6086
* -1 .. timeout
6087
* -2 .. error
6088
*/
6089
static int
6090
push_inner(struct mg_context *ctx,
6091
FILE *fp,
6092
SOCKET sock,
6093
SSL *ssl,
6094
const char *buf,
6095
int len,
6096
double timeout)
6097
{
6098
uint64_t start = 0, now = 0, timeout_ns = 0;
6099
int n, err;
6100
unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
6101
6102
#if defined(_WIN32)
6103
typedef int len_t;
6104
#else
6105
typedef size_t len_t;
6106
#endif
6107
6108
if (timeout > 0) {
6109
now = mg_get_current_time_ns();
6110
start = now;
6111
timeout_ns = (uint64_t)(timeout * 1.0E9);
6112
}
6113
6114
if (ctx == NULL) {
6115
return -2;
6116
}
6117
6118
#if defined(NO_SSL)
6119
if (ssl) {
6120
return -2;
6121
}
6122
#endif
6123
6124
/* Try to read until it succeeds, fails, times out, or the server
6125
* shuts down. */
6126
for (;;) {
6127
6128
#if !defined(NO_SSL)
6129
if (ssl != NULL) {
6130
n = SSL_write(ssl, buf, len);
6131
if (n <= 0) {
6132
err = SSL_get_error(ssl, n);
6133
if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
6134
err = ERRNO;
6135
} else if ((err == SSL_ERROR_WANT_READ)
6136
|| (err == SSL_ERROR_WANT_WRITE)) {
6137
n = 0;
6138
} else {
6139
DEBUG_TRACE("SSL_write() failed, error %d", err);
6140
return -2;
6141
}
6142
} else {
6143
err = 0;
6144
}
6145
} else
6146
#endif
6147
if (fp != NULL) {
6148
n = (int)fwrite(buf, 1, (size_t)len, fp);
6149
if (ferror(fp)) {
6150
n = -1;
6151
err = ERRNO;
6152
} else {
6153
err = 0;
6154
}
6155
} else {
6156
n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
6157
err = (n < 0) ? ERRNO : 0;
6158
#if defined(_WIN32)
6159
if (err == WSAEWOULDBLOCK) {
6160
err = 0;
6161
n = 0;
6162
}
6163
#else
6164
if (err == EWOULDBLOCK) {
6165
err = 0;
6166
n = 0;
6167
}
6168
#endif
6169
if (n < 0) {
6170
/* shutdown of the socket at client side */
6171
return -2;
6172
}
6173
}
6174
6175
if (ctx->stop_flag) {
6176
return -2;
6177
}
6178
6179
if ((n > 0) || ((n == 0) && (len == 0))) {
6180
/* some data has been read, or no data was requested */
6181
return n;
6182
}
6183
if (n < 0) {
6184
/* socket error - check errno */
6185
DEBUG_TRACE("send() failed, error %d", err);
6186
6187
/* TODO (mid): error handling depending on the error code.
6188
* These codes are different between Windows and Linux.
6189
* Currently there is no problem with failing send calls,
6190
* if there is a reproducible situation, it should be
6191
* investigated in detail.
6192
*/
6193
return -2;
6194
}
6195
6196
/* Only in case n=0 (timeout), repeat calling the write function */
6197
6198
/* If send failed, wait before retry */
6199
if (fp != NULL) {
6200
/* For files, just wait a fixed time.
6201
* Maybe it helps, maybe not. */
6202
mg_sleep(5);
6203
} else {
6204
/* For sockets, wait for the socket using poll */
6205
struct pollfd pfd[1];
6206
int pollres;
6207
6208
pfd[0].fd = sock;
6209
pfd[0].events = POLLOUT;
6210
pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
6211
if (ctx->stop_flag) {
6212
return -2;
6213
}
6214
if (pollres > 0) {
6215
continue;
6216
}
6217
}
6218
6219
if (timeout > 0) {
6220
now = mg_get_current_time_ns();
6221
if ((now - start) > timeout_ns) {
6222
/* Timeout */
6223
break;
6224
}
6225
}
6226
}
6227
6228
(void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
6229
used */
6230
6231
return -1;
6232
}
6233
6234
6235
static int64_t
6236
push_all(struct mg_context *ctx,
6237
FILE *fp,
6238
SOCKET sock,
6239
SSL *ssl,
6240
const char *buf,
6241
int64_t len)
6242
{
6243
double timeout = -1.0;
6244
int64_t n, nwritten = 0;
6245
6246
if (ctx == NULL) {
6247
return -1;
6248
}
6249
6250
if (ctx->dd.config[REQUEST_TIMEOUT]) {
6251
timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
6252
}
6253
6254
while ((len > 0) && (ctx->stop_flag == 0)) {
6255
n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
6256
if (n < 0) {
6257
if (nwritten == 0) {
6258
nwritten = n; /* Propagate the error */
6259
}
6260
break;
6261
} else if (n == 0) {
6262
break; /* No more data to write */
6263
} else {
6264
nwritten += n;
6265
len -= n;
6266
}
6267
}
6268
6269
return nwritten;
6270
}
6271
6272
6273
/* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
6274
* Return value:
6275
* >=0 .. number of bytes successfully read
6276
* -1 .. timeout
6277
* -2 .. error
6278
*/
6279
static int
6280
pull_inner(FILE *fp,
6281
struct mg_connection *conn,
6282
char *buf,
6283
int len,
6284
double timeout)
6285
{
6286
int nread, err = 0;
6287
6288
#if defined(_WIN32)
6289
typedef int len_t;
6290
#else
6291
typedef size_t len_t;
6292
#endif
6293
#if !defined(NO_SSL)
6294
int ssl_pending;
6295
#endif
6296
6297
/* We need an additional wait loop around this, because in some cases
6298
* with TLSwe may get data from the socket but not from SSL_read.
6299
* In this case we need to repeat at least once.
6300
*/
6301
6302
if (fp != NULL) {
6303
#if !defined(_WIN32_WCE)
6304
/* Use read() instead of fread(), because if we're reading from the
6305
* CGI pipe, fread() may block until IO buffer is filled up. We
6306
* cannot afford to block and must pass all read bytes immediately
6307
* to the client. */
6308
nread = (int)read(fileno(fp), buf, (size_t)len);
6309
#else
6310
/* WinCE does not support CGI pipes */
6311
nread = (int)fread(buf, 1, (size_t)len, fp);
6312
#endif
6313
err = (nread < 0) ? ERRNO : 0;
6314
if ((nread == 0) && (len > 0)) {
6315
/* Should get data, but got EOL */
6316
return -2;
6317
}
6318
6319
#if !defined(NO_SSL)
6320
} else if ((conn->ssl != NULL)
6321
&& ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
6322
/* We already know there is no more data buffered in conn->buf
6323
* but there is more available in the SSL layer. So don't poll
6324
* conn->client.sock yet. */
6325
if (ssl_pending > len) {
6326
ssl_pending = len;
6327
}
6328
nread = SSL_read(conn->ssl, buf, ssl_pending);
6329
if (nread <= 0) {
6330
err = SSL_get_error(conn->ssl, nread);
6331
if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
6332
err = ERRNO;
6333
} else if ((err == SSL_ERROR_WANT_READ)
6334
|| (err == SSL_ERROR_WANT_WRITE)) {
6335
nread = 0;
6336
} else {
6337
DEBUG_TRACE("SSL_read() failed, error %d", err);
6338
return -1;
6339
}
6340
} else {
6341
err = 0;
6342
}
6343
6344
} else if (conn->ssl != NULL) {
6345
6346
struct pollfd pfd[1];
6347
int pollres;
6348
6349
pfd[0].fd = conn->client.sock;
6350
pfd[0].events = POLLIN;
6351
pollres = mg_poll(pfd,
6352
1,
6353
(int)(timeout * 1000.0),
6354
&(conn->phys_ctx->stop_flag));
6355
if (conn->phys_ctx->stop_flag) {
6356
return -2;
6357
}
6358
if (pollres > 0) {
6359
nread = SSL_read(conn->ssl, buf, len);
6360
if (nread <= 0) {
6361
err = SSL_get_error(conn->ssl, nread);
6362
if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
6363
err = ERRNO;
6364
} else if ((err == SSL_ERROR_WANT_READ)
6365
|| (err == SSL_ERROR_WANT_WRITE)) {
6366
nread = 0;
6367
} else {
6368
DEBUG_TRACE("SSL_read() failed, error %d", err);
6369
return -2;
6370
}
6371
} else {
6372
err = 0;
6373
}
6374
6375
} else if (pollres < 0) {
6376
/* Error */
6377
return -2;
6378
} else {
6379
/* pollres = 0 means timeout */
6380
nread = 0;
6381
}
6382
#endif
6383
6384
} else {
6385
struct pollfd pfd[1];
6386
int pollres;
6387
6388
pfd[0].fd = conn->client.sock;
6389
pfd[0].events = POLLIN;
6390
pollres = mg_poll(pfd,
6391
1,
6392
(int)(timeout * 1000.0),
6393
&(conn->phys_ctx->stop_flag));
6394
if (conn->phys_ctx->stop_flag) {
6395
return -2;
6396
}
6397
if (pollres > 0) {
6398
nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
6399
err = (nread < 0) ? ERRNO : 0;
6400
if (nread <= 0) {
6401
/* shutdown of the socket at client side */
6402
return -2;
6403
}
6404
} else if (pollres < 0) {
6405
/* error callint poll */
6406
return -2;
6407
} else {
6408
/* pollres = 0 means timeout */
6409
nread = 0;
6410
}
6411
}
6412
6413
if (conn->phys_ctx->stop_flag) {
6414
return -2;
6415
}
6416
6417
if ((nread > 0) || ((nread == 0) && (len == 0))) {
6418
/* some data has been read, or no data was requested */
6419
return nread;
6420
}
6421
6422
if (nread < 0) {
6423
/* socket error - check errno */
6424
#if defined(_WIN32)
6425
if (err == WSAEWOULDBLOCK) {
6426
/* TODO (low): check if this is still required */
6427
/* standard case if called from close_socket_gracefully */
6428
return -2;
6429
} else if (err == WSAETIMEDOUT) {
6430
/* TODO (low): check if this is still required */
6431
/* timeout is handled by the while loop */
6432
return 0;
6433
} else if (err == WSAECONNABORTED) {
6434
/* See https://www.chilkatsoft.com/p/p_299.asp */
6435
return -2;
6436
} else {
6437
DEBUG_TRACE("recv() failed, error %d", err);
6438
return -2;
6439
}
6440
#else
6441
/* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
6442
* if the timeout is reached and if the socket was set to non-
6443
* blocking in close_socket_gracefully, so we can not distinguish
6444
* here. We have to wait for the timeout in both cases for now.
6445
*/
6446
if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
6447
/* TODO (low): check if this is still required */
6448
/* EAGAIN/EWOULDBLOCK:
6449
* standard case if called from close_socket_gracefully
6450
* => should return -1 */
6451
/* or timeout occurred
6452
* => the code must stay in the while loop */
6453
6454
/* EINTR can be generated on a socket with a timeout set even
6455
* when SA_RESTART is effective for all relevant signals
6456
* (see signal(7)).
6457
* => stay in the while loop */
6458
} else {
6459
DEBUG_TRACE("recv() failed, error %d", err);
6460
return -2;
6461
}
6462
#endif
6463
}
6464
6465
/* Timeout occurred, but no data available. */
6466
return -1;
6467
}
6468
6469
6470
static int
6471
pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
6472
{
6473
int n, nread = 0;
6474
double timeout = -1.0;
6475
uint64_t start_time = 0, now = 0, timeout_ns = 0;
6476
6477
if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
6478
timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
6479
}
6480
if (timeout >= 0.0) {
6481
start_time = mg_get_current_time_ns();
6482
timeout_ns = (uint64_t)(timeout * 1.0E9);
6483
}
6484
6485
while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
6486
n = pull_inner(fp, conn, buf + nread, len, timeout);
6487
if (n == -2) {
6488
if (nread == 0) {
6489
nread = -1; /* Propagate the error */
6490
}
6491
break;
6492
} else if (n == -1) {
6493
/* timeout */
6494
if (timeout >= 0.0) {
6495
now = mg_get_current_time_ns();
6496
if ((now - start_time) <= timeout_ns) {
6497
continue;
6498
}
6499
}
6500
break;
6501
} else if (n == 0) {
6502
break; /* No more data to read */
6503
} else {
6504
conn->consumed_content += n;
6505
nread += n;
6506
len -= n;
6507
}
6508
}
6509
6510
return nread;
6511
}
6512
6513
6514
static void
6515
discard_unread_request_data(struct mg_connection *conn)
6516
{
6517
char buf[MG_BUF_LEN];
6518
size_t to_read;
6519
int nread;
6520
6521
if (conn == NULL) {
6522
return;
6523
}
6524
6525
to_read = sizeof(buf);
6526
6527
if (conn->is_chunked) {
6528
/* Chunked encoding: 3=chunk read completely
6529
* completely */
6530
while (conn->is_chunked != 3) {
6531
nread = mg_read(conn, buf, to_read);
6532
if (nread <= 0) {
6533
break;
6534
}
6535
}
6536
6537
} else {
6538
/* Not chunked: content length is known */
6539
while (conn->consumed_content < conn->content_len) {
6540
if (to_read
6541
> (size_t)(conn->content_len - conn->consumed_content)) {
6542
to_read = (size_t)(conn->content_len - conn->consumed_content);
6543
}
6544
6545
nread = mg_read(conn, buf, to_read);
6546
if (nread <= 0) {
6547
break;
6548
}
6549
}
6550
}
6551
}
6552
6553
6554
static int
6555
mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
6556
{
6557
int64_t n, buffered_len, nread;
6558
int64_t len64 =
6559
(int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
6560
* int, we may not read more
6561
* bytes */
6562
const char *body;
6563
6564
if (conn == NULL) {
6565
return 0;
6566
}
6567
6568
/* If Content-Length is not set for a request with body data
6569
* (e.g., a PUT or POST request), we do not know in advance
6570
* how much data should be read. */
6571
if (conn->consumed_content == 0) {
6572
if (conn->is_chunked == 1) {
6573
conn->content_len = len64;
6574
conn->is_chunked = 2;
6575
} else if (conn->content_len == -1) {
6576
/* The body data is completed when the connection
6577
* is closed. */
6578
conn->content_len = INT64_MAX;
6579
conn->must_close = 1;
6580
}
6581
}
6582
6583
nread = 0;
6584
if (conn->consumed_content < conn->content_len) {
6585
/* Adjust number of bytes to read. */
6586
int64_t left_to_read = conn->content_len - conn->consumed_content;
6587
if (left_to_read < len64) {
6588
/* Do not read more than the total content length of the
6589
* request.
6590
*/
6591
len64 = left_to_read;
6592
}
6593
6594
/* Return buffered data */
6595
buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
6596
- conn->consumed_content;
6597
if (buffered_len > 0) {
6598
if (len64 < buffered_len) {
6599
buffered_len = len64;
6600
}
6601
body = conn->buf + conn->request_len + conn->consumed_content;
6602
memcpy(buf, body, (size_t)buffered_len);
6603
len64 -= buffered_len;
6604
conn->consumed_content += buffered_len;
6605
nread += buffered_len;
6606
buf = (char *)buf + buffered_len;
6607
}
6608
6609
/* We have returned all buffered data. Read new data from the remote
6610
* socket.
6611
*/
6612
if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
6613
nread += n;
6614
} else {
6615
nread = ((nread > 0) ? nread : n);
6616
}
6617
}
6618
return (int)nread;
6619
}
6620
6621
6622
static char
6623
mg_getc(struct mg_connection *conn)
6624
{
6625
char c;
6626
if (conn == NULL) {
6627
return 0;
6628
}
6629
if (mg_read_inner(conn, &c, 1) <= 0) {
6630
return (char)0;
6631
}
6632
return c;
6633
}
6634
6635
6636
int
6637
mg_read(struct mg_connection *conn, void *buf, size_t len)
6638
{
6639
if (len > INT_MAX) {
6640
len = INT_MAX;
6641
}
6642
6643
if (conn == NULL) {
6644
return 0;
6645
}
6646
6647
if (conn->is_chunked) {
6648
size_t all_read = 0;
6649
6650
while (len > 0) {
6651
if (conn->is_chunked == 3) {
6652
/* No more data left to read */
6653
return 0;
6654
}
6655
6656
if (conn->chunk_remainder) {
6657
/* copy from the remainder of the last received chunk */
6658
long read_ret;
6659
size_t read_now =
6660
((conn->chunk_remainder > len) ? (len)
6661
: (conn->chunk_remainder));
6662
6663
conn->content_len += (int)read_now;
6664
read_ret =
6665
mg_read_inner(conn, (char *)buf + all_read, read_now);
6666
6667
if (read_ret < 1) {
6668
/* read error */
6669
return -1;
6670
}
6671
6672
all_read += (size_t)read_ret;
6673
conn->chunk_remainder -= (size_t)read_ret;
6674
len -= (size_t)read_ret;
6675
6676
if (conn->chunk_remainder == 0) {
6677
/* Add data bytes in the current chunk have been read,
6678
* so we are expecting \r\n now. */
6679
char x1, x2;
6680
conn->content_len += 2;
6681
x1 = mg_getc(conn);
6682
x2 = mg_getc(conn);
6683
if ((x1 != '\r') || (x2 != '\n')) {
6684
/* Protocol violation */
6685
return -1;
6686
}
6687
}
6688
6689
} else {
6690
/* fetch a new chunk */
6691
int i = 0;
6692
char lenbuf[64];
6693
char *end = 0;
6694
unsigned long chunkSize = 0;
6695
6696
for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
6697
conn->content_len++;
6698
lenbuf[i] = mg_getc(conn);
6699
if ((i > 0) && (lenbuf[i] == '\r')
6700
&& (lenbuf[i - 1] != '\r')) {
6701
continue;
6702
}
6703
if ((i > 1) && (lenbuf[i] == '\n')
6704
&& (lenbuf[i - 1] == '\r')) {
6705
lenbuf[i + 1] = 0;
6706
chunkSize = strtoul(lenbuf, &end, 16);
6707
if (chunkSize == 0) {
6708
/* regular end of content */
6709
conn->is_chunked = 3;
6710
}
6711
break;
6712
}
6713
if (!isxdigit(lenbuf[i])) {
6714
/* illegal character for chunk length */
6715
return -1;
6716
}
6717
}
6718
if ((end == NULL) || (*end != '\r')) {
6719
/* chunksize not set correctly */
6720
return -1;
6721
}
6722
if (chunkSize == 0) {
6723
break;
6724
}
6725
6726
conn->chunk_remainder = chunkSize;
6727
}
6728
}
6729
6730
return (int)all_read;
6731
}
6732
return mg_read_inner(conn, buf, len);
6733
}
6734
6735
6736
int
6737
mg_write(struct mg_connection *conn, const void *buf, size_t len)
6738
{
6739
time_t now;
6740
int64_t n, total, allowed;
6741
6742
if (conn == NULL) {
6743
return 0;
6744
}
6745
6746
if (conn->throttle > 0) {
6747
if ((now = time(NULL)) != conn->last_throttle_time) {
6748
conn->last_throttle_time = now;
6749
conn->last_throttle_bytes = 0;
6750
}
6751
allowed = conn->throttle - conn->last_throttle_bytes;
6752
if (allowed > (int64_t)len) {
6753
allowed = (int64_t)len;
6754
}
6755
if ((total = push_all(conn->phys_ctx,
6756
NULL,
6757
conn->client.sock,
6758
conn->ssl,
6759
(const char *)buf,
6760
(int64_t)allowed))
6761
== allowed) {
6762
buf = (const char *)buf + total;
6763
conn->last_throttle_bytes += total;
6764
while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
6765
allowed = (conn->throttle > ((int64_t)len - total))
6766
? (int64_t)len - total
6767
: conn->throttle;
6768
if ((n = push_all(conn->phys_ctx,
6769
NULL,
6770
conn->client.sock,
6771
conn->ssl,
6772
(const char *)buf,
6773
(int64_t)allowed))
6774
!= allowed) {
6775
break;
6776
}
6777
sleep(1);
6778
conn->last_throttle_bytes = allowed;
6779
conn->last_throttle_time = time(NULL);
6780
buf = (const char *)buf + n;
6781
total += n;
6782
}
6783
}
6784
} else {
6785
total = push_all(conn->phys_ctx,
6786
NULL,
6787
conn->client.sock,
6788
conn->ssl,
6789
(const char *)buf,
6790
(int64_t)len);
6791
}
6792
if (total > 0) {
6793
conn->num_bytes_sent += total;
6794
}
6795
return (int)total;
6796
}
6797
6798
6799
/* Send a chunk, if "Transfer-Encoding: chunked" is used */
6800
int
6801
mg_send_chunk(struct mg_connection *conn,
6802
const char *chunk,
6803
unsigned int chunk_len)
6804
{
6805
char lenbuf[16];
6806
size_t lenbuf_len;
6807
int ret;
6808
int t;
6809
6810
/* First store the length information in a text buffer. */
6811
sprintf(lenbuf, "%x\r\n", chunk_len);
6812
lenbuf_len = strlen(lenbuf);
6813
6814
/* Then send length information, chunk and terminating \r\n. */
6815
ret = mg_write(conn, lenbuf, lenbuf_len);
6816
if (ret != (int)lenbuf_len) {
6817
return -1;
6818
}
6819
t = ret;
6820
6821
ret = mg_write(conn, chunk, chunk_len);
6822
if (ret != (int)chunk_len) {
6823
return -1;
6824
}
6825
t += ret;
6826
6827
ret = mg_write(conn, "\r\n", 2);
6828
if (ret != 2) {
6829
return -1;
6830
}
6831
t += ret;
6832
6833
return t;
6834
}
6835
6836
6837
#if defined(GCC_DIAGNOSTIC)
6838
/* This block forwards format strings to printf implementations,
6839
* so we need to disable the format-nonliteral warning. */
6840
#pragma GCC diagnostic push
6841
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
6842
#endif
6843
6844
6845
/* Alternative alloc_vprintf() for non-compliant C runtimes */
6846
static int
6847
alloc_vprintf2(char **buf, const char *fmt, va_list ap)
6848
{
6849
va_list ap_copy;
6850
size_t size = MG_BUF_LEN / 4;
6851
int len = -1;
6852
6853
*buf = NULL;
6854
while (len < 0) {
6855
if (*buf) {
6856
mg_free(*buf);
6857
}
6858
6859
size *= 4;
6860
*buf = (char *)mg_malloc(size);
6861
if (!*buf) {
6862
break;
6863
}
6864
6865
va_copy(ap_copy, ap);
6866
len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
6867
va_end(ap_copy);
6868
(*buf)[size - 1] = 0;
6869
}
6870
6871
return len;
6872
}
6873
6874
6875
/* Print message to buffer. If buffer is large enough to hold the message,
6876
* return buffer. If buffer is to small, allocate large enough buffer on
6877
* heap,
6878
* and return allocated buffer. */
6879
static int
6880
alloc_vprintf(char **out_buf,
6881
char *prealloc_buf,
6882
size_t prealloc_size,
6883
const char *fmt,
6884
va_list ap)
6885
{
6886
va_list ap_copy;
6887
int len;
6888
6889
/* Windows is not standard-compliant, and vsnprintf() returns -1 if
6890
* buffer is too small. Also, older versions of msvcrt.dll do not have
6891
* _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
6892
* Therefore, we make two passes: on first pass, get required message
6893
* length.
6894
* On second pass, actually print the message. */
6895
va_copy(ap_copy, ap);
6896
len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
6897
va_end(ap_copy);
6898
6899
if (len < 0) {
6900
/* C runtime is not standard compliant, vsnprintf() returned -1.
6901
* Switch to alternative code path that uses incremental
6902
* allocations.
6903
*/
6904
va_copy(ap_copy, ap);
6905
len = alloc_vprintf2(out_buf, fmt, ap_copy);
6906
va_end(ap_copy);
6907
6908
} else if ((size_t)(len) >= prealloc_size) {
6909
/* The pre-allocated buffer not large enough. */
6910
/* Allocate a new buffer. */
6911
*out_buf = (char *)mg_malloc((size_t)(len) + 1);
6912
if (!*out_buf) {
6913
/* Allocation failed. Return -1 as "out of memory" error. */
6914
return -1;
6915
}
6916
/* Buffer allocation successful. Store the string there. */
6917
va_copy(ap_copy, ap);
6918
IGNORE_UNUSED_RESULT(
6919
vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
6920
va_end(ap_copy);
6921
6922
} else {
6923
/* The pre-allocated buffer is large enough.
6924
* Use it to store the string and return the address. */
6925
va_copy(ap_copy, ap);
6926
IGNORE_UNUSED_RESULT(
6927
vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
6928
va_end(ap_copy);
6929
*out_buf = prealloc_buf;
6930
}
6931
6932
return len;
6933
}
6934
6935
6936
#if defined(GCC_DIAGNOSTIC)
6937
/* Enable format-nonliteral warning again. */
6938
#pragma GCC diagnostic pop
6939
#endif
6940
6941
6942
static int
6943
mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
6944
{
6945
char mem[MG_BUF_LEN];
6946
char *buf = NULL;
6947
int len;
6948
6949
if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
6950
len = mg_write(conn, buf, (size_t)len);
6951
}
6952
if ((buf != mem) && (buf != NULL)) {
6953
mg_free(buf);
6954
}
6955
6956
return len;
6957
}
6958
6959
6960
int
6961
mg_printf(struct mg_connection *conn, const char *fmt, ...)
6962
{
6963
va_list ap;
6964
int result;
6965
6966
va_start(ap, fmt);
6967
result = mg_vprintf(conn, fmt, ap);
6968
va_end(ap);
6969
6970
return result;
6971
}
6972
6973
6974
int
6975
mg_url_decode(const char *src,
6976
int src_len,
6977
char *dst,
6978
int dst_len,
6979
int is_form_url_encoded)
6980
{
6981
int i, j, a, b;
6982
#define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
6983
6984
for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
6985
if ((i < src_len - 2) && (src[i] == '%')
6986
&& isxdigit(*(const unsigned char *)(src + i + 1))
6987
&& isxdigit(*(const unsigned char *)(src + i + 2))) {
6988
a = tolower(*(const unsigned char *)(src + i + 1));
6989
b = tolower(*(const unsigned char *)(src + i + 2));
6990
dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
6991
i += 2;
6992
} else if (is_form_url_encoded && (src[i] == '+')) {
6993
dst[j] = ' ';
6994
} else {
6995
dst[j] = src[i];
6996
}
6997
}
6998
6999
dst[j] = '\0'; /* Null-terminate the destination */
7000
7001
return (i >= src_len) ? j : -1;
7002
}
7003
7004
7005
int
7006
mg_get_var(const char *data,
7007
size_t data_len,
7008
const char *name,
7009
char *dst,
7010
size_t dst_len)
7011
{
7012
return mg_get_var2(data, data_len, name, dst, dst_len, 0);
7013
}
7014
7015
7016
int
7017
mg_get_var2(const char *data,
7018
size_t data_len,
7019
const char *name,
7020
char *dst,
7021
size_t dst_len,
7022
size_t occurrence)
7023
{
7024
const char *p, *e, *s;
7025
size_t name_len;
7026
int len;
7027
7028
if ((dst == NULL) || (dst_len == 0)) {
7029
len = -2;
7030
} else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
7031
len = -1;
7032
dst[0] = '\0';
7033
} else {
7034
name_len = strlen(name);
7035
e = data + data_len;
7036
len = -1;
7037
dst[0] = '\0';
7038
7039
/* data is "var1=val1&var2=val2...". Find variable first */
7040
for (p = data; p + name_len < e; p++) {
7041
if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
7042
&& !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
7043
/* Point p to variable value */
7044
p += name_len + 1;
7045
7046
/* Point s to the end of the value */
7047
s = (const char *)memchr(p, '&', (size_t)(e - p));
7048
if (s == NULL) {
7049
s = e;
7050
}
7051
DEBUG_ASSERT(s >= p);
7052
if (s < p) {
7053
return -3;
7054
}
7055
7056
/* Decode variable into destination buffer */
7057
len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
7058
7059
/* Redirect error code from -1 to -2 (destination buffer too
7060
* small). */
7061
if (len == -1) {
7062
len = -2;
7063
}
7064
break;
7065
}
7066
}
7067
}
7068
7069
return len;
7070
}
7071
7072
7073
/* HCP24: some changes to compare hole var_name */
7074
int
7075
mg_get_cookie(const char *cookie_header,
7076
const char *var_name,
7077
char *dst,
7078
size_t dst_size)
7079
{
7080
const char *s, *p, *end;
7081
int name_len, len = -1;
7082
7083
if ((dst == NULL) || (dst_size == 0)) {
7084
return -2;
7085
}
7086
7087
dst[0] = '\0';
7088
if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
7089
return -1;
7090
}
7091
7092
name_len = (int)strlen(var_name);
7093
end = s + strlen(s);
7094
for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
7095
if (s[name_len] == '=') {
7096
/* HCP24: now check is it a substring or a full cookie name */
7097
if ((s == cookie_header) || (s[-1] == ' ')) {
7098
s += name_len + 1;
7099
if ((p = strchr(s, ' ')) == NULL) {
7100
p = end;
7101
}
7102
if (p[-1] == ';') {
7103
p--;
7104
}
7105
if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
7106
s++;
7107
p--;
7108
}
7109
if ((size_t)(p - s) < dst_size) {
7110
len = (int)(p - s);
7111
mg_strlcpy(dst, s, (size_t)len + 1);
7112
} else {
7113
len = -3;
7114
}
7115
break;
7116
}
7117
}
7118
}
7119
return len;
7120
}
7121
7122
7123
#if defined(USE_WEBSOCKET) || defined(USE_LUA)
7124
static void
7125
base64_encode(const unsigned char *src, int src_len, char *dst)
7126
{
7127
static const char *b64 =
7128
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7129
int i, j, a, b, c;
7130
7131
for (i = j = 0; i < src_len; i += 3) {
7132
a = src[i];
7133
b = ((i + 1) >= src_len) ? 0 : src[i + 1];
7134
c = ((i + 2) >= src_len) ? 0 : src[i + 2];
7135
7136
dst[j++] = b64[a >> 2];
7137
dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
7138
if (i + 1 < src_len) {
7139
dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
7140
}
7141
if (i + 2 < src_len) {
7142
dst[j++] = b64[c & 63];
7143
}
7144
}
7145
while (j % 4 != 0) {
7146
dst[j++] = '=';
7147
}
7148
dst[j++] = '\0';
7149
}
7150
#endif
7151
7152
7153
#if defined(USE_LUA)
7154
static unsigned char
7155
b64reverse(char letter)
7156
{
7157
if ((letter >= 'A') && (letter <= 'Z')) {
7158
return letter - 'A';
7159
}
7160
if ((letter >= 'a') && (letter <= 'z')) {
7161
return letter - 'a' + 26;
7162
}
7163
if ((letter >= '0') && (letter <= '9')) {
7164
return letter - '0' + 52;
7165
}
7166
if (letter == '+') {
7167
return 62;
7168
}
7169
if (letter == '/') {
7170
return 63;
7171
}
7172
if (letter == '=') {
7173
return 255; /* normal end */
7174
}
7175
return 254; /* error */
7176
}
7177
7178
7179
static int
7180
base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
7181
{
7182
int i;
7183
unsigned char a, b, c, d;
7184
7185
*dst_len = 0;
7186
7187
for (i = 0; i < src_len; i += 4) {
7188
a = b64reverse(src[i]);
7189
if (a >= 254) {
7190
return i;
7191
}
7192
7193
b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
7194
if (b >= 254) {
7195
return i + 1;
7196
}
7197
7198
c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
7199
if (c == 254) {
7200
return i + 2;
7201
}
7202
7203
d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
7204
if (d == 254) {
7205
return i + 3;
7206
}
7207
7208
dst[(*dst_len)++] = (a << 2) + (b >> 4);
7209
if (c != 255) {
7210
dst[(*dst_len)++] = (b << 4) + (c >> 2);
7211
if (d != 255) {
7212
dst[(*dst_len)++] = (c << 6) + d;
7213
}
7214
}
7215
}
7216
return -1;
7217
}
7218
#endif
7219
7220
7221
static int
7222
is_put_or_delete_method(const struct mg_connection *conn)
7223
{
7224
if (conn) {
7225
const char *s = conn->request_info.request_method;
7226
return (s != NULL)
7227
&& (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
7228
|| !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
7229
}
7230
return 0;
7231
}
7232
7233
7234
#if !defined(NO_FILES)
7235
static int
7236
extention_matches_script(
7237
struct mg_connection *conn, /* in: request (must be valid) */
7238
const char *filename /* in: filename (must be valid) */
7239
)
7240
{
7241
#if !defined(NO_CGI)
7242
if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
7243
strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
7244
filename)
7245
> 0) {
7246
return 1;
7247
}
7248
#endif
7249
#if defined(USE_LUA)
7250
if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
7251
strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
7252
filename)
7253
> 0) {
7254
return 1;
7255
}
7256
#endif
7257
#if defined(USE_DUKTAPE)
7258
if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
7259
strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
7260
filename)
7261
> 0) {
7262
return 1;
7263
}
7264
#endif
7265
/* filename and conn could be unused, if all preocessor conditions
7266
* are false (no script language supported). */
7267
(void)filename;
7268
(void)conn;
7269
7270
return 0;
7271
}
7272
7273
7274
/* For given directory path, substitute it to valid index file.
7275
* Return 1 if index file has been found, 0 if not found.
7276
* If the file is found, it's stats is returned in stp. */
7277
static int
7278
substitute_index_file(struct mg_connection *conn,
7279
char *path,
7280
size_t path_len,
7281
struct mg_file_stat *filestat)
7282
{
7283
const char *list = conn->dom_ctx->config[INDEX_FILES];
7284
struct vec filename_vec;
7285
size_t n = strlen(path);
7286
int found = 0;
7287
7288
/* The 'path' given to us points to the directory. Remove all trailing
7289
* directory separator characters from the end of the path, and
7290
* then append single directory separator character. */
7291
while ((n > 0) && (path[n - 1] == '/')) {
7292
n--;
7293
}
7294
path[n] = '/';
7295
7296
/* Traverse index files list. For each entry, append it to the given
7297
* path and see if the file exists. If it exists, break the loop */
7298
while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
7299
/* Ignore too long entries that may overflow path buffer */
7300
if ((filename_vec.len + 1) > (path_len - (n + 1))) {
7301
continue;
7302
}
7303
7304
/* Prepare full path to the index file */
7305
mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
7306
7307
/* Does it exist? */
7308
if (mg_stat(conn, path, filestat)) {
7309
/* Yes it does, break the loop */
7310
found = 1;
7311
break;
7312
}
7313
}
7314
7315
/* If no index file exists, restore directory path */
7316
if (!found) {
7317
path[n] = '\0';
7318
}
7319
7320
return found;
7321
}
7322
#endif
7323
7324
7325
static void
7326
interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
7327
char *filename, /* out: filename */
7328
size_t filename_buf_len, /* in: size of filename buffer */
7329
struct mg_file_stat *filestat, /* out: file status structure */
7330
int *is_found, /* out: file found (directly) */
7331
int *is_script_resource, /* out: handled by a script? */
7332
int *is_websocket_request, /* out: websocket connetion? */
7333
int *is_put_or_delete_request /* out: put/delete a file? */
7334
)
7335
{
7336
char const *accept_encoding;
7337
7338
#if !defined(NO_FILES)
7339
const char *uri = conn->request_info.local_uri;
7340
const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
7341
const char *rewrite;
7342
struct vec a, b;
7343
ptrdiff_t match_len;
7344
char gz_path[PATH_MAX];
7345
int truncated;
7346
#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7347
char *tmp_str;
7348
size_t tmp_str_len, sep_pos;
7349
int allow_substitute_script_subresources;
7350
#endif
7351
#else
7352
(void)filename_buf_len; /* unused if NO_FILES is defined */
7353
#endif
7354
7355
/* Step 1: Set all initially unknown outputs to zero */
7356
memset(filestat, 0, sizeof(*filestat));
7357
*filename = 0;
7358
*is_found = 0;
7359
*is_script_resource = 0;
7360
7361
/* Step 2: Check if the request attempts to modify the file system */
7362
*is_put_or_delete_request = is_put_or_delete_method(conn);
7363
7364
/* Step 3: Check if it is a websocket request, and modify the document
7365
* root if required */
7366
#if defined(USE_WEBSOCKET)
7367
*is_websocket_request = is_websocket_protocol(conn);
7368
#if !defined(NO_FILES)
7369
if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
7370
root = conn->dom_ctx->config[WEBSOCKET_ROOT];
7371
}
7372
#endif /* !NO_FILES */
7373
#else /* USE_WEBSOCKET */
7374
*is_websocket_request = 0;
7375
#endif /* USE_WEBSOCKET */
7376
7377
/* Step 4: Check if gzip encoded response is allowed */
7378
conn->accept_gzip = 0;
7379
if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
7380
if (strstr(accept_encoding, "gzip") != NULL) {
7381
conn->accept_gzip = 1;
7382
}
7383
}
7384
7385
#if !defined(NO_FILES)
7386
/* Step 5: If there is no root directory, don't look for files. */
7387
/* Note that root == NULL is a regular use case here. This occurs,
7388
* if all requests are handled by callbacks, so the WEBSOCKET_ROOT
7389
* config is not required. */
7390
if (root == NULL) {
7391
/* all file related outputs have already been set to 0, just return
7392
*/
7393
return;
7394
}
7395
7396
/* Step 6: Determine the local file path from the root path and the
7397
* request uri. */
7398
/* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
7399
* part of the path one byte on the right. */
7400
mg_snprintf(
7401
conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
7402
7403
if (truncated) {
7404
goto interpret_cleanup;
7405
}
7406
7407
/* Step 7: URI rewriting */
7408
rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
7409
while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
7410
if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
7411
mg_snprintf(conn,
7412
&truncated,
7413
filename,
7414
filename_buf_len - 1,
7415
"%.*s%s",
7416
(int)b.len,
7417
b.ptr,
7418
uri + match_len);
7419
break;
7420
}
7421
}
7422
7423
if (truncated) {
7424
goto interpret_cleanup;
7425
}
7426
7427
/* Step 8: Check if the file exists at the server */
7428
/* Local file path and name, corresponding to requested URI
7429
* is now stored in "filename" variable. */
7430
if (mg_stat(conn, filename, filestat)) {
7431
int uri_len = (int)strlen(uri);
7432
int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
7433
7434
/* 8.1: File exists. */
7435
*is_found = 1;
7436
7437
/* 8.2: Check if it is a script type. */
7438
if (extention_matches_script(conn, filename)) {
7439
/* The request addresses a CGI resource, Lua script or
7440
* server-side javascript.
7441
* The URI corresponds to the script itself (like
7442
* /path/script.cgi), and there is no additional resource
7443
* path (like /path/script.cgi/something).
7444
* Requests that modify (replace or delete) a resource, like
7445
* PUT and DELETE requests, should replace/delete the script
7446
* file.
7447
* Requests that read or write from/to a resource, like GET and
7448
* POST requests, should call the script and return the
7449
* generated response. */
7450
*is_script_resource = (!*is_put_or_delete_request);
7451
}
7452
7453
/* 8.3: If the request target is a directory, there could be
7454
* a substitute file (index.html, index.cgi, ...). */
7455
if (filestat->is_directory && is_uri_end_slash) {
7456
/* Use a local copy here, since substitute_index_file will
7457
* change the content of the file status */
7458
struct mg_file_stat tmp_filestat;
7459
memset(&tmp_filestat, 0, sizeof(tmp_filestat));
7460
7461
if (substitute_index_file(
7462
conn, filename, filename_buf_len, &tmp_filestat)) {
7463
7464
/* Substitute file found. Copy stat to the output, then
7465
* check if the file is a script file */
7466
*filestat = tmp_filestat;
7467
7468
if (extention_matches_script(conn, filename)) {
7469
/* Substitute file is a script file */
7470
*is_script_resource = 1;
7471
} else {
7472
/* Substitute file is a regular file */
7473
*is_script_resource = 0;
7474
*is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
7475
}
7476
}
7477
/* If there is no substitute file, the server could return
7478
* a directory listing in a later step */
7479
}
7480
return;
7481
}
7482
7483
/* Step 9: Check for zipped files: */
7484
/* If we can't find the actual file, look for the file
7485
* with the same name but a .gz extension. If we find it,
7486
* use that and set the gzipped flag in the file struct
7487
* to indicate that the response need to have the content-
7488
* encoding: gzip header.
7489
* We can only do this if the browser declares support. */
7490
if (conn->accept_gzip) {
7491
mg_snprintf(
7492
conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
7493
7494
if (truncated) {
7495
goto interpret_cleanup;
7496
}
7497
7498
if (mg_stat(conn, gz_path, filestat)) {
7499
if (filestat) {
7500
filestat->is_gzipped = 1;
7501
*is_found = 1;
7502
}
7503
/* Currently gz files can not be scripts. */
7504
return;
7505
}
7506
}
7507
7508
#if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
7509
/* Step 10: Script resources may handle sub-resources */
7510
/* Support PATH_INFO for CGI scripts. */
7511
tmp_str_len = strlen(filename);
7512
tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
7513
if (!tmp_str) {
7514
/* Out of memory */
7515
goto interpret_cleanup;
7516
}
7517
memcpy(tmp_str, filename, tmp_str_len + 1);
7518
7519
/* Check config, if index scripts may have sub-resources */
7520
allow_substitute_script_subresources =
7521
!mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
7522
"yes");
7523
7524
sep_pos = tmp_str_len;
7525
while (sep_pos > 0) {
7526
sep_pos--;
7527
if (tmp_str[sep_pos] == '/') {
7528
int is_script = 0, does_exist = 0;
7529
7530
tmp_str[sep_pos] = 0;
7531
if (tmp_str[0]) {
7532
is_script = extention_matches_script(conn, tmp_str);
7533
does_exist = mg_stat(conn, tmp_str, filestat);
7534
}
7535
7536
if (does_exist && is_script) {
7537
filename[sep_pos] = 0;
7538
memmove(filename + sep_pos + 2,
7539
filename + sep_pos + 1,
7540
strlen(filename + sep_pos + 1) + 1);
7541
conn->path_info = filename + sep_pos + 1;
7542
filename[sep_pos + 1] = '/';
7543
*is_script_resource = 1;
7544
*is_found = 1;
7545
break;
7546
}
7547
7548
if (allow_substitute_script_subresources) {
7549
if (substitute_index_file(
7550
conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
7551
7552
/* some intermediate directory has an index file */
7553
if (extention_matches_script(conn, tmp_str)) {
7554
7555
char *tmp_str2;
7556
7557
DEBUG_TRACE("Substitute script %s serving path %s",
7558
tmp_str,
7559
filename);
7560
7561
/* this index file is a script */
7562
tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
7563
conn->phys_ctx);
7564
mg_snprintf(conn,
7565
&truncated,
7566
filename,
7567
filename_buf_len,
7568
"%s//%s",
7569
tmp_str,
7570
tmp_str2);
7571
mg_free(tmp_str2);
7572
7573
if (truncated) {
7574
mg_free(tmp_str);
7575
goto interpret_cleanup;
7576
}
7577
sep_pos = strlen(tmp_str);
7578
filename[sep_pos] = 0;
7579
conn->path_info = filename + sep_pos + 1;
7580
*is_script_resource = 1;
7581
*is_found = 1;
7582
break;
7583
7584
} else {
7585
7586
DEBUG_TRACE("Substitute file %s serving path %s",
7587
tmp_str,
7588
filename);
7589
7590
/* non-script files will not have sub-resources */
7591
filename[sep_pos] = 0;
7592
conn->path_info = 0;
7593
*is_script_resource = 0;
7594
*is_found = 0;
7595
break;
7596
}
7597
}
7598
}
7599
7600
tmp_str[sep_pos] = '/';
7601
}
7602
}
7603
7604
mg_free(tmp_str);
7605
7606
#endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
7607
#endif /* !defined(NO_FILES) */
7608
return;
7609
7610
#if !defined(NO_FILES)
7611
/* Reset all outputs */
7612
interpret_cleanup:
7613
memset(filestat, 0, sizeof(*filestat));
7614
*filename = 0;
7615
*is_found = 0;
7616
*is_script_resource = 0;
7617
*is_websocket_request = 0;
7618
*is_put_or_delete_request = 0;
7619
#endif /* !defined(NO_FILES) */
7620
}
7621
7622
7623
/* Check whether full request is buffered. Return:
7624
* -1 if request or response is malformed
7625
* 0 if request or response is not yet fully buffered
7626
* >0 actual request length, including last \r\n\r\n */
7627
static int
7628
get_http_header_len(const char *buf, int buflen)
7629
{
7630
int i;
7631
for (i = 0; i < buflen; i++) {
7632
/* Do an unsigned comparison in some conditions below */
7633
const unsigned char c = ((const unsigned char *)buf)[i];
7634
7635
if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
7636
&& !isprint(c)) {
7637
/* abort scan as soon as one malformed character is found */
7638
return -1;
7639
}
7640
7641
if (i < buflen - 1) {
7642
if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
7643
/* Two newline, no carriage return - not standard compliant,
7644
* but
7645
* it
7646
* should be accepted */
7647
return i + 2;
7648
}
7649
}
7650
7651
if (i < buflen - 3) {
7652
if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
7653
&& (buf[i + 3] == '\n')) {
7654
/* Two \r\n - standard compliant */
7655
return i + 4;
7656
}
7657
}
7658
}
7659
7660
return 0;
7661
}
7662
7663
7664
#if !defined(NO_CACHING)
7665
/* Convert month to the month number. Return -1 on error, or month number */
7666
static int
7667
get_month_index(const char *s)
7668
{
7669
size_t i;
7670
7671
for (i = 0; i < ARRAY_SIZE(month_names); i++) {
7672
if (!strcmp(s, month_names[i])) {
7673
return (int)i;
7674
}
7675
}
7676
7677
return -1;
7678
}
7679
7680
7681
/* Parse UTC date-time string, and return the corresponding time_t value. */
7682
static time_t
7683
parse_date_string(const char *datetime)
7684
{
7685
char month_str[32] = {0};
7686
int second, minute, hour, day, month, year;
7687
time_t result = (time_t)0;
7688
struct tm tm;
7689
7690
if ((sscanf(datetime,
7691
"%d/%3s/%d %d:%d:%d",
7692
&day,
7693
month_str,
7694
&year,
7695
&hour,
7696
&minute,
7697
&second)
7698
== 6)
7699
|| (sscanf(datetime,
7700
"%d %3s %d %d:%d:%d",
7701
&day,
7702
month_str,
7703
&year,
7704
&hour,
7705
&minute,
7706
&second)
7707
== 6)
7708
|| (sscanf(datetime,
7709
"%*3s, %d %3s %d %d:%d:%d",
7710
&day,
7711
month_str,
7712
&year,
7713
&hour,
7714
&minute,
7715
&second)
7716
== 6)
7717
|| (sscanf(datetime,
7718
"%d-%3s-%d %d:%d:%d",
7719
&day,
7720
month_str,
7721
&year,
7722
&hour,
7723
&minute,
7724
&second)
7725
== 6)) {
7726
month = get_month_index(month_str);
7727
if ((month >= 0) && (year >= 1970)) {
7728
memset(&tm, 0, sizeof(tm));
7729
tm.tm_year = year - 1900;
7730
tm.tm_mon = month;
7731
tm.tm_mday = day;
7732
tm.tm_hour = hour;
7733
tm.tm_min = minute;
7734
tm.tm_sec = second;
7735
result = timegm(&tm);
7736
}
7737
}
7738
7739
return result;
7740
}
7741
#endif /* !NO_CACHING */
7742
7743
7744
/* Protect against directory disclosure attack by removing '..',
7745
* excessive '/' and '\' characters */
7746
static void
7747
remove_double_dots_and_double_slashes(char *s)
7748
{
7749
char *p = s;
7750
7751
while ((s[0] == '.') && (s[1] == '.')) {
7752
s++;
7753
}
7754
7755
while (*s != '\0') {
7756
*p++ = *s++;
7757
if ((s[-1] == '/') || (s[-1] == '\\')) {
7758
/* Skip all following slashes, backslashes and double-dots */
7759
while (s[0] != '\0') {
7760
if ((s[0] == '/') || (s[0] == '\\')) {
7761
s++;
7762
} else if ((s[0] == '.') && (s[1] == '.')) {
7763
s += 2;
7764
} else {
7765
break;
7766
}
7767
}
7768
}
7769
}
7770
*p = '\0';
7771
}
7772
7773
7774
static const struct {
7775
const char *extension;
7776
size_t ext_len;
7777
const char *mime_type;
7778
} builtin_mime_types[] = {
7779
/* IANA registered MIME types
7780
* (http://www.iana.org/assignments/media-types)
7781
* application types */
7782
{".doc", 4, "application/msword"},
7783
{".eps", 4, "application/postscript"},
7784
{".exe", 4, "application/octet-stream"},
7785
{".js", 3, "application/javascript"},
7786
{".json", 5, "application/json"},
7787
{".pdf", 4, "application/pdf"},
7788
{".ps", 3, "application/postscript"},
7789
{".rtf", 4, "application/rtf"},
7790
{".xhtml", 6, "application/xhtml+xml"},
7791
{".xsl", 4, "application/xml"},
7792
{".xslt", 5, "application/xml"},
7793
7794
/* fonts */
7795
{".ttf", 4, "application/font-sfnt"},
7796
{".cff", 4, "application/font-sfnt"},
7797
{".otf", 4, "application/font-sfnt"},
7798
{".aat", 4, "application/font-sfnt"},
7799
{".sil", 4, "application/font-sfnt"},
7800
{".pfr", 4, "application/font-tdpfr"},
7801
{".woff", 5, "application/font-woff"},
7802
7803
/* audio */
7804
{".mp3", 4, "audio/mpeg"},
7805
{".oga", 4, "audio/ogg"},
7806
{".ogg", 4, "audio/ogg"},
7807
7808
/* image */
7809
{".gif", 4, "image/gif"},
7810
{".ief", 4, "image/ief"},
7811
{".jpeg", 5, "image/jpeg"},
7812
{".jpg", 4, "image/jpeg"},
7813
{".jpm", 4, "image/jpm"},
7814
{".jpx", 4, "image/jpx"},
7815
{".png", 4, "image/png"},
7816
{".svg", 4, "image/svg+xml"},
7817
{".tif", 4, "image/tiff"},
7818
{".tiff", 5, "image/tiff"},
7819
7820
/* model */
7821
{".wrl", 4, "model/vrml"},
7822
7823
/* text */
7824
{".css", 4, "text/css"},
7825
{".csv", 4, "text/csv"},
7826
{".htm", 4, "text/html"},
7827
{".html", 5, "text/html"},
7828
{".sgm", 4, "text/sgml"},
7829
{".shtm", 5, "text/html"},
7830
{".shtml", 6, "text/html"},
7831
{".txt", 4, "text/plain"},
7832
{".xml", 4, "text/xml"},
7833
7834
/* video */
7835
{".mov", 4, "video/quicktime"},
7836
{".mp4", 4, "video/mp4"},
7837
{".mpeg", 5, "video/mpeg"},
7838
{".mpg", 4, "video/mpeg"},
7839
{".ogv", 4, "video/ogg"},
7840
{".qt", 3, "video/quicktime"},
7841
7842
/* not registered types
7843
* (http://reference.sitepoint.com/html/mime-types-full,
7844
* http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
7845
{".arj", 4, "application/x-arj-compressed"},
7846
{".gz", 3, "application/x-gunzip"},
7847
{".rar", 4, "application/x-arj-compressed"},
7848
{".swf", 4, "application/x-shockwave-flash"},
7849
{".tar", 4, "application/x-tar"},
7850
{".tgz", 4, "application/x-tar-gz"},
7851
{".torrent", 8, "application/x-bittorrent"},
7852
{".ppt", 4, "application/x-mspowerpoint"},
7853
{".xls", 4, "application/x-msexcel"},
7854
{".zip", 4, "application/x-zip-compressed"},
7855
{".aac",
7856
4,
7857
"audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
7858
{".aif", 4, "audio/x-aif"},
7859
{".m3u", 4, "audio/x-mpegurl"},
7860
{".mid", 4, "audio/x-midi"},
7861
{".ra", 3, "audio/x-pn-realaudio"},
7862
{".ram", 4, "audio/x-pn-realaudio"},
7863
{".wav", 4, "audio/x-wav"},
7864
{".bmp", 4, "image/bmp"},
7865
{".ico", 4, "image/x-icon"},
7866
{".pct", 4, "image/x-pct"},
7867
{".pict", 5, "image/pict"},
7868
{".rgb", 4, "image/x-rgb"},
7869
{".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
7870
{".asf", 4, "video/x-ms-asf"},
7871
{".avi", 4, "video/x-msvideo"},
7872
{".m4v", 4, "video/x-m4v"},
7873
{NULL, 0, NULL}};
7874
7875
7876
const char *
7877
mg_get_builtin_mime_type(const char *path)
7878
{
7879
const char *ext;
7880
size_t i, path_len;
7881
7882
path_len = strlen(path);
7883
7884
for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
7885
ext = path + (path_len - builtin_mime_types[i].ext_len);
7886
if ((path_len > builtin_mime_types[i].ext_len)
7887
&& (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
7888
return builtin_mime_types[i].mime_type;
7889
}
7890
}
7891
7892
return "text/plain";
7893
}
7894
7895
7896
/* Look at the "path" extension and figure what mime type it has.
7897
* Store mime type in the vector. */
7898
static void
7899
get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
7900
{
7901
struct vec ext_vec, mime_vec;
7902
const char *list, *ext;
7903
size_t path_len;
7904
7905
path_len = strlen(path);
7906
7907
if ((conn == NULL) || (vec == NULL)) {
7908
if (vec != NULL) {
7909
memset(vec, '\0', sizeof(struct vec));
7910
}
7911
return;
7912
}
7913
7914
/* Scan user-defined mime types first, in case user wants to
7915
* override default mime types. */
7916
list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
7917
while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
7918
/* ext now points to the path suffix */
7919
ext = path + path_len - ext_vec.len;
7920
if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
7921
*vec = mime_vec;
7922
return;
7923
}
7924
}
7925
7926
vec->ptr = mg_get_builtin_mime_type(path);
7927
vec->len = strlen(vec->ptr);
7928
}
7929
7930
7931
/* Stringify binary data. Output buffer must be twice as big as input,
7932
* because each byte takes 2 bytes in string representation */
7933
static void
7934
bin2str(char *to, const unsigned char *p, size_t len)
7935
{
7936
static const char *hex = "0123456789abcdef";
7937
7938
for (; len--; p++) {
7939
*to++ = hex[p[0] >> 4];
7940
*to++ = hex[p[0] & 0x0f];
7941
}
7942
*to = '\0';
7943
}
7944
7945
7946
/* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
7947
*/
7948
char *
7949
mg_md5(char buf[33], ...)
7950
{
7951
md5_byte_t hash[16];
7952
const char *p;
7953
va_list ap;
7954
md5_state_t ctx;
7955
7956
md5_init(&ctx);
7957
7958
va_start(ap, buf);
7959
while ((p = va_arg(ap, const char *)) != NULL) {
7960
md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
7961
}
7962
va_end(ap);
7963
7964
md5_finish(&ctx, hash);
7965
bin2str(buf, hash, sizeof(hash));
7966
return buf;
7967
}
7968
7969
7970
/* Check the user's password, return 1 if OK */
7971
static int
7972
check_password(const char *method,
7973
const char *ha1,
7974
const char *uri,
7975
const char *nonce,
7976
const char *nc,
7977
const char *cnonce,
7978
const char *qop,
7979
const char *response)
7980
{
7981
char ha2[32 + 1], expected_response[32 + 1];
7982
7983
/* Some of the parameters may be NULL */
7984
if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
7985
|| (qop == NULL) || (response == NULL)) {
7986
return 0;
7987
}
7988
7989
/* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
7990
if (strlen(response) != 32) {
7991
return 0;
7992
}
7993
7994
mg_md5(ha2, method, ":", uri, NULL);
7995
mg_md5(expected_response,
7996
ha1,
7997
":",
7998
nonce,
7999
":",
8000
nc,
8001
":",
8002
cnonce,
8003
":",
8004
qop,
8005
":",
8006
ha2,
8007
NULL);
8008
8009
return mg_strcasecmp(response, expected_response) == 0;
8010
}
8011
8012
8013
/* Use the global passwords file, if specified by auth_gpass option,
8014
* or search for .htpasswd in the requested directory. */
8015
static void
8016
open_auth_file(struct mg_connection *conn,
8017
const char *path,
8018
struct mg_file *filep)
8019
{
8020
if ((conn != NULL) && (conn->dom_ctx != NULL)) {
8021
char name[PATH_MAX];
8022
const char *p, *e,
8023
*gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
8024
int truncated;
8025
8026
if (gpass != NULL) {
8027
/* Use global passwords file */
8028
if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
8029
#if defined(DEBUG)
8030
/* Use mg_cry_internal here, since gpass has been configured. */
8031
mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
8032
#endif
8033
}
8034
/* Important: using local struct mg_file to test path for
8035
* is_directory flag. If filep is used, mg_stat() makes it
8036
* appear as if auth file was opened.
8037
* TODO(mid): Check if this is still required after rewriting
8038
* mg_stat */
8039
} else if (mg_stat(conn, path, &filep->stat)
8040
&& filep->stat.is_directory) {
8041
mg_snprintf(conn,
8042
&truncated,
8043
name,
8044
sizeof(name),
8045
"%s/%s",
8046
path,
8047
PASSWORDS_FILE_NAME);
8048
8049
if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8050
#if defined(DEBUG)
8051
/* Don't use mg_cry_internal here, but only a trace, since this
8052
* is
8053
* a typical case. It will occur for every directory
8054
* without a password file. */
8055
DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8056
#endif
8057
}
8058
} else {
8059
/* Try to find .htpasswd in requested directory. */
8060
for (p = path, e = p + strlen(p) - 1; e > p; e--) {
8061
if (e[0] == '/') {
8062
break;
8063
}
8064
}
8065
mg_snprintf(conn,
8066
&truncated,
8067
name,
8068
sizeof(name),
8069
"%.*s/%s",
8070
(int)(e - p),
8071
p,
8072
PASSWORDS_FILE_NAME);
8073
8074
if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
8075
#if defined(DEBUG)
8076
/* Don't use mg_cry_internal here, but only a trace, since this
8077
* is
8078
* a typical case. It will occur for every directory
8079
* without a password file. */
8080
DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
8081
#endif
8082
}
8083
}
8084
}
8085
}
8086
8087
8088
/* Parsed Authorization header */
8089
struct ah {
8090
char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
8091
};
8092
8093
8094
/* Return 1 on success. Always initializes the ah structure. */
8095
static int
8096
parse_auth_header(struct mg_connection *conn,
8097
char *buf,
8098
size_t buf_size,
8099
struct ah *ah)
8100
{
8101
char *name, *value, *s;
8102
const char *auth_header;
8103
uint64_t nonce;
8104
8105
if (!ah || !conn) {
8106
return 0;
8107
}
8108
8109
(void)memset(ah, 0, sizeof(*ah));
8110
if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
8111
|| mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
8112
return 0;
8113
}
8114
8115
/* Make modifiable copy of the auth header */
8116
(void)mg_strlcpy(buf, auth_header + 7, buf_size);
8117
s = buf;
8118
8119
/* Parse authorization header */
8120
for (;;) {
8121
/* Gobble initial spaces */
8122
while (isspace(*(unsigned char *)s)) {
8123
s++;
8124
}
8125
name = skip_quoted(&s, "=", " ", 0);
8126
/* Value is either quote-delimited, or ends at first comma or space.
8127
*/
8128
if (s[0] == '\"') {
8129
s++;
8130
value = skip_quoted(&s, "\"", " ", '\\');
8131
if (s[0] == ',') {
8132
s++;
8133
}
8134
} else {
8135
value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
8136
* spaces */
8137
}
8138
if (*name == '\0') {
8139
break;
8140
}
8141
8142
if (!strcmp(name, "username")) {
8143
ah->user = value;
8144
} else if (!strcmp(name, "cnonce")) {
8145
ah->cnonce = value;
8146
} else if (!strcmp(name, "response")) {
8147
ah->response = value;
8148
} else if (!strcmp(name, "uri")) {
8149
ah->uri = value;
8150
} else if (!strcmp(name, "qop")) {
8151
ah->qop = value;
8152
} else if (!strcmp(name, "nc")) {
8153
ah->nc = value;
8154
} else if (!strcmp(name, "nonce")) {
8155
ah->nonce = value;
8156
}
8157
}
8158
8159
#if !defined(NO_NONCE_CHECK)
8160
/* Read the nonce from the response. */
8161
if (ah->nonce == NULL) {
8162
return 0;
8163
}
8164
s = NULL;
8165
nonce = strtoull(ah->nonce, &s, 10);
8166
if ((s == NULL) || (*s != 0)) {
8167
return 0;
8168
}
8169
8170
/* Convert the nonce from the client to a number. */
8171
nonce ^= conn->dom_ctx->auth_nonce_mask;
8172
8173
/* The converted number corresponds to the time the nounce has been
8174
* created. This should not be earlier than the server start. */
8175
/* Server side nonce check is valuable in all situations but one:
8176
* if the server restarts frequently, but the client should not see
8177
* that, so the server should accept nonces from previous starts. */
8178
/* However, the reasonable default is to not accept a nonce from a
8179
* previous start, so if anyone changed the access rights between
8180
* two restarts, a new login is required. */
8181
if (nonce < (uint64_t)conn->phys_ctx->start_time) {
8182
/* nonce is from a previous start of the server and no longer valid
8183
* (replay attack?) */
8184
return 0;
8185
}
8186
/* Check if the nonce is too high, so it has not (yet) been used by the
8187
* server. */
8188
if (nonce >= ((uint64_t)conn->phys_ctx->start_time
8189
+ conn->dom_ctx->nonce_count)) {
8190
return 0;
8191
}
8192
#else
8193
(void)nonce;
8194
#endif
8195
8196
/* CGI needs it as REMOTE_USER */
8197
if (ah->user != NULL) {
8198
conn->request_info.remote_user =
8199
mg_strdup_ctx(ah->user, conn->phys_ctx);
8200
} else {
8201
return 0;
8202
}
8203
8204
return 1;
8205
}
8206
8207
8208
static const char *
8209
mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
8210
{
8211
#if defined(MG_USE_OPEN_FILE)
8212
const char *eof;
8213
size_t len;
8214
const char *memend;
8215
#else
8216
(void)p; /* parameter is unused */
8217
#endif
8218
8219
if (!filep) {
8220
return NULL;
8221
}
8222
8223
#if defined(MG_USE_OPEN_FILE)
8224
if ((filep->access.membuf != NULL) && (*p != NULL)) {
8225
memend = (const char *)&filep->access.membuf[filep->stat.size];
8226
/* Search for \n from p till the end of stream */
8227
eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
8228
if (eof != NULL) {
8229
eof += 1; /* Include \n */
8230
} else {
8231
eof = memend; /* Copy remaining data */
8232
}
8233
len =
8234
((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
8235
memcpy(buf, *p, len);
8236
buf[len] = '\0';
8237
*p += len;
8238
return len ? eof : NULL;
8239
} else /* filep->access.fp block below */
8240
#endif
8241
if (filep->access.fp != NULL) {
8242
return fgets(buf, (int)size, filep->access.fp);
8243
} else {
8244
return NULL;
8245
}
8246
}
8247
8248
/* Define the initial recursion depth for procesesing htpasswd files that
8249
* include other htpasswd
8250
* (or even the same) files. It is not difficult to provide a file or files
8251
* s.t. they force civetweb
8252
* to infinitely recurse and then crash.
8253
*/
8254
#define INITIAL_DEPTH 9
8255
#if INITIAL_DEPTH <= 0
8256
#error Bad INITIAL_DEPTH for recursion, set to at least 1
8257
#endif
8258
8259
struct read_auth_file_struct {
8260
struct mg_connection *conn;
8261
struct ah ah;
8262
const char *domain;
8263
char buf[256 + 256 + 40];
8264
const char *f_user;
8265
const char *f_domain;
8266
const char *f_ha1;
8267
};
8268
8269
8270
static int
8271
read_auth_file(struct mg_file *filep,
8272
struct read_auth_file_struct *workdata,
8273
int depth)
8274
{
8275
char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
8276
int is_authorized = 0;
8277
struct mg_file fp;
8278
size_t l;
8279
8280
if (!filep || !workdata || (0 == depth)) {
8281
return 0;
8282
}
8283
8284
/* Loop over passwords file */
8285
#if defined(MG_USE_OPEN_FILE)
8286
p = (char *)filep->access.membuf;
8287
#endif
8288
while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
8289
l = strlen(workdata->buf);
8290
while (l > 0) {
8291
if (isspace(workdata->buf[l - 1])
8292
|| iscntrl(workdata->buf[l - 1])) {
8293
l--;
8294
workdata->buf[l] = 0;
8295
} else
8296
break;
8297
}
8298
if (l < 1) {
8299
continue;
8300
}
8301
8302
workdata->f_user = workdata->buf;
8303
8304
if (workdata->f_user[0] == ':') {
8305
/* user names may not contain a ':' and may not be empty,
8306
* so lines starting with ':' may be used for a special purpose
8307
*/
8308
if (workdata->f_user[1] == '#') {
8309
/* :# is a comment */
8310
continue;
8311
} else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
8312
if (mg_fopen(workdata->conn,
8313
workdata->f_user + 9,
8314
MG_FOPEN_MODE_READ,
8315
&fp)) {
8316
is_authorized = read_auth_file(&fp, workdata, depth - 1);
8317
(void)mg_fclose(
8318
&fp.access); /* ignore error on read only file */
8319
8320
/* No need to continue processing files once we have a
8321
* match, since nothing will reset it back
8322
* to 0.
8323
*/
8324
if (is_authorized) {
8325
return is_authorized;
8326
}
8327
} else {
8328
mg_cry_internal(workdata->conn,
8329
"%s: cannot open authorization file: %s",
8330
__func__,
8331
workdata->buf);
8332
}
8333
continue;
8334
}
8335
/* everything is invalid for the moment (might change in the
8336
* future) */
8337
mg_cry_internal(workdata->conn,
8338
"%s: syntax error in authorization file: %s",
8339
__func__,
8340
workdata->buf);
8341
continue;
8342
}
8343
8344
workdata->f_domain = strchr(workdata->f_user, ':');
8345
if (workdata->f_domain == NULL) {
8346
mg_cry_internal(workdata->conn,
8347
"%s: syntax error in authorization file: %s",
8348
__func__,
8349
workdata->buf);
8350
continue;
8351
}
8352
*(char *)(workdata->f_domain) = 0;
8353
(workdata->f_domain)++;
8354
8355
workdata->f_ha1 = strchr(workdata->f_domain, ':');
8356
if (workdata->f_ha1 == NULL) {
8357
mg_cry_internal(workdata->conn,
8358
"%s: syntax error in authorization file: %s",
8359
__func__,
8360
workdata->buf);
8361
continue;
8362
}
8363
*(char *)(workdata->f_ha1) = 0;
8364
(workdata->f_ha1)++;
8365
8366
if (!strcmp(workdata->ah.user, workdata->f_user)
8367
&& !strcmp(workdata->domain, workdata->f_domain)) {
8368
return check_password(workdata->conn->request_info.request_method,
8369
workdata->f_ha1,
8370
workdata->ah.uri,
8371
workdata->ah.nonce,
8372
workdata->ah.nc,
8373
workdata->ah.cnonce,
8374
workdata->ah.qop,
8375
workdata->ah.response);
8376
}
8377
}
8378
8379
return is_authorized;
8380
}
8381
8382
8383
/* Authorize against the opened passwords file. Return 1 if authorized. */
8384
static int
8385
authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
8386
{
8387
struct read_auth_file_struct workdata;
8388
char buf[MG_BUF_LEN];
8389
8390
if (!conn || !conn->dom_ctx) {
8391
return 0;
8392
}
8393
8394
memset(&workdata, 0, sizeof(workdata));
8395
workdata.conn = conn;
8396
8397
if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
8398
return 0;
8399
}
8400
8401
if (realm) {
8402
workdata.domain = realm;
8403
} else {
8404
workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
8405
}
8406
8407
return read_auth_file(filep, &workdata, INITIAL_DEPTH);
8408
}
8409
8410
8411
/* Public function to check http digest authentication header */
8412
int
8413
mg_check_digest_access_authentication(struct mg_connection *conn,
8414
const char *realm,
8415
const char *filename)
8416
{
8417
struct mg_file file = STRUCT_FILE_INITIALIZER;
8418
int auth;
8419
8420
if (!conn || !filename) {
8421
return -1;
8422
}
8423
if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
8424
return -2;
8425
}
8426
8427
auth = authorize(conn, &file, realm);
8428
8429
mg_fclose(&file.access);
8430
8431
return auth;
8432
}
8433
8434
8435
/* Return 1 if request is authorised, 0 otherwise. */
8436
static int
8437
check_authorization(struct mg_connection *conn, const char *path)
8438
{
8439
char fname[PATH_MAX];
8440
struct vec uri_vec, filename_vec;
8441
const char *list;
8442
struct mg_file file = STRUCT_FILE_INITIALIZER;
8443
int authorized = 1, truncated;
8444
8445
if (!conn || !conn->dom_ctx) {
8446
return 0;
8447
}
8448
8449
list = conn->dom_ctx->config[PROTECT_URI];
8450
while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
8451
if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
8452
mg_snprintf(conn,
8453
&truncated,
8454
fname,
8455
sizeof(fname),
8456
"%.*s",
8457
(int)filename_vec.len,
8458
filename_vec.ptr);
8459
8460
if (truncated
8461
|| !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
8462
mg_cry_internal(conn,
8463
"%s: cannot open %s: %s",
8464
__func__,
8465
fname,
8466
strerror(errno));
8467
}
8468
break;
8469
}
8470
}
8471
8472
if (!is_file_opened(&file.access)) {
8473
open_auth_file(conn, path, &file);
8474
}
8475
8476
if (is_file_opened(&file.access)) {
8477
authorized = authorize(conn, &file, NULL);
8478
(void)mg_fclose(&file.access); /* ignore error on read only file */
8479
}
8480
8481
return authorized;
8482
}
8483
8484
8485
/* Internal function. Assumes conn is valid */
8486
static void
8487
send_authorization_request(struct mg_connection *conn, const char *realm)
8488
{
8489
char date[64];
8490
time_t curtime = time(NULL);
8491
uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
8492
8493
if (!realm) {
8494
realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
8495
}
8496
8497
(void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
8498
nonce += conn->dom_ctx->nonce_count;
8499
++conn->dom_ctx->nonce_count;
8500
(void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
8501
8502
nonce ^= conn->dom_ctx->auth_nonce_mask;
8503
conn->status_code = 401;
8504
conn->must_close = 1;
8505
8506
gmt_time_string(date, sizeof(date), &curtime);
8507
8508
mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
8509
send_no_cache_header(conn);
8510
send_additional_header(conn);
8511
mg_printf(conn,
8512
"Date: %s\r\n"
8513
"Connection: %s\r\n"
8514
"Content-Length: 0\r\n"
8515
"WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
8516
"nonce=\"%" UINT64_FMT "\"\r\n\r\n",
8517
date,
8518
suggest_connection_header(conn),
8519
realm,
8520
nonce);
8521
}
8522
8523
8524
/* Interface function. Parameters are provided by the user, so do
8525
* at least some basic checks.
8526
*/
8527
int
8528
mg_send_digest_access_authentication_request(struct mg_connection *conn,
8529
const char *realm)
8530
{
8531
if (conn && conn->dom_ctx) {
8532
send_authorization_request(conn, realm);
8533
return 0;
8534
}
8535
return -1;
8536
}
8537
8538
8539
#if !defined(NO_FILES)
8540
static int
8541
is_authorized_for_put(struct mg_connection *conn)
8542
{
8543
if (conn) {
8544
struct mg_file file = STRUCT_FILE_INITIALIZER;
8545
const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
8546
int ret = 0;
8547
8548
if (passfile != NULL
8549
&& mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
8550
ret = authorize(conn, &file, NULL);
8551
(void)mg_fclose(&file.access); /* ignore error on read only file */
8552
}
8553
8554
return ret;
8555
}
8556
return 0;
8557
}
8558
#endif
8559
8560
8561
int
8562
mg_modify_passwords_file(const char *fname,
8563
const char *domain,
8564
const char *user,
8565
const char *pass)
8566
{
8567
int found, i;
8568
char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
8569
FILE *fp, *fp2;
8570
8571
found = 0;
8572
fp = fp2 = NULL;
8573
8574
/* Regard empty password as no password - remove user record. */
8575
if ((pass != NULL) && (pass[0] == '\0')) {
8576
pass = NULL;
8577
}
8578
8579
/* Other arguments must not be empty */
8580
if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
8581
return 0;
8582
}
8583
8584
/* Using the given file format, user name and domain must not contain
8585
* ':'
8586
*/
8587
if (strchr(user, ':') != NULL) {
8588
return 0;
8589
}
8590
if (strchr(domain, ':') != NULL) {
8591
return 0;
8592
}
8593
8594
/* Do not allow control characters like newline in user name and domain.
8595
* Do not allow excessively long names either. */
8596
for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
8597
if (iscntrl(user[i])) {
8598
return 0;
8599
}
8600
}
8601
if (user[i]) {
8602
return 0;
8603
}
8604
for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
8605
if (iscntrl(domain[i])) {
8606
return 0;
8607
}
8608
}
8609
if (domain[i]) {
8610
return 0;
8611
}
8612
8613
/* The maximum length of the path to the password file is limited */
8614
if ((strlen(fname) + 4) >= PATH_MAX) {
8615
return 0;
8616
}
8617
8618
/* Create a temporary file name. Length has been checked before. */
8619
strcpy(tmp, fname);
8620
strcat(tmp, ".tmp");
8621
8622
/* Create the file if does not exist */
8623
/* Use of fopen here is OK, since fname is only ASCII */
8624
if ((fp = fopen(fname, "a+")) != NULL) {
8625
(void)fclose(fp);
8626
}
8627
8628
/* Open the given file and temporary file */
8629
if ((fp = fopen(fname, "r")) == NULL) {
8630
return 0;
8631
} else if ((fp2 = fopen(tmp, "w+")) == NULL) {
8632
fclose(fp);
8633
return 0;
8634
}
8635
8636
/* Copy the stuff to temporary file */
8637
while (fgets(line, sizeof(line), fp) != NULL) {
8638
if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
8639
continue;
8640
}
8641
u[255] = 0;
8642
d[255] = 0;
8643
8644
if (!strcmp(u, user) && !strcmp(d, domain)) {
8645
found++;
8646
if (pass != NULL) {
8647
mg_md5(ha1, user, ":", domain, ":", pass, NULL);
8648
fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8649
}
8650
} else {
8651
fprintf(fp2, "%s", line);
8652
}
8653
}
8654
8655
/* If new user, just add it */
8656
if (!found && (pass != NULL)) {
8657
mg_md5(ha1, user, ":", domain, ":", pass, NULL);
8658
fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
8659
}
8660
8661
/* Close files */
8662
fclose(fp);
8663
fclose(fp2);
8664
8665
/* Put the temp file in place of real file */
8666
IGNORE_UNUSED_RESULT(remove(fname));
8667
IGNORE_UNUSED_RESULT(rename(tmp, fname));
8668
8669
return 1;
8670
}
8671
8672
8673
static int
8674
is_valid_port(unsigned long port)
8675
{
8676
return (port <= 0xffff);
8677
}
8678
8679
8680
static int
8681
mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
8682
{
8683
struct addrinfo hints, *res, *ressave;
8684
int func_ret = 0;
8685
int gai_ret;
8686
8687
memset(&hints, 0, sizeof(struct addrinfo));
8688
hints.ai_family = af;
8689
8690
gai_ret = getaddrinfo(src, NULL, &hints, &res);
8691
if (gai_ret != 0) {
8692
/* gai_strerror could be used to convert gai_ret to a string */
8693
/* POSIX return values: see
8694
* http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
8695
*/
8696
/* Windows return values: see
8697
* https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
8698
*/
8699
return 0;
8700
}
8701
8702
ressave = res;
8703
8704
while (res) {
8705
if (dstlen >= (size_t)res->ai_addrlen) {
8706
memcpy(dst, res->ai_addr, res->ai_addrlen);
8707
func_ret = 1;
8708
}
8709
res = res->ai_next;
8710
}
8711
8712
freeaddrinfo(ressave);
8713
return func_ret;
8714
}
8715
8716
8717
static int
8718
connect_socket(struct mg_context *ctx /* may be NULL */,
8719
const char *host,
8720
int port,
8721
int use_ssl,
8722
char *ebuf,
8723
size_t ebuf_len,
8724
SOCKET *sock /* output: socket, must not be NULL */,
8725
union usa *sa /* output: socket address, must not be NULL */
8726
)
8727
{
8728
int ip_ver = 0;
8729
int conn_ret = -1;
8730
int ret;
8731
*sock = INVALID_SOCKET;
8732
memset(sa, 0, sizeof(*sa));
8733
8734
if (ebuf_len > 0) {
8735
*ebuf = 0;
8736
}
8737
8738
if (host == NULL) {
8739
mg_snprintf(NULL,
8740
NULL, /* No truncation check for ebuf */
8741
ebuf,
8742
ebuf_len,
8743
"%s",
8744
"NULL host");
8745
return 0;
8746
}
8747
8748
if ((port <= 0) || !is_valid_port((unsigned)port)) {
8749
mg_snprintf(NULL,
8750
NULL, /* No truncation check for ebuf */
8751
ebuf,
8752
ebuf_len,
8753
"%s",
8754
"invalid port");
8755
return 0;
8756
}
8757
8758
#if !defined(NO_SSL)
8759
#if !defined(NO_SSL_DL)
8760
#if defined(OPENSSL_API_1_1)
8761
if (use_ssl && (TLS_client_method == NULL)) {
8762
mg_snprintf(NULL,
8763
NULL, /* No truncation check for ebuf */
8764
ebuf,
8765
ebuf_len,
8766
"%s",
8767
"SSL is not initialized");
8768
return 0;
8769
}
8770
#else
8771
if (use_ssl && (SSLv23_client_method == NULL)) {
8772
mg_snprintf(NULL,
8773
NULL, /* No truncation check for ebuf */
8774
ebuf,
8775
ebuf_len,
8776
"%s",
8777
"SSL is not initialized");
8778
return 0;
8779
}
8780
8781
#endif /* OPENSSL_API_1_1 */
8782
#else
8783
(void)use_ssl;
8784
#endif /* NO_SSL_DL */
8785
#else
8786
(void)use_ssl;
8787
#endif /* !defined(NO_SSL) */
8788
8789
if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
8790
sa->sin.sin_family = AF_INET;
8791
sa->sin.sin_port = htons((uint16_t)port);
8792
ip_ver = 4;
8793
#if defined(USE_IPV6)
8794
} else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
8795
sa->sin6.sin6_family = AF_INET6;
8796
sa->sin6.sin6_port = htons((uint16_t)port);
8797
ip_ver = 6;
8798
} else if (host[0] == '[') {
8799
/* While getaddrinfo on Windows will work with [::1],
8800
* getaddrinfo on Linux only works with ::1 (without []). */
8801
size_t l = strlen(host + 1);
8802
char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
8803
if (h) {
8804
h[l - 1] = 0;
8805
if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
8806
sa->sin6.sin6_family = AF_INET6;
8807
sa->sin6.sin6_port = htons((uint16_t)port);
8808
ip_ver = 6;
8809
}
8810
mg_free(h);
8811
}
8812
#endif
8813
}
8814
8815
if (ip_ver == 0) {
8816
mg_snprintf(NULL,
8817
NULL, /* No truncation check for ebuf */
8818
ebuf,
8819
ebuf_len,
8820
"%s",
8821
"host not found");
8822
return 0;
8823
}
8824
8825
if (ip_ver == 4) {
8826
*sock = socket(PF_INET, SOCK_STREAM, 0);
8827
}
8828
#if defined(USE_IPV6)
8829
else if (ip_ver == 6) {
8830
*sock = socket(PF_INET6, SOCK_STREAM, 0);
8831
}
8832
#endif
8833
8834
if (*sock == INVALID_SOCKET) {
8835
mg_snprintf(NULL,
8836
NULL, /* No truncation check for ebuf */
8837
ebuf,
8838
ebuf_len,
8839
"socket(): %s",
8840
strerror(ERRNO));
8841
return 0;
8842
}
8843
8844
if (0 != set_non_blocking_mode(*sock)) {
8845
mg_snprintf(NULL,
8846
NULL, /* No truncation check for ebuf */
8847
ebuf,
8848
ebuf_len,
8849
"Cannot set socket to non-blocking: %s",
8850
strerror(ERRNO));
8851
closesocket(*sock);
8852
*sock = INVALID_SOCKET;
8853
return 0;
8854
}
8855
8856
set_close_on_exec(*sock, fc(ctx));
8857
8858
if (ip_ver == 4) {
8859
/* connected with IPv4 */
8860
conn_ret = connect(*sock,
8861
(struct sockaddr *)((void *)&sa->sin),
8862
sizeof(sa->sin));
8863
}
8864
#if defined(USE_IPV6)
8865
else if (ip_ver == 6) {
8866
/* connected with IPv6 */
8867
conn_ret = connect(*sock,
8868
(struct sockaddr *)((void *)&sa->sin6),
8869
sizeof(sa->sin6));
8870
}
8871
#endif
8872
8873
#if defined(_WIN32)
8874
if (conn_ret != 0) {
8875
DWORD err = WSAGetLastError(); /* could return WSAEWOULDBLOCK */
8876
conn_ret = (int)err;
8877
#if !defined(EINPROGRESS)
8878
#define EINPROGRESS (WSAEWOULDBLOCK) /* Winsock equivalent */
8879
#endif /* if !defined(EINPROGRESS) */
8880
}
8881
#endif
8882
8883
if ((conn_ret != 0) && (conn_ret != EINPROGRESS)) {
8884
/* Data for getsockopt */
8885
int sockerr = -1;
8886
void *psockerr = &sockerr;
8887
8888
#if defined(_WIN32)
8889
int len = (int)sizeof(sockerr);
8890
#else
8891
socklen_t len = (socklen_t)sizeof(sockerr);
8892
#endif
8893
8894
/* Data for poll */
8895
struct pollfd pfd[1];
8896
int pollres;
8897
int ms_wait = 10000; /* 10 second timeout */
8898
8899
/* For a non-blocking socket, the connect sequence is:
8900
* 1) call connect (will not block)
8901
* 2) wait until the socket is ready for writing (select or poll)
8902
* 3) check connection state with getsockopt
8903
*/
8904
pfd[0].fd = *sock;
8905
pfd[0].events = POLLOUT;
8906
pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
8907
8908
if (pollres != 1) {
8909
/* Not connected */
8910
mg_snprintf(NULL,
8911
NULL, /* No truncation check for ebuf */
8912
ebuf,
8913
ebuf_len,
8914
"connect(%s:%d): timeout",
8915
host,
8916
port);
8917
closesocket(*sock);
8918
*sock = INVALID_SOCKET;
8919
return 0;
8920
}
8921
8922
#if defined(_WIN32)
8923
ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
8924
#else
8925
ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
8926
#endif
8927
8928
if ((ret != 0) || (sockerr != 0)) {
8929
/* Not connected */
8930
mg_snprintf(NULL,
8931
NULL, /* No truncation check for ebuf */
8932
ebuf,
8933
ebuf_len,
8934
"connect(%s:%d): error %s",
8935
host,
8936
port,
8937
strerror(sockerr));
8938
closesocket(*sock);
8939
*sock = INVALID_SOCKET;
8940
return 0;
8941
}
8942
}
8943
8944
return 1;
8945
}
8946
8947
8948
int
8949
mg_url_encode(const char *src, char *dst, size_t dst_len)
8950
{
8951
static const char *dont_escape = "._-$,;~()";
8952
static const char *hex = "0123456789abcdef";
8953
char *pos = dst;
8954
const char *end = dst + dst_len - 1;
8955
8956
for (; ((*src != '\0') && (pos < end)); src++, pos++) {
8957
if (isalnum(*(const unsigned char *)src)
8958
|| (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
8959
*pos = *src;
8960
} else if (pos + 2 < end) {
8961
pos[0] = '%';
8962
pos[1] = hex[(*(const unsigned char *)src) >> 4];
8963
pos[2] = hex[(*(const unsigned char *)src) & 0xf];
8964
pos += 2;
8965
} else {
8966
break;
8967
}
8968
}
8969
8970
*pos = '\0';
8971
return (*src == '\0') ? (int)(pos - dst) : -1;
8972
}
8973
8974
/* Return 0 on success, non-zero if an error occurs. */
8975
8976
static int
8977
print_dir_entry(struct de *de)
8978
{
8979
size_t hrefsize;
8980
char *href;
8981
char size[64], mod[64];
8982
#if defined(REENTRANT_TIME)
8983
struct tm _tm;
8984
struct tm *tm = &_tm;
8985
#else
8986
struct tm *tm;
8987
#endif
8988
8989
hrefsize = PATH_MAX * 3; /* worst case */
8990
href = (char *)mg_malloc(hrefsize);
8991
if (href == NULL) {
8992
return -1;
8993
}
8994
if (de->file.is_directory) {
8995
mg_snprintf(de->conn,
8996
NULL, /* Buffer is big enough */
8997
size,
8998
sizeof(size),
8999
"%s",
9000
"[DIRECTORY]");
9001
} else {
9002
/* We use (signed) cast below because MSVC 6 compiler cannot
9003
* convert unsigned __int64 to double. Sigh. */
9004
if (de->file.size < 1024) {
9005
mg_snprintf(de->conn,
9006
NULL, /* Buffer is big enough */
9007
size,
9008
sizeof(size),
9009
"%d",
9010
(int)de->file.size);
9011
} else if (de->file.size < 0x100000) {
9012
mg_snprintf(de->conn,
9013
NULL, /* Buffer is big enough */
9014
size,
9015
sizeof(size),
9016
"%.1fk",
9017
(double)de->file.size / 1024.0);
9018
} else if (de->file.size < 0x40000000) {
9019
mg_snprintf(de->conn,
9020
NULL, /* Buffer is big enough */
9021
size,
9022
sizeof(size),
9023
"%.1fM",
9024
(double)de->file.size / 1048576);
9025
} else {
9026
mg_snprintf(de->conn,
9027
NULL, /* Buffer is big enough */
9028
size,
9029
sizeof(size),
9030
"%.1fG",
9031
(double)de->file.size / 1073741824);
9032
}
9033
}
9034
9035
/* Note: mg_snprintf will not cause a buffer overflow above.
9036
* So, string truncation checks are not required here. */
9037
9038
#if defined(REENTRANT_TIME)
9039
localtime_r(&de->file.last_modified, tm);
9040
#else
9041
tm = localtime(&de->file.last_modified);
9042
#endif
9043
if (tm != NULL) {
9044
strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
9045
} else {
9046
mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
9047
mod[sizeof(mod) - 1] = '\0';
9048
}
9049
mg_url_encode(de->file_name, href, hrefsize);
9050
mg_printf(de->conn,
9051
"<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
9052
"<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
9053
de->conn->request_info.local_uri,
9054
href,
9055
de->file.is_directory ? "/" : "",
9056
de->file_name,
9057
de->file.is_directory ? "/" : "",
9058
mod,
9059
size);
9060
mg_free(href);
9061
return 0;
9062
}
9063
9064
9065
/* This function is called from send_directory() and used for
9066
* sorting directory entries by size, or name, or modification time.
9067
* On windows, __cdecl specification is needed in case if project is built
9068
* with __stdcall convention. qsort always requires __cdels callback. */
9069
static int WINCDECL
9070
compare_dir_entries(const void *p1, const void *p2)
9071
{
9072
if (p1 && p2) {
9073
const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
9074
const char *query_string = a->conn->request_info.query_string;
9075
int cmp_result = 0;
9076
9077
if (query_string == NULL) {
9078
query_string = "na";
9079
}
9080
9081
if (a->file.is_directory && !b->file.is_directory) {
9082
return -1; /* Always put directories on top */
9083
} else if (!a->file.is_directory && b->file.is_directory) {
9084
return 1; /* Always put directories on top */
9085
} else if (*query_string == 'n') {
9086
cmp_result = strcmp(a->file_name, b->file_name);
9087
} else if (*query_string == 's') {
9088
cmp_result = (a->file.size == b->file.size)
9089
? 0
9090
: ((a->file.size > b->file.size) ? 1 : -1);
9091
} else if (*query_string == 'd') {
9092
cmp_result =
9093
(a->file.last_modified == b->file.last_modified)
9094
? 0
9095
: ((a->file.last_modified > b->file.last_modified) ? 1
9096
: -1);
9097
}
9098
9099
return (query_string[1] == 'd') ? -cmp_result : cmp_result;
9100
}
9101
return 0;
9102
}
9103
9104
9105
static int
9106
must_hide_file(struct mg_connection *conn, const char *path)
9107
{
9108
if (conn && conn->dom_ctx) {
9109
const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
9110
const char *pattern = conn->dom_ctx->config[HIDE_FILES];
9111
return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
9112
|| ((pattern != NULL)
9113
&& (match_prefix(pattern, strlen(pattern), path) > 0));
9114
}
9115
return 0;
9116
}
9117
9118
9119
static int
9120
scan_directory(struct mg_connection *conn,
9121
const char *dir,
9122
void *data,
9123
int (*cb)(struct de *, void *))
9124
{
9125
char path[PATH_MAX];
9126
struct dirent *dp;
9127
DIR *dirp;
9128
struct de de;
9129
int truncated;
9130
9131
if ((dirp = mg_opendir(conn, dir)) == NULL) {
9132
return 0;
9133
} else {
9134
de.conn = conn;
9135
9136
while ((dp = mg_readdir(dirp)) != NULL) {
9137
/* Do not show current dir and hidden files */
9138
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
9139
|| must_hide_file(conn, dp->d_name)) {
9140
continue;
9141
}
9142
9143
mg_snprintf(
9144
conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9145
9146
/* If we don't memset stat structure to zero, mtime will have
9147
* garbage and strftime() will segfault later on in
9148
* print_dir_entry(). memset is required only if mg_stat()
9149
* fails. For more details, see
9150
* http://code.google.com/p/mongoose/issues/detail?id=79 */
9151
memset(&de.file, 0, sizeof(de.file));
9152
9153
if (truncated) {
9154
/* If the path is not complete, skip processing. */
9155
continue;
9156
}
9157
9158
if (!mg_stat(conn, path, &de.file)) {
9159
mg_cry_internal(conn,
9160
"%s: mg_stat(%s) failed: %s",
9161
__func__,
9162
path,
9163
strerror(ERRNO));
9164
}
9165
de.file_name = dp->d_name;
9166
cb(&de, data);
9167
}
9168
(void)mg_closedir(dirp);
9169
}
9170
return 1;
9171
}
9172
9173
9174
#if !defined(NO_FILES)
9175
static int
9176
remove_directory(struct mg_connection *conn, const char *dir)
9177
{
9178
char path[PATH_MAX];
9179
struct dirent *dp;
9180
DIR *dirp;
9181
struct de de;
9182
int truncated;
9183
int ok = 1;
9184
9185
if ((dirp = mg_opendir(conn, dir)) == NULL) {
9186
return 0;
9187
} else {
9188
de.conn = conn;
9189
9190
while ((dp = mg_readdir(dirp)) != NULL) {
9191
/* Do not show current dir (but show hidden files as they will
9192
* also be removed) */
9193
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
9194
continue;
9195
}
9196
9197
mg_snprintf(
9198
conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
9199
9200
/* If we don't memset stat structure to zero, mtime will have
9201
* garbage and strftime() will segfault later on in
9202
* print_dir_entry(). memset is required only if mg_stat()
9203
* fails. For more details, see
9204
* http://code.google.com/p/mongoose/issues/detail?id=79 */
9205
memset(&de.file, 0, sizeof(de.file));
9206
9207
if (truncated) {
9208
/* Do not delete anything shorter */
9209
ok = 0;
9210
continue;
9211
}
9212
9213
if (!mg_stat(conn, path, &de.file)) {
9214
mg_cry_internal(conn,
9215
"%s: mg_stat(%s) failed: %s",
9216
__func__,
9217
path,
9218
strerror(ERRNO));
9219
ok = 0;
9220
}
9221
9222
if (de.file.is_directory) {
9223
if (remove_directory(conn, path) == 0) {
9224
ok = 0;
9225
}
9226
} else {
9227
/* This will fail file is the file is in memory */
9228
if (mg_remove(conn, path) == 0) {
9229
ok = 0;
9230
}
9231
}
9232
}
9233
(void)mg_closedir(dirp);
9234
9235
IGNORE_UNUSED_RESULT(rmdir(dir));
9236
}
9237
9238
return ok;
9239
}
9240
#endif
9241
9242
9243
struct dir_scan_data {
9244
struct de *entries;
9245
unsigned int num_entries;
9246
unsigned int arr_size;
9247
};
9248
9249
9250
/* Behaves like realloc(), but frees original pointer on failure */
9251
static void *
9252
realloc2(void *ptr, size_t size)
9253
{
9254
void *new_ptr = mg_realloc(ptr, size);
9255
if (new_ptr == NULL) {
9256
mg_free(ptr);
9257
}
9258
return new_ptr;
9259
}
9260
9261
9262
static int
9263
dir_scan_callback(struct de *de, void *data)
9264
{
9265
struct dir_scan_data *dsd = (struct dir_scan_data *)data;
9266
9267
if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
9268
dsd->arr_size *= 2;
9269
dsd->entries =
9270
(struct de *)realloc2(dsd->entries,
9271
dsd->arr_size * sizeof(dsd->entries[0]));
9272
}
9273
if (dsd->entries == NULL) {
9274
/* TODO(lsm, low): propagate an error to the caller */
9275
dsd->num_entries = 0;
9276
} else {
9277
dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
9278
dsd->entries[dsd->num_entries].file = de->file;
9279
dsd->entries[dsd->num_entries].conn = de->conn;
9280
dsd->num_entries++;
9281
}
9282
9283
return 0;
9284
}
9285
9286
9287
static void
9288
handle_directory_request(struct mg_connection *conn, const char *dir)
9289
{
9290
unsigned int i;
9291
int sort_direction;
9292
struct dir_scan_data data = {NULL, 0, 128};
9293
char date[64];
9294
time_t curtime = time(NULL);
9295
9296
if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
9297
mg_send_http_error(conn,
9298
500,
9299
"Error: Cannot open directory\nopendir(%s): %s",
9300
dir,
9301
strerror(ERRNO));
9302
return;
9303
}
9304
9305
gmt_time_string(date, sizeof(date), &curtime);
9306
9307
if (!conn) {
9308
return;
9309
}
9310
9311
sort_direction = ((conn->request_info.query_string != NULL)
9312
&& (conn->request_info.query_string[1] == 'd'))
9313
? 'a'
9314
: 'd';
9315
9316
conn->must_close = 1;
9317
mg_printf(conn, "HTTP/1.1 200 OK\r\n");
9318
send_static_cache_header(conn);
9319
send_additional_header(conn);
9320
mg_printf(conn,
9321
"Date: %s\r\n"
9322
"Connection: close\r\n"
9323
"Content-Type: text/html; charset=utf-8\r\n\r\n",
9324
date);
9325
mg_printf(conn,
9326
"<html><head><title>Index of %s</title>"
9327
"<style>th {text-align: left;}</style></head>"
9328
"<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
9329
"<tr><th><a href=\"?n%c\">Name</a></th>"
9330
"<th><a href=\"?d%c\">Modified</a></th>"
9331
"<th><a href=\"?s%c\">Size</a></th></tr>"
9332
"<tr><td colspan=\"3\"><hr></td></tr>",
9333
conn->request_info.local_uri,
9334
conn->request_info.local_uri,
9335
sort_direction,
9336
sort_direction,
9337
sort_direction);
9338
9339
/* Print first entry - link to a parent directory */
9340
mg_printf(conn,
9341
"<tr><td><a href=\"%s%s\">%s</a></td>"
9342
"<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
9343
conn->request_info.local_uri,
9344
"..",
9345
"Parent directory",
9346
"-",
9347
"-");
9348
9349
/* Sort and print directory entries */
9350
if (data.entries != NULL) {
9351
qsort(data.entries,
9352
(size_t)data.num_entries,
9353
sizeof(data.entries[0]),
9354
compare_dir_entries);
9355
for (i = 0; i < data.num_entries; i++) {
9356
print_dir_entry(&data.entries[i]);
9357
mg_free(data.entries[i].file_name);
9358
}
9359
mg_free(data.entries);
9360
}
9361
9362
mg_printf(conn, "%s", "</table></body></html>");
9363
conn->status_code = 200;
9364
}
9365
9366
9367
/* Send len bytes from the opened file to the client. */
9368
static void
9369
send_file_data(struct mg_connection *conn,
9370
struct mg_file *filep,
9371
int64_t offset,
9372
int64_t len)
9373
{
9374
char buf[MG_BUF_LEN];
9375
int to_read, num_read, num_written;
9376
int64_t size;
9377
9378
if (!filep || !conn) {
9379
return;
9380
}
9381
9382
/* Sanity check the offset */
9383
size = (filep->stat.size > INT64_MAX) ? INT64_MAX
9384
: (int64_t)(filep->stat.size);
9385
offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
9386
9387
#if defined(MG_USE_OPEN_FILE)
9388
if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
9389
/* file stored in memory */
9390
if (len > size - offset) {
9391
len = size - offset;
9392
}
9393
mg_write(conn, filep->access.membuf + offset, (size_t)len);
9394
} else /* else block below */
9395
#endif
9396
if (len > 0 && filep->access.fp != NULL) {
9397
/* file stored on disk */
9398
#if defined(__linux__)
9399
/* sendfile is only available for Linux */
9400
if ((conn->ssl == 0) && (conn->throttle == 0)
9401
&& (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
9402
"yes"))) {
9403
off_t sf_offs = (off_t)offset;
9404
ssize_t sf_sent;
9405
int sf_file = fileno(filep->access.fp);
9406
int loop_cnt = 0;
9407
9408
do {
9409
/* 2147479552 (0x7FFFF000) is a limit found by experiment on
9410
* 64 bit Linux (2^31 minus one memory page of 4k?). */
9411
size_t sf_tosend =
9412
(size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
9413
sf_sent =
9414
sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
9415
if (sf_sent > 0) {
9416
len -= sf_sent;
9417
offset += sf_sent;
9418
} else if (loop_cnt == 0) {
9419
/* This file can not be sent using sendfile.
9420
* This might be the case for pseudo-files in the
9421
* /sys/ and /proc/ file system.
9422
* Use the regular user mode copy code instead. */
9423
break;
9424
} else if (sf_sent == 0) {
9425
/* No error, but 0 bytes sent. May be EOF? */
9426
return;
9427
}
9428
loop_cnt++;
9429
9430
} while ((len > 0) && (sf_sent >= 0));
9431
9432
if (sf_sent > 0) {
9433
return; /* OK */
9434
}
9435
9436
/* sf_sent<0 means error, thus fall back to the classic way */
9437
/* This is always the case, if sf_file is not a "normal" file,
9438
* e.g., for sending data from the output of a CGI process. */
9439
offset = (int64_t)sf_offs;
9440
}
9441
#endif
9442
if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
9443
mg_cry_internal(conn,
9444
"%s: fseeko() failed: %s",
9445
__func__,
9446
strerror(ERRNO));
9447
mg_send_http_error(
9448
conn,
9449
500,
9450
"%s",
9451
"Error: Unable to access file at requested position.");
9452
} else {
9453
while (len > 0) {
9454
/* Calculate how much to read from the file in the buffer */
9455
to_read = sizeof(buf);
9456
if ((int64_t)to_read > len) {
9457
to_read = (int)len;
9458
}
9459
9460
/* Read from file, exit the loop on error */
9461
if ((num_read =
9462
(int)fread(buf, 1, (size_t)to_read, filep->access.fp))
9463
<= 0) {
9464
break;
9465
}
9466
9467
/* Send read bytes to the client, exit the loop on error */
9468
if ((num_written = mg_write(conn, buf, (size_t)num_read))
9469
!= num_read) {
9470
break;
9471
}
9472
9473
/* Both read and were successful, adjust counters */
9474
len -= num_written;
9475
}
9476
}
9477
}
9478
}
9479
9480
9481
static int
9482
parse_range_header(const char *header, int64_t *a, int64_t *b)
9483
{
9484
return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
9485
}
9486
9487
9488
static void
9489
construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
9490
{
9491
if ((filestat != NULL) && (buf != NULL)) {
9492
mg_snprintf(NULL,
9493
NULL, /* All calls to construct_etag use 64 byte buffer */
9494
buf,
9495
buf_len,
9496
"\"%lx.%" INT64_FMT "\"",
9497
(unsigned long)filestat->last_modified,
9498
filestat->size);
9499
}
9500
}
9501
9502
9503
static void
9504
fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
9505
{
9506
if (filep != NULL && filep->fp != NULL) {
9507
#if defined(_WIN32)
9508
(void)conn; /* Unused. */
9509
#else
9510
if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
9511
mg_cry_internal(conn,
9512
"%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
9513
__func__,
9514
strerror(ERRNO));
9515
}
9516
#endif
9517
}
9518
}
9519
9520
9521
#if defined(USE_ZLIB)
9522
#include "mod_zlib.inl"
9523
#endif
9524
9525
9526
static void
9527
handle_static_file_request(struct mg_connection *conn,
9528
const char *path,
9529
struct mg_file *filep,
9530
const char *mime_type,
9531
const char *additional_headers)
9532
{
9533
char date[64], lm[64], etag[64];
9534
char range[128]; /* large enough, so there will be no overflow */
9535
const char *msg = "OK", *hdr;
9536
time_t curtime = time(NULL);
9537
int64_t cl, r1, r2;
9538
struct vec mime_vec;
9539
int n, truncated;
9540
char gz_path[PATH_MAX];
9541
const char *encoding = "";
9542
const char *cors1, *cors2, *cors3;
9543
int is_head_request;
9544
9545
#if defined(USE_ZLIB)
9546
/* Compression is allowed, unless there is a reason not to use compression.
9547
* If the file is already compressed, too small or a "range" request was
9548
* made, on the fly compression is not possible. */
9549
int allow_on_the_fly_compression = 1;
9550
#endif
9551
9552
if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
9553
return;
9554
}
9555
9556
is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
9557
9558
if (mime_type == NULL) {
9559
get_mime_type(conn, path, &mime_vec);
9560
} else {
9561
mime_vec.ptr = mime_type;
9562
mime_vec.len = strlen(mime_type);
9563
}
9564
if (filep->stat.size > INT64_MAX) {
9565
mg_send_http_error(conn,
9566
500,
9567
"Error: File size is too large to send\n%" INT64_FMT,
9568
filep->stat.size);
9569
return;
9570
}
9571
cl = (int64_t)filep->stat.size;
9572
conn->status_code = 200;
9573
range[0] = '\0';
9574
9575
#if defined(USE_ZLIB)
9576
/* if this file is in fact a pre-gzipped file, rewrite its filename
9577
* it's important to rewrite the filename after resolving
9578
* the mime type from it, to preserve the actual file's type */
9579
if (!conn->accept_gzip) {
9580
allow_on_the_fly_compression = 0;
9581
}
9582
#endif
9583
9584
if (filep->stat.is_gzipped) {
9585
mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
9586
9587
if (truncated) {
9588
mg_send_http_error(conn,
9589
500,
9590
"Error: Path of zipped file too long (%s)",
9591
path);
9592
return;
9593
}
9594
9595
path = gz_path;
9596
encoding = "Content-Encoding: gzip\r\n";
9597
9598
#if defined(USE_ZLIB)
9599
/* File is already compressed. No "on the fly" compression. */
9600
allow_on_the_fly_compression = 0;
9601
#endif
9602
}
9603
9604
if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
9605
mg_send_http_error(conn,
9606
500,
9607
"Error: Cannot open file\nfopen(%s): %s",
9608
path,
9609
strerror(ERRNO));
9610
return;
9611
}
9612
9613
fclose_on_exec(&filep->access, conn);
9614
9615
/* If "Range" request was made: parse header, send only selected part
9616
* of the file. */
9617
r1 = r2 = 0;
9618
hdr = mg_get_header(conn, "Range");
9619
if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
9620
&& (r1 >= 0) && (r2 >= 0)) {
9621
/* actually, range requests don't play well with a pre-gzipped
9622
* file (since the range is specified in the uncompressed space) */
9623
if (filep->stat.is_gzipped) {
9624
mg_send_http_error(
9625
conn,
9626
416, /* 416 = Range Not Satisfiable */
9627
"%s",
9628
"Error: Range requests in gzipped files are not supported");
9629
(void)mg_fclose(
9630
&filep->access); /* ignore error on read only file */
9631
return;
9632
}
9633
conn->status_code = 206;
9634
cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
9635
mg_snprintf(conn,
9636
NULL, /* range buffer is big enough */
9637
range,
9638
sizeof(range),
9639
"Content-Range: bytes "
9640
"%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
9641
r1,
9642
r1 + cl - 1,
9643
filep->stat.size);
9644
msg = "Partial Content";
9645
9646
#if defined(USE_ZLIB)
9647
/* Do not compress ranges. */
9648
allow_on_the_fly_compression = 0;
9649
#endif
9650
}
9651
9652
/* Do not compress small files. Small files do not benefit from file
9653
* compression, but there is still some overhead. */
9654
#if defined(USE_ZLIB)
9655
if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
9656
/* File is below the size limit. */
9657
allow_on_the_fly_compression = 0;
9658
}
9659
#endif
9660
9661
/* Standard CORS header */
9662
hdr = mg_get_header(conn, "Origin");
9663
if (hdr) {
9664
/* Cross-origin resource sharing (CORS), see
9665
* http://www.html5rocks.com/en/tutorials/cors/,
9666
* http://www.html5rocks.com/static/images/cors_server_flowchart.png
9667
* -
9668
* preflight is not supported for files. */
9669
cors1 = "Access-Control-Allow-Origin: ";
9670
cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
9671
cors3 = "\r\n";
9672
} else {
9673
cors1 = cors2 = cors3 = "";
9674
}
9675
9676
/* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
9677
* according to
9678
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
9679
gmt_time_string(date, sizeof(date), &curtime);
9680
gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
9681
construct_etag(etag, sizeof(etag), &filep->stat);
9682
9683
/* Send header */
9684
(void)mg_printf(conn,
9685
"HTTP/1.1 %d %s\r\n"
9686
"%s%s%s" /* CORS */
9687
"Date: %s\r\n"
9688
"Last-Modified: %s\r\n"
9689
"Etag: %s\r\n"
9690
"Content-Type: %.*s\r\n"
9691
"Connection: %s\r\n",
9692
conn->status_code,
9693
msg,
9694
cors1,
9695
cors2,
9696
cors3,
9697
date,
9698
lm,
9699
etag,
9700
(int)mime_vec.len,
9701
mime_vec.ptr,
9702
suggest_connection_header(conn));
9703
send_static_cache_header(conn);
9704
send_additional_header(conn);
9705
9706
#if defined(USE_ZLIB)
9707
/* On the fly compression allowed */
9708
if (allow_on_the_fly_compression) {
9709
/* For on the fly compression, we don't know the content size in
9710
* advance, so we have to use chunked encoding */
9711
(void)mg_printf(conn,
9712
"Content-Encoding: gzip\r\n"
9713
"Transfer-Encoding: chunked\r\n");
9714
} else
9715
#endif
9716
{
9717
/* Without on-the-fly compression, we know the content-length
9718
* and we can use ranges (with on-the-fly compression we cannot).
9719
* So we send these response headers only in this case. */
9720
(void)mg_printf(conn,
9721
"Content-Length: %" INT64_FMT "\r\n"
9722
"Accept-Ranges: bytes\r\n"
9723
"%s" /* range */
9724
"%s" /* encoding */,
9725
cl,
9726
range,
9727
encoding);
9728
}
9729
9730
/* The previous code must not add any header starting with X- to make
9731
* sure no one of the additional_headers is included twice */
9732
if (additional_headers != NULL) {
9733
(void)mg_printf(conn,
9734
"%.*s\r\n\r\n",
9735
(int)strlen(additional_headers),
9736
additional_headers);
9737
} else {
9738
(void)mg_printf(conn, "\r\n");
9739
}
9740
9741
if (!is_head_request) {
9742
#if defined(USE_ZLIB)
9743
if (allow_on_the_fly_compression) {
9744
/* Compress and send */
9745
send_compressed_data(conn, filep);
9746
} else
9747
#endif
9748
{
9749
/* Send file directly */
9750
send_file_data(conn, filep, r1, cl);
9751
}
9752
}
9753
(void)mg_fclose(&filep->access); /* ignore error on read only file */
9754
}
9755
9756
9757
int
9758
mg_send_file_body(struct mg_connection *conn, const char *path)
9759
{
9760
struct mg_file file = STRUCT_FILE_INITIALIZER;
9761
if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
9762
return -1;
9763
}
9764
fclose_on_exec(&file.access, conn);
9765
send_file_data(conn, &file, 0, INT64_MAX);
9766
(void)mg_fclose(&file.access); /* Ignore errors for readonly files */
9767
return 0; /* >= 0 for OK */
9768
}
9769
9770
9771
#if !defined(NO_CACHING)
9772
/* Return True if we should reply 304 Not Modified. */
9773
static int
9774
is_not_modified(const struct mg_connection *conn,
9775
const struct mg_file_stat *filestat)
9776
{
9777
char etag[64];
9778
const char *ims = mg_get_header(conn, "If-Modified-Since");
9779
const char *inm = mg_get_header(conn, "If-None-Match");
9780
construct_etag(etag, sizeof(etag), filestat);
9781
9782
return ((inm != NULL) && !mg_strcasecmp(etag, inm))
9783
|| ((ims != NULL)
9784
&& (filestat->last_modified <= parse_date_string(ims)));
9785
}
9786
9787
static void
9788
handle_not_modified_static_file_request(struct mg_connection *conn,
9789
struct mg_file *filep)
9790
{
9791
char date[64], lm[64], etag[64];
9792
time_t curtime = time(NULL);
9793
9794
if ((conn == NULL) || (filep == NULL)) {
9795
return;
9796
}
9797
conn->status_code = 304;
9798
gmt_time_string(date, sizeof(date), &curtime);
9799
gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
9800
construct_etag(etag, sizeof(etag), &filep->stat);
9801
9802
(void)mg_printf(conn,
9803
"HTTP/1.1 %d %s\r\n"
9804
"Date: %s\r\n",
9805
conn->status_code,
9806
mg_get_response_code_text(conn, conn->status_code),
9807
date);
9808
send_static_cache_header(conn);
9809
send_additional_header(conn);
9810
(void)mg_printf(conn,
9811
"Last-Modified: %s\r\n"
9812
"Etag: %s\r\n"
9813
"Connection: %s\r\n"
9814
"\r\n",
9815
lm,
9816
etag,
9817
suggest_connection_header(conn));
9818
}
9819
#endif
9820
9821
9822
void
9823
mg_send_file(struct mg_connection *conn, const char *path)
9824
{
9825
mg_send_mime_file2(conn, path, NULL, NULL);
9826
}
9827
9828
9829
void
9830
mg_send_mime_file(struct mg_connection *conn,
9831
const char *path,
9832
const char *mime_type)
9833
{
9834
mg_send_mime_file2(conn, path, mime_type, NULL);
9835
}
9836
9837
9838
void
9839
mg_send_mime_file2(struct mg_connection *conn,
9840
const char *path,
9841
const char *mime_type,
9842
const char *additional_headers)
9843
{
9844
struct mg_file file = STRUCT_FILE_INITIALIZER;
9845
9846
if (!conn) {
9847
/* No conn */
9848
return;
9849
}
9850
9851
if (mg_stat(conn, path, &file.stat)) {
9852
#if !defined(NO_CACHING)
9853
if (is_not_modified(conn, &file.stat)) {
9854
/* Send 304 "Not Modified" - this must not send any body data */
9855
handle_not_modified_static_file_request(conn, &file);
9856
} else
9857
#endif /* NO_CACHING */
9858
if (file.stat.is_directory) {
9859
if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
9860
"yes")) {
9861
handle_directory_request(conn, path);
9862
} else {
9863
mg_send_http_error(conn,
9864
403,
9865
"%s",
9866
"Error: Directory listing denied");
9867
}
9868
} else {
9869
handle_static_file_request(
9870
conn, path, &file, mime_type, additional_headers);
9871
}
9872
} else {
9873
mg_send_http_error(conn, 404, "%s", "Error: File not found");
9874
}
9875
}
9876
9877
9878
/* For a given PUT path, create all intermediate subdirectories.
9879
* Return 0 if the path itself is a directory.
9880
* Return 1 if the path leads to a file.
9881
* Return -1 for if the path is too long.
9882
* Return -2 if path can not be created.
9883
*/
9884
static int
9885
put_dir(struct mg_connection *conn, const char *path)
9886
{
9887
char buf[PATH_MAX];
9888
const char *s, *p;
9889
struct mg_file file = STRUCT_FILE_INITIALIZER;
9890
size_t len;
9891
int res = 1;
9892
9893
for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
9894
len = (size_t)(p - path);
9895
if (len >= sizeof(buf)) {
9896
/* path too long */
9897
res = -1;
9898
break;
9899
}
9900
memcpy(buf, path, len);
9901
buf[len] = '\0';
9902
9903
/* Try to create intermediate directory */
9904
DEBUG_TRACE("mkdir(%s)", buf);
9905
if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
9906
/* path does not exixt and can not be created */
9907
res = -2;
9908
break;
9909
}
9910
9911
/* Is path itself a directory? */
9912
if (p[1] == '\0') {
9913
res = 0;
9914
}
9915
}
9916
9917
return res;
9918
}
9919
9920
9921
static void
9922
remove_bad_file(const struct mg_connection *conn, const char *path)
9923
{
9924
int r = mg_remove(conn, path);
9925
if (r != 0) {
9926
mg_cry_internal(conn,
9927
"%s: Cannot remove invalid file %s",
9928
__func__,
9929
path);
9930
}
9931
}
9932
9933
9934
long long
9935
mg_store_body(struct mg_connection *conn, const char *path)
9936
{
9937
char buf[MG_BUF_LEN];
9938
long long len = 0;
9939
int ret, n;
9940
struct mg_file fi;
9941
9942
if (conn->consumed_content != 0) {
9943
mg_cry_internal(conn, "%s: Contents already consumed", __func__);
9944
return -11;
9945
}
9946
9947
ret = put_dir(conn, path);
9948
if (ret < 0) {
9949
/* -1 for path too long,
9950
* -2 for path can not be created. */
9951
return ret;
9952
}
9953
if (ret != 1) {
9954
/* Return 0 means, path itself is a directory. */
9955
return 0;
9956
}
9957
9958
if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
9959
return -12;
9960
}
9961
9962
ret = mg_read(conn, buf, sizeof(buf));
9963
while (ret > 0) {
9964
n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
9965
if (n != ret) {
9966
(void)mg_fclose(
9967
&fi.access); /* File is bad and will be removed anyway. */
9968
remove_bad_file(conn, path);
9969
return -13;
9970
}
9971
len += ret;
9972
ret = mg_read(conn, buf, sizeof(buf));
9973
}
9974
9975
/* File is open for writing. If fclose fails, there was probably an
9976
* error flushing the buffer to disk, so the file on disk might be
9977
* broken. Delete it and return an error to the caller. */
9978
if (mg_fclose(&fi.access) != 0) {
9979
remove_bad_file(conn, path);
9980
return -14;
9981
}
9982
9983
return len;
9984
}
9985
9986
9987
/* Parse a buffer:
9988
* Forward the string pointer till the end of a word, then
9989
* terminate it and forward till the begin of the next word.
9990
*/
9991
static int
9992
skip_to_end_of_word_and_terminate(char **ppw, int eol)
9993
{
9994
/* Forward until a space is found - use isgraph here */
9995
/* See http://www.cplusplus.com/reference/cctype/ */
9996
while (isgraph(**ppw)) {
9997
(*ppw)++;
9998
}
9999
10000
/* Check end of word */
10001
if (eol) {
10002
/* must be a end of line */
10003
if ((**ppw != '\r') && (**ppw != '\n')) {
10004
return -1;
10005
}
10006
} else {
10007
/* must be a end of a word, but not a line */
10008
if (**ppw != ' ') {
10009
return -1;
10010
}
10011
}
10012
10013
/* Terminate and forward to the next word */
10014
do {
10015
**ppw = 0;
10016
(*ppw)++;
10017
} while ((**ppw) && isspace(**ppw));
10018
10019
/* Check after term */
10020
if (!eol) {
10021
/* if it's not the end of line, there must be a next word */
10022
if (!isgraph(**ppw)) {
10023
return -1;
10024
}
10025
}
10026
10027
/* ok */
10028
return 1;
10029
}
10030
10031
10032
/* Parse HTTP headers from the given buffer, advance buf pointer
10033
* to the point where parsing stopped.
10034
* All parameters must be valid pointers (not NULL).
10035
* Return <0 on error. */
10036
static int
10037
parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
10038
{
10039
int i;
10040
int num_headers = 0;
10041
10042
for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
10043
char *dp = *buf;
10044
while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
10045
dp++;
10046
}
10047
if (dp == *buf) {
10048
/* End of headers reached. */
10049
break;
10050
}
10051
if (*dp != ':') {
10052
/* This is not a valid field. */
10053
return -1;
10054
}
10055
10056
/* End of header key (*dp == ':') */
10057
/* Truncate here and set the key name */
10058
*dp = 0;
10059
hdr[i].name = *buf;
10060
do {
10061
dp++;
10062
} while (*dp == ' ');
10063
10064
/* The rest of the line is the value */
10065
hdr[i].value = dp;
10066
*buf = dp + strcspn(dp, "\r\n");
10067
if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
10068
*buf = NULL;
10069
}
10070
10071
num_headers = i + 1;
10072
if (*buf) {
10073
(*buf)[0] = 0;
10074
(*buf)[1] = 0;
10075
*buf += 2;
10076
} else {
10077
*buf = dp;
10078
break;
10079
}
10080
10081
if ((*buf)[0] == '\r') {
10082
/* This is the end of the header */
10083
break;
10084
}
10085
}
10086
return num_headers;
10087
}
10088
10089
10090
struct mg_http_method_info {
10091
const char *name;
10092
int request_has_body;
10093
int response_has_body;
10094
int is_safe;
10095
int is_idempotent;
10096
int is_cacheable;
10097
};
10098
10099
10100
/* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
10101
static struct mg_http_method_info http_methods[] = {
10102
/* HTTP (RFC 2616) */
10103
{"GET", 0, 1, 1, 1, 1},
10104
{"POST", 1, 1, 0, 0, 0},
10105
{"PUT", 1, 0, 0, 1, 0},
10106
{"DELETE", 0, 0, 0, 1, 0},
10107
{"HEAD", 0, 0, 1, 1, 1},
10108
{"OPTIONS", 0, 0, 1, 1, 0},
10109
{"CONNECT", 1, 1, 0, 0, 0},
10110
/* TRACE method (RFC 2616) is not supported for security reasons */
10111
10112
/* PATCH method (RFC 5789) */
10113
{"PATCH", 1, 0, 0, 0, 0},
10114
/* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
10115
10116
/* WEBDAV (RFC 2518) */
10117
{"PROPFIND", 0, 1, 1, 1, 0},
10118
/* http://www.webdav.org/specs/rfc4918.html, 9.1:
10119
* Some PROPFIND results MAY be cached, with care,
10120
* as there is no cache validation mechanism for
10121
* most properties. This method is both safe and
10122
* idempotent (see Section 9.1 of [RFC2616]). */
10123
{"MKCOL", 0, 0, 0, 1, 0},
10124
/* http://www.webdav.org/specs/rfc4918.html, 9.1:
10125
* When MKCOL is invoked without a request body,
10126
* the newly created collection SHOULD have no
10127
* members. A MKCOL request message may contain
10128
* a message body. The precise behavior of a MKCOL
10129
* request when the body is present is undefined,
10130
* ... ==> We do not support MKCOL with body data.
10131
* This method is idempotent, but not safe (see
10132
* Section 9.1 of [RFC2616]). Responses to this
10133
* method MUST NOT be cached. */
10134
10135
/* Unsupported WEBDAV Methods: */
10136
/* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
10137
/* + 11 methods from RFC 3253 */
10138
/* ORDERPATCH (RFC 3648) */
10139
/* ACL (RFC 3744) */
10140
/* SEARCH (RFC 5323) */
10141
/* + MicroSoft extensions
10142
* https://msdn.microsoft.com/en-us/library/aa142917.aspx */
10143
10144
/* REPORT method (RFC 3253) */
10145
{"REPORT", 1, 1, 1, 1, 1},
10146
/* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
10147
/* It was defined for WEBDAV in RFC 3253, Sec. 3.6
10148
* (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
10149
* to be useful for REST in case a "GET request with body" is
10150
* required. */
10151
10152
{NULL, 0, 0, 0, 0, 0}
10153
/* end of list */
10154
};
10155
10156
10157
static const struct mg_http_method_info *
10158
get_http_method_info(const char *method)
10159
{
10160
/* Check if the method is known to the server. The list of all known
10161
* HTTP methods can be found here at
10162
* http://www.iana.org/assignments/http-methods/http-methods.xhtml
10163
*/
10164
const struct mg_http_method_info *m = http_methods;
10165
10166
while (m->name) {
10167
if (!strcmp(m->name, method)) {
10168
return m;
10169
}
10170
m++;
10171
}
10172
return NULL;
10173
}
10174
10175
10176
static int
10177
is_valid_http_method(const char *method)
10178
{
10179
return (get_http_method_info(method) != NULL);
10180
}
10181
10182
10183
/* Parse HTTP request, fill in mg_request_info structure.
10184
* This function modifies the buffer by NUL-terminating
10185
* HTTP request components, header names and header values.
10186
* Parameters:
10187
* buf (in/out): pointer to the HTTP header to parse and split
10188
* len (in): length of HTTP header buffer
10189
* re (out): parsed header as mg_request_info
10190
* buf and ri must be valid pointers (not NULL), len>0.
10191
* Returns <0 on error. */
10192
static int
10193
parse_http_request(char *buf, int len, struct mg_request_info *ri)
10194
{
10195
int request_length;
10196
int init_skip = 0;
10197
10198
/* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
10199
* remote_port */
10200
ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
10201
NULL;
10202
ri->num_headers = 0;
10203
10204
/* RFC says that all initial whitespaces should be ingored */
10205
/* This included all leading \r and \n (isspace) */
10206
/* See table: http://www.cplusplus.com/reference/cctype/ */
10207
while ((len > 0) && isspace(*(unsigned char *)buf)) {
10208
buf++;
10209
len--;
10210
init_skip++;
10211
}
10212
10213
if (len == 0) {
10214
/* Incomplete request */
10215
return 0;
10216
}
10217
10218
/* Control characters are not allowed, including zero */
10219
if (iscntrl(*(unsigned char *)buf)) {
10220
return -1;
10221
}
10222
10223
/* Find end of HTTP header */
10224
request_length = get_http_header_len(buf, len);
10225
if (request_length <= 0) {
10226
return request_length;
10227
}
10228
buf[request_length - 1] = '\0';
10229
10230
if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10231
return -1;
10232
}
10233
10234
/* The first word has to be the HTTP method */
10235
ri->request_method = buf;
10236
10237
if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10238
return -1;
10239
}
10240
10241
/* Check for a valid http method */
10242
if (!is_valid_http_method(ri->request_method)) {
10243
return -1;
10244
}
10245
10246
/* The second word is the URI */
10247
ri->request_uri = buf;
10248
10249
if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10250
return -1;
10251
}
10252
10253
/* Next would be the HTTP version */
10254
ri->http_version = buf;
10255
10256
if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
10257
return -1;
10258
}
10259
10260
/* Check for a valid HTTP version key */
10261
if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
10262
/* Invalid request */
10263
return -1;
10264
}
10265
ri->http_version += 5;
10266
10267
10268
/* Parse all HTTP headers */
10269
ri->num_headers = parse_http_headers(&buf, ri->http_headers);
10270
if (ri->num_headers < 0) {
10271
/* Error while parsing headers */
10272
return -1;
10273
}
10274
10275
return request_length + init_skip;
10276
}
10277
10278
10279
static int
10280
parse_http_response(char *buf, int len, struct mg_response_info *ri)
10281
{
10282
int response_length;
10283
int init_skip = 0;
10284
char *tmp, *tmp2;
10285
long l;
10286
10287
/* Initialize elements. */
10288
ri->http_version = ri->status_text = NULL;
10289
ri->num_headers = ri->status_code = 0;
10290
10291
/* RFC says that all initial whitespaces should be ingored */
10292
/* This included all leading \r and \n (isspace) */
10293
/* See table: http://www.cplusplus.com/reference/cctype/ */
10294
while ((len > 0) && isspace(*(unsigned char *)buf)) {
10295
buf++;
10296
len--;
10297
init_skip++;
10298
}
10299
10300
if (len == 0) {
10301
/* Incomplete request */
10302
return 0;
10303
}
10304
10305
/* Control characters are not allowed, including zero */
10306
if (iscntrl(*(unsigned char *)buf)) {
10307
return -1;
10308
}
10309
10310
/* Find end of HTTP header */
10311
response_length = get_http_header_len(buf, len);
10312
if (response_length <= 0) {
10313
return response_length;
10314
}
10315
buf[response_length - 1] = '\0';
10316
10317
if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
10318
return -1;
10319
}
10320
10321
/* The first word is the HTTP version */
10322
/* Check for a valid HTTP version key */
10323
if (strncmp(buf, "HTTP/", 5) != 0) {
10324
/* Invalid request */
10325
return -1;
10326
}
10327
buf += 5;
10328
if (!isgraph(buf[0])) {
10329
/* Invalid request */
10330
return -1;
10331
}
10332
ri->http_version = buf;
10333
10334
if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10335
return -1;
10336
}
10337
10338
/* The second word is the status as a number */
10339
tmp = buf;
10340
10341
if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
10342
return -1;
10343
}
10344
10345
l = strtol(tmp, &tmp2, 10);
10346
if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
10347
/* Everything else but a 3 digit code is invalid */
10348
return -1;
10349
}
10350
ri->status_code = (int)l;
10351
10352
/* The rest of the line is the status text */
10353
ri->status_text = buf;
10354
10355
/* Find end of status text */
10356
/* isgraph or isspace = isprint */
10357
while (isprint(*buf)) {
10358
buf++;
10359
}
10360
if ((*buf != '\r') && (*buf != '\n')) {
10361
return -1;
10362
}
10363
/* Terminate string and forward buf to next line */
10364
do {
10365
*buf = 0;
10366
buf++;
10367
} while ((*buf) && isspace(*buf));
10368
10369
10370
/* Parse all HTTP headers */
10371
ri->num_headers = parse_http_headers(&buf, ri->http_headers);
10372
if (ri->num_headers < 0) {
10373
/* Error while parsing headers */
10374
return -1;
10375
}
10376
10377
return response_length + init_skip;
10378
}
10379
10380
10381
/* Keep reading the input (either opened file descriptor fd, or socket sock,
10382
* or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
10383
* buffer (which marks the end of HTTP request). Buffer buf may already
10384
* have some data. The length of the data is stored in nread.
10385
* Upon every read operation, increase nread by the number of bytes read. */
10386
static int
10387
read_message(FILE *fp,
10388
struct mg_connection *conn,
10389
char *buf,
10390
int bufsiz,
10391
int *nread)
10392
{
10393
int request_len, n = 0;
10394
struct timespec last_action_time;
10395
double request_timeout;
10396
10397
if (!conn) {
10398
return 0;
10399
}
10400
10401
memset(&last_action_time, 0, sizeof(last_action_time));
10402
10403
if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
10404
/* value of request_timeout is in seconds, config in milliseconds */
10405
request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
10406
} else {
10407
request_timeout = -1.0;
10408
}
10409
if (conn->handled_requests > 0) {
10410
if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
10411
request_timeout =
10412
atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
10413
}
10414
}
10415
10416
request_len = get_http_header_len(buf, *nread);
10417
10418
/* first time reading from this connection */
10419
clock_gettime(CLOCK_MONOTONIC, &last_action_time);
10420
10421
while (request_len == 0) {
10422
/* Full request not yet received */
10423
if (conn->phys_ctx->stop_flag != 0) {
10424
/* Server is to be stopped. */
10425
return -1;
10426
}
10427
10428
if (*nread >= bufsiz) {
10429
/* Request too long */
10430
return -2;
10431
}
10432
10433
n = pull_inner(
10434
fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
10435
if (n == -2) {
10436
/* Receive error */
10437
return -1;
10438
}
10439
if (n > 0) {
10440
*nread += n;
10441
request_len = get_http_header_len(buf, *nread);
10442
} else {
10443
request_len = 0;
10444
}
10445
10446
if ((request_len == 0) && (request_timeout >= 0)) {
10447
if (mg_difftimespec(&last_action_time, &(conn->req_time))
10448
> request_timeout) {
10449
/* Timeout */
10450
return -1;
10451
}
10452
clock_gettime(CLOCK_MONOTONIC, &last_action_time);
10453
}
10454
}
10455
10456
return request_len;
10457
}
10458
10459
10460
#if !defined(NO_CGI) || !defined(NO_FILES)
10461
static int
10462
forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
10463
{
10464
const char *expect, *body;
10465
char buf[MG_BUF_LEN];
10466
int to_read, nread, success = 0;
10467
int64_t buffered_len;
10468
double timeout = -1.0;
10469
10470
if (!conn) {
10471
return 0;
10472
}
10473
if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
10474
timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
10475
}
10476
10477
expect = mg_get_header(conn, "Expect");
10478
DEBUG_ASSERT(fp != NULL);
10479
if (!fp) {
10480
mg_send_http_error(conn, 500, "%s", "Error: NULL File");
10481
return 0;
10482
}
10483
10484
if ((conn->content_len == -1) && (!conn->is_chunked)) {
10485
/* Content length is not specified by the client. */
10486
mg_send_http_error(conn,
10487
411,
10488
"%s",
10489
"Error: Client did not specify content length");
10490
} else if ((expect != NULL)
10491
&& (mg_strcasecmp(expect, "100-continue") != 0)) {
10492
/* Client sent an "Expect: xyz" header and xyz is not 100-continue.
10493
*/
10494
mg_send_http_error(conn,
10495
417,
10496
"Error: Can not fulfill expectation %s",
10497
expect);
10498
} else {
10499
if (expect != NULL) {
10500
(void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
10501
conn->status_code = 100;
10502
} else {
10503
conn->status_code = 200;
10504
}
10505
10506
buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
10507
- conn->consumed_content;
10508
10509
DEBUG_ASSERT(buffered_len >= 0);
10510
DEBUG_ASSERT(conn->consumed_content == 0);
10511
10512
if ((buffered_len < 0) || (conn->consumed_content != 0)) {
10513
mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
10514
return 0;
10515
}
10516
10517
if (buffered_len > 0) {
10518
if ((int64_t)buffered_len > conn->content_len) {
10519
buffered_len = (int)conn->content_len;
10520
}
10521
body = conn->buf + conn->request_len + conn->consumed_content;
10522
push_all(
10523
conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
10524
conn->consumed_content += buffered_len;
10525
}
10526
10527
nread = 0;
10528
while (conn->consumed_content < conn->content_len) {
10529
to_read = sizeof(buf);
10530
if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
10531
to_read = (int)(conn->content_len - conn->consumed_content);
10532
}
10533
nread = pull_inner(NULL, conn, buf, to_read, timeout);
10534
if (nread == -2) {
10535
/* error */
10536
break;
10537
}
10538
if (nread > 0) {
10539
if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
10540
!= nread) {
10541
break;
10542
}
10543
}
10544
conn->consumed_content += nread;
10545
}
10546
10547
if (conn->consumed_content == conn->content_len) {
10548
success = (nread >= 0);
10549
}
10550
10551
/* Each error code path in this function must send an error */
10552
if (!success) {
10553
/* NOTE: Maybe some data has already been sent. */
10554
/* TODO (low): If some data has been sent, a correct error
10555
* reply can no longer be sent, so just close the connection */
10556
mg_send_http_error(conn, 500, "%s", "");
10557
}
10558
}
10559
10560
return success;
10561
}
10562
#endif
10563
10564
10565
#if defined(USE_TIMERS)
10566
10567
#define TIMER_API static
10568
#include "timer.inl"
10569
10570
#endif /* USE_TIMERS */
10571
10572
10573
#if !defined(NO_CGI)
10574
/* This structure helps to create an environment for the spawned CGI
10575
* program.
10576
* Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
10577
* last element must be NULL.
10578
* However, on Windows there is a requirement that all these
10579
* VARIABLE=VALUE\0
10580
* strings must reside in a contiguous buffer. The end of the buffer is
10581
* marked by two '\0' characters.
10582
* We satisfy both worlds: we create an envp array (which is vars), all
10583
* entries are actually pointers inside buf. */
10584
struct cgi_environment {
10585
struct mg_connection *conn;
10586
/* Data block */
10587
char *buf; /* Environment buffer */
10588
size_t buflen; /* Space available in buf */
10589
size_t bufused; /* Space taken in buf */
10590
/* Index block */
10591
char **var; /* char **envp */
10592
size_t varlen; /* Number of variables available in var */
10593
size_t varused; /* Number of variables stored in var */
10594
};
10595
10596
10597
static void addenv(struct cgi_environment *env,
10598
PRINTF_FORMAT_STRING(const char *fmt),
10599
...) PRINTF_ARGS(2, 3);
10600
10601
/* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
10602
* pointer into the vars array. Assumes env != NULL and fmt != NULL. */
10603
static void
10604
addenv(struct cgi_environment *env, const char *fmt, ...)
10605
{
10606
size_t n, space;
10607
int truncated = 0;
10608
char *added;
10609
va_list ap;
10610
10611
/* Calculate how much space is left in the buffer */
10612
space = (env->buflen - env->bufused);
10613
10614
/* Calculate an estimate for the required space */
10615
n = strlen(fmt) + 2 + 128;
10616
10617
do {
10618
if (space <= n) {
10619
/* Allocate new buffer */
10620
n = env->buflen + CGI_ENVIRONMENT_SIZE;
10621
added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
10622
if (!added) {
10623
/* Out of memory */
10624
mg_cry_internal(
10625
env->conn,
10626
"%s: Cannot allocate memory for CGI variable [%s]",
10627
__func__,
10628
fmt);
10629
return;
10630
}
10631
env->buf = added;
10632
env->buflen = n;
10633
space = (env->buflen - env->bufused);
10634
}
10635
10636
/* Make a pointer to the free space int the buffer */
10637
added = env->buf + env->bufused;
10638
10639
/* Copy VARIABLE=VALUE\0 string into the free space */
10640
va_start(ap, fmt);
10641
mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
10642
va_end(ap);
10643
10644
/* Do not add truncated strings to the environment */
10645
if (truncated) {
10646
/* Reallocate the buffer */
10647
space = 0;
10648
n = 1;
10649
}
10650
} while (truncated);
10651
10652
/* Calculate number of bytes added to the environment */
10653
n = strlen(added) + 1;
10654
env->bufused += n;
10655
10656
/* Now update the variable index */
10657
space = (env->varlen - env->varused);
10658
if (space < 2) {
10659
mg_cry_internal(env->conn,
10660
"%s: Cannot register CGI variable [%s]",
10661
__func__,
10662
fmt);
10663
return;
10664
}
10665
10666
/* Append a pointer to the added string into the envp array */
10667
env->var[env->varused] = added;
10668
env->varused++;
10669
}
10670
10671
/* Return 0 on success, non-zero if an error occurs. */
10672
10673
static int
10674
prepare_cgi_environment(struct mg_connection *conn,
10675
const char *prog,
10676
struct cgi_environment *env)
10677
{
10678
const char *s;
10679
struct vec var_vec;
10680
char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
10681
int i, truncated, uri_len;
10682
10683
if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
10684
return -1;
10685
}
10686
10687
env->conn = conn;
10688
env->buflen = CGI_ENVIRONMENT_SIZE;
10689
env->bufused = 0;
10690
env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
10691
if (env->buf == NULL) {
10692
mg_cry_internal(conn,
10693
"%s: Not enough memory for environmental buffer",
10694
__func__);
10695
return -1;
10696
}
10697
env->varlen = MAX_CGI_ENVIR_VARS;
10698
env->varused = 0;
10699
env->var =
10700
(char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
10701
if (env->var == NULL) {
10702
mg_cry_internal(conn,
10703
"%s: Not enough memory for environmental variables",
10704
__func__);
10705
mg_free(env->buf);
10706
return -1;
10707
}
10708
10709
addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
10710
addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
10711
addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
10712
addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
10713
10714
/* Prepare the environment block */
10715
addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
10716
addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
10717
addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
10718
10719
#if defined(USE_IPV6)
10720
if (conn->client.lsa.sa.sa_family == AF_INET6) {
10721
addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
10722
} else
10723
#endif
10724
{
10725
addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
10726
}
10727
10728
sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
10729
addenv(env, "REMOTE_ADDR=%s", src_addr);
10730
10731
addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
10732
addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
10733
10734
addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
10735
addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
10736
10737
/* SCRIPT_NAME */
10738
uri_len = (int)strlen(conn->request_info.local_uri);
10739
if (conn->path_info == NULL) {
10740
if (conn->request_info.local_uri[uri_len - 1] != '/') {
10741
/* URI: /path_to_script/script.cgi */
10742
addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
10743
} else {
10744
/* URI: /path_to_script/ ... using index.cgi */
10745
const char *index_file = strrchr(prog, '/');
10746
if (index_file) {
10747
addenv(env,
10748
"SCRIPT_NAME=%s%s",
10749
conn->request_info.local_uri,
10750
index_file + 1);
10751
}
10752
}
10753
} else {
10754
/* URI: /path_to_script/script.cgi/path_info */
10755
addenv(env,
10756
"SCRIPT_NAME=%.*s",
10757
uri_len - (int)strlen(conn->path_info),
10758
conn->request_info.local_uri);
10759
}
10760
10761
addenv(env, "SCRIPT_FILENAME=%s", prog);
10762
if (conn->path_info == NULL) {
10763
addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
10764
} else {
10765
addenv(env,
10766
"PATH_TRANSLATED=%s%s",
10767
conn->dom_ctx->config[DOCUMENT_ROOT],
10768
conn->path_info);
10769
}
10770
10771
addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
10772
10773
if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
10774
addenv(env, "CONTENT_TYPE=%s", s);
10775
}
10776
if (conn->request_info.query_string != NULL) {
10777
addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
10778
}
10779
if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
10780
addenv(env, "CONTENT_LENGTH=%s", s);
10781
}
10782
if ((s = getenv("PATH")) != NULL) {
10783
addenv(env, "PATH=%s", s);
10784
}
10785
if (conn->path_info != NULL) {
10786
addenv(env, "PATH_INFO=%s", conn->path_info);
10787
}
10788
10789
if (conn->status_code > 0) {
10790
/* CGI error handler should show the status code */
10791
addenv(env, "STATUS=%d", conn->status_code);
10792
}
10793
10794
#if defined(_WIN32)
10795
if ((s = getenv("COMSPEC")) != NULL) {
10796
addenv(env, "COMSPEC=%s", s);
10797
}
10798
if ((s = getenv("SYSTEMROOT")) != NULL) {
10799
addenv(env, "SYSTEMROOT=%s", s);
10800
}
10801
if ((s = getenv("SystemDrive")) != NULL) {
10802
addenv(env, "SystemDrive=%s", s);
10803
}
10804
if ((s = getenv("ProgramFiles")) != NULL) {
10805
addenv(env, "ProgramFiles=%s", s);
10806
}
10807
if ((s = getenv("ProgramFiles(x86)")) != NULL) {
10808
addenv(env, "ProgramFiles(x86)=%s", s);
10809
}
10810
#else
10811
if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
10812
addenv(env, "LD_LIBRARY_PATH=%s", s);
10813
}
10814
#endif /* _WIN32 */
10815
10816
if ((s = getenv("PERLLIB")) != NULL) {
10817
addenv(env, "PERLLIB=%s", s);
10818
}
10819
10820
if (conn->request_info.remote_user != NULL) {
10821
addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
10822
addenv(env, "%s", "AUTH_TYPE=Digest");
10823
}
10824
10825
/* Add all headers as HTTP_* variables */
10826
for (i = 0; i < conn->request_info.num_headers; i++) {
10827
10828
(void)mg_snprintf(conn,
10829
&truncated,
10830
http_var_name,
10831
sizeof(http_var_name),
10832
"HTTP_%s",
10833
conn->request_info.http_headers[i].name);
10834
10835
if (truncated) {
10836
mg_cry_internal(conn,
10837
"%s: HTTP header variable too long [%s]",
10838
__func__,
10839
conn->request_info.http_headers[i].name);
10840
continue;
10841
}
10842
10843
/* Convert variable name into uppercase, and change - to _ */
10844
for (p = http_var_name; *p != '\0'; p++) {
10845
if (*p == '-') {
10846
*p = '_';
10847
}
10848
*p = (char)toupper(*(unsigned char *)p);
10849
}
10850
10851
addenv(env,
10852
"%s=%s",
10853
http_var_name,
10854
conn->request_info.http_headers[i].value);
10855
}
10856
10857
/* Add user-specified variables */
10858
s = conn->dom_ctx->config[CGI_ENVIRONMENT];
10859
while ((s = next_option(s, &var_vec, NULL)) != NULL) {
10860
addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
10861
}
10862
10863
env->var[env->varused] = NULL;
10864
env->buf[env->bufused] = '\0';
10865
10866
return 0;
10867
}
10868
10869
10870
/* Data for CGI process control: PID and number of references */
10871
struct process_control_data {
10872
pid_t pid;
10873
int references;
10874
};
10875
10876
static int
10877
abort_process(void *data)
10878
{
10879
/* Waitpid checks for child status and won't work for a pid that does not
10880
* identify a child of the current process. Thus, if the pid is reused,
10881
* we will not affect a different process. */
10882
struct process_control_data *proc = (struct process_control_data *)data;
10883
int status = 0;
10884
int refs;
10885
pid_t ret_pid;
10886
10887
ret_pid = waitpid(proc->pid, &status, WNOHANG);
10888
if ((ret_pid != (pid_t)-1) && (status == 0)) {
10889
/* Stop child process */
10890
DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
10891
kill(proc->pid, SIGABRT);
10892
10893
/* Wait until process is terminated (don't leave zombies) */
10894
while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
10895
;
10896
} else {
10897
DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
10898
}
10899
/* Dec reference counter */
10900
refs = mg_atomic_dec(&proc->references);
10901
if (refs == 0) {
10902
/* no more references - free data */
10903
mg_free(data);
10904
}
10905
10906
return 0;
10907
}
10908
10909
10910
static void
10911
handle_cgi_request(struct mg_connection *conn, const char *prog)
10912
{
10913
char *buf;
10914
size_t buflen;
10915
int headers_len, data_len, i, truncated;
10916
int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
10917
const char *status, *status_text, *connection_state;
10918
char *pbuf, dir[PATH_MAX], *p;
10919
struct mg_request_info ri;
10920
struct cgi_environment blk;
10921
FILE *in = NULL, *out = NULL, *err = NULL;
10922
struct mg_file fout = STRUCT_FILE_INITIALIZER;
10923
pid_t pid = (pid_t)-1;
10924
struct process_control_data *proc = NULL;
10925
10926
#if defined(USE_TIMERS)
10927
double cgi_timeout = -1.0;
10928
if (conn->dom_ctx->config[CGI_TIMEOUT]) {
10929
/* Get timeout in seconds */
10930
cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
10931
}
10932
#endif
10933
10934
if (conn == NULL) {
10935
return;
10936
}
10937
10938
buf = NULL;
10939
buflen = conn->phys_ctx->max_request_size;
10940
i = prepare_cgi_environment(conn, prog, &blk);
10941
if (i != 0) {
10942
blk.buf = NULL;
10943
blk.var = NULL;
10944
goto done;
10945
}
10946
10947
/* CGI must be executed in its own directory. 'dir' must point to the
10948
* directory containing executable program, 'p' must point to the
10949
* executable program name relative to 'dir'. */
10950
(void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
10951
10952
if (truncated) {
10953
mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
10954
mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
10955
goto done;
10956
}
10957
10958
if ((p = strrchr(dir, '/')) != NULL) {
10959
*p++ = '\0';
10960
} else {
10961
dir[0] = '.';
10962
dir[1] = '\0';
10963
p = (char *)prog;
10964
}
10965
10966
if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
10967
status = strerror(ERRNO);
10968
mg_cry_internal(
10969
conn,
10970
"Error: CGI program \"%s\": Can not create CGI pipes: %s",
10971
prog,
10972
status);
10973
mg_send_http_error(conn,
10974
500,
10975
"Error: Cannot create CGI pipe: %s",
10976
status);
10977
goto done;
10978
}
10979
10980
proc = (struct process_control_data *)
10981
mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
10982
if (proc == NULL) {
10983
mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
10984
mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
10985
goto done;
10986
}
10987
10988
DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
10989
pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
10990
10991
if (pid == (pid_t)-1) {
10992
status = strerror(ERRNO);
10993
mg_cry_internal(
10994
conn,
10995
"Error: CGI program \"%s\": Can not spawn CGI process: %s",
10996
prog,
10997
status);
10998
mg_send_http_error(conn,
10999
500,
11000
"Error: Cannot spawn CGI process [%s]: %s",
11001
prog,
11002
status);
11003
mg_free(proc);
11004
proc = NULL;
11005
goto done;
11006
}
11007
11008
/* Store data in shared process_control_data */
11009
proc->pid = pid;
11010
proc->references = 1;
11011
11012
#if defined(USE_TIMERS)
11013
if (cgi_timeout > 0.0) {
11014
proc->references = 2;
11015
11016
// Start a timer for CGI
11017
timer_add(conn->phys_ctx,
11018
cgi_timeout /* in seconds */,
11019
0.0,
11020
1,
11021
abort_process,
11022
(void *)proc);
11023
}
11024
#endif
11025
11026
/* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
11027
set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
11028
set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
11029
set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
11030
set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
11031
set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
11032
set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
11033
11034
/* Parent closes only one side of the pipes.
11035
* If we don't mark them as closed, close() attempt before
11036
* return from this function throws an exception on Windows.
11037
* Windows does not like when closed descriptor is closed again. */
11038
(void)close(fdin[0]);
11039
(void)close(fdout[1]);
11040
(void)close(fderr[1]);
11041
fdin[0] = fdout[1] = fderr[1] = -1;
11042
11043
if ((in = fdopen(fdin[1], "wb")) == NULL) {
11044
status = strerror(ERRNO);
11045
mg_cry_internal(conn,
11046
"Error: CGI program \"%s\": Can not open stdin: %s",
11047
prog,
11048
status);
11049
mg_send_http_error(conn,
11050
500,
11051
"Error: CGI can not open fdin\nfopen: %s",
11052
status);
11053
goto done;
11054
}
11055
11056
if ((out = fdopen(fdout[0], "rb")) == NULL) {
11057
status = strerror(ERRNO);
11058
mg_cry_internal(conn,
11059
"Error: CGI program \"%s\": Can not open stdout: %s",
11060
prog,
11061
status);
11062
mg_send_http_error(conn,
11063
500,
11064
"Error: CGI can not open fdout\nfopen: %s",
11065
status);
11066
goto done;
11067
}
11068
11069
if ((err = fdopen(fderr[0], "rb")) == NULL) {
11070
status = strerror(ERRNO);
11071
mg_cry_internal(conn,
11072
"Error: CGI program \"%s\": Can not open stderr: %s",
11073
prog,
11074
status);
11075
mg_send_http_error(conn,
11076
500,
11077
"Error: CGI can not open fderr\nfopen: %s",
11078
status);
11079
goto done;
11080
}
11081
11082
setbuf(in, NULL);
11083
setbuf(out, NULL);
11084
setbuf(err, NULL);
11085
fout.access.fp = out;
11086
11087
if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
11088
DEBUG_TRACE("CGI: send body data (%lli)\n",
11089
(signed long long)conn->request_info.content_length);
11090
11091
/* This is a POST/PUT request, or another request with body data. */
11092
if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
11093
/* Error sending the body data */
11094
mg_cry_internal(
11095
conn,
11096
"Error: CGI program \"%s\": Forward body data failed",
11097
prog);
11098
goto done;
11099
}
11100
}
11101
11102
/* Close so child gets an EOF. */
11103
fclose(in);
11104
in = NULL;
11105
fdin[1] = -1;
11106
11107
/* Now read CGI reply into a buffer. We need to set correct
11108
* status code, thus we need to see all HTTP headers first.
11109
* Do not send anything back to client, until we buffer in all
11110
* HTTP headers. */
11111
data_len = 0;
11112
buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
11113
if (buf == NULL) {
11114
mg_send_http_error(conn,
11115
500,
11116
"Error: Not enough memory for CGI buffer (%u bytes)",
11117
(unsigned int)buflen);
11118
mg_cry_internal(
11119
conn,
11120
"Error: CGI program \"%s\": Not enough memory for buffer (%u "
11121
"bytes)",
11122
prog,
11123
(unsigned int)buflen);
11124
goto done;
11125
}
11126
11127
DEBUG_TRACE("CGI: %s", "wait for response");
11128
headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
11129
DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
11130
11131
if (headers_len <= 0) {
11132
11133
/* Could not parse the CGI response. Check if some error message on
11134
* stderr. */
11135
i = pull_all(err, conn, buf, (int)buflen);
11136
if (i > 0) {
11137
/* CGI program explicitly sent an error */
11138
/* Write the error message to the internal log */
11139
mg_cry_internal(conn,
11140
"Error: CGI program \"%s\" sent error "
11141
"message: [%.*s]",
11142
prog,
11143
i,
11144
buf);
11145
/* Don't send the error message back to the client */
11146
mg_send_http_error(conn,
11147
500,
11148
"Error: CGI program \"%s\" failed.",
11149
prog);
11150
} else {
11151
/* CGI program did not explicitly send an error, but a broken
11152
* respon header */
11153
mg_cry_internal(conn,
11154
"Error: CGI program sent malformed or too big "
11155
"(>%u bytes) HTTP headers: [%.*s]",
11156
(unsigned)buflen,
11157
data_len,
11158
buf);
11159
11160
mg_send_http_error(conn,
11161
500,
11162
"Error: CGI program sent malformed or too big "
11163
"(>%u bytes) HTTP headers: [%.*s]",
11164
(unsigned)buflen,
11165
data_len,
11166
buf);
11167
}
11168
11169
/* in both cases, abort processing CGI */
11170
goto done;
11171
}
11172
11173
pbuf = buf;
11174
buf[headers_len - 1] = '\0';
11175
ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
11176
11177
/* Make up and send the status line */
11178
status_text = "OK";
11179
if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
11180
!= NULL) {
11181
conn->status_code = atoi(status);
11182
status_text = status;
11183
while (isdigit(*(const unsigned char *)status_text)
11184
|| *status_text == ' ') {
11185
status_text++;
11186
}
11187
} else if (get_header(ri.http_headers, ri.num_headers, "Location")
11188
!= NULL) {
11189
conn->status_code = 307;
11190
} else {
11191
conn->status_code = 200;
11192
}
11193
connection_state =
11194
get_header(ri.http_headers, ri.num_headers, "Connection");
11195
if (!header_has_option(connection_state, "keep-alive")) {
11196
conn->must_close = 1;
11197
}
11198
11199
DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
11200
11201
(void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
11202
11203
/* Send headers */
11204
for (i = 0; i < ri.num_headers; i++) {
11205
mg_printf(conn,
11206
"%s: %s\r\n",
11207
ri.http_headers[i].name,
11208
ri.http_headers[i].value);
11209
}
11210
mg_write(conn, "\r\n", 2);
11211
11212
/* Send chunk of data that may have been read after the headers */
11213
mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
11214
11215
/* Read the rest of CGI output and send to the client */
11216
DEBUG_TRACE("CGI: %s", "forward all data");
11217
send_file_data(conn, &fout, 0, INT64_MAX);
11218
DEBUG_TRACE("CGI: %s", "all data sent");
11219
11220
done:
11221
mg_free(blk.var);
11222
mg_free(blk.buf);
11223
11224
if (pid != (pid_t)-1) {
11225
abort_process((void *)proc);
11226
}
11227
11228
if (fdin[0] != -1) {
11229
close(fdin[0]);
11230
}
11231
if (fdout[1] != -1) {
11232
close(fdout[1]);
11233
}
11234
11235
if (in != NULL) {
11236
fclose(in);
11237
} else if (fdin[1] != -1) {
11238
close(fdin[1]);
11239
}
11240
11241
if (out != NULL) {
11242
fclose(out);
11243
} else if (fdout[0] != -1) {
11244
close(fdout[0]);
11245
}
11246
11247
if (err != NULL) {
11248
fclose(err);
11249
} else if (fderr[0] != -1) {
11250
close(fderr[0]);
11251
}
11252
11253
if (buf != NULL) {
11254
mg_free(buf);
11255
}
11256
}
11257
#endif /* !NO_CGI */
11258
11259
11260
#if !defined(NO_FILES)
11261
static void
11262
mkcol(struct mg_connection *conn, const char *path)
11263
{
11264
int rc, body_len;
11265
struct de de;
11266
char date[64];
11267
time_t curtime = time(NULL);
11268
11269
if (conn == NULL) {
11270
return;
11271
}
11272
11273
/* TODO (mid): Check the mg_send_http_error situations in this function
11274
*/
11275
11276
memset(&de.file, 0, sizeof(de.file));
11277
if (!mg_stat(conn, path, &de.file)) {
11278
mg_cry_internal(conn,
11279
"%s: mg_stat(%s) failed: %s",
11280
__func__,
11281
path,
11282
strerror(ERRNO));
11283
}
11284
11285
if (de.file.last_modified) {
11286
/* TODO (mid): This check does not seem to make any sense ! */
11287
/* TODO (mid): Add a webdav unit test first, before changing
11288
* anything here. */
11289
mg_send_http_error(
11290
conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11291
return;
11292
}
11293
11294
body_len = conn->data_len - conn->request_len;
11295
if (body_len > 0) {
11296
mg_send_http_error(
11297
conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11298
return;
11299
}
11300
11301
rc = mg_mkdir(conn, path, 0755);
11302
11303
if (rc == 0) {
11304
conn->status_code = 201;
11305
gmt_time_string(date, sizeof(date), &curtime);
11306
mg_printf(conn,
11307
"HTTP/1.1 %d Created\r\n"
11308
"Date: %s\r\n",
11309
conn->status_code,
11310
date);
11311
send_static_cache_header(conn);
11312
send_additional_header(conn);
11313
mg_printf(conn,
11314
"Content-Length: 0\r\n"
11315
"Connection: %s\r\n\r\n",
11316
suggest_connection_header(conn));
11317
} else {
11318
if (errno == EEXIST) {
11319
mg_send_http_error(
11320
conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11321
} else if (errno == EACCES) {
11322
mg_send_http_error(
11323
conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11324
} else if (errno == ENOENT) {
11325
mg_send_http_error(
11326
conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
11327
} else {
11328
mg_send_http_error(
11329
conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
11330
}
11331
}
11332
}
11333
11334
11335
static void
11336
put_file(struct mg_connection *conn, const char *path)
11337
{
11338
struct mg_file file = STRUCT_FILE_INITIALIZER;
11339
const char *range;
11340
int64_t r1, r2;
11341
int rc;
11342
char date[64];
11343
time_t curtime = time(NULL);
11344
11345
if (conn == NULL) {
11346
return;
11347
}
11348
11349
if (mg_stat(conn, path, &file.stat)) {
11350
/* File already exists */
11351
conn->status_code = 200;
11352
11353
if (file.stat.is_directory) {
11354
/* This is an already existing directory,
11355
* so there is nothing to do for the server. */
11356
rc = 0;
11357
11358
} else {
11359
/* File exists and is not a directory. */
11360
/* Can it be replaced? */
11361
11362
#if defined(MG_USE_OPEN_FILE)
11363
if (file.access.membuf != NULL) {
11364
/* This is an "in-memory" file, that can not be replaced */
11365
mg_send_http_error(conn,
11366
405,
11367
"Error: Put not possible\nReplacing %s "
11368
"is not supported",
11369
path);
11370
return;
11371
}
11372
#endif
11373
11374
/* Check if the server may write this file */
11375
if (access(path, W_OK) == 0) {
11376
/* Access granted */
11377
conn->status_code = 200;
11378
rc = 1;
11379
} else {
11380
mg_send_http_error(
11381
conn,
11382
403,
11383
"Error: Put not possible\nReplacing %s is not allowed",
11384
path);
11385
return;
11386
}
11387
}
11388
} else {
11389
/* File should be created */
11390
conn->status_code = 201;
11391
rc = put_dir(conn, path);
11392
}
11393
11394
if (rc == 0) {
11395
/* put_dir returns 0 if path is a directory */
11396
gmt_time_string(date, sizeof(date), &curtime);
11397
mg_printf(conn,
11398
"HTTP/1.1 %d %s\r\n",
11399
conn->status_code,
11400
mg_get_response_code_text(NULL, conn->status_code));
11401
send_no_cache_header(conn);
11402
send_additional_header(conn);
11403
mg_printf(conn,
11404
"Date: %s\r\n"
11405
"Content-Length: 0\r\n"
11406
"Connection: %s\r\n\r\n",
11407
date,
11408
suggest_connection_header(conn));
11409
11410
/* Request to create a directory has been fulfilled successfully.
11411
* No need to put a file. */
11412
return;
11413
}
11414
11415
if (rc == -1) {
11416
/* put_dir returns -1 if the path is too long */
11417
mg_send_http_error(conn,
11418
414,
11419
"Error: Path too long\nput_dir(%s): %s",
11420
path,
11421
strerror(ERRNO));
11422
return;
11423
}
11424
11425
if (rc == -2) {
11426
/* put_dir returns -2 if the directory can not be created */
11427
mg_send_http_error(conn,
11428
500,
11429
"Error: Can not create directory\nput_dir(%s): %s",
11430
path,
11431
strerror(ERRNO));
11432
return;
11433
}
11434
11435
/* A file should be created or overwritten. */
11436
/* Currently CivetWeb does not nead read+write access. */
11437
if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
11438
|| file.access.fp == NULL) {
11439
(void)mg_fclose(&file.access);
11440
mg_send_http_error(conn,
11441
500,
11442
"Error: Can not create file\nfopen(%s): %s",
11443
path,
11444
strerror(ERRNO));
11445
return;
11446
}
11447
11448
fclose_on_exec(&file.access, conn);
11449
range = mg_get_header(conn, "Content-Range");
11450
r1 = r2 = 0;
11451
if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
11452
conn->status_code = 206; /* Partial content */
11453
fseeko(file.access.fp, r1, SEEK_SET);
11454
}
11455
11456
if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
11457
/* forward_body_data failed.
11458
* The error code has already been sent to the client,
11459
* and conn->status_code is already set. */
11460
(void)mg_fclose(&file.access);
11461
return;
11462
}
11463
11464
if (mg_fclose(&file.access) != 0) {
11465
/* fclose failed. This might have different reasons, but a likely
11466
* one is "no space on disk", http 507. */
11467
conn->status_code = 507;
11468
}
11469
11470
gmt_time_string(date, sizeof(date), &curtime);
11471
mg_printf(conn,
11472
"HTTP/1.1 %d %s\r\n",
11473
conn->status_code,
11474
mg_get_response_code_text(NULL, conn->status_code));
11475
send_no_cache_header(conn);
11476
send_additional_header(conn);
11477
mg_printf(conn,
11478
"Date: %s\r\n"
11479
"Content-Length: 0\r\n"
11480
"Connection: %s\r\n\r\n",
11481
date,
11482
suggest_connection_header(conn));
11483
}
11484
11485
11486
static void
11487
delete_file(struct mg_connection *conn, const char *path)
11488
{
11489
struct de de;
11490
memset(&de.file, 0, sizeof(de.file));
11491
if (!mg_stat(conn, path, &de.file)) {
11492
/* mg_stat returns 0 if the file does not exist */
11493
mg_send_http_error(conn,
11494
404,
11495
"Error: Cannot delete file\nFile %s not found",
11496
path);
11497
return;
11498
}
11499
11500
#if 0 /* Ignore if a file in memory is inside a folder */
11501
if (de.access.membuf != NULL) {
11502
/* the file is cached in memory */
11503
mg_send_http_error(
11504
conn,
11505
405,
11506
"Error: Delete not possible\nDeleting %s is not supported",
11507
path);
11508
return;
11509
}
11510
#endif
11511
11512
if (de.file.is_directory) {
11513
if (remove_directory(conn, path)) {
11514
/* Delete is successful: Return 204 without content. */
11515
mg_send_http_error(conn, 204, "%s", "");
11516
} else {
11517
/* Delete is not successful: Return 500 (Server error). */
11518
mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
11519
}
11520
return;
11521
}
11522
11523
/* This is an existing file (not a directory).
11524
* Check if write permission is granted. */
11525
if (access(path, W_OK) != 0) {
11526
/* File is read only */
11527
mg_send_http_error(
11528
conn,
11529
403,
11530
"Error: Delete not possible\nDeleting %s is not allowed",
11531
path);
11532
return;
11533
}
11534
11535
/* Try to delete it. */
11536
if (mg_remove(conn, path) == 0) {
11537
/* Delete was successful: Return 204 without content. */
11538
mg_send_http_error(conn, 204, "%s", "");
11539
} else {
11540
/* Delete not successful (file locked). */
11541
mg_send_http_error(conn,
11542
423,
11543
"Error: Cannot delete file\nremove(%s): %s",
11544
path,
11545
strerror(ERRNO));
11546
}
11547
}
11548
#endif /* !NO_FILES */
11549
11550
11551
static void
11552
send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
11553
11554
11555
static void
11556
do_ssi_include(struct mg_connection *conn,
11557
const char *ssi,
11558
char *tag,
11559
int include_level)
11560
{
11561
char file_name[MG_BUF_LEN], path[512], *p;
11562
struct mg_file file = STRUCT_FILE_INITIALIZER;
11563
size_t len;
11564
int truncated = 0;
11565
11566
if (conn == NULL) {
11567
return;
11568
}
11569
11570
/* sscanf() is safe here, since send_ssi_file() also uses buffer
11571
* of size MG_BUF_LEN to get the tag. So strlen(tag) is
11572
* always < MG_BUF_LEN. */
11573
if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
11574
/* File name is relative to the webserver root */
11575
file_name[511] = 0;
11576
(void)mg_snprintf(conn,
11577
&truncated,
11578
path,
11579
sizeof(path),
11580
"%s/%s",
11581
conn->dom_ctx->config[DOCUMENT_ROOT],
11582
file_name);
11583
11584
} else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
11585
/* File name is relative to the webserver working directory
11586
* or it is absolute system path */
11587
file_name[511] = 0;
11588
(void)
11589
mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
11590
11591
} else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
11592
|| (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
11593
/* File name is relative to the currect document */
11594
file_name[511] = 0;
11595
(void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
11596
11597
if (!truncated) {
11598
if ((p = strrchr(path, '/')) != NULL) {
11599
p[1] = '\0';
11600
}
11601
len = strlen(path);
11602
(void)mg_snprintf(conn,
11603
&truncated,
11604
path + len,
11605
sizeof(path) - len,
11606
"%s",
11607
file_name);
11608
}
11609
11610
} else {
11611
mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
11612
return;
11613
}
11614
11615
if (truncated) {
11616
mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
11617
return;
11618
}
11619
11620
if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
11621
mg_cry_internal(conn,
11622
"Cannot open SSI #include: [%s]: fopen(%s): %s",
11623
tag,
11624
path,
11625
strerror(ERRNO));
11626
} else {
11627
fclose_on_exec(&file.access, conn);
11628
if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
11629
strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
11630
path)
11631
> 0) {
11632
send_ssi_file(conn, path, &file, include_level + 1);
11633
} else {
11634
send_file_data(conn, &file, 0, INT64_MAX);
11635
}
11636
(void)mg_fclose(&file.access); /* Ignore errors for readonly files */
11637
}
11638
}
11639
11640
11641
#if !defined(NO_POPEN)
11642
static void
11643
do_ssi_exec(struct mg_connection *conn, char *tag)
11644
{
11645
char cmd[1024] = "";
11646
struct mg_file file = STRUCT_FILE_INITIALIZER;
11647
11648
if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
11649
mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
11650
} else {
11651
cmd[1023] = 0;
11652
if ((file.access.fp = popen(cmd, "r")) == NULL) {
11653
mg_cry_internal(conn,
11654
"Cannot SSI #exec: [%s]: %s",
11655
cmd,
11656
strerror(ERRNO));
11657
} else {
11658
send_file_data(conn, &file, 0, INT64_MAX);
11659
pclose(file.access.fp);
11660
}
11661
}
11662
}
11663
#endif /* !NO_POPEN */
11664
11665
11666
static int
11667
mg_fgetc(struct mg_file *filep, int offset)
11668
{
11669
(void)offset; /* unused in case MG_USE_OPEN_FILE is set */
11670
11671
if (filep == NULL) {
11672
return EOF;
11673
}
11674
#if defined(MG_USE_OPEN_FILE)
11675
if ((filep->access.membuf != NULL) && (offset >= 0)
11676
&& (((unsigned int)(offset)) < filep->stat.size)) {
11677
return ((const unsigned char *)filep->access.membuf)[offset];
11678
} else /* else block below */
11679
#endif
11680
if (filep->access.fp != NULL) {
11681
return fgetc(filep->access.fp);
11682
} else {
11683
return EOF;
11684
}
11685
}
11686
11687
11688
static void
11689
send_ssi_file(struct mg_connection *conn,
11690
const char *path,
11691
struct mg_file *filep,
11692
int include_level)
11693
{
11694
char buf[MG_BUF_LEN];
11695
int ch, offset, len, in_tag, in_ssi_tag;
11696
11697
if (include_level > 10) {
11698
mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
11699
return;
11700
}
11701
11702
in_tag = in_ssi_tag = len = offset = 0;
11703
11704
/* Read file, byte by byte, and look for SSI include tags */
11705
while ((ch = mg_fgetc(filep, offset++)) != EOF) {
11706
11707
if (in_tag) {
11708
/* We are in a tag, either SSI tag or html tag */
11709
11710
if (ch == '>') {
11711
/* Tag is closing */
11712
buf[len++] = '>';
11713
11714
if (in_ssi_tag) {
11715
/* Handle SSI tag */
11716
buf[len] = 0;
11717
11718
if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
11719
do_ssi_include(conn, path, buf + 12, include_level + 1);
11720
#if !defined(NO_POPEN)
11721
} else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
11722
do_ssi_exec(conn, buf + 9);
11723
#endif /* !NO_POPEN */
11724
} else {
11725
mg_cry_internal(conn,
11726
"%s: unknown SSI "
11727
"command: \"%s\"",
11728
path,
11729
buf);
11730
}
11731
len = 0;
11732
in_ssi_tag = in_tag = 0;
11733
11734
} else {
11735
/* Not an SSI tag */
11736
/* Flush buffer */
11737
(void)mg_write(conn, buf, (size_t)len);
11738
len = 0;
11739
in_tag = 0;
11740
}
11741
11742
} else {
11743
/* Tag is still open */
11744
buf[len++] = (char)(ch & 0xff);
11745
11746
if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
11747
/* All SSI tags start with <!--# */
11748
in_ssi_tag = 1;
11749
}
11750
11751
if ((len + 2) > (int)sizeof(buf)) {
11752
/* Tag to long for buffer */
11753
mg_cry_internal(conn, "%s: tag is too large", path);
11754
return;
11755
}
11756
}
11757
11758
} else {
11759
11760
/* We are not in a tag yet. */
11761
if (ch == '<') {
11762
/* Tag is opening */
11763
in_tag = 1;
11764
11765
if (len > 0) {
11766
/* Flush current buffer.
11767
* Buffer is filled with "len" bytes. */
11768
(void)mg_write(conn, buf, (size_t)len);
11769
}
11770
/* Store the < */
11771
len = 1;
11772
buf[0] = '<';
11773
11774
} else {
11775
/* No Tag */
11776
/* Add data to buffer */
11777
buf[len++] = (char)(ch & 0xff);
11778
/* Flush if buffer is full */
11779
if (len == (int)sizeof(buf)) {
11780
mg_write(conn, buf, (size_t)len);
11781
len = 0;
11782
}
11783
}
11784
}
11785
}
11786
11787
/* Send the rest of buffered data */
11788
if (len > 0) {
11789
mg_write(conn, buf, (size_t)len);
11790
}
11791
}
11792
11793
11794
static void
11795
handle_ssi_file_request(struct mg_connection *conn,
11796
const char *path,
11797
struct mg_file *filep)
11798
{
11799
char date[64];
11800
time_t curtime = time(NULL);
11801
const char *cors1, *cors2, *cors3;
11802
11803
if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
11804
return;
11805
}
11806
11807
if (mg_get_header(conn, "Origin")) {
11808
/* Cross-origin resource sharing (CORS). */
11809
cors1 = "Access-Control-Allow-Origin: ";
11810
cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
11811
cors3 = "\r\n";
11812
} else {
11813
cors1 = cors2 = cors3 = "";
11814
}
11815
11816
if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
11817
/* File exists (precondition for calling this function),
11818
* but can not be opened by the server. */
11819
mg_send_http_error(conn,
11820
500,
11821
"Error: Cannot read file\nfopen(%s): %s",
11822
path,
11823
strerror(ERRNO));
11824
} else {
11825
conn->must_close = 1;
11826
gmt_time_string(date, sizeof(date), &curtime);
11827
fclose_on_exec(&filep->access, conn);
11828
mg_printf(conn, "HTTP/1.1 200 OK\r\n");
11829
send_no_cache_header(conn);
11830
send_additional_header(conn);
11831
mg_printf(conn,
11832
"%s%s%s"
11833
"Date: %s\r\n"
11834
"Content-Type: text/html\r\n"
11835
"Connection: %s\r\n\r\n",
11836
cors1,
11837
cors2,
11838
cors3,
11839
date,
11840
suggest_connection_header(conn));
11841
send_ssi_file(conn, path, filep, 0);
11842
(void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
11843
}
11844
}
11845
11846
11847
#if !defined(NO_FILES)
11848
static void
11849
send_options(struct mg_connection *conn)
11850
{
11851
char date[64];
11852
time_t curtime = time(NULL);
11853
11854
if (!conn) {
11855
return;
11856
}
11857
11858
conn->status_code = 200;
11859
conn->must_close = 1;
11860
gmt_time_string(date, sizeof(date), &curtime);
11861
11862
/* We do not set a "Cache-Control" header here, but leave the default.
11863
* Since browsers do not send an OPTIONS request, we can not test the
11864
* effect anyway. */
11865
mg_printf(conn,
11866
"HTTP/1.1 200 OK\r\n"
11867
"Date: %s\r\n"
11868
"Connection: %s\r\n"
11869
"Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
11870
"PROPFIND, MKCOL\r\n"
11871
"DAV: 1\r\n",
11872
date,
11873
suggest_connection_header(conn));
11874
send_additional_header(conn);
11875
mg_printf(conn, "\r\n");
11876
}
11877
11878
11879
/* Writes PROPFIND properties for a collection element */
11880
static void
11881
print_props(struct mg_connection *conn,
11882
const char *uri,
11883
struct mg_file_stat *filep)
11884
{
11885
char mtime[64];
11886
11887
if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
11888
return;
11889
}
11890
11891
gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
11892
mg_printf(conn,
11893
"<d:response>"
11894
"<d:href>%s</d:href>"
11895
"<d:propstat>"
11896
"<d:prop>"
11897
"<d:resourcetype>%s</d:resourcetype>"
11898
"<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
11899
"<d:getlastmodified>%s</d:getlastmodified>"
11900
"</d:prop>"
11901
"<d:status>HTTP/1.1 200 OK</d:status>"
11902
"</d:propstat>"
11903
"</d:response>\n",
11904
uri,
11905
filep->is_directory ? "<d:collection/>" : "",
11906
filep->size,
11907
mtime);
11908
}
11909
11910
11911
static int
11912
print_dav_dir_entry(struct de *de, void *data)
11913
{
11914
char href[PATH_MAX];
11915
int truncated;
11916
11917
struct mg_connection *conn = (struct mg_connection *)data;
11918
if (!de || !conn) {
11919
return -1;
11920
}
11921
mg_snprintf(conn,
11922
&truncated,
11923
href,
11924
sizeof(href),
11925
"%s%s",
11926
conn->request_info.local_uri,
11927
de->file_name);
11928
11929
if (!truncated) {
11930
size_t href_encoded_size;
11931
char *href_encoded;
11932
11933
href_encoded_size = PATH_MAX * 3; /* worst case */
11934
href_encoded = (char *)mg_malloc(href_encoded_size);
11935
if (href_encoded == NULL) {
11936
return -1;
11937
}
11938
mg_url_encode(href, href_encoded, href_encoded_size);
11939
print_props(conn, href_encoded, &de->file);
11940
mg_free(href_encoded);
11941
}
11942
11943
return 0;
11944
}
11945
11946
11947
static void
11948
handle_propfind(struct mg_connection *conn,
11949
const char *path,
11950
struct mg_file_stat *filep)
11951
{
11952
const char *depth = mg_get_header(conn, "Depth");
11953
char date[64];
11954
time_t curtime = time(NULL);
11955
11956
gmt_time_string(date, sizeof(date), &curtime);
11957
11958
if (!conn || !path || !filep || !conn->dom_ctx) {
11959
return;
11960
}
11961
11962
conn->must_close = 1;
11963
conn->status_code = 207;
11964
mg_printf(conn,
11965
"HTTP/1.1 207 Multi-Status\r\n"
11966
"Date: %s\r\n",
11967
date);
11968
send_static_cache_header(conn);
11969
send_additional_header(conn);
11970
mg_printf(conn,
11971
"Connection: %s\r\n"
11972
"Content-Type: text/xml; charset=utf-8\r\n\r\n",
11973
suggest_connection_header(conn));
11974
11975
mg_printf(conn,
11976
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
11977
"<d:multistatus xmlns:d='DAV:'>\n");
11978
11979
/* Print properties for the requested resource itself */
11980
print_props(conn, conn->request_info.local_uri, filep);
11981
11982
/* If it is a directory, print directory entries too if Depth is not 0
11983
*/
11984
if (filep->is_directory
11985
&& !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
11986
"yes")
11987
&& ((depth == NULL) || (strcmp(depth, "0") != 0))) {
11988
scan_directory(conn, path, conn, &print_dav_dir_entry);
11989
}
11990
11991
mg_printf(conn, "%s\n", "</d:multistatus>");
11992
}
11993
#endif
11994
11995
void
11996
mg_lock_connection(struct mg_connection *conn)
11997
{
11998
if (conn) {
11999
(void)pthread_mutex_lock(&conn->mutex);
12000
}
12001
}
12002
12003
void
12004
mg_unlock_connection(struct mg_connection *conn)
12005
{
12006
if (conn) {
12007
(void)pthread_mutex_unlock(&conn->mutex);
12008
}
12009
}
12010
12011
void
12012
mg_lock_context(struct mg_context *ctx)
12013
{
12014
if (ctx) {
12015
(void)pthread_mutex_lock(&ctx->nonce_mutex);
12016
}
12017
}
12018
12019
void
12020
mg_unlock_context(struct mg_context *ctx)
12021
{
12022
if (ctx) {
12023
(void)pthread_mutex_unlock(&ctx->nonce_mutex);
12024
}
12025
}
12026
12027
12028
#if defined(USE_LUA)
12029
#include "mod_lua.inl"
12030
#endif /* USE_LUA */
12031
12032
#if defined(USE_DUKTAPE)
12033
#include "mod_duktape.inl"
12034
#endif /* USE_DUKTAPE */
12035
12036
#if defined(USE_WEBSOCKET)
12037
12038
#if !defined(NO_SSL_DL)
12039
#define SHA_API static
12040
#include "sha1.inl"
12041
#endif
12042
12043
static int
12044
send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
12045
{
12046
static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
12047
char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
12048
SHA_CTX sha_ctx;
12049
int truncated;
12050
12051
/* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
12052
mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
12053
if (truncated) {
12054
conn->must_close = 1;
12055
return 0;
12056
}
12057
12058
DEBUG_TRACE("%s", "Send websocket handshake");
12059
12060
SHA1_Init(&sha_ctx);
12061
SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
12062
SHA1_Final((unsigned char *)sha, &sha_ctx);
12063
base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
12064
mg_printf(conn,
12065
"HTTP/1.1 101 Switching Protocols\r\n"
12066
"Upgrade: websocket\r\n"
12067
"Connection: Upgrade\r\n"
12068
"Sec-WebSocket-Accept: %s\r\n",
12069
b64_sha);
12070
if (conn->request_info.acceptedWebSocketSubprotocol) {
12071
mg_printf(conn,
12072
"Sec-WebSocket-Protocol: %s\r\n\r\n",
12073
conn->request_info.acceptedWebSocketSubprotocol);
12074
} else {
12075
mg_printf(conn, "%s", "\r\n");
12076
}
12077
12078
return 1;
12079
}
12080
12081
12082
#if !defined(MG_MAX_UNANSWERED_PING)
12083
/* Configuration of the maximum number of websocket PINGs that might
12084
* stay unanswered before the connection is considered broken.
12085
* Note: The name of this define may still change (until it is
12086
* defined as a compile parameter in a documentation).
12087
*/
12088
#define MG_MAX_UNANSWERED_PING (5)
12089
#endif
12090
12091
12092
static void
12093
read_websocket(struct mg_connection *conn,
12094
mg_websocket_data_handler ws_data_handler,
12095
void *callback_data)
12096
{
12097
/* Pointer to the beginning of the portion of the incoming websocket
12098
* message queue.
12099
* The original websocket upgrade request is never removed, so the queue
12100
* begins after it. */
12101
unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
12102
int n, error, exit_by_callback;
12103
int ret;
12104
12105
/* body_len is the length of the entire queue in bytes
12106
* len is the length of the current message
12107
* data_len is the length of the current message's data payload
12108
* header_len is the length of the current message's header */
12109
size_t i, len, mask_len = 0, header_len, body_len;
12110
uint64_t data_len = 0;
12111
12112
/* "The masking key is a 32-bit value chosen at random by the client."
12113
* http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
12114
*/
12115
unsigned char mask[4];
12116
12117
/* data points to the place where the message is stored when passed to
12118
* the websocket_data callback. This is either mem on the stack, or a
12119
* dynamically allocated buffer if it is too large. */
12120
unsigned char mem[4096];
12121
unsigned char mop; /* mask flag and opcode */
12122
12123
12124
/* Variables used for connection monitoring */
12125
double timeout = -1.0;
12126
int enable_ping_pong = 0;
12127
int ping_count = 0;
12128
12129
if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
12130
enable_ping_pong =
12131
!mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
12132
"yes");
12133
}
12134
12135
if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
12136
timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
12137
}
12138
if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
12139
timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
12140
}
12141
12142
/* Enter data processing loop */
12143
DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
12144
conn->request_info.remote_addr,
12145
conn->request_info.remote_port);
12146
conn->in_websocket_handling = 1;
12147
mg_set_thread_name("wsock");
12148
12149
/* Loop continuously, reading messages from the socket, invoking the
12150
* callback, and waiting repeatedly until an error occurs. */
12151
while (!conn->phys_ctx->stop_flag && !conn->must_close) {
12152
header_len = 0;
12153
DEBUG_ASSERT(conn->data_len >= conn->request_len);
12154
if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
12155
len = buf[1] & 127;
12156
mask_len = (buf[1] & 128) ? 4 : 0;
12157
if ((len < 126) && (body_len >= mask_len)) {
12158
/* inline 7-bit length field */
12159
data_len = len;
12160
header_len = 2 + mask_len;
12161
} else if ((len == 126) && (body_len >= (4 + mask_len))) {
12162
/* 16-bit length field */
12163
header_len = 4 + mask_len;
12164
data_len = ((((size_t)buf[2]) << 8) + buf[3]);
12165
} else if (body_len >= (10 + mask_len)) {
12166
/* 64-bit length field */
12167
uint32_t l1, l2;
12168
memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
12169
memcpy(&l2, &buf[6], 4);
12170
header_len = 10 + mask_len;
12171
data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
12172
12173
if (data_len > (uint64_t)0x7FFF0000ul) {
12174
/* no can do */
12175
mg_cry_internal(
12176
conn,
12177
"%s",
12178
"websocket out of memory; closing connection");
12179
break;
12180
}
12181
}
12182
}
12183
12184
if ((header_len > 0) && (body_len >= header_len)) {
12185
/* Allocate space to hold websocket payload */
12186
unsigned char *data = mem;
12187
12188
if ((size_t)data_len > (size_t)sizeof(mem)) {
12189
data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
12190
conn->phys_ctx);
12191
if (data == NULL) {
12192
/* Allocation failed, exit the loop and then close the
12193
* connection */
12194
mg_cry_internal(
12195
conn,
12196
"%s",
12197
"websocket out of memory; closing connection");
12198
break;
12199
}
12200
}
12201
12202
/* Copy the mask before we shift the queue and destroy it */
12203
if (mask_len > 0) {
12204
memcpy(mask, buf + header_len - mask_len, sizeof(mask));
12205
} else {
12206
memset(mask, 0, sizeof(mask));
12207
}
12208
12209
/* Read frame payload from the first message in the queue into
12210
* data and advance the queue by moving the memory in place. */
12211
DEBUG_ASSERT(body_len >= header_len);
12212
if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
12213
mop = buf[0]; /* current mask and opcode */
12214
/* Overflow case */
12215
len = body_len - header_len;
12216
memcpy(data, buf + header_len, len);
12217
error = 0;
12218
while ((uint64_t)len < data_len) {
12219
n = pull_inner(NULL,
12220
conn,
12221
(char *)(data + len),
12222
(int)(data_len - len),
12223
timeout);
12224
if (n <= -2) {
12225
error = 1;
12226
break;
12227
} else if (n > 0) {
12228
len += (size_t)n;
12229
} else {
12230
/* Timeout: should retry */
12231
/* TODO: retry condition */
12232
}
12233
}
12234
if (error) {
12235
mg_cry_internal(
12236
conn,
12237
"%s",
12238
"Websocket pull failed; closing connection");
12239
if (data != mem) {
12240
mg_free(data);
12241
}
12242
break;
12243
}
12244
12245
conn->data_len = conn->request_len;
12246
12247
} else {
12248
12249
mop = buf[0]; /* current mask and opcode, overwritten by
12250
* memmove() */
12251
12252
/* Length of the message being read at the front of the
12253
* queue. Cast to 31 bit is OK, since we limited
12254
* data_len before. */
12255
len = (size_t)data_len + header_len;
12256
12257
/* Copy the data payload into the data pointer for the
12258
* callback. Cast to 31 bit is OK, since we
12259
* limited data_len */
12260
memcpy(data, buf + header_len, (size_t)data_len);
12261
12262
/* Move the queue forward len bytes */
12263
memmove(buf, buf + len, body_len - len);
12264
12265
/* Mark the queue as advanced */
12266
conn->data_len -= (int)len;
12267
}
12268
12269
/* Apply mask if necessary */
12270
if (mask_len > 0) {
12271
for (i = 0; i < (size_t)data_len; i++) {
12272
data[i] ^= mask[i & 3];
12273
}
12274
}
12275
12276
exit_by_callback = 0;
12277
if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
12278
/* filter PONG messages */
12279
DEBUG_TRACE("PONG from %s:%u",
12280
conn->request_info.remote_addr,
12281
conn->request_info.remote_port);
12282
/* No unanwered PINGs left */
12283
ping_count = 0;
12284
} else if (enable_ping_pong
12285
&& ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
12286
/* reply PING messages */
12287
DEBUG_TRACE("Reply PING from %s:%u",
12288
conn->request_info.remote_addr,
12289
conn->request_info.remote_port);
12290
ret = mg_websocket_write(conn,
12291
MG_WEBSOCKET_OPCODE_PONG,
12292
(char *)data,
12293
(size_t)data_len);
12294
if (ret <= 0) {
12295
/* Error: send failed */
12296
DEBUG_TRACE("Reply PONG failed (%i)", ret);
12297
break;
12298
}
12299
12300
12301
} else {
12302
/* Exit the loop if callback signals to exit (server side),
12303
* or "connection close" opcode received (client side). */
12304
if ((ws_data_handler != NULL)
12305
&& !ws_data_handler(conn,
12306
mop,
12307
(char *)data,
12308
(size_t)data_len,
12309
callback_data)) {
12310
exit_by_callback = 1;
12311
}
12312
}
12313
12314
/* It a buffer has been allocated, free it again */
12315
if (data != mem) {
12316
mg_free(data);
12317
}
12318
12319
if (exit_by_callback) {
12320
DEBUG_TRACE("Callback requests to close connection from %s:%u",
12321
conn->request_info.remote_addr,
12322
conn->request_info.remote_port);
12323
break;
12324
}
12325
if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
12326
/* Opcode == 8, connection close */
12327
DEBUG_TRACE("Message requests to close connection from %s:%u",
12328
conn->request_info.remote_addr,
12329
conn->request_info.remote_port);
12330
break;
12331
}
12332
12333
/* Not breaking the loop, process next websocket frame. */
12334
} else {
12335
/* Read from the socket into the next available location in the
12336
* message queue. */
12337
n = pull_inner(NULL,
12338
conn,
12339
conn->buf + conn->data_len,
12340
conn->buf_size - conn->data_len,
12341
timeout);
12342
if (n <= -2) {
12343
/* Error, no bytes read */
12344
DEBUG_TRACE("PULL from %s:%u failed",
12345
conn->request_info.remote_addr,
12346
conn->request_info.remote_port);
12347
break;
12348
}
12349
if (n > 0) {
12350
conn->data_len += n;
12351
/* Reset open PING count */
12352
ping_count = 0;
12353
} else {
12354
if (!conn->phys_ctx->stop_flag && !conn->must_close) {
12355
if (ping_count > MG_MAX_UNANSWERED_PING) {
12356
/* Stop sending PING */
12357
DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
12358
"- closing connection",
12359
ping_count,
12360
conn->request_info.remote_addr,
12361
conn->request_info.remote_port);
12362
break;
12363
}
12364
if (enable_ping_pong) {
12365
/* Send Websocket PING message */
12366
DEBUG_TRACE("PING to %s:%u",
12367
conn->request_info.remote_addr,
12368
conn->request_info.remote_port);
12369
ret = mg_websocket_write(conn,
12370
MG_WEBSOCKET_OPCODE_PING,
12371
NULL,
12372
0);
12373
12374
if (ret <= 0) {
12375
/* Error: send failed */
12376
DEBUG_TRACE("Send PING failed (%i)", ret);
12377
break;
12378
}
12379
ping_count++;
12380
}
12381
}
12382
/* Timeout: should retry */
12383
/* TODO: get timeout def */
12384
}
12385
}
12386
}
12387
12388
/* Leave data processing loop */
12389
mg_set_thread_name("worker");
12390
conn->in_websocket_handling = 0;
12391
DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
12392
conn->request_info.remote_addr,
12393
conn->request_info.remote_port);
12394
}
12395
12396
12397
static int
12398
mg_websocket_write_exec(struct mg_connection *conn,
12399
int opcode,
12400
const char *data,
12401
size_t dataLen,
12402
uint32_t masking_key)
12403
{
12404
unsigned char header[14];
12405
size_t headerLen;
12406
int retval;
12407
12408
#if defined(GCC_DIAGNOSTIC)
12409
/* Disable spurious conversion warning for GCC */
12410
#pragma GCC diagnostic push
12411
#pragma GCC diagnostic ignored "-Wconversion"
12412
#endif
12413
12414
header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
12415
12416
#if defined(GCC_DIAGNOSTIC)
12417
#pragma GCC diagnostic pop
12418
#endif
12419
12420
/* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
12421
if (dataLen < 126) {
12422
/* inline 7-bit length field */
12423
header[1] = (unsigned char)dataLen;
12424
headerLen = 2;
12425
} else if (dataLen <= 0xFFFF) {
12426
/* 16-bit length field */
12427
uint16_t len = htons((uint16_t)dataLen);
12428
header[1] = 126;
12429
memcpy(header + 2, &len, 2);
12430
headerLen = 4;
12431
} else {
12432
/* 64-bit length field */
12433
uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
12434
uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
12435
header[1] = 127;
12436
memcpy(header + 2, &len1, 4);
12437
memcpy(header + 6, &len2, 4);
12438
headerLen = 10;
12439
}
12440
12441
if (masking_key) {
12442
/* add mask */
12443
header[1] |= 0x80;
12444
memcpy(header + headerLen, &masking_key, 4);
12445
headerLen += 4;
12446
}
12447
12448
/* Note that POSIX/Winsock's send() is threadsafe
12449
* http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
12450
* but mongoose's mg_printf/mg_write is not (because of the loop in
12451
* push(), although that is only a problem if the packet is large or
12452
* outgoing buffer is full). */
12453
12454
/* TODO: Check if this lock should be moved to user land.
12455
* Currently the server sets this lock for websockets, but
12456
* not for any other connection. It must be set for every
12457
* conn read/written by more than one thread, no matter if
12458
* it is a websocket or regular connection. */
12459
(void)mg_lock_connection(conn);
12460
12461
retval = mg_write(conn, header, headerLen);
12462
if (retval != (int)headerLen) {
12463
/* Did not send complete header */
12464
retval = -1;
12465
} else {
12466
if (dataLen > 0) {
12467
retval = mg_write(conn, data, dataLen);
12468
}
12469
/* if dataLen == 0, the header length (2) is returned */
12470
}
12471
12472
/* TODO: Remove this unlock as well, when lock is removed. */
12473
mg_unlock_connection(conn);
12474
12475
return retval;
12476
}
12477
12478
int
12479
mg_websocket_write(struct mg_connection *conn,
12480
int opcode,
12481
const char *data,
12482
size_t dataLen)
12483
{
12484
return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
12485
}
12486
12487
12488
static void
12489
mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
12490
{
12491
size_t i = 0;
12492
12493
i = 0;
12494
if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
12495
/* Convert in 32 bit words, if data is 4 byte aligned */
12496
while (i < (in_len - 3)) {
12497
*(uint32_t *)(void *)(out + i) =
12498
*(uint32_t *)(void *)(in + i) ^ masking_key;
12499
i += 4;
12500
}
12501
}
12502
if (i != in_len) {
12503
/* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
12504
while (i < in_len) {
12505
*(uint8_t *)(void *)(out + i) =
12506
*(uint8_t *)(void *)(in + i)
12507
^ *(((uint8_t *)&masking_key) + (i % 4));
12508
i++;
12509
}
12510
}
12511
}
12512
12513
12514
int
12515
mg_websocket_client_write(struct mg_connection *conn,
12516
int opcode,
12517
const char *data,
12518
size_t dataLen)
12519
{
12520
int retval = -1;
12521
char *masked_data =
12522
(char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
12523
uint32_t masking_key = 0;
12524
12525
if (masked_data == NULL) {
12526
/* Return -1 in an error case */
12527
mg_cry_internal(conn,
12528
"%s",
12529
"Cannot allocate buffer for masked websocket response: "
12530
"Out of memory");
12531
return -1;
12532
}
12533
12534
do {
12535
/* Get a masking key - but not 0 */
12536
masking_key = (uint32_t)get_random();
12537
} while (masking_key == 0);
12538
12539
mask_data(data, dataLen, masking_key, masked_data);
12540
12541
retval = mg_websocket_write_exec(
12542
conn, opcode, masked_data, dataLen, masking_key);
12543
mg_free(masked_data);
12544
12545
return retval;
12546
}
12547
12548
12549
static void
12550
handle_websocket_request(struct mg_connection *conn,
12551
const char *path,
12552
int is_callback_resource,
12553
struct mg_websocket_subprotocols *subprotocols,
12554
mg_websocket_connect_handler ws_connect_handler,
12555
mg_websocket_ready_handler ws_ready_handler,
12556
mg_websocket_data_handler ws_data_handler,
12557
mg_websocket_close_handler ws_close_handler,
12558
void *cbData)
12559
{
12560
const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
12561
const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
12562
ptrdiff_t lua_websock = 0;
12563
12564
#if !defined(USE_LUA)
12565
(void)path;
12566
#endif
12567
12568
/* Step 1: Check websocket protocol version. */
12569
/* Step 1.1: Check Sec-WebSocket-Key. */
12570
if (!websock_key) {
12571
/* The RFC standard version (https://tools.ietf.org/html/rfc6455)
12572
* requires a Sec-WebSocket-Key header.
12573
*/
12574
/* It could be the hixie draft version
12575
* (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
12576
*/
12577
const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
12578
const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
12579
char key3[8];
12580
12581
if ((key1 != NULL) && (key2 != NULL)) {
12582
/* This version uses 8 byte body data in a GET request */
12583
conn->content_len = 8;
12584
if (8 == mg_read(conn, key3, 8)) {
12585
/* This is the hixie version */
12586
mg_send_http_error(conn,
12587
426,
12588
"%s",
12589
"Protocol upgrade to RFC 6455 required");
12590
return;
12591
}
12592
}
12593
/* This is an unknown version */
12594
mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
12595
return;
12596
}
12597
12598
/* Step 1.2: Check websocket protocol version. */
12599
/* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
12600
if ((version == NULL) || (strcmp(version, "13") != 0)) {
12601
/* Reject wrong versions */
12602
mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
12603
return;
12604
}
12605
12606
/* Step 1.3: Could check for "Host", but we do not really nead this
12607
* value for anything, so just ignore it. */
12608
12609
/* Step 2: If a callback is responsible, call it. */
12610
if (is_callback_resource) {
12611
/* Step 2.1 check and select subprotocol */
12612
const char *protocols[64]; // max 64 headers
12613
int nbSubprotocolHeader = get_req_headers(&conn->request_info,
12614
"Sec-WebSocket-Protocol",
12615
protocols,
12616
64);
12617
if ((nbSubprotocolHeader > 0) && subprotocols) {
12618
int cnt = 0;
12619
int idx;
12620
unsigned long len;
12621
const char *sep, *curSubProtocol,
12622
*acceptedWebSocketSubprotocol = NULL;
12623
12624
12625
/* look for matching subprotocol */
12626
do {
12627
const char *protocol = protocols[cnt];
12628
12629
do {
12630
sep = strchr(protocol, ',');
12631
curSubProtocol = protocol;
12632
len = sep ? (unsigned long)(sep - protocol)
12633
: (unsigned long)strlen(protocol);
12634
while (sep && isspace(*++sep))
12635
; // ignore leading whitespaces
12636
protocol = sep;
12637
12638
12639
for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
12640
if ((strlen(subprotocols->subprotocols[idx]) == len)
12641
&& (strncmp(curSubProtocol,
12642
subprotocols->subprotocols[idx],
12643
len)
12644
== 0)) {
12645
acceptedWebSocketSubprotocol =
12646
subprotocols->subprotocols[idx];
12647
break;
12648
}
12649
}
12650
} while (sep && !acceptedWebSocketSubprotocol);
12651
} while (++cnt < nbSubprotocolHeader
12652
&& !acceptedWebSocketSubprotocol);
12653
12654
conn->request_info.acceptedWebSocketSubprotocol =
12655
acceptedWebSocketSubprotocol;
12656
12657
} else if (nbSubprotocolHeader > 0) {
12658
/* keep legacy behavior */
12659
const char *protocol = protocols[0];
12660
12661
/* The protocol is a comma separated list of names. */
12662
/* The server must only return one value from this list. */
12663
/* First check if it is a list or just a single value. */
12664
const char *sep = strrchr(protocol, ',');
12665
if (sep == NULL) {
12666
/* Just a single protocol -> accept it. */
12667
conn->request_info.acceptedWebSocketSubprotocol = protocol;
12668
} else {
12669
/* Multiple protocols -> accept the last one. */
12670
/* This is just a quick fix if the client offers multiple
12671
* protocols. The handler should have a list of accepted
12672
* protocols on his own
12673
* and use it to select one protocol among those the client
12674
* has
12675
* offered.
12676
*/
12677
while (isspace(*++sep)) {
12678
; /* ignore leading whitespaces */
12679
}
12680
conn->request_info.acceptedWebSocketSubprotocol = sep;
12681
}
12682
}
12683
12684
if ((ws_connect_handler != NULL)
12685
&& (ws_connect_handler(conn, cbData) != 0)) {
12686
/* C callback has returned non-zero, do not proceed with
12687
* handshake.
12688
*/
12689
/* Note that C callbacks are no longer called when Lua is
12690
* responsible, so C can no longer filter callbacks for Lua. */
12691
return;
12692
}
12693
}
12694
12695
#if defined(USE_LUA)
12696
/* Step 3: No callback. Check if Lua is responsible. */
12697
else {
12698
/* Step 3.1: Check if Lua is responsible. */
12699
if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
12700
lua_websock = match_prefix(
12701
conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
12702
strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
12703
path);
12704
}
12705
12706
if (lua_websock) {
12707
/* Step 3.2: Lua is responsible: call it. */
12708
conn->lua_websocket_state = lua_websocket_new(path, conn);
12709
if (!conn->lua_websocket_state) {
12710
/* Lua rejected the new client */
12711
return;
12712
}
12713
}
12714
}
12715
#endif
12716
12717
/* Step 4: Check if there is a responsible websocket handler. */
12718
if (!is_callback_resource && !lua_websock) {
12719
/* There is no callback, and Lua is not responsible either. */
12720
/* Reply with a 404 Not Found. We are still at a standard
12721
* HTTP request here, before the websocket handshake, so
12722
* we can still send standard HTTP error replies. */
12723
mg_send_http_error(conn, 404, "%s", "Not found");
12724
return;
12725
}
12726
12727
/* Step 5: The websocket connection has been accepted */
12728
if (!send_websocket_handshake(conn, websock_key)) {
12729
mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
12730
return;
12731
}
12732
12733
/* Step 6: Call the ready handler */
12734
if (is_callback_resource) {
12735
if (ws_ready_handler != NULL) {
12736
ws_ready_handler(conn, cbData);
12737
}
12738
#if defined(USE_LUA)
12739
} else if (lua_websock) {
12740
if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
12741
/* the ready handler returned false */
12742
return;
12743
}
12744
#endif
12745
}
12746
12747
/* Step 7: Enter the read loop */
12748
if (is_callback_resource) {
12749
read_websocket(conn, ws_data_handler, cbData);
12750
#if defined(USE_LUA)
12751
} else if (lua_websock) {
12752
read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
12753
#endif
12754
}
12755
12756
/* Step 8: Call the close handler */
12757
if (ws_close_handler) {
12758
ws_close_handler(conn, cbData);
12759
}
12760
}
12761
12762
12763
static int
12764
is_websocket_protocol(const struct mg_connection *conn)
12765
{
12766
const char *upgrade, *connection;
12767
12768
/* A websocket protocoll has the following HTTP headers:
12769
*
12770
* Connection: Upgrade
12771
* Upgrade: Websocket
12772
*/
12773
12774
upgrade = mg_get_header(conn, "Upgrade");
12775
if (upgrade == NULL) {
12776
return 0; /* fail early, don't waste time checking other header
12777
* fields
12778
*/
12779
}
12780
if (!mg_strcasestr(upgrade, "websocket")) {
12781
return 0;
12782
}
12783
12784
connection = mg_get_header(conn, "Connection");
12785
if (connection == NULL) {
12786
return 0;
12787
}
12788
if (!mg_strcasestr(connection, "upgrade")) {
12789
return 0;
12790
}
12791
12792
/* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
12793
* "Sec-WebSocket-Version" are also required.
12794
* Don't check them here, since even an unsupported websocket protocol
12795
* request still IS a websocket request (in contrast to a standard HTTP
12796
* request). It will fail later in handle_websocket_request.
12797
*/
12798
12799
return 1;
12800
}
12801
#endif /* !USE_WEBSOCKET */
12802
12803
12804
static int
12805
isbyte(int n)
12806
{
12807
return (n >= 0) && (n <= 255);
12808
}
12809
12810
12811
static int
12812
parse_net(const char *spec, uint32_t *net, uint32_t *mask)
12813
{
12814
int n, a, b, c, d, slash = 32, len = 0;
12815
12816
if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
12817
|| (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
12818
&& isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
12819
&& (slash < 33)) {
12820
len = n;
12821
*net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
12822
| (uint32_t)d;
12823
*mask = slash ? (0xffffffffU << (32 - slash)) : 0;
12824
}
12825
12826
return len;
12827
}
12828
12829
12830
static int
12831
set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
12832
{
12833
int throttle = 0;
12834
struct vec vec, val;
12835
uint32_t net, mask;
12836
char mult;
12837
double v;
12838
12839
while ((spec = next_option(spec, &vec, &val)) != NULL) {
12840
mult = ',';
12841
if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
12842
|| (v < 0)
12843
|| ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
12844
&& (mult != ','))) {
12845
continue;
12846
}
12847
v *= (lowercase(&mult) == 'k')
12848
? 1024
12849
: ((lowercase(&mult) == 'm') ? 1048576 : 1);
12850
if (vec.len == 1 && vec.ptr[0] == '*') {
12851
throttle = (int)v;
12852
} else if (parse_net(vec.ptr, &net, &mask) > 0) {
12853
if ((remote_ip & mask) == net) {
12854
throttle = (int)v;
12855
}
12856
} else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
12857
throttle = (int)v;
12858
}
12859
}
12860
12861
return throttle;
12862
}
12863
12864
12865
static uint32_t
12866
get_remote_ip(const struct mg_connection *conn)
12867
{
12868
if (!conn) {
12869
return 0;
12870
}
12871
return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
12872
}
12873
12874
12875
/* The mg_upload function is superseeded by mg_handle_form_request. */
12876
#include "handle_form.inl"
12877
12878
12879
#if defined(MG_LEGACY_INTERFACE)
12880
/* Implement the deprecated mg_upload function by calling the new
12881
* mg_handle_form_request function. While mg_upload could only handle
12882
* HTML forms sent as POST request in multipart/form-data format
12883
* containing only file input elements, mg_handle_form_request can
12884
* handle all form input elements and all standard request methods. */
12885
struct mg_upload_user_data {
12886
struct mg_connection *conn;
12887
const char *destination_dir;
12888
int num_uploaded_files;
12889
};
12890
12891
12892
/* Helper function for deprecated mg_upload. */
12893
static int
12894
mg_upload_field_found(const char *key,
12895
const char *filename,
12896
char *path,
12897
size_t pathlen,
12898
void *user_data)
12899
{
12900
int truncated = 0;
12901
struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
12902
(void)key;
12903
12904
if (!filename) {
12905
mg_cry_internal(fud->conn, "%s: No filename set", __func__);
12906
return FORM_FIELD_STORAGE_ABORT;
12907
}
12908
mg_snprintf(fud->conn,
12909
&truncated,
12910
path,
12911
pathlen - 1,
12912
"%s/%s",
12913
fud->destination_dir,
12914
filename);
12915
if (truncated) {
12916
mg_cry_internal(fud->conn, "%s: File path too long", __func__);
12917
return FORM_FIELD_STORAGE_ABORT;
12918
}
12919
return FORM_FIELD_STORAGE_STORE;
12920
}
12921
12922
12923
/* Helper function for deprecated mg_upload. */
12924
static int
12925
mg_upload_field_get(const char *key,
12926
const char *value,
12927
size_t value_size,
12928
void *user_data)
12929
{
12930
/* Function should never be called */
12931
(void)key;
12932
(void)value;
12933
(void)value_size;
12934
(void)user_data;
12935
12936
return 0;
12937
}
12938
12939
12940
/* Helper function for deprecated mg_upload. */
12941
static int
12942
mg_upload_field_stored(const char *path, long long file_size, void *user_data)
12943
{
12944
struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
12945
(void)file_size;
12946
12947
fud->num_uploaded_files++;
12948
fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
12949
12950
return 0;
12951
}
12952
12953
12954
/* Deprecated function mg_upload - use mg_handle_form_request instead. */
12955
int
12956
mg_upload(struct mg_connection *conn, const char *destination_dir)
12957
{
12958
struct mg_upload_user_data fud = {conn, destination_dir, 0};
12959
struct mg_form_data_handler fdh = {mg_upload_field_found,
12960
mg_upload_field_get,
12961
mg_upload_field_stored,
12962
0};
12963
int ret;
12964
12965
fdh.user_data = (void *)&fud;
12966
ret = mg_handle_form_request(conn, &fdh);
12967
12968
if (ret < 0) {
12969
mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
12970
}
12971
12972
return fud.num_uploaded_files;
12973
}
12974
#endif
12975
12976
12977
static int
12978
get_first_ssl_listener_index(const struct mg_context *ctx)
12979
{
12980
unsigned int i;
12981
int idx = -1;
12982
if (ctx) {
12983
for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
12984
idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
12985
}
12986
}
12987
return idx;
12988
}
12989
12990
12991
/* Return host (without port) */
12992
/* Use mg_free to free the result */
12993
static const char *
12994
alloc_get_host(struct mg_connection *conn)
12995
{
12996
char buf[1025];
12997
size_t buflen = sizeof(buf);
12998
const char *host_header = get_header(conn->request_info.http_headers,
12999
conn->request_info.num_headers,
13000
"Host");
13001
char *host;
13002
13003
if (host_header != NULL) {
13004
char *pos;
13005
13006
/* Create a local copy of the "Host" header, since it might be
13007
* modified here. */
13008
mg_strlcpy(buf, host_header, buflen);
13009
buf[buflen - 1] = '\0';
13010
host = buf;
13011
while (isspace(*host)) {
13012
host++;
13013
}
13014
13015
/* If the "Host" is an IPv6 address, like [::1], parse until ]
13016
* is found. */
13017
if (*host == '[') {
13018
pos = strchr(host, ']');
13019
if (!pos) {
13020
/* Malformed hostname starts with '[', but no ']' found */
13021
DEBUG_TRACE("%s", "Host name format error '[' without ']'");
13022
return NULL;
13023
}
13024
/* terminate after ']' */
13025
pos[1] = 0;
13026
} else {
13027
/* Otherwise, a ':' separates hostname and port number */
13028
pos = strchr(host, ':');
13029
if (pos != NULL) {
13030
*pos = '\0';
13031
}
13032
}
13033
13034
if (conn->ssl) {
13035
/* This is a HTTPS connection, maybe we have a hostname
13036
* from SNI (set in ssl_servername_callback). */
13037
const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
13038
if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
13039
/* We are not using the default domain */
13040
if (mg_strcasecmp(host, sslhost)) {
13041
/* Mismatch between SNI domain and HTTP domain */
13042
DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
13043
sslhost,
13044
host);
13045
return NULL;
13046
}
13047
}
13048
DEBUG_TRACE("HTTPS Host: %s", host);
13049
13050
} else {
13051
struct mg_domain_context *dom = &(conn->phys_ctx->dd);
13052
while (dom) {
13053
if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
13054
13055
/* Found matching domain */
13056
DEBUG_TRACE("HTTP domain %s found",
13057
dom->config[AUTHENTICATION_DOMAIN]);
13058
13059
/* TODO: Check if this is a HTTP or HTTPS domain */
13060
conn->dom_ctx = dom;
13061
break;
13062
}
13063
dom = dom->next;
13064
}
13065
13066
DEBUG_TRACE("HTTP Host: %s", host);
13067
}
13068
13069
} else {
13070
sockaddr_to_string(buf, buflen, &conn->client.lsa);
13071
host = buf;
13072
13073
DEBUG_TRACE("IP: %s", host);
13074
}
13075
13076
return mg_strdup_ctx(host, conn->phys_ctx);
13077
}
13078
13079
13080
static void
13081
redirect_to_https_port(struct mg_connection *conn, int ssl_index)
13082
{
13083
char target_url[MG_BUF_LEN];
13084
int truncated = 0;
13085
13086
conn->must_close = 1;
13087
13088
/* Send host, port, uri and (if it exists) ?query_string */
13089
if (conn->host) {
13090
13091
/* Use "308 Permanent Redirect" */
13092
int redirect_code = 308;
13093
13094
/* Create target URL */
13095
mg_snprintf(
13096
conn,
13097
&truncated,
13098
target_url,
13099
sizeof(target_url),
13100
"https://%s:%d%s%s%s",
13101
13102
conn->host,
13103
#if defined(USE_IPV6)
13104
(conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
13105
== AF_INET6)
13106
? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
13107
.lsa.sin6.sin6_port)
13108
:
13109
#endif
13110
(int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
13111
.lsa.sin.sin_port),
13112
conn->request_info.local_uri,
13113
(conn->request_info.query_string == NULL) ? "" : "?",
13114
(conn->request_info.query_string == NULL)
13115
? ""
13116
: conn->request_info.query_string);
13117
13118
/* Check overflow in location buffer (will not occur if MG_BUF_LEN
13119
* is used as buffer size) */
13120
if (truncated) {
13121
mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
13122
return;
13123
}
13124
13125
/* Use redirect helper function */
13126
mg_send_http_redirect(conn, target_url, redirect_code);
13127
}
13128
}
13129
13130
13131
static void
13132
handler_info_acquire(struct mg_handler_info *handler_info)
13133
{
13134
pthread_mutex_lock(&handler_info->refcount_mutex);
13135
handler_info->refcount++;
13136
pthread_mutex_unlock(&handler_info->refcount_mutex);
13137
}
13138
13139
13140
static void
13141
handler_info_release(struct mg_handler_info *handler_info)
13142
{
13143
pthread_mutex_lock(&handler_info->refcount_mutex);
13144
handler_info->refcount--;
13145
pthread_cond_signal(&handler_info->refcount_cond);
13146
pthread_mutex_unlock(&handler_info->refcount_mutex);
13147
}
13148
13149
13150
static void
13151
handler_info_wait_unused(struct mg_handler_info *handler_info)
13152
{
13153
pthread_mutex_lock(&handler_info->refcount_mutex);
13154
while (handler_info->refcount) {
13155
pthread_cond_wait(&handler_info->refcount_cond,
13156
&handler_info->refcount_mutex);
13157
}
13158
pthread_mutex_unlock(&handler_info->refcount_mutex);
13159
}
13160
13161
13162
static void
13163
mg_set_handler_type(struct mg_context *phys_ctx,
13164
struct mg_domain_context *dom_ctx,
13165
const char *uri,
13166
int handler_type,
13167
int is_delete_request,
13168
mg_request_handler handler,
13169
struct mg_websocket_subprotocols *subprotocols,
13170
mg_websocket_connect_handler connect_handler,
13171
mg_websocket_ready_handler ready_handler,
13172
mg_websocket_data_handler data_handler,
13173
mg_websocket_close_handler close_handler,
13174
mg_authorization_handler auth_handler,
13175
void *cbdata)
13176
{
13177
struct mg_handler_info *tmp_rh, **lastref;
13178
size_t urilen = strlen(uri);
13179
13180
if (handler_type == WEBSOCKET_HANDLER) {
13181
DEBUG_ASSERT(handler == NULL);
13182
DEBUG_ASSERT(is_delete_request || connect_handler != NULL
13183
|| ready_handler != NULL || data_handler != NULL
13184
|| close_handler != NULL);
13185
13186
DEBUG_ASSERT(auth_handler == NULL);
13187
if (handler != NULL) {
13188
return;
13189
}
13190
if (!is_delete_request && (connect_handler == NULL)
13191
&& (ready_handler == NULL) && (data_handler == NULL)
13192
&& (close_handler == NULL)) {
13193
return;
13194
}
13195
if (auth_handler != NULL) {
13196
return;
13197
}
13198
} else if (handler_type == REQUEST_HANDLER) {
13199
DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13200
&& data_handler == NULL && close_handler == NULL);
13201
DEBUG_ASSERT(is_delete_request || (handler != NULL));
13202
DEBUG_ASSERT(auth_handler == NULL);
13203
13204
if ((connect_handler != NULL) || (ready_handler != NULL)
13205
|| (data_handler != NULL) || (close_handler != NULL)) {
13206
return;
13207
}
13208
if (!is_delete_request && (handler == NULL)) {
13209
return;
13210
}
13211
if (auth_handler != NULL) {
13212
return;
13213
}
13214
} else { /* AUTH_HANDLER */
13215
DEBUG_ASSERT(handler == NULL);
13216
DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
13217
&& data_handler == NULL && close_handler == NULL);
13218
DEBUG_ASSERT(auth_handler != NULL);
13219
if (handler != NULL) {
13220
return;
13221
}
13222
if ((connect_handler != NULL) || (ready_handler != NULL)
13223
|| (data_handler != NULL) || (close_handler != NULL)) {
13224
return;
13225
}
13226
if (!is_delete_request && (auth_handler == NULL)) {
13227
return;
13228
}
13229
}
13230
13231
if (!phys_ctx || !dom_ctx) {
13232
return;
13233
}
13234
13235
mg_lock_context(phys_ctx);
13236
13237
/* first try to find an existing handler */
13238
lastref = &(dom_ctx->handlers);
13239
for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
13240
if (tmp_rh->handler_type == handler_type) {
13241
if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
13242
if (!is_delete_request) {
13243
/* update existing handler */
13244
if (handler_type == REQUEST_HANDLER) {
13245
/* Wait for end of use before updating */
13246
handler_info_wait_unused(tmp_rh);
13247
13248
/* Ok, the handler is no more use -> Update it */
13249
tmp_rh->handler = handler;
13250
} else if (handler_type == WEBSOCKET_HANDLER) {
13251
tmp_rh->subprotocols = subprotocols;
13252
tmp_rh->connect_handler = connect_handler;
13253
tmp_rh->ready_handler = ready_handler;
13254
tmp_rh->data_handler = data_handler;
13255
tmp_rh->close_handler = close_handler;
13256
} else { /* AUTH_HANDLER */
13257
tmp_rh->auth_handler = auth_handler;
13258
}
13259
tmp_rh->cbdata = cbdata;
13260
} else {
13261
/* remove existing handler */
13262
if (handler_type == REQUEST_HANDLER) {
13263
/* Wait for end of use before removing */
13264
handler_info_wait_unused(tmp_rh);
13265
13266
/* Ok, the handler is no more used -> Destroy resources
13267
*/
13268
pthread_cond_destroy(&tmp_rh->refcount_cond);
13269
pthread_mutex_destroy(&tmp_rh->refcount_mutex);
13270
}
13271
*lastref = tmp_rh->next;
13272
mg_free(tmp_rh->uri);
13273
mg_free(tmp_rh);
13274
}
13275
mg_unlock_context(phys_ctx);
13276
return;
13277
}
13278
}
13279
lastref = &(tmp_rh->next);
13280
}
13281
13282
if (is_delete_request) {
13283
/* no handler to set, this was a remove request to a non-existing
13284
* handler */
13285
mg_unlock_context(phys_ctx);
13286
return;
13287
}
13288
13289
tmp_rh =
13290
(struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
13291
1,
13292
phys_ctx);
13293
if (tmp_rh == NULL) {
13294
mg_unlock_context(phys_ctx);
13295
mg_cry_internal(fc(phys_ctx),
13296
"%s",
13297
"Cannot create new request handler struct, OOM");
13298
return;
13299
}
13300
tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
13301
if (!tmp_rh->uri) {
13302
mg_unlock_context(phys_ctx);
13303
mg_free(tmp_rh);
13304
mg_cry_internal(fc(phys_ctx),
13305
"%s",
13306
"Cannot create new request handler struct, OOM");
13307
return;
13308
}
13309
tmp_rh->uri_len = urilen;
13310
if (handler_type == REQUEST_HANDLER) {
13311
/* Init refcount mutex and condition */
13312
if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
13313
mg_unlock_context(phys_ctx);
13314
mg_free(tmp_rh);
13315
mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
13316
return;
13317
}
13318
if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
13319
mg_unlock_context(phys_ctx);
13320
pthread_mutex_destroy(&tmp_rh->refcount_mutex);
13321
mg_free(tmp_rh);
13322
mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
13323
return;
13324
}
13325
tmp_rh->refcount = 0;
13326
tmp_rh->handler = handler;
13327
} else if (handler_type == WEBSOCKET_HANDLER) {
13328
tmp_rh->subprotocols = subprotocols;
13329
tmp_rh->connect_handler = connect_handler;
13330
tmp_rh->ready_handler = ready_handler;
13331
tmp_rh->data_handler = data_handler;
13332
tmp_rh->close_handler = close_handler;
13333
} else { /* AUTH_HANDLER */
13334
tmp_rh->auth_handler = auth_handler;
13335
}
13336
tmp_rh->cbdata = cbdata;
13337
tmp_rh->handler_type = handler_type;
13338
tmp_rh->next = NULL;
13339
13340
*lastref = tmp_rh;
13341
mg_unlock_context(phys_ctx);
13342
}
13343
13344
13345
void
13346
mg_set_request_handler(struct mg_context *ctx,
13347
const char *uri,
13348
mg_request_handler handler,
13349
void *cbdata)
13350
{
13351
mg_set_handler_type(ctx,
13352
&(ctx->dd),
13353
uri,
13354
REQUEST_HANDLER,
13355
handler == NULL,
13356
handler,
13357
NULL,
13358
NULL,
13359
NULL,
13360
NULL,
13361
NULL,
13362
NULL,
13363
cbdata);
13364
}
13365
13366
13367
void
13368
mg_set_websocket_handler(struct mg_context *ctx,
13369
const char *uri,
13370
mg_websocket_connect_handler connect_handler,
13371
mg_websocket_ready_handler ready_handler,
13372
mg_websocket_data_handler data_handler,
13373
mg_websocket_close_handler close_handler,
13374
void *cbdata)
13375
{
13376
mg_set_websocket_handler_with_subprotocols(ctx,
13377
uri,
13378
NULL,
13379
connect_handler,
13380
ready_handler,
13381
data_handler,
13382
close_handler,
13383
cbdata);
13384
}
13385
13386
13387
void
13388
mg_set_websocket_handler_with_subprotocols(
13389
struct mg_context *ctx,
13390
const char *uri,
13391
struct mg_websocket_subprotocols *subprotocols,
13392
mg_websocket_connect_handler connect_handler,
13393
mg_websocket_ready_handler ready_handler,
13394
mg_websocket_data_handler data_handler,
13395
mg_websocket_close_handler close_handler,
13396
void *cbdata)
13397
{
13398
int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
13399
&& (data_handler == NULL)
13400
&& (close_handler == NULL);
13401
mg_set_handler_type(ctx,
13402
&(ctx->dd),
13403
uri,
13404
WEBSOCKET_HANDLER,
13405
is_delete_request,
13406
NULL,
13407
subprotocols,
13408
connect_handler,
13409
ready_handler,
13410
data_handler,
13411
close_handler,
13412
NULL,
13413
cbdata);
13414
}
13415
13416
13417
void
13418
mg_set_auth_handler(struct mg_context *ctx,
13419
const char *uri,
13420
mg_request_handler handler,
13421
void *cbdata)
13422
{
13423
mg_set_handler_type(ctx,
13424
&(ctx->dd),
13425
uri,
13426
AUTH_HANDLER,
13427
handler == NULL,
13428
NULL,
13429
NULL,
13430
NULL,
13431
NULL,
13432
NULL,
13433
NULL,
13434
handler,
13435
cbdata);
13436
}
13437
13438
13439
static int
13440
get_request_handler(struct mg_connection *conn,
13441
int handler_type,
13442
mg_request_handler *handler,
13443
struct mg_websocket_subprotocols **subprotocols,
13444
mg_websocket_connect_handler *connect_handler,
13445
mg_websocket_ready_handler *ready_handler,
13446
mg_websocket_data_handler *data_handler,
13447
mg_websocket_close_handler *close_handler,
13448
mg_authorization_handler *auth_handler,
13449
void **cbdata,
13450
struct mg_handler_info **handler_info)
13451
{
13452
const struct mg_request_info *request_info = mg_get_request_info(conn);
13453
if (request_info) {
13454
const char *uri = request_info->local_uri;
13455
size_t urilen = strlen(uri);
13456
struct mg_handler_info *tmp_rh;
13457
13458
if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
13459
return 0;
13460
}
13461
13462
mg_lock_context(conn->phys_ctx);
13463
13464
/* first try for an exact match */
13465
for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
13466
tmp_rh = tmp_rh->next) {
13467
if (tmp_rh->handler_type == handler_type) {
13468
if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
13469
if (handler_type == WEBSOCKET_HANDLER) {
13470
*subprotocols = tmp_rh->subprotocols;
13471
*connect_handler = tmp_rh->connect_handler;
13472
*ready_handler = tmp_rh->ready_handler;
13473
*data_handler = tmp_rh->data_handler;
13474
*close_handler = tmp_rh->close_handler;
13475
} else if (handler_type == REQUEST_HANDLER) {
13476
*handler = tmp_rh->handler;
13477
/* Acquire handler and give it back */
13478
handler_info_acquire(tmp_rh);
13479
*handler_info = tmp_rh;
13480
} else { /* AUTH_HANDLER */
13481
*auth_handler = tmp_rh->auth_handler;
13482
}
13483
*cbdata = tmp_rh->cbdata;
13484
mg_unlock_context(conn->phys_ctx);
13485
return 1;
13486
}
13487
}
13488
}
13489
13490
/* next try for a partial match, we will accept uri/something */
13491
for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
13492
tmp_rh = tmp_rh->next) {
13493
if (tmp_rh->handler_type == handler_type) {
13494
if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
13495
&& (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
13496
if (handler_type == WEBSOCKET_HANDLER) {
13497
*subprotocols = tmp_rh->subprotocols;
13498
*connect_handler = tmp_rh->connect_handler;
13499
*ready_handler = tmp_rh->ready_handler;
13500
*data_handler = tmp_rh->data_handler;
13501
*close_handler = tmp_rh->close_handler;
13502
} else if (handler_type == REQUEST_HANDLER) {
13503
*handler = tmp_rh->handler;
13504
/* Acquire handler and give it back */
13505
handler_info_acquire(tmp_rh);
13506
*handler_info = tmp_rh;
13507
} else { /* AUTH_HANDLER */
13508
*auth_handler = tmp_rh->auth_handler;
13509
}
13510
*cbdata = tmp_rh->cbdata;
13511
mg_unlock_context(conn->phys_ctx);
13512
return 1;
13513
}
13514
}
13515
}
13516
13517
/* finally try for pattern match */
13518
for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
13519
tmp_rh = tmp_rh->next) {
13520
if (tmp_rh->handler_type == handler_type) {
13521
if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
13522
if (handler_type == WEBSOCKET_HANDLER) {
13523
*subprotocols = tmp_rh->subprotocols;
13524
*connect_handler = tmp_rh->connect_handler;
13525
*ready_handler = tmp_rh->ready_handler;
13526
*data_handler = tmp_rh->data_handler;
13527
*close_handler = tmp_rh->close_handler;
13528
} else if (handler_type == REQUEST_HANDLER) {
13529
*handler = tmp_rh->handler;
13530
/* Acquire handler and give it back */
13531
handler_info_acquire(tmp_rh);
13532
*handler_info = tmp_rh;
13533
} else { /* AUTH_HANDLER */
13534
*auth_handler = tmp_rh->auth_handler;
13535
}
13536
*cbdata = tmp_rh->cbdata;
13537
mg_unlock_context(conn->phys_ctx);
13538
return 1;
13539
}
13540
}
13541
}
13542
13543
mg_unlock_context(conn->phys_ctx);
13544
}
13545
return 0; /* none found */
13546
}
13547
13548
13549
/* Check if the script file is in a path, allowed for script files.
13550
* This can be used if uploading files is possible not only for the server
13551
* admin, and the upload mechanism does not check the file extension.
13552
*/
13553
static int
13554
is_in_script_path(const struct mg_connection *conn, const char *path)
13555
{
13556
/* TODO (Feature): Add config value for allowed script path.
13557
* Default: All allowed. */
13558
(void)conn;
13559
(void)path;
13560
return 1;
13561
}
13562
13563
13564
#if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
13565
static int
13566
deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
13567
void *cbdata)
13568
{
13569
struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13570
if (pcallbacks->websocket_connect) {
13571
return pcallbacks->websocket_connect(conn);
13572
}
13573
/* No handler set - assume "OK" */
13574
return 0;
13575
}
13576
13577
13578
static void
13579
deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
13580
{
13581
struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13582
if (pcallbacks->websocket_ready) {
13583
pcallbacks->websocket_ready(conn);
13584
}
13585
}
13586
13587
13588
static int
13589
deprecated_websocket_data_wrapper(struct mg_connection *conn,
13590
int bits,
13591
char *data,
13592
size_t len,
13593
void *cbdata)
13594
{
13595
struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
13596
if (pcallbacks->websocket_data) {
13597
return pcallbacks->websocket_data(conn, bits, data, len);
13598
}
13599
/* No handler set - assume "OK" */
13600
return 1;
13601
}
13602
#endif
13603
13604
13605
/* This is the heart of the Civetweb's logic.
13606
* This function is called when the request is read, parsed and validated,
13607
* and Civetweb must decide what action to take: serve a file, or
13608
* a directory, or call embedded function, etcetera. */
13609
static void
13610
handle_request(struct mg_connection *conn)
13611
{
13612
struct mg_request_info *ri = &conn->request_info;
13613
char path[PATH_MAX];
13614
int uri_len, ssl_index;
13615
int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
13616
is_put_or_delete_request = 0, is_callback_resource = 0;
13617
int i;
13618
struct mg_file file = STRUCT_FILE_INITIALIZER;
13619
mg_request_handler callback_handler = NULL;
13620
struct mg_handler_info *handler_info = NULL;
13621
struct mg_websocket_subprotocols *subprotocols;
13622
mg_websocket_connect_handler ws_connect_handler = NULL;
13623
mg_websocket_ready_handler ws_ready_handler = NULL;
13624
mg_websocket_data_handler ws_data_handler = NULL;
13625
mg_websocket_close_handler ws_close_handler = NULL;
13626
void *callback_data = NULL;
13627
mg_authorization_handler auth_handler = NULL;
13628
void *auth_callback_data = NULL;
13629
int handler_type;
13630
time_t curtime = time(NULL);
13631
char date[64];
13632
13633
path[0] = 0;
13634
13635
/* 1. get the request url */
13636
/* 1.1. split into url and query string */
13637
if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
13638
!= NULL) {
13639
*((char *)conn->request_info.query_string++) = '\0';
13640
}
13641
13642
/* 1.2. do a https redirect, if required. Do not decode URIs yet. */
13643
if (!conn->client.is_ssl && conn->client.ssl_redir) {
13644
ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
13645
if (ssl_index >= 0) {
13646
redirect_to_https_port(conn, ssl_index);
13647
} else {
13648
/* A http to https forward port has been specified,
13649
* but no https port to forward to. */
13650
mg_send_http_error(conn,
13651
503,
13652
"%s",
13653
"Error: SSL forward not configured properly");
13654
mg_cry_internal(conn,
13655
"%s",
13656
"Can not redirect to SSL, no SSL port available");
13657
}
13658
return;
13659
}
13660
uri_len = (int)strlen(ri->local_uri);
13661
13662
/* 1.3. decode url (if config says so) */
13663
if (should_decode_url(conn)) {
13664
mg_url_decode(
13665
ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
13666
}
13667
13668
/* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
13669
* not possible */
13670
remove_double_dots_and_double_slashes((char *)ri->local_uri);
13671
13672
/* step 1. completed, the url is known now */
13673
uri_len = (int)strlen(ri->local_uri);
13674
DEBUG_TRACE("URL: %s", ri->local_uri);
13675
13676
/* 2. if this ip has limited speed, set it for this connection */
13677
conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
13678
get_remote_ip(conn),
13679
ri->local_uri);
13680
13681
/* 3. call a "handle everything" callback, if registered */
13682
if (conn->phys_ctx->callbacks.begin_request != NULL) {
13683
/* Note that since V1.7 the "begin_request" function is called
13684
* before an authorization check. If an authorization check is
13685
* required, use a request_handler instead. */
13686
i = conn->phys_ctx->callbacks.begin_request(conn);
13687
if (i > 0) {
13688
/* callback already processed the request. Store the
13689
return value as a status code for the access log. */
13690
conn->status_code = i;
13691
discard_unread_request_data(conn);
13692
return;
13693
} else if (i == 0) {
13694
/* civetweb should process the request */
13695
} else {
13696
/* unspecified - may change with the next version */
13697
return;
13698
}
13699
}
13700
13701
/* request not yet handled by a handler or redirect, so the request
13702
* is processed here */
13703
13704
/* 4. Check for CORS preflight requests and handle them (if configured).
13705
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
13706
*/
13707
if (!strcmp(ri->request_method, "OPTIONS")) {
13708
/* Send a response to CORS preflights only if
13709
* access_control_allow_methods is not NULL and not an empty string.
13710
* In this case, scripts can still handle CORS. */
13711
const char *cors_meth_cfg =
13712
conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
13713
const char *cors_orig_cfg =
13714
conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
13715
const char *cors_origin =
13716
get_header(ri->http_headers, ri->num_headers, "Origin");
13717
const char *cors_acrm = get_header(ri->http_headers,
13718
ri->num_headers,
13719
"Access-Control-Request-Method");
13720
13721
/* Todo: check if cors_origin is in cors_orig_cfg.
13722
* Or, let the client check this. */
13723
13724
if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
13725
&& (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
13726
&& (cors_origin != NULL) && (cors_acrm != NULL)) {
13727
/* This is a valid CORS preflight, and the server is configured
13728
* to
13729
* handle it automatically. */
13730
const char *cors_acrh =
13731
get_header(ri->http_headers,
13732
ri->num_headers,
13733
"Access-Control-Request-Headers");
13734
13735
gmt_time_string(date, sizeof(date), &curtime);
13736
mg_printf(conn,
13737
"HTTP/1.1 200 OK\r\n"
13738
"Date: %s\r\n"
13739
"Access-Control-Allow-Origin: %s\r\n"
13740
"Access-Control-Allow-Methods: %s\r\n"
13741
"Content-Length: 0\r\n"
13742
"Connection: %s\r\n",
13743
date,
13744
cors_orig_cfg,
13745
((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
13746
suggest_connection_header(conn));
13747
13748
if (cors_acrh != NULL) {
13749
/* CORS request is asking for additional headers */
13750
const char *cors_hdr_cfg =
13751
conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
13752
13753
if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
13754
/* Allow only if access_control_allow_headers is
13755
* not NULL and not an empty string. If this
13756
* configuration is set to *, allow everything.
13757
* Otherwise this configuration must be a list
13758
* of allowed HTTP header names. */
13759
mg_printf(conn,
13760
"Access-Control-Allow-Headers: %s\r\n",
13761
((cors_hdr_cfg[0] == '*') ? cors_acrh
13762
: cors_hdr_cfg));
13763
}
13764
}
13765
mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
13766
13767
mg_printf(conn, "\r\n");
13768
return;
13769
}
13770
}
13771
13772
/* 5. interpret the url to find out how the request must be handled
13773
*/
13774
/* 5.1. first test, if the request targets the regular http(s)://
13775
* protocol namespace or the websocket ws(s):// protocol namespace.
13776
*/
13777
is_websocket_request = is_websocket_protocol(conn);
13778
#if defined(USE_WEBSOCKET)
13779
handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
13780
#else
13781
handler_type = REQUEST_HANDLER;
13782
#endif /* defined(USE_WEBSOCKET) */
13783
/* 5.2. check if the request will be handled by a callback */
13784
if (get_request_handler(conn,
13785
handler_type,
13786
&callback_handler,
13787
&subprotocols,
13788
&ws_connect_handler,
13789
&ws_ready_handler,
13790
&ws_data_handler,
13791
&ws_close_handler,
13792
NULL,
13793
&callback_data,
13794
&handler_info)) {
13795
/* 5.2.1. A callback will handle this request. All requests
13796
* handled
13797
* by a callback have to be considered as requests to a script
13798
* resource. */
13799
is_callback_resource = 1;
13800
is_script_resource = 1;
13801
is_put_or_delete_request = is_put_or_delete_method(conn);
13802
} else {
13803
no_callback_resource:
13804
13805
/* 5.2.2. No callback is responsible for this request. The URI
13806
* addresses a file based resource (static content or Lua/cgi
13807
* scripts in the file system). */
13808
is_callback_resource = 0;
13809
interpret_uri(conn,
13810
path,
13811
sizeof(path),
13812
&file.stat,
13813
&is_found,
13814
&is_script_resource,
13815
&is_websocket_request,
13816
&is_put_or_delete_request);
13817
}
13818
13819
/* 6. authorization check */
13820
/* 6.1. a custom authorization handler is installed */
13821
if (get_request_handler(conn,
13822
AUTH_HANDLER,
13823
NULL,
13824
NULL,
13825
NULL,
13826
NULL,
13827
NULL,
13828
NULL,
13829
&auth_handler,
13830
&auth_callback_data,
13831
NULL)) {
13832
if (!auth_handler(conn, auth_callback_data)) {
13833
return;
13834
}
13835
} else if (is_put_or_delete_request && !is_script_resource
13836
&& !is_callback_resource) {
13837
/* 6.2. this request is a PUT/DELETE to a real file */
13838
/* 6.2.1. thus, the server must have real files */
13839
#if defined(NO_FILES)
13840
if (1) {
13841
#else
13842
if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
13843
#endif
13844
/* This server does not have any real files, thus the
13845
* PUT/DELETE methods are not valid. */
13846
mg_send_http_error(conn,
13847
405,
13848
"%s method not allowed",
13849
conn->request_info.request_method);
13850
return;
13851
}
13852
13853
#if !defined(NO_FILES)
13854
/* 6.2.2. Check if put authorization for static files is
13855
* available.
13856
*/
13857
if (!is_authorized_for_put(conn)) {
13858
send_authorization_request(conn, NULL);
13859
return;
13860
}
13861
#endif
13862
13863
} else {
13864
/* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
13865
* or it is a PUT or DELETE request to a resource that does not
13866
* correspond to a file. Check authorization. */
13867
if (!check_authorization(conn, path)) {
13868
send_authorization_request(conn, NULL);
13869
return;
13870
}
13871
}
13872
13873
/* request is authorized or does not need authorization */
13874
13875
/* 7. check if there are request handlers for this uri */
13876
if (is_callback_resource) {
13877
if (!is_websocket_request) {
13878
i = callback_handler(conn, callback_data);
13879
13880
/* Callback handler will not be used anymore. Release it */
13881
handler_info_release(handler_info);
13882
13883
if (i > 0) {
13884
/* Do nothing, callback has served the request. Store
13885
* then return value as status code for the log and discard
13886
* all data from the client not used by the callback. */
13887
conn->status_code = i;
13888
discard_unread_request_data(conn);
13889
} else {
13890
/* The handler did NOT handle the request. */
13891
/* Some proper reactions would be:
13892
* a) close the connections without sending anything
13893
* b) send a 404 not found
13894
* c) try if there is a file matching the URI
13895
* It would be possible to do a, b or c in the callback
13896
* implementation, and return 1 - we cannot do anything
13897
* here, that is not possible in the callback.
13898
*
13899
* TODO: What would be the best reaction here?
13900
* (Note: The reaction may change, if there is a better
13901
*idea.)
13902
*/
13903
13904
/* For the moment, use option c: We look for a proper file,
13905
* but since a file request is not always a script resource,
13906
* the authorization check might be different. */
13907
interpret_uri(conn,
13908
path,
13909
sizeof(path),
13910
&file.stat,
13911
&is_found,
13912
&is_script_resource,
13913
&is_websocket_request,
13914
&is_put_or_delete_request);
13915
callback_handler = NULL;
13916
13917
/* Here we are at a dead end:
13918
* According to URI matching, a callback should be
13919
* responsible for handling the request,
13920
* we called it, but the callback declared itself
13921
* not responsible.
13922
* We use a goto here, to get out of this dead end,
13923
* and continue with the default handling.
13924
* A goto here is simpler and better to understand
13925
* than some curious loop. */
13926
goto no_callback_resource;
13927
}
13928
} else {
13929
#if defined(USE_WEBSOCKET)
13930
handle_websocket_request(conn,
13931
path,
13932
is_callback_resource,
13933
subprotocols,
13934
ws_connect_handler,
13935
ws_ready_handler,
13936
ws_data_handler,
13937
ws_close_handler,
13938
callback_data);
13939
#endif
13940
}
13941
return;
13942
}
13943
13944
/* 8. handle websocket requests */
13945
#if defined(USE_WEBSOCKET)
13946
if (is_websocket_request) {
13947
if (is_script_resource) {
13948
13949
if (is_in_script_path(conn, path)) {
13950
/* Websocket Lua script */
13951
handle_websocket_request(conn,
13952
path,
13953
0 /* Lua Script */,
13954
NULL,
13955
NULL,
13956
NULL,
13957
NULL,
13958
NULL,
13959
conn->phys_ctx->user_data);
13960
} else {
13961
/* Script was in an illegal path */
13962
mg_send_http_error(conn, 403, "%s", "Forbidden");
13963
}
13964
} else {
13965
#if defined(MG_LEGACY_INTERFACE)
13966
handle_websocket_request(
13967
conn,
13968
path,
13969
!is_script_resource /* could be deprecated global callback */,
13970
NULL,
13971
deprecated_websocket_connect_wrapper,
13972
deprecated_websocket_ready_wrapper,
13973
deprecated_websocket_data_wrapper,
13974
NULL,
13975
conn->phys_ctx->user_data);
13976
#else
13977
mg_send_http_error(conn, 404, "%s", "Not found");
13978
#endif
13979
}
13980
return;
13981
} else
13982
#endif
13983
13984
#if defined(NO_FILES)
13985
/* 9a. In case the server uses only callbacks, this uri is
13986
* unknown.
13987
* Then, all request handling ends here. */
13988
mg_send_http_error(conn, 404, "%s", "Not Found");
13989
13990
#else
13991
/* 9b. This request is either for a static file or resource handled
13992
* by a script file. Thus, a DOCUMENT_ROOT must exist. */
13993
if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
13994
mg_send_http_error(conn, 404, "%s", "Not Found");
13995
return;
13996
}
13997
13998
/* 10. Request is handled by a script */
13999
if (is_script_resource) {
14000
handle_file_based_request(conn, path, &file);
14001
return;
14002
}
14003
14004
/* 11. Handle put/delete/mkcol requests */
14005
if (is_put_or_delete_request) {
14006
/* 11.1. PUT method */
14007
if (!strcmp(ri->request_method, "PUT")) {
14008
put_file(conn, path);
14009
return;
14010
}
14011
/* 11.2. DELETE method */
14012
if (!strcmp(ri->request_method, "DELETE")) {
14013
delete_file(conn, path);
14014
return;
14015
}
14016
/* 11.3. MKCOL method */
14017
if (!strcmp(ri->request_method, "MKCOL")) {
14018
mkcol(conn, path);
14019
return;
14020
}
14021
/* 11.4. PATCH method
14022
* This method is not supported for static resources,
14023
* only for scripts (Lua, CGI) and callbacks. */
14024
mg_send_http_error(conn,
14025
405,
14026
"%s method not allowed",
14027
conn->request_info.request_method);
14028
return;
14029
}
14030
14031
/* 11. File does not exist, or it was configured that it should be
14032
* hidden */
14033
if (!is_found || (must_hide_file(conn, path))) {
14034
mg_send_http_error(conn, 404, "%s", "Not found");
14035
return;
14036
}
14037
14038
/* 12. Directory uris should end with a slash */
14039
if (file.stat.is_directory && (uri_len > 0)
14040
&& (ri->local_uri[uri_len - 1] != '/')) {
14041
gmt_time_string(date, sizeof(date), &curtime);
14042
mg_printf(conn,
14043
"HTTP/1.1 301 Moved Permanently\r\n"
14044
"Location: %s/\r\n"
14045
"Date: %s\r\n"
14046
/* "Cache-Control: private\r\n" (= default) */
14047
"Content-Length: 0\r\n"
14048
"Connection: %s\r\n",
14049
ri->request_uri,
14050
date,
14051
suggest_connection_header(conn));
14052
send_additional_header(conn);
14053
mg_printf(conn, "\r\n");
14054
return;
14055
}
14056
14057
/* 13. Handle other methods than GET/HEAD */
14058
/* 13.1. Handle PROPFIND */
14059
if (!strcmp(ri->request_method, "PROPFIND")) {
14060
handle_propfind(conn, path, &file.stat);
14061
return;
14062
}
14063
/* 13.2. Handle OPTIONS for files */
14064
if (!strcmp(ri->request_method, "OPTIONS")) {
14065
/* This standard handler is only used for real files.
14066
* Scripts should support the OPTIONS method themselves, to allow a
14067
* maximum flexibility.
14068
* Lua and CGI scripts may fully support CORS this way (including
14069
* preflights). */
14070
send_options(conn);
14071
return;
14072
}
14073
/* 13.3. everything but GET and HEAD (e.g. POST) */
14074
if ((0 != strcmp(ri->request_method, "GET"))
14075
&& (0 != strcmp(ri->request_method, "HEAD"))) {
14076
mg_send_http_error(conn,
14077
405,
14078
"%s method not allowed",
14079
conn->request_info.request_method);
14080
return;
14081
}
14082
14083
/* 14. directories */
14084
if (file.stat.is_directory) {
14085
/* Substitute files have already been handled above. */
14086
/* Here we can either generate and send a directory listing,
14087
* or send an "access denied" error. */
14088
if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
14089
"yes")) {
14090
handle_directory_request(conn, path);
14091
} else {
14092
mg_send_http_error(conn,
14093
403,
14094
"%s",
14095
"Error: Directory listing denied");
14096
}
14097
return;
14098
}
14099
14100
/* 15. read a normal file with GET or HEAD */
14101
handle_file_based_request(conn, path, &file);
14102
#endif /* !defined(NO_FILES) */
14103
}
14104
14105
14106
static void
14107
handle_file_based_request(struct mg_connection *conn,
14108
const char *path,
14109
struct mg_file *file)
14110
{
14111
if (!conn || !conn->dom_ctx) {
14112
return;
14113
}
14114
14115
if (0) {
14116
#if defined(USE_LUA)
14117
} else if (match_prefix(
14118
conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
14119
strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
14120
path)
14121
> 0) {
14122
if (is_in_script_path(conn, path)) {
14123
/* Lua server page: an SSI like page containing mostly plain
14124
* html
14125
* code
14126
* plus some tags with server generated contents. */
14127
handle_lsp_request(conn, path, file, NULL);
14128
} else {
14129
/* Script was in an illegal path */
14130
mg_send_http_error(conn, 403, "%s", "Forbidden");
14131
}
14132
14133
} else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
14134
strlen(
14135
conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
14136
path)
14137
> 0) {
14138
if (is_in_script_path(conn, path)) {
14139
/* Lua in-server module script: a CGI like script used to
14140
* generate
14141
* the
14142
* entire reply. */
14143
mg_exec_lua_script(conn, path, NULL);
14144
} else {
14145
/* Script was in an illegal path */
14146
mg_send_http_error(conn, 403, "%s", "Forbidden");
14147
}
14148
#endif
14149
#if defined(USE_DUKTAPE)
14150
} else if (match_prefix(
14151
conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
14152
strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
14153
path)
14154
> 0) {
14155
if (is_in_script_path(conn, path)) {
14156
/* Call duktape to generate the page */
14157
mg_exec_duktape_script(conn, path);
14158
} else {
14159
/* Script was in an illegal path */
14160
mg_send_http_error(conn, 403, "%s", "Forbidden");
14161
}
14162
#endif
14163
#if !defined(NO_CGI)
14164
} else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
14165
strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
14166
path)
14167
> 0) {
14168
if (is_in_script_path(conn, path)) {
14169
/* CGI scripts may support all HTTP methods */
14170
handle_cgi_request(conn, path);
14171
} else {
14172
/* Script was in an illegal path */
14173
mg_send_http_error(conn, 403, "%s", "Forbidden");
14174
}
14175
#endif /* !NO_CGI */
14176
} else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
14177
strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
14178
path)
14179
> 0) {
14180
if (is_in_script_path(conn, path)) {
14181
handle_ssi_file_request(conn, path, file);
14182
} else {
14183
/* Script was in an illegal path */
14184
mg_send_http_error(conn, 403, "%s", "Forbidden");
14185
}
14186
#if !defined(NO_CACHING)
14187
} else if ((!conn->in_error_handler)
14188
&& is_not_modified(conn, &file->stat)) {
14189
/* Send 304 "Not Modified" - this must not send any body data */
14190
handle_not_modified_static_file_request(conn, file);
14191
#endif /* !NO_CACHING */
14192
} else {
14193
handle_static_file_request(conn, path, file, NULL, NULL);
14194
}
14195
}
14196
14197
14198
static void
14199
close_all_listening_sockets(struct mg_context *ctx)
14200
{
14201
unsigned int i;
14202
if (!ctx) {
14203
return;
14204
}
14205
14206
for (i = 0; i < ctx->num_listening_sockets; i++) {
14207
closesocket(ctx->listening_sockets[i].sock);
14208
ctx->listening_sockets[i].sock = INVALID_SOCKET;
14209
}
14210
mg_free(ctx->listening_sockets);
14211
ctx->listening_sockets = NULL;
14212
mg_free(ctx->listening_socket_fds);
14213
ctx->listening_socket_fds = NULL;
14214
}
14215
14216
14217
/* Valid listening port specification is: [ip_address:]port[s]
14218
* Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
14219
* Examples for IPv6: [::]:80, [::1]:80,
14220
* [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
14221
* see https://tools.ietf.org/html/rfc3513#section-2.2
14222
* In order to bind to both, IPv4 and IPv6, you can either add
14223
* both ports using 8080,[::]:8080, or the short form +8080.
14224
* Both forms differ in detail: 8080,[::]:8080 create two sockets,
14225
* one only accepting IPv4 the other only IPv6. +8080 creates
14226
* one socket accepting IPv4 and IPv6. Depending on the IPv6
14227
* environment, they might work differently, or might not work
14228
* at all - it must be tested what options work best in the
14229
* relevant network environment.
14230
*/
14231
static int
14232
parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
14233
{
14234
unsigned int a, b, c, d, port;
14235
int ch, len;
14236
const char *cb;
14237
#if defined(USE_IPV6)
14238
char buf[100] = {0};
14239
#endif
14240
14241
/* MacOS needs that. If we do not zero it, subsequent bind() will fail.
14242
* Also, all-zeroes in the socket address means binding to all addresses
14243
* for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
14244
memset(so, 0, sizeof(*so));
14245
so->lsa.sin.sin_family = AF_INET;
14246
*ip_version = 0;
14247
14248
/* Initialize port and len as invalid. */
14249
port = 0;
14250
len = 0;
14251
14252
/* Test for different ways to format this string */
14253
if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
14254
== 5) {
14255
/* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
14256
so->lsa.sin.sin_addr.s_addr =
14257
htonl((a << 24) | (b << 16) | (c << 8) | d);
14258
so->lsa.sin.sin_port = htons((uint16_t)port);
14259
*ip_version = 4;
14260
14261
#if defined(USE_IPV6)
14262
} else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
14263
&& mg_inet_pton(
14264
AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
14265
/* IPv6 address, examples: see above */
14266
/* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
14267
*/
14268
so->lsa.sin6.sin6_port = htons((uint16_t)port);
14269
*ip_version = 6;
14270
#endif
14271
14272
} else if ((vec->ptr[0] == '+')
14273
&& (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
14274
14275
/* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
14276
/* Add 1 to len for the + character we skipped before */
14277
len++;
14278
14279
#if defined(USE_IPV6)
14280
/* Set socket family to IPv6, do not use IPV6_V6ONLY */
14281
so->lsa.sin6.sin6_family = AF_INET6;
14282
so->lsa.sin6.sin6_port = htons((uint16_t)port);
14283
*ip_version = 4 + 6;
14284
#else
14285
/* Bind to IPv4 only, since IPv6 is not built in. */
14286
so->lsa.sin.sin_port = htons((uint16_t)port);
14287
*ip_version = 4;
14288
#endif
14289
14290
} else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
14291
/* If only port is specified, bind to IPv4, INADDR_ANY */
14292
so->lsa.sin.sin_port = htons((uint16_t)port);
14293
*ip_version = 4;
14294
14295
} else if ((cb = strchr(vec->ptr, ':')) != NULL) {
14296
/* String could be a hostname. This check algotithm
14297
* will only work for RFC 952 compliant hostnames,
14298
* starting with a letter, containing only letters,
14299
* digits and hyphen ('-'). Newer specs may allow
14300
* more, but this is not guaranteed here, since it
14301
* may interfere with rules for port option lists. */
14302
14303
/* According to RFC 1035, hostnames are restricted to 255 characters
14304
* in total (63 between two dots). */
14305
char hostname[256];
14306
size_t hostnlen = (size_t)(cb - vec->ptr);
14307
14308
if (hostnlen >= sizeof(hostname)) {
14309
/* This would be invalid in any case */
14310
*ip_version = 0;
14311
return 0;
14312
}
14313
14314
memcpy(hostname, vec->ptr, hostnlen);
14315
hostname[hostnlen] = 0;
14316
14317
if (mg_inet_pton(
14318
AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
14319
if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
14320
*ip_version = 4;
14321
so->lsa.sin.sin_family = AF_INET;
14322
so->lsa.sin.sin_port = htons((uint16_t)port);
14323
len += (int)(hostnlen + 1);
14324
} else {
14325
port = 0;
14326
len = 0;
14327
}
14328
#if defined(USE_IPV6)
14329
} else if (mg_inet_pton(AF_INET6,
14330
vec->ptr,
14331
&so->lsa.sin6,
14332
sizeof(so->lsa.sin6))) {
14333
if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
14334
*ip_version = 6;
14335
so->lsa.sin6.sin6_family = AF_INET6;
14336
so->lsa.sin.sin_port = htons((uint16_t)port);
14337
len += (int)(hostnlen + 1);
14338
} else {
14339
port = 0;
14340
len = 0;
14341
}
14342
#endif
14343
}
14344
14345
14346
} else {
14347
/* Parsing failure. */
14348
}
14349
14350
/* sscanf and the option splitting code ensure the following condition
14351
*/
14352
if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
14353
*ip_version = 0;
14354
return 0;
14355
}
14356
ch = vec->ptr[len]; /* Next character after the port number */
14357
so->is_ssl = (ch == 's');
14358
so->ssl_redir = (ch == 'r');
14359
14360
/* Make sure the port is valid and vector ends with 's', 'r' or ',' */
14361
if (is_valid_port(port)
14362
&& ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
14363
return 1;
14364
}
14365
14366
/* Reset ip_version to 0 if there is an error */
14367
*ip_version = 0;
14368
return 0;
14369
}
14370
14371
14372
/* Is there any SSL port in use? */
14373
static int
14374
is_ssl_port_used(const char *ports)
14375
{
14376
if (ports) {
14377
/* There are several different allowed syntax variants:
14378
* - "80" for a single port using every network interface
14379
* - "localhost:80" for a single port using only localhost
14380
* - "80,localhost:8080" for two ports, one bound to localhost
14381
* - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
14382
* to IPv4 localhost, one to IPv6 localhost
14383
* - "+80" use port 80 for IPv4 and IPv6
14384
* - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
14385
* for both: IPv4 and IPv4
14386
* - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
14387
* additionally port 8080 bound to localhost connections
14388
*
14389
* If we just look for 's' anywhere in the string, "localhost:80"
14390
* will be detected as SSL (false positive).
14391
* Looking for 's' after a digit may cause false positives in
14392
* "my24service:8080".
14393
* Looking from 's' backward if there are only ':' and numbers
14394
* before will not work for "24service:8080" (non SSL, port 8080)
14395
* or "24s" (SSL, port 24).
14396
*
14397
* Remark: Initially hostnames were not allowed to start with a
14398
* digit (according to RFC 952), this was allowed later (RFC 1123,
14399
* Section 2.1).
14400
*
14401
* To get this correct, the entire string must be parsed as a whole,
14402
* reading it as a list element for element and parsing with an
14403
* algorithm equivalent to parse_port_string.
14404
*
14405
* In fact, we use local interface names here, not arbitrary hostnames,
14406
* so in most cases the only name will be "localhost".
14407
*
14408
* So, for now, we use this simple algorithm, that may still return
14409
* a false positive in bizarre cases.
14410
*/
14411
int i;
14412
int portslen = (int)strlen(ports);
14413
char prevIsNumber = 0;
14414
14415
for (i = 0; i < portslen; i++) {
14416
if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
14417
return 1;
14418
}
14419
if (ports[i] >= '0' && ports[i] <= '9') {
14420
prevIsNumber = 1;
14421
} else {
14422
prevIsNumber = 0;
14423
}
14424
}
14425
}
14426
return 0;
14427
}
14428
14429
14430
static int
14431
set_ports_option(struct mg_context *phys_ctx)
14432
{
14433
const char *list;
14434
int on = 1;
14435
#if defined(USE_IPV6)
14436
int off = 0;
14437
#endif
14438
struct vec vec;
14439
struct socket so, *ptr;
14440
14441
struct pollfd *pfd;
14442
union usa usa;
14443
socklen_t len;
14444
int ip_version;
14445
14446
int portsTotal = 0;
14447
int portsOk = 0;
14448
14449
if (!phys_ctx) {
14450
return 0;
14451
}
14452
14453
memset(&so, 0, sizeof(so));
14454
memset(&usa, 0, sizeof(usa));
14455
len = sizeof(usa);
14456
list = phys_ctx->dd.config[LISTENING_PORTS];
14457
14458
while ((list = next_option(list, &vec, NULL)) != NULL) {
14459
14460
portsTotal++;
14461
14462
if (!parse_port_string(&vec, &so, &ip_version)) {
14463
mg_cry_internal(
14464
fc(phys_ctx),
14465
"%.*s: invalid port spec (entry %i). Expecting list of: %s",
14466
(int)vec.len,
14467
vec.ptr,
14468
portsTotal,
14469
"[IP_ADDRESS:]PORT[s|r]");
14470
continue;
14471
}
14472
14473
#if !defined(NO_SSL)
14474
if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
14475
14476
mg_cry_internal(fc(phys_ctx),
14477
"Cannot add SSL socket (entry %i)",
14478
portsTotal);
14479
continue;
14480
}
14481
#endif
14482
14483
if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
14484
== INVALID_SOCKET) {
14485
14486
mg_cry_internal(fc(phys_ctx),
14487
"cannot create socket (entry %i)",
14488
portsTotal);
14489
continue;
14490
}
14491
14492
#if defined(_WIN32)
14493
/* Windows SO_REUSEADDR lets many procs binds to a
14494
* socket, SO_EXCLUSIVEADDRUSE makes the bind fail
14495
* if someone already has the socket -- DTL */
14496
/* NOTE: If SO_EXCLUSIVEADDRUSE is used,
14497
* Windows might need a few seconds before
14498
* the same port can be used again in the
14499
* same process, so a short Sleep may be
14500
* required between mg_stop and mg_start.
14501
*/
14502
if (setsockopt(so.sock,
14503
SOL_SOCKET,
14504
SO_EXCLUSIVEADDRUSE,
14505
(SOCK_OPT_TYPE)&on,
14506
sizeof(on))
14507
!= 0) {
14508
14509
/* Set reuse option, but don't abort on errors. */
14510
mg_cry_internal(
14511
fc(phys_ctx),
14512
"cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
14513
portsTotal);
14514
}
14515
#else
14516
if (setsockopt(so.sock,
14517
SOL_SOCKET,
14518
SO_REUSEADDR,
14519
(SOCK_OPT_TYPE)&on,
14520
sizeof(on))
14521
!= 0) {
14522
14523
/* Set reuse option, but don't abort on errors. */
14524
mg_cry_internal(fc(phys_ctx),
14525
"cannot set socket option SO_REUSEADDR (entry %i)",
14526
portsTotal);
14527
}
14528
#endif
14529
14530
if (ip_version > 4) {
14531
/* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
14532
#if defined(USE_IPV6)
14533
if (ip_version > 6) {
14534
if (so.lsa.sa.sa_family == AF_INET6
14535
&& setsockopt(so.sock,
14536
IPPROTO_IPV6,
14537
IPV6_V6ONLY,
14538
(void *)&off,
14539
sizeof(off))
14540
!= 0) {
14541
14542
/* Set IPv6 only option, but don't abort on errors. */
14543
mg_cry_internal(
14544
fc(phys_ctx),
14545
"cannot set socket option IPV6_V6ONLY=off (entry %i)",
14546
portsTotal);
14547
}
14548
} else {
14549
if (so.lsa.sa.sa_family == AF_INET6
14550
&& setsockopt(so.sock,
14551
IPPROTO_IPV6,
14552
IPV6_V6ONLY,
14553
(void *)&on,
14554
sizeof(on))
14555
!= 0) {
14556
14557
/* Set IPv6 only option, but don't abort on errors. */
14558
mg_cry_internal(
14559
fc(phys_ctx),
14560
"cannot set socket option IPV6_V6ONLY=on (entry %i)",
14561
portsTotal);
14562
}
14563
}
14564
#else
14565
mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
14566
closesocket(so.sock);
14567
so.sock = INVALID_SOCKET;
14568
continue;
14569
#endif
14570
}
14571
14572
if (so.lsa.sa.sa_family == AF_INET) {
14573
14574
len = sizeof(so.lsa.sin);
14575
if (bind(so.sock, &so.lsa.sa, len) != 0) {
14576
mg_cry_internal(fc(phys_ctx),
14577
"cannot bind to %.*s: %d (%s)",
14578
(int)vec.len,
14579
vec.ptr,
14580
(int)ERRNO,
14581
strerror(errno));
14582
closesocket(so.sock);
14583
so.sock = INVALID_SOCKET;
14584
continue;
14585
}
14586
}
14587
#if defined(USE_IPV6)
14588
else if (so.lsa.sa.sa_family == AF_INET6) {
14589
14590
len = sizeof(so.lsa.sin6);
14591
if (bind(so.sock, &so.lsa.sa, len) != 0) {
14592
mg_cry_internal(fc(phys_ctx),
14593
"cannot bind to IPv6 %.*s: %d (%s)",
14594
(int)vec.len,
14595
vec.ptr,
14596
(int)ERRNO,
14597
strerror(errno));
14598
closesocket(so.sock);
14599
so.sock = INVALID_SOCKET;
14600
continue;
14601
}
14602
}
14603
#endif
14604
else {
14605
mg_cry_internal(
14606
fc(phys_ctx),
14607
"cannot bind: address family not supported (entry %i)",
14608
portsTotal);
14609
closesocket(so.sock);
14610
so.sock = INVALID_SOCKET;
14611
continue;
14612
}
14613
14614
if (listen(so.sock, SOMAXCONN) != 0) {
14615
14616
mg_cry_internal(fc(phys_ctx),
14617
"cannot listen to %.*s: %d (%s)",
14618
(int)vec.len,
14619
vec.ptr,
14620
(int)ERRNO,
14621
strerror(errno));
14622
closesocket(so.sock);
14623
so.sock = INVALID_SOCKET;
14624
continue;
14625
}
14626
14627
if ((getsockname(so.sock, &(usa.sa), &len) != 0)
14628
|| (usa.sa.sa_family != so.lsa.sa.sa_family)) {
14629
14630
int err = (int)ERRNO;
14631
mg_cry_internal(fc(phys_ctx),
14632
"call to getsockname failed %.*s: %d (%s)",
14633
(int)vec.len,
14634
vec.ptr,
14635
err,
14636
strerror(errno));
14637
closesocket(so.sock);
14638
so.sock = INVALID_SOCKET;
14639
continue;
14640
}
14641
14642
/* Update lsa port in case of random free ports */
14643
#if defined(USE_IPV6)
14644
if (so.lsa.sa.sa_family == AF_INET6) {
14645
so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
14646
} else
14647
#endif
14648
{
14649
so.lsa.sin.sin_port = usa.sin.sin_port;
14650
}
14651
14652
if ((ptr = (struct socket *)
14653
mg_realloc_ctx(phys_ctx->listening_sockets,
14654
(phys_ctx->num_listening_sockets + 1)
14655
* sizeof(phys_ctx->listening_sockets[0]),
14656
phys_ctx))
14657
== NULL) {
14658
14659
mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
14660
closesocket(so.sock);
14661
so.sock = INVALID_SOCKET;
14662
continue;
14663
}
14664
14665
if ((pfd = (struct pollfd *)
14666
mg_realloc_ctx(phys_ctx->listening_socket_fds,
14667
(phys_ctx->num_listening_sockets + 1)
14668
* sizeof(phys_ctx->listening_socket_fds[0]),
14669
phys_ctx))
14670
== NULL) {
14671
14672
mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
14673
closesocket(so.sock);
14674
so.sock = INVALID_SOCKET;
14675
mg_free(ptr);
14676
continue;
14677
}
14678
14679
set_close_on_exec(so.sock, fc(phys_ctx));
14680
phys_ctx->listening_sockets = ptr;
14681
phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
14682
phys_ctx->listening_socket_fds = pfd;
14683
phys_ctx->num_listening_sockets++;
14684
portsOk++;
14685
}
14686
14687
if (portsOk != portsTotal) {
14688
close_all_listening_sockets(phys_ctx);
14689
portsOk = 0;
14690
}
14691
14692
return portsOk;
14693
}
14694
14695
14696
static const char *
14697
header_val(const struct mg_connection *conn, const char *header)
14698
{
14699
const char *header_value;
14700
14701
if ((header_value = mg_get_header(conn, header)) == NULL) {
14702
return "-";
14703
} else {
14704
return header_value;
14705
}
14706
}
14707
14708
14709
#if defined(MG_EXTERNAL_FUNCTION_log_access)
14710
static void log_access(const struct mg_connection *conn);
14711
#include "external_log_access.inl"
14712
#else
14713
14714
static void
14715
log_access(const struct mg_connection *conn)
14716
{
14717
const struct mg_request_info *ri;
14718
struct mg_file fi;
14719
char date[64], src_addr[IP_ADDR_STR_LEN];
14720
struct tm *tm;
14721
14722
const char *referer;
14723
const char *user_agent;
14724
14725
char buf[4096];
14726
14727
if (!conn || !conn->dom_ctx) {
14728
return;
14729
}
14730
14731
if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
14732
if (mg_fopen(conn,
14733
conn->dom_ctx->config[ACCESS_LOG_FILE],
14734
MG_FOPEN_MODE_APPEND,
14735
&fi)
14736
== 0) {
14737
fi.access.fp = NULL;
14738
}
14739
} else {
14740
fi.access.fp = NULL;
14741
}
14742
14743
/* Log is written to a file and/or a callback. If both are not set,
14744
* executing the rest of the function is pointless. */
14745
if ((fi.access.fp == NULL)
14746
&& (conn->phys_ctx->callbacks.log_access == NULL)) {
14747
return;
14748
}
14749
14750
tm = localtime(&conn->conn_birth_time);
14751
if (tm != NULL) {
14752
strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
14753
} else {
14754
mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
14755
date[sizeof(date) - 1] = '\0';
14756
}
14757
14758
ri = &conn->request_info;
14759
14760
sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
14761
referer = header_val(conn, "Referer");
14762
user_agent = header_val(conn, "User-Agent");
14763
14764
mg_snprintf(conn,
14765
NULL, /* Ignore truncation in access log */
14766
buf,
14767
sizeof(buf),
14768
"%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
14769
src_addr,
14770
(ri->remote_user == NULL) ? "-" : ri->remote_user,
14771
date,
14772
ri->request_method ? ri->request_method : "-",
14773
ri->request_uri ? ri->request_uri : "-",
14774
ri->query_string ? "?" : "",
14775
ri->query_string ? ri->query_string : "",
14776
ri->http_version,
14777
conn->status_code,
14778
conn->num_bytes_sent,
14779
referer,
14780
user_agent);
14781
14782
if (conn->phys_ctx->callbacks.log_access) {
14783
conn->phys_ctx->callbacks.log_access(conn, buf);
14784
}
14785
14786
if (fi.access.fp) {
14787
int ok = 1;
14788
flockfile(fi.access.fp);
14789
if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
14790
ok = 0;
14791
}
14792
if (fflush(fi.access.fp) != 0) {
14793
ok = 0;
14794
}
14795
funlockfile(fi.access.fp);
14796
if (mg_fclose(&fi.access) != 0) {
14797
ok = 0;
14798
}
14799
if (!ok) {
14800
mg_cry_internal(conn,
14801
"Error writing log file %s",
14802
conn->dom_ctx->config[ACCESS_LOG_FILE]);
14803
}
14804
}
14805
}
14806
14807
#endif /* Externally provided function */
14808
14809
14810
/* Verify given socket address against the ACL.
14811
* Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
14812
*/
14813
static int
14814
check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
14815
{
14816
int allowed, flag;
14817
uint32_t net, mask;
14818
struct vec vec;
14819
14820
if (phys_ctx) {
14821
const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
14822
14823
/* If any ACL is set, deny by default */
14824
allowed = (list == NULL) ? '+' : '-';
14825
14826
while ((list = next_option(list, &vec, NULL)) != NULL) {
14827
flag = vec.ptr[0];
14828
if ((flag != '+' && flag != '-')
14829
|| (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
14830
mg_cry_internal(fc(phys_ctx),
14831
"%s: subnet must be [+|-]x.x.x.x[/x]",
14832
__func__);
14833
return -1;
14834
}
14835
14836
if (net == (remote_ip & mask)) {
14837
allowed = flag;
14838
}
14839
}
14840
14841
return allowed == '+';
14842
}
14843
return -1;
14844
}
14845
14846
14847
#if !defined(_WIN32)
14848
static int
14849
set_uid_option(struct mg_context *phys_ctx)
14850
{
14851
int success = 0;
14852
14853
if (phys_ctx) {
14854
/* We are currently running as curr_uid. */
14855
const uid_t curr_uid = getuid();
14856
/* If set, we want to run as run_as_user. */
14857
const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
14858
const struct passwd *to_pw = NULL;
14859
14860
if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
14861
/* run_as_user does not exist on the system. We can't proceed
14862
* further. */
14863
mg_cry_internal(fc(phys_ctx),
14864
"%s: unknown user [%s]",
14865
__func__,
14866
run_as_user);
14867
} else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
14868
/* There was either no request to change user, or we're already
14869
* running as run_as_user. Nothing else to do.
14870
*/
14871
success = 1;
14872
} else {
14873
/* Valid change request. */
14874
if (setgid(to_pw->pw_gid) == -1) {
14875
mg_cry_internal(fc(phys_ctx),
14876
"%s: setgid(%s): %s",
14877
__func__,
14878
run_as_user,
14879
strerror(errno));
14880
} else if (setgroups(0, NULL) == -1) {
14881
mg_cry_internal(fc(phys_ctx),
14882
"%s: setgroups(): %s",
14883
__func__,
14884
strerror(errno));
14885
} else if (setuid(to_pw->pw_uid) == -1) {
14886
mg_cry_internal(fc(phys_ctx),
14887
"%s: setuid(%s): %s",
14888
__func__,
14889
run_as_user,
14890
strerror(errno));
14891
} else {
14892
success = 1;
14893
}
14894
}
14895
}
14896
14897
return success;
14898
}
14899
#endif /* !_WIN32 */
14900
14901
14902
static void
14903
tls_dtor(void *key)
14904
{
14905
struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
14906
/* key == pthread_getspecific(sTlsKey); */
14907
14908
if (tls) {
14909
if (tls->is_master == 2) {
14910
tls->is_master = -3; /* Mark memory as dead */
14911
mg_free(tls);
14912
}
14913
}
14914
pthread_setspecific(sTlsKey, NULL);
14915
}
14916
14917
14918
#if !defined(NO_SSL)
14919
14920
static int ssl_use_pem_file(struct mg_context *phys_ctx,
14921
struct mg_domain_context *dom_ctx,
14922
const char *pem,
14923
const char *chain);
14924
static const char *ssl_error(void);
14925
14926
14927
static int
14928
refresh_trust(struct mg_connection *conn)
14929
{
14930
static int reload_lock = 0;
14931
static long int data_check = 0;
14932
volatile int *p_reload_lock = (volatile int *)&reload_lock;
14933
14934
struct stat cert_buf;
14935
long int t;
14936
const char *pem;
14937
const char *chain;
14938
int should_verify_peer;
14939
14940
if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
14941
/* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
14942
* refresh_trust still can not work. */
14943
return 0;
14944
}
14945
chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
14946
if (chain == NULL) {
14947
/* pem is not NULL here */
14948
chain = pem;
14949
}
14950
if (*chain == 0) {
14951
chain = NULL;
14952
}
14953
14954
t = data_check;
14955
if (stat(pem, &cert_buf) != -1) {
14956
t = (long int)cert_buf.st_mtime;
14957
}
14958
14959
if (data_check != t) {
14960
data_check = t;
14961
14962
should_verify_peer = 0;
14963
if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
14964
if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
14965
== 0) {
14966
should_verify_peer = 1;
14967
} else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
14968
"optional")
14969
== 0) {
14970
should_verify_peer = 1;
14971
}
14972
}
14973
14974
if (should_verify_peer) {
14975
char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
14976
char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
14977
if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
14978
ca_file,
14979
ca_path)
14980
!= 1) {
14981
mg_cry_internal(
14982
fc(conn->phys_ctx),
14983
"SSL_CTX_load_verify_locations error: %s "
14984
"ssl_verify_peer requires setting "
14985
"either ssl_ca_path or ssl_ca_file. Is any of them "
14986
"present in "
14987
"the .conf file?",
14988
ssl_error());
14989
return 0;
14990
}
14991
}
14992
14993
if (1 == mg_atomic_inc(p_reload_lock)) {
14994
if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
14995
== 0) {
14996
return 0;
14997
}
14998
*p_reload_lock = 0;
14999
}
15000
}
15001
/* lock while cert is reloading */
15002
while (*p_reload_lock) {
15003
sleep(1);
15004
}
15005
15006
return 1;
15007
}
15008
15009
#if defined(OPENSSL_API_1_1)
15010
#else
15011
static pthread_mutex_t *ssl_mutexes;
15012
#endif /* OPENSSL_API_1_1 */
15013
15014
static int
15015
sslize(struct mg_connection *conn,
15016
SSL_CTX *s,
15017
int (*func)(SSL *),
15018
volatile int *stop_server)
15019
{
15020
int ret, err;
15021
int short_trust;
15022
unsigned i;
15023
15024
if (!conn) {
15025
return 0;
15026
}
15027
15028
short_trust =
15029
(conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
15030
&& (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
15031
15032
if (short_trust) {
15033
int trust_ret = refresh_trust(conn);
15034
if (!trust_ret) {
15035
return trust_ret;
15036
}
15037
}
15038
15039
conn->ssl = SSL_new(s);
15040
if (conn->ssl == NULL) {
15041
return 0;
15042
}
15043
SSL_set_app_data(conn->ssl, (char *)conn);
15044
15045
ret = SSL_set_fd(conn->ssl, conn->client.sock);
15046
if (ret != 1) {
15047
err = SSL_get_error(conn->ssl, ret);
15048
mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
15049
SSL_free(conn->ssl);
15050
conn->ssl = NULL;
15051
/* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
15052
* https://wiki.openssl.org/index.php/Talk:Library_Initialization */
15053
#if !defined(OPENSSL_API_1_1)
15054
ERR_remove_state(0);
15055
#endif
15056
return 0;
15057
}
15058
15059
/* SSL functions may fail and require to be called again:
15060
* see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
15061
* Here "func" could be SSL_connect or SSL_accept. */
15062
for (i = 16; i <= 1024; i *= 2) {
15063
ret = func(conn->ssl);
15064
if (ret != 1) {
15065
err = SSL_get_error(conn->ssl, ret);
15066
if ((err == SSL_ERROR_WANT_CONNECT)
15067
|| (err == SSL_ERROR_WANT_ACCEPT)
15068
|| (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
15069
|| (err == SSL_ERROR_WANT_X509_LOOKUP)) {
15070
/* Need to retry the function call "later".
15071
* See https://linux.die.net/man/3/ssl_get_error
15072
* This is typical for non-blocking sockets. */
15073
if (*stop_server) {
15074
/* Don't wait if the server is going to be stopped. */
15075
break;
15076
}
15077
mg_sleep(i);
15078
15079
} else if (err == SSL_ERROR_SYSCALL) {
15080
/* This is an IO error. Look at errno. */
15081
err = errno;
15082
mg_cry_internal(conn, "SSL syscall error %i", err);
15083
break;
15084
15085
} else {
15086
/* This is an SSL specific error, e.g. SSL_ERROR_SSL */
15087
mg_cry_internal(conn, "sslize error: %s", ssl_error());
15088
break;
15089
}
15090
15091
} else {
15092
/* success */
15093
break;
15094
}
15095
}
15096
15097
if (ret != 1) {
15098
SSL_free(conn->ssl);
15099
conn->ssl = NULL;
15100
/* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
15101
* https://wiki.openssl.org/index.php/Talk:Library_Initialization */
15102
#if !defined(OPENSSL_API_1_1)
15103
ERR_remove_state(0);
15104
#endif
15105
return 0;
15106
}
15107
15108
return 1;
15109
}
15110
15111
15112
/* Return OpenSSL error message (from CRYPTO lib) */
15113
static const char *
15114
ssl_error(void)
15115
{
15116
unsigned long err;
15117
err = ERR_get_error();
15118
return ((err == 0) ? "" : ERR_error_string(err, NULL));
15119
}
15120
15121
15122
static int
15123
hexdump2string(void *mem, int memlen, char *buf, int buflen)
15124
{
15125
int i;
15126
const char hexdigit[] = "0123456789abcdef";
15127
15128
if ((memlen <= 0) || (buflen <= 0)) {
15129
return 0;
15130
}
15131
if (buflen < (3 * memlen)) {
15132
return 0;
15133
}
15134
15135
for (i = 0; i < memlen; i++) {
15136
if (i > 0) {
15137
buf[3 * i - 1] = ' ';
15138
}
15139
buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
15140
buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
15141
}
15142
buf[3 * memlen - 1] = 0;
15143
15144
return 1;
15145
}
15146
15147
15148
static void
15149
ssl_get_client_cert_info(struct mg_connection *conn)
15150
{
15151
X509 *cert = SSL_get_peer_certificate(conn->ssl);
15152
if (cert) {
15153
char str_subject[1024];
15154
char str_issuer[1024];
15155
char str_finger[1024];
15156
unsigned char buf[256];
15157
char *str_serial = NULL;
15158
unsigned int ulen;
15159
int ilen;
15160
unsigned char *tmp_buf;
15161
unsigned char *tmp_p;
15162
15163
/* Handle to algorithm used for fingerprint */
15164
const EVP_MD *digest = EVP_get_digestbyname("sha1");
15165
15166
/* Get Subject and issuer */
15167
X509_NAME *subj = X509_get_subject_name(cert);
15168
X509_NAME *iss = X509_get_issuer_name(cert);
15169
15170
/* Get serial number */
15171
ASN1_INTEGER *serial = X509_get_serialNumber(cert);
15172
15173
/* Translate serial number to a hex string */
15174
BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
15175
str_serial = BN_bn2hex(serial_bn);
15176
BN_free(serial_bn);
15177
15178
/* Translate subject and issuer to a string */
15179
(void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
15180
(void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
15181
15182
/* Calculate SHA1 fingerprint and store as a hex string */
15183
ulen = 0;
15184
15185
/* ASN1_digest is deprecated. Do the calculation manually,
15186
* using EVP_Digest. */
15187
ilen = i2d_X509(cert, NULL);
15188
tmp_buf = (ilen > 0)
15189
? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
15190
conn->phys_ctx)
15191
: NULL;
15192
if (tmp_buf) {
15193
tmp_p = tmp_buf;
15194
(void)i2d_X509(cert, &tmp_p);
15195
if (!EVP_Digest(
15196
tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
15197
ulen = 0;
15198
}
15199
mg_free(tmp_buf);
15200
}
15201
15202
if (!hexdump2string(
15203
buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
15204
*str_finger = 0;
15205
}
15206
15207
conn->request_info.client_cert = (struct mg_client_cert *)
15208
mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
15209
if (conn->request_info.client_cert) {
15210
conn->request_info.client_cert->peer_cert = (void *)cert;
15211
conn->request_info.client_cert->subject =
15212
mg_strdup_ctx(str_subject, conn->phys_ctx);
15213
conn->request_info.client_cert->issuer =
15214
mg_strdup_ctx(str_issuer, conn->phys_ctx);
15215
conn->request_info.client_cert->serial =
15216
mg_strdup_ctx(str_serial, conn->phys_ctx);
15217
conn->request_info.client_cert->finger =
15218
mg_strdup_ctx(str_finger, conn->phys_ctx);
15219
} else {
15220
mg_cry_internal(conn,
15221
"%s",
15222
"Out of memory: Cannot allocate memory for client "
15223
"certificate");
15224
}
15225
15226
/* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
15227
* see https://linux.die.net/man/3/bn_bn2hex */
15228
OPENSSL_free(str_serial);
15229
}
15230
}
15231
15232
15233
#if defined(OPENSSL_API_1_1)
15234
#else
15235
static void
15236
ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
15237
{
15238
(void)line;
15239
(void)file;
15240
15241
if (mode & 1) {
15242
/* 1 is CRYPTO_LOCK */
15243
(void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
15244
} else {
15245
(void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
15246
}
15247
}
15248
#endif /* OPENSSL_API_1_1 */
15249
15250
15251
#if !defined(NO_SSL_DL)
15252
static void *
15253
load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
15254
{
15255
union {
15256
void *p;
15257
void (*fp)(void);
15258
} u;
15259
void *dll_handle;
15260
struct ssl_func *fp;
15261
int ok;
15262
int truncated = 0;
15263
15264
if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
15265
mg_snprintf(NULL,
15266
NULL, /* No truncation check for ebuf */
15267
ebuf,
15268
ebuf_len,
15269
"%s: cannot load %s",
15270
__func__,
15271
dll_name);
15272
return NULL;
15273
}
15274
15275
ok = 1;
15276
for (fp = sw; fp->name != NULL; fp++) {
15277
#if defined(_WIN32)
15278
/* GetProcAddress() returns pointer to function */
15279
u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
15280
#else
15281
/* dlsym() on UNIX returns void *. ISO C forbids casts of data
15282
* pointers to function pointers. We need to use a union to make a
15283
* cast. */
15284
u.p = dlsym(dll_handle, fp->name);
15285
#endif /* _WIN32 */
15286
if (u.fp == NULL) {
15287
if (ok) {
15288
mg_snprintf(NULL,
15289
&truncated,
15290
ebuf,
15291
ebuf_len,
15292
"%s: %s: cannot find %s",
15293
__func__,
15294
dll_name,
15295
fp->name);
15296
ok = 0;
15297
} else {
15298
size_t cur_len = strlen(ebuf);
15299
if (!truncated) {
15300
mg_snprintf(NULL,
15301
&truncated,
15302
ebuf + cur_len,
15303
ebuf_len - cur_len - 3,
15304
", %s",
15305
fp->name);
15306
if (truncated) {
15307
/* If truncated, add "..." */
15308
strcat(ebuf, "...");
15309
}
15310
}
15311
}
15312
/* Debug:
15313
* printf("Missing function: %s\n", fp->name); */
15314
} else {
15315
fp->ptr = u.fp;
15316
}
15317
}
15318
15319
if (!ok) {
15320
(void)dlclose(dll_handle);
15321
return NULL;
15322
}
15323
15324
return dll_handle;
15325
}
15326
15327
15328
static void *ssllib_dll_handle; /* Store the ssl library handle. */
15329
static void *cryptolib_dll_handle; /* Store the crypto library handle. */
15330
15331
#endif /* NO_SSL_DL */
15332
15333
15334
#if defined(SSL_ALREADY_INITIALIZED)
15335
static int cryptolib_users = 1; /* Reference counter for crypto library. */
15336
#else
15337
static int cryptolib_users = 0; /* Reference counter for crypto library. */
15338
#endif
15339
15340
15341
static int
15342
initialize_ssl(char *ebuf, size_t ebuf_len)
15343
{
15344
#if defined(OPENSSL_API_1_1)
15345
if (ebuf_len > 0) {
15346
ebuf[0] = 0;
15347
}
15348
15349
#if !defined(NO_SSL_DL)
15350
if (!cryptolib_dll_handle) {
15351
cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
15352
if (!cryptolib_dll_handle) {
15353
mg_snprintf(NULL,
15354
NULL, /* No truncation check for ebuf */
15355
ebuf,
15356
ebuf_len,
15357
"%s: error loading library %s",
15358
__func__,
15359
CRYPTO_LIB);
15360
DEBUG_TRACE("%s", ebuf);
15361
return 0;
15362
}
15363
}
15364
#endif /* NO_SSL_DL */
15365
15366
if (mg_atomic_inc(&cryptolib_users) > 1) {
15367
return 1;
15368
}
15369
15370
#else /* not OPENSSL_API_1_1 */
15371
int i, num_locks;
15372
size_t size;
15373
15374
if (ebuf_len > 0) {
15375
ebuf[0] = 0;
15376
}
15377
15378
#if !defined(NO_SSL_DL)
15379
if (!cryptolib_dll_handle) {
15380
cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
15381
if (!cryptolib_dll_handle) {
15382
mg_snprintf(NULL,
15383
NULL, /* No truncation check for ebuf */
15384
ebuf,
15385
ebuf_len,
15386
"%s: error loading library %s",
15387
__func__,
15388
CRYPTO_LIB);
15389
DEBUG_TRACE("%s", ebuf);
15390
return 0;
15391
}
15392
}
15393
#endif /* NO_SSL_DL */
15394
15395
if (mg_atomic_inc(&cryptolib_users) > 1) {
15396
return 1;
15397
}
15398
15399
/* Initialize locking callbacks, needed for thread safety.
15400
* http://www.openssl.org/support/faq.html#PROG1
15401
*/
15402
num_locks = CRYPTO_num_locks();
15403
if (num_locks < 0) {
15404
num_locks = 0;
15405
}
15406
size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
15407
15408
/* allocate mutex array, if required */
15409
if (num_locks == 0) {
15410
/* No mutex array required */
15411
ssl_mutexes = NULL;
15412
} else {
15413
/* Mutex array required - allocate it */
15414
ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
15415
15416
/* Check OOM */
15417
if (ssl_mutexes == NULL) {
15418
mg_snprintf(NULL,
15419
NULL, /* No truncation check for ebuf */
15420
ebuf,
15421
ebuf_len,
15422
"%s: cannot allocate mutexes: %s",
15423
__func__,
15424
ssl_error());
15425
DEBUG_TRACE("%s", ebuf);
15426
return 0;
15427
}
15428
15429
/* initialize mutex array */
15430
for (i = 0; i < num_locks; i++) {
15431
if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
15432
mg_snprintf(NULL,
15433
NULL, /* No truncation check for ebuf */
15434
ebuf,
15435
ebuf_len,
15436
"%s: error initializing mutex %i of %i",
15437
__func__,
15438
i,
15439
num_locks);
15440
DEBUG_TRACE("%s", ebuf);
15441
mg_free(ssl_mutexes);
15442
return 0;
15443
}
15444
}
15445
}
15446
15447
CRYPTO_set_locking_callback(&ssl_locking_callback);
15448
CRYPTO_set_id_callback(&mg_current_thread_id);
15449
#endif /* OPENSSL_API_1_1 */
15450
15451
#if !defined(NO_SSL_DL)
15452
if (!ssllib_dll_handle) {
15453
ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
15454
if (!ssllib_dll_handle) {
15455
#if !defined(OPENSSL_API_1_1)
15456
mg_free(ssl_mutexes);
15457
#endif
15458
DEBUG_TRACE("%s", ebuf);
15459
return 0;
15460
}
15461
}
15462
#endif /* NO_SSL_DL */
15463
15464
#if defined(OPENSSL_API_1_1)
15465
/* Initialize SSL library */
15466
OPENSSL_init_ssl(0, NULL);
15467
OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
15468
| OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
15469
NULL);
15470
#else
15471
/* Initialize SSL library */
15472
SSL_library_init();
15473
SSL_load_error_strings();
15474
#endif
15475
15476
return 1;
15477
}
15478
15479
15480
static int
15481
ssl_use_pem_file(struct mg_context *phys_ctx,
15482
struct mg_domain_context *dom_ctx,
15483
const char *pem,
15484
const char *chain)
15485
{
15486
if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
15487
mg_cry_internal(fc(phys_ctx),
15488
"%s: cannot open certificate file %s: %s",
15489
__func__,
15490
pem,
15491
ssl_error());
15492
return 0;
15493
}
15494
15495
/* could use SSL_CTX_set_default_passwd_cb_userdata */
15496
if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
15497
mg_cry_internal(fc(phys_ctx),
15498
"%s: cannot open private key file %s: %s",
15499
__func__,
15500
pem,
15501
ssl_error());
15502
return 0;
15503
}
15504
15505
if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
15506
mg_cry_internal(fc(phys_ctx),
15507
"%s: certificate and private key do not match: %s",
15508
__func__,
15509
pem);
15510
return 0;
15511
}
15512
15513
/* In contrast to OpenSSL, wolfSSL does not support certificate
15514
* chain files that contain private keys and certificates in
15515
* SSL_CTX_use_certificate_chain_file.
15516
* The CivetWeb-Server used pem-Files that contained both information.
15517
* In order to make wolfSSL work, it is split in two files.
15518
* One file that contains key and certificate used by the server and
15519
* an optional chain file for the ssl stack.
15520
*/
15521
if (chain) {
15522
if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
15523
mg_cry_internal(fc(phys_ctx),
15524
"%s: cannot use certificate chain file %s: %s",
15525
__func__,
15526
pem,
15527
ssl_error());
15528
return 0;
15529
}
15530
}
15531
return 1;
15532
}
15533
15534
15535
#if defined(OPENSSL_API_1_1)
15536
static unsigned long
15537
ssl_get_protocol(int version_id)
15538
{
15539
long unsigned ret = (long unsigned)SSL_OP_ALL;
15540
if (version_id > 0)
15541
ret |= SSL_OP_NO_SSLv2;
15542
if (version_id > 1)
15543
ret |= SSL_OP_NO_SSLv3;
15544
if (version_id > 2)
15545
ret |= SSL_OP_NO_TLSv1;
15546
if (version_id > 3)
15547
ret |= SSL_OP_NO_TLSv1_1;
15548
return ret;
15549
}
15550
#else
15551
static long
15552
ssl_get_protocol(int version_id)
15553
{
15554
long ret = (long)SSL_OP_ALL;
15555
if (version_id > 0)
15556
ret |= SSL_OP_NO_SSLv2;
15557
if (version_id > 1)
15558
ret |= SSL_OP_NO_SSLv3;
15559
if (version_id > 2)
15560
ret |= SSL_OP_NO_TLSv1;
15561
if (version_id > 3)
15562
ret |= SSL_OP_NO_TLSv1_1;
15563
return ret;
15564
}
15565
#endif /* OPENSSL_API_1_1 */
15566
15567
15568
/* SSL callback documentation:
15569
* https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
15570
* https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
15571
* https://linux.die.net/man/3/ssl_set_info_callback */
15572
/* Note: There is no "const" for the first argument in the documentation,
15573
* however some (maybe most, but not all) headers of OpenSSL versions /
15574
* OpenSSL compatibility layers have it. Having a different definition
15575
* will cause a warning in C and an error in C++. With inconsitent
15576
* definitions of this function, having a warning in one version or
15577
* another is unavoidable. */
15578
static void
15579
ssl_info_callback(SSL *ssl, int what, int ret)
15580
{
15581
(void)ret;
15582
15583
if (what & SSL_CB_HANDSHAKE_START) {
15584
SSL_get_app_data(ssl);
15585
}
15586
if (what & SSL_CB_HANDSHAKE_DONE) {
15587
/* TODO: check for openSSL 1.1 */
15588
//#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
15589
// ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
15590
}
15591
}
15592
15593
15594
static int
15595
ssl_servername_callback(SSL *ssl, int *ad, void *arg)
15596
{
15597
struct mg_context *ctx = (struct mg_context *)arg;
15598
struct mg_domain_context *dom =
15599
(struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
15600
15601
#if defined(GCC_DIAGNOSTIC)
15602
#pragma GCC diagnostic push
15603
#pragma GCC diagnostic ignored "-Wcast-align"
15604
#endif /* defined(GCC_DIAGNOSTIC) */
15605
15606
/* We used an aligned pointer in SSL_set_app_data */
15607
struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
15608
15609
#if defined(GCC_DIAGNOSTIC)
15610
#pragma GCC diagnostic pop
15611
#endif /* defined(GCC_DIAGNOSTIC) */
15612
15613
const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
15614
15615
(void)ad;
15616
15617
if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
15618
DEBUG_TRACE("%s", "internal error - assertion failed");
15619
return SSL_TLSEXT_ERR_NOACK;
15620
}
15621
15622
/* Old clients (Win XP) will not support SNI. Then, there
15623
* is no server name available in the request - we can
15624
* only work with the default certificate.
15625
* Multiple HTTPS hosts on one IP+port are only possible
15626
* with a certificate containing all alternative names.
15627
*/
15628
if ((servername == NULL) || (*servername == 0)) {
15629
DEBUG_TRACE("%s", "SSL connection not supporting SNI");
15630
conn->dom_ctx = &(ctx->dd);
15631
SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
15632
return SSL_TLSEXT_ERR_NOACK;
15633
}
15634
15635
DEBUG_TRACE("TLS connection to host %s", servername);
15636
15637
while (dom) {
15638
if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
15639
15640
/* Found matching domain */
15641
DEBUG_TRACE("TLS domain %s found",
15642
dom->config[AUTHENTICATION_DOMAIN]);
15643
SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
15644
conn->dom_ctx = dom;
15645
return SSL_TLSEXT_ERR_OK;
15646
}
15647
dom = dom->next;
15648
}
15649
15650
/* Default domain */
15651
DEBUG_TRACE("TLS default domain %s used",
15652
ctx->dd.config[AUTHENTICATION_DOMAIN]);
15653
conn->dom_ctx = &(ctx->dd);
15654
SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
15655
return SSL_TLSEXT_ERR_OK;
15656
}
15657
15658
15659
/* Setup SSL CTX as required by CivetWeb */
15660
static int
15661
init_ssl_ctx_impl(struct mg_context *phys_ctx,
15662
struct mg_domain_context *dom_ctx,
15663
const char *pem,
15664
const char *chain)
15665
{
15666
int callback_ret;
15667
int should_verify_peer;
15668
int peer_certificate_optional;
15669
const char *ca_path;
15670
const char *ca_file;
15671
int use_default_verify_paths;
15672
int verify_depth;
15673
struct timespec now_mt;
15674
md5_byte_t ssl_context_id[16];
15675
md5_state_t md5state;
15676
int protocol_ver;
15677
15678
#if defined(OPENSSL_API_1_1)
15679
if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
15680
mg_cry_internal(fc(phys_ctx),
15681
"SSL_CTX_new (server) error: %s",
15682
ssl_error());
15683
return 0;
15684
}
15685
#else
15686
if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
15687
mg_cry_internal(fc(phys_ctx),
15688
"SSL_CTX_new (server) error: %s",
15689
ssl_error());
15690
return 0;
15691
}
15692
#endif /* OPENSSL_API_1_1 */
15693
15694
SSL_CTX_clear_options(dom_ctx->ssl_ctx,
15695
SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
15696
| SSL_OP_NO_TLSv1_1);
15697
protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
15698
SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
15699
SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
15700
SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
15701
SSL_CTX_set_options(dom_ctx->ssl_ctx,
15702
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
15703
SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
15704
#if !defined(NO_SSL_DL)
15705
SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
15706
#endif /* NO_SSL_DL */
15707
15708
#if defined(__clang__)
15709
#pragma clang diagnostic push
15710
#pragma clang diagnostic ignored "-Wincompatible-pointer-types"
15711
#endif
15712
#if defined(GCC_DIAGNOSTIC)
15713
#pragma GCC diagnostic push
15714
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
15715
#endif
15716
/* Depending on the OpenSSL version, the callback may be
15717
* 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
15718
* yielding in an "incompatible-pointer-type" warning for the other
15719
* version. It seems to be "unclear" what is correct:
15720
* https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
15721
* https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
15722
* https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
15723
* https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
15724
* Disable this warning here.
15725
* Alternative would be a version dependent ssl_info_callback and
15726
* a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
15727
*/
15728
SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
15729
15730
15731
SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
15732
ssl_servername_callback);
15733
SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
15734
15735
#if defined(GCC_DIAGNOSTIC)
15736
#pragma GCC diagnostic pop
15737
#endif
15738
#if defined(__clang__)
15739
#pragma clang diagnostic pop
15740
#endif
15741
15742
/* If a callback has been specified, call it. */
15743
callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
15744
? 0
15745
: (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
15746
phys_ctx->user_data));
15747
15748
/* If callback returns 0, civetweb sets up the SSL certificate.
15749
* If it returns 1, civetweb assumes the calback already did this.
15750
* If it returns -1, initializing ssl fails. */
15751
if (callback_ret < 0) {
15752
mg_cry_internal(fc(phys_ctx),
15753
"SSL callback returned error: %i",
15754
callback_ret);
15755
return 0;
15756
}
15757
if (callback_ret > 0) {
15758
/* Callback did everything. */
15759
return 1;
15760
}
15761
15762
/* Use some combination of start time, domain and port as a SSL
15763
* context ID. This should be unique on the current machine. */
15764
md5_init(&md5state);
15765
clock_gettime(CLOCK_MONOTONIC, &now_mt);
15766
md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
15767
md5_append(&md5state,
15768
(const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
15769
strlen(phys_ctx->dd.config[LISTENING_PORTS]));
15770
md5_append(&md5state,
15771
(const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
15772
strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
15773
md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
15774
md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
15775
md5_finish(&md5state, ssl_context_id);
15776
15777
SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
15778
(unsigned char *)ssl_context_id,
15779
sizeof(ssl_context_id));
15780
15781
if (pem != NULL) {
15782
if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
15783
return 0;
15784
}
15785
}
15786
15787
/* Should we support client certificates? */
15788
/* Default is "no". */
15789
should_verify_peer = 0;
15790
peer_certificate_optional = 0;
15791
if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
15792
if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
15793
/* Yes, they are mandatory */
15794
should_verify_peer = 1;
15795
peer_certificate_optional = 0;
15796
} else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
15797
"optional")
15798
== 0) {
15799
/* Yes, they are optional */
15800
should_verify_peer = 1;
15801
peer_certificate_optional = 1;
15802
}
15803
}
15804
15805
use_default_verify_paths =
15806
(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
15807
&& (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
15808
== 0);
15809
15810
if (should_verify_peer) {
15811
ca_path = dom_ctx->config[SSL_CA_PATH];
15812
ca_file = dom_ctx->config[SSL_CA_FILE];
15813
if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
15814
!= 1) {
15815
mg_cry_internal(fc(phys_ctx),
15816
"SSL_CTX_load_verify_locations error: %s "
15817
"ssl_verify_peer requires setting "
15818
"either ssl_ca_path or ssl_ca_file. "
15819
"Is any of them present in the "
15820
".conf file?",
15821
ssl_error());
15822
return 0;
15823
}
15824
15825
if (peer_certificate_optional) {
15826
SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
15827
} else {
15828
SSL_CTX_set_verify(dom_ctx->ssl_ctx,
15829
SSL_VERIFY_PEER
15830
| SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
15831
NULL);
15832
}
15833
15834
if (use_default_verify_paths
15835
&& (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
15836
mg_cry_internal(fc(phys_ctx),
15837
"SSL_CTX_set_default_verify_paths error: %s",
15838
ssl_error());
15839
return 0;
15840
}
15841
15842
if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
15843
verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
15844
SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
15845
}
15846
}
15847
15848
if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
15849
if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
15850
dom_ctx->config[SSL_CIPHER_LIST])
15851
!= 1) {
15852
mg_cry_internal(fc(phys_ctx),
15853
"SSL_CTX_set_cipher_list error: %s",
15854
ssl_error());
15855
}
15856
}
15857
15858
return 1;
15859
}
15860
15861
15862
/* Check if SSL is required.
15863
* If so, dynamically load SSL library
15864
* and set up ctx->ssl_ctx pointer. */
15865
static int
15866
init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
15867
{
15868
void *ssl_ctx = 0;
15869
int callback_ret;
15870
const char *pem;
15871
const char *chain;
15872
char ebuf[128];
15873
15874
if (!phys_ctx) {
15875
return 0;
15876
}
15877
15878
if (!dom_ctx) {
15879
dom_ctx = &(phys_ctx->dd);
15880
}
15881
15882
if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
15883
/* No SSL port is set. No need to setup SSL. */
15884
return 1;
15885
}
15886
15887
/* Check for external SSL_CTX */
15888
callback_ret =
15889
(phys_ctx->callbacks.external_ssl_ctx == NULL)
15890
? 0
15891
: (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
15892
phys_ctx->user_data));
15893
15894
if (callback_ret < 0) {
15895
mg_cry_internal(fc(phys_ctx),
15896
"external_ssl_ctx callback returned error: %i",
15897
callback_ret);
15898
return 0;
15899
} else if (callback_ret > 0) {
15900
dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
15901
if (!initialize_ssl(ebuf, sizeof(ebuf))) {
15902
mg_cry_internal(fc(phys_ctx), "%s", ebuf);
15903
return 0;
15904
}
15905
return 1;
15906
}
15907
/* else: external_ssl_ctx does not exist or returns 0,
15908
* CivetWeb should continue initializing SSL */
15909
15910
/* If PEM file is not specified and the init_ssl callback
15911
* is not specified, setup will fail. */
15912
if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
15913
&& (phys_ctx->callbacks.init_ssl == NULL)) {
15914
/* No certificate and no callback:
15915
* Essential data to set up TLS is missing.
15916
*/
15917
mg_cry_internal(fc(phys_ctx),
15918
"Initializing SSL failed: -%s is not set",
15919
config_options[SSL_CERTIFICATE].name);
15920
return 0;
15921
}
15922
15923
chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
15924
if (chain == NULL) {
15925
chain = pem;
15926
}
15927
if ((chain != NULL) && (*chain == 0)) {
15928
chain = NULL;
15929
}
15930
15931
if (!initialize_ssl(ebuf, sizeof(ebuf))) {
15932
mg_cry_internal(fc(phys_ctx), "%s", ebuf);
15933
return 0;
15934
}
15935
15936
return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
15937
}
15938
15939
15940
static void
15941
uninitialize_ssl(void)
15942
{
15943
#if defined(OPENSSL_API_1_1)
15944
15945
if (mg_atomic_dec(&cryptolib_users) == 0) {
15946
15947
/* Shutdown according to
15948
* https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
15949
* http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
15950
*/
15951
CONF_modules_unload(1);
15952
#else
15953
int i;
15954
15955
if (mg_atomic_dec(&cryptolib_users) == 0) {
15956
15957
/* Shutdown according to
15958
* https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
15959
* http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
15960
*/
15961
CRYPTO_set_locking_callback(NULL);
15962
CRYPTO_set_id_callback(NULL);
15963
ENGINE_cleanup();
15964
CONF_modules_unload(1);
15965
ERR_free_strings();
15966
EVP_cleanup();
15967
CRYPTO_cleanup_all_ex_data();
15968
ERR_remove_state(0);
15969
15970
for (i = 0; i < CRYPTO_num_locks(); i++) {
15971
pthread_mutex_destroy(&ssl_mutexes[i]);
15972
}
15973
mg_free(ssl_mutexes);
15974
ssl_mutexes = NULL;
15975
#endif /* OPENSSL_API_1_1 */
15976
}
15977
}
15978
#endif /* !NO_SSL */
15979
15980
15981
static int
15982
set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
15983
{
15984
if (phys_ctx) {
15985
struct mg_file file = STRUCT_FILE_INITIALIZER;
15986
const char *path;
15987
if (!dom_ctx) {
15988
dom_ctx = &(phys_ctx->dd);
15989
}
15990
path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
15991
if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
15992
mg_cry_internal(fc(phys_ctx),
15993
"Cannot open %s: %s",
15994
path,
15995
strerror(ERRNO));
15996
return 0;
15997
}
15998
return 1;
15999
}
16000
return 0;
16001
}
16002
16003
16004
static int
16005
set_acl_option(struct mg_context *phys_ctx)
16006
{
16007
return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
16008
}
16009
16010
16011
static void
16012
reset_per_request_attributes(struct mg_connection *conn)
16013
{
16014
if (!conn) {
16015
return;
16016
}
16017
conn->connection_type =
16018
CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
16019
16020
conn->num_bytes_sent = conn->consumed_content = 0;
16021
16022
conn->path_info = NULL;
16023
conn->status_code = -1;
16024
conn->content_len = -1;
16025
conn->is_chunked = 0;
16026
conn->must_close = 0;
16027
conn->request_len = 0;
16028
conn->throttle = 0;
16029
conn->data_len = 0;
16030
conn->chunk_remainder = 0;
16031
conn->accept_gzip = 0;
16032
16033
conn->response_info.content_length = conn->request_info.content_length = -1;
16034
conn->response_info.http_version = conn->request_info.http_version = NULL;
16035
conn->response_info.num_headers = conn->request_info.num_headers = 0;
16036
conn->response_info.status_text = NULL;
16037
conn->response_info.status_code = 0;
16038
16039
conn->request_info.remote_user = NULL;
16040
conn->request_info.request_method = NULL;
16041
conn->request_info.request_uri = NULL;
16042
conn->request_info.local_uri = NULL;
16043
16044
#if defined(MG_LEGACY_INTERFACE)
16045
/* Legacy before split into local_uri and request_uri */
16046
conn->request_info.uri = NULL;
16047
#endif
16048
}
16049
16050
16051
#if 0
16052
/* Note: set_sock_timeout is not required for non-blocking sockets.
16053
* Leave this function here (commented out) for reference until
16054
* CivetWeb 1.9 is tested, and the tests confirme this function is
16055
* no longer required.
16056
*/
16057
static int
16058
set_sock_timeout(SOCKET sock, int milliseconds)
16059
{
16060
int r0 = 0, r1, r2;
16061
16062
#if defined(_WIN32)
16063
/* Windows specific */
16064
16065
DWORD tv = (DWORD)milliseconds;
16066
16067
#else
16068
/* Linux, ... (not Windows) */
16069
16070
struct timeval tv;
16071
16072
/* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
16073
* max. time waiting for the acknowledged of TCP data before the connection
16074
* will be forcefully closed and ETIMEDOUT is returned to the application.
16075
* If this option is not set, the default timeout of 20-30 minutes is used.
16076
*/
16077
/* #define TCP_USER_TIMEOUT (18) */
16078
16079
#if defined(TCP_USER_TIMEOUT)
16080
unsigned int uto = (unsigned int)milliseconds;
16081
r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
16082
#endif
16083
16084
memset(&tv, 0, sizeof(tv));
16085
tv.tv_sec = milliseconds / 1000;
16086
tv.tv_usec = (milliseconds * 1000) % 1000000;
16087
16088
#endif /* _WIN32 */
16089
16090
r1 = setsockopt(
16091
sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
16092
r2 = setsockopt(
16093
sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
16094
16095
return r0 || r1 || r2;
16096
}
16097
#endif
16098
16099
16100
static int
16101
set_tcp_nodelay(SOCKET sock, int nodelay_on)
16102
{
16103
if (setsockopt(sock,
16104
IPPROTO_TCP,
16105
TCP_NODELAY,
16106
(SOCK_OPT_TYPE)&nodelay_on,
16107
sizeof(nodelay_on))
16108
!= 0) {
16109
/* Error */
16110
return 1;
16111
}
16112
/* OK */
16113
return 0;
16114
}
16115
16116
16117
static void
16118
close_socket_gracefully(struct mg_connection *conn)
16119
{
16120
#if defined(_WIN32)
16121
char buf[MG_BUF_LEN];
16122
int n;
16123
#endif
16124
struct linger linger;
16125
int error_code = 0;
16126
int linger_timeout = -2;
16127
socklen_t opt_len = sizeof(error_code);
16128
16129
if (!conn) {
16130
return;
16131
}
16132
16133
/* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
16134
* "Note that enabling a nonzero timeout on a nonblocking socket
16135
* is not recommended.", so set it to blocking now */
16136
set_blocking_mode(conn->client.sock);
16137
16138
/* Send FIN to the client */
16139
shutdown(conn->client.sock, SHUTDOWN_WR);
16140
16141
16142
#if defined(_WIN32)
16143
/* Read and discard pending incoming data. If we do not do that and
16144
* close
16145
* the socket, the data in the send buffer may be discarded. This
16146
* behaviour is seen on Windows, when client keeps sending data
16147
* when server decides to close the connection; then when client
16148
* does recv() it gets no data back. */
16149
do {
16150
n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
16151
} while (n > 0);
16152
#endif
16153
16154
if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
16155
linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
16156
}
16157
16158
/* Set linger option according to configuration */
16159
if (linger_timeout >= 0) {
16160
/* Set linger option to avoid socket hanging out after close. This
16161
* prevent ephemeral port exhaust problem under high QPS. */
16162
linger.l_onoff = 1;
16163
16164
#if defined(_MSC_VER)
16165
#pragma warning(push)
16166
#pragma warning(disable : 4244)
16167
#endif
16168
#if defined(GCC_DIAGNOSTIC)
16169
#pragma GCC diagnostic push
16170
#pragma GCC diagnostic ignored "-Wconversion"
16171
#endif
16172
/* Data type of linger structure elements may differ,
16173
* so we don't know what cast we need here.
16174
* Disable type conversion warnings. */
16175
16176
linger.l_linger = (linger_timeout + 999) / 1000;
16177
16178
#if defined(GCC_DIAGNOSTIC)
16179
#pragma GCC diagnostic pop
16180
#endif
16181
#if defined(_MSC_VER)
16182
#pragma warning(pop)
16183
#endif
16184
16185
} else {
16186
linger.l_onoff = 0;
16187
linger.l_linger = 0;
16188
}
16189
16190
if (linger_timeout < -1) {
16191
/* Default: don't configure any linger */
16192
} else if (getsockopt(conn->client.sock,
16193
SOL_SOCKET,
16194
SO_ERROR,
16195
#if defined(_WIN32) /* WinSock uses different data type here */
16196
(char *)&error_code,
16197
#else
16198
&error_code,
16199
#endif
16200
&opt_len)
16201
!= 0) {
16202
/* Cannot determine if socket is already closed. This should
16203
* not occur and never did in a test. Log an error message
16204
* and continue. */
16205
mg_cry_internal(conn,
16206
"%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
16207
__func__,
16208
strerror(ERRNO));
16209
} else if (error_code == ECONNRESET) {
16210
/* Socket already closed by client/peer, close socket without linger
16211
*/
16212
} else {
16213
16214
/* Set linger timeout */
16215
if (setsockopt(conn->client.sock,
16216
SOL_SOCKET,
16217
SO_LINGER,
16218
(char *)&linger,
16219
sizeof(linger))
16220
!= 0) {
16221
mg_cry_internal(
16222
conn,
16223
"%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
16224
__func__,
16225
linger.l_onoff,
16226
linger.l_linger,
16227
strerror(ERRNO));
16228
}
16229
}
16230
16231
/* Now we know that our FIN is ACK-ed, safe to close */
16232
closesocket(conn->client.sock);
16233
conn->client.sock = INVALID_SOCKET;
16234
}
16235
16236
16237
static void
16238
close_connection(struct mg_connection *conn)
16239
{
16240
#if defined(USE_SERVER_STATS)
16241
conn->conn_state = 6; /* to close */
16242
#endif
16243
16244
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
16245
if (conn->lua_websocket_state) {
16246
lua_websocket_close(conn, conn->lua_websocket_state);
16247
conn->lua_websocket_state = NULL;
16248
}
16249
#endif
16250
16251
mg_lock_connection(conn);
16252
16253
/* Set close flag, so keep-alive loops will stop */
16254
conn->must_close = 1;
16255
16256
/* call the connection_close callback if assigned */
16257
if (conn->phys_ctx->callbacks.connection_close != NULL) {
16258
if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
16259
conn->phys_ctx->callbacks.connection_close(conn);
16260
}
16261
}
16262
16263
/* Reset user data, after close callback is called.
16264
* Do not reuse it. If the user needs a destructor,
16265
* it must be done in the connection_close callback. */
16266
mg_set_user_connection_data(conn, NULL);
16267
16268
16269
#if defined(USE_SERVER_STATS)
16270
conn->conn_state = 7; /* closing */
16271
#endif
16272
16273
#if !defined(NO_SSL)
16274
if (conn->ssl != NULL) {
16275
/* Run SSL_shutdown twice to ensure completely close SSL connection
16276
*/
16277
SSL_shutdown(conn->ssl);
16278
SSL_free(conn->ssl);
16279
/* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
16280
* https://wiki.openssl.org/index.php/Talk:Library_Initialization */
16281
#if !defined(OPENSSL_API_1_1)
16282
ERR_remove_state(0);
16283
#endif
16284
conn->ssl = NULL;
16285
}
16286
#endif
16287
if (conn->client.sock != INVALID_SOCKET) {
16288
close_socket_gracefully(conn);
16289
conn->client.sock = INVALID_SOCKET;
16290
}
16291
16292
if (conn->host) {
16293
mg_free((void *)conn->host);
16294
conn->host = NULL;
16295
}
16296
16297
mg_unlock_connection(conn);
16298
16299
#if defined(USE_SERVER_STATS)
16300
conn->conn_state = 8; /* closed */
16301
#endif
16302
}
16303
16304
16305
void
16306
mg_close_connection(struct mg_connection *conn)
16307
{
16308
#if defined(USE_WEBSOCKET)
16309
struct mg_context *client_ctx = NULL;
16310
#endif /* defined(USE_WEBSOCKET) */
16311
16312
if ((conn == NULL) || (conn->phys_ctx == NULL)) {
16313
return;
16314
}
16315
16316
#if defined(USE_WEBSOCKET)
16317
if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
16318
if (conn->in_websocket_handling) {
16319
/* Set close flag, so the server thread can exit. */
16320
conn->must_close = 1;
16321
return;
16322
}
16323
}
16324
if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
16325
16326
unsigned int i;
16327
16328
/* ws/wss client */
16329
client_ctx = conn->phys_ctx;
16330
16331
/* client context: loops must end */
16332
client_ctx->stop_flag = 1;
16333
conn->must_close = 1;
16334
16335
/* We need to get the client thread out of the select/recv call
16336
* here. */
16337
/* Since we use a sleep quantum of some seconds to check for recv
16338
* timeouts, we will just wait a few seconds in mg_join_thread. */
16339
16340
/* join worker thread */
16341
for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
16342
if (client_ctx->worker_threadids[i] != 0) {
16343
mg_join_thread(client_ctx->worker_threadids[i]);
16344
}
16345
}
16346
}
16347
#endif /* defined(USE_WEBSOCKET) */
16348
16349
close_connection(conn);
16350
16351
#if !defined(NO_SSL)
16352
if (conn->client_ssl_ctx != NULL) {
16353
SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
16354
}
16355
#endif
16356
16357
#if defined(USE_WEBSOCKET)
16358
if (client_ctx != NULL) {
16359
/* free context */
16360
mg_free(client_ctx->worker_threadids);
16361
mg_free(client_ctx);
16362
(void)pthread_mutex_destroy(&conn->mutex);
16363
mg_free(conn);
16364
} else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
16365
mg_free(conn);
16366
}
16367
#else
16368
if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
16369
mg_free(conn);
16370
}
16371
#endif /* defined(USE_WEBSOCKET) */
16372
}
16373
16374
16375
/* Only for memory statistics */
16376
static struct mg_context common_client_context;
16377
16378
16379
static struct mg_connection *
16380
mg_connect_client_impl(const struct mg_client_options *client_options,
16381
int use_ssl,
16382
char *ebuf,
16383
size_t ebuf_len)
16384
{
16385
struct mg_connection *conn = NULL;
16386
SOCKET sock;
16387
union usa sa;
16388
struct sockaddr *psa;
16389
socklen_t len;
16390
16391
unsigned max_req_size =
16392
(unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
16393
16394
/* Size of structures, aligned to 8 bytes */
16395
size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
16396
size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
16397
16398
conn = (struct mg_connection *)mg_calloc_ctx(
16399
1, conn_size + ctx_size + max_req_size, &common_client_context);
16400
16401
if (conn == NULL) {
16402
mg_snprintf(NULL,
16403
NULL, /* No truncation check for ebuf */
16404
ebuf,
16405
ebuf_len,
16406
"calloc(): %s",
16407
strerror(ERRNO));
16408
return NULL;
16409
}
16410
16411
#if defined(GCC_DIAGNOSTIC)
16412
#pragma GCC diagnostic push
16413
#pragma GCC diagnostic ignored "-Wcast-align"
16414
#endif /* defined(GCC_DIAGNOSTIC) */
16415
/* conn_size is aligned to 8 bytes */
16416
16417
conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
16418
16419
#if defined(GCC_DIAGNOSTIC)
16420
#pragma GCC diagnostic pop
16421
#endif /* defined(GCC_DIAGNOSTIC) */
16422
16423
conn->buf = (((char *)conn) + conn_size + ctx_size);
16424
conn->buf_size = (int)max_req_size;
16425
conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
16426
conn->dom_ctx = &(conn->phys_ctx->dd);
16427
16428
if (!connect_socket(&common_client_context,
16429
client_options->host,
16430
client_options->port,
16431
use_ssl,
16432
ebuf,
16433
ebuf_len,
16434
&sock,
16435
&sa)) {
16436
/* ebuf is set by connect_socket,
16437
* free all memory and return NULL; */
16438
mg_free(conn);
16439
return NULL;
16440
}
16441
16442
#if !defined(NO_SSL)
16443
#if defined(OPENSSL_API_1_1)
16444
if (use_ssl
16445
&& (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
16446
mg_snprintf(NULL,
16447
NULL, /* No truncation check for ebuf */
16448
ebuf,
16449
ebuf_len,
16450
"SSL_CTX_new error");
16451
closesocket(sock);
16452
mg_free(conn);
16453
return NULL;
16454
}
16455
#else
16456
if (use_ssl
16457
&& (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
16458
== NULL) {
16459
mg_snprintf(NULL,
16460
NULL, /* No truncation check for ebuf */
16461
ebuf,
16462
ebuf_len,
16463
"SSL_CTX_new error");
16464
closesocket(sock);
16465
mg_free(conn);
16466
return NULL;
16467
}
16468
#endif /* OPENSSL_API_1_1 */
16469
#endif /* NO_SSL */
16470
16471
16472
#if defined(USE_IPV6)
16473
len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
16474
: sizeof(conn->client.rsa.sin6);
16475
psa = (sa.sa.sa_family == AF_INET)
16476
? (struct sockaddr *)&(conn->client.rsa.sin)
16477
: (struct sockaddr *)&(conn->client.rsa.sin6);
16478
#else
16479
len = sizeof(conn->client.rsa.sin);
16480
psa = (struct sockaddr *)&(conn->client.rsa.sin);
16481
#endif
16482
16483
conn->client.sock = sock;
16484
conn->client.lsa = sa;
16485
16486
if (getsockname(sock, psa, &len) != 0) {
16487
mg_cry_internal(conn,
16488
"%s: getsockname() failed: %s",
16489
__func__,
16490
strerror(ERRNO));
16491
}
16492
16493
conn->client.is_ssl = use_ssl ? 1 : 0;
16494
if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
16495
mg_snprintf(NULL,
16496
NULL, /* No truncation check for ebuf */
16497
ebuf,
16498
ebuf_len,
16499
"Can not create mutex");
16500
#if !defined(NO_SSL)
16501
SSL_CTX_free(conn->client_ssl_ctx);
16502
#endif
16503
closesocket(sock);
16504
mg_free(conn);
16505
return NULL;
16506
}
16507
16508
16509
#if !defined(NO_SSL)
16510
if (use_ssl) {
16511
common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
16512
16513
/* TODO: Check ssl_verify_peer and ssl_ca_path here.
16514
* SSL_CTX_set_verify call is needed to switch off server
16515
* certificate checking, which is off by default in OpenSSL and
16516
* on in yaSSL. */
16517
/* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
16518
* SSL_VERIFY_PEER, verify_ssl_server); */
16519
16520
if (client_options->client_cert) {
16521
if (!ssl_use_pem_file(&common_client_context,
16522
&(common_client_context.dd),
16523
client_options->client_cert,
16524
NULL)) {
16525
mg_snprintf(NULL,
16526
NULL, /* No truncation check for ebuf */
16527
ebuf,
16528
ebuf_len,
16529
"Can not use SSL client certificate");
16530
SSL_CTX_free(conn->client_ssl_ctx);
16531
closesocket(sock);
16532
mg_free(conn);
16533
return NULL;
16534
}
16535
}
16536
16537
if (client_options->server_cert) {
16538
SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
16539
client_options->server_cert,
16540
NULL);
16541
SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
16542
} else {
16543
SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
16544
}
16545
16546
if (!sslize(conn,
16547
conn->client_ssl_ctx,
16548
SSL_connect,
16549
&(conn->phys_ctx->stop_flag))) {
16550
mg_snprintf(NULL,
16551
NULL, /* No truncation check for ebuf */
16552
ebuf,
16553
ebuf_len,
16554
"SSL connection error");
16555
SSL_CTX_free(conn->client_ssl_ctx);
16556
closesocket(sock);
16557
mg_free(conn);
16558
return NULL;
16559
}
16560
}
16561
#endif
16562
16563
if (0 != set_non_blocking_mode(sock)) {
16564
mg_cry_internal(conn,
16565
"Cannot set non-blocking mode for client %s:%i",
16566
client_options->host,
16567
client_options->port);
16568
}
16569
16570
return conn;
16571
}
16572
16573
16574
CIVETWEB_API struct mg_connection *
16575
mg_connect_client_secure(const struct mg_client_options *client_options,
16576
char *error_buffer,
16577
size_t error_buffer_size)
16578
{
16579
return mg_connect_client_impl(client_options,
16580
1,
16581
error_buffer,
16582
error_buffer_size);
16583
}
16584
16585
16586
struct mg_connection *
16587
mg_connect_client(const char *host,
16588
int port,
16589
int use_ssl,
16590
char *error_buffer,
16591
size_t error_buffer_size)
16592
{
16593
struct mg_client_options opts;
16594
memset(&opts, 0, sizeof(opts));
16595
opts.host = host;
16596
opts.port = port;
16597
return mg_connect_client_impl(&opts,
16598
use_ssl,
16599
error_buffer,
16600
error_buffer_size);
16601
}
16602
16603
16604
static const struct {
16605
const char *proto;
16606
size_t proto_len;
16607
unsigned default_port;
16608
} abs_uri_protocols[] = {{"http://", 7, 80},
16609
{"https://", 8, 443},
16610
{"ws://", 5, 80},
16611
{"wss://", 6, 443},
16612
{NULL, 0, 0}};
16613
16614
16615
/* Check if the uri is valid.
16616
* return 0 for invalid uri,
16617
* return 1 for *,
16618
* return 2 for relative uri,
16619
* return 3 for absolute uri without port,
16620
* return 4 for absolute uri with port */
16621
static int
16622
get_uri_type(const char *uri)
16623
{
16624
int i;
16625
const char *hostend, *portbegin;
16626
char *portend;
16627
unsigned long port;
16628
16629
/* According to the HTTP standard
16630
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
16631
* URI can be an asterisk (*) or should start with slash (relative uri),
16632
* or it should start with the protocol (absolute uri). */
16633
if ((uri[0] == '*') && (uri[1] == '\0')) {
16634
/* asterisk */
16635
return 1;
16636
}
16637
16638
/* Valid URIs according to RFC 3986
16639
* (https://www.ietf.org/rfc/rfc3986.txt)
16640
* must only contain reserved characters :/?#[]@!$&'()*+,;=
16641
* and unreserved characters A-Z a-z 0-9 and -._~
16642
* and % encoded symbols.
16643
*/
16644
for (i = 0; uri[i] != 0; i++) {
16645
if (uri[i] < 33) {
16646
/* control characters and spaces are invalid */
16647
return 0;
16648
}
16649
if (uri[i] > 126) {
16650
/* non-ascii characters must be % encoded */
16651
return 0;
16652
} else {
16653
switch (uri[i]) {
16654
case '"': /* 34 */
16655
case '<': /* 60 */
16656
case '>': /* 62 */
16657
case '\\': /* 92 */
16658
case '^': /* 94 */
16659
case '`': /* 96 */
16660
case '{': /* 123 */
16661
case '|': /* 124 */
16662
case '}': /* 125 */
16663
return 0;
16664
default:
16665
/* character is ok */
16666
break;
16667
}
16668
}
16669
}
16670
16671
/* A relative uri starts with a / character */
16672
if (uri[0] == '/') {
16673
/* relative uri */
16674
return 2;
16675
}
16676
16677
/* It could be an absolute uri: */
16678
/* This function only checks if the uri is valid, not if it is
16679
* addressing the current server. So civetweb can also be used
16680
* as a proxy server. */
16681
for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
16682
if (mg_strncasecmp(uri,
16683
abs_uri_protocols[i].proto,
16684
abs_uri_protocols[i].proto_len)
16685
== 0) {
16686
16687
hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
16688
if (!hostend) {
16689
return 0;
16690
}
16691
portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
16692
if (!portbegin) {
16693
return 3;
16694
}
16695
16696
port = strtoul(portbegin + 1, &portend, 10);
16697
if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
16698
return 0;
16699
}
16700
16701
return 4;
16702
}
16703
}
16704
16705
return 0;
16706
}
16707
16708
16709
/* Return NULL or the relative uri at the current server */
16710
static const char *
16711
get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
16712
{
16713
const char *server_domain;
16714
size_t server_domain_len;
16715
size_t request_domain_len = 0;
16716
unsigned long port = 0;
16717
int i, auth_domain_check_enabled;
16718
const char *hostbegin = NULL;
16719
const char *hostend = NULL;
16720
const char *portbegin;
16721
char *portend;
16722
16723
auth_domain_check_enabled =
16724
!mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
16725
16726
/* DNS is case insensitive, so use case insensitive string compare here
16727
*/
16728
for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
16729
if (mg_strncasecmp(uri,
16730
abs_uri_protocols[i].proto,
16731
abs_uri_protocols[i].proto_len)
16732
== 0) {
16733
16734
hostbegin = uri + abs_uri_protocols[i].proto_len;
16735
hostend = strchr(hostbegin, '/');
16736
if (!hostend) {
16737
return 0;
16738
}
16739
portbegin = strchr(hostbegin, ':');
16740
if ((!portbegin) || (portbegin > hostend)) {
16741
port = abs_uri_protocols[i].default_port;
16742
request_domain_len = (size_t)(hostend - hostbegin);
16743
} else {
16744
port = strtoul(portbegin + 1, &portend, 10);
16745
if ((portend != hostend) || (port <= 0)
16746
|| !is_valid_port(port)) {
16747
return 0;
16748
}
16749
request_domain_len = (size_t)(portbegin - hostbegin);
16750
}
16751
/* protocol found, port set */
16752
break;
16753
}
16754
}
16755
16756
if (!port) {
16757
/* port remains 0 if the protocol is not found */
16758
return 0;
16759
}
16760
16761
/* Check if the request is directed to a different server. */
16762
/* First check if the port is the same (IPv4 and IPv6). */
16763
#if defined(USE_IPV6)
16764
if (conn->client.lsa.sa.sa_family == AF_INET6) {
16765
if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
16766
/* Request is directed to a different port */
16767
return 0;
16768
}
16769
} else
16770
#endif
16771
{
16772
if (ntohs(conn->client.lsa.sin.sin_port) != port) {
16773
/* Request is directed to a different port */
16774
return 0;
16775
}
16776
}
16777
16778
/* Finally check if the server corresponds to the authentication
16779
* domain of the server (the server domain).
16780
* Allow full matches (like http://mydomain.com/path/file.ext), and
16781
* allow subdomain matches (like http://www.mydomain.com/path/file.ext),
16782
* but do not allow substrings (like
16783
* http://notmydomain.com/path/file.ext
16784
* or http://mydomain.com.fake/path/file.ext).
16785
*/
16786
if (auth_domain_check_enabled) {
16787
server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
16788
server_domain_len = strlen(server_domain);
16789
if ((server_domain_len == 0) || (hostbegin == NULL)) {
16790
return 0;
16791
}
16792
if ((request_domain_len == server_domain_len)
16793
&& (!memcmp(server_domain, hostbegin, server_domain_len))) {
16794
/* Request is directed to this server - full name match. */
16795
} else {
16796
if (request_domain_len < (server_domain_len + 2)) {
16797
/* Request is directed to another server: The server name
16798
* is longer than the request name.
16799
* Drop this case here to avoid overflows in the
16800
* following checks. */
16801
return 0;
16802
}
16803
if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
16804
/* Request is directed to another server: It could be a
16805
* substring
16806
* like notmyserver.com */
16807
return 0;
16808
}
16809
if (0
16810
!= memcmp(server_domain,
16811
hostbegin + request_domain_len - server_domain_len,
16812
server_domain_len)) {
16813
/* Request is directed to another server:
16814
* The server name is different. */
16815
return 0;
16816
}
16817
}
16818
}
16819
16820
return hostend;
16821
}
16822
16823
16824
static int
16825
get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
16826
{
16827
if (ebuf_len > 0) {
16828
ebuf[0] = '\0';
16829
}
16830
*err = 0;
16831
16832
reset_per_request_attributes(conn);
16833
16834
if (!conn) {
16835
mg_snprintf(conn,
16836
NULL, /* No truncation check for ebuf */
16837
ebuf,
16838
ebuf_len,
16839
"%s",
16840
"Internal error");
16841
*err = 500;
16842
return 0;
16843
}
16844
/* Set the time the request was received. This value should be used for
16845
* timeouts. */
16846
clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
16847
16848
conn->request_len =
16849
read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
16850
DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
16851
if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
16852
mg_snprintf(conn,
16853
NULL, /* No truncation check for ebuf */
16854
ebuf,
16855
ebuf_len,
16856
"%s",
16857
"Invalid message size");
16858
*err = 500;
16859
return 0;
16860
}
16861
16862
if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
16863
mg_snprintf(conn,
16864
NULL, /* No truncation check for ebuf */
16865
ebuf,
16866
ebuf_len,
16867
"%s",
16868
"Message too large");
16869
*err = 413;
16870
return 0;
16871
}
16872
16873
if (conn->request_len <= 0) {
16874
if (conn->data_len > 0) {
16875
mg_snprintf(conn,
16876
NULL, /* No truncation check for ebuf */
16877
ebuf,
16878
ebuf_len,
16879
"%s",
16880
"Malformed message");
16881
*err = 400;
16882
} else {
16883
/* Server did not recv anything -> just close the connection */
16884
conn->must_close = 1;
16885
mg_snprintf(conn,
16886
NULL, /* No truncation check for ebuf */
16887
ebuf,
16888
ebuf_len,
16889
"%s",
16890
"No data received");
16891
*err = 0;
16892
}
16893
return 0;
16894
}
16895
return 1;
16896
}
16897
16898
16899
static int
16900
get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
16901
{
16902
const char *cl;
16903
if (!get_message(conn, ebuf, ebuf_len, err)) {
16904
return 0;
16905
}
16906
16907
if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
16908
<= 0) {
16909
mg_snprintf(conn,
16910
NULL, /* No truncation check for ebuf */
16911
ebuf,
16912
ebuf_len,
16913
"%s",
16914
"Bad request");
16915
*err = 400;
16916
return 0;
16917
}
16918
16919
/* Message is a valid request */
16920
16921
/* Is there a "host" ? */
16922
conn->host = alloc_get_host(conn);
16923
if (!conn->host) {
16924
mg_snprintf(conn,
16925
NULL, /* No truncation check for ebuf */
16926
ebuf,
16927
ebuf_len,
16928
"%s",
16929
"Bad request: Host mismatch");
16930
*err = 400;
16931
return 0;
16932
}
16933
16934
/* Do we know the content length? */
16935
if ((cl = get_header(conn->request_info.http_headers,
16936
conn->request_info.num_headers,
16937
"Content-Length"))
16938
!= NULL) {
16939
/* Request/response has content length set */
16940
char *endptr = NULL;
16941
conn->content_len = strtoll(cl, &endptr, 10);
16942
if (endptr == cl) {
16943
mg_snprintf(conn,
16944
NULL, /* No truncation check for ebuf */
16945
ebuf,
16946
ebuf_len,
16947
"%s",
16948
"Bad request");
16949
*err = 411;
16950
return 0;
16951
}
16952
/* Publish the content length back to the request info. */
16953
conn->request_info.content_length = conn->content_len;
16954
} else if ((cl = get_header(conn->request_info.http_headers,
16955
conn->request_info.num_headers,
16956
"Transfer-Encoding"))
16957
!= NULL
16958
&& !mg_strcasecmp(cl, "chunked")) {
16959
conn->is_chunked = 1;
16960
conn->content_len = -1; /* unknown content length */
16961
} else {
16962
const struct mg_http_method_info *meth =
16963
get_http_method_info(conn->request_info.request_method);
16964
if (!meth) {
16965
/* No valid HTTP method */
16966
mg_snprintf(conn,
16967
NULL, /* No truncation check for ebuf */
16968
ebuf,
16969
ebuf_len,
16970
"%s",
16971
"Bad request");
16972
*err = 411;
16973
return 0;
16974
}
16975
if (meth->request_has_body) {
16976
/* POST or PUT request without content length set */
16977
conn->content_len = -1; /* unknown content length */
16978
} else {
16979
/* Other request */
16980
conn->content_len = 0; /* No content */
16981
}
16982
}
16983
16984
conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
16985
return 1;
16986
}
16987
16988
16989
/* conn is assumed to be valid in this internal function */
16990
static int
16991
get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
16992
{
16993
const char *cl;
16994
if (!get_message(conn, ebuf, ebuf_len, err)) {
16995
return 0;
16996
}
16997
16998
if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
16999
<= 0) {
17000
mg_snprintf(conn,
17001
NULL, /* No truncation check for ebuf */
17002
ebuf,
17003
ebuf_len,
17004
"%s",
17005
"Bad response");
17006
*err = 400;
17007
return 0;
17008
}
17009
17010
/* Message is a valid response */
17011
17012
/* Do we know the content length? */
17013
if ((cl = get_header(conn->response_info.http_headers,
17014
conn->response_info.num_headers,
17015
"Content-Length"))
17016
!= NULL) {
17017
/* Request/response has content length set */
17018
char *endptr = NULL;
17019
conn->content_len = strtoll(cl, &endptr, 10);
17020
if (endptr == cl) {
17021
mg_snprintf(conn,
17022
NULL, /* No truncation check for ebuf */
17023
ebuf,
17024
ebuf_len,
17025
"%s",
17026
"Bad request");
17027
*err = 411;
17028
return 0;
17029
}
17030
/* Publish the content length back to the response info. */
17031
conn->response_info.content_length = conn->content_len;
17032
17033
/* TODO: check if it is still used in response_info */
17034
conn->request_info.content_length = conn->content_len;
17035
17036
} else if ((cl = get_header(conn->response_info.http_headers,
17037
conn->response_info.num_headers,
17038
"Transfer-Encoding"))
17039
!= NULL
17040
&& !mg_strcasecmp(cl, "chunked")) {
17041
conn->is_chunked = 1;
17042
conn->content_len = -1; /* unknown content length */
17043
} else {
17044
conn->content_len = -1; /* unknown content length */
17045
}
17046
17047
conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
17048
return 1;
17049
}
17050
17051
17052
int
17053
mg_get_response(struct mg_connection *conn,
17054
char *ebuf,
17055
size_t ebuf_len,
17056
int timeout)
17057
{
17058
int err, ret;
17059
char txt[32]; /* will not overflow */
17060
char *save_timeout;
17061
char *new_timeout;
17062
17063
if (ebuf_len > 0) {
17064
ebuf[0] = '\0';
17065
}
17066
17067
if (!conn) {
17068
mg_snprintf(conn,
17069
NULL, /* No truncation check for ebuf */
17070
ebuf,
17071
ebuf_len,
17072
"%s",
17073
"Parameter error");
17074
return -1;
17075
}
17076
17077
/* Implementation of API function for HTTP clients */
17078
save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
17079
17080
if (timeout >= 0) {
17081
mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
17082
new_timeout = txt;
17083
/* Not required for non-blocking sockets.
17084
set_sock_timeout(conn->client.sock, timeout);
17085
*/
17086
} else {
17087
new_timeout = NULL;
17088
}
17089
17090
conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
17091
ret = get_response(conn, ebuf, ebuf_len, &err);
17092
conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
17093
17094
#if defined(MG_LEGACY_INTERFACE)
17095
/* TODO: 1) uri is deprecated;
17096
* 2) here, ri.uri is the http response code */
17097
conn->request_info.uri = conn->request_info.request_uri;
17098
#endif
17099
conn->request_info.local_uri = conn->request_info.request_uri;
17100
17101
/* TODO (mid): Define proper return values - maybe return length?
17102
* For the first test use <0 for error and >0 for OK */
17103
return (ret == 0) ? -1 : +1;
17104
}
17105
17106
17107
struct mg_connection *
17108
mg_download(const char *host,
17109
int port,
17110
int use_ssl,
17111
char *ebuf,
17112
size_t ebuf_len,
17113
const char *fmt,
17114
...)
17115
{
17116
struct mg_connection *conn;
17117
va_list ap;
17118
int i;
17119
int reqerr;
17120
17121
if (ebuf_len > 0) {
17122
ebuf[0] = '\0';
17123
}
17124
17125
va_start(ap, fmt);
17126
17127
/* open a connection */
17128
conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
17129
17130
if (conn != NULL) {
17131
i = mg_vprintf(conn, fmt, ap);
17132
if (i <= 0) {
17133
mg_snprintf(conn,
17134
NULL, /* No truncation check for ebuf */
17135
ebuf,
17136
ebuf_len,
17137
"%s",
17138
"Error sending request");
17139
} else {
17140
get_response(conn, ebuf, ebuf_len, &reqerr);
17141
17142
#if defined(MG_LEGACY_INTERFACE)
17143
/* TODO: 1) uri is deprecated;
17144
* 2) here, ri.uri is the http response code */
17145
conn->request_info.uri = conn->request_info.request_uri;
17146
#endif
17147
conn->request_info.local_uri = conn->request_info.request_uri;
17148
}
17149
}
17150
17151
/* if an error occurred, close the connection */
17152
if ((ebuf[0] != '\0') && (conn != NULL)) {
17153
mg_close_connection(conn);
17154
conn = NULL;
17155
}
17156
17157
va_end(ap);
17158
return conn;
17159
}
17160
17161
17162
struct websocket_client_thread_data {
17163
struct mg_connection *conn;
17164
mg_websocket_data_handler data_handler;
17165
mg_websocket_close_handler close_handler;
17166
void *callback_data;
17167
};
17168
17169
17170
#if defined(USE_WEBSOCKET)
17171
#if defined(_WIN32)
17172
static unsigned __stdcall websocket_client_thread(void *data)
17173
#else
17174
static void *
17175
websocket_client_thread(void *data)
17176
#endif
17177
{
17178
struct websocket_client_thread_data *cdata =
17179
(struct websocket_client_thread_data *)data;
17180
17181
#if !defined(_WIN32)
17182
struct sigaction sa;
17183
17184
/* Ignore SIGPIPE */
17185
memset(&sa, 0, sizeof(sa));
17186
sa.sa_handler = SIG_IGN;
17187
sigaction(SIGPIPE, &sa, NULL);
17188
#endif
17189
17190
mg_set_thread_name("ws-clnt");
17191
17192
if (cdata->conn->phys_ctx) {
17193
if (cdata->conn->phys_ctx->callbacks.init_thread) {
17194
/* 3 indicates a websocket client thread */
17195
/* TODO: check if conn->phys_ctx can be set */
17196
cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
17197
3);
17198
}
17199
}
17200
17201
read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
17202
17203
DEBUG_TRACE("%s", "Websocket client thread exited\n");
17204
17205
if (cdata->close_handler != NULL) {
17206
cdata->close_handler(cdata->conn, cdata->callback_data);
17207
}
17208
17209
/* The websocket_client context has only this thread. If it runs out,
17210
set the stop_flag to 2 (= "stopped"). */
17211
cdata->conn->phys_ctx->stop_flag = 2;
17212
17213
mg_free((void *)cdata);
17214
17215
#if defined(_WIN32)
17216
return 0;
17217
#else
17218
return NULL;
17219
#endif
17220
}
17221
#endif
17222
17223
17224
struct mg_connection *
17225
mg_connect_websocket_client(const char *host,
17226
int port,
17227
int use_ssl,
17228
char *error_buffer,
17229
size_t error_buffer_size,
17230
const char *path,
17231
const char *origin,
17232
mg_websocket_data_handler data_func,
17233
mg_websocket_close_handler close_func,
17234
void *user_data)
17235
{
17236
struct mg_connection *conn = NULL;
17237
17238
#if defined(USE_WEBSOCKET)
17239
struct mg_context *newctx = NULL;
17240
struct websocket_client_thread_data *thread_data;
17241
static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
17242
static const char *handshake_req;
17243
17244
if (origin != NULL) {
17245
handshake_req = "GET %s HTTP/1.1\r\n"
17246
"Host: %s\r\n"
17247
"Upgrade: websocket\r\n"
17248
"Connection: Upgrade\r\n"
17249
"Sec-WebSocket-Key: %s\r\n"
17250
"Sec-WebSocket-Version: 13\r\n"
17251
"Origin: %s\r\n"
17252
"\r\n";
17253
} else {
17254
handshake_req = "GET %s HTTP/1.1\r\n"
17255
"Host: %s\r\n"
17256
"Upgrade: websocket\r\n"
17257
"Connection: Upgrade\r\n"
17258
"Sec-WebSocket-Key: %s\r\n"
17259
"Sec-WebSocket-Version: 13\r\n"
17260
"\r\n";
17261
}
17262
17263
#if defined(__clang__)
17264
#pragma clang diagnostic push
17265
#pragma clang diagnostic ignored "-Wformat-nonliteral"
17266
#endif
17267
17268
/* Establish the client connection and request upgrade */
17269
conn = mg_download(host,
17270
port,
17271
use_ssl,
17272
error_buffer,
17273
error_buffer_size,
17274
handshake_req,
17275
path,
17276
host,
17277
magic,
17278
origin);
17279
17280
#if defined(__clang__)
17281
#pragma clang diagnostic pop
17282
#endif
17283
17284
/* Connection object will be null if something goes wrong */
17285
if (conn == NULL) {
17286
if (!*error_buffer) {
17287
/* There should be already an error message */
17288
mg_snprintf(conn,
17289
NULL, /* No truncation check for ebuf */
17290
error_buffer,
17291
error_buffer_size,
17292
"Unexpected error");
17293
}
17294
return NULL;
17295
}
17296
17297
if (conn->response_info.status_code != 101) {
17298
/* We sent an "upgrade" request. For a correct websocket
17299
* protocol handshake, we expect a "101 Continue" response.
17300
* Otherwise it is a protocol violation. Maybe the HTTP
17301
* Server does not know websockets. */
17302
if (!*error_buffer) {
17303
/* set an error, if not yet set */
17304
mg_snprintf(conn,
17305
NULL, /* No truncation check for ebuf */
17306
error_buffer,
17307
error_buffer_size,
17308
"Unexpected server reply");
17309
}
17310
17311
DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
17312
mg_free(conn);
17313
return NULL;
17314
}
17315
17316
/* For client connections, mg_context is fake. Since we need to set a
17317
* callback function, we need to create a copy and modify it. */
17318
newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
17319
if (!newctx) {
17320
DEBUG_TRACE("%s\r\n", "Out of memory");
17321
mg_free(conn);
17322
return NULL;
17323
}
17324
17325
memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
17326
newctx->user_data = user_data;
17327
newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
17328
newctx->cfg_worker_threads = 1; /* one worker thread will be created */
17329
newctx->worker_threadids =
17330
(pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
17331
sizeof(pthread_t),
17332
newctx);
17333
17334
conn->phys_ctx = newctx;
17335
conn->dom_ctx = &(newctx->dd);
17336
17337
thread_data = (struct websocket_client_thread_data *)
17338
mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
17339
if (!thread_data) {
17340
DEBUG_TRACE("%s\r\n", "Out of memory");
17341
mg_free(newctx);
17342
mg_free(conn);
17343
return NULL;
17344
}
17345
17346
thread_data->conn = conn;
17347
thread_data->data_handler = data_func;
17348
thread_data->close_handler = close_func;
17349
thread_data->callback_data = user_data;
17350
17351
/* Start a thread to read the websocket client connection
17352
* This thread will automatically stop when mg_disconnect is
17353
* called on the client connection */
17354
if (mg_start_thread_with_id(websocket_client_thread,
17355
(void *)thread_data,
17356
newctx->worker_threadids)
17357
!= 0) {
17358
mg_free((void *)thread_data);
17359
mg_free((void *)newctx->worker_threadids);
17360
mg_free((void *)newctx);
17361
mg_free((void *)conn);
17362
conn = NULL;
17363
DEBUG_TRACE("%s",
17364
"Websocket client connect thread could not be started\r\n");
17365
}
17366
17367
#else
17368
/* Appease "unused parameter" warnings */
17369
(void)host;
17370
(void)port;
17371
(void)use_ssl;
17372
(void)error_buffer;
17373
(void)error_buffer_size;
17374
(void)path;
17375
(void)origin;
17376
(void)user_data;
17377
(void)data_func;
17378
(void)close_func;
17379
#endif
17380
17381
return conn;
17382
}
17383
17384
17385
/* Prepare connection data structure */
17386
static void
17387
init_connection(struct mg_connection *conn)
17388
{
17389
/* Is keep alive allowed by the server */
17390
int keep_alive_enabled =
17391
!mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
17392
17393
if (!keep_alive_enabled) {
17394
conn->must_close = 1;
17395
}
17396
17397
/* Important: on new connection, reset the receiving buffer. Credit
17398
* goes to crule42. */
17399
conn->data_len = 0;
17400
conn->handled_requests = 0;
17401
mg_set_user_connection_data(conn, NULL);
17402
17403
#if defined(USE_SERVER_STATS)
17404
conn->conn_state = 2; /* init */
17405
#endif
17406
17407
/* call the init_connection callback if assigned */
17408
if (conn->phys_ctx->callbacks.init_connection != NULL) {
17409
if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
17410
void *conn_data = NULL;
17411
conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
17412
mg_set_user_connection_data(conn, conn_data);
17413
}
17414
}
17415
}
17416
17417
17418
/* Process a connection - may handle multiple requests
17419
* using the same connection.
17420
* Must be called with a valid connection (conn and
17421
* conn->phys_ctx must be valid).
17422
*/
17423
static void
17424
process_new_connection(struct mg_connection *conn)
17425
{
17426
struct mg_request_info *ri = &conn->request_info;
17427
int keep_alive, discard_len;
17428
char ebuf[100];
17429
const char *hostend;
17430
int reqerr, uri_type;
17431
17432
#if defined(USE_SERVER_STATS)
17433
int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
17434
mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
17435
if (mcon > (conn->phys_ctx->max_connections)) {
17436
/* could use atomic compare exchange, but this
17437
* seems overkill for statistics data */
17438
conn->phys_ctx->max_connections = mcon;
17439
}
17440
#endif
17441
17442
init_connection(conn);
17443
17444
DEBUG_TRACE("Start processing connection from %s",
17445
conn->request_info.remote_addr);
17446
17447
/* Loop over multiple requests sent using the same connection
17448
* (while "keep alive"). */
17449
do {
17450
17451
DEBUG_TRACE("calling get_request (%i times for this connection)",
17452
conn->handled_requests + 1);
17453
17454
#if defined(USE_SERVER_STATS)
17455
conn->conn_state = 3; /* ready */
17456
#endif
17457
17458
if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
17459
/* The request sent by the client could not be understood by
17460
* the server, or it was incomplete or a timeout. Send an
17461
* error message and close the connection. */
17462
if (reqerr > 0) {
17463
DEBUG_ASSERT(ebuf[0] != '\0');
17464
mg_send_http_error(conn, reqerr, "%s", ebuf);
17465
}
17466
} else if (strcmp(ri->http_version, "1.0")
17467
&& strcmp(ri->http_version, "1.1")) {
17468
mg_snprintf(conn,
17469
NULL, /* No truncation check for ebuf */
17470
ebuf,
17471
sizeof(ebuf),
17472
"Bad HTTP version: [%s]",
17473
ri->http_version);
17474
mg_send_http_error(conn, 505, "%s", ebuf);
17475
}
17476
17477
if (ebuf[0] == '\0') {
17478
uri_type = get_uri_type(conn->request_info.request_uri);
17479
switch (uri_type) {
17480
case 1:
17481
/* Asterisk */
17482
conn->request_info.local_uri = NULL;
17483
break;
17484
case 2:
17485
/* relative uri */
17486
conn->request_info.local_uri = conn->request_info.request_uri;
17487
break;
17488
case 3:
17489
case 4:
17490
/* absolute uri (with/without port) */
17491
hostend = get_rel_url_at_current_server(
17492
conn->request_info.request_uri, conn);
17493
if (hostend) {
17494
conn->request_info.local_uri = hostend;
17495
} else {
17496
conn->request_info.local_uri = NULL;
17497
}
17498
break;
17499
default:
17500
mg_snprintf(conn,
17501
NULL, /* No truncation check for ebuf */
17502
ebuf,
17503
sizeof(ebuf),
17504
"Invalid URI");
17505
mg_send_http_error(conn, 400, "%s", ebuf);
17506
conn->request_info.local_uri = NULL;
17507
break;
17508
}
17509
17510
#if defined(MG_LEGACY_INTERFACE)
17511
/* Legacy before split into local_uri and request_uri */
17512
conn->request_info.uri = conn->request_info.local_uri;
17513
#endif
17514
}
17515
17516
DEBUG_TRACE("http: %s, error: %s",
17517
(ri->http_version ? ri->http_version : "none"),
17518
(ebuf[0] ? ebuf : "none"));
17519
17520
if (ebuf[0] == '\0') {
17521
if (conn->request_info.local_uri) {
17522
17523
/* handle request to local server */
17524
#if defined(USE_SERVER_STATS)
17525
conn->conn_state = 4; /* processing */
17526
#endif
17527
handle_request(conn);
17528
17529
#if defined(USE_SERVER_STATS)
17530
conn->conn_state = 5; /* processed */
17531
17532
mg_atomic_add(&(conn->phys_ctx->total_data_read),
17533
conn->consumed_content);
17534
mg_atomic_add(&(conn->phys_ctx->total_data_written),
17535
conn->num_bytes_sent);
17536
#endif
17537
17538
DEBUG_TRACE("%s", "handle_request done");
17539
17540
if (conn->phys_ctx->callbacks.end_request != NULL) {
17541
conn->phys_ctx->callbacks.end_request(conn,
17542
conn->status_code);
17543
DEBUG_TRACE("%s", "end_request callback done");
17544
}
17545
log_access(conn);
17546
} else {
17547
/* TODO: handle non-local request (PROXY) */
17548
conn->must_close = 1;
17549
}
17550
} else {
17551
conn->must_close = 1;
17552
}
17553
17554
if (ri->remote_user != NULL) {
17555
mg_free((void *)ri->remote_user);
17556
/* Important! When having connections with and without auth
17557
* would cause double free and then crash */
17558
ri->remote_user = NULL;
17559
}
17560
17561
/* NOTE(lsm): order is important here. should_keep_alive() call
17562
* is using parsed request, which will be invalid after
17563
* memmove's below.
17564
* Therefore, memorize should_keep_alive() result now for later
17565
* use in loop exit condition. */
17566
keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
17567
&& (conn->content_len >= 0);
17568
17569
17570
/* Discard all buffered data for this request */
17571
discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
17572
&& ((conn->request_len + conn->content_len)
17573
< (int64_t)conn->data_len))
17574
? (int)(conn->request_len + conn->content_len)
17575
: conn->data_len;
17576
DEBUG_ASSERT(discard_len >= 0);
17577
if (discard_len < 0) {
17578
DEBUG_TRACE("internal error: discard_len = %li",
17579
(long int)discard_len);
17580
break;
17581
}
17582
conn->data_len -= discard_len;
17583
if (conn->data_len > 0) {
17584
DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
17585
memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
17586
}
17587
17588
DEBUG_ASSERT(conn->data_len >= 0);
17589
DEBUG_ASSERT(conn->data_len <= conn->buf_size);
17590
17591
if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
17592
DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
17593
(long int)conn->data_len,
17594
(long int)conn->buf_size);
17595
break;
17596
}
17597
17598
conn->handled_requests++;
17599
17600
} while (keep_alive);
17601
17602
DEBUG_TRACE("Done processing connection from %s (%f sec)",
17603
conn->request_info.remote_addr,
17604
difftime(time(NULL), conn->conn_birth_time));
17605
17606
close_connection(conn);
17607
17608
#if defined(USE_SERVER_STATS)
17609
mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
17610
mg_atomic_dec(&(conn->phys_ctx->active_connections));
17611
#endif
17612
}
17613
17614
17615
#if defined(ALTERNATIVE_QUEUE)
17616
17617
static void
17618
produce_socket(struct mg_context *ctx, const struct socket *sp)
17619
{
17620
unsigned int i;
17621
17622
while (!ctx->stop_flag) {
17623
for (i = 0; i < ctx->cfg_worker_threads; i++) {
17624
/* find a free worker slot and signal it */
17625
if (ctx->client_socks[i].in_use == 0) {
17626
ctx->client_socks[i] = *sp;
17627
ctx->client_socks[i].in_use = 1;
17628
event_signal(ctx->client_wait_events[i]);
17629
return;
17630
}
17631
}
17632
/* queue is full */
17633
mg_sleep(1);
17634
}
17635
}
17636
17637
17638
static int
17639
consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
17640
{
17641
DEBUG_TRACE("%s", "going idle");
17642
ctx->client_socks[thread_index].in_use = 0;
17643
event_wait(ctx->client_wait_events[thread_index]);
17644
*sp = ctx->client_socks[thread_index];
17645
DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
17646
17647
return !ctx->stop_flag;
17648
}
17649
17650
#else /* ALTERNATIVE_QUEUE */
17651
17652
/* Worker threads take accepted socket from the queue */
17653
static int
17654
consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
17655
{
17656
#define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
17657
17658
(void)thread_index;
17659
17660
(void)pthread_mutex_lock(&ctx->thread_mutex);
17661
DEBUG_TRACE("%s", "going idle");
17662
17663
/* If the queue is empty, wait. We're idle at this point. */
17664
while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
17665
pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
17666
}
17667
17668
/* If we're stopping, sq_head may be equal to sq_tail. */
17669
if (ctx->sq_head > ctx->sq_tail) {
17670
/* Copy socket from the queue and increment tail */
17671
*sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
17672
ctx->sq_tail++;
17673
17674
DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
17675
17676
/* Wrap pointers if needed */
17677
while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
17678
ctx->sq_tail -= QUEUE_SIZE(ctx);
17679
ctx->sq_head -= QUEUE_SIZE(ctx);
17680
}
17681
}
17682
17683
(void)pthread_cond_signal(&ctx->sq_empty);
17684
(void)pthread_mutex_unlock(&ctx->thread_mutex);
17685
17686
return !ctx->stop_flag;
17687
#undef QUEUE_SIZE
17688
}
17689
17690
17691
/* Master thread adds accepted socket to a queue */
17692
static void
17693
produce_socket(struct mg_context *ctx, const struct socket *sp)
17694
{
17695
#define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
17696
if (!ctx) {
17697
return;
17698
}
17699
(void)pthread_mutex_lock(&ctx->thread_mutex);
17700
17701
/* If the queue is full, wait */
17702
while ((ctx->stop_flag == 0)
17703
&& (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
17704
(void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
17705
}
17706
17707
if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
17708
/* Copy socket to the queue and increment head */
17709
ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
17710
ctx->sq_head++;
17711
DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
17712
}
17713
17714
(void)pthread_cond_signal(&ctx->sq_full);
17715
(void)pthread_mutex_unlock(&ctx->thread_mutex);
17716
#undef QUEUE_SIZE
17717
}
17718
#endif /* ALTERNATIVE_QUEUE */
17719
17720
17721
struct worker_thread_args {
17722
struct mg_context *ctx;
17723
int index;
17724
};
17725
17726
17727
static void *
17728
worker_thread_run(struct worker_thread_args *thread_args)
17729
{
17730
struct mg_context *ctx = thread_args->ctx;
17731
struct mg_connection *conn;
17732
struct mg_workerTLS tls;
17733
#if defined(MG_LEGACY_INTERFACE)
17734
uint32_t addr;
17735
#endif
17736
17737
mg_set_thread_name("worker");
17738
17739
tls.is_master = 0;
17740
tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
17741
#if defined(_WIN32)
17742
tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
17743
#endif
17744
17745
/* Initialize thread local storage before calling any callback */
17746
pthread_setspecific(sTlsKey, &tls);
17747
17748
if (ctx->callbacks.init_thread) {
17749
/* call init_thread for a worker thread (type 1) */
17750
ctx->callbacks.init_thread(ctx, 1);
17751
}
17752
17753
/* Connection structure has been pre-allocated */
17754
if (((int)thread_args->index < 0)
17755
|| ((unsigned)thread_args->index
17756
>= (unsigned)ctx->cfg_worker_threads)) {
17757
mg_cry_internal(fc(ctx),
17758
"Internal error: Invalid worker index %i",
17759
(int)thread_args->index);
17760
return NULL;
17761
}
17762
conn = ctx->worker_connections + thread_args->index;
17763
17764
/* Request buffers are not pre-allocated. They are private to the
17765
* request and do not contain any state information that might be
17766
* of interest to anyone observing a server status. */
17767
conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
17768
if (conn->buf == NULL) {
17769
mg_cry_internal(fc(ctx),
17770
"Out of memory: Cannot allocate buffer for worker %i",
17771
(int)thread_args->index);
17772
return NULL;
17773
}
17774
conn->buf_size = (int)ctx->max_request_size;
17775
17776
conn->phys_ctx = ctx;
17777
conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
17778
conn->host = NULL; /* until we have more information. */
17779
17780
conn->thread_index = thread_args->index;
17781
conn->request_info.user_data = ctx->user_data;
17782
/* Allocate a mutex for this connection to allow communication both
17783
* within the request handler and from elsewhere in the application
17784
*/
17785
if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
17786
mg_free(conn->buf);
17787
mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
17788
return NULL;
17789
}
17790
17791
#if defined(USE_SERVER_STATS)
17792
conn->conn_state = 1; /* not consumed */
17793
#endif
17794
17795
#if defined(ALTERNATIVE_QUEUE)
17796
while ((ctx->stop_flag == 0)
17797
&& consume_socket(ctx, &conn->client, conn->thread_index)) {
17798
#else
17799
/* Call consume_socket() even when ctx->stop_flag > 0, to let it
17800
* signal sq_empty condvar to wake up the master waiting in
17801
* produce_socket() */
17802
while (consume_socket(ctx, &conn->client, conn->thread_index)) {
17803
#endif
17804
17805
conn->conn_birth_time = time(NULL);
17806
17807
/* Fill in IP, port info early so even if SSL setup below fails,
17808
* error handler would have the corresponding info.
17809
* Thanks to Johannes Winkelmann for the patch.
17810
*/
17811
#if defined(USE_IPV6)
17812
if (conn->client.rsa.sa.sa_family == AF_INET6) {
17813
conn->request_info.remote_port =
17814
ntohs(conn->client.rsa.sin6.sin6_port);
17815
} else
17816
#endif
17817
{
17818
conn->request_info.remote_port =
17819
ntohs(conn->client.rsa.sin.sin_port);
17820
}
17821
17822
sockaddr_to_string(conn->request_info.remote_addr,
17823
sizeof(conn->request_info.remote_addr),
17824
&conn->client.rsa);
17825
17826
DEBUG_TRACE("Start processing connection from %s",
17827
conn->request_info.remote_addr);
17828
17829
conn->request_info.is_ssl = conn->client.is_ssl;
17830
17831
if (conn->client.is_ssl) {
17832
#if !defined(NO_SSL)
17833
/* HTTPS connection */
17834
if (sslize(conn,
17835
conn->dom_ctx->ssl_ctx,
17836
SSL_accept,
17837
&(conn->phys_ctx->stop_flag))) {
17838
/* conn->dom_ctx is set in get_request */
17839
17840
/* Get SSL client certificate information (if set) */
17841
ssl_get_client_cert_info(conn);
17842
17843
/* process HTTPS connection */
17844
process_new_connection(conn);
17845
17846
/* Free client certificate info */
17847
if (conn->request_info.client_cert) {
17848
mg_free((void *)(conn->request_info.client_cert->subject));
17849
mg_free((void *)(conn->request_info.client_cert->issuer));
17850
mg_free((void *)(conn->request_info.client_cert->serial));
17851
mg_free((void *)(conn->request_info.client_cert->finger));
17852
/* Free certificate memory */
17853
X509_free(
17854
(X509 *)conn->request_info.client_cert->peer_cert);
17855
conn->request_info.client_cert->peer_cert = 0;
17856
conn->request_info.client_cert->subject = 0;
17857
conn->request_info.client_cert->issuer = 0;
17858
conn->request_info.client_cert->serial = 0;
17859
conn->request_info.client_cert->finger = 0;
17860
mg_free(conn->request_info.client_cert);
17861
conn->request_info.client_cert = 0;
17862
}
17863
} else {
17864
/* make sure the connection is cleaned up on SSL failure */
17865
close_connection(conn);
17866
}
17867
#endif
17868
} else {
17869
/* process HTTP connection */
17870
process_new_connection(conn);
17871
}
17872
17873
DEBUG_TRACE("%s", "Connection closed");
17874
}
17875
17876
17877
pthread_setspecific(sTlsKey, NULL);
17878
#if defined(_WIN32)
17879
CloseHandle(tls.pthread_cond_helper_mutex);
17880
#endif
17881
pthread_mutex_destroy(&conn->mutex);
17882
17883
/* Free the request buffer. */
17884
conn->buf_size = 0;
17885
mg_free(conn->buf);
17886
conn->buf = NULL;
17887
17888
#if defined(USE_SERVER_STATS)
17889
conn->conn_state = 9; /* done */
17890
#endif
17891
17892
DEBUG_TRACE("%s", "exiting");
17893
return NULL;
17894
}
17895
17896
17897
/* Threads have different return types on Windows and Unix. */
17898
#if defined(_WIN32)
17899
static unsigned __stdcall worker_thread(void *thread_func_param)
17900
{
17901
struct worker_thread_args *pwta =
17902
(struct worker_thread_args *)thread_func_param;
17903
worker_thread_run(pwta);
17904
mg_free(thread_func_param);
17905
return 0;
17906
}
17907
#else
17908
static void *
17909
worker_thread(void *thread_func_param)
17910
{
17911
struct worker_thread_args *pwta =
17912
(struct worker_thread_args *)thread_func_param;
17913
struct sigaction sa;
17914
17915
/* Ignore SIGPIPE */
17916
memset(&sa, 0, sizeof(sa));
17917
sa.sa_handler = SIG_IGN;
17918
sigaction(SIGPIPE, &sa, NULL);
17919
17920
worker_thread_run(pwta);
17921
mg_free(thread_func_param);
17922
return NULL;
17923
}
17924
#endif /* _WIN32 */
17925
17926
17927
/* This is an internal function, thus all arguments are expected to be
17928
* valid - a NULL check is not required. */
17929
static void
17930
accept_new_connection(const struct socket *listener, struct mg_context *ctx)
17931
{
17932
struct socket so;
17933
char src_addr[IP_ADDR_STR_LEN];
17934
socklen_t len = sizeof(so.rsa);
17935
int on = 1;
17936
17937
if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
17938
== INVALID_SOCKET) {
17939
} else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
17940
sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
17941
mg_cry_internal(fc(ctx),
17942
"%s: %s is not allowed to connect",
17943
__func__,
17944
src_addr);
17945
closesocket(so.sock);
17946
} else {
17947
/* Put so socket structure into the queue */
17948
DEBUG_TRACE("Accepted socket %d", (int)so.sock);
17949
set_close_on_exec(so.sock, fc(ctx));
17950
so.is_ssl = listener->is_ssl;
17951
so.ssl_redir = listener->ssl_redir;
17952
if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
17953
mg_cry_internal(fc(ctx),
17954
"%s: getsockname() failed: %s",
17955
__func__,
17956
strerror(ERRNO));
17957
}
17958
17959
/* Set TCP keep-alive. This is needed because if HTTP-level
17960
* keep-alive
17961
* is enabled, and client resets the connection, server won't get
17962
* TCP FIN or RST and will keep the connection open forever. With
17963
* TCP keep-alive, next keep-alive handshake will figure out that
17964
* the client is down and will close the server end.
17965
* Thanks to Igor Klopov who suggested the patch. */
17966
if (setsockopt(so.sock,
17967
SOL_SOCKET,
17968
SO_KEEPALIVE,
17969
(SOCK_OPT_TYPE)&on,
17970
sizeof(on))
17971
!= 0) {
17972
mg_cry_internal(
17973
fc(ctx),
17974
"%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
17975
__func__,
17976
strerror(ERRNO));
17977
}
17978
17979
/* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
17980
* to effectively fill up the underlying IP packet payload and
17981
* reduce the overhead of sending lots of small buffers. However
17982
* this hurts the server's throughput (ie. operations per second)
17983
* when HTTP 1.1 persistent connections are used and the responses
17984
* are relatively small (eg. less than 1400 bytes).
17985
*/
17986
if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
17987
&& (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
17988
if (set_tcp_nodelay(so.sock, 1) != 0) {
17989
mg_cry_internal(
17990
fc(ctx),
17991
"%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
17992
__func__,
17993
strerror(ERRNO));
17994
}
17995
}
17996
17997
/* We are using non-blocking sockets. Thus, the
17998
* set_sock_timeout(so.sock, timeout);
17999
* call is no longer required. */
18000
18001
/* The "non blocking" property should already be
18002
* inherited from the parent socket. Set it for
18003
* non-compliant socket implementations. */
18004
set_non_blocking_mode(so.sock);
18005
18006
so.in_use = 0;
18007
produce_socket(ctx, &so);
18008
}
18009
}
18010
18011
18012
static void
18013
master_thread_run(void *thread_func_param)
18014
{
18015
struct mg_context *ctx = (struct mg_context *)thread_func_param;
18016
struct mg_workerTLS tls;
18017
struct pollfd *pfd;
18018
unsigned int i;
18019
unsigned int workerthreadcount;
18020
18021
if (!ctx) {
18022
return;
18023
}
18024
18025
mg_set_thread_name("master");
18026
18027
/* Increase priority of the master thread */
18028
#if defined(_WIN32)
18029
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
18030
#elif defined(USE_MASTER_THREAD_PRIORITY)
18031
int min_prio = sched_get_priority_min(SCHED_RR);
18032
int max_prio = sched_get_priority_max(SCHED_RR);
18033
if ((min_prio >= 0) && (max_prio >= 0)
18034
&& ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
18035
&& ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
18036
struct sched_param sched_param = {0};
18037
sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
18038
pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
18039
}
18040
#endif
18041
18042
/* Initialize thread local storage */
18043
#if defined(_WIN32)
18044
tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
18045
#endif
18046
tls.is_master = 1;
18047
pthread_setspecific(sTlsKey, &tls);
18048
18049
if (ctx->callbacks.init_thread) {
18050
/* Callback for the master thread (type 0) */
18051
ctx->callbacks.init_thread(ctx, 0);
18052
}
18053
18054
/* Server starts *now* */
18055
ctx->start_time = time(NULL);
18056
18057
/* Start the server */
18058
pfd = ctx->listening_socket_fds;
18059
while (ctx->stop_flag == 0) {
18060
for (i = 0; i < ctx->num_listening_sockets; i++) {
18061
pfd[i].fd = ctx->listening_sockets[i].sock;
18062
pfd[i].events = POLLIN;
18063
}
18064
18065
if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
18066
for (i = 0; i < ctx->num_listening_sockets; i++) {
18067
/* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
18068
* successful poll, and POLLIN is defined as
18069
* (POLLRDNORM | POLLRDBAND)
18070
* Therefore, we're checking pfd[i].revents & POLLIN, not
18071
* pfd[i].revents == POLLIN. */
18072
if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
18073
accept_new_connection(&ctx->listening_sockets[i], ctx);
18074
}
18075
}
18076
}
18077
}
18078
18079
/* Here stop_flag is 1 - Initiate shutdown. */
18080
DEBUG_TRACE("%s", "stopping workers");
18081
18082
/* Stop signal received: somebody called mg_stop. Quit. */
18083
close_all_listening_sockets(ctx);
18084
18085
/* Wakeup workers that are waiting for connections to handle. */
18086
(void)pthread_mutex_lock(&ctx->thread_mutex);
18087
#if defined(ALTERNATIVE_QUEUE)
18088
for (i = 0; i < ctx->cfg_worker_threads; i++) {
18089
event_signal(ctx->client_wait_events[i]);
18090
18091
/* Since we know all sockets, we can shutdown the connections. */
18092
if (ctx->client_socks[i].in_use) {
18093
shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
18094
}
18095
}
18096
#else
18097
pthread_cond_broadcast(&ctx->sq_full);
18098
#endif
18099
(void)pthread_mutex_unlock(&ctx->thread_mutex);
18100
18101
/* Join all worker threads to avoid leaking threads. */
18102
workerthreadcount = ctx->cfg_worker_threads;
18103
for (i = 0; i < workerthreadcount; i++) {
18104
if (ctx->worker_threadids[i] != 0) {
18105
mg_join_thread(ctx->worker_threadids[i]);
18106
}
18107
}
18108
18109
#if defined(USE_LUA)
18110
/* Free Lua state of lua background task */
18111
if (ctx->lua_background_state) {
18112
lua_State *lstate = (lua_State *)ctx->lua_background_state;
18113
lua_getglobal(lstate, LUABACKGROUNDPARAMS);
18114
if (lua_istable(lstate, -1)) {
18115
reg_boolean(lstate, "shutdown", 1);
18116
lua_pop(lstate, 1);
18117
mg_sleep(2);
18118
}
18119
lua_close(lstate);
18120
ctx->lua_background_state = 0;
18121
}
18122
#endif
18123
18124
DEBUG_TRACE("%s", "exiting");
18125
18126
#if defined(_WIN32)
18127
CloseHandle(tls.pthread_cond_helper_mutex);
18128
#endif
18129
pthread_setspecific(sTlsKey, NULL);
18130
18131
/* Signal mg_stop() that we're done.
18132
* WARNING: This must be the very last thing this
18133
* thread does, as ctx becomes invalid after this line. */
18134
ctx->stop_flag = 2;
18135
}
18136
18137
18138
/* Threads have different return types on Windows and Unix. */
18139
#if defined(_WIN32)
18140
static unsigned __stdcall master_thread(void *thread_func_param)
18141
{
18142
master_thread_run(thread_func_param);
18143
return 0;
18144
}
18145
#else
18146
static void *
18147
master_thread(void *thread_func_param)
18148
{
18149
struct sigaction sa;
18150
18151
/* Ignore SIGPIPE */
18152
memset(&sa, 0, sizeof(sa));
18153
sa.sa_handler = SIG_IGN;
18154
sigaction(SIGPIPE, &sa, NULL);
18155
18156
master_thread_run(thread_func_param);
18157
return NULL;
18158
}
18159
#endif /* _WIN32 */
18160
18161
18162
static void
18163
free_context(struct mg_context *ctx)
18164
{
18165
int i;
18166
struct mg_handler_info *tmp_rh;
18167
18168
if (ctx == NULL) {
18169
return;
18170
}
18171
18172
if (ctx->callbacks.exit_context) {
18173
ctx->callbacks.exit_context(ctx);
18174
}
18175
18176
/* All threads exited, no sync is needed. Destroy thread mutex and
18177
* condvars
18178
*/
18179
(void)pthread_mutex_destroy(&ctx->thread_mutex);
18180
#if defined(ALTERNATIVE_QUEUE)
18181
mg_free(ctx->client_socks);
18182
for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
18183
event_destroy(ctx->client_wait_events[i]);
18184
}
18185
mg_free(ctx->client_wait_events);
18186
#else
18187
(void)pthread_cond_destroy(&ctx->sq_empty);
18188
(void)pthread_cond_destroy(&ctx->sq_full);
18189
#endif
18190
18191
/* Destroy other context global data structures mutex */
18192
(void)pthread_mutex_destroy(&ctx->nonce_mutex);
18193
18194
#if defined(USE_TIMERS)
18195
timers_exit(ctx);
18196
#endif
18197
18198
/* Deallocate config parameters */
18199
for (i = 0; i < NUM_OPTIONS; i++) {
18200
if (ctx->dd.config[i] != NULL) {
18201
#if defined(_MSC_VER)
18202
#pragma warning(suppress : 6001)
18203
#endif
18204
mg_free(ctx->dd.config[i]);
18205
}
18206
}
18207
18208
/* Deallocate request handlers */
18209
while (ctx->dd.handlers) {
18210
tmp_rh = ctx->dd.handlers;
18211
ctx->dd.handlers = tmp_rh->next;
18212
if (tmp_rh->handler_type == REQUEST_HANDLER) {
18213
pthread_cond_destroy(&tmp_rh->refcount_cond);
18214
pthread_mutex_destroy(&tmp_rh->refcount_mutex);
18215
}
18216
mg_free(tmp_rh->uri);
18217
mg_free(tmp_rh);
18218
}
18219
18220
#if !defined(NO_SSL)
18221
/* Deallocate SSL context */
18222
if (ctx->dd.ssl_ctx != NULL) {
18223
void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
18224
int callback_ret =
18225
(ctx->callbacks.external_ssl_ctx == NULL)
18226
? 0
18227
: (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
18228
18229
if (callback_ret == 0) {
18230
SSL_CTX_free(ctx->dd.ssl_ctx);
18231
}
18232
/* else: ignore error and ommit SSL_CTX_free in case
18233
* callback_ret is 1 */
18234
}
18235
#endif /* !NO_SSL */
18236
18237
/* Deallocate worker thread ID array */
18238
if (ctx->worker_threadids != NULL) {
18239
mg_free(ctx->worker_threadids);
18240
}
18241
18242
/* Deallocate worker thread ID array */
18243
if (ctx->worker_connections != NULL) {
18244
mg_free(ctx->worker_connections);
18245
}
18246
18247
/* deallocate system name string */
18248
mg_free(ctx->systemName);
18249
18250
/* Deallocate context itself */
18251
mg_free(ctx);
18252
}
18253
18254
18255
void
18256
mg_stop(struct mg_context *ctx)
18257
{
18258
pthread_t mt;
18259
if (!ctx) {
18260
return;
18261
}
18262
18263
/* We don't use a lock here. Calling mg_stop with the same ctx from
18264
* two threads is not allowed. */
18265
mt = ctx->masterthreadid;
18266
if (mt == 0) {
18267
return;
18268
}
18269
18270
ctx->masterthreadid = 0;
18271
18272
/* Set stop flag, so all threads know they have to exit. */
18273
ctx->stop_flag = 1;
18274
18275
/* Wait until everything has stopped. */
18276
while (ctx->stop_flag != 2) {
18277
(void)mg_sleep(10);
18278
}
18279
18280
mg_join_thread(mt);
18281
free_context(ctx);
18282
18283
#if defined(_WIN32)
18284
(void)WSACleanup();
18285
#endif /* _WIN32 */
18286
}
18287
18288
18289
static void
18290
get_system_name(char **sysName)
18291
{
18292
#if defined(_WIN32)
18293
#if !defined(__SYMBIAN32__)
18294
#if defined(_WIN32_WCE)
18295
*sysName = mg_strdup("WinCE");
18296
#else
18297
char name[128];
18298
DWORD dwVersion = 0;
18299
DWORD dwMajorVersion = 0;
18300
DWORD dwMinorVersion = 0;
18301
DWORD dwBuild = 0;
18302
BOOL wowRet, isWoW = FALSE;
18303
18304
#if defined(_MSC_VER)
18305
#pragma warning(push)
18306
/* GetVersion was declared deprecated */
18307
#pragma warning(disable : 4996)
18308
#endif
18309
dwVersion = GetVersion();
18310
#if defined(_MSC_VER)
18311
#pragma warning(pop)
18312
#endif
18313
18314
dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
18315
dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
18316
dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
18317
(void)dwBuild;
18318
18319
wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
18320
18321
sprintf(name,
18322
"Windows %u.%u%s",
18323
(unsigned)dwMajorVersion,
18324
(unsigned)dwMinorVersion,
18325
(wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
18326
18327
*sysName = mg_strdup(name);
18328
#endif
18329
#else
18330
*sysName = mg_strdup("Symbian");
18331
#endif
18332
#else
18333
struct utsname name;
18334
memset(&name, 0, sizeof(name));
18335
uname(&name);
18336
*sysName = mg_strdup(name.sysname);
18337
#endif
18338
}
18339
18340
18341
struct mg_context *
18342
mg_start(const struct mg_callbacks *callbacks,
18343
void *user_data,
18344
const char **options)
18345
{
18346
struct mg_context *ctx;
18347
const char *name, *value, *default_value;
18348
int idx, ok, workerthreadcount;
18349
unsigned int i;
18350
int itmp;
18351
void (*exit_callback)(const struct mg_context *ctx) = 0;
18352
18353
struct mg_workerTLS tls;
18354
18355
#if defined(_WIN32)
18356
WSADATA data;
18357
WSAStartup(MAKEWORD(2, 2), &data);
18358
#endif /* _WIN32 */
18359
18360
/* Allocate context and initialize reasonable general case defaults. */
18361
if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
18362
return NULL;
18363
}
18364
18365
/* Random number generator will initialize at the first call */
18366
ctx->dd.auth_nonce_mask =
18367
(uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
18368
18369
if (mg_init_library_called == 0) {
18370
/* Legacy INIT, if mg_start is called without mg_init_library.
18371
* Note: This may cause a memory leak */
18372
const char *ports_option =
18373
config_options[LISTENING_PORTS].default_value;
18374
18375
if (options) {
18376
const char **run_options = options;
18377
const char *optname = config_options[LISTENING_PORTS].name;
18378
18379
/* Try to find the "listening_ports" option */
18380
while (*run_options) {
18381
if (!strcmp(*run_options, optname)) {
18382
ports_option = run_options[1];
18383
}
18384
run_options += 2;
18385
}
18386
}
18387
18388
if (is_ssl_port_used(ports_option)) {
18389
/* Initialize with SSL support */
18390
mg_init_library(MG_FEATURES_TLS);
18391
} else {
18392
/* Initialize without SSL support */
18393
mg_init_library(MG_FEATURES_DEFAULT);
18394
}
18395
}
18396
18397
tls.is_master = -1;
18398
tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
18399
#if defined(_WIN32)
18400
tls.pthread_cond_helper_mutex = NULL;
18401
#endif
18402
pthread_setspecific(sTlsKey, &tls);
18403
18404
ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
18405
#if !defined(ALTERNATIVE_QUEUE)
18406
ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
18407
ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
18408
#endif
18409
ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
18410
if (!ok) {
18411
/* Fatal error - abort start. However, this situation should never
18412
* occur in practice. */
18413
mg_cry_internal(fc(ctx),
18414
"%s",
18415
"Cannot initialize thread synchronization objects");
18416
mg_free(ctx);
18417
pthread_setspecific(sTlsKey, NULL);
18418
return NULL;
18419
}
18420
18421
if (callbacks) {
18422
ctx->callbacks = *callbacks;
18423
exit_callback = callbacks->exit_context;
18424
ctx->callbacks.exit_context = 0;
18425
}
18426
ctx->user_data = user_data;
18427
ctx->dd.handlers = NULL;
18428
ctx->dd.next = NULL;
18429
18430
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
18431
ctx->dd.shared_lua_websockets = NULL;
18432
#endif
18433
18434
/* Store options */
18435
while (options && (name = *options++) != NULL) {
18436
if ((idx = get_option_index(name)) == -1) {
18437
mg_cry_internal(fc(ctx), "Invalid option: %s", name);
18438
free_context(ctx);
18439
pthread_setspecific(sTlsKey, NULL);
18440
return NULL;
18441
} else if ((value = *options++) == NULL) {
18442
mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
18443
free_context(ctx);
18444
pthread_setspecific(sTlsKey, NULL);
18445
return NULL;
18446
}
18447
if (ctx->dd.config[idx] != NULL) {
18448
mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
18449
mg_free(ctx->dd.config[idx]);
18450
}
18451
ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
18452
DEBUG_TRACE("[%s] -> [%s]", name, value);
18453
}
18454
18455
/* Set default value if needed */
18456
for (i = 0; config_options[i].name != NULL; i++) {
18457
default_value = config_options[i].default_value;
18458
if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
18459
ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
18460
}
18461
}
18462
18463
/* Request size option */
18464
itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
18465
if (itmp < 1024) {
18466
mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
18467
free_context(ctx);
18468
pthread_setspecific(sTlsKey, NULL);
18469
return NULL;
18470
}
18471
ctx->max_request_size = (unsigned)itmp;
18472
18473
/* Worker thread count option */
18474
workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
18475
18476
if (workerthreadcount > MAX_WORKER_THREADS) {
18477
mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
18478
free_context(ctx);
18479
pthread_setspecific(sTlsKey, NULL);
18480
return NULL;
18481
}
18482
18483
if (workerthreadcount <= 0) {
18484
mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
18485
free_context(ctx);
18486
pthread_setspecific(sTlsKey, NULL);
18487
return NULL;
18488
}
18489
18490
/* Document root */
18491
#if defined(NO_FILES)
18492
if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
18493
mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
18494
free_context(ctx);
18495
pthread_setspecific(sTlsKey, NULL);
18496
return NULL;
18497
}
18498
#endif
18499
18500
get_system_name(&ctx->systemName);
18501
18502
#if defined(USE_LUA)
18503
/* If a Lua background script has been configured, start it. */
18504
if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
18505
char ebuf[256];
18506
struct vec opt_vec;
18507
struct vec eq_vec;
18508
const char *sparams;
18509
lua_State *state = mg_prepare_lua_context_script(
18510
ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
18511
if (!state) {
18512
mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
18513
free_context(ctx);
18514
pthread_setspecific(sTlsKey, NULL);
18515
return NULL;
18516
}
18517
ctx->lua_background_state = (void *)state;
18518
18519
lua_newtable(state);
18520
reg_boolean(state, "shutdown", 0);
18521
18522
sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
18523
18524
while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
18525
reg_llstring(
18526
state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
18527
if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
18528
break;
18529
}
18530
lua_setglobal(state, LUABACKGROUNDPARAMS);
18531
18532
} else {
18533
ctx->lua_background_state = 0;
18534
}
18535
#endif
18536
18537
/* NOTE(lsm): order is important here. SSL certificates must
18538
* be initialized before listening ports. UID must be set last. */
18539
if (!set_gpass_option(ctx, NULL) ||
18540
#if !defined(NO_SSL)
18541
!init_ssl_ctx(ctx, NULL) ||
18542
#endif
18543
!set_ports_option(ctx) ||
18544
#if !defined(_WIN32)
18545
!set_uid_option(ctx) ||
18546
#endif
18547
!set_acl_option(ctx)) {
18548
free_context(ctx);
18549
pthread_setspecific(sTlsKey, NULL);
18550
return NULL;
18551
}
18552
18553
ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
18554
ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
18555
sizeof(pthread_t),
18556
ctx);
18557
18558
if (ctx->worker_threadids == NULL) {
18559
mg_cry_internal(fc(ctx),
18560
"%s",
18561
"Not enough memory for worker thread ID array");
18562
free_context(ctx);
18563
pthread_setspecific(sTlsKey, NULL);
18564
return NULL;
18565
}
18566
ctx->worker_connections =
18567
(struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
18568
sizeof(struct mg_connection),
18569
ctx);
18570
if (ctx->worker_connections == NULL) {
18571
mg_cry_internal(fc(ctx),
18572
"%s",
18573
"Not enough memory for worker thread connection array");
18574
free_context(ctx);
18575
pthread_setspecific(sTlsKey, NULL);
18576
return NULL;
18577
}
18578
18579
18580
#if defined(ALTERNATIVE_QUEUE)
18581
ctx->client_wait_events =
18582
(void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
18583
ctx->cfg_worker_threads,
18584
ctx);
18585
if (ctx->client_wait_events == NULL) {
18586
mg_cry_internal(fc(ctx),
18587
"%s",
18588
"Not enough memory for worker event array");
18589
mg_free(ctx->worker_threadids);
18590
free_context(ctx);
18591
pthread_setspecific(sTlsKey, NULL);
18592
return NULL;
18593
}
18594
18595
ctx->client_socks =
18596
(struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
18597
ctx->cfg_worker_threads,
18598
ctx);
18599
if (ctx->client_socks == NULL) {
18600
mg_cry_internal(fc(ctx),
18601
"%s",
18602
"Not enough memory for worker socket array");
18603
mg_free(ctx->client_wait_events);
18604
mg_free(ctx->worker_threadids);
18605
free_context(ctx);
18606
pthread_setspecific(sTlsKey, NULL);
18607
return NULL;
18608
}
18609
18610
for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
18611
ctx->client_wait_events[i] = event_create();
18612
if (ctx->client_wait_events[i] == 0) {
18613
mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
18614
while (i > 0) {
18615
i--;
18616
event_destroy(ctx->client_wait_events[i]);
18617
}
18618
mg_free(ctx->client_socks);
18619
mg_free(ctx->client_wait_events);
18620
mg_free(ctx->worker_threadids);
18621
free_context(ctx);
18622
pthread_setspecific(sTlsKey, NULL);
18623
return NULL;
18624
}
18625
}
18626
#endif
18627
18628
18629
#if defined(USE_TIMERS)
18630
if (timers_init(ctx) != 0) {
18631
mg_cry_internal(fc(ctx), "%s", "Error creating timers");
18632
free_context(ctx);
18633
pthread_setspecific(sTlsKey, NULL);
18634
return NULL;
18635
}
18636
#endif
18637
18638
/* Context has been created - init user libraries */
18639
if (ctx->callbacks.init_context) {
18640
ctx->callbacks.init_context(ctx);
18641
}
18642
ctx->callbacks.exit_context = exit_callback;
18643
ctx->context_type = CONTEXT_SERVER; /* server context */
18644
18645
/* Start master (listening) thread */
18646
mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
18647
18648
/* Start worker threads */
18649
for (i = 0; i < ctx->cfg_worker_threads; i++) {
18650
struct worker_thread_args *wta = (struct worker_thread_args *)
18651
mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
18652
if (wta) {
18653
wta->ctx = ctx;
18654
wta->index = (int)i;
18655
}
18656
18657
if ((wta == NULL)
18658
|| (mg_start_thread_with_id(worker_thread,
18659
wta,
18660
&ctx->worker_threadids[i])
18661
!= 0)) {
18662
18663
/* thread was not created */
18664
if (wta != NULL) {
18665
mg_free(wta);
18666
}
18667
18668
if (i > 0) {
18669
mg_cry_internal(fc(ctx),
18670
"Cannot start worker thread %i: error %ld",
18671
i + 1,
18672
(long)ERRNO);
18673
} else {
18674
mg_cry_internal(fc(ctx),
18675
"Cannot create threads: error %ld",
18676
(long)ERRNO);
18677
free_context(ctx);
18678
pthread_setspecific(sTlsKey, NULL);
18679
return NULL;
18680
}
18681
break;
18682
}
18683
}
18684
18685
pthread_setspecific(sTlsKey, NULL);
18686
return ctx;
18687
}
18688
18689
18690
#if defined(MG_EXPERIMENTAL_INTERFACES)
18691
/* Add an additional domain to an already running web server. */
18692
int
18693
mg_start_domain(struct mg_context *ctx, const char **options)
18694
{
18695
const char *name;
18696
const char *value;
18697
const char *default_value;
18698
struct mg_domain_context *new_dom;
18699
struct mg_domain_context *dom;
18700
int idx, i;
18701
18702
if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
18703
return -1;
18704
}
18705
18706
new_dom = (struct mg_domain_context *)
18707
mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
18708
18709
if (!new_dom) {
18710
/* Out of memory */
18711
return -6;
18712
}
18713
18714
/* Store options - TODO: unite duplicate code */
18715
while (options && (name = *options++) != NULL) {
18716
if ((idx = get_option_index(name)) == -1) {
18717
mg_cry_internal(fc(ctx), "Invalid option: %s", name);
18718
mg_free(new_dom);
18719
return -2;
18720
} else if ((value = *options++) == NULL) {
18721
mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
18722
mg_free(new_dom);
18723
return -2;
18724
}
18725
if (new_dom->config[idx] != NULL) {
18726
mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
18727
mg_free(new_dom->config[idx]);
18728
}
18729
new_dom->config[idx] = mg_strdup_ctx(value, ctx);
18730
DEBUG_TRACE("[%s] -> [%s]", name, value);
18731
}
18732
18733
/* Authentication domain is mandatory */
18734
/* TODO: Maybe use a new option hostname? */
18735
if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
18736
mg_cry_internal(fc(ctx), "%s", "authentication domain required");
18737
mg_free(new_dom);
18738
return -4;
18739
}
18740
18741
/* Set default value if needed. Take the config value from
18742
* ctx as a default value. */
18743
for (i = 0; config_options[i].name != NULL; i++) {
18744
default_value = ctx->dd.config[i];
18745
if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
18746
new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
18747
}
18748
}
18749
18750
new_dom->handlers = NULL;
18751
new_dom->next = NULL;
18752
new_dom->nonce_count = 0;
18753
new_dom->auth_nonce_mask =
18754
(uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
18755
18756
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
18757
new_dom->shared_lua_websockets = NULL;
18758
#endif
18759
18760
if (!init_ssl_ctx(ctx, new_dom)) {
18761
/* Init SSL failed */
18762
mg_free(new_dom);
18763
return -3;
18764
}
18765
18766
/* Add element to linked list. */
18767
mg_lock_context(ctx);
18768
18769
idx = 0;
18770
dom = &(ctx->dd);
18771
for (;;) {
18772
if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
18773
dom->config[AUTHENTICATION_DOMAIN])) {
18774
/* Domain collision */
18775
mg_cry_internal(fc(ctx),
18776
"domain %s already in use",
18777
new_dom->config[AUTHENTICATION_DOMAIN]);
18778
mg_free(new_dom);
18779
return -5;
18780
}
18781
18782
/* Count number of domains */
18783
idx++;
18784
18785
if (dom->next == NULL) {
18786
dom->next = new_dom;
18787
break;
18788
}
18789
dom = dom->next;
18790
}
18791
18792
mg_unlock_context(ctx);
18793
18794
/* Return domain number */
18795
return idx;
18796
}
18797
#endif
18798
18799
18800
/* Feature check API function */
18801
unsigned
18802
mg_check_feature(unsigned feature)
18803
{
18804
static const unsigned feature_set = 0
18805
/* Set bits for available features according to API documentation.
18806
* This bit mask is created at compile time, according to the active
18807
* preprocessor defines. It is a single const value at runtime. */
18808
#if !defined(NO_FILES)
18809
| MG_FEATURES_FILES
18810
#endif
18811
#if !defined(NO_SSL)
18812
| MG_FEATURES_SSL
18813
#endif
18814
#if !defined(NO_CGI)
18815
| MG_FEATURES_CGI
18816
#endif
18817
#if defined(USE_IPV6)
18818
| MG_FEATURES_IPV6
18819
#endif
18820
#if defined(USE_WEBSOCKET)
18821
| MG_FEATURES_WEBSOCKET
18822
#endif
18823
#if defined(USE_LUA)
18824
| MG_FEATURES_LUA
18825
#endif
18826
#if defined(USE_DUKTAPE)
18827
| MG_FEATURES_SSJS
18828
#endif
18829
#if !defined(NO_CACHING)
18830
| MG_FEATURES_CACHE
18831
#endif
18832
#if defined(USE_SERVER_STATS)
18833
| MG_FEATURES_STATS
18834
#endif
18835
#if defined(USE_ZLIB)
18836
| MG_FEATURES_COMPRESSION
18837
#endif
18838
18839
/* Set some extra bits not defined in the API documentation.
18840
* These bits may change without further notice. */
18841
#if defined(MG_LEGACY_INTERFACE)
18842
| 0x00008000u
18843
#endif
18844
#if defined(MG_EXPERIMENTAL_INTERFACES)
18845
| 0x00004000u
18846
#endif
18847
#if defined(MEMORY_DEBUGGING)
18848
| 0x00001000u
18849
#endif
18850
#if defined(USE_TIMERS)
18851
| 0x00020000u
18852
#endif
18853
#if !defined(NO_NONCE_CHECK)
18854
| 0x00040000u
18855
#endif
18856
#if !defined(NO_POPEN)
18857
| 0x00080000u
18858
#endif
18859
;
18860
return (feature & feature_set);
18861
}
18862
18863
18864
/* strcat with additional NULL check to avoid clang scan-build warning. */
18865
#define strcat0(a, b) \
18866
{ \
18867
if ((a != NULL) && (b != NULL)) { \
18868
strcat(a, b); \
18869
} \
18870
}
18871
18872
18873
/* Get system information. It can be printed or stored by the caller.
18874
* Return the size of available information. */
18875
static int
18876
mg_get_system_info_impl(char *buffer, int buflen)
18877
{
18878
char block[256];
18879
int system_info_length = 0;
18880
18881
#if defined(_WIN32)
18882
const char *eol = "\r\n";
18883
#else
18884
const char *eol = "\n";
18885
#endif
18886
18887
const char *eoobj = "}";
18888
int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
18889
18890
if ((buffer == NULL) || (buflen < 1)) {
18891
buflen = 0;
18892
} else {
18893
*buffer = 0;
18894
}
18895
18896
mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
18897
system_info_length += (int)strlen(block);
18898
if (system_info_length < buflen) {
18899
strcat0(buffer, block);
18900
}
18901
18902
/* Server version */
18903
{
18904
const char *version = mg_version();
18905
mg_snprintf(NULL,
18906
NULL,
18907
block,
18908
sizeof(block),
18909
"\"version\" : \"%s\",%s",
18910
version,
18911
eol);
18912
system_info_length += (int)strlen(block);
18913
if (system_info_length < buflen) {
18914
strcat0(buffer, block);
18915
}
18916
}
18917
18918
/* System info */
18919
{
18920
#if defined(_WIN32)
18921
DWORD dwVersion = 0;
18922
DWORD dwMajorVersion = 0;
18923
DWORD dwMinorVersion = 0;
18924
SYSTEM_INFO si;
18925
18926
GetSystemInfo(&si);
18927
18928
#if defined(_MSC_VER)
18929
#pragma warning(push)
18930
/* GetVersion was declared deprecated */
18931
#pragma warning(disable : 4996)
18932
#endif
18933
dwVersion = GetVersion();
18934
#if defined(_MSC_VER)
18935
#pragma warning(pop)
18936
#endif
18937
18938
dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
18939
dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
18940
18941
mg_snprintf(NULL,
18942
NULL,
18943
block,
18944
sizeof(block),
18945
"\"os\" : \"Windows %u.%u\",%s",
18946
(unsigned)dwMajorVersion,
18947
(unsigned)dwMinorVersion,
18948
eol);
18949
system_info_length += (int)strlen(block);
18950
if (system_info_length < buflen) {
18951
strcat0(buffer, block);
18952
}
18953
18954
mg_snprintf(NULL,
18955
NULL,
18956
block,
18957
sizeof(block),
18958
"\"cpu\" : \"type %u, cores %u, mask %x\",%s",
18959
(unsigned)si.wProcessorArchitecture,
18960
(unsigned)si.dwNumberOfProcessors,
18961
(unsigned)si.dwActiveProcessorMask,
18962
eol);
18963
system_info_length += (int)strlen(block);
18964
if (system_info_length < buflen) {
18965
strcat0(buffer, block);
18966
}
18967
#else
18968
struct utsname name;
18969
memset(&name, 0, sizeof(name));
18970
uname(&name);
18971
18972
mg_snprintf(NULL,
18973
NULL,
18974
block,
18975
sizeof(block),
18976
"\"os\" : \"%s %s (%s) - %s\",%s",
18977
name.sysname,
18978
name.version,
18979
name.release,
18980
name.machine,
18981
eol);
18982
system_info_length += (int)strlen(block);
18983
if (system_info_length < buflen) {
18984
strcat0(buffer, block);
18985
}
18986
#endif
18987
}
18988
18989
/* Features */
18990
{
18991
mg_snprintf(NULL,
18992
NULL,
18993
block,
18994
sizeof(block),
18995
"\"features\" : %lu,%s"
18996
"\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
18997
(unsigned long)mg_check_feature(0xFFFFFFFFu),
18998
eol,
18999
mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
19000
mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
19001
mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
19002
mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
19003
mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
19004
: "",
19005
mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
19006
mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
19007
mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
19008
mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
19009
eol);
19010
system_info_length += (int)strlen(block);
19011
if (system_info_length < buflen) {
19012
strcat0(buffer, block);
19013
}
19014
19015
#if defined(USE_LUA)
19016
mg_snprintf(NULL,
19017
NULL,
19018
block,
19019
sizeof(block),
19020
"\"lua_version\" : \"%u (%s)\",%s",
19021
(unsigned)LUA_VERSION_NUM,
19022
LUA_RELEASE,
19023
eol);
19024
system_info_length += (int)strlen(block);
19025
if (system_info_length < buflen) {
19026
strcat0(buffer, block);
19027
}
19028
#endif
19029
#if defined(USE_DUKTAPE)
19030
mg_snprintf(NULL,
19031
NULL,
19032
block,
19033
sizeof(block),
19034
"\"javascript\" : \"Duktape %u.%u.%u\",%s",
19035
(unsigned)DUK_VERSION / 10000,
19036
((unsigned)DUK_VERSION / 100) % 100,
19037
(unsigned)DUK_VERSION % 100,
19038
eol);
19039
system_info_length += (int)strlen(block);
19040
if (system_info_length < buflen) {
19041
strcat0(buffer, block);
19042
}
19043
#endif
19044
}
19045
19046
/* Build date */
19047
{
19048
#if defined(GCC_DIAGNOSTIC)
19049
#pragma GCC diagnostic push
19050
/* Disable bogus compiler warning -Wdate-time */
19051
#pragma GCC diagnostic ignored "-Wdate-time"
19052
#endif
19053
mg_snprintf(NULL,
19054
NULL,
19055
block,
19056
sizeof(block),
19057
"\"build\" : \"%s\",%s",
19058
__DATE__,
19059
eol);
19060
19061
#if defined(GCC_DIAGNOSTIC)
19062
#pragma GCC diagnostic pop
19063
#endif
19064
19065
system_info_length += (int)strlen(block);
19066
if (system_info_length < buflen) {
19067
strcat0(buffer, block);
19068
}
19069
}
19070
19071
19072
/* Compiler information */
19073
/* http://sourceforge.net/p/predef/wiki/Compilers/ */
19074
{
19075
#if defined(_MSC_VER)
19076
mg_snprintf(NULL,
19077
NULL,
19078
block,
19079
sizeof(block),
19080
"\"compiler\" : \"MSC: %u (%u)\",%s",
19081
(unsigned)_MSC_VER,
19082
(unsigned)_MSC_FULL_VER,
19083
eol);
19084
system_info_length += (int)strlen(block);
19085
if (system_info_length < buflen) {
19086
strcat0(buffer, block);
19087
}
19088
#elif defined(__MINGW64__)
19089
mg_snprintf(NULL,
19090
NULL,
19091
block,
19092
sizeof(block),
19093
"\"compiler\" : \"MinGW64: %u.%u\",%s",
19094
(unsigned)__MINGW64_VERSION_MAJOR,
19095
(unsigned)__MINGW64_VERSION_MINOR,
19096
eol);
19097
system_info_length += (int)strlen(block);
19098
if (system_info_length < buflen) {
19099
strcat0(buffer, block);
19100
}
19101
mg_snprintf(NULL,
19102
NULL,
19103
block,
19104
sizeof(block),
19105
"\"compiler\" : \"MinGW32: %u.%u\",%s",
19106
(unsigned)__MINGW32_MAJOR_VERSION,
19107
(unsigned)__MINGW32_MINOR_VERSION,
19108
eol);
19109
system_info_length += (int)strlen(block);
19110
if (system_info_length < buflen) {
19111
strcat0(buffer, block);
19112
}
19113
#elif defined(__MINGW32__)
19114
mg_snprintf(NULL,
19115
NULL,
19116
block,
19117
sizeof(block),
19118
"\"compiler\" : \"MinGW32: %u.%u\",%s",
19119
(unsigned)__MINGW32_MAJOR_VERSION,
19120
(unsigned)__MINGW32_MINOR_VERSION,
19121
eol);
19122
system_info_length += (int)strlen(block);
19123
if (system_info_length < buflen) {
19124
strcat0(buffer, block);
19125
}
19126
#elif defined(__clang__)
19127
mg_snprintf(NULL,
19128
NULL,
19129
block,
19130
sizeof(block),
19131
"\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
19132
__clang_major__,
19133
__clang_minor__,
19134
__clang_patchlevel__,
19135
__clang_version__,
19136
eol);
19137
system_info_length += (int)strlen(block);
19138
if (system_info_length < buflen) {
19139
strcat0(buffer, block);
19140
}
19141
#elif defined(__GNUC__)
19142
mg_snprintf(NULL,
19143
NULL,
19144
block,
19145
sizeof(block),
19146
"\"compiler\" : \"gcc: %u.%u.%u\",%s",
19147
(unsigned)__GNUC__,
19148
(unsigned)__GNUC_MINOR__,
19149
(unsigned)__GNUC_PATCHLEVEL__,
19150
eol);
19151
system_info_length += (int)strlen(block);
19152
if (system_info_length < buflen) {
19153
strcat0(buffer, block);
19154
}
19155
#elif defined(__INTEL_COMPILER)
19156
mg_snprintf(NULL,
19157
NULL,
19158
block,
19159
sizeof(block),
19160
"\"compiler\" : \"Intel C/C++: %u\",%s",
19161
(unsigned)__INTEL_COMPILER,
19162
eol);
19163
system_info_length += (int)strlen(block);
19164
if (system_info_length < buflen) {
19165
strcat0(buffer, block);
19166
}
19167
#elif defined(__BORLANDC__)
19168
mg_snprintf(NULL,
19169
NULL,
19170
block,
19171
sizeof(block),
19172
"\"compiler\" : \"Borland C: 0x%x\",%s",
19173
(unsigned)__BORLANDC__,
19174
eol);
19175
system_info_length += (int)strlen(block);
19176
if (system_info_length < buflen) {
19177
strcat0(buffer, block);
19178
}
19179
#elif defined(__SUNPRO_C)
19180
mg_snprintf(NULL,
19181
NULL,
19182
block,
19183
sizeof(block),
19184
"\"compiler\" : \"Solaris: 0x%x\",%s",
19185
(unsigned)__SUNPRO_C,
19186
eol);
19187
system_info_length += (int)strlen(block);
19188
if (system_info_length < buflen) {
19189
strcat0(buffer, block);
19190
}
19191
#else
19192
mg_snprintf(NULL,
19193
NULL,
19194
block,
19195
sizeof(block),
19196
"\"compiler\" : \"other\",%s",
19197
eol);
19198
system_info_length += (int)strlen(block);
19199
if (system_info_length < buflen) {
19200
strcat0(buffer, block);
19201
}
19202
#endif
19203
}
19204
19205
/* Determine 32/64 bit data mode.
19206
* see https://en.wikipedia.org/wiki/64-bit_computing */
19207
{
19208
mg_snprintf(NULL,
19209
NULL,
19210
block,
19211
sizeof(block),
19212
"\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
19213
"char:%u/%u, "
19214
"ptr:%u, size:%u, time:%u\"%s",
19215
(unsigned)sizeof(short),
19216
(unsigned)sizeof(int),
19217
(unsigned)sizeof(long),
19218
(unsigned)sizeof(long long),
19219
(unsigned)sizeof(float),
19220
(unsigned)sizeof(double),
19221
(unsigned)sizeof(long double),
19222
(unsigned)sizeof(char),
19223
(unsigned)sizeof(wchar_t),
19224
(unsigned)sizeof(void *),
19225
(unsigned)sizeof(size_t),
19226
(unsigned)sizeof(time_t),
19227
eol);
19228
system_info_length += (int)strlen(block);
19229
if (system_info_length < buflen) {
19230
strcat0(buffer, block);
19231
}
19232
}
19233
19234
/* Terminate string */
19235
if ((buflen > 0) && buffer && buffer[0]) {
19236
if (system_info_length < buflen) {
19237
strcat0(buffer, eoobj);
19238
strcat0(buffer, eol);
19239
}
19240
}
19241
system_info_length += reserved_len;
19242
19243
return system_info_length;
19244
}
19245
19246
19247
#if defined(USE_SERVER_STATS)
19248
/* Get context information. It can be printed or stored by the caller.
19249
* Return the size of available information. */
19250
static int
19251
mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
19252
19253
{
19254
char block[256];
19255
int context_info_length = 0;
19256
19257
#if defined(_WIN32)
19258
const char *eol = "\r\n";
19259
#else
19260
const char *eol = "\n";
19261
#endif
19262
struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
19263
19264
const char *eoobj = "}";
19265
int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
19266
19267
if ((buffer == NULL) || (buflen < 1)) {
19268
buflen = 0;
19269
} else {
19270
*buffer = 0;
19271
}
19272
19273
mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
19274
context_info_length += (int)strlen(block);
19275
if (context_info_length < buflen) {
19276
strcat0(buffer, block);
19277
}
19278
19279
if (ms) { /* <-- should be always true */
19280
/* Memory information */
19281
mg_snprintf(NULL,
19282
NULL,
19283
block,
19284
sizeof(block),
19285
"\"memory\" : {%s"
19286
"\"blocks\" : %i,%s"
19287
"\"used\" : %" INT64_FMT ",%s"
19288
"\"maxUsed\" : %" INT64_FMT "%s"
19289
"}%s%s",
19290
eol,
19291
ms->blockCount,
19292
eol,
19293
ms->totalMemUsed,
19294
eol,
19295
ms->maxMemUsed,
19296
eol,
19297
(ctx ? "," : ""),
19298
eol);
19299
19300
context_info_length += (int)strlen(block);
19301
if (context_info_length + reserved_len < buflen) {
19302
strcat0(buffer, block);
19303
}
19304
}
19305
19306
if (ctx) {
19307
/* Declare all variables at begin of the block, to comply
19308
* with old C standards. */
19309
char start_time_str[64] = {0};
19310
char now_str[64] = {0};
19311
time_t start_time = ctx->start_time;
19312
time_t now = time(NULL);
19313
19314
/* Connections information */
19315
mg_snprintf(NULL,
19316
NULL,
19317
block,
19318
sizeof(block),
19319
"\"connections\" : {%s"
19320
"\"active\" : %i,%s"
19321
"\"maxActive\" : %i,%s"
19322
"\"total\" : %" INT64_FMT "%s"
19323
"},%s",
19324
eol,
19325
ctx->active_connections,
19326
eol,
19327
ctx->max_connections,
19328
eol,
19329
ctx->total_connections,
19330
eol,
19331
eol);
19332
19333
context_info_length += (int)strlen(block);
19334
if (context_info_length + reserved_len < buflen) {
19335
strcat0(buffer, block);
19336
}
19337
19338
/* Requests information */
19339
mg_snprintf(NULL,
19340
NULL,
19341
block,
19342
sizeof(block),
19343
"\"requests\" : {%s"
19344
"\"total\" : %" INT64_FMT "%s"
19345
"},%s",
19346
eol,
19347
ctx->total_requests,
19348
eol,
19349
eol);
19350
19351
context_info_length += (int)strlen(block);
19352
if (context_info_length + reserved_len < buflen) {
19353
strcat0(buffer, block);
19354
}
19355
19356
/* Data information */
19357
mg_snprintf(NULL,
19358
NULL,
19359
block,
19360
sizeof(block),
19361
"\"data\" : {%s"
19362
"\"read\" : %" INT64_FMT "%s,"
19363
"\"written\" : %" INT64_FMT "%s"
19364
"},%s",
19365
eol,
19366
ctx->total_data_read,
19367
eol,
19368
ctx->total_data_written,
19369
eol,
19370
eol);
19371
19372
context_info_length += (int)strlen(block);
19373
if (context_info_length + reserved_len < buflen) {
19374
strcat0(buffer, block);
19375
}
19376
19377
/* Execution time information */
19378
gmt_time_string(start_time_str,
19379
sizeof(start_time_str) - 1,
19380
&start_time);
19381
gmt_time_string(now_str, sizeof(now_str) - 1, &now);
19382
19383
mg_snprintf(NULL,
19384
NULL,
19385
block,
19386
sizeof(block),
19387
"\"time\" : {%s"
19388
"\"uptime\" : %.0f,%s"
19389
"\"start\" : \"%s\",%s"
19390
"\"now\" : \"%s\"%s"
19391
"}%s",
19392
eol,
19393
difftime(now, start_time),
19394
eol,
19395
start_time_str,
19396
eol,
19397
now_str,
19398
eol,
19399
eol);
19400
19401
context_info_length += (int)strlen(block);
19402
if (context_info_length + reserved_len < buflen) {
19403
strcat0(buffer, block);
19404
}
19405
}
19406
19407
/* Terminate string */
19408
if ((buflen > 0) && buffer && buffer[0]) {
19409
if (context_info_length < buflen) {
19410
strcat0(buffer, eoobj);
19411
strcat0(buffer, eol);
19412
}
19413
}
19414
context_info_length += reserved_len;
19415
19416
return context_info_length;
19417
}
19418
#endif
19419
19420
19421
#if defined(MG_EXPERIMENTAL_INTERFACES)
19422
/* Get connection information. It can be printed or stored by the caller.
19423
* Return the size of available information. */
19424
static int
19425
mg_get_connection_info_impl(const struct mg_context *ctx,
19426
int idx,
19427
char *buffer,
19428
int buflen)
19429
{
19430
const struct mg_connection *conn;
19431
const struct mg_request_info *ri;
19432
char block[256];
19433
int connection_info_length = 0;
19434
int state = 0;
19435
const char *state_str = "unknown";
19436
19437
#if defined(_WIN32)
19438
const char *eol = "\r\n";
19439
#else
19440
const char *eol = "\n";
19441
#endif
19442
19443
const char *eoobj = "}";
19444
int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
19445
19446
if ((buffer == NULL) || (buflen < 1)) {
19447
buflen = 0;
19448
} else {
19449
*buffer = 0;
19450
}
19451
19452
if ((ctx == NULL) || (idx < 0)) {
19453
/* Parameter error */
19454
return 0;
19455
}
19456
19457
if ((unsigned)idx >= ctx->cfg_worker_threads) {
19458
/* Out of range */
19459
return 0;
19460
}
19461
19462
/* Take connection [idx]. This connection is not locked in
19463
* any way, so some other thread might use it. */
19464
conn = (ctx->worker_connections) + idx;
19465
19466
/* Initialize output string */
19467
mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
19468
connection_info_length += (int)strlen(block);
19469
if (connection_info_length < buflen) {
19470
strcat0(buffer, block);
19471
}
19472
19473
/* Init variables */
19474
ri = &(conn->request_info);
19475
19476
#if defined(USE_SERVER_STATS)
19477
state = conn->conn_state;
19478
19479
/* State as string */
19480
switch (state) {
19481
case 0:
19482
state_str = "undefined";
19483
break;
19484
case 1:
19485
state_str = "not used";
19486
break;
19487
case 2:
19488
state_str = "init";
19489
break;
19490
case 3:
19491
state_str = "ready";
19492
break;
19493
case 4:
19494
state_str = "processing";
19495
break;
19496
case 5:
19497
state_str = "processed";
19498
break;
19499
case 6:
19500
state_str = "to close";
19501
break;
19502
case 7:
19503
state_str = "closing";
19504
break;
19505
case 8:
19506
state_str = "closed";
19507
break;
19508
case 9:
19509
state_str = "done";
19510
break;
19511
}
19512
#endif
19513
19514
/* Connection info */
19515
if ((state >= 3) && (state < 9)) {
19516
mg_snprintf(NULL,
19517
NULL,
19518
block,
19519
sizeof(block),
19520
"\"connection\" : {%s"
19521
"\"remote\" : {%s"
19522
"\"protocol\" : \"%s\",%s"
19523
"\"addr\" : \"%s\",%s"
19524
"\"port\" : %u%s"
19525
"},%s"
19526
"\"handled_requests\" : %u%s"
19527
"},%s",
19528
eol,
19529
eol,
19530
get_proto_name(conn),
19531
eol,
19532
ri->remote_addr,
19533
eol,
19534
ri->remote_port,
19535
eol,
19536
eol,
19537
conn->handled_requests,
19538
eol,
19539
eol);
19540
19541
connection_info_length += (int)strlen(block);
19542
if (connection_info_length + reserved_len < buflen) {
19543
strcat0(buffer, block);
19544
}
19545
}
19546
19547
/* Request info */
19548
if ((state >= 4) && (state < 6)) {
19549
mg_snprintf(NULL,
19550
NULL,
19551
block,
19552
sizeof(block),
19553
"\"request_info\" : {%s"
19554
"\"method\" : \"%s\",%s"
19555
"\"uri\" : \"%s\",%s"
19556
"\"query\" : %s%s%s%s"
19557
"},%s",
19558
eol,
19559
ri->request_method,
19560
eol,
19561
ri->request_uri,
19562
eol,
19563
ri->query_string ? "\"" : "",
19564
ri->query_string ? ri->query_string : "null",
19565
ri->query_string ? "\"" : "",
19566
eol,
19567
eol);
19568
19569
connection_info_length += (int)strlen(block);
19570
if (connection_info_length + reserved_len < buflen) {
19571
strcat0(buffer, block);
19572
}
19573
}
19574
19575
/* Execution time information */
19576
if ((state >= 2) && (state < 9)) {
19577
char start_time_str[64] = {0};
19578
char now_str[64] = {0};
19579
time_t start_time = conn->conn_birth_time;
19580
time_t now = time(NULL);
19581
19582
gmt_time_string(start_time_str,
19583
sizeof(start_time_str) - 1,
19584
&start_time);
19585
gmt_time_string(now_str, sizeof(now_str) - 1, &now);
19586
19587
mg_snprintf(NULL,
19588
NULL,
19589
block,
19590
sizeof(block),
19591
"\"time\" : {%s"
19592
"\"uptime\" : %.0f,%s"
19593
"\"start\" : \"%s\",%s"
19594
"\"now\" : \"%s\"%s"
19595
"},%s",
19596
eol,
19597
difftime(now, start_time),
19598
eol,
19599
start_time_str,
19600
eol,
19601
now_str,
19602
eol,
19603
eol);
19604
19605
connection_info_length += (int)strlen(block);
19606
if (connection_info_length + reserved_len < buflen) {
19607
strcat0(buffer, block);
19608
}
19609
}
19610
19611
/* Remote user name */
19612
if ((ri->remote_user) && (state < 9)) {
19613
mg_snprintf(NULL,
19614
NULL,
19615
block,
19616
sizeof(block),
19617
"\"user\" : {%s"
19618
"\"name\" : \"%s\",%s"
19619
"},%s",
19620
eol,
19621
ri->remote_user,
19622
eol,
19623
eol);
19624
19625
connection_info_length += (int)strlen(block);
19626
if (connection_info_length + reserved_len < buflen) {
19627
strcat0(buffer, block);
19628
}
19629
}
19630
19631
/* Data block */
19632
if (state >= 3) {
19633
mg_snprintf(NULL,
19634
NULL,
19635
block,
19636
sizeof(block),
19637
"\"data\" : {%s"
19638
"\"read\" : %" INT64_FMT ",%s"
19639
"\"written\" : %" INT64_FMT "%s"
19640
"},%s",
19641
eol,
19642
conn->consumed_content,
19643
eol,
19644
conn->num_bytes_sent,
19645
eol,
19646
eol);
19647
19648
connection_info_length += (int)strlen(block);
19649
if (connection_info_length + reserved_len < buflen) {
19650
strcat0(buffer, block);
19651
}
19652
}
19653
19654
/* State */
19655
mg_snprintf(NULL,
19656
NULL,
19657
block,
19658
sizeof(block),
19659
"\"state\" : \"%s\"%s",
19660
state_str,
19661
eol);
19662
19663
connection_info_length += (int)strlen(block);
19664
if (connection_info_length + reserved_len < buflen) {
19665
strcat0(buffer, block);
19666
}
19667
19668
/* Terminate string */
19669
if ((buflen > 0) && buffer && buffer[0]) {
19670
if (connection_info_length < buflen) {
19671
strcat0(buffer, eoobj);
19672
strcat0(buffer, eol);
19673
}
19674
}
19675
connection_info_length += reserved_len;
19676
19677
return connection_info_length;
19678
}
19679
#endif
19680
19681
19682
/* Get system information. It can be printed or stored by the caller.
19683
* Return the size of available information. */
19684
int
19685
mg_get_system_info(char *buffer, int buflen)
19686
{
19687
if ((buffer == NULL) || (buflen < 1)) {
19688
return mg_get_system_info_impl(NULL, 0);
19689
} else {
19690
/* Reset buffer, so we can always use strcat. */
19691
buffer[0] = 0;
19692
return mg_get_system_info_impl(buffer, buflen);
19693
}
19694
}
19695
19696
19697
/* Get context information. It can be printed or stored by the caller.
19698
* Return the size of available information. */
19699
int
19700
mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
19701
{
19702
#if defined(USE_SERVER_STATS)
19703
if ((buffer == NULL) || (buflen < 1)) {
19704
return mg_get_context_info_impl(ctx, NULL, 0);
19705
} else {
19706
/* Reset buffer, so we can always use strcat. */
19707
buffer[0] = 0;
19708
return mg_get_context_info_impl(ctx, buffer, buflen);
19709
}
19710
#else
19711
(void)ctx;
19712
if ((buffer != NULL) && (buflen > 0)) {
19713
buffer[0] = 0;
19714
}
19715
return 0;
19716
#endif
19717
}
19718
19719
19720
#if defined(MG_EXPERIMENTAL_INTERFACES)
19721
int
19722
mg_get_connection_info(const struct mg_context *ctx,
19723
int idx,
19724
char *buffer,
19725
int buflen)
19726
{
19727
if ((buffer == NULL) || (buflen < 1)) {
19728
return mg_get_connection_info_impl(ctx, idx, NULL, 0);
19729
} else {
19730
/* Reset buffer, so we can always use strcat. */
19731
buffer[0] = 0;
19732
return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
19733
}
19734
}
19735
#endif
19736
19737
19738
/* Initialize this library. This function does not need to be thread safe.
19739
*/
19740
unsigned
19741
mg_init_library(unsigned features)
19742
{
19743
#if !defined(NO_SSL)
19744
char ebuf[128];
19745
#endif
19746
19747
unsigned features_to_init = mg_check_feature(features & 0xFFu);
19748
unsigned features_inited = features_to_init;
19749
19750
if (mg_init_library_called <= 0) {
19751
/* Not initialized yet */
19752
if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
19753
return 0;
19754
}
19755
}
19756
19757
mg_global_lock();
19758
19759
if (mg_init_library_called <= 0) {
19760
if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
19761
/* Fatal error - abort start. However, this situation should
19762
* never occur in practice. */
19763
mg_global_unlock();
19764
return 0;
19765
}
19766
19767
#if defined(_WIN32)
19768
InitializeCriticalSection(&global_log_file_lock);
19769
#endif
19770
#if !defined(_WIN32)
19771
pthread_mutexattr_init(&pthread_mutex_attr);
19772
pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
19773
#endif
19774
19775
#if defined(USE_LUA)
19776
lua_init_optional_libraries();
19777
#endif
19778
}
19779
19780
mg_global_unlock();
19781
19782
#if !defined(NO_SSL)
19783
if (features_to_init & MG_FEATURES_SSL) {
19784
if (!mg_ssl_initialized) {
19785
if (initialize_ssl(ebuf, sizeof(ebuf))) {
19786
mg_ssl_initialized = 1;
19787
} else {
19788
(void)ebuf;
19789
DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
19790
features_inited &= ~((unsigned)(MG_FEATURES_SSL));
19791
}
19792
} else {
19793
/* ssl already initialized */
19794
}
19795
}
19796
#endif
19797
19798
/* Start WinSock for Windows */
19799
mg_global_lock();
19800
if (mg_init_library_called <= 0) {
19801
#if defined(_WIN32)
19802
WSADATA data;
19803
WSAStartup(MAKEWORD(2, 2), &data);
19804
#endif /* _WIN32 */
19805
mg_init_library_called = 1;
19806
} else {
19807
mg_init_library_called++;
19808
}
19809
mg_global_unlock();
19810
19811
return features_inited;
19812
}
19813
19814
19815
/* Un-initialize this library. */
19816
unsigned
19817
mg_exit_library(void)
19818
{
19819
if (mg_init_library_called <= 0) {
19820
return 0;
19821
}
19822
19823
mg_global_lock();
19824
19825
mg_init_library_called--;
19826
if (mg_init_library_called == 0) {
19827
#if defined(_WIN32)
19828
(void)WSACleanup();
19829
#endif /* _WIN32 */
19830
#if !defined(NO_SSL)
19831
if (mg_ssl_initialized) {
19832
uninitialize_ssl();
19833
mg_ssl_initialized = 0;
19834
}
19835
#endif
19836
19837
#if defined(_WIN32)
19838
(void)DeleteCriticalSection(&global_log_file_lock);
19839
#endif /* _WIN32 */
19840
#if !defined(_WIN32)
19841
(void)pthread_mutexattr_destroy(&pthread_mutex_attr);
19842
#endif
19843
19844
(void)pthread_key_delete(sTlsKey);
19845
19846
#if defined(USE_LUA)
19847
lua_exit_optional_libraries();
19848
#endif
19849
19850
mg_global_unlock();
19851
(void)pthread_mutex_destroy(&global_lock_mutex);
19852
return 1;
19853
}
19854
19855
mg_global_unlock();
19856
return 1;
19857
}
19858
19859
19860
/* End of civetweb.c */
19861
19862