-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathconfig.py
1665 lines (1379 loc) · 71.7 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Back In Time
# Copyright (C) 2008-2022 Oprea Dan, Bart de Koning, Richard Bailey,
# Germar Reitze
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Configuration logic.
This module and its `Config` class contain the appliation logic handling the
configuration of Back In Time. The handling of the configuration file itself
is separated in the module :py:module:`configfile`.
Development notes:
Some of the methods have code comments starting with `#? ` instead of
`# `. These special comments are used to generate the manpage
`backintime-config`. The script `create-manpage-backintime-config.py`
parses this module for that.
"""
import os
import sys
import datetime
import gettext
import socket
import random
import shlex
try:
import pwd
except ImportError:
import getpass
pwd = None
import tools
import configfile
import logger
import sshtools
import encfstools
import password
import pluginmanager
from exceptions import PermissionDeniedByPolicy, \
InvalidChar, \
InvalidCmd, \
LimitExceeded
_ = gettext.gettext
gettext.bindtextdomain('backintime', os.path.join(tools.sharePath(), 'locale'))
gettext.textdomain('backintime')
class Config(configfile.ConfigFileWithProfiles):
APP_NAME = 'Back In Time'
VERSION = '1.3.3'
COPYRIGHT = 'Copyright (C) 2008-2022 Oprea Dan, Bart de Koning, ' \
'Richard Bailey, Germar Reitze'
CONFIG_VERSION = 6
"""Latest or highest possible version of Backin Time's config file."""
NONE = 0
AT_EVERY_BOOT = 1
_5_MIN = 2
_10_MIN = 4
_30_MIN = 7
HOUR = 10
_1_HOUR = 10
_2_HOURS = 12
_4_HOURS = 14
_6_HOURS = 16
_12_HOURS = 18
CUSTOM_HOUR = 19
DAY = 20
REPEATEDLY = 25
UDEV = 27
WEEK = 30
MONTH = 40
YEAR = 80
DISK_UNIT_MB = 10
DISK_UNIT_GB = 20
SCHEDULE_MODES = {
NONE: _('Disabled'),
AT_EVERY_BOOT: _('At every boot/reboot'),
_5_MIN: _('Every 5 minutes'),
_10_MIN: _('Every 10 minutes'),
_30_MIN: _('Every 30 minutes'),
_1_HOUR: _('Every hour'),
_2_HOURS: _('Every 2 hours'),
_4_HOURS: _('Every 4 hours'),
_6_HOURS: _('Every 6 hours'),
_12_HOURS: _('Every 12 hours'),
CUSTOM_HOUR: _('Custom Hours'),
DAY: _('Every Day'),
REPEATEDLY: _('Repeatedly (anacron)'),
UDEV: _('When drive get connected (udev)'),
WEEK: _('Every Week'),
MONTH: _('Every Month'),
YEAR: _('Every Year')
}
REMOVE_OLD_BACKUP_UNITS = {
DAY: _('Day(s)'),
WEEK: _('Week(s)'),
YEAR: _('Year(s)')
}
REPEATEDLY_UNITS = {
HOUR: _('Hour(s)'),
DAY: _('Day(s)'),
WEEK: _('Week(s)'),
MONTH: _('Month(s)')
}
MIN_FREE_SPACE_UNITS = {
DISK_UNIT_MB: 'MiB',
DISK_UNIT_GB : 'GiB'
}
DEFAULT_EXCLUDE = [ '.gvfs', '.cache/*', '.thumbnails*',
'.local/share/[Tt]rash*', '*.backup*', '*~', '.dropbox*', '/proc/*',
'/sys/*', '/dev/*', '/run/*', '/etc/mtab', '/var/cache/apt/archives/*.deb',
'lost+found/*', '/tmp/*', '/var/tmp/*', '/var/backups/*', '.Private' ]
DEFAULT_RUN_NICE_FROM_CRON = True
DEFAULT_RUN_NICE_ON_REMOTE = False
DEFAULT_RUN_IONICE_FROM_CRON = True
DEFAULT_RUN_IONICE_FROM_USER = False
DEFAULT_RUN_IONICE_ON_REMOTE = False
DEFAULT_RUN_NOCACHE_ON_LOCAL = False
DEFAULT_RUN_NOCACHE_ON_REMOTE = False
DEFAULT_SSH_PREFIX = 'PATH=/opt/bin:/opt/sbin:\\$PATH'
DEFAULT_REDIRECT_STDOUT_IN_CRON = True
DEFAULT_REDIRECT_STDERR_IN_CRON = False
exp = _(' EXPERIMENTAL!')
SNAPSHOT_MODES = {
#mode : (<mounttools>, 'ComboBox Text', need_pw|lbl_pw_1, need_2_pw|lbl_pw_2),
'local' : (None, _('Local'), False, False),
'ssh' : (sshtools.SSH, _('SSH'), _('SSH private key'), False),
'local_encfs' : (encfstools.EncFS_mount, _('Local encrypted'), _('Encryption'), False),
'ssh_encfs' : (encfstools.EncFS_SSH, _('SSH encrypted'), _('SSH private key'), _('Encryption'))
}
SSH_CIPHERS = {'default': _('Default'),
'aes128-ctr': _('AES128-CTR'),
'aes192-ctr': _('AES192-CTR'),
'aes256-ctr': _('AES256-CTR'),
'arcfour256': _('ARCFOUR256'),
'arcfour128': _('ARCFOUR128'),
'aes128-cbc': _('AES128-CBC'),
'3des-cbc': _('3DES-CBC'),
'blowfish-cbc': _('Blowfish-CBC'),
'cast128-cbc': _('Cast128-CBC'),
'aes192-cbc': _('AES192-CBC'),
'aes256-cbc': _('AES256-CBC'),
'arcfour': _('ARCFOUR') }
ENCODE = encfstools.Bounce()
PLUGIN_MANAGER = pluginmanager.PluginManager()
def __init__(self, config_path=None, data_path=None):
configfile.ConfigFileWithProfiles.__init__(self, _('Main profile'))
self._APP_PATH = tools.backintimePath()
self._DOC_PATH = os.path.join(tools.sharePath(), 'doc', 'backintime-common')
if os.path.exists(os.path.join(self._APP_PATH, 'LICENSE')):
self._DOC_PATH = self._APP_PATH
self._GLOBAL_CONFIG_PATH = '/etc/backintime/config'
HOME_FOLDER = os.path.expanduser('~')
DATA_FOLDER = '.local/share'
CONFIG_FOLDER = '.config'
BIT_FOLDER = 'backintime'
self._DEFAULT_LOCAL_DATA_FOLDER = os.path.join(HOME_FOLDER, DATA_FOLDER, BIT_FOLDER)
self._LOCAL_CONFIG_FOLDER = os.path.join(HOME_FOLDER, CONFIG_FOLDER, BIT_FOLDER)
self._MOUNT_ROOT = os.path.join(DATA_FOLDER, BIT_FOLDER, 'mnt')
if data_path:
self.DATA_FOLDER_ROOT = data_path
self._LOCAL_DATA_FOLDER = os.path.join(data_path, DATA_FOLDER, BIT_FOLDER)
self._LOCAL_MOUNT_ROOT = os.path.join(data_path, self._MOUNT_ROOT)
else:
self.DATA_FOLDER_ROOT = HOME_FOLDER
self._LOCAL_DATA_FOLDER = self._DEFAULT_LOCAL_DATA_FOLDER
self._LOCAL_MOUNT_ROOT = os.path.join(HOME_FOLDER, self._MOUNT_ROOT)
tools.makeDirs(self._LOCAL_CONFIG_FOLDER)
tools.makeDirs(self._LOCAL_DATA_FOLDER)
tools.makeDirs(self._LOCAL_MOUNT_ROOT)
self._DEFAULT_CONFIG_PATH = os.path.join(self._LOCAL_CONFIG_FOLDER, 'config')
if config_path is None:
self._LOCAL_CONFIG_PATH = self._DEFAULT_CONFIG_PATH
else:
self._LOCAL_CONFIG_PATH = os.path.abspath(config_path)
self._LOCAL_CONFIG_FOLDER = os.path.dirname(self._LOCAL_CONFIG_PATH)
old_path = os.path.join(self._LOCAL_CONFIG_FOLDER, 'config2')
if os.path.exists(old_path):
if os.path.exists(self._LOCAL_CONFIG_PATH):
os.remove(old_path)
else:
os.rename(old_path, self._LOCAL_CONFIG_PATH)
# Load global config file
self.load(self._GLOBAL_CONFIG_PATH)
# Append local config file
self.append(self._LOCAL_CONFIG_PATH)
# Get the version of the config file
# or assume the highest config version if it isn't set.
currentConfigVersion \
= self.intValue('config.version', self.CONFIG_VERSION)
if currentConfigVersion < self.CONFIG_VERSION:
# config.version value wasn't stored since BiT version 0.9.99.22
# until version 1.2.0 because of a bug. So we can't really tell
# which version the config is. But most likely it is version > 4
if currentConfigVersion < 4:
#update from BackInTime version < 1.0 is deprecated
logger.error("config.version is < 4. This config was made with "\
"BackInTime version < 1.0. This version ({}) " \
"doesn't support upgrading config from version " \
"< 1.0 anymore. Please use BackInTime version " \
"<= 1.1.12 to upgrade the config to a more recent "\
"version.".format(self.VERSION))
#TODO: add popup warning
sys.exit(2)
if currentConfigVersion < 5:
logger.info("Update to config version 5: other snapshot locations", self)
profiles = self.profiles()
for profile_id in profiles:
#change include
old_values = self.includeV4(profile_id)
values = []
for value in old_values:
values.append((value, 0))
self.setInclude(values, profile_id)
#change exclude
old_values = self.excludeV4(profile_id)
self.setExclude(old_values, profile_id)
#remove keys
self.removeProfileKey('snapshots.include_folders', profile_id)
self.removeProfileKey('snapshots.exclude_patterns', profile_id)
if currentConfigVersion < 6:
logger.info('Update to config version 6', self)
# remap some keys
for profile in self.profiles():
# make a 'schedule' domain for everything relating schedules
self.remapProfileKey('snapshots.automatic_backup_anacron_period',
'schedule.repeatedly.period',
profile)
self.remapProfileKey('snapshots.automatic_backup_anacron_unit',
'schedule.repeatedly.unit',
profile)
self.remapProfileKey('snapshots.automatic_backup_day',
'schedule.day',
profile)
self.remapProfileKey('snapshots.automatic_backup_mode',
'schedule.mode',
profile)
self.remapProfileKey('snapshots.automatic_backup_time',
'schedule.time',
profile)
self.remapProfileKey('snapshots.automatic_backup_weekday',
'schedule.weekday',
profile)
self.remapProfileKey('snapshots.custom_backup_time',
'schedule.custom_time',
profile)
# we don't have 'full rsync mode' anymore
self.remapProfileKey('snapshots.full_rsync.take_snapshot_regardless_of_changes',
'snapshots.take_snapshot_regardless_of_changes',
profile)
# remap 'qt4' keys
self.remapKeyRegex(r'qt4', 'qt')
# remove old gnome and kde keys
self.removeKeysStartsWith('gnome')
self.removeKeysStartsWith('kde')
self.save()
self.current_hash_id = 'local'
self.pw = None
self.forceUseChecksum = False
self.xWindowId = None
self.inhibitCookie = None
self.setupUdev = tools.SetupUdev()
def save(self):
self.setIntValue('config.version', self.CONFIG_VERSION)
return super(Config, self).save(self._LOCAL_CONFIG_PATH)
def checkConfig(self):
profiles = self.profiles()
for profile_id in profiles:
profile_name = self.profileName(profile_id)
snapshots_path = self.snapshotsPath(profile_id)
logger.debug('Check profile %s' %profile_name, self)
#check snapshots path
if not snapshots_path:
self.notifyError(_('Profile: "%s"') % profile_name + '\n' + _('Snapshots folder is not valid !'))
return False
#check include
include_list = self.include(profile_id)
if not include_list:
self.notifyError(_('Profile: "%s"') % profile_name + '\n' + _('You must select at least one folder to backup !'))
return False
snapshots_path2 = snapshots_path + '/'
for item in include_list:
if item[1] != 0:
continue
path = item[0]
if path == snapshots_path:
self.notifyError(_('Profile: "%s"') % profile_name + '\n' + _('You can\'t include backup folder !'))
return False
if len(path) >= len(snapshots_path2):
if path[: len(snapshots_path2)] == snapshots_path2:
self.notifyError(_('Profile: "%s"') % self.currentProfile() + '\n' + _('You can\'t include a backup sub-folder !'))
return False
return True
def user(self):
"""
portable way to get username
cc by-sa 3.0 http://stackoverflow.com/a/19865396/1139841
author: techtonik http://stackoverflow.com/users/239247/techtonik
"""
if pwd:
return pwd.getpwuid(os.geteuid()).pw_name
else:
return getpass.getuser()
def pid(self):
return str(os.getpid())
def host(self):
return socket.gethostname()
def snapshotsPath(self, profile_id = None, mode = None, tmp_mount = False):
if mode is None:
mode = self.snapshotsMode(profile_id)
if self.SNAPSHOT_MODES[mode][0] == None:
#no mount needed
#?Where to save snapshots in mode 'local'. This path must contain a
#?folderstructure like 'backintime/<HOST>/<USER>/<PROFILE_ID>';absolute path
return self.profileStrValue('snapshots.path', '', profile_id)
else:
#mode need to be mounted; return mountpoint
symlink = self.snapshotsSymlink(profile_id = profile_id, tmp_mount = tmp_mount)
return os.path.join(self._LOCAL_MOUNT_ROOT, symlink)
def snapshotsFullPath(self, profile_id = None):
"""
Returns the full path for the snapshots: .../backintime/machine/user/profile_id/
"""
host, user, profile = self.hostUserProfile(profile_id)
return os.path.join(self.snapshotsPath(profile_id), 'backintime', host, user, profile)
def setSnapshotsPath(self, value, profile_id = None, mode = None):
"""
Sets the snapshot path to value, initializes, and checks it
"""
if not value:
return False
if profile_id == None:
profile_id = self.currentProfile()
if mode is None:
mode = self.snapshotsMode(profile_id)
if not os.path.isdir(value):
self.notifyError(_('%s is not a folder !') % value)
return False
#Initialize the snapshots folder
logger.debug("Check snapshot folder: %s" %value, self)
host, user, profile = self.hostUserProfile(profile_id)
if not all((host, user, profile)):
self.notifyError(_('Host/User/Profile-ID must not be empty!'))
return False
full_path = os.path.join(value, 'backintime', host, user, profile)
if not os.path.isdir(full_path):
logger.debug("Create folder: %s" %full_path, self)
tools.makeDirs(full_path)
if not os.path.isdir(full_path):
self.notifyError(_('Can\'t write to: %s\nAre you sure you have write access ?' % value))
return False
for p in (os.path.join(value, 'backintime'),
os.path.join(value, 'backintime', host)):
try:
os.chmod(p, 0o777)
except PermissionError as e:
msg = "Failed to change permissions world writeable for '{}': {}"
logger.warning(msg.format(p, str(e)), self)
#Test filesystem
fs = tools.filesystem(full_path)
if fs == 'vfat':
self.notifyError(_("Destination filesystem for '%(path)s' is formatted with FAT which doesn't support hard-links. "
"Please use a native Linux filesystem.") %
{'path': value})
return False
elif fs == 'cifs' and not self.copyLinks():
self.notifyError(_("Destination filsystem for '%(path)s' is a SMB mounted share. Please make sure "
"the remote SMB server supports symlinks or activate '%(copyLinks)s' in '%(expertOptions)s'.") %
{'path': value,
'copyLinks': _('Copy links (dereference symbolic links)'),
'expertOptions': _('Expert Options')})
elif fs == 'fuse.sshfs' and mode not in ('ssh', 'ssh_encfs'):
self.notifyError(_("Destination filesystem for '%(path)s is a sshfs mounted share. sshfs doesn't support hard-links. "
"Please use mode 'SSH' instead.") %
{'path': value})
return False
#Test write access for the folder
check_path = os.path.join(full_path, 'check')
tools.makeDirs(check_path)
if not os.path.isdir(check_path):
self.notifyError(_('Can\'t write to: %s\nAre you sure you have write access ?' % full_path))
return False
os.rmdir(check_path)
if self.SNAPSHOT_MODES[mode][0] is None:
self.setProfileStrValue('snapshots.path', value, profile_id)
return True
def snapshotsMode(self, profile_id=None):
#? Use mode (or backend) for this snapshot. Look at 'man backintime'
#? section 'Modes'.;local|local_encfs|ssh|ssh_encfs
return self.profileStrValue('snapshots.mode', 'local', profile_id)
def setSnapshotsMode(self, value, profile_id = None):
self.setProfileStrValue('snapshots.mode', value, profile_id)
def snapshotsSymlink(self, profile_id = None, tmp_mount = False):
if profile_id is None:
profile_id = self.current_profile_id
symlink = '%s_%s' % (profile_id, self.pid())
if tmp_mount:
symlink = 'tmp_%s' % symlink
return symlink
def setCurrentHashId(self, hash_id):
self.current_hash_id = hash_id
def hashCollision(self):
#?Internal value used to prevent hash collisions on mountpoints. Do not change this.
return self.intValue('global.hash_collision', 0)
def incrementHashCollision(self):
value = self.hashCollision() + 1
self.setIntValue('global.hash_collision', value)
# SSH
def sshSnapshotsPath(self, profile_id = None):
#?Snapshot path on remote host. If the path is relative (no leading '/')
#?it will start from remote Users homedir. An empty path will be replaced
#?with './'.;absolute or relative path
return self.profileStrValue('snapshots.ssh.path', '', profile_id)
def sshSnapshotsFullPath(self, profile_id = None):
"""
Returns the full path for the snapshots: .../backintime/machine/user/profile_id/
"""
path = self.sshSnapshotsPath(profile_id)
if not path:
path = './'
host, user, profile = self.hostUserProfile(profile_id)
return os.path.join(path, 'backintime', host, user, profile)
def setSshSnapshotsPath(self, value, profile_id = None):
self.setProfileStrValue('snapshots.ssh.path', value, profile_id)
return True
def sshHost(self, profile_id = None):
#?Remote host used for mode 'ssh' and 'ssh_encfs'.;IP or domain address
return self.profileStrValue('snapshots.ssh.host', '', profile_id)
def setSshHost(self, value, profile_id = None):
self.setProfileStrValue('snapshots.ssh.host', value, profile_id)
def sshPort(self, profile_id = None):
#?SSH Port on remote host.;0-65535
return self.profileIntValue('snapshots.ssh.port', '22', profile_id)
def setSshPort(self, value, profile_id = None):
self.setProfileIntValue('snapshots.ssh.port', value, profile_id)
def sshCipher(self, profile_id = None):
#?Cipher that is used for encrypting the SSH tunnel. Depending on the
#?environment (network bandwidth, cpu and hdd performance) a different
#?cipher might be faster.;default | aes192-cbc | aes256-cbc | aes128-ctr |
#? aes192-ctr | aes256-ctr | arcfour | arcfour256 | arcfour128 | aes128-cbc |
#? 3des-cbc | blowfish-cbc | cast128-cbc
return self.profileStrValue('snapshots.ssh.cipher', 'default', profile_id)
def setSshCipher(self, value, profile_id = None):
self.setProfileStrValue('snapshots.ssh.cipher', value, profile_id)
def sshUser(self, profile_id = None):
#?Remote SSH user;;local users name
return self.profileStrValue('snapshots.ssh.user', self.user(), profile_id)
def setSshUser(self, value, profile_id = None):
self.setProfileStrValue('snapshots.ssh.user', value, profile_id)
def sshHostUserPortPathCipher(self, profile_id = None):
host = self.sshHost(profile_id)
port = self.sshPort(profile_id)
user = self.sshUser(profile_id)
path = self.sshSnapshotsPath(profile_id)
cipher = self.sshCipher(profile_id)
if not path:
path = './'
return (host, port, user, path, cipher)
def sshPrivateKeyFile(self, profile_id = None):
ssh = self.sshPrivateKeyFolder()
default = ''
for f in ['id_dsa', 'id_rsa', 'identity']:
private_key = os.path.join(ssh, f)
if os.path.isfile(private_key):
default = private_key
break
#?Private key file used for password-less authentication on remote host.
#?;absolute path to private key file;~/.ssh/id_dsa
f = self.profileStrValue('snapshots.ssh.private_key_file', default, profile_id)
if f:
return f
return default
def sshPrivateKeyFolder(self):
return os.path.join(os.path.expanduser('~'), '.ssh')
def setSshPrivateKeyFile(self, value, profile_id = None):
self.setProfileStrValue('snapshots.ssh.private_key_file', value, profile_id)
def sshMaxArgLength(self, profile_id = None):
#?Maximum command length of commands run on remote host. This can be tested
#?for all ssh profiles in the configuration
#?with 'python3 /usr/share/backintime/common/sshMaxArg.py [initial_ssh_cmd_length]'.\n
#?0 = unlimited;0, >700
value = self.profileIntValue('snapshots.ssh.max_arg_length', 0, profile_id)
if value and value < 700:
raise ValueError('SSH max arg length %s is to low to run commands' % value)
return value
def setSshMaxArgLength(self, value, profile_id = None):
self.setProfileIntValue('snapshots.ssh.max_arg_length', value, profile_id)
def sshCheckCommands(self, profile_id = None):
#?Check if all commands (used during takeSnapshot) work like expected
#?on the remote host.
return self.profileBoolValue('snapshots.ssh.check_commands', True, profile_id)
def setSshCheckCommands(self, value, profile_id = None):
self.setProfileBoolValue('snapshots.ssh.check_commands', value, profile_id)
def sshCheckPingHost(self, profile_id = None):
#?Check if the remote host is available before trying to mount.
return self.profileBoolValue('snapshots.ssh.check_ping', True, profile_id)
def setSshCheckPingHost(self, value, profile_id = None):
self.setProfileBoolValue('snapshots.ssh.check_ping', value, profile_id)
def sshDefaultArgs(self, profile_id = None):
"""
Default arguments used for ``ssh`` and ``sshfs`` commands.
Returns:
list: arguments for ssh
"""
# keep connection alive
args = ['-o', 'ServerAliveInterval=240']
# disable ssh banner
args += ['-o', 'LogLevel=Error']
# specifying key file here allows to override for potentially
# conflicting .ssh/config key entry
args += ['-o', 'IdentityFile={}'.format(self.sshPrivateKeyFile(profile_id))]
return args
def sshCommand(self,
cmd = None,
custom_args = None,
port = True,
cipher = True,
user_host = True,
ionice = True,
nice = True,
quote = False,
prefix = True,
profile_id = None):
"""
Return SSH command with all arguments.
Args:
cmd (list): command that should run on remote host
custom_args (list): additional arguments paste to the command
port (bool): use port from config
cipher (bool): use cipher from config
user_host (bool): use user@host from config
ionice (bool): use ionice if configured
nice (bool): use nice if configured
quote (bool): quote remote command
prefix (bool): use prefix from config before remote command
profile_id (str): profile ID that should be used in config
Returns:
list: ssh command with chosen arguments
"""
assert cmd is None or isinstance(cmd, list), "cmd '{}' is not list instance".format(cmd)
assert custom_args is None or isinstance(custom_args, list), "custom_args '{}' is not list instance".format(custom_args)
ssh = ['ssh']
ssh += self.sshDefaultArgs(profile_id)
# remote port
if port:
ssh += ['-p', str(self.sshPort(profile_id))]
# cipher used to transfer data
c = self.sshCipher(profile_id)
if cipher and c != 'default':
ssh += ['-o', 'Ciphers={}'.format(c)]
# custom arguments
if custom_args:
ssh += custom_args
# user@host
if user_host:
ssh.append('{}@{}'.format(self.sshUser(profile_id),
self.sshHost(profile_id)))
# quote the command running on remote host
if quote and cmd:
ssh.append("'")
# run 'ionice' on remote host
if ionice and self.ioniceOnRemote(profile_id) and cmd:
ssh += ['ionice', '-c2', '-n7']
# run 'nice' on remote host
if nice and self.niceOnRemote(profile_id) and cmd:
ssh += ['nice', '-n19']
# run prefix on remote host
if prefix and cmd and self.sshPrefixEnabled(profile_id):
ssh += self.sshPrefixCmd(profile_id, cmd_type = list)
# add the command
if cmd:
ssh += cmd
# close quote
if quote and cmd:
ssh.append("'")
return ssh
#ENCFS
def localEncfsPath(self, profile_id = None):
#?Where to save snapshots in mode 'local_encfs'.;absolute path
return self.profileStrValue('snapshots.local_encfs.path', '', profile_id)
def setLocalEncfsPath(self, value, profile_id = None):
self.setProfileStrValue('snapshots.local_encfs.path', value, profile_id)
def passwordSave(self, profile_id = None, mode = None):
if mode is None:
mode = self.snapshotsMode(profile_id)
#?Save password to system keyring (gnome-keyring or kwallet).
#?<MODE> must be the same as \fIprofile<N>.snapshots.mode\fR
return self.profileBoolValue('snapshots.%s.password.save' % mode, False, profile_id)
def setPasswordSave(self, value, profile_id = None, mode = None):
if mode is None:
mode = self.snapshotsMode(profile_id)
self.setProfileBoolValue('snapshots.%s.password.save' % mode, value, profile_id)
def passwordUseCache(self, profile_id = None, mode = None):
if mode is None:
mode = self.snapshotsMode(profile_id)
default = not tools.checkHomeEncrypt()
#?Cache password in RAM so it can be read by cronjobs.
#?Security issue: root might be able to read that password, too.
#?<MODE> must be the same as \fIprofile<N>.snapshots.mode\fR;;true if home is not encrypted
return self.profileBoolValue('snapshots.%s.password.use_cache' % mode, default, profile_id)
def setPasswordUseCache(self, value, profile_id = None, mode = None):
if mode is None:
mode = self.snapshotsMode(profile_id)
self.setProfileBoolValue('snapshots.%s.password.use_cache' % mode, value, profile_id)
def password(self, parent = None, profile_id = None, mode = None, pw_id = 1, only_from_keyring = False):
if self.pw is None:
self.pw = password.Password(self)
if profile_id is None:
profile_id = self.currentProfile()
if mode is None:
mode = self.snapshotsMode(profile_id)
return self.pw.password(parent, profile_id, mode, pw_id, only_from_keyring)
def setPassword(self, password, profile_id = None, mode = None, pw_id = 1):
if self.pw is None:
self.pw = password.Password(self)
if profile_id is None:
profile_id = self.currentProfile()
if mode is None:
mode = self.snapshotsMode(profile_id)
self.pw.setPassword(password, profile_id, mode, pw_id)
def modeNeedPassword(self, mode, pw_id = 1):
need_pw = self.SNAPSHOT_MODES[mode][pw_id + 1]
if need_pw is False:
return False
return True
def keyringServiceName(self, profile_id = None, mode = None, pw_id = 1):
if mode is None:
mode = self.snapshotsMode(profile_id)
if pw_id > 1:
return 'backintime/%s_%s' % (mode, pw_id)
return 'backintime/%s' % mode
def keyringUserName(self, profile_id = None):
if profile_id is None:
profile_id = self.currentProfile()
return 'profile_id_%s' % profile_id
def hostUserProfileDefault(self, profile_id = None):
host = socket.gethostname()
user = self.user()
profile = profile_id
if profile is None:
profile = self.currentProfile()
return (host, user, profile)
def hostUserProfile(self, profile_id = None):
default_host, default_user, default_profile = self.hostUserProfileDefault(profile_id)
#?Set Host for snapshot path;;local hostname
host = self.profileStrValue('snapshots.path.host', default_host, profile_id)
#?Set User for snapshot path;;local username
user = self.profileStrValue('snapshots.path.user', default_user, profile_id)
#?Set Profile-ID for snapshot path;1-99999;current Profile-ID
profile = self.profileStrValue('snapshots.path.profile', default_profile, profile_id)
return (host, user, profile)
def setHostUserProfile(self, host, user, profile, profile_id = None):
self.setProfileStrValue('snapshots.path.host', host, profile_id)
self.setProfileStrValue('snapshots.path.user', user, profile_id)
self.setProfileStrValue('snapshots.path.profile', profile, profile_id)
def includeV4(self, profile_id = None):
#?!ignore this in manpage
value = self.profileStrValue('snapshots.include_folders', '', profile_id)
if not value:
return []
paths = []
for item in value.split(':'):
fields = item.split('|')
path = os.path.expanduser(fields[0])
path = os.path.abspath(path)
paths.append(path)
return paths
def include(self, profile_id = None):
#?Include this file or folder. <I> must be a counter starting with 1;absolute path::
#?Specify if \fIprofile<N>.snapshots.include.<I>.value\fR is a folder (0) or a file (1).;0|1;0
return self.profileListValue('snapshots.include', ('str:value', 'int:type'), [], profile_id)
def setInclude(self, values, profile_id = None):
self.setProfileListValue('snapshots.include', ('str:value', 'int:type'), values, profile_id)
def excludeV4(self, profile_id = None):
"""
Gets the exclude patterns: conf version 4
"""
#?!ignore this in manpage
value = self.profileStrValue('snapshots.exclude_patterns', '.gvfs:.cache*:[Cc]ache*:.thumbnails*:[Tt]rash*:*.backup*:*~', profile_id)
if not value:
return []
return value.split(':')
def exclude(self, profile_id = None):
"""
Gets the exclude patterns
"""
#?Exclude this file or folder. <I> must be a counter
#?starting with 1;file, folder or pattern (relative or absolute)
return self.profileListValue('snapshots.exclude', 'str:value', self.DEFAULT_EXCLUDE, profile_id)
def setExclude(self, values, profile_id = None):
self.setProfileListValue('snapshots.exclude', 'str:value', values, profile_id)
def excludeBySizeEnabled(self, profile_id = None):
#?Enable exclude files by size.
return self.profileBoolValue('snapshots.exclude.bysize.enabled', False, profile_id)
def excludeBySize(self, profile_id = None):
#?Exclude files bigger than value in MiB.
#?With 'Full rsync mode' disabled this will only affect new files
#?because for rsync this is a transfer option, not an exclude option.
#?So big files that has been backed up before will remain in snapshots
#?even if they had changed.
return self.profileIntValue('snapshots.exclude.bysize.value', 500, profile_id)
def setExcludeBySize(self, enabled, value, profile_id = None):
self.setProfileBoolValue('snapshots.exclude.bysize.enabled', enabled, profile_id)
self.setProfileIntValue('snapshots.exclude.bysize.value', value, profile_id)
def tag(self, profile_id = None):
#?!ignore this in manpage
return self.profileStrValue('snapshots.tag', str(random.randint(100, 999)), profile_id)
def scheduleMode(self, profile_id = None):
#?Which schedule used for crontab. The crontab entry will be
#?generated with 'backintime check-config'.\n
#? 0 = Disabled\n 1 = at every boot\n 2 = every 5 minute\n
#? 4 = every 10 minute\n 7 = every 30 minute\n10 = every hour\n
#?12 = every 2 hours\n14 = every 4 hours\n16 = every 6 hours\n
#?18 = every 12 hours\n19 = custom defined hours\n20 = every day\n
#?25 = daily anacron\n27 = when drive get connected\n30 = every week\n
#?40 = every month\n80 = every year
#?;0|1|2|4|7|10|12|14|16|18|19|20|25|27|30|40|80;0
return self.profileIntValue('schedule.mode', self.NONE, profile_id)
def setScheduleMode(self, value, profile_id = None):
self.setProfileIntValue('schedule.mode', value, profile_id)
def scheduleTime(self, profile_id = None):
#?Position-coded number with the format "hhmm" to specify the hour
#?and minute the cronjob should start (eg. 2015 means a quarter
#?past 8pm). Leading zeros can be omitted (eg. 30 = 0030).
#?Only valid for
#?\fIprofile<N>.schedule.mode\fR = 20 (daily), 30 (weekly),
#?40 (monthly) and 80 (yearly);0-2400
return self.profileIntValue('schedule.time', 0, profile_id)
def setScheduleTime(self, value, profile_id = None):
self.setProfileIntValue('schedule.time', value, profile_id)
def scheduleDay(self, profile_id = None):
#?Which day of month the cronjob should run? Only valid for
#?\fIprofile<N>.schedule.mode\fR >= 40;1-28
return self.profileIntValue('schedule.day', 1, profile_id)
def setScheduleDay(self, value, profile_id = None):
self.setProfileIntValue('schedule.day', value, profile_id)
def scheduleWeekday(self, profile_id = None):
#?Which day of week the cronjob should run? Only valid for
#?\fIprofile<N>.schedule.mode\fR = 30;1 = monday \- 7 = sunday
return self.profileIntValue('schedule.weekday', 7, profile_id)
def setScheduleWeekday(self, value, profile_id = None):
self.setProfileIntValue('schedule.weekday', value, profile_id)
def customBackupTime(self, profile_id = None):
#?Custom hours for cronjob. Only valid for
#?\fIprofile<N>.schedule.mode\fR = 19
#?;comma separated int (8,12,18,23) or */3;8,12,18,23
return self.profileStrValue('schedule.custom_time', '8,12,18,23', profile_id)
def setCustomBackupTime(self, value, profile_id = None):
self.setProfileStrValue('schedule.custom_time', value, profile_id)
def scheduleRepeatedPeriod(self, profile_id = None):
#?How many units to wait between new snapshots with anacron? Only valid
#?for \fIprofile<N>.schedule.mode\fR = 25|27
return self.profileIntValue('schedule.repeatedly.period', 1, profile_id)
def setScheduleRepeatedPeriod(self, value, profile_id = None):
self.setProfileIntValue('schedule.repeatedly.period', value, profile_id)
def scheduleRepeatedUnit(self, profile_id = None):
#?Units to wait between new snapshots with anacron.\n
#?10 = hours\n20 = days\n30 = weeks\n40 = months\n
#?Only valid for \fIprofile<N>.schedule.mode\fR = 25|27;
#?10|20|30|40;20
return self.profileIntValue('schedule.repeatedly.unit', self.DAY, profile_id)
def setScheduleRepeatedUnit(self, value, profile_id = None):
self.setProfileIntValue('schedule.repeatedly.unit', value, profile_id)
def removeOldSnapshots(self, profile_id = None):
#?Remove all snapshots older than value + unit
return (self.profileBoolValue('snapshots.remove_old_snapshots.enabled', True, profile_id),
#?Snapshots older than this times units will be removed
self.profileIntValue('snapshots.remove_old_snapshots.value', 10, profile_id),
#?20 = days\n30 = weeks\n80 = years;20|30|80;80
self.profileIntValue('snapshots.remove_old_snapshots.unit', self.YEAR, profile_id))
def keepOnlyOneSnapshot(self, profile_id = None):
#?NOT YET IMPLEMENTED. Remove all snapshots but one.
return self.profileBoolValue('snapshots.keep_only_one_snapshot.enabled', False, profile_id)
def setKeepOnlyOneSnapshot(self, value, profile_id = None):
self.setProfileBoolValue('snapshots.keep_only_one_snapshot.enabled', value, profile_id)
def removeOldSnapshotsEnabled(self, profile_id = None):
return self.profileBoolValue('snapshots.remove_old_snapshots.enabled', True, profile_id)
def removeOldSnapshotsDate(self, profile_id = None):
enabled, value, unit = self.removeOldSnapshots(profile_id)
if not enabled:
return datetime.date(1, 1, 1)
if unit == self.DAY:
date = datetime.date.today()
date = date - datetime.timedelta(days = value)
return date
if unit == self.WEEK:
date = datetime.date.today()
date = date - datetime.timedelta(days = date.weekday() + 7 * value)
return date
if unit == self.YEAR:
date = datetime.date.today()
return date.replace(day = 1, year = date.year - value)
return datetime.date(1, 1, 1)
def setRemoveOldSnapshots(self, enabled, value, unit, profile_id = None):
self.setProfileBoolValue('snapshots.remove_old_snapshots.enabled', enabled, profile_id)
self.setProfileIntValue('snapshots.remove_old_snapshots.value', value, profile_id)
self.setProfileIntValue('snapshots.remove_old_snapshots.unit', unit, profile_id)
def minFreeSpace(self, profile_id = None):
#?Remove snapshots until \fIprofile<N>.snapshots.min_free_space.value\fR
#?free space is reached.
return (self.profileBoolValue('snapshots.min_free_space.enabled', True, profile_id),
#?Keep at least value + unit free space.;1-99999
self.profileIntValue('snapshots.min_free_space.value', 1, profile_id),
#?10 = MB\n20 = GB;10|20;20
self.profileIntValue('snapshots.min_free_space.unit', self.DISK_UNIT_GB, profile_id))
def minFreeSpaceEnabled(self, profile_id = None):
return self.profileBoolValue('snapshots.min_free_space.enabled', True, profile_id)
def minFreeSpaceMib(self, profile_id = None):
enabled, value, unit = self.minFreeSpace(profile_id)
if not enabled:
return 0
if self.DISK_UNIT_MB == unit:
return value
value *= 1024 #Gb
if self.DISK_UNIT_GB == unit:
return value
return 0
def setMinFreeSpace(self, enabled, value, unit, profile_id = None):
self.setProfileBoolValue('snapshots.min_free_space.enabled', enabled, profile_id)
self.setProfileIntValue('snapshots.min_free_space.value', value, profile_id)
self.setProfileIntValue('snapshots.min_free_space.unit', unit, profile_id)
def minFreeInodes(self, profile_id = None):
#?Keep at least value % free inodes.;1-15
return self.profileIntValue('snapshots.min_free_inodes.value', 2, profile_id)
def minFreeInodesEnabled(self, profile_id = None):
#?Remove snapshots until \fIprofile<N>.snapshots.min_free_inodes.value\fR
#?free inodes in % is reached.
return self.profileBoolValue('snapshots.min_free_inodes.enabled', True, profile_id)
def setMinFreeInodes(self, enabled, value, profile_id = None):