3 ### Efficiently construct canonical digests of filesystems
5 ### (c) 2012 Mark Wooding
8 ###----- Licensing notice ---------------------------------------------------
10 ### This file is part of the `rsync-backup' program.
12 ### rsync-backup is free software; you can redistribute it and/or modify
13 ### it under the terms of the GNU General Public License as published by
14 ### the Free Software Foundation; either version 2 of the License, or
15 ### (at your option) any later version.
17 ### rsync-backup is distributed in the hope that it will be useful,
18 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ### GNU General Public License for more details.
22 ### You should have received a copy of the GNU General Public License
23 ### along with rsync-backup; if not, write to the Free Software Foundation,
24 ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 from sys import argv, exc_info, exit, stdin, stdout, stderr
41 ###--------------------------------------------------------------------------
46 def excval(): return exc_info()[1]
48 QUIS = OS.path.basename(argv[0])
51 stderr.write('%s: %s\n' % (QUIS, msg))
63 ###--------------------------------------------------------------------------
64 ### File system enumeration.
66 class FileInfo (object):
67 def __init__(me, file, st = None):
74 me.st = OS.lstat(file)
80 def enum_walk(file, func):
84 return OS.listdir(name)
86 syserr("failed to read directory `%s': %s" % (name, excval().strerror))
94 if fi.st and fi.st.st_dev != dev: pass
95 if fi.st and ST.S_ISDIR(fi.st.st_mode): dd.append(fi)
97 ff.sort(key = lambda fi: fi.name)
98 dd.sort(key = lambda fi: fi.name + '/')
102 if d.st.st_dev == dev:
104 dir([OS.path.join(d.name, e) for e in dirents(d.name)], dev)
106 if file.endswith('/'):
107 cwd = OS.open('.', OS.O_RDONLY)
112 dir(dirents('.'), fi.st.st_dev)
119 if fi.st and ST.S_ISDIR(fi.st.st_mode):
120 dir([OS.path.join(fi.name, e) for e in dirents(fi.name)],
123 def enum_find0(f, func):
128 names = (tail + buf).split('\0')
135 moan("ignored trailing junk after last filename")
137 R_RSYNCESC = RX.compile(r'\\ \# ([0-7]{3})', RX.VERBOSE)
138 def enum_rsync(f, func):
140 ## The format is a little fiddly. Each line consists of PERMS SIZE DATE
141 ## TIME NAME, separated by runs of whitespace, but the NAME starts exactly
142 ## one space character after the TIME and may begin with a space.
143 ## Sequences of the form `\#OOO', where OOO are three octal digits, stand
144 ## for a byte with that value. Newlines, and backslashes which would be
145 ## ambiguous, are converted into this form; all other characters are
148 ## We ignore the stat information and retrieve it ourselves, because it's
149 ## incomplete. Hopefully the dcache is still warm.
152 if line.endswith('\n'): line = line[:-1]
154 ## Extract the escaped name.
155 ff = line.split(None, 3)
157 syserr("ignoring invalid line from rsync: `%s'" % line)
161 spc = tail.index(' ')
163 syserr("ignoring invalid line from rsync: `%s'" % line)
165 name = tail[spc + 1:]
167 ## Now translate escape sequences.
168 name = R_RSYNCESC.sub(lambda m: chr(int(m.group(1), 8)), name)
174 syserr("failed to stat `%s': %s" % (name, excval().strerror))
178 ###--------------------------------------------------------------------------
181 class HashCache (object):
187 """CREATE TABLE meta (
188 version INTEGER NOT NULL,
191 """CREATE TABLE hash (
192 ino INTEGER PRIMARY KEY,
193 mtime INTEGER NOT NULL,
194 ctime INTEGER NOT NULL,
195 size INTEGER NOT NULL,
197 seen BOOLEAN NOT NULL DEFAULT TRUE
199 """PRAGMA journal_mode = WAL;"""
202 def __init__(me, file, hash = None):
206 ## We're going this alone, with no cache.
209 die("no hash specified and no database cache to read from")
212 ## Connect to the database.
213 db = DB.connect(file)
214 db.text_factory = str
216 ## See whether we can understand the cache database.
220 c.execute('SELECT version, hash FROM meta')
222 if c.fetchone() is not None:
223 die("cache database corrupt: meta table has mutliple rows")
224 except (DB.Error, TypeError):
227 ## If that didn't work, we'd better clear the thing and start again.
228 ## But only if we know how to initialize it.
231 ## Explain the situation.
232 moan("cache version %s not understood" % v)
235 die("can't initialize cache: no hash function set")
241 die("unknown hash function `%s'" % hash)
244 c.execute('SELECT type, name FROM sqlite_master')
245 for type, name in c.fetchall():
246 c.execute('DROP %s IF EXISTS %s' % (type, name))
248 ## Now we're ready to go.
251 c.execute('INSERT INTO meta VALUES (?, ?)', [me.VERSION, hash])
254 ## Check the hash function if necessary.
257 elif h is not None and h != hash:
258 die("hash mismatch: cache uses %s but %s requested" % (h, hash))
265 def hashfile(me, fi):
267 ## If this isn't a proper file then don't try to hash it.
268 if fi.err or not ST.S_ISREG(fi.st.st_mode):
271 ## See whether there's a valid entry in the cache.
275 'SELECT mtime, size, hash, seen FROM hash WHERE ino = ?;',
280 if mt == fi.st.st_mtime and \
283 c.execute('UPDATE hash SET seen = 1 WHERE ino = ?',
288 ## Hash the file. Beware raciness: update the file information from the
289 ## open descriptor, but set the size from what we actually read.
292 with open(fi.name, 'rb') as f:
295 buf = f.read(me.BUFSZ)
300 fi.st = OS.fstat(f.fileno())
303 except (OSError, IOError):
307 hash = text(B.hexlify(hash))
309 ## Insert a record into the database.
312 INSERT OR REPLACE INTO hash
313 (ino, mtime, ctime, size, hash, seen)
338 die("no cache database")
343 c.execute('DELETE FROM hash WHERE ino = ?', [ino])
348 c.execute('UPDATE hash SET seen = 0 WHERE seen')
354 c.execute('DELETE FROM hash WHERE NOT seen')
357 ###--------------------------------------------------------------------------
360 class GenericFormatter (object):
361 def __init__(me, fi):
363 def _fmt_time(me, t):
365 return T.strftime('%Y-%m-%dT%H:%M:%SZ', tm)
366 def _enc_name(me, n):
367 return ' \\-> '.join(n.encode('string_escape').split(' -> '))
369 return me._enc_name(me.fi.name)
373 return '%06o' % me.fi.st.st_mode
375 return me.fi.st.st_size
377 return me._fmt_time(me.fi.st.st_mtime)
379 return '%5d:%d' % (me.fi.st.st_uid, me.fi.st.st_gid)
381 class ErrorFormatter (GenericFormatter):
383 return 'E%d %s' % (me.fi.err.errno, me.fi.err.strerror)
384 def error(me): return 'error'
385 mode = size = mtime = owner = error
387 class SocketFormatter (GenericFormatter):
389 class PipeFormatter (GenericFormatter):
392 class LinkFormatter (GenericFormatter):
393 TYPE = 'symbolic-link'
395 n = GenericFormatter.name(me)
397 d = OS.readlink(me.fi.name)
398 return '%s -> %s' % (n, me._enc_name(d))
401 return '%s -> <E%d %s>' % (n, err.errno, err.strerror)
403 class DirectoryFormatter (GenericFormatter):
405 def name(me): return GenericFormatter.name(me) + '/'
406 def size(me): return 'dir'
408 class DeviceFormatter (GenericFormatter):
410 return '%s %d:%d' % (me.TYPE,
411 OS.major(me.fi.st.st_rdev),
412 OS.minor(me.fi.st.st_rdev))
413 class BlockDeviceFormatter (DeviceFormatter):
414 TYPE = 'block-device'
415 class CharDeviceFormatter (DeviceFormatter):
416 TYPE = 'character-device'
418 class FileFormatter (GenericFormatter):
419 TYPE = 'regular-file'
421 class Reporter (object):
424 ST.S_IFSOCK: SocketFormatter,
425 ST.S_IFDIR: DirectoryFormatter,
426 ST.S_IFLNK: LinkFormatter,
427 ST.S_IFREG: FileFormatter,
428 ST.S_IFBLK: BlockDeviceFormatter,
429 ST.S_IFCHR: CharDeviceFormatter,
430 ST.S_IFIFO: PipeFormatter,
433 def __init__(me, db):
437 me._hsz = int(H.new(db.hash).digest_size)
440 h = me._db.hashfile(fi)
442 fmt = ErrorFormatter(fi)
445 fmt = me.TYMAP[ST.S_IFMT(fi.st.st_mode)](fi)
446 inoidx = fi.st.st_dev, fi.st.st_ino
448 vino = me._inomap[inoidx]
453 vino = '%08x' % (Z.crc32(bin(fi.name + suffix)) & 0xffffffff)
454 if vino not in me._vinomap: break
455 suffix = '\0%d' % seq
457 me._inomap[inoidx] = vino
458 if OPTS.compat >= 2: me._vinomap[vino] = inoidx
460 else: info = '[%-*s]' % (2*me._hsz - 2, fmt.info())
461 print('%s %8s %6s %-12s %-20s %20s %s' %
462 (info, vino, fmt.mode(), fmt.owner(),
463 fmt.mtime(), fmt.size(), fmt.name()))
465 ###--------------------------------------------------------------------------
466 ### Database clearing from diff files.
468 R_HUNK = RX.compile(r'^@@ -\d+,(\d+) \+\d+,(\d+) @@$')
470 def clear_entry(db, lno, line):
474 if line.startswith('['):
477 moan("failed to parse file entry (type field; line %d)" % lno)
479 ty = line[1:pos].strip()
480 rest = line[pos + 1:]
483 ff = line.split(None, 1)
485 moan("failed to parse file entry (field split; line %d)" % lno)
490 ff = rest.split(None, 5)
492 moan("failed to parse file entry (field split; line %d)" % lno)
494 ino, mode, uidgid, mtime, sz, name = ff
496 if ty != 'symbolic-link':
499 nn = name.split(' -> ', 1)
501 moan("failed to parse file entry (name split; line %d)" % lno)
504 target = target.decode('string_escape')
505 name = name.decode('string_escape')
511 moan("failed to stat `%s': %s" % (name, e.strerror))
512 if e.errno != E.ENOENT: good = False
514 print("Clear cache entry for `%s'" % name)
521 ## Work through the input diff file one line at a time.
526 if line.endswith('\n'): line = line[:-1]
529 ## We're in a gap between hunks. Find a hunk header and extract the line
531 if diffstate == 'gap':
532 m = R_HUNK.match(line)
534 oldlines = int(m.group(1))
535 newlines = int(m.group(2))
539 ## We're in a hunk. Keep track of whether we've reached the end, and
540 ## discard entries from the cache for mismatching lines.
541 elif diffstate == 'hunk':
543 moan("empty line in diff hunk (line %d)" % lno)
547 oldlines -= 1; newlines -= 1
550 if not clear_entry(db, lno, line[1:]): good = False
553 if not clear_entry(db, lno, line[1:]): good = False
555 moan("incomprehensible line in diff hunk (line %d)" % lno)
557 if oldlines < 0 or newlines < 0:
558 moan("inconsistent lengths in diff hunk header (line %d)" % hdrlno)
560 if oldlines == newlines == 0:
563 if diffstate == 'hunk':
564 moan("truncated diff hunk (started at line %d)" % hdrlno)
569 ###--------------------------------------------------------------------------
573 'rsync': lambda f: enum_rsync(stdin, f),
574 'find0': lambda f: enum_find0(stdin, f)
576 op = OP.OptionParser(
577 usage = '%prog [-au] [-c CACHE] [-f FORMAT] [-H HASH] [FILE ...]',
578 version = '%%prog, version %s' % VERSION,
580 Print a digest of a filesystem (or a collection of specified files) to
581 standard output. The idea is that the digest should be mostly /complete/
582 (i.e., any `interesting\' change to the filesystem results in a different
583 digest) and /canonical/ (i.e., identical filesystem contents result in
587 for short, long, props in [
588 ('-a', '--all', { 'action': 'store_true', 'dest': 'all',
589 'help': 'clear cache of all files not seen' }),
590 ('-c', '--cache', { 'dest': 'cache', 'metavar': 'FILE',
591 'help': 'use FILE as a cache for file hashes' }),
592 ('-f', '--files', { 'dest': 'files', 'metavar': 'FORMAT',
593 'type': 'choice', 'choices': list(FMTMAP.keys()),
594 'help': 'read files to report in the given FORMAT' }),
595 ('-u', '--udiff', { 'action': 'store_true', 'dest': 'udiff',
596 'help': 'read diff from stdin, clear cache entries' }),
597 ('-C', '--compat', { 'dest': 'compat', 'metavar': 'VERSION',
598 'type': 'int', 'default': 2,
599 'help': 'produce output with given compatibility VERSION' }),
600 ('-H', '--hash', { 'dest': 'hash', 'metavar': 'HASH',
601 ##'type': 'choice', 'choices': H.algorithms,
602 'help': 'use HASH as the hash function' })]:
603 op.add_option(short, long, **props)
604 OPTS, args = op.parse_args(argv)
605 if not 1 <= OPTS.compat <= 2:
606 die("unknown compatibility version %d" % OPTS.compat)
608 if OPTS.cache is None or OPTS.all or OPTS.files or len(args) > 2:
609 die("incompatible options: `-u' requires `-c CACHE', forbids others")
610 db = HashCache(OPTS.cache, OPTS.hash)
611 if len(args) == 2: OS.chdir(args[1])
613 if not clear_cache(db): good = False
617 if not OPTS.files and len(args) <= 1:
618 die("no filename sources: nothing to do")
619 db = HashCache(OPTS.cache, OPTS.hash)
623 print("## fshash report format version %d" % OPTS.compat)
626 FMTMAP[OPTS.files](rep.file)
628 enum_walk(dir, rep.file)
633 ###----- That's all, folks --------------------------------------------------