This file is indexed.

/usr/bin/duplicity is in duplicity 0.7.17-0ubuntu1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
#! /usr/bin/python
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# duplicity -- Encrypted bandwidth efficient backup
# Version 0.7.17 released February 26, 2018
#
# Copyright 2002 Ben Escoto <ben@emerose.org>
# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# Duplicity is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with duplicity; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# See http://www.nongnu.org/duplicity for more information.
# Please send mail to me or the mailing list if you find bugs or have
# any suggestions.

import gzip
import os
import sys
import time
import types
import traceback
import platform
import statvfs
import resource
import re
import threading
from datetime import datetime
import fasteners

from duplicity import log
log.setup()

import duplicity.errors

from duplicity import collections
from duplicity import commandline
from duplicity import diffdir
from duplicity import dup_temp
from duplicity import dup_time
from duplicity import file_naming
from duplicity import globals
from duplicity import gpg
from duplicity import manifest
from duplicity import patchdir
from duplicity import path
from duplicity import robust
from duplicity import tempdir
from duplicity import asyncscheduler
from duplicity import util
from duplicity import progress


if '--pydevd' in sys.argv or os.getenv('PYDEVD', None):
    # The following is for starting remote debugging in Eclipse with Pydev.
    # Adjust the path to your location and version of Eclipse and Pydev.
    if platform.platform().startswith('Linux'):
        pysrc = "/opt/liclipse/plugins/org.python.pydev_5.7.0.201704111135/pysrc"
    elif platform.platform().startswith('Darwin'):
        pysrc = "/Applications/LiClipse.app/Contents/liclipse/plugins/org.python.pydev_5.7.0.201704111135/pysrc"
    else:
        raise Exception("Platform %s not supported by pydevd." % platform.platform())
    sys.path.append(pysrc)
    import pydevd  # @UnresolvedImport
    pydevd.settrace()
    # In a dev environment the path is screwed so fix it.
    base = sys.path.pop(0)
    base = base.split(os.path.sep)[:-1]
    base = os.path.sep.join(base)
    sys.path.insert(0, base)
# end remote debugger startup

# If exit_val is not None, exit with given value at end.
exit_val = None


def getpass_safe(message):
    # getpass() in Python 2.x will call str() on our prompt.  So we can't pass
    # in non-ascii characters.
    import getpass
    import locale
    message = message.encode(locale.getpreferredencoding(), 'replace')
    return getpass.getpass(message)


def get_passphrase(n, action, for_signing=False):
    """
    Check to make sure passphrase is indeed needed, then get
    the passphrase from environment, from gpg-agent, or user

    If n=3, a password is requested and verified. If n=2, the current
    password is verified. If n=1, a password is requested without
    verification for the time being.

    @type  n: int
    @param n: verification level for a passphrase being requested
    @type  action: string
    @param action: action to perform
    @type  for_signing: boolean
    @param for_signing: true if the passphrase is for a signing key, false if not
    @rtype: string
    @return: passphrase
    """

    # First try the environment
    try:
        if for_signing:
            return os.environ['SIGN_PASSPHRASE']
        else:
            return os.environ['PASSPHRASE']
    except KeyError:
        pass

    # check if we can reuse an already set (signing_)passphrase
    # if signing key is also an encryption key assume that the passphrase is identical
    if (for_signing and
            (globals.gpg_profile.sign_key in globals.gpg_profile.recipients or
             globals.gpg_profile.sign_key in globals.gpg_profile.hidden_recipients) and
             'PASSPHRASE' in os.environ):  # noqa
        log.Notice(_("Reuse configured PASSPHRASE as SIGN_PASSPHRASE"))
        return os.environ['PASSPHRASE']
    # if one encryption key is also the signing key assume that the passphrase is identical
    if (not for_signing and
            (globals.gpg_profile.sign_key in globals.gpg_profile.recipients or
             globals.gpg_profile.sign_key in globals.gpg_profile.hidden_recipients) and
             'SIGN_PASSPHRASE' in os.environ):  # noqa
        log.Notice(_("Reuse configured SIGN_PASSPHRASE as PASSPHRASE"))
        return os.environ['SIGN_PASSPHRASE']

    # Next, verify we need to ask the user

    # Assumptions:
    #   - encrypt-key has no passphrase
    #   - sign-key requires passphrase
    #   - gpg-agent supplies all, no user interaction

    # no passphrase if --no-encryption or --use-agent
    if not globals.encryption or globals.use_agent:
        return ""

    # these commands don't need a password
    elif action in ["collection-status",
                    "list-current",
                    "remove-all-but-n-full",
                    "remove-all-inc-of-but-n-full",
                    "remove-old",
                    ]:
        return ""

    # for a full backup, we don't need a password if
    # there is no sign_key and there are recipients
    elif (action == "full" and
          (globals.gpg_profile.recipients or globals.gpg_profile.hidden_recipients) and not
          globals.gpg_profile.sign_key and not globals.restart):
        return ""

    # for an inc backup, we don't need a password if
    # there is no sign_key and there are recipients
    elif (action == "inc" and
          (globals.gpg_profile.recipients or globals.gpg_profile.hidden_recipients) and not
          globals.gpg_profile.sign_key and not globals.restart):
        return ""

    # Finally, ask the user for the passphrase
    else:
        log.Info(_("PASSPHRASE variable not set, asking user."))
        use_cache = True
        while 1:
            # ask the user to enter a new passphrase to avoid an infinite loop
            # if the user made a typo in the first passphrase
            if use_cache and n == 2:
                if for_signing:
                    pass1 = globals.gpg_profile.signing_passphrase
                else:
                    pass1 = globals.gpg_profile.passphrase
            else:
                if for_signing:
                    if use_cache and globals.gpg_profile.signing_passphrase:
                        pass1 = globals.gpg_profile.signing_passphrase
                    else:
                        pass1 = getpass_safe(_("GnuPG passphrase for signing key:") + " ")
                else:
                    if use_cache and globals.gpg_profile.passphrase:
                        pass1 = globals.gpg_profile.passphrase
                    else:
                        pass1 = getpass_safe(_("GnuPG passphrase for decryption:") + " ")

            if n == 1:
                pass2 = pass1
            elif for_signing:
                pass2 = getpass_safe(_("Retype passphrase for signing key to confirm: "))
            else:
                pass2 = getpass_safe(_("Retype passphrase for decryption to confirm: "))

            if not pass1 == pass2:
                log.Log(_("First and second passphrases do not match!  Please try again."),
                        log.WARNING, force_print=True)
                use_cache = False
                continue

            if not pass1 and not (globals.gpg_profile.recipients or
                                  globals.gpg_profile.hidden_recipients) and not for_signing:
                log.Log(_("Cannot use empty passphrase with symmetric encryption!  Please try again."),
                        log.WARNING, force_print=True)
                use_cache = False
                continue

            return pass1


def dummy_backup(tarblock_iter):
    """
    Fake writing to backend, but do go through all the source paths.

    @type tarblock_iter: tarblock_iter
    @param tarblock_iter: iterator for current tar block

    @rtype: int
    @return: constant 0 (zero)
    """
    try:
        # Just spin our wheels
        while tarblock_iter.next():
            pass
    except StopIteration:
        pass
    log.Progress(None, diffdir.stats.SourceFileSize)
    return 0


def restart_position_iterator(tarblock_iter):
    """
    Fake writing to backend, but do go through all the source paths.
    Stop when we have processed the last file and block from the
    last backup.  Normal backup will proceed at the start of the
    next volume in the set.

    @type tarblock_iter: tarblock_iter
    @param tarblock_iter: iterator for current tar block

    @rtype: int
    @return: constant 0 (zero)
    """
    last_index = globals.restart.last_index
    last_block = globals.restart.last_block
    try:
        # Just spin our wheels
        iter_result = tarblock_iter.next()
        while iter_result:
            if (tarblock_iter.previous_index == last_index):
                # If both the previous index and this index are done, exit now
                # before we hit the next index, to prevent skipping its first
                # block.
                if not last_block and not tarblock_iter.previous_block:
                    break
                # Only check block number if last_block is also a number
                if last_block and tarblock_iter.previous_block > last_block:
                    break
            if tarblock_iter.previous_index > last_index:
                log.Warn(_("File %s complete in backup set.\n"
                           "Continuing restart on file %s.") %
                         (util.uindex(last_index), util.uindex(tarblock_iter.previous_index)),
                         log.ErrorCode.restart_file_not_found)
                # We went too far! Stuff the data back into place before restarting
                tarblock_iter.queue_index_data(iter_result)
                break
            iter_result = tarblock_iter.next()
    except StopIteration:
        log.Warn(_("File %s missing in backup set.\n"
                   "Continuing restart on file %s.") %
                 (util.uindex(last_index), util.uindex(tarblock_iter.previous_index)),
                 log.ErrorCode.restart_file_not_found)


def write_multivol(backup_type, tarblock_iter, man_outfp, sig_outfp, backend):
    """
    Encrypt volumes of tarblock_iter and write to backend

    backup_type should be "inc" or "full" and only matters here when
    picking the filenames.  The path_prefix will determine the names
    of the files written to backend.  Also writes manifest file.
    Returns number of bytes written.

    @type backup_type: string
    @param backup_type: type of backup to perform, either 'inc' or 'full'
    @type tarblock_iter: tarblock_iter
    @param tarblock_iter: iterator for current tar block
    @type backend: callable backend object
    @param backend: I/O backend for selected protocol

    @rtype: int
    @return: bytes written
    """

    def get_indicies(tarblock_iter):
        """Return start_index and end_index of previous volume"""
        start_index, start_block = tarblock_iter.recall_index()
        if start_index is None:
            start_index = ()
            start_block = None
        if start_block:
            start_block -= 1
        end_index, end_block = tarblock_iter.get_previous_index()
        if end_index is None:
            end_index = start_index
            end_block = start_block
        if end_block:
            end_block -= 1
        return start_index, start_block, end_index, end_block

    def validate_block(orig_size, dest_filename):
        info = backend.query_info([dest_filename])[dest_filename]
        size = info['size']
        if size is None:
            return  # error querying file
        if size != orig_size:
            code_extra = "%s %d %d" % (util.escape(dest_filename), orig_size, size)
            log.FatalError(_("File %s was corrupted during upload.") % util.ufn(dest_filename),
                           log.ErrorCode.volume_wrong_size, code_extra)

    def put(tdp, dest_filename, vol_num):
        """
        Retrieve file size *before* calling backend.put(), which may (at least
        in case of the localbackend) rename the temporary file to the target
        instead of copying.
        """
        putsize = tdp.getsize()
        if globals.skip_volume != vol_num:  # for testing purposes only
            backend.put(tdp, dest_filename)
        validate_block(putsize, dest_filename)
        if tdp.stat:
            tdp.delete()
        return putsize

    def validate_encryption_settings(backup_set, manifest):
        """
        When restarting a backup, we have no way to verify that the current
        passphrase is the same as the one used for the beginning of the backup.
        This is because the local copy of the manifest is unencrypted and we
        don't need to decrypt the existing volumes on the backend.  To ensure
        that we are using the same passphrase, we manually download volume 1
        and decrypt it with the current passphrase.  We also want to confirm
        that we're using the same encryption settings (i.e. we don't switch
        from encrypted to non in the middle of a backup chain), so we check
        that the vol1 filename on the server matches the settings of this run.
        """
        vol1_filename = file_naming.get(backup_type, 1,
                                        encrypted=globals.encryption,
                                        gzipped=globals.compression)
        if vol1_filename != backup_set.volume_name_dict[1]:
            log.FatalError(_("Restarting backup, but current encryption "
                             "settings do not match original settings"),
                           log.ErrorCode.enryption_mismatch)

        # Settings are same, let's check passphrase itself if we are encrypted
        if globals.encryption:
            fileobj = restore_get_enc_fileobj(globals.backend, vol1_filename,
                                              manifest.volume_info_dict[1])
            fileobj.close()

    if not globals.restart:
        # normal backup start
        vol_num = 0
        mf = manifest.Manifest(fh=man_outfp)
        mf.set_dirinfo()
    else:
        # restart from last known position
        mf = globals.restart.last_backup.get_local_manifest()
        globals.restart.checkManifest(mf)
        globals.restart.setLastSaved(mf)
        validate_encryption_settings(globals.restart.last_backup, mf)
        mf.fh = man_outfp
        last_block = globals.restart.last_block
        log.Notice(_("Restarting after volume %s, file %s, block %s") %
                   (globals.restart.start_vol,
                    util.uindex(globals.restart.last_index),
                    globals.restart.last_block))
        vol_num = globals.restart.start_vol
        restart_position_iterator(tarblock_iter)

    at_end = 0
    bytes_written = 0

    # If --progress option is given, initiate a background thread that will
    # periodically report progress to the Log.
    if globals.progress:
        progress.tracker.set_start_volume(vol_num + 1)
        progress.progress_thread.start()

    # This assertion must be kept until we have solved the problem
    # of concurrency at the backend level. Concurrency 1 is fine
    # because the actual I/O concurrency on backends is limited to
    # 1 as usual, but we are allowed to perform local CPU
    # intensive tasks while that single upload is happening. This
    # is an assert put in place to avoid someone accidentally
    # enabling concurrency above 1, before adequate work has been
    # done on the backends to make them support concurrency.
    assert globals.async_concurrency <= 1

    io_scheduler = asyncscheduler.AsyncScheduler(globals.async_concurrency)
    async_waiters = []

    while not at_end:
        # set up iterator
        tarblock_iter.remember_next_index()  # keep track of start index

        # Create volume
        vol_num += 1
        dest_filename = file_naming.get(backup_type, vol_num,
                                        encrypted=globals.encryption,
                                        gzipped=globals.compression)
        tdp = dup_temp.new_tempduppath(file_naming.parse(dest_filename))

        # write volume
        if globals.encryption:
            at_end = gpg.GPGWriteFile(tarblock_iter, tdp.name, globals.gpg_profile,
                                      globals.volsize)
        elif globals.compression:
            at_end = gpg.GzipWriteFile(tarblock_iter, tdp.name, globals.volsize)
        else:
            at_end = gpg.PlainWriteFile(tarblock_iter, tdp.name, globals.volsize)
        tdp.setdata()

        # Add volume information to manifest
        vi = manifest.VolumeInfo()
        vi.set_info(vol_num, *get_indicies(tarblock_iter))
        vi.set_hash("SHA1", gpg.get_hash("SHA1", tdp))
        mf.add_volume_info(vi)

        # Checkpoint after each volume so restart has a place to restart.
        # Note that until after the first volume, all files are temporary.
        if vol_num == 1:
            sig_outfp.to_partial()
            man_outfp.to_partial()
        else:
            sig_outfp.flush()
            man_outfp.flush()

        async_waiters.append(io_scheduler.schedule_task(lambda tdp, dest_filename,
                                                        vol_num: put(tdp, dest_filename, vol_num),
                                                        (tdp, dest_filename, vol_num)))

        # Log human-readable version as well as raw numbers for machine consumers
        log.Progress(_('Processed volume %d') % vol_num, diffdir.stats.SourceFileSize)
        # Snapshot (serialize) progress now as a Volume has been completed.
        # This is always the last restore point when it comes to restart a failed backup
        if globals.progress:
            progress.tracker.snapshot_progress(vol_num)

        # for testing purposes only - assert on inc or full
        assert globals.fail_on_volume != vol_num, "Forced assertion for testing at volume %d" % vol_num

    # Collect byte count from all asynchronous jobs; also implicitly waits
    # for them all to complete.
    for waiter in async_waiters:
        bytes_written += waiter()

    # Upload the collection summary.
    # bytes_written += write_manifest(mf, backup_type, backend)

    return bytes_written


def get_man_fileobj(backup_type):
    """
    Return a fileobj opened for writing, save results as manifest

    Save manifest in globals.archive_dir gzipped.
    Save them on the backend encrypted as needed.

    @type man_type: string
    @param man_type: either "full" or "new"

    @rtype: fileobj
    @return: fileobj opened for writing
    """
    assert backup_type == "full" or backup_type == "inc"

    part_man_filename = file_naming.get(backup_type,
                                        manifest=True,
                                        partial=True)
    perm_man_filename = file_naming.get(backup_type,
                                        manifest=True)
    remote_man_filename = file_naming.get(backup_type,
                                          manifest=True,
                                          encrypted=globals.encryption)

    fh = dup_temp.get_fileobj_duppath(globals.archive_dir,
                                      part_man_filename,
                                      perm_man_filename,
                                      remote_man_filename)
    return fh


def get_sig_fileobj(sig_type):
    """
    Return a fileobj opened for writing, save results as signature

    Save signatures in globals.archive_dir gzipped.
    Save them on the backend encrypted as needed.

    @type sig_type: string
    @param sig_type: either "full-sig" or "new-sig"

    @rtype: fileobj
    @return: fileobj opened for writing
    """
    assert sig_type in ["full-sig", "new-sig"]

    part_sig_filename = file_naming.get(sig_type,
                                        gzipped=False,
                                        partial=True)
    perm_sig_filename = file_naming.get(sig_type,
                                        gzipped=True)
    remote_sig_filename = file_naming.get(sig_type, encrypted=globals.encryption,
                                          gzipped=globals.compression)

    fh = dup_temp.get_fileobj_duppath(globals.archive_dir,
                                      part_sig_filename,
                                      perm_sig_filename,
                                      remote_sig_filename,
                                      overwrite=True)
    return fh


def full_backup(col_stats):
    """
    Do full backup of directory to backend, using archive_dir

    @type col_stats: CollectionStatus object
    @param col_stats: collection status

    @rtype: void
    @return: void
    """
    if globals.progress:
        progress.tracker = progress.ProgressTracker()
        # Fake a backup to compute total of moving bytes
        tarblock_iter = diffdir.DirFull(globals.select)
        dummy_backup(tarblock_iter)
        # Store computed stats to compute progress later
        progress.tracker.set_evidence(diffdir.stats, True)
        # Reinit the globals.select iterator, so
        # the core of duplicity can rescan the paths
        commandline.set_selection()
        progress.progress_thread = progress.LogProgressThread()

    if globals.dry_run:
        tarblock_iter = diffdir.DirFull(globals.select)
        bytes_written = dummy_backup(tarblock_iter)
        col_stats.set_values(sig_chain_warning=None)
    else:
        sig_outfp = get_sig_fileobj("full-sig")
        man_outfp = get_man_fileobj("full")
        tarblock_iter = diffdir.DirFull_WriteSig(globals.select,
                                                 sig_outfp)
        bytes_written = write_multivol("full", tarblock_iter,
                                       man_outfp, sig_outfp,
                                       globals.backend)

        # close sig file, send to remote, and rename to final
        sig_outfp.close()
        sig_outfp.to_remote()
        sig_outfp.to_final()

        # close manifest, send to remote, and rename to final
        man_outfp.close()
        man_outfp.to_remote()
        man_outfp.to_final()

        if globals.progress:
            # Terminate the background thread now, if any
            progress.progress_thread.finished = True
            progress.progress_thread.join()
            log.TransferProgress(100.0, 0, progress.tracker.total_bytecount,
                                 progress.tracker.total_elapsed_seconds(),
                                 progress.tracker.speed, False)

        col_stats.set_values(sig_chain_warning=None)

    print_statistics(diffdir.stats, bytes_written)


def check_sig_chain(col_stats):
    """
    Get last signature chain for inc backup, or None if none available

    @type col_stats: CollectionStatus object
    @param col_stats: collection status
    """
    if not col_stats.matched_chain_pair:
        if globals.incremental:
            log.FatalError(_("Fatal Error: Unable to start incremental backup.  "
                             "Old signatures not found and incremental specified"),
                           log.ErrorCode.inc_without_sigs)
        else:
            log.Warn(_("No signatures found, switching to full backup."))
        return None
    return col_stats.matched_chain_pair[0]


def print_statistics(stats, bytes_written):
    """
    If globals.print_statistics, print stats after adding bytes_written

    @rtype: void
    @return: void
    """
    if globals.print_statistics:
        diffdir.stats.TotalDestinationSizeChange = bytes_written
        logstring = diffdir.stats.get_stats_logstring(_("Backup Statistics"))
        log.Log(logstring, log.NOTICE, force_print=True)


def incremental_backup(sig_chain):
    """
    Do incremental backup of directory to backend, using archive_dir

    @rtype: void
    @return: void
    """
    if not globals.restart:
        dup_time.setprevtime(sig_chain.end_time)
        if dup_time.curtime == dup_time.prevtime:
            time.sleep(2)
            dup_time.setcurtime()
            assert dup_time.curtime != dup_time.prevtime, \
                "time not moving forward at appropriate pace - system clock issues?"

    if globals.progress:
        progress.tracker = progress.ProgressTracker()
        # Fake a backup to compute total of moving bytes
        tarblock_iter = diffdir.DirDelta(globals.select,
                                         sig_chain.get_fileobjs())
        dummy_backup(tarblock_iter)
        # Store computed stats to compute progress later
        progress.tracker.set_evidence(diffdir.stats, False)
        # Reinit the globals.select iterator, so
        # the core of duplicity can rescan the paths
        commandline.set_selection()
        progress.progress_thread = progress.LogProgressThread()

    if globals.dry_run:
        tarblock_iter = diffdir.DirDelta(globals.select,
                                         sig_chain.get_fileobjs())
        bytes_written = dummy_backup(tarblock_iter)
    else:
        new_sig_outfp = get_sig_fileobj("new-sig")
        new_man_outfp = get_man_fileobj("inc")
        tarblock_iter = diffdir.DirDelta_WriteSig(globals.select,
                                                  sig_chain.get_fileobjs(),
                                                  new_sig_outfp)
        bytes_written = write_multivol("inc", tarblock_iter,
                                       new_man_outfp, new_sig_outfp,
                                       globals.backend)

        # close sig file and rename to final
        new_sig_outfp.close()
        new_sig_outfp.to_remote()
        new_sig_outfp.to_final()

        # close manifest and rename to final
        new_man_outfp.close()
        new_man_outfp.to_remote()
        new_man_outfp.to_final()

        if globals.progress:
            # Terminate the background thread now, if any
            progress.progress_thread.finished = True
            progress.progress_thread.join()
            log.TransferProgress(100.0, 0, progress.tracker.total_bytecount,
                                 progress.tracker.total_elapsed_seconds(),
                                 progress.tracker.speed, False)

    print_statistics(diffdir.stats, bytes_written)


def list_current(col_stats):
    """
    List the files current in the archive (examining signature only)

    @type col_stats: CollectionStatus object
    @param col_stats: collection status

    @rtype: void
    @return: void
    """
    time = globals.restore_time or dup_time.curtime
    sig_chain = col_stats.get_signature_chain_at_time(time)
    path_iter = diffdir.get_combined_path_iter(sig_chain.get_fileobjs(time))
    for path in path_iter:
        if path.difftype != "deleted":
            user_info = u"%s %s" % (dup_time.timetopretty(path.getmtime()),
                                    util.ufn(path.get_relative_path()))
            log_info = "%s %s %s" % (dup_time.timetostring(path.getmtime()),
                                     util.escape(path.get_relative_path()),
                                     path.type)
            log.Log(user_info, log.INFO, log.InfoCode.file_list,
                    log_info, True)


def restore(col_stats):
    """
    Restore archive in globals.backend to globals.local_path

    @type col_stats: CollectionStatus object
    @param col_stats: collection status

    @rtype: void
    @return: void
    """
    if globals.dry_run:
        return
    if not patchdir.Write_ROPaths(globals.local_path,
                                  restore_get_patched_rop_iter(col_stats)):
        if globals.restore_dir:
            log.FatalError(_("%s not found in archive - no files restored.")
                           % (util.ufn(globals.restore_dir)),
                           log.ErrorCode.restore_dir_not_found)
        else:
            log.FatalError(_("No files found in archive - nothing restored."),
                           log.ErrorCode.no_restore_files)


def restore_get_patched_rop_iter(col_stats):
    """
    Return iterator of patched ROPaths of desired restore data

    @type col_stats: CollectionStatus object
    @param col_stats: collection status
    """
    if globals.restore_dir:
        index = tuple(globals.restore_dir.split("/"))
    else:
        index = ()
    time = globals.restore_time or dup_time.curtime
    backup_chain = col_stats.get_backup_chain_at_time(time)
    assert backup_chain, col_stats.all_backup_chains
    backup_setlist = backup_chain.get_sets_at_time(time)
    num_vols = 0
    for s in backup_setlist:
        num_vols += len(s)
    cur_vol = [0]

    def get_fileobj_iter(backup_set):
        """Get file object iterator from backup_set contain given index"""
        manifest = backup_set.get_manifest()
        volumes = manifest.get_containing_volumes(index)
        for vol_num in volumes:
            yield restore_get_enc_fileobj(backup_set.backend,
                                          backup_set.volume_name_dict[vol_num],
                                          manifest.volume_info_dict[vol_num])
            cur_vol[0] += 1
            log.Progress(_('Processed volume %d of %d') % (cur_vol[0], num_vols),
                         cur_vol[0], num_vols)

    if hasattr(globals.backend, 'pre_process_download'):
        file_names = []
        for backup_set in backup_setlist:
            manifest = backup_set.get_manifest()
            volumes = manifest.get_containing_volumes(index)
            for vol_num in volumes:
                file_names.append(backup_set.volume_name_dict[vol_num])
        globals.backend.pre_process_download(file_names)

    fileobj_iters = list(map(get_fileobj_iter, backup_setlist))
    tarfiles = list(map(patchdir.TarFile_FromFileobjs, fileobj_iters))
    return patchdir.tarfiles2rop_iter(tarfiles, index)


def restore_get_enc_fileobj(backend, filename, volume_info):
    """
    Return plaintext fileobj from encrypted filename on backend

    If volume_info is set, the hash of the file will be checked,
    assuming some hash is available.  Also, if globals.sign_key is
    set, a fatal error will be raised if file not signed by sign_key.

    """
    parseresults = file_naming.parse(filename)
    tdp = dup_temp.new_tempduppath(parseresults)
    backend.get(filename, tdp)

    """ verify hash of the remote file """
    verified, hash_pair, calculated_hash = restore_check_hash(volume_info, tdp)
    if not verified:
        log.FatalError("%s\n %s\n %s\n %s\n" %
                       (_("Invalid data - %s hash mismatch for file:") %
                        hash_pair[0],
                        util.ufn(filename),
                        _("Calculated hash: %s") % calculated_hash,
                        _("Manifest hash: %s") % hash_pair[1]),
                       log.ErrorCode.mismatched_hash)

    fileobj = tdp.filtered_open_with_delete("rb")
    if parseresults.encrypted and globals.gpg_profile.sign_key:
        restore_add_sig_check(fileobj)
    return fileobj


def restore_check_hash(volume_info, vol_path):
    """
    Check the hash of vol_path path against data in volume_info

    @rtype: boolean
    @return: true (verified) / false (failed)
    """
    hash_pair = volume_info.get_best_hash()
    if hash_pair:
        calculated_hash = gpg.get_hash(hash_pair[0], vol_path)
        if calculated_hash != hash_pair[1]:
            return False, hash_pair, calculated_hash
    """ reached here, verification passed """
    return True, hash_pair, calculated_hash


def restore_add_sig_check(fileobj):
    """
    Require signature when closing fileobj matches sig in gpg_profile

    @rtype: void
    @return: void
    """
    assert (isinstance(fileobj, dup_temp.FileobjHooked) and
            isinstance(fileobj.fileobj, gpg.GPGFile)), fileobj

    def check_signature():
        """Thunk run when closing volume file"""
        actual_sig = fileobj.fileobj.get_signature()
        actual_sig = "None" if actual_sig is None else actual_sig
        sign_key = globals.gpg_profile.sign_key
        sign_key = "None" if sign_key is None else sign_key
        ofs = -min(len(actual_sig), len(sign_key))
        if actual_sig[ofs:] != sign_key[ofs:]:
            log.FatalError(_("Volume was signed by key %s, not %s") %
                           (actual_sig[ofs:], sign_key[ofs:]),
                           log.ErrorCode.unsigned_volume)

    fileobj.addhook(check_signature)


def verify(col_stats):
    """
    Verify files, logging differences

    @type col_stats: CollectionStatus object
    @param col_stats: collection status

    @rtype: void
    @return: void
    """
    global exit_val
    collated = diffdir.collate2iters(restore_get_patched_rop_iter(col_stats),
                                     globals.select)
    diff_count = 0
    total_count = 0
    for backup_ropath, current_path in collated:
        if not backup_ropath:
            backup_ropath = path.ROPath(current_path.index)
        if not current_path:
            current_path = path.ROPath(backup_ropath.index)
        if not backup_ropath.compare_verbose(current_path, globals.compare_data):
            diff_count += 1
        total_count += 1
    # Unfortunately, ngettext doesn't handle multiple number variables, so we
    # split up the string.
    log.Notice(_("Verify complete: %s, %s.") %
               (ngettext("%d file compared",
                         "%d files compared", total_count) % total_count,
                ngettext("%d difference found",
                         "%d differences found", diff_count) % diff_count))
    if diff_count >= 1:
        exit_val = 1


def cleanup(col_stats):
    """
    Delete the extraneous files in the current backend

    @type col_stats: CollectionStatus object
    @param col_stats: collection status

    @rtype: void
    @return: void
    """
    ext_local, ext_remote = col_stats.get_extraneous(globals.extra_clean)
    extraneous = ext_local + ext_remote
    if not extraneous:
        log.Warn(_("No extraneous files found, nothing deleted in cleanup."))
        return

    filestr = u"\n".join(map(util.ufn, extraneous))
    if globals.force:
        log.Notice(ngettext("Deleting this file from backend:",
                            "Deleting these files from backend:",
                            len(extraneous)) + u"\n" + filestr)
        if not globals.dry_run:
            col_stats.backend.delete(ext_remote)
            for fn in ext_local:
                try:
                    globals.archive_dir.append(fn).delete()
                except Exception:
                    pass
    else:
        log.Notice(ngettext("Found the following file to delete:",
                            "Found the following files to delete:",
                            len(extraneous)) + u"\n" + filestr + u"\n" +
                   _("Run duplicity again with the --force option to actually delete."))


def remove_all_but_n_full(col_stats):
    """
    Remove backup files older than the last n full backups.

    @type col_stats: CollectionStatus object
    @param col_stats: collection status

    @rtype: void
    @return: void
    """
    assert globals.keep_chains is not None

    globals.remove_time = col_stats.get_nth_last_full_backup_time(globals.keep_chains)

    remove_old(col_stats)


def remove_old(col_stats):
    """
    Remove backup files older than globals.remove_time from backend

    @type col_stats: CollectionStatus object
    @param col_stats: collection status

    @rtype: void
    @return: void
    """
    assert globals.remove_time is not None

    def set_times_str(setlist):
        """Return string listing times of sets in setlist"""
        return "\n".join([dup_time.timetopretty(s.get_time()) for s in setlist])

    def chain_times_str(chainlist):
        """Return string listing times of chains in chainlist"""
        return "\n".join([dup_time.timetopretty(s.end_time) for s in chainlist])

    req_list = col_stats.get_older_than_required(globals.remove_time)
    if req_list:
        log.Warn("%s\n%s\n%s" %
                 (_("There are backup set(s) at time(s):"),
                  set_times_str(req_list),
                  _("Which can't be deleted because newer sets depend on them.")))

    if (col_stats.matched_chain_pair and
            col_stats.matched_chain_pair[1].end_time < globals.remove_time):
        log.Warn(_("Current active backup chain is older than specified time.  "
                   "However, it will not be deleted.  To remove all your backups, "
                   "manually purge the repository."))

    chainlist = col_stats.get_chains_older_than(globals.remove_time)

    if globals.remove_all_inc_of_but_n_full_mode:
        # ignore chains without incremental backups:
        chainlist = list(x for x in chainlist if
                         (isinstance(x, collections.SignatureChain) and x.inclist) or
                         (isinstance(x, collections.BackupChain) and x.incset_list))

    if not chainlist:
        log.Notice(_("No old backup sets found, nothing deleted."))
        return
    if globals.force:
        log.Notice(ngettext("Deleting backup chain at time:",
                            "Deleting backup chains at times:",
                            len(chainlist)) +
                   "\n" + chain_times_str(chainlist))
        # Add signature files too, since they won't be needed anymore
        chainlist += col_stats.get_signature_chains_older_than(globals.remove_time)
        chainlist.reverse()  # save oldest for last
        for chain in chainlist:
            # if remove_all_inc_of_but_n_full_mode mode, remove only
            # incrementals one and not full
            if globals.remove_all_inc_of_but_n_full_mode:
                if isinstance(chain, collections.SignatureChain):
                    chain_desc = _("Deleting any incremental signature chain rooted at %s")
                else:
                    chain_desc = _("Deleting any incremental backup chain rooted at %s")
            else:
                if isinstance(chain, collections.SignatureChain):
                    chain_desc = _("Deleting complete signature chain %s")
                else:
                    chain_desc = _("Deleting complete backup chain %s")
            log.Notice(chain_desc % dup_time.timetopretty(chain.end_time))
            if not globals.dry_run:
                chain.delete(keep_full=globals.remove_all_inc_of_but_n_full_mode)
        col_stats.set_values(sig_chain_warning=None)
    else:
        log.Notice(ngettext("Found old backup chain at the following time:",
                            "Found old backup chains at the following times:",
                            len(chainlist)) +
                   "\n" + chain_times_str(chainlist) + "\n" +
                   _("Rerun command with --force option to actually delete."))


def sync_archive():
    """
    Synchronize local archive manifest file and sig chains to remote archives.
    Copy missing files from remote to local as needed to make sure the local
    archive is synchronized to remote storage.

    @rtype: void
    @return: void
    """
    suffixes = [".g", ".gpg", ".z", ".gz", ".part"]

    def get_metafiles(filelist):
        """
        Return metafiles of interest from the file list.
        Files of interest are:
          sigtar - signature files
          manifest - signature files
          duplicity partial versions of the above
        Files excluded are:
          non-duplicity files

        @rtype: list
        @return: list of duplicity metadata files
        """
        metafiles = {}
        partials = {}
        need_passphrase = False
        for fn in filelist:
            pr = file_naming.parse(fn)
            if not pr:
                continue
            if pr.encrypted:
                need_passphrase = True
            if pr.type in ["full-sig", "new-sig"] or pr.manifest:
                base, ext = os.path.splitext(fn)
                if ext not in suffixes:
                    base = fn
                if pr.partial:
                    partials[base] = fn
                else:
                    metafiles[base] = fn
        return metafiles, partials, need_passphrase

    def copy_raw(src_iter, filename):
        """
        Copy data from src_iter to file at fn
        """
        file = open(filename, "wb")
        while True:
            try:
                data = src_iter.next().data
            except StopIteration:
                break
            file.write(data)
        file.close()

    def resolve_basename(fn):
        """
        @return: (parsedresult, local_name, remote_name)
        """
        pr = file_naming.parse(fn)

        base, ext = os.path.splitext(fn)
        if ext not in suffixes:
            base = fn

        suffix = file_naming.get_suffix(False, not pr.manifest)
        loc_name = base + suffix

        return (pr, loc_name, fn)

    def remove_local(fn):
        del_name = globals.archive_dir.append(fn).name

        log.Notice(_("Deleting local %s (not authoritative at backend).") %
                   util.ufn(del_name))
        try:
            util.ignore_missing(os.unlink, del_name)
        except Exception as e:
            log.Warn(_("Unable to delete %s: %s") % (util.ufn(del_name),
                                                     util.uexc(e)))

    def copy_to_local(fn):
        """
        Copy remote file fn to local cache.
        """
        class Block:
            """
            Data block to return from SrcIter
            """

            def __init__(self, data):
                self.data = data

        class SrcIter:
            """
            Iterate over source and return Block of data.
            """

            def __init__(self, fileobj):
                self.fileobj = fileobj

            def next(self):
                try:
                    res = Block(self.fileobj.read(self.get_read_size()))
                except Exception:
                    if hasattr(self.fileobj, 'name'):
                        name = self.fileobj.name
                    else:
                        name = None
                    log.FatalError(_("Failed to read %s: %s") %
                                   (util.ufn(name), sys.exc_info()),
                                   log.ErrorCode.generic)
                if not res.data:
                    self.fileobj.close()
                    raise StopIteration
                return res

            def get_read_size(self):
                return 128 * 1024

            def get_footer(self):
                return ""

        log.Notice(_("Copying %s to local cache.") % util.ufn(fn))

        pr, loc_name, rem_name = resolve_basename(fn)

        fileobj = globals.backend.get_fileobj_read(fn)
        src_iter = SrcIter(fileobj)
        tdp = dup_temp.new_tempduppath(file_naming.parse(loc_name))
        if pr.manifest:
            copy_raw(src_iter, tdp.name)
        else:
            gpg.GzipWriteFile(src_iter, tdp.name, size=sys.maxsize)
        tdp.setdata()
        tdp.move(globals.archive_dir.append(loc_name))

    # get remote metafile list
    remlist = globals.backend.list()
    remote_metafiles, ignored, rem_needpass = get_metafiles(remlist)

    # get local metafile list
    loclist = globals.archive_dir.listdir()
    local_metafiles, local_partials, loc_needpass = get_metafiles(loclist)

    # we have the list of metafiles on both sides. remote is always
    # authoritative. figure out which are local spurious (should not
    # be there) and missing (should be there but are not).
    local_keys = local_metafiles.keys()
    remote_keys = remote_metafiles.keys()

    local_missing = []
    local_spurious = []

    for key in remote_keys:
        # If we lost our cache, re-get the remote file.  But don't do it if we
        # already have a local partial.  The local partial will already be
        # complete in this case (seems we got interrupted before we could move
        # it to its final location).
        if key not in local_keys and key not in local_partials:
            local_missing.append(remote_metafiles[key])

    for key in local_keys:
        # If we have a file locally that is unnecessary, delete it.  Also
        # delete final versions of partial files because if we have both, it
        # means the write of the final version got interrupted.
        if key not in remote_keys or key in local_partials:
            local_spurious.append(local_metafiles[key])

    # finally finish the process
    if not local_missing and not local_spurious:
        log.Notice(_("Local and Remote metadata are synchronized, no sync needed."))
    else:
        local_missing.sort()
        local_spurious.sort()
        if not globals.dry_run:
            log.Notice(_("Synchronizing remote metadata to local cache..."))
            if local_missing and (rem_needpass or loc_needpass):
                # password for the --encrypt-key
                globals.gpg_profile.passphrase = get_passphrase(1, "sync")
            for fn in local_spurious:
                remove_local(fn)
            if hasattr(globals.backend, 'pre_process_download'):
                globals.backend.pre_process_download(local_missing)
            for fn in local_missing:
                copy_to_local(fn)
        else:
            if local_missing:
                log.Notice(_("Sync would copy the following from remote to local:") +
                           u"\n" + u"\n".join(map(util.ufn, local_missing)))
            if local_spurious:
                log.Notice(_("Sync would remove the following spurious local files:") +
                           u"\n" + u"\n".join(map(util.ufn, local_spurious)))


def check_last_manifest(col_stats):
    """
    Check consistency and hostname/directory of last manifest

    @type col_stats: CollectionStatus object
    @param col_stats: collection status

    @rtype: void
    @return: void
    """
    if not col_stats.all_backup_chains:
        return
    last_backup_set = col_stats.all_backup_chains[-1].get_last()
    last_backup_set.check_manifests()


def check_resources(action):
    """
    Check for sufficient resources:
      - temp space for volume build
      - enough max open files
    Put out fatal error if not sufficient to run

    @type action: string
    @param action: action in progress

    @rtype: void
    @return: void
    """
    if action in ["full", "inc", "restore"]:
        # Make sure we have enough resouces to run
        # First check disk space in temp area.
        tempfile, tempname = tempdir.default().mkstemp()
        os.close(tempfile)
        # strip off the temp dir and file
        tempfs = os.path.sep.join(tempname.split(os.path.sep)[:-2])
        try:
            stats = os.statvfs(tempfs)
        except Exception:
            log.FatalError(_("Unable to get free space on temp."),
                           log.ErrorCode.get_freespace_failed)
        # Calculate space we need for at least 2 volumes of full or inc
        # plus about 30% of one volume for the signature files.
        freespace = stats[statvfs.F_FRSIZE] * stats[statvfs.F_BAVAIL]
        needspace = (((globals.async_concurrency + 1) * globals.volsize) +
                     int(0.30 * globals.volsize))
        if freespace < needspace:
            log.FatalError(_("Temp space has %d available, backup needs approx %d.") %
                           (freespace, needspace), log.ErrorCode.not_enough_freespace)
        else:
            log.Info(_("Temp has %d available, backup will use approx %d.") %
                     (freespace, needspace))

        # Some environments like Cygwin run with an artificially
        # low value for max open files.  Check for safe number.
        try:
            soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
        except resource.error:
            log.FatalError(_("Unable to get max open files."),
                           log.ErrorCode.get_ulimit_failed)
        maxopen = min([l for l in (soft, hard) if l > -1])
        if maxopen < 1024:
            log.FatalError(_("Max open files of %s is too low, should be >= 1024.\n"
                             "Use 'ulimit -n 1024' or higher to correct.\n") % (maxopen,),
                           log.ErrorCode.maxopen_too_low)


def log_startup_parms(verbosity=log.INFO):
    """
    log Python, duplicity, and system versions
    """
    log.Log(u'=' * 80, verbosity)
    log.Log(u"duplicity 0.7.17 (February 26, 2018)", verbosity)
    log.Log(u"Args: %s" % util.ufn(' '.join(sys.argv)), verbosity)
    log.Log(u' '.join(platform.uname()), verbosity)
    log.Log(u"%s %s" % (sys.executable or sys.platform, sys.version), verbosity)
    log.Log(u'=' * 80, verbosity)


class Restart:
    """
    Class to aid in restart of inc or full backup.
    Instance in globals.restart if restart in progress.
    """

    def __init__(self, last_backup):
        self.type = None
        self.start_time = None
        self.end_time = None
        self.start_vol = None
        self.last_index = None
        self.last_block = None
        self.last_backup = last_backup
        self.setParms(last_backup)

    def setParms(self, last_backup):
        if last_backup.time:
            self.type = "full"
            self.time = last_backup.time
        else:
            self.type = "inc"
            self.end_time = last_backup.end_time
            self.start_time = last_backup.start_time
        # We start one volume back in case we weren't able to finish writing
        # the most recent block.  Actually checking if we did (via hash) would
        # involve downloading the block.  Easier to just redo one block.
        self.start_vol = max(len(last_backup) - 1, 0)

    def checkManifest(self, mf):
        mf_len = len(mf.volume_info_dict)
        if (mf_len != self.start_vol) or not (mf_len and self.start_vol):
            if self.start_vol == 0:
                # upload of 1st vol failed, clean and restart
                log.Notice(_("RESTART: The first volume failed to upload before termination.\n"
                             "         Restart is impossible...starting backup from beginning."))
                self.last_backup.delete()
                os.execve(sys.argv[0], sys.argv, os.environ)
            elif mf_len - self.start_vol > 0:
                # upload of N vols failed, fix manifest and restart
                log.Notice(_("RESTART: Volumes %d to %d failed to upload before termination.\n"
                             "         Restarting backup at volume %d.") %
                           (self.start_vol + 1, mf_len, self.start_vol + 1))
                for vol in range(self.start_vol + 1, mf_len + 1):
                    mf.del_volume_info(vol)
            else:
                # this is an 'impossible' state, remove last partial and restart
                log.Notice(_("RESTART: Impossible backup state: manifest has %d vols, remote has %d vols.\n"
                             "         Restart is impossible ... duplicity will clean off the last partial\n"
                             "         backup then restart the backup from the beginning.") %
                           (mf_len, self.start_vol))
                self.last_backup.delete()
                os.execve(sys.argv[0], sys.argv, os.environ)

    def setLastSaved(self, mf):
        vi = mf.volume_info_dict[self.start_vol]
        self.last_index = vi.end_index
        self.last_block = vi.end_block or 0


def main():
    """
    Start/end here
    """
    # per bug https://bugs.launchpad.net/duplicity/+bug/931175
    # duplicity crashes when PYTHONOPTIMIZE is set, so check
    # and refuse to run if it is set.
    if 'PYTHONOPTIMIZE' in os.environ:
        log.FatalError(_("""
PYTHONOPTIMIZE in the environment causes duplicity to fail to
recognize its own backups.  Please remove PYTHONOPTIMIZE from
the environment and rerun the backup.

See https://bugs.launchpad.net/duplicity/+bug/931175
"""), log.ErrorCode.pythonoptimize_set)

    # if python is run setuid, it's only partway set,
    # so make sure to run with euid/egid of root
    if os.geteuid() == 0:
        # make sure uid/gid match euid/egid
        os.setuid(os.geteuid())
        os.setgid(os.getegid())

    # set the current time strings (make it available for command line processing)
    dup_time.setcurtime()

    # determine what action we're performing and process command line
    action = commandline.ProcessCommandLine(sys.argv[1:])

    globals.lockpath = os.path.join(globals.archive_dir.name, "lockfile")
    globals.lockfile = fasteners.process_lock.InterProcessLock(globals.lockpath)
    log.Debug(_("Acquiring lockfile %s") % globals.lockpath)
    if not globals.lockfile.acquire(blocking=False):
        log.FatalError(
            "Another duplicity instance is already running with this archive directory\n",
            log.ErrorCode.user_error)
        log.shutdown()
        sys.exit(2)

    try:
        do_backup(action)

    finally:
        util.release_lockfile()


def do_backup(action):
    # set the current time strings again now that we have time separator
    if globals.current_time:
        dup_time.setcurtime(globals.current_time)
    else:
        dup_time.setcurtime()

    # log some debugging status info
    log_startup_parms(log.INFO)

    # check for disk space and available file handles
    check_resources(action)

    # check archive synch with remote, fix if needed
    if action not in ["collection-status"]:
        sync_archive()

    # get current collection status
    col_stats = collections.CollectionsStatus(globals.backend,
                                              globals.archive_dir,
                                              action).set_values()

    while True:
        # if we have to clean up the last partial, then col_stats are invalidated
        # and we have to start the process all over again until clean.
        if action in ["full", "inc", "cleanup"]:
            last_full_chain = col_stats.get_last_backup_chain()
            if not last_full_chain:
                break
            last_backup = last_full_chain.get_last()
            if last_backup.partial:
                if action in ["full", "inc"]:
                    # set restart parms from last_backup info
                    globals.restart = Restart(last_backup)
                    # (possibly) reset action
                    action = globals.restart.type
                    # reset the time strings
                    if action == "full":
                        dup_time.setcurtime(globals.restart.time)
                    else:
                        dup_time.setcurtime(globals.restart.end_time)
                        dup_time.setprevtime(globals.restart.start_time)
                    # log it -- main restart heavy lifting is done in write_multivol
                    log.Notice(_("Last %s backup left a partial set, restarting." % action))
                    break
                else:
                    # remove last partial backup and get new collection status
                    log.Notice(_("Cleaning up previous partial %s backup set, restarting." % action))
                    last_backup.delete()
                    col_stats = collections.CollectionsStatus(globals.backend,
                                                              globals.archive_dir,
                                                              action).set_values()
                    continue
            break
        break

    # OK, now we have a stable collection
    last_full_time = col_stats.get_last_full_backup_time()
    if last_full_time > 0:
        log.Notice(_("Last full backup date:") + " " + dup_time.timetopretty(last_full_time))
    else:
        log.Notice(_("Last full backup date: none"))
    if not globals.restart and action == "inc" and last_full_time < globals.full_force_time:
        log.Notice(_("Last full backup is too old, forcing full backup"))
        action = "full"
    log.PrintCollectionStatus(col_stats)

    os.umask(0o77)

    # get the passphrase if we need to based on action/options
    globals.gpg_profile.passphrase = get_passphrase(1, action)

    if action == "restore":
        restore(col_stats)
    elif action == "verify":
        verify(col_stats)
    elif action == "list-current":
        list_current(col_stats)
    elif action == "collection-status":
        log.PrintCollectionStatus(col_stats, True)
    elif action == "cleanup":
        cleanup(col_stats)
    elif action == "remove-old":
        remove_old(col_stats)
    elif action == "remove-all-but-n-full" or action == "remove-all-inc-of-but-n-full":
        remove_all_but_n_full(col_stats)
    elif action == "sync":
        sync_archive()
    else:
        assert action == "inc" or action == "full", action
        # the passphrase for full and inc is used by --sign-key
        # the sign key can have a different passphrase than the encrypt
        # key, therefore request a passphrase
        if globals.gpg_profile.sign_key:
            globals.gpg_profile.signing_passphrase = get_passphrase(1, action, True)

        # if there are no recipients (no --encrypt-key), it must be a
        # symmetric key. Therefore, confirm the passphrase
        if not (globals.gpg_profile.recipients or globals.gpg_profile.hidden_recipients):
            globals.gpg_profile.passphrase = get_passphrase(2, action)
            # a limitation in the GPG implementation does not allow for
            # inputting different passphrases, this affects symmetric+sign.
            # Allow an empty passphrase for the key though to allow a non-empty
            # symmetric key
            if (globals.gpg_profile.signing_passphrase and
                    globals.gpg_profile.passphrase != globals.gpg_profile.signing_passphrase):
                log.FatalError(_(
                    "When using symmetric encryption, the signing passphrase "
                    "must equal the encryption passphrase."),
                    log.ErrorCode.user_error)

        if action == "full":
            full_backup(col_stats)
        else:  # attempt incremental
            sig_chain = check_sig_chain(col_stats)
            # action == "inc" was requested, but no full backup is available
            if not sig_chain:
                full_backup(col_stats)
            else:
                if not globals.restart:
                    # only ask for a passphrase if there was a previous backup
                    if col_stats.all_backup_chains:
                        globals.gpg_profile.passphrase = get_passphrase(1, action)
                    check_last_manifest(col_stats)  # not needed for full backup
                incremental_backup(sig_chain)
    globals.backend.close()
    log.shutdown()
    if exit_val is not None:
        sys.exit(exit_val)


def with_tempdir(fn):
    """
    Execute function and guarantee cleanup of tempdir is called

    @type fn: callable function
    @param fn: function to execute

    @return: void
    @rtype: void
    """
    try:
        fn()
    finally:
        tempdir.default().cleanup()


if __name__ == "__main__":
    try:

        #         import cProfile
        #         import pstats
        #         import StringIO
        #         prof = cProfile.Profile()
        #         prof.enable(subcalls=True, builtins=True)

        with_tempdir(main)

        #         prof.disable()
        #         s = StringIO.StringIO()
        #         ps = pstats.Stats(prof, stream=s).sort_stats('cumulative')
        #         ps.print_stats(20)
        #         print s.getvalue()

    # Don't move this lower.  In order to get an exit
    # status out of the system, you have to call the
    # sys.exit() function.  Python handles this by
    # raising the SystemExit exception.  Cleanup code
    # goes here, if needed.
    except SystemExit as e:
        # No traceback, just get out
        util.release_lockfile()
        sys.exit(e.code)

    except KeyboardInterrupt as e:
        # No traceback, just get out
        log.Info(_("INT intercepted...exiting."))
        util.release_lockfile()
        sys.exit(4)

    except gpg.GPGError as e:
        # For gpg errors, don't show an ugly stack trace by
        # default. But do with sufficient verbosity.
        util.release_lockfile()
        log.Info(_("GPG error detail: %s")
                 % util.exception_traceback())
        log.FatalError(u"%s: %s" % (e.__class__.__name__, e.args[0]),
                       log.ErrorCode.gpg_failed,
                       e.__class__.__name__)

    except duplicity.errors.UserError as e:
        util.release_lockfile()
        # For user errors, don't show an ugly stack trace by
        # default. But do with sufficient verbosity.
        log.Info(_("User error detail: %s")
                 % util.exception_traceback())
        log.FatalError(u"%s: %s" % (e.__class__.__name__, util.uexc(e)),
                       log.ErrorCode.user_error,
                       e.__class__.__name__)

    except duplicity.errors.BackendException as e:
        util.release_lockfile()
        # For backend errors, don't show an ugly stack trace by
        # default. But do with sufficient verbosity.
        log.Info(_("Backend error detail: %s")
                 % util.exception_traceback())
        log.FatalError(u"%s: %s" % (e.__class__.__name__, util.uexc(e)),
                       log.ErrorCode.user_error,
                       e.__class__.__name__)

    except Exception as e:
        util.release_lockfile()
        if "Forced assertion for testing" in util.uexc(e):
            log.FatalError(u"%s: %s" % (e.__class__.__name__, util.uexc(e)),
                           log.ErrorCode.exception,
                           e.__class__.__name__)
        else:
            # Traceback and that mess
            log.FatalError(util.exception_traceback(),
                           log.ErrorCode.exception,
                           e.__class__.__name__)