-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcivetweb.c
6463 lines (5624 loc) · 206 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) 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
#else
#ifdef __linux__
#define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
#endif
#define _LARGEFILE_SOURCE /* Enable 64-bit file offsets */
#define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
#define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
#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)
#endif
/* Disable WIN32_LEAN_AND_MEAN.
This makes windows.h always include winsock2.h */
#if defined(WIN32_LEAN_AND_MEAN) && (_MSC_VER <= 1400)
#undef WIN32_LEAN_AND_MEAN
#endif
#if defined USE_IPV6 && defined(_WIN32)
#include <ws2tcpip.h>
#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 */
#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>
#define MAX_WORKER_THREADS 1024
#define in_port_t u_short
#if defined(_WIN32) && !defined(__SYMBIAN32__) /* Windows specific */
#if defined(_MSC_VER) && _MSC_VER <= 1400
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0400 /* To make it link in VS2005 */
#endif
#include <windows.h>
#ifndef PATH_MAX
#define PATH_MAX MAX_PATH
#endif
#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 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) && _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 /* _MSC_VER */
#define ERRNO GetLastError()
#define NO_SOCKLEN_T
#define SSL_LIB "ssleay32.dll"
#define CRYPTO_LIB "libeay32.dll"
#define O_NONBLOCK 0
#if !defined(EWOULDBLOCK)
#define EWOULDBLOCK WSAEWOULDBLOCK
#endif /* !EWOULDBLOCK */
#define _POSIX_
#define INT64_FMT "I64d"
#define WINCDECL __cdecl
#define SHUT_WR 1
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#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))
#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)
#if !defined(va_copy)
#define va_copy(x, y) x = y
#endif /* !va_copy MINGW #defines va_copy */
#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;
typedef DWORD clockid_t;
#define CLOCK_MONOTONIC (1)
#define CLOCK_REALTIME (2)
#if _MSC_VER >= 1900
#else
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 int uint32_t;
typedef unsigned short uint16_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(USE_IPV6) && defined(_WIN32)
#ifndef HAVE_POLL
struct pollfd {
SOCKET fd;
short events;
short revents;
};
#define POLLIN 1
#endif
#endif
/* Mark required libraries */
#ifdef _MSC_VER
#pragma comment(lib, "Ws2_32.lib")
#endif
#else /* UNIX specific */
#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 <stdint.h>
#include <inttypes.h>
#include <netdb.h>
#include <pwd.h>
#include <unistd.h>
#include <dirent.h>
#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
typedef int SOCKET;
#define WINCDECL
#endif /* End of Windows and UNIX specific includes */
#include "civetweb.h"
#define PASSWORDS_FILE_NAME ".htpasswd"
#define CGI_ENVIRONMENT_SIZE 4096
#define MAX_CGI_ENVIR_VARS 64
#define MG_BUF_LEN 8192
#ifndef MAX_REQUEST_SIZE
#define MAX_REQUEST_SIZE 16384
#endif
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
#ifdef _WIN32
static CRITICAL_SECTION global_log_file_lock;
static DWORD pthread_self(void)
{
return GetCurrentThreadId();
}
int pthread_key_create(pthread_key_t *key, void (*_must_be_zero)(void*) /* destructor function not supported for windows */)
{
assert(_must_be_zero == NULL);
if ((key!=0) && (_must_be_zero == NULL)) {
*key = TlsAlloc();
return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
}
return -2;
}
int pthread_key_delete(pthread_key_t key)
{
return TlsFree(key) ? 0 : 1;
}
int pthread_setspecific(pthread_key_t key, void * value)
{
return TlsSetValue(key, value) ? 0 : 1;
}
void *pthread_getspecific(pthread_key_t key)
{
return TlsGetValue(key);
}
#endif /* _WIN32 */
#define MD5_STATIC static
#include "md5.inl"
#ifdef DEBUG_TRACE
#undef DEBUG_TRACE
#define DEBUG_TRACE(x)
#else
#if defined(DEBUG)
#define DEBUG_TRACE(x) do { \
flockfile(stdout); \
printf("*** %lu.%p.%s.%d: ", \
(unsigned long) time(NULL), (void *) pthread_self(), \
__func__, __LINE__); \
printf x; \
putchar('\n'); \
fflush(stdout); \
funlockfile(stdout); \
} while (0)
#else
#define DEBUG_TRACE(x)
#endif /* DEBUG */
#endif /* DEBUG_TRACE */
/* 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
#if !defined(PATH_MAX)
#define PATH_MAX 4096
#endif
/* Size of the accepted socket queue */
#if !defined(MGSQLEN)
#define MGSQLEN 20
#endif
static const char *http_500_error = "Internal Server Error";
#if defined(NO_SSL_DL)
#include <openssl/ssl.h>
#include <openssl/err.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;
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)) ssl_sw[19].ptr)
#define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr)
#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)
/* 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},
{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},
{NULL, NULL}
};
#endif /* NO_SSL */
#endif /* NO_SSL_DL */
static const char *month_names[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
/* Unified socket address. For IPv6 support, add IPv6 address structure
in the union u. */
union usa {
struct sockaddr sa;
struct sockaddr_in sin;
#if defined(USE_IPV6)
struct sockaddr_in6 sin6;
#endif
};
/* Describes a string (chunk of memory). */
struct vec {
const char *ptr;
size_t len;
};
struct file {
int is_directory;
time_t modification_time;
int64_t size;
FILE *fp;
const char *membuf; /* Non-NULL if file data is in memory */
/* set to 1 if the content is gzipped
in which case we need a content-encoding: gzip header */
int gzipped;
};
#define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL, 0}
/* Describes listening socket, or socket which was accept()-ed by the master
thread and queued for future handling by the worker thread. */
struct socket {
SOCKET sock; /* Listening socket */
union usa lsa; /* Local socket address */
union usa rsa; /* Remote socket address */
unsigned is_ssl:1; /* Is port SSL-ed */
unsigned ssl_redir:1; /* Is port supposed to redirect everything to SSL
port */
};
/* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
enum {
CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
#if defined(USE_LUA)
LUA_SCRIPT_EXTENSIONS, LUA_SERVER_PAGE_EXTENSIONS,
#endif
#if defined(USE_WEBSOCKET)
WEBSOCKET_ROOT,
#endif
NUM_OPTIONS
};
static const char *config_options[] = {
"cgi_pattern", "**.cgi$|**.pl$|**.php$",
"cgi_environment", NULL,
"put_delete_auth_file", NULL,
"cgi_interpreter", NULL,
"protect_uri", NULL,
"authentication_domain", "mydomain.com",
"ssi_pattern", "**.shtml$|**.shtm$",
"throttle", NULL,
"access_log_file", NULL,
"enable_directory_listing", "yes",
"error_log_file", NULL,
"global_auth_file", NULL,
"index_files",
#ifdef USE_LUA
"index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,index.shtml,index.php",
#else
"index.html,index.htm,index.cgi,index.shtml,index.php",
#endif
"enable_keep_alive", "no",
"access_control_list", NULL,
"extra_mime_types", NULL,
"listening_ports", "8080",
"document_root", NULL,
"ssl_certificate", NULL,
"num_threads", "50",
"run_as_user", NULL,
"url_rewrite_patterns", NULL,
"hide_files_patterns", NULL,
"request_timeout_ms", "30000",
#if defined(USE_LUA)
"lua_script_pattern", "**.lua$",
"lua_server_page_pattern", "**.lp$|**.lsp$",
#endif
#if defined(USE_WEBSOCKET)
"websocket_root", NULL,
#endif
NULL
};
struct mg_request_handler_info {
char *uri;
size_t uri_len;
mg_request_handler handler;
void *cbdata;
struct mg_request_handler_info *next;
};
struct mg_context {
volatile int stop_flag; /* Should we stop event loop */
void *ssllib_dll_handle; /* Store the ssl library handle. */
void *cryptolib_dll_handle; /* Store the crypto library handle. */
SSL_CTX *ssl_ctx; /* SSL context */
char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
struct mg_callbacks callbacks; /* User-defined callback function */
void *user_data; /* User-defined data */
struct socket *listening_sockets;
in_port_t *listening_ports;
int num_listening_sockets;
volatile int num_threads; /* Number of threads */
pthread_mutex_t mutex; /* Protects (max|num)_threads */
pthread_cond_t cond; /* Condvar for tracking workers terminations */
struct socket queue[MGSQLEN]; /* Accepted sockets */
volatile int sq_head; /* Head of the socket queue */
volatile int sq_tail; /* Tail of the socket queue */
pthread_cond_t sq_full; /* Signaled when socket is produced */
pthread_cond_t sq_empty; /* Signaled when socket is consumed */
pthread_t masterthreadid; /* The master thread ID. */
int workerthreadcount; /* The amount of worker threads. */
pthread_t *workerthreadids;/* The worker thread IDs. */
/* linked list of uri handlers */
struct mg_request_handler_info *request_handlers;
};
struct mg_connection {
struct mg_request_info request_info;
struct mg_context *ctx;
SSL *ssl; /* SSL descriptor */
SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
struct socket client; /* Connected client */
time_t birth_time; /* Time when request was received */
int64_t num_bytes_sent; /* Total bytes sent to client */
int64_t content_len; /* Content-Length header value */
int64_t consumed_content; /* How many bytes of content have been read */
char *buf; /* Buffer for received data */
char *path_info; /* PATH_INFO part of the URL */
int must_close; /* 1 if connection must be closed */
int buf_size; /* Buffer size */
int request_len; /* Size of the request + headers in a buffer */
int data_len; /* Total size of data in a buffer */
int status_code; /* HTTP reply status code, e.g. 200 */
int throttle; /* Throttling, bytes/sec. <= 0 means no
throttle */
time_t last_throttle_time; /* Last time throttled data was sent */
int64_t last_throttle_bytes;/* Bytes sent this second */
pthread_mutex_t mutex; /* Used by mg_lock/mg_unlock to ensure atomic
transmissions for websockets */
#if defined(USE_LUA) && defined(USE_WEBSOCKET)
void * lua_websocket_state; /* Lua_State for a websocket connection */
#endif
};
static pthread_key_t sTlsKey; /* Thread local storage index */
static int sTlsInit = 0;
struct mg_workerTLS {
int is_master;
#if defined(_WIN32) && !defined(__SYMBIAN32__)
HANDLE pthread_cond_helper_mutex;
#endif
};
/* Directory entry */
struct de {
struct mg_connection *conn;
char *file_name;
struct file file;
};
#if defined(USE_WEBSOCKET)
static int is_websocket_request(const struct mg_connection *conn);
#endif
const char **mg_get_valid_option_names(void)
{
return config_options;
}
static int is_file_in_memory(struct mg_connection *conn, const char *path,
struct file *filep)
{
size_t size = 0;
if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :
conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
/* NOTE: override filep->size only on success. Otherwise, it might
break constructs like if (!mg_stat() || !mg_fopen()) ... */
filep->size = size;
}
return filep->membuf != NULL;
}
static int is_file_opened(const struct file *filep)
{
return filep->membuf != NULL || filep->fp != NULL;
}
static int mg_fopen(struct mg_connection *conn, const char *path,
const char *mode, struct file *filep)
{
if (!is_file_in_memory(conn, path, filep)) {
#ifdef _WIN32
wchar_t wbuf[PATH_MAX], wmode[20];
to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
filep->fp = _wfopen(wbuf, wmode);
#else
filep->fp = fopen(path, mode);
#endif
}
return is_file_opened(filep);
}
static void mg_fclose(struct file *filep)
{
if (filep != NULL && filep->fp != NULL) {
fclose(filep->fp);
}
}
static int get_option_index(const char *name)
{
int i;
for (i = 0; config_options[i * 2] != NULL; i++) {
if (strcmp(config_options[i * 2], name) == 0) {
return i;
}
}
return -1;
}
const char *mg_get_option(const struct mg_context *ctx, const char *name)
{
int i;
if ((i = get_option_index(name)) == -1) {
return NULL;
} else if (ctx->config[i] == NULL) {
return "";
} else {
return ctx->config[i];
}
}
size_t mg_get_ports(const struct mg_context *ctx, size_t size, int* ports, int* ssl)
{
size_t i;
for (i = 0; i < size && i < (size_t)ctx->num_listening_sockets; i++)
{
ssl[i] = ctx->listening_sockets[i].is_ssl;
ports[i] = ctx->listening_ports[i];
}
return i;
}
static void sockaddr_to_string(char *buf, size_t len,
const union usa *usa)
{
buf[0] = '\0';
#if defined(USE_IPV6)
inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
(void *) &usa->sin.sin_addr :
(void *) &usa->sin6.sin6_addr, buf, len);
#elif defined(_WIN32)
/* Only Windows Vista (and newer) have inet_ntop() */
strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
#else
inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
#endif
}
/* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be included in all responses other than 100, 101, 5xx. */
static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
{
struct tm *tm;
tm = gmtime(t);
if (tm != NULL) {
strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
} else {
strncpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
buf[buf_len - 1] = '\0';
}
}
/* Print error message to the opened error log stream. */
void mg_cry(struct mg_connection *conn, const char *fmt, ...)
{
char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
va_list ap;
FILE *fp;
time_t timestamp;
va_start(ap, fmt);
IGNORE_UNUSED_RESULT(vsnprintf(buf, sizeof(buf), fmt, ap));
va_end(ap);
/* Do not lock when getting the callback value, here and below.
I suppose this is fine, since function cannot disappear in the
same way string option can. */
if (conn->ctx->callbacks.log_message == NULL ||
conn->ctx->callbacks.log_message(conn, buf) == 0) {
fp = conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
if (fp != NULL) {
flockfile(fp);
timestamp = time(NULL);
sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
src_addr);
if (conn->request_info.request_method != NULL) {
fprintf(fp, "%s %s: ", conn->request_info.request_method,
conn->request_info.uri);
}
fprintf(fp, "%s", buf);
fputc('\n', fp);
funlockfile(fp);
fclose(fp);
}
}
}
/* Return fake connection structure. Used for logging, if connection
is not applicable at the moment of logging. */
static struct mg_connection *fc(struct mg_context *ctx)
{
static struct mg_connection fake_connection;
fake_connection.ctx = ctx;
return &fake_connection;
}
const char *mg_version(void)
{
return CIVETWEB_VERSION;
}
struct mg_request_info *mg_get_request_info(struct mg_connection *conn)
{
return &conn->request_info;
}
static void mg_strlcpy(register char *dst, register const char *src, size_t n)
{
for (; *src != '\0' && n > 1; n--) {
*dst++ = *src++;
}
*dst = '\0';
}
static int lowercase(const char *s)
{
return tolower(* (const unsigned char *) s);
}
int mg_strncasecmp(const char *s1, const char *s2, size_t len)
{
int diff = 0;
if (len > 0)
do {
diff = lowercase(s1++) - lowercase(s2++);
} while (diff == 0 && s1[-1] != '\0' && --len > 0);
return diff;
}
static int mg_strcasecmp(const char *s1, const char *s2)
{
int diff;
do {
diff = lowercase(s1++) - lowercase(s2++);
} while (diff == 0 && s1[-1] != '\0');
return diff;
}
static char * mg_strndup(const char *ptr, size_t len)
{
char *p;
if ((p = (char *) malloc(len + 1)) != NULL) {
mg_strlcpy(p, ptr, len + 1);
}
return p;
}
static char * mg_strdup(const char *str)
{
return mg_strndup(str, strlen(str));
}
static const char *mg_strcasestr(const char *big_str, const char *small_str)
{
int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
for (i = 0; i <= big_len - small_len; i++) {
if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
return big_str + i;
}
}
return NULL;
}
/* Like snprintf(), but never returns negative value, or a value
that is larger than a supplied buffer.
Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
in his audit report. */
static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
const char *fmt, va_list ap)
{
int n;
if (buflen == 0)
return 0;
n = vsnprintf(buf, buflen, fmt, ap);
if (n < 0) {
mg_cry(conn, "vsnprintf error");
n = 0;
} else if (n >= (int) buflen) {
mg_cry(conn, "truncating vsnprintf buffer: [%.*s]",
n > 200 ? 200 : n, buf);
n = (int) buflen - 1;
}
buf[n] = '\0';
return n;
}
static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
PRINTF_FORMAT_STRING(const char *fmt), ...)
PRINTF_ARGS(4, 5);
static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
const char *fmt, ...)
{
va_list ap;
int n;
va_start(ap, fmt);
n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
va_end(ap);
return n;
}
/* Skip the characters until one of the delimiters characters found.
0-terminate resulting word. Skip the delimiter and following whitespaces.
Advance pointer to buffer to the next word. Return found 0-terminated word.
Delimiters can be quoted with quotechar. */
static char *skip_quoted(char **buf, const char *delimiters,
const char *whitespace, char quotechar)
{
char *p, *begin_word, *end_word, *end_whitespace;
begin_word = *buf;
end_word = begin_word + strcspn(begin_word, delimiters);
/* Check for quotechar */
if (end_word > begin_word) {
p = end_word - 1;
while (*p == quotechar) {
/* If there is anything beyond end_word, copy it */
if (*end_word == '\0') {
*p = '\0';
break;
} else {
size_t end_off = strcspn(end_word + 1, delimiters);
memmove (p, end_word, end_off + 1);
p += end_off; /* p must correspond to end_word - 1 */
end_word += end_off + 1;
}
}
for (p++; p < end_word; p++) {
*p = '\0';
}
}
if (*end_word == '\0') {
*buf = end_word;
} else {
end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
for (p = end_word; p < end_whitespace; p++) {
*p = '\0';
}
*buf = end_whitespace;
}
return begin_word;
}
/* Simplified version of skip_quoted without quote char
and whitespace == delimiters */