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, exit, stdin, stdout, stderr
39 ###--------------------------------------------------------------------------
42 QUIS = OS.path.basename(argv[0])
45 stderr.write('%s: %s\n' % (QUIS, msg))
57 ###--------------------------------------------------------------------------
58 ### File system enumeration.
60 class FileInfo (object):
61 def __init__(me, file, st = None):
68 me.st = OS.lstat(file)
74 def enum_walk(file, func):
78 return OS.listdir(name)
80 syserr("failed to read directory `%s': %s" % (name, err.strerror))
88 if fi.st and fi.st.st_dev != dev: pass
89 if fi.st and ST.S_ISDIR(fi.st.st_mode): dd.append(fi)
91 ff.sort(key = lambda fi: fi.name)
92 dd.sort(key = lambda fi: fi.name + '/')
96 if d.st.st_dev == dev:
98 dir([OS.path.join(d.name, e) for e in dirents(d.name)], dev)
100 if file.endswith('/'):
104 dir(dirents('.'), fi.st.st_dev)
108 if fi.st and ST.S_ISDIR(fi.st.st_mode):
109 dir([OS.path.join(fi.name, e) for e in dirents(fi.name)],
112 def enum_find0(f, func):
117 names = (tail + buf).split('\0')
124 moan("ignored trailing junk after last filename")
126 RX_RSYNCESC = RX.compile(r'\\ \# ([0-7]{3})', RX.VERBOSE)
127 def enum_rsync(f, func):
129 ## The format is a little fiddly. Each line consists of PERMS SIZE DATE
130 ## TIME NAME, separated by runs of whitespace, but the NAME starts exactly
131 ## one space character after the TIME and may begin with a space.
132 ## Sequences of the form `\#OOO' where OOO are three octal digits, stand
133 ## for a byte with that value. Newlines and backslashes which would be
134 ## ambiguous are converted into this form; all other characters are
137 ## We ignore the stat information and retrieve it ourselves, because it's
138 ## incomplete. Hopefully the dcache is still warm.
141 if line.endswith('\n'): line = line[:-1]
143 ## Extract the escaped name.
144 ff = line.split(None, 3)
146 syserr("ignoring invalid line from rsync: `%s'" % line)
150 spc = tail.index(' ')
152 syserr("ignoring invalid line from rsync: `%s'" % line)
154 name = tail[spc + 1:]
156 ## Now translate escape sequences.
157 name = RX_RSYNCESC.sub(lambda m: chr(int(m.group(1), 8)), name)
163 syserr("failed to stat `%s': %s" % (name, err.strerror))
167 ###--------------------------------------------------------------------------
170 class HashCache (object):
176 """CREATE TABLE meta (
177 version INTEGER NOT NULL,
180 """CREATE TABLE hash (
181 ino INTEGER PRIMARY KEY,
182 mtime INTEGER NOT NULL,
183 ctime INTEGER NOT NULL,
184 size INTEGER NOT NULL,
186 seen BOOLEAN NOT NULL DEFAULT TRUE
188 """PRAGMA journal_mode = WAL;"""
191 def __init__(me, file, hash = None):
195 ## We're going this alone, with no cache.
198 die("no hash specified and no database cache to read from")
201 ## Connect to the database.
202 db = DB.connect(file)
203 db.text_factory = str
205 ## See whether we can understand the cache database.
209 c.execute('SELECT version, hash FROM meta')
211 if c.fetchone() is not None:
212 die("cache database corrupt: meta table has mutliple rows")
213 except (DB.Error, TypeError):
216 ## If that didn't work, we'd better clear the thing and start again.
217 ## But only if we know how to initialize it.
220 ## Explain the situation.
221 moan("cache version %s not understood" % v)
224 die("can't initialize cache: no hash function set")
230 die("unknown hash function `%s'" % hash)
233 c.execute('SELECT type, name FROM sqlite_master')
234 for type, name in c.fetchall():
235 c.execute('DROP %s IF EXISTS %s' % (type, name))
237 ## Now we're ready to go.
240 c.execute('INSERT INTO meta VALUES (?, ?)', [me.VERSION, hash])
243 ## Check the hash function if necessary.
246 elif h is not None and h != hash:
247 die("hash mismatch: cache uses %s but %s requested" % (h, hash))
254 def hashfile(me, fi):
256 ## If this isn't a proper file then don't try to hash it.
257 if fi.err or not ST.S_ISREG(fi.st.st_mode):
260 ## See whether there's a valid entry in the cache.
264 'SELECT mtime, size, hash, seen FROM hash WHERE ino = ?;',
269 if mt == fi.st.st_mtime and \
272 c.execute('UPDATE hash SET seen = 1 WHERE ino = ?',
277 ## Hash the file. Beware raciness: update the file information from the
278 ## open descriptor, but set the size from what we actually read.
281 with open(fi.name, 'rb') as f:
284 buf = f.read(me.BUFSZ)
289 fi.st = OS.fstat(f.fileno())
292 except (OSError, IOError), err:
296 hash = hash.encode('hex')
298 ## Insert a record into the database.
301 INSERT OR REPLACE INTO hash
302 (ino, mtime, ctime, size, hash, seen)
327 die("no cache database")
332 c.execute('UPDATE hash SET seen = 0 WHERE seen')
338 c.execute('DELETE FROM hash WHERE NOT seen')
341 ###--------------------------------------------------------------------------
344 class GenericFormatter (object):
345 def __init__(me, fi):
347 def _fmt_time(me, t):
349 return T.strftime('%Y-%m-%dT%H:%M:%SZ', tm)
350 def _enc_name(me, n):
351 return n.encode('string_escape')
353 return me._enc_name(me.fi.name)
357 return '%06o' % me.fi.st.st_mode
359 return me.fi.st.st_size
361 return me._fmt_time(me.fi.st.st_mtime)
363 return '%5d:%d' % (me.fi.st.st_uid, me.fi.st.st_gid)
365 class ErrorFormatter (GenericFormatter):
367 return 'E%d %s' % (me.fi.err.errno, me.fi.err.strerror)
368 def error(me): return 'error'
369 mode = size = mtime = owner = error
371 class SocketFormatter (GenericFormatter):
373 class PipeFormatter (GenericFormatter):
376 class LinkFormatter (GenericFormatter):
377 TYPE = 'symbolic-link'
379 n = GenericFormatter.name(me)
381 d = OS.readlink(me.fi.name)
382 return '%s -> %s' % (n, me._enc_name(d))
384 return '%s -> <E%d %s>' % (n, err.errno, err.strerror)
386 class DirectoryFormatter (GenericFormatter):
388 def name(me): return GenericFormatter.name(me) + '/'
389 def size(me): return 'dir'
391 class DeviceFormatter (GenericFormatter):
393 return '%s %d:%d' % (me.TYPE,
394 OS.major(me.fi.st.st_rdev),
395 OS.minor(me.fi.st.st_rdev))
396 class BlockDeviceFormatter (DeviceFormatter):
397 TYPE = 'block-device'
398 class CharDeviceFormatter (DeviceFormatter):
399 TYPE = 'character-device'
401 class FileFormatter (GenericFormatter):
402 TYPE = 'regular-file'
404 class Reporter (object):
407 ST.S_IFSOCK: SocketFormatter,
408 ST.S_IFDIR: DirectoryFormatter,
409 ST.S_IFLNK: LinkFormatter,
410 ST.S_IFREG: FileFormatter,
411 ST.S_IFBLK: BlockDeviceFormatter,
412 ST.S_IFCHR: CharDeviceFormatter,
413 ST.S_IFIFO: PipeFormatter,
416 def __init__(me, db):
420 me._hsz = int(H.new(db.hash).digest_size)
423 h = me._db.hashfile(fi)
425 fmt = ErrorFormatter(fi)
428 fmt = me.TYMAP[ST.S_IFMT(fi.st.st_mode)](fi)
429 inoidx = fi.st.st_dev, fi.st.st_ino
431 vino = me._inomap[inoidx]
436 vino = '%08x' % (Z.crc32(fi.name + suffix) & 0xffffffff)
437 if vino not in me._vinomap: break
438 suffix = '\0%d' % seq
440 me._inomap[inoidx] = vino
442 else: info = '[%-*s]' % (2*me._hsz - 2, fmt.info())
443 print '%s %8s %6s %-12s %-20s %20s %s' % (
444 info, vino, fmt.mode(), fmt.owner(),
445 fmt.mtime(), fmt.size(), fmt.name())
447 ###--------------------------------------------------------------------------
451 'rsync': lambda f: enum_rsync(stdin, f),
452 'find0': lambda f: enum_find0(stdin, f)
454 op = OP.OptionParser(
455 usage = '%prog [-a] [-c CACHE] [-f FORMAT] [-H HASH] [FILE ...]',
456 version = '%%prog, version %s' % VERSION,
458 Print a digest of a filesystem (or a collection of specified files) to
459 standard output. The idea is that the digest should be mostly /complete/
460 (i.e., any `interesting\' change to the filesystem results in a different
461 digest) and /canonical/ (i.e., identical filesystem contents result in
465 for short, long, props in [
466 ('-a', '--all', { 'action': 'store_true', 'dest': 'all',
467 'help': 'clear cache of all files not seen' }),
468 ('-c', '--cache', { 'dest': 'cache', 'metavar': 'FILE',
469 'help': 'use FILE as a cache for file hashes' }),
470 ('-f', '--files', { 'dest': 'files', 'metavar': 'FORMAT',
471 'type': 'choice', 'choices': FMTMAP.keys(),
472 'help': 'read files to report in the given FORMAT' }),
473 ('-H', '--hash', { 'dest': 'hash', 'metavar': 'HASH',
474 ##'type': 'choice', 'choices': H.algorithms,
475 'help': 'use HASH as the hash function' })]:
476 op.add_option(short, long, **props)
477 opts, args = op.parse_args(argv)
479 if not opts.files and len(args) <= 1:
480 die("no filename sources: nothing to do")
481 db = HashCache(opts.cache, opts.hash)
486 FMTMAP[opts.files](rep.file)
488 enum_walk(dir, rep.file)
493 ###----- That's all, folks --------------------------------------------------