Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion common/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module go.podman.io/common

// Warning: Ensure the "go" and "toolchain" versions match exactly to prevent unwanted auto-updates

go 1.23.3
go 1.24.0

require (
github.com/BurntSushi/toml v1.5.0
Expand Down
11 changes: 5 additions & 6 deletions common/libimage/copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"net"
"os"
"slices"
"strings"
"time"

Expand Down Expand Up @@ -396,7 +397,7 @@ func (c *Copier) copyInternal(ctx context.Context, source, destination types.Ima
// TimeoutStartSec=, the service manager will allow the service to continue to start, provided the
// service repeats "EXTEND_TIMEOUT_USEC=..." within the interval specified until the service startup
// status is finished by "READY=1"."
extendValue := []byte(fmt.Sprintf("EXTEND_TIMEOUT_USEC=%d", extension.Microseconds()))
extendValue := fmt.Appendf(nil, "EXTEND_TIMEOUT_USEC=%d", extension.Microseconds())
extendTimeout := func() {
if _, err := conn.Write(extendValue); err != nil {
logrus.Errorf("Increasing EXTEND_TIMEOUT_USEC failed: %v", err)
Expand Down Expand Up @@ -555,11 +556,9 @@ func checkRegistrySourcesAllows(dest types.ImageReference) (insecure *bool, err
return nil, fmt.Errorf("registry %q denied by policy: not in allowed registries list (%s)", reference.Domain(dref), registrySources)
}

for _, insecureDomain := range sources.InsecureRegistries {
if insecureDomain == reference.Domain(dref) {
insecure := true
return &insecure, nil
}
if slices.Contains(sources.InsecureRegistries, reference.Domain(dref)) {
insecure := true
return &insecure, nil
}

return nil, nil
Expand Down
12 changes: 6 additions & 6 deletions common/libimage/filter/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,25 @@ type SearchFilter struct {
func ParseSearchFilter(filter []string) (*SearchFilter, error) {
sFilter := new(SearchFilter)
for _, f := range filter {
arr := strings.SplitN(f, "=", 2)
switch arr[0] {
keyword, value, ok := strings.Cut(f, "=")
switch keyword {
case define.SearchFilterStars:
if len(arr) < 2 {
if !ok {
return nil, fmt.Errorf("invalid filter %q, should be stars=<value>", filter)
}
stars, err := strconv.Atoi(arr[1])
stars, err := strconv.Atoi(value)
if err != nil {
return nil, fmt.Errorf("incorrect value type for stars filter: %w", err)
}
sFilter.Stars = stars
case define.SearchFilterAutomated:
if len(arr) == 2 && arr[1] == "false" {
if ok && value == "false" {
sFilter.IsAutomated = types.OptionalBoolFalse
} else {
sFilter.IsAutomated = types.OptionalBoolTrue
}
case define.SearchFilterOfficial:
if len(arr) == 2 && arr[1] == "false" {
if ok && value == "false" {
sFilter.IsOfficial = types.OptionalBoolFalse
} else {
sFilter.IsOfficial = types.OptionalBoolTrue
Expand Down
10 changes: 4 additions & 6 deletions common/libimage/filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,18 +89,16 @@ func (r *Runtime) compileImageFilters(ctx context.Context, options *ListImagesOp
var key, value string
var filter filterFunc
negate := false
split := strings.SplitN(f, "!=", 2)
if len(split) == 2 {
key, value, ok := strings.Cut(f, "!=")
if ok {
negate = true
} else {
split = strings.SplitN(f, "=", 2)
if len(split) != 2 {
key, value, ok = strings.Cut(f, "=")
if !ok {
return nil, false, fmt.Errorf(filterInvalidValue, f)
}
}

key = split[0]
value = split[1]
switch key {
case "after", "since":
img, err := r.time(key, value)
Expand Down
17 changes: 3 additions & 14 deletions common/libimage/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"path/filepath"
"slices"
"sort"
"strings"
"time"
Expand Down Expand Up @@ -173,12 +174,7 @@ func (i *Image) Digests() []digest.Digest {
// hasDigest returns whether the specified value matches any digest of the
// image.
func (i *Image) hasDigest(wantedDigest digest.Digest) bool {
for _, d := range i.Digests() {
if d == wantedDigest {
return true
}
}
return false
return slices.Contains(i.Digests(), wantedDigest)
}

// containsDigestPrefix returns whether the specified value matches any digest of the
Expand Down Expand Up @@ -638,16 +634,9 @@ func (i *Image) Untag(name string) error {

name = ref.String()

foundName := false
for _, n := range i.Names() {
if n == name {
foundName = true
break
}
}
// Return an error if the name is not found, the c/storage
// RemoveNames() API does not create one if no match is found.
if !foundName {
if !slices.Contains(i.Names(), name) {
return fmt.Errorf("%s: %w", name, errTagUnknown)
}

Expand Down
31 changes: 9 additions & 22 deletions common/libimage/image_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,17 @@ func ImageConfigFromChanges(changes []string) (*ImageConfig, error) { // nolint:
for _, change := range changes {
// First, let's assume proper Dockerfile format - space
// separator between instruction and value
split := strings.SplitN(change, " ", 2)
outerKey, value, ok := strings.Cut(change, " ")

if len(split) != 2 {
split = strings.SplitN(change, "=", 2)
if len(split) != 2 {
if !ok {
outerKey, value, ok = strings.Cut(change, "=")
if !ok {
return nil, fmt.Errorf("invalid change %q - must be formatted as KEY VALUE", change)
}
}

outerKey := strings.ToUpper(strings.TrimSpace(split[0]))
value := strings.TrimSpace(split[1])
outerKey = strings.ToUpper(strings.TrimSpace(outerKey))
value = strings.TrimSpace(value)
switch outerKey {
case "USER":
// Assume literal contents are the user.
Expand Down Expand Up @@ -96,18 +96,11 @@ func ImageConfigFromChanges(changes []string) (*ImageConfig, error) { // nolint:
// For now: we only support key=value
// We will attempt to strip quotation marks if present.

var key, val string

splitEnv := strings.SplitN(value, "=", 2)
key = splitEnv[0]
key, val, _ := strings.Cut(value, "=") // val is "" if there is no "="
// We do need a key
if key == "" {
return nil, fmt.Errorf("invalid change %q - ENV must have at least one argument", change)
}
// Perfectly valid to not have a value
if len(splitEnv) == 2 {
val = splitEnv[1]
}

if strings.HasPrefix(key, `"`) && strings.HasSuffix(key, `"`) {
key = strings.TrimPrefix(strings.TrimSuffix(key, `"`), `"`)
Expand Down Expand Up @@ -192,17 +185,11 @@ func ImageConfigFromChanges(changes []string) (*ImageConfig, error) { // nolint:
// Potentially problematic: LABEL might theoretically
// allow an = in the key? If people really do this, we
// may need to investigate more advanced parsing.
var (
key, val string
)

splitLabel := strings.SplitN(value, "=", 2)
key, val, ok := strings.Cut(value, "=")
// Unlike ENV, LABEL must have a value
if len(splitLabel) != 2 {
if !ok {
return nil, fmt.Errorf("invalid change %q - LABEL must be formatted key=value", change)
}
key = splitLabel[0]
val = splitLabel[1]

if strings.HasPrefix(key, `"`) && strings.HasSuffix(key, `"`) {
key = strings.TrimPrefix(strings.TrimSuffix(key, `"`), `"`)
Expand Down
6 changes: 2 additions & 4 deletions common/libimage/manifest_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,10 +303,8 @@ func (m *ManifestList) LookupInstance(ctx context.Context, architecture, os, var
}

for _, image := range allImages {
for _, imageDigest := range append(image.Digests(), image.Digest()) {
if imageDigest == instanceDigest {
return image, nil
}
if slices.Contains(image.Digests(), instanceDigest) || instanceDigest == image.Digest() {
return image, nil
}
}

Expand Down
6 changes: 2 additions & 4 deletions common/libimage/manifests/manifests.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,10 +252,8 @@ func (l *list) InstanceByFile(file string) (digest.Digest, error) {
return "", err
}
for instanceDigest, files := range l.artifacts.Files {
for _, file := range files {
if file == abs {
return instanceDigest, nil
}
if slices.Contains(files, abs) {
return instanceDigest, nil
}
}
return "", os.ErrNotExist
Expand Down
6 changes: 3 additions & 3 deletions common/libimage/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,8 +253,8 @@ func (r *Runtime) copyFromDefault(ctx context.Context, ref types.ImageReference,
storageName = imageName

case ociTransport.Transport.Name():
split := strings.SplitN(ref.StringWithinTransport(), ":", 2)
if len(split) == 1 || split[1] == "" {
_, refName, ok := strings.Cut(ref.StringWithinTransport(), ":")
if !ok || refName == "" {
// Same trick as for the dir transport: we cannot use
// the path to a directory as the name.
storageName, err = getImageID(ctx, ref, nil)
Expand All @@ -263,7 +263,7 @@ func (r *Runtime) copyFromDefault(ctx context.Context, ref types.ImageReference,
}
imageName = "sha256:" + storageName[1:]
} else { // If the OCI-reference includes an image reference, use it
storageName = split[1]
storageName = refName
imageName = storageName
}

Expand Down
28 changes: 8 additions & 20 deletions common/libimage/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,11 @@ func (r *Runtime) Search(ctx context.Context, term string, options *SearchOption
// that we cannot use the reference parser from the containers/image
// library as the search term may container arbitrary input such as
// wildcards. See bugzilla.redhat.com/show_bug.cgi?id=1846629.
spl := strings.SplitN(term, "/", 2)
perhapsRegistry, perhapsTerm, ok := strings.Cut(term, "/")
switch {
case len(spl) > 1:
searchRegistries = []string{spl[0]}
term = spl[1]
case ok:
searchRegistries = []string{perhapsRegistry}
term = perhapsTerm
case len(options.Registries) > 0:
searchRegistries = options.Registries
default:
Expand Down Expand Up @@ -203,15 +203,9 @@ func (r *Runtime) searchImageInRegistry(ctx context.Context, term, registry stri
// limit is the number of results to output
// if the total number of results is less than the limit, output all
// if the limit has been set by the user, output those number of queries
limit = searchMaxQueries
if len(results) < limit {
limit = len(results)
}
limit = min(len(results), searchMaxQueries)
if options.Limit != 0 {
limit = len(results)
if options.Limit < len(results) {
limit = options.Limit
}
limit = min(len(results), options.Limit)
}

paramsArr := []SearchResult{}
Expand Down Expand Up @@ -264,15 +258,9 @@ func searchRepositoryTags(ctx context.Context, sys *types.SystemContext, registr
if err != nil {
return nil, fmt.Errorf("getting repository tags: %v", err)
}
limit := searchMaxQueries
if len(tags) < limit {
limit = len(tags)
}
limit := min(len(tags), searchMaxQueries)
if options.Limit != 0 {
limit = len(tags)
if options.Limit < limit {
limit = options.Limit
}
limit = min(len(tags), options.Limit)
}
paramsArr := []SearchResult{}
for i := range limit {
Expand Down
4 changes: 1 addition & 3 deletions common/libnetwork/cni/cni_conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,9 +355,7 @@ func convertSpecgenPortsToCNIPorts(ports []types.PortMapping) ([]cniPortMapEntry
if port.Protocol == "" {
return nil, errors.New("port protocol should not be empty")
}
protocols := strings.Split(port.Protocol, ",")

for _, protocol := range protocols {
for protocol := range strings.SplitSeq(port.Protocol, ",") {
if !slices.Contains([]string{"tcp", "udp", "sctp"}, protocol) {
return nil, fmt.Errorf("unknown port protocol %s", protocol)
}
Expand Down
6 changes: 3 additions & 3 deletions common/libnetwork/cni/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,9 @@ func getRuntimeConfig(netns, conName, conID, networkName string, ports []cniPort
}

// Propagate environment CNI_ARGS
for _, kvpairs := range strings.Split(os.Getenv("CNI_ARGS"), ";") {
if keyval := strings.SplitN(kvpairs, "=", 2); len(keyval) == 2 {
rt.Args = append(rt.Args, [2]string{keyval[0], keyval[1]})
for kvpairs := range strings.SplitSeq(os.Getenv("CNI_ARGS"), ";") {
if key, val, ok := strings.Cut(kvpairs, "="); ok {
rt.Args = append(rt.Args, [2]string{key, val})
}
}

Expand Down
13 changes: 6 additions & 7 deletions common/libnetwork/etchosts/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,24 +236,23 @@ func checkIfEntryExists(current HostEntry, entries HostEntries) bool {
func parseExtraHosts(extraHosts []string, hostContainersInternalIP string) (HostEntries, error) {
entries := make(HostEntries, 0, len(extraHosts))
for _, entry := range extraHosts {
values := strings.SplitN(entry, ":", 2)
if len(values) != 2 {
namesString, ip, ok := strings.Cut(entry, ":")
if !ok {
return nil, fmt.Errorf("unable to parse host entry %q: incorrect format", entry)
}
if values[0] == "" {
if namesString == "" {
return nil, fmt.Errorf("hostname in host entry %q is empty", entry)
}
if values[1] == "" {
if ip == "" {
return nil, fmt.Errorf("IP address in host entry %q is empty", entry)
}
ip := values[1]
if values[1] == HostGateway {
if ip == HostGateway {
if hostContainersInternalIP == "" {
return nil, fmt.Errorf("unable to replace %q of host entry %q: host containers internal IP address is empty", HostGateway, entry)
}
ip = hostContainersInternalIP
}
names := strings.Split(values[0], ";")
names := strings.Split(namesString, ";")
e := HostEntry{IP: ip, Names: names}
entries = append(entries, e)
}
Expand Down
3 changes: 1 addition & 2 deletions common/libnetwork/pasta/pasta_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,7 @@ func createPastaArgs(opts *SetupOptions) ([]string, []string, []string, error) {
}

for _, i := range opts.Ports {
protocols := strings.Split(i.Protocol, ",")
for _, protocol := range protocols {
for protocol := range strings.SplitSeq(i.Protocol, ",") {
var addr string

if i.HostIP != "" {
Expand Down
3 changes: 1 addition & 2 deletions common/libnetwork/resolvconf/resolvconf.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,8 @@ func filterResolvDNS(resolvConf []byte, ipv6Enabled bool, netnsEnabled bool) []b

// getLines parses input into lines and strips away comments.
func getLines(input []byte) [][]byte {
lines := bytes.Split(input, []byte("\n"))
var output [][]byte
for _, currentLine := range lines {
for currentLine := range bytes.SplitSeq(input, []byte("\n")) {
commentIndex := bytes.Index(currentLine, []byte("#"))
if commentIndex == -1 {
output = append(output, currentLine)
Expand Down
8 changes: 3 additions & 5 deletions common/libnetwork/slirp4netns/slirp4netns.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,10 @@ func parseNetworkOptions(config *config.Config, extraOptions []string) (*network
enableIPv6: true,
}
for _, o := range options {
parts := strings.SplitN(o, "=", 2)
if len(parts) < 2 {
option, value, ok := strings.Cut(o, "=")
if !ok {
return nil, fmt.Errorf("unknown option for slirp4netns: %q", o)
}
option, value := parts[0], parts[1]
switch option {
case "cidr":
ipv4, _, err := net.ParseCIDR(value)
Expand Down Expand Up @@ -639,8 +638,7 @@ func setupRootlessPortMappingViaSlirp(ports []types.PortMapping, cmd *exec.Cmd,
// for each port we want to add we need to open a connection to the slirp4netns control socket
// and send the add_hostfwd command.
for _, port := range ports {
protocols := strings.Split(port.Protocol, ",")
for _, protocol := range protocols {
for protocol := range strings.SplitSeq(port.Protocol, ",") {
hostIP := port.HostIP
if hostIP == "" {
hostIP = "0.0.0.0"
Expand Down
Loading