-
Notifications
You must be signed in to change notification settings - Fork 203
/
tools.py
2435 lines (2071 loc) · 78.3 KB
/
tools.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, Taylor Raack
#
# 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.
import os
import sys
import pathlib
import subprocess
import shlex
import signal
import re
import errno
import gzip
import tempfile
try:
from collections.abc import MutableSet
except ImportError:
from collections import MutableSet
import hashlib
import ipaddress
import atexit
from datetime import datetime
from packaging.version import Version
from time import sleep
keyring = None
keyring_warn = False
try:
if os.getenv('BIT_USE_KEYRING', 'true') == 'true' and os.geteuid() != 0:
import keyring
from keyring import backend
except:
keyring = None
os.putenv('BIT_USE_KEYRING', 'false')
keyring_warn = True
# getting dbus imports to work in Travis CI is a huge pain
# use conditional dbus import
ON_TRAVIS = os.environ.get('TRAVIS', 'None').lower() == 'true'
ON_RTD = os.environ.get('READTHEDOCS', 'None').lower() == 'true'
try:
import dbus
except ImportError:
if ON_TRAVIS or ON_RTD:
#python-dbus doesn't work on Travis yet.
dbus = None
else:
raise
import configfile
import logger
import bcolors
from applicationinstance import ApplicationInstance
from exceptions import Timeout, InvalidChar, InvalidCmd, LimitExceeded, PermissionDeniedByPolicy
DISK_BY_UUID = '/dev/disk/by-uuid'
def sharePath():
"""
Get BackInTimes installation base path.
If running from source return default '/usr/share'
Returns:
str: share path like::
/usr/share
/usr/local/share
/opt/usr/share
"""
share = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, os.pardir))
if os.path.basename(share) == 'share':
return share
else:
return '/usr/share'
def backintimePath(*path):
"""
Get path inside 'backintime' install folder.
Args:
*path (str): paths that should be joined to 'backintime'
Returns:
str: 'backintime' child path like::
/usr/share/backintime/common
/usr/share/backintime/qt
"""
return os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, *path))
def registerBackintimePath(*path):
"""
Add BackInTime path ``path`` to :py:data:`sys.path` so subsequent imports
can discover them.
Args:
*path (str): paths that should be joind to 'backintime'
Note:
Duplicate in :py:func:`qt/qttools.py` because modules in qt folder
would need this to actually import :py:mod:`tools`.
"""
path = backintimePath(*path)
if not path in sys.path:
sys.path.insert(0, path)
def runningFromSource():
"""
Check if BackInTime is running from source (without installing).
Returns:
bool: ``True`` if BackInTime is running from source
"""
return os.path.isfile(backintimePath('common', 'backintime'))
def addSourceToPathEnviron():
"""
Add 'backintime/common' path to 'PATH' environ variable.
"""
source = backintimePath('common')
path = os.getenv('PATH')
if path and source not in path.split(':'):
os.environ['PATH'] = '%s:%s' %(source, path)
def gitRevisionAndHash():
"""
Get the current Git Branch and the last HashID (shot form) if running
from source.
Returns:
tuple: two items of either :py:class:`str` instance if running from
source or ``None``
"""
ref, hashid = None, None
gitPath = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, '.git'))
headPath = os.path.join(gitPath, 'HEAD')
refPath = ''
if not os.path.isdir(gitPath):
return (ref, hashid)
try:
with open(headPath, 'rt') as f:
refPath = f.read().strip('\n')
if refPath.startswith('ref: '):
refPath = refPath[5:]
if refPath:
refPath = os.path.join(gitPath, refPath)
ref = os.path.basename(refPath)
except Exception as e:
pass
if os.path.isfile(refPath):
try:
with open(refPath, 'rt') as f:
hashid = f.read().strip('\n')[:7]
except:
pass
return (ref, hashid)
def readFile(path, default=None):
"""
Read the file in ``path`` or its '.gz' compressed variant and return its
content or ``default`` if ``path`` does not exist.
Args:
path (str): full path to file that should be read.
'.gz' will be added automatically if the file
is compressed
default (str): default if ``path`` does not exist
Returns:
str: content of file in ``path``
"""
ret_val = default
try:
if os.path.exists(path):
with open(path) as f:
ret_val = f.read()
elif os.path.exists(path + '.gz'):
with gzip.open(path + '.gz', 'rt') as f:
ret_val = f.read()
except:
pass
return ret_val
def readFileLines(path, default = None):
"""
Read the file in ``path`` or its '.gz' compressed variant and return its
content as a list of lines or ``default`` if ``path`` does not exist.
Args:
path (str): full path to file that should be read.
'.gz' will be added automatically if the file
is compressed
default (list): default if ``path`` does not exist
Returns:
list: content of file in ``path`` splitted by lines.
"""
ret_val = default
try:
if os.path.exists(path):
with open(path) as f:
ret_val = [x.rstrip('\n') for x in f.readlines()]
elif os.path.exists(path + '.gz'):
with gzip.open(path + '.gz', 'rt') as f:
ret_val = [x.rstrip('\n') for x in f.readlines()]
except:
pass
return ret_val
def checkCommand(cmd):
"""
Check if command ``cmd`` is a file in 'PATH' environ.
Args:
cmd (str): command
Returns:
bool: ``True`` if command ``cmd`` is in 'PATH' environ
"""
cmd = cmd.strip()
if not cmd:
return False
if os.path.isfile(cmd):
return True
return not which(cmd) is None
def which(cmd):
"""
Get the fullpath of executable command ``cmd``. Works like
command-line 'which' command.
Args:
cmd (str): command
Returns:
str: fullpath of command ``cmd`` or ``None`` if command is
not available
"""
pathenv = os.getenv('PATH', '')
path = pathenv.split(":")
common = backintimePath('common')
if runningFromSource() and common not in path:
path.insert(0, common)
for directory in path:
fullpath = os.path.join(directory, cmd)
if os.path.isfile(fullpath) and os.access(fullpath, os.X_OK):
return fullpath
return None
def makeDirs(path):
"""
Create directories ``path`` recursive and return success.
Args:
path (str): fullpath to directories that should be created
Returns:
bool: ``True`` if successful
"""
path = path.rstrip(os.sep)
if not path:
return False
if os.path.isdir(path):
return True
else:
try:
os.makedirs(path)
except Exception as e:
logger.error("Failed to make dirs '%s': %s"
%(path, str(e)), traceDepth = 1)
return os.path.isdir(path)
def mkdir(path, mode = 0o755, enforce_permissions = True):
"""
Create directory ``path``.
Args:
path (str): full path to directory that should be created
mode (int): numeric permission mode
Returns:
bool: ``True`` if successful
"""
if os.path.isdir(path):
try:
if enforce_permissions:
os.chmod(path, mode)
except:
return False
return True
else:
os.mkdir(path, mode)
if mode & 0o002 == 0o002:
#make file world (other) writable was requested
#debian and ubuntu won't set o+w with os.mkdir
#this will fix it
os.chmod(path, mode)
return os.path.isdir(path)
def pids():
"""
List all PIDs currently running on the system.
Returns:
list: PIDs as int
"""
return [int(x) for x in os.listdir('/proc') if x.isdigit()]
def processStat(pid):
"""
Get the stat's of the process with ``pid``.
Args:
pid (int): Process Indicator
Returns:
str: stat from /proc/PID/stat
"""
try:
with open('/proc/{}/stat'.format(pid), 'rt') as f:
return f.read()
except OSError as e:
logger.warning('Failed to read process stat from {}: [{}] {}'
.format(e.filename, e.errno, e.strerror))
return ''
def processPaused(pid):
"""
Check if process ``pid`` is paused (got signal SIGSTOP).
Args:
pid (int): Process Indicator
Returns:
bool: True if process is paused
"""
m = re.match(r'\d+ \(.+\) T', processStat(pid))
return bool(m)
def processName(pid):
"""
Get the name of the process with ``pid``.
Args:
pid (int): Process Indicator
Returns:
str: name of the process
"""
m = re.match(r'.*\((.+)\).*', processStat(pid))
if m:
return m.group(1)
def processCmdline(pid):
"""
Get the cmdline (command that spawnd this process) of the process with
``pid``.
Args:
pid (int): Process Indicator
Returns:
str: cmdline of the process
"""
try:
with open('/proc/{}/cmdline'.format(pid), 'rt') as f:
return f.read().strip('\n')
except OSError as e:
logger.warning('Failed to read process cmdline from {}: [{}] {}'.format(e.filename, e.errno, e.strerror))
return ''
def pidsWithName(name):
"""
Get all processes currently running with name ``name``.
Args:
name (str): name of a process like 'python3' or 'backintime'
Returns:
list: PIDs as int
"""
# /proc/###/stat stores just the first 16 chars of the process name
return [x for x in pids() if processName(x) == name[:15]]
def processExists(name):
"""
Check if process ``name`` is currently running.
Args:
name (str): name of a process like 'python3' or 'backintime'
Returns:
bool: ``True`` if there is a process running with ``name``
"""
return len(pidsWithName(name)) > 0
def processAlive(pid):
"""
Check if the process with PID ``pid`` is alive.
Args:
pid (int): Process Indicator
Returns:
bool: ``True`` if the process with PID ``pid`` is alive
Raises:
ValueError: If ``pid`` is 0 because 'kill(0, SIG)' would send SIG to all
processes
"""
if pid < 0:
return False
elif pid == 0:
raise ValueError('invalid PID 0')
else:
try:
os.kill(pid, 0) #this will raise an exception if the pid is not valid
except OSError as err:
if err.errno == errno.ESRCH:
# ESRCH == No such process
return False
elif err.errno == errno.EPERM:
# EPERM clearly means there's a process to deny access to
return True
else:
raise
else:
return True
def checkXServer():
"""
Check if there is a X11 server running on this system.
Returns:
bool: ``True`` if X11 server is running
"""
if checkCommand('xdpyinfo'):
proc = subprocess.Popen(['xdpyinfo'],
stdout = subprocess.DEVNULL,
stderr = subprocess.DEVNULL)
proc.communicate()
return proc.returncode == 0
else:
return False
def preparePath(path):
"""
Removes trailing slash '/' from ``path``.
Args:
path (str): absolut path
Returns:
str: path ``path`` without trailing but with leading slash
"""
path = path.strip("/")
path = os.sep + path
return path
def powerStatusAvailable():
"""
Check if org.freedesktop.UPower is available so that
:py:func:`tools.onBattery` would return the correct power status.
Returns:
bool: ``True`` if :py:func:`tools.onBattery` can report power status
"""
if dbus:
try:
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.UPower',
'/org/freedesktop/UPower')
return 'OnBattery' in proxy.GetAll('org.freedesktop.UPower',
dbus_interface = 'org.freedesktop.DBus.Properties')
except dbus.exceptions.DBusException:
pass
return False
def onBattery():
"""
Checks if the system is on battery power.
Returns:
bool: ``True`` if system is running on battery
"""
if dbus:
try:
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.UPower',
'/org/freedesktop/UPower')
return bool(proxy.Get('org.freedesktop.UPower',
'OnBattery',
dbus_interface = 'org.freedesktop.DBus.Properties'))
except dbus.exceptions.DBusException:
pass
return False
def rsyncCaps(data = None):
"""
Get capabilities of the installed rsync binary. This can be different from
version to version and also on build arguments used when building rsync.
Args:
data (str): 'rsync --version' output. This is just for unittests.
Returns:
list: List of str with rsyncs capabilities
"""
if not data:
proc = subprocess.Popen(['rsync', '--version'],
stdout = subprocess.PIPE,
universal_newlines = True)
data = proc.communicate()[0]
caps = []
#rsync >= 3.1 does provide --info=progress2
matchers = [r'rsync\s*version\s*(\d\.\d)', r'rsync\s*version\s*v(\d\.\d.\d)']
for matcher in matchers:
m = re.match(matcher, data)
if m and Version(m.group(1)) >= Version('3.1'):
caps.append('progress2')
break
#all other capabilities are separated by ',' between
#'Capabilities:' and '\n\n'
m = re.match(r'.*Capabilities:(.+)\n\n.*', data, re.DOTALL)
if not m:
return caps
for line in m.group(1).split('\n'):
caps.extend([i.strip(' \n') for i in line.split(',') if i.strip(' \n')])
return caps
def rsyncPrefix(config,
no_perms=True,
use_mode=['ssh', 'ssh_encfs'],
progress=True):
"""
Get rsync command and all args for creating a new snapshot. Args are
based on current profile in ``config``.
Args:
config (config.Config): current config
no_perms (bool): don't sync permissions (--no-p --no-g --no-o)
if ``True``.
:py:func:`config.Config.preserveAcl` == ``True`` or
:py:func:`config.Config.preserveXattr` == ``True``
will overwrite this to ``False``
use_mode (list): if current mode is in this list add additional
args for that mode
progress (bool): add '--info=progress2' to show progress
Returns:
list: rsync command with all args but without
--include, --exclude, source and destination
"""
caps = rsyncCaps()
cmd = []
if config.nocacheOnLocal():
cmd.append('nocache')
cmd.append('rsync')
cmd.extend((
# recurse into directories
'--recursive',
# preserve modification times
'--times',
# preserve device files (super-user only)
'--devices',
# preserve special files
'--specials',
# preserve hard links
'--hard-links',
# numbers in a human-readable format
'--human-readable',
# use "new" argument protection
'-s'
))
if config.useChecksum() or config.forceUseChecksum:
cmd.append('--checksum')
if config.copyUnsafeLinks():
cmd.append('--copy-unsafe-links')
if config.copyLinks():
cmd.append('--copy-links')
else:
cmd.append('--links')
if config.preserveAcl() and "ACLs" in caps:
cmd.append('--acls') # preserve ACLs (implies --perms)
no_perms = False
if config.preserveXattr() and "xattrs" in caps:
cmd.append('--xattrs') # preserve extended attributes
no_perms = False
if no_perms:
cmd.extend(('--no-perms', '--no-group', '--no-owner'))
else:
cmd.extend(('--perms', # preserve permissions
'--executability', # preserve executability
'--group', # preserve group
'--owner')) # preserve owner (super-user only)
if progress and 'progress2' in caps:
cmd.extend(('--info=progress2',
'--no-inc-recursive'))
if config.bwlimitEnabled():
cmd.append('--bwlimit=%d' % config.bwlimit())
if config.rsyncOptionsEnabled():
cmd.extend(shlex.split(config.rsyncOptions()))
cmd.extend(rsyncSshArgs(config, use_mode))
return cmd
def rsyncSshArgs(config, use_mode=['ssh', 'ssh_encfs']):
"""
Get SSH args for rsync based on current profile in ``config``.
Args:
config (config.Config): Current config instance.
use_mode (list): If the profiles current mode is in this list
add additional args.
Returns:
list: List of rsync args related to SSH.
"""
cmd = []
mode = config.snapshotsMode()
if mode in ['ssh', 'ssh_encfs'] and mode in use_mode:
ssh = config.sshCommand(user_host=False,
ionice=False,
nice=False)
cmd.append('--rsh=' + ' '.join(ssh))
if config.niceOnRemote() \
or config.ioniceOnRemote() \
or config.nocacheOnRemote():
rsync_path = '--rsync-path='
if config.niceOnRemote():
rsync_path += 'nice -n 19 '
if config.ioniceOnRemote():
rsync_path += 'ionice -c2 -n7 '
if config.nocacheOnRemote():
rsync_path += 'nocache '
rsync_path += 'rsync'
cmd.append(rsync_path)
return cmd
def rsyncRemove(config, run_local = True):
"""
Get rsync command and all args for removing snapshots with rsync.
Args:
config (config.Config): current config
run_local (bool): if True and current mode is ``ssh``
or ``ssh_encfs`` this will add SSH options
Returns:
list: rsync command with all args
"""
cmd = ['rsync', '-a', '--delete', '-s']
if run_local:
cmd.extend(rsyncSshArgs(config))
return cmd
#TODO: check if we really need this
def tempFailureRetry(func, *args, **kwargs):
while True:
try:
return func(*args, **kwargs)
except (os.error, IOError) as ex:
if ex.errno == errno.EINTR:
continue
else:
raise
def md5sum(path):
"""
Calculate md5sum for file in ``path``.
Args:
path (str): full path to file
Returns:
str: md5sum of file
"""
md5 = hashlib.md5()
with open(path, 'rb') as f:
while True:
data = f.read(4096)
if not data:
break
md5.update(data)
return md5.hexdigest()
def checkCronPattern(s):
"""
Check if ``s`` is a valid cron pattern.
Examples::
0,10,13,15,17,20,23
*/6
Args:
s (str): pattern to check
Returns:
bool: ``True`` if ``s`` is a valid cron pattern
"""
if s.find(' ') >= 0:
return False
try:
if s.startswith('*/'):
if s[2:].isdigit() and int(s[2:]) <= 24:
return True
else:
return False
for i in s.split(','):
if i.isdigit() and int(i) <= 24:
continue
else:
return False
return True
except ValueError:
return False
#TODO: check if this is still necessary
def checkHomeEncrypt():
"""
Return ``True`` if users home is encrypted
"""
home = os.path.expanduser('~')
if not os.path.ismount(home):
return False
if checkCommand('ecryptfs-verify'):
try:
subprocess.check_call(['ecryptfs-verify', '--home'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError:
pass
else:
return True
if checkCommand('encfs'):
proc = subprocess.Popen(['mount'], stdout=subprocess.PIPE, universal_newlines = True)
mount = proc.communicate()[0]
r = re.compile('^encfs on %s type fuse' % home)
for line in mount.split('\n'):
if r.match(line):
return True
return False
def envLoad(f):
"""
Load environ variables from file ``f`` into current environ.
Do not overwrite existing environ variables.
Args:
f (str): full path to file with environ variables
"""
env = os.environ.copy()
env_file = configfile.ConfigFile()
env_file.load(f, maxsplit = 1)
for key in env_file.keys():
value = env_file.strValue(key)
if not value:
continue
if not key in list(env.keys()):
os.environ[key] = value
del(env_file)
def envSave(f):
"""
Save environ variables to file that are needed by cron
to connect to keyring. This will only work if the user is logged in.
Args:
f (str): full path to file for environ variables
"""
env = os.environ.copy()
env_file = configfile.ConfigFile()
for key in ('GNOME_KEYRING_CONTROL', 'DBUS_SESSION_BUS_ADDRESS', \
'DBUS_SESSION_BUS_PID', 'DBUS_SESSION_BUS_WINDOWID', \
'DISPLAY', 'XAUTHORITY', 'GNOME_DESKTOP_SESSION_ID', \
'KDE_FULL_SESSION'):
if key in env:
env_file.setStrValue(key, env[key])
env_file.save(f)
def keyringSupported():
if keyring is None:
logger.debug('No keyring due to import error.')
return False
# Determine the currently active backend
try:
# get_keyring() internally calls keyring.core.init_backend()
# which fixes non-available backends for the first call.
# See related issue #1321:
# https://github.com/bit-team/backintime/issues/1321
displayName = keyring.get_keyring().__module__
except:
displayName = str(keyring.get_keyring())
logger.debug("Available keyring backends:")
try:
for b in backend.get_all_keyring():
logger.debug(b)
except Exception as e:
logger.debug("Available backends cannot be listed: " + repr(e))
available_backends = []
# Create a list of installed backends that BiT supports (white-listed).
# This is done by trying to put the meta classes ("class definitions",
# NOT instances of the class itself!) of the supported backends
# into the "backends" list
try: available_backends.append(keyring.backends.SecretService.Keyring)
except Exception as e: logger.debug("Metaclass keyring.backends.SecretService.Keyring not found: " + repr(e))
try: available_backends.append(keyring.backends.Gnome.Keyring)
except Exception as e: logger.debug("Metaclass keyring.backends.Gnome.Keyring not found: " + repr(e))
try: available_backends.append(keyring.backends.kwallet.Keyring)
except Exception as e: logger.debug("Metaclass keyring.backends.kwallet.Keyring not found: " + repr(e))
try: available_backends.append(keyring.backends.kwallet.DBusKeyring)
except Exception as e: logger.debug("Metaclass keyring.backends.kwallet.DBusKeyring not found: " + repr(e))
try: available_backends.append(keyring.backend.SecretServiceKeyring)
except Exception as e: logger.debug("Metaclass keyring.backend.SecretServiceKeyring not found: " + repr(e))
try: available_backends.append(keyring.backend.GnomeKeyring)
except Exception as e: logger.debug("Metaclass keyring.backend.GnomeKeyring not found: " + repr(e))
try: available_backends.append(keyring.backend.KDEKWallet)
except Exception as e: logger.debug("Metaclass keyring.backend.KDEKWallet not found: " + repr(e))
# TODO (Oct. 7, 2022): Should the ChainerBackend also be supported?
# It could solve the problem of configuring the
# used backend since it iterates over all of them
# and seems to be the default backend now.
# On the other hand it could use a non-supported
# backend without a chance for BiT to notice this.
# See: https://github.com/jaraco/keyring/blob/977ed03677bb0602b91f005461ef3dddf01a49f6/keyring/backends/chainer.py#L11
# try: backends.append(keyring.backends.chainer.ChainerBackend)
# except Exception as e: logger.debug("Metaclass keyring.backend. not found:" + repr(e))
logger.debug("Available supported backends: " + repr(available_backends))
if available_backends and isinstance(keyring.get_keyring(), tuple(available_backends)):
logger.debug("Found appropriate keyring '{}'".format(displayName))
return True
logger.debug("No appropriate keyring found. '{}' can't be used with BackInTime".format(displayName))
# TODO (Oct. 07, 2022): Write log output indicating possible solutions for this (eg. via a URL)
return False
def password(*args):
if not keyring is None:
return keyring.get_password(*args)
return None
def setPassword(*args):
if not keyring is None:
return keyring.set_password(*args)
return False
def mountpoint(path):
"""
Get the mountpoint of ``path``. If your HOME is on a separate partition
mountpoint('/home/user/foo') would return '/home'.
Args:
path (str): full path
Returns:
str: mountpoint of the filesystem
"""
path = os.path.realpath(os.path.abspath(path))
while path != os.path.sep:
if os.path.ismount(path):
return path
path = os.path.abspath(os.path.join(path, os.pardir))
return path
def decodeOctalEscape(s):
"""
Decode octal-escaped characters with its ASCII dependance.
For example '\040' will be a space ' '
Args:
s (str): string with or without octal-escaped characters
Returns:
str: human readable string
"""
def repl(m):
return chr(int(m.group(1), 8))
return re.sub(r'\\(\d{3})', repl, s)
def mountArgs(path):
"""
Get all /etc/mtab args for the filesystem of ``path`` as a list.
Example::
[DEVICE, MOUNTPOINT, FILESYSTEM_TYPE, OPTIONS, DUMP, PASS]
['/dev/sda3', '/', 'ext4', 'defaults', '0', '0']
['/dev/sda1', '/boot', 'ext4', 'defaults', '0', '0']
Args:
path (str): full path
Returns:
list: mount args
"""
mp = mountpoint(path)
with open('/etc/mtab', 'r') as mounts:
for line in mounts:
args = line.strip('\n').split(' ')
if len(args) >= 2:
args[1] = decodeOctalEscape(args[1])
if args[1] == mp:
return args
return None
def device(path):
"""
Get the device for the filesystem of ``path``.
Example::
/dev/sda1
/dev/mapper/vglinux
proc
Args:
path (str): full path
Returns:
str: device
"""
args = mountArgs(path)
if args:
return args[0]