-
Notifications
You must be signed in to change notification settings - Fork 247
/
http.go
311 lines (265 loc) · 7.86 KB
/
http.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Copyright 2016 CoreOS, Inc.
//
// 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 resource
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/coreos/ignition/v2/config/v3_1_experimental/types"
"github.com/coreos/ignition/v2/internal/earlyrand"
"github.com/coreos/ignition/v2/internal/log"
"github.com/coreos/ignition/v2/internal/util"
"github.com/coreos/ignition/v2/internal/version"
"github.com/vincent-petithory/dataurl"
"golang.org/x/net/http/httpproxy"
)
const (
initialBackoff = 100 * time.Millisecond
maxBackoff = 5 * time.Second
defaultHttpResponseHeaderTimeout = 10
defaultHttpTotalTimeout = 0
)
var (
ErrTimeout = errors.New("unable to fetch resource in time")
ErrPEMDecodeFailed = errors.New("unable to decode PEM block")
)
// HttpClient is a simple wrapper around the Go HTTP client that standardizes
// the process and logging of fetching payloads.
type HttpClient struct {
client *http.Client
logger *log.Logger
timeout time.Duration
transport *http.Transport
cas map[types.CaReference][]byte
}
func (f *Fetcher) UpdateHttpTimeoutsAndCAs(timeouts types.Timeouts, cas []types.CaReference, proxy types.Proxy) error {
if f.client == nil {
if err := f.newHttpClient(); err != nil {
return err
}
}
// Update timeouts
responseHeader := defaultHttpResponseHeaderTimeout
total := defaultHttpTotalTimeout
if timeouts.HTTPResponseHeaders != nil {
responseHeader = *timeouts.HTTPResponseHeaders
}
if timeouts.HTTPTotal != nil {
total = *timeouts.HTTPTotal
}
f.client.client.Timeout = time.Duration(total) * time.Second
f.client.timeout = f.client.client.Timeout
f.client.transport.ResponseHeaderTimeout = time.Duration(responseHeader) * time.Second
f.client.client.Transport = f.client.transport
// Update proxy
f.client.transport.Proxy = func(req *http.Request) (*url.URL, error) {
return proxyFuncFromIgnitionConfig(proxy)(req.URL)
}
f.client.client.Transport = f.client.transport
// Update CAs
if len(cas) == 0 {
return nil
}
pool, err := x509.SystemCertPool()
if err != nil {
f.Logger.Err("Unable to read system certificate pool: %s", err)
return err
}
for _, ca := range cas {
cablob, err := f.getCABlob(ca)
if err != nil {
return err
}
block, _ := pem.Decode(cablob)
if block == nil {
f.Logger.Err("Unable to decode CA (%s)", ca.Source)
return ErrPEMDecodeFailed
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
f.Logger.Err("Unable to parse CA (%s): %s", ca.Source, err)
return err
}
f.Logger.Info("Adding %q to list of CAs", cert.Subject.CommonName)
pool.AddCert(cert)
}
f.client.transport.TLSClientConfig = &tls.Config{RootCAs: pool}
return nil
}
func (f *Fetcher) getCABlob(ca types.CaReference) ([]byte, error) {
if blob, ok := f.client.cas[ca]; ok {
return blob, nil
}
u, err := url.Parse(ca.Source)
if err != nil {
f.Logger.Crit("Unable to parse CA URL: %s", err)
return nil, err
}
hasher, err := util.GetHasher(ca.Verification)
if err != nil {
f.Logger.Crit("Unable to get hasher: %s", err)
return nil, err
}
var expectedSum []byte
if hasher != nil {
// explicitly ignoring the error here because the config should already
// be validated by this point
_, expectedSumString, _ := util.HashParts(ca.Verification)
expectedSum, err = hex.DecodeString(expectedSumString)
if err != nil {
f.Logger.Crit("Error parsing verification string %q: %v", expectedSumString, err)
return nil, err
}
}
cablob, err := f.FetchToBuffer(*u, FetchOptions{
Hash: hasher,
ExpectedSum: expectedSum,
})
if err != nil {
f.Logger.Err("Unable to fetch CA (%s): %s", u, err)
return nil, err
}
f.client.cas[ca] = cablob
return cablob, nil
}
// RewriteCAsWithDataUrls will modify the passed in slice of CA references to
// contain the actual CA file via a dataurl in their source field.
func (f *Fetcher) RewriteCAsWithDataUrls(cas []types.CaReference) error {
for i, ca := range cas {
blob, err := f.getCABlob(ca)
if err != nil {
return err
}
cas[i].Source = dataurl.EncodeBytes(blob)
}
return nil
}
// DefaultHTTPClient builds the default `http.client` for Ignition.
func defaultHTTPClient() (*http.Client, error) {
urand, err := earlyrand.UrandomReader()
if err != nil {
return nil, err
}
tlsConfig := tls.Config{
Rand: urand,
}
transport := http.Transport{
ResponseHeaderTimeout: time.Duration(defaultHttpResponseHeaderTimeout) * time.Second,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
Resolver: &net.Resolver{
PreferGo: true,
},
}).Dial,
TLSClientConfig: &tlsConfig,
TLSHandshakeTimeout: 10 * time.Second,
}
client := http.Client{
Transport: &transport,
}
return &client, nil
}
// newHttpClient populates the fetcher with the default HTTP client.
func (f *Fetcher) newHttpClient() error {
defaultClient, err := defaultHTTPClient()
if err != nil {
return err
}
f.client = &HttpClient{
client: defaultClient,
logger: f.Logger,
timeout: time.Duration(defaultHttpTotalTimeout) * time.Second,
transport: defaultClient.Transport.(*http.Transport),
cas: make(map[types.CaReference][]byte),
}
return nil
}
// getReaderWithHeader performs an HTTP GET on the provided URL with the
// provided request header and returns the response body Reader, HTTP status
// code, a cancel function for the result's context, and error (if any). By
// default, User-Agent is added to the header but this can be overridden.
func (c HttpClient) getReaderWithHeader(url string, header http.Header) (io.ReadCloser, int, context.CancelFunc, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, 0, nil, err
}
req.Header.Set("User-Agent", "Ignition/"+version.Raw)
for key, values := range header {
req.Header.Del(key)
for _, value := range values {
req.Header.Add(key, value)
}
}
ctx, cancelFn := context.WithCancel(context.Background())
if c.timeout != 0 {
cancelFn()
ctx, cancelFn = context.WithTimeout(context.Background(), c.timeout)
}
duration := initialBackoff
for attempt := 1; ; attempt++ {
c.logger.Info("GET %s: attempt #%d", url, attempt)
resp, err := c.client.Do(req.WithContext(ctx))
if err == nil {
c.logger.Info("GET result: %s", http.StatusText(resp.StatusCode))
if resp.StatusCode < 500 {
return resp.Body, resp.StatusCode, cancelFn, nil
}
resp.Body.Close()
} else {
c.logger.Info("GET error: %v", err)
}
duration = duration * 2
if duration > maxBackoff {
duration = maxBackoff
}
// Wait before next attempt or exit if we timeout while waiting
select {
case <-time.After(duration):
case <-ctx.Done():
return nil, 0, cancelFn, ErrTimeout
}
}
}
func proxyFuncFromIgnitionConfig(proxy types.Proxy) func(*url.URL) (*url.URL, error) {
noProxy := translateNoProxySliceToString(proxy.NoProxy)
if proxy.HTTPProxy == nil {
proxy.HTTPProxy = new(string)
}
if proxy.HTTPSProxy == nil {
proxy.HTTPSProxy = new(string)
}
cfg := &httpproxy.Config{
HTTPProxy: *proxy.HTTPProxy,
HTTPSProxy: *proxy.HTTPSProxy,
NoProxy: noProxy,
}
return cfg.ProxyFunc()
}
func translateNoProxySliceToString(items []types.NoProxyItem) string {
newItems := make([]string, len(items))
for i, o := range items {
newItems[i] = string(o)
}
return strings.Join(newItems, ",")
}