/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: 2018-07-08 14:45:27 UTC
  • mto: This revision was merged to the branch mainline in revision 7036.
  • Revision ID: jelmer@jelmer.uk-20180708144527-codhlvdcdg9y0nji
Fix a bunch of merge tests.

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 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 (
30
37
    errors,
31
 
    trace,
32
38
    osutils,
33
39
    )
34
 
 
 
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)
35
107
 
36
108
# A RangeFile expects the following grammar (simplified to outline the
37
109
# assumptions we rely upon).
38
110
 
39
 
# file: whole_file
40
 
#     | single_range
 
111
# file: single_range
41
112
#     | multiple_range
42
113
 
43
 
# whole_file: [content_length_header] data
44
 
 
45
114
# single_range: content_range_header data
46
115
 
47
116
# multiple_range: boundary_header boundary (content_range_header data boundary)+
48
117
 
49
 
class RangeFile(object):
 
118
class RangeFile(ResponseFile):
50
119
    """File-like object that allow access to partial available data.
51
120
 
52
121
    All accesses should happen sequentially since the acquisition occurs during
60
129
 
61
130
    # in _checked_read() below, we may have to discard several MB in the worst
62
131
    # 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
 
132
    # instead. The underlying file is either a socket or a BytesIO, so reading
64
133
    # 8k chunks should be fine.
65
134
    _discarded_buf_size = 8192
66
135
 
71
140
        """Constructor.
72
141
 
73
142
        :param path: File url, for error reports.
 
143
 
74
144
        :param infile: File-like socket set at body start.
75
145
        """
76
 
        self._path = path
77
 
        self._file = infile
 
146
        super(RangeFile, self).__init__(path, infile)
78
147
        self._boundary = None
79
148
        # When using multi parts response, this will be set with the headers
80
149
        # associated with the range currently read.
109
178
            # To be on the safe side we allow it before any boundary line
110
179
            boundary_line = self._file.readline()
111
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
 
112
188
        if boundary_line != '--' + self._boundary + '\r\n':
113
 
            # rfc822.unquote() incorrectly unquotes strings enclosed in <>
 
189
            # email_utils.unquote() incorrectly unquotes strings enclosed in <>
114
190
            # IIS 6 and 7 incorrectly wrap boundary strings in <>
115
191
            # together they make a beautiful bug, which we will be gracious
116
192
            # about here
122
198
                    % (self._boundary, boundary_line))
123
199
 
124
200
    def _unquote_boundary(self, b):
125
 
        return b[:2] + rfc822.unquote(b[2:-2]) + b[-2:]
 
201
        return b[:2] + email_utils.unquote(b[2:-2]) + b[-2:]
126
202
 
127
203
    def read_range_definition(self):
128
204
        """Read a new range definition in a multi parts message.
130
206
        Parse the headers including the empty line following them so that we
131
207
        are ready to read the data itself.
132
208
        """
133
 
        self._headers = httplib.HTTPMessage(self._file, seekable=0)
 
209
        self._headers = http_client.HTTPMessage(self._file, seekable=0)
134
210
        # Extract the range definition
135
211
        content_range = self._headers.getheader('content-range', None)
136
212
        if content_range is None:
221
297
                    % (size, self._start, self._size))
222
298
 
223
299
        # read data from file
224
 
        buffer = StringIO()
 
300
        buf = BytesIO()
225
301
        limited = size
226
302
        if self._size > 0:
227
303
            # Don't read past the range definition
228
304
            limited = self._start + self._size - self._pos
229
305
            if size >= 0:
230
306
                limited = min(limited, size)
231
 
        osutils.pumpfile(self._file, buffer, limited, self._max_read_size)
232
 
        data = buffer.getvalue()
 
307
        osutils.pumpfile(self._file, buf, limited, self._max_read_size)
 
308
        data = buf.getvalue()
233
309
 
234
310
        # Update _pos respecting the data effectively read
235
311
        self._pos += len(data)
291
367
    :return: A file-like object that can seek()+read() the
292
368
             ranges indicated by the headers.
293
369
    """
294
 
    rfile = RangeFile(url, data)
295
370
    if code == 200:
296
371
        # 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)
 
372
        rfile = ResponseFile(url, data)
303
373
    elif code == 206:
 
374
        rfile = RangeFile(url, data)
304
375
        content_type = msg.getheader('content-type', None)
305
376
        if content_type is None:
306
377
            # When there is no content-type header we treat the response as