1 # Copyright 2011 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
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.
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.
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.
34 from functools import wraps
36 from traceback import format_exc
37 from wsgiref.handlers import format_date_time
38 from binascii import hexlify
40 from django.conf import settings
41 from django.http import HttpResponse
42 from django.utils import simplejson as json
43 from django.utils.http import http_date, parse_etags
45 from pithos.api.compat import parse_http_date_safe, parse_http_date
46 from pithos.api.faults import (Fault, NotModified, BadRequest, Unauthorized, ItemNotFound,
47 Conflict, LengthRequired, PreconditionFailed, RangeNotSatisfiable,
49 from pithos.backends import backend
50 from pithos.backends.base import NotAllowedError
59 logger = logging.getLogger(__name__)
62 def rename_meta_key(d, old, new):
68 def printable_header_dict(d):
69 """Format a meta dictionary for printing out json/xml.
71 Convert all keys to lower case and replace dashes with underscores.
72 Format 'last_modified' timestamp.
75 d['last_modified'] = datetime.datetime.fromtimestamp(int(d['last_modified'])).isoformat()
76 return dict([(k.lower().replace('-', '_'), v) for k, v in d.iteritems()])
78 def format_header_key(k):
79 """Convert underscores to dashes and capitalize intra-dash strings."""
81 return '-'.join([x.capitalize() for x in k.replace('_', '-').split('-')])
83 def get_header_prefix(request, prefix):
84 """Get all prefix-* request headers in a dict. Reformat keys with format_header_key()."""
86 prefix = 'HTTP_' + prefix.upper().replace('-', '_')
87 # TODO: Document or remove '~' replacing.
88 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)])
90 def get_account_headers(request):
91 meta = get_header_prefix(request, 'X-Account-Meta-')
93 for k, v in get_header_prefix(request, 'X-Account-Group-').iteritems():
95 if '-' in n or '_' in n:
96 raise BadRequest('Bad characters in group name')
97 groups[n] = v.replace(' ', '').split(',')
102 def put_account_headers(response, meta, groups):
104 response['X-Account-Container-Count'] = meta['count']
106 response['X-Account-Bytes-Used'] = meta['bytes']
107 response['Last-Modified'] = http_date(int(meta['modified']))
108 for k in [x for x in meta.keys() if x.startswith('X-Account-Meta-')]:
109 response[k.encode('utf-8')] = meta[k].encode('utf-8')
110 if 'until_timestamp' in meta:
111 response['X-Account-Until-Timestamp'] = http_date(int(meta['until_timestamp']))
112 for k, v in groups.iteritems():
113 response[format_header_key('X-Account-Group-' + k).encode('utf-8')] = (','.join(v)).encode('utf-8')
115 def get_container_headers(request):
116 meta = get_header_prefix(request, 'X-Container-Meta-')
117 policy = dict([(k[19:].lower(), v.replace(' ', '')) for k, v in get_header_prefix(request, 'X-Container-Policy-').iteritems()])
120 def put_container_headers(response, meta, policy):
122 response['X-Container-Object-Count'] = meta['count']
124 response['X-Container-Bytes-Used'] = meta['bytes']
125 response['Last-Modified'] = http_date(int(meta['modified']))
126 for k in [x for x in meta.keys() if x.startswith('X-Container-Meta-')]:
127 response[k.encode('utf-8')] = meta[k].encode('utf-8')
128 response['X-Container-Object-Meta'] = ','.join([x[14:] for x in meta['object_meta'] if x.startswith('X-Object-Meta-')])
129 response['X-Container-Block-Size'] = backend.block_size
130 response['X-Container-Block-Hash'] = backend.hash_algorithm
131 if 'until_timestamp' in meta:
132 response['X-Container-Until-Timestamp'] = http_date(int(meta['until_timestamp']))
133 for k, v in policy.iteritems():
134 response[format_header_key('X-Container-Policy-' + k).encode('utf-8')] = v.encode('utf-8')
136 def get_object_headers(request):
137 meta = get_header_prefix(request, 'X-Object-Meta-')
138 if request.META.get('CONTENT_TYPE'):
139 meta['Content-Type'] = request.META['CONTENT_TYPE']
140 if request.META.get('HTTP_CONTENT_ENCODING'):
141 meta['Content-Encoding'] = request.META['HTTP_CONTENT_ENCODING']
142 if request.META.get('HTTP_CONTENT_DISPOSITION'):
143 meta['Content-Disposition'] = request.META['HTTP_CONTENT_DISPOSITION']
144 if request.META.get('HTTP_X_OBJECT_MANIFEST'):
145 meta['X-Object-Manifest'] = request.META['HTTP_X_OBJECT_MANIFEST']
146 return meta, get_sharing(request), get_public(request)
148 def put_object_headers(response, meta, restricted=False):
149 response['ETag'] = meta['hash']
150 response['Content-Length'] = meta['bytes']
151 response['Content-Type'] = meta.get('Content-Type', 'application/octet-stream')
152 response['Last-Modified'] = http_date(int(meta['modified']))
154 response['X-Object-Modified-By'] = meta['modified_by']
155 response['X-Object-Version'] = meta['version']
156 response['X-Object-Version-Timestamp'] = http_date(int(meta['version_timestamp']))
157 for k in [x for x in meta.keys() if x.startswith('X-Object-Meta-')]:
158 response[k.encode('utf-8')] = meta[k].encode('utf-8')
159 for k in ('Content-Encoding', 'Content-Disposition', 'X-Object-Manifest', 'X-Object-Sharing', 'X-Object-Shared-By', 'X-Object-Public'):
161 response[k] = meta[k]
163 for k in ('Content-Encoding', 'Content-Disposition'):
165 response[k] = meta[k]
167 def update_manifest_meta(request, v_account, meta):
168 """Update metadata if the object has an X-Object-Manifest."""
170 if 'X-Object-Manifest' in meta:
174 src_container, src_name = split_container_object_string('/' + meta['X-Object-Manifest'])
175 objects = backend.list_objects(request.user, v_account, src_container, prefix=src_name, virtual=False)
177 src_meta = backend.get_object_meta(request.user, v_account, src_container, x[0], x[1])
178 hash += src_meta['hash']
179 bytes += src_meta['bytes']
183 meta['bytes'] = bytes
186 meta['hash'] = md5.hexdigest().lower()
188 def update_sharing_meta(permissions, v_account, v_container, v_object, meta):
189 if permissions is None:
191 perm_path, perms = permissions
195 r = ','.join(perms.get('read', []))
197 ret.append('read=' + r)
198 w = ','.join(perms.get('write', []))
200 ret.append('write=' + w)
201 meta['X-Object-Sharing'] = '; '.join(ret)
202 if '/'.join((v_account, v_container, v_object)) != perm_path:
203 meta['X-Object-Shared-By'] = perm_path
205 def update_public_meta(public, meta):
208 meta['X-Object-Public'] = public
210 def validate_modification_preconditions(request, meta):
211 """Check that the modified timestamp conforms with the preconditions set."""
213 if 'modified' not in meta:
214 return # TODO: Always return?
216 if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')
217 if if_modified_since is not None:
218 if_modified_since = parse_http_date_safe(if_modified_since)
219 if if_modified_since is not None and int(meta['modified']) <= if_modified_since:
220 raise NotModified('Resource has not been modified')
222 if_unmodified_since = request.META.get('HTTP_IF_UNMODIFIED_SINCE')
223 if if_unmodified_since is not None:
224 if_unmodified_since = parse_http_date_safe(if_unmodified_since)
225 if if_unmodified_since is not None and int(meta['modified']) > if_unmodified_since:
226 raise PreconditionFailed('Resource has been modified')
228 def validate_matching_preconditions(request, meta):
229 """Check that the ETag conforms with the preconditions set."""
231 hash = meta.get('hash', None)
233 if_match = request.META.get('HTTP_IF_MATCH')
234 if if_match is not None:
236 raise PreconditionFailed('Resource does not exist')
237 if if_match != '*' and hash not in [x.lower() for x in parse_etags(if_match)]:
238 raise PreconditionFailed('Resource ETag does not match')
240 if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
241 if if_none_match is not None:
242 # TODO: If this passes, must ignore If-Modified-Since header.
244 if if_none_match == '*' or hash in [x.lower() for x in parse_etags(if_none_match)]:
245 # TODO: Continue if an If-Modified-Since header is present.
246 if request.method in ('HEAD', 'GET'):
247 raise NotModified('Resource ETag matches')
248 raise PreconditionFailed('Resource exists or ETag matches')
250 def split_container_object_string(s):
251 if not len(s) > 0 or s[0] != '/':
257 return s[:pos], s[(pos + 1):]
259 def copy_or_move_object(request, v_account, src_container, src_name, dest_container, dest_name, move=False):
260 """Copy or move an object."""
262 meta, permissions, public = get_object_headers(request)
263 src_version = request.META.get('HTTP_X_SOURCE_VERSION')
266 backend.move_object(request.user, v_account, src_container, src_name, dest_container, dest_name, meta, False, permissions)
268 backend.copy_object(request.user, v_account, src_container, src_name, dest_container, dest_name, meta, False, permissions, src_version)
269 except NotAllowedError:
270 raise Unauthorized('Access denied')
271 except (NameError, IndexError):
272 raise ItemNotFound('Container or object does not exist')
274 raise BadRequest('Invalid sharing header')
275 except AttributeError, e:
276 raise Conflict(json.dumps(e.data))
277 if public is not None:
279 backend.update_object_public(request.user, v_account, dest_container, dest_name, public)
280 except NotAllowedError:
281 raise Unauthorized('Access denied')
283 raise ItemNotFound('Object does not exist')
285 def get_int_parameter(p):
295 def get_content_length(request):
296 content_length = get_int_parameter(request.META.get('CONTENT_LENGTH'))
297 if content_length is None:
298 raise LengthRequired('Missing or invalid Content-Length header')
299 return content_length
301 def get_range(request, size):
302 """Parse a Range header from the request.
304 Either returns None, when the header is not existent or should be ignored,
305 or a list of (offset, length) tuples - should be further checked.
308 ranges = request.META.get('HTTP_RANGE', '').replace(' ', '')
309 if not ranges.startswith('bytes='):
313 for r in (x.strip() for x in ranges[6:].split(',')):
314 p = re.compile('^(?P<offset>\d*)-(?P<upto>\d*)$')
318 offset = m.group('offset')
319 upto = m.group('upto')
320 if offset == '' and upto == '':
329 ret.append((offset, upto - offset + 1))
331 ret.append((offset, size - offset))
334 ret.append((size - length, length))
338 def get_content_range(request):
339 """Parse a Content-Range header from the request.
341 Either returns None, when the header is not existent or should be ignored,
342 or an (offset, length, total) tuple - check as length, total may be None.
343 Returns (None, None, None) if the provided range is '*/*'.
346 ranges = request.META.get('HTTP_CONTENT_RANGE', '')
350 p = re.compile('^bytes (?P<offset>\d+)-(?P<upto>\d*)/(?P<total>(\d+|\*))$')
353 if ranges == 'bytes */*':
354 return (None, None, None)
356 offset = int(m.group('offset'))
357 upto = m.group('upto')
358 total = m.group('total')
367 if (upto is not None and offset > upto) or \
368 (total is not None and offset >= total) or \
369 (total is not None and upto is not None and upto >= total):
375 length = upto - offset + 1
376 return (offset, length, total)
378 def get_sharing(request):
379 """Parse an X-Object-Sharing header from the request.
381 Raises BadRequest on error.
384 permissions = request.META.get('HTTP_X_OBJECT_SHARING')
385 if permissions is None:
389 permissions = permissions.replace(' ', '')
390 if permissions == '':
392 for perm in (x for x in permissions.split(';')):
393 if perm.startswith('read='):
394 ret['read'] = list(set([v.replace(' ','').lower() for v in perm[5:].split(',')]))
395 if '' in ret['read']:
396 ret['read'].remove('')
397 if '*' in ret['read']:
399 if len(ret['read']) == 0:
400 raise BadRequest('Bad X-Object-Sharing header value')
401 elif perm.startswith('write='):
402 ret['write'] = list(set([v.replace(' ','').lower() for v in perm[6:].split(',')]))
403 if '' in ret['write']:
404 ret['write'].remove('')
405 if '*' in ret['write']:
407 if len(ret['write']) == 0:
408 raise BadRequest('Bad X-Object-Sharing header value')
410 raise BadRequest('Bad X-Object-Sharing header value')
413 def get_public(request):
414 """Parse an X-Object-Public header from the request.
416 Raises BadRequest on error.
419 public = request.META.get('HTTP_X_OBJECT_PUBLIC')
423 public = public.replace(' ', '').lower()
426 elif public == 'false' or public == '':
428 raise BadRequest('Bad X-Object-Public header value')
430 def raw_input_socket(request):
431 """Return the socket for reading the rest of the request."""
433 server_software = request.META.get('SERVER_SOFTWARE')
434 if server_software and server_software.startswith('mod_python'):
436 if 'wsgi.input' in request.environ:
437 return request.environ['wsgi.input']
438 raise ServiceUnavailable('Unknown server software')
440 MAX_UPLOAD_SIZE = 10 * (1024 * 1024) # 10MB
442 def socket_read_iterator(request, length=0, blocksize=4096):
443 """Return a maximum of blocksize data read from the socket in each iteration.
445 Read up to 'length'. If 'length' is negative, will attempt a chunked read.
446 The maximum ammount of data read is controlled by MAX_UPLOAD_SIZE.
449 sock = raw_input_socket(request)
450 if length < 0: # Chunked transfers
451 # Small version (server does the dechunking).
452 if request.environ.get('mod_wsgi.input_chunked', None):
453 while length < MAX_UPLOAD_SIZE:
454 data = sock.read(blocksize)
458 raise BadRequest('Maximum size is reached')
460 # Long version (do the dechunking).
462 while length < MAX_UPLOAD_SIZE:
464 if hasattr(sock, 'readline'):
465 chunk_length = sock.readline()
468 while chunk_length[-1:] != '\n':
469 chunk_length += sock.read(1)
471 pos = chunk_length.find(';')
473 chunk_length = chunk_length[:pos]
475 chunk_length = int(chunk_length, 16)
477 raise BadRequest('Bad chunk size') # TODO: Change to something more appropriate.
479 if chunk_length == 0:
483 # Get the actual data.
484 while chunk_length > 0:
485 chunk = sock.read(min(chunk_length, blocksize))
486 chunk_length -= len(chunk)
490 if len(data) >= blocksize:
491 ret = data[:blocksize]
492 data = data[blocksize:]
495 raise BadRequest('Maximum size is reached')
497 if length > MAX_UPLOAD_SIZE:
498 raise BadRequest('Maximum size is reached')
500 data = sock.read(min(length, blocksize))
504 class ObjectWrapper(object):
505 """Return the object's data block-per-block in each iteration.
507 Read from the object using the offset and length provided in each entry of the range list.
510 def __init__(self, ranges, sizes, hashmaps, boundary):
513 self.hashmaps = hashmaps
514 self.boundary = boundary
515 self.size = sum(self.sizes)
522 self.range_index = -1
523 self.offset, self.length = self.ranges[0]
528 def part_iterator(self):
530 # Get the file for the current offset.
531 file_size = self.sizes[self.file_index]
532 while self.offset >= file_size:
533 self.offset -= file_size
535 file_size = self.sizes[self.file_index]
537 # Get the block for the current position.
538 self.block_index = int(self.offset / backend.block_size)
539 if self.block_hash != self.hashmaps[self.file_index][self.block_index]:
540 self.block_hash = self.hashmaps[self.file_index][self.block_index]
542 self.block = backend.get_block(self.block_hash)
544 raise ItemNotFound('Block does not exist')
546 # Get the data from the block.
547 bo = self.offset % backend.block_size
548 bl = min(self.length, len(self.block) - bo)
549 data = self.block[bo:bo + bl]
557 if len(self.ranges) == 1:
558 return self.part_iterator()
559 if self.range_index == len(self.ranges):
562 if self.range_index == -1:
564 return self.part_iterator()
565 except StopIteration:
566 self.range_index += 1
568 if self.range_index < len(self.ranges):
570 self.offset, self.length = self.ranges[self.range_index]
572 if self.range_index > 0:
574 out.append('--' + self.boundary)
575 out.append('Content-Range: bytes %d-%d/%d' % (self.offset, self.offset + self.length - 1, self.size))
576 out.append('Content-Transfer-Encoding: binary')
579 return '\r\n'.join(out)
583 out.append('--' + self.boundary + '--')
585 return '\r\n'.join(out)
587 def object_data_response(request, sizes, hashmaps, meta, public=False):
588 """Get the HttpResponse object for replying with the object's data."""
592 ranges = get_range(request, size)
597 check = [True for offset, length in ranges if
598 length <= 0 or length > size or
599 offset < 0 or offset >= size or
600 offset + length > size]
602 raise RangeNotSatisfiable('Requested range exceeds object limits')
604 if_range = request.META.get('HTTP_IF_RANGE')
607 # Modification time has passed instead.
608 last_modified = parse_http_date(if_range)
609 if last_modified != meta['modified']:
613 if if_range != meta['hash']:
617 if ret == 206 and len(ranges) > 1:
618 boundary = uuid.uuid4().hex
621 wrapper = ObjectWrapper(ranges, sizes, hashmaps, boundary)
622 response = HttpResponse(wrapper, status=ret)
623 put_object_headers(response, meta, public)
626 offset, length = ranges[0]
627 response['Content-Length'] = length # Update with the correct length.
628 response['Content-Range'] = 'bytes %d-%d/%d' % (offset, offset + length - 1, size)
630 del(response['Content-Length'])
631 response['Content-Type'] = 'multipart/byteranges; boundary=%s' % (boundary,)
634 def put_object_block(hashmap, data, offset):
635 """Put one block of data at the given offset."""
637 bi = int(offset / backend.block_size)
638 bo = offset % backend.block_size
639 bl = min(len(data), backend.block_size - bo)
640 if bi < len(hashmap):
641 hashmap[bi] = backend.update_block(hashmap[bi], data[:bl], bo)
643 hashmap.append(backend.put_block(('\x00' * bo) + data[:bl]))
644 return bl # Return ammount of data written.
646 def hashmap_hash(hashmap):
647 """Produce the root hash, treating the hashmap as a Merkle-like tree."""
650 h = hashlib.new(backend.hash_algorithm)
654 if len(hashmap) == 0:
655 return hexlify(subhash(''))
656 if len(hashmap) == 1:
657 return hexlify(subhash(hashmap[0]))
659 while s < len(hashmap):
661 h = hashmap + ([('\x00' * len(hashmap[0]))] * (s - len(hashmap)))
662 h = [subhash(h[x] + (h[x + 1] if x + 1 < len(h) else '')) for x in range(0, len(h), 2)]
664 h = [subhash(h[x] + (h[x + 1] if x + 1 < len(h) else '')) for x in range(0, len(h), 2)]
667 def update_response_headers(request, response):
668 if request.serialization == 'xml':
669 response['Content-Type'] = 'application/xml; charset=UTF-8'
670 elif request.serialization == 'json':
671 response['Content-Type'] = 'application/json; charset=UTF-8'
672 elif not response['Content-Type']:
673 response['Content-Type'] = 'text/plain; charset=UTF-8'
675 if not response.has_header('Content-Length') and not (response.has_header('Content-Type') and response['Content-Type'].startswith('multipart/byteranges')):
676 response['Content-Length'] = len(response.content)
679 response['Date'] = format_date_time(time())
681 def render_fault(request, fault):
682 if settings.DEBUG or settings.TEST:
683 fault.details = format_exc(fault)
685 request.serialization = 'text'
686 data = '\n'.join((fault.message, fault.details)) + '\n'
687 response = HttpResponse(data, status=fault.code)
688 update_response_headers(request, response)
691 def request_serialization(request, format_allowed=False):
692 """Return the serialization format requested.
694 Valid formats are 'text' and 'json', 'xml' if 'format_allowed' is True.
697 if not format_allowed:
700 format = request.GET.get('format')
703 elif format == 'xml':
706 # for item in request.META.get('HTTP_ACCEPT', '').split(','):
707 # accept, sep, rest = item.strip().partition(';')
708 # if accept == 'application/json':
710 # elif accept == 'application/xml' or accept == 'text/xml':
715 def api_method(http_method=None, format_allowed=False):
716 """Decorator function for views that implement an API method."""
720 def wrapper(request, *args, **kwargs):
722 if http_method and request.method != http_method:
723 raise BadRequest('Method not allowed.')
725 # The args variable may contain up to (account, container, object).
726 if len(args) > 1 and len(args[1]) > 256:
727 raise BadRequest('Container name too large.')
728 if len(args) > 2 and len(args[2]) > 1024:
729 raise BadRequest('Object name too large.')
731 # Fill in custom request variables.
732 request.serialization = request_serialization(request, format_allowed)
734 response = func(request, *args, **kwargs)
735 update_response_headers(request, response)
738 return render_fault(request, fault)
739 except BaseException, e:
740 logger.exception('Unexpected error: %s' % e)
741 fault = ServiceUnavailable('Unexpected error')
742 return render_fault(request, fault)