blacklist content rather than hashes
[~helmut/debian-dedup.git] / importpkg.py
1 #!/usr/bin/python
2 """This tool reads a debian package from stdin and emits a yaml stream on
3 stdout.  It does not access a database. Therefore it can be run in parallel and
4 on multiple machines. The generated yaml conatins multiple documents. The first
5 document contains package metadata. Then a document is emitted for each file.
6 And finally a document consisting of the string "commit" is emitted."""
7
8 import hashlib
9 import optparse
10 import sys
11 import tarfile
12 import zlib
13
14 import lzma
15 import yaml
16
17 from dedup.arreader import ArReader
18 from dedup.debpkg import process_control, get_tar_hashes
19 from dedup.hashing import DecompressedHash, SuppressingHash, HashedStream, \
20         HashBlacklistContent
21 from dedup.compression import GzipDecompressor, DecompressedStream
22 from dedup.image import GIFHash, PNGHash
23
24 boring_content = set(("", "\n"))
25
26 def sha512_nontrivial():
27     return HashBlacklistContent(hashlib.sha512(), boring_content)
28
29 def gziphash():
30     hashobj = DecompressedHash(GzipDecompressor(), hashlib.sha512())
31     hashobj = SuppressingHash(hashobj, (ValueError, zlib.error))
32     hashobj.name = "gzip_sha512"
33     return HashBlacklistContent(hashobj, boring_content)
34
35 def pnghash():
36     hashobj = PNGHash(hashlib.sha512())
37     hashobj = SuppressingHash(hashobj, (ValueError,))
38     hashobj.name = "png_sha512"
39     return hashobj
40
41 def gifhash():
42     hashobj = GIFHash(hashlib.sha512())
43     hashobj = SuppressingHash(hashobj, (ValueError,))
44     hashobj.name = "gif_sha512"
45     return hashobj
46
47 def process_package(filelike, hash_functions):
48     af = ArReader(filelike)
49     af.read_magic()
50     state = "start"
51     while True:
52         try:
53             name = af.read_entry()
54         except EOFError:
55             raise ValueError("data.tar not found")
56         if name == "control.tar.gz":
57             if state != "start":
58                 raise ValueError("unexpected control.tar.gz")
59             state = "control"
60             tf = tarfile.open(fileobj=af, mode="r|gz")
61             for elem in tf:
62                 if elem.name != "./control":
63                     continue
64                 if state != "control":
65                     raise ValueError("duplicate control file")
66                 state = "control_file"
67                 yield process_control(tf.extractfile(elem).read())
68                 break
69             continue
70         elif name == "data.tar.gz":
71             tf = tarfile.open(fileobj=af, mode="r|gz")
72         elif name == "data.tar.bz2":
73             tf = tarfile.open(fileobj=af, mode="r|bz2")
74         elif name == "data.tar.xz":
75             zf = DecompressedStream(af, lzma.LZMADecompressor())
76             tf = tarfile.open(fileobj=zf, mode="r|")
77         elif name == "data.tar":
78             tf = tarfile.open(fileobj=af, mode="r|")
79         else:
80             continue
81         if state != "control_file":
82             raise ValueError("missing control file")
83         for name, size, hashes in get_tar_hashes(tf, hash_functions):
84             try:
85                 name = name.decode("utf8")
86             except UnicodeDecodeError:
87                 print("warning: skipping filename with encoding error")
88                 continue # skip files with non-utf8 encoding for now
89             yield dict(name=name, size=size, hashes=hashes)
90         yield "commit"
91         break
92
93 def process_package_with_hash(filelike, hash_functions, sha256hash):
94     hstream = HashedStream(filelike, hashlib.sha256())
95     for elem in process_package(hstream, hash_functions):
96         if elem == "commit":
97             while hstream.read(4096):
98                 pass
99             if hstream.hexdigest() != sha256hash:
100                 raise ValueError("hash sum mismatch")
101             yield elem
102             break
103         yield elem
104
105 def main():
106     parser = optparse.OptionParser()
107     parser.add_option("-H", "--hash", action="store",
108                       help="verify that stdin hash given sha256 hash")
109     options, args = parser.parse_args()
110     hash_functions = [sha512_nontrivial, gziphash, pnghash, gifhash]
111     if options.hash:
112         gen = process_package_with_hash(sys.stdin, hash_functions, options.hash)
113     else:
114         gen = process_package(sys.stdin, hash_functions)
115     yaml.safe_dump_all(gen, sys.stdout)
116
117 if __name__ == "__main__":
118     main()