forked from cloudera/squeasel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
squeasel.c
4959 lines (4291 loc) · 155 KB
/
squeasel.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
// Some portions Copyright (c) 2004-2013 Sergey Lyubka
// Some portions Copyright (c) 2013 Cloudera Inc.
//
// 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.
#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
#ifdef __linux__
#include <sys/prctl.h>
#endif // defined(__linux__)
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <time.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#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>
#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 sq_mkdir(x, y) mkdir(x, y)
#define sq_remove(x) remove(x)
#define sq_sleep(x) usleep((x) * 1000)
#define ERRNO errno
#define INVALID_SOCKET (-1)
#define INT64_FMT PRId64
typedef int SOCKET;
#include "squeasel.h"
#define SQUEASEL_VERSION "3.9"
#define PASSWORDS_FILE_NAME ".htpasswd"
#define CGI_ENVIRONMENT_SIZE 4096
#define MAX_CGI_ENVIR_VARS 64
#define SQ_BUF_LEN 8192
#define MAX_REQUEST_SIZE 16384
#define WORKER_THREAD_TIMEOUT_SECS 3
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
#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
#define RETRY_ON_EINTR(ret, expr) do { \
ret = expr; \
} while ((ret == -1) && (errno == EINTR));
static const char *http_500_error = "Internal Server Error";
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
// If these constants aren't defined, we still need them to compile and maintain backwards
// compatibility with pre-1.0.1 OpenSSL.
#ifndef SSL_OP_NO_TLSv1
#define SSL_OP_NO_TLSv1 0x04000000U
#endif
#ifndef SSL_OP_NO_TLSv1_1
#define SSL_OP_NO_TLSv1_1 0x10000000U
#endif
#define OPENSSL_MIN_VERSION_WITH_TLS_1_1 0x10001000L
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
};
char* SAFE_HTTP_METHODS[] = {
"GET", "POST", "HEAD", "OPTIONS" };
// See https://www.owasp.org/index.php/Test_HTTP_Methods_(OTG-CONFIG-006) for details.
#ifdef ALLOW_UNSAFE_HTTP_METHODS
char* UNSAFE_HTTP_METHODS[] = { "DELETE" , "CONNECT", "PUT" };
#endif
// 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, SSL_PRIVATE_KEY,
SSL_PRIVATE_KEY_PASSWORD, SSL_GLOBAL_INIT, NUM_THREADS, RUN_AS_USER, REWRITE,
HIDE_FILES, REQUEST_TIMEOUT, SSL_VERSION, SSL_CIPHERS, 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",
"index.html,index.htm,index.cgi,index.shtml,index.php,index.lp",
"enable_keep_alive", "no",
"access_control_list", NULL,
"extra_mime_types", NULL,
"listening_ports", "8080",
"document_root", NULL,
"ssl_certificate", NULL,
"ssl_private_key", NULL,
"ssl_private_key_password", NULL,
"ssl_global_init", "yes",
"num_threads", "50",
"run_as_user", NULL,
"url_rewrite_patterns", NULL,
"hide_files_patterns", NULL,
"request_timeout_ms", "30000",
"ssl_min_version", "tlsv1",
"ssl_ciphers", NULL,
NULL
};
struct sq_context {
volatile int stop_flag; // Should we stop event loop
int wakeup_fds[2]; // File descriptors used to wake up
// master thread.
SSL_CTX *ssl_ctx; // SSL context
char *config[NUM_OPTIONS]; // Squeasel configuration parameters
struct sq_callbacks callbacks; // User-defined callback function
void *user_data; // User-defined data
struct socket *listening_sockets;
int num_listening_sockets;
int max_threads; // Maximum number of threads to start.
int num_free_threads; // Number of worker threads currently not working
// on a request.
volatile int num_threads; // Number of threads
pthread_mutex_t mutex; // Protects (max|num|num_free)_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
};
struct sq_connection {
struct sq_request_info request_info;
struct sq_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
};
// Directory entry
struct de {
struct sq_connection *conn;
char *file_name;
struct file file;
};
const char **sq_get_valid_option_names(void) {
return config_options;
}
static int is_file_in_memory(struct sq_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 (!sq_stat() || !sq_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 sq_fopen(struct sq_connection *conn, const char *path,
const char *mode, struct file *filep) {
if (!is_file_in_memory(conn, path, filep)) {
filep->fp = fopen(path, mode);
}
return is_file_opened(filep);
}
static void sq_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 *sq_get_option(const struct sq_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];
}
}
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);
#else
inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
#endif
}
static void cry(struct sq_connection *conn,
PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
// Print error message to the opened error log stream.
static void cry(struct sq_connection *conn, const char *fmt, ...) {
char buf[SQ_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
va_list ap;
FILE *fp;
time_t timestamp;
va_start(ap, fmt);
(void) 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 == NULL || 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 sq_connection *fc(const struct sq_context *ctx) {
static struct sq_connection fake_connection;
fake_connection.ctx = (struct sq_context*)ctx;
return &fake_connection;
}
const char *sq_version(void) {
return SQUEASEL_VERSION;
}
struct sq_request_info *sq_get_request_info(struct sq_connection *conn) {
return &conn->request_info;
}
static void sq_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);
}
static int sq_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 sq_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 * sq_strndup(const char *ptr, size_t len) {
char *p;
if ((p = (char *) malloc(len + 1)) != NULL) {
sq_strlcpy(p, ptr, len + 1);
}
return p;
}
static char * sq_strdup(const char *str) {
return sq_strndup(str, strlen(str));
}
static const char *sq_strcasestr(const char *big_str, const char *small_str) {
int i, big_len = strlen(big_str), small_len = strlen(small_str);
for (i = 0; i <= big_len - small_len; i++) {
if (sq_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 sq_vsnprintf(struct sq_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 sq_snprintf(struct sq_connection *conn, char *buf, size_t buflen,
PRINTF_FORMAT_STRING(const char *fmt), ...)
PRINTF_ARGS(4, 5);
static int sq_snprintf(struct sq_connection *conn, char *buf, size_t buflen,
const char *fmt, ...) {
va_list ap;
int n;
va_start(ap, fmt);
n = sq_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
static char *skip(char **buf, const char *delimiters) {
return skip_quoted(buf, delimiters, delimiters, 0);
}
// Return HTTP header value, or NULL if not found.
static const char *get_header(const struct sq_request_info *ri,
const char *name) {
int i;
for (i = 0; i < ri->num_headers; i++)
if (!sq_strcasecmp(name, ri->http_headers[i].name))
return ri->http_headers[i].value;
return NULL;
}
const char *sq_get_header(const struct sq_connection *conn, const char *name) {
return get_header(&conn->request_info, name);
}
// A helper function for traversing a comma separated list of values.
// It returns a list pointer shifted to the next value, or 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 = (const char *) 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;
}
// Perform case-insensitive match of string against pattern
static int match_prefix(const char *pattern, int pattern_len, const char *str) {
const char *or_str;
int i, j, len, res;
if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
res = match_prefix(pattern, or_str - pattern, str);
return res > 0 ? res :
match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);
}
i = j = 0;
res = -1;
for (; i < pattern_len; i++, j++) {
if (pattern[i] == '?' && str[j] != '\0') {
continue;
} else if (pattern[i] == '$') {
return str[j] == '\0' ? j : -1;
} else if (pattern[i] == '*') {
i++;
if (pattern[i] == '*') {
i++;
len = (int) strlen(str + j);
} else {
len = (int) strcspn(str + j, "/");
}
if (i == pattern_len) {
return j + len;
}
do {
res = match_prefix(pattern + i, pattern_len - i, str + j + len);
} while (res == -1 && len-- > 0);
return res == -1 ? -1 : j + res + len;
} else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
return -1;
}
}
return j;
}
static int should_keep_alive(const struct sq_connection *conn) {
const char *http_version = conn->request_info.http_version;
const char *header = sq_get_header(conn, "Connection");
// Start by checking our own internal request state and configuration.
if (conn->must_close ||
sq_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
return 0;
}
// Now consider the HTTP version and "Connection:" header.
// If we couldn't parse an HTTP version, assume 1.0.
//
// We must tolerate situations when connection info is not set up, for
// example if HTTP request parsing failed.
int http_1_0 = !http_version || sq_strcasecmp(http_version, "1.0") == 0;
if (!header) {
// HTTP 1.1 assumes keep alive if the "Connection:" header is not set.
return !http_1_0;
}
// With HTTP 1.0, keep alive only if the "Connection: keep-alive" header
// exists. Otherwise, keep alive unless the "Connection: close" header exists.
return (http_1_0 && sq_strcasecmp(header, "keep-alive") == 0) ||
(!http_1_0 && sq_strcasecmp(header, "close") != 0);
}
static const char *suggest_connection_header(const struct sq_connection *conn) {
return should_keep_alive(conn) ? "keep-alive" : "close";
}
static void send_http_error(struct sq_connection *, int, const char *,
PRINTF_FORMAT_STRING(const char *fmt), ...)
PRINTF_ARGS(4, 5);
static void send_http_error(struct sq_connection *conn, int status,
const char *reason, const char *fmt, ...) {
char buf[SQ_BUF_LEN];
va_list ap;
int len = 0;
conn->status_code = status;
if (conn->ctx->callbacks.http_error == NULL ||
conn->ctx->callbacks.http_error(conn, status)) {
buf[0] = '\0';
// Errors 1xx, 204 and 304 MUST NOT send a body
if (status > 199 && status != 204 && status != 304) {
len = sq_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
buf[len++] = '\n';
va_start(ap, fmt);
len += sq_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
va_end(ap);
}
DEBUG_TRACE(("[%s]", buf));
sq_printf(conn, "HTTP/1.1 %d %s\r\n"
"Content-Length: %d\r\n"
"Connection: %s\r\n\r\n", status, reason, len,
suggest_connection_header(conn));
conn->num_bytes_sent += sq_printf(conn, "%s", buf);
}
}
static int sq_stat(struct sq_connection *conn, const char *path,
struct file *filep) {
struct stat st;
if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
filep->size = st.st_size;
filep->modification_time = st.st_mtime;
filep->is_directory = S_ISDIR(st.st_mode);
} else {
filep->modification_time = (time_t) 0;
}
return filep->membuf != NULL || filep->modification_time != (time_t) 0;
}
static void set_close_on_exec(int fd) {
fcntl(fd, F_SETFD, FD_CLOEXEC);
}
int sq_start_thread(sq_thread_func_t func, void *param) {
pthread_t thread_id;
pthread_attr_t attr;
int result;
(void) pthread_attr_init(&attr);
(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
#if USE_STACK_SIZE > 1
// Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
(void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
#endif
result = pthread_create(&thread_id, &attr, func, param);
pthread_attr_destroy(&attr);
return result;
}
#ifndef NO_CGI
static pid_t spawn_process(struct sq_connection *conn, const char *prog,
char *envblk, char *envp[], int fdin,
int fdout, const char *dir) {
pid_t pid;
const char *interp;
(void) envblk;
if ((pid = fork()) == -1) {
// Parent
send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
} else if (pid == 0) {
// Child
if (chdir(dir) != 0) {
cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
} else if (dup2(fdin, 0) == -1) {
cry(conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
} else if (dup2(fdout, 1) == -1) {
cry(conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
} else {
// Not redirecting stderr to stdout, to avoid output being littered
// with the error messages.
(void) close(fdin);
(void) close(fdout);
// After exec, all signal handlers are restored to their default values,
// with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
// implementation, SIGCHLD's handler will leave unchanged after exec
// if it was set to be ignored. Restore it to default action.
signal(SIGCHLD, SIG_DFL);
interp = conn->ctx->config[CGI_INTERPRETER];
if (interp == NULL) {
(void) execle(prog, prog, NULL, envp);
cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
} else {
(void) execle(interp, interp, prog, NULL, envp);
cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
strerror(ERRNO));
}
}
exit(EXIT_FAILURE);
}
return pid;
}
#endif // !NO_CGI
static int set_non_blocking_mode(SOCKET sock) {
int flags;
flags = fcntl(sock, F_GETFL, 0);
(void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
return 0;
}
int sq_get_bound_addresses(const struct sq_context *ctx, struct sockaddr_in ***addrs,
int *num_addrs) {
int n = ctx->num_listening_sockets;
int rc = 1;
int i;
struct sockaddr_in **addr_array = calloc(n, sizeof(struct sockaddr_in *));
if (addr_array == NULL) {
cry(fc(ctx), "%s: cannot allocate memory", __func__);
goto cleanup;
}
*addrs = addr_array;
for (i = 0; i < n; i++) {
addr_array[i] = malloc(sizeof(struct sockaddr_storage));
if (addr_array[i] == NULL) {
cry(fc(ctx), "%s: cannot allocate memory", __func__);
goto cleanup;
}
socklen_t len = sizeof(struct sockaddr_in *);
if (getsockname(ctx->listening_sockets[i].sock, (struct sockaddr*)addr_array[i],
&len) != 0) {
cry(fc(ctx), "%s: cannot get socket name: %s", __func__, strerror(errno));
goto cleanup;
}
}
*num_addrs = n;
return 0;
cleanup:
if (addr_array) {
for (i = 0; i < n; i++) {
free(addr_array[i]);
}
free(addr_array);
}
return rc;
}
// Write data to the IO channel - opened file descriptor, socket or SSL
// descriptor. Return number of bytes written.
static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
int64_t len) {
int64_t sent;
int n, k;
(void) ssl; // Get rid of warning
sent = 0;
while (sent < len) {
// How many bytes we send in this iteration
k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
#ifndef NO_SSL
if (ssl != NULL) {
n = SSL_write(ssl, buf + sent, k);
} else
#endif
if (fp != NULL) {
n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
if (ferror(fp))
n = -1;
} else {
RETRY_ON_EINTR(n, send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL));
}
if (n <= 0)
break;
sent += n;
}
return sent;
}
// Wait for either 'fd' or 'wakeup_fds' to have readable data.
static void wait_for_readable_or_wakeup(struct sq_context *ctx,
int fd, int timeout_ms) {
struct pollfd pfd[2];
pfd[0].fd = fd;
pfd[0].events = POLLIN;
pfd[1].fd = ctx->wakeup_fds[0];
pfd[1].events = POLLIN;
int poll_rc;
RETRY_ON_EINTR(poll_rc, poll(pfd, 2, timeout_ms));
}
// Read from IO channel - opened file descriptor, socket, or SSL descriptor.
// Return negative value on error, or number of bytes read on success.
static int pull(FILE *fp, struct sq_connection *conn, char *buf, int len) {
int nread;
if (fp != NULL) {
// Use read() instead of fread(), because if we're reading from the CGI
// pipe, fread() may block until IO buffer is filled up. We cannot afford
// to block and must pass all read bytes immediately to the client.
RETRY_ON_EINTR(nread, read(fileno(fp), buf, (size_t) len));
#ifndef NO_SSL
} else if (conn->ssl != NULL) {
nread = SSL_read(conn->ssl, buf, len);
#endif
} else {
RETRY_ON_EINTR(nread, recv(conn->client.sock, buf, (size_t) len, 0));
if (nread == -1 && errno != EAGAIN) {
cry(conn, "error reading: %s", strerror(errno));
}
}
return conn->ctx->stop_flag ? -1 : nread;
}
static int pull_all(FILE *fp, struct sq_connection *conn, char *buf, int len) {
int n, nread = 0;
while (len > 0 && conn->ctx->stop_flag == 0) {
n = pull(fp, conn, buf + nread, len);
if (n < 0) {
nread = n; // Propagate the error
break;
} else if (n == 0) {
break; // No more data to read
} else {
conn->consumed_content += n;
nread += n;
len -= n;
}
}
return nread;
}
int sq_read(struct sq_connection *conn, void *buf, size_t len) {
int n, buffered_len, nread;
const char *body;
// If Content-Length is not set, read until socket is closed
if (conn->consumed_content == 0 && conn->content_len == 0) {
conn->content_len = INT64_MAX;