diff options
author | Francis Lavoie <[email protected]> | 2024-09-25 16:30:56 -0400 |
---|---|---|
committer | GitHub <[email protected]> | 2024-09-25 14:30:56 -0600 |
commit | 2faeac0a104c72e9396717406ecb7c353bf9aa64 (patch) | |
tree | 5ae5bc9c450f5fb72ad618cac083f4cf8d71d139 /caddyconfig | |
parent | 9dda8fbf846db052243e6ce5ab707650da8c030e (diff) | |
download | caddy-2faeac0a104c72e9396717406ecb7c353bf9aa64.tar.gz caddy-2faeac0a104c72e9396717406ecb7c353bf9aa64.zip |
chore: Use slices package where possible (#6585)
* chore: Use slices package where possible
* More, mostly using ContainsFunc
* Even more slice operations
Diffstat (limited to 'caddyconfig')
-rw-r--r-- | caddyconfig/caddyfile/importgraph.go | 8 | ||||
-rw-r--r-- | caddyconfig/httpcaddyfile/directives.go | 39 | ||||
-rw-r--r-- | caddyconfig/httpcaddyfile/httptype.go | 33 | ||||
-rw-r--r-- | caddyconfig/httpcaddyfile/options.go | 40 | ||||
-rw-r--r-- | caddyconfig/httpcaddyfile/serveroptions.go | 24 | ||||
-rw-r--r-- | caddyconfig/httpcaddyfile/tlsapp.go | 55 |
6 files changed, 71 insertions, 128 deletions
diff --git a/caddyconfig/caddyfile/importgraph.go b/caddyconfig/caddyfile/importgraph.go index d5037fe62..ca859299d 100644 --- a/caddyconfig/caddyfile/importgraph.go +++ b/caddyconfig/caddyfile/importgraph.go @@ -16,6 +16,7 @@ package caddyfile import ( "fmt" + "slices" ) type adjacency map[string][]string @@ -91,12 +92,7 @@ func (i *importGraph) areConnected(from, to string) bool { if !ok { return false } - for _, v := range al { - if v == to { - return true - } - } - return false + return slices.Contains(al, to) } func (i *importGraph) willCycle(from, to string) bool { diff --git a/caddyconfig/httpcaddyfile/directives.go b/caddyconfig/httpcaddyfile/directives.go index 6972bb674..19ef4bc0e 100644 --- a/caddyconfig/httpcaddyfile/directives.go +++ b/caddyconfig/httpcaddyfile/directives.go @@ -17,6 +17,7 @@ package httpcaddyfile import ( "encoding/json" "net" + "slices" "sort" "strconv" "strings" @@ -100,17 +101,6 @@ var defaultDirectiveOrder = []string{ // plugins or by the user via the "order" global option. var directiveOrder = defaultDirectiveOrder -// directiveIsOrdered returns true if dir is -// a known, ordered (sorted) directive. -func directiveIsOrdered(dir string) bool { - for _, d := range directiveOrder { - if d == dir { - return true - } - } - return false -} - // RegisterDirective registers a unique directive dir with an // associated unmarshaling (setup) function. When directive dir // is encountered in a Caddyfile, setupFunc will be called to @@ -161,7 +151,7 @@ func RegisterHandlerDirective(dir string, setupFunc UnmarshalHandlerFunc) { // EXPERIMENTAL: This API may change or be removed. func RegisterDirectiveOrder(dir string, position Positional, standardDir string) { // check if directive was already ordered - if directiveIsOrdered(dir) { + if slices.Contains(directiveOrder, dir) { panic("directive '" + dir + "' already ordered") } @@ -172,12 +162,7 @@ func RegisterDirectiveOrder(dir string, position Positional, standardDir string) // check if directive exists in standard distribution, since // we can't allow plugins to depend on one another; we can't // guarantee the order that plugins are loaded in. - foundStandardDir := false - for _, d := range defaultDirectiveOrder { - if d == standardDir { - foundStandardDir = true - } - } + foundStandardDir := slices.Contains(defaultDirectiveOrder, standardDir) if !foundStandardDir { panic("the 3rd argument '" + standardDir + "' must be a directive that exists in the standard distribution of Caddy") } @@ -603,23 +588,17 @@ func (sb serverBlock) hostsFromKeysNotHTTP(httpPort string) []string { // hasHostCatchAllKey returns true if sb has a key that // omits a host portion, i.e. it "catches all" hosts. func (sb serverBlock) hasHostCatchAllKey() bool { - for _, addr := range sb.keys { - if addr.Host == "" { - return true - } - } - return false + return slices.ContainsFunc(sb.keys, func(addr Address) bool { + return addr.Host == "" + }) } // isAllHTTP returns true if all sb keys explicitly specify // the http:// scheme func (sb serverBlock) isAllHTTP() bool { - for _, addr := range sb.keys { - if addr.Scheme != "http" { - return false - } - } - return true + return !slices.ContainsFunc(sb.keys, func(addr Address) bool { + return addr.Scheme != "http" + }) } // Positional are the supported modes for ordering directives. diff --git a/caddyconfig/httpcaddyfile/httptype.go b/caddyconfig/httpcaddyfile/httptype.go index a8a2ae5b3..c858ee564 100644 --- a/caddyconfig/httpcaddyfile/httptype.go +++ b/caddyconfig/httpcaddyfile/httptype.go @@ -536,7 +536,7 @@ func (st *ServerType) serversFromPairings( if k == j { continue } - if sliceContains(sblock2.block.GetKeysText(), key) { + if slices.Contains(sblock2.block.GetKeysText(), key) { return nil, fmt.Errorf("ambiguous site definition: %s", key) } } @@ -720,7 +720,7 @@ func (st *ServerType) serversFromPairings( if srv.AutoHTTPS == nil { srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig) } - if !sliceContains(srv.AutoHTTPS.Skip, addr.Host) { + if !slices.Contains(srv.AutoHTTPS.Skip, addr.Host) { srv.AutoHTTPS.Skip = append(srv.AutoHTTPS.Skip, addr.Host) } } @@ -734,7 +734,7 @@ func (st *ServerType) serversFromPairings( // https://caddy.community/t/making-sense-of-auto-https-and-why-disabling-it-still-serves-https-instead-of-http/9761 createdTLSConnPolicies, ok := sblock.pile["tls.connection_policy"] hasTLSEnabled := (ok && len(createdTLSConnPolicies) > 0) || - (addr.Host != "" && srv.AutoHTTPS != nil && !sliceContains(srv.AutoHTTPS.Skip, addr.Host)) + (addr.Host != "" && srv.AutoHTTPS != nil && !slices.Contains(srv.AutoHTTPS.Skip, addr.Host)) // we'll need to remember if the address qualifies for auto-HTTPS, so we // can add a TLS conn policy if necessary @@ -1061,7 +1061,7 @@ func consolidateConnPolicies(cps caddytls.ConnectionPolicies) (caddytls.Connecti } else if cps[i].CertSelection != nil && cps[j].CertSelection != nil { // if both have one, then combine AnyTag for _, tag := range cps[j].CertSelection.AnyTag { - if !sliceContains(cps[i].CertSelection.AnyTag, tag) { + if !slices.Contains(cps[i].CertSelection.AnyTag, tag) { cps[i].CertSelection.AnyTag = append(cps[i].CertSelection.AnyTag, tag) } } @@ -1144,7 +1144,7 @@ func appendSubrouteToRouteList(routeList caddyhttp.RouteList, func buildSubroute(routes []ConfigValue, groupCounter counter, needsSorting bool) (*caddyhttp.Subroute, error) { if needsSorting { for _, val := range routes { - if !directiveIsOrdered(val.directive) { + if !slices.Contains(directiveOrder, val.directive) { return nil, fmt.Errorf("directive '%s' is not an ordered HTTP handler, so it cannot be used here - try placing within a route block or using the order global option", val.directive) } } @@ -1354,17 +1354,8 @@ func (st *ServerType) compileEncodedMatcherSets(sblock serverBlock) ([]caddy.Mod // add this server block's keys to the matcher // pair if it doesn't already exist - if addr.Host != "" { - var found bool - for _, h := range chosenMatcherPair.hostm { - if h == addr.Host { - found = true - break - } - } - if !found { - chosenMatcherPair.hostm = append(chosenMatcherPair.hostm, addr.Host) - } + if addr.Host != "" && !slices.Contains(chosenMatcherPair.hostm, addr.Host) { + chosenMatcherPair.hostm = append(chosenMatcherPair.hostm, addr.Host) } } @@ -1540,16 +1531,6 @@ func tryDuration(val any, warnings *[]caddyconfig.Warning) caddy.Duration { return durationVal } -// sliceContains returns true if needle is in haystack. -func sliceContains(haystack []string, needle string) bool { - for _, s := range haystack { - if s == needle { - return true - } - } - return false -} - // listenersUseAnyPortOtherThan returns true if there are any // listeners in addresses that use a port which is not otherPort. // Mostly borrowed from unexported method in caddyhttp package. diff --git a/caddyconfig/httpcaddyfile/options.go b/caddyconfig/httpcaddyfile/options.go index db9be52ca..53687d32a 100644 --- a/caddyconfig/httpcaddyfile/options.go +++ b/caddyconfig/httpcaddyfile/options.go @@ -15,6 +15,7 @@ package httpcaddyfile import ( + "slices" "strconv" "github.com/caddyserver/certmagic" @@ -110,17 +111,12 @@ func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) { } pos := Positional(d.Val()) - newOrder := directiveOrder + // if directive already had an order, drop it + newOrder := slices.DeleteFunc(directiveOrder, func(d string) bool { + return d == dirName + }) - // if directive exists, first remove it - for i, d := range newOrder { - if d == dirName { - newOrder = append(newOrder[:i], newOrder[i+1:]...) - break - } - } - - // act on the positional + // act on the positional; if it's First or Last, we're done right away switch pos { case First: newOrder = append([]string{dirName}, newOrder...) @@ -129,6 +125,7 @@ func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) { } directiveOrder = newOrder return newOrder, nil + case Last: newOrder = append(newOrder, dirName) if d.NextArg() { @@ -136,8 +133,11 @@ func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) { } directiveOrder = newOrder return newOrder, nil + + // if it's Before or After, continue case Before: case After: + default: return nil, d.Errf("unknown positional '%s'", pos) } @@ -151,17 +151,17 @@ func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) { return nil, d.ArgErr() } - // insert directive into proper position - for i, d := range newOrder { - if d == otherDir { - if pos == Before { - newOrder = append(newOrder[:i], append([]string{dirName}, newOrder[i:]...)...) - } else if pos == After { - newOrder = append(newOrder[:i+1], append([]string{dirName}, newOrder[i+1:]...)...) - } - break - } + // get the position of the target directive + targetIndex := slices.Index(newOrder, otherDir) + if targetIndex == -1 { + return nil, d.Errf("directive '%s' not found", otherDir) + } + // if we're inserting after, we need to increment the index to go after + if pos == After { + targetIndex++ } + // insert the directive into the new order + newOrder = slices.Insert(newOrder, targetIndex, dirName) directiveOrder = newOrder diff --git a/caddyconfig/httpcaddyfile/serveroptions.go b/caddyconfig/httpcaddyfile/serveroptions.go index 4246cd7dc..7087cdba5 100644 --- a/caddyconfig/httpcaddyfile/serveroptions.go +++ b/caddyconfig/httpcaddyfile/serveroptions.go @@ -17,6 +17,7 @@ package httpcaddyfile import ( "encoding/json" "fmt" + "slices" "github.com/dustin/go-humanize" @@ -180,7 +181,7 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) { if proto != "h1" && proto != "h2" && proto != "h2c" && proto != "h3" { return nil, d.Errf("unknown protocol '%s': expected h1, h2, h2c, or h3", proto) } - if sliceContains(serverOpts.Protocols, proto) { + if slices.Contains(serverOpts.Protocols, proto) { return nil, d.Errf("protocol %s specified more than once", proto) } serverOpts.Protocols = append(serverOpts.Protocols, proto) @@ -229,7 +230,7 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) { case "client_ip_headers": headers := d.RemainingArgs() for _, header := range headers { - if sliceContains(serverOpts.ClientIPHeaders, header) { + if slices.Contains(serverOpts.ClientIPHeaders, header) { return nil, d.Errf("client IP header %s specified more than once", header) } serverOpts.ClientIPHeaders = append(serverOpts.ClientIPHeaders, header) @@ -288,24 +289,15 @@ func applyServerOptions( for key, server := range servers { // find the options that apply to this server - opts := func() *serverOptions { - for _, entry := range serverOpts { - if entry.ListenerAddress == "" { - return &entry - } - for _, listener := range server.Listen { - if entry.ListenerAddress == listener { - return &entry - } - } - } - return nil - }() + optsIndex := slices.IndexFunc(serverOpts, func(s serverOptions) bool { + return s.ListenerAddress == "" || slices.Contains(server.Listen, s.ListenerAddress) + }) // if none apply, then move to the next server - if opts == nil { + if optsIndex == -1 { continue } + opts := serverOpts[optsIndex] // set all the options server.ListenerWrappersRaw = opts.ListenerWrappersRaw diff --git a/caddyconfig/httpcaddyfile/tlsapp.go b/caddyconfig/httpcaddyfile/tlsapp.go index f69e2c54a..157a3113e 100644 --- a/caddyconfig/httpcaddyfile/tlsapp.go +++ b/caddyconfig/httpcaddyfile/tlsapp.go @@ -19,6 +19,7 @@ import ( "encoding/json" "fmt" "reflect" + "slices" "sort" "strconv" "strings" @@ -57,19 +58,20 @@ func (st ServerType) buildTLSApp( for _, pair := range pairings { for _, sb := range pair.serverBlocks { for _, addr := range sb.keys { - if addr.Host == "" { - // this server block has a hostless key, now - // go through and add all the hosts to the set - for _, otherAddr := range sb.keys { - if otherAddr.Original == addr.Original { - continue - } - if otherAddr.Host != "" && otherAddr.Scheme != "http" && otherAddr.Port != httpPort { - httpsHostsSharedWithHostlessKey[otherAddr.Host] = struct{}{} - } + if addr.Host != "" { + continue + } + // this server block has a hostless key, now + // go through and add all the hosts to the set + for _, otherAddr := range sb.keys { + if otherAddr.Original == addr.Original { + continue + } + if otherAddr.Host != "" && otherAddr.Scheme != "http" && otherAddr.Port != httpPort { + httpsHostsSharedWithHostlessKey[otherAddr.Host] = struct{}{} } - break } + break } } } @@ -465,7 +467,7 @@ func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) e if globalACMECA != nil && acmeIssuer.CA == "" { acmeIssuer.CA = globalACMECA.(string) } - if globalACMECARoot != nil && !sliceContains(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string)) { + if globalACMECARoot != nil && !slices.Contains(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string)) { acmeIssuer.TrustedRootsPEMFiles = append(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string)) } if globalACMEDNS != nil && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.DNS == nil) { @@ -580,7 +582,7 @@ func consolidateAutomationPolicies(aps []*caddytls.AutomationPolicy) []*caddytls if !automationPolicyHasAllPublicNames(aps[i]) { // if this automation policy has internal names, we might as well remove it // so auto-https can implicitly use the internal issuer - aps = append(aps[:i], aps[i+1:]...) + aps = slices.Delete(aps, i, i+1) i-- } } @@ -597,7 +599,7 @@ outer: for j := i + 1; j < len(aps); j++ { // if they're exactly equal in every way, just keep one of them if reflect.DeepEqual(aps[i], aps[j]) { - aps = append(aps[:j], aps[j+1:]...) + aps = slices.Delete(aps, j, j+1) // must re-evaluate current i against next j; can't skip it! // even if i decrements to -1, will be incremented to 0 immediately i-- @@ -627,18 +629,18 @@ outer: // cause example.com to be served by the less specific policy for // '*.com', which might be different (yes we've seen this happen) if automationPolicyShadows(i, aps) >= j { - aps = append(aps[:i], aps[i+1:]...) + aps = slices.Delete(aps, i, i+1) i-- continue outer } } else { // avoid repeated subjects for _, subj := range aps[j].SubjectsRaw { - if !sliceContains(aps[i].SubjectsRaw, subj) { + if !slices.Contains(aps[i].SubjectsRaw, subj) { aps[i].SubjectsRaw = append(aps[i].SubjectsRaw, subj) } } - aps = append(aps[:j], aps[j+1:]...) + aps = slices.Delete(aps, j, j+1) j-- } } @@ -658,13 +660,9 @@ func automationPolicyIsSubset(a, b *caddytls.AutomationPolicy) bool { return false } for _, aSubj := range a.SubjectsRaw { - var inSuperset bool - for _, bSubj := range b.SubjectsRaw { - if certmagic.MatchWildcard(aSubj, bSubj) { - inSuperset = true - break - } - } + inSuperset := slices.ContainsFunc(b.SubjectsRaw, func(bSubj string) bool { + return certmagic.MatchWildcard(aSubj, bSubj) + }) if !inSuperset { return false } @@ -709,12 +707,9 @@ func subjectQualifiesForPublicCert(ap *caddytls.AutomationPolicy, subj string) b // automationPolicyHasAllPublicNames returns true if all the names on the policy // do NOT qualify for public certs OR are tailscale domains. func automationPolicyHasAllPublicNames(ap *caddytls.AutomationPolicy) bool { - for _, subj := range ap.SubjectsRaw { - if !subjectQualifiesForPublicCert(ap, subj) || isTailscaleDomain(subj) { - return false - } - } - return true + return !slices.ContainsFunc(ap.SubjectsRaw, func(i string) bool { + return !subjectQualifiesForPublicCert(ap, i) || isTailscaleDomain(i) + }) } func isTailscaleDomain(name string) bool { |