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