|
| 1 | +/* |
| 2 | + Copyright The containerd Authors. |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package dockerconfigresolver |
| 18 | + |
| 19 | +import ( |
| 20 | + "errors" |
| 21 | + "os" |
| 22 | + |
| 23 | + "github.com/containerd/containerd/v2/core/remotes/docker/config" |
| 24 | + "github.com/containerd/errdefs" |
| 25 | + "github.com/containerd/log" |
| 26 | +) |
| 27 | + |
| 28 | +// validateDirectories inspect a slice of strings and returns the ones that are valid readable directories |
| 29 | +func validateDirectories(orig []string) []string { |
| 30 | + ss := []string{} |
| 31 | + for _, v := range orig { |
| 32 | + fi, err := os.Stat(v) |
| 33 | + if err != nil || !fi.IsDir() { |
| 34 | + if !errors.Is(err, os.ErrNotExist) { |
| 35 | + log.L.WithError(err).Warnf("Ignoring hosts location %q", v) |
| 36 | + } |
| 37 | + continue |
| 38 | + } |
| 39 | + ss = append(ss, v) |
| 40 | + } |
| 41 | + return ss |
| 42 | +} |
| 43 | + |
| 44 | +// hostDirsFromRoot will retrieve a host.toml file for the namespace host, possibly trying without port |
| 45 | +// if the requested port is standard. |
| 46 | +// https://github.com/containerd/nerdctl/issues/3047 |
| 47 | +func hostDirsFromRoot(registryURL *RegistryURL, dirs []string) (string, error) { |
| 48 | + hostsDirs := validateDirectories(dirs) |
| 49 | + |
| 50 | + // Go through the configured system location to consider for hosts.toml files |
| 51 | + for _, hostsDir := range hostsDirs { |
| 52 | + found, err := config.HostDirFromRoot(hostsDir)(registryURL.Host) |
| 53 | + // If we errored with anything but NotFound, or if we found one, return now |
| 54 | + if (err != nil && !errdefs.IsNotFound(err)) || (found != "") { |
| 55 | + return found, err |
| 56 | + } |
| 57 | + // If not found, and the port is standard, try again without the port |
| 58 | + if registryURL.Port() == standardHTTPSPort { |
| 59 | + found, err = config.HostDirFromRoot(hostsDir)(registryURL.Hostname()) |
| 60 | + if (err != nil && !errors.Is(err, errdefs.ErrNotFound)) || (found != "") { |
| 61 | + return found, err |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + return "", nil |
| 66 | +} |
0 commit comments