-
Notifications
You must be signed in to change notification settings - Fork 80
/
fetcher.go
223 lines (202 loc) · 5.4 KB
/
fetcher.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
222
223
package ovalutil
import (
"compress/bzip2"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"github.com/quay/zlog"
"go.opentelemetry.io/otel/baggage"
"go.opentelemetry.io/otel/label"
"github.com/quay/claircore/libvuln/driver"
"github.com/quay/claircore/pkg/tmp"
)
// Compressor is used by Fetcher to decompress data it fetches.
type Compressor uint
//go:generate stringer -type Compressor -linecomment
// These are the kinds of Compession a Fetcher can deal with.
const (
CompressionNone Compressor = iota // none
CompressionGzip // gzip
CompressionBzip2 // bzip2
)
// ParseCompressor reports the Compressor indicated by the passed in string.
func ParseCompressor(s string) (c Compressor, err error) {
switch s {
case "gz", "gzip":
c = CompressionGzip
case "bz2", "bzip2":
c = CompressionBzip2
case "", "none":
c = CompressionNone
default:
return c, fmt.Errorf("ovalutil: unknown compression scheme %q", s)
}
return c, nil
}
// Fetcher implements the driver.Fetcher interface.
//
// Fetcher expects all of its exported members to be filled out appropriately,
// and may panic if not.
type Fetcher struct {
Compression Compressor
URL *url.URL
Client *http.Client
}
// Configure implements driver.Configurable.
//
// For users that embed a Fetcher, this provides a configuration hook by
// default.
func (f *Fetcher) Configure(ctx context.Context, cf driver.ConfigUnmarshaler, c *http.Client) error {
ctx = baggage.ContextWithValues(ctx,
label.String("component", "pkg/ovalutil/Fetcher.Configure"))
var cfg FetcherConfig
if err := cf(&cfg); err != nil {
return err
}
if cfg.URL != "" {
uri, err := url.Parse(cfg.URL)
if err != nil {
return err
}
f.URL = uri
zlog.Info(ctx).
Msg("configured database URL")
}
if cfg.Compression != "" {
c, err := ParseCompressor(cfg.Compression)
if err != nil {
return err
}
f.Compression = c
zlog.Info(ctx).
Msg("configured database compression")
}
f.Client = c
zlog.Info(ctx).
Msg("configured HTTP client")
return nil
}
// FetcherConfig is the configuration that the Fetcher's Configure method works
// with.
//
// Users the embed Fetcher and use Fetcher.Configure should make sure any of
// their configuration keys don't conflict with these names.
type FetcherConfig struct {
URL string `json:"url" yaml:"url"`
Compression string `json:"compression" yaml:"compression"`
}
// Fetch fetches the resource as specified by Fetcher.URL and
// Fetcher.Compression, using the client provided as Fetcher.Client.
//
// Fetch makes GET requests, and will make conditional requests using the
// passed-in hint.
//
// Tmp.File is used to return a ReadCloser that outlives the passed-in context.
func (f *Fetcher) Fetch(ctx context.Context, hint driver.Fingerprint) (io.ReadCloser, driver.Fingerprint, error) {
ctx = baggage.ContextWithValues(ctx,
label.String("component", "pkg/ovalutil/Fetcher.Fetch"))
zlog.Info(ctx).Str("database", f.URL.String()).Msg("starting fetch")
req := http.Request{
Method: http.MethodGet,
Header: http.Header{
"User-Agent": {"claircore/pkg/ovalutil.Fetcher"},
},
URL: f.URL,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Host: f.URL.Host,
}
var fp fingerprint
if h := string(hint); h != "" {
if err := json.Unmarshal([]byte(h), &fp); err == nil {
fp.Set(req.Header)
}
}
res, err := f.Client.Do(req.WithContext(ctx))
if res != nil {
defer res.Body.Close()
}
if err != nil {
return nil, hint, err
}
switch res.StatusCode {
case http.StatusNotModified:
return nil, hint, driver.Unchanged
case http.StatusOK:
// break
default:
return nil, hint, fmt.Errorf("ovalutil: fetcher got unexpected HTTP response: %d (%s)", res.StatusCode, res.Status)
}
zlog.Debug(ctx).Msg("request ok")
var r io.Reader
switch f.Compression {
case CompressionNone:
r = res.Body
case CompressionGzip:
r, err = gzip.NewReader(res.Body)
if err != nil {
return nil, hint, err
}
case CompressionBzip2:
r = bzip2.NewReader(res.Body)
default:
panic(fmt.Sprintf("ovalutil: programmer error: unknown compression scheme: %v", f.Compression))
}
zlog.Debug(ctx).
Str("compression", f.Compression.String()).
Msg("found compression scheme")
tf, err := tmp.NewFile("", "fetcher.")
if err != nil {
return nil, hint, err
}
zlog.Debug(ctx).
Str("path", tf.Name()).
Msg("using tempfile")
success := false
defer func() {
if !success {
zlog.Debug(ctx).Msg("unsuccessful, cleaning up tempfile")
if err := tf.Close(); err != nil {
zlog.Warn(ctx).Err(err).Msg("failed to close tempfile")
}
}
}()
if _, err := io.Copy(tf, r); err != nil {
return nil, hint, err
}
if o, err := tf.Seek(0, io.SeekStart); err != nil || o != 0 {
return nil, hint, err
}
zlog.Debug(ctx).Msg("decompressed and buffered database")
fp.From(res.Header)
hint = fp.Fingerprint()
success = true
return tf, hint, nil
}
type fingerprint struct {
Etag string `json:",omitempty"`
Date string `json:",omitempty"`
}
func (f fingerprint) Set(h http.Header) {
if f.Etag != "" {
h.Set("if-none-match", f.Etag)
}
if f.Date != "" {
h.Set("if-modified-since", f.Date)
}
}
func (f *fingerprint) From(h http.Header) {
if tag := h.Get("etag"); tag != "" {
f.Etag = tag
}
f.Date = h.Get("last-modified")
}
func (f fingerprint) Fingerprint() driver.Fingerprint {
b, _ := json.Marshal(f)
return driver.Fingerprint(string(b))
}