/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-09-02 11:51:19 UTC
  • mto: (7490.40.109 work)
  • mto: This revision was merged to the branch mainline in revision 7526.
  • Revision ID: jelmer@jelmer.uk-20200902115119-otuspc349t9rmhua
add test for git file merge.

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