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 ###--------------------------------------------------------------------------
44 def excval(): return exc_info()[1]
46 QUIS = OS.path.basename(argv[0])
49 stderr.write('%s: %s\n' % (QUIS, msg))
61 ###--------------------------------------------------------------------------
62 ### File system enumeration.
64 class FileInfo (object):
65 def __init__(me, file, st = None):
72 me.st = OS.lstat(file)
78 def enum_walk(file, func):
82 return OS.listdir(name)
84 syserr("failed to read directory `%s': %s" % (name, excval().strerror))
92 if fi.st and fi.st.st_dev != dev: pass
93 if fi.st and ST.S_ISDIR(fi.st.st_mode): dd.append(fi)
95 ff.sort(key = lambda fi: fi.name)
96 dd.sort(key = lambda fi: fi.name + '/')
100 if d.st.st_dev == dev:
102 dir([OS.path.join(d.name, e) for e in dirents(d.name)], dev)
104 if file.endswith('/'):
105 cwd = OS.open('.', OS.O_RDONLY)
110 dir(dirents('.'), fi.st.st_dev)
117 if fi.st and ST.S_ISDIR(fi.st.st_mode):
118 dir([OS.path.join(fi.name, e) for e in dirents(fi.name)],
121 def enum_find0(f, func):
126 names = (tail + buf).split('\0')
133 moan("ignored trailing junk after last filename")
135 R_RSYNCESC = RX.compile(r'\\ \# ([0-7]{3})', RX.VERBOSE)
136 def enum_rsync(f, func):
138 ## The format is a little fiddly. Each line consists of PERMS SIZE DATE
139 ## TIME NAME, separated by runs of whitespace, but the NAME starts exactly
140 ## one space character after the TIME and may begin with a space.
141 ## Sequences of the form `\#OOO', where OOO are three octal digits, stand
142 ## for a byte with that value. Newlines, and backslashes which would be
143 ## ambiguous, are converted into this form; all other characters are
146 ## We ignore the stat information and retrieve it ourselves, because it's
147 ## incomplete. Hopefully the dcache is still warm.
150 if line.endswith('\n'): line = line[:-1]
152 ## Extract the escaped name.
153 ff = line.split(None, 3)
155 syserr("ignoring invalid line from rsync: `%s'" % line)
159 spc = tail.index(' ')
161 syserr("ignoring invalid line from rsync: `%s'" % line)
163 name = tail[spc + 1:]
165 ## Now translate escape sequences.
166 name = R_RSYNCESC.sub(lambda m: chr(int(m.group(1), 8)), name)
172 syserr("failed to stat `%s': %s" % (name, excval().strerror))
176 ###--------------------------------------------------------------------------
179 class HashCache (object):
185 """CREATE TABLE meta (
186 version INTEGER NOT NULL,
189 """CREATE TABLE hash (
190 ino INTEGER PRIMARY KEY,
191 mtime INTEGER NOT NULL,
192 ctime INTEGER NOT NULL,
193 size INTEGER NOT NULL,
195 seen BOOLEAN NOT NULL DEFAULT TRUE
197 """PRAGMA journal_mode = WAL;"""
200 def __init__(me, file, hash = None):
204 ## We're going this alone, with no cache.
207 die("no hash specified and no database cache to read from")
210 ## Connect to the database.
211 db = DB.connect(file)
212 db.text_factory = str
214 ## See whether we can understand the cache database.
218 c.execute('SELECT version, hash FROM meta')
220 if c.fetchone() is not None:
221 die("cache database corrupt: meta table has mutliple rows")
222 except (DB.Error, TypeError):
225 ## If that didn't work, we'd better clear the thing and start again.
226 ## But only if we know how to initialize it.
229 ## Explain the situation.
230 moan("cache version %s not understood" % v)
233 die("can't initialize cache: no hash function set")
239 die("unknown hash function `%s'" % hash)
242 c.execute('SELECT type, name FROM sqlite_master')
243 for type, name in c.fetchall():
244 c.execute('DROP %s IF EXISTS %s' % (type, name))
246 ## Now we're ready to go.
249 c.execute('INSERT INTO meta VALUES (?, ?)', [me.VERSION, hash])
252 ## Check the hash function if necessary.
255 elif h is not None and h != hash:
256 die("hash mismatch: cache uses %s but %s requested" % (h, hash))
263 def hashfile(me, fi):
265 ## If this isn't a proper file then don't try to hash it.
266 if fi.err or not ST.S_ISREG(fi.st.st_mode):
269 ## See whether there's a valid entry in the cache.
273 'SELECT mtime, size, hash, seen FROM hash WHERE ino = ?;',
278 if mt == fi.st.st_mtime and \
281 c.execute('UPDATE hash SET seen = 1 WHERE ino = ?',
286 ## Hash the file. Beware raciness: update the file information from the
287 ## open descriptor, but set the size from what we actually read.
290 with open(fi.name, 'rb') as f:
293 buf = f.read(me.BUFSZ)
298 fi.st = OS.fstat(f.fileno())
301 except (OSError, IOError):
305 hash = B.hexlify(hash)
307 ## Insert a record into the database.
310 INSERT OR REPLACE INTO hash
311 (ino, mtime, ctime, size, hash, seen)
336 die("no cache database")
341 c.execute('DELETE FROM hash WHERE ino = ?', [ino])
346 c.execute('UPDATE hash SET seen = 0 WHERE seen')
352 c.execute('DELETE FROM hash WHERE NOT seen')
355 ###--------------------------------------------------------------------------
358 class GenericFormatter (object):
359 def __init__(me, fi):
361 def _fmt_time(me, t):
363 return T.strftime('%Y-%m-%dT%H:%M:%SZ', tm)
364 def _enc_name(me, n):
365 return ' \\-> '.join(n.encode('string_escape').split(' -> '))
367 return me._enc_name(me.fi.name)
371 return '%06o' % me.fi.st.st_mode
373 return me.fi.st.st_size
375 return me._fmt_time(me.fi.st.st_mtime)
377 return '%5d:%d' % (me.fi.st.st_uid, me.fi.st.st_gid)
379 class ErrorFormatter (GenericFormatter):
381 return 'E%d %s' % (me.fi.err.errno, me.fi.err.strerror)
382 def error(me): return 'error'
383 mode = size = mtime = owner = error
385 class SocketFormatter (GenericFormatter):
387 class PipeFormatter (GenericFormatter):
390 class LinkFormatter (GenericFormatter):
391 TYPE = 'symbolic-link'
393 n = GenericFormatter.name(me)
395 d = OS.readlink(me.fi.name)
396 return '%s -> %s' % (n, me._enc_name(d))
399 return '%s -> <E%d %s>' % (n, err.errno, err.strerror)
401 class DirectoryFormatter (GenericFormatter):
403 def name(me): return GenericFormatter.name(me) + '/'
404 def size(me): return 'dir'
406 class DeviceFormatter (GenericFormatter):
408 return '%s %d:%d' % (me.TYPE,
409 OS.major(me.fi.st.st_rdev),
410 OS.minor(me.fi.st.st_rdev))
411 class BlockDeviceFormatter (DeviceFormatter):
412 TYPE = 'block-device'
413 class CharDeviceFormatter (DeviceFormatter):
414 TYPE = 'character-device'
416 class FileFormatter (GenericFormatter):
417 TYPE = 'regular-file'
419 class Reporter (object):
422 ST.S_IFSOCK: SocketFormatter,
423 ST.S_IFDIR: DirectoryFormatter,
424 ST.S_IFLNK: LinkFormatter,
425 ST.S_IFREG: FileFormatter,
426 ST.S_IFBLK: BlockDeviceFormatter,
427 ST.S_IFCHR: CharDeviceFormatter,
428 ST.S_IFIFO: PipeFormatter,
431 def __init__(me, db):
435 me._hsz = int(H.new(db.hash).digest_size)
438 h = me._db.hashfile(fi)
440 fmt = ErrorFormatter(fi)
443 fmt = me.TYMAP[ST.S_IFMT(fi.st.st_mode)](fi)
444 inoidx = fi.st.st_dev, fi.st.st_ino
446 vino = me._inomap[inoidx]
451 vino = '%08x' % (Z.crc32(fi.name + suffix) & 0xffffffff)
452 if vino not in me._vinomap: break
453 suffix = '\0%d' % seq
455 me._inomap[inoidx] = vino
456 if OPTS.compat >= 2: me._vinomap[vino] = inoidx
458 else: info = '[%-*s]' % (2*me._hsz - 2, fmt.info())
459 print('%s %8s %6s %-12s %-20s %20s %s' %
460 (info, vino, fmt.mode(), fmt.owner(),
461 fmt.mtime(), fmt.size(), fmt.name()))
463 ###--------------------------------------------------------------------------
464 ### Database clearing from diff files.
466 R_HUNK = RX.compile(r'^@@ -\d+,(\d+) \+\d+,(\d+) @@$')
468 def clear_entry(db, lno, line):
472 if line.startswith('['):
475 moan("failed to parse file entry (type field; line %d)" % lno)
477 ty = line[1:pos].strip()
478 rest = line[pos + 1:]
481 ff = line.split(None, 1)
483 moan("failed to parse file entry (field split; line %d)" % lno)
488 ff = rest.split(None, 5)
490 moan("failed to parse file entry (field split; line %d)" % lno)
492 ino, mode, uidgid, mtime, sz, name = ff
494 if ty != 'symbolic-link':
497 nn = name.split(' -> ', 1)
499 moan("failed to parse file entry (name split; line %d)" % lno)
502 target = target.decode('string_escape')
503 name = name.decode('string_escape')
509 moan("failed to stat `%s': %s" % (name, e.strerror))
510 if e.errno != E.ENOENT: good = False
512 print("Clear cache entry for `%s'" % name)
519 ## Work through the input diff file one line at a time.
524 if line.endswith('\n'): line = line[:-1]
527 ## We're in a gap between hunks. Find a hunk header and extract the line
529 if diffstate == 'gap':
530 m = R_HUNK.match(line)
532 oldlines = int(m.group(1))
533 newlines = int(m.group(2))
537 ## We're in a hunk. Keep track of whether we've reached the end, and
538 ## discard entries from the cache for mismatching lines.
539 elif diffstate == 'hunk':
541 moan("empty line in diff hunk (line %d)" % lno)
545 oldlines -= 1; newlines -= 1
548 if not clear_entry(db, lno, line[1:]): good = False
551 if not clear_entry(db, lno, line[1:]): good = False
553 moan("incomprehensible line in diff hunk (line %d)" % lno)
555 if oldlines < 0 or newlines < 0:
556 moan("inconsistent lengths in diff hunk header (line %d)" % hdrlno)
558 if oldlines == newlines == 0:
561 if diffstate == 'hunk':
562 moan("truncated diff hunk (started at line %d)" % hdrlno)
567 ###--------------------------------------------------------------------------
571 'rsync': lambda f: enum_rsync(stdin, f),
572 'find0': lambda f: enum_find0(stdin, f)
574 op = OP.OptionParser(
575 usage = '%prog [-au] [-c CACHE] [-f FORMAT] [-H HASH] [FILE ...]',
576 version = '%%prog, version %s' % VERSION,
578 Print a digest of a filesystem (or a collection of specified files) to
579 standard output. The idea is that the digest should be mostly /complete/
580 (i.e., any `interesting\' change to the filesystem results in a different
581 digest) and /canonical/ (i.e., identical filesystem contents result in
585 for short, long, props in [
586 ('-a', '--all', { 'action': 'store_true', 'dest': 'all',
587 'help': 'clear cache of all files not seen' }),
588 ('-c', '--cache', { 'dest': 'cache', 'metavar': 'FILE',
589 'help': 'use FILE as a cache for file hashes' }),
590 ('-f', '--files', { 'dest': 'files', 'metavar': 'FORMAT',
591 'type': 'choice', 'choices': FMTMAP.keys(),
592 'help': 'read files to report in the given FORMAT' }),
593 ('-u', '--udiff', { 'action': 'store_true', 'dest': 'udiff',
594 'help': 'read diff from stdin, clear cache entries' }),
595 ('-C', '--compat', { 'dest': 'compat', 'metavar': 'VERSION',
596 'type': 'int', 'default': 2,
597 'help': 'produce output with given compatibility VERSION' }),
598 ('-H', '--hash', { 'dest': 'hash', 'metavar': 'HASH',
599 ##'type': 'choice', 'choices': H.algorithms,
600 'help': 'use HASH as the hash function' })]:
601 op.add_option(short, long, **props)
602 OPTS, args = op.parse_args(argv)
603 if not 1 <= OPTS.compat <= 2:
604 die("unknown compatibility version %d" % OPTS.compat)
606 if OPTS.cache is None or OPTS.all or OPTS.files or len(args) > 2:
607 die("incompatible options: `-u' requires `-c CACHE', forbids others")
608 db = HashCache(OPTS.cache, OPTS.hash)
609 if len(args) == 2: OS.chdir(args[1])
611 if not clear_cache(db): good = False
615 if not OPTS.files and len(args) <= 1:
616 die("no filename sources: nothing to do")
617 db = HashCache(OPTS.cache, OPTS.hash)
621 print("## fshash report format version %d" % OPTS.compat)
624 FMTMAP[OPTS.files](rep.file)
626 enum_walk(dir, rep.file)
631 ###----- That's all, folks --------------------------------------------------