2
0

helpers.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  1. import argparse
  2. from collections import namedtuple
  3. from functools import wraps
  4. import grp
  5. import os
  6. import stat
  7. import textwrap
  8. import pwd
  9. import re
  10. from shutil import get_terminal_size
  11. import sys
  12. import platform
  13. import time
  14. import unicodedata
  15. import logging
  16. from .logger import create_logger
  17. logger = create_logger()
  18. from datetime import datetime, timezone, timedelta
  19. from fnmatch import translate
  20. from operator import attrgetter
  21. from . import __version__ as borg_version
  22. from . import hashindex
  23. from . import chunker
  24. from . import crypto
  25. from . import shellpattern
  26. import msgpack
  27. import msgpack.fallback
  28. import socket
  29. # return codes returned by borg command
  30. # when borg is killed by signal N, rc = 128 + N
  31. EXIT_SUCCESS = 0 # everything done, no problems
  32. EXIT_WARNING = 1 # reached normal end of operation, but there were issues
  33. EXIT_ERROR = 2 # terminated abruptly, did not reach end of operation
  34. class Error(Exception):
  35. """Error base class"""
  36. # if we raise such an Error and it is only catched by the uppermost
  37. # exception handler (that exits short after with the given exit_code),
  38. # it is always a (fatal and abrupt) EXIT_ERROR, never just a warning.
  39. exit_code = EXIT_ERROR
  40. # show a traceback?
  41. traceback = False
  42. def get_message(self):
  43. return type(self).__doc__.format(*self.args)
  44. class ErrorWithTraceback(Error):
  45. """like Error, but show a traceback also"""
  46. traceback = True
  47. class IntegrityError(ErrorWithTraceback):
  48. """Data integrity error"""
  49. class ExtensionModuleError(Error):
  50. """The Borg binary extension modules do not seem to be properly installed"""
  51. def check_extension_modules():
  52. from . import platform
  53. if hashindex.API_VERSION != 2:
  54. raise ExtensionModuleError
  55. if chunker.API_VERSION != 2:
  56. raise ExtensionModuleError
  57. if crypto.API_VERSION != 2:
  58. raise ExtensionModuleError
  59. if platform.API_VERSION != 2:
  60. raise ExtensionModuleError
  61. class Manifest:
  62. MANIFEST_ID = b'\0' * 32
  63. def __init__(self, key, repository):
  64. self.archives = {}
  65. self.config = {}
  66. self.key = key
  67. self.repository = repository
  68. @classmethod
  69. def load(cls, repository, key=None):
  70. from .key import key_factory
  71. cdata = repository.get(cls.MANIFEST_ID)
  72. if not key:
  73. key = key_factory(repository, cdata)
  74. manifest = cls(key, repository)
  75. data = key.decrypt(None, cdata)
  76. manifest.id = key.id_hash(data)
  77. m = msgpack.unpackb(data)
  78. if not m.get(b'version') == 1:
  79. raise ValueError('Invalid manifest version')
  80. manifest.archives = dict((k.decode('utf-8'), v) for k, v in m[b'archives'].items())
  81. manifest.timestamp = m.get(b'timestamp')
  82. if manifest.timestamp:
  83. manifest.timestamp = manifest.timestamp.decode('ascii')
  84. manifest.config = m[b'config']
  85. return manifest, key
  86. def write(self):
  87. self.timestamp = datetime.utcnow().isoformat()
  88. data = msgpack.packb(StableDict({
  89. 'version': 1,
  90. 'archives': self.archives,
  91. 'timestamp': self.timestamp,
  92. 'config': self.config,
  93. }))
  94. self.id = self.key.id_hash(data)
  95. self.repository.put(self.MANIFEST_ID, self.key.encrypt(data))
  96. def list_archive_infos(self, sort_by=None, reverse=False):
  97. # inexpensive Archive.list_archives replacement if we just need .name, .id, .ts
  98. ArchiveInfo = namedtuple('ArchiveInfo', 'name id ts')
  99. archives = []
  100. for name, values in self.archives.items():
  101. ts = parse_timestamp(values[b'time'].decode('utf-8'))
  102. id = values[b'id']
  103. archives.append(ArchiveInfo(name=name, id=id, ts=ts))
  104. if sort_by is not None:
  105. archives = sorted(archives, key=attrgetter(sort_by), reverse=reverse)
  106. return archives
  107. def prune_within(archives, within):
  108. multiplier = {'H': 1, 'd': 24, 'w': 24 * 7, 'm': 24 * 31, 'y': 24 * 365}
  109. try:
  110. hours = int(within[:-1]) * multiplier[within[-1]]
  111. except (KeyError, ValueError):
  112. # I don't like how this displays the original exception too:
  113. raise argparse.ArgumentTypeError('Unable to parse --within option: "%s"' % within)
  114. if hours <= 0:
  115. raise argparse.ArgumentTypeError('Number specified using --within option must be positive')
  116. target = datetime.now(timezone.utc) - timedelta(seconds=hours * 3600)
  117. return [a for a in archives if a.ts > target]
  118. def prune_split(archives, pattern, n, skip=[]):
  119. last = None
  120. keep = []
  121. if n == 0:
  122. return keep
  123. for a in sorted(archives, key=attrgetter('ts'), reverse=True):
  124. period = to_localtime(a.ts).strftime(pattern)
  125. if period != last:
  126. last = period
  127. if a not in skip:
  128. keep.append(a)
  129. if len(keep) == n:
  130. break
  131. return keep
  132. class Statistics:
  133. def __init__(self):
  134. self.osize = self.csize = self.usize = self.nfiles = 0
  135. self.last_progress = 0 # timestamp when last progress was shown
  136. def update(self, size, csize, unique):
  137. self.osize += size
  138. self.csize += csize
  139. if unique:
  140. self.usize += csize
  141. summary = """\
  142. Original size Compressed size Deduplicated size
  143. {label:15} {stats.osize_fmt:>20s} {stats.csize_fmt:>20s} {stats.usize_fmt:>20s}"""
  144. def __str__(self):
  145. return self.summary.format(stats=self, label='This archive:')
  146. def __repr__(self):
  147. return "<{cls} object at {hash:#x} ({self.osize}, {self.csize}, {self.usize})>".format(cls=type(self).__name__, hash=id(self), self=self)
  148. @property
  149. def osize_fmt(self):
  150. return format_file_size(self.osize)
  151. @property
  152. def usize_fmt(self):
  153. return format_file_size(self.usize)
  154. @property
  155. def csize_fmt(self):
  156. return format_file_size(self.csize)
  157. def show_progress(self, item=None, final=False, stream=None, dt=None):
  158. now = time.time()
  159. if dt is None or now - self.last_progress > dt:
  160. self.last_progress = now
  161. columns, lines = get_terminal_size()
  162. if not final:
  163. msg = '{0.osize_fmt} O {0.csize_fmt} C {0.usize_fmt} D {0.nfiles} N '.format(self)
  164. path = remove_surrogates(item[b'path']) if item else ''
  165. space = columns - len(msg)
  166. if space < len('...') + len(path):
  167. path = '%s...%s' % (path[:(space // 2) - len('...')], path[-space // 2:])
  168. msg += "{0:<{space}}".format(path, space=space)
  169. else:
  170. msg = ' ' * columns
  171. print(msg, file=stream or sys.stderr, end="\r", flush=True)
  172. def get_keys_dir():
  173. """Determine where to repository keys and cache"""
  174. xdg_config = os.environ.get('XDG_CONFIG_HOME', os.path.join(os.path.expanduser('~'), '.config'))
  175. keys_dir = os.environ.get('BORG_KEYS_DIR', os.path.join(xdg_config, 'borg', 'keys'))
  176. if not os.path.exists(keys_dir):
  177. os.makedirs(keys_dir)
  178. os.chmod(keys_dir, stat.S_IRWXU)
  179. return keys_dir
  180. def get_cache_dir():
  181. """Determine where to repository keys and cache"""
  182. xdg_cache = os.environ.get('XDG_CACHE_HOME', os.path.join(os.path.expanduser('~'), '.cache'))
  183. cache_dir = os.environ.get('BORG_CACHE_DIR', os.path.join(xdg_cache, 'borg'))
  184. if not os.path.exists(cache_dir):
  185. os.makedirs(cache_dir)
  186. os.chmod(cache_dir, stat.S_IRWXU)
  187. with open(os.path.join(cache_dir, 'CACHEDIR.TAG'), 'w') as fd:
  188. fd.write(textwrap.dedent("""
  189. Signature: 8a477f597d28d172789f06886806bc55
  190. # This file is a cache directory tag created by Borg.
  191. # For information about cache directory tags, see:
  192. # http://www.brynosaurus.com/cachedir/
  193. """).lstrip())
  194. return cache_dir
  195. def to_localtime(ts):
  196. """Convert datetime object from UTC to local time zone"""
  197. return datetime(*time.localtime((ts - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())[:6])
  198. def parse_timestamp(timestamp):
  199. """Parse a ISO 8601 timestamp string"""
  200. if '.' in timestamp: # microseconds might not be present
  201. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)
  202. else:
  203. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc)
  204. def load_excludes(fh):
  205. """Load and parse exclude patterns from file object. Lines empty or starting with '#' after stripping whitespace on
  206. both line ends are ignored.
  207. """
  208. patterns = (line for line in (i.strip() for i in fh) if not line.startswith('#'))
  209. return [parse_pattern(pattern) for pattern in patterns if pattern]
  210. def update_excludes(args):
  211. """Merge exclude patterns from files with those on command line."""
  212. if hasattr(args, 'exclude_files') and args.exclude_files:
  213. if not hasattr(args, 'excludes') or args.excludes is None:
  214. args.excludes = []
  215. for file in args.exclude_files:
  216. args.excludes += load_excludes(file)
  217. file.close()
  218. class PatternMatcher:
  219. def __init__(self, fallback=None):
  220. self._items = []
  221. # Value to return from match function when none of the patterns match.
  222. self.fallback = fallback
  223. def add(self, patterns, value):
  224. """Add list of patterns to internal list. The given value is returned from the match function when one of the
  225. given patterns matches.
  226. """
  227. self._items.extend((i, value) for i in patterns)
  228. def match(self, path):
  229. for (pattern, value) in self._items:
  230. if pattern.match(path):
  231. return value
  232. return self.fallback
  233. def normalized(func):
  234. """ Decorator for the Pattern match methods, returning a wrapper that
  235. normalizes OSX paths to match the normalized pattern on OSX, and
  236. returning the original method on other platforms"""
  237. @wraps(func)
  238. def normalize_wrapper(self, path):
  239. return func(self, unicodedata.normalize("NFD", path))
  240. if sys.platform in ('darwin',):
  241. # HFS+ converts paths to a canonical form, so users shouldn't be
  242. # required to enter an exact match
  243. return normalize_wrapper
  244. else:
  245. # Windows and Unix filesystems allow different forms, so users
  246. # always have to enter an exact match
  247. return func
  248. class PatternBase:
  249. """Shared logic for inclusion/exclusion patterns.
  250. """
  251. PREFIX = NotImplemented
  252. def __init__(self, pattern):
  253. self.pattern_orig = pattern
  254. self.match_count = 0
  255. if sys.platform in ('darwin',):
  256. pattern = unicodedata.normalize("NFD", pattern)
  257. self._prepare(pattern)
  258. @normalized
  259. def match(self, path):
  260. matches = self._match(path)
  261. if matches:
  262. self.match_count += 1
  263. return matches
  264. def __repr__(self):
  265. return '%s(%s)' % (type(self), self.pattern)
  266. def __str__(self):
  267. return self.pattern_orig
  268. def _prepare(self, pattern):
  269. raise NotImplementedError
  270. def _match(self, path):
  271. raise NotImplementedError
  272. # For PathPrefixPattern, FnmatchPattern and ShellPattern, we require that the pattern either match the whole path
  273. # or an initial segment of the path up to but not including a path separator. To unify the two cases, we add a path
  274. # separator to the end of the path before matching.
  275. class PathPrefixPattern(PatternBase):
  276. """Literal files or directories listed on the command line
  277. for some operations (e.g. extract, but not create).
  278. If a directory is specified, all paths that start with that
  279. path match as well. A trailing slash makes no difference.
  280. """
  281. PREFIX = "pp"
  282. def _prepare(self, pattern):
  283. self.pattern = os.path.normpath(pattern).rstrip(os.path.sep) + os.path.sep
  284. def _match(self, path):
  285. return (path + os.path.sep).startswith(self.pattern)
  286. class FnmatchPattern(PatternBase):
  287. """Shell glob patterns to exclude. A trailing slash means to
  288. exclude the contents of a directory, but not the directory itself.
  289. """
  290. PREFIX = "fm"
  291. def _prepare(self, pattern):
  292. if pattern.endswith(os.path.sep):
  293. pattern = os.path.normpath(pattern).rstrip(os.path.sep) + os.path.sep + '*' + os.path.sep
  294. else:
  295. pattern = os.path.normpath(pattern) + os.path.sep + '*'
  296. self.pattern = pattern
  297. # fnmatch and re.match both cache compiled regular expressions.
  298. # Nevertheless, this is about 10 times faster.
  299. self.regex = re.compile(translate(self.pattern))
  300. def _match(self, path):
  301. return (self.regex.match(path + os.path.sep) is not None)
  302. class ShellPattern(PatternBase):
  303. """Shell glob patterns to exclude. A trailing slash means to
  304. exclude the contents of a directory, but not the directory itself.
  305. """
  306. PREFIX = "sh"
  307. def _prepare(self, pattern):
  308. sep = os.path.sep
  309. if pattern.endswith(sep):
  310. pattern = os.path.normpath(pattern).rstrip(sep) + sep + "**" + sep + "*" + sep
  311. else:
  312. pattern = os.path.normpath(pattern) + sep + "**" + sep + "*"
  313. self.pattern = pattern
  314. self.regex = re.compile(shellpattern.translate(self.pattern))
  315. def _match(self, path):
  316. return (self.regex.match(path + os.path.sep) is not None)
  317. class RegexPattern(PatternBase):
  318. """Regular expression to exclude.
  319. """
  320. PREFIX = "re"
  321. def _prepare(self, pattern):
  322. self.pattern = pattern
  323. self.regex = re.compile(pattern)
  324. def _match(self, path):
  325. # Normalize path separators
  326. if os.path.sep != '/':
  327. path = path.replace(os.path.sep, '/')
  328. return (self.regex.search(path) is not None)
  329. _PATTERN_STYLES = set([
  330. FnmatchPattern,
  331. PathPrefixPattern,
  332. RegexPattern,
  333. ShellPattern,
  334. ])
  335. _PATTERN_STYLE_BY_PREFIX = dict((i.PREFIX, i) for i in _PATTERN_STYLES)
  336. def parse_pattern(pattern, fallback=FnmatchPattern):
  337. """Read pattern from string and return an instance of the appropriate implementation class.
  338. """
  339. if len(pattern) > 2 and pattern[2] == ":" and pattern[:2].isalnum():
  340. (style, pattern) = (pattern[:2], pattern[3:])
  341. cls = _PATTERN_STYLE_BY_PREFIX.get(style, None)
  342. if cls is None:
  343. raise ValueError("Unknown pattern style: {}".format(style))
  344. else:
  345. cls = fallback
  346. return cls(pattern)
  347. def timestamp(s):
  348. """Convert a --timestamp=s argument to a datetime object"""
  349. try:
  350. # is it pointing to a file / directory?
  351. ts = os.stat(s).st_mtime
  352. return datetime.utcfromtimestamp(ts)
  353. except OSError:
  354. # didn't work, try parsing as timestamp. UTC, no TZ, no microsecs support.
  355. for format in ('%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S+00:00',
  356. '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S',
  357. '%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M',
  358. '%Y-%m-%d', '%Y-%j',
  359. ):
  360. try:
  361. return datetime.strptime(s, format)
  362. except ValueError:
  363. continue
  364. raise ValueError
  365. def ChunkerParams(s):
  366. chunk_min, chunk_max, chunk_mask, window_size = s.split(',')
  367. if int(chunk_max) > 23:
  368. # do not go beyond 2**23 (8MB) chunk size now,
  369. # COMPR_BUFFER can only cope with up to this size
  370. raise ValueError('max. chunk size exponent must not be more than 23 (2^23 = 8MiB max. chunk size)')
  371. return int(chunk_min), int(chunk_max), int(chunk_mask), int(window_size)
  372. def CompressionSpec(s):
  373. values = s.split(',')
  374. count = len(values)
  375. if count < 1:
  376. raise ValueError
  377. # --compression algo[,level]
  378. name = values[0]
  379. if name in ('none', 'lz4', ):
  380. return dict(name=name)
  381. if name in ('zlib', 'lzma', ):
  382. if count < 2:
  383. level = 6 # default compression level in py stdlib
  384. elif count == 2:
  385. level = int(values[1])
  386. if not 0 <= level <= 9:
  387. raise ValueError
  388. else:
  389. raise ValueError
  390. return dict(name=name, level=level)
  391. raise ValueError
  392. def dir_is_cachedir(path):
  393. """Determines whether the specified path is a cache directory (and
  394. therefore should potentially be excluded from the backup) according to
  395. the CACHEDIR.TAG protocol
  396. (http://www.brynosaurus.com/cachedir/spec.html).
  397. """
  398. tag_contents = b'Signature: 8a477f597d28d172789f06886806bc55'
  399. tag_path = os.path.join(path, 'CACHEDIR.TAG')
  400. try:
  401. if os.path.exists(tag_path):
  402. with open(tag_path, 'rb') as tag_file:
  403. tag_data = tag_file.read(len(tag_contents))
  404. if tag_data == tag_contents:
  405. return True
  406. except OSError:
  407. pass
  408. return False
  409. def dir_is_tagged(path, exclude_caches, exclude_if_present):
  410. """Determines whether the specified path is excluded by being a cache
  411. directory or containing user-specified tag files. Returns a list of the
  412. paths of the tag files (either CACHEDIR.TAG or the matching
  413. user-specified files).
  414. """
  415. tag_paths = []
  416. if exclude_caches and dir_is_cachedir(path):
  417. tag_paths.append(os.path.join(path, 'CACHEDIR.TAG'))
  418. if exclude_if_present is not None:
  419. for tag in exclude_if_present:
  420. tag_path = os.path.join(path, tag)
  421. if os.path.isfile(tag_path):
  422. tag_paths.append(tag_path)
  423. return tag_paths
  424. def format_line(format, data):
  425. # TODO: Filter out unwanted properties of str.format(), because "format" is user provided.
  426. try:
  427. return format.format(**data)
  428. except (KeyError, ValueError) as e:
  429. # this should catch format errors
  430. print('Error in lineformat: "{}" - reason "{}"'.format(format, str(e)))
  431. except:
  432. # something unexpected, print error and raise exception
  433. print('Error in lineformat: "{}" - reason "{}"'.format(format, str(e)))
  434. raise
  435. return ''
  436. def safe_timestamp(item_timestamp_ns):
  437. try:
  438. return datetime.fromtimestamp(bigint_to_int(item_timestamp_ns) / 1e9)
  439. except OverflowError:
  440. # likely a broken file time and datetime did not want to go beyond year 9999
  441. return datetime(9999, 12, 31, 23, 59, 59)
  442. def format_time(t):
  443. """use ISO-8601 date and time format
  444. """
  445. return t.strftime('%a, %Y-%m-%d %H:%M:%S')
  446. def format_timedelta(td):
  447. """Format timedelta in a human friendly format
  448. """
  449. # Since td.total_seconds() requires python 2.7
  450. ts = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
  451. s = ts % 60
  452. m = int(ts / 60) % 60
  453. h = int(ts / 3600) % 24
  454. txt = '%.2f seconds' % s
  455. if m:
  456. txt = '%d minutes %s' % (m, txt)
  457. if h:
  458. txt = '%d hours %s' % (h, txt)
  459. if td.days:
  460. txt = '%d days %s' % (td.days, txt)
  461. return txt
  462. def format_file_size(v, precision=2):
  463. """Format file size into a human friendly format
  464. """
  465. return sizeof_fmt_decimal(v, suffix='B', sep=' ', precision=precision)
  466. def sizeof_fmt(num, suffix='B', units=None, power=None, sep='', precision=2):
  467. for unit in units[:-1]:
  468. if abs(round(num, precision)) < power:
  469. if isinstance(num, int):
  470. return "{}{}{}{}".format(num, sep, unit, suffix)
  471. else:
  472. return "{:3.{}f}{}{}{}".format(num, precision, sep, unit, suffix)
  473. num /= float(power)
  474. return "{:.{}f}{}{}{}".format(num, precision, sep, units[-1], suffix)
  475. def sizeof_fmt_iec(num, suffix='B', sep='', precision=2):
  476. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, units=['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'], power=1024)
  477. def sizeof_fmt_decimal(num, suffix='B', sep='', precision=2):
  478. return sizeof_fmt(num, suffix=suffix, sep=sep, precision=precision, units=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], power=1000)
  479. def format_archive(archive):
  480. return '%-36s %s' % (archive.name, format_time(to_localtime(archive.ts)))
  481. def memoize(function):
  482. cache = {}
  483. def decorated_function(*args):
  484. try:
  485. return cache[args]
  486. except KeyError:
  487. val = function(*args)
  488. cache[args] = val
  489. return val
  490. return decorated_function
  491. @memoize
  492. def uid2user(uid, default=None):
  493. try:
  494. return pwd.getpwuid(uid).pw_name
  495. except KeyError:
  496. return default
  497. @memoize
  498. def user2uid(user, default=None):
  499. try:
  500. return user and pwd.getpwnam(user).pw_uid
  501. except KeyError:
  502. return default
  503. @memoize
  504. def gid2group(gid, default=None):
  505. try:
  506. return grp.getgrgid(gid).gr_name
  507. except KeyError:
  508. return default
  509. @memoize
  510. def group2gid(group, default=None):
  511. try:
  512. return group and grp.getgrnam(group).gr_gid
  513. except KeyError:
  514. return default
  515. def posix_acl_use_stored_uid_gid(acl):
  516. """Replace the user/group field with the stored uid/gid
  517. """
  518. entries = []
  519. for entry in safe_decode(acl).split('\n'):
  520. if entry:
  521. fields = entry.split(':')
  522. if len(fields) == 4:
  523. entries.append(':'.join([fields[0], fields[3], fields[2]]))
  524. else:
  525. entries.append(entry)
  526. return safe_encode('\n'.join(entries))
  527. def safe_decode(s, coding='utf-8', errors='surrogateescape'):
  528. """decode bytes to str, with round-tripping "invalid" bytes"""
  529. return s.decode(coding, errors)
  530. def safe_encode(s, coding='utf-8', errors='surrogateescape'):
  531. """encode str to bytes, with round-tripping "invalid" bytes"""
  532. return s.encode(coding, errors)
  533. class Location:
  534. """Object representing a repository / archive location
  535. """
  536. proto = user = host = port = path = archive = None
  537. # borg mount's FUSE filesystem creates one level of directories from
  538. # the archive names. Thus, we must not accept "/" in archive names.
  539. ssh_re = re.compile(r'(?P<proto>ssh)://(?:(?P<user>[^@]+)@)?'
  540. r'(?P<host>[^:/#]+)(?::(?P<port>\d+))?'
  541. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  542. file_re = re.compile(r'(?P<proto>file)://'
  543. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  544. scp_re = re.compile(r'((?:(?P<user>[^@]+)@)?(?P<host>[^:/]+):)?'
  545. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  546. # get the repo from BORG_RE env and the optional archive from param.
  547. # if the syntax requires giving REPOSITORY (see "borg mount"),
  548. # use "::" to let it use the env var.
  549. # if REPOSITORY argument is optional, it'll automatically use the env.
  550. env_re = re.compile(r'(?:::(?P<archive>[^/]+)?)?$')
  551. def __init__(self, text=''):
  552. self.orig = text
  553. if not self.parse(self.orig):
  554. raise ValueError
  555. def preformat_text(self, text):
  556. """Format repository and archive path with common tags"""
  557. current_time = datetime.now()
  558. data = {
  559. 'pid': os.getpid(),
  560. 'fqdn': socket.getfqdn(),
  561. 'hostname': socket.gethostname(),
  562. 'now': current_time.now(),
  563. 'utcnow': current_time.utcnow(),
  564. 'user': uid2user(os.getuid(), os.getuid())
  565. }
  566. return format_line(text, data)
  567. def parse(self, text):
  568. text = self.preformat_text(text)
  569. valid = self._parse(text)
  570. if valid:
  571. return True
  572. m = self.env_re.match(text)
  573. if not m:
  574. return False
  575. repo = os.environ.get('BORG_REPO')
  576. if repo is None:
  577. return False
  578. valid = self._parse(repo)
  579. if not valid:
  580. return False
  581. self.archive = m.group('archive')
  582. return True
  583. def _parse(self, text):
  584. m = self.ssh_re.match(text)
  585. if m:
  586. self.proto = m.group('proto')
  587. self.user = m.group('user')
  588. self.host = m.group('host')
  589. self.port = m.group('port') and int(m.group('port')) or None
  590. self.path = os.path.normpath(m.group('path'))
  591. self.archive = m.group('archive')
  592. return True
  593. m = self.file_re.match(text)
  594. if m:
  595. self.proto = m.group('proto')
  596. self.path = os.path.normpath(m.group('path'))
  597. self.archive = m.group('archive')
  598. return True
  599. m = self.scp_re.match(text)
  600. if m:
  601. self.user = m.group('user')
  602. self.host = m.group('host')
  603. self.path = os.path.normpath(m.group('path'))
  604. self.archive = m.group('archive')
  605. self.proto = self.host and 'ssh' or 'file'
  606. return True
  607. return False
  608. def __str__(self):
  609. items = [
  610. 'proto=%r' % self.proto,
  611. 'user=%r' % self.user,
  612. 'host=%r' % self.host,
  613. 'port=%r' % self.port,
  614. 'path=%r' % self.path,
  615. 'archive=%r' % self.archive,
  616. ]
  617. return ', '.join(items)
  618. def to_key_filename(self):
  619. name = re.sub('[^\w]', '_', self.path).strip('_')
  620. if self.proto != 'file':
  621. name = self.host + '__' + name
  622. return os.path.join(get_keys_dir(), name)
  623. def __repr__(self):
  624. return "Location(%s)" % self
  625. def canonical_path(self):
  626. if self.proto == 'file':
  627. return self.path
  628. else:
  629. if self.path and self.path.startswith('~'):
  630. path = '/' + self.path
  631. elif self.path and not self.path.startswith('/'):
  632. path = '/~/' + self.path
  633. else:
  634. path = self.path
  635. return 'ssh://{}{}{}{}'.format('{}@'.format(self.user) if self.user else '',
  636. self.host,
  637. ':{}'.format(self.port) if self.port else '',
  638. path)
  639. def location_validator(archive=None):
  640. def validator(text):
  641. try:
  642. loc = Location(text)
  643. except ValueError:
  644. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text) from None
  645. if archive is True and not loc.archive:
  646. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  647. elif archive is False and loc.archive:
  648. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  649. return loc
  650. return validator
  651. def archivename_validator():
  652. def validator(text):
  653. if '/' in text or '::' in text or not text:
  654. raise argparse.ArgumentTypeError('Invalid repository name: "%s"' % text)
  655. return text
  656. return validator
  657. def decode_dict(d, keys, encoding='utf-8', errors='surrogateescape'):
  658. for key in keys:
  659. if isinstance(d.get(key), bytes):
  660. d[key] = d[key].decode(encoding, errors)
  661. return d
  662. def remove_surrogates(s, errors='replace'):
  663. """Replace surrogates generated by fsdecode with '?'
  664. """
  665. return s.encode('utf-8', errors).decode('utf-8')
  666. _safe_re = re.compile(r'^((\.\.)?/+)+')
  667. def make_path_safe(path):
  668. """Make path safe by making it relative and local
  669. """
  670. return _safe_re.sub('', path) or '.'
  671. def daemonize():
  672. """Detach process from controlling terminal and run in background
  673. """
  674. pid = os.fork()
  675. if pid:
  676. os._exit(0)
  677. os.setsid()
  678. pid = os.fork()
  679. if pid:
  680. os._exit(0)
  681. os.chdir('/')
  682. os.close(0)
  683. os.close(1)
  684. os.close(2)
  685. fd = os.open('/dev/null', os.O_RDWR)
  686. os.dup2(fd, 0)
  687. os.dup2(fd, 1)
  688. os.dup2(fd, 2)
  689. class StableDict(dict):
  690. """A dict subclass with stable items() ordering"""
  691. def items(self):
  692. return sorted(super().items())
  693. def bigint_to_int(mtime):
  694. """Convert bytearray to int
  695. """
  696. if isinstance(mtime, bytes):
  697. return int.from_bytes(mtime, 'little', signed=True)
  698. return mtime
  699. def int_to_bigint(value):
  700. """Convert integers larger than 64 bits to bytearray
  701. Smaller integers are left alone
  702. """
  703. if value.bit_length() > 63:
  704. return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
  705. return value
  706. def is_slow_msgpack():
  707. return msgpack.Packer is msgpack.fallback.Packer
  708. FALSISH = ('No', 'NO', 'no', 'N', 'n', '0', )
  709. TRUISH = ('Yes', 'YES', 'yes', 'Y', 'y', '1', )
  710. DEFAULTISH = ('Default', 'DEFAULT', 'default', 'D', 'd', '', )
  711. def yes(msg=None, false_msg=None, true_msg=None, default_msg=None,
  712. retry_msg=None, invalid_msg=None, env_msg=None,
  713. falsish=FALSISH, truish=TRUISH, defaultish=DEFAULTISH,
  714. default=False, retry=True, env_var_override=None, ofile=None, input=input):
  715. """
  716. Output <msg> (usually a question) and let user input an answer.
  717. Qualifies the answer according to falsish, truish and defaultish as True, False or <default>.
  718. If it didn't qualify and retry_msg is None (no retries wanted),
  719. return the default [which defaults to False]. Otherwise let user retry
  720. answering until answer is qualified.
  721. If env_var_override is given and this var is present in the environment, do not ask
  722. the user, but just use the env var contents as answer as if it was typed in.
  723. Otherwise read input from stdin and proceed as normal.
  724. If EOF is received instead an input or an invalid input without retry possibility,
  725. return default.
  726. :param msg: introducing message to output on ofile, no \n is added [None]
  727. :param retry_msg: retry message to output on ofile, no \n is added [None]
  728. :param false_msg: message to output before returning False [None]
  729. :param true_msg: message to output before returning True [None]
  730. :param default_msg: message to output before returning a <default> [None]
  731. :param invalid_msg: message to output after a invalid answer was given [None]
  732. :param env_msg: message to output when using input from env_var_override [None],
  733. needs to have 2 placeholders for answer and env var name, e.g.: "{} (from {})"
  734. :param falsish: sequence of answers qualifying as False
  735. :param truish: sequence of answers qualifying as True
  736. :param defaultish: sequence of answers qualifying as <default>
  737. :param default: default return value (defaultish answer was given or no-answer condition) [False]
  738. :param retry: if True and input is incorrect, retry. Otherwise return default. [True]
  739. :param env_var_override: environment variable name [None]
  740. :param ofile: output stream [sys.stderr]
  741. :param input: input function [input from builtins]
  742. :return: boolean answer value, True or False
  743. """
  744. # note: we do not assign sys.stderr as default above, so it is
  745. # really evaluated NOW, not at function definition time.
  746. if ofile is None:
  747. ofile = sys.stderr
  748. if default not in (True, False):
  749. raise ValueError("invalid default value, must be True or False")
  750. if msg:
  751. print(msg, file=ofile, end='', flush=True)
  752. while True:
  753. answer = None
  754. if env_var_override:
  755. answer = os.environ.get(env_var_override)
  756. if answer is not None and env_msg:
  757. print(env_msg.format(answer, env_var_override), file=ofile)
  758. if answer is None:
  759. try:
  760. answer = input()
  761. except EOFError:
  762. # avoid defaultish[0], defaultish could be empty
  763. answer = truish[0] if default else falsish[0]
  764. if answer in defaultish:
  765. if default_msg:
  766. print(default_msg, file=ofile)
  767. return default
  768. if answer in truish:
  769. if true_msg:
  770. print(true_msg, file=ofile)
  771. return True
  772. if answer in falsish:
  773. if false_msg:
  774. print(false_msg, file=ofile)
  775. return False
  776. # if we get here, the answer was invalid
  777. if invalid_msg:
  778. print(invalid_msg, file=ofile)
  779. if not retry:
  780. return default
  781. if retry_msg:
  782. print(retry_msg, file=ofile, end='', flush=True)
  783. # in case we used an environment variable and it gave an invalid answer, do not use it again:
  784. env_var_override = None
  785. class ProgressIndicatorPercent:
  786. def __init__(self, total, step=5, start=0, same_line=False, msg="%3.0f%%", file=None):
  787. """
  788. Percentage-based progress indicator
  789. :param total: total amount of items
  790. :param step: step size in percent
  791. :param start: at which percent value to start
  792. :param same_line: if True, emit output always on same line
  793. :param msg: output message, must contain one %f placeholder for the percentage
  794. :param file: output file, default: sys.stderr
  795. """
  796. self.counter = 0 # 0 .. (total-1)
  797. self.total = total
  798. self.trigger_at = start # output next percentage value when reaching (at least) this
  799. self.step = step
  800. if file is None:
  801. file = sys.stderr
  802. self.file = file
  803. self.msg = msg
  804. self.same_line = same_line
  805. def progress(self, current=None):
  806. if current is not None:
  807. self.counter = current
  808. pct = self.counter * 100 / self.total
  809. self.counter += 1
  810. if pct >= self.trigger_at:
  811. self.trigger_at += self.step
  812. return pct
  813. def show(self, current=None):
  814. pct = self.progress(current)
  815. if pct is not None:
  816. return self.output(pct)
  817. def output(self, percent):
  818. print(self.msg % percent, file=self.file, end='\r' if self.same_line else '\n', flush=True)
  819. def finish(self):
  820. if self.same_line:
  821. print(" " * len(self.msg % 100.0), file=self.file, end='\r')
  822. class ProgressIndicatorEndless:
  823. def __init__(self, step=10, file=None):
  824. """
  825. Progress indicator (long row of dots)
  826. :param step: every Nth call, call the func
  827. :param file: output file, default: sys.stderr
  828. """
  829. self.counter = 0 # call counter
  830. self.triggered = 0 # increases 1 per trigger event
  831. self.step = step # trigger every <step> calls
  832. if file is None:
  833. file = sys.stderr
  834. self.file = file
  835. def progress(self):
  836. self.counter += 1
  837. trigger = self.counter % self.step == 0
  838. if trigger:
  839. self.triggered += 1
  840. return trigger
  841. def show(self):
  842. trigger = self.progress()
  843. if trigger:
  844. return self.output(self.triggered)
  845. def output(self, triggered):
  846. print('.', end='', file=self.file, flush=True)
  847. def finish(self):
  848. print(file=self.file)
  849. def sysinfo():
  850. info = []
  851. info.append('Platform: %s' % (' '.join(platform.uname()), ))
  852. if sys.platform.startswith('linux'):
  853. info.append('Linux: %s %s %s' % platform.linux_distribution())
  854. info.append('Borg: %s Python: %s %s' % (borg_version, platform.python_implementation(), platform.python_version()))
  855. info.append('PID: %d CWD: %s' % (os.getpid(), os.getcwd()))
  856. info.append('sys.argv: %r' % sys.argv)
  857. info.append('SSH_ORIGINAL_COMMAND: %r' % os.environ.get('SSH_ORIGINAL_COMMAND'))
  858. info.append('')
  859. return '\n'.join(info)
  860. def log_multi(*msgs, level=logging.INFO):
  861. """
  862. log multiple lines of text, each line by a separate logging call for cosmetic reasons
  863. each positional argument may be a single or multiple lines (separated by \n) of text.
  864. """
  865. lines = []
  866. for msg in msgs:
  867. lines.extend(msg.splitlines())
  868. for line in lines:
  869. logger.log(level, line)