26
from cStringIO import StringIO
25
from io import BytesIO
27
import http.client as http_client
28
import email.utils as email_utils
36
class ResponseFile(object):
37
"""A wrapper around the http socket containing the result of a GET request.
39
Only read() and seek() (forward) are supported.
43
def __init__(self, path, infile):
46
:param path: File url, for error reports.
48
:param infile: File-like socket set at body start.
57
Dummy implementation for consistency with the 'file' API.
63
def __exit__(self, exc_type, exc_val, exc_tb):
64
return False # propogate exceptions.
66
def read(self, size=None):
67
"""Read size bytes from the current position in the file.
69
:param size: The number of bytes to read. Leave unspecified or pass
72
data = self._file.read(size)
73
self._pos += len(data)
77
data = self._file.readline()
78
self._pos += len(data)
81
def readlines(self, size=None):
82
data = self._file.readlines()
83
self._pos += sum(map(len, data))
88
line = self.readline()
96
def seek(self, offset, whence=os.SEEK_SET):
97
if whence == os.SEEK_SET:
98
if offset < self._pos:
100
"Can't seek backwards, pos: %s, offset: %s"
101
% (self._pos, offset))
102
to_discard = offset - self._pos
103
elif whence == os.SEEK_CUR:
106
raise AssertionError("Can't seek backwards")
108
# Just discard the unwanted bytes
109
self.read(to_discard)
36
111
# A RangeFile expects the following grammar (simplified to outline the
37
112
# assumptions we rely upon).
41
115
# | multiple_range
43
# whole_file: [content_length_header] data
45
117
# single_range: content_range_header data
47
119
# multiple_range: boundary_header boundary (content_range_header data boundary)+
49
class RangeFile(object):
122
class RangeFile(ResponseFile):
50
123
"""File-like object that allow access to partial available data.
52
125
All accesses should happen sequentially since the acquisition occurs during
61
134
# in _checked_read() below, we may have to discard several MB in the worst
62
135
# 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
136
# instead. The underlying file is either a socket or a BytesIO, so reading
64
137
# 8k chunks should be fine.
65
138
_discarded_buf_size = 8192
73
146
:param path: File url, for error reports.
74
148
:param infile: File-like socket set at body start.
150
super(RangeFile, self).__init__(path, infile)
78
151
self._boundary = None
79
152
# When using multi parts response, this will be set with the headers
80
153
# associated with the range currently read.
95
168
The file should be at the beginning of the body, the first range
96
169
definition is read and taken into account.
171
if not isinstance(boundary, bytes):
172
raise TypeError(boundary)
98
173
self._boundary = boundary
99
174
# Decode the headers and setup the first range
100
175
self.read_boundary()
103
178
def read_boundary(self):
104
179
"""Read the boundary headers defining a new range"""
105
boundary_line = '\r\n'
106
while boundary_line == '\r\n':
180
boundary_line = b'\r\n'
181
while boundary_line == b'\r\n':
107
182
# RFC2616 19.2 Additional CRLFs may precede the first boundary
109
184
# To be on the safe side we allow it before any boundary line
110
185
boundary_line = self._file.readline()
112
if boundary_line != '--' + self._boundary + '\r\n':
113
# rfc822.unquote() incorrectly unquotes strings enclosed in <>
187
if boundary_line == b'':
188
# A timeout in the proxy server caused the response to end early.
189
# See launchpad bug 198646.
190
raise errors.HttpBoundaryMissing(
194
if boundary_line != b'--' + self._boundary + b'\r\n':
195
# email_utils.unquote() incorrectly unquotes strings enclosed in <>
114
196
# IIS 6 and 7 incorrectly wrap boundary strings in <>
115
197
# together they make a beautiful bug, which we will be gracious
117
199
if (self._unquote_boundary(boundary_line) !=
118
'--' + self._boundary + '\r\n'):
200
b'--' + self._boundary + b'\r\n'):
119
201
raise errors.InvalidHttpResponse(
121
203
"Expected a boundary (%s) line, got '%s'"
122
204
% (self._boundary, boundary_line))
124
206
def _unquote_boundary(self, b):
125
return b[:2] + rfc822.unquote(b[2:-2]) + b[-2:]
207
return b[:2] + email_utils.unquote(b[2:-2].decode('ascii')).encode('ascii') + b[-2:]
127
209
def read_range_definition(self):
128
210
"""Read a new range definition in a multi parts message.
130
212
Parse the headers including the empty line following them so that we
131
213
are ready to read the data itself.
133
self._headers = httplib.HTTPMessage(self._file, seekable=0)
215
self._headers = http_client.parse_headers(self._file)
134
216
# Extract the range definition
135
content_range = self._headers.getheader('content-range', None)
217
content_range = self._headers.get('content-range', None)
136
218
if content_range is None:
137
219
raise errors.InvalidHttpResponse(
221
303
% (size, self._start, self._size))
223
305
# read data from file
226
308
if self._size > 0:
227
309
# Don't read past the range definition
228
310
limited = self._start + self._size - self._pos
230
312
limited = min(limited, size)
231
osutils.pumpfile(self._file, buffer, limited, self._max_read_size)
232
data = buffer.getvalue()
313
osutils.pumpfile(self._file, buf, limited, self._max_read_size)
314
data = buf.getvalue()
234
316
# Update _pos respecting the data effectively read
235
317
self._pos += len(data)
280
def handle_response(url, code, msg, data):
362
def handle_response(url, code, getheader, data):
281
363
"""Interpret the code & headers and wrap the provided data in a RangeFile.
283
365
This is a factory method which returns an appropriate RangeFile based on
286
368
:param url: The url being processed. Mostly for error reporting
287
369
:param code: The integer HTTP response code
288
:param msg: An HTTPMessage containing the headers for the response
370
:param getheader: Function for retrieving header
289
371
:param data: A file-like object that can be read() to get the
291
373
:return: A file-like object that can seek()+read() the
292
374
ranges indicated by the headers.
294
rfile = RangeFile(url, data)
297
size = msg.getheader('content-length', None)
302
rfile.set_range(0, size)
378
rfile = ResponseFile(url, data)
303
379
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
309
# Therefore it is obviously not multipart
310
content_type = 'application/octet-stream'
313
is_multipart = (msg.getmaintype() == 'multipart'
314
and msg.getsubtype() == 'byteranges')
317
# Full fledged multipart response
318
rfile.set_boundary(msg.getparam('boundary'))
380
rfile = RangeFile(url, data)
381
# When there is no content-type header we treat the response as
382
# being of type 'application/octet-stream' as per RFC2616 section
384
# Therefore it is obviously not multipart
385
content_type = getheader('content-type', 'application/octet-stream')
386
mimetype, options = cgi.parse_header(content_type)
387
if mimetype == 'multipart/byteranges':
388
rfile.set_boundary(options['boundary'].encode('ascii'))
320
390
# A response to a range request, but not multipart
321
content_range = msg.getheader('content-range', None)
391
content_range = getheader('content-range', None)
322
392
if content_range is None:
323
raise errors.InvalidHttpResponse(url,
324
'Missing the Content-Range header in a 206 range response')
393
raise errors.InvalidHttpResponse(
394
url, 'Missing the Content-Range header in a 206 range response')
325
395
rfile.set_range_from_header(content_range)
327
raise errors.InvalidHttpResponse(url,
328
'Unknown response code %s' % code)
397
raise errors.UnexpectedHttpStatus(url, code)