Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/archive.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5
6 import gzip
7 import os
8 import stat
9 import tarfile
10 from contextlib import contextmanager
11
12 # 2016-01-01T00:00:00+0000
13 DEFAULT_MTIME = 1451606400
14
15
16 # Python 3.9 contains this change:
17 # https://github.com/python/cpython/commit/674935b8caf33e47c78f1b8e197b1b77a04992d2
18 # which changes the output of tar creation compared to earlier versions.
19 # As this code is used to generate tar files that are meant to be deterministic
20 # across versions of python (specifically, it's used as part of computing the hash
21 # of docker images, which needs to be identical between CI (which uses python 3.8),
22 # and developer environments (using arbitrary versions of python, at this point,
23 # most probably more recent than 3.9)).
24 # What we do is subblass TarInfo so that if used on python >= 3.9, it reproduces the
25 # behavior from python < 3.9.
26 # Here's how it goes:
27 # - the behavior in python >= 3.9 is the same as python < 3.9 when the type encoded
28 # in the tarinfo is CHRTYPE or BLKTYPE.
29 # - the value of the type is only compared in the context of choosing which behavior
30 # to take
31 # - we replace the type with the same value (so that using the value has no changes)
32 # but that pretends to be the same as CHRTYPE so that the condition that enables the
33 # old behavior is taken.
34 class HackedType(bytes):
35 def __eq__(self, other):
36 if other == tarfile.CHRTYPE:
37 return True
38 return self == other
39
40
41 class TarInfo(tarfile.TarInfo):
42 @staticmethod
43 def _create_header(info, format, encoding, errors):
44 info["type"] = HackedType(info["type"])
45 # ignore type checking because it looks like pyright complains because we're calling a
46 # non-public method
47 return tarfile.TarInfo._create_header(info, format, encoding, errors) # type: ignore
48
49
50 def create_tar_from_files(fp, files):
51 """Create a tar file deterministically.
52
53 Receives a dict mapping names of files in the archive to local filesystem
54 paths or ``mozpack.files.BaseFile`` instances.
55
56 The files will be archived and written to the passed file handle opened
57 for writing.
58
59 Only regular files can be written.
60
61 FUTURE accept a filename argument (or create APIs to write files)
62 """
63 # The format is explicitly set to tarfile.GNU_FORMAT, because this default format
64 # has been changed in Python 3.8.
65 with tarfile.open(
66 name="", mode="w", fileobj=fp, dereference=True, format=tarfile.GNU_FORMAT
67 ) as tf:
68 for archive_path, f in sorted(files.items()):
69 if isinstance(f, str):
70 s = os.stat(f)
71 mode = s.st_mode
72 size = s.st_size
73 f = open(f, "rb")
74 else:
75 mode = 0o0644
76 size = len(f.read())
77 f.seek(0)
78
79 ti = TarInfo(archive_path)
80 ti.mode = mode
81 ti.type = tarfile.REGTYPE
82
83 if not ti.isreg():
84 raise ValueError(f"not a regular file: {f}")
85
86 # Disallow setuid and setgid bits. This is an arbitrary restriction.
87 # However, since we set uid/gid to root:root, setuid and setgid
88 # would be a glaring security hole if the archive were
89 # uncompressed as root.
90 if ti.mode & (stat.S_ISUID | stat.S_ISGID):
91 raise ValueError(f"cannot add file with setuid or setgid set: {f}")
92
93 # Set uid, gid, username, and group as deterministic values.
94 ti.uid = 0
95 ti.gid = 0
96 ti.uname = ""
97 ti.gname = ""
98
99 # Set mtime to a constant value.
100 ti.mtime = DEFAULT_MTIME
101
102 ti.size = size
103 # tarfile wants to pass a size argument to read(). So just
104 # wrap/buffer in a proper file object interface.
105 tf.addfile(ti, f)
106
107
108 @contextmanager
109 def gzip_compressor(fp, filename=None, compresslevel=9):
110 """Create a deterministic GzipFile writer.
111
112 This is a glorified wrapper around ``GzipFile`` that adds some
113 determinism.
114
115 The passed file handle should be opened for writing in binary mode.
116 """
117 # Offset 3-7 in the gzip header contains an mtime. Pin it to a known
118 # value so output is deterministic.
119 gf = gzip.GzipFile(
120 filename=filename or "",
121 mode="wb",
122 fileobj=fp,
123 compresslevel=compresslevel,
124 mtime=DEFAULT_MTIME,
125 )
126 with gf:
127 yield gf
128
129
130 def create_tar_gz_from_files(fp, files, filename=None, compresslevel=9):
131 """Create a tar.gz file deterministically from files.
132
133 This is a glorified wrapper around ``create_tar_from_files`` that
134 adds gzip compression.
135
136 The passed file handle should be opened for writing in binary mode.
137 When the function returns, all data has been written to the handle.
138 """
139 with gzip_compressor(fp, filename, compresslevel) as gf:
140 create_tar_from_files(gf, files)