helpers.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. from .support import argparse # see support/__init__.py docstring, DEPRECATED - remove after requiring py 3.4
  2. import binascii
  3. from collections import namedtuple
  4. from functools import wraps
  5. import grp
  6. import os
  7. import pwd
  8. import re
  9. try:
  10. from shutil import get_terminal_size
  11. except ImportError:
  12. def get_terminal_size(fallback=(80, 24)):
  13. TerminalSize = namedtuple('TerminalSize', ['columns', 'lines'])
  14. return TerminalSize(int(os.environ.get('COLUMNS', fallback[0])), int(os.environ.get('LINES', fallback[1])))
  15. import sys
  16. import time
  17. import unicodedata
  18. from datetime import datetime, timezone, timedelta
  19. from fnmatch import translate
  20. from operator import attrgetter
  21. from . import hashindex
  22. from . import chunker
  23. from . import crypto
  24. import msgpack
  25. import msgpack.fallback
  26. # return codes returned by borg command
  27. # when borg is killed by signal N, rc = 128 + N
  28. EXIT_SUCCESS = 0 # everything done, no problems
  29. EXIT_WARNING = 1 # reached normal end of operation, but there were issues
  30. EXIT_ERROR = 2 # terminated abruptly, did not reach end of operation
  31. class Error(Exception):
  32. """Error base class"""
  33. # if we raise such an Error and it is only catched by the uppermost
  34. # exception handler (that exits short after with the given exit_code),
  35. # it is always a (fatal and abrupt) EXIT_ERROR, never just a warning.
  36. exit_code = EXIT_ERROR
  37. # show a traceback?
  38. traceback = False
  39. def get_message(self):
  40. return type(self).__doc__.format(*self.args)
  41. class ErrorWithTraceback(Error):
  42. """like Error, but show a traceback also"""
  43. traceback = True
  44. class IntegrityError(ErrorWithTraceback):
  45. """Data integrity error"""
  46. class ExtensionModuleError(Error):
  47. """The Borg binary extension modules do not seem to be properly installed"""
  48. def check_extension_modules():
  49. from . import platform
  50. if hashindex.API_VERSION != 2:
  51. raise ExtensionModuleError
  52. if chunker.API_VERSION != 2:
  53. raise ExtensionModuleError
  54. if crypto.API_VERSION != 2:
  55. raise ExtensionModuleError
  56. if platform.API_VERSION != 2:
  57. raise ExtensionModuleError
  58. class Manifest:
  59. MANIFEST_ID = b'\0' * 32
  60. def __init__(self, key, repository):
  61. self.archives = {}
  62. self.config = {}
  63. self.key = key
  64. self.repository = repository
  65. @classmethod
  66. def load(cls, repository, key=None):
  67. from .key import key_factory
  68. cdata = repository.get(cls.MANIFEST_ID)
  69. if not key:
  70. key = key_factory(repository, cdata)
  71. manifest = cls(key, repository)
  72. data = key.decrypt(None, cdata)
  73. manifest.id = key.id_hash(data)
  74. m = msgpack.unpackb(data)
  75. if not m.get(b'version') == 1:
  76. raise ValueError('Invalid manifest version')
  77. manifest.archives = dict((k.decode('utf-8'), v) for k, v in m[b'archives'].items())
  78. manifest.timestamp = m.get(b'timestamp')
  79. if manifest.timestamp:
  80. manifest.timestamp = manifest.timestamp.decode('ascii')
  81. manifest.config = m[b'config']
  82. return manifest, key
  83. def write(self):
  84. self.timestamp = datetime.utcnow().isoformat()
  85. data = msgpack.packb(StableDict({
  86. 'version': 1,
  87. 'archives': self.archives,
  88. 'timestamp': self.timestamp,
  89. 'config': self.config,
  90. }))
  91. self.id = self.key.id_hash(data)
  92. self.repository.put(self.MANIFEST_ID, self.key.encrypt(data))
  93. def list_archive_infos(self, sort_by=None, reverse=False):
  94. # inexpensive Archive.list_archives replacement if we just need .name, .id, .ts
  95. ArchiveInfo = namedtuple('ArchiveInfo', 'name id ts')
  96. archives = []
  97. for name, values in self.archives.items():
  98. ts = parse_timestamp(values[b'time'].decode('utf-8'))
  99. id = values[b'id']
  100. archives.append(ArchiveInfo(name=name, id=id, ts=ts))
  101. if sort_by is not None:
  102. archives = sorted(archives, key=attrgetter(sort_by), reverse=reverse)
  103. return archives
  104. def prune_within(archives, within):
  105. multiplier = {'H': 1, 'd': 24, 'w': 24*7, 'm': 24*31, 'y': 24*365}
  106. try:
  107. hours = int(within[:-1]) * multiplier[within[-1]]
  108. except (KeyError, ValueError):
  109. # I don't like how this displays the original exception too:
  110. raise argparse.ArgumentTypeError('Unable to parse --within option: "%s"' % within)
  111. if hours <= 0:
  112. raise argparse.ArgumentTypeError('Number specified using --within option must be positive')
  113. target = datetime.now(timezone.utc) - timedelta(seconds=hours*60*60)
  114. return [a for a in archives if a.ts > target]
  115. def prune_split(archives, pattern, n, skip=[]):
  116. last = None
  117. keep = []
  118. if n == 0:
  119. return keep
  120. for a in sorted(archives, key=attrgetter('ts'), reverse=True):
  121. period = to_localtime(a.ts).strftime(pattern)
  122. if period != last:
  123. last = period
  124. if a not in skip:
  125. keep.append(a)
  126. if len(keep) == n:
  127. break
  128. return keep
  129. class Statistics:
  130. def __init__(self):
  131. self.osize = self.csize = self.usize = self.nfiles = 0
  132. def update(self, size, csize, unique):
  133. self.osize += size
  134. self.csize += csize
  135. if unique:
  136. self.usize += csize
  137. summary = """\
  138. Original size Compressed size Deduplicated size
  139. {label:15} {stats.osize_fmt:>20s} {stats.csize_fmt:>20s} {stats.usize_fmt:>20s}"""
  140. def __str__(self):
  141. return self.summary.format(stats=self, label='This archive:')
  142. def __repr__(self):
  143. return "<{cls} object at {hash:#x} ({self.osize}, {self.csize}, {self.usize})>".format(cls=type(self).__name__, hash=id(self), self=self)
  144. @property
  145. def osize_fmt(self):
  146. return format_file_size(self.osize)
  147. @property
  148. def usize_fmt(self):
  149. return format_file_size(self.usize)
  150. @property
  151. def csize_fmt(self):
  152. return format_file_size(self.csize)
  153. def show_progress(self, item=None, final=False, stream=None):
  154. columns, lines = get_terminal_size()
  155. if not final:
  156. msg = '{0.osize_fmt} O {0.csize_fmt} C {0.usize_fmt} D {0.nfiles} N '.format(self)
  157. path = remove_surrogates(item[b'path']) if item else ''
  158. space = columns - len(msg)
  159. if space < len('...') + len(path):
  160. path = '%s...%s' % (path[:(space//2)-len('...')], path[-space//2:])
  161. msg += "{0:<{space}}".format(path, space=space)
  162. else:
  163. msg = ' ' * columns
  164. print(msg, file=stream or sys.stderr, end="\r")
  165. (stream or sys.stderr).flush()
  166. def get_keys_dir():
  167. """Determine where to repository keys and cache"""
  168. return os.environ.get('BORG_KEYS_DIR',
  169. os.path.join(os.path.expanduser('~'), '.borg', 'keys'))
  170. def get_cache_dir():
  171. """Determine where to repository keys and cache"""
  172. xdg_cache = os.environ.get('XDG_CACHE_HOME', os.path.join(os.path.expanduser('~'), '.cache'))
  173. return os.environ.get('BORG_CACHE_DIR', os.path.join(xdg_cache, 'borg'))
  174. def to_localtime(ts):
  175. """Convert datetime object from UTC to local time zone"""
  176. return datetime(*time.localtime((ts - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())[:6])
  177. def parse_timestamp(timestamp):
  178. """Parse a ISO 8601 timestamp string"""
  179. if '.' in timestamp: # microseconds might not be pressent
  180. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)
  181. else:
  182. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc)
  183. def update_excludes(args):
  184. """Merge exclude patterns from files with those on command line.
  185. Empty lines and lines starting with '#' are ignored, but whitespace
  186. is not stripped."""
  187. if hasattr(args, 'exclude_files') and args.exclude_files:
  188. if not hasattr(args, 'excludes') or args.excludes is None:
  189. args.excludes = []
  190. for file in args.exclude_files:
  191. patterns = [line.rstrip('\r\n') for line in file if not line.startswith('#')]
  192. args.excludes += [ExcludePattern(pattern) for pattern in patterns if pattern]
  193. file.close()
  194. def adjust_patterns(paths, excludes):
  195. if paths:
  196. return (excludes or []) + [IncludePattern(path) for path in paths] + [ExcludePattern('*')]
  197. else:
  198. return excludes
  199. def exclude_path(path, patterns):
  200. """Used by create and extract sub-commands to determine
  201. whether or not an item should be processed.
  202. """
  203. for pattern in (patterns or []):
  204. if pattern.match(path):
  205. return isinstance(pattern, ExcludePattern)
  206. return False
  207. # For both IncludePattern and ExcludePattern, we require that
  208. # the pattern either match the whole path or an initial segment
  209. # of the path up to but not including a path separator. To
  210. # unify the two cases, we add a path separator to the end of
  211. # the path before matching.
  212. def normalized(func):
  213. """ Decorator for the Pattern match methods, returning a wrapper that
  214. normalizes OSX paths to match the normalized pattern on OSX, and
  215. returning the original method on other platforms"""
  216. @wraps(func)
  217. def normalize_wrapper(self, path):
  218. return func(self, unicodedata.normalize("NFD", path))
  219. if sys.platform in ('darwin',):
  220. # HFS+ converts paths to a canonical form, so users shouldn't be
  221. # required to enter an exact match
  222. return normalize_wrapper
  223. else:
  224. # Windows and Unix filesystems allow different forms, so users
  225. # always have to enter an exact match
  226. return func
  227. class IncludePattern:
  228. """Literal files or directories listed on the command line
  229. for some operations (e.g. extract, but not create).
  230. If a directory is specified, all paths that start with that
  231. path match as well. A trailing slash makes no difference.
  232. """
  233. def __init__(self, pattern):
  234. self.pattern_orig = pattern
  235. self.match_count = 0
  236. if sys.platform in ('darwin',):
  237. pattern = unicodedata.normalize("NFD", pattern)
  238. self.pattern = os.path.normpath(pattern).rstrip(os.path.sep)+os.path.sep
  239. @normalized
  240. def match(self, path):
  241. matches = (path+os.path.sep).startswith(self.pattern)
  242. if matches:
  243. self.match_count += 1
  244. return matches
  245. def __repr__(self):
  246. return '%s(%s)' % (type(self), self.pattern)
  247. def __str__(self):
  248. return self.pattern_orig
  249. class ExcludePattern(IncludePattern):
  250. """Shell glob patterns to exclude. A trailing slash means to
  251. exclude the contents of a directory, but not the directory itself.
  252. """
  253. def __init__(self, pattern):
  254. self.pattern_orig = pattern
  255. self.match_count = 0
  256. if pattern.endswith(os.path.sep):
  257. self.pattern = os.path.normpath(pattern).rstrip(os.path.sep)+os.path.sep+'*'+os.path.sep
  258. else:
  259. self.pattern = os.path.normpath(pattern)+os.path.sep+'*'
  260. if sys.platform in ('darwin',):
  261. self.pattern = unicodedata.normalize("NFD", self.pattern)
  262. # fnmatch and re.match both cache compiled regular expressions.
  263. # Nevertheless, this is about 10 times faster.
  264. self.regex = re.compile(translate(self.pattern))
  265. @normalized
  266. def match(self, path):
  267. matches = self.regex.match(path+os.path.sep) is not None
  268. if matches:
  269. self.match_count += 1
  270. return matches
  271. def __repr__(self):
  272. return '%s(%s)' % (type(self), self.pattern)
  273. def __str__(self):
  274. return self.pattern_orig
  275. def timestamp(s):
  276. """Convert a --timestamp=s argument to a datetime object"""
  277. try:
  278. # is it pointing to a file / directory?
  279. ts = os.stat(s).st_mtime
  280. return datetime.utcfromtimestamp(ts)
  281. except OSError:
  282. # didn't work, try parsing as timestamp. UTC, no TZ, no microsecs support.
  283. for format in ('%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S+00:00',
  284. '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S',
  285. '%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M',
  286. '%Y-%m-%d', '%Y-%j',
  287. ):
  288. try:
  289. return datetime.strptime(s, format)
  290. except ValueError:
  291. continue
  292. raise ValueError
  293. def ChunkerParams(s):
  294. chunk_min, chunk_max, chunk_mask, window_size = s.split(',')
  295. if int(chunk_max) > 23:
  296. # do not go beyond 2**23 (8MB) chunk size now,
  297. # COMPR_BUFFER can only cope with up to this size
  298. raise ValueError('max. chunk size exponent must not be more than 23 (2^23 = 8MiB max. chunk size)')
  299. return int(chunk_min), int(chunk_max), int(chunk_mask), int(window_size)
  300. def CompressionSpec(s):
  301. values = s.split(',')
  302. count = len(values)
  303. if count < 1:
  304. raise ValueError
  305. compression = values[0]
  306. try:
  307. compression = int(compression)
  308. if count > 1:
  309. raise ValueError
  310. # DEPRECATED: it is just --compression N
  311. if 0 <= compression <= 9:
  312. print('Warning: --compression %d is deprecated, please use --compression zlib,%d.' % (compression, compression))
  313. if compression == 0:
  314. print('Hint: instead of --compression zlib,0 you could also use --compression none for better performance.')
  315. print('Hint: archives generated using --compression none are not compatible with borg < 0.25.0.')
  316. return dict(name='zlib', level=compression)
  317. raise ValueError
  318. except ValueError:
  319. # --compression algo[,...]
  320. name = compression
  321. if name in ('none', 'lz4', ):
  322. return dict(name=name)
  323. if name in ('zlib', 'lzma', ):
  324. if count < 2:
  325. level = 6 # default compression level in py stdlib
  326. elif count == 2:
  327. level = int(values[1])
  328. if not 0 <= level <= 9:
  329. raise ValueError
  330. else:
  331. raise ValueError
  332. return dict(name=name, level=level)
  333. raise ValueError
  334. def dir_is_cachedir(path):
  335. """Determines whether the specified path is a cache directory (and
  336. therefore should potentially be excluded from the backup) according to
  337. the CACHEDIR.TAG protocol
  338. (http://www.brynosaurus.com/cachedir/spec.html).
  339. """
  340. tag_contents = b'Signature: 8a477f597d28d172789f06886806bc55'
  341. tag_path = os.path.join(path, 'CACHEDIR.TAG')
  342. try:
  343. if os.path.exists(tag_path):
  344. with open(tag_path, 'rb') as tag_file:
  345. tag_data = tag_file.read(len(tag_contents))
  346. if tag_data == tag_contents:
  347. return True
  348. except OSError:
  349. pass
  350. return False
  351. def dir_is_tagged(path, exclude_caches, exclude_if_present):
  352. """Determines whether the specified path is excluded by being a cache
  353. directory or containing the user-specified tag file. Returns the
  354. path of the tag file (either CACHEDIR.TAG or the matching
  355. user-specified file)
  356. """
  357. if exclude_caches and dir_is_cachedir(path):
  358. return os.path.join(path, 'CACHEDIR.TAG')
  359. if exclude_if_present is not None:
  360. for tag in exclude_if_present:
  361. tag_path = os.path.join(path, tag)
  362. if os.path.isfile(tag_path):
  363. return tag_path
  364. return None
  365. def format_time(t):
  366. """use ISO-8601 date and time format
  367. """
  368. return t.strftime('%Y-%m-%d %H:%M:%S')
  369. def format_timedelta(td):
  370. """Format timedelta in a human friendly format
  371. """
  372. # Since td.total_seconds() requires python 2.7
  373. ts = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
  374. s = ts % 60
  375. m = int(ts / 60) % 60
  376. h = int(ts / 3600) % 24
  377. txt = '%.2f seconds' % s
  378. if m:
  379. txt = '%d minutes %s' % (m, txt)
  380. if h:
  381. txt = '%d hours %s' % (h, txt)
  382. if td.days:
  383. txt = '%d days %s' % (td.days, txt)
  384. return txt
  385. def format_file_mode(mod):
  386. """Format file mode bits for list output
  387. """
  388. def x(v):
  389. return ''.join(v & m and s or '-'
  390. for m, s in ((4, 'r'), (2, 'w'), (1, 'x')))
  391. return '%s%s%s' % (x(mod // 64), x(mod // 8), x(mod))
  392. def format_file_size(v, precision=2):
  393. """Format file size into a human friendly format
  394. """
  395. return sizeof_fmt_decimal(v, suffix='B', sep=' ', precision=precision)
  396. def sizeof_fmt(num, suffix='B', units=None, power=None, sep='', precision=2):
  397. for unit in units[:-1]:
  398. if abs(round(num, precision)) < power:
  399. if isinstance(num, int):
  400. return "{}{}{}{}".format(num, sep, unit, suffix)
  401. else:
  402. return "{:3.{}f}{}{}{}".format(num, precision, sep, unit, suffix)
  403. num /= float(power)
  404. return "{:.{}f}{}{}{}".format(num, precision, sep, units[-1], suffix)
  405. def sizeof_fmt_iec(num, suffix='B', sep='', precision=2):
  406. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, units=['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'], power=1024)
  407. def sizeof_fmt_decimal(num, suffix='B', sep='', precision=2):
  408. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, units=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], power=1000)
  409. def format_archive(archive):
  410. return '%-36s %s' % (archive.name, format_time(to_localtime(archive.ts)))
  411. def memoize(function):
  412. cache = {}
  413. def decorated_function(*args):
  414. try:
  415. return cache[args]
  416. except KeyError:
  417. val = function(*args)
  418. cache[args] = val
  419. return val
  420. return decorated_function
  421. @memoize
  422. def uid2user(uid, default=None):
  423. try:
  424. return pwd.getpwuid(uid).pw_name
  425. except KeyError:
  426. return default
  427. @memoize
  428. def user2uid(user, default=None):
  429. try:
  430. return user and pwd.getpwnam(user).pw_uid
  431. except KeyError:
  432. return default
  433. @memoize
  434. def gid2group(gid, default=None):
  435. try:
  436. return grp.getgrgid(gid).gr_name
  437. except KeyError:
  438. return default
  439. @memoize
  440. def group2gid(group, default=None):
  441. try:
  442. return group and grp.getgrnam(group).gr_gid
  443. except KeyError:
  444. return default
  445. def posix_acl_use_stored_uid_gid(acl):
  446. """Replace the user/group field with the stored uid/gid
  447. """
  448. entries = []
  449. for entry in safe_decode(acl).split('\n'):
  450. if entry:
  451. fields = entry.split(':')
  452. if len(fields) == 4:
  453. entries.append(':'.join([fields[0], fields[3], fields[2]]))
  454. else:
  455. entries.append(entry)
  456. return safe_encode('\n'.join(entries))
  457. def safe_decode(s, coding='utf-8', errors='surrogateescape'):
  458. """decode bytes to str, with round-tripping "invalid" bytes"""
  459. return s.decode(coding, errors)
  460. def safe_encode(s, coding='utf-8', errors='surrogateescape'):
  461. """encode str to bytes, with round-tripping "invalid" bytes"""
  462. return s.encode(coding, errors)
  463. class Location:
  464. """Object representing a repository / archive location
  465. """
  466. proto = user = host = port = path = archive = None
  467. # borg mount's FUSE filesystem creates one level of directories from
  468. # the archive names. Thus, we must not accept "/" in archive names.
  469. ssh_re = re.compile(r'(?P<proto>ssh)://(?:(?P<user>[^@]+)@)?'
  470. r'(?P<host>[^:/#]+)(?::(?P<port>\d+))?'
  471. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  472. file_re = re.compile(r'(?P<proto>file)://'
  473. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  474. scp_re = re.compile(r'((?:(?P<user>[^@]+)@)?(?P<host>[^:/]+):)?'
  475. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  476. # get the repo from BORG_RE env and the optional archive from param.
  477. # if the syntax requires giving REPOSITORY (see "borg mount"),
  478. # use "::" to let it use the env var.
  479. # if REPOSITORY argument is optional, it'll automatically use the env.
  480. env_re = re.compile(r'(?:::(?P<archive>[^/]+)?)?$')
  481. def __init__(self, text=''):
  482. self.orig = text
  483. if not self.parse(self.orig):
  484. raise ValueError
  485. def parse(self, text):
  486. valid = self._parse(text)
  487. if valid:
  488. return True
  489. m = self.env_re.match(text)
  490. if not m:
  491. return False
  492. repo = os.environ.get('BORG_REPO')
  493. if repo is None:
  494. return False
  495. valid = self._parse(repo)
  496. if not valid:
  497. return False
  498. self.archive = m.group('archive')
  499. return True
  500. def _parse(self, text):
  501. m = self.ssh_re.match(text)
  502. if m:
  503. self.proto = m.group('proto')
  504. self.user = m.group('user')
  505. self.host = m.group('host')
  506. self.port = m.group('port') and int(m.group('port')) or None
  507. self.path = m.group('path')
  508. self.archive = m.group('archive')
  509. return True
  510. m = self.file_re.match(text)
  511. if m:
  512. self.proto = m.group('proto')
  513. self.path = m.group('path')
  514. self.archive = m.group('archive')
  515. return True
  516. m = self.scp_re.match(text)
  517. if m:
  518. self.user = m.group('user')
  519. self.host = m.group('host')
  520. self.path = m.group('path')
  521. self.archive = m.group('archive')
  522. self.proto = self.host and 'ssh' or 'file'
  523. return True
  524. return False
  525. def __str__(self):
  526. items = [
  527. 'proto=%r' % self.proto,
  528. 'user=%r' % self.user,
  529. 'host=%r' % self.host,
  530. 'port=%r' % self.port,
  531. 'path=%r' % self.path,
  532. 'archive=%r' % self.archive,
  533. ]
  534. return ', '.join(items)
  535. def to_key_filename(self):
  536. name = re.sub('[^\w]', '_', self.path).strip('_')
  537. if self.proto != 'file':
  538. name = self.host + '__' + name
  539. return os.path.join(get_keys_dir(), name)
  540. def __repr__(self):
  541. return "Location(%s)" % self
  542. def canonical_path(self):
  543. if self.proto == 'file':
  544. return self.path
  545. else:
  546. if self.path and self.path.startswith('~'):
  547. path = '/' + self.path
  548. elif self.path and not self.path.startswith('/'):
  549. path = '/~/' + self.path
  550. else:
  551. path = self.path
  552. return 'ssh://{}{}{}{}'.format('{}@'.format(self.user) if self.user else '',
  553. self.host,
  554. ':{}'.format(self.port) if self.port else '',
  555. path)
  556. def location_validator(archive=None):
  557. def validator(text):
  558. try:
  559. loc = Location(text)
  560. except ValueError:
  561. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text)
  562. if archive is True and not loc.archive:
  563. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  564. elif archive is False and loc.archive:
  565. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  566. return loc
  567. return validator
  568. def read_msgpack(filename):
  569. with open(filename, 'rb') as fd:
  570. return msgpack.unpack(fd)
  571. def write_msgpack(filename, d):
  572. with open(filename + '.tmp', 'wb') as fd:
  573. msgpack.pack(d, fd)
  574. fd.flush()
  575. os.fsync(fd.fileno())
  576. os.rename(filename + '.tmp', filename)
  577. def decode_dict(d, keys, encoding='utf-8', errors='surrogateescape'):
  578. for key in keys:
  579. if isinstance(d.get(key), bytes):
  580. d[key] = d[key].decode(encoding, errors)
  581. return d
  582. def remove_surrogates(s, errors='replace'):
  583. """Replace surrogates generated by fsdecode with '?'
  584. """
  585. return s.encode('utf-8', errors).decode('utf-8')
  586. _safe_re = re.compile(r'^((\.\.)?/+)+')
  587. def make_path_safe(path):
  588. """Make path safe by making it relative and local
  589. """
  590. return _safe_re.sub('', path) or '.'
  591. def daemonize():
  592. """Detach process from controlling terminal and run in background
  593. """
  594. pid = os.fork()
  595. if pid:
  596. os._exit(0)
  597. os.setsid()
  598. pid = os.fork()
  599. if pid:
  600. os._exit(0)
  601. os.chdir('/')
  602. os.close(0)
  603. os.close(1)
  604. os.close(2)
  605. fd = os.open('/dev/null', os.O_RDWR)
  606. os.dup2(fd, 0)
  607. os.dup2(fd, 1)
  608. os.dup2(fd, 2)
  609. class StableDict(dict):
  610. """A dict subclass with stable items() ordering"""
  611. def items(self):
  612. return sorted(super().items())
  613. if sys.version < '3.3':
  614. # st_xtime_ns attributes only available in 3.3+
  615. def st_atime_ns(st):
  616. return int(st.st_atime * 1e9)
  617. def st_ctime_ns(st):
  618. return int(st.st_ctime * 1e9)
  619. def st_mtime_ns(st):
  620. return int(st.st_mtime * 1e9)
  621. # unhexlify in < 3.3 incorrectly only accepts bytes input
  622. def unhexlify(data):
  623. if isinstance(data, str):
  624. data = data.encode('ascii')
  625. return binascii.unhexlify(data)
  626. else:
  627. def st_atime_ns(st):
  628. return st.st_atime_ns
  629. def st_ctime_ns(st):
  630. return st.st_ctime_ns
  631. def st_mtime_ns(st):
  632. return st.st_mtime_ns
  633. unhexlify = binascii.unhexlify
  634. def bigint_to_int(mtime):
  635. """Convert bytearray to int
  636. """
  637. if isinstance(mtime, bytes):
  638. return int.from_bytes(mtime, 'little', signed=True)
  639. return mtime
  640. def int_to_bigint(value):
  641. """Convert integers larger than 64 bits to bytearray
  642. Smaller integers are left alone
  643. """
  644. if value.bit_length() > 63:
  645. return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
  646. return value
  647. def is_slow_msgpack():
  648. return msgpack.Packer is msgpack.fallback.Packer
  649. def yes(msg=None, retry_msg=None, false_msg=None, true_msg=None,
  650. default=False, default_notty=None, default_eof=None,
  651. falsish=('No', 'no', 'N', 'n'), truish=('Yes', 'yes', 'Y', 'y'),
  652. env_var_override=None, ifile=None, ofile=None, input=input):
  653. """
  654. Output <msg> (usually a question) and let user input an answer.
  655. Qualifies the answer according to falsish and truish as True or False.
  656. If it didn't qualify and retry_msg is None (no retries wanted),
  657. return the default [which defaults to False]. Otherwise let user retry
  658. answering until answer is qualified.
  659. If env_var_override is given and it is non-empty, counts as truish answer
  660. and won't ask user for an answer.
  661. If we don't have a tty as input and default_notty is not None, return its value.
  662. Otherwise read input from non-tty and proceed as normal.
  663. If EOF is received instead an input, return default_eof [or default, if not given].
  664. :param msg: introducing message to output on ofile, no \n is added [None]
  665. :param retry_msg: retry message to output on ofile, no \n is added [None]
  666. (also enforces retries instead of returning default)
  667. :param false_msg: message to output before returning False [None]
  668. :param true_msg: message to output before returning True [None]
  669. :param default: default return value (empty answer is given) [False]
  670. :param default_notty: if not None, return its value if no tty is connected [None]
  671. :param default_eof: return value if EOF was read as answer [same as default]
  672. :param falsish: sequence of answers qualifying as False
  673. :param truish: sequence of answers qualifying as True
  674. :param env_var_override: environment variable name [None]
  675. :param ifile: input stream [sys.stdin] (only for testing!)
  676. :param ofile: output stream [sys.stderr]
  677. :param input: input function [input from builtins]
  678. :return: boolean answer value, True or False
  679. """
  680. # note: we do not assign sys.stdin/stderr as defaults above, so they are
  681. # really evaluated NOW, not at function definition time.
  682. if ifile is None:
  683. ifile = sys.stdin
  684. if ofile is None:
  685. ofile = sys.stderr
  686. if default not in (True, False):
  687. raise ValueError("invalid default value, must be True or False")
  688. if default_notty not in (None, True, False):
  689. raise ValueError("invalid default_notty value, must be None, True or False")
  690. if default_eof not in (None, True, False):
  691. raise ValueError("invalid default_eof value, must be None, True or False")
  692. if msg:
  693. print(msg, file=ofile, end='')
  694. ofile.flush()
  695. if env_var_override:
  696. value = os.environ.get(env_var_override)
  697. # currently, any non-empty value counts as truish
  698. # TODO: change this so one can give y/n there?
  699. if value:
  700. value = bool(value)
  701. value_str = truish[0] if value else falsish[0]
  702. print("{} (from {})".format(value_str, env_var_override), file=ofile)
  703. return value
  704. if default_notty is not None and not ifile.isatty():
  705. # looks like ifile is not a terminal (but e.g. a pipe)
  706. return default_notty
  707. while True:
  708. try:
  709. answer = input() # XXX how can we use ifile?
  710. except EOFError:
  711. return default_eof if default_eof is not None else default
  712. if answer in truish:
  713. if true_msg:
  714. print(true_msg, file=ofile)
  715. return True
  716. if answer in falsish:
  717. if false_msg:
  718. print(false_msg, file=ofile)
  719. return False
  720. if retry_msg is None:
  721. # no retries wanted, we just return the default
  722. return default
  723. if retry_msg:
  724. print(retry_msg, file=ofile, end='')
  725. ofile.flush()