Browse code

Merge pull request #1120 from anbnyc/patch-1

Update wiki URL in error message

Florent Viard authored on 2020/07/01 05:25:59
Showing 1 changed files
... ...
@@ -1,3264 +0,0 @@
1
-#!/usr/bin/env python
2
-# -*- coding: utf-8 -*-
3
-
4
-## --------------------------------------------------------------------
5
-## s3cmd - S3 client
6
-##
7
-## Authors   : Michal Ludvig and contributors
8
-## Copyright : TGRMN Software - http://www.tgrmn.com - and contributors
9
-## Website   : http://s3tools.org
10
-## License   : GPL Version 2
11
-## --------------------------------------------------------------------
12
-## This program is free software; you can redistribute it and/or modify
13
-## it under the terms of the GNU General Public License as published by
14
-## the Free Software Foundation; either version 2 of the License, or
15
-## (at your option) any later version.
16
-## This program is distributed in the hope that it will be useful,
17
-## but WITHOUT ANY WARRANTY; without even the implied warranty of
18
-## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
-## GNU General Public License for more details.
20
-## --------------------------------------------------------------------
21
-
22
-from __future__ import absolute_import, print_function, division
23
-
24
-import sys
25
-
26
-if sys.version_info < (2, 6):
27
-    sys.stderr.write(u"ERROR: Python 2.6 or higher required, sorry.\n")
28
-    sys.exit(EX_OSFILE)
29
-
30
-PY3 = (sys.version_info >= (3, 0))
31
-
32
-import codecs
33
-import errno
34
-import glob
35
-import io
36
-import locale
37
-import logging
38
-import os
39
-import re
40
-import shutil
41
-import socket
42
-import subprocess
43
-import tempfile
44
-import time
45
-import traceback
46
-
47
-from copy import copy
48
-from optparse import OptionParser, Option, OptionValueError, IndentedHelpFormatter
49
-from logging import debug, info, warning, error
50
-
51
-
52
-try:
53
-    import htmlentitydefs
54
-except Exception:
55
-    # python 3 support
56
-    import html.entities as htmlentitydefs
57
-
58
-try:
59
-    unicode
60
-except NameError:
61
-    # python 3 support
62
-    # In python 3, unicode -> str, and str -> bytes
63
-    unicode = str
64
-
65
-try:
66
-    from shutil import which
67
-except ImportError:
68
-    # python2 fallback code
69
-    from distutils.spawn import find_executable as which
70
-
71
-
72
-def output(message):
73
-    sys.stdout.write(message + "\n")
74
-    sys.stdout.flush()
75
-
76
-def check_args_type(args, type, verbose_type):
77
-    """NOTE: This function looks like to not be used."""
78
-    for arg in args:
79
-        if S3Uri(arg).type != type:
80
-            raise ParameterError("Expecting %s instead of '%s'" % (verbose_type, arg))
81
-
82
-def cmd_du(args):
83
-    s3 = S3(Config())
84
-    if len(args) > 0:
85
-        uri = S3Uri(args[0])
86
-        if uri.type == "s3" and uri.has_bucket():
87
-            subcmd_bucket_usage(s3, uri)
88
-            return EX_OK
89
-    subcmd_bucket_usage_all(s3)
90
-    return EX_OK
91
-
92
-def subcmd_bucket_usage_all(s3):
93
-    """
94
-    Returns: sum of bucket sizes as integer
95
-    Raises: S3Error
96
-    """
97
-    cfg = Config()
98
-    response = s3.list_all_buckets()
99
-
100
-    buckets_size = 0
101
-    for bucket in response["list"]:
102
-        size = subcmd_bucket_usage(s3, S3Uri("s3://" + bucket["Name"]))
103
-        if size != None:
104
-            buckets_size += size
105
-    total_size, size_coeff = formatSize(buckets_size, cfg.human_readable_sizes)
106
-    total_size_str = str(total_size) + size_coeff
107
-    output(u"".rjust(12, "-"))
108
-    output(u"%s Total" % (total_size_str.ljust(12)))
109
-    return size
110
-
111
-def subcmd_bucket_usage(s3, uri):
112
-    """
113
-    Returns: bucket size as integer
114
-    Raises: S3Error
115
-    """
116
-    bucket_size = 0
117
-    object_count = 0
118
-    extra_info = u''
119
-
120
-    bucket = uri.bucket()
121
-    prefix = uri.object()
122
-    try:
123
-        for _, _, objects in s3.bucket_list_streaming(bucket, prefix=prefix, recursive=True):
124
-            for obj in objects:
125
-                bucket_size += int(obj["Size"])
126
-                object_count += 1
127
-
128
-    except S3Error as e:
129
-        if e.info["Code"] in S3.codes:
130
-            error(S3.codes[e.info["Code"]] % bucket)
131
-        raise
132
-
133
-    except KeyboardInterrupt as e:
134
-        extra_info = u' [interrupted]'
135
-
136
-    total_size_str = u"%d%s" % formatSize(bucket_size,
137
-                                          Config().human_readable_sizes)
138
-    if Config().human_readable_sizes:
139
-        total_size_str = total_size_str.rjust(5)
140
-    else:
141
-        total_size_str = total_size_str.rjust(12)
142
-    output(u"%s %7s objects %s%s" % (total_size_str, object_count, uri,
143
-                                     extra_info))
144
-    return bucket_size
145
-
146
-def cmd_ls(args):
147
-    cfg = Config()
148
-    s3 = S3(cfg)
149
-    if len(args) > 0:
150
-        uri = S3Uri(args[0])
151
-        if uri.type == "s3" and uri.has_bucket():
152
-            subcmd_bucket_list(s3, uri, cfg.limit)
153
-            return EX_OK
154
-
155
-    # If not a s3 type uri or no bucket was provided, list all the buckets
156
-    subcmd_all_buckets_list(s3)
157
-    return EX_OK
158
-
159
-def subcmd_all_buckets_list(s3):
160
-
161
-    response = s3.list_all_buckets()
162
-
163
-    for bucket in sorted(response["list"], key=lambda b:b["Name"]):
164
-        output(u"%s  s3://%s" % (formatDateTime(bucket["CreationDate"]),
165
-                                 bucket["Name"]))
166
-
167
-def cmd_all_buckets_list_all_content(args):
168
-    cfg = Config()
169
-    s3 = S3(cfg)
170
-
171
-    response = s3.list_all_buckets()
172
-
173
-    for bucket in response["list"]:
174
-        subcmd_bucket_list(s3, S3Uri("s3://" + bucket["Name"]), cfg.limit)
175
-        output(u"")
176
-    return EX_OK
177
-
178
-def subcmd_bucket_list(s3, uri, limit):
179
-    cfg = Config()
180
-
181
-    bucket = uri.bucket()
182
-    prefix = uri.object()
183
-
184
-    debug(u"Bucket 's3://%s':" % bucket)
185
-    if prefix.endswith('*'):
186
-        prefix = prefix[:-1]
187
-    try:
188
-        response = s3.bucket_list(bucket, prefix = prefix, limit = limit)
189
-    except S3Error as e:
190
-        if e.info["Code"] in S3.codes:
191
-            error(S3.codes[e.info["Code"]] % bucket)
192
-        raise
193
-
194
-    # md5 are 32 char long, but for multipart there could be a suffix
195
-    if Config().human_readable_sizes:
196
-        # %(size)5s%(coeff)1s
197
-        format_size = u"%5d%1s"
198
-        dir_str = u"DIR".rjust(6)
199
-    else:
200
-        format_size = u"%12d%s"
201
-        dir_str = u"DIR".rjust(12)
202
-    if cfg.long_listing:
203
-        format_string = u"%(timestamp)16s %(size)s  %(md5)-35s  %(storageclass)-11s  %(uri)s"
204
-    elif cfg.list_md5:
205
-        format_string = u"%(timestamp)16s %(size)s  %(md5)-35s  %(uri)s"
206
-    else:
207
-        format_string = u"%(timestamp)16s %(size)s  %(uri)s"
208
-
209
-    for prefix in response['common_prefixes']:
210
-        output(format_string % {
211
-            "timestamp": "",
212
-            "size": dir_str,
213
-            "md5": "",
214
-            "storageclass": "",
215
-            "uri": uri.compose_uri(bucket, prefix["Prefix"])})
216
-
217
-    for object in response["list"]:
218
-        md5 = object.get('ETag', '').strip('"\'')
219
-        storageclass = object.get('StorageClass','')
220
-
221
-        if cfg.list_md5:
222
-            if '-' in md5: # need to get md5 from the object
223
-                object_uri = uri.compose_uri(bucket, object["Key"])
224
-                info_response = s3.object_info(S3Uri(object_uri))
225
-                try:
226
-                    md5 = info_response['s3cmd-attrs']['md5']
227
-                except KeyError:
228
-                    pass
229
-
230
-        size_and_coeff = formatSize(object["Size"],
231
-                                    Config().human_readable_sizes)
232
-        output(format_string % {
233
-            "timestamp": formatDateTime(object["LastModified"]),
234
-            "size" : format_size % size_and_coeff,
235
-            "md5" : md5,
236
-            "storageclass" : storageclass,
237
-            "uri": uri.compose_uri(bucket, object["Key"]),
238
-            })
239
-
240
-    if response["truncated"]:
241
-        warning(u"The list is truncated because the settings limit was reached.")
242
-
243
-def cmd_bucket_create(args):
244
-    cfg = Config()
245
-    s3 = S3(cfg)
246
-    for arg in args:
247
-        uri = S3Uri(arg)
248
-        if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
249
-            raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
250
-        try:
251
-            response = s3.bucket_create(uri.bucket(), cfg.bucket_location)
252
-            output(u"Bucket '%s' created" % uri.uri())
253
-        except S3Error as e:
254
-            if e.info["Code"] in S3.codes:
255
-                error(S3.codes[e.info["Code"]] % uri.bucket())
256
-            raise
257
-    return EX_OK
258
-
259
-def cmd_website_info(args):
260
-    cfg = Config()
261
-    s3 = S3(cfg)
262
-    for arg in args:
263
-        uri = S3Uri(arg)
264
-        if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
265
-            raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
266
-        try:
267
-            response = s3.website_info(uri, cfg.bucket_location)
268
-            if response:
269
-                output(u"Bucket %s: Website configuration" % uri.uri())
270
-                output(u"Website endpoint: %s" % response['website_endpoint'])
271
-                output(u"Index document:   %s" % response['index_document'])
272
-                output(u"Error document:   %s" % response['error_document'])
273
-            else:
274
-                output(u"Bucket %s: Unable to receive website configuration." % (uri.uri()))
275
-        except S3Error as e:
276
-            if e.info["Code"] in S3.codes:
277
-                error(S3.codes[e.info["Code"]] % uri.bucket())
278
-            raise
279
-    return EX_OK
280
-
281
-def cmd_website_create(args):
282
-    cfg = Config()
283
-    s3 = S3(cfg)
284
-    for arg in args:
285
-        uri = S3Uri(arg)
286
-        if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
287
-            raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
288
-        try:
289
-            response = s3.website_create(uri, cfg.bucket_location)
290
-            output(u"Bucket '%s': website configuration created." % (uri.uri()))
291
-        except S3Error as e:
292
-            if e.info["Code"] in S3.codes:
293
-                error(S3.codes[e.info["Code"]] % uri.bucket())
294
-            raise
295
-    return EX_OK
296
-
297
-def cmd_website_delete(args):
298
-    cfg = Config()
299
-    s3 = S3(cfg)
300
-    for arg in args:
301
-        uri = S3Uri(arg)
302
-        if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
303
-            raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
304
-        try:
305
-            response = s3.website_delete(uri, cfg.bucket_location)
306
-            output(u"Bucket '%s': website configuration deleted." % (uri.uri()))
307
-        except S3Error as e:
308
-            if e.info["Code"] in S3.codes:
309
-                error(S3.codes[e.info["Code"]] % uri.bucket())
310
-            raise
311
-    return EX_OK
312
-
313
-def cmd_expiration_set(args):
314
-    cfg = Config()
315
-    s3 = S3(cfg)
316
-    for arg in args:
317
-        uri = S3Uri(arg)
318
-        if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
319
-            raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
320
-        try:
321
-            response = s3.expiration_set(uri, cfg.bucket_location)
322
-            if response["status"] == 200:
323
-                output(u"Bucket '%s': expiration configuration is set." % (uri.uri()))
324
-            elif response["status"] == 204:
325
-                output(u"Bucket '%s': expiration configuration is deleted." % (uri.uri()))
326
-        except S3Error as e:
327
-            if e.info["Code"] in S3.codes:
328
-                error(S3.codes[e.info["Code"]] % uri.bucket())
329
-            raise
330
-    return EX_OK
331
-
332
-def cmd_bucket_delete(args):
333
-    cfg = Config()
334
-    s3 = S3(cfg)
335
-
336
-    def _bucket_delete_one(uri, retry=True):
337
-        try:
338
-            response = s3.bucket_delete(uri.bucket())
339
-            output(u"Bucket '%s' removed" % uri.uri())
340
-        except S3Error as e:
341
-            if e.info['Code'] == 'NoSuchBucket':
342
-                if cfg.force:
343
-                    return EX_OK
344
-                else:
345
-                    raise
346
-            if e.info['Code'] == 'BucketNotEmpty' and retry and (cfg.force or cfg.recursive):
347
-                warning(u"Bucket is not empty. Removing all the objects from it first. This may take some time...")
348
-                rc = subcmd_batch_del(uri_str = uri.uri())
349
-                if rc == EX_OK:
350
-                    return _bucket_delete_one(uri, False)
351
-                else:
352
-                    output(u"Bucket was not removed")
353
-            elif e.info["Code"] in S3.codes:
354
-                error(S3.codes[e.info["Code"]] % uri.bucket())
355
-            raise
356
-        return EX_OK
357
-
358
-    for arg in args:
359
-        uri = S3Uri(arg)
360
-        if not uri.type == "s3" or not uri.has_bucket() or uri.has_object():
361
-            raise ParameterError("Expecting S3 URI with just the bucket name set instead of '%s'" % arg)
362
-        rc = _bucket_delete_one(uri)
363
-        if rc != EX_OK:
364
-            return rc
365
-    return EX_OK
366
-
367
-def cmd_object_put(args):
368
-    cfg = Config()
369
-    s3 = S3(cfg)
370
-
371
-    if len(args) == 0:
372
-        raise ParameterError("Nothing to upload. Expecting a local file or directory and a S3 URI destination.")
373
-
374
-    ## Normalize URI to convert s3://bkt to s3://bkt/ (trailing slash)
375
-    destination_base_uri = S3Uri(args.pop())
376
-    if destination_base_uri.type != 's3':
377
-        raise ParameterError("Destination must be S3Uri. Got: %s" % destination_base_uri)
378
-    destination_base = destination_base_uri.uri()
379
-
380
-    if len(args) == 0:
381
-        raise ParameterError("Nothing to upload. Expecting a local file or directory.")
382
-
383
-    local_list, single_file_local, exclude_list, total_size_local = fetch_local_list(args, is_src = True)
384
-
385
-    local_count = len(local_list)
386
-
387
-    info(u"Summary: %d local files to upload" % local_count)
388
-
389
-    if local_count == 0:
390
-        raise ParameterError("Nothing to upload.")
391
-
392
-    if local_count > 0:
393
-        if not single_file_local and '-' in local_list.keys():
394
-            raise ParameterError("Cannot specify multiple local files if uploading from '-' (ie stdin)")
395
-        elif single_file_local and local_list.keys()[0] == "-" and destination_base.endswith("/"):
396
-            raise ParameterError("Destination S3 URI must not end with '/' when uploading from stdin.")
397
-        elif not destination_base.endswith("/"):
398
-            if not single_file_local:
399
-                raise ParameterError("Destination S3 URI must end with '/' (ie must refer to a directory on the remote side).")
400
-            local_list[local_list.keys()[0]]['remote_uri'] = destination_base
401
-        else:
402
-            for key in local_list:
403
-                local_list[key]['remote_uri'] = destination_base + key
404
-
405
-    if cfg.dry_run:
406
-        for key in exclude_list:
407
-            output(u"exclude: %s" % key)
408
-        for key in local_list:
409
-            if key != "-":
410
-                nicekey = local_list[key]['full_name']
411
-            else:
412
-                nicekey = "<stdin>"
413
-            output(u"upload: '%s' -> '%s'" % (nicekey, local_list[key]['remote_uri']))
414
-
415
-        warning(u"Exiting now because of --dry-run")
416
-        return EX_OK
417
-
418
-    seq = 0
419
-    ret = EX_OK
420
-    for key in local_list:
421
-        seq += 1
422
-
423
-        uri_final = S3Uri(local_list[key]['remote_uri'])
424
-        try:
425
-            src_md5 = local_list.get_md5(key)
426
-        except IOError:
427
-            src_md5 = None
428
-
429
-        extra_headers = copy(cfg.extra_headers)
430
-        full_name_orig = local_list[key]['full_name']
431
-        full_name = full_name_orig
432
-        seq_label = "[%d of %d]" % (seq, local_count)
433
-        if Config().encrypt:
434
-            gpg_exitcode, full_name, extra_headers["x-amz-meta-s3tools-gpgenc"] = gpg_encrypt(full_name_orig)
435
-        attr_header = _build_attr_header(local_list[key], key, src_md5)
436
-        debug(u"attr_header: %s" % attr_header)
437
-        extra_headers.update(attr_header)
438
-        try:
439
-            response = s3.object_put(full_name, uri_final, extra_headers, extra_label = seq_label)
440
-        except S3UploadError as exc:
441
-            error(u"Upload of '%s' failed too many times (Last reason: %s)" % (full_name_orig, exc))
442
-            if cfg.stop_on_error:
443
-                ret = EX_DATAERR
444
-                error(u"Exiting now because of --stop-on-error")
445
-                break
446
-            ret = EX_PARTIAL
447
-            continue
448
-        except InvalidFileError as exc:
449
-            error(u"Upload of '%s' is not possible (Reason: %s)" % (full_name_orig, exc))
450
-            ret = EX_PARTIAL
451
-            if cfg.stop_on_error:
452
-                ret = EX_OSFILE
453
-                error(u"Exiting now because of --stop-on-error")
454
-                break
455
-            continue
456
-        if response is not None:
457
-            speed_fmt = formatSize(response["speed"], human_readable = True, floating_point = True)
458
-            if not Config().progress_meter:
459
-                if full_name_orig != "-":
460
-                    nicekey = full_name_orig
461
-                else:
462
-                    nicekey = "<stdin>"
463
-                output(u"upload: '%s' -> '%s' (%d bytes in %0.1f seconds, %0.2f %sB/s) %s" %
464
-                       (nicekey, uri_final, response["size"], response["elapsed"],
465
-                        speed_fmt[0], speed_fmt[1], seq_label))
466
-        if Config().acl_public:
467
-            output(u"Public URL of the object is: %s" %
468
-                   (uri_final.public_url()))
469
-        if Config().encrypt and full_name != full_name_orig:
470
-            debug(u"Removing temporary encrypted file: %s" % full_name)
471
-            os.remove(deunicodise(full_name))
472
-    return ret
473
-
474
-def cmd_object_get(args):
475
-    cfg = Config()
476
-    s3 = S3(cfg)
477
-
478
-    ## Check arguments:
479
-    ## if not --recursive:
480
-    ##   - first N arguments must be S3Uri
481
-    ##   - if the last one is S3 make current dir the destination_base
482
-    ##   - if the last one is a directory:
483
-    ##       - take all 'basenames' of the remote objects and
484
-    ##         make the destination name be 'destination_base'+'basename'
485
-    ##   - if the last one is a file or not existing:
486
-    ##       - if the number of sources (N, above) == 1 treat it
487
-    ##         as a filename and save the object there.
488
-    ##       - if there's more sources -> Error
489
-    ## if --recursive:
490
-    ##   - first N arguments must be S3Uri
491
-    ##       - for each Uri get a list of remote objects with that Uri as a prefix
492
-    ##       - apply exclude/include rules
493
-    ##       - each list item will have MD5sum, Timestamp and pointer to S3Uri
494
-    ##         used as a prefix.
495
-    ##   - the last arg may be '-' (stdout)
496
-    ##   - the last arg may be a local directory - destination_base
497
-    ##   - if the last one is S3 make current dir the destination_base
498
-    ##   - if the last one doesn't exist check remote list:
499
-    ##       - if there is only one item and its_prefix==its_name
500
-    ##         download that item to the name given in last arg.
501
-    ##       - if there are more remote items use the last arg as a destination_base
502
-    ##         and try to create the directory (incl. all parents).
503
-    ##
504
-    ## In both cases we end up with a list mapping remote object names (keys) to local file names.
505
-
506
-    ## Each item will be a dict with the following attributes
507
-    # {'remote_uri', 'local_filename'}
508
-    download_list = []
509
-
510
-    if len(args) == 0:
511
-        raise ParameterError("Nothing to download. Expecting S3 URI.")
512
-
513
-    if S3Uri(args[-1]).type == 'file':
514
-        destination_base = args.pop()
515
-    else:
516
-        destination_base = "."
517
-
518
-    if len(args) == 0:
519
-        raise ParameterError("Nothing to download. Expecting S3 URI.")
520
-
521
-    remote_list, exclude_list, remote_total_size = fetch_remote_list(args, require_attribs = False)
522
-
523
-    remote_count = len(remote_list)
524
-
525
-    info(u"Summary: %d remote files to download" % remote_count)
526
-
527
-    if remote_count > 0:
528
-        if destination_base == "-":
529
-            ## stdout is ok for multiple remote files!
530
-            for key in remote_list:
531
-                remote_list[key]['local_filename'] = "-"
532
-        elif not os.path.isdir(deunicodise(destination_base)):
533
-            ## We were either given a file name (existing or not)
534
-            if remote_count > 1:
535
-                raise ParameterError("Destination must be a directory or stdout when downloading multiple sources.")
536
-            remote_list[remote_list.keys()[0]]['local_filename'] = destination_base
537
-        else:
538
-            if destination_base[-1] != os.path.sep:
539
-                destination_base += os.path.sep
540
-            for key in remote_list:
541
-                local_filename = destination_base + key
542
-                if os.path.sep != "/":
543
-                    local_filename = os.path.sep.join(local_filename.split("/"))
544
-                remote_list[key]['local_filename'] = local_filename
545
-
546
-    if cfg.dry_run:
547
-        for key in exclude_list:
548
-            output(u"exclude: %s" % key)
549
-        for key in remote_list:
550
-            output(u"download: '%s' -> '%s'" % (remote_list[key]['object_uri_str'], remote_list[key]['local_filename']))
551
-
552
-        warning(u"Exiting now because of --dry-run")
553
-        return EX_OK
554
-
555
-    seq = 0
556
-    ret = EX_OK
557
-    for key in remote_list:
558
-        seq += 1
559
-        item = remote_list[key]
560
-        uri = S3Uri(item['object_uri_str'])
561
-        ## Encode / Decode destination with "replace" to make sure it's compatible with current encoding
562
-        destination = unicodise_safe(item['local_filename'])
563
-        seq_label = "[%d of %d]" % (seq, remote_count)
564
-
565
-        start_position = 0
566
-
567
-        if destination == "-":
568
-            ## stdout
569
-            dst_stream = io.open(sys.__stdout__.fileno(), mode='wb', closefd=False)
570
-            dst_stream.stream_name = u'<stdout>'
571
-            file_exists = True
572
-        else:
573
-            ## File
574
-            try:
575
-                file_exists = os.path.exists(deunicodise(destination))
576
-                try:
577
-                    dst_stream = io.open(deunicodise(destination), mode='ab')
578
-                    dst_stream.stream_name = destination
579
-                except IOError as e:
580
-                    if e.errno == errno.ENOENT:
581
-                        basename = destination[:destination.rindex(os.path.sep)]
582
-                        info(u"Creating directory: %s" % basename)
583
-                        os.makedirs(deunicodise(basename))
584
-                        dst_stream = io.open(deunicodise(destination), mode='ab')
585
-                        dst_stream.stream_name = destination
586
-                    else:
587
-                        raise
588
-                if file_exists:
589
-                    if Config().get_continue:
590
-                        start_position = dst_stream.tell()
591
-                    elif Config().force:
592
-                        start_position = 0
593
-                        dst_stream.seek(0)
594
-                        dst_stream.truncate()
595
-                    elif Config().skip_existing:
596
-                        info(u"Skipping over existing file: %s" % (destination))
597
-                        continue
598
-                    else:
599
-                        dst_stream.close()
600
-                        raise ParameterError(u"File %s already exists. Use either of --force / --continue / --skip-existing or give it a new name." % destination)
601
-            except IOError as e:
602
-                error(u"Skipping %s: %s" % (destination, e.strerror))
603
-                continue
604
-        try:
605
-            try:
606
-                response = s3.object_get(uri, dst_stream, destination, start_position = start_position, extra_label = seq_label)
607
-            finally:
608
-                dst_stream.close()
609
-        except S3DownloadError as e:
610
-            error(u"%s: Skipping that file.  This is usually a transient error, please try again later." % e)
611
-            if not file_exists: # Delete, only if file didn't exist before!
612
-                debug(u"object_get failed for '%s', deleting..." % (destination,))
613
-                os.unlink(deunicodise(destination))
614
-                ret = EX_PARTIAL
615
-                if cfg.stop_on_error:
616
-                    ret = EX_DATAERR
617
-                    break
618
-            continue
619
-        except S3Error as e:
620
-            if not file_exists: # Delete, only if file didn't exist before!
621
-                debug(u"object_get failed for '%s', deleting..." % (destination,))
622
-                os.unlink(deunicodise(destination))
623
-            raise
624
-
625
-        if "x-amz-meta-s3tools-gpgenc" in response["headers"]:
626
-            gpg_decrypt(destination, response["headers"]["x-amz-meta-s3tools-gpgenc"])
627
-            response["size"] = os.stat(deunicodise(destination))[6]
628
-        if "last-modified" in response["headers"] and destination != "-":
629
-            last_modified = time.mktime(time.strptime(response["headers"]["last-modified"], "%a, %d %b %Y %H:%M:%S GMT"))
630
-            os.utime(deunicodise(destination), (last_modified, last_modified))
631
-            debug("set mtime to %s" % last_modified)
632
-        if not Config().progress_meter and destination != "-":
633
-            speed_fmt = formatSize(response["speed"], human_readable = True, floating_point = True)
634
-            output(u"download: '%s' -> '%s' (%d bytes in %0.1f seconds, %0.2f %sB/s)" %
635
-                (uri, destination, response["size"], response["elapsed"], speed_fmt[0], speed_fmt[1]))
636
-        if Config().delete_after_fetch:
637
-            s3.object_delete(uri)
638
-            output(u"File '%s' removed after fetch" % (uri))
639
-    return EX_OK
640
-
641
-def cmd_object_del(args):
642
-    cfg = Config()
643
-    recursive = cfg.recursive
644
-    for uri_str in args:
645
-        uri = S3Uri(uri_str)
646
-        if uri.type != "s3":
647
-            raise ParameterError("Expecting S3 URI instead of '%s'" % uri_str)
648
-        if not uri.has_object():
649
-            if recursive and not cfg.force:
650
-                raise ParameterError("Please use --force to delete ALL contents of %s" % uri_str)
651
-            elif not recursive:
652
-                raise ParameterError("File name required, not only the bucket name. Alternatively use --recursive")
653
-
654
-        if not recursive:
655
-            rc = subcmd_object_del_uri(uri_str)
656
-        elif cfg.exclude or cfg.include or cfg.max_delete > 0:
657
-            # subcmd_batch_del_iterative does not support file exclusion and can't
658
-            # accurately know how many total files will be deleted, so revert to batch delete.
659
-            rc = subcmd_batch_del(uri_str = uri_str)
660
-        else:
661
-            rc = subcmd_batch_del_iterative(uri_str = uri_str)
662
-        if not rc:
663
-            return rc
664
-    return EX_OK
665
-
666
-def subcmd_batch_del_iterative(uri_str = None, bucket = None):
667
-    """ Streaming version of batch deletion (doesn't realize whole list in memory before deleting).
668
-
669
-    Differences from subcmd_batch_del:
670
-      - Does not obey --exclude directives or obey cfg.max_delete (use subcmd_batch_del in those cases)
671
-    """
672
-    if bucket and uri_str:
673
-        raise ValueError("Pass only one of uri_str or bucket")
674
-    if bucket: # bucket specified
675
-        uri_str = "s3://%s" % bucket
676
-    cfg = Config()
677
-    s3 = S3(cfg)
678
-    uri = S3Uri(uri_str)
679
-    bucket = uri.bucket()
680
-
681
-    deleted_bytes = deleted_count = 0
682
-
683
-    for _, _, to_delete in s3.bucket_list_streaming(bucket, prefix=uri.object(), recursive=True):
684
-        if not to_delete:
685
-            continue
686
-        if not cfg.dry_run:
687
-            response = s3.object_batch_delete_uri_strs([uri.compose_uri(bucket, item['Key']) for item in to_delete])
688
-        deleted_bytes += sum(int(item["Size"]) for item in to_delete)
689
-        deleted_count += len(to_delete)
690
-        output(u'\n'.join(u"delete: '%s'" % uri.compose_uri(bucket, p['Key']) for p in to_delete))
691
-
692
-    if deleted_count:
693
-        # display summary data of deleted files
694
-        if cfg.stats:
695
-            stats_info = StatsInfo()
696
-            stats_info.files_deleted = deleted_count
697
-            stats_info.size_deleted = deleted_bytes
698
-            output(stats_info.format_output())
699
-        else:
700
-            total_size, size_coeff = formatSize(deleted_bytes, Config().human_readable_sizes)
701
-            total_size_str = str(total_size) + size_coeff
702
-            info(u"Deleted %s objects (%s) from %s" % (deleted_count, total_size_str, uri))
703
-    else:
704
-        warning(u"Remote list is empty.")
705
-
706
-    return EX_OK
707
-
708
-def subcmd_batch_del(uri_str = None, bucket = None, remote_list = None):
709
-    """
710
-    Returns: EX_OK
711
-    Raises: ValueError
712
-    """
713
-    cfg = Config()
714
-    s3 = S3(cfg)
715
-    def _batch_del(remote_list):
716
-        to_delete = remote_list[:1000]
717
-        remote_list = remote_list[1000:]
718
-        while len(to_delete):
719
-            debug(u"Batch delete %d, remaining %d" % (len(to_delete), len(remote_list)))
720
-            if not cfg.dry_run:
721
-                response = s3.object_batch_delete(to_delete)
722
-            output(u'\n'.join((u"delete: '%s'" % to_delete[p]['object_uri_str']) for p in to_delete))
723
-            to_delete = remote_list[:1000]
724
-            remote_list = remote_list[1000:]
725
-
726
-    if remote_list is not None and len(remote_list) == 0:
727
-        return False
728
-
729
-    if len([item for item in [uri_str, bucket, remote_list] if item]) != 1:
730
-        raise ValueError("One and only one of 'uri_str', 'bucket', 'remote_list' can be specified.")
731
-
732
-    if bucket: # bucket specified
733
-        uri_str = "s3://%s" % bucket
734
-    if remote_list is None: # uri_str specified
735
-        remote_list, exclude_list, remote_total_size = fetch_remote_list(uri_str, require_attribs = False)
736
-
737
-    if len(remote_list) == 0:
738
-        warning(u"Remote list is empty.")
739
-        return EX_OK
740
-
741
-    if cfg.max_delete > 0 and len(remote_list) > cfg.max_delete:
742
-        warning(u"delete: maximum requested number of deletes would be exceeded, none performed.")
743
-        return EX_OK
744
-
745
-    _batch_del(remote_list)
746
-
747
-    if cfg.dry_run:
748
-        warning(u"Exiting now because of --dry-run")
749
-    return EX_OK
750
-
751
-def subcmd_object_del_uri(uri_str, recursive = None):
752
-    """
753
-    Returns: True if XXX, False if XXX
754
-    Raises: ValueError
755
-    """
756
-    cfg = Config()
757
-    s3 = S3(cfg)
758
-
759
-    if recursive is None:
760
-        recursive = cfg.recursive
761
-
762
-    remote_list, exclude_list, remote_total_size = fetch_remote_list(uri_str, require_attribs = False, recursive = recursive)
763
-
764
-    remote_count = len(remote_list)
765
-
766
-    info(u"Summary: %d remote files to delete" % remote_count)
767
-    if cfg.max_delete > 0 and remote_count > cfg.max_delete:
768
-        warning(u"delete: maximum requested number of deletes would be exceeded, none performed.")
769
-        return False
770
-
771
-    if cfg.dry_run:
772
-        for key in exclude_list:
773
-            output(u"exclude: %s" % key)
774
-        for key in remote_list:
775
-            output(u"delete: %s" % remote_list[key]['object_uri_str'])
776
-
777
-        warning(u"Exiting now because of --dry-run")
778
-        return True
779
-
780
-    for key in remote_list:
781
-        item = remote_list[key]
782
-        response = s3.object_delete(S3Uri(item['object_uri_str']))
783
-        output(u"delete: '%s'" % item['object_uri_str'])
784
-    return True
785
-
786
-def cmd_object_restore(args):
787
-    cfg = Config()
788
-    s3 = S3(cfg)
789
-
790
-    if cfg.restore_days < 1:
791
-        raise ParameterError("You must restore a file for 1 or more days")
792
-
793
-    # accept case-insensitive argument but fix it to match S3 API
794
-    if cfg.restore_priority.title() not in ['Standard', 'Expedited', 'Bulk']:
795
-        raise ParameterError("Valid restoration priorities: bulk, standard, expedited")
796
-    else:
797
-        cfg.restore_priority = cfg.restore_priority.title()
798
-
799
-    remote_list, exclude_list, remote_total_size = fetch_remote_list(args, require_attribs = False, recursive = cfg.recursive)
800
-
801
-    remote_count = len(remote_list)
802
-
803
-    info(u"Summary: Restoring %d remote files for %d days at %s priority" % (remote_count, cfg.restore_days, cfg.restore_priority))
804
-
805
-    if cfg.dry_run:
806
-        for key in exclude_list:
807
-            output(u"exclude: %s" % key)
808
-        for key in remote_list:
809
-            output(u"restore: '%s'" % remote_list[key]['object_uri_str'])
810
-
811
-        warning(u"Exiting now because of --dry-run")
812
-        return EX_OK
813
-
814
-    for key in remote_list:
815
-        item = remote_list[key]
816
-
817
-        uri = S3Uri(item['object_uri_str'])
818
-        if not item['object_uri_str'].endswith("/"):
819
-            try:
820
-                response = s3.object_restore(S3Uri(item['object_uri_str']))
821
-                output(u"restore: '%s'" % item['object_uri_str'])
822
-            except S3Error as e:
823
-                if e.code == "RestoreAlreadyInProgress":
824
-                    warning("%s: %s" % (e.message, item['object_uri_str']))
825
-                else:
826
-                    raise e
827
-        else:
828
-            debug(u"Skipping directory since only files may be restored")
829
-    return EX_OK
830
-
831
-
832
-def subcmd_cp_mv(args, process_fce, action_str, message):
833
-    cfg = Config()
834
-    if action_str == 'modify':
835
-        if len(args) < 1:
836
-            raise ParameterError("Expecting one or more S3 URIs for "
837
-                                 + action_str)
838
-        destination_base = None
839
-    else:
840
-        if len(args) < 2:
841
-            raise ParameterError("Expecting two or more S3 URIs for "
842
-                                 + action_str)
843
-        dst_base_uri = S3Uri(args.pop())
844
-        if dst_base_uri.type != "s3":
845
-            raise ParameterError("Destination must be S3 URI. To download a "
846
-                                 "file use 'get' or 'sync'.")
847
-        destination_base = dst_base_uri.uri()
848
-
849
-    scoreboard = ExitScoreboard()
850
-
851
-    remote_list, exclude_list, remote_total_size = \
852
-        fetch_remote_list(args, require_attribs=False)
853
-
854
-    remote_count = len(remote_list)
855
-
856
-    info(u"Summary: %d remote files to %s" % (remote_count, action_str))
857
-
858
-    if destination_base:
859
-        # Trying to mv dir1/ to dir2 will not pass a test in S3.FileLists,
860
-        # so we don't need to test for it here.
861
-        if not destination_base.endswith('/') \
862
-           and (len(remote_list) > 1 or cfg.recursive):
863
-            raise ParameterError("Destination must be a directory and end with"
864
-                                 " '/' when acting on a folder content or on "
865
-                                 "multiple sources.")
866
-
867
-        if cfg.recursive:
868
-            for key in remote_list:
869
-                remote_list[key]['dest_name'] = destination_base + key
870
-        else:
871
-            for key in remote_list:
872
-                if destination_base.endswith("/"):
873
-                    remote_list[key]['dest_name'] = destination_base + key
874
-                else:
875
-                    remote_list[key]['dest_name'] = destination_base
876
-    else:
877
-        for key in remote_list:
878
-            remote_list[key]['dest_name'] = remote_list[key]['object_uri_str']
879
-
880
-    if cfg.dry_run:
881
-        for key in exclude_list:
882
-            output(u"exclude: %s" % key)
883
-        for key in remote_list:
884
-            output(u"%s: '%s' -> '%s'" % (action_str,
885
-                                          remote_list[key]['object_uri_str'],
886
-                                          remote_list[key]['dest_name']))
887
-
888
-        warning(u"Exiting now because of --dry-run")
889
-        return EX_OK
890
-
891
-    seq = 0
892
-    for key in remote_list:
893
-        seq += 1
894
-        seq_label = "[%d of %d]" % (seq, remote_count)
895
-
896
-        item = remote_list[key]
897
-        src_uri = S3Uri(item['object_uri_str'])
898
-        dst_uri = S3Uri(item['dest_name'])
899
-        src_size = item.get('size')
900
-
901
-        extra_headers = copy(cfg.extra_headers)
902
-        try:
903
-            response = process_fce(src_uri, dst_uri, extra_headers,
904
-                                   src_size=src_size,
905
-                                   extra_label=seq_label)
906
-            output(message % {"src": src_uri, "dst": dst_uri,
907
-                              "extra": seq_label})
908
-            if Config().acl_public:
909
-                info(u"Public URL is: %s" % dst_uri.public_url())
910
-            scoreboard.success()
911
-        except (S3Error, S3UploadError) as exc:
912
-            if isinstance(exc, S3Error) and exc.code == "NoSuchKey":
913
-                scoreboard.notfound()
914
-                warning(u"Key not found %s" % item['object_uri_str'])
915
-            else:
916
-                scoreboard.failed()
917
-                error(u"Copy failed for: '%s' (%s)", item['object_uri_str'],
918
-                      exc)
919
-
920
-            if cfg.stop_on_error:
921
-                break
922
-    return scoreboard.rc()
923
-
924
-def cmd_cp(args):
925
-    s3 = S3(Config())
926
-    return subcmd_cp_mv(args, s3.object_copy, "copy",
927
-                        u"remote copy: '%(src)s' -> '%(dst)s'  %(extra)s")
928
-
929
-def cmd_modify(args):
930
-    s3 = S3(Config())
931
-    return subcmd_cp_mv(args, s3.object_modify, "modify",
932
-                        u"modify: '%(src)s'  %(extra)s")
933
-
934
-def cmd_mv(args):
935
-    s3 = S3(Config())
936
-    return subcmd_cp_mv(args, s3.object_move, "move",
937
-                        u"move: '%(src)s' -> '%(dst)s'  %(extra)s")
938
-
939
-def cmd_info(args):
940
-    cfg = Config()
941
-    s3 = S3(cfg)
942
-
943
-    while (len(args)):
944
-        uri_arg = args.pop(0)
945
-        uri = S3Uri(uri_arg)
946
-        if uri.type != "s3" or not uri.has_bucket():
947
-            raise ParameterError("Expecting S3 URI instead of '%s'" % uri_arg)
948
-
949
-        try:
950
-            if uri.has_object():
951
-                info = s3.object_info(uri)
952
-                output(u"%s (object):" % uri.uri())
953
-                output(u"   File size: %s" % info['headers']['content-length'])
954
-                output(u"   Last mod:  %s" % info['headers']['last-modified'])
955
-                output(u"   MIME type: %s" % info['headers'].get('content-type', 'none'))
956
-                output(u"   Storage:   %s" % info['headers'].get('x-amz-storage-class', 'STANDARD'))
957
-                md5 = info['headers'].get('etag', '').strip('"\'')
958
-                try:
959
-                    md5 = info['s3cmd-attrs']['md5']
960
-                except KeyError:
961
-                    pass
962
-                output(u"   MD5 sum:   %s" % md5)
963
-                if 'x-amz-server-side-encryption' in info['headers']:
964
-                    output(u"   SSE:       %s" % info['headers']['x-amz-server-side-encryption'])
965
-                else:
966
-                    output(u"   SSE:       none")
967
-
968
-            else:
969
-                info = s3.bucket_info(uri)
970
-                output(u"%s (bucket):" % uri.uri())
971
-                output(u"   Location:  %s" % (info['bucket-location']
972
-                                              or 'none'))
973
-                output(u"   Payer:     %s" % (info['requester-pays']
974
-                                              or 'none'))
975
-                expiration = s3.expiration_info(uri, cfg.bucket_location)
976
-                if expiration:
977
-                    expiration_desc = "Expiration Rule: "
978
-                    if expiration['prefix'] == "":
979
-                        expiration_desc += "all objects in this bucket "
980
-                    elif expiration['prefix'] is not None:
981
-                        expiration_desc += "objects with key prefix '" + expiration['prefix'] + "' "
982
-                    expiration_desc += "will expire in '"
983
-                    if expiration['days']:
984
-                        expiration_desc += expiration['days'] + "' day(s) after creation"
985
-                    elif expiration['date']:
986
-                        expiration_desc += expiration['date'] + "' "
987
-                    output(u"   %s" % expiration_desc)
988
-                else:
989
-                    output(u"   Expiration Rule: none")
990
-
991
-            try:
992
-                policy = s3.get_policy(uri)
993
-                output(u"   Policy:    %s" % policy)
994
-            except S3Error as exc:
995
-                # Ignore the exception and don't fail the info
996
-                # if the server doesn't support setting ACLs
997
-                if exc.status == 403:
998
-                    output(u"   Policy:    Not available: GetPolicy permission is needed to read the policy")
999
-                elif exc.status == 405:
1000
-                    output(u"   Policy:    Not available: Only the bucket owner can read the policy")
1001
-                elif exc.status not in [404, 501]:
1002
-                    raise exc
1003
-                else:
1004
-                    output(u"   Policy:    none")
1005
-
1006
-            try:
1007
-                cors = s3.get_cors(uri)
1008
-                output(u"   CORS:      %s" % cors)
1009
-            except S3Error as exc:
1010
-                # Ignore the exception and don't fail the info
1011
-                # if the server doesn't support setting ACLs
1012
-                if exc.status not in [404, 501]:
1013
-                    raise exc
1014
-                output(u"   CORS:      none")
1015
-
1016
-            try:
1017
-                acl = s3.get_acl(uri)
1018
-                acl_grant_list = acl.getGrantList()
1019
-                for grant in acl_grant_list:
1020
-                    output(u"   ACL:       %s: %s" % (grant['grantee'], grant['permission']))
1021
-                if acl.isAnonRead():
1022
-                    output(u"   URL:       %s" % uri.public_url())
1023
-            except S3Error as exc:
1024
-                # Ignore the exception and don't fail the info
1025
-                # if the server doesn't support setting ACLs
1026
-                if exc.status not in [404, 501]:
1027
-                    raise exc
1028
-                else:
1029
-                    output(u"   ACL:       none")
1030
-
1031
-            if uri.has_object():
1032
-                # Temporary hack for performance + python3 compatibility
1033
-                if PY3:
1034
-                    info_headers_iter = info['headers'].items()
1035
-                else:
1036
-                    info_headers_iter = info['headers'].iteritems()
1037
-                for header, value in info_headers_iter:
1038
-                    if header.startswith('x-amz-meta-'):
1039
-                        output(u"   %s: %s" % (header, value))
1040
-
1041
-        except S3Error as e:
1042
-            if e.info["Code"] in S3.codes:
1043
-                error(S3.codes[e.info["Code"]] % uri.bucket())
1044
-            raise
1045
-    return EX_OK
1046
-
1047
-def filedicts_to_keys(*args):
1048
-    keys = set()
1049
-    for a in args:
1050
-        keys.update(a.keys())
1051
-    keys = list(keys)
1052
-    keys.sort()
1053
-    return keys
1054
-
1055
-def cmd_sync_remote2remote(args):
1056
-    cfg = Config()
1057
-    s3 = S3(cfg)
1058
-
1059
-    # Normalise s3://uri (e.g. assert trailing slash)
1060
-    destination_base = S3Uri(args[-1]).uri()
1061
-
1062
-    destbase_with_source_list = set()
1063
-    for source_arg in args[:-1]:
1064
-        if source_arg.endswith('/'):
1065
-            destbase_with_source_list.add(destination_base)
1066
-        else:
1067
-            destbase_with_source_list.add(os.path.join(destination_base,
1068
-                                                  os.path.basename(source_arg)))
1069
-
1070
-    stats_info = StatsInfo()
1071
-
1072
-    src_list, src_exclude_list, remote_total_size = fetch_remote_list(args[:-1], recursive = True, require_attribs = True)
1073
-    dst_list, dst_exclude_list, _ = fetch_remote_list(destbase_with_source_list, recursive = True, require_attribs = True)
1074
-
1075
-    src_count = len(src_list)
1076
-    orig_src_count = src_count
1077
-    dst_count = len(dst_list)
1078
-    deleted_count = 0
1079
-
1080
-    info(u"Found %d source files, %d destination files" % (src_count, dst_count))
1081
-
1082
-    src_list, dst_list, update_list, copy_pairs = compare_filelists(src_list, dst_list, src_remote = True, dst_remote = True)
1083
-
1084
-    src_count = len(src_list)
1085
-    update_count = len(update_list)
1086
-    dst_count = len(dst_list)
1087
-
1088
-    print(u"Summary: %d source files to copy, %d files at destination to delete" % (src_count + update_count, dst_count))
1089
-
1090
-    ### Populate 'target_uri' only if we've got something to sync from src to dst
1091
-    for key in src_list:
1092
-        src_list[key]['target_uri'] = destination_base + key
1093
-    for key in update_list:
1094
-        update_list[key]['target_uri'] = destination_base + key
1095
-
1096
-    if cfg.dry_run:
1097
-        keys = filedicts_to_keys(src_exclude_list, dst_exclude_list)
1098
-        for key in keys:
1099
-            output(u"exclude: %s" % key)
1100
-        if cfg.delete_removed:
1101
-            for key in dst_list:
1102
-                output(u"delete: '%s'" % dst_list[key]['object_uri_str'])
1103
-        for key in src_list:
1104
-            output(u"remote copy: '%s' -> '%s'" % (src_list[key]['object_uri_str'], src_list[key]['target_uri']))
1105
-        for key in update_list:
1106
-            output(u"remote copy: '%s' -> '%s'" % (update_list[key]['object_uri_str'], update_list[key]['target_uri']))
1107
-        warning(u"Exiting now because of --dry-run")
1108
-        return EX_OK
1109
-
1110
-    # if there are copy pairs, we can't do delete_before, on the chance
1111
-    # we need one of the to-be-deleted files as a copy source.
1112
-    if len(copy_pairs) > 0:
1113
-        cfg.delete_after = True
1114
-
1115
-    if cfg.delete_removed and orig_src_count == 0 and len(dst_list) and not cfg.force:
1116
-        warning(u"delete: cowardly refusing to delete because no source files were found.  Use --force to override.")
1117
-        cfg.delete_removed = False
1118
-
1119
-    # Delete items in destination that are not in source
1120
-    if cfg.delete_removed and not cfg.delete_after:
1121
-        subcmd_batch_del(remote_list = dst_list)
1122
-        deleted_count = len(dst_list)
1123
-
1124
-    def _upload(src_list, seq, src_count):
1125
-        file_list = src_list.keys()
1126
-        file_list.sort()
1127
-        ret = EX_OK
1128
-        total_nb_files = 0
1129
-        total_size = 0
1130
-        for file in file_list:
1131
-            seq += 1
1132
-            item = src_list[file]
1133
-            src_uri = S3Uri(item['object_uri_str'])
1134
-            dst_uri = S3Uri(item['target_uri'])
1135
-            src_size = item.get('size')
1136
-            seq_label = "[%d of %d]" % (seq, src_count)
1137
-            extra_headers = copy(cfg.extra_headers)
1138
-            try:
1139
-                response = s3.object_copy(src_uri, dst_uri, extra_headers,
1140
-                                          src_size=src_size,
1141
-                                          extra_label=seq_label)
1142
-                output(u"remote copy: '%s' -> '%s'  %s" %
1143
-                       (src_uri, dst_uri, seq_label))
1144
-                total_nb_files += 1
1145
-                total_size += item.get(u'size', 0)
1146
-            except (S3Error, S3UploadError) as exc:
1147
-                ret = EX_PARTIAL
1148
-                error(u"File '%s' could not be copied: %s", src_uri, exc)
1149
-                if cfg.stop_on_error:
1150
-                    raise
1151
-        return ret, seq, total_nb_files, total_size
1152
-
1153
-    # Perform the synchronization of files
1154
-    timestamp_start = time.time()
1155
-    seq = 0
1156
-    ret, seq, nb_files, size = _upload(src_list, seq, src_count + update_count)
1157
-    total_files_copied = nb_files
1158
-    total_size_copied = size
1159
-
1160
-    status, seq, nb_files, size = _upload(update_list, seq, src_count + update_count)
1161
-    if ret == EX_OK:
1162
-        ret = status
1163
-    total_files_copied += nb_files
1164
-    total_size_copied += size
1165
-
1166
-    n_copied, bytes_saved, failed_copy_files = remote_copy(
1167
-        s3, copy_pairs, destination_base, None, False)
1168
-    total_files_copied += n_copied
1169
-    total_size_copied += bytes_saved
1170
-
1171
-    #process files not copied
1172
-    debug("Process files that were not remotely copied")
1173
-    failed_copy_count = len(failed_copy_files)
1174
-    for key in failed_copy_files:
1175
-        failed_copy_files[key]['target_uri'] = destination_base + key
1176
-    status, seq, nb_files, size = _upload(failed_copy_files, seq, src_count + update_count + failed_copy_count)
1177
-    if ret == EX_OK:
1178
-        ret = status
1179
-    total_files_copied += nb_files
1180
-    total_size_copied += size
1181
-
1182
-    # Delete items in destination that are not in source
1183
-    if cfg.delete_removed and cfg.delete_after:
1184
-        subcmd_batch_del(remote_list = dst_list)
1185
-        deleted_count = len(dst_list)
1186
-
1187
-    stats_info.files = orig_src_count
1188
-    stats_info.size = remote_total_size
1189
-    stats_info.files_copied = total_files_copied
1190
-    stats_info.size_copied = total_size_copied
1191
-    stats_info.files_deleted = deleted_count
1192
-
1193
-    total_elapsed = max(1.0, time.time() - timestamp_start)
1194
-    outstr = "Done. Copied %d files in %0.1f seconds, %0.2f files/s." % (total_files_copied, total_elapsed, seq / total_elapsed)
1195
-    if cfg.stats:
1196
-        outstr += stats_info.format_output()
1197
-        output(outstr)
1198
-    elif seq > 0:
1199
-        output(outstr)
1200
-    else:
1201
-        info(outstr)
1202
-
1203
-    return ret
1204
-
1205
-def cmd_sync_remote2local(args):
1206
-    cfg = Config()
1207
-    s3 = S3(cfg)
1208
-
1209
-    def _do_deletes(local_list):
1210
-        total_size = 0
1211
-        if cfg.max_delete > 0 and len(local_list) > cfg.max_delete:
1212
-            warning(u"delete: maximum requested number of deletes would be exceeded, none performed.")
1213
-            return total_size
1214
-        for key in local_list:
1215
-            os.unlink(deunicodise(local_list[key]['full_name']))
1216
-            output(u"delete: '%s'" % local_list[key]['full_name'])
1217
-            total_size += local_list[key].get(u'size', 0)
1218
-        return len(local_list), total_size
1219
-
1220
-    destination_base = args[-1]
1221
-    source_args = args[:-1]
1222
-    fetch_source_args = args[:-1]
1223
-
1224
-    if not destination_base.endswith(os.path.sep):
1225
-        if fetch_source_args[0].endswith(u'/') or len(fetch_source_args) > 1:
1226
-            raise ParameterError("Destination must be a directory and end with '/' when downloading multiple sources.")
1227
-
1228
-    stats_info = StatsInfo()
1229
-
1230
-    remote_list, src_exclude_list, remote_total_size = fetch_remote_list(fetch_source_args, recursive = True, require_attribs = True)
1231
-
1232
-
1233
-    # - The source path is either like "/myPath/my_src_folder" and
1234
-    # the user want to download this single folder and Optionally only delete
1235
-    # things that have been removed inside this folder. For this case, we only
1236
-    # have to look inside destination_base/my_src_folder and not at the root of
1237
-    # destination_base.
1238
-    # - Or like "/myPath/my_src_folder/" and the user want to have the sync
1239
-    # with the content of this folder
1240
-    destbase_with_source_list = set()
1241
-    for source_arg in fetch_source_args:
1242
-        if source_arg.endswith('/'):
1243
-            if destination_base.endswith(os.path.sep):
1244
-                destbase_with_source_list.add(destination_base)
1245
-            else:
1246
-                destbase_with_source_list.add(destination_base + os.path.sep)
1247
-        else:
1248
-            destbase_with_source_list.add(os.path.join(destination_base,
1249
-                                                      os.path.basename(source_arg)))
1250
-    local_list, single_file_local, dst_exclude_list, local_total_size = fetch_local_list(destbase_with_source_list, is_src = False, recursive = True)
1251
-
1252
-    local_count = len(local_list)
1253
-    remote_count = len(remote_list)
1254
-    orig_remote_count = remote_count
1255
-
1256
-    info(u"Found %d remote files, %d local files" % (remote_count, local_count))
1257
-
1258
-    remote_list, local_list, update_list, copy_pairs = compare_filelists(remote_list, local_list, src_remote = True, dst_remote = False)
1259
-
1260
-    local_count = len(local_list)
1261
-    remote_count = len(remote_list)
1262
-    update_count = len(update_list)
1263
-    copy_pairs_count = len(copy_pairs)
1264
-
1265
-    info(u"Summary: %d remote files to download, %d local files to delete, %d local files to hardlink" % (remote_count + update_count, local_count, copy_pairs_count))
1266
-
1267
-    def _set_local_filename(remote_list, destination_base, source_args):
1268
-        if len(remote_list) == 0:
1269
-            return
1270
-
1271
-        if destination_base.endswith(os.path.sep):
1272
-            if not os.path.exists(deunicodise(destination_base)):
1273
-                if not cfg.dry_run:
1274
-                    os.makedirs(deunicodise(destination_base))
1275
-            if not os.path.isdir(deunicodise(destination_base)):
1276
-                raise ParameterError("Destination is not an existing directory")
1277
-        elif len(remote_list) == 1 and \
1278
-             source_args[0] == remote_list[remote_list.keys()[0]].get(u'object_uri_str', ''):
1279
-            if os.path.isdir(deunicodise(destination_base)):
1280
-                raise ParameterError("Destination already exists and is a directory")
1281
-            remote_list[remote_list.keys()[0]]['local_filename'] = destination_base
1282
-            return
1283
-
1284
-        if destination_base[-1] != os.path.sep:
1285
-            destination_base += os.path.sep
1286
-        for key in remote_list:
1287
-            local_filename = destination_base + key
1288
-            if os.path.sep != "/":
1289
-                local_filename = os.path.sep.join(local_filename.split("/"))
1290
-            remote_list[key]['local_filename'] = local_filename
1291
-
1292
-    _set_local_filename(remote_list, destination_base, source_args)
1293
-    _set_local_filename(update_list, destination_base, source_args)
1294
-
1295
-    if cfg.dry_run:
1296
-        keys = filedicts_to_keys(src_exclude_list, dst_exclude_list)
1297
-        for key in keys:
1298
-            output(u"exclude: %s" % key)
1299
-        if cfg.delete_removed:
1300
-            for key in local_list:
1301
-                output(u"delete: '%s'" % local_list[key]['full_name'])
1302
-        for key in remote_list:
1303
-            output(u"download: '%s' -> '%s'" % (remote_list[key]['object_uri_str'], remote_list[key]['local_filename']))
1304
-        for key in update_list:
1305
-            output(u"download: '%s' -> '%s'" % (update_list[key]['object_uri_str'], update_list[key]['local_filename']))
1306
-
1307
-        warning(u"Exiting now because of --dry-run")
1308
-        return EX_OK
1309
-
1310
-    # if there are copy pairs, we can't do delete_before, on the chance
1311
-    # we need one of the to-be-deleted files as a copy source.
1312
-    if len(copy_pairs) > 0:
1313
-        cfg.delete_after = True
1314
-
1315
-    if cfg.delete_removed and orig_remote_count == 0 and len(local_list) and not cfg.force:
1316
-        warning(u"delete: cowardly refusing to delete because no source files were found.  Use --force to override.")
1317
-        cfg.delete_removed = False
1318
-
1319
-    if cfg.delete_removed and not cfg.delete_after:
1320
-        deleted_count, deleted_size = _do_deletes(local_list)
1321
-    else:
1322
-        deleted_count, deleted_size = (0, 0)
1323
-
1324
-    def _download(remote_list, seq, total, total_size, dir_cache):
1325
-        original_umask = os.umask(0)
1326
-        os.umask(original_umask)
1327
-        file_list = remote_list.keys()
1328
-        file_list.sort()
1329
-        ret = EX_OK
1330
-        for file in file_list:
1331
-            seq += 1
1332
-            item = remote_list[file]
1333
-            uri = S3Uri(item['object_uri_str'])
1334
-            dst_file = item['local_filename']
1335
-            is_empty_directory = dst_file.endswith('/')
1336
-            seq_label = "[%d of %d]" % (seq, total)
1337
-
1338
-            dst_dir = unicodise(os.path.dirname(deunicodise(dst_file)))
1339
-            if not dst_dir in dir_cache:
1340
-                dir_cache[dst_dir] = Utils.mkdir_with_parents(dst_dir)
1341
-            if dir_cache[dst_dir] == False:
1342
-                if cfg.stop_on_error:
1343
-                    error(u"Exiting now because of --stop-on-error")
1344
-                    raise OSError("Download of '%s' failed (Reason: %s destination directory is not writable)" % (file, dst_dir))
1345
-                error(u"Download of '%s' failed (Reason: %s destination directory is not writable)" % (file, dst_dir))
1346
-                ret = EX_PARTIAL
1347
-                continue
1348
-
1349
-            try:
1350
-                chkptfname_b = ''
1351
-                if not is_empty_directory: # ignore empty directory at S3:
1352
-                    debug(u"dst_file=%s" % dst_file)
1353
-                    # create temporary files (of type .s3cmd.XXXX.tmp) in the same directory
1354
-                    # for downloading and then rename once downloaded
1355
-                    # unicode provided to mkstemp argument
1356
-                    chkptfd, chkptfname_b = tempfile.mkstemp(u".tmp", u".s3cmd.",
1357
-                                                           os.path.dirname(dst_file))
1358
-                    with io.open(chkptfd, mode='wb') as dst_stream:
1359
-                        dst_stream.stream_name = unicodise(chkptfname_b)
1360
-                        debug(u"created chkptfname=%s" % dst_stream.stream_name)
1361
-                        response = s3.object_get(uri, dst_stream, dst_file, extra_label = seq_label)
1362
-
1363
-                    # download completed, rename the file to destination
1364
-                    if os.name == "nt":
1365
-                        # Windows is really a bad OS. Rename can't overwrite an existing file
1366
-                        try:
1367
-                            os.unlink(deunicodise(dst_file))
1368
-                        except OSError:
1369
-                            pass
1370
-                    os.rename(chkptfname_b, deunicodise(dst_file))
1371
-                    debug(u"renamed chkptfname=%s to dst_file=%s" % (dst_stream.stream_name, dst_file))
1372
-            except OSError as exc:
1373
-                allow_partial = True
1374
-
1375
-                if exc.errno == errno.EISDIR:
1376
-                    error(u"Download of '%s' failed (Reason: %s is a directory)" % (file, dst_file))
1377
-                elif os.name != "nt" and exc.errno == errno.ETXTBSY:
1378
-                    error(u"Download of '%s' failed (Reason: %s is currently open for execute, cannot be overwritten)" % (file, dst_file))
1379
-                elif exc.errno == errno.EPERM or exc.errno == errno.EACCES:
1380
-                    error(u"Download of '%s' failed (Reason: %s permission denied)" % (file, dst_file))
1381
-                elif exc.errno == errno.EBUSY:
1382
-                    error(u"Download of '%s' failed (Reason: %s is busy)" % (file, dst_file))
1383
-                elif exc.errno == errno.EFBIG:
1384
-                    error(u"Download of '%s' failed (Reason: %s is too big)" % (file, dst_file))
1385
-                elif exc.errno == errno.ENAMETOOLONG:
1386
-                    error(u"Download of '%s' failed (Reason: File Name is too long)" % file)
1387
-
1388
-                elif (exc.errno == errno.ENOSPC or (os.name != "nt" and exc.errno == errno.EDQUOT)):
1389
-                    error(u"Download of '%s' failed (Reason: No space left)" % file)
1390
-                    allow_partial = False
1391
-                else:
1392
-                    error(u"Download of '%s' failed (Reason: Unknown OsError %d)" % (file, exc.errno or 0))
1393
-                    allow_partial = False
1394
-
1395
-                try:
1396
-                    # Try to remove the temp file if it exists
1397
-                    if chkptfname_b:
1398
-                        os.unlink(chkptfname_b)
1399
-                except Exception:
1400
-                    pass
1401
-
1402
-                if allow_partial and not cfg.stop_on_error:
1403
-                    ret = EX_PARTIAL
1404
-                    continue
1405
-
1406
-                ret = EX_OSFILE
1407
-                if allow_partial:
1408
-                    error(u"Exiting now because of --stop-on-error")
1409
-                else:
1410
-                    error(u"Exiting now because of fatal error")
1411
-                raise
1412
-            except S3DownloadError as exc:
1413
-                error(u"Download of '%s' failed too many times (Last Reason: %s). "
1414
-                      "This is usually a transient error, please try again "
1415
-                      "later." % (file, exc))
1416
-                try:
1417
-                    os.unlink(chkptfname_b)
1418
-                except Exception as sub_exc:
1419
-                    warning(u"Error deleting temporary file %s (Reason: %s)",
1420
-                            (dst_stream.stream_name, sub_exc))
1421
-                if cfg.stop_on_error:
1422
-                    ret = EX_DATAERR
1423
-                    error(u"Exiting now because of --stop-on-error")
1424
-                    raise
1425
-                ret = EX_PARTIAL
1426
-                continue
1427
-            except S3Error as exc:
1428
-                warning(u"Remote file '%s'. S3Error: %s" % (exc.resource, exc))
1429
-                try:
1430
-                    os.unlink(chkptfname_b)
1431
-                except Exception as sub_exc:
1432
-                    warning(u"Error deleting temporary file %s (Reason: %s)",
1433
-                            (dst_stream.stream_name, sub_exc))
1434
-                if cfg.stop_on_error:
1435
-                    raise
1436
-                ret = EX_PARTIAL
1437
-                continue
1438
-
1439
-            try:
1440
-                # set permissions on destination file
1441
-                if not is_empty_directory: # a normal file
1442
-                    mode = 0o777 - original_umask
1443
-                else:
1444
-                    # an empty directory, make them readable/executable
1445
-                    mode = 0o775
1446
-                debug(u"mode=%s" % oct(mode))
1447
-                os.chmod(deunicodise(dst_file), mode)
1448
-            except:
1449
-                raise
1450
-
1451
-            # because we don't upload empty directories,
1452
-            # we can continue the loop here, we won't be setting stat info.
1453
-            # if we do start to upload empty directories, we'll have to reconsider this.
1454
-            if is_empty_directory:
1455
-                continue
1456
-
1457
-            try:
1458
-                if 's3cmd-attrs' in response and cfg.preserve_attrs:
1459
-                    attrs = response['s3cmd-attrs']
1460
-                    if 'mode' in attrs:
1461
-                        os.chmod(deunicodise(dst_file), int(attrs['mode']))
1462
-                    if 'mtime' in attrs or 'atime' in attrs:
1463
-                        mtime = ('mtime' in attrs) and int(attrs['mtime']) or int(time.time())
1464
-                        atime = ('atime' in attrs) and int(attrs['atime']) or int(time.time())
1465
-                        os.utime(deunicodise(dst_file), (atime, mtime))
1466
-                    if 'uid' in attrs and 'gid' in attrs:
1467
-                        uid = int(attrs['uid'])
1468
-                        gid = int(attrs['gid'])
1469
-                        os.lchown(deunicodise(dst_file),uid,gid)
1470
-                elif 'last-modified' in response['headers']:
1471
-                    last_modified = time.mktime(time.strptime(response["headers"]["last-modified"], "%a, %d %b %Y %H:%M:%S GMT"))
1472
-                    os.utime(deunicodise(dst_file), (last_modified, last_modified))
1473
-                    debug("set mtime to %s" % last_modified)
1474
-            except OSError as e:
1475
-                ret = EX_PARTIAL
1476
-                if e.errno == errno.EEXIST:
1477
-                    warning(u"%s exists - not overwriting" % dst_file)
1478
-                    continue
1479
-                if e.errno in (errno.EPERM, errno.EACCES):
1480
-                    warning(u"%s not writable: %s" % (dst_file, e.strerror))
1481
-                    if cfg.stop_on_error:
1482
-                        raise e
1483
-                    continue
1484
-                raise e
1485
-            except KeyboardInterrupt:
1486
-                warning(u"Exiting after keyboard interrupt")
1487
-                return
1488
-            except Exception as e:
1489
-                ret = EX_PARTIAL
1490
-                error(u"%s: %s" % (file, e))
1491
-                if cfg.stop_on_error:
1492
-                    raise OSError(e)
1493
-                continue
1494
-            finally:
1495
-                try:
1496
-                    os.remove(chkptfname_b)
1497
-                except Exception:
1498
-                    pass
1499
-
1500
-            speed_fmt = formatSize(response["speed"], human_readable = True, floating_point = True)
1501
-            if not Config().progress_meter:
1502
-                output(u"download: '%s' -> '%s' (%d bytes in %0.1f seconds, %0.2f %sB/s) %s" %
1503
-                    (uri, dst_file, response["size"], response["elapsed"], speed_fmt[0], speed_fmt[1],
1504
-                    seq_label))
1505
-            total_size += response["size"]
1506
-            if Config().delete_after_fetch:
1507
-                s3.object_delete(uri)
1508
-                output(u"File '%s' removed after syncing" % (uri))
1509
-        return ret, seq, total_size
1510
-
1511
-    size_transferred = 0
1512
-    total_elapsed = 0.0
1513
-    timestamp_start = time.time()
1514
-    dir_cache = {}
1515
-    seq = 0
1516
-    ret, seq, size_transferred = _download(remote_list, seq, remote_count + update_count, size_transferred, dir_cache)
1517
-    status, seq, size_transferred = _download(update_list, seq, remote_count + update_count, size_transferred, dir_cache)
1518
-    if ret == EX_OK:
1519
-        ret = status
1520
-
1521
-    n_copies, size_copies, failed_copy_list = local_copy(copy_pairs, destination_base)
1522
-    _set_local_filename(failed_copy_list, destination_base, source_args)
1523
-    status, seq, size_transferred = _download(failed_copy_list, seq, len(failed_copy_list) + remote_count + update_count, size_transferred, dir_cache)
1524
-    if ret == EX_OK:
1525
-        ret = status
1526
-
1527
-    if cfg.delete_removed and cfg.delete_after:
1528
-        deleted_count, deleted_size = _do_deletes(local_list)
1529
-
1530
-    total_elapsed = max(1.0, time.time() - timestamp_start)
1531
-    speed_fmt = formatSize(size_transferred / total_elapsed, human_readable = True, floating_point = True)
1532
-
1533
-    stats_info.files = orig_remote_count
1534
-    stats_info.size = remote_total_size
1535
-    stats_info.files_transferred = len(failed_copy_list) + remote_count + update_count
1536
-    stats_info.size_transferred = size_transferred
1537
-    stats_info.files_copied = n_copies
1538
-    stats_info.size_copied = size_copies
1539
-    stats_info.files_deleted = deleted_count
1540
-    stats_info.size_deleted = deleted_size
1541
-
1542
-    # Only print out the result if any work has been done or
1543
-    # if the user asked for verbose output
1544
-    outstr = "Done. Downloaded %d bytes in %0.1f seconds, %0.2f %sB/s." % (size_transferred, total_elapsed, speed_fmt[0], speed_fmt[1])
1545
-    if cfg.stats:
1546
-        outstr += stats_info.format_output()
1547
-        output(outstr)
1548
-    elif size_transferred > 0:
1549
-        output(outstr)
1550
-    else:
1551
-        info(outstr)
1552
-
1553
-    return ret
1554
-
1555
-def local_copy(copy_pairs, destination_base):
1556
-    # Do NOT hardlink local files by default, that'd be silly
1557
-    # For instance all empty files would become hardlinked together!
1558
-    saved_bytes = 0
1559
-    failed_copy_list = FileDict()
1560
-    for (src_obj, dst1, relative_file, md5) in copy_pairs:
1561
-        src_file = os.path.join(destination_base, dst1)
1562
-        dst_file = os.path.join(destination_base, relative_file)
1563
-        dst_dir = os.path.dirname(deunicodise(dst_file))
1564
-        try:
1565
-            if not os.path.isdir(deunicodise(dst_dir)):
1566
-                debug("MKDIR %s" % dst_dir)
1567
-                os.makedirs(deunicodise(dst_dir))
1568
-            debug(u"Copying %s to %s" % (src_file, dst_file))
1569
-            shutil.copy2(deunicodise(src_file), deunicodise(dst_file))
1570
-            saved_bytes += src_obj.get(u'size', 0)
1571
-        except (IOError, OSError) as e:
1572
-            warning(u'Unable to copy or hardlink files %s -> %s (Reason: %s)' % (src_file, dst_file, e))
1573
-            failed_copy_list[relative_file] = src_obj
1574
-    return len(copy_pairs), saved_bytes, failed_copy_list
1575
-
1576
-def remote_copy(s3, copy_pairs, destination_base, uploaded_objects_list=None,
1577
-                metadata_update=False):
1578
-    cfg = Config()
1579
-    saved_bytes = 0
1580
-    failed_copy_list = FileDict()
1581
-    seq = 0
1582
-    src_count = len(copy_pairs)
1583
-    for (src_obj, dst1, dst2, src_md5) in copy_pairs:
1584
-        seq += 1
1585
-        debug(u"Remote Copying from %s to %s" % (dst1, dst2))
1586
-        dst1_uri = S3Uri(destination_base + dst1)
1587
-        dst2_uri = S3Uri(destination_base + dst2)
1588
-        src_obj_size = src_obj.get(u'size', 0)
1589
-        seq_label = "[%d of %d]" % (seq, src_count)
1590
-        extra_headers = copy(cfg.extra_headers)
1591
-        if metadata_update:
1592
-            # source is a real local file with its own personal metadata
1593
-            attr_header = _build_attr_header(src_obj, dst2, src_md5)
1594
-            debug(u"attr_header: %s" % attr_header)
1595
-            extra_headers.update(attr_header)
1596
-            extra_headers['content-type'] = \
1597
-                s3.content_type(filename=src_obj['full_name'])
1598
-        try:
1599
-            s3.object_copy(dst1_uri, dst2_uri, extra_headers,
1600
-                           src_size=src_obj_size,
1601
-                           extra_label=seq_label)
1602
-            output(u"remote copy: '%s' -> '%s'  %s" % (dst1, dst2, seq_label))
1603
-            saved_bytes += src_obj_size
1604
-            if uploaded_objects_list is not None:
1605
-                uploaded_objects_list.append(dst2)
1606
-        except Exception:
1607
-            warning(u"Unable to remote copy files '%s' -> '%s'" % (dst1_uri, dst2_uri))
1608
-            failed_copy_list[dst2] = src_obj
1609
-    return (len(copy_pairs), saved_bytes, failed_copy_list)
1610
-
1611
-def _build_attr_header(src_obj, src_relative_name, md5=None):
1612
-    cfg = Config()
1613
-    attrs = {}
1614
-    if cfg.preserve_attrs:
1615
-        for attr in cfg.preserve_attrs_list:
1616
-            val = None
1617
-            if attr == 'uname':
1618
-                try:
1619
-                    val = Utils.urlencode_string(Utils.getpwuid_username(src_obj['uid']), unicode_output=True)
1620
-                except (KeyError, TypeError):
1621
-                    attr = "uid"
1622
-                    val = src_obj.get('uid')
1623
-                    if val:
1624
-                        warning(u"%s: Owner username not known. Storing UID=%d instead." % (src_relative_name, val))
1625
-            elif attr == 'gname':
1626
-                try:
1627
-                    val = Utils.urlencode_string(Utils.getgrgid_grpname(src_obj.get('gid')), unicode_output=True)
1628
-                except (KeyError, TypeError):
1629
-                    attr = "gid"
1630
-                    val = src_obj.get('gid')
1631
-                    if val:
1632
-                        warning(u"%s: Owner groupname not known. Storing GID=%d instead." % (src_relative_name, val))
1633
-            elif attr != "md5":
1634
-                try:
1635
-                    val = getattr(src_obj['sr'], 'st_' + attr)
1636
-                except Exception:
1637
-                    val = None
1638
-            if val is not None:
1639
-                attrs[attr] = val
1640
-
1641
-    if 'md5' in cfg.preserve_attrs_list and md5:
1642
-        attrs['md5'] = md5
1643
-
1644
-    if attrs:
1645
-        attr_str_list = []
1646
-        for k in sorted(attrs.keys()):
1647
-            attr_str_list.append(u"%s:%s" % (k, attrs[k]))
1648
-        attr_header = {'x-amz-meta-s3cmd-attrs': u'/'.join(attr_str_list)}
1649
-    else:
1650
-        attr_header = {}
1651
-
1652
-    return attr_header
1653
-
1654
-def cmd_sync_local2remote(args):
1655
-    cfg = Config()
1656
-    s3 = S3(cfg)
1657
-
1658
-    def _single_process(source_args):
1659
-        for dest in destinations:
1660
-            ## Normalize URI to convert s3://bkt to s3://bkt/ (trailing slash)
1661
-            destination_base_uri = S3Uri(dest)
1662
-            if destination_base_uri.type != 's3':
1663
-                raise ParameterError("Destination must be S3Uri. Got: %s" % destination_base_uri)
1664
-            destination_base = destination_base_uri.uri()
1665
-        return _child(destination_base, source_args)
1666
-
1667
-    def _parent(source_args):
1668
-        # Now that we've done all the disk I/O to look at the local file system and
1669
-        # calculate the md5 for each file, fork for each destination to upload to them separately
1670
-        # and in parallel
1671
-        child_pids = []
1672
-        ret = EX_OK
1673
-
1674
-        for dest in destinations:
1675
-            ## Normalize URI to convert s3://bkt to s3://bkt/ (trailing slash)
1676
-            destination_base_uri = S3Uri(dest)
1677
-            if destination_base_uri.type != 's3':
1678
-                raise ParameterError("Destination must be S3Uri. Got: %s" % destination_base_uri)
1679
-            destination_base = destination_base_uri.uri()
1680
-            child_pid = os.fork()
1681
-            if child_pid == 0:
1682
-                os._exit(_child(destination_base, source_args))
1683
-            else:
1684
-                child_pids.append(child_pid)
1685
-
1686
-        while len(child_pids):
1687
-            (pid, status) = os.wait()
1688
-            child_pids.remove(pid)
1689
-            if ret == EX_OK:
1690
-                ret = os.WEXITSTATUS(status)
1691
-
1692
-        return ret
1693
-
1694
-    def _child(destination_base, source_args):
1695
-        def _set_remote_uri(local_list, destination_base, single_file_local):
1696
-            if len(local_list) > 0:
1697
-                ## Populate 'remote_uri' only if we've got something to upload
1698
-                if not destination_base.endswith("/"):
1699
-                    if not single_file_local:
1700
-                        raise ParameterError("Destination S3 URI must end with '/' (ie must refer to a directory on the remote side).")
1701
-                    local_list[local_list.keys()[0]]['remote_uri'] = destination_base
1702
-                else:
1703
-                    for key in local_list:
1704
-                        local_list[key]['remote_uri'] = destination_base + key
1705
-
1706
-        def _upload(local_list, seq, total, total_size):
1707
-            file_list = local_list.keys()
1708
-            file_list.sort()
1709
-            ret = EX_OK
1710
-            for file in file_list:
1711
-                seq += 1
1712
-                item = local_list[file]
1713
-                src = item['full_name']
1714
-                try:
1715
-                    src_md5 = local_list.get_md5(file)
1716
-                except IOError:
1717
-                    src_md5 = None
1718
-                uri = S3Uri(item['remote_uri'])
1719
-                seq_label = "[%d of %d]" % (seq, total)
1720
-                extra_headers = copy(cfg.extra_headers)
1721
-                try:
1722
-                    attr_header = _build_attr_header(local_list[file],
1723
-                                                     file, src_md5)
1724
-                    debug(u"attr_header: %s" % attr_header)
1725
-                    extra_headers.update(attr_header)
1726
-                    response = s3.object_put(src, uri, extra_headers, extra_label = seq_label)
1727
-                except S3UploadError as exc:
1728
-                    error(u"Upload of '%s' failed too many times (Last reason: %s)" % (item['full_name'], exc))
1729
-                    if cfg.stop_on_error:
1730
-                        ret = EX_DATAERR
1731
-                        error(u"Exiting now because of --stop-on-error")
1732
-                        raise
1733
-                    ret = EX_PARTIAL
1734
-                    continue
1735
-                except InvalidFileError as exc:
1736
-                    error(u"Upload of '%s' is not possible (Reason: %s)" % (item['full_name'], exc))
1737
-                    ret = EX_PARTIAL
1738
-                    if cfg.stop_on_error:
1739
-                        ret = EX_OSFILE
1740
-                        error(u"Exiting now because of --stop-on-error")
1741
-                        raise
1742
-                    continue
1743
-                speed_fmt = formatSize(response["speed"], human_readable = True, floating_point = True)
1744
-                if not cfg.progress_meter:
1745
-                    output(u"upload: '%s' -> '%s' (%d bytes in %0.1f seconds, %0.2f %sB/s) %s" %
1746
-                        (item['full_name'], uri, response["size"], response["elapsed"],
1747
-                        speed_fmt[0], speed_fmt[1], seq_label))
1748
-                total_size += response["size"]
1749
-                uploaded_objects_list.append(uri.object())
1750
-            return ret, seq, total_size
1751
-
1752
-
1753
-        stats_info = StatsInfo()
1754
-
1755
-        local_list, single_file_local, src_exclude_list, local_total_size = fetch_local_list(args[:-1], is_src = True, recursive = True)
1756
-
1757
-        # - The source path is either like "/myPath/my_src_folder" and
1758
-        # the user want to upload this single folder and optionally only delete
1759
-        # things that have been removed inside this folder. For this case,
1760
-        # we only have to look inside destination_base/my_src_folder and not at
1761
-        # the root of destination_base.
1762
-        # - Or like "/myPath/my_src_folder/" and the user want to have the sync
1763
-        # with the content of this folder
1764
-        # Special case, "." for current folder.
1765
-        destbase_with_source_list = set()
1766
-        for source_arg in source_args:
1767
-            if not source_arg.endswith('/') and os.path.basename(source_arg) != '.' \
1768
-               and not single_file_local:
1769
-                destbase_with_source_list.add(os.path.join(destination_base,
1770
-                                                    os.path.basename(source_arg)))
1771
-            else:
1772
-                destbase_with_source_list.add(destination_base)
1773
-
1774
-        remote_list, dst_exclude_list, remote_total_size = fetch_remote_list(destbase_with_source_list, recursive = True, require_attribs = True)
1775
-
1776
-        local_count = len(local_list)
1777
-        orig_local_count = local_count
1778
-        remote_count = len(remote_list)
1779
-
1780
-        info(u"Found %d local files, %d remote files" % (local_count, remote_count))
1781
-
1782
-        if single_file_local and len(local_list) == 1 and len(remote_list) == 1:
1783
-            ## Make remote_key same as local_key for comparison if we're dealing with only one file
1784
-            remote_list_entry = remote_list[remote_list.keys()[0]]
1785
-            # Flush remote_list, by the way
1786
-            remote_list = FileDict()
1787
-            remote_list[local_list.keys()[0]] =  remote_list_entry
1788
-
1789
-        local_list, remote_list, update_list, copy_pairs = compare_filelists(local_list, remote_list, src_remote = False, dst_remote = True)
1790
-
1791
-        local_count = len(local_list)
1792
-        update_count = len(update_list)
1793
-        copy_count = len(copy_pairs)
1794
-        remote_count = len(remote_list)
1795
-        upload_count = local_count + update_count
1796
-
1797
-        info(u"Summary: %d local files to upload, %d files to remote copy, %d remote files to delete" % (upload_count, copy_count, remote_count))
1798
-
1799
-        _set_remote_uri(local_list, destination_base, single_file_local)
1800
-        _set_remote_uri(update_list, destination_base, single_file_local)
1801
-
1802
-        if cfg.dry_run:
1803
-            keys = filedicts_to_keys(src_exclude_list, dst_exclude_list)
1804
-            for key in keys:
1805
-                output(u"exclude: %s" % key)
1806
-            for key in local_list:
1807
-                output(u"upload: '%s' -> '%s'" % (local_list[key]['full_name'], local_list[key]['remote_uri']))
1808
-            for key in update_list:
1809
-                output(u"upload: '%s' -> '%s'" % (update_list[key]['full_name'], update_list[key]['remote_uri']))
1810
-            for (src_obj, dst1, dst2, md5) in copy_pairs:
1811
-                output(u"remote copy: '%s' -> '%s'" % (dst1, dst2))
1812
-            if cfg.delete_removed:
1813
-                for key in remote_list:
1814
-                    output(u"delete: '%s'" % remote_list[key]['object_uri_str'])
1815
-
1816
-            warning(u"Exiting now because of --dry-run")
1817
-            return EX_OK
1818
-
1819
-        # if there are copy pairs, we can't do delete_before, on the chance
1820
-        # we need one of the to-be-deleted files as a copy source.
1821
-        if len(copy_pairs) > 0:
1822
-            cfg.delete_after = True
1823
-
1824
-        if cfg.delete_removed and orig_local_count == 0 and len(remote_list) and not cfg.force:
1825
-            warning(u"delete: cowardly refusing to delete because no source files were found.  Use --force to override.")
1826
-            cfg.delete_removed = False
1827
-
1828
-        if cfg.delete_removed and not cfg.delete_after and remote_list:
1829
-            subcmd_batch_del(remote_list = remote_list)
1830
-
1831
-        size_transferred = 0
1832
-        total_elapsed = 0.0
1833
-        timestamp_start = time.time()
1834
-        ret, n, size_transferred = _upload(local_list, 0, upload_count, size_transferred)
1835
-        status, n, size_transferred = _upload(update_list, n, upload_count, size_transferred)
1836
-        if ret == EX_OK:
1837
-            ret = status
1838
-        # uploaded_objects_list reference is passed so it can be filled with
1839
-        # destination object of succcessful copies so that they can be
1840
-        # invalidated by cf
1841
-        n_copies, saved_bytes, failed_copy_files  = remote_copy(
1842
-            s3, copy_pairs, destination_base, uploaded_objects_list, True)
1843
-
1844
-        #upload file that could not be copied
1845
-        debug("Process files that were not remotely copied")
1846
-        failed_copy_count = len(failed_copy_files)
1847
-        _set_remote_uri(failed_copy_files, destination_base, single_file_local)
1848
-        status, n, size_transferred = _upload(failed_copy_files, n, upload_count + failed_copy_count, size_transferred)
1849
-        if ret == EX_OK:
1850
-            ret = status
1851
-
1852
-        if cfg.delete_removed and cfg.delete_after and remote_list:
1853
-            subcmd_batch_del(remote_list = remote_list)
1854
-        total_elapsed = max(1.0, time.time() - timestamp_start)
1855
-        total_speed = total_elapsed and size_transferred / total_elapsed or 0.0
1856
-        speed_fmt = formatSize(total_speed, human_readable = True, floating_point = True)
1857
-
1858
-
1859
-        stats_info.files = orig_local_count
1860
-        stats_info.size = local_total_size
1861
-        stats_info.files_transferred = upload_count + failed_copy_count
1862
-        stats_info.size_transferred = size_transferred
1863
-        stats_info.files_copied = n_copies
1864
-        stats_info.size_copied = saved_bytes
1865
-        stats_info.files_deleted = remote_count
1866
-
1867
-
1868
-        # Only print out the result if any work has been done or
1869
-        # if the user asked for verbose output
1870
-        outstr = "Done. Uploaded %d bytes in %0.1f seconds, %0.2f %sB/s." % (size_transferred, total_elapsed, speed_fmt[0], speed_fmt[1])
1871
-        if cfg.stats:
1872
-            outstr += stats_info.format_output()
1873
-            output(outstr)
1874
-        elif size_transferred + saved_bytes > 0:
1875
-            output(outstr)
1876
-        else:
1877
-            info(outstr)
1878
-
1879
-        return ret
1880
-
1881
-    def _invalidate_on_cf(destination_base_uri):
1882
-        cf = CloudFront(cfg)
1883
-        default_index_file = None
1884
-        if cfg.invalidate_default_index_on_cf or cfg.invalidate_default_index_root_on_cf:
1885
-            info_response = s3.website_info(destination_base_uri, cfg.bucket_location)
1886
-            if info_response:
1887
-              default_index_file = info_response['index_document']
1888
-              if len(default_index_file) < 1:
1889
-                  default_index_file = None
1890
-
1891
-        results = cf.InvalidateObjects(destination_base_uri, uploaded_objects_list, default_index_file, cfg.invalidate_default_index_on_cf, cfg.invalidate_default_index_root_on_cf)
1892
-        for result in results:
1893
-            if result['status'] == 201:
1894
-                output(u"Created invalidation request for %d paths" % len(uploaded_objects_list))
1895
-                output(u"Check progress with: s3cmd cfinvalinfo cf://%s/%s" % (result['dist_id'], result['request_id']))
1896
-
1897
-    # main execution
1898
-    uploaded_objects_list = []
1899
-
1900
-    if cfg.encrypt:
1901
-        error(u"S3cmd 'sync' doesn't yet support GPG encryption, sorry.")
1902
-        error(u"Either use unconditional 's3cmd put --recursive'")
1903
-        error(u"or disable encryption with --no-encrypt parameter.")
1904
-        sys.exit(EX_USAGE)
1905
-
1906
-    for arg in args[:-1]:
1907
-        if not os.path.exists(deunicodise(arg)):
1908
-            raise ParameterError("Invalid source: '%s' is not an existing file or directory" % arg)
1909
-
1910
-    destinations = [args[-1]]
1911
-    if cfg.additional_destinations:
1912
-        destinations = destinations + cfg.additional_destinations
1913
-
1914
-    if 'fork' not in os.__all__ or len(destinations) < 2:
1915
-        ret = _single_process(args[:-1])
1916
-        destination_base_uri = S3Uri(destinations[-1])
1917
-        if cfg.invalidate_on_cf:
1918
-            if len(uploaded_objects_list) == 0:
1919
-                info("Nothing to invalidate in CloudFront")
1920
-            else:
1921
-                _invalidate_on_cf(destination_base_uri)
1922
-    else:
1923
-        ret = _parent(args[:-1])
1924
-        if cfg.invalidate_on_cf:
1925
-            error(u"You cannot use both --cf-invalidate and --add-destination.")
1926
-            return(EX_USAGE)
1927
-
1928
-    return ret
1929
-
1930
-def cmd_sync(args):
1931
-    cfg = Config()
1932
-    if (len(args) < 2):
1933
-        raise ParameterError("Too few parameters! Expected: %s" % commands['sync']['param'])
1934
-    if cfg.delay_updates:
1935
-        warning(u"`delay-updates` is obsolete.")
1936
-
1937
-    for arg in args:
1938
-        if arg == u'-':
1939
-            raise ParameterError("Stdin or stdout ('-') can't be used for a source or a destination with the sync command.")
1940
-
1941
-    if S3Uri(args[0]).type == "file" and S3Uri(args[-1]).type == "s3":
1942
-        return cmd_sync_local2remote(args)
1943
-    if S3Uri(args[0]).type == "s3" and S3Uri(args[-1]).type == "file":
1944
-        return cmd_sync_remote2local(args)
1945
-    if S3Uri(args[0]).type == "s3" and S3Uri(args[-1]).type == "s3":
1946
-        return cmd_sync_remote2remote(args)
1947
-    raise ParameterError("Invalid source/destination: '%s'" % "' '".join(args))
1948
-
1949
-def cmd_setacl(args):
1950
-    cfg = Config()
1951
-    s3 = S3(cfg)
1952
-
1953
-    set_to_acl = cfg.acl_public and "Public" or "Private"
1954
-
1955
-    if not cfg.recursive:
1956
-        old_args = args
1957
-        args = []
1958
-        for arg in old_args:
1959
-            uri = S3Uri(arg)
1960
-            if not uri.has_object():
1961
-                if cfg.acl_public != None:
1962
-                    info("Setting bucket-level ACL for %s to %s" % (uri.uri(), set_to_acl))
1963
-                else:
1964
-                    info("Setting bucket-level ACL for %s" % (uri.uri()))
1965
-                if not cfg.dry_run:
1966
-                    update_acl(s3, uri)
1967
-            else:
1968
-                args.append(arg)
1969
-
1970
-    remote_list, exclude_list, _ = fetch_remote_list(args)
1971
-
1972
-    remote_count = len(remote_list)
1973
-
1974
-    info(u"Summary: %d remote files to update" % remote_count)
1975
-
1976
-    if cfg.dry_run:
1977
-        for key in exclude_list:
1978
-            output(u"exclude: %s" % key)
1979
-        for key in remote_list:
1980
-            output(u"setacl: '%s'" % remote_list[key]['object_uri_str'])
1981
-
1982
-        warning(u"Exiting now because of --dry-run")
1983
-        return EX_OK
1984
-
1985
-    seq = 0
1986
-    for key in remote_list:
1987
-        seq += 1
1988
-        seq_label = "[%d of %d]" % (seq, remote_count)
1989
-        uri = S3Uri(remote_list[key]['object_uri_str'])
1990
-        update_acl(s3, uri, seq_label)
1991
-    return EX_OK
1992
-
1993
-def cmd_setpolicy(args):
1994
-    cfg = Config()
1995
-    s3 = S3(cfg)
1996
-    uri = S3Uri(args[1])
1997
-    policy_file = args[0]
1998
-
1999
-    with open(deunicodise(policy_file), 'r') as fp:
2000
-        policy = fp.read()
2001
-
2002
-    if cfg.dry_run:
2003
-        return EX_OK
2004
-
2005
-    response = s3.set_policy(uri, policy)
2006
-
2007
-    #if retsponse['status'] == 200:
2008
-    debug(u"response - %s" % response['status'])
2009
-    if response['status'] == 204:
2010
-        output(u"%s: Policy updated" % uri)
2011
-    return EX_OK
2012
-
2013
-def cmd_delpolicy(args):
2014
-    cfg = Config()
2015
-    s3 = S3(cfg)
2016
-    uri = S3Uri(args[0])
2017
-    if cfg.dry_run: return EX_OK
2018
-
2019
-    response = s3.delete_policy(uri)
2020
-
2021
-    #if retsponse['status'] == 200:
2022
-    debug(u"response - %s" % response['status'])
2023
-    output(u"%s: Policy deleted" % uri)
2024
-    return EX_OK
2025
-
2026
-def cmd_setcors(args):
2027
-    cfg = Config()
2028
-    s3 = S3(cfg)
2029
-    uri = S3Uri(args[1])
2030
-    cors_file = args[0]
2031
-
2032
-    with open(deunicodise(cors_file), 'r') as fp:
2033
-        cors = fp.read()
2034
-
2035
-    if cfg.dry_run:
2036
-        return EX_OK
2037
-
2038
-    response = s3.set_cors(uri, cors)
2039
-
2040
-    #if retsponse['status'] == 200:
2041
-    debug(u"response - %s" % response['status'])
2042
-    if response['status'] == 204:
2043
-        output(u"%s: CORS updated" % uri)
2044
-    return EX_OK
2045
-
2046
-def cmd_delcors(args):
2047
-    cfg = Config()
2048
-    s3 = S3(cfg)
2049
-    uri = S3Uri(args[0])
2050
-    if cfg.dry_run: return EX_OK
2051
-
2052
-    response = s3.delete_cors(uri)
2053
-
2054
-    #if retsponse['status'] == 200:
2055
-    debug(u"response - %s" % response['status'])
2056
-    output(u"%s: CORS deleted" % uri)
2057
-    return EX_OK
2058
-
2059
-def cmd_set_payer(args):
2060
-    cfg = Config()
2061
-    s3 = S3(cfg)
2062
-    uri = S3Uri(args[0])
2063
-
2064
-    if cfg.dry_run: return EX_OK
2065
-
2066
-    response = s3.set_payer(uri)
2067
-    if response['status'] == 200:
2068
-        output(u"%s: Payer updated" % uri)
2069
-        return EX_OK
2070
-    else:
2071
-        output(u"%s: Payer NOT updated" % uri)
2072
-        return EX_CONFLICT
2073
-
2074
-def cmd_setlifecycle(args):
2075
-    cfg = Config()
2076
-    s3 = S3(cfg)
2077
-    uri = S3Uri(args[1])
2078
-    lifecycle_policy_file = args[0]
2079
-
2080
-    with open(deunicodise(lifecycle_policy_file), 'r') as fp:
2081
-        lifecycle_policy = fp.read()
2082
-
2083
-    if cfg.dry_run:
2084
-        return EX_OK
2085
-
2086
-    response = s3.set_lifecycle_policy(uri, lifecycle_policy)
2087
-
2088
-    debug(u"response - %s" % response['status'])
2089
-    if response['status'] == 200:
2090
-        output(u"%s: Lifecycle Policy updated" % uri)
2091
-    return EX_OK
2092
-
2093
-def cmd_getlifecycle(args):
2094
-    cfg = Config()
2095
-    s3 = S3(cfg)
2096
-    uri = S3Uri(args[0])
2097
-
2098
-    response = s3.get_lifecycle_policy(uri)
2099
-
2100
-    output(u"%s" % getPrettyFromXml(response['data']))
2101
-    return EX_OK
2102
-
2103
-def cmd_dellifecycle(args):
2104
-    cfg = Config()
2105
-    s3 = S3(cfg)
2106
-    uri = S3Uri(args[0])
2107
-    if cfg.dry_run: return EX_OK
2108
-
2109
-    response = s3.delete_lifecycle_policy(uri)
2110
-
2111
-    debug(u"response - %s" % response['status'])
2112
-    output(u"%s: Lifecycle Policy deleted" % uri)
2113
-    return EX_OK
2114
-
2115
-def cmd_multipart(args):
2116
-    cfg = Config()
2117
-    s3 = S3(cfg)
2118
-    uri = S3Uri(args[0])
2119
-
2120
-    #id = ''
2121
-    #if(len(args) > 1): id = args[1]
2122
-
2123
-    upload_list = s3.get_multipart(uri)
2124
-    output(u"%s" % uri)
2125
-    debug(upload_list)
2126
-    output(u"Initiated\tPath\tId")
2127
-    for mpupload in upload_list:
2128
-        try:
2129
-            output(u"%s\t%s\t%s" % (
2130
-                mpupload['Initiated'],
2131
-                "s3://" + uri.bucket() + "/" + mpupload['Key'],
2132
-                mpupload['UploadId']))
2133
-        except KeyError:
2134
-            pass
2135
-    return EX_OK
2136
-
2137
-def cmd_abort_multipart(args):
2138
-    '''{"cmd":"abortmp",   "label":"abort a multipart upload", "param":"s3://BUCKET Id", "func":cmd_abort_multipart, "argc":2},'''
2139
-    cfg = Config()
2140
-    s3 = S3(cfg)
2141
-    uri = S3Uri(args[0])
2142
-    id = args[1]
2143
-    response = s3.abort_multipart(uri, id)
2144
-    debug(u"response - %s" % response['status'])
2145
-    output(u"%s" % uri)
2146
-    return EX_OK
2147
-
2148
-def cmd_list_multipart(args):
2149
-    '''{"cmd":"abortmp",   "label":"list a multipart upload", "param":"s3://BUCKET Id", "func":cmd_list_multipart, "argc":2},'''
2150
-    cfg = Config()
2151
-    s3 = S3(cfg)
2152
-    uri = S3Uri(args[0])
2153
-    id = args[1]
2154
-
2155
-    part_list = s3.list_multipart(uri, id)
2156
-    output(u"LastModified\t\t\tPartNumber\tETag\tSize")
2157
-    for mpupload in part_list:
2158
-        try:
2159
-            output(u"%s\t%s\t%s\t%s" % (mpupload['LastModified'],
2160
-                                        mpupload['PartNumber'],
2161
-                                        mpupload['ETag'],
2162
-                                        mpupload['Size']))
2163
-        except KeyError:
2164
-            pass
2165
-    return EX_OK
2166
-
2167
-def cmd_accesslog(args):
2168
-    cfg = Config()
2169
-    s3 = S3(cfg)
2170
-    bucket_uri = S3Uri(args.pop())
2171
-    if bucket_uri.object():
2172
-        raise ParameterError("Only bucket name is required for [accesslog] command")
2173
-    if cfg.log_target_prefix == False:
2174
-        accesslog, response = s3.set_accesslog(bucket_uri, enable = False)
2175
-    elif cfg.log_target_prefix:
2176
-        log_target_prefix_uri = S3Uri(cfg.log_target_prefix)
2177
-        if log_target_prefix_uri.type != "s3":
2178
-            raise ParameterError("--log-target-prefix must be a S3 URI")
2179
-        accesslog, response = s3.set_accesslog(bucket_uri, enable = True, log_target_prefix_uri = log_target_prefix_uri, acl_public = cfg.acl_public)
2180
-    else:   # cfg.log_target_prefix == None
2181
-        accesslog = s3.get_accesslog(bucket_uri)
2182
-
2183
-    output(u"Access logging for: %s" % bucket_uri.uri())
2184
-    output(u"   Logging Enabled: %s" % accesslog.isLoggingEnabled())
2185
-    if accesslog.isLoggingEnabled():
2186
-        output(u"     Target prefix: %s" % accesslog.targetPrefix().uri())
2187
-        #output(u"   Public Access:   %s" % accesslog.isAclPublic())
2188
-    return EX_OK
2189
-
2190
-def cmd_sign(args):
2191
-    string_to_sign = args.pop()
2192
-    debug(u"string-to-sign: %r" % string_to_sign)
2193
-    signature = Crypto.sign_string_v2(encode_to_s3(string_to_sign))
2194
-    output(u"Signature: %s" % decode_from_s3(signature))
2195
-    return EX_OK
2196
-
2197
-def cmd_signurl(args):
2198
-    expiry = args.pop()
2199
-    url_to_sign = S3Uri(args.pop())
2200
-    if url_to_sign.type != 's3':
2201
-        raise ParameterError("Must be S3Uri. Got: %s" % url_to_sign)
2202
-    debug("url to sign: %r" % url_to_sign)
2203
-    signed_url = Crypto.sign_url_v2(url_to_sign, expiry)
2204
-    output(signed_url)
2205
-    return EX_OK
2206
-
2207
-def cmd_fixbucket(args):
2208
-    def _unescape(text):
2209
-        ##
2210
-        # Removes HTML or XML character references and entities from a text string.
2211
-        #
2212
-        # @param text The HTML (or XML) source text.
2213
-        # @return The plain text, as a Unicode string, if necessary.
2214
-        #
2215
-        # From: http://effbot.org/zone/re-sub.htm#unescape-html
2216
-        def _unescape_fixup(m):
2217
-            text = m.group(0)
2218
-            if not 'apos' in htmlentitydefs.name2codepoint:
2219
-                htmlentitydefs.name2codepoint['apos'] = ord("'")
2220
-            if text[:2] == "&#":
2221
-                # character reference
2222
-                try:
2223
-                    if text[:3] == "&#x":
2224
-                        return unichr(int(text[3:-1], 16))
2225
-                    else:
2226
-                        return unichr(int(text[2:-1]))
2227
-                except ValueError:
2228
-                    pass
2229
-            else:
2230
-                # named entity
2231
-                try:
2232
-                    text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
2233
-                except KeyError:
2234
-                    pass
2235
-            return text # leave as is
2236
-            text = text.encode('ascii', 'xmlcharrefreplace')
2237
-        return re.sub("&#?\w+;", _unescape_fixup, text)
2238
-
2239
-    cfg = Config()
2240
-    cfg.urlencoding_mode = "fixbucket"
2241
-    s3 = S3(cfg)
2242
-
2243
-    count = 0
2244
-    for arg in args:
2245
-        culprit = S3Uri(arg)
2246
-        if culprit.type != "s3":
2247
-            raise ParameterError("Expecting S3Uri instead of: %s" % arg)
2248
-        response = s3.bucket_list_noparse(culprit.bucket(), culprit.object(), recursive = True)
2249
-        r_xent = re.compile("&#x[\da-fA-F]+;")
2250
-        keys = re.findall("<Key>(.*?)</Key>", response['data'], re.MULTILINE | re.UNICODE)
2251
-        debug("Keys: %r" % keys)
2252
-        for key in keys:
2253
-            if r_xent.search(key):
2254
-                info("Fixing: %s" % key)
2255
-                debug("Step 1: Transforming %s" % key)
2256
-                key_bin = _unescape(key)
2257
-                debug("Step 2:       ... to %s" % key_bin)
2258
-                key_new = replace_nonprintables(key_bin)
2259
-                debug("Step 3:  ... then to %s" % key_new)
2260
-                src = S3Uri("s3://%s/%s" % (culprit.bucket(), key_bin))
2261
-                dst = S3Uri("s3://%s/%s" % (culprit.bucket(), key_new))
2262
-                if cfg.dry_run:
2263
-                    output(u"[--dry-run] File %r would be renamed to %s" % (key_bin, key_new))
2264
-                    continue
2265
-                try:
2266
-                    resp_move = s3.object_move(src, dst)
2267
-                    if resp_move['status'] == 200:
2268
-                        output(u"File '%r' renamed to '%s'" % (key_bin, key_new))
2269
-                        count += 1
2270
-                    else:
2271
-                        error(u"Something went wrong for: %r" % key)
2272
-                        error(u"Please report the problem to s3tools-bugs@lists.sourceforge.net")
2273
-                except S3Error:
2274
-                    error(u"Something went wrong for: %r" % key)
2275
-                    error(u"Please report the problem to s3tools-bugs@lists.sourceforge.net")
2276
-
2277
-    if count > 0:
2278
-        warning(u"Fixed %d files' names. Their ACL were reset to Private." % count)
2279
-        warning(u"Use 's3cmd setacl --acl-public s3://...' to make")
2280
-        warning(u"them publicly readable if required.")
2281
-    return EX_OK
2282
-
2283
-def resolve_list(lst, args):
2284
-    retval = []
2285
-    for item in lst:
2286
-        retval.append(item % args)
2287
-    return retval
2288
-
2289
-def gpg_command(command, passphrase = ""):
2290
-    debug(u"GPG command: " + " ".join(command))
2291
-    command = [deunicodise(cmd_entry) for cmd_entry in command]
2292
-    p = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT,
2293
-                         close_fds = True)
2294
-    p_stdout, p_stderr = p.communicate(deunicodise(passphrase + "\n"))
2295
-    debug(u"GPG output:")
2296
-    for line in unicodise(p_stdout).split("\n"):
2297
-        debug(u"GPG: " + line)
2298
-    p_exitcode = p.wait()
2299
-    return p_exitcode
2300
-
2301
-def gpg_encrypt(filename):
2302
-    cfg = Config()
2303
-    tmp_filename = Utils.mktmpfile()
2304
-    args = {
2305
-        "gpg_command" : cfg.gpg_command,
2306
-        "passphrase_fd" : "0",
2307
-        "input_file" : filename,
2308
-        "output_file" : tmp_filename,
2309
-    }
2310
-    info(u"Encrypting file %s to %s..." % (filename, tmp_filename))
2311
-    command = resolve_list(cfg.gpg_encrypt.split(" "), args)
2312
-    code = gpg_command(command, cfg.gpg_passphrase)
2313
-    return (code, tmp_filename, "gpg")
2314
-
2315
-def gpg_decrypt(filename, gpgenc_header = "", in_place = True):
2316
-    cfg = Config()
2317
-    tmp_filename = Utils.mktmpfile(filename)
2318
-    args = {
2319
-        "gpg_command" : cfg.gpg_command,
2320
-        "passphrase_fd" : "0",
2321
-        "input_file" : filename,
2322
-        "output_file" : tmp_filename,
2323
-    }
2324
-    info(u"Decrypting file %s to %s..." % (filename, tmp_filename))
2325
-    command = resolve_list(cfg.gpg_decrypt.split(" "), args)
2326
-    code = gpg_command(command, cfg.gpg_passphrase)
2327
-    if code == 0 and in_place:
2328
-        debug(u"Renaming %s to %s" % (tmp_filename, filename))
2329
-        os.unlink(deunicodise(filename))
2330
-        os.rename(deunicodise(tmp_filename), deunicodise(filename))
2331
-        tmp_filename = filename
2332
-    return (code, tmp_filename)
2333
-
2334
-def run_configure(config_file, args):
2335
-    cfg = Config()
2336
-    options = [
2337
-        ("access_key", "Access Key", "Access key and Secret key are your identifiers for Amazon S3. Leave them empty for using the env variables."),
2338
-        ("secret_key", "Secret Key"),
2339
-        ("bucket_location", "Default Region"),
2340
-        ("host_base", "S3 Endpoint", "Use \"s3.amazonaws.com\" for S3 Endpoint and not modify it to the target Amazon S3."),
2341
-        ("host_bucket", "DNS-style bucket+hostname:port template for accessing a bucket", "Use \"%(bucket)s.s3.amazonaws.com\" to the target Amazon S3. \"%(bucket)s\" and \"%(location)s\" vars can be used\nif the target S3 system supports dns based buckets."),
2342
-        ("gpg_passphrase", "Encryption password", "Encryption password is used to protect your files from reading\nby unauthorized persons while in transfer to S3"),
2343
-        ("gpg_command", "Path to GPG program"),
2344
-        ("use_https", "Use HTTPS protocol", "When using secure HTTPS protocol all communication with Amazon S3\nservers is protected from 3rd party eavesdropping. This method is\nslower than plain HTTP, and can only be proxied with Python 2.7 or newer"),
2345
-        ("proxy_host", "HTTP Proxy server name", "On some networks all internet access must go through a HTTP proxy.\nTry setting it here if you can't connect to S3 directly"),
2346
-        ("proxy_port", "HTTP Proxy server port"),
2347
-        ]
2348
-    ## Option-specfic defaults
2349
-    if getattr(cfg, "gpg_command") == "":
2350
-        setattr(cfg, "gpg_command", which("gpg"))
2351
-
2352
-    if getattr(cfg, "proxy_host") == "" and os.getenv("http_proxy"):
2353
-        autodetected_encoding = locale.getpreferredencoding() or "UTF-8"
2354
-        re_match=re.match("(http://)?([^:]+):(\d+)",
2355
-                          unicodise_s(os.getenv("http_proxy"), autodetected_encoding))
2356
-        if re_match:
2357
-            setattr(cfg, "proxy_host", re_match.groups()[1])
2358
-            setattr(cfg, "proxy_port", re_match.groups()[2])
2359
-
2360
-    try:
2361
-        # Support for python3
2362
-        # raw_input only exists in py2 and was renamed to input in py3
2363
-        global input
2364
-        input = raw_input
2365
-    except NameError:
2366
-        pass
2367
-
2368
-    try:
2369
-        while True:
2370
-            output(u"\nEnter new values or accept defaults in brackets with Enter.")
2371
-            output(u"Refer to user manual for detailed description of all options.")
2372
-            for option in options:
2373
-                prompt = option[1]
2374
-                ## Option-specific handling
2375
-                if option[0] == 'proxy_host' and getattr(cfg, 'use_https') == True and sys.hexversion < 0x02070000:
2376
-                    setattr(cfg, option[0], "")
2377
-                    continue
2378
-                if option[0] == 'proxy_port' and getattr(cfg, 'proxy_host') == "":
2379
-                    setattr(cfg, option[0], 0)
2380
-                    continue
2381
-
2382
-                try:
2383
-                    val = getattr(cfg, option[0])
2384
-                    if type(val) is bool:
2385
-                        val = val and "Yes" or "No"
2386
-                    if val not in (None, ""):
2387
-                        prompt += " [%s]" % val
2388
-                except AttributeError:
2389
-                    pass
2390
-
2391
-                if len(option) >= 3:
2392
-                    output(u"\n%s" % option[2])
2393
-
2394
-                val = unicodise_s(input(prompt + ": "))
2395
-                if val != "":
2396
-                    if type(getattr(cfg, option[0])) is bool:
2397
-                        # Turn 'Yes' into True, everything else into False
2398
-                        val = val.lower().startswith('y')
2399
-                    setattr(cfg, option[0], val)
2400
-            output(u"\nNew settings:")
2401
-            for option in options:
2402
-                output(u"  %s: %s" % (option[1], getattr(cfg, option[0])))
2403
-            val = input("\nTest access with supplied credentials? [Y/n] ")
2404
-            if val.lower().startswith("y") or val == "":
2405
-                try:
2406
-                    # Default, we try to list 'all' buckets which requires
2407
-                    # ListAllMyBuckets permission
2408
-                    if len(args) == 0:
2409
-                        output(u"Please wait, attempting to list all buckets...")
2410
-                        S3(Config()).bucket_list("", "")
2411
-                    else:
2412
-                        # If user specified a bucket name directly, we check it and only it.
2413
-                        # Thus, access check can succeed even if user only has access to
2414
-                        # to a single bucket and not ListAllMyBuckets permission.
2415
-                        output(u"Please wait, attempting to list bucket: " + args[0])
2416
-                        uri = S3Uri(args[0])
2417
-                        if uri.type == "s3" and uri.has_bucket():
2418
-                            S3(Config()).bucket_list(uri.bucket(), "")
2419
-                        else:
2420
-                            raise Exception(u"Invalid bucket uri: " + args[0])
2421
-
2422
-                    output(u"Success. Your access key and secret key worked fine :-)")
2423
-
2424
-                    output(u"\nNow verifying that encryption works...")
2425
-                    if not getattr(cfg, "gpg_command") or not getattr(cfg, "gpg_passphrase"):
2426
-                        output(u"Not configured. Never mind.")
2427
-                    else:
2428
-                        if not getattr(cfg, "gpg_command"):
2429
-                            raise Exception("Path to GPG program not set")
2430
-                        if not os.path.isfile(deunicodise(getattr(cfg, "gpg_command"))):
2431
-                            raise Exception("GPG program not found")
2432
-                        filename = Utils.mktmpfile()
2433
-                        with open(deunicodise(filename), "w") as fp:
2434
-                            fp.write(os.sys.copyright)
2435
-                        ret_enc = gpg_encrypt(filename)
2436
-                        ret_dec = gpg_decrypt(ret_enc[1], ret_enc[2], False)
2437
-                        hash = [
2438
-                            Utils.hash_file_md5(filename),
2439
-                            Utils.hash_file_md5(ret_enc[1]),
2440
-                            Utils.hash_file_md5(ret_dec[1]),
2441
-                        ]
2442
-                        os.unlink(deunicodise(filename))
2443
-                        os.unlink(deunicodise(ret_enc[1]))
2444
-                        os.unlink(deunicodise(ret_dec[1]))
2445
-                        if hash[0] == hash[2] and hash[0] != hash[1]:
2446
-                            output(u"Success. Encryption and decryption worked fine :-)")
2447
-                        else:
2448
-                            raise Exception("Encryption verification error.")
2449
-
2450
-                except S3Error as e:
2451
-                    error(u"Test failed: %s" % (e))
2452
-                    if e.code == "AccessDenied":
2453
-                        error(u"Are you sure your keys have s3:ListAllMyBuckets permissions?")
2454
-                    val = input("\nRetry configuration? [Y/n] ")
2455
-                    if val.lower().startswith("y") or val == "":
2456
-                        continue
2457
-                except Exception as e:
2458
-                    error(u"Test failed: %s" % (e))
2459
-                    val = input("\nRetry configuration? [Y/n] ")
2460
-                    if val.lower().startswith("y") or val == "":
2461
-                        continue
2462
-
2463
-
2464
-            val = input("\nSave settings? [y/N] ")
2465
-            if val.lower().startswith("y"):
2466
-                break
2467
-            val = input("Retry configuration? [Y/n] ")
2468
-            if val.lower().startswith("n"):
2469
-                raise EOFError()
2470
-
2471
-        ## Overwrite existing config file, make it user-readable only
2472
-        old_mask = os.umask(0o077)
2473
-        try:
2474
-            os.remove(deunicodise(config_file))
2475
-        except OSError as e:
2476
-            if e.errno != errno.ENOENT:
2477
-                raise
2478
-        try:
2479
-            with io.open(deunicodise(config_file), "w", encoding=cfg.encoding) as fp:
2480
-                cfg.dump_config(fp)
2481
-        finally:
2482
-            os.umask(old_mask)
2483
-        output(u"Configuration saved to '%s'" % config_file)
2484
-
2485
-    except (EOFError, KeyboardInterrupt):
2486
-        output(u"\nConfiguration aborted. Changes were NOT saved.")
2487
-        return
2488
-
2489
-    except IOError as e:
2490
-        error(u"Writing config file failed: %s: %s" % (config_file, e.strerror))
2491
-        sys.exit(EX_IOERR)
2492
-
2493
-def process_patterns_from_file(fname, patterns_list):
2494
-    try:
2495
-        with open(deunicodise(fname), "rt") as fn:
2496
-            for pattern in fn:
2497
-                pattern = unicodise(pattern).strip()
2498
-                if re.match("^#", pattern) or re.match("^\s*$", pattern):
2499
-                    continue
2500
-                debug(u"%s: adding rule: %s" % (fname, pattern))
2501
-                patterns_list.append(pattern)
2502
-    except IOError as e:
2503
-        error(e)
2504
-        sys.exit(EX_IOERR)
2505
-
2506
-    return patterns_list
2507
-
2508
-def process_patterns(patterns_list, patterns_from, is_glob, option_txt = ""):
2509
-    """
2510
-    process_patterns(patterns, patterns_from, is_glob, option_txt = "")
2511
-    Process --exclude / --include GLOB and REGEXP patterns.
2512
-    'option_txt' is 'exclude' / 'include' / 'rexclude' / 'rinclude'
2513
-    Returns: patterns_compiled, patterns_text
2514
-    Note: process_patterns_from_file will ignore lines starting with # as these
2515
-    are comments. To target escape the initial #, to use it in a file name, one
2516
-    can use: "[#]" (for exclude) or "\#" (for rexclude).
2517
-    """
2518
-
2519
-    patterns_compiled = []
2520
-    patterns_textual = {}
2521
-
2522
-    if patterns_list is None:
2523
-        patterns_list = []
2524
-
2525
-    if patterns_from:
2526
-        ## Append patterns from glob_from
2527
-        for fname in patterns_from:
2528
-            debug(u"processing --%s-from %s" % (option_txt, fname))
2529
-            patterns_list = process_patterns_from_file(fname, patterns_list)
2530
-
2531
-    for pattern in patterns_list:
2532
-        debug(u"processing %s rule: %s" % (option_txt, patterns_list))
2533
-        if is_glob:
2534
-            pattern = glob.fnmatch.translate(pattern)
2535
-        r = re.compile(pattern)
2536
-        patterns_compiled.append(r)
2537
-        patterns_textual[r] = pattern
2538
-
2539
-    return patterns_compiled, patterns_textual
2540
-
2541
-def get_commands_list():
2542
-    return [
2543
-    {"cmd":"mb", "label":"Make bucket", "param":"s3://BUCKET", "func":cmd_bucket_create, "argc":1},
2544
-    {"cmd":"rb", "label":"Remove bucket", "param":"s3://BUCKET", "func":cmd_bucket_delete, "argc":1},
2545
-    {"cmd":"ls", "label":"List objects or buckets", "param":"[s3://BUCKET[/PREFIX]]", "func":cmd_ls, "argc":0},
2546
-    {"cmd":"la", "label":"List all object in all buckets", "param":"", "func":cmd_all_buckets_list_all_content, "argc":0},
2547
-    {"cmd":"put", "label":"Put file into bucket", "param":"FILE [FILE...] s3://BUCKET[/PREFIX]", "func":cmd_object_put, "argc":2},
2548
-    {"cmd":"get", "label":"Get file from bucket", "param":"s3://BUCKET/OBJECT LOCAL_FILE", "func":cmd_object_get, "argc":1},
2549
-    {"cmd":"del", "label":"Delete file from bucket", "param":"s3://BUCKET/OBJECT", "func":cmd_object_del, "argc":1},
2550
-    {"cmd":"rm", "label":"Delete file from bucket (alias for del)", "param":"s3://BUCKET/OBJECT", "func":cmd_object_del, "argc":1},
2551
-    #{"cmd":"mkdir", "label":"Make a virtual S3 directory", "param":"s3://BUCKET/path/to/dir", "func":cmd_mkdir, "argc":1},
2552
-    {"cmd":"restore", "label":"Restore file from Glacier storage", "param":"s3://BUCKET/OBJECT", "func":cmd_object_restore, "argc":1},
2553
-    {"cmd":"sync", "label":"Synchronize a directory tree to S3 (checks files freshness using size and md5 checksum, unless overridden by options, see below)", "param":"LOCAL_DIR s3://BUCKET[/PREFIX] or s3://BUCKET[/PREFIX] LOCAL_DIR", "func":cmd_sync, "argc":2},
2554
-    {"cmd":"du", "label":"Disk usage by buckets", "param":"[s3://BUCKET[/PREFIX]]", "func":cmd_du, "argc":0},
2555
-    {"cmd":"info", "label":"Get various information about Buckets or Files", "param":"s3://BUCKET[/OBJECT]", "func":cmd_info, "argc":1},
2556
-    {"cmd":"cp", "label":"Copy object", "param":"s3://BUCKET1/OBJECT1 s3://BUCKET2[/OBJECT2]", "func":cmd_cp, "argc":2},
2557
-    {"cmd":"modify", "label":"Modify object metadata", "param":"s3://BUCKET1/OBJECT", "func":cmd_modify, "argc":1},
2558
-    {"cmd":"mv", "label":"Move object", "param":"s3://BUCKET1/OBJECT1 s3://BUCKET2[/OBJECT2]", "func":cmd_mv, "argc":2},
2559
-    {"cmd":"setacl", "label":"Modify Access control list for Bucket or Files", "param":"s3://BUCKET[/OBJECT]", "func":cmd_setacl, "argc":1},
2560
-
2561
-    {"cmd":"setpolicy", "label":"Modify Bucket Policy", "param":"FILE s3://BUCKET", "func":cmd_setpolicy, "argc":2},
2562
-    {"cmd":"delpolicy", "label":"Delete Bucket Policy", "param":"s3://BUCKET", "func":cmd_delpolicy, "argc":1},
2563
-    {"cmd":"setcors", "label":"Modify Bucket CORS", "param":"FILE s3://BUCKET", "func":cmd_setcors, "argc":2},
2564
-    {"cmd":"delcors", "label":"Delete Bucket CORS", "param":"s3://BUCKET", "func":cmd_delcors, "argc":1},
2565
-
2566
-    {"cmd":"payer",     "label":"Modify Bucket Requester Pays policy", "param":"s3://BUCKET", "func":cmd_set_payer, "argc":1},
2567
-    {"cmd":"multipart", "label":"Show multipart uploads", "param":"s3://BUCKET [Id]", "func":cmd_multipart, "argc":1},
2568
-    {"cmd":"abortmp",   "label":"Abort a multipart upload", "param":"s3://BUCKET/OBJECT Id", "func":cmd_abort_multipart, "argc":2},
2569
-
2570
-    {"cmd":"listmp",    "label":"List parts of a multipart upload", "param":"s3://BUCKET/OBJECT Id", "func":cmd_list_multipart, "argc":2},
2571
-
2572
-    {"cmd":"accesslog", "label":"Enable/disable bucket access logging", "param":"s3://BUCKET", "func":cmd_accesslog, "argc":1},
2573
-    {"cmd":"sign", "label":"Sign arbitrary string using the secret key", "param":"STRING-TO-SIGN", "func":cmd_sign, "argc":1},
2574
-    {"cmd":"signurl", "label":"Sign an S3 URL to provide limited public access with expiry", "param":"s3://BUCKET/OBJECT <expiry_epoch|+expiry_offset>", "func":cmd_signurl, "argc":2},
2575
-    {"cmd":"fixbucket", "label":"Fix invalid file names in a bucket", "param":"s3://BUCKET[/PREFIX]", "func":cmd_fixbucket, "argc":1},
2576
-
2577
-    ## Website commands
2578
-    {"cmd":"ws-create", "label":"Create Website from bucket", "param":"s3://BUCKET", "func":cmd_website_create, "argc":1},
2579
-    {"cmd":"ws-delete", "label":"Delete Website", "param":"s3://BUCKET", "func":cmd_website_delete, "argc":1},
2580
-    {"cmd":"ws-info", "label":"Info about Website", "param":"s3://BUCKET", "func":cmd_website_info, "argc":1},
2581
-
2582
-    ## Lifecycle commands
2583
-    {"cmd":"expire", "label":"Set or delete expiration rule for the bucket", "param":"s3://BUCKET", "func":cmd_expiration_set, "argc":1},
2584
-    {"cmd":"setlifecycle", "label":"Upload a lifecycle policy for the bucket", "param":"FILE s3://BUCKET", "func":cmd_setlifecycle, "argc":2},
2585
-    {"cmd":"getlifecycle", "label":"Get a lifecycle policy for the bucket",    "param":"s3://BUCKET", "func":cmd_getlifecycle, "argc":1},
2586
-    {"cmd":"dellifecycle", "label":"Remove a lifecycle policy for the bucket", "param":"s3://BUCKET", "func":cmd_dellifecycle, "argc":1},
2587
-
2588
-    ## CloudFront commands
2589
-    {"cmd":"cflist", "label":"List CloudFront distribution points", "param":"", "func":CfCmd.info, "argc":0},
2590
-    {"cmd":"cfinfo", "label":"Display CloudFront distribution point parameters", "param":"[cf://DIST_ID]", "func":CfCmd.info, "argc":0},
2591
-    {"cmd":"cfcreate", "label":"Create CloudFront distribution point", "param":"s3://BUCKET", "func":CfCmd.create, "argc":1},
2592
-    {"cmd":"cfdelete", "label":"Delete CloudFront distribution point", "param":"cf://DIST_ID", "func":CfCmd.delete, "argc":1},
2593
-    {"cmd":"cfmodify", "label":"Change CloudFront distribution point parameters", "param":"cf://DIST_ID", "func":CfCmd.modify, "argc":1},
2594
-    #{"cmd":"cfinval", "label":"Invalidate CloudFront objects", "param":"s3://BUCKET/OBJECT [s3://BUCKET/OBJECT ...]", "func":CfCmd.invalidate, "argc":1},
2595
-    {"cmd":"cfinvalinfo", "label":"Display CloudFront invalidation request(s) status", "param":"cf://DIST_ID[/INVAL_ID]", "func":CfCmd.invalinfo, "argc":1},
2596
-    ]
2597
-
2598
-def format_commands(progname, commands_list):
2599
-    help = "Commands:\n"
2600
-    for cmd in commands_list:
2601
-        help += "  %s\n      %s %s %s\n" % (cmd["label"], progname, cmd["cmd"], cmd["param"])
2602
-    return help
2603
-
2604
-
2605
-def update_acl(s3, uri, seq_label=""):
2606
-    cfg = Config()
2607
-    something_changed = False
2608
-    acl = s3.get_acl(uri)
2609
-    debug(u"acl: %s - %r" % (uri, acl.grantees))
2610
-    if cfg.acl_public == True:
2611
-        if acl.isAnonRead():
2612
-            info(u"%s: already Public, skipping %s" % (uri, seq_label))
2613
-        else:
2614
-            acl.grantAnonRead()
2615
-            something_changed = True
2616
-    elif cfg.acl_public == False:  # we explicitely check for False, because it could be None
2617
-        if not acl.isAnonRead():
2618
-            info(u"%s: already Private, skipping %s" % (uri, seq_label))
2619
-        else:
2620
-            acl.revokeAnonRead()
2621
-            something_changed = True
2622
-
2623
-    # update acl with arguments
2624
-    # grant first and revoke later, because revoke has priority
2625
-    if cfg.acl_grants:
2626
-        something_changed = True
2627
-        for grant in cfg.acl_grants:
2628
-            acl.grant(**grant)
2629
-
2630
-    if cfg.acl_revokes:
2631
-        something_changed = True
2632
-        for revoke in cfg.acl_revokes:
2633
-            acl.revoke(**revoke)
2634
-
2635
-    if not something_changed:
2636
-        return
2637
-
2638
-    retsponse = s3.set_acl(uri, acl)
2639
-    if retsponse['status'] == 200:
2640
-        if cfg.acl_public in (True, False):
2641
-            set_to_acl = cfg.acl_public and "Public" or "Private"
2642
-            output(u"%s: ACL set to %s  %s" % (uri, set_to_acl, seq_label))
2643
-        else:
2644
-            output(u"%s: ACL updated" % uri)
2645
-
2646
-class OptionMimeType(Option):
2647
-    def check_mimetype(option, opt, value):
2648
-        if re.compile("^[a-z0-9]+/[a-z0-9+\.-]+(;.*)?$", re.IGNORECASE).match(value):
2649
-            return value
2650
-        raise OptionValueError("option %s: invalid MIME-Type format: %r" % (opt, value))
2651
-
2652
-class OptionS3ACL(Option):
2653
-    def check_s3acl(option, opt, value):
2654
-        permissions = ('read', 'write', 'read_acp', 'write_acp', 'full_control', 'all')
2655
-        try:
2656
-            permission, grantee = re.compile("^(\w+):(.+)$", re.IGNORECASE).match(value).groups()
2657
-            if not permission or not grantee:
2658
-                raise
2659
-            if permission in permissions:
2660
-                return { 'name' : grantee, 'permission' : permission.upper() }
2661
-            else:
2662
-                raise OptionValueError("option %s: invalid S3 ACL permission: %s (valid values: %s)" %
2663
-                    (opt, permission, ", ".join(permissions)))
2664
-        except Exception:
2665
-            raise OptionValueError("option %s: invalid S3 ACL format: %r" % (opt, value))
2666
-
2667
-class OptionAll(OptionMimeType, OptionS3ACL):
2668
-    TYPE_CHECKER = copy(Option.TYPE_CHECKER)
2669
-    TYPE_CHECKER["mimetype"] = OptionMimeType.check_mimetype
2670
-    TYPE_CHECKER["s3acl"] = OptionS3ACL.check_s3acl
2671
-    TYPES = Option.TYPES + ("mimetype", "s3acl")
2672
-
2673
-class MyHelpFormatter(IndentedHelpFormatter):
2674
-    def format_epilog(self, epilog):
2675
-        if epilog:
2676
-            return "\n" + epilog + "\n"
2677
-        else:
2678
-            return ""
2679
-
2680
-def main():
2681
-    cfg = Config()
2682
-    commands_list = get_commands_list()
2683
-    commands = {}
2684
-
2685
-    ## Populate "commands" from "commands_list"
2686
-    for cmd in commands_list:
2687
-        if 'cmd' in cmd:
2688
-            commands[cmd['cmd']] = cmd
2689
-
2690
-    optparser = OptionParser(option_class=OptionAll, formatter=MyHelpFormatter())
2691
-    #optparser.disable_interspersed_args()
2692
-
2693
-    autodetected_encoding = locale.getpreferredencoding() or "UTF-8"
2694
-
2695
-    config_file = None
2696
-    if os.getenv("S3CMD_CONFIG"):
2697
-        config_file = unicodise_s(os.getenv("S3CMD_CONFIG"),
2698
-                                  autodetected_encoding)
2699
-    elif os.name == "nt" and os.getenv("USERPROFILE"):
2700
-        config_file = os.path.join(
2701
-            unicodise_s(os.getenv("USERPROFILE"), autodetected_encoding),
2702
-            os.getenv("APPDATA")
2703
-               and unicodise_s(os.getenv("APPDATA"), autodetected_encoding)
2704
-               or 'Application Data',
2705
-            "s3cmd.ini")
2706
-    else:
2707
-        from os.path import expanduser
2708
-        config_file = os.path.join(expanduser("~"), ".s3cfg")
2709
-
2710
-    optparser.set_defaults(config = config_file)
2711
-
2712
-    optparser.add_option(      "--configure", dest="run_configure", action="store_true", help="Invoke interactive (re)configuration tool. Optionally use as '--configure s3://some-bucket' to test access to a specific bucket instead of attempting to list them all.")
2713
-    optparser.add_option("-c", "--config", dest="config", metavar="FILE", help="Config file name. Defaults to $HOME/.s3cfg")
2714
-    optparser.add_option(      "--dump-config", dest="dump_config", action="store_true", help="Dump current configuration after parsing config files and command line options and exit.")
2715
-    optparser.add_option(      "--access_key", dest="access_key", help="AWS Access Key")
2716
-    optparser.add_option(      "--secret_key", dest="secret_key", help="AWS Secret Key")
2717
-    optparser.add_option(      "--access_token", dest="access_token", help="AWS Access Token")
2718
-
2719
-    optparser.add_option("-n", "--dry-run", dest="dry_run", action="store_true", help="Only show what should be uploaded or downloaded but don't actually do it. May still perform S3 requests to get bucket listings and other information though (only for file transfer commands)")
2720
-
2721
-    optparser.add_option("-s", "--ssl", dest="use_https", action="store_true", help="Use HTTPS connection when communicating with S3. (default)")
2722
-    optparser.add_option(      "--no-ssl", dest="use_https", action="store_false", help="Don't use HTTPS.")
2723
-    optparser.add_option("-e", "--encrypt", dest="encrypt", action="store_true", help="Encrypt files before uploading to S3.")
2724
-    optparser.add_option(      "--no-encrypt", dest="encrypt", action="store_false", help="Don't encrypt files.")
2725
-    optparser.add_option("-f", "--force", dest="force", action="store_true", help="Force overwrite and other dangerous operations.")
2726
-    optparser.add_option(      "--continue", dest="get_continue", action="store_true", help="Continue getting a partially downloaded file (only for [get] command).")
2727
-    optparser.add_option(      "--continue-put", dest="put_continue", action="store_true", help="Continue uploading partially uploaded files or multipart upload parts.  Restarts parts/files that don't have matching size and md5.  Skips files/parts that do.  Note: md5sum checks are not always sufficient to check (part) file equality.  Enable this at your own risk.")
2728
-    optparser.add_option(      "--upload-id", dest="upload_id", help="UploadId for Multipart Upload, in case you want continue an existing upload (equivalent to --continue-put) and there are multiple partial uploads.  Use s3cmd multipart [URI] to see what UploadIds are associated with the given URI.")
2729
-    optparser.add_option(      "--skip-existing", dest="skip_existing", action="store_true", help="Skip over files that exist at the destination (only for [get] and [sync] commands).")
2730
-    optparser.add_option("-r", "--recursive", dest="recursive", action="store_true", help="Recursive upload, download or removal.")
2731
-    optparser.add_option(      "--check-md5", dest="check_md5", action="store_true", help="Check MD5 sums when comparing files for [sync]. (default)")
2732
-    optparser.add_option(      "--no-check-md5", dest="check_md5", action="store_false", help="Do not check MD5 sums when comparing files for [sync]. Only size will be compared. May significantly speed up transfer but may also miss some changed files.")
2733
-    optparser.add_option("-P", "--acl-public", dest="acl_public", action="store_true", help="Store objects with ACL allowing read for anyone.")
2734
-    optparser.add_option(      "--acl-private", dest="acl_public", action="store_false", help="Store objects with default ACL allowing access for you only.")
2735
-    optparser.add_option(      "--acl-grant", dest="acl_grants", type="s3acl", action="append", metavar="PERMISSION:EMAIL or USER_CANONICAL_ID", help="Grant stated permission to a given amazon user. Permission is one of: read, write, read_acp, write_acp, full_control, all")
2736
-    optparser.add_option(      "--acl-revoke", dest="acl_revokes", type="s3acl", action="append", metavar="PERMISSION:USER_CANONICAL_ID", help="Revoke stated permission for a given amazon user. Permission is one of: read, write, read_acp, write_acp, full_control, all")
2737
-
2738
-    optparser.add_option("-D", "--restore-days", dest="restore_days", action="store", help="Number of days to keep restored file available (only for 'restore' command). Default is 1 day.", metavar="NUM")
2739
-    optparser.add_option(      "--restore-priority", dest="restore_priority", action="store", choices=['standard', 'expedited', 'bulk'], help="Priority for restoring files from S3 Glacier (only for 'restore' command). Choices available: bulk, standard, expedited")
2740
-
2741
-    optparser.add_option(      "--delete-removed", dest="delete_removed", action="store_true", help="Delete destination objects with no corresponding source file [sync]")
2742
-    optparser.add_option(      "--no-delete-removed", dest="delete_removed", action="store_false", help="Don't delete destination objects.")
2743
-    optparser.add_option(      "--delete-after", dest="delete_after", action="store_true", help="Perform deletes AFTER new uploads when delete-removed is enabled [sync]")
2744
-    optparser.add_option(      "--delay-updates", dest="delay_updates", action="store_true", help="*OBSOLETE* Put all updated files into place at end [sync]")  # OBSOLETE
2745
-    optparser.add_option(      "--max-delete", dest="max_delete", action="store", help="Do not delete more than NUM files. [del] and [sync]", metavar="NUM")
2746
-    optparser.add_option(      "--limit", dest="limit", action="store", help="Limit number of objects returned in the response body (only for [ls] and [la] commands)", metavar="NUM")
2747
-    optparser.add_option(      "--add-destination", dest="additional_destinations", action="append", help="Additional destination for parallel uploads, in addition to last arg.  May be repeated.")
2748
-    optparser.add_option(      "--delete-after-fetch", dest="delete_after_fetch", action="store_true", help="Delete remote objects after fetching to local file (only for [get] and [sync] commands).")
2749
-    optparser.add_option("-p", "--preserve", dest="preserve_attrs", action="store_true", help="Preserve filesystem attributes (mode, ownership, timestamps). Default for [sync] command.")
2750
-    optparser.add_option(      "--no-preserve", dest="preserve_attrs", action="store_false", help="Don't store FS attributes")
2751
-    optparser.add_option(      "--exclude", dest="exclude", action="append", metavar="GLOB", help="Filenames and paths matching GLOB will be excluded from sync")
2752
-    optparser.add_option(      "--exclude-from", dest="exclude_from", action="append", metavar="FILE", help="Read --exclude GLOBs from FILE")
2753
-    optparser.add_option(      "--rexclude", dest="rexclude", action="append", metavar="REGEXP", help="Filenames and paths matching REGEXP (regular expression) will be excluded from sync")
2754
-    optparser.add_option(      "--rexclude-from", dest="rexclude_from", action="append", metavar="FILE", help="Read --rexclude REGEXPs from FILE")
2755
-    optparser.add_option(      "--include", dest="include", action="append", metavar="GLOB", help="Filenames and paths matching GLOB will be included even if previously excluded by one of --(r)exclude(-from) patterns")
2756
-    optparser.add_option(      "--include-from", dest="include_from", action="append", metavar="FILE", help="Read --include GLOBs from FILE")
2757
-    optparser.add_option(      "--rinclude", dest="rinclude", action="append", metavar="REGEXP", help="Same as --include but uses REGEXP (regular expression) instead of GLOB")
2758
-    optparser.add_option(      "--rinclude-from", dest="rinclude_from", action="append", metavar="FILE", help="Read --rinclude REGEXPs from FILE")
2759
-
2760
-    optparser.add_option(      "--files-from", dest="files_from", action="append", metavar="FILE", help="Read list of source-file names from FILE. Use - to read from stdin.")
2761
-    optparser.add_option(      "--region", "--bucket-location", metavar="REGION", dest="bucket_location", help="Region to create bucket in. As of now the regions are: us-east-1, us-west-1, us-west-2, eu-west-1, eu-central-1, ap-northeast-1, ap-southeast-1, ap-southeast-2, sa-east-1")
2762
-    optparser.add_option(      "--host", metavar="HOSTNAME", dest="host_base", help="HOSTNAME:PORT for S3 endpoint (default: %s, alternatives such as s3-eu-west-1.amazonaws.com). You should also set --host-bucket." % (cfg.host_base))
2763
-    optparser.add_option(      "--host-bucket", dest="host_bucket", help="DNS-style bucket+hostname:port template for accessing a bucket (default: %s)" % (cfg.host_bucket))
2764
-    optparser.add_option(      "--reduced-redundancy", "--rr", dest="reduced_redundancy", action="store_true", help="Store object with 'Reduced redundancy'. Lower per-GB price. [put, cp, mv]")
2765
-    optparser.add_option(      "--no-reduced-redundancy", "--no-rr", dest="reduced_redundancy", action="store_false", help="Store object without 'Reduced redundancy'. Higher per-GB price. [put, cp, mv]")
2766
-    optparser.add_option(      "--storage-class", dest="storage_class", action="store", metavar="CLASS", help="Store object with specified CLASS (STANDARD, STANDARD_IA, ONEZONE_IA, INTELLIGENT_TIERING, GLACIER or DEEP_ARCHIVE). [put, cp, mv]")
2767
-    optparser.add_option(      "--access-logging-target-prefix", dest="log_target_prefix", help="Target prefix for access logs (S3 URI) (for [cfmodify] and [accesslog] commands)")
2768
-    optparser.add_option(      "--no-access-logging", dest="log_target_prefix", action="store_false", help="Disable access logging (for [cfmodify] and [accesslog] commands)")
2769
-
2770
-    optparser.add_option(      "--default-mime-type", dest="default_mime_type", type="mimetype", action="store", help="Default MIME-type for stored objects. Application default is binary/octet-stream.")
2771
-    optparser.add_option("-M", "--guess-mime-type", dest="guess_mime_type", action="store_true", help="Guess MIME-type of files by their extension or mime magic. Fall back to default MIME-Type as specified by --default-mime-type option")
2772
-    optparser.add_option(      "--no-guess-mime-type", dest="guess_mime_type", action="store_false", help="Don't guess MIME-type and use the default type instead.")
2773
-    optparser.add_option(      "--no-mime-magic", dest="use_mime_magic", action="store_false", help="Don't use mime magic when guessing MIME-type.")
2774
-    optparser.add_option("-m", "--mime-type", dest="mime_type", type="mimetype", metavar="MIME/TYPE", help="Force MIME-type. Override both --default-mime-type and --guess-mime-type.")
2775
-
2776
-    optparser.add_option(      "--add-header", dest="add_header", action="append", metavar="NAME:VALUE", help="Add a given HTTP header to the upload request. Can be used multiple times. For instance set 'Expires' or 'Cache-Control' headers (or both) using this option.")
2777
-    optparser.add_option(      "--remove-header", dest="remove_headers", action="append", metavar="NAME", help="Remove a given HTTP header.  Can be used multiple times.  For instance, remove 'Expires' or 'Cache-Control' headers (or both) using this option. [modify]")
2778
-
2779
-    optparser.add_option(      "--server-side-encryption", dest="server_side_encryption", action="store_true", help="Specifies that server-side encryption will be used when putting objects. [put, sync, cp, modify]")
2780
-    optparser.add_option(      "--server-side-encryption-kms-id", dest="kms_key", action="store", help="Specifies the key id used for server-side encryption with AWS KMS-Managed Keys (SSE-KMS) when putting objects. [put, sync, cp, modify]")
2781
-
2782
-    optparser.add_option(      "--encoding", dest="encoding", metavar="ENCODING", help="Override autodetected terminal and filesystem encoding (character set). Autodetected: %s" % autodetected_encoding)
2783
-    optparser.add_option(      "--add-encoding-exts", dest="add_encoding_exts", metavar="EXTENSIONs", help="Add encoding to these comma delimited extensions i.e. (css,js,html) when uploading to S3 )")
2784
-    optparser.add_option(      "--verbatim", dest="urlencoding_mode", action="store_const", const="verbatim", help="Use the S3 name as given on the command line. No pre-processing, encoding, etc. Use with caution!")
2785
-
2786
-    optparser.add_option(      "--disable-multipart", dest="enable_multipart", action="store_false", help="Disable multipart upload on files bigger than --multipart-chunk-size-mb")
2787
-    optparser.add_option(      "--multipart-chunk-size-mb", dest="multipart_chunk_size_mb", type="int", action="store", metavar="SIZE", help="Size of each chunk of a multipart upload. Files bigger than SIZE are automatically uploaded as multithreaded-multipart, smaller files are uploaded using the traditional method. SIZE is in Mega-Bytes, default chunk size is 15MB, minimum allowed chunk size is 5MB, maximum is 5GB.")
2788
-
2789
-    optparser.add_option(      "--list-md5", dest="list_md5", action="store_true", help="Include MD5 sums in bucket listings (only for 'ls' command).")
2790
-    optparser.add_option("-H", "--human-readable-sizes", dest="human_readable_sizes", action="store_true", help="Print sizes in human readable form (eg 1kB instead of 1234).")
2791
-
2792
-    optparser.add_option(      "--ws-index", dest="website_index", action="store", help="Name of index-document (only for [ws-create] command)")
2793
-    optparser.add_option(      "--ws-error", dest="website_error", action="store", help="Name of error-document (only for [ws-create] command)")
2794
-
2795
-    optparser.add_option(      "--expiry-date", dest="expiry_date", action="store", help="Indicates when the expiration rule takes effect. (only for [expire] command)")
2796
-    optparser.add_option(      "--expiry-days", dest="expiry_days", action="store", help="Indicates the number of days after object creation the expiration rule takes effect. (only for [expire] command)")
2797
-    optparser.add_option(      "--expiry-prefix", dest="expiry_prefix", action="store", help="Identifying one or more objects with the prefix to which the expiration rule applies. (only for [expire] command)")
2798
-
2799
-    optparser.add_option(      "--progress", dest="progress_meter", action="store_true", help="Display progress meter (default on TTY).")
2800
-    optparser.add_option(      "--no-progress", dest="progress_meter", action="store_false", help="Don't display progress meter (default on non-TTY).")
2801
-    optparser.add_option(      "--stats", dest="stats", action="store_true", help="Give some file-transfer stats.")
2802
-    optparser.add_option(      "--enable", dest="enable", action="store_true", help="Enable given CloudFront distribution (only for [cfmodify] command)")
2803
-    optparser.add_option(      "--disable", dest="enable", action="store_false", help="Disable given CloudFront distribution (only for [cfmodify] command)")
2804
-    optparser.add_option(      "--cf-invalidate", dest="invalidate_on_cf", action="store_true", help="Invalidate the uploaded filed in CloudFront. Also see [cfinval] command.")
2805
-    # joseprio: adding options to invalidate the default index and the default
2806
-    # index root
2807
-    optparser.add_option(      "--cf-invalidate-default-index", dest="invalidate_default_index_on_cf", action="store_true", help="When using Custom Origin and S3 static website, invalidate the default index file.")
2808
-    optparser.add_option(      "--cf-no-invalidate-default-index-root", dest="invalidate_default_index_root_on_cf", action="store_false", help="When using Custom Origin and S3 static website, don't invalidate the path to the default index file.")
2809
-    optparser.add_option(      "--cf-add-cname", dest="cf_cnames_add", action="append", metavar="CNAME", help="Add given CNAME to a CloudFront distribution (only for [cfcreate] and [cfmodify] commands)")
2810
-    optparser.add_option(      "--cf-remove-cname", dest="cf_cnames_remove", action="append", metavar="CNAME", help="Remove given CNAME from a CloudFront distribution (only for [cfmodify] command)")
2811
-    optparser.add_option(      "--cf-comment", dest="cf_comment", action="store", metavar="COMMENT", help="Set COMMENT for a given CloudFront distribution (only for [cfcreate] and [cfmodify] commands)")
2812
-    optparser.add_option(      "--cf-default-root-object", dest="cf_default_root_object", action="store", metavar="DEFAULT_ROOT_OBJECT", help="Set the default root object to return when no object is specified in the URL. Use a relative path, i.e. default/index.html instead of /default/index.html or s3://bucket/default/index.html (only for [cfcreate] and [cfmodify] commands)")
2813
-    optparser.add_option("-v", "--verbose", dest="verbosity", action="store_const", const=logging.INFO, help="Enable verbose output.")
2814
-    optparser.add_option("-d", "--debug", dest="verbosity", action="store_const", const=logging.DEBUG, help="Enable debug output.")
2815
-    optparser.add_option(      "--version", dest="show_version", action="store_true", help="Show s3cmd version (%s) and exit." % (PkgInfo.version))
2816
-    optparser.add_option("-F", "--follow-symlinks", dest="follow_symlinks", action="store_true", default=False, help="Follow symbolic links as if they are regular files")
2817
-    optparser.add_option(      "--cache-file", dest="cache_file", action="store", default="",  metavar="FILE", help="Cache FILE containing local source MD5 values")
2818
-    optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False, help="Silence output on stdout")
2819
-    optparser.add_option(      "--ca-certs", dest="ca_certs_file", action="store", default=None, help="Path to SSL CA certificate FILE (instead of system default)")
2820
-    optparser.add_option(      "--ssl-cert", dest="ssl_client_cert_file", action="store", default=None, help="Path to client own SSL certificate CRT_FILE")
2821
-    optparser.add_option(      "--ssl-key", dest="ssl_client_key_file", action="store", default=None, help="Path to client own SSL certificate private key KEY_FILE")
2822
-    optparser.add_option(      "--check-certificate", dest="check_ssl_certificate", action="store_true", help="Check SSL certificate validity")
2823
-    optparser.add_option(      "--no-check-certificate", dest="check_ssl_certificate", action="store_false", help="Do not check SSL certificate validity")
2824
-    optparser.add_option(      "--check-hostname", dest="check_ssl_hostname", action="store_true", help="Check SSL certificate hostname validity")
2825
-    optparser.add_option(      "--no-check-hostname", dest="check_ssl_hostname", action="store_false", help="Do not check SSL certificate hostname validity")
2826
-    optparser.add_option(      "--signature-v2", dest="signature_v2", action="store_true", help="Use AWS Signature version 2 instead of newer signature methods. Helpful for S3-like systems that don't have AWS Signature v4 yet.")
2827
-    optparser.add_option(      "--limit-rate", dest="limitrate", action="store", type="string", help="Limit the upload or download speed to amount bytes per second.  Amount may be expressed in bytes, kilobytes with the k suffix, or megabytes with the m suffix")
2828
-    optparser.add_option(      "--no-connection-pooling", dest="connection_pooling", action="store_false", help="Disable connection re-use")
2829
-    optparser.add_option(      "--requester-pays", dest="requester_pays", action="store_true", help="Set the REQUESTER PAYS flag for operations")
2830
-    optparser.add_option("-l", "--long-listing", dest="long_listing", action="store_true", help="Produce long listing [ls]")
2831
-    optparser.add_option(      "--stop-on-error", dest="stop_on_error", action="store_true", help="stop if error in transfer")
2832
-    optparser.add_option(      "--content-disposition", dest="content_disposition", action="store", help="Provide a Content-Disposition for signed URLs, e.g., \"inline; filename=myvideo.mp4\"")
2833
-    optparser.add_option(      "--content-type", dest="content_type", action="store", help="Provide a Content-Type for signed URLs, e.g., \"video/mp4\"")
2834
-
2835
-    optparser.set_usage(optparser.usage + " COMMAND [parameters]")
2836
-    optparser.set_description('S3cmd is a tool for managing objects in '+
2837
-        'Amazon S3 storage. It allows for making and removing '+
2838
-        '"buckets" and uploading, downloading and removing '+
2839
-        '"objects" from these buckets.')
2840
-    optparser.epilog = format_commands(optparser.get_prog_name(), commands_list)
2841
-    optparser.epilog += ("\nFor more information, updates and news, visit the s3cmd website:\n%s\n" % PkgInfo.url)
2842
-
2843
-    (options, args) = optparser.parse_args()
2844
-
2845
-    ## Some mucking with logging levels to enable
2846
-    ## debugging/verbose output for config file parser on request
2847
-    logging.basicConfig(level=options.verbosity or Config().verbosity,
2848
-                        format='%(levelname)s: %(message)s',
2849
-                        stream = sys.stderr)
2850
-
2851
-    if options.show_version:
2852
-        output(u"s3cmd version %s" % PkgInfo.version)
2853
-        sys.exit(EX_OK)
2854
-    debug(u"s3cmd version %s" % PkgInfo.version)
2855
-
2856
-    if options.quiet:
2857
-        try:
2858
-            f = open("/dev/null", "w")
2859
-            sys.stdout = f
2860
-        except IOError:
2861
-            warning(u"Unable to open /dev/null: --quiet disabled.")
2862
-
2863
-    ## Now finally parse the config file
2864
-    if not options.config:
2865
-        error(u"Can't find a config file. Please use --config option.")
2866
-        sys.exit(EX_CONFIG)
2867
-
2868
-    try:
2869
-        cfg = Config(options.config, options.access_key, options.secret_key, options.access_token)
2870
-    except ValueError as exc:
2871
-        raise ParameterError(unicode(exc))
2872
-    except IOError as e:
2873
-        if options.run_configure:
2874
-            cfg = Config()
2875
-        else:
2876
-            error(u"%s: %s"  % (options.config, e.strerror))
2877
-            error(u"Configuration file not available.")
2878
-            error(u"Consider using --configure parameter to create one.")
2879
-            sys.exit(EX_CONFIG)
2880
-
2881
-    # allow commandline verbosity config to override config file
2882
-    if options.verbosity is not None:
2883
-        cfg.verbosity = options.verbosity
2884
-    logging.root.setLevel(cfg.verbosity)
2885
-    ## Unsupported features on Win32 platform
2886
-    if os.name == "nt":
2887
-        if cfg.preserve_attrs:
2888
-            error(u"Option --preserve is not yet supported on MS Windows platform. Assuming --no-preserve.")
2889
-            cfg.preserve_attrs = False
2890
-        if cfg.progress_meter:
2891
-            error(u"Option --progress is not yet supported on MS Windows platform. Assuming --no-progress.")
2892
-            cfg.progress_meter = False
2893
-
2894
-    ## Pre-process --add-header's and put them to Config.extra_headers SortedDict()
2895
-    if options.add_header:
2896
-        for hdr in options.add_header:
2897
-            try:
2898
-                key, val = unicodise_s(hdr).split(":", 1)
2899
-            except ValueError:
2900
-                raise ParameterError("Invalid header format: %s" % unicodise_s(hdr))
2901
-            # key char restrictions of the http headers name specification
2902
-            key_inval = re.sub(r"[a-zA-Z0-9\-.!#$%&*+^_|]", "", key)
2903
-            if key_inval:
2904
-                key_inval = key_inval.replace(" ", "<space>")
2905
-                key_inval = key_inval.replace("\t", "<tab>")
2906
-                raise ParameterError("Invalid character(s) in header name '%s'"
2907
-                                     ": \"%s\"" % (key, key_inval))
2908
-            debug(u"Updating Config.Config extra_headers[%s] -> %s" %
2909
-                  (key.strip().lower(), val.strip()))
2910
-            cfg.extra_headers[key.strip().lower()] = val.strip()
2911
-
2912
-    # Process --remove-header
2913
-    if options.remove_headers:
2914
-        cfg.remove_headers = options.remove_headers
2915
-
2916
-    ## --acl-grant/--acl-revoke arguments are pre-parsed by OptionS3ACL()
2917
-    if options.acl_grants:
2918
-        for grant in options.acl_grants:
2919
-            cfg.acl_grants.append(grant)
2920
-
2921
-    if options.acl_revokes:
2922
-        for grant in options.acl_revokes:
2923
-            cfg.acl_revokes.append(grant)
2924
-
2925
-    ## Process --(no-)check-md5
2926
-    if options.check_md5 == False:
2927
-        try:
2928
-            cfg.sync_checks.remove("md5")
2929
-            cfg.preserve_attrs_list.remove("md5")
2930
-        except Exception:
2931
-            pass
2932
-    if options.check_md5 == True:
2933
-        if cfg.sync_checks.count("md5") == 0:
2934
-            cfg.sync_checks.append("md5")
2935
-        if cfg.preserve_attrs_list.count("md5") == 0:
2936
-            cfg.preserve_attrs_list.append("md5")
2937
-
2938
-    ## Update Config with other parameters
2939
-    for option in cfg.option_list():
2940
-        try:
2941
-            value = getattr(options, option)
2942
-            if value != None:
2943
-                if type(value) == type(b''):
2944
-                    value = unicodise_s(value)
2945
-                debug(u"Updating Config.Config %s -> %s" % (option, value))
2946
-                cfg.update_option(option, value)
2947
-        except AttributeError:
2948
-            ## Some Config() options are not settable from command line
2949
-            pass
2950
-
2951
-    ## Special handling for tri-state options (True, False, None)
2952
-    cfg.update_option("enable", options.enable)
2953
-    if options.acl_public is not None:
2954
-        cfg.update_option("acl_public", options.acl_public)
2955
-
2956
-    ## Check multipart chunk constraints
2957
-    if cfg.multipart_chunk_size_mb < MultiPartUpload.MIN_CHUNK_SIZE_MB:
2958
-        raise ParameterError("Chunk size %d MB is too small, must be >= %d MB. Please adjust --multipart-chunk-size-mb" % (cfg.multipart_chunk_size_mb, MultiPartUpload.MIN_CHUNK_SIZE_MB))
2959
-    if cfg.multipart_chunk_size_mb > MultiPartUpload.MAX_CHUNK_SIZE_MB:
2960
-        raise ParameterError("Chunk size %d MB is too large, must be <= %d MB. Please adjust --multipart-chunk-size-mb" % (cfg.multipart_chunk_size_mb, MultiPartUpload.MAX_CHUNK_SIZE_MB))
2961
-
2962
-    ## If an UploadId was provided, set put_continue True
2963
-    if options.upload_id:
2964
-        cfg.upload_id = options.upload_id
2965
-        cfg.put_continue = True
2966
-
2967
-    if cfg.upload_id and not cfg.multipart_chunk_size_mb:
2968
-        raise ParameterError("Must have --multipart-chunk-size-mb if using --put-continue or --upload-id")
2969
-
2970
-    ## CloudFront's cf_enable and Config's enable share the same --enable switch
2971
-    options.cf_enable = options.enable
2972
-
2973
-    ## CloudFront's cf_logging and Config's log_target_prefix share the same --log-target-prefix switch
2974
-    options.cf_logging = options.log_target_prefix
2975
-
2976
-    ## Update CloudFront options if some were set
2977
-    for option in CfCmd.options.option_list():
2978
-        try:
2979
-            value = getattr(options, option)
2980
-            if value != None:
2981
-                if type(value) == type(b''):
2982
-                    value = unicodise_s(value)
2983
-            if value != None:
2984
-                debug(u"Updating CloudFront.Cmd %s -> %s" % (option, value))
2985
-                CfCmd.options.update_option(option, value)
2986
-        except AttributeError:
2987
-            ## Some CloudFront.Cmd.Options() options are not settable from command line
2988
-            pass
2989
-
2990
-    if options.additional_destinations:
2991
-        cfg.additional_destinations = options.additional_destinations
2992
-    if options.files_from:
2993
-        cfg.files_from = options.files_from
2994
-
2995
-    ## Set output and filesystem encoding for printing out filenames.
2996
-    try:
2997
-        # Support for python3
2998
-        # That don't need codecs if output is the
2999
-        # encoding of the system, but just in case, still use it.
3000
-        # For that, we need to use directly the binary buffer
3001
-        # of stdout/stderr
3002
-        sys.stdout = codecs.getwriter(cfg.encoding)(sys.stdout.buffer, "replace")
3003
-        sys.stderr = codecs.getwriter(cfg.encoding)(sys.stderr.buffer, "replace")
3004
-        # getwriter with create an "IObuffer" that have not the encoding attribute
3005
-        # better to add it to not break some functions like "input".
3006
-        sys.stdout.encoding = cfg.encoding
3007
-        sys.stderr.encoding = cfg.encoding
3008
-    except AttributeError:
3009
-        sys.stdout = codecs.getwriter(cfg.encoding)(sys.stdout, "replace")
3010
-        sys.stderr = codecs.getwriter(cfg.encoding)(sys.stderr, "replace")
3011
-
3012
-    ## Process --exclude and --exclude-from
3013
-    patterns_list, patterns_textual = process_patterns(options.exclude, options.exclude_from, is_glob = True, option_txt = "exclude")
3014
-    cfg.exclude.extend(patterns_list)
3015
-    cfg.debug_exclude.update(patterns_textual)
3016
-
3017
-    ## Process --rexclude and --rexclude-from
3018
-    patterns_list, patterns_textual = process_patterns(options.rexclude, options.rexclude_from, is_glob = False, option_txt = "rexclude")
3019
-    cfg.exclude.extend(patterns_list)
3020
-    cfg.debug_exclude.update(patterns_textual)
3021
-
3022
-    ## Process --include and --include-from
3023
-    patterns_list, patterns_textual = process_patterns(options.include, options.include_from, is_glob = True, option_txt = "include")
3024
-    cfg.include.extend(patterns_list)
3025
-    cfg.debug_include.update(patterns_textual)
3026
-
3027
-    ## Process --rinclude and --rinclude-from
3028
-    patterns_list, patterns_textual = process_patterns(options.rinclude, options.rinclude_from, is_glob = False, option_txt = "rinclude")
3029
-    cfg.include.extend(patterns_list)
3030
-    cfg.debug_include.update(patterns_textual)
3031
-
3032
-    ## Set socket read()/write() timeout
3033
-    socket.setdefaulttimeout(cfg.socket_timeout)
3034
-
3035
-    if cfg.encrypt and cfg.gpg_passphrase == "":
3036
-        error(u"Encryption requested but no passphrase set in config file.")
3037
-        error(u"Please re-run 's3cmd --configure' and supply it.")
3038
-        sys.exit(EX_CONFIG)
3039
-
3040
-    if options.dump_config:
3041
-        cfg.dump_config(sys.stdout)
3042
-        sys.exit(EX_OK)
3043
-
3044
-    if options.run_configure:
3045
-        # 'args' may contain the test-bucket URI
3046
-        run_configure(options.config, args)
3047
-        sys.exit(EX_OK)
3048
-
3049
-    ## set config if stop_on_error is set
3050
-    if options.stop_on_error:
3051
-        cfg.stop_on_error = options.stop_on_error
3052
-
3053
-    if options.content_disposition:
3054
-        cfg.content_disposition = options.content_disposition
3055
-
3056
-    if options.content_type:
3057
-        cfg.content_type = options.content_type
3058
-
3059
-    if len(args) < 1:
3060
-        optparser.print_help()
3061
-        sys.exit(EX_USAGE)
3062
-
3063
-    ## Unicodise all remaining arguments:
3064
-    args = [unicodise(arg) for arg in args]
3065
-
3066
-    command = args.pop(0)
3067
-    try:
3068
-        debug(u"Command: %s" % commands[command]["cmd"])
3069
-        ## We must do this lookup in extra step to
3070
-        ## avoid catching all KeyError exceptions
3071
-        ## from inner functions.
3072
-        cmd_func = commands[command]["func"]
3073
-    except KeyError as e:
3074
-        error(u"Invalid command: %s", command)
3075
-        sys.exit(EX_USAGE)
3076
-
3077
-    if len(args) < commands[command]["argc"]:
3078
-        error(u"Not enough parameters for command '%s'" % command)
3079
-        sys.exit(EX_USAGE)
3080
-
3081
-    rc = cmd_func(args)
3082
-    if rc is None: # if we missed any cmd_*() returns
3083
-        rc = EX_GENERAL
3084
-    return rc
3085
-
3086
-def report_exception(e, msg=u''):
3087
-        alert_header = u"""
3088
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3089
-    An unexpected error has occurred.
3090
-  Please try reproducing the error using
3091
-  the latest s3cmd code from the git master
3092
-  branch found at:
3093
-    https://github.com/s3tools/s3cmd
3094
-  and have a look at the known issues list:
3095
-    https://github.com/s3tools/s3cmd/wiki/Common-known-issues-and-their-solutions
3096
-  If the error persists, please report the
3097
-  %s (removing any private
3098
-  info as necessary) to:
3099
-   s3tools-bugs@lists.sourceforge.net%s
3100
-!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3101
-
3102
-"""
3103
-        sys.stderr.write(alert_header % (u"following lines", u"\n\n" + msg))
3104
-        tb = traceback.format_exc()
3105
-        try:
3106
-            s = u' '.join([unicodise(a) for a in sys.argv])
3107
-        except NameError:
3108
-            # Error happened before Utils module was yet imported to provide
3109
-            # unicodise
3110
-            try:
3111
-                s = u' '.join([(a) for a in sys.argv])
3112
-            except UnicodeDecodeError:
3113
-                s = u'[encoding safe] ' + u' '.join([('%r'%a) for a in sys.argv])
3114
-        sys.stderr.write(u"Invoked as: %s\n" % s)
3115
-
3116
-        e_class = str(e.__class__)
3117
-        e_class = e_class[e_class.rfind(".")+1 : -2]
3118
-        try:
3119
-            sys.stderr.write(u"Problem: %s: %s\n" % (e_class, e))
3120
-        except UnicodeDecodeError:
3121
-            sys.stderr.write(u"Problem: [encoding safe] %r: %r\n"
3122
-                             % (e_class, e))
3123
-        try:
3124
-            sys.stderr.write(u"S3cmd:   %s\n" % PkgInfo.version)
3125
-        except NameError:
3126
-            sys.stderr.write(u"S3cmd:   unknown version."
3127
-                             "Module import problem?\n")
3128
-        sys.stderr.write(u"python:   %s\n" % sys.version)
3129
-        try:
3130
-            sys.stderr.write(u"environment LANG=%s\n"
3131
-                             % unicodise_s(os.getenv("LANG", "NOTSET"),
3132
-                                           'ascii'))
3133
-        except NameError:
3134
-            # Error happened before Utils module was yet imported to provide
3135
-            # unicodise
3136
-            sys.stderr.write(u"environment LANG=%s\n"
3137
-                             % os.getenv("LANG", "NOTSET"))
3138
-        sys.stderr.write(u"\n")
3139
-        if type(tb) == unicode:
3140
-            sys.stderr.write(tb)
3141
-        else:
3142
-            sys.stderr.write(unicode(tb, errors="replace"))
3143
-
3144
-        if type(e) == ImportError:
3145
-            sys.stderr.write("\n")
3146
-            sys.stderr.write("Your sys.path contains these entries:\n")
3147
-            for path in sys.path:
3148
-                sys.stderr.write(u"\t%s\n" % path)
3149
-            sys.stderr.write("Now the question is where have the s3cmd modules"
3150
-                             " been installed?\n")
3151
-
3152
-        sys.stderr.write(alert_header % (u"above lines", u""))
3153
-
3154
-if __name__ == '__main__':
3155
-    try:
3156
-        ## Our modules
3157
-        ## Keep them in try/except block to
3158
-        ## detect any syntax errors in there
3159
-        from S3.ExitCodes import *
3160
-        from S3.Exceptions import *
3161
-        from S3 import PkgInfo
3162
-        from S3.S3 import S3
3163
-        from S3.Config import Config
3164
-        from S3.SortedDict import SortedDict
3165
-        from S3.FileDict import FileDict
3166
-        from S3.S3Uri import S3Uri
3167
-        from S3 import Utils
3168
-        from S3 import Crypto
3169
-        from S3.Utils import *
3170
-        from S3.Progress import Progress, StatsInfo
3171
-        from S3.CloudFront import Cmd as CfCmd
3172
-        from S3.CloudFront import CloudFront
3173
-        from S3.FileLists import *
3174
-        from S3.MultiPart import MultiPartUpload
3175
-    except Exception as e:
3176
-        report_exception(e, "Error loading some components of s3cmd (Import Error)")
3177
-        # 1 = EX_GENERAL but be safe in that situation
3178
-        sys.exit(1)
3179
-
3180
-    try:
3181
-        rc = main()
3182
-        sys.exit(rc)
3183
-
3184
-    except ImportError as e:
3185
-        report_exception(e)
3186
-        sys.exit(EX_GENERAL)
3187
-
3188
-    except (ParameterError, InvalidFileError) as e:
3189
-        error(u"Parameter problem: %s" % e)
3190
-        sys.exit(EX_USAGE)
3191
-
3192
-    except (S3DownloadError, S3UploadError, S3RequestError) as e:
3193
-        error(u"S3 Temporary Error: %s.  Please try again later." % e)
3194
-        sys.exit(EX_TEMPFAIL)
3195
-
3196
-    except S3Error as e:
3197
-        error(u"S3 error: %s" % e)
3198
-        sys.exit(e.get_error_code())
3199
-
3200
-    except (S3Exception, S3ResponseError, CloudFrontError) as e:
3201
-        report_exception(e)
3202
-        sys.exit(EX_SOFTWARE)
3203
-
3204
-    except SystemExit as e:
3205
-        sys.exit(e.code)
3206
-
3207
-    except KeyboardInterrupt:
3208
-        sys.stderr.write("See ya!\n")
3209
-        sys.exit(EX_BREAK)
3210
-
3211
-    except (S3SSLError, S3SSLCertificateError) as e:
3212
-        # SSLError is a subtype of IOError
3213
-        error("SSL certificate verification failure: %s" % e)
3214
-        sys.exit(EX_ACCESSDENIED)
3215
-
3216
-    except socket.gaierror as e:
3217
-        # gaierror is a subset of IOError
3218
-        # typically encountered error is:
3219
-        # gaierror: [Errno -2] Name or service not known
3220
-        error(e)
3221
-        error("Connection Error: Error resolving a server hostname.\n"
3222
-              "Please check the servers address specified in 'host_base', 'host_bucket', 'cloudfront_host', 'website_endpoint'")
3223
-        sys.exit(EX_IOERR)
3224
-
3225
-    except IOError as e:
3226
-        if e.errno == errno.EPIPE:
3227
-            # Fail silently on SIGPIPE. This likely means we wrote to a closed
3228
-            # pipe and user does not care for any more output.
3229
-            sys.exit(EX_IOERR)
3230
-
3231
-        report_exception(e)
3232
-        sys.exit(EX_IOERR)
3233
-
3234
-    except OSError as e:
3235
-        error(e)
3236
-        sys.exit(EX_OSERR)
3237
-
3238
-    except MemoryError:
3239
-        msg = """
3240
-MemoryError!  You have exceeded the amount of memory available for this process.
3241
-This usually occurs when syncing >750,000 files on a 32-bit python instance.
3242
-The solutions to this are:
3243
-1) sync several smaller subtrees; or
3244
-2) use a 64-bit python on a 64-bit OS with >8GB RAM
3245
-        """
3246
-        sys.stderr.write(msg)
3247
-        sys.exit(EX_OSERR)
3248
-
3249
-    except UnicodeEncodeError as e:
3250
-        lang = unicodise_s(os.getenv("LANG", "NOTSET"), 'ascii')
3251
-        msg = """
3252
-You have encountered a UnicodeEncodeError.  Your environment
3253
-variable LANG=%s may not specify a Unicode encoding (e.g. UTF-8).
3254
-Please set LANG=en_US.UTF-8 or similar in your environment before
3255
-invoking s3cmd.
3256
-        """ % lang
3257
-        report_exception(e, msg)
3258
-        sys.exit(EX_GENERAL)
3259
-
3260
-    except Exception as e:
3261
-        report_exception(e)
3262
-        sys.exit(EX_GENERAL)
3263
-
3264
-# vim:et:ts=4:sts=4:ai