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