~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/http/response.py

  • Committer: Martin Packman
  • Date: 2011-12-23 19:38:22 UTC
  • mto: This revision was merged to the branch mainline in revision 6405.
  • Revision ID: martin.packman@canonical.com-20111223193822-hesheea4o8aqwexv
Accept and document passing the medium rather than transport for smart connections

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
 
1
# Copyright (C) 2006-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Handlers for HTTP Responses.
18
18
 
22
22
"""
23
23
 
24
24
 
25
 
from bisect import bisect
 
25
import httplib
26
26
from cStringIO import StringIO
27
 
import re
28
 
 
29
 
from bzrlib import errors
30
 
from bzrlib.trace import mutter
31
 
 
32
 
 
33
 
class ResponseRange(object):
34
 
    """A range in a RangeFile-object."""
35
 
 
36
 
    __slots__ = ['_ent_start', '_ent_end', '_data_start']
37
 
 
38
 
    def __init__(self, ent_start, ent_end, data_start):
39
 
        self._ent_start = ent_start
40
 
        self._ent_end = ent_end
41
 
        self._data_start = data_start
42
 
 
43
 
    def __cmp__(self, other):
44
 
        """Compare this to other.
45
 
 
46
 
        We need this both for sorting, and so that we can
47
 
        bisect the list of ranges.
48
 
        """
49
 
        if isinstance(other, int):
50
 
            # Later on we bisect for a starting point
51
 
            # so we allow comparing against a single integer
52
 
            return cmp(self._ent_start, other)
53
 
        else:
54
 
            return cmp((self._ent_start, self._ent_end, self._data_start),
55
 
                       (other._ent_start, other._ent_end, other._data_start))
56
 
 
57
 
    def __str__(self):
58
 
        return "%s(%s-%s,%s)" % (self.__class__.__name__,
59
 
                                 self._ent_start, self._ent_end,
60
 
                                 self._data_start)
61
 
 
62
 
    __repr__ = __str__
63
 
 
 
27
import rfc822
 
28
 
 
29
from bzrlib import (
 
30
    errors,
 
31
    osutils,
 
32
    )
 
33
 
 
34
 
 
35
# A RangeFile expects the following grammar (simplified to outline the
 
36
# assumptions we rely upon).
 
37
 
 
38
# file: whole_file
 
39
#     | single_range
 
40
#     | multiple_range
 
41
 
 
42
# whole_file: [content_length_header] data
 
43
 
 
44
# single_range: content_range_header data
 
45
 
 
46
# multiple_range: boundary_header boundary (content_range_header data boundary)+
64
47
 
65
48
class RangeFile(object):
66
49
    """File-like object that allow access to partial available data.
67
50
 
68
 
    Specified by a set of ranges.
 
51
    All accesses should happen sequentially since the acquisition occurs during
 
52
    an http response reception (as sockets can't be seeked, we simulate the
 
53
    seek by just reading and discarding the data).
 
54
 
 
55
    The access pattern is defined by a set of ranges discovered as reading
 
56
    progress. Only one range is available at a given time, so all accesses
 
57
    should happen with monotonically increasing offsets.
69
58
    """
70
59
 
71
 
    def __init__(self, path, input_file):
 
60
    # in _checked_read() below, we may have to discard several MB in the worst
 
61
    # case. To avoid buffering that much, we read and discard by chunks
 
62
    # instead. The underlying file is either a socket or a StringIO, so reading
 
63
    # 8k chunks should be fine.
 
64
    _discarded_buf_size = 8192
 
65
 
 
66
    # maximum size of read requests -- used to avoid MemoryError issues in recv
 
67
    _max_read_size = 512 * 1024
 
68
 
 
69
    def __init__(self, path, infile):
 
70
        """Constructor.
 
71
 
 
72
        :param path: File url, for error reports.
 
73
        :param infile: File-like socket set at body start.
 
74
        """
72
75
        self._path = path
73
 
        self._pos = 0
74
 
        self._len = 0
75
 
        self._ranges = []
76
 
        self._data = input_file.read()
77
 
 
78
 
    def _add_range(self, ent_start, ent_end, data_start):
79
 
        """Add an entity range.
80
 
 
81
 
        :param ent_start: Start offset of entity
82
 
        :param ent_end: End offset of entity (inclusive)
83
 
        :param data_start: Start offset of data in data stream.
84
 
        """
85
 
        self._ranges.append(ResponseRange(ent_start, ent_end, data_start))
86
 
        self._len = max(self._len, ent_end)
87
 
 
88
 
    def _finish_ranges(self):
89
 
        self._ranges.sort()
90
 
 
91
 
    def read(self, size):
 
76
        self._file = infile
 
77
        self._boundary = None
 
78
        # When using multi parts response, this will be set with the headers
 
79
        # associated with the range currently read.
 
80
        self._headers = None
 
81
        # Default to the whole file of unspecified size
 
82
        self.set_range(0, -1)
 
83
 
 
84
    def set_range(self, start, size):
 
85
        """Change the range mapping"""
 
86
        self._start = start
 
87
        self._size = size
 
88
        # Set the new _pos since that's what we want to expose
 
89
        self._pos = self._start
 
90
 
 
91
    def set_boundary(self, boundary):
 
92
        """Define the boundary used in a multi parts message.
 
93
 
 
94
        The file should be at the beginning of the body, the first range
 
95
        definition is read and taken into account.
 
96
        """
 
97
        self._boundary = boundary
 
98
        # Decode the headers and setup the first range
 
99
        self.read_boundary()
 
100
        self.read_range_definition()
 
101
 
 
102
    def read_boundary(self):
 
103
        """Read the boundary headers defining a new range"""
 
104
        boundary_line = '\r\n'
 
105
        while boundary_line == '\r\n':
 
106
            # RFC2616 19.2 Additional CRLFs may precede the first boundary
 
107
            # string entity.
 
108
            # To be on the safe side we allow it before any boundary line
 
109
            boundary_line = self._file.readline()
 
110
 
 
111
        if boundary_line == '':
 
112
            # A timeout in the proxy server caused the response to end early.
 
113
            # See launchpad bug 198646.
 
114
            raise errors.HttpBoundaryMissing(
 
115
                self._path,
 
116
                self._boundary)
 
117
 
 
118
        if boundary_line != '--' + self._boundary + '\r\n':
 
119
            # rfc822.unquote() incorrectly unquotes strings enclosed in <>
 
120
            # IIS 6 and 7 incorrectly wrap boundary strings in <>
 
121
            # together they make a beautiful bug, which we will be gracious
 
122
            # about here
 
123
            if (self._unquote_boundary(boundary_line) !=
 
124
                '--' + self._boundary + '\r\n'):
 
125
                raise errors.InvalidHttpResponse(
 
126
                    self._path,
 
127
                    "Expected a boundary (%s) line, got '%s'"
 
128
                    % (self._boundary, boundary_line))
 
129
 
 
130
    def _unquote_boundary(self, b):
 
131
        return b[:2] + rfc822.unquote(b[2:-2]) + b[-2:]
 
132
 
 
133
    def read_range_definition(self):
 
134
        """Read a new range definition in a multi parts message.
 
135
 
 
136
        Parse the headers including the empty line following them so that we
 
137
        are ready to read the data itself.
 
138
        """
 
139
        self._headers = httplib.HTTPMessage(self._file, seekable=0)
 
140
        # Extract the range definition
 
141
        content_range = self._headers.getheader('content-range', None)
 
142
        if content_range is None:
 
143
            raise errors.InvalidHttpResponse(
 
144
                self._path,
 
145
                'Content-Range header missing in a multi-part response')
 
146
        self.set_range_from_header(content_range)
 
147
 
 
148
    def set_range_from_header(self, content_range):
 
149
        """Helper to set the new range from its description in the headers"""
 
150
        try:
 
151
            rtype, values = content_range.split()
 
152
        except ValueError:
 
153
            raise errors.InvalidHttpRange(self._path, content_range,
 
154
                                          'Malformed header')
 
155
        if rtype != 'bytes':
 
156
            raise errors.InvalidHttpRange(self._path, content_range,
 
157
                                          "Unsupported range type '%s'" % rtype)
 
158
        try:
 
159
            # We don't need total, but note that it may be either the file size
 
160
            # or '*' if the server can't or doesn't want to return the file
 
161
            # size.
 
162
            start_end, total = values.split('/')
 
163
            start, end = start_end.split('-')
 
164
            start = int(start)
 
165
            end = int(end)
 
166
        except ValueError:
 
167
            raise errors.InvalidHttpRange(self._path, content_range,
 
168
                                          'Invalid range values')
 
169
        size = end - start + 1
 
170
        if size <= 0:
 
171
            raise errors.InvalidHttpRange(self._path, content_range,
 
172
                                          'Invalid range, size <= 0')
 
173
        self.set_range(start, size)
 
174
 
 
175
    def _checked_read(self, size):
 
176
        """Read the file checking for short reads.
 
177
 
 
178
        The data read is discarded along the way.
 
179
        """
 
180
        pos = self._pos
 
181
        remaining = size
 
182
        while remaining > 0:
 
183
            data = self._file.read(min(remaining, self._discarded_buf_size))
 
184
            remaining -= len(data)
 
185
            if not data:
 
186
                raise errors.ShortReadvError(self._path, pos, size,
 
187
                                             size - remaining)
 
188
        self._pos += size
 
189
 
 
190
    def _seek_to_next_range(self):
 
191
        # We will cross range boundaries
 
192
        if self._boundary is None:
 
193
            # If we don't have a boundary, we can't find another range
 
194
            raise errors.InvalidRange(self._path, self._pos,
 
195
                                      "Range (%s, %s) exhausted"
 
196
                                      % (self._start, self._size))
 
197
        self.read_boundary()
 
198
        self.read_range_definition()
 
199
 
 
200
    def read(self, size=-1):
92
201
        """Read size bytes from the current position in the file.
93
202
 
94
 
        Reading across ranges is not supported.
 
203
        Reading across ranges is not supported. We rely on the underlying http
 
204
        client to clean the socket if we leave bytes unread. This may occur for
 
205
        the final boundary line of a multipart response or for any range
 
206
        request not entirely consumed by the client (due to offset coalescing)
 
207
 
 
208
        :param size:  The number of bytes to read.  Leave unspecified or pass
 
209
            -1 to read to EOF.
95
210
        """
96
 
        # find the last range which has a start <= pos
97
 
        i = bisect(self._ranges, self._pos) - 1
98
 
 
99
 
        if i < 0 or self._pos > self._ranges[i]._ent_end:
100
 
            mutter('Bisect for pos: %s failed. Found offset: %d, ranges:%s',
101
 
                   self._pos, i, self._ranges)
102
 
            raise errors.InvalidRange(self._path, self._pos)
103
 
 
104
 
        r = self._ranges[i]
105
 
 
106
 
        # mutter('found range %s %s for pos %s', i, self._ranges[i], self._pos)
107
 
 
108
 
        if (self._pos + size - 1) > r._ent_end:
109
 
            raise errors.InvalidRange(self._path, self._pos)
110
 
 
111
 
        start = r._data_start + (self._pos - r._ent_start)
112
 
        end   = start + size
113
 
        # mutter("range read %d bytes at %d == %d-%d", size, self._pos,
114
 
        #         start, end)
115
 
        self._pos += (end-start)
116
 
        return self._data[start:end]
 
211
        if (self._size > 0
 
212
            and self._pos == self._start + self._size):
 
213
            if size == 0:
 
214
                return ''
 
215
            else:
 
216
                self._seek_to_next_range()
 
217
        elif self._pos < self._start:
 
218
            raise errors.InvalidRange(
 
219
                self._path, self._pos,
 
220
                "Can't read %s bytes before range (%s, %s)"
 
221
                % (size, self._start, self._size))
 
222
        if self._size > 0:
 
223
            if size > 0 and self._pos + size > self._start + self._size:
 
224
                raise errors.InvalidRange(
 
225
                    self._path, self._pos,
 
226
                    "Can't read %s bytes across range (%s, %s)"
 
227
                    % (size, self._start, self._size))
 
228
 
 
229
        # read data from file
 
230
        buffer = StringIO()
 
231
        limited = size
 
232
        if self._size > 0:
 
233
            # Don't read past the range definition
 
234
            limited = self._start + self._size - self._pos
 
235
            if size >= 0:
 
236
                limited = min(limited, size)
 
237
        osutils.pumpfile(self._file, buffer, limited, self._max_read_size)
 
238
        data = buffer.getvalue()
 
239
 
 
240
        # Update _pos respecting the data effectively read
 
241
        self._pos += len(data)
 
242
        return data
117
243
 
118
244
    def seek(self, offset, whence=0):
 
245
        start_pos = self._pos
119
246
        if whence == 0:
120
 
            self._pos = offset
 
247
            final_pos = offset
121
248
        elif whence == 1:
122
 
            self._pos += offset
 
249
            final_pos = start_pos + offset
123
250
        elif whence == 2:
124
 
            self._pos = self._len + offset
 
251
            if self._size > 0:
 
252
                final_pos = self._start + self._size + offset # offset < 0
 
253
            else:
 
254
                raise errors.InvalidRange(
 
255
                    self._path, self._pos,
 
256
                    "RangeFile: can't seek from end while size is unknown")
125
257
        else:
126
258
            raise ValueError("Invalid value %s for whence." % whence)
127
259
 
128
 
        if self._pos < 0:
129
 
            self._pos = 0
 
260
        if final_pos < self._pos:
 
261
            # Can't seek backwards
 
262
            raise errors.InvalidRange(
 
263
                self._path, self._pos,
 
264
                'RangeFile: trying to seek backwards to %s' % final_pos)
 
265
 
 
266
        if self._size > 0:
 
267
            cur_limit = self._start + self._size
 
268
            while final_pos > cur_limit:
 
269
                # We will cross range boundaries
 
270
                remain = cur_limit - self._pos
 
271
                if remain > 0:
 
272
                    # Finish reading the current range
 
273
                    self._checked_read(remain)
 
274
                self._seek_to_next_range()
 
275
                cur_limit = self._start + self._size
 
276
 
 
277
        size = final_pos - self._pos
 
278
        if size > 0: # size can be < 0 if we crossed a range boundary
 
279
            # We don't need the data, just read it and throw it away
 
280
            self._checked_read(size)
130
281
 
131
282
    def tell(self):
132
283
        return self._pos
133
284
 
134
285
 
135
 
class HttpRangeResponse(RangeFile):
136
 
    """A single-range HTTP response."""
137
 
 
138
 
    # TODO: jam 20060706 Consider compiling these regexes on demand
139
 
    _CONTENT_RANGE_RE = re.compile(
140
 
        r'\s*([^\s]+)\s+([0-9]+)-([0-9]+)/([0-9]+)\s*$')
141
 
 
142
 
    def __init__(self, path, content_range, input_file):
143
 
        # mutter("parsing 206 non-multipart response for %s", path)
144
 
        RangeFile.__init__(self, path, input_file)
145
 
        start, end = self._parse_range(content_range, path)
146
 
        self._add_range(start, end, 0)
147
 
        self._finish_ranges()
148
 
 
149
 
    @staticmethod
150
 
    def _parse_range(range, path='<unknown>'):
151
 
        """Parse an http Content-range header and return start + end
152
 
 
153
 
        :param range: The value for Content-range
154
 
        :param path: Provide to give better error messages.
155
 
        :return: (start, end) A tuple of integers
156
 
        """
157
 
        match = HttpRangeResponse._CONTENT_RANGE_RE.match(range)
158
 
        if not match:
159
 
            raise errors.InvalidHttpRange(path, range,
160
 
                                          "Invalid Content-range")
161
 
 
162
 
        rtype, start, end, total = match.groups()
163
 
 
164
 
        if rtype != 'bytes':
165
 
            raise errors.InvalidHttpRange(path, range,
166
 
                    "Unsupported range type '%s'" % (rtype,))
167
 
 
168
 
        try:
169
 
            start = int(start)
170
 
            end = int(end)
171
 
        except ValueError, e:
172
 
            raise errors.InvalidHttpRange(path, range, str(e))
173
 
 
174
 
        return start, end
175
 
 
176
 
 
177
 
class HttpMultipartRangeResponse(RangeFile):
178
 
    """A multi-range HTTP response."""
179
 
    
180
 
    _CONTENT_TYPE_RE = re.compile(
181
 
        r'^\s*multipart/byteranges\s*;\s*boundary\s*=\s*("?)([^"]*?)\1\s*$')
182
 
    
183
 
    # Start with --<boundary>\r\n
184
 
    # and ignore all headers ending in \r\n
185
 
    # except for content-range:
186
 
    # and find the two trailing \r\n separators
187
 
    # indicating the start of the text
188
 
    # TODO: jam 20060706 This requires exact conformance
189
 
    #       to the spec, we probably could relax the requirement
190
 
    #       of \r\n, and use something more like (\r?\n)
191
 
    _BOUNDARY_PATT = (
192
 
        "^--%s(?:\r\n(?:(?:content-range:([^\r]+))|[^\r]+))+\r\n\r\n")
193
 
 
194
 
    def __init__(self, path, content_type, input_file):
195
 
        # mutter("parsing 206 multipart response for %s", path)
196
 
        # TODO: jam 20060706 Is it valid to initialize a
197
 
        #       grandparent without initializing parent?
198
 
        RangeFile.__init__(self, path, input_file)
199
 
 
200
 
        self.boundary_regex = self._parse_boundary(content_type, path)
201
 
        # mutter('response:\n%r', self._data)
202
 
 
203
 
        for match in self.boundary_regex.finditer(self._data):
204
 
            ent_start, ent_end = HttpRangeResponse._parse_range(match.group(1),
205
 
                                                                path)
206
 
            self._add_range(ent_start, ent_end, match.end())
207
 
 
208
 
        self._finish_ranges()
209
 
 
210
 
    @staticmethod
211
 
    def _parse_boundary(ctype, path='<unknown>'):
212
 
        """Parse the Content-type field.
213
 
        
214
 
        This expects a multipart Content-type, and returns a
215
 
        regex which is capable of finding the boundaries
216
 
        in the multipart data.
217
 
        """
218
 
        match = HttpMultipartRangeResponse._CONTENT_TYPE_RE.match(ctype)
219
 
        if not match:
220
 
            raise errors.InvalidHttpContentType(path, ctype,
221
 
                    "Expected multipart/byteranges with boundary")
222
 
 
223
 
        boundary = match.group(2)
224
 
        # mutter('multipart boundary is %s', boundary)
225
 
        pattern = HttpMultipartRangeResponse._BOUNDARY_PATT
226
 
        return re.compile(pattern % re.escape(boundary),
227
 
                          re.IGNORECASE | re.MULTILINE)
228
 
 
229
 
 
230
 
def _is_multipart(content_type):
231
 
    return content_type.startswith('multipart/byteranges;')
232
 
 
233
 
 
234
 
def handle_response(url, code, headers, data):
235
 
    """Interpret the code & headers and return a HTTP response.
236
 
 
237
 
    This is a factory method which returns an appropriate HTTP response
238
 
    based on the code & headers it's given.
 
286
def handle_response(url, code, msg, data):
 
287
    """Interpret the code & headers and wrap the provided data in a RangeFile.
 
288
 
 
289
    This is a factory method which returns an appropriate RangeFile based on
 
290
    the code & headers it's given.
239
291
 
240
292
    :param url: The url being processed. Mostly for error reporting
241
293
    :param code: The integer HTTP response code
242
 
    :param headers: A dict-like object that contains the HTTP response headers
 
294
    :param msg: An HTTPMessage containing the headers for the response
243
295
    :param data: A file-like object that can be read() to get the
244
296
                 requested data
245
 
    :return: A file-like object that can seek()+read() the 
 
297
    :return: A file-like object that can seek()+read() the
246
298
             ranges indicated by the headers.
247
299
    """
248
 
 
249
 
    if code == 206:
250
 
        try:
251
 
            content_type = headers['Content-Type']
252
 
        except KeyError:
253
 
            # When there is no content-type header we treat
254
 
            # the response as being of type 'application/octet-stream' as per
255
 
            # RFC2616 section 7.2.1.
 
300
    rfile = RangeFile(url, data)
 
301
    if code == 200:
 
302
        # A whole file
 
303
        size = msg.getheader('content-length', None)
 
304
        if size is None:
 
305
            size = -1
 
306
        else:
 
307
            size = int(size)
 
308
        rfile.set_range(0, size)
 
309
    elif code == 206:
 
310
        content_type = msg.getheader('content-type', None)
 
311
        if content_type is None:
 
312
            # When there is no content-type header we treat the response as
 
313
            # being of type 'application/octet-stream' as per RFC2616 section
 
314
            # 7.2.1.
256
315
            # Therefore it is obviously not multipart
257
316
            content_type = 'application/octet-stream'
258
317
            is_multipart = False
259
318
        else:
260
 
            is_multipart = _is_multipart(content_type)
 
319
            is_multipart = (msg.getmaintype() == 'multipart'
 
320
                            and msg.getsubtype() == 'byteranges')
261
321
 
262
322
        if is_multipart:
263
323
            # Full fledged multipart response
264
 
            return HttpMultipartRangeResponse(url, content_type, data)
 
324
            rfile.set_boundary(msg.getparam('boundary'))
265
325
        else:
266
326
            # A response to a range request, but not multipart
267
 
            try:
268
 
                content_range = headers['Content-Range']
269
 
            except KeyError:
 
327
            content_range = msg.getheader('content-range', None)
 
328
            if content_range is None:
270
329
                raise errors.InvalidHttpResponse(url,
271
330
                    'Missing the Content-Range header in a 206 range response')
272
 
            return HttpRangeResponse(url, content_range, data)
273
 
    elif code == 200:
274
 
        # A regular non-range response, unfortunately the result from
275
 
        # urllib doesn't support seek, so we wrap it in a StringIO
276
 
        tell = getattr(data, 'tell', None)
277
 
        if tell is None:
278
 
            return StringIO(data.read())
279
 
        return data
280
 
    elif code == 404:
281
 
        raise errors.NoSuchFile(url)
282
 
    elif code == 416:
283
 
        # We don't know which, but one of the ranges we specified
284
 
        # was wrong. So we raise with 0 for a lack of a better
285
 
        # magic value.
286
 
        raise errors.InvalidRange(url,0)
287
 
 
288
 
    # TODO: jam 20060713 Properly handle redirects (302 Found, etc)
289
 
    #       The '_get' code says to follow redirects, we probably 
290
 
    #       should actually handle the return values
 
331
            rfile.set_range_from_header(content_range)
291
332
    else:
292
 
        raise errors.InvalidHttpResponse(url, "Unknown response code %s" 
293
 
                                              % (code,))
 
333
        raise errors.InvalidHttpResponse(url,
 
334
                                         'Unknown response code %s' % code)
 
335
 
 
336
    return rfile
294
337