Debian Codegraph @

resources/resource_factories/create/create.go

raw
1 // Copyright 2019 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 contains functions for to create Resource objects. This will
15 // typically non-files.
16 package create
17
18 import (
19 "context"
20 "errors"
21 "net"
22 "net/http"
23 "net/url"
24 "os"
25 "path"
26 "path/filepath"
27 "strings"
28 "syscall"
29 "time"
30
31 "golang.org/x/net/http/httpproxy"
32
33 "github.com/bep/helpers/contexthelpers"
34
35 "github.com/bep/logg"
36 "github.com/gohugoio/httpcache"
37 hhttpcache "github.com/gohugoio/hugo/cache/httpcache"
38 "github.com/gohugoio/hugo/hugofs/hglob"
39 "github.com/gohugoio/hugo/identity"
40
41 "github.com/gohugoio/hugo/hugofs"
42
43 "github.com/gohugoio/hugo/cache/dynacache"
44 "github.com/gohugoio/hugo/cache/filecache"
45 "github.com/gohugoio/hugo/common/hashing"
46
47 "github.com/gohugoio/hugo/common/hugio"
48 "github.com/gohugoio/hugo/common/tasks"
49 "github.com/gohugoio/hugo/config/security"
50 "github.com/gohugoio/hugo/resources"
51 "github.com/gohugoio/hugo/resources/resource"
52 )
53
54 // Client contains methods to create Resource objects.
55 // tasks to Resource objects.
56 type Client struct {
57 rs *resources.Spec
58 httpClient *http.Client
59 httpCacheConfig hhttpcache.ConfigCompiled
60 cacheGetResource *filecache.Cache
61 resourceIDDispatcher contexthelpers.ContextDispatcher[string]
62
63 // Set when watching.
64 remoteResourceChecker *tasks.RunEvery
65 remoteResourceLogger logg.LevelLogger
66 }
67
68 type contextKey uint8
69
70 const (
71 contextKeyResourceID contextKey = iota
72 contextKeyProxyURL
73 )
74
75 // New creates a new Client with the given specification.
76 func New(rs *resources.Spec) *Client {
77 fileCache := rs.FileCaches.GetResourceCache()
78 resourceIDDispatcher := contexthelpers.NewContextDispatcher[string](contextKeyResourceID)
79 httpCacheConfig := rs.Cfg.GetConfigSection("httpCacheCompiled").(hhttpcache.ConfigCompiled)
80 var remoteResourceChecker *tasks.RunEvery
81 if rs.Cfg.Watching() && !httpCacheConfig.IsPollingDisabled() {
82 remoteResourceChecker = &tasks.RunEvery{
83 HandleError: func(name string, err error) {
84 rs.Logger.Warnf("Failed to check remote resource: %s", err)
85 },
86 RunImmediately: false,
87 }
88
89 if err := remoteResourceChecker.Start(); err != nil {
90 panic(err)
91 }
92
93 rs.BuildClosers.Add(remoteResourceChecker)
94 }
95
96 httpTimeout := 2 * time.Minute // Need to cover retries.
97 if httpTimeout < (rs.Cfg.Timeout() + 30*time.Second) {
98 httpTimeout = rs.Cfg.Timeout() + 30*time.Second
99 }
100
101 return &Client{
102 rs: rs,
103 httpCacheConfig: httpCacheConfig,
104 resourceIDDispatcher: resourceIDDispatcher,
105 remoteResourceChecker: remoteResourceChecker,
106 remoteResourceLogger: rs.Logger.InfoCommand("remote"),
107 httpClient: &http.Client{
108 Timeout: httpTimeout,
109 CheckRedirect: func(req *http.Request, via []*http.Request) error {
110 if err := rs.ExecHelper.Sec().CheckAllowedHTTPURL(req.URL.String()); err != nil {
111 return err
112 }
113 if len(via) >= 10 {
114 return errors.New("stopped after 10 redirects")
115 }
116 return nil
117 },
118 Transport: &httpcache.Transport{
119 Cache: fileCache.AsHTTPCache(),
120 CacheKey: func(req *http.Request) string {
121 return resourceIDDispatcher.Get(req.Context())
122 },
123 Around: func(req *http.Request, key string) func() {
124 return fileCache.NamedLock(key)
125 },
126 AlwaysUseCachedResponse: func(req *http.Request, key string) bool {
127 return !httpCacheConfig.For(req.URL.String())
128 },
129 ShouldCache: func(req *http.Request, resp *http.Response, key string) bool {
130 return shouldCache(resp.StatusCode)
131 },
132 CanStore: func(reqCacheControl, respCacheControl httpcache.CacheControl) (canStore bool) {
133 if httpCacheConfig.Base.RespectCacheControlNoStoreInResponse {
134 if _, ok := respCacheControl["no-store"]; ok {
135 return false
136 }
137 }
138 if httpCacheConfig.Base.RespectCacheControlNoStoreInRequest {
139 if _, ok := reqCacheControl["no-store"]; ok {
140 return false
141 }
142 }
143 return true
144 },
145 MarkCachedResponses: true,
146 EnableETagPair: true,
147 Transport: &transport{
148 Cfg: rs.Cfg,
149 Logger: rs.Logger,
150 base: newSecureBaseTransport(rs.ExecHelper.Sec()),
151 },
152 },
153 },
154 cacheGetResource: fileCache,
155 }
156 }
157
158 // newSecureBaseTransport clones the default transport and installs a dial-time
159 // hook that validates the resolved destination address against the security
160 // policy, so a hostname resolving to an internal address cannot be used to
161 // reach internal endpoints. See CheckAllowedHTTPAddress.
162 //
163 // Proxies are only used when security.http.proxyFromEnvironment is enabled.
164 // A proxied connection is dialed to the proxy, not the destination, so the
165 // address check is skipped for that dial; the user has opted into trusting
166 // the proxy with the destination. The proxy decision is carried per request
167 // in its context, so a direct dial is always validated, even to the proxy's
168 // own address.
169 func newSecureBaseTransport(sec security.Config) http.RoundTripper {
170 base := http.DefaultTransport.(*http.Transport).Clone()
171 secureDialer := &net.Dialer{
172 Timeout: 30 * time.Second,
173 KeepAlive: 30 * time.Second,
174 Control: func(network, address string, _ syscall.RawConn) error {
175 return sec.CheckAllowedHTTPAddress(network, address)
176 },
177 }
178 base.Proxy = nil
179 base.DialContext = secureDialer.DialContext
180
181 if !sec.HTTP.ProxyFromEnvironment {
182 return base
183 }
184
185 proxyFromCtx := func(ctx context.Context) *url.URL {
186 u, _ := ctx.Value(contextKeyProxyURL).(*url.URL)
187 return u
188 }
189 base.Proxy = func(req *http.Request) (*url.URL, error) {
190 return proxyFromCtx(req.Context()), nil
191 }
192 proxyDialer := &net.Dialer{Timeout: secureDialer.Timeout, KeepAlive: secureDialer.KeepAlive}
193 base.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
194 if u := proxyFromCtx(ctx); u != nil && canonicalAddr(u) == addr {
195 return proxyDialer.DialContext(ctx, network, addr)
196 }
197 return secureDialer.DialContext(ctx, network, addr)
198 }
199 return &proxyTransport{base: base, proxyFunc: httpproxy.FromEnvironment().ProxyFunc()}
200 }
201
202 // proxyTransport resolves the proxy for each request up front and stores it
203 // in the request context, where both the Proxy and DialContext hooks of base
204 // can see it.
205 type proxyTransport struct {
206 base *http.Transport
207 proxyFunc func(*url.URL) (*url.URL, error)
208 }
209
210 func (t *proxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
211 u, err := t.proxyFunc(req.URL)
212 if err != nil {
213 return nil, err
214 }
215 if u != nil {
216 req = req.WithContext(context.WithValue(req.Context(), contextKeyProxyURL, u))
217 }
218 return t.base.RoundTrip(req)
219 }
220
221 // canonicalAddr mirrors net/http's canonicalAddr: the host:port the transport
222 // dials for u, with the port defaulted from the scheme.
223 func canonicalAddr(u *url.URL) string {
224 port := u.Port()
225 if port == "" {
226 switch u.Scheme {
227 case "http":
228 port = "80"
229 case "https":
230 port = "443"
231 case "socks5", "socks5h":
232 port = "1080"
233 }
234 }
235 return net.JoinHostPort(u.Hostname(), port)
236 }
237
238 // Copy copies r to the new targetPath.
239 func (c *Client) Copy(r resource.Resource, targetPath string) (resource.Resource, error) {
240 key := dynacache.CleanKey(targetPath) + "__copy"
241 return c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) {
242 return resources.Copy(r, targetPath), nil
243 })
244 }
245
246 // Get creates a new Resource by opening the given pathname in the assets filesystem.
247 func (c *Client) Get(pathname string) (resource.Resource, error) {
248 pathname = path.Clean(pathname)
249 key := dynacache.CleanKey(pathname) + "__get"
250
251 return c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) {
252 // The resource file will not be read before it gets used (e.g. in .Content),
253 // so we need to check that the file exists here.
254 filename := filepath.FromSlash(pathname)
255 fi, err := c.rs.BaseFs.Assets.Fs.Stat(filename)
256 if err != nil {
257 if os.IsNotExist(err) {
258 return nil, nil
259 }
260 // A real error.
261 return nil, err
262 }
263
264 return c.getOrCreateFileResource(fi.(hugofs.FileMetaInfo))
265 })
266 }
267
268 // Match gets the resources matching the given pattern from the assets filesystem.
269 func (c *Client) Match(pattern string) (resource.Resources, error) {
270 return c.match("__match", pattern, nil, false)
271 }
272
273 func (c *Client) ByType(tp string) resource.Resources {
274 res, err := c.match(path.Join("_byType", tp), "**", func(r resource.Resource) bool { return r.ResourceType() == tp }, false)
275 if err != nil {
276 panic(err)
277 }
278 return res
279 }
280
281 // GetMatch gets first resource matching the given pattern from the assets filesystem.
282 func (c *Client) GetMatch(pattern string) (resource.Resource, error) {
283 res, err := c.match("__get-match", pattern, nil, true)
284 if err != nil || len(res) == 0 {
285 return nil, err
286 }
287 return res[0], err
288 }
289
290 func (c *Client) getOrCreateFileResource(info hugofs.FileMetaInfo) (resource.Resource, error) {
291 meta := info.Meta()
292 return c.rs.ResourceCache.GetOrCreateFile(filepath.ToSlash(meta.Filename), func() (resource.Resource, error) {
293 return c.rs.NewResource(resources.ResourceSourceDescriptor{
294 LazyPublish: true,
295 OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {
296 return meta.Open()
297 },
298 NameNormalized: meta.PathInfo.Path(),
299 NameOriginal: meta.PathInfo.Unnormalized().Path(),
300 GroupIdentity: meta.PathInfo,
301 TargetPath: meta.PathInfo.Unnormalized().Path(),
302 SourceFilenameOrPath: meta.Filename,
303 })
304 })
305 }
306
307 func (c *Client) match(name, pattern string, matchFunc func(r resource.Resource) bool, firstOnly bool) (resource.Resources, error) {
308 pattern = hglob.NormalizePath(pattern)
309 partitions := hglob.FilterGlobParts(strings.Split(pattern, "/"))
310 key := path.Join(name, path.Join(partitions...))
311 key = path.Join(key, pattern)
312
313 return c.rs.ResourceCache.GetOrCreateResources(key, func() (resource.Resources, error) {
314 var res resource.Resources
315
316 handle := func(info hugofs.FileMetaInfo) (bool, error) {
317 r, err := c.getOrCreateFileResource(info)
318 if err != nil {
319 return true, err
320 }
321
322 if matchFunc != nil && !matchFunc(r) {
323 return false, nil
324 }
325
326 res = append(res, r)
327
328 return firstOnly, nil
329 }
330
331 if err := hugofs.Glob(c.rs.BaseFs.Assets.Fs, pattern, handle); err != nil {
332 return nil, err
333 }
334
335 return res, nil
336 })
337 }
338
339 type Options struct {
340 // The target path relative to the publish directory.
341 // Unix style path, i.e. "images/logo.png".
342 TargetPath string
343
344 // Whether the TargetPath has a hash in it which will change if the resource changes.
345 // If not, we will calculate a hash from the content.
346 TargetPathHasHash bool
347
348 // The content to create the Resource from.
349 CreateContent func() (func() (hugio.ReadSeekCloser, error), error)
350 }
351
352 // FromOpts creates a new Resource from the given Options.
353 // Make sure to set optis.TargetPathHasHash if the TargetPath already contains a hash,
354 // as this avoids the need to calculate it.
355 // To create a new ReadSeekCloser from a string, use hugio.NewReadSeekerNoOpCloserFromString,
356 // or hugio.NewReadSeekerNoOpCloserFromBytes for a byte slice.
357 // See FromString.
358 func (c *Client) FromOpts(opts Options) (resource.Resource, error) {
359 opts.TargetPath = path.Clean(opts.TargetPath)
360 var hash string
361 var newReadSeeker func() (hugio.ReadSeekCloser, error) = nil
362 if !opts.TargetPathHasHash {
363 var err error
364 newReadSeeker, err = opts.CreateContent()
365 if err != nil {
366 return nil, err
367 }
368 if err := func() error {
369 r, err := newReadSeeker()
370 if err != nil {
371 return err
372 }
373 defer r.Close()
374
375 hash, err = hashing.XxHashFromReaderHexEncoded(r)
376 if err != nil {
377 return err
378 }
379 return nil
380 }(); err != nil {
381 return nil, err
382 }
383 }
384
385 key := dynacache.CleanKey(opts.TargetPath) + hash
386 r, err := c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) {
387 if newReadSeeker == nil {
388 var err error
389 newReadSeeker, err = opts.CreateContent()
390 if err != nil {
391 return nil, err
392 }
393 }
394 return c.rs.NewResource(
395 resources.ResourceSourceDescriptor{
396 LazyPublish: true,
397 IncludeHashInKey: !opts.TargetPathHasHash,
398 GroupIdentity: identity.Anonymous, // All usage of this resource are tracked via its string content.
399 OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {
400 return newReadSeeker()
401 },
402 TargetPath: opts.TargetPath,
403 })
404 })
405
406 return r, err
407 }
408
409 // FromString creates a new Resource from a string with the given relative target path.
410 func (c *Client) FromString(targetPath, content string) (resource.Resource, error) {
411 return c.FromOpts(Options{
412 TargetPath: targetPath,
413 CreateContent: func() (func() (hugio.ReadSeekCloser, error), error) {
414 return func() (hugio.ReadSeekCloser, error) {
415 return hugio.NewReadSeekerNoOpCloserFromString(content), nil
416 }, nil
417 },
418 })
419 }