-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
http_filters.c
2350 lines (2104 loc) · 80.7 KB
/
http_filters.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
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* http_filter.c --- HTTP routines which either filters or deal with filters.
*/
#include "apr.h"
#include "apr_strings.h"
#include "apr_buckets.h"
#include "apr_lib.h"
#include "apr_signal.h"
#define APR_WANT_STDIO /* for sscanf */
#define APR_WANT_STRFUNC
#define APR_WANT_MEMFUNC
#include "apr_want.h"
#include "util_filter.h"
#include "ap_config.h"
#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_protocol.h"
#include "http_main.h"
#include "http_request.h"
#include "http_vhost.h"
#include "http_connection.h"
#include "http_log.h" /* For errors detected in basic auth common
* support code... */
#include "apr_date.h" /* For apr_date_parse_http and APR_DATE_BAD */
#include "util_charset.h"
#include "util_ebcdic.h"
#include "util_time.h"
#include "mod_core.h"
#if APR_HAVE_STDARG_H
#include <stdarg.h>
#endif
#if APR_HAVE_UNISTD_H
#include <unistd.h>
#endif
APLOG_USE_MODULE(http);
static apr_bucket *create_trailers_bucket(request_rec *r, apr_bucket_alloc_t *bucket_alloc);
static apr_bucket *create_response_bucket(request_rec *r, apr_bucket_alloc_t *bucket_alloc);
static void merge_response_headers(request_rec *r);
typedef struct http_filter_ctx
{
apr_off_t remaining;
apr_off_t limit;
apr_off_t limit_used;
apr_int32_t chunk_used;
apr_int32_t chunk_bws;
apr_int32_t chunkbits;
enum
{
BODY_NONE, /* streamed data */
BODY_LENGTH, /* data constrained by content length */
BODY_CHUNK, /* chunk expected */
BODY_CHUNK_PART, /* chunk digits */
BODY_CHUNK_EXT, /* chunk extension */
BODY_CHUNK_CR, /* got space(s) after digits, expect [CR]LF or ext */
BODY_CHUNK_LF, /* got CR after digits or ext, expect LF */
BODY_CHUNK_DATA, /* data constrained by chunked encoding */
BODY_CHUNK_END, /* chunked data terminating CRLF */
BODY_CHUNK_END_LF, /* got CR after data, expect LF */
BODY_CHUNK_TRAILER /* trailers */
} state;
unsigned int at_eos:1,
seen_data:1;
} http_ctx_t;
/**
* Parse a chunk line with optional extension, detect overflow.
* There are several error cases:
* 1) If the chunk link is misformatted, APR_EINVAL is returned.
* 2) If the conversion would require too many bits, APR_EGENERAL is returned.
* 3) If the conversion used the correct number of bits, but an overflow
* caused only the sign bit to flip, then APR_ENOSPC is returned.
* A negative chunk length always indicates an overflow error.
*/
static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer,
apr_size_t len, int linelimit, int strict)
{
apr_size_t i = 0;
while (i < len) {
char c = buffer[i];
ap_xlate_proto_from_ascii(&c, 1);
/* handle CRLF after the chunk */
if (ctx->state == BODY_CHUNK_END
|| ctx->state == BODY_CHUNK_END_LF) {
if (c == LF) {
if (strict && (ctx->state != BODY_CHUNK_END_LF)) {
/*
* CR missing before LF.
*/
return APR_EINVAL;
}
ctx->state = BODY_CHUNK;
}
else if (c == CR && ctx->state == BODY_CHUNK_END) {
ctx->state = BODY_CHUNK_END_LF;
}
else {
/*
* CRLF expected.
*/
return APR_EINVAL;
}
i++;
continue;
}
/* handle start of the chunk */
if (ctx->state == BODY_CHUNK) {
if (!apr_isxdigit(c)) {
/*
* Detect invalid character at beginning. This also works for
* empty chunk size lines.
*/
return APR_EINVAL;
}
else {
ctx->state = BODY_CHUNK_PART;
}
ctx->remaining = 0;
/* The maximum number of bits that can be handled in a
* chunk size is in theory sizeof(apr_off_t)*8-1 since
* off_t is signed, but use -4 to avoid undefined
* behaviour when bitshifting left. */
ctx->chunkbits = sizeof(apr_off_t) * 8 - 4;
ctx->chunk_used = 0;
ctx->chunk_bws = 0;
}
if (c == LF) {
if (strict && (ctx->state != BODY_CHUNK_LF)) {
/*
* CR missing before LF.
*/
return APR_EINVAL;
}
if (ctx->remaining) {
ctx->state = BODY_CHUNK_DATA;
}
else {
ctx->state = BODY_CHUNK_TRAILER;
}
}
else if (ctx->state == BODY_CHUNK_LF) {
/*
* LF expected.
*/
return APR_EINVAL;
}
else if (c == CR) {
ctx->state = BODY_CHUNK_LF;
}
else if (c == ';') {
ctx->state = BODY_CHUNK_EXT;
}
else if (ctx->state == BODY_CHUNK_EXT) {
/*
* Control chars (excluding tabs) are invalid.
* TODO: more precisely limit input
*/
if (c != '\t' && apr_iscntrl(c)) {
return APR_EINVAL;
}
}
else if (c == ' ' || c == '\t') {
/* This allows limited BWS (or 'implied *LWS' in RFC2616
* terms) between chunk-size and '[chunk-ext] CRLF'. This
* is not allowed by RFC7230/9112 though servers have been
* seen which emit spaces here. The code previously (and
* mistakenly?) referenced the 7230 errata concerning BWS
* *within* chunk-ext, but the conditional above is
* followed during chunk-ext (state BODY_CHUNK_EXT):
* https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4667
* See also: https://github.com/squid-cache/squid/pull/1914
*/
ctx->state = BODY_CHUNK_CR;
if (++ctx->chunk_bws > 10) {
return APR_EINVAL;
}
}
else if (ctx->state == BODY_CHUNK_CR) {
/*
* ';', CR or LF expected.
*/
return APR_EINVAL;
}
else if (ctx->state == BODY_CHUNK_PART) {
int xvalue;
/* ignore leading zeros */
if (!ctx->remaining && c == '0') {
i++;
continue;
}
ctx->chunkbits -= 4;
if (ctx->chunkbits < 0) {
/* overflow */
return APR_ENOSPC;
}
if (c >= '0' && c <= '9') {
xvalue = c - '0';
}
else if (c >= 'A' && c <= 'F') {
xvalue = c - 'A' + 0xa;
}
else if (c >= 'a' && c <= 'f') {
xvalue = c - 'a' + 0xa;
}
else {
/* bogus character */
return APR_EINVAL;
}
ctx->remaining = (ctx->remaining << 4) | xvalue;
if (ctx->remaining < 0) {
/* Overflow - should be unreachable since the
* chunkbits limit will be reached first. */
return APR_ENOSPC;
}
}
else {
/* Should not happen */
return APR_EGENERAL;
}
i++;
}
/* sanity check */
ctx->chunk_used += len;
if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) {
return APR_ENOSPC;
}
return APR_SUCCESS;
}
static apr_status_t read_chunked_trailers(http_ctx_t *ctx, ap_filter_t *f,
apr_bucket_brigade *b)
{
int rv;
apr_bucket *e;
request_rec *r = f->r;
apr_table_t *trailers;
apr_table_t *saved_headers_in = r->headers_in;
int saved_status = r->status;
trailers = apr_table_make(r->pool, 5);
r->status = HTTP_OK;
r->headers_in = trailers;
ap_get_mime_headers(r);
r->headers_in = saved_headers_in;
if (r->status == HTTP_OK) {
r->status = saved_status;
if (!apr_is_empty_table(trailers)) {
e = ap_bucket_headers_create(trailers, r->pool, b->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
}
e = apr_bucket_eos_create(f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
ctx->at_eos = 1;
rv = APR_SUCCESS;
}
else {
const char *error_notes = apr_table_get(r->notes,
"error-notes");
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02656)
"Error while reading HTTP trailer: %i%s%s",
r->status, error_notes ? ": " : "",
error_notes ? error_notes : "");
rv = APR_EINVAL;
}
return rv;
}
typedef struct h1_in_ctx_t
{
unsigned int at_trailers:1;
unsigned int at_eos:1;
unsigned int seen_data:1;
} h1_in_ctx_t;
/* This is the HTTP_INPUT filter for HTTP requests and responses from
* proxied servers (mod_proxy). It handles chunked and content-length
* bodies. This can only be inserted/used after the headers
* are successfully parsed.
*/
apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b,
ap_input_mode_t mode, apr_read_type_e block,
apr_off_t readbytes)
{
apr_bucket *e, *next;
h1_in_ctx_t *ctx = f->ctx;
request_rec *r = f->r;
apr_status_t rv;
if (!ctx) {
f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
}
/* Since we're about to read data, send 100-Continue if needed.
* Only valid on chunked and C-L bodies where the C-L is > 0.
*
* If the read is to be nonblocking though, the caller may not want to
* handle this just now (e.g. mod_proxy_http), and is prepared to read
* nothing if the client really waits for 100 continue, so we don't
* send it now and wait for later blocking read.
*
* In any case, even if r->expecting remains set at the end of the
* request handling, ap_set_keepalive() will finally do the right
* thing (i.e. "Connection: close" the connection).
*/
if (block == APR_BLOCK_READ
&& r->expecting_100 && r->proto_num >= HTTP_VERSION(1,1)
&& !(ctx->at_eos || r->eos_sent || r->bytes_sent)) {
if (!ap_is_HTTP_SUCCESS(r->status)) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"ap_http_in_filter: status != OK, not sending 100-continue");
ctx->at_eos = 1; /* send EOS below */
}
else if (!ctx->seen_data) {
int saved_status = r->status;
const char *saved_status_line = r->status_line;
ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
"ap_http_in_filter: sending 100-continue");
r->status = HTTP_CONTINUE;
r->status_line = NULL;
ap_send_interim_response(r, 0);
AP_DEBUG_ASSERT(!r->expecting_100);
r->status_line = saved_status_line;
r->status = saved_status;
}
else {
/* https://tools.ietf.org/html/rfc7231#section-5.1.1
* A server MAY omit sending a 100 (Continue) response if it
* has already received some or all of the message body for
* the corresponding request [...]
*/
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(10260)
"request body already/partly received while "
"100-continue is expected, omit sending interim "
"response");
r->expecting_100 = 0;
}
}
/* sanity check in case we're read twice */
if (ctx->at_eos) {
e = apr_bucket_eos_create(f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
rv = APR_SUCCESS;
goto cleanup;
}
rv = ap_get_brigade(f->next, b, mode, block, readbytes);
if (APR_SUCCESS == rv) {
for (e = APR_BRIGADE_FIRST(b);
e != APR_BRIGADE_SENTINEL(b);
e = next)
{
next = APR_BUCKET_NEXT(e);
if (!APR_BUCKET_IS_METADATA(e)) {
if (e->length != 0) {
ctx->seen_data = 1;
}
if (ctx->at_trailers) {
/* DATA after trailers? Someone smuggling something? */
rv = AP_FILTER_ERROR;
goto cleanup;
}
continue;
}
if (AP_BUCKET_IS_HEADERS(e)) {
/* trailers */
ap_bucket_headers * hdrs = e->data;
/* Allow multiple HEADERS buckets carrying trailers here,
* will not happen from HTTP/1.x and current H2 implementation,
* but is an option. */
ctx->at_trailers = 1;
if (!apr_is_empty_table(hdrs->headers)) {
r->trailers_in = apr_table_overlay(r->pool, r->trailers_in, hdrs->headers);
}
apr_bucket_delete(e);
}
if (APR_BUCKET_IS_EOS(e)) {
ctx->at_eos = 1;
if (!apr_is_empty_table(r->trailers_in)) {
core_server_config *conf = ap_get_module_config(
r->server->module_config, &core_module);
if (conf->merge_trailers == AP_MERGE_TRAILERS_ENABLE) {
r->headers_in = apr_table_overlay(r->pool, r->headers_in, r->trailers_in);
}
}
goto cleanup;
}
}
}
cleanup:
return rv;
}
apr_status_t ap_h1_body_in_filter(ap_filter_t *f, apr_bucket_brigade *b,
ap_input_mode_t mode, apr_read_type_e block,
apr_off_t readbytes)
{
core_server_config *conf =
(core_server_config *) ap_get_module_config(f->r->server->module_config,
&core_module);
int strict = (conf->http_conformance != AP_HTTP_CONFORMANCE_UNSAFE);
apr_bucket *e;
http_ctx_t *ctx = f->ctx;
apr_status_t rv;
int again;
/* just get out of the way of things we don't want. */
if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE) {
return ap_get_brigade(f->next, b, mode, block, readbytes);
}
if (!ctx) {
const char *tenc, *lenp;
f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
ctx->state = BODY_NONE;
/* LimitRequestBody does not apply to proxied responses.
* Consider implementing this check in its own filter.
* Would adding a directive to limit the size of proxied
* responses be useful?
*/
if (f->r->proxyreq != PROXYREQ_RESPONSE) {
ctx->limit = ap_get_limit_req_body(f->r);
}
else {
ctx->limit = 0;
}
tenc = apr_table_get(f->r->headers_in, "Transfer-Encoding");
lenp = apr_table_get(f->r->headers_in, "Content-Length");
if (tenc) {
if (ap_is_chunked(f->r->pool, tenc)) {
ctx->state = BODY_CHUNK;
}
else if (f->r->proxyreq == PROXYREQ_RESPONSE) {
/* http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-23
* Section 3.3.3.3: "If a Transfer-Encoding header field is
* present in a response and the chunked transfer coding is not
* the final encoding, the message body length is determined by
* reading the connection until it is closed by the server."
*/
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(02555)
"Unknown Transfer-Encoding: %s; "
"using read-until-close", tenc);
tenc = NULL;
}
else {
/* Something that isn't a HTTP request, unless some future
* edition defines new transfer encodings, is unsupported.
*/
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01585)
"Unknown Transfer-Encoding: %s", tenc);
ap_die(HTTP_NOT_IMPLEMENTED, f->r);
return APR_EGENERAL;
}
lenp = NULL;
}
if (lenp) {
ctx->state = BODY_LENGTH;
/* Protects against over/underflow, non-digit chars in the
* string, leading plus/minus signs, trailing characters and
* a negative number.
*/
if (!ap_parse_strict_length(&ctx->remaining, lenp)) {
ctx->remaining = 0;
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01587)
"Invalid Content-Length");
return APR_EINVAL;
}
/* If we have a limit in effect and we know the C-L ahead of
* time, stop it here if it is invalid.
*/
if (ctx->limit && ctx->limit < ctx->remaining) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01588)
"Requested content-length of %" APR_OFF_T_FMT
" is larger than the configured limit"
" of %" APR_OFF_T_FMT, ctx->remaining, ctx->limit);
return APR_ENOSPC;
}
}
/* If we don't have a request entity indicated by the headers, EOS.
* (BODY_NONE is a valid intermediate state due to trailers,
* but it isn't a valid starting state.)
*
* RFC 2616 Section 4.4 note 5 states that connection-close
* is invalid for a request entity - request bodies must be
* denoted by C-L or T-E: chunked.
*
* Note that since the proxy uses this filter to handle the
* proxied *response*, proxy responses MUST be exempt.
*/
if (ctx->state == BODY_NONE && f->r->proxyreq != PROXYREQ_RESPONSE) {
ctx->at_eos = 1; /* send EOS below */
}
}
/* sanity check in case we're read twice */
if (ctx->at_eos) {
e = apr_bucket_eos_create(f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
return APR_SUCCESS;
}
do {
apr_brigade_cleanup(b);
again = 0; /* until further notice */
/* read and handle the brigade */
switch (ctx->state) {
case BODY_CHUNK:
case BODY_CHUNK_PART:
case BODY_CHUNK_EXT:
case BODY_CHUNK_CR:
case BODY_CHUNK_LF:
case BODY_CHUNK_END:
case BODY_CHUNK_END_LF: {
rv = ap_get_brigade(f->next, b, AP_MODE_GETLINE, block, 0);
/* for timeout */
if (block == APR_NONBLOCK_READ
&& ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b))
|| (APR_STATUS_IS_EAGAIN(rv)))) {
return APR_EAGAIN;
}
if (rv == APR_EOF) {
return APR_INCOMPLETE;
}
if (rv != APR_SUCCESS) {
return rv;
}
e = APR_BRIGADE_FIRST(b);
while (e != APR_BRIGADE_SENTINEL(b)) {
const char *buffer;
apr_size_t len;
if (!APR_BUCKET_IS_METADATA(e)) {
rv = apr_bucket_read(e, &buffer, &len, APR_BLOCK_READ);
if (rv == APR_SUCCESS) {
if (len > 0) {
ctx->seen_data = 1;
}
rv = parse_chunk_size(ctx, buffer, len,
f->r->server->limit_req_fieldsize, strict);
}
if (rv != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, rv, f->r, APLOGNO(01590)
"Error reading/parsing chunk %s ",
(APR_ENOSPC == rv) ? "(overflow)" : "");
return rv;
}
}
apr_bucket_delete(e);
e = APR_BRIGADE_FIRST(b);
}
again = 1; /* come around again */
if (ctx->state == BODY_CHUNK_TRAILER) {
/* Treat UNSET as DISABLE - trailers aren't merged by default */
return read_chunked_trailers(ctx, f, b);
}
break;
}
case BODY_NONE:
case BODY_LENGTH:
case BODY_CHUNK_DATA: {
/* Ensure that the caller can not go over our boundary point. */
if (ctx->state != BODY_NONE && ctx->remaining < readbytes) {
readbytes = ctx->remaining;
}
if (readbytes > 0) {
apr_off_t totalread;
rv = ap_get_brigade(f->next, b, mode, block, readbytes);
/* for timeout */
if (block == APR_NONBLOCK_READ
&& ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b))
|| (APR_STATUS_IS_EAGAIN(rv)))) {
return APR_EAGAIN;
}
if (rv == APR_EOF && ctx->state != BODY_NONE
&& ctx->remaining > 0) {
return APR_INCOMPLETE;
}
if (rv != APR_SUCCESS) {
return rv;
}
/* How many bytes did we just read? */
apr_brigade_length(b, 0, &totalread);
if (totalread > 0) {
ctx->seen_data = 1;
}
/* If this happens, we have a bucket of unknown length. Die because
* it means our assumptions have changed. */
AP_DEBUG_ASSERT(totalread >= 0);
if (ctx->state != BODY_NONE) {
ctx->remaining -= totalread;
if (ctx->remaining > 0) {
e = APR_BRIGADE_LAST(b);
if (APR_BUCKET_IS_EOS(e)) {
apr_bucket_delete(e);
return APR_INCOMPLETE;
}
}
else if (ctx->state == BODY_CHUNK_DATA) {
/* next chunk please */
ctx->state = BODY_CHUNK_END;
ctx->chunk_used = 0;
}
}
/* We have a limit in effect. */
if (ctx->limit) {
/* FIXME: Note that we might get slightly confused on
* chunked inputs as we'd need to compensate for the chunk
* lengths which may not really count. This seems to be up
* for interpretation.
*/
ctx->limit_used += totalread;
if (ctx->limit < ctx->limit_used) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r,
APLOGNO(01591) "Read content length of "
"%" APR_OFF_T_FMT " is larger than the "
"configured limit of %" APR_OFF_T_FMT,
ctx->limit_used, ctx->limit);
return APR_ENOSPC;
}
}
}
/* If we have no more bytes remaining on a C-L request,
* save the caller a round trip to discover EOS.
*/
if (ctx->state == BODY_LENGTH && ctx->remaining == 0) {
e = apr_bucket_eos_create(f->c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
ctx->at_eos = 1;
}
break;
}
case BODY_CHUNK_TRAILER: {
rv = ap_get_brigade(f->next, b, mode, block, readbytes);
/* for timeout */
if (block == APR_NONBLOCK_READ
&& ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b))
|| (APR_STATUS_IS_EAGAIN(rv)))) {
return APR_EAGAIN;
}
if (rv != APR_SUCCESS) {
return rv;
}
break;
}
default: {
/* Should not happen */
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(02901)
"Unexpected body state (%i)", (int)ctx->state);
return APR_EGENERAL;
}
}
} while (again);
return APR_SUCCESS;
}
struct check_header_ctx {
request_rec *r;
int strict;
};
/* check a single header, to be used with apr_table_do() */
static int check_header(struct check_header_ctx *ctx,
const char *name, const char **val)
{
const char *pos, *end;
char *dst = NULL;
if (name[0] == '\0') {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, APLOGNO(02428)
"Empty response header name, aborting request");
return 0;
}
if (ctx->strict) {
end = ap_scan_http_token(name);
}
else {
end = ap_scan_vchar_obstext(name);
}
if (*end) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, APLOGNO(02429)
"Response header name '%s' contains invalid "
"characters, aborting request",
name);
return 0;
}
for (pos = *val; *pos; pos = end) {
end = ap_scan_http_field_content(pos);
if (*end) {
if (end[0] != CR || end[1] != LF || (end[2] != ' ' &&
end[2] != '\t')) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, APLOGNO(02430)
"Response header '%s' value of '%s' contains "
"invalid characters, aborting request",
name, pos);
return 0;
}
if (!dst) {
*val = dst = apr_palloc(ctx->r->pool, strlen(*val) + 1);
}
}
if (dst) {
memcpy(dst, pos, end - pos);
dst += end - pos;
if (*end) {
/* skip folding and replace with a single space */
end += 3 + strspn(end + 3, "\t ");
*dst++ = ' ';
}
}
}
if (dst) {
*dst = '\0';
}
return 1;
}
static int check_headers_table(apr_table_t *t, struct check_header_ctx *ctx)
{
const apr_array_header_t *headers = apr_table_elts(t);
apr_table_entry_t *header;
int i;
for (i = 0; i < headers->nelts; ++i) {
header = &APR_ARRAY_IDX(headers, i, apr_table_entry_t);
if (!header->key) {
continue;
}
if (!check_header(ctx, header->key, (const char **)&header->val)) {
return 0;
}
}
return 1;
}
/**
* Check headers for HTTP conformance
* @return 1 if ok, 0 if bad
*/
static APR_INLINE int check_headers(request_rec *r)
{
struct check_header_ctx ctx;
core_server_config *conf =
ap_get_core_module_config(r->server->module_config);
const char *val;
if ((val = apr_table_get(r->headers_out, "Transfer-Encoding"))) {
if (apr_table_get(r->headers_out, "Content-Length")) {
apr_table_unset(r->headers_out, "Content-Length");
r->connection->keepalive = AP_CONN_CLOSE;
}
if (!ap_is_chunked(r->pool, val)) {
r->connection->keepalive = AP_CONN_CLOSE;
return 0;
}
}
ctx.r = r;
ctx.strict = (conf->http_conformance != AP_HTTP_CONFORMANCE_UNSAFE);
return check_headers_table(r->headers_out, &ctx) &&
check_headers_table(r->err_headers_out, &ctx);
}
static int check_headers_recursion(request_rec *r)
{
void *check = NULL;
apr_pool_userdata_get(&check, "check_headers_recursion", r->pool);
if (check) {
return 1;
}
apr_pool_userdata_setn("true", "check_headers_recursion", NULL, r->pool);
return 0;
}
typedef struct header_struct {
apr_pool_t *pool;
apr_bucket_brigade *bb;
} header_struct;
/* Send a single HTTP header field to the client. Note that this function
* is used in calls to apr_table_do(), so don't change its interface.
* It returns true unless there was a write error of some kind.
*/
static int form_header_field(header_struct *h,
const char *fieldname, const char *fieldval)
{
#if APR_CHARSET_EBCDIC
char *headfield;
apr_size_t len;
headfield = apr_pstrcat(h->pool, fieldname, ": ", fieldval, CRLF, NULL);
len = strlen(headfield);
ap_xlate_proto_to_ascii(headfield, len);
apr_brigade_write(h->bb, NULL, NULL, headfield, len);
#else
struct iovec vec[4];
struct iovec *v = vec;
v->iov_base = (void *)fieldname;
v->iov_len = strlen(fieldname);
v++;
v->iov_base = ": ";
v->iov_len = sizeof(": ") - 1;
v++;
v->iov_base = (void *)fieldval;
v->iov_len = strlen(fieldval);
v++;
v->iov_base = CRLF;
v->iov_len = sizeof(CRLF) - 1;
apr_brigade_writev(h->bb, NULL, NULL, vec, 4);
#endif /* !APR_CHARSET_EBCDIC */
return 1;
}
/* This routine is called by apr_table_do and merges all instances of
* the passed field values into a single array that will be further
* processed by some later routine. Originally intended to help split
* and recombine multiple Vary fields, though it is generic to any field
* consisting of comma/space-separated tokens.
*/
static int uniq_field_values(void *d, const char *key, const char *val)
{
apr_array_header_t *values;
char *start;
char *e;
char **strpp;
int i;
values = (apr_array_header_t *)d;
e = apr_pstrdup(values->pool, val);
do {
/* Find a non-empty fieldname */
while (*e == ',' || apr_isspace(*e)) {
++e;
}
if (*e == '\0') {
break;
}
start = e;
while (*e != '\0' && *e != ',' && !apr_isspace(*e)) {
++e;
}
if (*e != '\0') {
*e++ = '\0';
}
/* Now add it to values if it isn't already represented.
* Could be replaced by a ap_array_strcasecmp() if we had one.
*/
for (i = 0, strpp = (char **) values->elts; i < values->nelts;
++i, ++strpp) {
if (*strpp && ap_cstr_casecmp(*strpp, start) == 0) {
break;
}
}
if (i == values->nelts) { /* if not found */
*(char **)apr_array_push(values) = start;
}
} while (*e != '\0');
return 1;
}
/*
* Since some clients choke violently on multiple Vary fields, or
* Vary fields with duplicate tokens, combine any multiples and remove
* any duplicates.
*/
static void fixup_vary(request_rec *r)
{
apr_array_header_t *varies;
varies = apr_array_make(r->pool, 5, sizeof(char *));
/* Extract all Vary fields from the headers_out, separate each into
* its comma-separated fieldname values, and then add them to varies
* if not already present in the array.
*/
apr_table_do(uniq_field_values, varies, r->headers_out, "Vary", NULL);
/* If we found any, replace old Vary fields with unique-ified value */
if (varies->nelts > 0) {
apr_table_setn(r->headers_out, "Vary",
apr_array_pstrcat(r->pool, varies, ','));
}
}
/* Confirm that the status line is well-formed and matches r->status.
* If they don't match, a filter may have negated the status line set by a
* handler.
* Zap r->status_line if bad.
*/
static apr_status_t validate_status_line(request_rec *r)
{
char *end;
if (r->status_line) {
int len = strlen(r->status_line);
if (len < 3
|| apr_strtoi64(r->status_line, &end, 10) != r->status
|| (end - 3) != r->status_line
|| (len >= 4 && ! apr_isspace(r->status_line[3]))) {
r->status_line = NULL;
return APR_EGENERAL;
}
/* Since we passed the above check, we know that length three
* is equivalent to only a 3 digit numeric http status.
* RFC2616 mandates a trailing space, let's add it.
*/
if (len == 3) {
r->status_line = apr_pstrcat(r->pool, r->status_line, " ", NULL);
return APR_EGENERAL;
}
return APR_SUCCESS;
}
return APR_EGENERAL;
}
/*
* Determine the protocol to use for the response. Potentially downgrade
* to HTTP/1.0 in some situations and/or turn off keepalives.