diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000000..d3a2fc784f --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,111 @@ +version: "2" +run: + skip-dirs: + - ^doc/ + timeout: 3m +linters: + default: none + enable: + - contextcheck + - copyloopvar + - errcheck + - forbidigo + - goheader + - govet + - ineffassign + - lll + - misspell + - rowserrcheck + - sqlclosecheck + - staticcheck + - unconvert + - unused + settings: + staticcheck: + checks: + - all + - "-QF1001" # disable "Apply De Morgan's law". + # The use of Go ideomatic identifiers is a recommendation, not a law. + - "-ST1003" # disable "Poorly chosen identifier". + - "-QF1008" # disable "Omit embedded fields from selector expression". + errcheck: + exclude-functions: + - (*github.com/spf13/cobra.Command).MarkFlagRequired + forbidigo: + forbid: + - pattern: ([iI][fF][iI]d)|([iI]F[iI][dD])|([iI][fF]i[dD]) + msg: spell interface ID as ifID / IfID + - pattern: (?i)interfaceID + msg: spell interface ID as ifID / IfID + - pattern: Trc + msg: spell trust root certificate as trc / TRC + goheader: + values: + regexp: + copyright-lines: |- + (Copyright 20[0-9][0-9] .*)( + Copyright 20[0-9][0-9] .*)* + template: |- + {{copyright-lines}} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + lll: + line-length: 100 + tab-width: 4 + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - linters: + - lll + source: http[s]://\S{80,}$ + - linters: + - lll + source: '`(yaml|toml|json):"[^`]*`$' + - linters: + - goheader + path: pkg/private/util/duration.go + - linters: + - errcheck + - goheader + path: pkg/private/serrors/stack.go + - linters: + - errcheck + - goheader + - lll + path: scion-pki/certs/(certinfo|certformat).go + - linters: + - goheader + path: pkg/scrypto/cms + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + settings: + goimports: + local-prefixes: + - github.com/scionproto/scion + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/.golangcilint.yml b/.golangcilint.yml deleted file mode 100644 index 0f098f717f..0000000000 --- a/.golangcilint.yml +++ /dev/null @@ -1,79 +0,0 @@ -linters: - # FIXME(roosd): For now, we disable all linters and turn them on one-by-one. - disable-all: true - enable: - # Default linters. - - forbidigo - - errcheck - - goimports - - gosimple - - govet - - ineffassign - - typecheck - - unused - # Extended linters. - - copyloopvar - - rowserrcheck - - sqlclosecheck - - unconvert - - gofmt - - lll - - misspell - - goheader - - contextcheck -linters-settings: - # ... - forbidigo: - forbid: - - p: "([iI][fF][iI]d)|([iI]F[iI][dD])|([iI][fF]i[dD])" - msg: "spell interface ID as ifID / IfID" - - p: "(?i)interfaceID" # case insensitive - msg: "spell interface ID as ifID / IfID" - - p: "Trc" - msg: "spell trust root certificate as trc / TRC" - lll: - line-length: 100 - tab-width: 4 - errcheck: - exclude-functions: - - (*github.com/spf13/cobra.Command).MarkFlagRequired - goheader: - values: - regexp: - copyright-lines: "(Copyright 20[0-9][0-9] .*)(\nCopyright 20[0-9][0-9] .*)*" - template: |- - {{copyright-lines}} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - goimports: - local-prefixes: github.com/scionproto/scion - -issues: - exclude-rules: - # don't report long lines with long links - - linters: [lll] - source: "http[s]://\\S{80,}$" - # don't report long lines with yaml/json/toml tags - - linters: [lll] - source: "`(yaml|toml|json):\"[^`]*`$" - - # these files originate from third-party projects - - path: pkg/private/util/duration.go - linters: [goheader] - - path: pkg/private/serrors/stack.go - linters: [goheader, errcheck] - - path: scion-pki/certs/(certinfo|certformat).go - linters: [lll, goheader, errcheck] - - path: pkg/scrypto/cms - linters: [goheader] - diff --git a/Makefile b/Makefile index 19241bac84..34b9bb750b 100644 --- a/Makefile +++ b/Makefile @@ -123,7 +123,7 @@ GO_BUILD_TAGS_ARG=$(shell bazel info --ui_event_filters=-stdout,-stderr --announ lint-go-golangci: $(info ==> $@) - @tools/quiet bazel run --config=quiet @rules_go//go -- run github.com/golangci/golangci-lint/cmd/golangci-lint@v1.64.8 run --config="${PWD}/.golangcilint.yml" --timeout=3m $(GO_BUILD_TAGS_ARG),lint --exclude-dirs doc ./... + @tools/quiet bazel run --config=quiet @rules_go//go -- run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.1.6 run --config="${PWD}/.golangci.yml" $(GO_BUILD_TAGS_ARG),lint ./... lint-go-semgrep: $(info ==> $@) diff --git a/acceptance/router_benchmark/brload/main.go b/acceptance/router_benchmark/brload/main.go index 8d69acb22e..48cf770126 100644 --- a/acceptance/router_benchmark/brload/main.go +++ b/acceptance/router_benchmark/brload/main.go @@ -51,7 +51,7 @@ func (c *caseChoice) String() string { func (c *caseChoice) Set(v string) error { _, ok := allCases[v] if !ok { - return errors.New("No such case") + return errors.New("no such case") } *c = caseChoice(v) return nil diff --git a/acceptance/topo_cs_reload/reload_test.go b/acceptance/topo_cs_reload/reload_test.go index edae7c1711..b6d5e9db32 100644 --- a/acceptance/topo_cs_reload/reload_test.go +++ b/acceptance/topo_cs_reload/reload_test.go @@ -90,10 +90,13 @@ func setupTest(t *testing.T) testState { s := testState{ extraEnv: []string{"TOPO_CS_RELOAD_CONFIG_DIR=" + tmpDir}, } + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4775). scionPKI, err := bazel.Runfile(*scionPKILocation) require.NoError(t, err) + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4775). cryptoLib, err := bazel.Runfile(*cryptoLibLocation) require.NoError(t, err) + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4775). topoFile, err := bazel.Runfile(*topoLocation) require.NoError(t, err) s.mustExec(t, *genCryptoLocation, scionPKI, "crypto.tar", topoFile, cryptoLib) diff --git a/control/beaconing/extender_test.go b/control/beaconing/extender_test.go index 10505af956..bfb9bbae28 100644 --- a/control/beaconing/extender_test.go +++ b/control/beaconing/extender_test.go @@ -93,6 +93,7 @@ func TestDefaultExtenderExtend(t *testing.T) { // Setup interfaces with active parent, child and one peer interface. intfs := ifstate.NewInterfaces(interfaceInfos(topo), ifstate.Config{}) for _, peer := range tc.peers { + //nolint:staticcheck // SA1019: Activate is fine for testing. intfs.Get(peer).Activate(peerRemoteIfs[peer]) } ext := &beaconing.DefaultExtender{ diff --git a/control/beaconing/writer.go b/control/beaconing/writer.go index 52dd7a2b3c..ef1552c0cc 100644 --- a/control/beaconing/writer.go +++ b/control/beaconing/writer.go @@ -113,7 +113,7 @@ func (r *WriteScheduler) Run(ctx context.Context) { } func (r *WriteScheduler) run(ctx context.Context) error { - if !(r.Tick.Overdue(r.lastWrite) || r.Tick.Passed()) { + if !r.Tick.Overdue(r.lastWrite) && !r.Tick.Passed() { return nil } segments, err := r.Provider.SegmentsToRegister(ctx, r.Type) diff --git a/control/cmd/control/main.go b/control/cmd/control/main.go index 63d2e4395b..f228d829e7 100644 --- a/control/cmd/control/main.go +++ b/control/cmd/control/main.go @@ -488,6 +488,8 @@ func realMain(ctx context.Context) error { }, } // Periodically check the connection to the CA backend + // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). + //nolint:staticcheck caHealthChecker := periodic.Start( periodic.Func{ TaskName: "ca healthcheck", @@ -519,6 +521,7 @@ func realMain(ctx context.Context) error { } // Frequently regenerate signers to catch problems, and update the metrics. + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). periodic.Start( periodic.Func{ TaskName: "signer generator", @@ -537,6 +540,7 @@ func realMain(ctx context.Context) error { 5*time.Second, ) + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). trcRunner := periodic.Start( periodic.Func{ TaskName: "trc expiration updater", diff --git a/control/drkey/grpc/drkey_service.go b/control/drkey/grpc/drkey_service.go index 6f5961f2e2..d94641c4b5 100644 --- a/control/drkey/grpc/drkey_service.go +++ b/control/drkey/grpc/drkey_service.go @@ -333,8 +333,8 @@ func validateHostHostReq(meta drkey.HostHostMeta, localIA addr.IA, peerAddr net. srcHost := net.ParseIP(meta.SrcHost) dstHost := net.ParseIP(meta.DstHost) - if !((meta.SrcIA.Equal(localIA) && hostAddr.Equal(srcHost)) || - (meta.DstIA.Equal(localIA) && hostAddr.Equal(dstHost))) { + if (!meta.SrcIA.Equal(localIA) || !hostAddr.Equal(srcHost)) && + (!meta.DstIA.Equal(localIA) || !hostAddr.Equal(dstHost)) { return serrors.New( "invalid request", "local_isd_as", localIA, diff --git a/control/drkey/grpc/fetcher_test.go b/control/drkey/grpc/fetcher_test.go index 1cc3b380fd..2667bf0142 100644 --- a/control/drkey/grpc/fetcher_test.go +++ b/control/drkey/grpc/fetcher_test.go @@ -157,7 +157,8 @@ func genCrypto(t testing.TB) string { "--isd-dir", "--as-validity", "1y", }) - cmd.SetOutput(&buf) + cmd.SetOut(&buf) + cmd.SetErr(&buf) err := cmd.Execute() require.NoError(t, err, buf.String()) diff --git a/control/tasks.go b/control/tasks.go index 4de2588cc6..3484fd1740 100644 --- a/control/tasks.go +++ b/control/tasks.go @@ -97,6 +97,7 @@ func (t *TasksConfig) Originator() *periodic.Runner { if t.Metrics != nil { s.Originated = metrics.NewPromCounter(t.Metrics.BeaconingOriginatedTotal) } + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). return periodic.Start(s, 500*time.Millisecond, t.OriginationInterval) } @@ -118,6 +119,7 @@ func (t *TasksConfig) Propagator() *periodic.Runner { p.Propagated = metrics.NewPromCounter(t.Metrics.BeaconingPropagatedTotal) p.InternalErrors = metrics.NewPromCounter(t.Metrics.BeaconingPropagatorInternalErrorsTotal) } + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). return periodic.Start(p, 500*time.Millisecond, t.PropagationInterval) } @@ -199,6 +201,7 @@ func (t *TasksConfig) segmentWriter(segType seg.Type, // as we can until we succeed. After succeeding, the task does nothing // until the end of the interval. The interval itself is used as a // timeout. If we fail slow we give up at the end of the cycle. + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). return periodic.Start(r, 500*time.Millisecond, t.RegistrationInterval) } @@ -236,6 +239,7 @@ func (t *TasksConfig) DRKeyCleaners() []*periodic.Runner { cleaners := t.DRKeyEngine.CreateStorageCleaners() cleanerTasks := make([]*periodic.Runner, len(cleaners)) for i, cleaner := range cleaners { + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). cleanerTasks[i] = periodic.Start(cleaner, cleanerPeriod, cleanerPeriod) } return cleanerTasks @@ -246,6 +250,7 @@ func (t *TasksConfig) DRKeyPrefetcher() *periodic.Runner { return nil } prefetchPeriod := t.DRKeyEpochInterval / 2 + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). return periodic.Start( &drkey.Prefetcher{ LocalIA: t.IA, @@ -276,6 +281,7 @@ func StartTasks(cfg TasksConfig) (*Tasks, error) { Originator: cfg.Originator(), Propagator: cfg.Propagator(), Registrars: cfg.SegmentWriters(), + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). PathCleaner: periodic.Start( periodic.Func{ Task: func(ctx context.Context) { diff --git a/control/trust/main_test.go b/control/trust/main_test.go index 42b29a0432..afe9d7770b 100644 --- a/control/trust/main_test.go +++ b/control/trust/main_test.go @@ -37,7 +37,8 @@ func genCrypto(t *testing.T) string { "--isd-dir", "--as-validity", "1y", }) - cmd.SetOutput(&buf) + cmd.SetOut(&buf) + cmd.SetErr(&buf) err := cmd.Execute() require.NoError(t, err, buf.String()) diff --git a/daemon/cmd/daemon/main.go b/daemon/cmd/daemon/main.go index 0ed7ba7746..f926377dee 100644 --- a/daemon/cmd/daemon/main.go +++ b/daemon/cmd/daemon/main.go @@ -117,9 +117,11 @@ func realMain(ctx context.Context) error { }) defer pathDB.Close() defer revCache.Close() + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). cleaner := periodic.Start(pathdb.NewCleaner(pathDB, "sd_segments"), 300*time.Second, 295*time.Second) defer cleaner.Stop() + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). rcCleaner := periodic.Start(revcache.NewCleaner(revCache, "sd_revocation"), 10*time.Second, 10*time.Second) defer rcCleaner.Stop() @@ -169,6 +171,7 @@ func realMain(ctx context.Context) error { Dir: filepath.Join(globalCfg.General.ConfigDir, "certs"), DB: trustDB, } + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). trcLoaderTask := periodic.Start(periodic.Func{ Task: func(ctx context.Context) { res, err := trcLoader.Load(ctx) @@ -222,6 +225,8 @@ func realMain(ctx context.Context) error { } cleaners := drkeyClientEngine.CreateStorageCleaners() for _, cleaner := range cleaners { + // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). + //nolint:staticcheck cleaner_task := periodic.Start(cleaner, 5*time.Minute, 5*time.Minute) defer cleaner_task.Stop() diff --git a/daemon/internal/servers/grpc.go b/daemon/internal/servers/grpc.go index e04759ca8a..36dfadbccc 100644 --- a/daemon/internal/servers/grpc.go +++ b/daemon/internal/servers/grpc.go @@ -36,8 +36,7 @@ import ( "github.com/scionproto/scion/pkg/private/prom" "github.com/scionproto/scion/pkg/private/serrors" "github.com/scionproto/scion/pkg/private/util" - pb_daemon "github.com/scionproto/scion/pkg/proto/daemon" - sdpb "github.com/scionproto/scion/pkg/proto/daemon" + "github.com/scionproto/scion/pkg/proto/daemon" "github.com/scionproto/scion/pkg/segment/iface" "github.com/scionproto/scion/pkg/snet" snetpath "github.com/scionproto/scion/pkg/snet/path" @@ -71,8 +70,8 @@ type DaemonServer struct { // Paths serves the paths request. func (s *DaemonServer) Paths(ctx context.Context, - req *sdpb.PathsRequest, -) (*sdpb.PathsResponse, error) { + req *daemon.PathsRequest, +) (*daemon.PathsResponse, error) { start := time.Now() dstI := addr.IA(req.DestinationIsdAs).ISD() response, err := s.paths(ctx, req) @@ -84,8 +83,8 @@ func (s *DaemonServer) Paths(ctx context.Context, } func (s *DaemonServer) paths(ctx context.Context, - req *sdpb.PathsRequest, -) (*sdpb.PathsResponse, error) { + req *daemon.PathsRequest, +) (*daemon.PathsResponse, error) { if _, ok := ctx.Deadline(); !ok { var cancelF context.CancelFunc ctx, cancelF = context.WithTimeout(ctx, 10*time.Second) @@ -102,7 +101,7 @@ func (s *DaemonServer) paths(ctx context.Context, "src", srcIA, "dst", dstIA, "refresh", req.Refresh) return nil, err } - reply := &sdpb.PathsResponse{} + reply := &daemon.PathsResponse{} for _, p := range paths { reply.Paths = append(reply.Paths, pathToPB(p)) } @@ -126,11 +125,11 @@ func (s *DaemonServer) fetchPaths( return paths, err } -func pathToPB(path snet.Path) *sdpb.Path { +func pathToPB(path snet.Path) *daemon.Path { meta := path.Metadata() - interfaces := make([]*sdpb.PathInterface, len(meta.Interfaces)) + interfaces := make([]*daemon.PathInterface, len(meta.Interfaces)) for i, intf := range meta.Interfaces { - interfaces[i] = &sdpb.PathInterface{ + interfaces[i] = &daemon.PathInterface{ Id: uint64(intf.ID), IsdAs: uint64(intf.IA), } @@ -142,15 +141,15 @@ func pathToPB(path snet.Path) *sdpb.Path { nanos := int32(v - time.Duration(seconds)*time.Second) latency[i] = &durationpb.Duration{Seconds: seconds, Nanos: nanos} } - geo := make([]*sdpb.GeoCoordinates, len(meta.Geo)) + geo := make([]*daemon.GeoCoordinates, len(meta.Geo)) for i, v := range meta.Geo { - geo[i] = &sdpb.GeoCoordinates{ + geo[i] = &daemon.GeoCoordinates{ Latitude: v.Latitude, Longitude: v.Longitude, Address: v.Address, } } - linkType := make([]sdpb.LinkType, len(meta.LinkType)) + linkType := make([]daemon.LinkType, len(meta.LinkType)) for i, v := range meta.LinkType { linkType[i] = linkTypeToPB(v) } @@ -165,15 +164,15 @@ func pathToPB(path snet.Path) *sdpb.Path { nextHopStr = nextHop.String() } - epicAuths := &sdpb.EpicAuths{ + epicAuths := &daemon.EpicAuths{ AuthPhvf: append([]byte(nil), meta.EpicAuths.AuthPHVF...), AuthLhvf: append([]byte(nil), meta.EpicAuths.AuthLHVF...), } - return &sdpb.Path{ + return &daemon.Path{ Raw: raw, - Interface: &sdpb.Interface{ - Address: &sdpb.Underlay{Address: nextHopStr}, + Interface: &daemon.Interface{ + Address: &daemon.Underlay{Address: nextHopStr}, }, Interfaces: interfaces, Mtu: uint32(meta.MTU), @@ -188,16 +187,16 @@ func pathToPB(path snet.Path) *sdpb.Path { } } -func linkTypeToPB(lt snet.LinkType) sdpb.LinkType { +func linkTypeToPB(lt snet.LinkType) daemon.LinkType { switch lt { case snet.LinkTypeDirect: - return sdpb.LinkType_LINK_TYPE_DIRECT + return daemon.LinkType_LINK_TYPE_DIRECT case snet.LinkTypeMultihop: - return sdpb.LinkType_LINK_TYPE_MULTI_HOP + return daemon.LinkType_LINK_TYPE_MULTI_HOP case snet.LinkTypeOpennet: - return sdpb.LinkType_LINK_TYPE_OPEN_NET + return daemon.LinkType_LINK_TYPE_OPEN_NET default: - return sdpb.LinkType_LINK_TYPE_UNSPECIFIED + return daemon.LinkType_LINK_TYPE_UNSPECIFIED } } @@ -226,7 +225,7 @@ func (s *DaemonServer) backgroundPaths(origCtx context.Context, src, dst addr.IA } // AS serves the AS request. -func (s *DaemonServer) AS(ctx context.Context, req *sdpb.ASRequest) (*sdpb.ASResponse, error) { +func (s *DaemonServer) AS(ctx context.Context, req *daemon.ASRequest) (*daemon.ASResponse, error) { start := time.Now() response, err := s.as(ctx, req) s.Metrics.ASRequests.inc( @@ -236,7 +235,7 @@ func (s *DaemonServer) AS(ctx context.Context, req *sdpb.ASRequest) (*sdpb.ASRes return response, unwrapMetricsError(err) } -func (s *DaemonServer) as(ctx context.Context, req *sdpb.ASRequest) (*sdpb.ASResponse, error) { +func (s *DaemonServer) as(ctx context.Context, req *daemon.ASRequest) (*daemon.ASResponse, error) { reqIA := addr.IA(req.IsdAs) if reqIA.IsZero() { reqIA = s.IA @@ -250,7 +249,7 @@ func (s *DaemonServer) as(ctx context.Context, req *sdpb.ASRequest) (*sdpb.ASRes log.FromCtx(ctx).Error("Inspecting ISD-AS", "err", err, "isd_as", reqIA) return nil, serrors.Wrap("inspecting ISD-AS", err, "isd_as", reqIA) } - reply := &sdpb.ASResponse{ + reply := &daemon.ASResponse{ IsdAs: uint64(reqIA), Core: core, Mtu: mtu, @@ -260,8 +259,8 @@ func (s *DaemonServer) as(ctx context.Context, req *sdpb.ASRequest) (*sdpb.ASRes // Interfaces serves the interfaces request. func (s *DaemonServer) Interfaces(ctx context.Context, - req *sdpb.InterfacesRequest, -) (*sdpb.InterfacesResponse, error) { + req *daemon.InterfacesRequest, +) (*daemon.InterfacesResponse, error) { start := time.Now() response, err := s.interfaces(ctx, req) s.Metrics.InterfacesRequests.inc( @@ -272,10 +271,10 @@ func (s *DaemonServer) Interfaces(ctx context.Context, } func (s *DaemonServer) interfaces(ctx context.Context, - _ *sdpb.InterfacesRequest, -) (*sdpb.InterfacesResponse, error) { - reply := &sdpb.InterfacesResponse{ - Interfaces: make(map[uint64]*sdpb.Interface), + _ *daemon.InterfacesRequest, +) (*daemon.InterfacesResponse, error) { + reply := &daemon.InterfacesResponse{ + Interfaces: make(map[uint64]*daemon.Interface), } topo := s.Topology for _, ifID := range topo.IfIDs() { @@ -283,8 +282,8 @@ func (s *DaemonServer) interfaces(ctx context.Context, if nextHop == nil { continue } - reply.Interfaces[uint64(ifID)] = &sdpb.Interface{ - Address: &sdpb.Underlay{ + reply.Interfaces[uint64(ifID)] = &daemon.Interface{ + Address: &daemon.Underlay{ Address: nextHop.String(), }, } @@ -294,8 +293,8 @@ func (s *DaemonServer) interfaces(ctx context.Context, // Services serves the services request. func (s *DaemonServer) Services(ctx context.Context, - req *sdpb.ServicesRequest, -) (*sdpb.ServicesResponse, error) { + req *daemon.ServicesRequest, +) (*daemon.ServicesResponse, error) { start := time.Now() respsonse, err := s.services(ctx, req) s.Metrics.ServicesRequests.inc( @@ -306,15 +305,15 @@ func (s *DaemonServer) Services(ctx context.Context, } func (s *DaemonServer) services(ctx context.Context, - _ *sdpb.ServicesRequest, -) (*sdpb.ServicesResponse, error) { - reply := &sdpb.ServicesResponse{ - Services: make(map[string]*sdpb.ListService), + _ *daemon.ServicesRequest, +) (*daemon.ServicesResponse, error) { + reply := &daemon.ServicesResponse{ + Services: make(map[string]*daemon.ListService), } - list := &sdpb.ListService{} + list := &daemon.ListService{} for _, h := range s.Topology.ControlServiceAddresses() { // TODO(lukedirtwalker): build actual URI after it's defined (anapapaya/scion#3587) - list.Services = append(list.Services, &sdpb.Service{Uri: h.String()}) + list.Services = append(list.Services, &daemon.Service{Uri: h.String()}) } reply.Services[topology.Control.String()] = list return reply, nil @@ -322,8 +321,8 @@ func (s *DaemonServer) services(ctx context.Context, // NotifyInterfaceDown notifies the server about an interface that is down. func (s *DaemonServer) NotifyInterfaceDown(ctx context.Context, - req *sdpb.NotifyInterfaceDownRequest, -) (*sdpb.NotifyInterfaceDownResponse, error) { + req *daemon.NotifyInterfaceDownRequest, +) (*daemon.NotifyInterfaceDownResponse, error) { start := time.Now() response, err := s.notifyInterfaceDown(ctx, req) s.Metrics.InterfaceDownNotifications.inc( @@ -334,8 +333,8 @@ func (s *DaemonServer) NotifyInterfaceDown(ctx context.Context, } func (s *DaemonServer) notifyInterfaceDown(ctx context.Context, - req *sdpb.NotifyInterfaceDownRequest, -) (*sdpb.NotifyInterfaceDownResponse, error) { + req *daemon.NotifyInterfaceDownRequest, +) (*daemon.NotifyInterfaceDownResponse, error) { revInfo := &path_mgmt.RevInfo{ RawIsdas: addr.IA(req.IsdAs), IfID: iface.ID(req.Id), @@ -351,16 +350,16 @@ func (s *DaemonServer) notifyInterfaceDown(ctx context.Context, result: prom.ErrDB, } } - return &sdpb.NotifyInterfaceDownResponse{}, nil + return &daemon.NotifyInterfaceDownResponse{}, nil } // PortRange returns the port range for the dispatched ports. func (s *DaemonServer) PortRange( _ context.Context, _ *emptypb.Empty, -) (*sdpb.PortRangeResponse, error) { +) (*daemon.PortRangeResponse, error) { startPort, endPort := s.Topology.PortRange() - return &sdpb.PortRangeResponse{ + return &daemon.PortRangeResponse{ DispatchedPortStart: uint32(startPort), DispatchedPortEnd: uint32(endPort), }, nil @@ -368,8 +367,8 @@ func (s *DaemonServer) PortRange( func (s *DaemonServer) DRKeyASHost( ctx context.Context, - req *pb_daemon.DRKeyASHostRequest, -) (*pb_daemon.DRKeyASHostResponse, error) { + req *daemon.DRKeyASHostRequest, +) (*daemon.DRKeyASHostResponse, error) { if s.DRKeyClient == nil { return nil, serrors.New("DRKey is not available") } @@ -383,7 +382,7 @@ func (s *DaemonServer) DRKeyASHost( return nil, serrors.Wrap("getting AS-Host from client store", err) } - return &sdpb.DRKeyASHostResponse{ + return &daemon.DRKeyASHostResponse{ EpochBegin: ×tamppb.Timestamp{Seconds: lvl2Key.Epoch.NotBefore.Unix()}, EpochEnd: ×tamppb.Timestamp{Seconds: lvl2Key.Epoch.NotAfter.Unix()}, Key: lvl2Key.Key[:], @@ -392,8 +391,8 @@ func (s *DaemonServer) DRKeyASHost( func (s *DaemonServer) DRKeyHostAS( ctx context.Context, - req *pb_daemon.DRKeyHostASRequest, -) (*pb_daemon.DRKeyHostASResponse, error) { + req *daemon.DRKeyHostASRequest, +) (*daemon.DRKeyHostASResponse, error) { if s.DRKeyClient == nil { return nil, serrors.New("DRKey is not available") } @@ -407,7 +406,7 @@ func (s *DaemonServer) DRKeyHostAS( return nil, serrors.Wrap("getting Host-AS from client store", err) } - return &sdpb.DRKeyHostASResponse{ + return &daemon.DRKeyHostASResponse{ EpochBegin: ×tamppb.Timestamp{Seconds: lvl2Key.Epoch.NotBefore.Unix()}, EpochEnd: ×tamppb.Timestamp{Seconds: lvl2Key.Epoch.NotAfter.Unix()}, Key: lvl2Key.Key[:], @@ -416,8 +415,8 @@ func (s *DaemonServer) DRKeyHostAS( func (s *DaemonServer) DRKeyHostHost( ctx context.Context, - req *pb_daemon.DRKeyHostHostRequest, -) (*pb_daemon.DRKeyHostHostResponse, error) { + req *daemon.DRKeyHostHostRequest, +) (*daemon.DRKeyHostHostResponse, error) { if s.DRKeyClient == nil { return nil, serrors.New("DRKey is not available") } @@ -430,14 +429,14 @@ func (s *DaemonServer) DRKeyHostHost( return nil, serrors.Wrap("getting Host-Host from client store", err) } - return &sdpb.DRKeyHostHostResponse{ + return &daemon.DRKeyHostHostResponse{ EpochBegin: ×tamppb.Timestamp{Seconds: lvl2Key.Epoch.NotBefore.Unix()}, EpochEnd: ×tamppb.Timestamp{Seconds: lvl2Key.Epoch.NotAfter.Unix()}, Key: lvl2Key.Key[:], }, nil } -func requestToASHostMeta(req *sdpb.DRKeyASHostRequest) (drkey.ASHostMeta, error) { +func requestToASHostMeta(req *daemon.DRKeyASHostRequest) (drkey.ASHostMeta, error) { err := req.ValTime.CheckValid() if err != nil { return drkey.ASHostMeta{}, serrors.Wrap("invalid valTime from pb request", err) @@ -451,7 +450,7 @@ func requestToASHostMeta(req *sdpb.DRKeyASHostRequest) (drkey.ASHostMeta, error) }, nil } -func requestToHostASMeta(req *sdpb.DRKeyHostASRequest) (drkey.HostASMeta, error) { +func requestToHostASMeta(req *daemon.DRKeyHostASRequest) (drkey.HostASMeta, error) { err := req.ValTime.CheckValid() if err != nil { return drkey.HostASMeta{}, serrors.Wrap("invalid valTime from pb request", err) @@ -465,7 +464,7 @@ func requestToHostASMeta(req *sdpb.DRKeyHostASRequest) (drkey.HostASMeta, error) }, nil } -func requestToHostHostMeta(req *sdpb.DRKeyHostHostRequest) (drkey.HostHostMeta, error) { +func requestToHostHostMeta(req *daemon.DRKeyHostHostRequest) (drkey.HostHostMeta, error) { err := req.ValTime.CheckValid() if err != nil { return drkey.HostHostMeta{}, serrors.Wrap("invalid valTime from pb request", err) diff --git a/demo/drkey/main.go b/demo/drkey/main.go index cd42b0dd87..ee6f6e2a22 100644 --- a/demo/drkey/main.go +++ b/demo/drkey/main.go @@ -270,6 +270,7 @@ func (s Server) FetchSV( } // Contact CS directly for SV + //nolint:staticcheck // ignore SA1019; Support remains in 1.x; we won't use v2. conn, err := grpc.DialContext( ctx, cs[0], grpc.WithTransportCredentials(insecure.NewCredentials()), ) diff --git a/gateway/control/enginecontroller_test.go b/gateway/control/enginecontroller_test.go index d81efb421b..6a8032b244 100644 --- a/gateway/control/enginecontroller_test.go +++ b/gateway/control/enginecontroller_test.go @@ -551,4 +551,4 @@ type testPktWriter struct { ID uint8 } -func (_ testPktWriter) Write(gopacket.Packet) {} +func (testPktWriter) Write(gopacket.Packet) {} diff --git a/gateway/control/watcher_test.go b/gateway/control/watcher_test.go index c6559ba7fd..9403f13263 100644 --- a/gateway/control/watcher_test.go +++ b/gateway/control/watcher_test.go @@ -87,10 +87,7 @@ func TestGatewayWatcherRun(t *testing.T) { assert.NoError(t, bg.Wait()) }) - for { - if metrics.GaugeValue(remotes) > 0 { - break - } + for metrics.GaugeValue(remotes) <= 0 { time.Sleep(10 * time.Millisecond) } cancel() diff --git a/gateway/dataplane/encoder.go b/gateway/dataplane/encoder.go index 135f287f72..483a6c9761 100644 --- a/gateway/dataplane/encoder.go +++ b/gateway/dataplane/encoder.go @@ -102,7 +102,7 @@ func (e *encoder) Read() []byte { // Increase the sequence number. e.seq++ // First, use the data remaining from the last packet, if any. - var pos int = hdrLen + pos := hdrLen if len(e.pkt) > 0 { pos += e.copyToFrame() if len(e.pkt) > 0 { diff --git a/gateway/dataplane/routingtable_test.go b/gateway/dataplane/routingtable_test.go index db94e0e490..7a139ef8ed 100644 --- a/gateway/dataplane/routingtable_test.go +++ b/gateway/dataplane/routingtable_test.go @@ -301,7 +301,7 @@ type testPktWriter struct { ID int } -func (_ testPktWriter) Write(gopacket.Packet) {} +func (testPktWriter) Write(gopacket.Packet) {} func (w testPktWriter) String() string { return fmt.Sprintf("%d", w.ID) } diff --git a/gateway/gateway.go b/gateway/gateway.go index 0705a0753e..06bd6a38d1 100644 --- a/gateway/gateway.go +++ b/gateway/gateway.go @@ -282,6 +282,7 @@ func (g *Gateway) Run(ctx context.Context) error { revStore := &pathhealth.MemoryRevocationStore{} // periodically clean up the revocation store. + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). revCleaner := periodic.Start(periodic.Func{ Task: revStore.Cleanup, TaskName: "revocation_store_cleaner", diff --git a/gateway/routemgr/device.go b/gateway/routemgr/device.go index 6b993db0e7..fdbaba218f 100644 --- a/gateway/routemgr/device.go +++ b/gateway/routemgr/device.go @@ -57,7 +57,7 @@ type deviceHandle struct { func (h *deviceHandle) Close() error { // The callback runs outside the mutex, thus avoiding deadlocks in deviceHandle // methods if for whatever reason the destruction callback blocks. - err, destructionF := h.innerClose() + destructionF, err := h.innerClose() if destructionF != nil { destructionF() } @@ -66,17 +66,17 @@ func (h *deviceHandle) Close() error { // innerClose closes the base handle and returns a cleanup function. The cleanup // function must always be executed, even if the error return value is non-nil. -func (h *deviceHandle) innerClose() (error, destructionCallback) { +func (h *deviceHandle) innerClose() (destructionCallback, error) { h.mtx.Lock() defer h.mtx.Unlock() if h.refCount == 0 { - return serrors.New("handle closed too many times"), nil + return nil, serrors.New("handle closed too many times") } h.refCount-- if h.refCount == 0 { - return h.base.Close(), h.destructionCallback + return h.destructionCallback, h.base.Close() } return nil, nil } diff --git a/pkg/drkey/specific/specific.go b/pkg/drkey/specific/specific.go index 7d517e9023..04ea4c2f55 100644 --- a/pkg/drkey/specific/specific.go +++ b/pkg/drkey/specific/specific.go @@ -59,13 +59,13 @@ func (d Deriver) DeriveASHost( } // DeriveHostAS returns the HostAS derived key. -func (p Deriver) DeriveHostAS(srcHost string, key drkey.Key) (drkey.Key, error) { +func (d Deriver) DeriveHostAS(srcHost string, key drkey.Key) (drkey.Key, error) { host, err := addr.ParseHost(srcHost) if err != nil { return drkey.Key{}, serrors.Wrap("parsing src host", err) } buf := make([]byte, 32) - l, err := p.serializeLevel2Input(buf, drkey.HostAS, host) + l, err := d.serializeLevel2Input(buf, drkey.HostAS, host) if err != nil { return drkey.Key{}, serrors.Wrap("serializing drkey level 2 input", err) } diff --git a/pkg/experimental/hiddenpath/grpc/discovery_test.go b/pkg/experimental/hiddenpath/grpc/discovery_test.go index ef09cb0a5b..2ffca55b7c 100644 --- a/pkg/experimental/hiddenpath/grpc/discovery_test.go +++ b/pkg/experimental/hiddenpath/grpc/discovery_test.go @@ -27,7 +27,6 @@ import ( hpgrpc "github.com/scionproto/scion/pkg/experimental/hiddenpath/grpc" "github.com/scionproto/scion/pkg/private/xtest" "github.com/scionproto/scion/pkg/proto/discovery" - dspb "github.com/scionproto/scion/pkg/proto/discovery" "github.com/scionproto/scion/pkg/proto/discovery/mock_discovery" ) @@ -38,15 +37,15 @@ func TestDiscovererDiscover(t *testing.T) { assertErr assert.ErrorAssertionFunc }{ "valid both entries": { - server: func(ctrl *gomock.Controller) dspb.DiscoveryServiceServer { + server: func(ctrl *gomock.Controller) discovery.DiscoveryServiceServer { s := mock_discovery.NewMockDiscoveryServiceServer(ctrl) s.EXPECT().HiddenSegmentServices(gomock.Any(), gomock.Any()).Return( - &dspb.HiddenSegmentServicesResponse{ - Lookup: []*dspb.HiddenSegmentLookupServer{ + &discovery.HiddenSegmentServicesResponse{ + Lookup: []*discovery.HiddenSegmentLookupServer{ {Address: "10.0.0.1:404"}, {Address: "10.0.0.2:405"}, }, - Registration: []*dspb.HiddenSegmentRegistrationServer{ + Registration: []*discovery.HiddenSegmentRegistrationServer{ {Address: "10.0.0.3:404"}, {Address: "10.0.0.4:405"}, }, @@ -74,7 +73,7 @@ func TestDiscovererDiscover(t *testing.T) { ctrl := gomock.NewController(t) svc := xtest.NewGRPCService() - dspb.RegisterDiscoveryServiceServer(svc.Server(), tc.server(ctrl)) + discovery.RegisterDiscoveryServiceServer(svc.Server(), tc.server(ctrl)) svc.Start(t) d := hpgrpc.Discoverer{Dialer: svc} diff --git a/pkg/experimental/hiddenpath/grpc/registerer.go b/pkg/experimental/hiddenpath/grpc/registerer.go index a74485eb36..2c161246ea 100644 --- a/pkg/experimental/hiddenpath/grpc/registerer.go +++ b/pkg/experimental/hiddenpath/grpc/registerer.go @@ -26,7 +26,6 @@ import ( "github.com/scionproto/scion/pkg/private/serrors" "github.com/scionproto/scion/pkg/proto/control_plane" cryptopb "github.com/scionproto/scion/pkg/proto/crypto" - hppb "github.com/scionproto/scion/pkg/proto/hidden_segment" hspb "github.com/scionproto/scion/pkg/proto/hidden_segment" seg "github.com/scionproto/scion/pkg/segment" ) @@ -68,7 +67,7 @@ func (s Registerer) RegisterSegment(ctx context.Context, client := hspb.NewHiddenSegmentRegistrationServiceClient(conn) body := &hspb.HiddenSegmentRegistrationRequestBody{ GroupId: reg.GroupID.ToUint64(), - Segments: map[int32]*hppb.Segments{ + Segments: map[int32]*hspb.Segments{ int32(reg.Seg.Type): {Segments: []*control_plane.PathSegment{ seg.PathSegmentToPB(reg.Seg.Segment), }}, diff --git a/pkg/experimental/hiddenpath/grpc/registerer_test.go b/pkg/experimental/hiddenpath/grpc/registerer_test.go index 27e9dbcc40..da85a220b9 100644 --- a/pkg/experimental/hiddenpath/grpc/registerer_test.go +++ b/pkg/experimental/hiddenpath/grpc/registerer_test.go @@ -33,9 +33,8 @@ import ( "github.com/scionproto/scion/pkg/private/xtest" "github.com/scionproto/scion/pkg/private/xtest/graph" cryptopb "github.com/scionproto/scion/pkg/proto/crypto" - "github.com/scionproto/scion/pkg/proto/hidden_segment" hspb "github.com/scionproto/scion/pkg/proto/hidden_segment" - "github.com/scionproto/scion/pkg/proto/hidden_segment/mock_hidden_segment" + mockhspb "github.com/scionproto/scion/pkg/proto/hidden_segment/mock_hidden_segment" seg "github.com/scionproto/scion/pkg/segment" "github.com/scionproto/scion/pkg/slayers/path" ) @@ -43,16 +42,16 @@ import ( func TestRegistererRegisterSegment(t *testing.T) { testCases := map[string]struct { input hiddenpath.SegmentRegistration - hpServer func(*gomock.Controller) hidden_segment.HiddenSegmentRegistrationServiceServer + hpServer func(*gomock.Controller) hspb.HiddenSegmentRegistrationServiceServer signer func(ctrl *gomock.Controller) hpgrpc.Signer regular func(*gomock.Controller) beaconing.RPC assertErr assert.ErrorAssertionFunc }{ "valid hidden": { hpServer: func(c *gomock.Controller) hspb.HiddenSegmentRegistrationServiceServer { - s := mock_hidden_segment.NewMockHiddenSegmentRegistrationServiceServer(c) + s := mockhspb.NewMockHiddenSegmentRegistrationServiceServer(c) s.EXPECT().HiddenSegmentRegistration(gomock.Any(), gomock.Any()). - Return(&hidden_segment.HiddenSegmentRegistrationResponse{}, nil) + Return(&hspb.HiddenSegmentRegistrationResponse{}, nil) return s }, signer: func(ctrl *gomock.Controller) hpgrpc.Signer { @@ -74,9 +73,9 @@ func TestRegistererRegisterSegment(t *testing.T) { }, "valid public": { hpServer: func(c *gomock.Controller) hspb.HiddenSegmentRegistrationServiceServer { - s := mock_hidden_segment.NewMockHiddenSegmentRegistrationServiceServer(c) + s := mockhspb.NewMockHiddenSegmentRegistrationServiceServer(c) s.EXPECT().HiddenSegmentRegistration(gomock.Any(), gomock.Any()). - Return(&hidden_segment.HiddenSegmentRegistrationResponse{}, nil).Times(0) + Return(&hspb.HiddenSegmentRegistrationResponse{}, nil).Times(0) return s }, signer: func(ctrl *gomock.Controller) hpgrpc.Signer { diff --git a/pkg/experimental/hiddenpath/grpc/requester_test.go b/pkg/experimental/hiddenpath/grpc/requester_test.go index 41b975818b..26d02cf8ba 100644 --- a/pkg/experimental/hiddenpath/grpc/requester_test.go +++ b/pkg/experimental/hiddenpath/grpc/requester_test.go @@ -31,7 +31,7 @@ import ( "github.com/scionproto/scion/pkg/private/xtest" cryptopb "github.com/scionproto/scion/pkg/proto/crypto" hspb "github.com/scionproto/scion/pkg/proto/hidden_segment" - "github.com/scionproto/scion/pkg/proto/hidden_segment/mock_hidden_segment" + mockhspb "github.com/scionproto/scion/pkg/proto/hidden_segment/mock_hidden_segment" seg "github.com/scionproto/scion/pkg/segment" "github.com/scionproto/scion/private/segment/segfetcher" "github.com/scionproto/scion/private/segment/segfetcher/mock_segfetcher" @@ -109,7 +109,7 @@ func TestRequesterSegments(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - server := mock_hidden_segment.NewMockHiddenSegmentLookupServiceServer(ctrl) + server := mockhspb.NewMockHiddenSegmentLookupServiceServer(ctrl) server.EXPECT().HiddenSegments(gomock.Any(), gomock.Any()). Return(&hspb.HiddenSegmentsResponse{ Segments: hpgrpc.ToHSPB([]*seg.Meta{&testSeg}), @@ -158,7 +158,7 @@ func TestAuthoritativeRequesterHiddenSegments(t *testing.T) { server: func( ctrl *gomock.Controller, ) hspb.AuthoritativeHiddenSegmentLookupServiceServer { - s := mock_hidden_segment.NewMockAuthoritativeHiddenSegmentLookupServiceServer(ctrl) + s := mockhspb.NewMockAuthoritativeHiddenSegmentLookupServiceServer(ctrl) s.EXPECT().AuthoritativeHiddenSegments(gomock.Any(), gomock.Any()). Return(&hspb.AuthoritativeHiddenSegmentsResponse{ Segments: hpgrpc.ToHSPB([]*seg.Meta{&testSeg}), diff --git a/pkg/grpc/dialer.go b/pkg/grpc/dialer.go index 08f9f44c3a..f758f9f6a1 100644 --- a/pkg/grpc/dialer.go +++ b/pkg/grpc/dialer.go @@ -43,8 +43,10 @@ type SimpleDialer struct{} // Dial dials the address by converting it to a string. func (SimpleDialer) Dial(ctx context.Context, address net.Addr) (*grpc.ClientConn, error) { + //nolint:staticcheck // ignore SA1019; Support remains in 1.x; we won't use v2. return grpc.DialContext(ctx, address.String(), grpc.WithTransportCredentials(insecure.NewCredentials()), + //nolint:staticcheck // ignore SA1019; Support remains in 1.x; we won't use v2. grpc.WithBlock(), UnaryClientInterceptor(), StreamClientInterceptor(), @@ -105,6 +107,7 @@ func (t *TCPDialer) Dial(ctx context.Context, dst net.Addr) (*grpc.ClientConn, e r := manual.NewBuilderWithScheme("svc") r.InitialState(resolver.State{Addresses: targets}) + //nolint:staticcheck // ignore SA1019; Support remains in 1.x; we won't use v2. return grpc.DialContext(ctx, r.Scheme()+":///"+v.SVC.BaseString(), grpc.WithDefaultServiceConfig(`{"loadBalancingConfig": [{"round_robin":{}}]}`), grpc.WithTransportCredentials(insecure.NewCredentials()), @@ -114,6 +117,7 @@ func (t *TCPDialer) Dial(ctx context.Context, dst net.Addr) (*grpc.ClientConn, e ) } + //nolint:staticcheck // ignore SA1019; Support remains in 1.x; we won't use v2. return grpc.DialContext(ctx, dst.String(), grpc.WithTransportCredentials(insecure.NewCredentials()), UnaryClientInterceptor(), @@ -155,6 +159,7 @@ func (d *QUICDialer) Dial(ctx context.Context, addr net.Addr) (*grpc.ClientConn, dialer := func(context.Context, string) (net.Conn, error) { return d.Dialer.Dial(ctx, addr) } + //nolint:staticcheck // ignore SA1019; Support remains in 1.x; we won't use v2. return grpc.DialContext(ctx, addr.String(), grpc.WithTransportCredentials(PassThroughCredentials{}), grpc.WithContextDialer(dialer), diff --git a/pkg/private/serrors/errors.go b/pkg/private/serrors/errors.go index abf6c8d5b1..cf387afef5 100644 --- a/pkg/private/serrors/errors.go +++ b/pkg/private/serrors/errors.go @@ -133,8 +133,8 @@ func mkErrorInfo(cause error, addStack bool, errCtx ...any) errorInfo { // basicError was without a stack trace, then there'll never be one. That's to avoid looking // for it in every level or every constructor. TB revisisted if necessary. // TODO(jiceatscion): should we define a "stackertracer" interface? - if r.cause == nil || !(errors.As(cause, &t1) || errors.As(cause, &t2) || - errors.As(cause, &t3) || errors.As(cause, &t4)) { + if r.cause == nil || (!errors.As(cause, &t1) && !errors.As(cause, &t2) && + !errors.As(cause, &t3) && !errors.As(cause, &t4)) { r.stack = callers() } diff --git a/pkg/private/xtest/graph/graph.go b/pkg/private/xtest/graph/graph.go index 0fdf70a4cc..4438a9dac2 100644 --- a/pkg/private/xtest/graph/graph.go +++ b/pkg/private/xtest/graph/graph.go @@ -193,11 +193,7 @@ func (g *Graph) GetPaths(xIA string, yIA string) [][]uint16 { newSolution(src), } var solution [][]uint16 - for { - if len(queue) == 0 { - // Nothing left to explore. - break - } + for len(queue) != 0 { // Explore the next element in the queue. curSolution := queue[0] queue = queue[1:] diff --git a/pkg/private/xtest/grpc.go b/pkg/private/xtest/grpc.go index 0b697997bb..688c3630dd 100644 --- a/pkg/private/xtest/grpc.go +++ b/pkg/private/xtest/grpc.go @@ -95,6 +95,7 @@ func (s *GRPCService) Dial(ctx context.Context, addr net.Addr) (*grpc.ClientConn } else { transportSecurity = grpc.WithTransportCredentials(insecure.NewCredentials()) } + //nolint:staticcheck // ignore SA1019; Support remains in 1.x; we won't use v2. return grpc.DialContext(ctx, addr.String(), grpc.WithContextDialer( func(context.Context, string) (net.Conn, error) { diff --git a/pkg/scrypto/cms/protocol/protocol_test.go b/pkg/scrypto/cms/protocol/protocol_test.go index fb15a13b34..a67a92b017 100644 --- a/pkg/scrypto/cms/protocol/protocol_test.go +++ b/pkg/scrypto/cms/protocol/protocol_test.go @@ -9,7 +9,6 @@ import ( "io" "strings" "testing" - "time" "golang.org/x/crypto/pkcs12" @@ -361,10 +360,9 @@ func testParseContentInfo(t *testing.T, der []byte) { t.Fatalf("unknown signature algorithm") } - var nilTime time.Time if st, errr := si.GetSigningTimeAttribute(); errr != nil { t.Fatal(errr) - } else if st == nilTime { + } else if st.IsZero() { t.Fatal("0 value signing time") } } diff --git a/pkg/scrypto/cppki/ca.go b/pkg/scrypto/cppki/ca.go index c7bbcbdb86..14700c1b32 100644 --- a/pkg/scrypto/cppki/ca.go +++ b/pkg/scrypto/cppki/ca.go @@ -122,7 +122,7 @@ func (ca CAPolicy) Equal(o CAPolicy) bool { } return certEqual && ca.Validity == o.Validity && - ca.CurrentTime == o.CurrentTime + ca.CurrentTime.Equal(o.CurrentTime) } // SubjectKeyID computes a subject key identifier for a given public key. @@ -131,6 +131,8 @@ func (ca CAPolicy) Equal(o CAPolicy) bool { func SubjectKeyID(pub crypto.PublicKey) ([]byte, error) { switch k := pub.(type) { case *ecdsa.PublicKey: + // SA1019: fix later (https://github.com/scionproto/scion/issues/4777). + //nolint:staticcheck skid := sha1.Sum(elliptic.Marshal(k.Curve, k.X, k.Y)) return skid[:], nil default: diff --git a/pkg/scrypto/cppki/trc_asn1.go b/pkg/scrypto/cppki/trc_asn1.go index a53cbd26e5..d87920abb2 100644 --- a/pkg/scrypto/cppki/trc_asn1.go +++ b/pkg/scrypto/cppki/trc_asn1.go @@ -106,40 +106,40 @@ func DecodeTRC(raw []byte) (TRC, error) { } // Encode encodes the payload in ASN.1 DER format. -func (pld *TRC) Encode() ([]byte, error) { - if err := pld.Validate(); err != nil { +func (trc *TRC) Encode() ([]byte, error) { + if err := trc.Validate(); err != nil { return nil, err } - certs, err := encodeCertificates(pld.Certificates) + certs, err := encodeCertificates(trc.Certificates) if err != nil { return nil, err } - cores, err := encodeASes(pld.CoreASes) + cores, err := encodeASes(trc.CoreASes) if err != nil { return nil, err } - auths, err := encodeASes(pld.AuthoritativeASes) + auths, err := encodeASes(trc.AuthoritativeASes) if err != nil { return nil, err } a := asn1TRCPayload{ - Version: int64(pld.Version - 1), + Version: int64(trc.Version - 1), ID: asn1ID{ - ISD: int64(pld.ID.ISD), - Serial: int64(pld.ID.Serial), - Base: int64(pld.ID.Base), + ISD: int64(trc.ID.ISD), + Serial: int64(trc.ID.Serial), + Base: int64(trc.ID.Base), }, Validity: asn1Validity{ - NotBefore: pld.Validity.NotBefore.UTC().Truncate(time.Second), - NotAfter: pld.Validity.NotAfter.UTC().Truncate(time.Second), + NotBefore: trc.Validity.NotBefore.UTC().Truncate(time.Second), + NotAfter: trc.Validity.NotAfter.UTC().Truncate(time.Second), }, - GracePeriod: int64(pld.GracePeriod / time.Second), - NoTrustReset: pld.NoTrustReset, - Votes: encodeVotes(pld.Votes), - Quorum: int64(pld.Quorum), + GracePeriod: int64(trc.GracePeriod / time.Second), + NoTrustReset: trc.NoTrustReset, + Votes: encodeVotes(trc.Votes), + Quorum: int64(trc.Quorum), CoreASes: cores, AuthoritativeASes: auths, - Description: pld.Description, + Description: trc.Description, Certificates: certs, } return asn1.Marshal(a) diff --git a/pkg/segment/extensions/epic/epic.go b/pkg/segment/extensions/epic/epic.go index 622e62b965..d8811af163 100644 --- a/pkg/segment/extensions/epic/epic.go +++ b/pkg/segment/extensions/epic/epic.go @@ -89,7 +89,7 @@ func (ed *Detached) DigestInput() ([]byte, error) { bufSize := 2 + (1+len(ed.AuthPeerEntries))*AuthLen b := make([]byte, bufSize) - var totalLen uint16 = uint16(1 + len(ed.AuthPeerEntries)) + totalLen := uint16(1 + len(ed.AuthPeerEntries)) binary.BigEndian.PutUint16(b, totalLen) if len(ed.AuthHopEntry) != AuthLen { diff --git a/pkg/slayers/extn.go b/pkg/slayers/extn.go index 1431ad82bd..02a17355d6 100644 --- a/pkg/slayers/extn.go +++ b/pkg/slayers/extn.go @@ -347,9 +347,10 @@ func decodeEndToEndExtn(data []byte, p gopacket.PacketBuilder) error { } func checkEndToEndExtnNextHdr(t L4ProtocolType) error { - if t == HopByHopClass { + switch t { + case HopByHopClass: return serrors.New("e2e extension must not come before the HBH extension") - } else if t == End2EndClass { + case End2EndClass: return serrors.New("e2e extension must not be repeated") } return nil @@ -403,7 +404,7 @@ func (s *HopByHopExtnSkipper) DecodeFromBytes(data []byte, df gopacket.DecodeFee return nil } -func (e *HopByHopExtnSkipper) LayerType() gopacket.LayerType { +func (s *HopByHopExtnSkipper) LayerType() gopacket.LayerType { return LayerTypeHopByHopExtn } @@ -411,8 +412,8 @@ func (s *HopByHopExtnSkipper) CanDecode() gopacket.LayerClass { return LayerClassHopByHopExtn } -func (h *HopByHopExtnSkipper) NextLayerType() gopacket.LayerType { - return scionNextLayerTypeAfterHBH(h.NextHdr) +func (s *HopByHopExtnSkipper) NextLayerType() gopacket.LayerType { + return scionNextLayerTypeAfterHBH(s.NextHdr) } // EndToEndExtnSkipper is a DecodingLayer which decodes an EndToEnd extension @@ -436,7 +437,7 @@ func (s *EndToEndExtnSkipper) DecodeFromBytes(data []byte, df gopacket.DecodeFee return nil } -func (e *EndToEndExtnSkipper) LayerType() gopacket.LayerType { +func (s *EndToEndExtnSkipper) LayerType() gopacket.LayerType { return LayerTypeEndToEndExtn } @@ -444,6 +445,6 @@ func (s *EndToEndExtnSkipper) CanDecode() gopacket.LayerClass { return LayerClassEndToEndExtn } -func (e *EndToEndExtnSkipper) NextLayerType() gopacket.LayerType { - return scionNextLayerTypeAfterE2E(e.NextHdr) +func (s *EndToEndExtnSkipper) NextLayerType() gopacket.LayerType { + return scionNextLayerTypeAfterE2E(s.NextHdr) } diff --git a/pkg/slayers/scion.go b/pkg/slayers/scion.go index 5680fdca1e..5511d87ea6 100644 --- a/pkg/slayers/scion.go +++ b/pkg/slayers/scion.go @@ -57,8 +57,8 @@ type AddrType uint8 // AddrType constants const ( T4Ip AddrType = 0b0000 // T=0, L=0 - T4Svc = 0b0100 // T=1, L=0 - T16Ip = 0b0011 // T=0, L=3 + T4Svc AddrType = 0b0100 // T=1, L=0 + T16Ip AddrType = 0b0011 // T=0, L=3 ) // Length returns the length of this AddrType value. diff --git a/pkg/slayers/udp.go b/pkg/slayers/udp.go index 60a348c30d..fa516fc722 100644 --- a/pkg/slayers/udp.go +++ b/pkg/slayers/udp.go @@ -57,7 +57,7 @@ func (u *UDP) TransportFlow() gopacket.Flow { func (u *UDP) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { if len(data) < 8 { df.SetTruncated() - return fmt.Errorf("Invalid UDP header. Length %d less than 8", len(data)) + return fmt.Errorf("invalid UDP header. Length %d less than 8", len(data)) } u.SrcPort = binary.BigEndian.Uint16(data[0:2]) u.sPort = data[0:2] diff --git a/pkg/snet/squic/net_test.go b/pkg/snet/squic/net_test.go index 7951fcd422..3fc6d40a21 100644 --- a/pkg/snet/squic/net_test.go +++ b/pkg/snet/squic/net_test.go @@ -77,6 +77,7 @@ func TestAcceptLoopParallelism(t *testing.T) { defer cancel() dialer := connDialer(t) + //nolint:staticcheck // ignore SA1019; Support remains in 1.x; we won't use v2. conn, err := grpc.DialContext(ctx, "server", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { @@ -129,6 +130,7 @@ func TestGRPCQUIC(t *testing.T) { }() dialer := connDialer(t) + //nolint:staticcheck // ignore SA1019; Support remains in 1.x; we won't use v2. conn, err := grpc.DialContext(context.Background(), "server", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { diff --git a/private/app/launcher/launcher.go b/private/app/launcher/launcher.go index 29b4e1adc1..de0b899809 100644 --- a/private/app/launcher/launcher.go +++ b/private/app/launcher/launcher.go @@ -33,7 +33,6 @@ import ( "github.com/scionproto/scion/pkg/private/serrors" "github.com/scionproto/scion/private/app/command" "github.com/scionproto/scion/private/config" - libconfig "github.com/scionproto/scion/private/config" "github.com/scionproto/scion/private/env" ) @@ -53,7 +52,7 @@ type ApplicationBase struct { // supports additional methods (e.g., custom logging or instance ID) and // extract them from the config if that is the case. See the XxxConfig interfaces // in this package for more information. - TOMLConfig libconfig.Config + TOMLConfig config.Config // Samplers contains additional configuration samplers to be included // under the sample subcommand. If empty, no additional samplers are @@ -105,7 +104,7 @@ func (a *ApplicationBase) loadConfig() error { } - if err := libconfig.LoadFile(a.config.GetString(cfgConfigFile), a.TOMLConfig); err != nil { + if err := config.LoadFile(a.config.GetString(cfgConfigFile), a.TOMLConfig); err != nil { return serrors.Wrap("loading config from file", err, "file", a.config.GetString(cfgConfigFile)) diff --git a/private/ca/renewal/main_test.go b/private/ca/renewal/main_test.go index 1c085bbcfd..3c3eb9d124 100644 --- a/private/ca/renewal/main_test.go +++ b/private/ca/renewal/main_test.go @@ -43,7 +43,8 @@ func genCrypto(t *testing.T) string { "-t", "testdata/golden.topo", "-o", dir, }) - cmd.SetOutput(&buf) + cmd.SetOut(&buf) + cmd.SetErr(&buf) err := cmd.Execute() require.NoError(t, err) diff --git a/private/file/periodicview.go b/private/file/periodicview.go index b31bd87941..cbafa0b0c7 100644 --- a/private/file/periodicview.go +++ b/private/file/periodicview.go @@ -79,6 +79,7 @@ func (v *PeriodicView) Get() (any, error) { v.readTask.read() // Launch goroutine for future reads. + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). v.taskRunner = periodic.Start(v.readTask, v.ReadInterval, v.ReadInterval) v.running = true } diff --git a/private/mgmtapi/cppki/api/api.go b/private/mgmtapi/cppki/api/api.go index 7c1e871742..ebeadbf489 100644 --- a/private/mgmtapi/cppki/api/api.go +++ b/private/mgmtapi/cppki/api/api.go @@ -235,7 +235,7 @@ func (s *Server) GetTrcs( ) { db := s.TrustDB - q := truststorage.TRCsQuery{Latest: !(params.All != nil && *params.All)} + q := truststorage.TRCsQuery{Latest: params.All == nil || !*params.All} if params.Isd != nil { q.ISD = make([]addr.ISD, 0, len(*params.Isd)) for _, isd := range *params.Isd { diff --git a/private/path/pathpol/acl.go b/private/path/pathpol/acl.go index 7a07fad96b..8e444bca73 100644 --- a/private/path/pathpol/acl.go +++ b/private/path/pathpol/acl.go @@ -182,13 +182,13 @@ func (ae *ACLEntry) UnmarshalYAML(unmarshal func(any) error) error { } func getAction(symbol string) (ACLAction, error) { - if symbol == allowSymbol { + switch symbol { + case allowSymbol: return true, nil - } else if symbol == denySymbol { + case denySymbol: return false, nil - } else { - return false, serrors.New("Bad action symbol", "action", symbol) } + return false, serrors.New("Bad action symbol", "action", symbol) } // ACLAction has two options: Deny and Allow diff --git a/private/periodic/legacy_metrics.go b/private/periodic/legacy_metrics.go index 7c0c33184a..052e4e1419 100644 --- a/private/periodic/legacy_metrics.go +++ b/private/periodic/legacy_metrics.go @@ -25,7 +25,7 @@ import ( // uses the same old metrics as prior to the introduction of the // StartWithMetrics function. func newLegacyMetrics(prefix string) Metrics { - namespace := strcase.ToSnake(strings.Replace(prefix, ".", "_", -1)) + namespace := strcase.ToSnake(strings.ReplaceAll(prefix, ".", "_")) subsystem := "periodic" events := prometheus.NewCounterVec(prometheus.CounterOpts{ diff --git a/private/storage/storage.go b/private/storage/storage.go index bc400dd462..95f2f6da40 100644 --- a/private/storage/storage.go +++ b/private/storage/storage.go @@ -169,6 +169,7 @@ func NewBeaconStorage(c DBConfig, ia addr.IA) (BeaconDB, error) { SetConnLimits(db, c) // Start a periodic task that cleans up the expired beacons. + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). cleaner := periodic.Start( cleaner.New( func(ctx context.Context) (int, error) { @@ -206,6 +207,7 @@ func NewPathStorage(c DBConfig) (PathDB, error) { SetConnLimits(db, c) // Start a periodic task that cleans up the expired path segments. + //nolint:staticcheck // SA1019: fix later (https://github.com/scionproto/scion/issues/4776). cleaner := periodic.Start( cleaner.New( func(ctx context.Context) (int, error) { diff --git a/private/topology/underlay/defs.go b/private/topology/underlay/defs.go index a6fa30c23b..9ea422661f 100644 --- a/private/topology/underlay/defs.go +++ b/private/topology/underlay/defs.go @@ -44,8 +44,8 @@ const ( EndhostPort = 30041 ) -func (o Type) String() string { - switch o { +func (ot Type) String() string { + switch ot { case UDPIPv4: return UDPIPv4Name case UDPIPv6: @@ -53,7 +53,7 @@ func (o Type) String() string { case UDPIPv46: return UDPIPv46Name default: - return fmt.Sprintf("UNKNOWN (%d)", o) + return fmt.Sprintf("UNKNOWN (%d)", ot) } } diff --git a/private/trust/grpc/main_test.go b/private/trust/grpc/main_test.go index 6150b32c82..3fbfca50a1 100644 --- a/private/trust/grpc/main_test.go +++ b/private/trust/grpc/main_test.go @@ -35,7 +35,8 @@ func genCrypto(t testing.TB) string { "--isd-dir", "--as-validity", "1y", }) - cmd.SetOutput(&buf) + cmd.SetOut(&buf) + cmd.SetErr(&buf) err := cmd.Execute() require.NoError(t, err, buf.String()) diff --git a/private/trust/main_test.go b/private/trust/main_test.go index 392f003418..30e1d57365 100644 --- a/private/trust/main_test.go +++ b/private/trust/main_test.go @@ -45,7 +45,8 @@ func genCrypto(t testing.TB) string { "--isd-dir", "--as-validity", "1y", }) - cmd.SetOutput(&buf) + cmd.SetOut(&buf) + cmd.SetErr(&buf) err := cmd.Execute() require.NoError(t, err, buf.String()) @@ -61,7 +62,8 @@ func genCrypto(t testing.TB) string { "--out=" + filepath.Join(dir, "ISD1/trcs/ISD1-B1-S1.pem.trc"), filepath.Join(dir, "ISD1/trcs/ISD1-B1-S1.trc"), }) - cmd.SetOutput(&buf) + cmd.SetOut(&buf) + cmd.SetErr(&buf) err = cmd.Execute() require.NoError(t, err, buf.String()) diff --git a/private/trust/signer_gen_test.go b/private/trust/signer_gen_test.go index 7f18859ce5..690410a10e 100644 --- a/private/trust/signer_gen_test.go +++ b/private/trust/signer_gen_test.go @@ -61,7 +61,8 @@ func TestSignerGenGenerate(t *testing.T) { filepath.Join(dir, "certs/ISD1-ASff00_0_110-2.pem"), filepath.Join(dir, "ISD1/ASff00_0_110/crypto/as/cp-as-2.key"), }) - cmd.SetOutput(&buf) + cmd.SetOut(&buf) + cmd.SetErr(&buf) err := cmd.Execute() require.NoError(t, err, buf.String()) diff --git a/private/underlay/conn/conn_linux.go b/private/underlay/conn/conn_linux.go index e4980639e8..1faf273af5 100644 --- a/private/underlay/conn/conn_linux.go +++ b/private/underlay/conn/conn_linux.go @@ -35,12 +35,12 @@ import ( // connected to a given remote address, will receive ony traffic from that remote address. // The router's udp/ip underlay uses this, if possible, rather than using the un-connected internal // socket when taking to sibling routers. -func (cc *connUDPBase) initConnUDP( +func (c *connUDPBase) initConnUDP( network string, laddr, raddr netip.AddrPort, cfg *Config) error { - var c *net.UDPConn + var conn *net.UDPConn var err error if !laddr.IsValid() { return serrors.New("listen address must be specified") @@ -66,7 +66,7 @@ func (cc *connUDPBase) initConnUDP( return serrors.Wrap("Error listening on socket", err, "network", network, "listen", laddr) } - c = ci.(*net.UDPConn) + conn = ci.(*net.UDPConn) } else { dialer := net.Dialer{ Control: func(n, a string, rc syscall.RawConn) error { @@ -87,12 +87,12 @@ func (cc *connUDPBase) initConnUDP( return serrors.Wrap("Error listening on socket", err, "network", network, "listen", laddr) } - c = ci.(*net.UDPConn) + conn = ci.(*net.UDPConn) } // Set and confirm send buffer size if cfg.SendBufferSize != 0 { - before, err := sockctrl.GetsockoptInt(c, syscall.SOL_SOCKET, syscall.SO_SNDBUF) + before, err := sockctrl.GetsockoptInt(conn, syscall.SOL_SOCKET, syscall.SO_SNDBUF) if err != nil { return serrors.Wrap("Error getting SO_SNDBUF socket option (before)", err, "listen", laddr, @@ -100,13 +100,13 @@ func (cc *connUDPBase) initConnUDP( ) } target := cfg.SendBufferSize - if err = c.SetWriteBuffer(target); err != nil { + if err = conn.SetWriteBuffer(target); err != nil { return serrors.Wrap("Error setting send buffer size", err, "listen", laddr, "remote", raddr, ) } - after, err := sockctrl.GetsockoptInt(c, syscall.SOL_SOCKET, syscall.SO_SNDBUF) + after, err := sockctrl.GetsockoptInt(conn, syscall.SOL_SOCKET, syscall.SO_SNDBUF) if err != nil { return serrors.Wrap("Error getting SO_SNDBUF socket option (after)", err, "listen", laddr, @@ -126,7 +126,7 @@ func (cc *connUDPBase) initConnUDP( // Set and confirm receive buffer size if cfg.ReceiveBufferSize != 0 { - before, err := sockctrl.GetsockoptInt(c, syscall.SOL_SOCKET, syscall.SO_RCVBUF) + before, err := sockctrl.GetsockoptInt(conn, syscall.SOL_SOCKET, syscall.SO_RCVBUF) if err != nil { return serrors.Wrap("Error getting SO_RCVBUF socket option (before)", err, "listen", laddr, @@ -134,13 +134,13 @@ func (cc *connUDPBase) initConnUDP( ) } target := cfg.ReceiveBufferSize - if err = c.SetReadBuffer(target); err != nil { + if err = conn.SetReadBuffer(target); err != nil { return serrors.Wrap("Error setting recv buffer size", err, "listen", laddr, "remote", raddr, ) } - after, err := sockctrl.GetsockoptInt(c, syscall.SOL_SOCKET, syscall.SO_RCVBUF) + after, err := sockctrl.GetsockoptInt(conn, syscall.SOL_SOCKET, syscall.SO_RCVBUF) if err != nil { return serrors.Wrap("Error getting SO_RCVBUF socket option (after)", err, "listen", laddr, @@ -158,9 +158,9 @@ func (cc *connUDPBase) initConnUDP( } } - cc.conn = c - cc.Listen = laddr - cc.Remote = raddr + c.conn = conn + c.Listen = laddr + c.Remote = raddr return nil } diff --git a/router/bfd/session.go b/router/bfd/session.go index fef910451d..935d97a6a5 100644 --- a/router/bfd/session.go +++ b/router/bfd/session.go @@ -534,15 +534,15 @@ func shouldDiscard(pkt *layers.BFD) (bool, string) { if pkt.MyDiscriminator == 0 { return true, "" } - if pkt.YourDiscriminator == 0 { - if !((pkt.State == layers.BFDStateAdminDown) || (pkt.State == layers.BFDStateDown)) { - return true, "" - } + if pkt.YourDiscriminator == 0 && + pkt.State != layers.BFDStateAdminDown && + pkt.State != layers.BFDStateDown { + return true, "" } - if !pkt.AuthPresent { - if pkt.AuthHeader != nil && pkt.AuthHeader.AuthType != layers.BFDAuthTypeNone { - return true, "" - } + if !pkt.AuthPresent && + pkt.AuthHeader != nil && + pkt.AuthHeader.AuthType != layers.BFDAuthTypeNone { + return true, "" } // Authentication is not supported (see Anapaya/scion#3280). We currently discard diff --git a/router/dataplane.go b/router/dataplane.go index 70caa24340..3e8466d3cb 100644 --- a/router/dataplane.go +++ b/router/dataplane.go @@ -1145,8 +1145,8 @@ type slowPathType int8 const ( slowPathSCMP slowPathType = 0 // >=0 means it is an SCMP error - slowPathRouterAlertIngress = -1 - slowPathRouterAlertEgress = -2 + slowPathRouterAlertIngress slowPathType = -1 + slowPathRouterAlertEgress slowPathType = -2 ) func (p *slowPathPacketProcessor) packSCMP( @@ -1439,7 +1439,7 @@ func (p *scionPacketProcessor) updateNonConsDirIngressSegID() disposition { // against construction dir the ingress router updates the SegID, ifID == 0 // means this comes from this AS itself, so nothing has to be done. // For packets destined to peer links this shouldn't be updated. - if !(p.infoField.ConsDir || p.ingressFromLink == 0 || p.peering) { + if !p.infoField.ConsDir && p.ingressFromLink != 0 && !p.peering { p.infoField.UpdateSegID(p.hopField.Mac) if err := p.path.SetInfoField(p.infoField, int(p.path.PathMeta.CurrINF)); err != nil { return errorDiscard("error", err) diff --git a/router/export_test.go b/router/export_test.go index f300bc53ec..7062f33f49 100644 --- a/router/export_test.go +++ b/router/export_test.go @@ -280,6 +280,6 @@ func ExtractServices(s *Services[netip.AddrPort]) map[addr.SVC][]netip.AddrPort // We cannot know which tests are going to mock which underlay and what the opener's // signature is. So we'll let the underlay implementation type-assert it. -func (dp *DataPlane) SetConnOpener(underlay string, opener any) { - dp.underlays[underlay].SetConnOpener(opener) +func (d *DataPlane) SetConnOpener(underlay string, opener any) { + d.underlays[underlay].SetConnOpener(opener) } diff --git a/router/underlayproviders/udpip/udpip.go b/router/underlayproviders/udpip/udpip.go index 9299f595e3..e5730093f1 100644 --- a/router/underlayproviders/udpip/udpip.go +++ b/router/underlayproviders/udpip/udpip.go @@ -58,11 +58,11 @@ type ConnOpener interface { // The default ConnOpener for this underlay: opens a UDP BatchConn. type uo struct{} -func (_ uo) Open(l netip.AddrPort, r netip.AddrPort, c *conn.Config) (router.BatchConn, error) { +func (uo) Open(l netip.AddrPort, r netip.AddrPort, c *conn.Config) (router.BatchConn, error) { return conn.New(l, r, c) } -func (_ uo) UDPCanReuseLocal() bool { +func (uo) UDPCanReuseLocal() bool { // By default we follow the local UDP capabilities. Unit tests can chose to model one behavior // or the other. return conn.UDPCanReuseLocal() diff --git a/router/underlayproviders/udpip/udpip_test.go b/router/underlayproviders/udpip/udpip_test.go index 3526e0cda7..a0594c3a7b 100644 --- a/router/underlayproviders/udpip/udpip_test.go +++ b/router/underlayproviders/udpip/udpip_test.go @@ -185,7 +185,7 @@ func TestComputeProcId(t *testing.T) { spkt.SetDstAddr(addr.HostIP(netip.AddrFrom4([4]byte{10, 0, 200, 200})))) assert.NoError(t, spkt.SetSrcAddr(addr.HostIP(netip.MustParseAddr("2001:db8::68")))) assert.Equal(t, slayers.T4Ip, spkt.DstAddrType) - assert.Equal(t, slayers.T16Ip, int(spkt.SrcAddrType)) + assert.Equal(t, slayers.T16Ip, spkt.SrcAddrType) return []ret{ { payload: payload, @@ -201,7 +201,7 @@ func TestComputeProcId(t *testing.T) { spkt.SetDstAddr(addr.HostIP(netip.AddrFrom4([4]byte{10, 0, 200, 200})))) assert.NoError(t, spkt.SetSrcAddr(addr.HostSVC(addr.SvcWildcard))) assert.Equal(t, slayers.T4Ip, spkt.DstAddrType) - assert.Equal(t, slayers.T4Svc, int(spkt.SrcAddrType)) + assert.Equal(t, slayers.T4Svc, spkt.SrcAddrType) return []ret{ { payload: payload, diff --git a/scion-pki/certs/certformat.go b/scion-pki/certs/certformat.go index 802bb1da9c..574f535d6d 100644 --- a/scion-pki/certs/certformat.go +++ b/scion-pki/certs/certformat.go @@ -45,7 +45,7 @@ type formatBuffer struct { // Writef writes a formatted string to b. func (b *formatBuffer) Writef(format string, args ...any) (int, error) { - return fmt.Fprintf(b, format, args...) + return fmt.Fprintf(&b.Buffer, format, args...) } type certificateShort struct { diff --git a/tools/end2end/main.go b/tools/end2end/main.go index 03a0268f2d..e1d5fed9cf 100644 --- a/tools/end2end/main.go +++ b/tools/end2end/main.go @@ -430,7 +430,7 @@ func readFrom(conn *snet.Conn, pld []byte) (int, net.Addr, error) { n, remoteAddr, err := conn.ReadFrom(pld) // Attach more context to error var opErr *snet.OpError - if !(errors.As(err, &opErr) && opErr.RevInfo() != nil) { + if !errors.As(err, &opErr) || opErr.RevInfo() == nil { return n, remoteAddr, err } return n, remoteAddr, serrors.WrapNoStack("error", err, diff --git a/tools/end2end_integration/main.go b/tools/end2end_integration/main.go index 1650ed1bdc..30a5637d98 100644 --- a/tools/end2end_integration/main.go +++ b/tools/end2end_integration/main.go @@ -215,7 +215,7 @@ func runTests(in integration.Integration, pairs []integration.IAPair) error { defer clean() if *integration.Docker { - socket = strings.Replace(socket, doneDir, "/share/logs/socks", -1) + socket = strings.ReplaceAll(socket, doneDir, "/share/logs/socks") } // CI collapses if parallelism is too high. diff --git a/tools/integration/binary.go b/tools/integration/binary.go index b86c96989e..bff4289782 100644 --- a/tools/integration/binary.go +++ b/tools/integration/binary.go @@ -220,7 +220,7 @@ func replacePattern(pattern string, replacement string, args []string) []string argsCopy := append([]string(nil), args...) for i, arg := range argsCopy { if strings.Contains(arg, pattern) { - argsCopy[i] = strings.Replace(arg, pattern, replacement, -1) + argsCopy[i] = strings.ReplaceAll(arg, pattern, replacement) } } return argsCopy diff --git a/tools/integration/docker.go b/tools/integration/docker.go index 0b26344a31..bc1e3cc007 100644 --- a/tools/integration/docker.go +++ b/tools/integration/docker.go @@ -82,7 +82,7 @@ func (di *dockerIntegration) StartClient(ctx context.Context, // TesterID returns the ID of the tester container. func TesterID(a *snet.UDPAddr) string { ia := addr.FormatIA(a.IA, addr.WithFileSeparator()) - envID, ok := os.LookupEnv(fmt.Sprintf("tester_%s", strings.Replace(ia, "-", "_", -1))) + envID, ok := os.LookupEnv(fmt.Sprintf("tester_%s", strings.ReplaceAll(ia, "-", "_"))) if !ok { return fmt.Sprintf("tester_%s", ia) } diff --git a/tools/pathdb_dump/main.go b/tools/pathdb_dump/main.go index 05f36404c2..e316d4b4d1 100644 --- a/tools/pathdb_dump/main.go +++ b/tools/pathdb_dump/main.go @@ -184,7 +184,7 @@ func defaultDBfilename() (string, error) { glob := filepath.Join(searchPath, "ps*path.db") filenames, err := filepath.Glob(glob) if err != nil { - return "", fmt.Errorf("Error while listing files: %v", err) + return "", fmt.Errorf("error while listing files: %v", err) } if len(filenames) == 1 { return filenames[0], nil @@ -193,6 +193,6 @@ func defaultDBfilename() (string, error) { if len(filenames) > 1 { reason = "more than one" } - return "", fmt.Errorf("Found %s files matching '%s'. "+ - "Please specify the path to a DB file using the -db flag.", reason, glob) + return "", fmt.Errorf("found %s files matching '%s'. "+ + "Please specify the path to a DB file using the -db flag", reason, glob) }