]> granicus.if.org Git - apache/blob - modules/http/byterange_filter.c
* We don't need a copy of the original range as we don't change it. A pointer to...
[apache] / modules / http / byterange_filter.c
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /*
18  * byterange_filter.c --- HTTP byterange filter and friends.
19  */
20
21 #include "apr.h"
22
23 #if APR_HAVE_PROCESS_H
24 #include <process.h>            /* for getpid() on Win32 */
25 #endif
26
27 #include "apr_strings.h"
28 #include "apr_buckets.h"
29 #include "apr_lib.h"
30 #include "apr_signal.h"
31
32 #define APR_WANT_STDIO          /* for sscanf */
33 #define APR_WANT_STRFUNC
34 #define APR_WANT_MEMFUNC
35 #include "apr_want.h"
36
37 #include "util_filter.h"
38 #include "ap_config.h"
39 #include "httpd.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
47                                  * support code... */
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"
52
53 #include "mod_core.h"
54
55 #if APR_HAVE_STDARG_H
56 #include <stdarg.h>
57 #endif
58 #if APR_HAVE_UNISTD_H
59 #include <unistd.h>
60 #endif
61
62 #ifndef DEFAULT_MAX_RANGES
63 #define DEFAULT_MAX_RANGES 200
64 #endif
65
66 APLOG_USE_MODULE(http);
67
68 static int ap_set_byterange(request_rec *r, apr_off_t clength,
69                             apr_array_header_t **indexes);
70
71 /*
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.
77  */
78 static int use_range_x(request_rec *r)
79 {
80     const char *ua;
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")));
84 }
85
86 #define BYTERANGE_FMT "%" APR_OFF_T_FMT "-%" APR_OFF_T_FMT "/%" APR_OFF_T_FMT
87 #define MAX_PREALLOC_RANGES 100
88
89 static apr_status_t copy_brigade_range(apr_bucket_brigade *bb,
90                                        apr_bucket_brigade *bbout,
91                                        apr_off_t start,
92                                        apr_off_t end)
93 {
94     apr_bucket *first = NULL, *last = NULL, *out_first = NULL, *e;
95     apr_uint64_t pos = 0, off_first = 0, off_last = 0;
96     apr_status_t rv;
97     const char *s;
98     apr_size_t len;
99     apr_uint64_t start64, end64;
100     apr_off_t pofft = 0;
101
102     /*
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.
106      */
107     start64 = (apr_uint64_t)start;
108     end64 = (apr_uint64_t)end;
109
110     if (start < 0 || end < 0 || start64 > end64)
111         return APR_EINVAL;
112
113     for (e = APR_BRIGADE_FIRST(bb);
114          e != APR_BRIGADE_SENTINEL(bb);
115          e = APR_BUCKET_NEXT(e))
116     {
117         apr_uint64_t elen64;
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)) {
122             first = e;
123             off_first = pos;
124         }
125         if (elen64 + pos > end64) {
126             last = e;
127             off_last = pos;
128             break;
129         }
130         pos += elen64;
131     }
132     if (!first || !last)
133         return APR_EINVAL;
134
135     e = first;
136     while (1)
137     {
138         apr_bucket *copy;
139         AP_DEBUG_ASSERT(e != APR_BRIGADE_SENTINEL(bb));
140         rv = apr_bucket_copy(e, &copy);
141         if (rv != APR_SUCCESS) {
142             apr_brigade_cleanup(bbout);
143             return rv;
144         }
145
146         APR_BRIGADE_INSERT_TAIL(bbout, copy);
147         if (e == first) {
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);
154                         return rv;
155                     }
156                     /*
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.
160                      */
161                     while (start64 - off_first > (apr_uint64_t)copy->length) {
162                         apr_bucket *tmp;
163                         int i = 0;
164                         if (i++ >= 99999)
165                             return APR_EINVAL;
166
167                         tmp = APR_BUCKET_NEXT(copy);
168                         off_first += (apr_uint64_t)copy->length;
169                         APR_BUCKET_REMOVE(copy);
170                         apr_bucket_destroy(copy);
171                         copy = tmp;
172                         rv = apr_bucket_read(copy, &s, &len, APR_BLOCK_READ);
173                         if (rv != APR_SUCCESS) {
174                             apr_brigade_cleanup(bbout);
175                             return rv;
176                         }
177                     }
178                     if (start64 > off_first) {
179                         rv = apr_bucket_split(copy, (apr_size_t)(start64 - off_first));
180                         if (rv != APR_SUCCESS) {
181                             apr_brigade_cleanup(bbout);
182                             return rv;
183                         }
184                     }
185                     else {
186                         copy = APR_BUCKET_PREV(copy);
187                     }
188                 }
189                 else if (rv != APR_SUCCESS) {
190                         apr_brigade_cleanup(bbout);
191                         return rv;
192                 }
193                 out_first = APR_BUCKET_NEXT(copy);
194                 APR_BUCKET_REMOVE(copy);
195                 apr_bucket_destroy(copy);
196             }
197             else {
198                 out_first = copy;
199             }
200         }
201         if (e == last) {
202             if (e == first) {
203                 off_last += start64 - off_first;
204                 copy = out_first;
205             }
206             if (end64 - off_last != (apr_uint64_t)e->length) {
207                 rv = apr_bucket_split(copy, (apr_size_t)(end64 + 1 - off_last));
208                 if (rv == APR_ENOTIMPL) {
209                     rv = apr_bucket_read(copy, &s, &len, APR_BLOCK_READ);
210                     if (rv != APR_SUCCESS) {
211                         apr_brigade_cleanup(bbout);
212                         return rv;
213                     }
214                     /*
215                      * The read above might have morphed copy in a bucket
216                      * of shorter length. So read until we reached
217                      * the correct bucket for splitting.
218                      */
219                     while (end64 + 1 - off_last > (apr_uint64_t)copy->length) {
220                         off_last += (apr_uint64_t)copy->length;
221                         copy = APR_BUCKET_NEXT(copy);
222                         rv = apr_bucket_read(copy, &s, &len, APR_BLOCK_READ);
223                         if (rv != APR_SUCCESS) {
224                             apr_brigade_cleanup(bbout);
225                             return rv;
226                         }
227                     }
228                     if (end64 < off_last + (apr_uint64_t)copy->length - 1) {
229                         rv = apr_bucket_split(copy, end64 + 1 - off_last);
230                         if (rv != APR_SUCCESS) {
231                             apr_brigade_cleanup(bbout);
232                             return rv;
233                         }
234                     }
235                 }
236                 else if (rv != APR_SUCCESS) {
237                         apr_brigade_cleanup(bbout);
238                         return rv;
239                 }
240                 copy = APR_BUCKET_NEXT(copy);
241                 if (copy != APR_BRIGADE_SENTINEL(bbout)) {
242                     APR_BUCKET_REMOVE(copy);
243                     apr_bucket_destroy(copy);
244                 }
245             }
246             break;
247         }
248         e = APR_BUCKET_NEXT(e);
249     }
250
251     AP_DEBUG_ASSERT(APR_SUCCESS == apr_brigade_length(bbout, 1, &pofft));
252     pos = (apr_uint64_t)pofft;
253     AP_DEBUG_ASSERT(pos == end64 - start64 + 1);
254     return APR_SUCCESS;
255 }
256
257 typedef struct indexes_t {
258     apr_off_t start;
259     apr_off_t end;
260 } indexes_t;
261
262 static int get_max_ranges(request_rec *r) { 
263     core_dir_config *core_conf = ap_get_core_module_config(r->per_dir_config);
264     return core_conf->max_ranges == -1 ? DEFAULT_MAX_RANGES : core_conf->max_ranges;
265 }
266
267 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_byterange_filter(ap_filter_t *f,
268                                                          apr_bucket_brigade *bb)
269 {
270     request_rec *r = f->r;
271     conn_rec *c = r->connection;
272     apr_bucket *e;
273     apr_bucket_brigade *bsend;
274     apr_bucket_brigade *tmpbb;
275     apr_off_t range_start;
276     apr_off_t range_end;
277     apr_off_t clength = 0;
278     apr_status_t rv;
279     int found = 0;
280     int num_ranges;
281     char *boundary = NULL;
282     char *bound_head = NULL;
283     apr_array_header_t *indexes;
284     indexes_t *idx;
285     int i;
286     int original_status;
287     int max_ranges = get_max_ranges(r);
288
289     /*
290      * Iterate through the brigade until reaching EOS or a bucket with
291      * unknown length.
292      */
293     for (e = APR_BRIGADE_FIRST(bb);
294          (e != APR_BRIGADE_SENTINEL(bb) && !APR_BUCKET_IS_EOS(e)
295           && e->length != (apr_size_t)-1);
296          e = APR_BUCKET_NEXT(e)) {
297         clength += e->length;
298     }
299
300     /*
301      * Don't attempt to do byte range work if this brigade doesn't
302      * contain an EOS, or if any of the buckets has an unknown length;
303      * this avoids the cases where it is expensive to perform
304      * byteranging (i.e. may require arbitrary amounts of memory).
305      */
306     if (!APR_BUCKET_IS_EOS(e) || clength <= 0) {
307         ap_remove_output_filter(f);
308         return ap_pass_brigade(f->next, bb);
309     }
310
311     original_status = r->status;
312     num_ranges = ap_set_byterange(r, clength, &indexes);
313
314     /* We have nothing to do, get out of the way. */
315     if (num_ranges == 0 || (max_ranges > 0 && num_ranges > max_ranges)) {
316         r->status = original_status;
317         ap_remove_output_filter(f);
318         return ap_pass_brigade(f->next, bb);
319     }
320
321     if (num_ranges > 1) {
322         /* Is ap_make_content_type required here? */
323         const char *orig_ct = ap_make_content_type(r, r->content_type);
324         boundary = apr_psprintf(r->pool, "%" APR_UINT64_T_HEX_FMT "%lx",
325                                 (apr_uint64_t)r->request_time, (long) getpid());
326
327         ap_set_content_type(r, apr_pstrcat(r->pool, "multipart",
328                                            use_range_x(r) ? "/x-" : "/",
329                                            "byteranges; boundary=",
330                                            boundary, NULL));
331
332         if (orig_ct) {
333             bound_head = apr_pstrcat(r->pool,
334                                      CRLF "--", boundary,
335                                      CRLF "Content-type: ",
336                                      orig_ct,
337                                      CRLF "Content-range: bytes ",
338                                      NULL);
339         }
340         else {
341             /* if we have no type for the content, do our best */
342             bound_head = apr_pstrcat(r->pool,
343                                      CRLF "--", boundary,
344                                      CRLF "Content-range: bytes ",
345                                      NULL);
346         }
347         ap_xlate_proto_to_ascii(bound_head, strlen(bound_head));
348     }
349
350     /* this brigade holds what we will be sending */
351     bsend = apr_brigade_create(r->pool, c->bucket_alloc);
352     tmpbb = apr_brigade_create(r->pool, c->bucket_alloc);
353
354     idx = (indexes_t *)indexes->elts;
355     for (i = 0; i < indexes->nelts; i++, idx++) {
356         range_start = idx->start;
357         range_end = idx->end;
358
359         rv = copy_brigade_range(bb, tmpbb, range_start, range_end);
360         if (rv != APR_SUCCESS ) {
361             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
362                           "copy_brigade_range() failed [%" APR_OFF_T_FMT
363                           "-%" APR_OFF_T_FMT ",%" APR_OFF_T_FMT "]",
364                           range_start, range_end, clength);
365             continue;
366         }
367         found = 1;
368
369         /*
370          * For single range requests, we must produce Content-Range header.
371          * Otherwise, we need to produce the multipart boundaries.
372          */
373         if (num_ranges == 1) {
374             apr_table_setn(r->headers_out, "Content-Range",
375                            apr_psprintf(r->pool, "bytes " BYTERANGE_FMT,
376                                         range_start, range_end, clength));
377         }
378         else {
379             char *ts;
380
381             e = apr_bucket_pool_create(bound_head, strlen(bound_head),
382                                        r->pool, c->bucket_alloc);
383             APR_BRIGADE_INSERT_TAIL(bsend, e);
384
385             ts = apr_psprintf(r->pool, BYTERANGE_FMT CRLF CRLF,
386                               range_start, range_end, clength);
387             ap_xlate_proto_to_ascii(ts, strlen(ts));
388             e = apr_bucket_pool_create(ts, strlen(ts), r->pool,
389                                        c->bucket_alloc);
390             APR_BRIGADE_INSERT_TAIL(bsend, e);
391         }
392
393         APR_BRIGADE_CONCAT(bsend, tmpbb);
394         if (i && !(i & 0x1F)) {
395             /*
396              * Every now and then, pass what we have down the filter chain.
397              * In this case, the content-length filter cannot calculate and
398              * set the content length and we must remove any Content-Length
399              * header already present.
400              */
401             apr_table_unset(r->headers_out, "Content-Length");
402             if ((rv = ap_pass_brigade(f->next, bsend)) != APR_SUCCESS)
403                 return rv;
404             apr_brigade_cleanup(bsend);
405         }
406     }
407
408     if (found == 0) {
409         ap_remove_output_filter(f);
410         r->status = HTTP_OK;
411         /* bsend is assumed to be empty if we get here. */
412         e = ap_bucket_error_create(HTTP_RANGE_NOT_SATISFIABLE, NULL,
413                                    r->pool, c->bucket_alloc);
414         APR_BRIGADE_INSERT_TAIL(bsend, e);
415         e = apr_bucket_eos_create(c->bucket_alloc);
416         APR_BRIGADE_INSERT_TAIL(bsend, e);
417         return ap_pass_brigade(f->next, bsend);
418     }
419
420     if (num_ranges > 1) {
421         char *end;
422
423         /* add the final boundary */
424         end = apr_pstrcat(r->pool, CRLF "--", boundary, "--" CRLF, NULL);
425         ap_xlate_proto_to_ascii(end, strlen(end));
426         e = apr_bucket_pool_create(end, strlen(end), r->pool, c->bucket_alloc);
427         APR_BRIGADE_INSERT_TAIL(bsend, e);
428     }
429
430     e = apr_bucket_eos_create(c->bucket_alloc);
431     APR_BRIGADE_INSERT_TAIL(bsend, e);
432
433     /* we're done with the original content - all of our data is in bsend. */
434     apr_brigade_cleanup(bb);
435     apr_brigade_destroy(tmpbb);
436
437     /* send our multipart output */
438     return ap_pass_brigade(f->next, bsend);
439 }
440
441 static int ap_set_byterange(request_rec *r, apr_off_t clength,
442                             apr_array_header_t **indexes)
443 {
444     const char *range;
445     const char *if_range;
446     const char *match;
447     const char *ct;
448     char *cur, **new;
449     apr_array_header_t *merged;
450     int num_ranges = 0;
451     apr_off_t ostart = 0, oend = 0, sum_lengths = 0;
452     int in_merge = 0;
453     indexes_t *idx;
454     int overlaps = 0, reversals = 0;
455     int ranges = 1;
456     const char *it;
457
458     if (r->assbackwards) {
459         return 0;
460     }
461
462     /*
463      * Check for Range request-header (HTTP/1.1) or Request-Range for
464      * backwards-compatibility with second-draft Luotonen/Franks
465      * byte-ranges (e.g. Netscape Navigator 2-3).
466      *
467      * We support this form, with Request-Range, and (farther down) we
468      * send multipart/x-byteranges instead of multipart/byteranges for
469      * Request-Range based requests to work around a bug in Netscape
470      * Navigator 2-3 and MSIE 3.
471      */
472
473     if (!(range = apr_table_get(r->headers_in, "Range"))) {
474         range = apr_table_get(r->headers_in, "Request-Range");
475     }
476
477     if (!range || strncasecmp(range, "bytes=", 6) || r->status != HTTP_OK) {
478         return 0;
479     }
480
481     /* is content already a single range? */
482     if (apr_table_get(r->headers_out, "Content-Range")) {
483        return 0;
484     }
485
486     /* is content already a multiple range? */
487     if ((ct = apr_table_get(r->headers_out, "Content-Type"))
488         && (!strncasecmp(ct, "multipart/byteranges", 20)
489             || !strncasecmp(ct, "multipart/x-byteranges", 22))) {
490        return 0;
491     }
492
493     /*
494      * Check the If-Range header for Etag or Date.
495      * Note that this check will return false (as required) if either
496      * of the two etags are weak.
497      */
498     if ((if_range = apr_table_get(r->headers_in, "If-Range"))) {
499         if (if_range[0] == '"') {
500             if (!(match = apr_table_get(r->headers_out, "Etag"))
501                 || (strcmp(if_range, match) != 0)) {
502                 return 0;
503             }
504         }
505         else if (!(match = apr_table_get(r->headers_out, "Last-Modified"))
506                  || (strcmp(if_range, match) != 0)) {
507             return 0;
508         }
509     }
510
511     range += 6;
512     it = range;
513     while (*it) {
514         if (*it++ == ',') {
515             ranges++;
516         }
517     }
518     it = range;
519     if (ranges > MAX_PREALLOC_RANGES) {
520         ranges = MAX_PREALLOC_RANGES;
521     }
522     *indexes = apr_array_make(r->pool, ranges, sizeof(indexes_t));
523     merged = apr_array_make(r->pool, ranges, sizeof(char *));
524     while ((cur = ap_getword(r->pool, &range, ','))) {
525         char *dash;
526         char *errp;
527         apr_off_t number, start, end;
528
529         if (!(dash = strchr(cur, '-'))) {
530             break;
531         }
532
533         if (dash == range) {
534             /* In the form "-5" */
535             if (apr_strtoff(&number, dash+1, &errp, 10) || *errp) {
536                 break;
537             }
538             start = clength - number;
539             end = clength - 1;
540         }
541         else {
542             *dash++ = '\0';
543             if (apr_strtoff(&number, cur, &errp, 10) || *errp) {
544                 break;
545             }
546             start = number;
547             if (*dash) {
548                 if (apr_strtoff(&number, dash, &errp, 10) || *errp) {
549                     break;
550                 }
551                 end = number;
552             }
553             else {                  /* "5-" */
554                 end = clength - 1;
555             }
556         }
557
558         if (start < 0) {
559             start = 0;
560         }
561         if (end >= clength) {
562             end = clength - 1;
563         }
564
565         if (start > end) {
566             /* ignore? count? */
567             break;
568         }
569         if (!in_merge) {
570             /* new set */
571             ostart = start;
572             oend = end;
573             in_merge = 1;
574             continue;
575         }
576         in_merge = 0;
577
578         if (start >= ostart && end <= oend) {
579             in_merge = 1;
580         }
581
582         if (start < ostart && end >= ostart-1) {
583             ostart = start;
584             reversals++;
585             in_merge = 1;
586         }
587         if (end >= oend && start <= oend+1 ) {
588             oend = end;
589             in_merge = 1;
590         }
591
592         if (in_merge) {
593             overlaps++;
594             continue;
595         } else {
596             new = (char **)apr_array_push(merged);
597             *new = apr_psprintf(r->pool, "%" APR_OFF_T_FMT "-%" APR_OFF_T_FMT,
598                                     ostart, oend);
599             idx = (indexes_t *)apr_array_push(*indexes);
600             idx->start = ostart;
601             idx->end = oend;
602             sum_lengths += oend - ostart + 1;
603             /* new set again */
604             in_merge = 1;
605             ostart = start;
606             oend = end;
607             num_ranges++;
608         }
609     }
610
611     if (in_merge) {
612         new = (char **)apr_array_push(merged);
613         *new = apr_psprintf(r->pool, "%" APR_OFF_T_FMT "-%" APR_OFF_T_FMT,
614                             ostart, oend);
615         idx = (indexes_t *)apr_array_push(*indexes);
616         idx->start = ostart;
617         idx->end = oend;
618         sum_lengths += oend - ostart + 1;
619         num_ranges++;
620     }
621     if (sum_lengths >= clength) {
622         ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
623                       "Sum of ranges not smaller than file, ignoring.");
624         return 0;
625     }
626
627     r->status = HTTP_PARTIAL_CONTENT;
628     r->range = apr_array_pstrcat(r->pool, merged, ',');
629     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
630                   "Range: %s | %s (%d : %d : %"APR_OFF_T_FMT")",
631                   it, r->range, overlaps, reversals, clength);
632
633     return num_ranges;
634 }