This repository has been archived by the owner on Jan 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
http.c
2439 lines (2272 loc) · 78.5 KB
/
http.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
/*
* Pound - the reverse-proxy load-balancer
* Copyright (C) 2002-2010 Apsis GmbH
*
* This file is part of Pound.
*
* Pound is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Pound is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact information:
* Apsis GmbH
* P.O.Box
* 8707 Uetikon am See
* Switzerland
* EMail: [email protected]
*/
#include "pound.h"
/* HTTP error replies */
static char *h500 = "500 Internal Server Error",
*h501 = "501 Not Implemented",
*h503 = "503 Service Unavailable",
*h400 = "400 Bad Request",
*h414 = "414 Request URI too long", *h403 = "403 Request forbidden";
static char *err_response =
"HTTP/1.0 %s\r\nContent-Type: text/html\r\nContent-Length: %d\r\nExpires: now\r\nPragma: no-cache\r\nCache-control: no-cache,no-store\r\n\r\n%s";
/*
* Reply with an error
*/
static void err_reply(BIO * const c, const char *head, const char *txt)
{
BIO_printf(c, err_response, head, strlen(txt), txt);
BIO_flush(c);
return;
}
/*
* Reply with a redirect
*/
static void redirect_reply(BIO * const c, const char *url, const int code)
{
char rep[MAXBUF], cont[MAXBUF], *code_msg;
int i, j;
switch (code) {
case 301:
code_msg = "Moved Permanently";
break;
case 307:
code_msg = "Temporary Redirect";
break;
default:
code_msg = "Found";
break;
}
/*
* Make sure to return a safe version of the URL (otherwise CSRF becomes a possibility)
*/
snprintf(cont, sizeof(cont),
"<html><head><title>Redirect</title></head><body><h1>Redirect</h1><p>You should go to <a href=\"%s\">%s</a></p></body></html>",
url, url);
snprintf(rep, sizeof(rep),
"HTTP/1.0 %d %s\r\nLocation: %s\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n",
code, code_msg, url, strlen(cont));
BIO_write(c, rep, strlen(rep));
BIO_write(c, cont, strlen(cont));
BIO_flush(c);
return;
}
/*
* Read and write some binary data
*/
static int
copy_bin(BIO * const cl, BIO * const be, LONG cont, LONG * res_bytes,
const int no_write)
{
char buf[MAXBUF];
int res;
while (cont > L0) {
if ((res = BIO_read(cl, buf, cont > MAXBUF ? MAXBUF : cont)) < 0)
return -1;
else if (res == 0)
return -2;
if (!no_write)
if (BIO_write(be, buf, res) != res)
return -3;
cont -= res;
if (res_bytes)
*res_bytes += res;
}
if (!no_write)
if (BIO_flush(be) != 1)
return -4;
return 0;
}
/*
* Get a "line" from a BIO, strip the trailing newline, skip the input stream if buffer too small
* The result buffer is NULL terminated
* Return 0 on success
*/
static int
get_line(BIO * const in, char *const buf, const int bufsize, int *out_line_size)
{
char tmp;
int i, n_read;
// memset(buf, 0, bufsize);
*out_line_size = 0;
for (n_read = 0;;)
switch (BIO_gets(in, buf + n_read, bufsize - n_read - 1)) {
case -2:
/* BIO_gets not implemented */
return -1;
case 0:
case -1:
return 1;
default:
for (i = n_read; i < bufsize && buf[i]; i++)
if (buf[i] == '\n' || buf[i] == '\r') {
buf[i] = '\0';
*out_line_size = i;
return 0;
}
if (i < bufsize) {
n_read = i;
continue;
}
logmsg(LOG_NOTICE, "(%lx) line too long: %s", pthread_self(), buf);
/* skip rest of "line" */
tmp = '\0';
while (tmp != '\n')
if (BIO_read(in, &tmp, 1) != 1)
return 1;
break;
}
return 0;
}
/*
* Strip trailing CRLF
*/
static int strip_eol(char *lin)
{
while (*lin)
if (*lin == '\n' || (*lin == '\r' && *(lin + 1) == '\n')) {
*lin = '\0';
return 1;
} else
lin++;
return 0;
}
/*
* Copy chunked
*/
static int
copy_chunks(BIO * const cl, BIO * const be, LONG * res_bytes,
const int no_write, const LONG max_size)
{
char buf[MAXBUF];
LONG cont, tot_size;
regmatch_t matches[2];
int res, line_len = 0;
for (tot_size = 0L;;) {
if ((res = get_line(cl, buf, MAXBUF, &line_len)) < 0) {
logmsg(LOG_NOTICE, "(%lx) chunked read error: %s", pthread_self(),
strerror(errno));
return -1;
} else if (res > 0)
/* EOF */
return 0;
if (!regexec(&CHUNK_HEAD, buf, 2, matches, 0))
cont = STRTOL(buf, NULL, 16);
else {
/* not chunk header */
logmsg(LOG_NOTICE, "(%lx) bad chunk header <%s>: %s", pthread_self(), buf,
strerror(errno));
return -2;
}
if (!no_write)
if (BIO_printf(be, "%s\r\n", buf) <= 0) {
logmsg(LOG_NOTICE, "(%lx) error write chunked: %s", pthread_self(),
strerror(errno));
return -3;
}
tot_size += cont;
if (max_size > L0 && tot_size > max_size) {
logmsg(LOG_WARNING, "(%lx) chunk content too large", pthread_self);
return -4;
}
if (cont > L0) {
if (copy_bin(cl, be, cont, res_bytes, no_write)) {
if (errno)
logmsg(LOG_NOTICE, "(%lx) error copy chunk cont: %s", pthread_self(),
strerror(errno));
return -4;
}
} else
break;
/* final CRLF */
if ((res = get_line(cl, buf, MAXBUF, &line_len)) < 0) {
logmsg(LOG_NOTICE, "(%lx) error after chunk: %s", pthread_self(),
strerror(errno));
return -5;
} else if (res > 0) {
logmsg(LOG_NOTICE, "(%lx) unexpected EOF after chunk", pthread_self());
return -5;
}
if (buf[0])
logmsg(LOG_NOTICE, "(%lx) unexpected after chunk \"%s\"", pthread_self(),
buf);
if (!no_write)
if (BIO_printf(be, "%s\r\n", buf) <= 0) {
logmsg(LOG_NOTICE, "(%lx) error after chunk write: %s", pthread_self(),
strerror(errno));
return -6;
}
}
/* possibly trailing headers */
for (;;) {
if ((res = get_line(cl, buf, MAXBUF, &line_len)) < 0) {
logmsg(LOG_NOTICE, "(%lx) error post-chunk: %s", pthread_self(),
strerror(errno));
return -7;
} else if (res > 0)
break;
if (!no_write)
if (BIO_printf(be, "%s\r\n", buf) <= 0) {
logmsg(LOG_NOTICE, "(%lx) error post-chunk write: %s", pthread_self(),
strerror(errno));
return -8;
}
if (!buf[0])
break;
}
if (!no_write)
if (BIO_flush(be) != 1) {
logmsg(LOG_NOTICE, "(%lx) copy_chunks flush error: %s", pthread_self(),
strerror(errno));
return -4;
}
return 0;
}
static int err_to = -1;
typedef struct {
int timeout;
RENEG_STATE *reneg_state;
} BIO_ARG;
/*
* Time-out for client read/gets
* the SSL manual says not to do it, but it works well enough anyway...
*/
static long
bio_callback(BIO * const bio, const int cmd, const char *argp, int argi,
long argl, long ret)
{
BIO_ARG *bio_arg;
struct pollfd p;
int to, p_res, p_err;
if (cmd != BIO_CB_READ && cmd != BIO_CB_WRITE)
return ret;
/* a time-out already occured */
if ((bio_arg = (BIO_ARG *) BIO_get_callback_arg(bio)) == NULL)
return ret;
if ((to = bio_arg->timeout * 1000) < 0) {
errno = ETIMEDOUT;
return -1;
}
/* Renegotiations */
/* logmsg(LOG_NOTICE, "RENEG STATE %d", bio_arg->reneg_state==NULL?-1:*bio_arg->reneg_state); */
if (bio_arg->reneg_state != NULL && *bio_arg->reneg_state == RENEG_ABORT) {
logmsg(LOG_NOTICE, "REJECTING renegotiated session");
errno = ECONNABORTED;
return -1;
}
if (to == 0)
return ret;
for (;;) {
memset(&p, 0, sizeof(p));
BIO_get_fd(bio, &p.fd);
p.events = (cmd == BIO_CB_READ) ? (POLLIN | POLLPRI) : POLLOUT;
p_res = poll(&p, 1, to);
p_err = errno;
switch (p_res) {
case 1:
if (cmd == BIO_CB_READ) {
if ((p.revents & POLLIN) || (p.revents & POLLPRI))
/* there is readable data */
return ret;
else {
#ifdef EBUG
logmsg(LOG_WARNING, "(%lx) CALLBACK read 0x%04x poll: %s",
pthread_self(), p.revents, strerror(p_err));
#endif
errno = EIO;
}
} else {
if (p.revents & POLLOUT)
/* data can be written */
return ret;
else {
#ifdef EBUG
logmsg(LOG_WARNING, "(%lx) CALLBACK write 0x%04x poll: %s",
pthread_self(), p.revents, strerror(p_err));
#endif
errno = ECONNRESET;
}
}
return -1;
case 0:
/* timeout - mark the BIO as unusable for the future */
bio_arg->timeout = err_to;
#ifdef EBUG
logmsg(LOG_WARNING, "(%lx) CALLBACK timeout poll after %d secs: %s",
pthread_self(), to / 1000, strerror(p_err));
#endif
errno = ETIMEDOUT;
return 0;
default:
/* error */
if (p_err != EINTR) {
#ifdef EBUG
logmsg(LOG_WARNING, "(%lx) CALLBACK bad %d poll: %s",
pthread_self(), p_res, strerror(p_err));
#endif
return -2;
#ifdef EBUG
} else
logmsg(LOG_WARNING, "(%lx) CALLBACK interrupted %d poll: %s",
pthread_self(), p_res, strerror(p_err));
#else
}
#endif
}
}
}
/*
* Check if the file underlying a BIO is readable
*/
static int is_readable(BIO * const bio, const int to_wait)
{
struct pollfd p;
if (BIO_pending(bio) > 0)
return 1;
memset(&p, 0, sizeof(p));
BIO_get_fd(bio, &p.fd);
p.events = POLLIN | POLLPRI;
return (poll(&p, 1, to_wait * 1000) > 0);
}
static void free_headers(char **headers)
{
int i;
for (i = 0; i < MAXHEADERS; i++)
if (headers[i])
free(headers[i]);
free(headers);
return;
}
static char **get_headers(BIO * const in, BIO * const cl, const LISTENER * lstn)
{
char **headers, buf[MAXBUF];
int res, n, has_eol, line_len;
/* HTTP/1.1 allows leading CRLF */
memset(buf, 0, MAXBUF);
while ((res = BIO_gets(in, buf, MAXBUF - 1)) > 0) {
has_eol = strip_eol(buf);
if (buf[0])
break;
}
if (res <= 0) {
/* this is expected to occur only on client reads */
/* logmsg(LOG_NOTICE, "headers: bad starting read"); */
return NULL;
} else if (!has_eol) {
/* check for request length limit */
logmsg(LOG_WARNING, "(%lx) e414 headers: request URI too long",
pthread_self());
err_reply(cl, h414, lstn->err414);
return NULL;
}
if ((headers = (char **) calloc(MAXHEADERS, sizeof(char *))) == NULL) {
logmsg(LOG_WARNING, "(%lx) e500 headers: out of memory", pthread_self());
err_reply(cl, h500, lstn->err500);
return NULL;
}
if ((headers[0] = (char *) calloc(res + 2, sizeof(char))) == NULL) {
free_headers(headers);
logmsg(LOG_WARNING, "(%lx) e500 header: out of memory", pthread_self());
err_reply(cl, h500, lstn->err500);
return NULL;
}
// memset(headers[0], 0, MAXBUF);
strncpy(headers[0], buf, res);
for (n = 1; n < MAXHEADERS; n++) {
if (get_line(in, buf, MAXBUF, &line_len)) {
free_headers(headers);
logmsg(LOG_WARNING, "(%lx) e500 can't read header", pthread_self());
err_reply(cl, h500, lstn->err500);
return NULL;
}
if (!buf[0])
return headers;
if ((headers[n] = (char *) calloc(line_len + 2, sizeof(char))) == NULL) {
free_headers(headers);
logmsg(LOG_WARNING, "(%lx) e500 header: out of memory", pthread_self());
err_reply(cl, h500, lstn->err500);
return NULL;
}
// memset(headers[n], 0, MAXBUF);
strncpy(headers[n], buf, line_len);
}
free_headers(headers);
logmsg(LOG_NOTICE, "(%lx) e500 too many headers", pthread_self());
err_reply(cl, h500, lstn->err500);
return NULL;
}
#define LOG_TIME_SIZE 32
/*
* Apache log-file-style time format
*/
static void log_time(char *res)
{
time_t now;
struct tm *t_now, t_res;
now = time(NULL);
#ifdef HAVE_LOCALTIME_R
t_now = localtime_r(&now, &t_res);
#else
t_now = localtime(&now);
#endif
strftime(res, LOG_TIME_SIZE - 1, "%d/%b/%Y:%H:%M:%S %z", t_now);
return;
}
static double cur_time(void)
{
#ifdef HAVE_GETTIMEOFDAY
struct timeval tv;
struct timezone tz;
int sv_errno;
sv_errno = errno;
gettimeofday(&tv, &tz);
errno = sv_errno;
return tv.tv_sec * 1000000.0 + tv.tv_usec;
#else
return time(NULL) * 1000000.0;
#endif
}
#define LOG_BYTES_SIZE 32
/*
* Apache log-file-style number format
*/
static void log_bytes(char *res, const LONG cnt)
{
if (cnt > L0)
#ifdef HAVE_LONG_LONG_INT
snprintf(res, LOG_BYTES_SIZE - 1, "%lld", cnt);
#else
snprintf(res, LOG_BYTES_SIZE - 1, "%ld", cnt);
#endif
else
strcpy(res, "-");
return;
}
/* Cleanup code. This should really be in the pthread_cleanup_push, except for bugs in some implementations */
// if(count_backend->connections > 0)
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
#define clear_error()
#elif OPENSSL_VERSION_NUMBER >= 0x10000000L
#define clear_error() \
if(ssl != NULL) { ERR_clear_error(); ERR_remove_thread_state(NULL); }
#else
#define clear_error() \
if(ssl != NULL) { ERR_clear_error(); ERR_remove_state(0); }
#endif
#define clean_all() { \
if(flagCount) {decrease_backend_conn(cur_backend); } \
if(ssl != NULL) { BIO_ssl_shutdown(cl); } \
if(be != NULL) { BIO_flush(be); BIO_reset(be); BIO_free_all(be); be = NULL; } \
if(cl != NULL) { BIO_flush(cl); BIO_reset(cl); BIO_free_all(cl); cl = NULL; } \
if(x509 != NULL) { X509_free(x509); x509 = NULL; } \
waf_del_transaction(&modsec_transaction); \
if(waf_rules != NULL) { waf_memo_decrease(waf_rules); waf_memo_clean(waf_rules); } \
if(body_buff != NULL) {free(body_buff); body_buff = NULL; } \
clear_error(); \
}
void increase_backend_conn(BACKEND * backend)
{
int ret_val;
if (ret_val = pthread_mutex_lock(&backend->mut))
logmsg(LOG_WARNING, "increase_backend_conn() lock: %s", strerror(ret_val));
backend->connections++;
if (ret_val = pthread_mutex_unlock(&backend->mut))
logmsg(LOG_WARNING, "increase_backend_conn() unlock: %s",
strerror(ret_val));
}
void decrease_backend_conn(BACKEND * backend)
{
int ret_val;
if (ret_val = pthread_mutex_lock(&backend->mut))
logmsg(LOG_WARNING, "increase_backend_conn() lock: %s", strerror(ret_val));
backend->connections--;
if (ret_val = pthread_mutex_unlock(&backend->mut))
logmsg(LOG_WARNING, "increase_backend_conn() unlock: %s",
strerror(ret_val));
}
static int zcu_str_find_str(int *off_start, int *off_end, const char *ori_str,
int ori_len, const char *match_str, int match_len)
{
int i, flag = 0;
*off_start = -1;
*off_end = -1;
for (i = 0; i < ori_len && flag < match_len; i++) {
if (ori_str[i] == match_str[flag]) {
if (flag == 0)
*off_start = i;
flag++;
} else
flag = 0;
}
if (flag == 0)
return 0;
*off_end = *off_start + match_len;
return 1;
}
static int zcu_str_replace_str(char *buf, const char *ori_str, int ori_len,
const char *match_str, int match_len, char *replace_str,
int replace_len)
{
int offst = -1, offend = -1, offcopy = 0,
buf_len = ori_len - match_len + replace_len;
if (!zcu_str_find_str(&offst, &offend, ori_str, ori_len, match_str,
match_len)) {
return 0;
}
if (buf_len > ZCU_DEF_BUFFER_SIZE) {
logmsg(
LOG_ERR,
"String could not be replaced, the buffer size is not enought - %.*s",
ori_len, ori_str);
return 0;
}
if (offst != 0) {
memcpy(buf, ori_str, offst);
}
offcopy += offst;
memcpy(buf + offcopy, replace_str, replace_len);
if (offend != ori_len) {
offcopy += replace_len;
memcpy(buf + offcopy, ori_str + offend, ori_len - offend);
}
buf[buf_len] = '\0';
return 1;
}
char url_orig[MAXBUF] = { 0 };
/*
* handle an HTTP request
*/
void do_http(thr_arg * arg)
{
int cl_11, be_11, res, chunked, n, sock, no_cont, skip, conn_closed, force_10,
sock_proto, is_rpc, exp_cont, read_cl_body, is_ws;
int headers_num = 0;
#if WAF
int waf_code = 200;
WAF_ACTION waf_action = ALLOW;
WAF_RULESET_MEMO *waf_rules = NULL; // ruleset used for this transaction
Transaction *modsec_transaction = NULL;
#endif
int flagCount = 0;
LISTENER *lstn;
SERVICE *svc;
BACKEND *backend, *old_backend = NULL, *cur_backend;
struct addrinfo from_host, z_addr;
struct sockaddr_storage from_host_addr;
BIO *oldcl, *cl, *be, *bb, *b64;
X509 *x509;
char request[MAXBUF], response[MAXBUF], buf[MAXBUF], url[MAXBUF],
loc_path[MAXBUF], **headers, headers_ok[MAXHEADERS], v_host[MAXBUF],
referer[MAXBUF], u_agent[MAXBUF], u_name[MAXBUF], caddr[MAXADDRBUFF],
req_time[LOG_TIME_SIZE], s_res_bytes[LOG_BYTES_SIZE], *mh,
buf_log_tag[MAXBUF], h_xfwf[MAXBUF];
char *body_buff = NULL;
char ip_ori[MAXADDRBUFF], ip_dst[MAXADDRBUFF];
int port_ori, port_dst;
SSL *ssl, *be_ssl;
LONG cont, res_bytes;
regmatch_t matches[4];
struct linger l;
time_t exptime;
double start_req, end_req;
RENEG_STATE reneg_state;
BIO_ARG ba1, ba2;
reneg_state = RENEG_INIT;
ba1.reneg_state = &reneg_state;
ba2.reneg_state = &reneg_state;
ba1.timeout = 0;
ba2.timeout = 0;
from_host = ((thr_arg *) arg)->from_host;
memcpy(&from_host_addr, from_host.ai_addr, from_host.ai_addrlen);
from_host.ai_addr = (struct sockaddr *) &from_host_addr;
lstn = ((thr_arg *) arg)->lstn;
sock = ((thr_arg *) arg)->sock;
free(((thr_arg *) arg)->from_host.ai_addr);
free(arg);
if (lstn->allow_client_reneg)
reneg_state = RENEG_ALLOW;
n = 1;
setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &n, sizeof(n));
l.l_onoff = 1;
l.l_linger = 10;
setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &l, sizeof(l));
#ifdef TCP_LINGER2
n = 5;
setsockopt(sock, SOL_TCP, TCP_LINGER2, (void *) &n, sizeof(n));
#endif
n = 1;
setsockopt(sock, SOL_TCP, TCP_NODELAY, (void *) &n, sizeof(n));
cl = NULL;
be = NULL;
ssl = NULL;
x509 = NULL;
if ((cl = BIO_new_socket(sock, 1)) == NULL) {
logmsg(LOG_WARNING, "(%lx) BIO_new_socket failed", pthread_self());
shutdown(sock, 2);
close(sock);
return;
}
ba1.timeout = lstn->to;
BIO_set_callback_arg(cl, (char *) &ba1);
BIO_set_callback(cl, bio_callback);
if (lstn->ctx != NULL) {
if ((ssl = SSL_new(lstn->ctx->ctx)) == NULL) {
logmsg(LOG_WARNING, "(%lx) SSL_new: failed", pthread_self());
BIO_reset(cl);
BIO_free_all(cl);
return;
}
SSL_set_app_data(ssl, &reneg_state);
SSL_set_bio(ssl, cl, cl);
if ((bb = BIO_new(BIO_f_ssl())) == NULL) {
logmsg(LOG_WARNING, "(%lx) BIO_new(Bio_f_ssl()) failed", pthread_self());
BIO_reset(cl);
BIO_free_all(cl);
return;
}
BIO_set_ssl(bb, ssl, BIO_CLOSE);
BIO_set_ssl_mode(bb, 0);
oldcl = cl;
cl = bb;
if (BIO_do_handshake(cl) <= 0) {
if ((ERR_GET_REASON(ERR_peek_error()) == SSL_R_HTTP_REQUEST)
&& (ERR_GET_LIB(ERR_peek_error()) == ERR_LIB_SSL)) {
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
if (lstn->nossl_redir) {
logmsg(LOG_NOTICE, "(%lx) errNoSsl from %s redirecting to \"%s\"",
pthread_self(), caddr, lstn->nossl_url);
redirect_reply(oldcl, lstn->nossl_url, lstn->nossl_redir);
} else {
logmsg(LOG_NOTICE, "(%lx) errNoSsl from %s sending error",
pthread_self(), caddr);
err_reply(oldcl, h400, lstn->errnossl);
}
}
BIO_reset(cl);
BIO_free_all(cl);
return;
} else {
if ((x509 = SSL_get_peer_certificate(ssl)) != NULL && lstn->clnt_check < 3
&& SSL_get_verify_result(ssl) != X509_V_OK) {
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
logmsg(LOG_NOTICE, "Bad certificate from %s", caddr);
X509_free(x509);
BIO_reset(cl);
BIO_free_all(cl);
return;
}
}
} else {
x509 = NULL;
}
cur_backend = NULL;
if ((bb = BIO_new(BIO_f_buffer())) == NULL) {
logmsg(LOG_WARNING, "(%lx) BIO_new(buffer) failed", pthread_self());
if (x509 != NULL)
X509_free(x509);
BIO_reset(cl);
BIO_free_all(cl);
return;
}
BIO_set_close(cl, BIO_CLOSE);
BIO_set_buffer_size(cl, MAXBUF);
cl = BIO_push(bb, cl);
#if WAF
pthread_mutex_lock(&waf_rules_memo_mtx);
if (waf_rules_memo && waf_rules_memo->rules) {
waf_rules = waf_rules_memo;
waf_memo_increase(waf_rules);
}
pthread_mutex_unlock(&waf_rules_memo_mtx);
#endif
for (cl_11 = be_11 = 0;;) {
memset(url_orig, '\0', MAXBUF);
res_bytes = L0;
is_rpc = -1;
is_ws = 0;
v_host[0] = referer[0] = u_agent[0] = u_name[0] = h_xfwf[0] = '\0';
conn_closed = 0;
for (n = 0; n < MAXHEADERS; n++)
headers_ok[n] = 1;
if ((headers = get_headers(cl, cl, lstn)) == NULL) {
if (!cl_11) {
if (errno) {
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
logmsg(LOG_NOTICE, "(%lx) error read from %s: %s", pthread_self(),
caddr, strerror(errno));
/* err_reply(cl, h500, lstn->err500); */
}
}
clean_all();
return;
}
memset(req_time, 0, LOG_TIME_SIZE);
start_req = cur_time();
log_time(req_time);
/* check for correct request */
strncpy(request, headers[0], MAXBUF);
if (!regexec(&lstn->verb, request, 3, matches, 0)) {
no_cont =
!strncasecmp(request + matches[1].rm_so, "HEAD",
matches[1].rm_eo - matches[1].rm_so);
if (!strncasecmp
(request + matches[1].rm_so, "RPC_IN_DATA",
matches[1].rm_eo - matches[1].rm_so))
is_rpc = 1;
else
if (!strncasecmp
(request + matches[1].rm_so, "RPC_OUT_DATA",
matches[1].rm_eo - matches[1].rm_so))
is_rpc = 0;
else
if (!strncasecmp
(request + matches[1].rm_so, "GET",
matches[1].rm_eo - matches[1].rm_so))
is_ws |= 0x1;
} else {
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
logmsg(LOG_WARNING, "(%lx) e501 bad request \"%s\" from %s",
pthread_self(), request, caddr);
err_reply(cl, h501, lstn->err501);
free_headers(headers);
clean_all();
return;
}
cl_11 = (request[strlen(request) - 1] == '1');
strncpy(url_orig, request + matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so);
n =
cpURL(url, request + matches[2].rm_so,
matches[2].rm_eo - matches[2].rm_so);
if (n != strlen(url)) {
/* the URL probably contained a %00 aka NULL - which we don't allow */
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
logmsg(LOG_NOTICE, "(%lx) e501 URL \"%s\" (contains NULL) from %s",
pthread_self(), url, caddr);
err_reply(cl, h501, lstn->err501);
free_headers(headers);
clean_all();
return;
}
if (lstn->has_pat && regexec(&lstn->url_pat, url, 0, NULL, 0)) {
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
logmsg(LOG_NOTICE, "(%lx) e501 bad URL \"%s\" from %s", pthread_self(),
url, caddr);
err_reply(cl, h501, lstn->err501);
free_headers(headers);
clean_all();
return;
}
/* check other headers */
for (chunked = 0, cont = L_1, n = 1, exp_cont = 0;
n < MAXHEADERS && headers[n]; n++) {
/* no overflow - see check_header for details */
switch (check_header(headers[n], buf)) {
case HEADER_HOST:
strcpy(v_host, buf);
break;
case HEADER_REFERER:
strcpy(referer, buf);
break;
case HEADER_USER_AGENT:
strcpy(u_agent, buf);
break;
case HEADER_CONNECTION:
if (!strcasecmp("close", buf))
conn_closed = 1;
/* Connection: upgrade */
else if (!regexec(&CONN_UPGRD, buf, 0, NULL, 0))
is_ws |= 0x2;
break;
case HEADER_UPGRADE:
if (!strcasecmp("websocket", buf))
is_ws |= 0x4;
case HEADER_TRANSFER_ENCODING:
if (cont >= L0)
headers_ok[n] = 0;
else if (!strcasecmp("chunked", buf))
if (chunked)
headers_ok[n] = 0;
else
chunked = 1;
break;
case HEADER_CONTENT_LENGTH:
if (chunked || cont >= 0L)
headers_ok[n] = 0;
else {
if ((cont = ATOL(buf)) < 0L)
headers_ok[n] = 0;
if (is_rpc == 1 && (cont < 0x20000L || cont > 0x80000000L))
is_rpc = -1;
}
break;
case HEADER_EXPECT:
// By Zen Load Balancer: Supported "Expect: 100-continue" headers
if (!strcasecmp("100-continue", buf)) {
if (ignore_100 == 1) {
headers_ok[n] = 0;
} else {
exp_cont = 1;
}
}
break;
case HEADER_ILLEGAL:
if (lstn->log_level > 0) {
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
logmsg(LOG_NOTICE, "(%lx) bad header from %s (%s)", pthread_self(),
caddr, headers[n]);
}
headers_ok[n] = 0;
break;
case HEADER_X_FORWARDED_FOR:
strcpy(h_xfwf, buf);
headers_ok[n] = 0;
break;
}
if (headers_ok[n] && lstn->head_off) {
/* maybe header to be removed */
MATCHER *m;
for (m = lstn->head_off; m; m = m->next)
if (!(headers_ok[n] = regexec(&m->pat, headers[n], 0, NULL, 0)))
break;
}
/* get User name */
if (!regexec(&AUTHORIZATION, headers[n], 2, matches, 0)) {
int inlen;
if ((bb = BIO_new(BIO_s_mem())) == NULL) {
logmsg(LOG_WARNING, "(%lx) Can't alloc BIO_s_mem", pthread_self());
continue;
}
if ((b64 = BIO_new(BIO_f_base64())) == NULL) {
logmsg(LOG_WARNING, "(%lx) Can't alloc BIO_f_base64", pthread_self());
BIO_free(bb);
continue;
}
b64 = BIO_push(b64, bb);
BIO_write(bb, headers[n] + matches[1].rm_so,
matches[1].rm_eo - matches[1].rm_so);
BIO_write(bb, "\n", 1);
if ((inlen = BIO_read(b64, buf, MAXBUF - 1)) <= 0) {
logmsg(LOG_WARNING, "(%lx) Can't read BIO_f_base64", pthread_self());
BIO_free_all(b64);
continue;
}
BIO_free_all(b64);
if ((mh = strchr(buf, ':')) == NULL) {
logmsg(LOG_WARNING, "(%lx) Unknown authentication", pthread_self());
continue;
}
*mh = '\0';
strcpy(u_name, buf);
}
}
// number of headers
headers_num = n;
/* possibly limited request size */
if (lstn->max_req > L0 && cont > L0 && cont > lstn->max_req && is_rpc != 1) {
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
logmsg(LOG_NOTICE, "(%lx) e501 request too large (%ld) from %s",
pthread_self(), cont, caddr);
err_reply(cl, h501, lstn->err501);
free_headers(headers);
clean_all();
return;
}
if (be != NULL) {
if (is_readable(be, 0)) {
/* The only way it's readable is if it's at EOF, so close it! */
BIO_reset(be);
BIO_free_all(be);
be = NULL;
}
}
/* check that the requested URL still fits the old back-end (if any) */
if ((svc = get_service(lstn, url, &headers[1])) == NULL) {
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
logmsg(LOG_NOTICE, "(%lx) e503 no service \"%s\" from %s %s",
pthread_self(), request, caddr, v_host[0] ? v_host : "-");
err_reply(cl, h503, lstn->err503);
free_headers(headers);
clean_all();
return;
}
/* get a backend of the service */
if ((backend =
get_backend(svc, &from_host, url, &headers[1],
lstn->log_level)) == NULL) {
addr2str(caddr, MAXADDRBUFF - 1, &from_host, 1);
logmsg(LOG_NOTICE, "service %s, (%lx) e503 no back-end \"%s\" from %s %s",
svc->name, pthread_self(), request, caddr,
v_host[0] ? v_host : "-");