/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: Jelmer Vernooij
  • Date: 2020-05-24 00:42:36 UTC
  • mto: This revision was merged to the branch mainline in revision 7505.
  • Revision ID: jelmer@jelmer.uk-20200524004236-jdj6obo4k5lznqw2
Cleanup Windows functions.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007 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
21
21
responses.
22
22
"""
23
23
 
24
 
 
25
 
import httplib
26
 
from cStringIO import StringIO
27
 
import rfc822
28
 
 
29
 
from bzrlib import (
 
24
import cgi
 
25
from io import BytesIO
 
26
import os
 
27
import http.client as http_client
 
28
import email.utils as email_utils
 
29
 
 
30
from ... import (
30
31
    errors,
31
 
    trace,
32
32
    osutils,
33
33
    )
34
34
 
35
35
 
 
36
class ResponseFile(object):
 
37
    """A wrapper around the http socket containing the result of a GET request.
 
38
 
 
39
    Only read() and seek() (forward) are supported.
 
40
 
 
41
    """
 
42
 
 
43
    def __init__(self, path, infile):
 
44
        """Constructor.
 
45
 
 
46
        :param path: File url, for error reports.
 
47
 
 
48
        :param infile: File-like socket set at body start.
 
49
        """
 
50
        self._path = path
 
51
        self._file = infile
 
52
        self._pos = 0
 
53
 
 
54
    def close(self):
 
55
        """Close this file.
 
56
 
 
57
        Dummy implementation for consistency with the 'file' API.
 
58
        """
 
59
 
 
60
    def __enter__(self):
 
61
        return self
 
62
 
 
63
    def __exit__(self, exc_type, exc_val, exc_tb):
 
64
        return False  # propogate exceptions.
 
65
 
 
66
    def read(self, size=None):
 
67
        """Read size bytes from the current position in the file.
 
68
 
 
69
        :param size:  The number of bytes to read.  Leave unspecified or pass
 
70
            -1 to read to EOF.
 
71
        """
 
72
        data = self._file.read(size)
 
73
        self._pos += len(data)
 
74
        return data
 
75
 
 
76
    def readline(self):
 
77
        data = self._file.readline()
 
78
        self._pos += len(data)
 
79
        return data
 
80
 
 
81
    def __iter__(self):
 
82
        while True:
 
83
            line = self.readline()
 
84
            if not line:
 
85
                return
 
86
            yield line
 
87
 
 
88
    def tell(self):
 
89
        return self._pos
 
90
 
 
91
    def seek(self, offset, whence=os.SEEK_SET):
 
92
        if whence == os.SEEK_SET:
 
93
            if offset < self._pos:
 
94
                raise AssertionError(
 
95
                    "Can't seek backwards, pos: %s, offset: %s"
 
96
                    % (self._pos, offset))
 
97
            to_discard = offset - self._pos
 
98
        elif whence == os.SEEK_CUR:
 
99
            to_discard = offset
 
100
        else:
 
101
            raise AssertionError("Can't seek backwards")
 
102
        if to_discard:
 
103
            # Just discard the unwanted bytes
 
104
            self.read(to_discard)
 
105
 
36
106
# A RangeFile expects the following grammar (simplified to outline the
37
107
# assumptions we rely upon).
38
108
 
39
 
# file: whole_file
40
 
#     | single_range
 
109
# file: single_range
41
110
#     | multiple_range
42
111
 
43
 
# whole_file: [content_length_header] data
44
 
 
45
112
# single_range: content_range_header data
46
113
 
47
114
# multiple_range: boundary_header boundary (content_range_header data boundary)+
48
115
 
49
 
class RangeFile(object):
 
116
 
 
117
class RangeFile(ResponseFile):
50
118
    """File-like object that allow access to partial available data.
51
119
 
52
120
    All accesses should happen sequentially since the acquisition occurs during
60
128
 
61
129
    # in _checked_read() below, we may have to discard several MB in the worst
62
130
    # case. To avoid buffering that much, we read and discard by chunks
63
 
    # instead. The underlying file is either a socket or a StringIO, so reading
 
131
    # instead. The underlying file is either a socket or a BytesIO, so reading
64
132
    # 8k chunks should be fine.
65
133
    _discarded_buf_size = 8192
66
134
 
71
139
        """Constructor.
72
140
 
73
141
        :param path: File url, for error reports.
 
142
 
74
143
        :param infile: File-like socket set at body start.
75
144
        """
76
 
        self._path = path
77
 
        self._file = infile
 
145
        super(RangeFile, self).__init__(path, infile)
78
146
        self._boundary = None
79
147
        # When using multi parts response, this will be set with the headers
80
148
        # associated with the range currently read.
95
163
        The file should be at the beginning of the body, the first range
96
164
        definition is read and taken into account.
97
165
        """
 
166
        if not isinstance(boundary, bytes):
 
167
            raise TypeError(boundary)
98
168
        self._boundary = boundary
99
169
        # Decode the headers and setup the first range
100
170
        self.read_boundary()
102
172
 
103
173
    def read_boundary(self):
104
174
        """Read the boundary headers defining a new range"""
105
 
        boundary_line = '\r\n'
106
 
        while boundary_line == '\r\n':
 
175
        boundary_line = b'\r\n'
 
176
        while boundary_line == b'\r\n':
107
177
            # RFC2616 19.2 Additional CRLFs may precede the first boundary
108
178
            # string entity.
109
179
            # To be on the safe side we allow it before any boundary line
110
180
            boundary_line = self._file.readline()
111
181
 
112
 
        if boundary_line != '--' + self._boundary + '\r\n':
113
 
            # rfc822.unquote() incorrectly unquotes strings enclosed in <>
 
182
        if boundary_line == b'':
 
183
            # A timeout in the proxy server caused the response to end early.
 
184
            # See launchpad bug 198646.
 
185
            raise errors.HttpBoundaryMissing(
 
186
                self._path,
 
187
                self._boundary)
 
188
 
 
189
        if boundary_line != b'--' + self._boundary + b'\r\n':
 
190
            # email_utils.unquote() incorrectly unquotes strings enclosed in <>
114
191
            # IIS 6 and 7 incorrectly wrap boundary strings in <>
115
192
            # together they make a beautiful bug, which we will be gracious
116
193
            # about here
117
194
            if (self._unquote_boundary(boundary_line) !=
118
 
                '--' + self._boundary + '\r\n'):
 
195
                    b'--' + self._boundary + b'\r\n'):
119
196
                raise errors.InvalidHttpResponse(
120
197
                    self._path,
121
198
                    "Expected a boundary (%s) line, got '%s'"
122
199
                    % (self._boundary, boundary_line))
123
200
 
124
201
    def _unquote_boundary(self, b):
125
 
        return b[:2] + rfc822.unquote(b[2:-2]) + b[-2:]
 
202
        return b[:2] + email_utils.unquote(b[2:-2].decode('ascii')).encode('ascii') + b[-2:]
126
203
 
127
204
    def read_range_definition(self):
128
205
        """Read a new range definition in a multi parts message.
130
207
        Parse the headers including the empty line following them so that we
131
208
        are ready to read the data itself.
132
209
        """
133
 
        self._headers = httplib.HTTPMessage(self._file, seekable=0)
 
210
        self._headers = http_client.parse_headers(self._file)
134
211
        # Extract the range definition
135
 
        content_range = self._headers.getheader('content-range', None)
 
212
        content_range = self._headers.get('content-range', None)
136
213
        if content_range is None:
137
214
            raise errors.InvalidHttpResponse(
138
215
                self._path,
203
280
            -1 to read to EOF.
204
281
        """
205
282
        if (self._size > 0
206
 
            and self._pos == self._start + self._size):
 
283
                and self._pos == self._start + self._size):
207
284
            if size == 0:
208
 
                return ''
 
285
                return b''
209
286
            else:
210
287
                self._seek_to_next_range()
211
288
        elif self._pos < self._start:
221
298
                    % (size, self._start, self._size))
222
299
 
223
300
        # read data from file
224
 
        buffer = StringIO()
 
301
        buf = BytesIO()
225
302
        limited = size
226
303
        if self._size > 0:
227
304
            # Don't read past the range definition
228
305
            limited = self._start + self._size - self._pos
229
306
            if size >= 0:
230
307
                limited = min(limited, size)
231
 
        osutils.pumpfile(self._file, buffer, limited, self._max_read_size)
232
 
        data = buffer.getvalue()
 
308
        osutils.pumpfile(self._file, buf, limited, self._max_read_size)
 
309
        data = buf.getvalue()
233
310
 
234
311
        # Update _pos respecting the data effectively read
235
312
        self._pos += len(data)
243
320
            final_pos = start_pos + offset
244
321
        elif whence == 2:
245
322
            if self._size > 0:
246
 
                final_pos = self._start + self._size + offset # offset < 0
 
323
                final_pos = self._start + self._size + offset  # offset < 0
247
324
            else:
248
325
                raise errors.InvalidRange(
249
326
                    self._path, self._pos,
269
346
                cur_limit = self._start + self._size
270
347
 
271
348
        size = final_pos - self._pos
272
 
        if size > 0: # size can be < 0 if we crossed a range boundary
 
349
        if size > 0:  # size can be < 0 if we crossed a range boundary
273
350
            # We don't need the data, just read it and throw it away
274
351
            self._checked_read(size)
275
352
 
277
354
        return self._pos
278
355
 
279
356
 
280
 
def handle_response(url, code, msg, data):
 
357
def handle_response(url, code, getheader, data):
281
358
    """Interpret the code & headers and wrap the provided data in a RangeFile.
282
359
 
283
360
    This is a factory method which returns an appropriate RangeFile based on
285
362
 
286
363
    :param url: The url being processed. Mostly for error reporting
287
364
    :param code: The integer HTTP response code
288
 
    :param msg: An HTTPMessage containing the headers for the response
 
365
    :param getheader: Function for retrieving header
289
366
    :param data: A file-like object that can be read() to get the
290
367
                 requested data
291
368
    :return: A file-like object that can seek()+read() the
292
369
             ranges indicated by the headers.
293
370
    """
294
 
    rfile = RangeFile(url, data)
295
371
    if code == 200:
296
372
        # A whole file
297
 
        size = msg.getheader('content-length', None)
298
 
        if size is None:
299
 
            size = -1
300
 
        else:
301
 
            size = int(size)
302
 
        rfile.set_range(0, size)
 
373
        rfile = ResponseFile(url, data)
303
374
    elif code == 206:
304
 
        content_type = msg.getheader('content-type', None)
305
 
        if content_type is None:
306
 
            # When there is no content-type header we treat the response as
307
 
            # being of type 'application/octet-stream' as per RFC2616 section
308
 
            # 7.2.1.
309
 
            # Therefore it is obviously not multipart
310
 
            content_type = 'application/octet-stream'
311
 
            is_multipart = False
312
 
        else:
313
 
            is_multipart = (msg.getmaintype() == 'multipart'
314
 
                            and msg.getsubtype() == 'byteranges')
315
 
 
316
 
        if is_multipart:
317
 
            # Full fledged multipart response
318
 
            rfile.set_boundary(msg.getparam('boundary'))
 
375
        rfile = RangeFile(url, data)
 
376
        # When there is no content-type header we treat the response as
 
377
        # being of type 'application/octet-stream' as per RFC2616 section
 
378
        # 7.2.1.
 
379
        # Therefore it is obviously not multipart
 
380
        content_type = getheader('content-type', 'application/octet-stream')
 
381
        mimetype, options = cgi.parse_header(content_type)
 
382
        if mimetype == 'multipart/byteranges':
 
383
            rfile.set_boundary(options['boundary'].encode('ascii'))
319
384
        else:
320
385
            # A response to a range request, but not multipart
321
 
            content_range = msg.getheader('content-range', None)
 
386
            content_range = getheader('content-range', None)
322
387
            if content_range is None:
323
 
                raise errors.InvalidHttpResponse(url,
324
 
                    'Missing the Content-Range header in a 206 range response')
 
388
                raise errors.InvalidHttpResponse(
 
389
                    url, 'Missing the Content-Range header in a 206 range response')
325
390
            rfile.set_range_from_header(content_range)
326
391
    else:
327
392
        raise errors.InvalidHttpResponse(url,
328
393
                                         'Unknown response code %s' % code)
329
394
 
330
395
    return rfile
331