root / pithos / api / util.py @ e809b989
History | View | Annotate | Download (34.6 kB)
1 |
# Copyright 2011-2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
from functools import wraps |
35 |
from time import time |
36 |
from traceback import format_exc |
37 |
from wsgiref.handlers import format_date_time |
38 |
from binascii import hexlify, unhexlify |
39 |
from datetime import datetime, tzinfo, timedelta |
40 |
from urllib import quote, unquote |
41 |
|
42 |
from django.conf import settings |
43 |
from django.http import HttpResponse |
44 |
from django.template.loader import render_to_string |
45 |
from django.utils import simplejson as json |
46 |
from django.utils.http import http_date, parse_etags |
47 |
from django.utils.encoding import smart_unicode, smart_str |
48 |
from django.core.files.uploadhandler import FileUploadHandler |
49 |
from django.core.files.uploadedfile import UploadedFile |
50 |
|
51 |
from pithos.lib.compat import parse_http_date_safe, parse_http_date |
52 |
|
53 |
from pithos.api.faults import (Fault, NotModified, BadRequest, Unauthorized, Forbidden, ItemNotFound, |
54 |
Conflict, LengthRequired, PreconditionFailed, RequestEntityTooLarge, |
55 |
RangeNotSatisfiable, InternalServerError, NotImplemented)
|
56 |
from pithos.api.short_url import encode_url |
57 |
from pithos.api.settings import (BACKEND_DB_MODULE, BACKEND_DB_CONNECTION, |
58 |
BACKEND_BLOCK_MODULE, BACKEND_BLOCK_PATH, |
59 |
BACKEND_QUEUE_MODULE, BACKEND_QUEUE_CONNECTION, |
60 |
BACKEND_QUOTA, BACKEND_VERSIONING) |
61 |
from pithos.backends import connect_backend |
62 |
from pithos.backends.base import NotAllowedError, QuotaError |
63 |
|
64 |
import logging |
65 |
import re |
66 |
import hashlib |
67 |
import uuid |
68 |
import decimal |
69 |
|
70 |
|
71 |
logger = logging.getLogger(__name__) |
72 |
|
73 |
|
74 |
class UTC(tzinfo): |
75 |
def utcoffset(self, dt): |
76 |
return timedelta(0) |
77 |
|
78 |
def tzname(self, dt): |
79 |
return 'UTC' |
80 |
|
81 |
def dst(self, dt): |
82 |
return timedelta(0) |
83 |
|
84 |
def json_encode_decimal(obj): |
85 |
if isinstance(obj, decimal.Decimal): |
86 |
return str(obj) |
87 |
raise TypeError(repr(obj) + " is not JSON serializable") |
88 |
|
89 |
def isoformat(d): |
90 |
"""Return an ISO8601 date string that includes a timezone."""
|
91 |
|
92 |
return d.replace(tzinfo=UTC()).isoformat()
|
93 |
|
94 |
def rename_meta_key(d, old, new): |
95 |
if old not in d: |
96 |
return
|
97 |
d[new] = d[old] |
98 |
del(d[old])
|
99 |
|
100 |
def printable_header_dict(d): |
101 |
"""Format a meta dictionary for printing out json/xml.
|
102 |
|
103 |
Convert all keys to lower case and replace dashes with underscores.
|
104 |
Format 'last_modified' timestamp.
|
105 |
"""
|
106 |
|
107 |
if 'last_modified' in d: |
108 |
d['last_modified'] = isoformat(datetime.fromtimestamp(d['last_modified'])) |
109 |
return dict([(k.lower().replace('-', '_'), v) for k, v in d.iteritems()]) |
110 |
|
111 |
def format_header_key(k): |
112 |
"""Convert underscores to dashes and capitalize intra-dash strings."""
|
113 |
return '-'.join([x.capitalize() for x in k.replace('_', '-').split('-')]) |
114 |
|
115 |
def get_header_prefix(request, prefix): |
116 |
"""Get all prefix-* request headers in a dict. Reformat keys with format_header_key()."""
|
117 |
|
118 |
prefix = 'HTTP_' + prefix.upper().replace('-', '_') |
119 |
# TODO: Document or remove '~' replacing.
|
120 |
return dict([(format_header_key(k[5:]), v.replace('~', '')) for k, v in request.META.iteritems() if k.startswith(prefix) and len(k) > len(prefix)]) |
121 |
|
122 |
def get_account_headers(request): |
123 |
meta = get_header_prefix(request, 'X-Account-Meta-')
|
124 |
groups = {} |
125 |
for k, v in get_header_prefix(request, 'X-Account-Group-').iteritems(): |
126 |
n = k[16:].lower()
|
127 |
if '-' in n or '_' in n: |
128 |
raise BadRequest('Bad characters in group name') |
129 |
groups[n] = v.replace(' ', '').split(',') |
130 |
while '' in groups[n]: |
131 |
groups[n].remove('')
|
132 |
return meta, groups
|
133 |
|
134 |
def put_account_headers(response, meta, groups, policy): |
135 |
if 'count' in meta: |
136 |
response['X-Account-Container-Count'] = meta['count'] |
137 |
if 'bytes' in meta: |
138 |
response['X-Account-Bytes-Used'] = meta['bytes'] |
139 |
response['Last-Modified'] = http_date(int(meta['modified'])) |
140 |
for k in [x for x in meta.keys() if x.startswith('X-Account-Meta-')]: |
141 |
response[smart_str(k, strings_only=True)] = smart_str(meta[k], strings_only=True) |
142 |
if 'until_timestamp' in meta: |
143 |
response['X-Account-Until-Timestamp'] = http_date(int(meta['until_timestamp'])) |
144 |
for k, v in groups.iteritems(): |
145 |
k = smart_str(k, strings_only=True)
|
146 |
k = format_header_key('X-Account-Group-' + k)
|
147 |
v = smart_str(','.join(v), strings_only=True) |
148 |
response[k] = v |
149 |
for k, v in policy.iteritems(): |
150 |
response[smart_str(format_header_key('X-Account-Policy-' + k), strings_only=True)] = smart_str(v, strings_only=True) |
151 |
|
152 |
def get_container_headers(request): |
153 |
meta = get_header_prefix(request, 'X-Container-Meta-')
|
154 |
policy = dict([(k[19:].lower(), v.replace(' ', '')) for k, v in get_header_prefix(request, 'X-Container-Policy-').iteritems()]) |
155 |
return meta, policy
|
156 |
|
157 |
def put_container_headers(request, response, meta, policy): |
158 |
if 'count' in meta: |
159 |
response['X-Container-Object-Count'] = meta['count'] |
160 |
if 'bytes' in meta: |
161 |
response['X-Container-Bytes-Used'] = meta['bytes'] |
162 |
response['Last-Modified'] = http_date(int(meta['modified'])) |
163 |
for k in [x for x in meta.keys() if x.startswith('X-Container-Meta-')]: |
164 |
response[smart_str(k, strings_only=True)] = smart_str(meta[k], strings_only=True) |
165 |
l = [smart_str(x, strings_only=True) for x in meta['object_meta'] if x.startswith('X-Object-Meta-')] |
166 |
response['X-Container-Object-Meta'] = ','.join([x[14:] for x in l]) |
167 |
response['X-Container-Block-Size'] = request.backend.block_size
|
168 |
response['X-Container-Block-Hash'] = request.backend.hash_algorithm
|
169 |
if 'until_timestamp' in meta: |
170 |
response['X-Container-Until-Timestamp'] = http_date(int(meta['until_timestamp'])) |
171 |
for k, v in policy.iteritems(): |
172 |
response[smart_str(format_header_key('X-Container-Policy-' + k), strings_only=True)] = smart_str(v, strings_only=True) |
173 |
|
174 |
def get_object_headers(request): |
175 |
meta = get_header_prefix(request, 'X-Object-Meta-')
|
176 |
if request.META.get('CONTENT_TYPE'): |
177 |
meta['Content-Type'] = request.META['CONTENT_TYPE'] |
178 |
if request.META.get('HTTP_CONTENT_ENCODING'): |
179 |
meta['Content-Encoding'] = request.META['HTTP_CONTENT_ENCODING'] |
180 |
if request.META.get('HTTP_CONTENT_DISPOSITION'): |
181 |
meta['Content-Disposition'] = request.META['HTTP_CONTENT_DISPOSITION'] |
182 |
if request.META.get('HTTP_X_OBJECT_MANIFEST'): |
183 |
meta['X-Object-Manifest'] = request.META['HTTP_X_OBJECT_MANIFEST'] |
184 |
return meta, get_sharing(request), get_public(request)
|
185 |
|
186 |
def put_object_headers(response, meta, restricted=False): |
187 |
if 'ETag' in meta: |
188 |
response['ETag'] = meta['ETag'] |
189 |
response['Content-Length'] = meta['bytes'] |
190 |
response['Content-Type'] = meta.get('Content-Type', 'application/octet-stream') |
191 |
response['Last-Modified'] = http_date(int(meta['modified'])) |
192 |
if not restricted: |
193 |
response['X-Object-Hash'] = meta['hash'] |
194 |
response['X-Object-UUID'] = meta['uuid'] |
195 |
response['X-Object-Modified-By'] = smart_str(meta['modified_by'], strings_only=True) |
196 |
response['X-Object-Version'] = meta['version'] |
197 |
response['X-Object-Version-Timestamp'] = http_date(int(meta['version_timestamp'])) |
198 |
for k in [x for x in meta.keys() if x.startswith('X-Object-Meta-')]: |
199 |
response[smart_str(k, strings_only=True)] = smart_str(meta[k], strings_only=True) |
200 |
for k in ('Content-Encoding', 'Content-Disposition', 'X-Object-Manifest', |
201 |
'X-Object-Sharing', 'X-Object-Shared-By', 'X-Object-Allowed-To', |
202 |
'X-Object-Public'):
|
203 |
if k in meta: |
204 |
response[k] = smart_str(meta[k], strings_only=True)
|
205 |
else:
|
206 |
for k in ('Content-Encoding', 'Content-Disposition'): |
207 |
if k in meta: |
208 |
response[k] = smart_str(meta[k], strings_only=True)
|
209 |
|
210 |
def update_manifest_meta(request, v_account, meta): |
211 |
"""Update metadata if the object has an X-Object-Manifest."""
|
212 |
|
213 |
if 'X-Object-Manifest' in meta: |
214 |
etag = ''
|
215 |
bytes = 0
|
216 |
try:
|
217 |
src_container, src_name = split_container_object_string('/' + meta['X-Object-Manifest']) |
218 |
objects = request.backend.list_objects(request.user_uniq, v_account, |
219 |
src_container, prefix=src_name, virtual=False)
|
220 |
for x in objects: |
221 |
src_meta = request.backend.get_object_meta(request.user_uniq, |
222 |
v_account, src_container, x[0], 'pithos', x[1]) |
223 |
if 'ETag' in src_meta: |
224 |
etag += src_meta['ETag']
|
225 |
bytes += src_meta['bytes'] |
226 |
except:
|
227 |
# Ignore errors.
|
228 |
return
|
229 |
meta['bytes'] = bytes |
230 |
md5 = hashlib.md5() |
231 |
md5.update(etag) |
232 |
meta['ETag'] = md5.hexdigest().lower()
|
233 |
|
234 |
def update_sharing_meta(request, permissions, v_account, v_container, v_object, meta): |
235 |
if permissions is None: |
236 |
return
|
237 |
allowed, perm_path, perms = permissions |
238 |
if len(perms) == 0: |
239 |
return
|
240 |
ret = [] |
241 |
r = ','.join(perms.get('read', [])) |
242 |
if r:
|
243 |
ret.append('read=' + r)
|
244 |
w = ','.join(perms.get('write', [])) |
245 |
if w:
|
246 |
ret.append('write=' + w)
|
247 |
meta['X-Object-Sharing'] = '; '.join(ret) |
248 |
if '/'.join((v_account, v_container, v_object)) != perm_path: |
249 |
meta['X-Object-Shared-By'] = perm_path
|
250 |
if request.user_uniq != v_account:
|
251 |
meta['X-Object-Allowed-To'] = allowed
|
252 |
|
253 |
def update_public_meta(public, meta): |
254 |
if not public: |
255 |
return
|
256 |
meta['X-Object-Public'] = '/public/' + encode_url(public) |
257 |
|
258 |
def validate_modification_preconditions(request, meta): |
259 |
"""Check that the modified timestamp conforms with the preconditions set."""
|
260 |
|
261 |
if 'modified' not in meta: |
262 |
return # TODO: Always return? |
263 |
|
264 |
if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')
|
265 |
if if_modified_since is not None: |
266 |
if_modified_since = parse_http_date_safe(if_modified_since) |
267 |
if if_modified_since is not None and int(meta['modified']) <= if_modified_since: |
268 |
raise NotModified('Resource has not been modified') |
269 |
|
270 |
if_unmodified_since = request.META.get('HTTP_IF_UNMODIFIED_SINCE')
|
271 |
if if_unmodified_since is not None: |
272 |
if_unmodified_since = parse_http_date_safe(if_unmodified_since) |
273 |
if if_unmodified_since is not None and int(meta['modified']) > if_unmodified_since: |
274 |
raise PreconditionFailed('Resource has been modified') |
275 |
|
276 |
def validate_matching_preconditions(request, meta): |
277 |
"""Check that the ETag conforms with the preconditions set."""
|
278 |
|
279 |
etag = meta.get('ETag', None) |
280 |
|
281 |
if_match = request.META.get('HTTP_IF_MATCH')
|
282 |
if if_match is not None: |
283 |
if etag is None: |
284 |
raise PreconditionFailed('Resource does not exist') |
285 |
if if_match != '*' and etag not in [x.lower() for x in parse_etags(if_match)]: |
286 |
raise PreconditionFailed('Resource ETag does not match') |
287 |
|
288 |
if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
|
289 |
if if_none_match is not None: |
290 |
# TODO: If this passes, must ignore If-Modified-Since header.
|
291 |
if etag is not None: |
292 |
if if_none_match == '*' or etag in [x.lower() for x in parse_etags(if_none_match)]: |
293 |
# TODO: Continue if an If-Modified-Since header is present.
|
294 |
if request.method in ('HEAD', 'GET'): |
295 |
raise NotModified('Resource ETag matches') |
296 |
raise PreconditionFailed('Resource exists or ETag matches') |
297 |
|
298 |
def split_container_object_string(s): |
299 |
if not len(s) > 0 or s[0] != '/': |
300 |
raise ValueError |
301 |
s = s[1:]
|
302 |
pos = s.find('/')
|
303 |
if pos == -1 or pos == len(s) - 1: |
304 |
raise ValueError |
305 |
return s[:pos], s[(pos + 1):] |
306 |
|
307 |
def copy_or_move_object(request, src_account, src_container, src_name, dest_account, dest_container, dest_name, move=False): |
308 |
"""Copy or move an object."""
|
309 |
|
310 |
if 'ignore_content_type' in request.GET and 'CONTENT_TYPE' in request.META: |
311 |
del(request.META['CONTENT_TYPE']) |
312 |
meta, permissions, public = get_object_headers(request) |
313 |
src_version = request.META.get('HTTP_X_SOURCE_VERSION')
|
314 |
try:
|
315 |
if move:
|
316 |
version_id = request.backend.move_object(request.user_uniq, src_account, src_container, src_name, |
317 |
dest_account, dest_container, dest_name, |
318 |
'pithos', meta, False, permissions) |
319 |
else:
|
320 |
version_id = request.backend.copy_object(request.user_uniq, src_account, src_container, src_name, |
321 |
dest_account, dest_container, dest_name, |
322 |
'pithos', meta, False, permissions, src_version) |
323 |
except NotAllowedError:
|
324 |
raise Forbidden('Not allowed') |
325 |
except (NameError, IndexError): |
326 |
raise ItemNotFound('Container or object does not exist') |
327 |
except ValueError: |
328 |
raise BadRequest('Invalid sharing header') |
329 |
except QuotaError:
|
330 |
raise RequestEntityTooLarge('Quota exceeded') |
331 |
if public is not None: |
332 |
try:
|
333 |
request.backend.update_object_public(request.user_uniq, dest_account, dest_container, dest_name, public) |
334 |
except NotAllowedError:
|
335 |
raise Forbidden('Not allowed') |
336 |
except NameError: |
337 |
raise ItemNotFound('Object does not exist') |
338 |
return version_id
|
339 |
|
340 |
def get_int_parameter(p): |
341 |
if p is not None: |
342 |
try:
|
343 |
p = int(p)
|
344 |
except ValueError: |
345 |
return None |
346 |
if p < 0: |
347 |
return None |
348 |
return p
|
349 |
|
350 |
def get_content_length(request): |
351 |
content_length = get_int_parameter(request.META.get('CONTENT_LENGTH'))
|
352 |
if content_length is None: |
353 |
raise LengthRequired('Missing or invalid Content-Length header') |
354 |
return content_length
|
355 |
|
356 |
def get_range(request, size): |
357 |
"""Parse a Range header from the request.
|
358 |
|
359 |
Either returns None, when the header is not existent or should be ignored,
|
360 |
or a list of (offset, length) tuples - should be further checked.
|
361 |
"""
|
362 |
|
363 |
ranges = request.META.get('HTTP_RANGE', '').replace(' ', '') |
364 |
if not ranges.startswith('bytes='): |
365 |
return None |
366 |
|
367 |
ret = [] |
368 |
for r in (x.strip() for x in ranges[6:].split(',')): |
369 |
p = re.compile('^(?P<offset>\d*)-(?P<upto>\d*)$')
|
370 |
m = p.match(r) |
371 |
if not m: |
372 |
return None |
373 |
offset = m.group('offset')
|
374 |
upto = m.group('upto')
|
375 |
if offset == '' and upto == '': |
376 |
return None |
377 |
|
378 |
if offset != '': |
379 |
offset = int(offset)
|
380 |
if upto != '': |
381 |
upto = int(upto)
|
382 |
if offset > upto:
|
383 |
return None |
384 |
ret.append((offset, upto - offset + 1))
|
385 |
else:
|
386 |
ret.append((offset, size - offset)) |
387 |
else:
|
388 |
length = int(upto)
|
389 |
ret.append((size - length, length)) |
390 |
|
391 |
return ret
|
392 |
|
393 |
def get_content_range(request): |
394 |
"""Parse a Content-Range header from the request.
|
395 |
|
396 |
Either returns None, when the header is not existent or should be ignored,
|
397 |
or an (offset, length, total) tuple - check as length, total may be None.
|
398 |
Returns (None, None, None) if the provided range is '*/*'.
|
399 |
"""
|
400 |
|
401 |
ranges = request.META.get('HTTP_CONTENT_RANGE', '') |
402 |
if not ranges: |
403 |
return None |
404 |
|
405 |
p = re.compile('^bytes (?P<offset>\d+)-(?P<upto>\d*)/(?P<total>(\d+|\*))$')
|
406 |
m = p.match(ranges) |
407 |
if not m: |
408 |
if ranges == 'bytes */*': |
409 |
return (None, None, None) |
410 |
return None |
411 |
offset = int(m.group('offset')) |
412 |
upto = m.group('upto')
|
413 |
total = m.group('total')
|
414 |
if upto != '': |
415 |
upto = int(upto)
|
416 |
else:
|
417 |
upto = None
|
418 |
if total != '*': |
419 |
total = int(total)
|
420 |
else:
|
421 |
total = None
|
422 |
if (upto is not None and offset > upto) or \ |
423 |
(total is not None and offset >= total) or \ |
424 |
(total is not None and upto is not None and upto >= total): |
425 |
return None |
426 |
|
427 |
if upto is None: |
428 |
length = None
|
429 |
else:
|
430 |
length = upto - offset + 1
|
431 |
return (offset, length, total)
|
432 |
|
433 |
def get_sharing(request): |
434 |
"""Parse an X-Object-Sharing header from the request.
|
435 |
|
436 |
Raises BadRequest on error.
|
437 |
"""
|
438 |
|
439 |
permissions = request.META.get('HTTP_X_OBJECT_SHARING')
|
440 |
if permissions is None: |
441 |
return None |
442 |
|
443 |
# TODO: Document or remove '~' replacing.
|
444 |
permissions = permissions.replace('~', '') |
445 |
|
446 |
ret = {} |
447 |
permissions = permissions.replace(' ', '') |
448 |
if permissions == '': |
449 |
return ret
|
450 |
for perm in (x for x in permissions.split(';')): |
451 |
if perm.startswith('read='): |
452 |
ret['read'] = list(set([v.replace(' ','').lower() for v in perm[5:].split(',')])) |
453 |
if '' in ret['read']: |
454 |
ret['read'].remove('') |
455 |
if '*' in ret['read']: |
456 |
ret['read'] = ['*'] |
457 |
if len(ret['read']) == 0: |
458 |
raise BadRequest('Bad X-Object-Sharing header value') |
459 |
elif perm.startswith('write='): |
460 |
ret['write'] = list(set([v.replace(' ','').lower() for v in perm[6:].split(',')])) |
461 |
if '' in ret['write']: |
462 |
ret['write'].remove('') |
463 |
if '*' in ret['write']: |
464 |
ret['write'] = ['*'] |
465 |
if len(ret['write']) == 0: |
466 |
raise BadRequest('Bad X-Object-Sharing header value') |
467 |
else:
|
468 |
raise BadRequest('Bad X-Object-Sharing header value') |
469 |
|
470 |
# Keep duplicates only in write list.
|
471 |
dups = [x for x in ret.get('read', []) if x in ret.get('write', []) and x != '*'] |
472 |
if dups:
|
473 |
for x in dups: |
474 |
ret['read'].remove(x)
|
475 |
if len(ret['read']) == 0: |
476 |
del(ret['read']) |
477 |
|
478 |
return ret
|
479 |
|
480 |
def get_public(request): |
481 |
"""Parse an X-Object-Public header from the request.
|
482 |
|
483 |
Raises BadRequest on error.
|
484 |
"""
|
485 |
|
486 |
public = request.META.get('HTTP_X_OBJECT_PUBLIC')
|
487 |
if public is None: |
488 |
return None |
489 |
|
490 |
public = public.replace(' ', '').lower() |
491 |
if public == 'true': |
492 |
return True |
493 |
elif public == 'false' or public == '': |
494 |
return False |
495 |
raise BadRequest('Bad X-Object-Public header value') |
496 |
|
497 |
def raw_input_socket(request): |
498 |
"""Return the socket for reading the rest of the request."""
|
499 |
|
500 |
server_software = request.META.get('SERVER_SOFTWARE')
|
501 |
if server_software and server_software.startswith('mod_python'): |
502 |
return request._req
|
503 |
if 'wsgi.input' in request.environ: |
504 |
return request.environ['wsgi.input'] |
505 |
raise NotImplemented('Unknown server software') |
506 |
|
507 |
MAX_UPLOAD_SIZE = 5 * (1024 * 1024 * 1024) # 5GB |
508 |
|
509 |
def socket_read_iterator(request, length=0, blocksize=4096): |
510 |
"""Return a maximum of blocksize data read from the socket in each iteration.
|
511 |
|
512 |
Read up to 'length'. If 'length' is negative, will attempt a chunked read.
|
513 |
The maximum ammount of data read is controlled by MAX_UPLOAD_SIZE.
|
514 |
"""
|
515 |
|
516 |
sock = raw_input_socket(request) |
517 |
if length < 0: # Chunked transfers |
518 |
# Small version (server does the dechunking).
|
519 |
if request.environ.get('mod_wsgi.input_chunked', None) or request.META['SERVER_SOFTWARE'].startswith('gunicorn'): |
520 |
while length < MAX_UPLOAD_SIZE:
|
521 |
data = sock.read(blocksize) |
522 |
if data == '': |
523 |
return
|
524 |
yield data
|
525 |
raise BadRequest('Maximum size is reached') |
526 |
|
527 |
# Long version (do the dechunking).
|
528 |
data = ''
|
529 |
while length < MAX_UPLOAD_SIZE:
|
530 |
# Get chunk size.
|
531 |
if hasattr(sock, 'readline'): |
532 |
chunk_length = sock.readline() |
533 |
else:
|
534 |
chunk_length = ''
|
535 |
while chunk_length[-1:] != '\n': |
536 |
chunk_length += sock.read(1)
|
537 |
chunk_length.strip() |
538 |
pos = chunk_length.find(';')
|
539 |
if pos >= 0: |
540 |
chunk_length = chunk_length[:pos] |
541 |
try:
|
542 |
chunk_length = int(chunk_length, 16) |
543 |
except Exception, e: |
544 |
raise BadRequest('Bad chunk size') # TODO: Change to something more appropriate. |
545 |
# Check if done.
|
546 |
if chunk_length == 0: |
547 |
if len(data) > 0: |
548 |
yield data
|
549 |
return
|
550 |
# Get the actual data.
|
551 |
while chunk_length > 0: |
552 |
chunk = sock.read(min(chunk_length, blocksize))
|
553 |
chunk_length -= len(chunk)
|
554 |
if length > 0: |
555 |
length += len(chunk)
|
556 |
data += chunk |
557 |
if len(data) >= blocksize: |
558 |
ret = data[:blocksize] |
559 |
data = data[blocksize:] |
560 |
yield ret
|
561 |
sock.read(2) # CRLF |
562 |
raise BadRequest('Maximum size is reached') |
563 |
else:
|
564 |
if length > MAX_UPLOAD_SIZE:
|
565 |
raise BadRequest('Maximum size is reached') |
566 |
while length > 0: |
567 |
data = sock.read(min(length, blocksize))
|
568 |
if not data: |
569 |
raise BadRequest()
|
570 |
length -= len(data)
|
571 |
yield data
|
572 |
|
573 |
class SaveToBackendHandler(FileUploadHandler): |
574 |
"""Handle a file from an HTML form the django way."""
|
575 |
|
576 |
def __init__(self, request=None): |
577 |
super(SaveToBackendHandler, self).__init__(request) |
578 |
self.backend = request.backend
|
579 |
|
580 |
def put_data(self, length): |
581 |
if len(self.data) >= length: |
582 |
block = self.data[:length]
|
583 |
self.file.hashmap.append(self.backend.put_block(block)) |
584 |
self.md5.update(block)
|
585 |
self.data = self.data[length:] |
586 |
|
587 |
def new_file(self, field_name, file_name, content_type, content_length, charset=None): |
588 |
self.md5 = hashlib.md5()
|
589 |
self.data = '' |
590 |
self.file = UploadedFile(name=file_name, content_type=content_type, charset=charset)
|
591 |
self.file.size = 0 |
592 |
self.file.hashmap = []
|
593 |
|
594 |
def receive_data_chunk(self, raw_data, start): |
595 |
self.data += raw_data
|
596 |
self.file.size += len(raw_data) |
597 |
self.put_data(self.request.backend.block_size) |
598 |
return None |
599 |
|
600 |
def file_complete(self, file_size): |
601 |
l = len(self.data) |
602 |
if l > 0: |
603 |
self.put_data(l)
|
604 |
self.file.etag = self.md5.hexdigest().lower() |
605 |
return self.file |
606 |
|
607 |
class ObjectWrapper(object): |
608 |
"""Return the object's data block-per-block in each iteration.
|
609 |
|
610 |
Read from the object using the offset and length provided in each entry of the range list.
|
611 |
"""
|
612 |
|
613 |
def __init__(self, backend, ranges, sizes, hashmaps, boundary): |
614 |
self.backend = backend
|
615 |
self.ranges = ranges
|
616 |
self.sizes = sizes
|
617 |
self.hashmaps = hashmaps
|
618 |
self.boundary = boundary
|
619 |
self.size = sum(self.sizes) |
620 |
|
621 |
self.file_index = 0 |
622 |
self.block_index = 0 |
623 |
self.block_hash = -1 |
624 |
self.block = '' |
625 |
|
626 |
self.range_index = -1 |
627 |
self.offset, self.length = self.ranges[0] |
628 |
|
629 |
def __iter__(self): |
630 |
return self |
631 |
|
632 |
def part_iterator(self): |
633 |
if self.length > 0: |
634 |
# Get the file for the current offset.
|
635 |
file_size = self.sizes[self.file_index] |
636 |
while self.offset >= file_size: |
637 |
self.offset -= file_size
|
638 |
self.file_index += 1 |
639 |
file_size = self.sizes[self.file_index] |
640 |
|
641 |
# Get the block for the current position.
|
642 |
self.block_index = int(self.offset / self.backend.block_size) |
643 |
if self.block_hash != self.hashmaps[self.file_index][self.block_index]: |
644 |
self.block_hash = self.hashmaps[self.file_index][self.block_index] |
645 |
try:
|
646 |
self.block = self.backend.get_block(self.block_hash) |
647 |
except NameError: |
648 |
raise ItemNotFound('Block does not exist') |
649 |
|
650 |
# Get the data from the block.
|
651 |
bo = self.offset % self.backend.block_size |
652 |
bl = min(self.length, len(self.block) - bo) |
653 |
data = self.block[bo:bo + bl]
|
654 |
self.offset += bl
|
655 |
self.length -= bl
|
656 |
return data
|
657 |
else:
|
658 |
raise StopIteration |
659 |
|
660 |
def next(self): |
661 |
if len(self.ranges) == 1: |
662 |
return self.part_iterator() |
663 |
if self.range_index == len(self.ranges): |
664 |
raise StopIteration |
665 |
try:
|
666 |
if self.range_index == -1: |
667 |
raise StopIteration |
668 |
return self.part_iterator() |
669 |
except StopIteration: |
670 |
self.range_index += 1 |
671 |
out = [] |
672 |
if self.range_index < len(self.ranges): |
673 |
# Part header.
|
674 |
self.offset, self.length = self.ranges[self.range_index] |
675 |
self.file_index = 0 |
676 |
if self.range_index > 0: |
677 |
out.append('')
|
678 |
out.append('--' + self.boundary) |
679 |
out.append('Content-Range: bytes %d-%d/%d' % (self.offset, self.offset + self.length - 1, self.size)) |
680 |
out.append('Content-Transfer-Encoding: binary')
|
681 |
out.append('')
|
682 |
out.append('')
|
683 |
return '\r\n'.join(out) |
684 |
else:
|
685 |
# Footer.
|
686 |
out.append('')
|
687 |
out.append('--' + self.boundary + '--') |
688 |
out.append('')
|
689 |
return '\r\n'.join(out) |
690 |
|
691 |
def object_data_response(request, sizes, hashmaps, meta, public=False): |
692 |
"""Get the HttpResponse object for replying with the object's data."""
|
693 |
|
694 |
# Range handling.
|
695 |
size = sum(sizes)
|
696 |
ranges = get_range(request, size) |
697 |
if ranges is None: |
698 |
ranges = [(0, size)]
|
699 |
ret = 200
|
700 |
else:
|
701 |
check = [True for offset, length in ranges if |
702 |
length <= 0 or length > size or |
703 |
offset < 0 or offset >= size or |
704 |
offset + length > size] |
705 |
if len(check) > 0: |
706 |
raise RangeNotSatisfiable('Requested range exceeds object limits') |
707 |
ret = 206
|
708 |
if_range = request.META.get('HTTP_IF_RANGE')
|
709 |
if if_range:
|
710 |
try:
|
711 |
# Modification time has passed instead.
|
712 |
last_modified = parse_http_date(if_range) |
713 |
if last_modified != meta['modified']: |
714 |
ranges = [(0, size)]
|
715 |
ret = 200
|
716 |
except ValueError: |
717 |
if if_range != meta['ETag']: |
718 |
ranges = [(0, size)]
|
719 |
ret = 200
|
720 |
|
721 |
if ret == 206 and len(ranges) > 1: |
722 |
boundary = uuid.uuid4().hex |
723 |
else:
|
724 |
boundary = ''
|
725 |
wrapper = ObjectWrapper(request.backend, ranges, sizes, hashmaps, boundary) |
726 |
response = HttpResponse(wrapper, status=ret) |
727 |
put_object_headers(response, meta, public) |
728 |
if ret == 206: |
729 |
if len(ranges) == 1: |
730 |
offset, length = ranges[0]
|
731 |
response['Content-Length'] = length # Update with the correct length. |
732 |
response['Content-Range'] = 'bytes %d-%d/%d' % (offset, offset + length - 1, size) |
733 |
else:
|
734 |
del(response['Content-Length']) |
735 |
response['Content-Type'] = 'multipart/byteranges; boundary=%s' % (boundary,) |
736 |
return response
|
737 |
|
738 |
def put_object_block(request, hashmap, data, offset): |
739 |
"""Put one block of data at the given offset."""
|
740 |
|
741 |
bi = int(offset / request.backend.block_size)
|
742 |
bo = offset % request.backend.block_size |
743 |
bl = min(len(data), request.backend.block_size - bo) |
744 |
if bi < len(hashmap): |
745 |
hashmap[bi] = request.backend.update_block(hashmap[bi], data[:bl], bo) |
746 |
else:
|
747 |
hashmap.append(request.backend.put_block(('\x00' * bo) + data[:bl]))
|
748 |
return bl # Return ammount of data written. |
749 |
|
750 |
def hashmap_md5(request, hashmap, size): |
751 |
"""Produce the MD5 sum from the data in the hashmap."""
|
752 |
|
753 |
# TODO: Search backend for the MD5 of another object with the same hashmap and size...
|
754 |
md5 = hashlib.md5() |
755 |
bs = request.backend.block_size |
756 |
for bi, hash in enumerate(hashmap): |
757 |
data = request.backend.get_block(hash)
|
758 |
if bi == len(hashmap) - 1: |
759 |
bs = size % bs |
760 |
pad = bs - min(len(data), bs) |
761 |
md5.update(data + ('\x00' * pad))
|
762 |
return md5.hexdigest().lower()
|
763 |
|
764 |
def simple_list_response(request, l): |
765 |
if request.serialization == 'text': |
766 |
return '\n'.join(l) + '\n' |
767 |
if request.serialization == 'xml': |
768 |
return render_to_string('items.xml', {'items': l}) |
769 |
if request.serialization == 'json': |
770 |
return json.dumps(l)
|
771 |
|
772 |
def get_backend(): |
773 |
backend = connect_backend(db_module=BACKEND_DB_MODULE, |
774 |
db_connection=BACKEND_DB_CONNECTION, |
775 |
block_module=BACKEND_BLOCK_MODULE, |
776 |
block_path=BACKEND_BLOCK_PATH, |
777 |
queue_module=BACKEND_QUEUE_MODULE, |
778 |
queue_connection=BACKEND_QUEUE_CONNECTION) |
779 |
backend.default_policy['quota'] = BACKEND_QUOTA
|
780 |
backend.default_policy['versioning'] = BACKEND_VERSIONING
|
781 |
return backend
|
782 |
|
783 |
def update_request_headers(request): |
784 |
# Handle URL-encoded keys and values.
|
785 |
# Handle URL-encoded keys and values.
|
786 |
meta = dict([(k, v) for k, v in request.META.iteritems() if k.startswith('HTTP_')]) |
787 |
if len(meta) > 90: |
788 |
raise BadRequest('Too many headers.') |
789 |
for k, v in meta.iteritems(): |
790 |
if len(k) > 128: |
791 |
raise BadRequest('Header name too large.') |
792 |
if len(v) > 256: |
793 |
raise BadRequest('Header value too large.') |
794 |
try:
|
795 |
k.decode('ascii')
|
796 |
v.decode('ascii')
|
797 |
except UnicodeDecodeError: |
798 |
raise BadRequest('Bad character in headers.') |
799 |
if '%' in k or '%' in v: |
800 |
del(request.META[k])
|
801 |
request.META[unquote(k)] = smart_unicode(unquote(v), strings_only=True)
|
802 |
|
803 |
def update_response_headers(request, response): |
804 |
if request.serialization == 'xml': |
805 |
response['Content-Type'] = 'application/xml; charset=UTF-8' |
806 |
elif request.serialization == 'json': |
807 |
response['Content-Type'] = 'application/json; charset=UTF-8' |
808 |
elif not response['Content-Type']: |
809 |
response['Content-Type'] = 'text/plain; charset=UTF-8' |
810 |
|
811 |
if (not response.has_header('Content-Length') and |
812 |
not (response.has_header('Content-Type') and |
813 |
response['Content-Type'].startswith('multipart/byteranges'))): |
814 |
response['Content-Length'] = len(response.content) |
815 |
|
816 |
# URL-encode unicode in headers.
|
817 |
meta = response.items() |
818 |
for k, v in meta: |
819 |
if (k.startswith('X-Account-') or k.startswith('X-Container-') or |
820 |
k.startswith('X-Object-') or k.startswith('Content-')): |
821 |
del(response[k])
|
822 |
response[quote(k)] = quote(v, safe='/=,:@; ')
|
823 |
|
824 |
def render_fault(request, fault): |
825 |
if isinstance(fault, InternalServerError) and settings.DEBUG: |
826 |
fault.details = format_exc(fault) |
827 |
|
828 |
request.serialization = 'text'
|
829 |
data = fault.message + '\n'
|
830 |
if fault.details:
|
831 |
data += '\n' + fault.details
|
832 |
response = HttpResponse(data, status=fault.code) |
833 |
update_response_headers(request, response) |
834 |
return response
|
835 |
|
836 |
def request_serialization(request, format_allowed=False): |
837 |
"""Return the serialization format requested.
|
838 |
|
839 |
Valid formats are 'text' and 'json', 'xml' if 'format_allowed' is True.
|
840 |
"""
|
841 |
|
842 |
if not format_allowed: |
843 |
return 'text' |
844 |
|
845 |
format = request.GET.get('format')
|
846 |
if format == 'json': |
847 |
return 'json' |
848 |
elif format == 'xml': |
849 |
return 'xml' |
850 |
|
851 |
for item in request.META.get('HTTP_ACCEPT', '').split(','): |
852 |
accept, sep, rest = item.strip().partition(';')
|
853 |
if accept == 'application/json': |
854 |
return 'json' |
855 |
elif accept == 'application/xml' or accept == 'text/xml': |
856 |
return 'xml' |
857 |
|
858 |
return 'text' |
859 |
|
860 |
def api_method(http_method=None, format_allowed=False, user_required=True): |
861 |
"""Decorator function for views that implement an API method."""
|
862 |
|
863 |
def decorator(func): |
864 |
@wraps(func)
|
865 |
def wrapper(request, *args, **kwargs): |
866 |
try:
|
867 |
if http_method and request.method != http_method: |
868 |
raise BadRequest('Method not allowed.') |
869 |
if user_required and getattr(request, 'user', None) is None: |
870 |
raise Unauthorized('Access denied') |
871 |
|
872 |
# The args variable may contain up to (account, container, object).
|
873 |
if len(args) > 1 and len(args[1]) > 256: |
874 |
raise BadRequest('Container name too large.') |
875 |
if len(args) > 2 and len(args[2]) > 1024: |
876 |
raise BadRequest('Object name too large.') |
877 |
|
878 |
# Format and check headers.
|
879 |
update_request_headers(request) |
880 |
|
881 |
# Fill in custom request variables.
|
882 |
request.serialization = request_serialization(request, format_allowed) |
883 |
request.backend = get_backend() |
884 |
|
885 |
response = func(request, *args, **kwargs) |
886 |
update_response_headers(request, response) |
887 |
return response
|
888 |
except Fault, fault:
|
889 |
return render_fault(request, fault)
|
890 |
except BaseException, e: |
891 |
logger.exception('Unexpected error: %s' % e)
|
892 |
fault = InternalServerError('Unexpected error')
|
893 |
return render_fault(request, fault)
|
894 |
finally:
|
895 |
if getattr(request, 'backend', None) is not None: |
896 |
request.backend.close() |
897 |
return wrapper
|
898 |
return decorator
|