/
civetweb.c
20722 lines (17984 loc) · 557 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-2020 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(__GNUC__) || defined(__MINGW32__)
#define GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION >= 40500
/* gcc diagnostic pragmas available */
//#define GCC_DIAGNOSTIC
#endif
#endif
#if defined(GCC_DIAGNOSTIC)
/* Disable unused macros warnings - not all defines are required
* for all systems and all compilers. */
# pragma GCC diagnostic ignored "-Wunused-macros"
/* A padding warning is just plain useless */
# pragma GCC diagnostic ignored "-Wpadded"
#endif
#if defined(__clang__) /* GCC does not (yet) support this pragma */
/* We must set some flags for the headers we include. These flags
* are reserved ids according to C99, so we need to disable a
* warning for that. */
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wreserved-id-macro"
#endif
#if defined(_WIN32)
#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
#endif
#if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
#define _WIN32_WINNT 0x0501
#endif
#else
#if !defined(_GNU_SOURCE)
#define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
#endif
#if defined(__linux__) && !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
#endif
#if defined(__LSB_VERSION__) || defined(__sun)
#define NEED_TIMEGM
#define NO_THREAD_NAME
#endif
#if !defined(_LARGEFILE_SOURCE)
#define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
#endif
#if !defined(_FILE_OFFSET_BITS)
#define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
#endif
#if !defined(__STDC_FORMAT_MACROS)
#define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
#endif
#if !defined(__STDC_LIMIT_MACROS)
#define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
#endif
#if !defined(_DARWIN_UNLIMITED_SELECT)
#define _DARWIN_UNLIMITED_SELECT
#endif
#if defined(__sun)
#define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
#define __inline inline /* not recognized on older compiler versions */
#endif
#endif
#if defined(__clang__)
/* Enable reserved-id-macro warning again. */
# pragma GCC diagnostic pop
#endif
#if defined(USE_LUA)
#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(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
#define mg_static_assert _Static_assert
#elif defined(__cplusplus) && __cplusplus >= 201103L
#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");
/* Select queue implementation. Diagnosis features originally only implemented
* for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
* implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
* "CONNECTION_QUEUE_SIZE" is only available for the previous queue
* implementation, since the queue length is independent from the number of
* worker threads there, while the new queue is one element per worker thread.
*
*/
#if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
/* The queues are exclusive or - only one can be used. */
#error \
"Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
#endif
#if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
/* Use a default implementation */
#define NO_ALTERNATIVE_QUEUE
#endif
#if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
/* File system access:
* NO_FILES = do not serve any files from the file system automatically.
* However, with NO_FILES CivetWeb may still write log files, read access
* control files, default error page files or use API functions like
* mg_send_file in callbacks to send files from the server local
* file system.
* NO_FILES only disables the automatic mapping between URLs and local
* file names.
* NO_FILESYSTEM = do not access any file at all. Useful for embedded
* devices without file system. Logging to files in not available
* (use callbacks instead) and API functions like mg_send_file are not
* available.
* If NO_FILESYSTEM is set, NO_FILES must be set as well.
*/
#error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
#endif
/* DTL -- including winsock2.h works better if lean and mean */
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#if defined(__SYMBIAN32__)
/* According to https://en.wikipedia.org/wiki/Symbian#History,
* Symbian is no longer maintained since 2014-01-01.
* Support for Symbian has been removed from CivetWeb
*/
#error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
#endif /* __SYMBIAN32__ */
#if defined(__ZEPHYR__)
#include <time.h>
#include <ctype.h>
#include <net/socket.h>
#include <posix/pthread.h>
#include <posix/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zephyr.h>
#include <fcntl.h>
#include <libc_extensions.h>
/* Max worker threads is the max of pthreads minus the main application thread
* and minus the main civetweb thread, thus -2
*/
#define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
#define ZEPHYR_STACK_SIZE USE_STACK_SIZE
#else
#define ZEPHYR_STACK_SIZE 8096
#endif
K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
MAX_WORKER_THREADS,
ZEPHYR_STACK_SIZE);
static int zephyr_worker_stack_index;
#endif
#if !defined(CIVETWEB_HEADER_INCLUDED)
/* Include the header file here, so the CivetWeb interface is defined for the
* entire implementation, including the following forward definitions. */
#include "civetweb.h"
#endif
#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);
#define DEBUG_TRACE(fmt, ...) \
DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
#define NEED_DEBUG_TRACE_FUNC
#ifndef DEBUG_TRACE_STREAM
# define DEBUG_TRACE_STREAM stdout
#endif
#else
#define DEBUG_TRACE(fmt, ...) \
do { \
} while (0)
#endif /* DEBUG */
#endif /* DEBUG_TRACE */
#if !defined(DEBUG_ASSERT)
#if defined(DEBUG)
#define DEBUG_ASSERT(cond) \
do { \
if (!(cond)) { \
DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
exit(2); /* Exit with error */ \
} \
} while (0)
#else
#define DEBUG_ASSERT(cond)
#endif /* DEBUG */
#endif
#if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
void __cyg_profile_func_enter(void *this_fn, void *call_site)
__attribute__((no_instrument_function));
void __cyg_profile_func_exit(void *this_fn, void *call_site)
__attribute__((no_instrument_function));
void
__cyg_profile_func_enter(void *this_fn, void *call_site)
{
if ((void *)this_fn != (void *)printf) {
printf("E %p %p\n", this_fn, call_site);
}
}
void
__cyg_profile_func_exit(void *this_fn, void *call_site)
{
if ((void *)this_fn != (void *)printf) {
printf("X %p %p\n", this_fn, call_site);
}
}
#endif
#if !defined(IGNORE_UNUSED_RESULT)
#define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
#endif
#if defined(__GNUC__) || defined(__MINGW32__)
/* GCC unused function attribute seems fundamentally broken.
* Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
* OR UNUSED" for individual functions failed.
* Either the compiler creates an "unused-function" warning if a
* function is not marked with __attribute__((unused)).
* On the other hand, if the function is marked with this attribute,
* but is used, the compiler raises a completely idiotic
* "used-but-marked-unused" warning - and
* # pragma GCC diagnostic ignored "-Wused-but-marked-unused"
* raises error: unknown option after "# pragma GCC diagnostic".
* Disable this warning completely, until the GCC guys sober up
* again.
*/
# pragma GCC diagnostic ignored "-Wunused-function"
#define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
#else
#define FUNCTION_MAY_BE_UNUSED
#endif
/* Some ANSI #includes are not available on Windows CE */
#if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif /* !_WIN32_WCE */
#if defined(__clang__)
/* When using -Weverything, clang does not accept it's own headers
* in a release build configuration. Disable what is too much in
* -Weverything. */
# pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
#endif
#if defined(__GNUC__) || defined(__MINGW32__)
/* Who on earth came to the conclusion, using __DATE__ should rise
* an "expansion of date or time macro is not reproducible"
* warning. That's exactly what was intended by using this macro.
* Just disable this nonsense warning. */
/* And disabling them does not work either:
* # pragma clang diagnostic ignored "-Wno-error=date-time"
* # pragma clang diagnostic ignored "-Wdate-time"
* So we just have to disable ALL warnings for some lines
* of code.
* This seems to be a known GCC bug, not resolved since 2012:
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
*/
#endif
#if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
#if defined(__clang__)
#if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
/* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
# pragma clang diagnostic ignored "-Wno-reserved-id-macro"
# pragma clang diagnostic ignored "-Wno-keyword-macro"
#endif
#endif
#define CLOCK_MONOTONIC (1)
#define CLOCK_REALTIME (2)
#include <mach/clock.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/errno.h>
#include <sys/time.h>
/* clock_gettime is not implemented on OSX prior to 10.12 */
static int
_civet_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);
DEBUG_ASSERT(mach_status == KERN_SUCCESS);
/* appease "unused variable" warning for release builds */
(void)mach_status;
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 */
}
/* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
#if defined(__CLOCK_AVAILABILITY)
/* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
* declared but it may be NULL at runtime. So we need to check before using
* it. */
static int
_civet_safe_clock_gettime(int clk_id, struct timespec *t)
{
if (clock_gettime) {
return clock_gettime(clk_id, t);
}
return _civet_clock_gettime(clk_id, t);
}
#define clock_gettime _civet_safe_clock_gettime
#else
#define clock_gettime _civet_clock_gettime
#endif
#endif
/********************************************************************/
/* CivetWeb configuration defines */
/********************************************************************/
/* Maximum number of threads that can be configured.
* The number of threads actually created depends on the "num_threads"
* configuration parameter, but this is the upper limit. */
#if !defined(MAX_WORKER_THREADS)
#define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
#endif
/* Timeout interval for select/poll calls.
* The timeouts depend on "*_timeout_ms" configuration values, but long
* timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
* This reduces the time required to stop the server. */
#if !defined(SOCKET_TIMEOUT_QUANTUM)
#define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
#endif
/* Do not try to compress files smaller than this limit. */
#if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
#define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
#endif
#if !defined(PASSWORDS_FILE_NAME)
#define PASSWORDS_FILE_NAME ".htpasswd"
#endif
/* Initial buffer size for all CGI environment variables. In case there is
* not enough space, another block is allocated. */
#if !defined(CGI_ENVIRONMENT_SIZE)
#define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
#endif
/* Maximum number of environment variables. */
#if !defined(MAX_CGI_ENVIR_VARS)
#define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
#endif
/* General purpose buffer size. */
#if !defined(MG_BUF_LEN) /* in bytes */
#define MG_BUF_LEN (1024 * 8)
#endif
/********************************************************************/
/* Helper makros */
#if !defined(ARRAY_SIZE)
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
#endif
#include <stdint.h>
/* Standard defines */
#if !defined(INT64_MAX)
#define INT64_MAX (9223372036854775807)
#endif
#define SHUTDOWN_RD (0)
#define SHUTDOWN_WR (1)
#define SHUTDOWN_BOTH (2)
mg_static_assert(MAX_WORKER_THREADS >= 1,
"worker threads must be a positive number");
mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
"size_t data type size check");
#if defined(_WIN32) /* WINDOWS include block */
#include <malloc.h> /* *alloc( */
#include <stdlib.h> /* *alloc( */
#include <time.h> /* struct timespec */
#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 W_PATH_MAX (MAX_PATH)
/* at most three UTF-8 chars per wchar_t */
#define PATH_MAX (W_PATH_MAX * 3)
#else
#define W_PATH_MAX ((PATH_MAX + 2) / 3)
#endif
mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
#if !defined(_IN_PORT_T)
#if !defined(in_port_t)
#define in_port_t u_short
#endif
#endif
#if !defined(_WIN32_WCE)
#include <direct.h>
#include <io.h>
#include <process.h>
#else /* _WIN32_WCE */
#define NO_CGI /* WinCE has no pipes */
#define NO_POPEN /* WinCE has no popen */
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
#if defined(_WIN64) || defined(__MINGW64__)
#if !defined(SSL_LIB)
#if defined(OPENSSL_API_1_1)
#define SSL_LIB "libssl-1_1-x64.dll"
#else /* OPENSSL_API_1_1 */
#define SSL_LIB "ssleay64.dll"
#endif /* OPENSSL_API_1_1 */
#endif /* SSL_LIB */
#if !defined(CRYPTO_LIB)
#if defined(OPENSSL_API_1_1)
#define CRYPTO_LIB "libcrypto-1_1-x64.dll"
#else /* OPENSSL_API_1_1 */
#define CRYPTO_LIB "libeay64.dll"
#endif /* OPENSSL_API_1_1 */
#endif /* CRYPTO_LIB */
#else /* defined(_WIN64) || defined(__MINGW64__) */
#if !defined(SSL_LIB)
#define SSL_LIB "ssleay32.dll"
#endif /* SSL_LIB */
#if !defined(CRYPTO_LIB)
#define CRYPTO_LIB "libeay32.dll"
#endif /* CRYPTO_LIB */
#endif /* defined(_WIN64) || defined(__MINGW64__) */
#define O_NONBLOCK (0)
#if !defined(W_OK)
#define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
#endif
#define _POSIX_
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#define INT64_FMT PRId64
#define UINT64_FMT PRIu64
#define WINCDECL __cdecl
#define vsnprintf_impl _vsnprintf
#define access _access
#define mg_sleep(x) (Sleep(x))
#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
#if !defined(popen)
#define popen(x, y) (_popen(x, y))
#endif
#if !defined(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) ((void)pthread_mutex_lock(&global_log_file_lock))
#define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
#define sleep(x) (Sleep((x)*1000))
#define rmdir(x) (_rmdir(x))
#if defined(_WIN64) || !defined(__MINGW32__)
/* Only MinGW 32 bit is missing this function */
#define timegm(x) (_mkgmtime(x))
#else
time_t timegm(struct tm *tm);
#define NEED_TIMEGM
#endif
#if !defined(fileno)
#define fileno(x) (_fileno(x))
#endif /* !fileno MINGW #defines fileno */
typedef struct {
CRITICAL_SECTION sec; /* Immovable */
} pthread_mutex_t;
typedef DWORD pthread_key_t;
typedef HANDLE pthread_t;
typedef struct {
pthread_mutex_t threadIdSec;
struct mg_workerTLS *waiting_thread; /* The chain of threads */
} pthread_cond_t;
#if !defined(__clockid_t_defined)
typedef DWORD clockid_t;
#endif
#if !defined(CLOCK_MONOTONIC)
#define CLOCK_MONOTONIC (1)
#endif
#if !defined(CLOCK_REALTIME)
#define CLOCK_REALTIME (2)
#endif
#if !defined(CLOCK_THREAD)
#define CLOCK_THREAD (3)
#endif
#if !defined(CLOCK_PROCESS)
#define CLOCK_PROCESS (4)
#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1900)
#define _TIMESPEC_DEFINED
#endif
#if !defined(_TIMESPEC_DEFINED)
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
#endif
#if !defined(WIN_PTHREADS_TIME_H)
#define MUST_IMPLEMENT_CLOCK_GETTIME
#endif
#if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
#define clock_gettime mg_clock_gettime
static int
clock_gettime(clockid_t clk_id, struct timespec *tp)
{
FILETIME ft;
ULARGE_INTEGER li, li2;
BOOL ok = FALSE;
double d;
static double perfcnt_per_sec = 0.0;
static BOOL initialized = FALSE;
if (!initialized) {
QueryPerformanceFrequency((LARGE_INTEGER *)&li);
perfcnt_per_sec = 1.0 / li.QuadPart;
initialized = TRUE;
}
if (tp) {
memset(tp, 0, sizeof(*tp));
if (clk_id == CLOCK_REALTIME) {
/* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
tp->tv_sec = (time_t)(li.QuadPart / 10000000);
tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
ok = TRUE;
/* END: CLOCK_REALTIME */
} else if (clk_id == CLOCK_MONOTONIC) {
/* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
QueryPerformanceCounter((LARGE_INTEGER *)&li);
d = li.QuadPart * perfcnt_per_sec;
tp->tv_sec = (time_t)d;
d -= (double)tp->tv_sec;
tp->tv_nsec = (long)(d * 1.0E9);
ok = TRUE;
/* END: CLOCK_MONOTONIC */
} else if (clk_id == CLOCK_THREAD) {
/* BEGIN: CLOCK_THREAD = CPU usage of thread */
FILETIME t_create, t_exit, t_kernel, t_user;
if (GetThreadTimes(GetCurrentThread(),
&t_create,
&t_exit,
&t_kernel,
&t_user)) {
li.LowPart = t_user.dwLowDateTime;
li.HighPart = t_user.dwHighDateTime;
li2.LowPart = t_kernel.dwLowDateTime;
li2.HighPart = t_kernel.dwHighDateTime;
li.QuadPart += li2.QuadPart;
tp->tv_sec = (time_t)(li.QuadPart / 10000000);
tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
ok = TRUE;
}
/* END: CLOCK_THREAD */
} else if (clk_id == CLOCK_PROCESS) {
/* BEGIN: CLOCK_PROCESS = CPU usage of process */
FILETIME t_create, t_exit, t_kernel, t_user;
if (GetProcessTimes(GetCurrentProcess(),
&t_create,
&t_exit,
&t_kernel,
&t_user)) {
li.LowPart = t_user.dwLowDateTime;
li.HighPart = t_user.dwHighDateTime;
li2.LowPart = t_kernel.dwLowDateTime;
li2.HighPart = t_kernel.dwHighDateTime;
li.QuadPart += li2.QuadPart;
tp->tv_sec = (time_t)(li.QuadPart / 10000000);
tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
ok = TRUE;
}
/* END: CLOCK_PROCESS */
} else {
/* BEGIN: unknown clock */
/* ok = FALSE; already set by init */
/* END: unknown clock */
}
}
return ok ? 0 : -1;
}
#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 path_to_unicode(const struct mg_connection *conn,
const char *path,
wchar_t *wbuf,
size_t wbuf_len);
/* All file operations need to be rewritten to solve #246. */
struct mg_file;
static const char *
mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
/* 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(HAVE_POLL)
#define mg_pollfd pollfd
#else
struct mg_pollfd {
SOCKET fd;
short events;
short revents;
};
#endif
/* Mark required libraries */
#if defined(_MSC_VER)
# pragma comment(lib, "Ws2_32.lib")
#endif
#else /* defined(_WIN32) - WINDOWS vs UNIX include block */
#include <inttypes.h>
typedef const void *SOCK_OPT_TYPE;
#if defined(ANDROID)
typedef unsigned short int in_port_t;
#endif
#if !defined(__ZEPHYR__)
#include <arpa/inet.h>
#include <ctype.h>
#include <dirent.h>
#include <grp.h>
#include <limits.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <pwd.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/poll.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#endif
#define vsnprintf_impl vsnprintf
#if !defined(NO_SSL_DL) && !defined(NO_SSL)
#include <dlfcn.h>
#endif
#if defined(__MACH__) && defined(__APPLE__)
#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
#if !defined(O_BINARY)
#define O_BINARY (0)
#endif /* O_BINARY */
#define closesocket(a) (close(a))
#define mg_mkdir(conn, path, mode) (mkdir(path, mode))
#define mg_remove(conn, x) (remove(x))
#define mg_sleep(x) (usleep((x)*1000))
#define mg_opendir(conn, x) (opendir(x))
#define mg_closedir(x) (closedir(x))
#define mg_readdir(x) (readdir(x))
#define ERRNO (errno)
#define INVALID_SOCKET (-1)
#define INT64_FMT PRId64
#define UINT64_FMT PRIu64
#define INT64_SFMT SCNd64
#define UINT64_SFMT SCNu64
typedef int SOCKET;
#define WINCDECL
#if defined(__hpux)
/* HPUX 11 does not have monotonic, fall back to realtime */
#if !defined(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 */
#define mg_pollfd pollfd
#endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
/* In case our C library is missing "timegm", provide an implementation */
#if defined(NEED_TIMEGM)
static inline int
is_leap(int y)
{
return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
}
static inline int
count_leap(int y)
{
return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
}
time_t
timegm(struct tm *tm)
{
static const unsigned short ydays[] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
int year = tm->tm_year + 1900;
int mon = tm->tm_mon;
int mday = tm->tm_mday - 1;
int hour = tm->tm_hour;
int min = tm->tm_min;
int sec = tm->tm_sec;
if (year < 1970 || mon < 0 || mon > 11 || mday < 0
|| (mday >= ydays[mon + 1] - ydays[mon]
+ (mon == 1 && is_leap(year) ? 1 : 0))
|| hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
return -1;
time_t res = year - 1970;
res *= 365;
res += mday;
res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
res += count_leap(year);
res *= 24;
res += hour;
res *= 60;
res += min;
res *= 60;
res += sec;
return res;
}
#endif /* NEED_TIMEGM */
/* va_copy should always be a macro, C99 and C++11 - DTL */
#if !defined(va_copy)
#define va_copy(x, y) ((x) = (y))
#endif
#if defined(_WIN32)
/* Create substitutes for POSIX functions in Win32. */
#if defined(GCC_DIAGNOSTIC)
/* Show no warning in case system functions are not used. */
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
static pthread_mutex_t global_log_file_lock;
FUNCTION_MAY_BE_UNUSED
static DWORD
pthread_self(void)
{
return GetCurrentThreadId();
}
FUNCTION_MAY_BE_UNUSED
static int
pthread_key_create(
pthread_key_t *key,
void (*_ignored)(void *) /* destructor not supported for Windows */
)
{
(void)_ignored;
if ((key != 0)) {