-
Notifications
You must be signed in to change notification settings - Fork 84
/
scanner.go
221 lines (202 loc) · 5.56 KB
/
scanner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Package dpkg implements a package indexer for dpkg packages.
package dpkg
import (
"bufio"
"context"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"net/textproto"
"path/filepath"
"runtime/trace"
"strings"
"github.com/quay/zlog"
"github.com/quay/claircore"
"github.com/quay/claircore/indexer"
"github.com/quay/claircore/pkg/tarfs"
)
const (
name = "dpkg"
kind = "package"
version = "5"
)
var (
_ indexer.VersionedScanner = (*Scanner)(nil)
_ indexer.PackageScanner = (*Scanner)(nil)
)
// Scanner implements the scanner.PackageScanner interface.
//
// This looks for directories that look like dpkg databases and examines the
// "status" file it finds there.
//
// The zero value is ready to use.
type Scanner struct{}
// Name implements scanner.VersionedScanner.
func (ps *Scanner) Name() string { return name }
// Version implements scanner.VersionedScanner.
func (ps *Scanner) Version() string { return version }
// Kind implements scanner.VersionedScanner.
func (ps *Scanner) Kind() string { return kind }
// Scan attempts to find a dpkg database within the layer and read all of the
// installed packages it can find in the "status" file.
//
// It's expected to return (nil, nil) if there's no dpkg database in the layer.
//
// It does not respect any dpkg configuration files.
func (ps *Scanner) Scan(ctx context.Context, layer *claircore.Layer) ([]*claircore.Package, error) {
// Preamble
defer trace.StartRegion(ctx, "Scanner.Scan").End()
trace.Log(ctx, "layer", layer.Hash.String())
ctx = zlog.ContextWithValues(ctx,
"component", "dpkg/Scanner.Scan",
"version", ps.Version(),
"layer", layer.Hash.String())
zlog.Debug(ctx).Msg("start")
defer zlog.Debug(ctx).Msg("done")
// Grab a handle to the tarball, make sure we can seek.
// If we can't, we'd need another reader for every database found.
// It's cleaner to just demand that it's a seeker.
rd, err := layer.Reader()
if err != nil {
return nil, fmt.Errorf("opening layer failed: %w", err)
}
defer rd.Close()
sys, err := tarfs.New(rd)
if err != nil {
return nil, fmt.Errorf("opening layer failed: %w", err)
}
// This is a map keyed by directory. A "score" of 2 means this is almost
// certainly a dpkg database.
loc := make(map[string]int)
walk := func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
switch dir, f := filepath.Split(p); {
case f == "status" && !d.IsDir():
loc[dir]++
case f == "info" && d.IsDir():
loc[dir]++
}
return nil
}
if err := fs.WalkDir(sys, ".", walk); err != nil {
return nil, err
}
zlog.Debug(ctx).Msg("scanned for possible databases")
// If we didn't find anything, this loop is completely skipped.
var pkgs []*claircore.Package
for p, x := range loc {
if x != 2 { // If we didn't find both files, skip this directory.
continue
}
ctx = zlog.ContextWithValues(ctx, "database", p)
zlog.Debug(ctx).Msg("examining package database")
// We want the "status" file.
fn := filepath.Join(p, "status")
db, err := sys.Open(fn)
switch {
case errors.Is(err, nil):
case errors.Is(err, fs.ErrNotExist):
zlog.Debug(ctx).
Str("filename", fn).
Msg("false positive")
continue
default:
return nil, fmt.Errorf("reading status file from layer failed: %w", err)
}
// Take all the packages found in the database and attach to the slice
// defined outside the loop.
found := make(map[string]*claircore.Package)
// The database is actually an RFC822-like message with "\n\n"
// separators, so don't be alarmed by the usage of the "net/textproto"
// package here.
tp := textproto.NewReader(bufio.NewReader(db))
Restart:
hdr, err := tp.ReadMIMEHeader()
for ; err == nil && len(hdr) > 0; hdr, err = tp.ReadMIMEHeader() {
var ok, installed bool
for _, s := range strings.Fields(hdr.Get("Status")) {
switch s {
case "installed":
installed = true
case "ok":
ok = true
}
}
if !ok || !installed {
continue
}
name := hdr.Get("Package")
v := hdr.Get("Version")
p := &claircore.Package{
Name: name,
Version: v,
Kind: claircore.BINARY,
Arch: hdr.Get("Architecture"),
PackageDB: fn,
}
if src := hdr.Get("Source"); src != "" {
p.Source = &claircore.Package{
Name: src,
Kind: claircore.SOURCE,
// Right now, this is an assumption that discovered source
// packages relate to their binary versions. We see this in
// Debian.
Version: v,
PackageDB: fn,
}
}
found[name] = p
pkgs = append(pkgs, p)
}
switch {
case errors.Is(err, io.EOF):
default:
zlog.Warn(ctx).Err(err).Msg("unable to read entry")
goto Restart
}
const suffix = ".md5sums"
ms, err := fs.Glob(sys, filepath.Join(p, "info", "*"+suffix))
if err != nil {
// ???
return nil, fmt.Errorf("resetting tar reader failed: %w", err)
}
hash := md5.New()
for _, n := range ms {
k := strings.TrimSuffix(filepath.Base(n), suffix)
if i := strings.IndexRune(k, ':'); i != -1 {
k = k[:i]
}
p, ok := found[k]
if !ok {
zlog.Debug(ctx).
Str("package", k).
Msg("extra metadata found, ignoring")
continue
}
f, err := sys.Open(n)
if err != nil {
return nil, fmt.Errorf("unable to open file %q: %w", n, err)
}
hash.Reset()
_, err = io.Copy(hash, f)
f.Close()
if err != nil {
zlog.Warn(ctx).
Err(err).
Str("package", n).
Msg("unable to read package metadata")
continue
}
p.RepositoryHint = hex.EncodeToString(hash.Sum(nil))
}
zlog.Debug(ctx).
Int("count", len(found)).
Msg("found packages")
}
return pkgs, nil
}