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