26
from cStringIO import StringIO
24
from __future__ import absolute_import
28
import http.client as http_client
29
except ImportError: # python < 3
30
import httplib as http_client
32
import email.utils as email_utils
33
except ImportError: # python < 3
34
import rfc822 as email_utils
40
from ...sixish import (
46
class ResponseFile(object):
47
"""A wrapper around the http socket containing the result of a GET request.
49
Only read() and seek() (forward) are supported.
52
def __init__(self, path, infile):
55
:param path: File url, for error reports.
57
:param infile: File-like socket set at body start.
66
Dummy implementation for consistency with the 'file' API.
72
def __exit__(self, exc_type, exc_val, exc_tb):
73
return False # propogate exceptions.
75
def read(self, size=None):
76
"""Read size bytes from the current position in the file.
78
:param size: The number of bytes to read. Leave unspecified or pass
81
if size is None and not PY3:
83
data = self._file.read(size)
84
self._pos += len(data)
88
data = self._file.readline()
89
self._pos += len(data)
94
line = self.readline()
102
def seek(self, offset, whence=os.SEEK_SET):
103
if whence == os.SEEK_SET:
104
if offset < self._pos:
105
raise AssertionError(
106
"Can't seek backwards, pos: %s, offset: %s"
107
% (self._pos, offset))
108
to_discard = offset - self._pos
109
elif whence == os.SEEK_CUR:
112
raise AssertionError("Can't seek backwards")
114
# Just discard the unwanted bytes
115
self.read(to_discard)
36
117
# A RangeFile expects the following grammar (simplified to outline the
37
118
# assumptions we rely upon).
41
121
# | multiple_range
43
# whole_file: [content_length_header] data
45
123
# single_range: content_range_header data
47
125
# multiple_range: boundary_header boundary (content_range_header data boundary)+
49
class RangeFile(object):
127
class RangeFile(ResponseFile):
50
128
"""File-like object that allow access to partial available data.
52
130
All accesses should happen sequentially since the acquisition occurs during
61
139
# in _checked_read() below, we may have to discard several MB in the worst
62
140
# 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
141
# instead. The underlying file is either a socket or a BytesIO, so reading
64
142
# 8k chunks should be fine.
65
143
_discarded_buf_size = 8192
73
151
:param path: File url, for error reports.
74
153
:param infile: File-like socket set at body start.
155
super(RangeFile, self).__init__(path, infile)
78
156
self._boundary = None
79
157
# When using multi parts response, this will be set with the headers
80
158
# associated with the range currently read.
95
173
The file should be at the beginning of the body, the first range
96
174
definition is read and taken into account.
176
if not isinstance(boundary, bytes):
177
raise TypeError(boundary)
98
178
self._boundary = boundary
99
179
# Decode the headers and setup the first range
100
180
self.read_boundary()
103
183
def read_boundary(self):
104
184
"""Read the boundary headers defining a new range"""
105
boundary_line = '\r\n'
106
while boundary_line == '\r\n':
185
boundary_line = b'\r\n'
186
while boundary_line == b'\r\n':
107
187
# RFC2616 19.2 Additional CRLFs may precede the first boundary
109
189
# To be on the safe side we allow it before any boundary line
110
190
boundary_line = self._file.readline()
112
if boundary_line != '--' + self._boundary + '\r\n':
113
# rfc822.unquote() incorrectly unquotes strings enclosed in <>
192
if boundary_line == b'':
193
# A timeout in the proxy server caused the response to end early.
194
# See launchpad bug 198646.
195
raise errors.HttpBoundaryMissing(
199
if boundary_line != b'--' + self._boundary + b'\r\n':
200
# email_utils.unquote() incorrectly unquotes strings enclosed in <>
114
201
# IIS 6 and 7 incorrectly wrap boundary strings in <>
115
202
# together they make a beautiful bug, which we will be gracious
117
204
if (self._unquote_boundary(boundary_line) !=
118
'--' + self._boundary + '\r\n'):
205
b'--' + self._boundary + b'\r\n'):
119
206
raise errors.InvalidHttpResponse(
121
208
"Expected a boundary (%s) line, got '%s'"
122
209
% (self._boundary, boundary_line))
124
211
def _unquote_boundary(self, b):
125
return b[:2] + rfc822.unquote(b[2:-2]) + b[-2:]
212
return b[:2] + email_utils.unquote(b[2:-2].decode('ascii')).encode('ascii') + b[-2:]
127
214
def read_range_definition(self):
128
215
"""Read a new range definition in a multi parts message.
130
217
Parse the headers including the empty line following them so that we
131
218
are ready to read the data itself.
133
self._headers = httplib.HTTPMessage(self._file, seekable=0)
221
self._headers = http_client.parse_headers(self._file)
223
self._headers = http_client.HTTPMessage(self._file, seekable=0)
134
224
# Extract the range definition
135
content_range = self._headers.getheader('content-range', None)
225
content_range = self._headers.get('content-range', None)
136
226
if content_range is None:
137
227
raise errors.InvalidHttpResponse(
221
311
% (size, self._start, self._size))
223
313
# read data from file
226
316
if self._size > 0:
227
317
# Don't read past the range definition
228
318
limited = self._start + self._size - self._pos
230
320
limited = min(limited, size)
231
osutils.pumpfile(self._file, buffer, limited, self._max_read_size)
232
data = buffer.getvalue()
321
osutils.pumpfile(self._file, buf, limited, self._max_read_size)
322
data = buf.getvalue()
234
324
# Update _pos respecting the data effectively read
235
325
self._pos += len(data)
291
381
:return: A file-like object that can seek()+read() the
292
382
ranges indicated by the headers.
294
rfile = RangeFile(url, data)
297
size = msg.getheader('content-length', None)
302
rfile.set_range(0, size)
386
rfile = ResponseFile(url, data)
303
387
elif code == 206:
304
content_type = msg.getheader('content-type', None)
388
rfile = RangeFile(url, data)
389
content_type = msg.get('content-type', None)
305
390
if content_type is None:
306
391
# When there is no content-type header we treat the response as
307
392
# being of type 'application/octet-stream' as per RFC2616 section
310
395
content_type = 'application/octet-stream'
311
396
is_multipart = False
313
is_multipart = (msg.getmaintype() == 'multipart'
314
and msg.getsubtype() == 'byteranges')
399
is_multipart = (msg.get_content_maintype() == 'multipart'
400
and msg.get_content_subtype() == 'byteranges')
402
is_multipart = (msg.getmaintype() == 'multipart'
403
and msg.getsubtype() == 'byteranges')
317
406
# Full fledged multipart response
318
rfile.set_boundary(msg.getparam('boundary'))
408
boundary = msg.get_param('boundary')
410
boundary = msg.getparam('boundary')
411
rfile.set_boundary(boundary.encode('ascii'))
320
413
# A response to a range request, but not multipart
321
content_range = msg.getheader('content-range', None)
414
content_range = msg.get('content-range', None)
322
415
if content_range is None:
323
416
raise errors.InvalidHttpResponse(url,
324
417
'Missing the Content-Range header in a 206 range response')