Close backend connection. Fix empty read.
[pithos] / pithos / api / util.py
1 # Copyright 2011 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
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
44 from django.utils.encoding import smart_str
45
46 from pithos.api.compat import parse_http_date_safe, parse_http_date
47 from pithos.api.faults import (Fault, NotModified, BadRequest, Unauthorized, ItemNotFound,
48                                 Conflict, LengthRequired, PreconditionFailed, RangeNotSatisfiable,
49                                 ServiceUnavailable)
50 from pithos.backends import connect_backend
51 from pithos.backends.base import NotAllowedError
52
53 import datetime
54 import logging
55 import re
56 import hashlib
57 import uuid
58
59
60 logger = logging.getLogger(__name__)
61
62
63 def rename_meta_key(d, old, new):
64     if old not in d:
65         return
66     d[new] = d[old]
67     del(d[old])
68
69 def printable_header_dict(d):
70     """Format a meta dictionary for printing out json/xml.
71     
72     Convert all keys to lower case and replace dashes with underscores.
73     Format 'last_modified' timestamp.
74     """
75     
76     d['last_modified'] = datetime.datetime.fromtimestamp(int(d['last_modified'])).isoformat()
77     return dict([(k.lower().replace('-', '_'), v) for k, v in d.iteritems()])
78
79 def format_header_key(k):
80     """Convert underscores to dashes and capitalize intra-dash strings."""
81     return '-'.join([x.capitalize() for x in k.replace('_', '-').split('-')])
82
83 def get_header_prefix(request, prefix):
84     """Get all prefix-* request headers in a dict. Reformat keys with format_header_key()."""
85     
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)])
89
90 def get_account_headers(request):
91     meta = get_header_prefix(request, 'X-Account-Meta-')
92     groups = {}
93     for k, v in get_header_prefix(request, 'X-Account-Group-').iteritems():
94         n = k[16:].lower()
95         if '-' in n or '_' in n:
96             raise BadRequest('Bad characters in group name')
97         groups[n] = v.replace(' ', '').split(',')
98         if '' in groups[n]:
99             groups[n].remove('')
100     return meta, groups
101
102 def put_account_headers(response, meta, groups):
103     if 'count' in meta:
104         response['X-Account-Container-Count'] = meta['count']
105     if 'bytes' in meta:
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[smart_str(k, strings_only=True)] = smart_str(meta[k], strings_only=True)
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         k = smart_str(k, strings_only=True)
114         k = format_header_key('X-Account-Group-' + k)
115         v = smart_str(','.join(v), strings_only=True)
116         response[k] = v
117     
118 def get_container_headers(request):
119     meta = get_header_prefix(request, 'X-Container-Meta-')
120     policy = dict([(k[19:].lower(), v.replace(' ', '')) for k, v in get_header_prefix(request, 'X-Container-Policy-').iteritems()])
121     return meta, policy
122
123 def put_container_headers(request, response, meta, policy):
124     if 'count' in meta:
125         response['X-Container-Object-Count'] = meta['count']
126     if 'bytes' in meta:
127         response['X-Container-Bytes-Used'] = meta['bytes']
128     response['Last-Modified'] = http_date(int(meta['modified']))
129     for k in [x for x in meta.keys() if x.startswith('X-Container-Meta-')]:
130         response[smart_str(k, strings_only=True)] = smart_str(meta[k], strings_only=True)
131     l = [smart_str(x, strings_only=True) for x in meta['object_meta'] if x.startswith('X-Object-Meta-')]
132     response['X-Container-Object-Meta'] = ','.join([x[14:] for x in l])
133     response['X-Container-Block-Size'] = request.backend.block_size
134     response['X-Container-Block-Hash'] = request.backend.hash_algorithm
135     if 'until_timestamp' in meta:
136         response['X-Container-Until-Timestamp'] = http_date(int(meta['until_timestamp']))
137     for k, v in policy.iteritems():
138         response[smart_str(format_header_key('X-Container-Policy-' + k), strings_only=True)] = smart_str(v, strings_only=True)
139
140 def get_object_headers(request):
141     meta = get_header_prefix(request, 'X-Object-Meta-')
142     if request.META.get('CONTENT_TYPE'):
143         meta['Content-Type'] = request.META['CONTENT_TYPE']
144     if request.META.get('HTTP_CONTENT_ENCODING'):
145         meta['Content-Encoding'] = request.META['HTTP_CONTENT_ENCODING']
146     if request.META.get('HTTP_CONTENT_DISPOSITION'):
147         meta['Content-Disposition'] = request.META['HTTP_CONTENT_DISPOSITION']
148     if request.META.get('HTTP_X_OBJECT_MANIFEST'):
149         meta['X-Object-Manifest'] = request.META['HTTP_X_OBJECT_MANIFEST']
150     return meta, get_sharing(request), get_public(request)
151
152 def put_object_headers(response, meta, restricted=False):
153     response['ETag'] = meta['hash']
154     response['Content-Length'] = meta['bytes']
155     response['Content-Type'] = meta.get('Content-Type', 'application/octet-stream')
156     response['Last-Modified'] = http_date(int(meta['modified']))
157     if not restricted:
158         response['X-Object-Modified-By'] = smart_str(meta['modified_by'], strings_only=True)
159         response['X-Object-Version'] = meta['version']
160         response['X-Object-Version-Timestamp'] = http_date(int(meta['version_timestamp']))
161         for k in [x for x in meta.keys() if x.startswith('X-Object-Meta-')]:
162             response[smart_str(k, strings_only=True)] = smart_str(meta[k], strings_only=True)
163         for k in ('Content-Encoding', 'Content-Disposition', 'X-Object-Manifest',
164                   'X-Object-Sharing', 'X-Object-Shared-By', 'X-Object-Allowed-To',
165                   'X-Object-Public'):
166             if k in meta:
167                 response[k] = smart_str(meta[k], strings_only=True)
168     else:
169         for k in ('Content-Encoding', 'Content-Disposition'):
170             if k in meta:
171                 response[k] = meta[k]
172
173 def update_manifest_meta(request, v_account, meta):
174     """Update metadata if the object has an X-Object-Manifest."""
175     
176     if 'X-Object-Manifest' in meta:
177         hash = ''
178         bytes = 0
179         try:
180             src_container, src_name = split_container_object_string('/' + meta['X-Object-Manifest'])
181             objects = request.backend.list_objects(request.user, v_account,
182                                 src_container, prefix=src_name, virtual=False)
183             for x in objects:
184                 src_meta = request.backend.get_object_meta(request.user,
185                                         v_account, src_container, x[0], x[1])
186                 hash += src_meta['hash']
187                 bytes += src_meta['bytes']
188         except:
189             # Ignore errors.
190             return
191         meta['bytes'] = bytes
192         md5 = hashlib.md5()
193         md5.update(hash)
194         meta['hash'] = md5.hexdigest().lower()
195
196 def update_sharing_meta(request, permissions, v_account, v_container, v_object, meta):
197     if permissions is None:
198         return
199     allowed, perm_path, perms = permissions
200     if len(perms) == 0:
201         return
202     ret = []
203     r = ','.join(perms.get('read', []))
204     if r:
205         ret.append('read=' + r)
206     w = ','.join(perms.get('write', []))
207     if w:
208         ret.append('write=' + w)
209     meta['X-Object-Sharing'] = '; '.join(ret)
210     if '/'.join((v_account, v_container, v_object)) != perm_path:
211         meta['X-Object-Shared-By'] = perm_path
212     if request.user != v_account:
213         meta['X-Object-Allowed-To'] = allowed
214
215 def update_public_meta(public, meta):
216     if not public:
217         return
218     meta['X-Object-Public'] = public
219
220 def validate_modification_preconditions(request, meta):
221     """Check that the modified timestamp conforms with the preconditions set."""
222     
223     if 'modified' not in meta:
224         return # TODO: Always return?
225     
226     if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')
227     if if_modified_since is not None:
228         if_modified_since = parse_http_date_safe(if_modified_since)
229     if if_modified_since is not None and int(meta['modified']) <= if_modified_since:
230         raise NotModified('Resource has not been modified')
231     
232     if_unmodified_since = request.META.get('HTTP_IF_UNMODIFIED_SINCE')
233     if if_unmodified_since is not None:
234         if_unmodified_since = parse_http_date_safe(if_unmodified_since)
235     if if_unmodified_since is not None and int(meta['modified']) > if_unmodified_since:
236         raise PreconditionFailed('Resource has been modified')
237
238 def validate_matching_preconditions(request, meta):
239     """Check that the ETag conforms with the preconditions set."""
240     
241     hash = meta.get('hash', None)
242     
243     if_match = request.META.get('HTTP_IF_MATCH')
244     if if_match is not None:
245         if hash is None:
246             raise PreconditionFailed('Resource does not exist')
247         if if_match != '*' and hash not in [x.lower() for x in parse_etags(if_match)]:
248             raise PreconditionFailed('Resource ETag does not match')
249     
250     if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
251     if if_none_match is not None:
252         # TODO: If this passes, must ignore If-Modified-Since header.
253         if hash is not None:
254             if if_none_match == '*' or hash in [x.lower() for x in parse_etags(if_none_match)]:
255                 # TODO: Continue if an If-Modified-Since header is present.
256                 if request.method in ('HEAD', 'GET'):
257                     raise NotModified('Resource ETag matches')
258                 raise PreconditionFailed('Resource exists or ETag matches')
259
260 def split_container_object_string(s):
261     if not len(s) > 0 or s[0] != '/':
262         raise ValueError
263     s = s[1:]
264     pos = s.find('/')
265     if pos == -1:
266         raise ValueError
267     return s[:pos], s[(pos + 1):]
268
269 def copy_or_move_object(request, v_account, src_container, src_name, dest_container, dest_name, move=False):
270     """Copy or move an object."""
271     
272     meta, permissions, public = get_object_headers(request)
273     src_version = request.META.get('HTTP_X_SOURCE_VERSION')    
274     try:
275         if move:
276             version_id = request.backend.move_object(request.user, v_account,
277                             src_container, src_name, dest_container, dest_name,
278                             meta, False, permissions)
279         else:
280             version_id = request.backend.copy_object(request.user, v_account,
281                             src_container, src_name, dest_container, dest_name,
282                             meta, False, permissions, src_version)
283     except NotAllowedError:
284         raise Unauthorized('Access denied')
285     except (NameError, IndexError):
286         raise ItemNotFound('Container or object does not exist')
287     except ValueError:
288         raise BadRequest('Invalid sharing header')
289     except AttributeError, e:
290         raise Conflict(json.dumps(e.data))
291     if public is not None:
292         try:
293             request.backend.update_object_public(request.user, v_account,
294                                             dest_container, dest_name, public)
295         except NotAllowedError:
296             raise Unauthorized('Access denied')
297         except NameError:
298             raise ItemNotFound('Object does not exist')
299     return version_id
300
301 def get_int_parameter(p):
302     if p is not None:
303         try:
304             p = int(p)
305         except ValueError:
306             return None
307         if p < 0:
308             return None
309     return p
310
311 def get_content_length(request):
312     content_length = get_int_parameter(request.META.get('CONTENT_LENGTH'))
313     if content_length is None:
314         raise LengthRequired('Missing or invalid Content-Length header')
315     return content_length
316
317 def get_range(request, size):
318     """Parse a Range header from the request.
319     
320     Either returns None, when the header is not existent or should be ignored,
321     or a list of (offset, length) tuples - should be further checked.
322     """
323     
324     ranges = request.META.get('HTTP_RANGE', '').replace(' ', '')
325     if not ranges.startswith('bytes='):
326         return None
327     
328     ret = []
329     for r in (x.strip() for x in ranges[6:].split(',')):
330         p = re.compile('^(?P<offset>\d*)-(?P<upto>\d*)$')
331         m = p.match(r)
332         if not m:
333             return None
334         offset = m.group('offset')
335         upto = m.group('upto')
336         if offset == '' and upto == '':
337             return None
338         
339         if offset != '':
340             offset = int(offset)
341             if upto != '':
342                 upto = int(upto)
343                 if offset > upto:
344                     return None
345                 ret.append((offset, upto - offset + 1))
346             else:
347                 ret.append((offset, size - offset))
348         else:
349             length = int(upto)
350             ret.append((size - length, length))
351     
352     return ret
353
354 def get_content_range(request):
355     """Parse a Content-Range header from the request.
356     
357     Either returns None, when the header is not existent or should be ignored,
358     or an (offset, length, total) tuple - check as length, total may be None.
359     Returns (None, None, None) if the provided range is '*/*'.
360     """
361     
362     ranges = request.META.get('HTTP_CONTENT_RANGE', '')
363     if not ranges:
364         return None
365     
366     p = re.compile('^bytes (?P<offset>\d+)-(?P<upto>\d*)/(?P<total>(\d+|\*))$')
367     m = p.match(ranges)
368     if not m:
369         if ranges == 'bytes */*':
370             return (None, None, None)
371         return None
372     offset = int(m.group('offset'))
373     upto = m.group('upto')
374     total = m.group('total')
375     if upto != '':
376         upto = int(upto)
377     else:
378         upto = None
379     if total != '*':
380         total = int(total)
381     else:
382         total = None
383     if (upto is not None and offset > upto) or \
384         (total is not None and offset >= total) or \
385         (total is not None and upto is not None and upto >= total):
386         return None
387     
388     if upto is None:
389         length = None
390     else:
391         length = upto - offset + 1
392     return (offset, length, total)
393
394 def get_sharing(request):
395     """Parse an X-Object-Sharing header from the request.
396     
397     Raises BadRequest on error.
398     """
399     
400     permissions = request.META.get('HTTP_X_OBJECT_SHARING')
401     if permissions is None:
402         return None
403     
404     # TODO: Document or remove '~' replacing.
405     permissions = permissions.replace('~', '')
406     
407     ret = {}
408     permissions = permissions.replace(' ', '')
409     if permissions == '':
410         return ret
411     for perm in (x for x in permissions.split(';')):
412         if perm.startswith('read='):
413             ret['read'] = list(set([v.replace(' ','').lower() for v in perm[5:].split(',')]))
414             if '' in ret['read']:
415                 ret['read'].remove('')
416             if '*' in ret['read']:
417                 ret['read'] = ['*']
418             if len(ret['read']) == 0:
419                 raise BadRequest('Bad X-Object-Sharing header value')
420         elif perm.startswith('write='):
421             ret['write'] = list(set([v.replace(' ','').lower() for v in perm[6:].split(',')]))
422             if '' in ret['write']:
423                 ret['write'].remove('')
424             if '*' in ret['write']:
425                 ret['write'] = ['*']
426             if len(ret['write']) == 0:
427                 raise BadRequest('Bad X-Object-Sharing header value')
428         else:
429             raise BadRequest('Bad X-Object-Sharing header value')
430     
431     # Keep duplicates only in write list.
432     dups = [x for x in ret.get('read', []) if x in ret.get('write', []) and x != '*']
433     if dups:
434         for x in dups:
435             ret['read'].remove(x)
436         if len(ret['read']) == 0:
437             del(ret['read'])
438     
439     return ret
440
441 def get_public(request):
442     """Parse an X-Object-Public header from the request.
443     
444     Raises BadRequest on error.
445     """
446     
447     public = request.META.get('HTTP_X_OBJECT_PUBLIC')
448     if public is None:
449         return None
450     
451     public = public.replace(' ', '').lower()
452     if public == 'true':
453         return True
454     elif public == 'false' or public == '':
455         return False
456     raise BadRequest('Bad X-Object-Public header value')
457
458 def raw_input_socket(request):
459     """Return the socket for reading the rest of the request."""
460     
461     server_software = request.META.get('SERVER_SOFTWARE')
462     if server_software and server_software.startswith('mod_python'):
463         return request._req
464     if 'wsgi.input' in request.environ:
465         return request.environ['wsgi.input']
466     raise ServiceUnavailable('Unknown server software')
467
468 MAX_UPLOAD_SIZE = 10 * (1024 * 1024) # 10MB
469
470 def socket_read_iterator(request, length=0, blocksize=4096):
471     """Return a maximum of blocksize data read from the socket in each iteration.
472     
473     Read up to 'length'. If 'length' is negative, will attempt a chunked read.
474     The maximum ammount of data read is controlled by MAX_UPLOAD_SIZE.
475     """
476     
477     sock = raw_input_socket(request)
478     if length < 0: # Chunked transfers
479         # Small version (server does the dechunking).
480         if request.environ.get('mod_wsgi.input_chunked', None):
481             while length < MAX_UPLOAD_SIZE:
482                 data = sock.read(blocksize)
483                 if data == '':
484                     return
485                 yield data
486             raise BadRequest('Maximum size is reached')
487         
488         # Long version (do the dechunking).
489         data = ''
490         while length < MAX_UPLOAD_SIZE:
491             # Get chunk size.
492             if hasattr(sock, 'readline'):
493                 chunk_length = sock.readline()
494             else:
495                 chunk_length = ''
496                 while chunk_length[-1:] != '\n':
497                     chunk_length += sock.read(1)
498                 chunk_length.strip()
499             pos = chunk_length.find(';')
500             if pos >= 0:
501                 chunk_length = chunk_length[:pos]
502             try:
503                 chunk_length = int(chunk_length, 16)
504             except Exception, e:
505                 raise BadRequest('Bad chunk size') # TODO: Change to something more appropriate.
506             # Check if done.
507             if chunk_length == 0:
508                 if len(data) > 0:
509                     yield data
510                 return
511             # Get the actual data.
512             while chunk_length > 0:
513                 chunk = sock.read(min(chunk_length, blocksize))
514                 chunk_length -= len(chunk)
515                 if length > 0:
516                     length += len(chunk)
517                 data += chunk
518                 if len(data) >= blocksize:
519                     ret = data[:blocksize]
520                     data = data[blocksize:]
521                     yield ret
522             sock.read(2) # CRLF
523         raise BadRequest('Maximum size is reached')
524     else:
525         if length > MAX_UPLOAD_SIZE:
526             raise BadRequest('Maximum size is reached')
527         while length > 0:
528             data = sock.read(min(length, blocksize))
529             if not data:
530                 raise BadRequest()
531             length -= len(data)
532             yield data
533
534 class ObjectWrapper(object):
535     """Return the object's data block-per-block in each iteration.
536     
537     Read from the object using the offset and length provided in each entry of the range list.
538     """
539     
540     def __init__(self, backend, ranges, sizes, hashmaps, boundary):
541         self.backend = backend
542         self.ranges = ranges
543         self.sizes = sizes
544         self.hashmaps = hashmaps
545         self.boundary = boundary
546         self.size = sum(self.sizes)
547         
548         self.file_index = 0
549         self.block_index = 0
550         self.block_hash = -1
551         self.block = ''
552         
553         self.range_index = -1
554         self.offset, self.length = self.ranges[0]
555     
556     def __iter__(self):
557         return self
558     
559     def part_iterator(self):
560         if self.length > 0:
561             # Get the file for the current offset.
562             file_size = self.sizes[self.file_index]
563             while self.offset >= file_size:
564                 self.offset -= file_size
565                 self.file_index += 1
566                 file_size = self.sizes[self.file_index]
567             
568             # Get the block for the current position.
569             self.block_index = int(self.offset / self.backend.block_size)
570             if self.block_hash != self.hashmaps[self.file_index][self.block_index]:
571                 self.block_hash = self.hashmaps[self.file_index][self.block_index]
572                 try:
573                     self.block = self.backend.get_block(self.block_hash)
574                 except NameError:
575                     raise ItemNotFound('Block does not exist')
576             
577             # Get the data from the block.
578             bo = self.offset % self.backend.block_size
579             bl = min(self.length, len(self.block) - bo)
580             data = self.block[bo:bo + bl]
581             self.offset += bl
582             self.length -= bl
583             return data
584         else:
585             raise StopIteration
586     
587     def next(self):
588         if len(self.ranges) == 1:
589             return self.part_iterator()
590         if self.range_index == len(self.ranges):
591             raise StopIteration
592         try:
593             if self.range_index == -1:
594                 raise StopIteration
595             return self.part_iterator()
596         except StopIteration:
597             self.range_index += 1
598             out = []
599             if self.range_index < len(self.ranges):
600                 # Part header.
601                 self.offset, self.length = self.ranges[self.range_index]
602                 self.file_index = 0
603                 if self.range_index > 0:
604                     out.append('')
605                 out.append('--' + self.boundary)
606                 out.append('Content-Range: bytes %d-%d/%d' % (self.offset, self.offset + self.length - 1, self.size))
607                 out.append('Content-Transfer-Encoding: binary')
608                 out.append('')
609                 out.append('')
610                 return '\r\n'.join(out)
611             else:
612                 # Footer.
613                 out.append('')
614                 out.append('--' + self.boundary + '--')
615                 out.append('')
616                 return '\r\n'.join(out)
617
618 def object_data_response(request, sizes, hashmaps, meta, public=False):
619     """Get the HttpResponse object for replying with the object's data."""
620     
621     # Range handling.
622     size = sum(sizes)
623     ranges = get_range(request, size)
624     if ranges is None:
625         ranges = [(0, size)]
626         ret = 200
627     else:
628         check = [True for offset, length in ranges if
629                     length <= 0 or length > size or
630                     offset < 0 or offset >= size or
631                     offset + length > size]
632         if len(check) > 0:
633             raise RangeNotSatisfiable('Requested range exceeds object limits')
634         ret = 206
635         if_range = request.META.get('HTTP_IF_RANGE')
636         if if_range:
637             try:
638                 # Modification time has passed instead.
639                 last_modified = parse_http_date(if_range)
640                 if last_modified != meta['modified']:
641                     ranges = [(0, size)]
642                     ret = 200
643             except ValueError:
644                 if if_range != meta['hash']:
645                     ranges = [(0, size)]
646                     ret = 200
647     
648     if ret == 206 and len(ranges) > 1:
649         boundary = uuid.uuid4().hex
650     else:
651         boundary = ''
652     wrapper = ObjectWrapper(request.backend, ranges, sizes, hashmaps, boundary)
653     response = HttpResponse(wrapper, status=ret)
654     put_object_headers(response, meta, public)
655     if ret == 206:
656         if len(ranges) == 1:
657             offset, length = ranges[0]
658             response['Content-Length'] = length # Update with the correct length.
659             response['Content-Range'] = 'bytes %d-%d/%d' % (offset, offset + length - 1, size)
660         else:
661             del(response['Content-Length'])
662             response['Content-Type'] = 'multipart/byteranges; boundary=%s' % (boundary,)
663     return response
664
665 def put_object_block(request, hashmap, data, offset):
666     """Put one block of data at the given offset."""
667     
668     bi = int(offset / request.backend.block_size)
669     bo = offset % request.backend.block_size
670     bl = min(len(data), request.backend.block_size - bo)
671     if bi < len(hashmap):
672         hashmap[bi] = request.backend.update_block(hashmap[bi], data[:bl], bo)
673     else:
674         hashmap.append(request.backend.put_block(('\x00' * bo) + data[:bl]))
675     return bl # Return ammount of data written.
676
677 def hashmap_hash(request, hashmap):
678     """Produce the root hash, treating the hashmap as a Merkle-like tree."""
679     
680     def subhash(d):
681         h = hashlib.new(request.backend.hash_algorithm)
682         h.update(d)
683         return h.digest()
684     
685     if len(hashmap) == 0:
686         return hexlify(subhash(''))
687     if len(hashmap) == 1:
688         return hashmap[0]
689     
690     s = 2
691     while s < len(hashmap):
692         s = s * 2
693     h = [unhexlify(x) for x in hashmap]
694     h += [('\x00' * len(h[0]))] * (s - len(hashmap))
695     while len(h) > 1:
696         h = [subhash(h[x] + h[x + 1]) for x in range(0, len(h), 2)]
697     return hexlify(h[0])
698
699 def update_response_headers(request, response):
700     if request.serialization == 'xml':
701         response['Content-Type'] = 'application/xml; charset=UTF-8'
702     elif request.serialization == 'json':
703         response['Content-Type'] = 'application/json; charset=UTF-8'
704     elif not response['Content-Type']:
705         response['Content-Type'] = 'text/plain; charset=UTF-8'
706     
707     if not response.has_header('Content-Length') and not (response.has_header('Content-Type') and response['Content-Type'].startswith('multipart/byteranges')):
708         response['Content-Length'] = len(response.content)
709     
710     if settings.TEST:
711         response['Date'] = format_date_time(time())
712
713 def render_fault(request, fault):
714     if settings.DEBUG or settings.TEST:
715         fault.details = format_exc(fault)
716     
717     request.serialization = 'text'
718     data = '\n'.join((fault.message, fault.details)) + '\n'
719     response = HttpResponse(data, status=fault.code)
720     update_response_headers(request, response)
721     return response
722
723 def request_serialization(request, format_allowed=False):
724     """Return the serialization format requested.
725     
726     Valid formats are 'text' and 'json', 'xml' if 'format_allowed' is True.
727     """
728     
729     if not format_allowed:
730         return 'text'
731     
732     format = request.GET.get('format')
733     if format == 'json':
734         return 'json'
735     elif format == 'xml':
736         return 'xml'
737     
738     for item in request.META.get('HTTP_ACCEPT', '').split(','):
739         accept, sep, rest = item.strip().partition(';')
740         if accept == 'application/json':
741             return 'json'
742         elif accept == 'application/xml' or accept == 'text/xml':
743             return 'xml'
744     
745     return 'text'
746
747 def api_method(http_method=None, format_allowed=False):
748     """Decorator function for views that implement an API method."""
749     
750     def decorator(func):
751         @wraps(func)
752         def wrapper(request, *args, **kwargs):
753             try:
754                 if http_method and request.method != http_method:
755                     raise BadRequest('Method not allowed.')
756                 
757                 # The args variable may contain up to (account, container, object).
758                 if len(args) > 1 and len(args[1]) > 256:
759                     raise BadRequest('Container name too large.')
760                 if len(args) > 2 and len(args[2]) > 1024:
761                     raise BadRequest('Object name too large.')
762                 
763                 # Fill in custom request variables.
764                 request.serialization = request_serialization(request, format_allowed)
765                 request.backend = connect_backend()
766
767                 response = func(request, *args, **kwargs)
768                 update_response_headers(request, response)
769                 return response
770             except Fault, fault:
771                 return render_fault(request, fault)
772             except BaseException, e:
773                 logger.exception('Unexpected error: %s' % e)
774                 fault = ServiceUnavailable('Unexpected error')
775                 return render_fault(request, fault)
776             finally:
777                 request.backend.wrapper.conn.close()
778         return wrapper
779     return decorator