1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * byterange_filter.c --- HTTP byterange filter and friends.
23 #if APR_HAVE_PROCESS_H
24 #include <process.h> /* for getpid() on Win32 */
27 #include "apr_strings.h"
28 #include "apr_buckets.h"
30 #include "apr_signal.h"
32 #define APR_WANT_STDIO /* for sscanf */
33 #define APR_WANT_STRFUNC
34 #define APR_WANT_MEMFUNC
37 #include "util_filter.h"
38 #include "ap_config.h"
40 #include "http_config.h"
41 #include "http_core.h"
42 #include "http_protocol.h"
43 #include "http_main.h"
44 #include "http_request.h"
45 #include "http_vhost.h"
46 #include "http_log.h" /* For errors detected in basic auth common
48 #include "apr_date.h" /* For apr_date_parse_http and APR_DATE_BAD */
49 #include "util_charset.h"
50 #include "util_ebcdic.h"
51 #include "util_time.h"
62 #ifndef DEFAULT_MAX_RANGES
63 #define DEFAULT_MAX_RANGES 200
66 APLOG_USE_MODULE(http);
68 static int ap_set_byterange(request_rec *r, apr_off_t clength,
69 apr_array_header_t **indexes);
72 * Here we try to be compatible with clients that want multipart/x-byteranges
73 * instead of multipart/byteranges (also see above), as per HTTP/1.1. We
74 * look for the Request-Range header (e.g. Netscape 2 and 3) as an indication
75 * that the browser supports an older protocol. We also check User-Agent
76 * for Microsoft Internet Explorer 3, which needs this as well.
78 static int use_range_x(request_rec *r)
81 return (apr_table_get(r->headers_in, "Request-Range")
82 || ((ua = apr_table_get(r->headers_in, "User-Agent"))
83 && ap_strstr_c(ua, "MSIE 3")));
86 #define BYTERANGE_FMT "%" APR_OFF_T_FMT "-%" APR_OFF_T_FMT "/%" APR_OFF_T_FMT
87 #define MAX_PREALLOC_RANGES 100
89 static apr_status_t copy_brigade_range(apr_bucket_brigade *bb,
90 apr_bucket_brigade *bbout,
94 apr_bucket *first = NULL, *last = NULL, *out_first = NULL, *e;
95 apr_uint64_t pos = 0, off_first = 0, off_last = 0;
99 apr_uint64_t start64, end64;
103 * Once we know that start and end are >= 0 convert everything to apr_uint64_t.
104 * See the comments in apr_brigade_partition why.
105 * In short apr_off_t (for values >= 0)and apr_size_t fit into apr_uint64_t.
107 start64 = (apr_uint64_t)start;
108 end64 = (apr_uint64_t)end;
110 if (start < 0 || end < 0 || start64 > end64)
113 for (e = APR_BRIGADE_FIRST(bb);
114 e != APR_BRIGADE_SENTINEL(bb);
115 e = APR_BUCKET_NEXT(e))
118 /* we know that no bucket has undefined length (-1) */
119 AP_DEBUG_ASSERT(e->length != (apr_size_t)(-1));
120 elen64 = (apr_uint64_t)e->length;
121 if (!first && (elen64 + pos > start64)) {
125 if (elen64 + pos > end64) {
139 AP_DEBUG_ASSERT(e != APR_BRIGADE_SENTINEL(bb));
140 rv = apr_bucket_copy(e, ©);
141 if (rv != APR_SUCCESS) {
142 apr_brigade_cleanup(bbout);
146 APR_BRIGADE_INSERT_TAIL(bbout, copy);
148 if (off_first != start64) {
149 rv = apr_bucket_split(copy, (apr_size_t)(start64 - off_first));
150 if (rv == APR_ENOTIMPL) {
151 rv = apr_bucket_read(copy, &s, &len, APR_BLOCK_READ);
152 if (rv != APR_SUCCESS) {
153 apr_brigade_cleanup(bbout);
157 * The read above might have morphed copy in a bucket
158 * of shorter length. So read and delete until we reached
159 * the correct bucket for splitting.
161 while (start64 - off_first > (apr_uint64_t)copy->length) {
162 apr_bucket *tmp = APR_BUCKET_NEXT(copy);
163 off_first += (apr_uint64_t)copy->length;
164 APR_BUCKET_REMOVE(copy);
165 apr_bucket_destroy(copy);
167 rv = apr_bucket_read(copy, &s, &len, APR_BLOCK_READ);
168 if (rv != APR_SUCCESS) {
169 apr_brigade_cleanup(bbout);
173 if (start64 > off_first) {
174 rv = apr_bucket_split(copy, (apr_size_t)(start64 - off_first));
175 if (rv != APR_SUCCESS) {
176 apr_brigade_cleanup(bbout);
181 copy = APR_BUCKET_PREV(copy);
184 else if (rv != APR_SUCCESS) {
185 apr_brigade_cleanup(bbout);
188 out_first = APR_BUCKET_NEXT(copy);
189 APR_BUCKET_REMOVE(copy);
190 apr_bucket_destroy(copy);
198 off_last += start64 - off_first;
201 if (end64 - off_last != (apr_uint64_t)e->length) {
202 rv = apr_bucket_split(copy, (apr_size_t)(end64 + 1 - off_last));
203 if (rv == APR_ENOTIMPL) {
204 rv = apr_bucket_read(copy, &s, &len, APR_BLOCK_READ);
205 if (rv != APR_SUCCESS) {
206 apr_brigade_cleanup(bbout);
210 * The read above might have morphed copy in a bucket
211 * of shorter length. So read until we reached
212 * the correct bucket for splitting.
214 while (end64 + 1 - off_last > (apr_uint64_t)copy->length) {
215 off_last += (apr_uint64_t)copy->length;
216 copy = APR_BUCKET_NEXT(copy);
217 rv = apr_bucket_read(copy, &s, &len, APR_BLOCK_READ);
218 if (rv != APR_SUCCESS) {
219 apr_brigade_cleanup(bbout);
223 if (end64 < off_last + (apr_uint64_t)copy->length - 1) {
224 rv = apr_bucket_split(copy, (apr_size_t)(end64 + 1 - off_last));
225 if (rv != APR_SUCCESS) {
226 apr_brigade_cleanup(bbout);
231 else if (rv != APR_SUCCESS) {
232 apr_brigade_cleanup(bbout);
235 copy = APR_BUCKET_NEXT(copy);
236 if (copy != APR_BRIGADE_SENTINEL(bbout)) {
237 APR_BUCKET_REMOVE(copy);
238 apr_bucket_destroy(copy);
243 e = APR_BUCKET_NEXT(e);
246 AP_DEBUG_ASSERT(APR_SUCCESS == apr_brigade_length(bbout, 1, &pofft));
247 pos = (apr_uint64_t)pofft;
248 AP_DEBUG_ASSERT(pos == end64 - start64 + 1);
252 typedef struct indexes_t {
257 static int get_max_ranges(request_rec *r) {
258 core_dir_config *core_conf = ap_get_core_module_config(r->per_dir_config);
259 return core_conf->max_ranges == -1 ? DEFAULT_MAX_RANGES : core_conf->max_ranges;
262 static apr_status_t send_416(ap_filter_t *f, apr_bucket_brigade *tmpbb)
265 conn_rec *c = f->r->connection;
266 ap_remove_output_filter(f);
267 f->r->status = HTTP_OK;
268 e = ap_bucket_error_create(HTTP_RANGE_NOT_SATISFIABLE, NULL,
269 f->r->pool, c->bucket_alloc);
270 APR_BRIGADE_INSERT_TAIL(tmpbb, e);
271 e = apr_bucket_eos_create(c->bucket_alloc);
272 APR_BRIGADE_INSERT_TAIL(tmpbb, e);
273 return ap_pass_brigade(f->next, tmpbb);
276 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_byterange_filter(ap_filter_t *f,
277 apr_bucket_brigade *bb)
279 request_rec *r = f->r;
280 conn_rec *c = r->connection;
282 apr_bucket_brigade *bsend;
283 apr_bucket_brigade *tmpbb;
284 apr_off_t range_start;
286 apr_off_t clength = 0;
290 char *boundary = NULL;
291 char *bound_head = NULL;
292 apr_array_header_t *indexes;
296 int max_ranges = get_max_ranges(r);
299 * Iterate through the brigade until reaching EOS or a bucket with
302 for (e = APR_BRIGADE_FIRST(bb);
303 (e != APR_BRIGADE_SENTINEL(bb) && !APR_BUCKET_IS_EOS(e)
304 && e->length != (apr_size_t)-1);
305 e = APR_BUCKET_NEXT(e)) {
306 clength += e->length;
310 * Don't attempt to do byte range work if this brigade doesn't
311 * contain an EOS, or if any of the buckets has an unknown length;
312 * this avoids the cases where it is expensive to perform
313 * byteranging (i.e. may require arbitrary amounts of memory).
315 if (!APR_BUCKET_IS_EOS(e) || clength <= 0) {
316 ap_remove_output_filter(f);
317 return ap_pass_brigade(f->next, bb);
320 original_status = r->status;
321 num_ranges = ap_set_byterange(r, clength, &indexes);
323 /* We have nothing to do, get out of the way. */
324 if (num_ranges == 0 || (max_ranges > 0 && num_ranges > max_ranges)) {
325 r->status = original_status;
326 ap_remove_output_filter(f);
327 return ap_pass_brigade(f->next, bb);
330 /* this brigade holds what we will be sending */
331 bsend = apr_brigade_create(r->pool, c->bucket_alloc);
334 return send_416(f, bsend);
336 if (num_ranges > 1) {
337 /* Is ap_make_content_type required here? */
338 const char *orig_ct = ap_make_content_type(r, r->content_type);
339 boundary = apr_psprintf(r->pool, "%" APR_UINT64_T_HEX_FMT "%lx",
340 (apr_uint64_t)r->request_time, (long) getpid());
342 ap_set_content_type(r, apr_pstrcat(r->pool, "multipart",
343 use_range_x(r) ? "/x-" : "/",
344 "byteranges; boundary=",
348 bound_head = apr_pstrcat(r->pool,
350 CRLF "Content-type: ",
352 CRLF "Content-range: bytes ",
356 /* if we have no type for the content, do our best */
357 bound_head = apr_pstrcat(r->pool,
359 CRLF "Content-range: bytes ",
362 ap_xlate_proto_to_ascii(bound_head, strlen(bound_head));
365 tmpbb = apr_brigade_create(r->pool, c->bucket_alloc);
367 idx = (indexes_t *)indexes->elts;
368 for (i = 0; i < indexes->nelts; i++, idx++) {
369 range_start = idx->start;
370 range_end = idx->end;
372 rv = copy_brigade_range(bb, tmpbb, range_start, range_end);
373 if (rv != APR_SUCCESS ) {
374 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
375 "copy_brigade_range() failed [%" APR_OFF_T_FMT
376 "-%" APR_OFF_T_FMT ",%" APR_OFF_T_FMT "]",
377 range_start, range_end, clength);
383 * For single range requests, we must produce Content-Range header.
384 * Otherwise, we need to produce the multipart boundaries.
386 if (num_ranges == 1) {
387 apr_table_setn(r->headers_out, "Content-Range",
388 apr_psprintf(r->pool, "bytes " BYTERANGE_FMT,
389 range_start, range_end, clength));
394 e = apr_bucket_pool_create(bound_head, strlen(bound_head),
395 r->pool, c->bucket_alloc);
396 APR_BRIGADE_INSERT_TAIL(bsend, e);
398 ts = apr_psprintf(r->pool, BYTERANGE_FMT CRLF CRLF,
399 range_start, range_end, clength);
400 ap_xlate_proto_to_ascii(ts, strlen(ts));
401 e = apr_bucket_pool_create(ts, strlen(ts), r->pool,
403 APR_BRIGADE_INSERT_TAIL(bsend, e);
406 APR_BRIGADE_CONCAT(bsend, tmpbb);
407 if (i && !(i & 0x1F)) {
409 * Every now and then, pass what we have down the filter chain.
410 * In this case, the content-length filter cannot calculate and
411 * set the content length and we must remove any Content-Length
412 * header already present.
414 apr_table_unset(r->headers_out, "Content-Length");
415 if ((rv = ap_pass_brigade(f->next, bsend)) != APR_SUCCESS)
417 apr_brigade_cleanup(bsend);
422 /* bsend is assumed to be empty if we get here. */
423 return send_416(f, bsend);
426 if (num_ranges > 1) {
429 /* add the final boundary */
430 end = apr_pstrcat(r->pool, CRLF "--", boundary, "--" CRLF, NULL);
431 ap_xlate_proto_to_ascii(end, strlen(end));
432 e = apr_bucket_pool_create(end, strlen(end), r->pool, c->bucket_alloc);
433 APR_BRIGADE_INSERT_TAIL(bsend, e);
436 e = apr_bucket_eos_create(c->bucket_alloc);
437 APR_BRIGADE_INSERT_TAIL(bsend, e);
439 /* we're done with the original content - all of our data is in bsend. */
440 apr_brigade_cleanup(bb);
441 apr_brigade_destroy(tmpbb);
443 /* send our multipart output */
444 return ap_pass_brigade(f->next, bsend);
447 static int ap_set_byterange(request_rec *r, apr_off_t clength,
448 apr_array_header_t **indexes)
451 const char *if_range;
455 apr_array_header_t *merged;
456 int num_ranges = 0, unsatisfiable = 0;
457 apr_off_t ostart = 0, oend = 0, sum_lengths = 0;
460 int overlaps = 0, reversals = 0;
464 if (r->assbackwards) {
469 * Check for Range request-header (HTTP/1.1) or Request-Range for
470 * backwards-compatibility with second-draft Luotonen/Franks
471 * byte-ranges (e.g. Netscape Navigator 2-3).
473 * We support this form, with Request-Range, and (farther down) we
474 * send multipart/x-byteranges instead of multipart/byteranges for
475 * Request-Range based requests to work around a bug in Netscape
476 * Navigator 2-3 and MSIE 3.
479 if (!(range = apr_table_get(r->headers_in, "Range"))) {
480 range = apr_table_get(r->headers_in, "Request-Range");
483 if (!range || strncasecmp(range, "bytes=", 6) || r->status != HTTP_OK) {
487 /* is content already a single range? */
488 if (apr_table_get(r->headers_out, "Content-Range")) {
492 /* is content already a multiple range? */
493 if ((ct = apr_table_get(r->headers_out, "Content-Type"))
494 && (!strncasecmp(ct, "multipart/byteranges", 20)
495 || !strncasecmp(ct, "multipart/x-byteranges", 22))) {
500 * Check the If-Range header for Etag or Date.
501 * Note that this check will return false (as required) if either
502 * of the two etags are weak.
504 if ((if_range = apr_table_get(r->headers_in, "If-Range"))) {
505 if (if_range[0] == '"') {
506 if (!(match = apr_table_get(r->headers_out, "Etag"))
507 || (strcmp(if_range, match) != 0)) {
511 else if (!(match = apr_table_get(r->headers_out, "Last-Modified"))
512 || (strcmp(if_range, match) != 0)) {
525 if (ranges > MAX_PREALLOC_RANGES) {
526 ranges = MAX_PREALLOC_RANGES;
528 *indexes = apr_array_make(r->pool, ranges, sizeof(indexes_t));
529 merged = apr_array_make(r->pool, ranges, sizeof(char *));
530 while ((cur = ap_getword(r->pool, &range, ','))) {
533 apr_off_t number, start, end;
539 * Per RFC 2616 14.35.1: If there is at least one syntactically invalid
540 * byte-range-spec, we must ignore the whole header.
543 if (!(dash = strchr(cur, '-'))) {
548 /* In the form "-5" */
549 if (apr_strtoff(&number, dash+1, &errp, 10) || *errp) {
555 start = clength - number;
560 if (apr_strtoff(&number, cur, &errp, 10) || *errp) {
565 if (apr_strtoff(&number, dash, &errp, 10) || *errp) {
581 if (start >= clength) {
585 if (end >= clength) {
598 if (start >= ostart && end <= oend) {
602 if (start < ostart && end >= ostart-1) {
607 if (end >= oend && start <= oend+1 ) {
616 new = (char **)apr_array_push(merged);
617 *new = apr_psprintf(r->pool, "%" APR_OFF_T_FMT "-%" APR_OFF_T_FMT,
619 idx = (indexes_t *)apr_array_push(*indexes);
622 sum_lengths += oend - ostart + 1;
632 new = (char **)apr_array_push(merged);
633 *new = apr_psprintf(r->pool, "%" APR_OFF_T_FMT "-%" APR_OFF_T_FMT,
635 idx = (indexes_t *)apr_array_push(*indexes);
638 sum_lengths += oend - ostart + 1;
641 else if (num_ranges == 0 && unsatisfiable) {
642 /* If all ranges are unsatisfiable, we should return 416 */
643 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
644 "All ranges in Range header (%s) are unsatisfiable",
648 if (sum_lengths > clength) {
649 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
650 "Sum of ranges larger than file, ignoring.");
654 r->status = HTTP_PARTIAL_CONTENT;
655 r->range = apr_array_pstrcat(r->pool, merged, ',');
656 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
657 "Range: %s | %s (%d : %d : %"APR_OFF_T_FMT")",
658 it, r->range, overlaps, reversals, clength);