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.http import http_date, parse_etags
44 from pithos.api.compat import parse_http_date_safe, parse_http_date
45 from pithos.api.faults import (Fault, NotModified, BadRequest, Unauthorized, ItemNotFound,
46 LengthRequired, PreconditionFailed, RangeNotSatisfiable,
48 from pithos.backends import backend
49 from pithos.backends.base import NotAllowedError
58 logger = logging.getLogger(__name__)
61 def printable_header_dict(d):
62 """Format a meta dictionary for printing out json/xml.
64 Convert all keys to lower case and replace dashes to underscores.
65 Change 'modified' key from backend to 'last_modified' and format date.
69 d['last_modified'] = datetime.datetime.fromtimestamp(int(d['modified'])).isoformat()
71 return dict([(k.lower().replace('-', '_'), v) for k, v in d.iteritems()])
73 def format_header_key(k):
74 """Convert underscores to dashes and capitalize intra-dash strings."""
76 return '-'.join([x.capitalize() for x in k.replace('_', '-').split('-')])
78 def get_header_prefix(request, prefix):
79 """Get all prefix-* request headers in a dict. Reformat keys with format_header_key()."""
81 prefix = 'HTTP_' + prefix.upper().replace('-', '_')
82 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)])
84 def get_account_headers(request):
85 meta = get_header_prefix(request, 'X-Account-Meta-')
87 for k, v in get_header_prefix(request, 'X-Account-Group-').iteritems():
89 if '-' in n or '_' in n:
90 raise BadRequest('Bad characters in group name')
91 groups[n] = v.replace(' ', '').split(',')
96 def put_account_headers(response, meta, groups):
97 response['X-Account-Container-Count'] = meta['count']
98 response['X-Account-Bytes-Used'] = meta['bytes']
99 if 'modified' in meta:
100 response['Last-Modified'] = http_date(int(meta['modified']))
101 for k in [x for x in meta.keys() if x.startswith('X-Account-Meta-')]:
102 response[k.encode('utf-8')] = meta[k].encode('utf-8')
103 if 'until_timestamp' in meta:
104 response['X-Account-Until-Timestamp'] = http_date(int(meta['until_timestamp']))
105 for k, v in groups.iteritems():
106 response[format_header_key('X-Account-Group-' + k).encode('utf-8')] = (','.join(v)).encode('utf-8')
108 def get_container_headers(request):
109 meta = get_header_prefix(request, 'X-Container-Meta-')
112 def put_container_headers(response, meta):
113 response['X-Container-Object-Count'] = meta['count']
114 response['X-Container-Bytes-Used'] = meta['bytes']
115 response['Last-Modified'] = http_date(int(meta['modified']))
116 for k in [x for x in meta.keys() if x.startswith('X-Container-Meta-')]:
117 response[k.encode('utf-8')] = meta[k].encode('utf-8')
118 response['X-Container-Object-Meta'] = [x[14:] for x in meta['object_meta'] if x.startswith('X-Object-Meta-')]
119 response['X-Container-Block-Size'] = backend.block_size
120 response['X-Container-Block-Hash'] = backend.hash_algorithm
121 if 'until_timestamp' in meta:
122 response['X-Container-Until-Timestamp'] = http_date(int(meta['until_timestamp']))
124 def get_object_headers(request):
125 meta = get_header_prefix(request, 'X-Object-Meta-')
126 if request.META.get('CONTENT_TYPE'):
127 meta['Content-Type'] = request.META['CONTENT_TYPE']
128 if request.META.get('HTTP_CONTENT_ENCODING'):
129 meta['Content-Encoding'] = request.META['HTTP_CONTENT_ENCODING']
130 if request.META.get('HTTP_CONTENT_DISPOSITION'):
131 meta['Content-Disposition'] = request.META['HTTP_CONTENT_DISPOSITION']
132 if request.META.get('HTTP_X_OBJECT_MANIFEST'):
133 meta['X-Object-Manifest'] = request.META['HTTP_X_OBJECT_MANIFEST']
136 def put_object_headers(response, meta, public=False):
137 response['ETag'] = meta['hash']
138 response['Content-Length'] = meta['bytes']
139 response['Content-Type'] = meta.get('Content-Type', 'application/octet-stream')
140 response['Last-Modified'] = http_date(int(meta['modified']))
142 response['X-Object-Modified-By'] = meta['modified_by']
143 response['X-Object-Version'] = meta['version']
144 response['X-Object-Version-Timestamp'] = http_date(int(meta['version_timestamp']))
145 for k in [x for x in meta.keys() if x.startswith('X-Object-Meta-')]:
146 response[k.encode('utf-8')] = meta[k].encode('utf-8')
147 for k in ('Content-Encoding', 'Content-Disposition', 'X-Object-Manifest', 'X-Object-Sharing', 'X-Object-Shared-By'):
149 response[k] = meta[k]
151 for k in ('Content-Encoding', 'Content-Disposition'):
153 response[k] = meta[k]
155 def update_manifest_meta(request, v_account, meta):
156 """Update metadata if the object has an X-Object-Manifest."""
158 if 'X-Object-Manifest' in meta:
162 src_container, src_name = split_container_object_string('/' + meta['X-Object-Manifest'])
163 objects = backend.list_objects(request.user, v_account, src_container, prefix=src_name, virtual=False)
165 src_meta = backend.get_object_meta(request.user, v_account, src_container, x[0], x[1])
166 hash += src_meta['hash']
167 bytes += src_meta['bytes']
171 meta['bytes'] = bytes
174 meta['hash'] = md5.hexdigest().lower()
176 def update_sharing_meta(permissions, v_account, v_container, v_object, meta):
177 if permissions is None:
179 perm_path, perms = permissions
183 r = ','.join(perms.get('read', []))
185 ret.append('read=' + r)
186 w = ','.join(perms.get('write', []))
188 ret.append('write=' + w)
189 meta['X-Object-Sharing'] = '; '.join(ret)
190 if '/'.join((v_account, v_container, v_object)) != perm_path:
191 meta['X-Object-Shared-By'] = perm_path
193 def validate_modification_preconditions(request, meta):
194 """Check that the modified timestamp conforms with the preconditions set."""
196 if 'modified' not in meta:
197 return # TODO: Always return?
199 if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')
200 if if_modified_since is not None:
201 if_modified_since = parse_http_date_safe(if_modified_since)
202 if if_modified_since is not None and int(meta['modified']) <= if_modified_since:
203 raise NotModified('Resource has not been modified')
205 if_unmodified_since = request.META.get('HTTP_IF_UNMODIFIED_SINCE')
206 if if_unmodified_since is not None:
207 if_unmodified_since = parse_http_date_safe(if_unmodified_since)
208 if if_unmodified_since is not None and int(meta['modified']) > if_unmodified_since:
209 raise PreconditionFailed('Resource has been modified')
211 def validate_matching_preconditions(request, meta):
212 """Check that the ETag conforms with the preconditions set."""
214 if 'hash' not in meta:
215 return # TODO: Always return?
217 if_match = request.META.get('HTTP_IF_MATCH')
218 if if_match is not None and if_match != '*':
219 if meta['hash'] not in [x.lower() for x in parse_etags(if_match)]:
220 raise PreconditionFailed('Resource Etag does not match')
222 if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
223 if if_none_match is not None:
224 if if_none_match == '*' or meta['hash'] in [x.lower() for x in parse_etags(if_none_match)]:
225 raise NotModified('Resource Etag matches')
227 def split_container_object_string(s):
228 if not len(s) > 0 or s[0] != '/':
234 return s[:pos], s[(pos + 1):]
236 def copy_or_move_object(request, v_account, src_container, src_name, dest_container, dest_name, move=False):
237 """Copy or move an object."""
239 meta = get_object_headers(request)
240 permissions = get_sharing(request)
241 src_version = request.META.get('HTTP_X_SOURCE_VERSION')
244 backend.move_object(request.user, v_account, src_container, src_name, dest_container, dest_name, meta, False, permissions)
246 backend.copy_object(request.user, v_account, src_container, src_name, dest_container, dest_name, meta, False, permissions, src_version)
247 except NotAllowedError:
248 raise Unauthorized('Access denied')
249 except NameError, IndexError:
250 raise ItemNotFound('Container or object does not exist')
252 raise BadRequest('Invalid sharing header')
253 except AttributeError:
254 raise Conflict('Sharing already set above or below this path in the hierarchy')
256 def get_int_parameter(request, name):
257 p = request.GET.get(name)
267 def get_content_length(request):
268 content_length = request.META.get('CONTENT_LENGTH')
269 if not content_length:
270 raise LengthRequired('Missing Content-Length header')
272 content_length = int(content_length)
273 if content_length < 0:
276 raise BadRequest('Invalid Content-Length header')
277 return content_length
279 def get_range(request, size):
280 """Parse a Range header from the request.
282 Either returns None, when the header is not existent or should be ignored,
283 or a list of (offset, length) tuples - should be further checked.
286 ranges = request.META.get('HTTP_RANGE', '').replace(' ', '')
287 if not ranges.startswith('bytes='):
291 for r in (x.strip() for x in ranges[6:].split(',')):
292 p = re.compile('^(?P<offset>\d*)-(?P<upto>\d*)$')
296 offset = m.group('offset')
297 upto = m.group('upto')
298 if offset == '' and upto == '':
307 ret.append((offset, upto - offset + 1))
309 ret.append((offset, size - offset))
312 ret.append((size - length, length))
316 def get_content_range(request):
317 """Parse a Content-Range header from the request.
319 Either returns None, when the header is not existent or should be ignored,
320 or an (offset, length, total) tuple - check as length, total may be None.
321 Returns (None, None, None) if the provided range is '*/*'.
324 ranges = request.META.get('HTTP_CONTENT_RANGE', '')
328 p = re.compile('^bytes (?P<offset>\d+)-(?P<upto>\d*)/(?P<total>(\d+|\*))$')
331 if ranges == 'bytes */*':
332 return (None, None, None)
334 offset = int(m.group('offset'))
335 upto = m.group('upto')
336 total = m.group('total')
345 if (upto is not None and offset > upto) or \
346 (total is not None and offset >= total) or \
347 (total is not None and upto is not None and upto >= total):
353 length = upto - offset + 1
354 return (offset, length, total)
356 def get_sharing(request):
357 """Parse an X-Object-Sharing header from the request.
359 Raises BadRequest on error.
362 permissions = request.META.get('HTTP_X_OBJECT_SHARING')
363 if permissions is None:
367 permissions = permissions.replace(' ', '')
368 if permissions == '':
370 for perm in (x for x in permissions.split(';')):
371 if perm.startswith('read='):
372 ret['read'] = [v.replace(' ','').lower() for v in perm[5:].split(',')]
373 if '' in ret['read']:
374 ret['read'].remove('')
375 if '*' in ret['read']:
377 if len(ret['read']) == 0:
378 raise BadRequest('Bad X-Object-Sharing header value')
379 elif perm.startswith('write='):
380 ret['write'] = [v.replace(' ','').lower() for v in perm[6:].split(',')]
381 if '' in ret['write']:
382 ret['write'].remove('')
383 if '*' in ret['write']:
385 if len(ret['write']) == 0:
386 raise BadRequest('Bad X-Object-Sharing header value')
388 raise BadRequest('Bad X-Object-Sharing header value')
391 def raw_input_socket(request):
392 """Return the socket for reading the rest of the request."""
394 server_software = request.META.get('SERVER_SOFTWARE')
395 if not server_software:
396 if 'wsgi.input' in request.environ:
397 return request.environ['wsgi.input']
398 raise ServiceUnavailable('Unknown server software')
399 if server_software.startswith('WSGIServer'):
400 return request.environ['wsgi.input']
401 elif server_software.startswith('mod_python'):
403 raise ServiceUnavailable('Unknown server software')
405 MAX_UPLOAD_SIZE = 10 * (1024 * 1024) # 10MB
407 def socket_read_iterator(sock, length=0, blocksize=4096):
408 """Return a maximum of blocksize data read from the socket in each iteration.
410 Read up to 'length'. If 'length' is negative, will attempt a chunked read.
411 The maximum ammount of data read is controlled by MAX_UPLOAD_SIZE.
414 if length < 0: # Chunked transfers
416 while length < MAX_UPLOAD_SIZE:
418 if hasattr(sock, 'readline'):
419 chunk_length = sock.readline()
422 while chunk_length[-1:] != '\n':
423 chunk_length += sock.read(1)
425 pos = chunk_length.find(';')
427 chunk_length = chunk_length[:pos]
429 chunk_length = int(chunk_length, 16)
431 raise BadRequest('Bad chunk size') # TODO: Change to something more appropriate.
433 if chunk_length == 0:
437 # Get the actual data.
438 while chunk_length > 0:
439 chunk = sock.read(min(chunk_length, blocksize))
440 chunk_length -= len(chunk)
444 if len(data) >= blocksize:
445 ret = data[:blocksize]
446 data = data[blocksize:]
449 # TODO: Raise something to note that maximum size is reached.
451 if length > MAX_UPLOAD_SIZE:
452 # TODO: Raise something to note that maximum size is reached.
455 data = sock.read(min(length, blocksize))
459 class ObjectWrapper(object):
460 """Return the object's data block-per-block in each iteration.
462 Read from the object using the offset and length provided in each entry of the range list.
465 def __init__(self, ranges, sizes, hashmaps, boundary):
468 self.hashmaps = hashmaps
469 self.boundary = boundary
470 self.size = sum(self.sizes)
477 self.range_index = -1
478 self.offset, self.length = self.ranges[0]
483 def part_iterator(self):
485 # Get the file for the current offset.
486 file_size = self.sizes[self.file_index]
487 while self.offset >= file_size:
488 self.offset -= file_size
490 file_size = self.sizes[self.file_index]
492 # Get the block for the current position.
493 self.block_index = int(self.offset / backend.block_size)
494 if self.block_hash != self.hashmaps[self.file_index][self.block_index]:
495 self.block_hash = self.hashmaps[self.file_index][self.block_index]
497 self.block = backend.get_block(self.block_hash)
499 raise ItemNotFound('Block does not exist')
501 # Get the data from the block.
502 bo = self.offset % backend.block_size
503 bl = min(self.length, len(self.block) - bo)
504 data = self.block[bo:bo + bl]
512 if len(self.ranges) == 1:
513 return self.part_iterator()
514 if self.range_index == len(self.ranges):
517 if self.range_index == -1:
519 return self.part_iterator()
520 except StopIteration:
521 self.range_index += 1
523 if self.range_index < len(self.ranges):
525 self.offset, self.length = self.ranges[self.range_index]
527 if self.range_index > 0:
529 out.append('--' + self.boundary)
530 out.append('Content-Range: bytes %d-%d/%d' % (self.offset, self.offset + self.length - 1, self.size))
531 out.append('Content-Transfer-Encoding: binary')
534 return '\r\n'.join(out)
538 out.append('--' + self.boundary + '--')
540 return '\r\n'.join(out)
542 def object_data_response(request, sizes, hashmaps, meta, public=False):
543 """Get the HttpResponse object for replying with the object's data."""
547 ranges = get_range(request, size)
552 check = [True for offset, length in ranges if
553 length <= 0 or length > size or
554 offset < 0 or offset >= size or
555 offset + length > size]
557 raise RangeNotSatisfiable('Requested range exceeds object limits')
559 if_range = request.META.get('HTTP_IF_RANGE', '')
560 if if_range and if_range.startswith('If-Range:'):
561 if_range = if_range.split('If-Range:')[1]
563 # modification time has passed instead
564 last_modified = parse_http_date(if_range)
565 if last_modified != meta['modified']:
569 if if_range != meta['hash']:
573 if ret == 206 and len(ranges) > 1:
574 boundary = uuid.uuid4().hex
577 wrapper = ObjectWrapper(ranges, sizes, hashmaps, boundary)
578 response = HttpResponse(wrapper, status=ret)
579 put_object_headers(response, meta, public)
582 offset, length = ranges[0]
583 response['Content-Length'] = length # Update with the correct length.
584 response['Content-Range'] = 'bytes %d-%d/%d' % (offset, offset + length - 1, size)
586 del(response['Content-Length'])
587 response['Content-Type'] = 'multipart/byteranges; boundary=%s' % (boundary,)
590 def put_object_block(hashmap, data, offset):
591 """Put one block of data at the given offset."""
593 bi = int(offset / backend.block_size)
594 bo = offset % backend.block_size
595 bl = min(len(data), backend.block_size - bo)
596 if bi < len(hashmap):
597 hashmap[bi] = backend.update_block(hashmap[bi], data[:bl], bo)
599 hashmap.append(backend.put_block(('\x00' * bo) + data[:bl]))
600 return bl # Return ammount of data written.
602 def hashmap_hash(hashmap):
603 """Produce the root hash, treating the hashmap as a Merkle-like tree."""
606 h = hashlib.new(backend.hash_algorithm)
610 if len(hashmap) == 0:
611 return hexlify(subhash(''))
612 if len(hashmap) == 1:
613 return hexlify(subhash(hashmap[0]))
615 while s < len(hashmap):
617 h = hashmap + ([('\x00' * len(hashmap[0]))] * (s - len(hashmap)))
618 h = [subhash(h[x] + (h[x + 1] if x + 1 < len(h) else '')) for x in range(0, len(h), 2)]
620 h = [subhash(h[x] + (h[x + 1] if x + 1 < len(h) else '')) for x in range(0, len(h), 2)]
623 def update_response_headers(request, response):
624 if request.serialization == 'xml':
625 response['Content-Type'] = 'application/xml; charset=UTF-8'
626 elif request.serialization == 'json':
627 response['Content-Type'] = 'application/json; charset=UTF-8'
628 elif not response['Content-Type']:
629 response['Content-Type'] = 'text/plain; charset=UTF-8'
632 response['Date'] = format_date_time(time())
634 def render_fault(request, fault):
635 if settings.DEBUG or settings.TEST:
636 fault.details = format_exc(fault)
638 request.serialization = 'text'
639 data = '\n'.join((fault.message, fault.details)) + '\n'
640 response = HttpResponse(data, status=fault.code)
641 update_response_headers(request, response)
644 def request_serialization(request, format_allowed=False):
645 """Return the serialization format requested.
647 Valid formats are 'text' and 'json', 'xml' if 'format_allowed' is True.
650 if not format_allowed:
653 format = request.GET.get('format')
656 elif format == 'xml':
659 for item in request.META.get('HTTP_ACCEPT', '').split(','):
660 accept, sep, rest = item.strip().partition(';')
661 if accept == 'application/json':
663 elif accept == 'application/xml' or accept == 'text/xml':
668 def api_method(http_method=None, format_allowed=False):
669 """Decorator function for views that implement an API method."""
673 def wrapper(request, *args, **kwargs):
675 if http_method and request.method != http_method:
676 raise BadRequest('Method not allowed.')
678 # The args variable may contain up to (account, container, object).
679 if len(args) > 1 and len(args[1]) > 256:
680 raise BadRequest('Container name too large.')
681 if len(args) > 2 and len(args[2]) > 1024:
682 raise BadRequest('Object name too large.')
684 # Fill in custom request variables.
685 request.serialization = request_serialization(request, format_allowed)
687 response = func(request, *args, **kwargs)
688 update_response_headers(request, response)
691 return render_fault(request, fault)
692 except BaseException, e:
693 logger.exception('Unexpected error: %s' % e)
694 fault = ServiceUnavailable('Unexpected error')
695 return render_fault(request, fault)