vpac / src / verify_full.v
264 lines · 254 sloc · 8.84 KB · 841315c100c81d9e6b14c4b55a25d4e3d12db762
Raw
1module main
2
3import nspkg
4import crypto.sha256
5import os
6
7#flag -larchive
8#include <archive.h>
9#include <archive_entry.h>
10
11// libalpm reads a package's mtree for us; these are the libarchive accessors
12// pacman's -Qkk reads each entry with
13fn C.archive_entry_pathname(entry &C.Archive_entry) &char
14fn C.archive_entry_filetype(entry &C.Archive_entry) u32
15fn C.archive_entry_mode(entry &C.Archive_entry) u32
16fn C.archive_entry_uid(entry &C.Archive_entry) i64
17fn C.archive_entry_gid(entry &C.Archive_entry) i64
18fn C.archive_entry_mtime(entry &C.Archive_entry) i64
19fn C.archive_entry_size(entry &C.Archive_entry) i64
20fn C.archive_entry_symlink(entry &C.Archive_entry) &char
21fn C.archive_entry_digest(entry &C.Archive_entry, kind int) &u8
22
23const ae_ifmt = u32(0o170000)
24const ae_ifreg = u32(0o100000)
25const ae_ifdir = u32(0o040000)
26const ae_iflnk = u32(0o120000)
27// the mode bits pacman compares: permissions, setuid, setgid and sticky
28const mode_bits = u32(0o7777)
29
30// MtreeEntry is what a package's mtree records of one of its files
31struct MtreeEntry {
32 path string // as in the mtree, './' stripped
33 kind u32 // ae_ifreg, ae_ifdir or ae_iflnk
34 mode u32
35 uid i64
36 gid i64
37 mtime i64
38 size i64
39 symlink string
40 sha256 string // hex, empty when the mtree has none
41}
42
43// mtree_entries reads a package's mtree. an error is a broken one: libalpm's
44// mtree reader hands an entry over at 0, answers 1 at the mtree's end and
45// anything else for entries beyond reading, so the loop tells the end and a
46// read failure apart — pacman's own loop stops at anything that is not 0,
47// which reports a partial mtree as a complete one. the second value is
48// whether the package carries an mtree file at all (packages built before
49// mtrees existed do not; that is not an error)
50fn mtree_entries(pkg &nspkg.Package) !([]MtreeEntry, bool) {
51 archive := pkg.mtree_open()
52 if archive == unsafe { nil } {
53 // libalpm answers nil both for no mtree file and for one libarchive
54 // cannot open; it tells them apart by the file being there, and so
55 // does this: a corrupt mtree is the package's problem, not a package
56 // built before mtrees (pacman's check.c leaves this as a TODO)
57 handle := pkg.get_handle()
58 // the reason is read first: libalpm's package getters clear it
59 reason := handle.error().msg()
60 mtfile := os.join_path(handle.option_get_dbpath(), 'local', '${pkg.get_name()}-${pkg.get_version()}',
61 'mtree')
62 if os.exists(mtfile) {
63 return error('the mtree file cannot be read (${reason}): ${mtfile}')
64 }
65 return []MtreeEntry{}, false
66 }
67 mut out := []MtreeEntry{}
68 mut entry := &C.Archive_entry(unsafe { nil })
69 for {
70 more := pkg.mtree_step(archive, &entry) or {
71 read_err := error('reading the mtree failed: ${err.msg()}')
72 pkg.mtree_close(archive) or {
73 return error('${read_err.msg()} (closing it failed too: ${err.msg()})')
74 }
75 return read_err
76 }
77 if !more { break }
78 mut path := unsafe { cstring_to_vstring(C.archive_entry_pathname(entry)) }
79 if path.starts_with('./') {
80 path = path[2..]
81 }
82 link := C.archive_entry_symlink(entry)
83 out << MtreeEntry{
84 path: path
85 kind: C.archive_entry_filetype(entry)
86 mode: C.archive_entry_mode(entry) & mode_bits
87 uid: C.archive_entry_uid(entry)
88 gid: C.archive_entry_gid(entry)
89 mtime: C.archive_entry_mtime(entry)
90 size: C.archive_entry_size(entry)
91 symlink: if link == unsafe { nil } { '' } else { unsafe { cstring_to_vstring(link) } }
92 sha256: digest_hex(C.archive_entry_digest(entry, C.ARCHIVE_ENTRY_DIGEST_SHA256))
93 }
94 }
95 pkg.mtree_close(archive) or {
96 // the close is the read's last word; the entries fail with it
97 return error('opening the mtree of ${pkg.get_name()} failed to close it: ${err.msg()}')
98 }
99 return out, true
100}
101
102// digest_hex is a 32 byte sha256 digest as hex, empty when it is all zero:
103// libarchive leaves it so when the mtree records none
104fn digest_hex(d &u8) string {
105 if d == unsafe { nil } {
106 return ''
107 }
108 bytes := unsafe { d.vbytes(32) }.clone()
109 return if bytes.all(it == 0) { '' } else { bytes.hex() }
110}
111
112// file_sha256 hashes a file in chunks, so a large one is never read whole.
113// the read names end of input as its own error (os.Eof); a failure to read
114// anything else is the caller's news — a digest of the part that came out
115// would pass itself off as the whole file's
116fn file_sha256(path string) !string {
117 mut f := os.open(path)!
118 defer { f.close() }
119 mut d := sha256.new()
120 mut buf := []u8{len: 65536}
121 for {
122 n := f.read(mut buf) or {
123 // end of input is a chunking loop's end, not a failure
124 if err is os.Eof {
125 break
126 }
127 return err
128 }
129 if n == 0 {
130 break
131 }
132 d.write(buf[..n])!
133 }
134 return d.sum([]).hex()
135}
136
137// check_file_full compares one file on disk with its mtree entry, the way
138// pacman's -Qkk does: the type first, then owner, group and mode, the target
139// of a link, and for anything that is not a directory the mtime, and for a
140// regular file the size and the sha256. a backup file is expected to change
141// in time, size and content, so those only make a note for it
142fn check_file_full(path string, e MtreeEntry, backup bool) []VerifyLine {
143 st := os.lstat(path) or {
144 // a stat denied by permissions is not a missing file, as in the
145 // fast check. the errno comes along on the error, so the reading
146 // does not lean on strerror's wording
147 if stat_denied(err) {
148 return [VerifyLine{false, '${path} (${err.msg()})'}]
149 }
150 return [VerifyLine{true, '${path} (missing)'}]
151 }
152 kind := st.mode & ae_ifmt
153 if kind != e.kind {
154 return [VerifyLine{true, '${path} (file type mismatch)'}]
155 }
156 mut out := []VerifyLine{}
157 if i64(st.uid) != e.uid {
158 out << VerifyLine{true, '${path} (UID mismatch)'}
159 }
160 if i64(st.gid) != e.gid {
161 out << VerifyLine{true, '${path} (GID mismatch)'}
162 }
163 if st.mode & mode_bits != e.mode {
164 out << VerifyLine{true, '${path} (permissions mismatch)'}
165 }
166 if kind == ae_iflnk {
167 // a link that cannot be read is its own finding, as pacman's
168 // check_symlink says it, not a target that differs
169 if target := os.readlink(path) {
170 if target != e.symlink {
171 out << VerifyLine{true, '${path} (symlink path mismatch)'}
172 }
173 } else {
174 out << VerifyLine{true, '${path} (unable to read symlink contents: ${err.msg()})'}
175 }
176 }
177 // a backup file's changes are the user's: they are noted, not counted
178 note := fn [backup, path] (what string) VerifyLine {
179 return if backup {
180 VerifyLine{false, 'backup file ${path} (${what})'}
181 } else {
182 VerifyLine{true, '${path} (${what})'}
183 }
184 }
185 if kind != ae_ifdir && st.mtime != e.mtime {
186 out << note('modification time mismatch')
187 }
188 if kind == ae_ifreg {
189 if i64(st.size) != e.size {
190 out << note('size mismatch')
191 }
192 if e.sha256 == '' {
193 out << VerifyLine{true, '${path} (SHA256 checksum information not available)'}
194 } else if sum := file_sha256(path) {
195 if sum != e.sha256 {
196 out << note('SHA256 checksum mismatch')
197 }
198 } else {
199 // unverified counts as altered, as pacman's "failed to calculate"
200 // does: run as root to read the root-only files
201 out << VerifyLine{true, '${path} (cannot read: ${err.msg()})'}
202 }
203 }
204 return out
205}
206
207// verify_pkg_full is pacman's -Qkk for one package: every entry of its
208// mtree against the disk. the .INSTALL and .CHANGELOG entries are the db's
209// own copies; the other dot entries describe the package, not its files.
210// the report is held and handed back with the number of altered files: the
211// caller prints it after its spinner stops, since an inline println would
212// draw under the running frame
213fn verify_pkg_full(handle &nspkg.Handle, pkg &nspkg.Package) (int, []VerifyLine) {
214 name := pkg.get_name()
215 mut lines := []VerifyLine{}
216 // a broken mtree is that package's verdict; the check goes on
217 entries, has_mtree := mtree_entries(pkg) or {
218 lines << VerifyLine{true, '${name}: ${err.msg()}'}
219 return 1, lines
220 }
221 if !has_mtree {
222 lines << VerifyLine{false, '${name}: no mtree file'}
223 return 0, lines
224 }
225 backups := backups_of(pkg).map(it.get_name())
226 mut altered := 0
227 for e in entries {
228 path := if e.path.starts_with('.') {
229 dbfile := match e.path {
230 '.INSTALL' { 'install' }
231 '.CHANGELOG' { 'changelog' }
232 else { '' }
233 }
234 if dbfile == '' {
235 continue
236 }
237 // the db the mtree was read from: the handle's, not the global
238 os.join_path(handle.option_get_dbpath(), 'local', '${name}-${pkg.get_version()}',
239 dbfile)
240 } else {
241 '${root_path}${e.path}'
242 }
243 if e.kind !in [ae_ifreg, ae_ifdir, ae_iflnk] {
244 lines << VerifyLine{false, '${name}: warning: ${path} (file type not recognized)'}
245 continue
246 }
247 // a file NoExtract kept off the disk is not missing
248 if !os.exists(path) && !os.is_link(path) && handle.option_match_no_extract(e.path) {
249 continue
250 }
251 findings := check_file_full(path, e, e.path in backups)
252 for f in findings {
253 lines << VerifyLine{f.problem, if f.problem {
254 '${name}: ${f.text}'
255 } else {
256 '${name}: note: ${f.text}'
257 }}
258 }
259 if findings.any(it.problem) {
260 altered++
261 }
262 }
263 return altered, lines
264}
265