helpers.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. from .support import argparse # see support/__init__.py docstring
  2. # DEPRECATED - remove after requiring py 3.4
  3. import binascii
  4. from collections import namedtuple
  5. from functools import wraps
  6. import grp
  7. import os
  8. import pwd
  9. import re
  10. import sys
  11. import time
  12. import unicodedata
  13. from datetime import datetime, timezone, timedelta
  14. from fnmatch import translate
  15. from operator import attrgetter
  16. def have_cython():
  17. """allow for a way to disable Cython includes
  18. this is used during usage docs build, in setup.py. It is to avoid
  19. loading the Cython libraries which are built, but sometimes not in
  20. the search path (namely, during Tox runs).
  21. we simply check an environment variable (``BORG_CYTHON_DISABLE``)
  22. which, when set (to anything) will disable includes of Cython
  23. libraries in key places to enable usage docs to be built.
  24. :returns: True if Cython is available, False otherwise.
  25. """
  26. return not os.environ.get('BORG_CYTHON_DISABLE')
  27. if have_cython():
  28. from . import hashindex
  29. from . import chunker
  30. from . import crypto
  31. import msgpack
  32. class Error(Exception):
  33. """Error base class"""
  34. exit_code = 1
  35. def get_message(self):
  36. return 'Error: ' + type(self).__doc__.format(*self.args)
  37. class ExtensionModuleError(Error):
  38. """The Borg binary extension modules do not seem to be properly installed"""
  39. def check_extension_modules():
  40. from . import platform
  41. if hashindex.API_VERSION != 2:
  42. raise ExtensionModuleError
  43. if chunker.API_VERSION != 2:
  44. raise ExtensionModuleError
  45. if crypto.API_VERSION != 2:
  46. raise ExtensionModuleError
  47. if platform.API_VERSION != 2:
  48. raise ExtensionModuleError
  49. class Manifest:
  50. MANIFEST_ID = b'\0' * 32
  51. def __init__(self, key, repository):
  52. self.archives = {}
  53. self.config = {}
  54. self.key = key
  55. self.repository = repository
  56. @classmethod
  57. def load(cls, repository, key=None):
  58. from .key import key_factory
  59. cdata = repository.get(cls.MANIFEST_ID)
  60. if not key:
  61. key = key_factory(repository, cdata)
  62. manifest = cls(key, repository)
  63. data = key.decrypt(None, cdata)
  64. manifest.id = key.id_hash(data)
  65. m = msgpack.unpackb(data)
  66. if not m.get(b'version') == 1:
  67. raise ValueError('Invalid manifest version')
  68. manifest.archives = dict((k.decode('utf-8'), v) for k, v in m[b'archives'].items())
  69. manifest.timestamp = m.get(b'timestamp')
  70. if manifest.timestamp:
  71. manifest.timestamp = manifest.timestamp.decode('ascii')
  72. manifest.config = m[b'config']
  73. return manifest, key
  74. def write(self):
  75. self.timestamp = datetime.utcnow().isoformat()
  76. data = msgpack.packb(StableDict({
  77. 'version': 1,
  78. 'archives': self.archives,
  79. 'timestamp': self.timestamp,
  80. 'config': self.config,
  81. }))
  82. self.id = self.key.id_hash(data)
  83. self.repository.put(self.MANIFEST_ID, self.key.encrypt(data))
  84. def list_archive_infos(self, sort_by=None, reverse=False):
  85. # inexpensive Archive.list_archives replacement if we just need .name, .id, .ts
  86. ArchiveInfo = namedtuple('ArchiveInfo', 'name id ts')
  87. archives = []
  88. for name, values in self.archives.items():
  89. ts = parse_timestamp(values[b'time'].decode('utf-8'))
  90. id = values[b'id']
  91. archives.append(ArchiveInfo(name=name, id=id, ts=ts))
  92. if sort_by is not None:
  93. archives = sorted(archives, key=attrgetter(sort_by), reverse=reverse)
  94. return archives
  95. def prune_within(archives, within):
  96. multiplier = {'H': 1, 'd': 24, 'w': 24*7, 'm': 24*31, 'y': 24*365}
  97. try:
  98. hours = int(within[:-1]) * multiplier[within[-1]]
  99. except (KeyError, ValueError):
  100. # I don't like how this displays the original exception too:
  101. raise argparse.ArgumentTypeError('Unable to parse --within option: "%s"' % within)
  102. if hours <= 0:
  103. raise argparse.ArgumentTypeError('Number specified using --within option must be positive')
  104. target = datetime.now(timezone.utc) - timedelta(seconds=hours*60*60)
  105. return [a for a in archives if a.ts > target]
  106. def prune_split(archives, pattern, n, skip=[]):
  107. last = None
  108. keep = []
  109. if n == 0:
  110. return keep
  111. for a in sorted(archives, key=attrgetter('ts'), reverse=True):
  112. period = to_localtime(a.ts).strftime(pattern)
  113. if period != last:
  114. last = period
  115. if a not in skip:
  116. keep.append(a)
  117. if len(keep) == n:
  118. break
  119. return keep
  120. class Statistics:
  121. def __init__(self):
  122. self.osize = self.csize = self.usize = self.nfiles = 0
  123. def update(self, size, csize, unique):
  124. self.osize += size
  125. self.csize += csize
  126. if unique:
  127. self.usize += csize
  128. def print_(self, label, cache):
  129. buf = str(self) % label
  130. buf += "\n"
  131. buf += str(cache)
  132. return buf
  133. def __str__(self):
  134. return format(self, """\
  135. Original size Compressed size Deduplicated size
  136. %-15s {0.osize:>20s} {0.csize:>20s} {0.usize:>20s}""")
  137. def __format__(self, format_spec):
  138. fields = ['osize', 'csize', 'usize']
  139. FormattedStats = namedtuple('FormattedStats', fields)
  140. return format_spec.format(FormattedStats(*map(format_file_size, [ getattr(self, x) for x in fields ])))
  141. def show_progress(self, item=None, final=False):
  142. if not final:
  143. path = remove_surrogates(item[b'path']) if item else ''
  144. if len(path) > 43:
  145. path = '%s...%s' % (path[:20], path[-20:])
  146. msg = '%9s O %9s C %9s D %-43s' % (
  147. format_file_size(self.osize), format_file_size(self.csize), format_file_size(self.usize), path)
  148. else:
  149. msg = ' ' * 79
  150. print(msg, file=sys.stderr, end='\r')
  151. sys.stderr.flush()
  152. def get_keys_dir():
  153. """Determine where to repository keys and cache"""
  154. return os.environ.get('BORG_KEYS_DIR',
  155. os.path.join(os.path.expanduser('~'), '.borg', 'keys'))
  156. def get_cache_dir():
  157. """Determine where to repository keys and cache"""
  158. xdg_cache = os.environ.get('XDG_CACHE_HOME', os.path.join(os.path.expanduser('~'), '.cache'))
  159. return os.environ.get('BORG_CACHE_DIR', os.path.join(xdg_cache, 'borg'))
  160. def to_localtime(ts):
  161. """Convert datetime object from UTC to local time zone"""
  162. return datetime(*time.localtime((ts - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())[:6])
  163. def parse_timestamp(timestamp):
  164. """Parse a ISO 8601 timestamp string"""
  165. if '.' in timestamp: # microseconds might not be pressent
  166. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)
  167. else:
  168. return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc)
  169. def update_excludes(args):
  170. """Merge exclude patterns from files with those on command line.
  171. Empty lines and lines starting with '#' are ignored, but whitespace
  172. is not stripped."""
  173. if hasattr(args, 'exclude_files') and args.exclude_files:
  174. if not hasattr(args, 'excludes') or args.excludes is None:
  175. args.excludes = []
  176. for file in args.exclude_files:
  177. patterns = [line.rstrip('\r\n') for line in file if not line.startswith('#')]
  178. args.excludes += [ExcludePattern(pattern) for pattern in patterns if pattern]
  179. file.close()
  180. def adjust_patterns(paths, excludes):
  181. if paths:
  182. return (excludes or []) + [IncludePattern(path) for path in paths] + [ExcludePattern('*')]
  183. else:
  184. return excludes
  185. def exclude_path(path, patterns):
  186. """Used by create and extract sub-commands to determine
  187. whether or not an item should be processed.
  188. """
  189. for pattern in (patterns or []):
  190. if pattern.match(path):
  191. return isinstance(pattern, ExcludePattern)
  192. return False
  193. # For both IncludePattern and ExcludePattern, we require that
  194. # the pattern either match the whole path or an initial segment
  195. # of the path up to but not including a path separator. To
  196. # unify the two cases, we add a path separator to the end of
  197. # the path before matching.
  198. def normalized(func):
  199. """ Decorator for the Pattern match methods, returning a wrapper that
  200. normalizes OSX paths to match the normalized pattern on OSX, and
  201. returning the original method on other platforms"""
  202. @wraps(func)
  203. def normalize_wrapper(self, path):
  204. return func(self, unicodedata.normalize("NFD", path))
  205. if sys.platform in ('darwin',):
  206. # HFS+ converts paths to a canonical form, so users shouldn't be
  207. # required to enter an exact match
  208. return normalize_wrapper
  209. else:
  210. # Windows and Unix filesystems allow different forms, so users
  211. # always have to enter an exact match
  212. return func
  213. class IncludePattern:
  214. """Literal files or directories listed on the command line
  215. for some operations (e.g. extract, but not create).
  216. If a directory is specified, all paths that start with that
  217. path match as well. A trailing slash makes no difference.
  218. """
  219. def __init__(self, pattern):
  220. self.pattern_orig = pattern
  221. self.match_count = 0
  222. if sys.platform in ('darwin',):
  223. pattern = unicodedata.normalize("NFD", pattern)
  224. self.pattern = os.path.normpath(pattern).rstrip(os.path.sep)+os.path.sep
  225. @normalized
  226. def match(self, path):
  227. matches = (path+os.path.sep).startswith(self.pattern)
  228. if matches:
  229. self.match_count += 1
  230. return matches
  231. def __repr__(self):
  232. return '%s(%s)' % (type(self), self.pattern)
  233. def __str__(self):
  234. return self.pattern_orig
  235. class ExcludePattern(IncludePattern):
  236. """Shell glob patterns to exclude. A trailing slash means to
  237. exclude the contents of a directory, but not the directory itself.
  238. """
  239. def __init__(self, pattern):
  240. self.pattern_orig = pattern
  241. self.match_count = 0
  242. if pattern.endswith(os.path.sep):
  243. self.pattern = os.path.normpath(pattern).rstrip(os.path.sep)+os.path.sep+'*'+os.path.sep
  244. else:
  245. self.pattern = os.path.normpath(pattern)+os.path.sep+'*'
  246. if sys.platform in ('darwin',):
  247. self.pattern = unicodedata.normalize("NFD", self.pattern)
  248. # fnmatch and re.match both cache compiled regular expressions.
  249. # Nevertheless, this is about 10 times faster.
  250. self.regex = re.compile(translate(self.pattern))
  251. @normalized
  252. def match(self, path):
  253. matches = self.regex.match(path+os.path.sep) is not None
  254. if matches:
  255. self.match_count += 1
  256. return matches
  257. def __repr__(self):
  258. return '%s(%s)' % (type(self), self.pattern)
  259. def __str__(self):
  260. return self.pattern_orig
  261. def timestamp(s):
  262. """Convert a --timestamp=s argument to a datetime object"""
  263. try:
  264. # is it pointing to a file / directory?
  265. ts = os.stat(s).st_mtime
  266. return datetime.utcfromtimestamp(ts)
  267. except OSError:
  268. # didn't work, try parsing as timestamp. UTC, no TZ, no microsecs support.
  269. for format in ('%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S+00:00',
  270. '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S',
  271. '%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M',
  272. '%Y-%m-%d', '%Y-%j',
  273. ):
  274. try:
  275. return datetime.strptime(s, format)
  276. except ValueError:
  277. continue
  278. raise ValueError
  279. def ChunkerParams(s):
  280. chunk_min, chunk_max, chunk_mask, window_size = s.split(',')
  281. if int(chunk_max) > 23:
  282. # do not go beyond 2**23 (8MB) chunk size now,
  283. # COMPR_BUFFER can only cope with up to this size
  284. raise ValueError('max. chunk size exponent must not be more than 23 (2^23 = 8MiB max. chunk size)')
  285. return int(chunk_min), int(chunk_max), int(chunk_mask), int(window_size)
  286. def CompressionSpec(s):
  287. values = s.split(',')
  288. count = len(values)
  289. if count < 1:
  290. raise ValueError
  291. compression = values[0]
  292. try:
  293. compression = int(compression)
  294. if count > 1:
  295. raise ValueError
  296. # DEPRECATED: it is just --compression N
  297. if 0 <= compression <= 9:
  298. return dict(name='zlib', level=compression)
  299. raise ValueError
  300. except ValueError:
  301. # --compression algo[,...]
  302. name = compression
  303. if name in ('none', 'lz4', ):
  304. return dict(name=name)
  305. if name in ('zlib', 'lzma', ):
  306. if count < 2:
  307. level = 6 # default compression level in py stdlib
  308. elif count == 2:
  309. level = int(values[1])
  310. if not 0 <= level <= 9:
  311. raise ValueError
  312. else:
  313. raise ValueError
  314. return dict(name=name, level=level)
  315. raise ValueError
  316. def is_cachedir(path):
  317. """Determines whether the specified path is a cache directory (and
  318. therefore should potentially be excluded from the backup) according to
  319. the CACHEDIR.TAG protocol
  320. (http://www.brynosaurus.com/cachedir/spec.html).
  321. """
  322. tag_contents = b'Signature: 8a477f597d28d172789f06886806bc55'
  323. tag_path = os.path.join(path, 'CACHEDIR.TAG')
  324. try:
  325. if os.path.exists(tag_path):
  326. with open(tag_path, 'rb') as tag_file:
  327. tag_data = tag_file.read(len(tag_contents))
  328. if tag_data == tag_contents:
  329. return True
  330. except OSError:
  331. pass
  332. return False
  333. def format_time(t):
  334. """Format datetime suitable for fixed length list output
  335. """
  336. if abs((datetime.now() - t).days) < 365:
  337. return t.strftime('%b %d %H:%M')
  338. else:
  339. return t.strftime('%b %d %Y')
  340. def format_timedelta(td):
  341. """Format timedelta in a human friendly format
  342. """
  343. # Since td.total_seconds() requires python 2.7
  344. ts = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
  345. s = ts % 60
  346. m = int(ts / 60) % 60
  347. h = int(ts / 3600) % 24
  348. txt = '%.2f seconds' % s
  349. if m:
  350. txt = '%d minutes %s' % (m, txt)
  351. if h:
  352. txt = '%d hours %s' % (h, txt)
  353. if td.days:
  354. txt = '%d days %s' % (td.days, txt)
  355. return txt
  356. def format_file_mode(mod):
  357. """Format file mode bits for list output
  358. """
  359. def x(v):
  360. return ''.join(v & m and s or '-'
  361. for m, s in ((4, 'r'), (2, 'w'), (1, 'x')))
  362. return '%s%s%s' % (x(mod // 64), x(mod // 8), x(mod))
  363. def format_file_size(v):
  364. """Format file size into a human friendly format
  365. """
  366. if abs(v) > 10**12:
  367. return '%.2f TB' % (v / 10**12)
  368. elif abs(v) > 10**9:
  369. return '%.2f GB' % (v / 10**9)
  370. elif abs(v) > 10**6:
  371. return '%.2f MB' % (v / 10**6)
  372. elif abs(v) > 10**3:
  373. return '%.2f kB' % (v / 10**3)
  374. else:
  375. return '%d B' % v
  376. def format_archive(archive):
  377. return '%-36s %s' % (archive.name, to_localtime(archive.ts).strftime('%c'))
  378. class IntegrityError(Error):
  379. """Data integrity error"""
  380. def memoize(function):
  381. cache = {}
  382. def decorated_function(*args):
  383. try:
  384. return cache[args]
  385. except KeyError:
  386. val = function(*args)
  387. cache[args] = val
  388. return val
  389. return decorated_function
  390. @memoize
  391. def uid2user(uid, default=None):
  392. try:
  393. return pwd.getpwuid(uid).pw_name
  394. except KeyError:
  395. return default
  396. @memoize
  397. def user2uid(user, default=None):
  398. try:
  399. return user and pwd.getpwnam(user).pw_uid
  400. except KeyError:
  401. return default
  402. @memoize
  403. def gid2group(gid, default=None):
  404. try:
  405. return grp.getgrgid(gid).gr_name
  406. except KeyError:
  407. return default
  408. @memoize
  409. def group2gid(group, default=None):
  410. try:
  411. return group and grp.getgrnam(group).gr_gid
  412. except KeyError:
  413. return default
  414. def posix_acl_use_stored_uid_gid(acl):
  415. """Replace the user/group field with the stored uid/gid
  416. """
  417. entries = []
  418. for entry in acl.decode('utf-8', 'surrogateescape').split('\n'):
  419. if entry:
  420. fields = entry.split(':')
  421. if len(fields) == 4:
  422. entries.append(':'.join([fields[0], fields[3], fields[2]]))
  423. else:
  424. entries.append(entry)
  425. return '\n'.join(entries).encode('utf-8', 'surrogateescape')
  426. class Location:
  427. """Object representing a repository / archive location
  428. """
  429. proto = user = host = port = path = archive = None
  430. # borg mount's FUSE filesystem creates one level of directories from
  431. # the archive names. Thus, we must not accept "/" in archive names.
  432. ssh_re = re.compile(r'(?P<proto>ssh)://(?:(?P<user>[^@]+)@)?'
  433. r'(?P<host>[^:/#]+)(?::(?P<port>\d+))?'
  434. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  435. file_re = re.compile(r'(?P<proto>file)://'
  436. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  437. scp_re = re.compile(r'((?:(?P<user>[^@]+)@)?(?P<host>[^:/]+):)?'
  438. r'(?P<path>[^:]+)(?:::(?P<archive>[^/]+))?$')
  439. # get the repo from BORG_RE env and the optional archive from param.
  440. # if the syntax requires giving REPOSITORY (see "borg mount"),
  441. # use "::" to let it use the env var.
  442. # if REPOSITORY argument is optional, it'll automatically use the env.
  443. env_re = re.compile(r'(?:::(?P<archive>[^/]+)?)?$')
  444. def __init__(self, text=''):
  445. self.orig = text
  446. if not self.parse(self.orig):
  447. raise ValueError
  448. def parse(self, text):
  449. valid = self._parse(text)
  450. if valid:
  451. return True
  452. m = self.env_re.match(text)
  453. if not m:
  454. return False
  455. repo = os.environ.get('BORG_REPO')
  456. if repo is None:
  457. return False
  458. valid = self._parse(repo)
  459. if not valid:
  460. return False
  461. self.archive = m.group('archive')
  462. return True
  463. def _parse(self, text):
  464. m = self.ssh_re.match(text)
  465. if m:
  466. self.proto = m.group('proto')
  467. self.user = m.group('user')
  468. self.host = m.group('host')
  469. self.port = m.group('port') and int(m.group('port')) or None
  470. self.path = m.group('path')
  471. self.archive = m.group('archive')
  472. return True
  473. m = self.file_re.match(text)
  474. if m:
  475. self.proto = m.group('proto')
  476. self.path = m.group('path')
  477. self.archive = m.group('archive')
  478. return True
  479. m = self.scp_re.match(text)
  480. if m:
  481. self.user = m.group('user')
  482. self.host = m.group('host')
  483. self.path = m.group('path')
  484. self.archive = m.group('archive')
  485. self.proto = self.host and 'ssh' or 'file'
  486. return True
  487. return False
  488. def __str__(self):
  489. items = []
  490. items.append('proto=%r' % self.proto)
  491. items.append('user=%r' % self.user)
  492. items.append('host=%r' % self.host)
  493. items.append('port=%r' % self.port)
  494. items.append('path=%r' % self.path)
  495. items.append('archive=%r' % self.archive)
  496. return ', '.join(items)
  497. def to_key_filename(self):
  498. name = re.sub('[^\w]', '_', self.path).strip('_')
  499. if self.proto != 'file':
  500. name = self.host + '__' + name
  501. return os.path.join(get_keys_dir(), name)
  502. def __repr__(self):
  503. return "Location(%s)" % self
  504. def canonical_path(self):
  505. if self.proto == 'file':
  506. return self.path
  507. else:
  508. if self.path and self.path.startswith('~'):
  509. path = '/' + self.path
  510. elif self.path and not self.path.startswith('/'):
  511. path = '/~/' + self.path
  512. else:
  513. path = self.path
  514. return 'ssh://{}{}{}{}'.format('{}@'.format(self.user) if self.user else '',
  515. self.host,
  516. ':{}'.format(self.port) if self.port else '',
  517. path)
  518. def location_validator(archive=None):
  519. def validator(text):
  520. try:
  521. loc = Location(text)
  522. except ValueError:
  523. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text)
  524. if archive is True and not loc.archive:
  525. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  526. elif archive is False and loc.archive:
  527. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  528. return loc
  529. return validator
  530. def read_msgpack(filename):
  531. with open(filename, 'rb') as fd:
  532. return msgpack.unpack(fd)
  533. def write_msgpack(filename, d):
  534. with open(filename + '.tmp', 'wb') as fd:
  535. msgpack.pack(d, fd)
  536. fd.flush()
  537. os.fsync(fd.fileno())
  538. os.rename(filename + '.tmp', filename)
  539. def decode_dict(d, keys, encoding='utf-8', errors='surrogateescape'):
  540. for key in keys:
  541. if isinstance(d.get(key), bytes):
  542. d[key] = d[key].decode(encoding, errors)
  543. return d
  544. def remove_surrogates(s, errors='replace'):
  545. """Replace surrogates generated by fsdecode with '?'
  546. """
  547. return s.encode('utf-8', errors).decode('utf-8')
  548. _safe_re = re.compile(r'^((\.\.)?/+)+')
  549. def make_path_safe(path):
  550. """Make path safe by making it relative and local
  551. """
  552. return _safe_re.sub('', path) or '.'
  553. def daemonize():
  554. """Detach process from controlling terminal and run in background
  555. """
  556. pid = os.fork()
  557. if pid:
  558. os._exit(0)
  559. os.setsid()
  560. pid = os.fork()
  561. if pid:
  562. os._exit(0)
  563. os.chdir('/')
  564. os.close(0)
  565. os.close(1)
  566. os.close(2)
  567. fd = os.open('/dev/null', os.O_RDWR)
  568. os.dup2(fd, 0)
  569. os.dup2(fd, 1)
  570. os.dup2(fd, 2)
  571. class StableDict(dict):
  572. """A dict subclass with stable items() ordering"""
  573. def items(self):
  574. return sorted(super().items())
  575. if sys.version < '3.3':
  576. # st_mtime_ns attribute only available in 3.3+
  577. def st_mtime_ns(st):
  578. return int(st.st_mtime * 1e9)
  579. # unhexlify in < 3.3 incorrectly only accepts bytes input
  580. def unhexlify(data):
  581. if isinstance(data, str):
  582. data = data.encode('ascii')
  583. return binascii.unhexlify(data)
  584. else:
  585. def st_mtime_ns(st):
  586. return st.st_mtime_ns
  587. unhexlify = binascii.unhexlify
  588. def bigint_to_int(mtime):
  589. """Convert bytearray to int
  590. """
  591. if isinstance(mtime, bytes):
  592. return int.from_bytes(mtime, 'little', signed=True)
  593. return mtime
  594. def int_to_bigint(value):
  595. """Convert integers larger than 64 bits to bytearray
  596. Smaller integers are left alone
  597. """
  598. if value.bit_length() > 63:
  599. return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
  600. return value