from pithos.api.compat import parse_http_date_safe
from pithos.api.faults import (Fault, NotModified, BadRequest, ItemNotFound, LengthRequired,
- PreconditionFailed, ServiceUnavailable)
+ PreconditionFailed, RangeNotSatisfiable, ServiceUnavailable)
from pithos.backends import backend
import datetime
import logging
import re
+import hashlib
+import uuid
logger = logging.getLogger(__name__)
Convert all keys to lower case and replace dashes to underscores.
Change 'modified' key from backend to 'last_modified' and format date.
"""
+
if 'modified' in d:
d['last_modified'] = datetime.datetime.fromtimestamp(int(d['modified'])).isoformat()
del(d['modified'])
return dict([(k.lower().replace('-', '_'), v) for k, v in d.iteritems()])
def format_meta_key(k):
- """Convert underscores to dashes and capitalize intra-dash strings"""
+ """Convert underscores to dashes and capitalize intra-dash strings."""
+
return '-'.join([x.capitalize() for x in k.replace('_', '-').split('-')])
def get_meta_prefix(request, prefix):
- """Get all prefix-* request headers in a dict. Reformat keys with format_meta_key()"""
+ """Get all prefix-* request headers in a dict. Reformat keys with format_meta_key()."""
+
prefix = 'HTTP_' + prefix.upper().replace('-', '_')
return dict([(format_meta_key(k[5:]), v) for k, v in request.META.iteritems() if k.startswith(prefix)])
def get_account_meta(request):
- """Get metadata from an account request"""
+ """Get metadata from an account request."""
+
meta = get_meta_prefix(request, 'X-Account-Meta-')
return meta
def put_account_meta(response, meta):
- """Put metadata in an account response"""
+ """Put metadata in an account response."""
+
response['X-Account-Container-Count'] = meta['count']
response['X-Account-Bytes-Used'] = meta['bytes']
if 'modified' in meta:
response['Last-Modified'] = http_date(int(meta['modified']))
for k in [x for x in meta.keys() if x.startswith('X-Account-Meta-')]:
response[k.encode('utf-8')] = meta[k].encode('utf-8')
+ if 'until_timestamp' in meta:
+ response['X-Account-Until-Timestamp'] = http_date(int(meta['until_timestamp']))
def get_container_meta(request):
- """Get metadata from a container request"""
+ """Get metadata from a container request."""
+
meta = get_meta_prefix(request, 'X-Container-Meta-')
return meta
def put_container_meta(response, meta):
- """Put metadata in a container response"""
+ """Put metadata in a container response."""
+
response['X-Container-Object-Count'] = meta['count']
response['X-Container-Bytes-Used'] = meta['bytes']
- if 'modified' in meta:
- response['Last-Modified'] = http_date(int(meta['modified']))
+ response['Last-Modified'] = http_date(int(meta['modified']))
for k in [x for x in meta.keys() if x.startswith('X-Container-Meta-')]:
response[k.encode('utf-8')] = meta[k].encode('utf-8')
response['X-Container-Object-Meta'] = [x[14:] for x in meta['object_meta'] if x.startswith('X-Object-Meta-')]
response['X-Container-Block-Size'] = backend.block_size
response['X-Container-Block-Hash'] = backend.hash_algorithm
+ if 'until_timestamp' in meta:
+ response['X-Container-Until-Timestamp'] = http_date(int(meta['until_timestamp']))
def get_object_meta(request):
- """Get metadata from an object request"""
+ """Get metadata from an object request."""
+
meta = get_meta_prefix(request, 'X-Object-Meta-')
if request.META.get('CONTENT_TYPE'):
meta['Content-Type'] = request.META['CONTENT_TYPE']
meta['X-Object-Manifest'] = request.META['HTTP_X_OBJECT_MANIFEST']
return meta
-def put_object_meta(response, meta):
- """Put metadata in an object response"""
+def put_object_meta(response, meta, public=False):
+ """Put metadata in an object response."""
+
response['ETag'] = meta['hash']
response['Content-Length'] = meta['bytes']
response['Content-Type'] = meta.get('Content-Type', 'application/octet-stream')
response['Last-Modified'] = http_date(int(meta['modified']))
- for k in [x for x in meta.keys() if x.startswith('X-Object-Meta-')]:
- response[k.encode('utf-8')] = meta[k].encode('utf-8')
- for k in ('Content-Encoding', 'Content-Disposition', 'X-Object-Manifest'):
- if k in meta:
- response[k] = meta[k]
+ if not public:
+ response['X-Object-Version'] = meta['version']
+ response['X-Object-Version-Timestamp'] = meta['version_timestamp']
+ for k in [x for x in meta.keys() if x.startswith('X-Object-Meta-')]:
+ response[k.encode('utf-8')] = meta[k].encode('utf-8')
+ for k in ('Content-Encoding', 'Content-Disposition', 'X-Object-Manifest', 'X-Object-Sharing'):
+ if k in meta:
+ response[k] = meta[k]
+ else:
+ for k in ('Content-Encoding', 'Content-Disposition'):
+ if k in meta:
+ response[k] = meta[k]
+
+def update_manifest_meta(request, v_account, meta):
+ """Update metadata if the object has an X-Object-Manifest."""
+
+ if 'X-Object-Manifest' in meta:
+ hash = ''
+ bytes = 0
+ try:
+ src_container, src_name = split_container_object_string('/' + meta['X-Object-Manifest'])
+ objects = backend.list_objects(request.user, v_account, src_container, prefix=src_name, virtual=False)
+ for x in objects:
+ src_meta = backend.get_object_meta(request.user, v_account, src_container, x[0], x[1])
+ hash += src_meta['hash']
+ bytes += src_meta['bytes']
+ except:
+ # Ignore errors.
+ return
+ meta['bytes'] = bytes
+ md5 = hashlib.md5()
+ md5.update(hash)
+ meta['hash'] = md5.hexdigest().lower()
+
+def format_permissions(permissions):
+ ret = []
+ if 'public' in permissions:
+ ret.append('public')
+ if 'private' in permissions:
+ ret.append('private')
+ r = ','.join(permissions.get('read', []))
+ if r:
+ ret.append('read=' + r)
+ w = ','.join(permissions.get('write', []))
+ if w:
+ ret.append('write=' + w)
+ return '; '.join(ret)
def validate_modification_preconditions(request, meta):
- """Check that the modified timestamp conforms with the preconditions set"""
+ """Check that the modified timestamp conforms with the preconditions set."""
+
if 'modified' not in meta:
return # TODO: Always return?
if if_modified_since is not None:
if_modified_since = parse_http_date_safe(if_modified_since)
if if_modified_since is not None and int(meta['modified']) <= if_modified_since:
- raise NotModified('Object has not been modified')
+ raise NotModified('Resource has not been modified')
if_unmodified_since = request.META.get('HTTP_IF_UNMODIFIED_SINCE')
if if_unmodified_since is not None:
if_unmodified_since = parse_http_date_safe(if_unmodified_since)
if if_unmodified_since is not None and int(meta['modified']) > if_unmodified_since:
- raise PreconditionFailed('Object has been modified')
+ raise PreconditionFailed('Resource has been modified')
def validate_matching_preconditions(request, meta):
- """Check that the ETag conforms with the preconditions set"""
+ """Check that the ETag conforms with the preconditions set."""
+
if 'hash' not in meta:
return # TODO: Always return?
if_match = request.META.get('HTTP_IF_MATCH')
if if_match is not None and if_match != '*':
if meta['hash'] not in [x.lower() for x in parse_etags(if_match)]:
- raise PreconditionFailed('Object Etag does not match')
+ raise PreconditionFailed('Resource Etag does not match')
if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
if if_none_match is not None:
if if_none_match == '*' or meta['hash'] in [x.lower() for x in parse_etags(if_none_match)]:
- raise NotModified('Object Etag matches')
-
-def copy_or_move_object(request, src_path, dest_path, move=False):
- """Copy or move an object"""
- if type(src_path) == str:
- parts = src_path.split('/')
- if len(parts) < 3 or parts[0] != '':
- raise BadRequest('Invalid X-Copy-From or X-Move-From header')
- src_container = parts[1]
- src_name = '/'.join(parts[2:])
- elif type(src_path) == tuple and len(src_path) == 2:
- src_container, src_name = src_path
- if type(dest_path) == str:
- parts = dest_path.split('/')
- if len(parts) < 3 or parts[0] != '':
- raise BadRequest('Invalid Destination header')
- dest_container = parts[1]
- dest_name = '/'.join(parts[2:])
- elif type(dest_path) == tuple and len(dest_path) == 2:
- dest_container, dest_name = dest_path
+ raise NotModified('Resource Etag matches')
+
+def split_container_object_string(s):
+ if not len(s) > 0 or s[0] != '/':
+ raise ValueError
+ s = s[1:]
+ pos = s.find('/')
+ if pos == -1:
+ raise ValueError
+ return s[:pos], s[(pos + 1):]
+
+def copy_or_move_object(request, v_account, src_container, src_name, dest_container, dest_name, move=False):
+ """Copy or move an object."""
meta = get_object_meta(request)
+ permissions = get_sharing(request)
# Keep previous values of 'Content-Type' (if a new one is absent) and 'hash'.
try:
- src_meta = backend.get_object_meta(request.user, src_container, src_name)
+ src_meta = backend.get_object_meta(request.user, v_account, src_container, src_name)
except NameError:
raise ItemNotFound('Container or object does not exist')
if 'Content-Type' in meta and 'Content-Type' in src_meta:
try:
if move:
- backend.move_object(request.user, src_container, src_name, dest_container, dest_name, meta, replace_meta=True)
+ backend.move_object(request.user, v_account, src_container, src_name, dest_container, dest_name, meta, True, permissions)
else:
- backend.copy_object(request.user, src_container, src_name, dest_container, dest_name, meta, replace_meta=True)
+ src_version = request.META.get('HTTP_X_SOURCE_VERSION')
+ backend.copy_object(request.user, v_account, src_container, src_name, dest_container, dest_name, meta, True, permissions, src_version)
except NameError:
raise ItemNotFound('Container or object does not exist')
+ except ValueError:
+ raise BadRequest('Invalid sharing header')
+ except AttributeError:
+ raise Conflict('Sharing already set above or below this path in the hierarchy')
+
+def get_int_parameter(request, name):
+ p = request.GET.get(name)
+ if p is not None:
+ try:
+ p = int(p)
+ except ValueError:
+ return None
+ if p < 0:
+ return None
+ return p
def get_content_length(request):
content_length = request.META.get('CONTENT_LENGTH')
return content_length
def get_range(request, size):
- """Parse a Range header from the request
+ """Parse a Range header from the request.
Either returns None, when the header is not existent or should be ignored,
or a list of (offset, length) tuples - should be further checked.
"""
+
ranges = request.META.get('HTTP_RANGE', '').replace(' ', '')
if not ranges.startswith('bytes='):
return None
return ret
def get_content_range(request):
- """Parse a Content-Range header from the request
+ """Parse a Content-Range header from the request.
Either returns None, when the header is not existent or should be ignored,
or an (offset, length, total) tuple - check as length, total may be None.
total = int(total)
else:
total = None
- if (upto and offset > upto) or \
- (total and offset >= total) or \
- (total and upto and upto >= total):
+ if (upto is not None and offset > upto) or \
+ (total is not None and offset >= total) or \
+ (total is not None and upto is not None and upto >= total):
return None
- if not upto:
+ if upto is None:
length = None
else:
length = upto - offset + 1
return (offset, length, total)
+def get_sharing(request):
+ """Parse an X-Object-Sharing header from the request.
+
+ Raises BadRequest on error.
+ """
+
+ permissions = request.META.get('HTTP_X_OBJECT_SHARING')
+ if permissions is None or permissions == '':
+ return None
+
+ ret = {}
+ for perm in (x.replace(' ','') for x in permissions.split(';')):
+ if perm == 'public':
+ ret['public'] = True
+ continue
+ elif perm == 'private':
+ ret['private'] = True
+ continue
+ elif perm.startswith('read='):
+ ret['read'] = [v.replace(' ','') for v in perm[5:].split(',')]
+ if len(ret['read']) == 0:
+ raise BadRequest('Bad X-Object-Sharing header value')
+ elif perm.startswith('write='):
+ ret['write'] = [v.replace(' ','') for v in perm[6:].split(',')]
+ if len(ret['write']) == 0:
+ raise BadRequest('Bad X-Object-Sharing header value')
+ else:
+ raise BadRequest('Bad X-Object-Sharing header value')
+ return ret
+
def raw_input_socket(request):
- """Return the socket for reading the rest of the request"""
+ """Return the socket for reading the rest of the request."""
+
server_software = request.META.get('SERVER_SOFTWARE')
if not server_software:
if 'wsgi.input' in request.environ:
MAX_UPLOAD_SIZE = 10 * (1024 * 1024) # 10MB
def socket_read_iterator(sock, length=0, blocksize=4096):
- """Return a maximum of blocksize data read from the socket in each iteration
+ """Return a maximum of blocksize data read from the socket in each iteration.
Read up to 'length'. If 'length' is negative, will attempt a chunked read.
The maximum ammount of data read is controlled by MAX_UPLOAD_SIZE.
"""
+
if length < 0: # Chunked transfers
data = ''
while length < MAX_UPLOAD_SIZE:
while chunk_length > 0:
chunk = sock.read(min(chunk_length, blocksize))
chunk_length -= len(chunk)
- length += len(chunk)
+ if length > 0:
+ length += len(chunk)
data += chunk
if len(data) >= blocksize:
ret = data[:blocksize]
yield data
class ObjectWrapper(object):
- """Return the object's data block-per-block in each iteration
+ """Return the object's data block-per-block in each iteration.
Read from the object using the offset and length provided in each entry of the range list.
"""
- def __init__(self, v_account, v_container, v_object, ranges, size, hashmap, boundary):
- self.v_account = v_account
- self.v_container = v_container
- self.v_object = v_object
+ def __init__(self, ranges, sizes, hashmaps, boundary):
self.ranges = ranges
- self.size = size
- self.hashmap = hashmap
+ self.sizes = sizes
+ self.hashmaps = hashmaps
self.boundary = boundary
+ self.size = sum(self.sizes)
- self.block_index = -1
+ self.file_index = 0
+ self.block_index = 0
+ self.block_hash = -1
self.block = ''
self.range_index = -1
def part_iterator(self):
if self.length > 0:
- # Get the block for the current offset.
- bi = int(self.offset / backend.block_size)
- if self.block_index != bi:
+ # Get the file for the current offset.
+ file_size = self.sizes[self.file_index]
+ while self.offset >= file_size:
+ self.offset -= file_size
+ self.file_index += 1
+ file_size = self.sizes[self.file_index]
+
+ # Get the block for the current position.
+ self.block_index = int(self.offset / backend.block_size)
+ if self.block_hash != self.hashmaps[self.file_index][self.block_index]:
+ self.block_hash = self.hashmaps[self.file_index][self.block_index]
try:
- self.block = backend.get_block(self.hashmap[bi])
+ self.block = backend.get_block(self.block_hash)
except NameError:
raise ItemNotFound('Block does not exist')
- self.block_index = bi
+
# Get the data from the block.
bo = self.offset % backend.block_size
- bl = min(self.length, backend.block_size - bo)
+ bl = min(self.length, len(self.block) - bo)
data = self.block[bo:bo + bl]
self.offset += bl
self.length -= bl
if self.range_index < len(self.ranges):
# Part header.
self.offset, self.length = self.ranges[self.range_index]
+ self.file_index = 0
if self.range_index > 0:
out.append('')
out.append('--' + self.boundary)
out.append('')
return '\r\n'.join(out)
+def object_data_response(request, sizes, hashmaps, meta, public=False):
+ """Get the HttpResponse object for replying with the object's data."""
+
+ # Range handling.
+ size = sum(sizes)
+ ranges = get_range(request, size)
+ if ranges is None:
+ ranges = [(0, size)]
+ ret = 200
+ else:
+ check = [True for offset, length in ranges if
+ length <= 0 or length > size or
+ offset < 0 or offset >= size or
+ offset + length > size]
+ if len(check) > 0:
+ raise RangeNotSatisfiable('Requested range exceeds object limits')
+ ret = 206
+
+ if ret == 206 and len(ranges) > 1:
+ boundary = uuid.uuid4().hex
+ else:
+ boundary = ''
+ wrapper = ObjectWrapper(ranges, sizes, hashmaps, boundary)
+ response = HttpResponse(wrapper, status=ret)
+ put_object_meta(response, meta, public)
+ if ret == 206:
+ if len(ranges) == 1:
+ offset, length = ranges[0]
+ response['Content-Length'] = length # Update with the correct length.
+ response['Content-Range'] = 'bytes %d-%d/%d' % (offset, offset + length - 1, size)
+ else:
+ del(response['Content-Length'])
+ response['Content-Type'] = 'multipart/byteranges; boundary=%s' % (boundary,)
+ return response
+
+def put_object_block(hashmap, data, offset):
+ """Put one block of data at the given offset."""
+
+ bi = int(offset / backend.block_size)
+ bo = offset % backend.block_size
+ bl = min(len(data), backend.block_size - bo)
+ if bi < len(hashmap):
+ hashmap[bi] = backend.update_block(hashmap[bi], data[:bl], bo)
+ else:
+ hashmap.append(backend.put_block(('\x00' * bo) + data[:bl]))
+ return bl # Return ammount of data written.
+
def hashmap_hash(hashmap):
- """ Produce the root hash, treating the hashmap as a Merkle-like tree."""
+ """Produce the root hash, treating the hashmap as a Merkle-like tree."""
def subhash(d):
h = hashlib.new(backend.hash_algorithm)
return response
def request_serialization(request, format_allowed=False):
- """Return the serialization format requested
+ """Return the serialization format requested.
Valid formats are 'text' and 'json', 'xml' if 'format_allowed' is True.
"""
+
if not format_allowed:
return 'text'
return 'text'
def api_method(http_method=None, format_allowed=False):
- """Decorator function for views that implement an API method"""
+ """Decorator function for views that implement an API method."""
+
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
try:
if http_method and request.method != http_method:
raise BadRequest('Method not allowed.')
-
+
# The args variable may contain up to (account, container, object).
if len(args) > 1 and len(args[1]) > 256:
raise BadRequest('Container name too large.')