importpkg: be more liberal in control file naming
[~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 contains 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 decompress_tar(filelike, extension):
48     if extension in (".lzma", ".xz"):
49         filelike = DecompressedStream(filelike, lzma.LZMADecompressor())
50         extension = ""
51     if extension not in ("", ".gz", ".bz2"):
52         raise ValueError("unknown compression format with extension %r" %
53                          extension)
54     return tarfile.open(fileobj=filelike, mode="r|" + extension[1:])
55
56 def process_package(filelike, hash_functions):
57     af = ArReader(filelike)
58     af.read_magic()
59     state = "start"
60     while True:
61         try:
62             name = af.read_entry()
63         except EOFError:
64             raise ValueError("data.tar not found")
65         if name.startswith("control.tar"):
66             if state != "start":
67                 raise ValueError("unexpected control.tar")
68             state = "control"
69             tf = decompress_tar(af, name[11:])
70             for elem in tf:
71                 if elem.name not in ("./control", "control"):
72                     continue
73                 if state != "control":
74                     raise ValueError("duplicate control file")
75                 state = "control_file"
76                 yield process_control(tf.extractfile(elem).read())
77                 break
78             continue
79         elif name.startswith("data.tar"):
80             if state != "control_file":
81                 raise ValueError("missing control file")
82             state = "data"
83             tf = decompress_tar(af, name[8:])
84             for name, size, hashes in get_tar_hashes(tf, hash_functions):
85                 try:
86                     name = name.decode("utf8")
87                 except UnicodeDecodeError:
88                     print("warning: skipping filename with encoding error")
89                     continue # skip files with non-utf8 encoding for now
90                 yield dict(name=name, size=size, hashes=hashes)
91             yield "commit"
92             break
93
94 def process_package_with_hash(filelike, hash_functions, sha256hash):
95     hstream = HashedStream(filelike, hashlib.sha256())
96     for elem in process_package(hstream, hash_functions):
97         if elem == "commit":
98             while hstream.read(4096):
99                 pass
100             if hstream.hexdigest() != sha256hash:
101                 raise ValueError("hash sum mismatch")
102             yield elem
103             break
104         yield elem
105
106 def main():
107     parser = optparse.OptionParser()
108     parser.add_option("-H", "--hash", action="store",
109                       help="verify that stdin hash given sha256 hash")
110     options, args = parser.parse_args()
111     hash_functions = [sha512_nontrivial, gziphash, pnghash, gifhash]
112     if options.hash:
113         gen = process_package_with_hash(sys.stdin, hash_functions, options.hash)
114     else:
115         gen = process_package(sys.stdin, hash_functions)
116     yaml.safe_dump_all(gen, sys.stdout)
117
118 if __name__ == "__main__":
119     main()