-
-
Notifications
You must be signed in to change notification settings - Fork 907
/
S3.py
2329 lines (2033 loc) · 102 KB
/
S3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
## --------------------------------------------------------------------
## Amazon S3 manager
##
## Authors : Michal Ludvig <michal@logix.cz> (https://www.logix.cz/michal)
## Florent Viard <florent@sodria.com> (https://www.sodria.com)
## Copyright : TGRMN Software, Sodria SAS and contributors
## License : GPL Version 2
## Website : https://s3tools.org
## --------------------------------------------------------------------
from __future__ import absolute_import, division
import sys
import os
import time
import errno
import mimetypes
import io
import pprint
from xml.sax import saxutils
from socket import timeout as SocketTimeoutException
from logging import debug, info, warning, error
from stat import ST_SIZE, ST_MODE, S_ISDIR, S_ISREG
try:
# python 3 support
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import select
from .BaseUtils import (getListFromXml, getTextFromXml, getRootTagName,
decode_from_s3, encode_to_s3, md5, s3_quote)
from .Utils import (convertHeaderTupleListToDict, unicodise,
deunicodise, check_bucket_name,
check_bucket_name_dns_support, getHostnameFromBucket)
from .SortedDict import SortedDict
from .AccessLog import AccessLog
from .ACL import ACL, GranteeLogDelivery
from .BidirMap import BidirMap
from .Config import Config
from .Exceptions import *
from .MultiPart import MultiPartUpload
from .S3Uri import S3Uri
from .ConnMan import ConnMan
from .Crypto import (sign_request_v2, sign_request_v4, checksum_sha256_file,
checksum_sha256_buffer, generate_content_md5,
hash_file_md5, calculateChecksum, format_param_str)
try:
from ctypes import ArgumentError
import magic
try:
## https://github.com/ahupp/python-magic
## Always expect unicode for python 2
## (has Magic class but no "open()" function)
magic_ = magic.Magic(mime=True)
def mime_magic_file(file):
return magic_.from_file(file)
except TypeError:
try:
## file-5.11 built-in python bindings
## Sources: http://www.darwinsys.com/file/
## Expects unicode since version 5.19, encoded strings before
## we can't tell if a given copy of the magic library will take a
## filesystem-encoded string or a unicode value, so try first
## with the unicode, then with the encoded string.
## (has Magic class and "open()" function)
magic_ = magic.open(magic.MAGIC_MIME)
magic_.load()
def mime_magic_file(file):
try:
return magic_.file(file)
except (UnicodeDecodeError, UnicodeEncodeError, ArgumentError):
return magic_.file(deunicodise(file))
except AttributeError:
## http://pypi.python.org/pypi/filemagic
## Accept gracefully both unicode and encoded
## (has Magic class but not "mime" argument and no "open()" function )
magic_ = magic.Magic(flags=magic.MAGIC_MIME)
def mime_magic_file(file):
return magic_.id_filename(file)
except AttributeError:
## Older python-magic versions doesn't have a "Magic" method
## Only except encoded strings
## (has no Magic class but "open()" function)
magic_ = magic.open(magic.MAGIC_MIME)
magic_.load()
def mime_magic_file(file):
return magic_.file(deunicodise(file))
except (ImportError, OSError) as e:
error_str = str(e)
if 'magic' in error_str:
magic_message = "Module python-magic is not available."
else:
magic_message = "Module python-magic can't be used (%s)." % error_str
magic_message += " Guessing MIME types based on file extensions."
magic_warned = False
def mime_magic_file(file):
global magic_warned
if (not magic_warned):
warning(magic_message)
magic_warned = True
return mimetypes.guess_type(file)[0]
def mime_magic(file):
## NOTE: So far in the code, "file" var is already unicode
def _mime_magic(file):
magictype = mime_magic_file(file)
return magictype
result = _mime_magic(file)
if result is not None:
if isinstance(result, str):
if ';' in result:
mimetype, charset = result.split(';')
charset = charset[len('charset'):]
result = (mimetype, charset)
else:
result = (result, None)
if result is None:
result = (None, None)
return result
EXPECT_CONTINUE_TIMEOUT = 2
SIZE_1MB = 1024 * 1024
__all__ = []
class S3Request(object):
region_map = {}
## S3 sometimes sends HTTP-301, HTTP-307 response
redir_map = {}
def __init__(self, s3, method_string, resource, headers, body, params = None):
self.s3 = s3
self.headers = SortedDict(headers or {}, ignore_case = True)
if len(self.s3.config.access_token)>0:
self.s3.config.role_refresh()
self.headers['x-amz-security-token']=self.s3.config.access_token
self.resource = resource
self.method_string = method_string
self.params = params or {}
self.body = body
self.requester_pays()
def requester_pays(self):
if self.s3.config.requester_pays and self.method_string in ("GET", "POST", "PUT", "HEAD"):
self.headers['x-amz-request-payer'] = 'requester'
def update_timestamp(self):
if "date" in self.headers:
del(self.headers["date"])
self.headers["x-amz-date"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
def use_signature_v2(self):
if self.s3.endpoint_requires_signature_v4:
return False
if self.s3.config.signature_v2 or self.s3.fallback_to_signature_v2:
return True
return False
def sign(self):
bucket_name = self.resource.get('bucket')
if self.use_signature_v2():
debug("Using signature v2")
if bucket_name:
resource_uri = "/%s%s" % (bucket_name, self.resource['uri'])
else:
resource_uri = self.resource['uri']
self.headers = sign_request_v2(self.method_string, resource_uri, self.params, self.headers)
else:
debug("Using signature v4")
hostname = self.s3.get_hostname(self.resource['bucket'])
## Default to bucket part of DNS.
## If bucket is not part of DNS assume path style to complete the request.
## Like for format_uri, take care that redirection could be to base path
if bucket_name and (
(bucket_name in S3Request.redir_map
and not S3Request.redir_map.get(bucket_name, '').startswith("%s."% bucket_name))
or (bucket_name not in S3Request.redir_map
and not check_bucket_name_dns_support(Config().host_bucket, bucket_name))
):
resource_uri = "/%s%s" % (bucket_name, self.resource['uri'])
else:
resource_uri = self.resource['uri']
bucket_region = S3Request.region_map.get(self.resource['bucket'], Config().bucket_location)
## Sign the data.
self.headers = sign_request_v4(self.method_string, hostname, resource_uri, self.params,
bucket_region, self.headers, self.body)
def get_triplet(self):
self.update_timestamp()
self.sign()
resource = dict(self.resource) ## take a copy
# URL Encode the uri for the http request
resource['uri'] = s3_quote(resource['uri'], quote_backslashes=False, unicode_output=True)
# Get the final uri by adding the uri parameters
resource['uri'] += format_param_str(self.params)
return (self.method_string, resource, self.headers)
class S3(object):
http_methods = BidirMap(
GET = 0x01,
PUT = 0x02,
HEAD = 0x04,
DELETE = 0x08,
POST = 0x10,
MASK = 0x1F,
)
targets = BidirMap(
SERVICE = 0x0100,
BUCKET = 0x0200,
OBJECT = 0x0400,
BATCH = 0x0800,
MASK = 0x0700,
)
operations = BidirMap(
UNDEFINED = 0x0000,
LIST_ALL_BUCKETS = targets["SERVICE"] | http_methods["GET"],
BUCKET_CREATE = targets["BUCKET"] | http_methods["PUT"],
BUCKET_LIST = targets["BUCKET"] | http_methods["GET"],
BUCKET_DELETE = targets["BUCKET"] | http_methods["DELETE"],
OBJECT_PUT = targets["OBJECT"] | http_methods["PUT"],
OBJECT_GET = targets["OBJECT"] | http_methods["GET"],
OBJECT_HEAD = targets["OBJECT"] | http_methods["HEAD"],
OBJECT_DELETE = targets["OBJECT"] | http_methods["DELETE"],
OBJECT_POST = targets["OBJECT"] | http_methods["POST"],
BATCH_DELETE = targets["BATCH"] | http_methods["POST"],
)
codes = {
"NoSuchBucket" : "Bucket '%s' does not exist",
"AccessDenied" : "Access to bucket '%s' was denied",
"BucketAlreadyExists" : "Bucket '%s' already exists",
}
def __init__(self, config):
self.config = config
self.fallback_to_signature_v2 = False
self.endpoint_requires_signature_v4 = False
self.expect_continue_not_supported = False
def storage_class(self):
# Note - you cannot specify GLACIER here
# https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html
cls = 'STANDARD'
if self.config.storage_class != "":
return self.config.storage_class
if self.config.reduced_redundancy:
cls = 'REDUCED_REDUNDANCY'
return cls
def get_hostname(self, bucket):
if bucket and bucket in S3Request.redir_map:
host = S3Request.redir_map[bucket]
elif bucket and check_bucket_name_dns_support(self.config.host_bucket, bucket):
host = getHostnameFromBucket(bucket)
else:
host = self.config.host_base.lower()
# The following hack is needed because it looks like that some servers
# are not respecting the HTTP spec and so will fail the signature check
# if the port is specified in the "Host" header for default ports.
# STUPIDIEST THING EVER FOR A SERVER...
# See: https://github.com/minio/minio/issues/9169
if self.config.use_https:
if host.endswith(':443'):
host = host[:-4]
elif host.endswith(':80'):
host = host[:-3]
debug('get_hostname(%s): %s' % (bucket, host))
return host
def set_hostname(self, bucket, redir_hostname):
S3Request.redir_map[bucket] = redir_hostname.lower()
def format_uri(self, resource, base_path=None):
bucket_name = resource.get('bucket')
if bucket_name and (
(bucket_name in S3Request.redir_map
and not S3Request.redir_map.get(bucket_name, '').startswith("%s."% bucket_name))
or (bucket_name not in S3Request.redir_map
and not check_bucket_name_dns_support(self.config.host_bucket, bucket_name))
):
uri = "/%s%s" % (s3_quote(bucket_name, quote_backslashes=False,
unicode_output=True),
resource['uri'])
else:
uri = resource['uri']
if base_path:
uri = "%s%s" % (base_path, uri)
if self.config.proxy_host != "" and not self.config.use_https:
uri = "http://%s%s" % (self.get_hostname(bucket_name), uri)
debug('format_uri(): ' + uri)
return uri
## Commands / Actions
def list_all_buckets(self):
request = self.create_request("LIST_ALL_BUCKETS")
response = self.send_request(request)
response["list"] = getListFromXml(response["data"], "Bucket")
return response
def bucket_list(self, bucket, prefix = None, recursive = None, uri_params = None, limit = -1):
item_list = []
prefixes = []
for truncated, dirs, objects in self.bucket_list_streaming(bucket, prefix, recursive, uri_params, limit):
item_list.extend(objects)
prefixes.extend(dirs)
response = {}
response['list'] = item_list
response['common_prefixes'] = prefixes
response['truncated'] = truncated
return response
def bucket_list_streaming(self, bucket, prefix = None, recursive = None, uri_params = None, limit = -1):
""" Generator that produces <dir_list>, <object_list> pairs of groups of content of a specified bucket. """
def _list_truncated(data):
## <IsTruncated> can either be "true" or "false" or be missing completely
is_truncated = getTextFromXml(data, ".//IsTruncated") or "false"
return is_truncated.lower() != "false"
def _get_contents(data):
return getListFromXml(data, "Contents")
def _get_common_prefixes(data):
return getListFromXml(data, "CommonPrefixes")
def _get_next_marker(data, current_elts, key):
return getTextFromXml(response["data"], "NextMarker") or current_elts[-1][key]
uri_params = uri_params and uri_params.copy() or {}
truncated = True
prefixes = []
num_objects = 0
num_prefixes = 0
max_keys = limit
while truncated:
response = self.bucket_list_noparse(bucket, prefix, recursive,
uri_params, max_keys)
current_list = _get_contents(response["data"])
current_prefixes = _get_common_prefixes(response["data"])
num_objects += len(current_list)
num_prefixes += len(current_prefixes)
if limit > num_objects + num_prefixes:
max_keys = limit - (num_objects + num_prefixes)
truncated = _list_truncated(response["data"])
if truncated:
if limit == -1 or num_objects + num_prefixes < limit:
if current_list:
uri_params['marker'] = \
_get_next_marker(response["data"], current_list, "Key")
elif current_prefixes:
uri_params['marker'] = \
_get_next_marker(response["data"], current_prefixes, "Prefix")
else:
# Unexpectedly, the server lied, and so the previous
# response was not truncated. So, no new key to get.
yield False, current_prefixes, current_list
break
debug("Listing continues after '%s'" % uri_params['marker'])
else:
yield truncated, current_prefixes, current_list
break
yield truncated, current_prefixes, current_list
def bucket_list_noparse(self, bucket, prefix = None, recursive = None, uri_params = None, max_keys = -1):
if uri_params is None:
uri_params = {}
if prefix:
uri_params['prefix'] = prefix
if not self.config.recursive and not recursive:
uri_params['delimiter'] = "/"
if max_keys != -1:
uri_params['max-keys'] = str(max_keys)
if self.config.list_allow_unordered:
uri_params['allow-unordered'] = "true"
request = self.create_request("BUCKET_LIST", bucket = bucket, uri_params = uri_params)
response = self.send_request(request)
#debug(response)
return response
def bucket_create(self, bucket, bucket_location = None, extra_headers = None):
headers = SortedDict(ignore_case = True)
if extra_headers:
headers.update(extra_headers)
body = ""
if bucket_location and bucket_location.strip().upper() != "US" and bucket_location.strip().lower() != "us-east-1":
bucket_location = bucket_location.strip()
if bucket_location.upper() == "EU":
bucket_location = bucket_location.upper()
body = "<CreateBucketConfiguration><LocationConstraint>"
body += bucket_location
body += "</LocationConstraint></CreateBucketConfiguration>"
debug("bucket_location: " + body)
check_bucket_name(bucket, dns_strict = True)
else:
check_bucket_name(bucket, dns_strict = False)
if self.config.acl_public:
headers["x-amz-acl"] = "public-read"
# AWS suddenly changed the default "ownership" control value mid 2023.
# ACL are disabled by default, so obviously the bucket can't be public.
# See: https://aws.amazon.com/fr/blogs/aws/heads-up-amazon-s3-security-changes-are-coming-in-april-of-2023/
# To be noted: "Block Public Access" flags should also be disabled after the bucket creation to be able to set a "public" acl for an object.
headers["x-amz-object-ownership"] = 'ObjectWriter'
request = self.create_request("BUCKET_CREATE", bucket = bucket, headers = headers, body = body)
response = self.send_request(request)
return response
def bucket_delete(self, bucket):
request = self.create_request("BUCKET_DELETE", bucket = bucket)
response = self.send_request(request)
return response
def get_bucket_location(self, uri, force_us_default=False):
bucket = uri.bucket()
request = self.create_request("BUCKET_LIST", bucket = uri.bucket(),
uri_params = {'location': None})
saved_redir_map = S3Request.redir_map.get(bucket, '')
saved_region_map = S3Request.region_map.get(bucket, '')
try:
if force_us_default and not (saved_redir_map and saved_region_map):
S3Request.redir_map[bucket] = self.config.host_base
S3Request.region_map[bucket] = 'us-east-1'
response = self.send_request(request)
finally:
if bucket in saved_redir_map:
S3Request.redir_map[bucket] = saved_redir_map
elif bucket in S3Request.redir_map:
del S3Request.redir_map[bucket]
if bucket in saved_region_map:
S3Request.region_map[bucket] = saved_region_map
elif bucket in S3Request.region_map:
del S3Request.region_map[bucket]
location = getTextFromXml(response['data'], "LocationConstraint")
if not location or location in [ "", "US" ]:
location = "us-east-1"
elif location == "EU":
location = "eu-west-1"
return location
def get_bucket_requester_pays(self, uri):
request = self.create_request("BUCKET_LIST", bucket=uri.bucket(),
uri_params={'requestPayment': None})
response = self.send_request(request)
resp_data = response.get('data', '')
if resp_data:
payer = getTextFromXml(resp_data, "Payer")
else:
payer = None
return payer
def set_bucket_ownership(self, uri, ownership):
headers = SortedDict(ignore_case=True)
body = '<OwnershipControls xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' \
'<Rule>' \
'<ObjectOwnership>%s</ObjectOwnership>' \
'</Rule>' \
'</OwnershipControls>'
body = body % ownership
debug(u"set_bucket_ownership(%s)" % body)
headers['content-md5'] = generate_content_md5(body)
request = self.create_request("BUCKET_CREATE", uri = uri,
headers = headers, body = body,
uri_params = {'ownershipControls': None})
response = self.send_request(request)
return response
def get_bucket_ownership(self, uri):
request = self.create_request("BUCKET_LIST", bucket=uri.bucket(),
uri_params={'ownershipControls': None})
response = self.send_request(request)
resp_data = response.get('data', '')
if resp_data:
ownership = getTextFromXml(resp_data, ".//Rule//ObjectOwnership")
else:
ownership = None
return ownership
def set_bucket_public_access_block(self, uri, flags):
headers = SortedDict(ignore_case=True)
body = '<PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
for tag in ('BlockPublicAcls', 'IgnorePublicAcls', 'BlockPublicPolicy', 'RestrictPublicBuckets'):
val = flags.get(tag, False) and "true" or "false"
body += '<%s>%s</%s>' % (tag, val, tag)
body += '</PublicAccessBlockConfiguration>'
debug(u"set_bucket_public_access_block(%s)" % body)
headers['content-md5'] = generate_content_md5(body)
request = self.create_request("BUCKET_CREATE", uri = uri,
headers = headers, body = body,
uri_params = {'publicAccessBlock': None})
response = self.send_request(request)
return response
def get_bucket_public_access_block(self, uri):
request = self.create_request("BUCKET_LIST", bucket=uri.bucket(),
uri_params={'publicAccessBlock': None})
response = self.send_request(request)
resp_data = response.get('data', '')
if resp_data:
flags = {
"BlockPublicAcls": getTextFromXml(resp_data, "BlockPublicAcls") == "true",
"IgnorePublicAcls": getTextFromXml(resp_data, "IgnorePublicAcls") == "true",
"BlockPublicPolicy": getTextFromXml(resp_data, "BlockPublicPolicy") == "true",
"RestrictPublicBuckets": getTextFromXml(resp_data, "RestrictPublicBuckets") == "true",
}
else:
flags = {}
return flags
def bucket_info(self, uri):
response = {}
response['bucket-location'] = self.get_bucket_location(uri)
for key, func in (('requester-pays', self.get_bucket_requester_pays),
('versioning', self.get_versioning),
('ownership', self.get_bucket_ownership)):
try:
response[key] = func(uri)
except S3Error as e:
response[key] = None
try:
response['public-access-block'] = self.get_bucket_public_access_block(uri)
except S3Error as e:
response['public-access-block'] = {}
return response
def website_info(self, uri, bucket_location = None):
bucket = uri.bucket()
request = self.create_request("BUCKET_LIST", bucket = bucket,
uri_params = {'website': None})
try:
response = self.send_request(request)
response['index_document'] = getTextFromXml(response['data'], ".//IndexDocument//Suffix")
response['error_document'] = getTextFromXml(response['data'], ".//ErrorDocument//Key")
response['website_endpoint'] = self.config.website_endpoint % {
"bucket" : uri.bucket(),
"location" : self.get_bucket_location(uri)}
return response
except S3Error as e:
if e.status == 404:
debug("Could not get /?website - website probably not configured for this bucket")
return None
raise
def website_create(self, uri, bucket_location = None):
bucket = uri.bucket()
body = '<WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
body += ' <IndexDocument>'
body += (' <Suffix>%s</Suffix>' % self.config.website_index)
body += ' </IndexDocument>'
if self.config.website_error:
body += ' <ErrorDocument>'
body += (' <Key>%s</Key>' % self.config.website_error)
body += ' </ErrorDocument>'
body += '</WebsiteConfiguration>'
request = self.create_request("BUCKET_CREATE", bucket = bucket, body = body,
uri_params = {'website': None})
response = self.send_request(request)
debug("Received response '%s'" % (response))
return response
def website_delete(self, uri, bucket_location = None):
bucket = uri.bucket()
request = self.create_request("BUCKET_DELETE", bucket = bucket,
uri_params = {'website': None})
response = self.send_request(request)
debug("Received response '%s'" % (response))
if response['status'] != 204:
raise S3ResponseError("Expected status 204: %s" % response)
return response
def expiration_info(self, uri, bucket_location = None):
bucket = uri.bucket()
request = self.create_request("BUCKET_LIST", bucket=bucket,
uri_params={'lifecycle': None})
try:
response = self.send_request(request)
except S3Error as e:
if e.status == 404:
debug("Could not get /?lifecycle - lifecycle probably not "
"configured for this bucket")
return None
elif e.status == 501:
debug("Could not get /?lifecycle - lifecycle support not "
"implemented by the server")
return None
raise
root_tag_name = getRootTagName(response['data'])
if root_tag_name != "LifecycleConfiguration":
debug("Could not get /?lifecycle - unexpected xml response: "
"%s", root_tag_name)
return None
response['prefix'] = getTextFromXml(response['data'],
".//Rule//Prefix")
response['date'] = getTextFromXml(response['data'],
".//Rule//Expiration//Date")
response['days'] = getTextFromXml(response['data'],
".//Rule//Expiration//Days")
return response
def expiration_set(self, uri, bucket_location = None):
if self.config.expiry_date and self.config.expiry_days:
raise ParameterError("Expect either --expiry-day or --expiry-date")
if not (self.config.expiry_date or self.config.expiry_days):
if self.config.expiry_prefix:
raise ParameterError("Expect either --expiry-day or --expiry-date")
debug("del bucket lifecycle")
bucket = uri.bucket()
request = self.create_request("BUCKET_DELETE", bucket = bucket,
uri_params = {'lifecycle': None})
else:
request = self._expiration_set(uri)
response = self.send_request(request)
debug("Received response '%s'" % (response))
return response
def _expiration_set(self, uri):
debug("put bucket lifecycle")
body = '<LifecycleConfiguration>'
body += ' <Rule>'
body += ' <Filter>'
body += ' <Prefix>%s</Prefix>' % self.config.expiry_prefix
body += ' </Filter>'
body += ' <Status>Enabled</Status>'
body += ' <Expiration>'
if self.config.expiry_date:
body += ' <Date>%s</Date>' % self.config.expiry_date
elif self.config.expiry_days:
body += ' <Days>%s</Days>' % self.config.expiry_days
body += ' </Expiration>'
body += ' </Rule>'
body += '</LifecycleConfiguration>'
headers = SortedDict(ignore_case = True)
headers['content-md5'] = generate_content_md5(body)
bucket = uri.bucket()
request = self.create_request("BUCKET_CREATE", bucket = bucket,
headers = headers, body = body,
uri_params = {'lifecycle': None})
return (request)
def _guess_content_type(self, filename):
content_type = self.config.default_mime_type
content_charset = None
if filename == "-" and not self.config.default_mime_type:
raise ParameterError("You must specify --mime-type or --default-mime-type for files uploaded from stdin.")
if self.config.guess_mime_type:
if self.config.follow_symlinks:
filename = unicodise(os.path.realpath(deunicodise(filename)))
if self.config.use_mime_magic:
(content_type, content_charset) = mime_magic(filename)
else:
(content_type, content_charset) = mimetypes.guess_type(filename)
if not content_type:
content_type = self.config.default_mime_type
return (content_type, content_charset)
def stdin_content_type(self):
content_type = self.config.mime_type
if not content_type:
content_type = self.config.default_mime_type
content_type += "; charset=" + self.config.encoding.upper()
return content_type
def content_type(self, filename=None, is_dir=False):
# explicit command line argument always wins
content_type = self.config.mime_type
content_charset = None
if filename == u'-':
return self.stdin_content_type()
if is_dir:
content_type = 'application/x-directory'
elif not content_type:
(content_type, content_charset) = self._guess_content_type(filename)
## add charset to content type
if not content_charset:
content_charset = self.config.encoding.upper()
if self.add_encoding(filename, content_type) and content_charset is not None:
content_type = content_type + "; charset=" + content_charset
return content_type
def add_encoding(self, filename, content_type):
if 'charset=' in content_type:
return False
exts = self.config.add_encoding_exts.split(',')
if exts[0]=='':
return False
parts = filename.rsplit('.',2)
if len(parts) < 2:
return False
ext = parts[1]
if ext in exts:
return True
else:
return False
def object_put(self, filename, uri, extra_headers = None, extra_label = ""):
# TODO TODO
# Make it consistent with stream-oriented object_get()
if uri.type != "s3":
raise ValueError("Expected URI type 's3', got '%s'" % uri.type)
try:
is_dir = False
size = 0
if filename == "-":
is_stream = True
src_stream = io.open(sys.stdin.fileno(), mode='rb', closefd=False)
src_stream.stream_name = u'<stdin>'
else:
is_stream = False
filename_bytes = deunicodise(filename)
stat = os.stat(filename_bytes)
mode = stat[ST_MODE]
if S_ISDIR(mode):
is_dir = True
# Dirs are represented as empty objects on S3
src_stream = io.BytesIO(b'')
elif not S_ISREG(mode):
raise InvalidFileError(u"Not a regular file")
else:
# Standard normal file
src_stream = io.open(filename_bytes, mode='rb')
size = stat[ST_SIZE]
src_stream.stream_name = filename
except (IOError, OSError) as e:
raise InvalidFileError(u"%s" % e.strerror)
headers = SortedDict(ignore_case=True)
if extra_headers:
headers.update(extra_headers)
## Set server side encryption
if self.config.server_side_encryption:
headers["x-amz-server-side-encryption"] = "AES256"
## Set kms headers
if self.config.kms_key:
headers['x-amz-server-side-encryption'] = 'aws:kms'
headers['x-amz-server-side-encryption-aws-kms-key-id'] = self.config.kms_key
## MIME-type handling
headers["content-type"] = self.content_type(filename=filename, is_dir=is_dir)
## Other Amazon S3 attributes
if self.config.acl_public:
headers["x-amz-acl"] = "public-read"
headers["x-amz-storage-class"] = self.storage_class()
## Multipart decision
multipart = False
if not self.config.enable_multipart and is_stream:
raise ParameterError("Multi-part upload is required to upload from stdin")
if self.config.enable_multipart:
if size > self.config.multipart_chunk_size_mb * SIZE_1MB or is_stream:
multipart = True
if size > self.config.multipart_max_chunks * self.config.multipart_chunk_size_mb * SIZE_1MB:
raise ParameterError("Chunk size %d MB results in more than %d chunks. Please increase --multipart-chunk-size-mb" % \
(self.config.multipart_chunk_size_mb, self.config.multipart_max_chunks))
if multipart:
# Multipart requests are quite different... drop here
return self.send_file_multipart(src_stream, headers, uri, size, extra_label)
## Not multipart...
if self.config.put_continue:
# Note, if input was stdin, we would be performing multipart upload.
# So this will always work as long as the file already uploaded was
# not uploaded via MultiUpload, in which case its ETag will not be
# an md5.
try:
info = self.object_info(uri)
except Exception:
info = None
if info is not None:
remote_size = int(info['headers']['content-length'])
remote_checksum = info['headers']['etag'].strip('"\'')
if size == remote_size:
checksum = calculateChecksum('', src_stream, 0, size, self.config.send_chunk)
if remote_checksum == checksum:
warning("Put: size and md5sum match for %s, skipping." % uri)
return
else:
warning("MultiPart: checksum (%s vs %s) does not match for %s, reuploading."
% (remote_checksum, checksum, uri))
else:
warning("MultiPart: size (%d vs %d) does not match for %s, reuploading."
% (remote_size, size, uri))
headers["content-length"] = str(size)
request = self.create_request("OBJECT_PUT", uri = uri, headers = headers)
labels = { 'source' : filename, 'destination' : uri.uri(), 'extra' : extra_label }
response = self.send_file(request, src_stream, labels)
return response
def object_get(self, uri, stream, dest_name, start_position = 0, extra_label = ""):
if uri.type != "s3":
raise ValueError("Expected URI type 's3', got '%s'" % uri.type)
request = self.create_request("OBJECT_GET", uri = uri)
labels = { 'source' : uri.uri(), 'destination' : dest_name, 'extra' : extra_label }
response = self.recv_file(request, stream, labels, start_position)
return response
def object_batch_delete(self, remote_list):
""" Batch delete given a remote_list """
uris = [remote_list[item]['object_uri_str'] for item in remote_list]
return self.object_batch_delete_uri_strs(uris)
def object_batch_delete_uri_strs(self, uris):
""" Batch delete given a list of object uris """
def compose_batch_del_xml(bucket, key_list):
body = u"<?xml version=\"1.0\" encoding=\"UTF-8\"?><Delete>"
for key in key_list:
uri = S3Uri(key)
if uri.type != "s3":
raise ValueError("Expected URI type 's3', got '%s'" % uri.type)
if not uri.has_object():
raise ValueError("URI '%s' has no object" % key)
if uri.bucket() != bucket:
raise ValueError("The batch should contain keys from the same bucket")
object = saxutils.escape(uri.object())
body += u"<Object><Key>%s</Key></Object>" % object
body += u"</Delete>"
body = encode_to_s3(body)
return body
batch = uris
if len(batch) == 0:
raise ValueError("Key list is empty")
bucket = S3Uri(batch[0]).bucket()
request_body = compose_batch_del_xml(bucket, batch)
headers = SortedDict({'content-md5': generate_content_md5(request_body),
'content-type': 'application/xml'}, ignore_case=True)
request = self.create_request("BATCH_DELETE", bucket = bucket,
headers = headers, body = request_body,
uri_params = {'delete': None})
response = self.send_request(request)
return response
def object_delete(self, uri):
if uri.type != "s3":
raise ValueError("Expected URI type 's3', got '%s'" % uri.type)
request = self.create_request("OBJECT_DELETE", uri = uri)
response = self.send_request(request)
return response
def object_restore(self, uri):
if uri.type != "s3":
raise ValueError("Expected URI type 's3', got '%s'" % uri.type)
if self.config.restore_days < 1:
raise ParameterError("You must restore a file for 1 or more days")
if self.config.restore_priority not in ['Standard', 'Expedited', 'Bulk']:
raise ParameterError("Valid restoration priorities: bulk, standard, expedited")
body = '<RestoreRequest xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
body += (' <Days>%s</Days>' % self.config.restore_days)
body += ' <GlacierJobParameters>'
body += (' <Tier>%s</Tier>' % self.config.restore_priority)
body += ' </GlacierJobParameters>'
body += '</RestoreRequest>'
request = self.create_request("OBJECT_POST", uri = uri, body = body,
uri_params = {'restore': None})
response = self.send_request(request)
debug("Received response '%s'" % (response))
return response
def _sanitize_headers(self, headers):
to_remove = [
# from http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
'date',
'content-length',
'last-modified',
'content-md5',
'x-amz-version-id',
'x-amz-delete-marker',
# other headers returned from object_info() we don't want to send
'accept-ranges',
'connection',
'etag',
'server',
'x-amz-id-2',
'x-amz-request-id',
# Cloudflare's R2 header we don't want to send
'cf-ray',
# Other headers that are not copying by a direct copy
'x-amz-storage-class',
## We should probably also add server-side encryption headers
]
for h in to_remove + self.config.remove_headers:
if h.lower() in headers:
del headers[h.lower()]
return headers
def object_copy(self, src_uri, dst_uri, extra_headers=None,
src_size=None, extra_label="", replace_meta=False):
"""Remote copy an object and eventually set metadata
Note: A little memo description of the nightmare for performance here:
** FOR AWS, 2 cases:
- COPY will copy the metadata of the source to dest, but you can't
modify them. Any additional header will be ignored anyway.
- REPLACE will set the additional metadata headers that are provided
but will not copy any of the source headers.
So, to add to existing meta during copy, you have to do an object_info
to get original source headers, then modify, then use REPLACE for the
copy operation.
** For Minio and maybe other implementations:
- if additional headers are sent, they will be set to the destination
on top of source original meta in all cases COPY and REPLACE.
It is a nice behavior except that it is different of the aws one.
As it was still too easy, there is another catch:
In all cases, for multipart copies, metadata data are never copied
from the source.
"""
if src_uri.type != "s3":
raise ValueError("Expected URI type 's3', got '%s'" % src_uri.type)
if dst_uri.type != "s3":
raise ValueError("Expected URI type 's3', got '%s'" % dst_uri.type)
if self.config.acl_public is None:
try:
acl = self.get_acl(src_uri)
except S3Error as exc:
# Ignore the exception and don't fail the copy
# if the server doesn't support setting ACLs
if exc.status != 501:
raise exc
acl = None
multipart = False
headers = None
if extra_headers or self.config.mime_type:
# Force replace, that will force getting meta with object_info()
replace_meta = True
if replace_meta:
src_info = self.object_info(src_uri)
headers = src_info['headers']
src_size = int(headers["content-length"])
if self.config.enable_multipart:
# Get size of remote source only if multipart is enabled and that no
# size info was provided
src_headers = headers
if src_size is None:
src_info = self.object_info(src_uri)
src_headers = src_info['headers']