/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

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

  • Committer: Martin
  • Date: 2018-07-03 17:23:08 UTC
  • mto: (7027.4.10 python3-blackbox)
  • mto: This revision was merged to the branch mainline in revision 7028.
  • Revision ID: gzlist@googlemail.com-20180703172308-lre82d15bfkdv48e
Fixup low level knit tests for Python 3

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2011 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Handlers for HTTP Responses.
 
18
 
 
19
The purpose of these classes is to provide a uniform interface for clients
 
20
to standard HTTP responses, single range responses and multipart range
 
21
responses.
 
22
"""
 
23
 
 
24
from __future__ import absolute_import
 
25
 
 
26
import os
 
27
try:
 
28
    import http.client as http_client
 
29
except ImportError:  # python < 3
 
30
    import httplib as http_client
 
31
try:
 
32
    import email.utils as email_utils
 
33
except ImportError:  # python < 3
 
34
    import rfc822 as email_utils
 
35
 
 
36
from ... import (
 
37
    errors,
 
38
    osutils,
 
39
    )
 
40
from ...sixish import (
 
41
    BytesIO,
 
42
    )
 
43
 
 
44
 
 
45
class ResponseFile(object):
 
46
    """A wrapper around the http socket containing the result of a GET request.
 
47
 
 
48
    Only read() and seek() (forward) are supported.
 
49
 
 
50
    """
 
51
    def __init__(self, path, infile):
 
52
        """Constructor.
 
53
 
 
54
        :param path: File url, for error reports.
 
55
 
 
56
        :param infile: File-like socket set at body start.
 
57
        """
 
58
        self._path = path
 
59
        self._file = infile
 
60
        self._pos = 0
 
61
 
 
62
    def close(self):
 
63
        """Close this file.
 
64
 
 
65
        Dummy implementation for consistency with the 'file' API.
 
66
        """
 
67
 
 
68
    def read(self, size=-1):
 
69
        """Read size bytes from the current position in the file.
 
70
 
 
71
        :param size:  The number of bytes to read.  Leave unspecified or pass
 
72
            -1 to read to EOF.
 
73
        """
 
74
        data =  self._file.read(size)
 
75
        self._pos += len(data)
 
76
        return data
 
77
 
 
78
    def readline(self):
 
79
        data = self._file.readline()
 
80
        self._pos += len(data)
 
81
        return data
 
82
 
 
83
    def __iter__(self):
 
84
        while True:
 
85
            line = self.readline()
 
86
            if not line:
 
87
                return
 
88
            yield line
 
89
 
 
90
    def tell(self):
 
91
        return self._pos
 
92
 
 
93
    def seek(self, offset, whence=os.SEEK_SET):
 
94
        if whence == os.SEEK_SET:
 
95
            if offset < self._pos:
 
96
                raise AssertionError(
 
97
                    "Can't seek backwards, pos: %s, offset: %s"
 
98
                    % (self._pos, offset))
 
99
            to_discard = offset - self._pos
 
100
        elif whence == os.SEEK_CUR:
 
101
            to_discard = offset
 
102
        else:
 
103
            raise AssertionError("Can't seek backwards")
 
104
        if to_discard:
 
105
            # Just discard the unwanted bytes
 
106
            self.read(to_discard)
 
107
 
 
108
# A RangeFile expects the following grammar (simplified to outline the
 
109
# assumptions we rely upon).
 
110
 
 
111
# file: single_range
 
112
#     | multiple_range
 
113
 
 
114
# single_range: content_range_header data
 
115
 
 
116
# multiple_range: boundary_header boundary (content_range_header data boundary)+
 
117
 
 
118
class RangeFile(ResponseFile):
 
119
    """File-like object that allow access to partial available data.
 
120
 
 
121
    All accesses should happen sequentially since the acquisition occurs during
 
122
    an http response reception (as sockets can't be seeked, we simulate the
 
123
    seek by just reading and discarding the data).
 
124
 
 
125
    The access pattern is defined by a set of ranges discovered as reading
 
126
    progress. Only one range is available at a given time, so all accesses
 
127
    should happen with monotonically increasing offsets.
 
128
    """
 
129
 
 
130
    # in _checked_read() below, we may have to discard several MB in the worst
 
131
    # case. To avoid buffering that much, we read and discard by chunks
 
132
    # instead. The underlying file is either a socket or a BytesIO, so reading
 
133
    # 8k chunks should be fine.
 
134
    _discarded_buf_size = 8192
 
135
 
 
136
    # maximum size of read requests -- used to avoid MemoryError issues in recv
 
137
    _max_read_size = 512 * 1024
 
138
 
 
139
    def __init__(self, path, infile):
 
140
        """Constructor.
 
141
 
 
142
        :param path: File url, for error reports.
 
143
 
 
144
        :param infile: File-like socket set at body start.
 
145
        """
 
146
        super(RangeFile, self).__init__(path, infile)
 
147
        self._boundary = None
 
148
        # When using multi parts response, this will be set with the headers
 
149
        # associated with the range currently read.
 
150
        self._headers = None
 
151
        # Default to the whole file of unspecified size
 
152
        self.set_range(0, -1)
 
153
 
 
154
    def set_range(self, start, size):
 
155
        """Change the range mapping"""
 
156
        self._start = start
 
157
        self._size = size
 
158
        # Set the new _pos since that's what we want to expose
 
159
        self._pos = self._start
 
160
 
 
161
    def set_boundary(self, boundary):
 
162
        """Define the boundary used in a multi parts message.
 
163
 
 
164
        The file should be at the beginning of the body, the first range
 
165
        definition is read and taken into account.
 
166
        """
 
167
        self._boundary = boundary
 
168
        # Decode the headers and setup the first range
 
169
        self.read_boundary()
 
170
        self.read_range_definition()
 
171
 
 
172
    def read_boundary(self):
 
173
        """Read the boundary headers defining a new range"""
 
174
        boundary_line = '\r\n'
 
175
        while boundary_line == '\r\n':
 
176
            # RFC2616 19.2 Additional CRLFs may precede the first boundary
 
177
            # string entity.
 
178
            # To be on the safe side we allow it before any boundary line
 
179
            boundary_line = self._file.readline()
 
180
 
 
181
        if boundary_line == '':
 
182
            # A timeout in the proxy server caused the response to end early.
 
183
            # See launchpad bug 198646.
 
184
            raise errors.HttpBoundaryMissing(
 
185
                self._path,
 
186
                self._boundary)
 
187
 
 
188
        if boundary_line != '--' + self._boundary + '\r\n':
 
189
            # email_utils.unquote() incorrectly unquotes strings enclosed in <>
 
190
            # IIS 6 and 7 incorrectly wrap boundary strings in <>
 
191
            # together they make a beautiful bug, which we will be gracious
 
192
            # about here
 
193
            if (self._unquote_boundary(boundary_line) !=
 
194
                '--' + self._boundary + '\r\n'):
 
195
                raise errors.InvalidHttpResponse(
 
196
                    self._path,
 
197
                    "Expected a boundary (%s) line, got '%s'"
 
198
                    % (self._boundary, boundary_line))
 
199
 
 
200
    def _unquote_boundary(self, b):
 
201
        return b[:2] + email_utils.unquote(b[2:-2]) + b[-2:]
 
202
 
 
203
    def read_range_definition(self):
 
204
        """Read a new range definition in a multi parts message.
 
205
 
 
206
        Parse the headers including the empty line following them so that we
 
207
        are ready to read the data itself.
 
208
        """
 
209
        self._headers = http_client.HTTPMessage(self._file, seekable=0)
 
210
        # Extract the range definition
 
211
        content_range = self._headers.getheader('content-range', None)
 
212
        if content_range is None:
 
213
            raise errors.InvalidHttpResponse(
 
214
                self._path,
 
215
                'Content-Range header missing in a multi-part response')
 
216
        self.set_range_from_header(content_range)
 
217
 
 
218
    def set_range_from_header(self, content_range):
 
219
        """Helper to set the new range from its description in the headers"""
 
220
        try:
 
221
            rtype, values = content_range.split()
 
222
        except ValueError:
 
223
            raise errors.InvalidHttpRange(self._path, content_range,
 
224
                                          'Malformed header')
 
225
        if rtype != 'bytes':
 
226
            raise errors.InvalidHttpRange(self._path, content_range,
 
227
                                          "Unsupported range type '%s'" % rtype)
 
228
        try:
 
229
            # We don't need total, but note that it may be either the file size
 
230
            # or '*' if the server can't or doesn't want to return the file
 
231
            # size.
 
232
            start_end, total = values.split('/')
 
233
            start, end = start_end.split('-')
 
234
            start = int(start)
 
235
            end = int(end)
 
236
        except ValueError:
 
237
            raise errors.InvalidHttpRange(self._path, content_range,
 
238
                                          'Invalid range values')
 
239
        size = end - start + 1
 
240
        if size <= 0:
 
241
            raise errors.InvalidHttpRange(self._path, content_range,
 
242
                                          'Invalid range, size <= 0')
 
243
        self.set_range(start, size)
 
244
 
 
245
    def _checked_read(self, size):
 
246
        """Read the file checking for short reads.
 
247
 
 
248
        The data read is discarded along the way.
 
249
        """
 
250
        pos = self._pos
 
251
        remaining = size
 
252
        while remaining > 0:
 
253
            data = self._file.read(min(remaining, self._discarded_buf_size))
 
254
            remaining -= len(data)
 
255
            if not data:
 
256
                raise errors.ShortReadvError(self._path, pos, size,
 
257
                                             size - remaining)
 
258
        self._pos += size
 
259
 
 
260
    def _seek_to_next_range(self):
 
261
        # We will cross range boundaries
 
262
        if self._boundary is None:
 
263
            # If we don't have a boundary, we can't find another range
 
264
            raise errors.InvalidRange(self._path, self._pos,
 
265
                                      "Range (%s, %s) exhausted"
 
266
                                      % (self._start, self._size))
 
267
        self.read_boundary()
 
268
        self.read_range_definition()
 
269
 
 
270
    def read(self, size=-1):
 
271
        """Read size bytes from the current position in the file.
 
272
 
 
273
        Reading across ranges is not supported. We rely on the underlying http
 
274
        client to clean the socket if we leave bytes unread. This may occur for
 
275
        the final boundary line of a multipart response or for any range
 
276
        request not entirely consumed by the client (due to offset coalescing)
 
277
 
 
278
        :param size:  The number of bytes to read.  Leave unspecified or pass
 
279
            -1 to read to EOF.
 
280
        """
 
281
        if (self._size > 0
 
282
            and self._pos == self._start + self._size):
 
283
            if size == 0:
 
284
                return ''
 
285
            else:
 
286
                self._seek_to_next_range()
 
287
        elif self._pos < self._start:
 
288
            raise errors.InvalidRange(
 
289
                self._path, self._pos,
 
290
                "Can't read %s bytes before range (%s, %s)"
 
291
                % (size, self._start, self._size))
 
292
        if self._size > 0:
 
293
            if size > 0 and self._pos + size > self._start + self._size:
 
294
                raise errors.InvalidRange(
 
295
                    self._path, self._pos,
 
296
                    "Can't read %s bytes across range (%s, %s)"
 
297
                    % (size, self._start, self._size))
 
298
 
 
299
        # read data from file
 
300
        buf = BytesIO()
 
301
        limited = size
 
302
        if self._size > 0:
 
303
            # Don't read past the range definition
 
304
            limited = self._start + self._size - self._pos
 
305
            if size >= 0:
 
306
                limited = min(limited, size)
 
307
        osutils.pumpfile(self._file, buf, limited, self._max_read_size)
 
308
        data = buf.getvalue()
 
309
 
 
310
        # Update _pos respecting the data effectively read
 
311
        self._pos += len(data)
 
312
        return data
 
313
 
 
314
    def seek(self, offset, whence=0):
 
315
        start_pos = self._pos
 
316
        if whence == 0:
 
317
            final_pos = offset
 
318
        elif whence == 1:
 
319
            final_pos = start_pos + offset
 
320
        elif whence == 2:
 
321
            if self._size > 0:
 
322
                final_pos = self._start + self._size + offset # offset < 0
 
323
            else:
 
324
                raise errors.InvalidRange(
 
325
                    self._path, self._pos,
 
326
                    "RangeFile: can't seek from end while size is unknown")
 
327
        else:
 
328
            raise ValueError("Invalid value %s for whence." % whence)
 
329
 
 
330
        if final_pos < self._pos:
 
331
            # Can't seek backwards
 
332
            raise errors.InvalidRange(
 
333
                self._path, self._pos,
 
334
                'RangeFile: trying to seek backwards to %s' % final_pos)
 
335
 
 
336
        if self._size > 0:
 
337
            cur_limit = self._start + self._size
 
338
            while final_pos > cur_limit:
 
339
                # We will cross range boundaries
 
340
                remain = cur_limit - self._pos
 
341
                if remain > 0:
 
342
                    # Finish reading the current range
 
343
                    self._checked_read(remain)
 
344
                self._seek_to_next_range()
 
345
                cur_limit = self._start + self._size
 
346
 
 
347
        size = final_pos - self._pos
 
348
        if size > 0: # size can be < 0 if we crossed a range boundary
 
349
            # We don't need the data, just read it and throw it away
 
350
            self._checked_read(size)
 
351
 
 
352
    def tell(self):
 
353
        return self._pos
 
354
 
 
355
 
 
356
def handle_response(url, code, msg, data):
 
357
    """Interpret the code & headers and wrap the provided data in a RangeFile.
 
358
 
 
359
    This is a factory method which returns an appropriate RangeFile based on
 
360
    the code & headers it's given.
 
361
 
 
362
    :param url: The url being processed. Mostly for error reporting
 
363
    :param code: The integer HTTP response code
 
364
    :param msg: An HTTPMessage containing the headers for the response
 
365
    :param data: A file-like object that can be read() to get the
 
366
                 requested data
 
367
    :return: A file-like object that can seek()+read() the
 
368
             ranges indicated by the headers.
 
369
    """
 
370
    if code == 200:
 
371
        # A whole file
 
372
        rfile = ResponseFile(url, data)
 
373
    elif code == 206:
 
374
        rfile = RangeFile(url, data)
 
375
        content_type = msg.getheader('content-type', None)
 
376
        if content_type is None:
 
377
            # When there is no content-type header we treat the response as
 
378
            # being of type 'application/octet-stream' as per RFC2616 section
 
379
            # 7.2.1.
 
380
            # Therefore it is obviously not multipart
 
381
            content_type = 'application/octet-stream'
 
382
            is_multipart = False
 
383
        else:
 
384
            is_multipart = (msg.getmaintype() == 'multipart'
 
385
                            and msg.getsubtype() == 'byteranges')
 
386
 
 
387
        if is_multipart:
 
388
            # Full fledged multipart response
 
389
            rfile.set_boundary(msg.getparam('boundary'))
 
390
        else:
 
391
            # A response to a range request, but not multipart
 
392
            content_range = msg.getheader('content-range', None)
 
393
            if content_range is None:
 
394
                raise errors.InvalidHttpResponse(url,
 
395
                    'Missing the Content-Range header in a 206 range response')
 
396
            rfile.set_range_from_header(content_range)
 
397
    else:
 
398
        raise errors.InvalidHttpResponse(url,
 
399
                                         'Unknown response code %s' % code)
 
400
 
 
401
    return rfile
 
402