| 1 |
// Copyright 2021 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package create |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"context" |
| 19 |
"fmt" |
| 20 |
"io" |
| 21 |
"maps" |
| 22 |
"math/rand" |
| 23 |
"mime" |
| 24 |
"net/http" |
| 25 |
"net/url" |
| 26 |
"path" |
| 27 |
"strconv" |
| 28 |
"strings" |
| 29 |
"time" |
| 30 |
|
| 31 |
"github.com/spf13/cast" |
| 32 |
|
| 33 |
"github.com/gohugoio/httpcache" |
| 34 |
"github.com/gohugoio/hugo/common/hashing" |
| 35 |
"github.com/gohugoio/hugo/common/hmaps" |
| 36 |
"github.com/gohugoio/hugo/common/hstrings" |
| 37 |
"github.com/gohugoio/hugo/common/hugio" |
| 38 |
"github.com/gohugoio/hugo/common/loggers" |
| 39 |
"github.com/gohugoio/hugo/common/tasks" |
| 40 |
"github.com/gohugoio/hugo/common/types" |
| 41 |
"github.com/gohugoio/hugo/config" |
| 42 |
"github.com/gohugoio/hugo/identity" |
| 43 |
"github.com/gohugoio/hugo/media" |
| 44 |
"github.com/gohugoio/hugo/resources" |
| 45 |
"github.com/gohugoio/hugo/resources/resource" |
| 46 |
"github.com/mitchellh/mapstructure" |
| 47 |
) |
| 48 |
|
| 49 |
type HTTPError struct { |
| 50 |
error |
| 51 |
Data map[string]any |
| 52 |
|
| 53 |
StatusCode int |
| 54 |
Body string |
| 55 |
} |
| 56 |
|
| 57 |
func responseToData(res *http.Response, readBody bool, includeHeaders []string) map[string]any { |
| 58 |
var body []byte |
| 59 |
if readBody { |
| 60 |
body, _ = io.ReadAll(res.Body) |
| 61 |
} |
| 62 |
|
| 63 |
responseHeaders := make(map[string][]string) |
| 64 |
if len(includeHeaders) > 0 { |
| 65 |
for k, v := range res.Header { |
| 66 |
if hstrings.InSlicEqualFold(includeHeaders, k) { |
| 67 |
responseHeaders[k] = v |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
m := map[string]any{ |
| 73 |
"StatusCode": res.StatusCode, |
| 74 |
"Status": res.Status, |
| 75 |
"TransferEncoding": res.TransferEncoding, |
| 76 |
"ContentLength": res.ContentLength, |
| 77 |
"ContentType": res.Header.Get("Content-Type"), |
| 78 |
"Headers": responseHeaders, |
| 79 |
} |
| 80 |
|
| 81 |
if readBody { |
| 82 |
m["Body"] = string(body) |
| 83 |
} |
| 84 |
|
| 85 |
return m |
| 86 |
} |
| 87 |
|
| 88 |
func toHTTPError(err error, res *http.Response, readBody bool, responseHeaders []string) *HTTPError { |
| 89 |
if err == nil { |
| 90 |
panic("err is nil") |
| 91 |
} |
| 92 |
if res == nil { |
| 93 |
return &HTTPError{ |
| 94 |
error: err, |
| 95 |
Data: map[string]any{}, |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
return &HTTPError{ |
| 100 |
error: err, |
| 101 |
Data: responseToData(res, readBody, responseHeaders), |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
var temporaryHTTPStatusCodes = map[int]bool{ |
| 106 |
408: true, |
| 107 |
429: true, |
| 108 |
500: true, |
| 109 |
502: true, |
| 110 |
503: true, |
| 111 |
504: true, |
| 112 |
} |
| 113 |
|
| 114 |
// parseRetryAfter returns the duration to wait per the Retry-After header in |
| 115 |
// resp, or 0 if the header is absent or unparseable. Per RFC 7231 the value |
| 116 |
// may be either delta-seconds or an HTTP-date. |
| 117 |
func parseRetryAfter(resp *http.Response) time.Duration { |
| 118 |
if resp == nil { |
| 119 |
return 0 |
| 120 |
} |
| 121 |
h := strings.TrimSpace(resp.Header.Get("Retry-After")) |
| 122 |
if h == "" { |
| 123 |
return 0 |
| 124 |
} |
| 125 |
if n, err := strconv.Atoi(h); err == nil && n >= 0 { |
| 126 |
return time.Duration(n) * time.Second |
| 127 |
} |
| 128 |
if t, err := http.ParseTime(h); err == nil { |
| 129 |
if d := time.Until(t); d > 0 { |
| 130 |
return d |
| 131 |
} |
| 132 |
} |
| 133 |
return 0 |
| 134 |
} |
| 135 |
|
| 136 |
func (c *Client) configurePollingIfEnabled(uri, optionsKey string, getRes func() (*http.Response, context.CancelFunc, error)) { |
| 137 |
if c.remoteResourceChecker == nil { |
| 138 |
return |
| 139 |
} |
| 140 |
|
| 141 |
// Set up polling for changes to this resource. |
| 142 |
pollingConfig := c.httpCacheConfig.PollConfigFor(uri) |
| 143 |
if pollingConfig.IsZero() || pollingConfig.Config.Disable { |
| 144 |
return |
| 145 |
} |
| 146 |
|
| 147 |
if c.remoteResourceChecker.Has(optionsKey) { |
| 148 |
return |
| 149 |
} |
| 150 |
|
| 151 |
var lastChange time.Time |
| 152 |
c.remoteResourceChecker.Add(optionsKey, |
| 153 |
tasks.Func{ |
| 154 |
IntervalLow: pollingConfig.Config.Low, |
| 155 |
IntervalHigh: pollingConfig.Config.High, |
| 156 |
F: func(interval time.Duration) (time.Duration, error) { |
| 157 |
start := time.Now() |
| 158 |
defer func() { |
| 159 |
duration := time.Since(start) |
| 160 |
c.rs.Logger.Debugf("Polled remote resource for changes in %13s. Interval: %4s (low: %4s high: %4s) resource: %q ", duration, interval, pollingConfig.Config.Low, pollingConfig.Config.High, uri) |
| 161 |
}() |
| 162 |
// TODO(bep) figure out a ways to remove unused tasks. |
| 163 |
res, cancel, err := getRes() |
| 164 |
if cancel != nil { |
| 165 |
defer cancel() |
| 166 |
} |
| 167 |
if err != nil { |
| 168 |
return pollingConfig.Config.High, err |
| 169 |
} |
| 170 |
// The caching is delayed until the body is read. |
| 171 |
io.Copy(io.Discard, res.Body) |
| 172 |
res.Body.Close() |
| 173 |
x1, x2 := res.Header.Get(httpcache.XETag1), res.Header.Get(httpcache.XETag2) |
| 174 |
if x1 != x2 { |
| 175 |
lastChange = time.Now() |
| 176 |
c.remoteResourceLogger.Logf("detected change in remote resource %q", uri) |
| 177 |
c.rs.Rebuilder.SignalRebuild(identity.StringIdentity(optionsKey)) |
| 178 |
} |
| 179 |
|
| 180 |
if time.Since(lastChange) < 10*time.Second { |
| 181 |
// The user is typing, check more often. |
| 182 |
return 0, nil |
| 183 |
} |
| 184 |
|
| 185 |
// Increase the interval to avoid hammering the server. |
| 186 |
interval += 1 * time.Second |
| 187 |
|
| 188 |
return interval, nil |
| 189 |
}, |
| 190 |
}) |
| 191 |
} |
| 192 |
|
| 193 |
// FromRemote expects one or n-parts of a URL to a resource |
| 194 |
// If you provide multiple parts they will be joined together to the final URL. |
| 195 |
func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resource, error) { |
| 196 |
rURL, err := url.Parse(uri) |
| 197 |
if err != nil { |
| 198 |
return nil, fmt.Errorf("failed to parse URL for resource %s: %w", uri, err) |
| 199 |
} |
| 200 |
|
| 201 |
method := "GET" |
| 202 |
if s, _, ok := hmaps.LookupEqualFold(optionsm, "method"); ok { |
| 203 |
method = strings.ToUpper(s.(string)) |
| 204 |
} |
| 205 |
isHeadMethod := method == "HEAD" |
| 206 |
|
| 207 |
optionsm = maps.Clone(optionsm) |
| 208 |
|
| 209 |
// Extract timeout before computing cache keys: it only affects fetch behaviour, |
| 210 |
// not the cached content, so it must not influence the cache key. |
| 211 |
var perRequestTimeout time.Duration |
| 212 |
if v, k, ok := hmaps.LookupEqualFold(optionsm, "timeout"); ok { |
| 213 |
d, err := cast.ToDurationE(v) |
| 214 |
if err != nil { |
| 215 |
return nil, fmt.Errorf("invalid timeout for resource %s: %w", uri, err) |
| 216 |
} |
| 217 |
perRequestTimeout = d |
| 218 |
delete(optionsm, k) |
| 219 |
} |
| 220 |
|
| 221 |
userKey, optionsKey := remoteResourceKeys(uri, optionsm) |
| 222 |
|
| 223 |
// A common pattern is to use the key in the options map as |
| 224 |
// a way to control cache eviction, |
| 225 |
// so make sure we use any user provided key as the file cache key, |
| 226 |
// but the auto generated and more stable key for everything else. |
| 227 |
filecacheKey := userKey |
| 228 |
|
| 229 |
return c.rs.ResourceCache.CacheResourceRemote.GetOrCreate(optionsKey, func(key string) (resource.Resource, error) { |
| 230 |
options, err := decodeRemoteOptions(optionsm) |
| 231 |
if err != nil { |
| 232 |
return nil, fmt.Errorf("failed to decode options for resource %s: %w", uri, err) |
| 233 |
} |
| 234 |
|
| 235 |
if err := c.validateFromRemoteArgs(uri, options); err != nil { |
| 236 |
return nil, err |
| 237 |
} |
| 238 |
|
| 239 |
getRes := func() (*http.Response, context.CancelFunc, error) { |
| 240 |
ctx := context.Background() |
| 241 |
var cancel context.CancelFunc |
| 242 |
if perRequestTimeout > 0 { |
| 243 |
ctx, cancel = context.WithTimeout(ctx, perRequestTimeout) |
| 244 |
} |
| 245 |
ctx = c.resourceIDDispatcher.Set(ctx, filecacheKey) |
| 246 |
|
| 247 |
req, err := options.NewRequest(uri) |
| 248 |
if err != nil { |
| 249 |
if cancel != nil { |
| 250 |
cancel() |
| 251 |
} |
| 252 |
return nil, nil, fmt.Errorf("failed to create request for resource %s: %w", uri, err) |
| 253 |
} |
| 254 |
|
| 255 |
req = req.WithContext(ctx) |
| 256 |
|
| 257 |
resp, err := c.httpClient.Do(req) |
| 258 |
if err != nil { |
| 259 |
if cancel != nil { |
| 260 |
cancel() |
| 261 |
} |
| 262 |
return nil, nil, err |
| 263 |
} |
| 264 |
return resp, cancel, nil |
| 265 |
} |
| 266 |
|
| 267 |
res, cancel, err := getRes() |
| 268 |
if cancel != nil { |
| 269 |
defer cancel() |
| 270 |
} |
| 271 |
if err != nil { |
| 272 |
return nil, err |
| 273 |
} |
| 274 |
defer res.Body.Close() |
| 275 |
|
| 276 |
c.configurePollingIfEnabled(uri, optionsKey, getRes) |
| 277 |
|
| 278 |
if res.StatusCode == http.StatusNotFound { |
| 279 |
// Not found. This matches how lookups for local resources work. |
| 280 |
// To cache this, we need to make sure the body is read. |
| 281 |
io.Copy(io.Discard, res.Body) |
| 282 |
return nil, nil |
| 283 |
} |
| 284 |
|
| 285 |
if res.StatusCode < 200 || res.StatusCode > 299 { |
| 286 |
return nil, toHTTPError(fmt.Errorf("failed to fetch remote resource from '%s': %s", uri, http.StatusText(res.StatusCode)), res, !isHeadMethod, options.ResponseHeaders) |
| 287 |
} |
| 288 |
|
| 289 |
var ( |
| 290 |
body []byte |
| 291 |
mediaType media.Type |
| 292 |
) |
| 293 |
// A response to a HEAD method should not have a body. If it has one anyway, that body must be ignored. |
| 294 |
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD |
| 295 |
if !isHeadMethod && res.Body != nil { |
| 296 |
body, err = io.ReadAll(res.Body) |
| 297 |
if err != nil { |
| 298 |
return nil, fmt.Errorf("failed to read remote resource %q: %w", uri, err) |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
filename := path.Base(rURL.Path) |
| 303 |
if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil { |
| 304 |
if _, ok := params["filename"]; ok { |
| 305 |
filename = params["filename"] |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
contentType := res.Header.Get("Content-Type") |
| 310 |
|
| 311 |
// For HEAD requests we have no body to work with, so we need to use the Content-Type header. |
| 312 |
if isHeadMethod || c.rs.ExecHelper.Sec().HTTP.MediaTypes.Accept(contentType) { |
| 313 |
var found bool |
| 314 |
mediaType, found = c.rs.MediaTypes().GetByType(contentType) |
| 315 |
if !found { |
| 316 |
// A media type not configured in Hugo, just create one from the content type string. |
| 317 |
mediaType, _ = media.FromString(contentType) |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
if mediaType.IsZero() { |
| 322 |
|
| 323 |
var extensionHints []string |
| 324 |
|
| 325 |
// mime.ExtensionsByType gives a long list of extensions for text/plain, |
| 326 |
// just use ".txt". |
| 327 |
if strings.HasPrefix(contentType, "text/plain") { |
| 328 |
extensionHints = []string{".txt"} |
| 329 |
} else { |
| 330 |
exts, _ := mime.ExtensionsByType(contentType) |
| 331 |
if exts != nil { |
| 332 |
extensionHints = exts |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
// Look for a file extension. If it's .txt, look for a more specific. |
| 337 |
if extensionHints == nil || extensionHints[0] == ".txt" { |
| 338 |
if ext := path.Ext(filename); ext != "" { |
| 339 |
extensionHints = []string{ext} |
| 340 |
} |
| 341 |
} |
| 342 |
|
| 343 |
// Now resolve the media type primarily using the content. |
| 344 |
mediaType = media.FromContent(c.rs.MediaTypes(), extensionHints, body) |
| 345 |
|
| 346 |
} |
| 347 |
|
| 348 |
if mediaType.IsZero() { |
| 349 |
return nil, fmt.Errorf("failed to resolve media type for remote resource %q", uri) |
| 350 |
} |
| 351 |
|
| 352 |
userKey = filename[:len(filename)-len(path.Ext(filename))] + "_" + userKey + mediaType.FirstSuffix.FullSuffix |
| 353 |
data := responseToData(res, false, options.ResponseHeaders) |
| 354 |
|
| 355 |
return c.rs.NewResource( |
| 356 |
resources.ResourceSourceDescriptor{ |
| 357 |
MediaType: mediaType, |
| 358 |
Data: data, |
| 359 |
GroupIdentity: identity.StringIdentity(optionsKey), |
| 360 |
LazyPublish: true, |
| 361 |
OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { |
| 362 |
return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil |
| 363 |
}, |
| 364 |
TargetPath: userKey, |
| 365 |
}) |
| 366 |
}) |
| 367 |
} |
| 368 |
|
| 369 |
func (c *Client) validateFromRemoteArgs(uri string, options fromRemoteOptions) error { |
| 370 |
if err := c.rs.ExecHelper.Sec().CheckAllowedHTTPURL(uri); err != nil { |
| 371 |
return err |
| 372 |
} |
| 373 |
|
| 374 |
if err := c.rs.ExecHelper.Sec().CheckAllowedHTTPMethod(options.Method); err != nil { |
| 375 |
return err |
| 376 |
} |
| 377 |
|
| 378 |
return nil |
| 379 |
} |
| 380 |
|
| 381 |
func remoteResourceKeys(uri string, optionsm map[string]any) (string, string) { |
| 382 |
var userKey string |
| 383 |
if key, k, found := hmaps.LookupEqualFold(optionsm, "key"); found { |
| 384 |
userKey = hashing.HashString(key) |
| 385 |
delete(optionsm, k) |
| 386 |
} |
| 387 |
optionsKey := hashing.HashString(uri, optionsm) |
| 388 |
if userKey == "" { |
| 389 |
userKey = optionsKey |
| 390 |
} |
| 391 |
return userKey, optionsKey |
| 392 |
} |
| 393 |
|
| 394 |
func addDefaultHeaders(req *http.Request) { |
| 395 |
if !hasHeaderKey(req.Header, "User-Agent") { |
| 396 |
req.Header.Add("User-Agent", "Hugo Static Site Generator") |
| 397 |
} |
| 398 |
} |
| 399 |
|
| 400 |
func addUserProvidedHeaders(headers map[string]any, req *http.Request) { |
| 401 |
if headers == nil { |
| 402 |
return |
| 403 |
} |
| 404 |
for key, val := range headers { |
| 405 |
vals := types.ToStringSlicePreserveString(val) |
| 406 |
for _, s := range vals { |
| 407 |
req.Header.Add(key, s) |
| 408 |
} |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
func hasHeaderKey(m http.Header, key string) bool { |
| 413 |
_, ok := m[key] |
| 414 |
return ok |
| 415 |
} |
| 416 |
|
| 417 |
type fromRemoteOptions struct { |
| 418 |
Method string |
| 419 |
Headers map[string]any |
| 420 |
Body []byte |
| 421 |
ResponseHeaders []string |
| 422 |
} |
| 423 |
|
| 424 |
func (o fromRemoteOptions) BodyReader() io.Reader { |
| 425 |
if o.Body == nil { |
| 426 |
return nil |
| 427 |
} |
| 428 |
return bytes.NewBuffer(o.Body) |
| 429 |
} |
| 430 |
|
| 431 |
func (o fromRemoteOptions) NewRequest(url string) (*http.Request, error) { |
| 432 |
req, err := http.NewRequest(o.Method, url, o.BodyReader()) |
| 433 |
if err != nil { |
| 434 |
return nil, err |
| 435 |
} |
| 436 |
|
| 437 |
// First add any user provided headers. |
| 438 |
if o.Headers != nil { |
| 439 |
addUserProvidedHeaders(o.Headers, req) |
| 440 |
} |
| 441 |
|
| 442 |
// Then add default headers not provided by the user. |
| 443 |
addDefaultHeaders(req) |
| 444 |
|
| 445 |
return req, nil |
| 446 |
} |
| 447 |
|
| 448 |
func decodeRemoteOptions(optionsm map[string]any) (fromRemoteOptions, error) { |
| 449 |
options := fromRemoteOptions{ |
| 450 |
Method: "GET", |
| 451 |
} |
| 452 |
|
| 453 |
err := mapstructure.WeakDecode(optionsm, &options) |
| 454 |
if err != nil { |
| 455 |
return options, err |
| 456 |
} |
| 457 |
options.Method = strings.ToUpper(options.Method) |
| 458 |
|
| 459 |
return options, nil |
| 460 |
} |
| 461 |
|
| 462 |
var _ http.RoundTripper = (*transport)(nil) |
| 463 |
|
| 464 |
type transport struct { |
| 465 |
Cfg config.AllProvider |
| 466 |
Logger loggers.Logger |
| 467 |
|
| 468 |
// base does the actual round trip. It carries a dial-time hook that |
| 469 |
// validates the resolved destination address (see New). |
| 470 |
base http.RoundTripper |
| 471 |
} |
| 472 |
|
| 473 |
func (t *transport) RoundTrip(req *http.Request) (resp *http.Response, err error) { |
| 474 |
defer func() { |
| 475 |
if resp != nil && resp.StatusCode != http.StatusNotFound && resp.StatusCode != http.StatusNotModified { |
| 476 |
t.Logger.Debugf("Fetched remote resource: %s", req.URL.String()) |
| 477 |
} |
| 478 |
}() |
| 479 |
|
| 480 |
var ( |
| 481 |
start time.Time |
| 482 |
nextSleep = time.Duration((rand.Intn(1000) + 100)) * time.Millisecond |
| 483 |
nextSleepLimit = time.Duration(5) * time.Second |
| 484 |
retry bool |
| 485 |
) |
| 486 |
|
| 487 |
for { |
| 488 |
resp, retry, err = func() (*http.Response, bool, error) { |
| 489 |
resp2, err := t.base.RoundTrip(req) |
| 490 |
if err != nil { |
| 491 |
return resp2, false, err |
| 492 |
} |
| 493 |
|
| 494 |
if resp2.StatusCode != http.StatusNotFound && resp2.StatusCode != http.StatusNotModified { |
| 495 |
if resp2.StatusCode < 200 || resp2.StatusCode > 299 { |
| 496 |
return resp2, temporaryHTTPStatusCodes[resp2.StatusCode], nil |
| 497 |
} |
| 498 |
} |
| 499 |
return resp2, false, nil |
| 500 |
}() |
| 501 |
|
| 502 |
if retry { |
| 503 |
sleep := nextSleep |
| 504 |
retryAfter := parseRetryAfter(resp) |
| 505 |
if retryAfter > 0 { |
| 506 |
sleep = retryAfter |
| 507 |
} |
| 508 |
if start.IsZero() { |
| 509 |
start = time.Now() |
| 510 |
} |
| 511 |
if d := time.Since(start) + sleep; d >= t.Cfg.Timeout() { |
| 512 |
msg := "<nil>" |
| 513 |
if resp != nil { |
| 514 |
msg = resp.Status |
| 515 |
} |
| 516 |
if retryAfter > 0 { |
| 517 |
msg = fmt.Sprintf("%s (server requested Retry-After: %s)", msg, retryAfter) |
| 518 |
} |
| 519 |
err := toHTTPError(fmt.Errorf("retry timeout (configured to %s) fetching remote resource: %s", t.Cfg.Timeout(), msg), resp, req.Method != "HEAD", nil) |
| 520 |
return resp, err |
| 521 |
} |
| 522 |
time.Sleep(sleep) |
| 523 |
if nextSleep < nextSleepLimit { |
| 524 |
nextSleep *= 2 |
| 525 |
} |
| 526 |
continue |
| 527 |
} |
| 528 |
|
| 529 |
return |
| 530 |
} |
| 531 |
} |
| 532 |
|
| 533 |
// We need to send the redirect responses back to the HTTP client from RoundTrip, |
| 534 |
// but we don't want to cache them. |
| 535 |
func shouldCache(statusCode int) bool { |
| 536 |
switch statusCode { |
| 537 |
case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect: |
| 538 |
return false |
| 539 |
} |
| 540 |
return true |
| 541 |
} |