forked from libretro/RetroArch
-
Notifications
You must be signed in to change notification settings - Fork 2
/
civetweb.c
13062 lines (11336 loc) · 328 KB
/
civetweb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2013-2016 the Civetweb developers
* Copyright (c) 2004-2013 Sergey Lyubka
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#if defined(_WIN32)
#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
#endif
#ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
#define _WIN32_WINNT 0x0501
#endif
#else
#if defined(__GNUC__) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE /* for setgroups() */
#endif
#if defined(__linux__) && !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
#endif
#ifndef _LARGEFILE_SOURCE
#define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
#endif
#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
#endif
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
#endif
#ifdef __sun
#define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
#define __inline inline /* not recognized on older compiler versions */
#endif
#endif
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
#define USE_TIMERS
#endif
#if defined(_MSC_VER)
/* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
#pragma warning(disable : 4306)
/* conditional expression is constant: introduced by FD_SET(..) */
#pragma warning(disable : 4127)
/* non-constant aggregate initializer: issued due to missing C99 support */
#pragma warning(disable : 4204)
/* padding added after data member */
#pragma warning(disable : 4820)
/* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
#pragma warning(disable : 4668)
/* no function prototype given: converting '()' to '(void)' */
#pragma warning(disable : 4255)
/* function has been selected for automatic inline expansion */
#pragma warning(disable : 4711)
#endif
/* This code uses static_assert to check some conditions.
* Unfortunately some compilers still do not support it, so we have a
* replacement function here. */
#if defined(_MSC_VER) && (_MSC_VER >= 1600)
#define mg_static_assert static_assert
#elif defined(__cplusplus) && (__cplusplus >= 201103L)
#define mg_static_assert static_assert
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
#define mg_static_assert _Static_assert
#else
char static_assert_replacement[1];
#define mg_static_assert(cond, txt) \
extern char static_assert_replacement[(cond) ? 1 : -1]
#endif
mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
"int data type size check");
mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
"pointer data type size check");
mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
/* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
* type size check"); */
/* DTL -- including winsock2.h works better if lean and mean */
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#if defined(__SYMBIAN32__)
#define NO_SSL /* SSL is not supported */
#define NO_CGI /* CGI is not supported */
#define PATH_MAX FILENAME_MAX
#endif /* __SYMBIAN32__ */
#ifndef IGNORE_UNUSED_RESULT
#define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
#endif
#ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#endif /* !_WIN32_WCE */
#ifdef __MACH__
#define CLOCK_MONOTONIC (1)
#define CLOCK_REALTIME (2)
#include <sys/time.h>
#include <mach/clock.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <assert.h>
/* clock_gettime is not implemented on OSX */
int clock_gettime(int clk_id, struct timespec *t);
int
clock_gettime(int clk_id, struct timespec *t)
{
memset(t, 0, sizeof(*t));
if (clk_id == CLOCK_REALTIME) {
struct timeval now;
int rv = gettimeofday(&now, NULL);
if (rv) {
return rv;
}
t->tv_sec = now.tv_sec;
t->tv_nsec = now.tv_usec * 1000;
return 0;
}
else if (clk_id == CLOCK_MONOTONIC) {
static uint64_t clock_start_time = 0;
static mach_timebase_info_data_t timebase_ifo = { 0, 0 };
uint64_t now = mach_absolute_time();
if (clock_start_time == 0) {
kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
#if defined(DEBUG)
assert(mach_status == KERN_SUCCESS);
#else
/* appease "unused variable" warning for release builds */
(void)mach_status;
#endif
clock_start_time = now;
}
now = (uint64_t)((double)(now - clock_start_time)
* (double)timebase_ifo.numer
/ (double)timebase_ifo.denom);
t->tv_sec = now / 1000000000;
t->tv_nsec = now % 1000000000;
return 0;
}
return -1; /* EINVAL - Clock ID is unknown */
}
#endif
#include <time.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#ifndef MAX_WORKER_THREADS
#define MAX_WORKER_THREADS (1024 * 64)
#endif
#ifndef SOCKET_TIMEOUT_QUANTUM
#define SOCKET_TIMEOUT_QUANTUM (10000)
#endif
mg_static_assert(MAX_WORKER_THREADS >= 1,
"worker threads must be a positive number");
#if defined(_WIN32) \
&& !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
#include <windows.h>
#include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
#include <ws2tcpip.h>
typedef const char *SOCK_OPT_TYPE;
#if !defined(PATH_MAX)
#define PATH_MAX (MAX_PATH)
#endif
#if !defined(PATH_MAX)
#define PATH_MAX (4096)
#endif
mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
#ifndef _IN_PORT_T
#ifndef in_port_t
#define in_port_t u_short
#endif
#endif
#ifndef _WIN32_WCE
#include <process.h>
#include <direct.h>
#include <io.h>
#else /* _WIN32_WCE */
#define NO_CGI /* WinCE has no pipes */
typedef long off_t;
#define errno ((int)(GetLastError()))
#define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
#endif /* _WIN32_WCE */
#define MAKEUQUAD(lo, hi) \
((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
#define RATE_DIFF (10000000) /* 100 nsecs */
#define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
#define SYS2UNIX_TIME(lo, hi) \
((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
/* Visual Studio 6 does not know __func__ or __FUNCTION__
* The rest of MS compilers use __FUNCTION__, not C99 __func__
* Also use _strtoui64 on modern M$ compilers */
#if defined(_MSC_VER)
#if (_MSC_VER < 1300)
#define STRX(x) #x
#define STR(x) STRX(x)
#define __func__ __FILE__ ":" STR(__LINE__)
#define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
#define strtoll(x, y, z) (_atoi64(x))
#else
#define __func__ __FUNCTION__
#define strtoull(x, y, z) (_strtoui64(x, y, z))
#define strtoll(x, y, z) (_strtoi64(x, y, z))
#endif
#endif /* _MSC_VER */
#define ERRNO ((int)(GetLastError()))
#define NO_SOCKLEN_T
#define SSL_LIB "ssleay32.dll"
#define CRYPTO_LIB "libeay32.dll"
#define O_NONBLOCK (0)
#ifndef W_OK
#define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
#endif
#if !defined(EWOULDBLOCK)
#define EWOULDBLOCK WSAEWOULDBLOCK
#endif /* !EWOULDBLOCK */
#define _POSIX_
#define INT64_FMT "I64d"
#define UINT64_FMT "I64u"
#define WINCDECL __cdecl
#define SHUT_RD (0)
#define SHUT_WR (1)
#define SHUT_BOTH (2)
#define vsnprintf_impl _vsnprintf
#define access _access
#define mg_sleep(x) (Sleep(x))
#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
#ifndef popen
#define popen(x, y) (_popen(x, y))
#endif
#ifndef pclose
#define pclose(x) (_pclose(x))
#endif
#define close(x) (_close(x))
#define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
#define RTLD_LAZY (0)
#define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
#define fdopen(x, y) (_fdopen((x), (y)))
#define write(x, y, z) (_write((x), (y), (unsigned)z))
#define read(x, y, z) (_read((x), (y), (unsigned)z))
#define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
#define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
#define sleep(x) (Sleep((x)*1000))
#define rmdir(x) (_rmdir(x))
#define timegm(x) (_mkgmtime(x))
#if !defined(fileno)
#define fileno(x) (_fileno(x))
#endif /* !fileno MINGW #defines fileno */
typedef HANDLE pthread_mutex_t;
typedef DWORD pthread_key_t;
typedef HANDLE pthread_t;
typedef struct {
CRITICAL_SECTION threadIdSec;
int waitingthreadcount; /* The number of threads queued. */
pthread_t *waitingthreadhdls; /* The thread handles. */
} pthread_cond_t;
#ifndef __clockid_t_defined
typedef DWORD clockid_t;
#endif
#ifndef CLOCK_MONOTONIC
#define CLOCK_MONOTONIC (1)
#endif
#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME (2)
#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1900)
#define _TIMESPEC_DEFINED
#endif
#ifndef _TIMESPEC_DEFINED
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
#endif
#define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
static int pthread_mutex_lock(pthread_mutex_t *);
static int pthread_mutex_unlock(pthread_mutex_t *);
static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
struct file;
static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
#if defined(HAVE_STDINT)
#include <stdint.h>
#else
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned __int64 uint64_t;
typedef __int64 int64_t;
#define INT64_MAX (9223372036854775807)
#endif /* HAVE_STDINT */
/* POSIX dirent interface */
struct dirent {
char d_name[PATH_MAX];
};
typedef struct DIR {
HANDLE handle;
WIN32_FIND_DATAW info;
struct dirent result;
} DIR;
#if defined(_WIN32) && !defined(POLLIN)
#ifndef HAVE_POLL
struct pollfd {
SOCKET fd;
short events;
short revents;
};
#define POLLIN (0x0300)
#endif
#endif
/* Mark required libraries */
#if defined(_MSC_VER)
#pragma comment(lib, "Ws2_32.lib")
#endif
#else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
block */
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/utsname.h>
#include <stdint.h>
#include <inttypes.h>
#include <netdb.h>
#include <netinet/tcp.h>
typedef const void *SOCK_OPT_TYPE;
#if defined(ANDROID)
typedef unsigned short int in_port_t;
#endif
#include <pwd.h>
#include <unistd.h>
#include <grp.h>
#include <dirent.h>
#define vsnprintf_impl vsnprintf
#if !defined(NO_SSL_DL) && !defined(NO_SSL)
#include <dlfcn.h>
#endif
#include <pthread.h>
#if defined(__MACH__)
#define SSL_LIB "libssl.dylib"
#define CRYPTO_LIB "libcrypto.dylib"
#else
#if !defined(SSL_LIB)
#define SSL_LIB "libssl.so"
#endif
#if !defined(CRYPTO_LIB)
#define CRYPTO_LIB "libcrypto.so"
#endif
#endif
#ifndef O_BINARY
#define O_BINARY (0)
#endif /* O_BINARY */
#define closesocket(a) (close(a))
#define mg_mkdir(x, y) (mkdir(x, y))
#define mg_remove(x) (remove(x))
#define mg_sleep(x) (usleep((x)*1000))
#define ERRNO (errno)
#define INVALID_SOCKET (-1)
#define INT64_FMT PRId64
#define UINT64_FMT PRIu64
typedef int SOCKET;
#define WINCDECL
#if defined(__hpux)
/* HPUX 11 does not have monotonic, fall back to realtime */
#ifndef CLOCK_MONOTONIC
#define CLOCK_MONOTONIC CLOCK_REALTIME
#endif
/* HPUX defines socklen_t incorrectly as size_t which is 64bit on
* Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
* the prototypes use int* rather than socklen_t* which matches the
* actual library expectation. When called with the wrong size arg
* accept() returns a zero client inet addr and check_acl() always
* fails. Since socklen_t is widely used below, just force replace
* their typedef with int. - DTL
*/
#define socklen_t int
#endif /* hpux */
#endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
block */
/* va_copy should always be a macro, C99 and C++11 - DTL */
#ifndef va_copy
#define va_copy(x, y) ((x) = (y))
#endif
#ifdef _WIN32
/* Create substitutes for POSIX functions in Win32. */
#if defined(__MINGW32__)
/* Show no warning in case system functions are not used. */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
static CRITICAL_SECTION global_log_file_lock;
static DWORD
pthread_self(void)
{
return GetCurrentThreadId();
}
static int
pthread_key_create(
pthread_key_t *key,
void(*_ignored)(void *) /* destructor not supported for Windows */
)
{
(void)_ignored;
if ((key != 0)) {
*key = TlsAlloc();
return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
}
return -2;
}
static int
pthread_key_delete(pthread_key_t key)
{
return TlsFree(key) ? 0 : 1;
}
static int
pthread_setspecific(pthread_key_t key, void *value)
{
return TlsSetValue(key, value) ? 0 : 1;
}
static void *
pthread_getspecific(pthread_key_t key)
{
return TlsGetValue(key);
}
#if defined(__MINGW32__)
/* Enable unused function warning again */
#pragma GCC diagnostic pop
#endif
static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
#else
static pthread_mutexattr_t pthread_mutex_attr;
#endif /* _WIN32 */
#include "civetweb.h"
#define PASSWORDS_FILE_NAME ".htpasswd"
#define CGI_ENVIRONMENT_SIZE (4096)
#define MAX_CGI_ENVIR_VARS (256)
#define MG_BUF_LEN (8192)
#ifndef MAX_REQUEST_SIZE
#define MAX_REQUEST_SIZE (16384)
#endif
mg_static_assert(MAX_REQUEST_SIZE >= 256,
"request size length must be a positive number");
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
#if !defined(DEBUG_TRACE)
#if defined(DEBUG)
static void DEBUG_TRACE_FUNC(const char *func,
unsigned line,
PRINTF_FORMAT_STRING(const char *fmt),
...) PRINTF_ARGS(3, 4);
static void
DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
{
va_list args;
flockfile(stdout);
printf("*** %lu.%p.%s.%u: ",
(unsigned long)time(NULL),
(void *)pthread_self(),
func,
line);
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
putchar('\n');
fflush(stdout);
funlockfile(stdout);
}
#define DEBUG_TRACE(fmt, ...) \
DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
#else
#define DEBUG_TRACE(fmt, ...) \
do { \
} while (0)
#endif /* DEBUG */
#endif /* DEBUG_TRACE */
#if defined(MEMORY_DEBUGGING)
unsigned long mg_memory_debug_blockCount = 0;
unsigned long mg_memory_debug_totalMemUsed = 0;
static void *
mg_malloc_ex(size_t size, const char *file, unsigned line)
{
void *data = malloc(size + sizeof(size_t));
void *memory = 0;
char mallocStr[256];
if (data) {
*(size_t *)data = size;
mg_memory_debug_totalMemUsed += size;
mg_memory_debug_blockCount++;
memory = (void *)(((char *)data) + sizeof(size_t));
}
sprintf(mallocStr,
"MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
memory,
(unsigned long)size,
mg_memory_debug_totalMemUsed,
mg_memory_debug_blockCount,
file,
line);
#if defined(_WIN32)
OutputDebugStringA(mallocStr);
#else
DEBUG_TRACE("%s", mallocStr);
#endif
return memory;
}
static void *
mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
{
void *data = mg_malloc_ex(size * count, file, line);
if (data) {
memset(data, 0, size);
}
return data;
}
static void
mg_free_ex(void *memory, const char *file, unsigned line)
{
char mallocStr[256];
void *data = (void *)(((char *)memory) - sizeof(size_t));
size_t size;
if (memory) {
size = *(size_t *)data;
mg_memory_debug_totalMemUsed -= size;
mg_memory_debug_blockCount--;
sprintf(mallocStr,
"MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
memory,
(unsigned long)size,
mg_memory_debug_totalMemUsed,
mg_memory_debug_blockCount,
file,
line);
#if defined(_WIN32)
OutputDebugStringA(mallocStr);
#else
DEBUG_TRACE("%s", mallocStr);
#endif
free(data);
}
}
static void *
mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
{
char mallocStr[256];
void *data;
void *_realloc;
size_t oldsize;
if (newsize) {
if (memory) {
data = (void *)(((char *)memory) - sizeof(size_t));
oldsize = *(size_t *)data;
_realloc = realloc(data, newsize + sizeof(size_t));
if (_realloc) {
data = _realloc;
mg_memory_debug_totalMemUsed -= oldsize;
sprintf(mallocStr,
"MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
memory,
(unsigned long)oldsize,
mg_memory_debug_totalMemUsed,
mg_memory_debug_blockCount,
file,
line);
#if defined(_WIN32)
OutputDebugStringA(mallocStr);
#else
DEBUG_TRACE("%s", mallocStr);
#endif
mg_memory_debug_totalMemUsed += newsize;
sprintf(mallocStr,
"MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
memory,
(unsigned long)newsize,
mg_memory_debug_totalMemUsed,
mg_memory_debug_blockCount,
file,
line);
#if defined(_WIN32)
OutputDebugStringA(mallocStr);
#else
DEBUG_TRACE("%s", mallocStr);
#endif
*(size_t *)data = newsize;
data = (void *)(((char *)data) + sizeof(size_t));
}
else {
#if defined(_WIN32)
OutputDebugStringA("MEM: realloc failed\n");
#else
DEBUG_TRACE("%s", "MEM: realloc failed\n");
#endif
return _realloc;
}
}
else {
data = mg_malloc_ex(newsize, file, line);
}
}
else {
data = 0;
mg_free_ex(memory, file, line);
}
return data;
}
#define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
#define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
#define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
#define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
#else
static __inline void *
mg_malloc(size_t a)
{
return malloc(a);
}
static __inline void *
mg_calloc(size_t a, size_t b)
{
return calloc(a, b);
}
static __inline void *
mg_realloc(void *a, size_t b)
{
return realloc(a, b);
}
static __inline void
mg_free(void *a)
{
free(a);
}
#endif
static void mg_vsnprintf(const struct mg_connection *conn,
int *truncated,
char *buf,
size_t buflen,
const char *fmt,
va_list ap);
static void mg_snprintf(const struct mg_connection *conn,
int *truncated,
char *buf,
size_t buflen,
PRINTF_FORMAT_STRING(const char *fmt),
...) PRINTF_ARGS(5, 6);
/* This following lines are just meant as a reminder to use the mg-functions
* for memory management */
#ifdef malloc
#undef malloc
#endif
#ifdef calloc
#undef calloc
#endif
#ifdef realloc
#undef realloc
#endif
#ifdef free
#undef free
#endif
#ifdef snprintf
#undef snprintf
#endif
#ifdef vsnprintf
#undef vsnprintf
#endif
/*#define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
#define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
#define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
#define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
#define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf*/
#ifdef _WIN32 /* vsnprintf must not be used in any system, * \
* but this define only works well for Windows. */
/*#define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf*/
#endif
#define MD5_STATIC static
#include "utils/md5.h"
/* Darwin prior to 7.0 and Win32 do not have socklen_t */
#ifdef NO_SOCKLEN_T
typedef int socklen_t;
#endif /* NO_SOCKLEN_T */
#define _DARWIN_UNLIMITED_SELECT
#define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL (0)
#endif
#if !defined(SOMAXCONN)
#define SOMAXCONN (100)
#endif
/* Size of the accepted socket queue */
#if !defined(MGSQLEN)
#define MGSQLEN (20)
#endif
#if defined(NO_SSL_DL)
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#else
/* SSL loaded dynamically from DLL.
* I put the prototypes here to be independent from OpenSSL source
* installation. */
typedef struct ssl_st SSL;
typedef struct ssl_method_st SSL_METHOD;
typedef struct ssl_ctx_st SSL_CTX;
typedef struct x509_store_ctx_st X509_STORE_CTX;
#define SSL_CTRL_OPTIONS (32)
#define SSL_CTRL_CLEAR_OPTIONS (77)
#define SSL_CTRL_SET_ECDH_AUTO (94)
#define SSL_VERIFY_NONE (0)
#define SSL_VERIFY_PEER (1)
#define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
#define SSL_VERIFY_CLIENT_ONCE (4)
#define SSL_OP_ALL (0x80000BFFL)
#define SSL_OP_NO_SSLv2 (0x01000000L)
#define SSL_OP_NO_SSLv3 (0x02000000L)
#define SSL_OP_NO_TLSv1 (0x04000000L)
#define SSL_OP_NO_TLSv1_2 (0x08000000L)
#define SSL_OP_NO_TLSv1_1 (0x10000000L)
#define SSL_OP_SINGLE_DH_USE (0x00100000L)
struct ssl_func {
const char *name; /* SSL function name */
void(*ptr)(void); /* Function pointer */
};
#define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
#define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
#define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
#define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
#define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
#define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
#define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
#define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
#define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
#define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
#define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
#define SSL_CTX_use_PrivateKey_file \
(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
#define SSL_CTX_use_certificate_file \
(*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
#define SSL_CTX_set_default_passwd_cb \
(*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
#define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
#define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
#define SSL_CTX_use_certificate_chain_file \
(*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
#define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
#define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
#define SSL_CTX_set_verify \
(*(void (*)(SSL_CTX *, \
int, \
int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
#define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
#define SSL_CTX_load_verify_locations \
(*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
#define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
#define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
#define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
#define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
#define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
#define SSL_CIPHER_get_name \
(*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
#define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
#define SSL_CTX_set_session_id_context \
(*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
#define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
#define SSL_CTX_set_cipher_list \
(*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
#define SSL_CTX_set_options(ctx, op) \
SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
#define SSL_CTX_clear_options(ctx, op) \
SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
#define SSL_CTX_set_ecdh_auto(ctx, onoff) \
SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
#define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
#define CRYPTO_set_locking_callback \
(*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
#define CRYPTO_set_id_callback \
(*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
#define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
#define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
#define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
#define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
#define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
#define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
#define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
#define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
/* set_ssl_option() function updates this array.
* It loads SSL library dynamically and changes NULLs to the actual addresses
* of respective functions. The macros above (like SSL_connect()) are really
* just calling these functions indirectly via the pointer. */
static struct ssl_func ssl_sw[] = { { "SSL_free", NULL },
{ "SSL_accept", NULL },
{ "SSL_connect", NULL },
{ "SSL_read", NULL },
{ "SSL_write", NULL },
{ "SSL_get_error", NULL },
{ "SSL_set_fd", NULL },
{ "SSL_new", NULL },
{ "SSL_CTX_new", NULL },
{ "SSLv23_server_method", NULL },
{ "SSL_library_init", NULL },
{ "SSL_CTX_use_PrivateKey_file", NULL },
{ "SSL_CTX_use_certificate_file", NULL },
{ "SSL_CTX_set_default_passwd_cb", NULL },
{ "SSL_CTX_free", NULL },
{ "SSL_load_error_strings", NULL },
{ "SSL_CTX_use_certificate_chain_file", NULL },
{ "SSLv23_client_method", NULL },
{ "SSL_pending", NULL },
{ "SSL_CTX_set_verify", NULL },
{ "SSL_shutdown", NULL },
{ "SSL_CTX_load_verify_locations", NULL },
{ "SSL_CTX_set_default_verify_paths", NULL },
{ "SSL_CTX_set_verify_depth", NULL },
{ "SSL_get_peer_certificate", NULL },
{ "SSL_get_version", NULL },
{ "SSL_get_current_cipher", NULL },
{ "SSL_CIPHER_get_name", NULL },
{ "SSL_CTX_check_private_key", NULL },
{ "SSL_CTX_set_session_id_context", NULL },
{ "SSL_CTX_ctrl", NULL },
{ "SSL_CTX_set_cipher_list", NULL },
{ NULL, NULL } };
/* Similar array as ssl_sw. These functions could be located in different
* lib. */
#if !defined(NO_SSL)
static struct ssl_func crypto_sw[] = { { "CRYPTO_num_locks", NULL },
{ "CRYPTO_set_locking_callback", NULL },
{ "CRYPTO_set_id_callback", NULL },
{ "ERR_get_error", NULL },
{ "ERR_error_string", NULL },
{ "ERR_remove_state", NULL },
{ "ERR_free_strings", NULL },
{ "ENGINE_cleanup", NULL },
{ "CONF_modules_unload", NULL },
{ "CRYPTO_cleanup_all_ex_data", NULL },
{ "EVP_cleanup", NULL },
{ NULL, NULL } };
#endif /* NO_SSL */
#endif /* NO_SSL_DL */
static const char *month_names[] = { "Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",