-
Notifications
You must be signed in to change notification settings - Fork 15
/
mongoose.c
4725 lines (4027 loc) · 127 KB
/
mongoose.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-2009 Sergey Lyubka
* Portions Copyright (c) 2009 Gilbert Wellisch
*
* 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.
*
* $Id$
*/
#if defined(_WIN32)
#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
#endif /* _WIN32 */
#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>
#if defined(_WIN32) /* Windows specific #includes and #defines */
#define _WIN32_WINNT 0x0400 /* To make it link in VS2005 */
#include <windows.h>
#ifndef _WIN32_WCE
#include <process.h>
#include <direct.h>
#include <io.h>
#else /* _WIN32_WCE */
/* Windows CE-specific definitions */
#include <winsock2.h>
#define NO_CGI /* WinCE has no pipes */
#define NO_SSI /* WinCE has no pipes */
#define FILENAME_MAX MAX_PATH
#define BUFSIZ 4096
typedef long off_t;
#define errno GetLastError()
#define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
#endif /* _WIN32_WCE */
#define EPOCH_DIFF 0x019DB1DED53E8000 /* 116444736000000000 nsecs */
#define RATE_DIFF 10000000 /* 100 nsecs */
#define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
((uint64_t)((uint32_t)(hi))) << 32))
#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__ "line " STR(__LINE__)
#define strtoull(x, y, z) strtoul(x, y, z)
#else
#define __func__ __FUNCTION__
#define strtoull(x, y, z) _strtoui64(x, y, z)
#endif /* _MSC_VER */
#define ERRNO GetLastError()
#define NO_SOCKLEN_T
#define SSL_LIB "ssleay32.dll"
#define CRYPTO_LIB "libeay32.dll"
#define DIRSEP '\\'
#define IS_DIRSEP_CHAR(c) ((c) == '/' || (c) == '\\')
#define O_NONBLOCK 0
#define EWOULDBLOCK WSAEWOULDBLOCK
#define _POSIX_
#define INT64_FMT "I64"
#define SHUT_WR 1
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define sleep(x) Sleep((x) * 1000)
#define popen(x, y) _popen(x, y)
#define pclose(x) _pclose(x)
#define close(x) _close(x)
#define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
#define RTLD_LAZY 0
#define fseeko(x, y, z) fseek((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) (void) 0
#define funlockfile(x) (void) 0
#if !defined(fileno)
#define fileno(x) _fileno(x)
#endif /* !fileno MINGW #defines fileno */
typedef HANDLE pthread_mutex_t;
typedef HANDLE pthread_cond_t;
typedef DWORD pthread_t;
#define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
struct timespec {
long tv_nsec;
long tv_sec;
};
static int pthread_mutex_lock(pthread_mutex_t *);
static int pthread_mutex_unlock(pthread_mutex_t *);
#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[FILENAME_MAX];
};
typedef struct DIR {
HANDLE handle;
WIN32_FIND_DATAW info;
struct dirent result;
} DIR;
#else /* UNIX specific */
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/mman.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <stdint.h>
#include <inttypes.h>
#include <pwd.h>
#include <unistd.h>
#include <dirent.h>
#include <dlfcn.h>
#include <pthread.h>
#define SSL_LIB "libssl.so"
#define CRYPTO_LIB "libcrypto.so"
#define DIRSEP '/'
#define IS_DIRSEP_CHAR(c) ((c) == '/')
#define O_BINARY 0
#define closesocket(a) close(a)
#define mg_fopen(x, y) fopen(x, y)
#define mg_mkdir(x, y) mkdir(x, y)
#define mg_remove(x) remove(x)
#define mg_rename(x, y) rename(x, y)
#define ERRNO errno
#define INVALID_SOCKET (-1)
#define INT64_FMT PRId64
typedef int SOCKET;
#endif /* End of Windows and UNIX specific includes */
#include "mongoose.h"
#define MONGOOSE_VERSION "2.9"
#define PASSWORDS_FILE_NAME ".htpasswd"
#define CGI_ENVIRONMENT_SIZE 4096
#define MAX_CGI_ENVIR_VARS 64
#define MAX_REQUEST_SIZE 8192
#define MAX_LISTENING_SOCKETS 10
#define MAX_CALLBACKS 20
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
#define DEBUG_MGS_PREFIX "*** Mongoose debug *** "
#if defined(DEBUG)
#define DEBUG_TRACE(x) do {printf x; putchar('\n'); fflush(stdout);} while (0)
#else
#define DEBUG_TRACE(x)
#endif /* DEBUG */
/*
* Darwin prior to 7.0 and Win32 do not have socklen_t
*/
#ifdef NO_SOCKLEN_T
typedef int socklen_t;
#endif /* NO_SOCKLEN_T */
#if !defined(FALSE)
enum {FALSE, TRUE};
#endif /* !FALSE */
typedef int bool_t;
typedef void * (*mg_thread_func_t)(void *);
static const char *http_500_error = "Internal Server Error";
/*
* Snatched from OpenSSL includes. I put the prototypes here to be independent
* from the OpenSSL source installation. Having this, mongoose + SSL can be
* built on any system with binary SSL libraries installed.
*/
typedef struct ssl_st SSL;
typedef struct ssl_method_st SSL_METHOD;
typedef struct ssl_ctx_st SSL_CTX;
#define SSL_ERROR_WANT_READ 2
#define SSL_ERROR_WANT_WRITE 3
#define SSL_FILETYPE_PEM 1
#define CRYPTO_LOCK 1
/*
* Dynamically loaded SSL functionality
*/
struct ssl_func {
const char *name; /* SSL function name */
void (*ptr)(void); /* Function pointer */
};
#define SSL_free(x) (* (void (*)(SSL *)) ssl_sw[0].ptr)(x)
#define SSL_accept(x) (* (int (*)(SSL *)) ssl_sw[1].ptr)(x)
#define SSL_connect(x) (* (int (*)(SSL *)) ssl_sw[2].ptr)(x)
#define SSL_read(x,y,z) (* (int (*)(SSL *, void *, int)) \
ssl_sw[3].ptr)((x),(y),(z))
#define SSL_write(x,y,z) (* (int (*)(SSL *, const void *,int)) \
ssl_sw[4].ptr)((x), (y), (z))
#define SSL_get_error(x,y)(* (int (*)(SSL *, int)) ssl_sw[5])((x), (y))
#define SSL_set_fd(x,y) (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)((x), (y))
#define SSL_new(x) (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)(x)
#define SSL_CTX_new(x) (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)(x)
#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(x,y,z) (* (int (*)(SSL_CTX *, \
const char *, int)) ssl_sw[11].ptr)((x), (y), (z))
#define SSL_CTX_use_certificate_file(x,y,z) (* (int (*)(SSL_CTX *, \
const char *, int)) ssl_sw[12].ptr)((x), (y), (z))
#define SSL_CTX_set_default_passwd_cb(x,y) \
(* (void (*)(SSL_CTX *, mg_spcb_t)) ssl_sw[13].ptr)((x),(y))
#define SSL_CTX_free(x) (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)(x)
#define CRYPTO_num_locks() (* (int (*)(void)) crypto_sw[0].ptr)()
#define CRYPTO_set_locking_callback(x) \
(* (void (*)(void (*)(int, int, const char *, int))) \
crypto_sw[1].ptr)(x)
#define CRYPTO_set_id_callback(x) \
(* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)(x)
/*
* set_ssl_option() function when called, 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},
{NULL, NULL}
};
/*
* Similar array as ssl_sw. These functions are located in different lib.
*/
static struct ssl_func crypto_sw[] = {
{"CRYPTO_num_locks", NULL},
{"CRYPTO_set_locking_callback", NULL},
{"CRYPTO_set_id_callback", NULL},
{NULL, NULL}
};
/*
* Month names
*/
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.
*/
struct usa {
socklen_t len;
union {
struct sockaddr sa;
struct sockaddr_in sin;
} u;
};
/*
* Specifies a string (chunk of memory).
* Used to traverse comma separated lists of options.
*/
struct vec {
const char *ptr;
size_t len;
};
/*
* Structure used by mg_stat() function. Uses 64 bit file length.
*/
struct mgstat {
bool_t is_directory; /* Directory marker */
int64_t size; /* File size */
time_t mtime; /* Modification time */
};
struct mg_option {
const char *name;
const char *description;
const char *default_value;
int index;
bool_t (*setter)(struct mg_context *, const char *);
};
/*
* Numeric indexes for the option values in context, ctx->options
*/
enum mg_option_index {
OPT_ROOT, OPT_INDEX_FILES, OPT_PORTS, OPT_DIR_LIST, OPT_CGI_EXTENSIONS,
OPT_CGI_INTERPRETER, OPT_CGI_ENV, OPT_SSI_EXTENSIONS, OPT_AUTH_DOMAIN,
OPT_AUTH_GPASSWD, OPT_AUTH_PUT, OPT_ACCESS_LOG, OPT_ERROR_LOG,
OPT_SSL_CERTIFICATE, OPT_ALIASES, OPT_ACL, OPT_UID, OPT_PROTECT,
OPT_SERVICE, OPT_HIDE, OPT_ADMIN_URI, OPT_MAX_THREADS, OPT_IDLE_TIME,
OPT_MIME_TYPES,
NUM_OPTIONS
};
/*
* Structure used to describe 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 */
struct usa lsa; /* Local socket address */
struct usa rsa; /* Remote socket address */
bool_t is_ssl; /* Is socket SSL-ed */
};
/*
* Callback function, and where it is bound to
*/
struct callback {
char *uri_regex; /* URI regex to handle */
mg_callback_t func; /* user callback */
bool_t is_auth; /* func is auth checker */
int status_code; /* error code to handle */
void *user_data; /* opaque user data */
};
/*
* Mongoose context
*/
struct mg_context {
int stop_flag; /* Should we stop event loop */
SSL_CTX *ssl_ctx; /* SSL context */
FILE *access_log; /* Opened access log */
FILE *error_log; /* Opened error log */
struct socket listeners[MAX_LISTENING_SOCKETS];
int num_listeners;
struct callback callbacks[MAX_CALLBACKS];
int num_callbacks;
char *options[NUM_OPTIONS]; /* Configured opions */
pthread_mutex_t opt_mutex[NUM_OPTIONS]; /* Option protector */
int max_threads; /* Maximum number of threads */
int num_threads; /* Number of threads */
int num_idle; /* Number of idle threads */
pthread_mutex_t thr_mutex; /* Protects (max|num)_threads */
pthread_cond_t thr_cond;
pthread_mutex_t bind_mutex; /* Protects bind operations */
struct socket queue[20]; /* Accepted sockets */
int sq_head; /* Head of the socket queue */
int sq_tail; /* Tail of the socket queue */
pthread_cond_t empty_cond; /* Socket queue empty condvar */
pthread_cond_t full_cond; /* Socket queue full condvar */
mg_spcb_t ssl_password_callback;
mg_callback_t log_callback;
};
/*
* Client connection.
*/
struct mg_connection {
struct mg_request_info request_info;
struct mg_context *ctx; /* Mongoose context we belong to*/
SSL *ssl; /* SSL descriptor */
struct socket client; /* Connected client */
time_t birth_time; /* Time connection was accepted */
bool_t free_post_data; /* post_data was malloc-ed */
bool_t embedded_auth; /* Used for authorization */
int64_t num_bytes_sent; /* Total bytes sent to client */
};
/*
* Print error message to the opened error log stream.
*/
static void
cry(struct mg_connection *conn, const char *fmt, ...)
{
char buf[BUFSIZ];
va_list ap;
va_start(ap, fmt);
(void) vsnprintf(buf, sizeof(buf), fmt, ap);
conn->ctx->log_callback(conn, &conn->request_info, buf);
va_end(ap);
}
/*
* 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);
}
/*
* If an embedded code does not intercept logging by calling
* mg_set_log_callback(), this function is used for logging. It prints
* stuff to the conn->error_log, which is stderr unless "error_log"
* option was set.
*/
static void
builtin_error_log(struct mg_connection *conn,
const struct mg_request_info *request_info, void *message)
{
FILE *fp;
time_t timestamp;
fp = conn->ctx->error_log;
flockfile(fp);
timestamp = time(NULL);
(void) fprintf(fp,
"[%010lu] [error] [client %s] ",
(unsigned long) timestamp,
inet_ntoa(conn->client.rsa.u.sin.sin_addr));
if (request_info->request_method != NULL)
(void) fprintf(fp, "%s %s: ",
request_info->request_method,
request_info->uri);
(void) fprintf(fp, "%s", (char *) message);
fputc('\n', fp);
funlockfile(fp);
}
const char *
mg_version(void)
{
return (MONGOOSE_VERSION);
}
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(* (unsigned char *) s));
}
static 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)));
}
/*
* Like snprintf(), but never returns negative value, or the 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) {
cry(conn, "vsnprintf error");
n = 0;
} else if (n >= (int) buflen) {
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, 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);
}
/*
* Convert string representing a boolean value to a boolean value
*/
static bool_t
is_true(const char *str)
{
static const char *trues[] = {"1", "yes", "true", "ja", NULL};
int i;
for (i = 0; trues[i] != NULL; i++)
if (str != NULL && mg_strcasecmp(str, trues[i]) == 0)
return (TRUE);
return (FALSE);
}
/*
* Skip the characters until one of the delimiters characters found.
* 0-terminate resulting word. Skip the rest of the delimiters if any.
* Advance pointer to buffer to the next word. Return found 0-terminated word.
*/
static char *
skip(char **buf, const char *delimiters)
{
char *p, *begin_word, *end_word, *end_delimiters;
begin_word = *buf;
end_word = begin_word + strcspn(begin_word, delimiters);
end_delimiters = end_word + strspn(end_word, delimiters);
for (p = end_word; p < end_delimiters; p++)
*p = '\0';
*buf = end_delimiters;
return (begin_word);
}
/*
* Return HTTP header value, or NULL if not found.
*/
static const char *
get_header(const struct mg_request_info *ri, const char *name)
{
int i;
for (i = 0; i < ri->num_headers; i++)
if (!mg_strcasecmp(name, ri->http_headers[i].name))
return (ri->http_headers[i].value);
return (NULL);
}
const char *
mg_get_header(const struct mg_connection *conn, const char *name)
{
return (get_header(&conn->request_info, name));
}
/*
* A helper function for traversing comma separated list of values.
* It returns a list pointer shifted to the next value, of NULL if the end
* of the list found.
* Value is stored in val vector. If value has form "x=y", then eq_val
* vector is initialized to point to the "y" part, and val vector length
* is adjusted to point only to "x".
*/
static const char *
next_option(const char *list, struct vec *val, struct vec *eq_val)
{
if (list == NULL || *list == '\0') {
/* End of the list */
list = NULL;
} else {
val->ptr = list;
if ((list = strchr(val->ptr, ',')) != NULL) {
/* Comma found. Store length and shift the list ptr */
val->len = list - val->ptr;
list++;
} else {
/* This value is the last one */
list = val->ptr + strlen(val->ptr);
val->len = list - val->ptr;
}
if (eq_val != NULL) {
/*
* Value has form "x=y", adjust pointers and lengths
* so that val points to "x", and eq_val points to "y".
*/
eq_val->len = 0;
eq_val->ptr = memchr(val->ptr, '=', val->len);
if (eq_val->ptr != NULL) {
eq_val->ptr++; /* Skip over '=' character */
eq_val->len = val->ptr + val->len - eq_val->ptr;
val->len = (eq_val->ptr - val->ptr) - 1;
}
}
}
return (list);
}
#if !(defined(NO_CGI) && defined(NO_SSI))
/*
* Verify that given file has certain extension
*/
static bool_t
match_extension(const char *path, const char *ext_list)
{
struct vec ext_vec;
size_t path_len;
path_len = strlen(path);
while ((ext_list = next_option(ext_list, &ext_vec, NULL)) != NULL)
if (ext_vec.len < path_len &&
mg_strncasecmp(path + path_len - ext_vec.len,
ext_vec.ptr, ext_vec.len) == 0)
return (TRUE);
return (FALSE);
}
#endif /* !(NO_CGI && NO_SSI) */
/*
* Return TRUE if "uri" matches "regexp".
* '*' in the regexp means zero or more characters.
*/
static bool_t
match_regex(const char *uri, const char *regexp)
{
if (*regexp == '\0')
return (*uri == '\0');
if (*regexp == '*')
do {
if (match_regex(uri, regexp + 1))
return (TRUE);
} while (*uri++ != '\0');
if (*uri != '\0' && *regexp == *uri)
return (match_regex(uri + 1, regexp + 1));
return (FALSE);
}
static const struct callback *
find_callback(struct mg_context *ctx, bool_t is_auth,
const char *uri, int status_code)
{
const struct callback *cb, *found;
int i;
found = NULL;
pthread_mutex_lock(&ctx->bind_mutex);
for (i = 0; i < ctx->num_callbacks; i++) {
cb = ctx->callbacks + i;
if ((uri != NULL && cb->uri_regex != NULL &&
((is_auth && cb->is_auth) || (!is_auth && !cb->is_auth)) &&
match_regex(uri, cb->uri_regex)) || (uri == NULL &&
(cb->status_code == 0 ||
cb->status_code == status_code))) {
found = cb;
break;
}
}
pthread_mutex_unlock(&ctx->bind_mutex);
return (found);
}
/*
* For use by external application. This sets custom logging function.
*/
void
mg_set_log_callback(struct mg_context *ctx, mg_callback_t log_callback)
{
/* If NULL is specified as a callback, revert back to the default */
if (log_callback == NULL)
ctx->log_callback = &builtin_error_log;
else
ctx->log_callback = log_callback;
}
/*
* Send error message back to the client.
*/
static void
send_error(struct mg_connection *conn, int status, const char *reason,
const char *fmt, ...)
{
const struct callback *cb;
char buf[BUFSIZ];
va_list ap;
int len;
conn->request_info.status_code = status;
/* If error handler is set, call it. Otherwise, send error message */
if ((cb = find_callback(conn->ctx, FALSE, NULL, status)) != NULL) {
cb->func(conn, &conn->request_info, cb->user_data);
} else {
buf[0] = '\0';
len = 0;
/* Errors 1xx, 204 and 304 MUST NOT send a body */
if (status > 199 && status != 204 && status != 304) {
len = mg_snprintf(conn, buf, sizeof(buf),
"Error %d: %s\n", status, reason);
cry(conn, "%s", buf);
va_start(ap, fmt);
len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len,
fmt, ap);
va_end(ap);
conn->num_bytes_sent = len;
}
(void) mg_printf(conn,
"HTTP/1.1 %d %s\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"Connection: close\r\n"
"\r\n%s", status, reason, len, buf);
}
}
#ifdef _WIN32
static int
pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
{
unused = NULL;
*mutex = CreateMutex(NULL, FALSE, NULL);
return (*mutex == NULL ? -1 : 0);
}
static int
pthread_mutex_destroy(pthread_mutex_t *mutex)
{
return (CloseHandle(*mutex) == 0 ? -1 : 0);
}
static int
pthread_mutex_lock(pthread_mutex_t *mutex)
{
return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1);
}
static int
pthread_mutex_unlock(pthread_mutex_t *mutex)
{
return (ReleaseMutex(*mutex) == 0 ? -1 : 0);
}
static int
pthread_cond_init(pthread_cond_t *cv, const void *unused)
{
unused = NULL;
*cv = CreateEvent(NULL, FALSE, FALSE, NULL);
return (*cv == NULL ? -1 : 0);
}
static int
pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mutex,
const struct timespec *ts)
{
DWORD status;
DWORD msec = INFINITE;
time_t now;
if (ts != NULL) {
now = time(NULL);
msec = 1000 * (now > ts->tv_sec ? 0 : ts->tv_sec - now);
}
(void) ReleaseMutex(*mutex);
status = WaitForSingleObject(*cv, msec);
(void) WaitForSingleObject(*mutex, INFINITE);
return (status == WAIT_OBJECT_0 ? 0 : -1);
}
static int
pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
{
return (pthread_cond_timedwait(cv, mutex, NULL));
}
static int
pthread_cond_signal(pthread_cond_t *cv)
{
return (SetEvent(*cv) == 0 ? -1 : 0);
}
static int
pthread_cond_destroy(pthread_cond_t *cv)
{
return (CloseHandle(*cv) == 0 ? -1 : 0);
}
static pthread_t
pthread_self(void)
{
return (GetCurrentThreadId());
}
/*
* Change all slashes to backslashes. It is Windows.
*/
static void
fix_directory_separators(char *path)
{
int i;
for (i = 0; path[i] != '\0'; i++) {
if (path[i] == '/')
path[i] = '\\';
/* i > 0 check is to preserve UNC paths, \\server\file.txt */
if (path[i] == '\\' && i > 0)
while (path[i + 1] == '\\' || path[i + 1] == '/')
(void) memmove(path + i + 1,
path + i + 2, strlen(path + i + 1));
}
}
/*
* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
* wbuf and wbuf_len is a target buffer and its length.
*/
static void
to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
{
char buf[FILENAME_MAX], *p;
mg_strlcpy(buf, path, sizeof(buf));
fix_directory_separators(buf);
/* Point p to the end of the file name */
p = buf + strlen(buf) - 1;
/* Trim trailing backslash character */
while (p > buf && *p == '\\' && p[-1] != ':')
*p-- = '\0';
/*
* Protect from CGI code disclosure.
* This is very nasty hole. Windows happily opens files with
* some garbage in the end of file name. So fopen("a.cgi ", "r")
* actually opens "a.cgi", and does not return an error!
*/
if (*p == 0x20 || /* No space at the end */
(*p == 0x2e && p > buf) || /* No '.' but allow '.' as full path */
*p == 0x2b || /* No '+' */
(*p & ~0x7f)) { /* And generally no non-ascii chars */
(void) fprintf(stderr, "Rejecting suspicious path: [%s]", buf);
buf[0] = '\0';
}
(void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
}
#if defined(_WIN32_WCE)
static time_t
time(time_t *ptime)
{
time_t t;
SYSTEMTIME st;
FILETIME ft;
GetSystemTime(&st);
SystemTimeToFileTime(&st, &ft);
t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
if (ptime != NULL)
*ptime = t;
return (t);
}
static time_t
mktime(struct tm *ptm)
{
SYSTEMTIME st;
FILETIME ft, lft;
st.wYear = ptm->tm_year + 1900;