helpers.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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 user-specified tag files. Returns a list of the
  354. paths of the tag files (either CACHEDIR.TAG or the matching
  355. user-specified files).
  356. """
  357. tag_paths = []
  358. if exclude_caches and dir_is_cachedir(path):
  359. tag_paths.append(os.path.join(path, 'CACHEDIR.TAG'))
  360. if exclude_if_present is not None:
  361. for tag in exclude_if_present:
  362. tag_path = os.path.join(path, tag)
  363. if os.path.isfile(tag_path):
  364. tag_paths.append(tag_path)
  365. return tag_paths
  366. def format_time(t):
  367. """use ISO-8601 date and time format
  368. """
  369. return t.strftime('%Y-%m-%d %H:%M:%S')
  370. def format_timedelta(td):
  371. """Format timedelta in a human friendly format
  372. """
  373. # Since td.total_seconds() requires python 2.7
  374. ts = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
  375. s = ts % 60
  376. m = int(ts / 60) % 60
  377. h = int(ts / 3600) % 24
  378. txt = '%.2f seconds' % s
  379. if m:
  380. txt = '%d minutes %s' % (m, txt)
  381. if h:
  382. txt = '%d hours %s' % (h, txt)
  383. if td.days:
  384. txt = '%d days %s' % (td.days, txt)
  385. return txt
  386. def format_file_mode(mod):
  387. """Format file mode bits for list output
  388. """
  389. def x(v):
  390. return ''.join(v & m and s or '-'
  391. for m, s in ((4, 'r'), (2, 'w'), (1, 'x')))
  392. return '%s%s%s' % (x(mod // 64), x(mod // 8), x(mod))
  393. def format_file_size(v, precision=2):
  394. """Format file size into a human friendly format
  395. """
  396. return sizeof_fmt_decimal(v, suffix='B', sep=' ', precision=precision)
  397. def sizeof_fmt(num, suffix='B', units=None, power=None, sep='', precision=2):
  398. for unit in units[:-1]:
  399. if abs(round(num, precision)) < power:
  400. if isinstance(num, int):
  401. return "{}{}{}{}".format(num, sep, unit, suffix)
  402. else:
  403. return "{:3.{}f}{}{}{}".format(num, precision, sep, unit, suffix)
  404. num /= float(power)
  405. return "{:.{}f}{}{}{}".format(num, precision, sep, units[-1], suffix)
  406. def sizeof_fmt_iec(num, suffix='B', sep='', precision=2):
  407. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, units=['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'], power=1024)
  408. def sizeof_fmt_decimal(num, suffix='B', sep='', precision=2):
  409. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, units=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], power=1000)
  410. def format_archive(archive):
  411. return '%-36s %s' % (archive.name, format_time(to_localtime(archive.ts)))
  412. def memoize(function):
  413. cache = {}
  414. def decorated_function(*args):
  415. try:
  416. return cache[args]
  417. except KeyError:
  418. val = function(*args)
  419. cache[args] = val
  420. return val
  421. return decorated_function
  422. @memoize
  423. def uid2user(uid, default=None):
  424. try:
  425. return pwd.getpwuid(uid).pw_name
  426. except KeyError:
  427. return default
  428. @memoize
  429. def user2uid(user, default=None):
  430. try:
  431. return user and pwd.getpwnam(user).pw_uid
  432. except KeyError:
  433. return default
  434. @memoize
  435. def gid2group(gid, default=None):
  436. try:
  437. return grp.getgrgid(gid).gr_name
  438. except KeyError:
  439. return default
  440. @memoize
  441. def group2gid(group, default=None):
  442. try:
  443. return group and grp.getgrnam(group).gr_gid
  444. except KeyError:
  445. return default
  446. def posix_acl_use_stored_uid_gid(acl):
  447. """Replace the user/group field with the stored uid/gid
  448. """
  449. entries = []
  450. for entry in safe_decode(acl).split('\n'):
  451. if entry:
  452. fields = entry.split(':')
  453. if len(fields) == 4:
  454. entries.append(':'.join([fields[0], fields[3], fields[2]]))
  455. else:
  456. entries.append(entry)
  457. return safe_encode('\n'.join(entries))
  458. def safe_decode(s, coding='utf-8', errors='surrogateescape'):
  459. """decode bytes to str, with round-tripping "invalid" bytes"""
  460. return s.decode(coding, errors)
  461. def safe_encode(s, coding='utf-8', errors='surrogateescape'):
  462. """encode str to bytes, with round-tripping "invalid" bytes"""
  463. return s.encode(coding, errors)
  464. class Location:
  465. """Object representing a repository / archive location
  466. """
  467. proto = user = host = port = path = archive = None
  468. # borg mount's FUSE filesystem creates one level of directories from
  469. # the archive names. Thus, we must not accept "/" in archive names.
  470. ssh_re = re.compile(r'(?P<proto>ssh)://(?:(?P<user>[^@]+)@)?'
  471. r'(?P<host>[^:/#]+)(?::(?P<port>\d+))?'
  472. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  473. file_re = re.compile(r'(?P<proto>file)://'
  474. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  475. scp_re = re.compile(r'((?:(?P<user>[^@]+)@)?(?P<host>[^:/]+):)?'
  476. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  477. # get the repo from BORG_RE env and the optional archive from param.
  478. # if the syntax requires giving REPOSITORY (see "borg mount"),
  479. # use "::" to let it use the env var.
  480. # if REPOSITORY argument is optional, it'll automatically use the env.
  481. env_re = re.compile(r'(?:::(?P<archive>[^/]+)?)?$')
  482. def __init__(self, text=''):
  483. self.orig = text
  484. if not self.parse(self.orig):
  485. raise ValueError
  486. def parse(self, text):
  487. valid = self._parse(text)
  488. if valid:
  489. return True
  490. m = self.env_re.match(text)
  491. if not m:
  492. return False
  493. repo = os.environ.get('BORG_REPO')
  494. if repo is None:
  495. return False
  496. valid = self._parse(repo)
  497. if not valid:
  498. return False
  499. self.archive = m.group('archive')
  500. return True
  501. def _parse(self, text):
  502. m = self.ssh_re.match(text)
  503. if m:
  504. self.proto = m.group('proto')
  505. self.user = m.group('user')
  506. self.host = m.group('host')
  507. self.port = m.group('port') and int(m.group('port')) or None
  508. self.path = m.group('path')
  509. self.archive = m.group('archive')
  510. return True
  511. m = self.file_re.match(text)
  512. if m:
  513. self.proto = m.group('proto')
  514. self.path = m.group('path')
  515. self.archive = m.group('archive')
  516. return True
  517. m = self.scp_re.match(text)
  518. if m:
  519. self.user = m.group('user')
  520. self.host = m.group('host')
  521. self.path = m.group('path')
  522. self.archive = m.group('archive')
  523. self.proto = self.host and 'ssh' or 'file'
  524. return True
  525. return False
  526. def __str__(self):
  527. items = [
  528. 'proto=%r' % self.proto,
  529. 'user=%r' % self.user,
  530. 'host=%r' % self.host,
  531. 'port=%r' % self.port,
  532. 'path=%r' % self.path,
  533. 'archive=%r' % self.archive,
  534. ]
  535. return ', '.join(items)
  536. def to_key_filename(self):
  537. name = re.sub('[^\w]', '_', self.path).strip('_')
  538. if self.proto != 'file':
  539. name = self.host + '__' + name
  540. return os.path.join(get_keys_dir(), name)
  541. def __repr__(self):
  542. return "Location(%s)" % self
  543. def canonical_path(self):
  544. if self.proto == 'file':
  545. return self.path
  546. else:
  547. if self.path and self.path.startswith('~'):
  548. path = '/' + self.path
  549. elif self.path and not self.path.startswith('/'):
  550. path = '/~/' + self.path
  551. else:
  552. path = self.path
  553. return 'ssh://{}{}{}{}'.format('{}@'.format(self.user) if self.user else '',
  554. self.host,
  555. ':{}'.format(self.port) if self.port else '',
  556. path)
  557. def location_validator(archive=None):
  558. def validator(text):
  559. try:
  560. loc = Location(text)
  561. except ValueError:
  562. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text)
  563. if archive is True and not loc.archive:
  564. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  565. elif archive is False and loc.archive:
  566. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  567. return loc
  568. return validator
  569. def read_msgpack(filename):
  570. with open(filename, 'rb') as fd:
  571. return msgpack.unpack(fd)
  572. def write_msgpack(filename, d):
  573. with open(filename + '.tmp', 'wb') as fd:
  574. msgpack.pack(d, fd)
  575. fd.flush()
  576. os.fsync(fd.fileno())
  577. os.rename(filename + '.tmp', filename)
  578. def decode_dict(d, keys, encoding='utf-8', errors='surrogateescape'):
  579. for key in keys:
  580. if isinstance(d.get(key), bytes):
  581. d[key] = d[key].decode(encoding, errors)
  582. return d
  583. def remove_surrogates(s, errors='replace'):
  584. """Replace surrogates generated by fsdecode with '?'
  585. """
  586. return s.encode('utf-8', errors).decode('utf-8')
  587. _safe_re = re.compile(r'^((\.\.)?/+)+')
  588. def make_path_safe(path):
  589. """Make path safe by making it relative and local
  590. """
  591. return _safe_re.sub('', path) or '.'
  592. def daemonize():
  593. """Detach process from controlling terminal and run in background
  594. """
  595. pid = os.fork()
  596. if pid:
  597. os._exit(0)
  598. os.setsid()
  599. pid = os.fork()
  600. if pid:
  601. os._exit(0)
  602. os.chdir('/')
  603. os.close(0)
  604. os.close(1)
  605. os.close(2)
  606. fd = os.open('/dev/null', os.O_RDWR)
  607. os.dup2(fd, 0)
  608. os.dup2(fd, 1)
  609. os.dup2(fd, 2)
  610. class StableDict(dict):
  611. """A dict subclass with stable items() ordering"""
  612. def items(self):
  613. return sorted(super().items())
  614. if sys.version < '3.3':
  615. # st_xtime_ns attributes only available in 3.3+
  616. def st_atime_ns(st):
  617. return int(st.st_atime * 1e9)
  618. def st_ctime_ns(st):
  619. return int(st.st_ctime * 1e9)
  620. def st_mtime_ns(st):
  621. return int(st.st_mtime * 1e9)
  622. # unhexlify in < 3.3 incorrectly only accepts bytes input
  623. def unhexlify(data):
  624. if isinstance(data, str):
  625. data = data.encode('ascii')
  626. return binascii.unhexlify(data)
  627. else:
  628. def st_atime_ns(st):
  629. return st.st_atime_ns
  630. def st_ctime_ns(st):
  631. return st.st_ctime_ns
  632. def st_mtime_ns(st):
  633. return st.st_mtime_ns
  634. unhexlify = binascii.unhexlify
  635. def bigint_to_int(mtime):
  636. """Convert bytearray to int
  637. """
  638. if isinstance(mtime, bytes):
  639. return int.from_bytes(mtime, 'little', signed=True)
  640. return mtime
  641. def int_to_bigint(value):
  642. """Convert integers larger than 64 bits to bytearray
  643. Smaller integers are left alone
  644. """
  645. if value.bit_length() > 63:
  646. return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
  647. return value
  648. def is_slow_msgpack():
  649. return msgpack.Packer is msgpack.fallback.Packer
  650. def yes(msg=None, retry_msg=None, false_msg=None, true_msg=None,
  651. default=False, default_notty=None, default_eof=None,
  652. falsish=('No', 'no', 'N', 'n'), truish=('Yes', 'yes', 'Y', 'y'),
  653. env_var_override=None, ifile=None, ofile=None, input=input):
  654. """
  655. Output <msg> (usually a question) and let user input an answer.
  656. Qualifies the answer according to falsish and truish as True or False.
  657. If it didn't qualify and retry_msg is None (no retries wanted),
  658. return the default [which defaults to False]. Otherwise let user retry
  659. answering until answer is qualified.
  660. If env_var_override is given and it is non-empty, counts as truish answer
  661. and won't ask user for an answer.
  662. If we don't have a tty as input and default_notty is not None, return its value.
  663. Otherwise read input from non-tty and proceed as normal.
  664. If EOF is received instead an input, return default_eof [or default, if not given].
  665. :param msg: introducing message to output on ofile, no \n is added [None]
  666. :param retry_msg: retry message to output on ofile, no \n is added [None]
  667. (also enforces retries instead of returning default)
  668. :param false_msg: message to output before returning False [None]
  669. :param true_msg: message to output before returning True [None]
  670. :param default: default return value (empty answer is given) [False]
  671. :param default_notty: if not None, return its value if no tty is connected [None]
  672. :param default_eof: return value if EOF was read as answer [same as default]
  673. :param falsish: sequence of answers qualifying as False
  674. :param truish: sequence of answers qualifying as True
  675. :param env_var_override: environment variable name [None]
  676. :param ifile: input stream [sys.stdin] (only for testing!)
  677. :param ofile: output stream [sys.stderr]
  678. :param input: input function [input from builtins]
  679. :return: boolean answer value, True or False
  680. """
  681. # note: we do not assign sys.stdin/stderr as defaults above, so they are
  682. # really evaluated NOW, not at function definition time.
  683. if ifile is None:
  684. ifile = sys.stdin
  685. if ofile is None:
  686. ofile = sys.stderr
  687. if default not in (True, False):
  688. raise ValueError("invalid default value, must be True or False")
  689. if default_notty not in (None, True, False):
  690. raise ValueError("invalid default_notty value, must be None, True or False")
  691. if default_eof not in (None, True, False):
  692. raise ValueError("invalid default_eof value, must be None, True or False")
  693. if msg:
  694. print(msg, file=ofile, end='')
  695. ofile.flush()
  696. if env_var_override:
  697. value = os.environ.get(env_var_override)
  698. # currently, any non-empty value counts as truish
  699. # TODO: change this so one can give y/n there?
  700. if value:
  701. value = bool(value)
  702. value_str = truish[0] if value else falsish[0]
  703. print("{} (from {})".format(value_str, env_var_override), file=ofile)
  704. return value
  705. if default_notty is not None and not ifile.isatty():
  706. # looks like ifile is not a terminal (but e.g. a pipe)
  707. return default_notty
  708. while True:
  709. try:
  710. answer = input() # XXX how can we use ifile?
  711. except EOFError:
  712. return default_eof if default_eof is not None else default
  713. if answer in truish:
  714. if true_msg:
  715. print(true_msg, file=ofile)
  716. return True
  717. if answer in falsish:
  718. if false_msg:
  719. print(false_msg, file=ofile)
  720. return False
  721. if retry_msg is None:
  722. # no retries wanted, we just return the default
  723. return default
  724. if retry_msg:
  725. print(retry_msg, file=ofile, end='')
  726. ofile.flush()