1
# Copyright (C) 2006-2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Handlers for HTTP Responses.
19
The purpose of these classes is to provide a uniform interface for clients
20
to standard HTTP responses, single range responses and multipart range
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 (
45
class ResponseFile(object):
46
"""A wrapper around the http socket containing the result of a GET request.
48
Only read() and seek() (forward) are supported.
51
def __init__(self, path, infile):
54
:param path: File url, for error reports.
56
:param infile: File-like socket set at body start.
65
Dummy implementation for consistency with the 'file' API.
68
def read(self, size=-1):
69
"""Read size bytes from the current position in the file.
71
:param size: The number of bytes to read. Leave unspecified or pass
74
data = self._file.read(size)
75
self._pos += len(data)
79
data = self._file.readline()
80
self._pos += len(data)
85
line = self.readline()
93
def seek(self, offset, whence=os.SEEK_SET):
94
if whence == os.SEEK_SET:
95
if offset < self._pos:
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:
103
raise AssertionError("Can't seek backwards")
105
# Just discard the unwanted bytes
106
self.read(to_discard)
108
# A RangeFile expects the following grammar (simplified to outline the
109
# assumptions we rely upon).
114
# single_range: content_range_header data
116
# multiple_range: boundary_header boundary (content_range_header data boundary)+
118
class RangeFile(ResponseFile):
119
"""File-like object that allow access to partial available data.
121
All accesses should happen sequentially since the acquisition occurs during
122
an http response reception (as sockets can't be seeked, we simulate the
123
seek by just reading and discarding the data).
125
The access pattern is defined by a set of ranges discovered as reading
126
progress. Only one range is available at a given time, so all accesses
127
should happen with monotonically increasing offsets.
130
# in _checked_read() below, we may have to discard several MB in the worst
131
# case. To avoid buffering that much, we read and discard by chunks
132
# instead. The underlying file is either a socket or a BytesIO, so reading
133
# 8k chunks should be fine.
134
_discarded_buf_size = 8192
136
# maximum size of read requests -- used to avoid MemoryError issues in recv
137
_max_read_size = 512 * 1024
139
def __init__(self, path, infile):
142
:param path: File url, for error reports.
144
:param infile: File-like socket set at body start.
146
super(RangeFile, self).__init__(path, infile)
147
self._boundary = None
148
# When using multi parts response, this will be set with the headers
149
# associated with the range currently read.
151
# Default to the whole file of unspecified size
152
self.set_range(0, -1)
154
def set_range(self, start, size):
155
"""Change the range mapping"""
158
# Set the new _pos since that's what we want to expose
159
self._pos = self._start
161
def set_boundary(self, boundary):
162
"""Define the boundary used in a multi parts message.
164
The file should be at the beginning of the body, the first range
165
definition is read and taken into account.
167
self._boundary = boundary
168
# Decode the headers and setup the first range
170
self.read_range_definition()
172
def read_boundary(self):
173
"""Read the boundary headers defining a new range"""
174
boundary_line = '\r\n'
175
while boundary_line == '\r\n':
176
# RFC2616 19.2 Additional CRLFs may precede the first boundary
178
# To be on the safe side we allow it before any boundary line
179
boundary_line = self._file.readline()
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(
188
if boundary_line != '--' + self._boundary + '\r\n':
189
# email_utils.unquote() incorrectly unquotes strings enclosed in <>
190
# IIS 6 and 7 incorrectly wrap boundary strings in <>
191
# together they make a beautiful bug, which we will be gracious
193
if (self._unquote_boundary(boundary_line) !=
194
'--' + self._boundary + '\r\n'):
195
raise errors.InvalidHttpResponse(
197
"Expected a boundary (%s) line, got '%s'"
198
% (self._boundary, boundary_line))
200
def _unquote_boundary(self, b):
201
return b[:2] + email_utils.unquote(b[2:-2]) + b[-2:]
203
def read_range_definition(self):
204
"""Read a new range definition in a multi parts message.
206
Parse the headers including the empty line following them so that we
207
are ready to read the data itself.
209
self._headers = http_client.HTTPMessage(self._file, seekable=0)
210
# Extract the range definition
211
content_range = self._headers.getheader('content-range', None)
212
if content_range is None:
213
raise errors.InvalidHttpResponse(
215
'Content-Range header missing in a multi-part response')
216
self.set_range_from_header(content_range)
218
def set_range_from_header(self, content_range):
219
"""Helper to set the new range from its description in the headers"""
221
rtype, values = content_range.split()
223
raise errors.InvalidHttpRange(self._path, content_range,
226
raise errors.InvalidHttpRange(self._path, content_range,
227
"Unsupported range type '%s'" % rtype)
229
# We don't need total, but note that it may be either the file size
230
# or '*' if the server can't or doesn't want to return the file
232
start_end, total = values.split('/')
233
start, end = start_end.split('-')
237
raise errors.InvalidHttpRange(self._path, content_range,
238
'Invalid range values')
239
size = end - start + 1
241
raise errors.InvalidHttpRange(self._path, content_range,
242
'Invalid range, size <= 0')
243
self.set_range(start, size)
245
def _checked_read(self, size):
246
"""Read the file checking for short reads.
248
The data read is discarded along the way.
253
data = self._file.read(min(remaining, self._discarded_buf_size))
254
remaining -= len(data)
256
raise errors.ShortReadvError(self._path, pos, size,
260
def _seek_to_next_range(self):
261
# We will cross range boundaries
262
if self._boundary is None:
263
# If we don't have a boundary, we can't find another range
264
raise errors.InvalidRange(self._path, self._pos,
265
"Range (%s, %s) exhausted"
266
% (self._start, self._size))
268
self.read_range_definition()
270
def read(self, size=-1):
271
"""Read size bytes from the current position in the file.
273
Reading across ranges is not supported. We rely on the underlying http
274
client to clean the socket if we leave bytes unread. This may occur for
275
the final boundary line of a multipart response or for any range
276
request not entirely consumed by the client (due to offset coalescing)
278
:param size: The number of bytes to read. Leave unspecified or pass
282
and self._pos == self._start + self._size):
286
self._seek_to_next_range()
287
elif self._pos < self._start:
288
raise errors.InvalidRange(
289
self._path, self._pos,
290
"Can't read %s bytes before range (%s, %s)"
291
% (size, self._start, self._size))
293
if size > 0 and self._pos + size > self._start + self._size:
294
raise errors.InvalidRange(
295
self._path, self._pos,
296
"Can't read %s bytes across range (%s, %s)"
297
% (size, self._start, self._size))
299
# read data from file
303
# Don't read past the range definition
304
limited = self._start + self._size - self._pos
306
limited = min(limited, size)
307
osutils.pumpfile(self._file, buf, limited, self._max_read_size)
308
data = buf.getvalue()
310
# Update _pos respecting the data effectively read
311
self._pos += len(data)
314
def seek(self, offset, whence=0):
315
start_pos = self._pos
319
final_pos = start_pos + offset
322
final_pos = self._start + self._size + offset # offset < 0
324
raise errors.InvalidRange(
325
self._path, self._pos,
326
"RangeFile: can't seek from end while size is unknown")
328
raise ValueError("Invalid value %s for whence." % whence)
330
if final_pos < self._pos:
331
# Can't seek backwards
332
raise errors.InvalidRange(
333
self._path, self._pos,
334
'RangeFile: trying to seek backwards to %s' % final_pos)
337
cur_limit = self._start + self._size
338
while final_pos > cur_limit:
339
# We will cross range boundaries
340
remain = cur_limit - self._pos
342
# Finish reading the current range
343
self._checked_read(remain)
344
self._seek_to_next_range()
345
cur_limit = self._start + self._size
347
size = final_pos - self._pos
348
if size > 0: # size can be < 0 if we crossed a range boundary
349
# We don't need the data, just read it and throw it away
350
self._checked_read(size)
356
def handle_response(url, code, msg, data):
357
"""Interpret the code & headers and wrap the provided data in a RangeFile.
359
This is a factory method which returns an appropriate RangeFile based on
360
the code & headers it's given.
362
:param url: The url being processed. Mostly for error reporting
363
:param code: The integer HTTP response code
364
:param msg: An HTTPMessage containing the headers for the response
365
:param data: A file-like object that can be read() to get the
367
:return: A file-like object that can seek()+read() the
368
ranges indicated by the headers.
372
rfile = ResponseFile(url, data)
374
rfile = RangeFile(url, data)
375
content_type = msg.getheader('content-type', None)
376
if content_type is None:
377
# When there is no content-type header we treat the response as
378
# being of type 'application/octet-stream' as per RFC2616 section
380
# Therefore it is obviously not multipart
381
content_type = 'application/octet-stream'
384
is_multipart = (msg.getmaintype() == 'multipart'
385
and msg.getsubtype() == 'byteranges')
388
# Full fledged multipart response
389
rfile.set_boundary(msg.getparam('boundary'))
391
# A response to a range request, but not multipart
392
content_range = msg.getheader('content-range', None)
393
if content_range is None:
394
raise errors.InvalidHttpResponse(url,
395
'Missing the Content-Range header in a 206 range response')
396
rfile.set_range_from_header(content_range)
398
raise errors.InvalidHttpResponse(url,
399
'Unknown response code %s' % code)