Statistics
| Branch: | Tag: | Revision:

root / pithos / api / functions.py @ a6eb13e9

History | View | Annotate | Download (27.9 kB)

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
import os
35
import logging
36
import hashlib
37

    
38
from django.http import HttpResponse
39
from django.template.loader import render_to_string
40
from django.utils import simplejson as json
41
from django.utils.http import parse_etags
42

    
43
from pithos.api.faults import (Fault, NotModified, BadRequest, Unauthorized, ItemNotFound, Conflict,
44
    LengthRequired, PreconditionFailed, RangeNotSatisfiable, UnprocessableEntity)
45
from pithos.api.util import (format_meta_key, printable_meta_dict, get_account_meta,
46
    put_account_meta, get_container_meta, put_container_meta, get_object_meta, put_object_meta,
47
    update_manifest_meta, format_permissions, validate_modification_preconditions,
48
    validate_matching_preconditions, split_container_object_string, copy_or_move_object,
49
    get_int_parameter, get_content_length, get_content_range, get_sharing, raw_input_socket,
50
    socket_read_iterator, object_data_response, put_object_block, hashmap_hash, api_method)
51
from pithos.backends import backend
52

    
53

    
54
logger = logging.getLogger(__name__)
55

    
56

    
57
def top_demux(request):
58
    if request.method == 'GET':
59
        return authenticate(request)
60
    else:
61
        return method_not_allowed(request)
62

    
63
def account_demux(request, v_account):
64
    if request.method == 'HEAD':
65
        return account_meta(request, v_account)
66
    elif request.method == 'POST':
67
        return account_update(request, v_account)
68
    elif request.method == 'GET':
69
        return container_list(request, v_account)
70
    else:
71
        return method_not_allowed(request)
72

    
73
def container_demux(request, v_account, v_container):
74
    if request.method == 'HEAD':
75
        return container_meta(request, v_account, v_container)
76
    elif request.method == 'PUT':
77
        return container_create(request, v_account, v_container)
78
    elif request.method == 'POST':
79
        return container_update(request, v_account, v_container)
80
    elif request.method == 'DELETE':
81
        return container_delete(request, v_account, v_container)
82
    elif request.method == 'GET':
83
        return object_list(request, v_account, v_container)
84
    else:
85
        return method_not_allowed(request)
86

    
87
def object_demux(request, v_account, v_container, v_object):
88
    if request.method == 'HEAD':
89
        return object_meta(request, v_account, v_container, v_object)
90
    elif request.method == 'GET':
91
        return object_read(request, v_account, v_container, v_object)
92
    elif request.method == 'PUT':
93
        return object_write(request, v_account, v_container, v_object)
94
    elif request.method == 'COPY':
95
        return object_copy(request, v_account, v_container, v_object)
96
    elif request.method == 'MOVE':
97
        return object_move(request, v_account, v_container, v_object)
98
    elif request.method == 'POST':
99
        return object_update(request, v_account, v_container, v_object)
100
    elif request.method == 'DELETE':
101
        return object_delete(request, v_account, v_container, v_object)
102
    else:
103
        return method_not_allowed(request)
104

    
105
@api_method('GET')
106
def authenticate(request):
107
    # Normal Response Codes: 204
108
    # Error Response Codes: serviceUnavailable (503),
109
    #                       unauthorized (401),
110
    #                       badRequest (400)
111
    
112
    x_auth_user = request.META.get('HTTP_X_AUTH_USER')
113
    x_auth_key = request.META.get('HTTP_X_AUTH_KEY')
114
    if not x_auth_user or not x_auth_key:
115
        raise BadRequest('Missing X-Auth-User or X-Auth-Key header')
116
    response = HttpResponse(status=204)
117
    response['X-Auth-Token'] = '0000'
118
    response['X-Storage-Url'] = os.path.join(request.build_absolute_uri(), 'demo')
119
    return response
120

    
121
@api_method('HEAD')
122
def account_meta(request, v_account):
123
    # Normal Response Codes: 204
124
    # Error Response Codes: serviceUnavailable (503),
125
    #                       unauthorized (401),
126
    #                       badRequest (400)
127
    
128
    until = get_int_parameter(request, 'until')
129
    meta = backend.get_account_meta(request.user, v_account, until)
130
    
131
    response = HttpResponse(status=204)
132
    put_account_meta(response, meta)
133
    return response
134

    
135
@api_method('POST')
136
def account_update(request, v_account):
137
    # Normal Response Codes: 202
138
    # Error Response Codes: serviceUnavailable (503),
139
    #                       unauthorized (401),
140
    #                       badRequest (400)
141
    
142
    meta = get_account_meta(request)
143
    replace = True
144
    if 'update' in request.GET:
145
        replace = False
146
    backend.update_account_meta(request.user, v_account, meta, replace)
147
    return HttpResponse(status=202)
148

    
149
@api_method('GET', format_allowed=True)
150
def container_list(request, v_account):
151
    # Normal Response Codes: 200, 204
152
    # Error Response Codes: serviceUnavailable (503),
153
    #                       itemNotFound (404),
154
    #                       unauthorized (401),
155
    #                       badRequest (400)
156
    
157
    until = get_int_parameter(request, 'until')
158
    meta = backend.get_account_meta(request.user, v_account, until)
159
    
160
    validate_modification_preconditions(request, meta)
161
    
162
    response = HttpResponse()
163
    put_account_meta(response, meta)
164
    
165
    marker = request.GET.get('marker')
166
    limit = request.GET.get('limit')
167
    if limit:
168
        try:
169
            limit = int(limit)
170
            if limit <= 0:
171
                raise ValueError
172
        except ValueError:
173
            limit = 10000
174
    
175
    try:
176
        containers = backend.list_containers(request.user, v_account, marker, limit, until)
177
    except NameError:
178
        containers = []
179
    
180
    if request.serialization == 'text':
181
        if len(containers) == 0:
182
            # The cloudfiles python bindings expect 200 if json/xml.
183
            response.status_code = 204
184
            return response
185
        response.status_code = 200
186
        response.content = '\n'.join([x[0] for x in containers]) + '\n'
187
        return response
188
    
189
    container_meta = []
190
    for x in containers:
191
        if x[1] is not None:
192
            try:
193
                meta = backend.get_container_meta(request.user, v_account, x[0], until)
194
                container_meta.append(printable_meta_dict(meta))
195
            except NameError:
196
                pass
197
    if request.serialization == 'xml':
198
        data = render_to_string('containers.xml', {'account': v_account, 'containers': container_meta})
199
    elif request.serialization  == 'json':
200
        data = json.dumps(container_meta)
201
    response.status_code = 200
202
    response.content = data
203
    return response
204

    
205
@api_method('HEAD')
206
def container_meta(request, v_account, v_container):
207
    # Normal Response Codes: 204
208
    # Error Response Codes: serviceUnavailable (503),
209
    #                       itemNotFound (404),
210
    #                       unauthorized (401),
211
    #                       badRequest (400)
212
    
213
    until = get_int_parameter(request, 'until')
214
    try:
215
        meta = backend.get_container_meta(request.user, v_account, v_container, until)
216
        meta['object_meta'] = backend.list_object_meta(request.user, v_account, v_container, until)
217
    except NameError:
218
        raise ItemNotFound('Container does not exist')
219
    
220
    response = HttpResponse(status=204)
221
    put_container_meta(response, meta)
222
    return response
223

    
224
@api_method('PUT')
225
def container_create(request, v_account, v_container):
226
    # Normal Response Codes: 201, 202
227
    # Error Response Codes: serviceUnavailable (503),
228
    #                       itemNotFound (404),
229
    #                       unauthorized (401),
230
    #                       badRequest (400)
231
    
232
    meta = get_container_meta(request)
233
    
234
    try:
235
        backend.put_container(request.user, v_account, v_container)
236
        ret = 201
237
    except NameError:
238
        ret = 202
239
    
240
    if len(meta) > 0:
241
        backend.update_container_meta(request.user, v_account, v_container, meta, replace=True)
242
    
243
    return HttpResponse(status=ret)
244

    
245
@api_method('POST')
246
def container_update(request, v_account, v_container):
247
    # Normal Response Codes: 202
248
    # Error Response Codes: serviceUnavailable (503),
249
    #                       itemNotFound (404),
250
    #                       unauthorized (401),
251
    #                       badRequest (400)
252
    
253
    meta = get_container_meta(request)
254
    replace = True
255
    if 'update' in request.GET:
256
        replace = False
257
    try:
258
        backend.update_container_meta(request.user, v_account, v_container, meta, replace)
259
    except NameError:
260
        raise ItemNotFound('Container does not exist')
261
    return HttpResponse(status=202)
262

    
263
@api_method('DELETE')
264
def container_delete(request, v_account, v_container):
265
    # Normal Response Codes: 204
266
    # Error Response Codes: serviceUnavailable (503),
267
    #                       conflict (409),
268
    #                       itemNotFound (404),
269
    #                       unauthorized (401),
270
    #                       badRequest (400)
271
    
272
    try:
273
        backend.delete_container(request.user, v_account, v_container)
274
    except NameError:
275
        raise ItemNotFound('Container does not exist')
276
    except IndexError:
277
        raise Conflict('Container is not empty')
278
    return HttpResponse(status=204)
279

    
280
@api_method('GET', format_allowed=True)
281
def object_list(request, v_account, v_container):
282
    # Normal Response Codes: 200, 204
283
    # Error Response Codes: serviceUnavailable (503),
284
    #                       itemNotFound (404),
285
    #                       unauthorized (401),
286
    #                       badRequest (400)
287
    
288
    until = get_int_parameter(request, 'until')
289
    try:
290
        meta = backend.get_container_meta(request.user, v_account, v_container, until)
291
        meta['object_meta'] = backend.list_object_meta(request.user, v_account, v_container, until)
292
    except NameError:
293
        raise ItemNotFound('Container does not exist')
294
    
295
    validate_modification_preconditions(request, meta)
296
    
297
    response = HttpResponse()
298
    put_container_meta(response, meta)
299
    
300
    path = request.GET.get('path')
301
    prefix = request.GET.get('prefix')
302
    delimiter = request.GET.get('delimiter')
303
    
304
    # Path overrides prefix and delimiter.
305
    virtual = True
306
    if path:
307
        prefix = path
308
        delimiter = '/'
309
        virtual = False
310
    
311
    # Naming policy.
312
    if prefix and delimiter:
313
        prefix = prefix + delimiter
314
    if not prefix:
315
        prefix = ''
316
    prefix = prefix.lstrip('/')
317
    
318
    marker = request.GET.get('marker')
319
    limit = request.GET.get('limit')
320
    if limit:
321
        try:
322
            limit = int(limit)
323
            if limit <= 0:
324
                raise ValueError
325
        except ValueError:
326
            limit = 10000
327
    
328
    keys = request.GET.get('meta')
329
    if keys:
330
        keys = keys.split(',')
331
        keys = [format_meta_key('X-Object-Meta-' + x.strip()) for x in keys if x.strip() != '']
332
    else:
333
        keys = []
334
    
335
    try:
336
        objects = backend.list_objects(request.user, v_account, v_container, prefix, delimiter, marker, limit, virtual, keys, until)
337
    except NameError:
338
        raise ItemNotFound('Container does not exist')
339
    
340
    if request.serialization == 'text':
341
        if len(objects) == 0:
342
            # The cloudfiles python bindings expect 200 if json/xml.
343
            response.status_code = 204
344
            return response
345
        response.status_code = 200
346
        response.content = '\n'.join([x[0] for x in objects]) + '\n'
347
        return response
348
    
349
    object_meta = []
350
    for x in objects:
351
        if x[1] is None:
352
            # Virtual objects/directories.
353
            object_meta.append({'subdir': x[0]})
354
        else:
355
            try:
356
                meta = backend.get_object_meta(request.user, v_account, v_container, x[0], x[1])
357
                if until is None:
358
                    permissions = backend.get_object_permissions(request.user, v_account, v_container, x[0])
359
                else:
360
                    permissions = None
361
            except NameError:
362
                pass
363
            if permissions:
364
                meta['X-Object-Sharing'] = format_permissions(permissions)
365
            object_meta.append(printable_meta_dict(meta))
366
    if request.serialization == 'xml':
367
        data = render_to_string('objects.xml', {'container': v_container, 'objects': object_meta})
368
    elif request.serialization  == 'json':
369
        data = json.dumps(object_meta)
370
    response.status_code = 200
371
    response.content = data
372
    return response
373

    
374
@api_method('HEAD')
375
def object_meta(request, v_account, v_container, v_object):
376
    # Normal Response Codes: 204
377
    # Error Response Codes: serviceUnavailable (503),
378
    #                       itemNotFound (404),
379
    #                       unauthorized (401),
380
    #                       badRequest (400)
381
    
382
    version = get_int_parameter(request, 'version')
383
    try:
384
        meta = backend.get_object_meta(request.user, v_account, v_container, v_object, version)
385
        if version is None:
386
            permissions = backend.get_object_permissions(request.user, v_account, v_container, v_object)
387
        else:
388
            permissions = None
389
    except NameError:
390
        raise ItemNotFound('Object does not exist')
391
    except IndexError:
392
        raise ItemNotFound('Version does not exist')
393
    
394
    if permissions:
395
        meta['X-Object-Sharing'] = format_permissions(permissions)
396
    update_manifest_meta(request, v_account, meta)
397
    
398
    response = HttpResponse(status=200)
399
    put_object_meta(response, meta)
400
    return response
401

    
402
@api_method('GET', format_allowed=True)
403
def object_read(request, v_account, v_container, v_object):
404
    # Normal Response Codes: 200, 206
405
    # Error Response Codes: serviceUnavailable (503),
406
    #                       rangeNotSatisfiable (416),
407
    #                       preconditionFailed (412),
408
    #                       itemNotFound (404),
409
    #                       unauthorized (401),
410
    #                       badRequest (400),
411
    #                       notModified (304)
412
    
413
    version = get_int_parameter(request, 'version')
414
    
415
    # Reply with the version list. Do this first, as the object may be deleted.
416
    if version is None and request.GET.get('version') == 'list':
417
        if request.serialization == 'text':
418
            raise BadRequest('No format specified for version list.')
419
        
420
        d = {'versions': backend.list_versions(request.user, v_account, v_container, v_object)}
421
        if request.serialization == 'xml':
422
            d['object'] = v_object
423
            data = render_to_string('versions.xml', d)
424
        elif request.serialization  == 'json':
425
            data = json.dumps(d)
426
        
427
        response = HttpResponse(data, status=200)
428
        response['Content-Length'] = len(data)
429
        return response
430
    
431
    try:
432
        meta = backend.get_object_meta(request.user, v_account, v_container, v_object, version)
433
        if version is None:
434
            permissions = backend.get_object_permissions(request.user, v_account, v_container, v_object)
435
        else:
436
            permissions = None
437
    except NameError:
438
        raise ItemNotFound('Object does not exist')
439
    except IndexError:
440
        raise ItemNotFound('Version does not exist')
441
    
442
    if permissions:
443
        meta['X-Object-Sharing'] = format_permissions(permissions)
444
    update_manifest_meta(request, v_account, meta)
445
    
446
    # Evaluate conditions.
447
    validate_modification_preconditions(request, meta)
448
    try:
449
        validate_matching_preconditions(request, meta)
450
    except NotModified:
451
        response = HttpResponse(status=304)
452
        response['ETag'] = meta['hash']
453
        return response
454
    
455
    sizes = []
456
    hashmaps = []
457
    if 'X-Object-Manifest' in meta:
458
        try:
459
            src_container, src_name = split_container_object_string('/' + meta['X-Object-Manifest'])
460
            objects = backend.list_objects(request.user, v_account, src_container, prefix=src_name, virtual=False)
461
        except ValueError:
462
            raise BadRequest('Invalid X-Object-Manifest header')
463
        except NameError:
464
            raise ItemNotFound('Container does not exist')
465
        
466
        try:
467
            for x in objects:
468
                s, h = backend.get_object_hashmap(request.user, v_account, src_container, x[0], x[1])
469
                sizes.append(s)
470
                hashmaps.append(h)
471
        except NameError:
472
            raise ItemNotFound('Object does not exist')
473
        except IndexError:
474
            raise ItemNotFound('Version does not exist')
475
    else:
476
        try:
477
            s, h = backend.get_object_hashmap(request.user, v_account, v_container, v_object, version)
478
            sizes.append(s)
479
            hashmaps.append(h)
480
        except NameError:
481
            raise ItemNotFound('Object does not exist')
482
        except IndexError:
483
            raise ItemNotFound('Version does not exist')
484
    
485
    # Reply with the hashmap.
486
    if request.serialization != 'text':
487
        size = sum(sizes)
488
        hashmap = sum(hashmaps, [])
489
        d = {'block_size': backend.block_size, 'block_hash': backend.hash_algorithm, 'bytes': size, 'hashes': hashmap}
490
        if request.serialization == 'xml':
491
            d['object'] = v_object
492
            data = render_to_string('hashes.xml', d)
493
        elif request.serialization  == 'json':
494
            data = json.dumps(d)
495
        
496
        response = HttpResponse(data, status=200)
497
        put_object_meta(response, meta)
498
        response['Content-Length'] = len(data)
499
        return response
500
    
501
    return object_data_response(request, sizes, hashmaps, meta)
502

    
503
@api_method('PUT')
504
def object_write(request, v_account, v_container, v_object):
505
    # Normal Response Codes: 201
506
    # Error Response Codes: serviceUnavailable (503),
507
    #                       unprocessableEntity (422),
508
    #                       lengthRequired (411),
509
    #                       conflict (409),
510
    #                       itemNotFound (404),
511
    #                       unauthorized (401),
512
    #                       badRequest (400)
513
    
514
    copy_from = request.META.get('HTTP_X_COPY_FROM')
515
    move_from = request.META.get('HTTP_X_MOVE_FROM')
516
    if copy_from or move_from:
517
        # TODO: Why is this required? Copy this ammount?
518
        content_length = get_content_length(request)
519
        
520
        if move_from:
521
            try:
522
                src_container, src_name = split_container_object_string(move_from)
523
            except ValueError:
524
                raise BadRequest('Invalid X-Move-From header')
525
            copy_or_move_object(request, v_account, src_container, src_name, v_container, v_object, move=True)
526
        else:
527
            try:
528
                src_container, src_name = split_container_object_string(copy_from)
529
            except ValueError:
530
                raise BadRequest('Invalid X-Copy-From header')
531
            copy_or_move_object(request, v_account, src_container, src_name, v_container, v_object, move=False)
532
        return HttpResponse(status=201)
533
    
534
    meta = get_object_meta(request)
535
    permissions = get_sharing(request)
536
    content_length = -1
537
    if request.META.get('HTTP_TRANSFER_ENCODING') != 'chunked':
538
        content_length = get_content_length(request)
539
    # Should be BadRequest, but API says otherwise.
540
    if 'Content-Type' not in meta:
541
        raise LengthRequired('Missing Content-Type header')
542
    
543
    md5 = hashlib.md5()
544
    size = 0
545
    hashmap = []
546
    sock = raw_input_socket(request)
547
    for data in socket_read_iterator(sock, content_length, backend.block_size):
548
        # TODO: Raise 408 (Request Timeout) if this takes too long.
549
        # TODO: Raise 499 (Client Disconnect) if a length is defined and we stop before getting this much data.
550
        size += len(data)
551
        hashmap.append(backend.put_block(data))
552
        md5.update(data)
553
    
554
    meta['hash'] = md5.hexdigest().lower()
555
    etag = request.META.get('HTTP_ETAG')
556
    if etag and parse_etags(etag)[0].lower() != meta['hash']:
557
        raise UnprocessableEntity('Object ETag does not match')
558
    
559
    try:
560
        backend.update_object_hashmap(request.user, v_account, v_container, v_object, size, hashmap, meta, True, permissions)
561
    except NameError:
562
        raise ItemNotFound('Container does not exist')
563
    except ValueError:
564
        raise BadRequest('Invalid sharing header')
565
    except AttributeError:
566
        raise Conflict('Sharing already set above or below this path in the hierarchy')
567
    
568
    response = HttpResponse(status=201)
569
    response['ETag'] = meta['hash']
570
    return response
571

    
572
@api_method('COPY')
573
def object_copy(request, v_account, v_container, v_object):
574
    # Normal Response Codes: 201
575
    # Error Response Codes: serviceUnavailable (503),
576
    #                       itemNotFound (404),
577
    #                       unauthorized (401),
578
    #                       badRequest (400)
579
    
580
    dest_path = request.META.get('HTTP_DESTINATION')
581
    if not dest_path:
582
        raise BadRequest('Missing Destination header')
583
    try:
584
        dest_container, dest_name = split_container_object_string(dest_path)
585
    except ValueError:
586
        raise BadRequest('Invalid Destination header')
587
    copy_or_move_object(request, v_account, v_container, v_object, dest_container, dest_name, move=False)
588
    return HttpResponse(status=201)
589

    
590
@api_method('MOVE')
591
def object_move(request, v_account, v_container, v_object):
592
    # Normal Response Codes: 201
593
    # Error Response Codes: serviceUnavailable (503),
594
    #                       itemNotFound (404),
595
    #                       unauthorized (401),
596
    #                       badRequest (400)
597
    
598
    dest_path = request.META.get('HTTP_DESTINATION')
599
    if not dest_path:
600
        raise BadRequest('Missing Destination header')
601
    try:
602
        dest_container, dest_name = split_container_object_string(dest_path)
603
    except ValueError:
604
        raise BadRequest('Invalid Destination header')
605
    copy_or_move_object(request, v_account, v_container, v_object, dest_container, dest_name, move=True)
606
    return HttpResponse(status=201)
607

    
608
@api_method('POST')
609
def object_update(request, v_account, v_container, v_object):
610
    # Normal Response Codes: 202, 204
611
    # Error Response Codes: serviceUnavailable (503),
612
    #                       conflict (409),
613
    #                       itemNotFound (404),
614
    #                       unauthorized (401),
615
    #                       badRequest (400)
616
    
617
    meta = get_object_meta(request)
618
    permissions = get_sharing(request)
619
    content_type = meta.get('Content-Type')
620
    if content_type:
621
        del(meta['Content-Type']) # Do not allow changing the Content-Type.
622
    
623
    try:
624
        prev_meta = backend.get_object_meta(request.user, v_account, v_container, v_object)
625
    except NameError:
626
        raise ItemNotFound('Object does not exist')
627
    # If replacing, keep previous values of 'Content-Type' and 'hash'.
628
    replace = True
629
    if 'update' in request.GET:
630
        replace = False
631
    if replace:
632
        for k in ('Content-Type', 'hash'):
633
            if k in prev_meta:
634
                meta[k] = prev_meta[k]
635
    
636
    # A Content-Type header indicates data updates.
637
    if not content_type or content_type != 'application/octet-stream':
638
        # Handle metadata changes.
639
        try:
640
            backend.update_object_meta(request.user, v_account, v_container, v_object, meta, replace)
641
        except NameError:
642
            raise ItemNotFound('Object does not exist')    
643
        # Handle permission changes.
644
        if permissions:
645
            try:
646
                backend.update_object_permissions(request.user, v_account, v_container, v_object, permissions)
647
            except NameError:
648
                raise ItemNotFound('Object does not exist')
649
            except ValueError:
650
                raise BadRequest('Invalid sharing header')
651
            except AttributeError:
652
                raise Conflict('Sharing already set above or below this path in the hierarchy')
653
        return HttpResponse(status=202)
654
    
655
    # Single range update. Range must be in Content-Range.
656
    # Based on: http://code.google.com/p/gears/wiki/ContentRangePostProposal
657
    # (with the addition that '*' is allowed for the range - will append).
658
    content_range = request.META.get('HTTP_CONTENT_RANGE')
659
    if not content_range:
660
        raise BadRequest('Missing Content-Range header')
661
    ranges = get_content_range(request)
662
    if not ranges:
663
        raise RangeNotSatisfiable('Invalid Content-Range header')
664
    # Require either a Content-Length, or 'chunked' Transfer-Encoding.
665
    content_length = -1
666
    if request.META.get('HTTP_TRANSFER_ENCODING') != 'chunked':
667
        content_length = get_content_length(request)
668
    
669
    try:
670
        size, hashmap = backend.get_object_hashmap(request.user, v_account, v_container, v_object)
671
    except NameError:
672
        raise ItemNotFound('Object does not exist')
673
    
674
    offset, length, total = ranges
675
    if offset is None:
676
        offset = size
677
    elif offset > size:
678
        raise RangeNotSatisfiable('Supplied offset is beyond object limits')
679
    if length is None or content_length == -1:
680
        length = content_length # Nevermind the error.
681
    elif length != content_length:
682
        raise BadRequest('Content length does not match range length')
683
    if total is not None and (total != size or offset >= size or (length > 0 and offset + length >= size)):
684
        raise RangeNotSatisfiable('Supplied range will change provided object limits')
685
    
686
    sock = raw_input_socket(request)
687
    data = ''
688
    for d in socket_read_iterator(sock, length, backend.block_size):
689
        # TODO: Raise 408 (Request Timeout) if this takes too long.
690
        # TODO: Raise 499 (Client Disconnect) if a length is defined and we stop before getting this much data.
691
        data += d
692
        bytes = put_object_block(hashmap, data, offset)
693
        offset += bytes
694
        data = data[bytes:]
695
    if len(data) > 0:
696
        put_object_block(hashmap, data, offset)
697
    
698
    if offset > size:
699
        size = offset
700
    meta.update({'hash': hashmap_hash(hashmap)}) # Update ETag.
701
    try:
702
        backend.update_object_hashmap(request.user, v_account, v_container, v_object, size, hashmap, meta, replace, permissions)
703
    except NameError:
704
        raise ItemNotFound('Container does not exist')
705
    except ValueError:
706
        raise BadRequest('Invalid sharing header')
707
    except AttributeError:
708
        raise Conflict('Sharing already set above or below this path in the hierarchy')
709
    
710
    response = HttpResponse(status=204)
711
    response['ETag'] = meta['hash']
712
    return response
713

    
714
@api_method('DELETE')
715
def object_delete(request, v_account, v_container, v_object):
716
    # Normal Response Codes: 204
717
    # Error Response Codes: serviceUnavailable (503),
718
    #                       itemNotFound (404),
719
    #                       unauthorized (401),
720
    #                       badRequest (400)
721
    
722
    try:
723
        backend.delete_object(request.user, v_account, v_container, v_object)
724
    except NameError:
725
        raise ItemNotFound('Object does not exist')
726
    return HttpResponse(status=204)
727

    
728
@api_method()
729
def method_not_allowed(request):
730
    raise BadRequest('Method not allowed')