clair/ext/featurefmt/apk/apk.go
Sida Chen 2cc61f9fc0 ext/featurefmt/apk: Extract origin package information from database
"o" field is used to extract the Package Origin from the APK database.
2018-10-11 18:02:58 -04:00

101 lines
2.6 KiB
Go

// Copyright 2017 clair authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package apk implements a featurefmt.Lister for APK packages.
package apk
import (
"bufio"
"bytes"
"github.com/deckarep/golang-set"
log "github.com/sirupsen/logrus"
"github.com/coreos/clair/database"
"github.com/coreos/clair/ext/featurefmt"
"github.com/coreos/clair/ext/versionfmt"
"github.com/coreos/clair/ext/versionfmt/dpkg"
"github.com/coreos/clair/pkg/tarutil"
)
func init() {
featurefmt.RegisterLister("apk", "1.0", &lister{})
}
type lister struct{}
func valid(pkg *featurefmt.PackageInfo) bool {
return pkg.PackageName != "" && pkg.PackageVersion != ""
}
func addSourceVersion(pkg *featurefmt.PackageInfo) {
if pkg.SourceName != "" {
pkg.SourceVersion = pkg.PackageVersion
}
}
func (l lister) ListFeatures(files tarutil.FilesMap) ([]database.Feature, error) {
file, exists := files["lib/apk/db/installed"]
if !exists {
return []database.Feature{}, nil
}
// Iterate over each line in the "installed" file attempting to parse each
// package into a feature that will be stored in a set to guarantee
// uniqueness.
packages := mapset.NewSet()
pkg := featurefmt.PackageInfo{}
scanner := bufio.NewScanner(bytes.NewBuffer(file))
for scanner.Scan() {
line := scanner.Text()
if len(line) < 2 {
if valid(&pkg) {
addSourceVersion(&pkg)
packages.Add(pkg)
pkg.Reset()
}
continue
}
// Parse the package name or version.
switch line[:2] {
case "P:":
pkg.PackageName = line[2:]
case "V:":
version := string(line[2:])
err := versionfmt.Valid(dpkg.ParserName, version)
if err != nil {
log.WithError(err).WithField("version", version).Warning("could not parse package version. skipping")
continue
} else {
pkg.PackageVersion = version
}
case "o:":
pkg.SourceName = line[2:]
}
}
// in case of no terminal line
if valid(&pkg) {
addSourceVersion(&pkg)
packages.Add(pkg)
}
return featurefmt.PackageSetToFeatures(dpkg.ParserName, packages), nil
}
func (l lister) RequiredFilenames() []string {
return []string{"lib/apk/db/installed"}
}