diff --git a/executor/oci/resolvconf.go b/executor/oci/resolvconf.go index c510a1a1bc18..da7745697645 100644 --- a/executor/oci/resolvconf.go +++ b/executor/oci/resolvconf.go @@ -7,7 +7,6 @@ import ( "path/filepath" "github.com/docker/docker/libnetwork/resolvconf" - "github.com/docker/docker/libnetwork/types" "github.com/docker/docker/pkg/idtools" "github.com/moby/buildkit/util/flightcontrol" "github.com/pkg/errors" @@ -74,7 +73,7 @@ func GetResolvConf(ctx context.Context, stateDir string, idmap *idtools.Identity if dns != nil { var ( - dnsNameservers = resolvconf.GetNameservers(dt, types.IP) + dnsNameservers = resolvconf.GetNameservers(dt, resolvconf.IP) dnsSearchDomains = resolvconf.GetSearchDomains(dt) dnsOptions = resolvconf.GetOptions(dt) ) diff --git a/frontend/dockerfile/builder/build.go b/frontend/dockerfile/builder/build.go index f4b4a04ace82..3b18364d2761 100644 --- a/frontend/dockerfile/builder/build.go +++ b/frontend/dockerfile/builder/build.go @@ -463,7 +463,7 @@ func Build(ctx context.Context, c client.Client) (*client.Result, error) { } c.Warn(ctx, defVtx, msg, warnOpts(sourceMap, location, detail, url)) }, - ContextByName: contextByNameFunc(c, tp), + ContextByName: contextByNameFunc(c), }) if err != nil { @@ -812,8 +812,8 @@ func warnOpts(sm *llb.SourceMap, r *parser.Range, detail [][]byte, url string) c return opts } -func contextByNameFunc(c client.Client, p *ocispecs.Platform) func(context.Context, string, string) (*llb.State, *dockerfile2llb.Image, *binfotypes.BuildInfo, error) { - return func(ctx context.Context, name, resolveMode string) (*llb.State, *dockerfile2llb.Image, *binfotypes.BuildInfo, error) { +func contextByNameFunc(c client.Client) func(context.Context, string, string, *ocispecs.Platform) (*llb.State, *dockerfile2llb.Image, *binfotypes.BuildInfo, error) { + return func(ctx context.Context, name, resolveMode string, p *ocispecs.Platform) (*llb.State, *dockerfile2llb.Image, *binfotypes.BuildInfo, error) { named, err := reference.ParseNormalizedNamed(name) if err != nil { return nil, nil, nil, errors.Wrapf(err, "invalid context name %s", name) @@ -879,6 +879,7 @@ func contextByName(ctx context.Context, c client.Client, name string, platform * if err := json.Unmarshal(data, &img); err != nil { return nil, nil, nil, err } + img.Created = nil st := llb.Image(ref, imgOpt...) st, err = st.WithImageConfig(data) diff --git a/frontend/dockerfile/dockerfile2llb/convert.go b/frontend/dockerfile/dockerfile2llb/convert.go index a18e36ea5a21..a20cd4f95ef4 100644 --- a/frontend/dockerfile/dockerfile2llb/convert.go +++ b/frontend/dockerfile/dockerfile2llb/convert.go @@ -70,16 +70,19 @@ type ConvertOpt struct { SourceMap *llb.SourceMap Hostname string Warn func(short, url string, detail [][]byte, location *parser.Range) - ContextByName func(ctx context.Context, name, resolveMode string) (*llb.State, *Image, *binfotypes.BuildInfo, error) + ContextByName func(ctx context.Context, name, resolveMode string, p *ocispecs.Platform) (*llb.State, *Image, *binfotypes.BuildInfo, error) } func Dockerfile2LLB(ctx context.Context, dt []byte, opt ConvertOpt) (*llb.State, *Image, *binfotypes.BuildInfo, error) { buildInfo := &binfotypes.BuildInfo{} contextByName := opt.ContextByName - opt.ContextByName = func(ctx context.Context, name, resolveMode string) (*llb.State, *Image, *binfotypes.BuildInfo, error) { + opt.ContextByName = func(ctx context.Context, name, resolveMode string, p *ocispecs.Platform) (*llb.State, *Image, *binfotypes.BuildInfo, error) { if !strings.EqualFold(name, "scratch") && !strings.EqualFold(name, "context") { if contextByName != nil { - st, img, bi, err := contextByName(ctx, name, resolveMode) + if p == nil { + p = opt.TargetPlatform + } + st, img, bi, err := contextByName(ctx, name, resolveMode, p) if err != nil { return nil, nil, nil, err } @@ -165,8 +168,21 @@ func Dockerfile2LLB(ctx context.Context, dt []byte, opt ConvertOpt) (*llb.State, prefixPlatform: opt.PrefixPlatform, } + if v := st.Platform; v != "" { + v, err := shlex.ProcessWordWithMap(v, metaArgsToMap(optMetaArgs)) + if err != nil { + return nil, nil, nil, parser.WithLocation(errors.Wrapf(err, "failed to process arguments for platform %s", v), st.Location) + } + + p, err := platforms.Parse(v) + if err != nil { + return nil, nil, nil, parser.WithLocation(errors.Wrapf(err, "failed to parse platform %s", v), st.Location) + } + ds.platform = &p + } + if st.Name != "" { - s, img, bi, err := opt.ContextByName(ctx, st.Name, opt.ImageResolveMode.String()) + s, img, bi, err := opt.ContextByName(ctx, st.Name, opt.ImageResolveMode.String(), ds.platform) if err != nil { return nil, nil, nil, err } @@ -195,18 +211,6 @@ func Dockerfile2LLB(ctx context.Context, dt []byte, opt ConvertOpt) (*llb.State, ds.stageName = fmt.Sprintf("stage-%d", i) } - if v := st.Platform; v != "" { - v, err := shlex.ProcessWordWithMap(v, metaArgsToMap(optMetaArgs)) - if err != nil { - return nil, nil, nil, parser.WithLocation(errors.Wrapf(err, "failed to process arguments for platform %s", v), st.Location) - } - - p, err := platforms.Parse(v) - if err != nil { - return nil, nil, nil, parser.WithLocation(errors.Wrapf(err, "failed to parse platform %s", v), st.Location) - } - ds.platform = &p - } allDispatchStates.addState(ds) total := 0 @@ -313,7 +317,7 @@ func Dockerfile2LLB(ctx context.Context, dt []byte, opt ConvertOpt) (*llb.State, d.stage.BaseName = reference.TagNameOnly(ref).String() var isScratch bool - st, img, bi, err := opt.ContextByName(ctx, d.stage.BaseName, opt.ImageResolveMode.String()) + st, img, bi, err := opt.ContextByName(ctx, d.stage.BaseName, opt.ImageResolveMode.String(), platform) if err != nil { return err } diff --git a/frontend/dockerfile/dockerfile_test.go b/frontend/dockerfile/dockerfile_test.go index 2fbb67a6d957..0f2864089ec3 100644 --- a/frontend/dockerfile/dockerfile_test.go +++ b/frontend/dockerfile/dockerfile_test.go @@ -116,6 +116,8 @@ var allTests = integration.TestFuncs( testUlimit, testCgroupParent, testNamedImageContext, + testNamedImageContextPlatform, + testNamedImageContextTimestamps, testNamedLocalContext, testNamedInputContext, testNamedMultiplatformInputContext, @@ -5434,6 +5436,163 @@ COPY --from=base /env_foobar / require.Contains(t, string(dt), "/foobar:") } +func testNamedImageContextPlatform(t *testing.T, sb integration.Sandbox) { + ctx := sb.Context() + + c, err := client.New(ctx, sb.Address()) + require.NoError(t, err) + defer c.Close() + + registry, err := sb.NewRegistry() + if errors.Is(err, integration.ErrRequirements) { + t.Skip(err.Error()) + } + require.NoError(t, err) + + // Build a base image and force buildkit to generate a manifest list. + dockerfile := []byte(`FROM --platform=$BUILDPLATFORM alpine:latest`) + target := registry + "/buildkit/testnamedimagecontextplatform:latest" + + dir, err := tmpdir( + fstest.CreateFile("Dockerfile", dockerfile, 0600), + ) + require.NoError(t, err) + + f := getFrontend(t, sb) + + _, err = f.Solve(sb.Context(), c, client.SolveOpt{ + FrontendAttrs: map[string]string{ + "build-arg:BUILDKIT_MULTI_PLATFORM": "true", + }, + LocalDirs: map[string]string{ + builder.DefaultLocalNameDockerfile: dir, + builder.DefaultLocalNameContext: dir, + }, + Exports: []client.ExportEntry{ + { + Type: client.ExporterImage, + Attrs: map[string]string{ + "name": target, + "push": "true", + }, + }, + }, + }, nil) + require.NoError(t, err) + + dockerfile = []byte(` +FROM --platform=$BUILDPLATFORM busybox AS target +RUN echo hello +`) + + dir, err = tmpdir( + fstest.CreateFile("Dockerfile", dockerfile, 0600), + ) + require.NoError(t, err) + + f = getFrontend(t, sb) + + _, err = f.Solve(sb.Context(), c, client.SolveOpt{ + FrontendAttrs: map[string]string{ + "context:busybox": "docker-image://" + target, + // random platform that would never exist so it doesn't conflict with the build machine + // here we specifically want to make sure that the platform chosen for the image source is the one in the dockerfile not the target platform. + "platform": "darwin/ppc64le", + }, + LocalDirs: map[string]string{ + builder.DefaultLocalNameDockerfile: dir, + builder.DefaultLocalNameContext: dir, + }, + }, nil) + require.NoError(t, err) +} + +func testNamedImageContextTimestamps(t *testing.T, sb integration.Sandbox) { + ctx := sb.Context() + + c, err := client.New(ctx, sb.Address()) + require.NoError(t, err) + defer c.Close() + + registry, err := sb.NewRegistry() + if errors.Is(err, integration.ErrRequirements) { + t.Skip(err.Error()) + } + require.NoError(t, err) + + f := getFrontend(t, sb) + + dockerfile := []byte(` +FROM alpine +RUN echo foo >> /test +`) + dir, err := tmpdir( + fstest.CreateFile("Dockerfile", dockerfile, 0600), + ) + require.NoError(t, err) + defer os.RemoveAll(dir) + + target := registry + "/buildkit/testnamedimagecontexttimestamps:latest" + _, err = f.Solve(sb.Context(), c, client.SolveOpt{ + LocalDirs: map[string]string{ + builder.DefaultLocalNameDockerfile: dir, + builder.DefaultLocalNameContext: dir, + }, + Exports: []client.ExportEntry{ + { + Type: client.ExporterImage, + Attrs: map[string]string{ + "name": target, + "push": "true", + }, + }, + }, + }, nil) + require.NoError(t, err) + + desc, provider, err := contentutil.ProviderFromRef(target) + require.NoError(t, err) + img, err := readImage(sb.Context(), provider, desc) + require.NoError(t, err) + + dirDerived, err := tmpdir( + fstest.CreateFile("Dockerfile", dockerfile, 0600), + ) + require.NoError(t, err) + defer os.RemoveAll(dirDerived) + + targetDerived := registry + "/buildkit/testnamedimagecontexttimestampsderived:latest" + _, err = f.Solve(sb.Context(), c, client.SolveOpt{ + FrontendAttrs: map[string]string{ + "context:alpine": "docker-image://" + target, + }, + LocalDirs: map[string]string{ + builder.DefaultLocalNameDockerfile: dirDerived, + builder.DefaultLocalNameContext: dirDerived, + }, + Exports: []client.ExportEntry{ + { + Type: client.ExporterImage, + Attrs: map[string]string{ + "name": targetDerived, + "push": "true", + }, + }, + }, + }, nil) + require.NoError(t, err) + + desc, provider, err = contentutil.ProviderFromRef(targetDerived) + require.NoError(t, err) + imgDerived, err := readImage(sb.Context(), provider, desc) + require.NoError(t, err) + + require.NotEqual(t, img.img.Created, imgDerived.img.Created) + diff := imgDerived.img.Created.Sub(*img.img.Created) + require.Greater(t, diff, time.Duration(0)) + require.Less(t, diff, 10*time.Minute) +} + func testNamedLocalContext(t *testing.T, sb integration.Sandbox) { ctx := sb.Context() @@ -6023,6 +6182,7 @@ func fixedWriteCloser(wc io.WriteCloser) func(map[string]string) (io.WriteCloser type imageInfo struct { desc ocispecs.Descriptor + img ocispecs.Image layers []map[string]*testutil.TarItem } @@ -6054,12 +6214,19 @@ func readImage(ctx context.Context, p content.Provider, desc ocispecs.Descriptor if err != nil { return nil, err } - var mfst ocispecs.Manifest if err := json.Unmarshal(dt, &mfst); err != nil { return nil, err } + dt, err = content.ReadBlob(ctx, p, mfst.Config) + if err != nil { + return nil, err + } + if err := json.Unmarshal(dt, &ii.img); err != nil { + return nil, err + } + for _, l := range mfst.Layers { dt, err := content.ReadBlob(ctx, p, l) if err != nil { diff --git a/frontend/gateway/container.go b/frontend/gateway/container.go index 824a503ffb55..45cf2d90eb50 100644 --- a/frontend/gateway/container.go +++ b/frontend/gateway/container.go @@ -361,6 +361,8 @@ func (gwCtr *gatewayContainer) Start(ctx context.Context, req client.StartReques } func (gwCtr *gatewayContainer) Release(ctx context.Context) error { + gwCtr.mu.Lock() + defer gwCtr.mu.Unlock() gwCtr.cancel() err1 := gwCtr.errGroup.Wait() @@ -371,6 +373,7 @@ func (gwCtr *gatewayContainer) Release(ctx context.Context) error { err2 = err } } + gwCtr.cleanup = nil if err1 != nil { return stack.Enable(err1) diff --git a/frontend/gateway/forwarder/forward.go b/frontend/gateway/forwarder/forward.go index b866de818c93..0a95de377dc2 100644 --- a/frontend/gateway/forwarder/forward.go +++ b/frontend/gateway/forwarder/forward.go @@ -52,6 +52,7 @@ type bridgeClient struct { workers worker.Infos workerRefByID map[string]*worker.WorkerRef buildOpts client.BuildOpts + ctrs []client.Container } func (c *bridgeClient) Solve(ctx context.Context, req client.SolveRequest) (*client.Result, error) { @@ -212,6 +213,10 @@ func (c *bridgeClient) toFrontendResult(r *client.Result) (*frontend.Result, err } func (c *bridgeClient) discard(err error) { + for _, ctr := range c.ctrs { + ctr.Release(context.TODO()) + } + for id, workerRef := range c.workerRefByID { workerRef.ImmutableRef.Release(context.TODO()) delete(c.workerRefByID, id) @@ -300,6 +305,7 @@ func (c *bridgeClient) NewContainer(ctx context.Context, req client.NewContainer if err != nil { return nil, err } + c.ctrs = append(c.ctrs, ctr) return ctr, nil } diff --git a/frontend/gateway/gateway.go b/frontend/gateway/gateway.go index 842e3252f377..85a42e299def 100644 --- a/frontend/gateway/gateway.go +++ b/frontend/gateway/gateway.go @@ -278,7 +278,7 @@ func (gf *gatewayFrontend) Solve(ctx context.Context, llbBridge frontend.Fronten err = w.Executor().Run(ctx, "", mountWithSession(rootFS, session.NewGroup(sid)), mnts, executor.ProcessInfo{Meta: meta, Stdin: lbf.Stdin, Stdout: lbf.Stdout, Stderr: os.Stderr}, nil) if err != nil { - if errdefs.IsCanceled(err) && lbf.isErrServerClosed { + if errdefs.IsCanceled(ctx, err) && lbf.isErrServerClosed { err = errors.Errorf("frontend grpc server closed unexpectedly") } // An existing error (set via Return rpc) takes @@ -345,6 +345,13 @@ func (b *bindMount) IdentityMapping() *idtools.IdentityMapping { func (lbf *llbBridgeForwarder) Discard() { lbf.mu.Lock() defer lbf.mu.Unlock() + + for ctr := range lbf.ctrs { + lbf.ReleaseContainer(context.TODO(), &pb.ReleaseContainerRequest{ + ContainerID: ctr, + }) + } + for id, workerRef := range lbf.workerRefByID { workerRef.ImmutableRef.Release(context.TODO()) delete(lbf.workerRefByID, id) diff --git a/go.mod b/go.mod index 33d1f2603ca4..49f906711fb2 100644 --- a/go.mod +++ b/go.mod @@ -101,7 +101,6 @@ require ( github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.1 // indirect github.com/hashicorp/go-retryablehttp v0.7.0 // indirect - github.com/ishidawataru/sctp v0.0.0-20210226210310-f2269e66cdee // indirect github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect github.com/moby/sys/mount v0.3.0 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect @@ -119,7 +118,7 @@ require ( go.opentelemetry.io/otel/metric v0.27.0 // indirect golang.org/x/text v0.3.7 // indirect google.golang.org/protobuf v1.27.1 // indirect - gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect + gopkg.in/yaml.v3 v3.0.0 // indirect ) replace github.com/docker/docker => github.com/docker/docker v20.10.3-0.20220414164044-61404de7df1a+incompatible diff --git a/go.sum b/go.sum index 9cfd296228e5..52e9a755abc7 100644 --- a/go.sum +++ b/go.sum @@ -809,8 +809,6 @@ github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/intel/goresctrl v0.2.0/go.mod h1:+CZdzouYFn5EsxgqAQTEzMfwKwuc0fVdMrT9FCCAVRQ= github.com/ishidawataru/sctp v0.0.0-20191218070446-00ab2ac2db07/go.mod h1:co9pwDoBCm1kGxawmb4sPq0cSIOOWNPT4KnHotMP1Zg= -github.com/ishidawataru/sctp v0.0.0-20210226210310-f2269e66cdee h1:PAXLXk1heNZ5yokbMBpVLZQxo43wCZxRwl00mX+dd44= -github.com/ishidawataru/sctp v0.0.0-20210226210310-f2269e66cdee/go.mod h1:co9pwDoBCm1kGxawmb4sPq0cSIOOWNPT4KnHotMP1Zg= github.com/j-keck/arping v0.0.0-20160618110441-2cf9dc699c56/go.mod h1:ymszkNOg6tORTn+6F6j+Jc8TOr5osrynvN6ivFWZ2GA= github.com/j-keck/arping v1.0.2/go.mod h1:aJbELhR92bSk7tp79AWM/ftfc90EfEi2bQJrbBFOsPw= github.com/jaguilar/vt100 v0.0.0-20150826170717-2703a27b14ea/go.mod h1:QMdK4dGB3YhEW2BmA1wgGpPYI3HZy/5gD705PXKUVSg= @@ -1976,8 +1974,9 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA= +gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= diff --git a/session/grpc.go b/session/grpc.go index a7237ac35046..dd67c69b6466 100644 --- a/session/grpc.go +++ b/session/grpc.go @@ -2,6 +2,7 @@ package session import ( "context" + "math" "net" "sync/atomic" "time" @@ -10,6 +11,7 @@ import ( "github.com/moby/buildkit/util/bklog" "github.com/moby/buildkit/util/grpcerrors" "github.com/pkg/errors" + "github.com/sirupsen/logrus" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "go.opentelemetry.io/otel/trace" "golang.org/x/net/http2" @@ -79,21 +81,55 @@ func monitorHealth(ctx context.Context, cc *grpc.ClientConn, cancelConn func()) defer cancelConn() defer cc.Close() - ticker := time.NewTicker(1 * time.Second) + ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() healthClient := grpc_health_v1.NewHealthClient(cc) + failedBefore := false + consecutiveSuccessful := 0 + defaultHealthcheckDuration := 30 * time.Second + lastHealthcheckDuration := time.Duration(0) + for { select { case <-ctx.Done(): return case <-ticker.C: - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + // This healthcheck can erroneously fail in some instances, such as receiving lots of data in a low-bandwidth scenario or too many concurrent builds. + // So, this healthcheck is purposely long, and can tolerate some failures on purpose. + + healthcheckStart := time.Now() + + timeout := time.Duration(math.Max(float64(defaultHealthcheckDuration), float64(lastHealthcheckDuration)*1.5)) + ctx, cancel := context.WithTimeout(ctx, timeout) _, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{}) cancel() + + lastHealthcheckDuration = time.Since(healthcheckStart) + logFields := logrus.Fields{ + "timeout": timeout, + "actualDuration": lastHealthcheckDuration, + } + if err != nil { - return + if failedBefore { + bklog.G(ctx).Error("healthcheck failed fatally") + return + } + + failedBefore = true + consecutiveSuccessful = 0 + bklog.G(ctx).WithFields(logFields).Warn("healthcheck failed") + } else { + consecutiveSuccessful++ + + if consecutiveSuccessful >= 5 && failedBefore { + failedBefore = false + bklog.G(ctx).WithFields(logFields).Debug("reset healthcheck failure") + } } + + bklog.G(ctx).WithFields(logFields).Debug("healthcheck completed") } } } diff --git a/solver/errdefs/context.go b/solver/errdefs/context.go index ea6bdfbf0985..9e0c5bb990c6 100644 --- a/solver/errdefs/context.go +++ b/solver/errdefs/context.go @@ -3,11 +3,25 @@ package errdefs import ( "context" "errors" + "strings" "github.com/moby/buildkit/util/grpcerrors" "google.golang.org/grpc/codes" ) -func IsCanceled(err error) bool { - return errors.Is(err, context.Canceled) || grpcerrors.Code(err) == codes.Canceled +func IsCanceled(ctx context.Context, err error) bool { + if errors.Is(err, context.Canceled) || grpcerrors.Code(err) == codes.Canceled { + return true + } + // grpc does not set cancel correctly when stream gets cancelled and then Recv is called + if err != nil && ctx.Err() == context.Canceled { + // when this error comes from containerd it is not typed at all, just concatenated string + if strings.Contains(err.Error(), "EOF") { + return true + } + if strings.Contains(err.Error(), context.Canceled.Error()) { + return true + } + } + return false } diff --git a/solver/jobs.go b/solver/jobs.go index 0d59fb368ece..25cb93d5992d 100644 --- a/solver/jobs.go +++ b/solver/jobs.go @@ -3,7 +3,6 @@ package solver import ( "context" "fmt" - "strings" "sync" "time" @@ -705,7 +704,7 @@ func (s *sharedOp) CalcSlowCache(ctx context.Context, index Index, p PreprocessF if err != nil { select { case <-ctx.Done(): - if strings.Contains(err.Error(), context.Canceled.Error()) { + if errdefs.IsCanceled(ctx, err) { complete = false releaseError(err) err = errors.Wrap(ctx.Err(), err.Error()) @@ -771,7 +770,7 @@ func (s *sharedOp) CacheMap(ctx context.Context, index int) (resp *cacheMapResp, if err != nil { select { case <-ctx.Done(): - if strings.Contains(err.Error(), context.Canceled.Error()) { + if errdefs.IsCanceled(ctx, err) { complete = false releaseError(err) err = errors.Wrap(ctx.Err(), err.Error()) @@ -810,8 +809,11 @@ func (s *sharedOp) Exec(ctx context.Context, inputs []Result) (outputs []Result, } flightControlKey := "exec" res, err := s.g.Do(ctx, flightControlKey, func(ctx context.Context) (ret interface{}, retErr error) { - if s.execRes != nil || s.execErr != nil { - return s.execRes, s.execErr + if s.execErr != nil { + return nil, s.execErr + } + if s.execRes != nil { + return s.execRes, nil } release, err := op.Acquire(ctx) if err != nil { @@ -838,7 +840,7 @@ func (s *sharedOp) Exec(ctx context.Context, inputs []Result) (outputs []Result, if err != nil { select { case <-ctx.Done(): - if strings.Contains(err.Error(), context.Canceled.Error()) { + if errdefs.IsCanceled(ctx, err) { complete = false releaseError(err) err = errors.Wrap(ctx.Err(), err.Error()) @@ -859,9 +861,12 @@ func (s *sharedOp) Exec(ctx context.Context, inputs []Result) (outputs []Result, } s.execErr = err } - return s.execRes, err + if s.execRes == nil || err != nil { + return nil, err + } + return s.execRes, nil }) - if err != nil { + if res == nil || err != nil { return nil, nil, err } r := res.(*execRes) diff --git a/solver/llbsolver/bridge.go b/solver/llbsolver/bridge.go index bd31bbfdc68b..8507280a109a 100644 --- a/solver/llbsolver/bridge.go +++ b/solver/llbsolver/bridge.go @@ -3,7 +3,6 @@ package llbsolver import ( "context" "fmt" - "strings" "sync" "time" @@ -290,7 +289,7 @@ func (rp *resultProxy) Result(ctx context.Context) (res solver.CachedResult, err if err != nil { select { case <-ctx.Done(): - if strings.Contains(err.Error(), context.Canceled.Error()) { + if errdefs.IsCanceled(ctx, err) { return v, err } default: diff --git a/source/containerimage/pull.go b/source/containerimage/pull.go index a989f0e1e9d4..99631db19ee0 100644 --- a/source/containerimage/pull.go +++ b/source/containerimage/pull.go @@ -182,7 +182,7 @@ func (p *puller) CacheKey(ctx context.Context, g session.Group, index int) (cach return nil, p.cacheKeyErr } defer func() { - if !errdefs.IsCanceled(err) { + if !errdefs.IsCanceled(ctx, err) { p.cacheKeyErr = err } }() diff --git a/vendor/github.com/docker/docker/libnetwork/types/types.go b/vendor/github.com/docker/docker/libnetwork/types/types.go deleted file mode 100644 index e4ade05902f7..000000000000 --- a/vendor/github.com/docker/docker/libnetwork/types/types.go +++ /dev/null @@ -1,576 +0,0 @@ -// Package types contains types that are common across libnetwork project -package types - -import ( - "bytes" - "fmt" - "net" - "strings" - - "github.com/ishidawataru/sctp" -) - -// constants for the IP address type -// Deprecated: use the consts defined in github.com/docker/docker/libnetwork/resolvconf -const ( - IP = iota // IPv4 and IPv6 - IPv4 - IPv6 -) - -// EncryptionKey is the libnetwork representation of the key distributed by the lead -// manager. -type EncryptionKey struct { - Subsystem string - Algorithm int32 - Key []byte - LamportTime uint64 -} - -// UUID represents a globally unique ID of various resources like network and endpoint -type UUID string - -// QosPolicy represents a quality of service policy on an endpoint -type QosPolicy struct { - MaxEgressBandwidth uint64 -} - -// TransportPort represents a local Layer 4 endpoint -type TransportPort struct { - Proto Protocol - Port uint16 -} - -// Equal checks if this instance of Transportport is equal to the passed one -func (t *TransportPort) Equal(o *TransportPort) bool { - if t == o { - return true - } - - if o == nil { - return false - } - - if t.Proto != o.Proto || t.Port != o.Port { - return false - } - - return true -} - -// GetCopy returns a copy of this TransportPort structure instance -func (t *TransportPort) GetCopy() TransportPort { - return TransportPort{Proto: t.Proto, Port: t.Port} -} - -// String returns the TransportPort structure in string form -func (t *TransportPort) String() string { - return fmt.Sprintf("%s/%d", t.Proto.String(), t.Port) -} - -// PortBinding represents a port binding between the container and the host -type PortBinding struct { - Proto Protocol - IP net.IP - Port uint16 - HostIP net.IP - HostPort uint16 - HostPortEnd uint16 -} - -// HostAddr returns the host side transport address -func (p PortBinding) HostAddr() (net.Addr, error) { - switch p.Proto { - case UDP: - return &net.UDPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil - case TCP: - return &net.TCPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil - case SCTP: - return &sctp.SCTPAddr{IPAddrs: []net.IPAddr{{IP: p.HostIP}}, Port: int(p.HostPort)}, nil - default: - return nil, ErrInvalidProtocolBinding(p.Proto.String()) - } -} - -// ContainerAddr returns the container side transport address -func (p PortBinding) ContainerAddr() (net.Addr, error) { - switch p.Proto { - case UDP: - return &net.UDPAddr{IP: p.IP, Port: int(p.Port)}, nil - case TCP: - return &net.TCPAddr{IP: p.IP, Port: int(p.Port)}, nil - case SCTP: - return &sctp.SCTPAddr{IPAddrs: []net.IPAddr{{IP: p.IP}}, Port: int(p.Port)}, nil - default: - return nil, ErrInvalidProtocolBinding(p.Proto.String()) - } -} - -// GetCopy returns a copy of this PortBinding structure instance -func (p *PortBinding) GetCopy() PortBinding { - return PortBinding{ - Proto: p.Proto, - IP: GetIPCopy(p.IP), - Port: p.Port, - HostIP: GetIPCopy(p.HostIP), - HostPort: p.HostPort, - HostPortEnd: p.HostPortEnd, - } -} - -// String returns the PortBinding structure in string form -func (p *PortBinding) String() string { - ret := fmt.Sprintf("%s/", p.Proto) - if p.IP != nil { - ret += p.IP.String() - } - ret = fmt.Sprintf("%s:%d/", ret, p.Port) - if p.HostIP != nil { - ret += p.HostIP.String() - } - ret = fmt.Sprintf("%s:%d", ret, p.HostPort) - return ret -} - -// Equal checks if this instance of PortBinding is equal to the passed one -func (p *PortBinding) Equal(o *PortBinding) bool { - if p == o { - return true - } - - if o == nil { - return false - } - - if p.Proto != o.Proto || p.Port != o.Port || - p.HostPort != o.HostPort || p.HostPortEnd != o.HostPortEnd { - return false - } - - if p.IP != nil { - if !p.IP.Equal(o.IP) { - return false - } - } else { - if o.IP != nil { - return false - } - } - - if p.HostIP != nil { - if !p.HostIP.Equal(o.HostIP) { - return false - } - } else { - if o.HostIP != nil { - return false - } - } - - return true -} - -// ErrInvalidProtocolBinding is returned when the port binding protocol is not valid. -type ErrInvalidProtocolBinding string - -func (ipb ErrInvalidProtocolBinding) Error() string { - return fmt.Sprintf("invalid transport protocol: %s", string(ipb)) -} - -const ( - // ICMP is for the ICMP ip protocol - ICMP = 1 - // TCP is for the TCP ip protocol - TCP = 6 - // UDP is for the UDP ip protocol - UDP = 17 - // SCTP is for the SCTP ip protocol - SCTP = 132 -) - -// Protocol represents an IP protocol number -type Protocol uint8 - -func (p Protocol) String() string { - switch p { - case ICMP: - return "icmp" - case TCP: - return "tcp" - case UDP: - return "udp" - case SCTP: - return "sctp" - default: - return fmt.Sprintf("%d", p) - } -} - -// ParseProtocol returns the respective Protocol type for the passed string -func ParseProtocol(s string) Protocol { - switch strings.ToLower(s) { - case "icmp": - return ICMP - case "udp": - return UDP - case "tcp": - return TCP - case "sctp": - return SCTP - default: - return 0 - } -} - -// GetMacCopy returns a copy of the passed MAC address -func GetMacCopy(from net.HardwareAddr) net.HardwareAddr { - if from == nil { - return nil - } - to := make(net.HardwareAddr, len(from)) - copy(to, from) - return to -} - -// GetIPCopy returns a copy of the passed IP address -func GetIPCopy(from net.IP) net.IP { - if from == nil { - return nil - } - to := make(net.IP, len(from)) - copy(to, from) - return to -} - -// GetIPNetCopy returns a copy of the passed IP Network -func GetIPNetCopy(from *net.IPNet) *net.IPNet { - if from == nil { - return nil - } - bm := make(net.IPMask, len(from.Mask)) - copy(bm, from.Mask) - return &net.IPNet{IP: GetIPCopy(from.IP), Mask: bm} -} - -// GetIPNetCanonical returns the canonical form for the passed network -func GetIPNetCanonical(nw *net.IPNet) *net.IPNet { - if nw == nil { - return nil - } - c := GetIPNetCopy(nw) - c.IP = c.IP.Mask(nw.Mask) - return c -} - -// CompareIPNet returns equal if the two IP Networks are equal -func CompareIPNet(a, b *net.IPNet) bool { - if a == b { - return true - } - if a == nil || b == nil { - return false - } - return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask) -} - -// GetMinimalIP returns the address in its shortest form -// If ip contains an IPv4-mapped IPv6 address, the 4-octet form of the IPv4 address will be returned. -// Otherwise ip is returned unchanged. -func GetMinimalIP(ip net.IP) net.IP { - if ip != nil && ip.To4() != nil { - return ip.To4() - } - return ip -} - -// IsIPNetValid returns true if the ipnet is a valid network/mask -// combination. Otherwise returns false. -func IsIPNetValid(nw *net.IPNet) bool { - return nw.String() != "0.0.0.0/0" -} - -var v4inV6MaskPrefix = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} - -// compareIPMask checks if the passed ip and mask are semantically compatible. -// It returns the byte indexes for the address and mask so that caller can -// do bitwise operations without modifying address representation. -func compareIPMask(ip net.IP, mask net.IPMask) (is int, ms int, err error) { - // Find the effective starting of address and mask - if len(ip) == net.IPv6len && ip.To4() != nil { - is = 12 - } - if len(ip[is:]) == net.IPv4len && len(mask) == net.IPv6len && bytes.Equal(mask[:12], v4inV6MaskPrefix) { - ms = 12 - } - // Check if address and mask are semantically compatible - if len(ip[is:]) != len(mask[ms:]) { - err = fmt.Errorf("ip and mask are not compatible: (%#v, %#v)", ip, mask) - } - return -} - -// GetHostPartIP returns the host portion of the ip address identified by the mask. -// IP address representation is not modified. If address and mask are not compatible -// an error is returned. -func GetHostPartIP(ip net.IP, mask net.IPMask) (net.IP, error) { - // Find the effective starting of address and mask - is, ms, err := compareIPMask(ip, mask) - if err != nil { - return nil, fmt.Errorf("cannot compute host portion ip address because %s", err) - } - - // Compute host portion - out := GetIPCopy(ip) - for i := 0; i < len(mask[ms:]); i++ { - out[is+i] &= ^mask[ms+i] - } - - return out, nil -} - -// GetBroadcastIP returns the broadcast ip address for the passed network (ip and mask). -// IP address representation is not modified. If address and mask are not compatible -// an error is returned. -func GetBroadcastIP(ip net.IP, mask net.IPMask) (net.IP, error) { - // Find the effective starting of address and mask - is, ms, err := compareIPMask(ip, mask) - if err != nil { - return nil, fmt.Errorf("cannot compute broadcast ip address because %s", err) - } - - // Compute broadcast address - out := GetIPCopy(ip) - for i := 0; i < len(mask[ms:]); i++ { - out[is+i] |= ^mask[ms+i] - } - - return out, nil -} - -// ParseCIDR returns the *net.IPNet represented by the passed CIDR notation -func ParseCIDR(cidr string) (n *net.IPNet, e error) { - var i net.IP - if i, n, e = net.ParseCIDR(cidr); e == nil { - n.IP = i - } - return -} - -const ( - // NEXTHOP indicates a StaticRoute with an IP next hop. - NEXTHOP = iota - - // CONNECTED indicates a StaticRoute with an interface for directly connected peers. - CONNECTED -) - -// StaticRoute is a statically-provisioned IP route. -type StaticRoute struct { - Destination *net.IPNet - - RouteType int // NEXT_HOP or CONNECTED - - // NextHop will be resolved by the kernel (i.e. as a loose hop). - NextHop net.IP -} - -// GetCopy returns a copy of this StaticRoute structure -func (r *StaticRoute) GetCopy() *StaticRoute { - d := GetIPNetCopy(r.Destination) - nh := GetIPCopy(r.NextHop) - return &StaticRoute{Destination: d, - RouteType: r.RouteType, - NextHop: nh, - } -} - -// InterfaceStatistics represents the interface's statistics -type InterfaceStatistics struct { - RxBytes uint64 - RxPackets uint64 - RxErrors uint64 - RxDropped uint64 - TxBytes uint64 - TxPackets uint64 - TxErrors uint64 - TxDropped uint64 -} - -func (is *InterfaceStatistics) String() string { - return fmt.Sprintf("\nRxBytes: %d, RxPackets: %d, RxErrors: %d, RxDropped: %d, TxBytes: %d, TxPackets: %d, TxErrors: %d, TxDropped: %d", - is.RxBytes, is.RxPackets, is.RxErrors, is.RxDropped, is.TxBytes, is.TxPackets, is.TxErrors, is.TxDropped) -} - -/****************************** - * Well-known Error Interfaces - ******************************/ - -// MaskableError is an interface for errors which can be ignored by caller -type MaskableError interface { - // Maskable makes implementer into MaskableError type - Maskable() -} - -// RetryError is an interface for errors which might get resolved through retry -type RetryError interface { - // Retry makes implementer into RetryError type - Retry() -} - -// BadRequestError is an interface for errors originated by a bad request -type BadRequestError interface { - // BadRequest makes implementer into BadRequestError type - BadRequest() -} - -// NotFoundError is an interface for errors raised because a needed resource is not available -type NotFoundError interface { - // NotFound makes implementer into NotFoundError type - NotFound() -} - -// ForbiddenError is an interface for errors which denote a valid request that cannot be honored -type ForbiddenError interface { - // Forbidden makes implementer into ForbiddenError type - Forbidden() -} - -// NoServiceError is an interface for errors returned when the required service is not available -type NoServiceError interface { - // NoService makes implementer into NoServiceError type - NoService() -} - -// TimeoutError is an interface for errors raised because of timeout -type TimeoutError interface { - // Timeout makes implementer into TimeoutError type - Timeout() -} - -// NotImplementedError is an interface for errors raised because of requested functionality is not yet implemented -type NotImplementedError interface { - // NotImplemented makes implementer into NotImplementedError type - NotImplemented() -} - -// InternalError is an interface for errors raised because of an internal error -type InternalError interface { - // Internal makes implementer into InternalError type - Internal() -} - -/****************************** - * Well-known Error Formatters - ******************************/ - -// BadRequestErrorf creates an instance of BadRequestError -func BadRequestErrorf(format string, params ...interface{}) error { - return badRequest(fmt.Sprintf(format, params...)) -} - -// NotFoundErrorf creates an instance of NotFoundError -func NotFoundErrorf(format string, params ...interface{}) error { - return notFound(fmt.Sprintf(format, params...)) -} - -// ForbiddenErrorf creates an instance of ForbiddenError -func ForbiddenErrorf(format string, params ...interface{}) error { - return forbidden(fmt.Sprintf(format, params...)) -} - -// NoServiceErrorf creates an instance of NoServiceError -func NoServiceErrorf(format string, params ...interface{}) error { - return noService(fmt.Sprintf(format, params...)) -} - -// NotImplementedErrorf creates an instance of NotImplementedError -func NotImplementedErrorf(format string, params ...interface{}) error { - return notImpl(fmt.Sprintf(format, params...)) -} - -// TimeoutErrorf creates an instance of TimeoutError -func TimeoutErrorf(format string, params ...interface{}) error { - return timeout(fmt.Sprintf(format, params...)) -} - -// InternalErrorf creates an instance of InternalError -func InternalErrorf(format string, params ...interface{}) error { - return internal(fmt.Sprintf(format, params...)) -} - -// InternalMaskableErrorf creates an instance of InternalError and MaskableError -func InternalMaskableErrorf(format string, params ...interface{}) error { - return maskInternal(fmt.Sprintf(format, params...)) -} - -// RetryErrorf creates an instance of RetryError -func RetryErrorf(format string, params ...interface{}) error { - return retry(fmt.Sprintf(format, params...)) -} - -/*********************** - * Internal Error Types - ***********************/ -type badRequest string - -func (br badRequest) Error() string { - return string(br) -} -func (br badRequest) BadRequest() {} - -type notFound string - -func (nf notFound) Error() string { - return string(nf) -} -func (nf notFound) NotFound() {} - -type forbidden string - -func (frb forbidden) Error() string { - return string(frb) -} -func (frb forbidden) Forbidden() {} - -type noService string - -func (ns noService) Error() string { - return string(ns) -} -func (ns noService) NoService() {} - -type timeout string - -func (to timeout) Error() string { - return string(to) -} -func (to timeout) Timeout() {} - -type notImpl string - -func (ni notImpl) Error() string { - return string(ni) -} -func (ni notImpl) NotImplemented() {} - -type internal string - -func (nt internal) Error() string { - return string(nt) -} -func (nt internal) Internal() {} - -type maskInternal string - -func (mnt maskInternal) Error() string { - return string(mnt) -} -func (mnt maskInternal) Internal() {} -func (mnt maskInternal) Maskable() {} - -type retry string - -func (r retry) Error() string { - return string(r) -} -func (r retry) Retry() {} diff --git a/vendor/github.com/ishidawataru/sctp/.gitignore b/vendor/github.com/ishidawataru/sctp/.gitignore deleted file mode 100644 index cf2d826c15f2..000000000000 --- a/vendor/github.com/ishidawataru/sctp/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ - -example/example diff --git a/vendor/github.com/ishidawataru/sctp/.travis.yml b/vendor/github.com/ishidawataru/sctp/.travis.yml deleted file mode 100644 index a1c693c0135a..000000000000 --- a/vendor/github.com/ishidawataru/sctp/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ -language: go -arch: - - amd64 - - ppc64le -go: - - 1.9.x - - 1.10.x - - 1.11.x - - 1.12.x - - 1.13.x -# allowing test cases to fail for the versions were not suppotred by ppc64le -matrix: - allow_failures: - - go: 1.9.x - - go: 1.10.x - - go: 1.13.x - - -script: - - go test -v -race ./... - - GOOS=linux GOARCH=amd64 go build . - - GOOS=linux GOARCH=arm go build . - - GOOS=linux GOARCH=arm64 go build . - - GOOS=linux GOARCH=ppc64le go build . - - GOOS=linux GOARCH=mips64le go build . - - (go version | grep go1.6 > /dev/null) || GOOS=linux GOARCH=s390x go build . -# can be compiled but not functional: - - GOOS=linux GOARCH=386 go build . - - GOOS=windows GOARCH=amd64 go build . diff --git a/vendor/github.com/ishidawataru/sctp/GO_LICENSE b/vendor/github.com/ishidawataru/sctp/GO_LICENSE deleted file mode 100644 index 6a66aea5eafe..000000000000 --- a/vendor/github.com/ishidawataru/sctp/GO_LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/ishidawataru/sctp/LICENSE b/vendor/github.com/ishidawataru/sctp/LICENSE deleted file mode 100644 index 8dada3edaf50..000000000000 --- a/vendor/github.com/ishidawataru/sctp/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/vendor/github.com/ishidawataru/sctp/NOTICE b/vendor/github.com/ishidawataru/sctp/NOTICE deleted file mode 100644 index cfb675fd4ba4..000000000000 --- a/vendor/github.com/ishidawataru/sctp/NOTICE +++ /dev/null @@ -1,3 +0,0 @@ -This source code includes following third party code - -- ipsock_linux.go : licensed by the Go authors, see GO_LICENSE file for the license which applies to the code diff --git a/vendor/github.com/ishidawataru/sctp/README.md b/vendor/github.com/ishidawataru/sctp/README.md deleted file mode 100644 index 574ececa8626..000000000000 --- a/vendor/github.com/ishidawataru/sctp/README.md +++ /dev/null @@ -1,18 +0,0 @@ -Stream Control Transmission Protocol (SCTP) ----- - -[![Build Status](https://travis-ci.org/ishidawataru/sctp.svg?branch=master)](https://travis-ci.org/ishidawataru/sctp/builds) - -Examples ----- - -See `example/sctp.go` - -```go -$ cd example -$ go build -$ # run example SCTP server -$ ./example -server -port 1000 -ip 10.10.0.1,10.20.0.1 -$ # run example SCTP client -$ ./example -port 1000 -ip 10.10.0.1,10.20.0.1 -``` diff --git a/vendor/github.com/ishidawataru/sctp/ipsock_linux.go b/vendor/github.com/ishidawataru/sctp/ipsock_linux.go deleted file mode 100644 index 3df30fa4601a..000000000000 --- a/vendor/github.com/ishidawataru/sctp/ipsock_linux.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the GO_LICENSE file. - -package sctp - -import ( - "net" - "os" - "sync" - "syscall" -) - -//from https://github.com/golang/go -// Boolean to int. -func boolint(b bool) int { - if b { - return 1 - } - return 0 -} - -//from https://github.com/golang/go -func ipToSockaddr(family int, ip net.IP, port int, zone string) (syscall.Sockaddr, error) { - switch family { - case syscall.AF_INET: - if len(ip) == 0 { - ip = net.IPv4zero - } - ip4 := ip.To4() - if ip4 == nil { - return nil, &net.AddrError{Err: "non-IPv4 address", Addr: ip.String()} - } - sa := &syscall.SockaddrInet4{Port: port} - copy(sa.Addr[:], ip4) - return sa, nil - case syscall.AF_INET6: - // In general, an IP wildcard address, which is either - // "0.0.0.0" or "::", means the entire IP addressing - // space. For some historical reason, it is used to - // specify "any available address" on some operations - // of IP node. - // - // When the IP node supports IPv4-mapped IPv6 address, - // we allow an listener to listen to the wildcard - // address of both IP addressing spaces by specifying - // IPv6 wildcard address. - if len(ip) == 0 || ip.Equal(net.IPv4zero) { - ip = net.IPv6zero - } - // We accept any IPv6 address including IPv4-mapped - // IPv6 address. - ip6 := ip.To16() - if ip6 == nil { - return nil, &net.AddrError{Err: "non-IPv6 address", Addr: ip.String()} - } - //we set ZoneId to 0, as currently we use this functon only to probe the IP capabilities of the host - //if real Zone handling is required, the zone cache implementation in golang/net should be pulled here - sa := &syscall.SockaddrInet6{Port: port, ZoneId: 0} - copy(sa.Addr[:], ip6) - return sa, nil - } - return nil, &net.AddrError{Err: "invalid address family", Addr: ip.String()} -} - -//from https://github.com/golang/go -func sockaddr(a *net.TCPAddr, family int) (syscall.Sockaddr, error) { - if a == nil { - return nil, nil - } - return ipToSockaddr(family, a.IP, a.Port, a.Zone) -} - -//from https://github.com/golang/go -type ipStackCapabilities struct { - sync.Once // guards following - ipv4Enabled bool - ipv6Enabled bool - ipv4MappedIPv6Enabled bool -} - -//from https://github.com/golang/go -var ipStackCaps ipStackCapabilities - -//from https://github.com/golang/go -// supportsIPv4 reports whether the platform supports IPv4 networking -// functionality. -func supportsIPv4() bool { - ipStackCaps.Once.Do(ipStackCaps.probe) - return ipStackCaps.ipv4Enabled -} - -//from https://github.com/golang/go -// supportsIPv6 reports whether the platform supports IPv6 networking -// functionality. -func supportsIPv6() bool { - ipStackCaps.Once.Do(ipStackCaps.probe) - return ipStackCaps.ipv6Enabled -} - -//from https://github.com/golang/go -// supportsIPv4map reports whether the platform supports mapping an -// IPv4 address inside an IPv6 address at transport layer -// protocols. See RFC 4291, RFC 4038 and RFC 3493. -func supportsIPv4map() bool { - ipStackCaps.Once.Do(ipStackCaps.probe) - return ipStackCaps.ipv4MappedIPv6Enabled -} - -//from https://github.com/golang/go -// Probe probes IPv4, IPv6 and IPv4-mapped IPv6 communication -// capabilities which are controlled by the IPV6_V6ONLY socket option -// and kernel configuration. -// -// Should we try to use the IPv4 socket interface if we're only -// dealing with IPv4 sockets? As long as the host system understands -// IPv4-mapped IPv6, it's okay to pass IPv4-mapeed IPv6 addresses to -// the IPv6 interface. That simplifies our code and is most -// general. Unfortunately, we need to run on kernels built without -// IPv6 support too. So probe the kernel to figure it out. -func (p *ipStackCapabilities) probe() { - s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP) - switch err { - case syscall.EAFNOSUPPORT, syscall.EPROTONOSUPPORT: - case nil: - syscall.Close(s) - p.ipv4Enabled = true - } - var probes = []struct { - laddr net.TCPAddr - value int - }{ - // IPv6 communication capability - {laddr: net.TCPAddr{IP: net.IPv6loopback}, value: 1}, - // IPv4-mapped IPv6 address communication capability - {laddr: net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}, value: 0}, - } - - for i := range probes { - s, err := syscall.Socket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP) - if err != nil { - continue - } - defer syscall.Close(s) - syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, probes[i].value) - sa, err := sockaddr(&(probes[i].laddr), syscall.AF_INET6) - if err != nil { - continue - } - if err := syscall.Bind(s, sa); err != nil { - continue - } - if i == 0 { - p.ipv6Enabled = true - } else { - p.ipv4MappedIPv6Enabled = true - } - } -} - -//from https://github.com/golang/go -//Change: we check the first IP address in the list of candidate SCTP IP addresses -func (a *SCTPAddr) isWildcard() bool { - if a == nil { - return true - } - if 0 == len(a.IPAddrs) { - return true - } - - return a.IPAddrs[0].IP.IsUnspecified() -} - -func (a *SCTPAddr) family() int { - if a != nil { - for _, ip := range a.IPAddrs { - if ip.IP.To4() == nil { - return syscall.AF_INET6 - } - } - } - return syscall.AF_INET -} - -//from https://github.com/golang/go -func favoriteAddrFamily(network string, laddr *SCTPAddr, raddr *SCTPAddr, mode string) (family int, ipv6only bool) { - switch network[len(network)-1] { - case '4': - return syscall.AF_INET, false - case '6': - return syscall.AF_INET6, true - } - - if mode == "listen" && (laddr == nil || laddr.isWildcard()) { - if supportsIPv4map() || !supportsIPv4() { - return syscall.AF_INET6, false - } - if laddr == nil { - return syscall.AF_INET, false - } - return laddr.family(), false - } - - if (laddr == nil || laddr.family() == syscall.AF_INET) && - (raddr == nil || raddr.family() == syscall.AF_INET) { - return syscall.AF_INET, false - } - return syscall.AF_INET6, false -} - -//from https://github.com/golang/go -//Changes: it is for SCTP only -func setDefaultSockopts(s int, family int, ipv6only bool) error { - if family == syscall.AF_INET6 { - // Allow both IP versions even if the OS default - // is otherwise. Note that some operating systems - // never admit this option. - syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, boolint(ipv6only)) - } - // Allow broadcast. - return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(s, syscall.SOL_SOCKET, syscall.SO_BROADCAST, 1)) -} diff --git a/vendor/github.com/ishidawataru/sctp/sctp.go b/vendor/github.com/ishidawataru/sctp/sctp.go deleted file mode 100644 index 94842f42702f..000000000000 --- a/vendor/github.com/ishidawataru/sctp/sctp.go +++ /dev/null @@ -1,729 +0,0 @@ -// Copyright 2019 Wataru Ishida. All rights reserved. -// -// 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. - -package sctp - -import ( - "bytes" - "encoding/binary" - "fmt" - "net" - "strconv" - "strings" - "sync" - "sync/atomic" - "syscall" - "time" - "unsafe" -) - -const ( - SOL_SCTP = 132 - - SCTP_BINDX_ADD_ADDR = 0x01 - SCTP_BINDX_REM_ADDR = 0x02 - - MSG_NOTIFICATION = 0x8000 -) - -const ( - SCTP_RTOINFO = iota - SCTP_ASSOCINFO - SCTP_INITMSG - SCTP_NODELAY - SCTP_AUTOCLOSE - SCTP_SET_PEER_PRIMARY_ADDR - SCTP_PRIMARY_ADDR - SCTP_ADAPTATION_LAYER - SCTP_DISABLE_FRAGMENTS - SCTP_PEER_ADDR_PARAMS - SCTP_DEFAULT_SENT_PARAM - SCTP_EVENTS - SCTP_I_WANT_MAPPED_V4_ADDR - SCTP_MAXSEG - SCTP_STATUS - SCTP_GET_PEER_ADDR_INFO - SCTP_DELAYED_ACK_TIME - SCTP_DELAYED_ACK = SCTP_DELAYED_ACK_TIME - SCTP_DELAYED_SACK = SCTP_DELAYED_ACK_TIME - - SCTP_SOCKOPT_BINDX_ADD = 100 - SCTP_SOCKOPT_BINDX_REM = 101 - SCTP_SOCKOPT_PEELOFF = 102 - SCTP_GET_PEER_ADDRS = 108 - SCTP_GET_LOCAL_ADDRS = 109 - SCTP_SOCKOPT_CONNECTX = 110 - SCTP_SOCKOPT_CONNECTX3 = 111 -) - -const ( - SCTP_EVENT_DATA_IO = 1 << iota - SCTP_EVENT_ASSOCIATION - SCTP_EVENT_ADDRESS - SCTP_EVENT_SEND_FAILURE - SCTP_EVENT_PEER_ERROR - SCTP_EVENT_SHUTDOWN - SCTP_EVENT_PARTIAL_DELIVERY - SCTP_EVENT_ADAPTATION_LAYER - SCTP_EVENT_AUTHENTICATION - SCTP_EVENT_SENDER_DRY - - SCTP_EVENT_ALL = SCTP_EVENT_DATA_IO | SCTP_EVENT_ASSOCIATION | SCTP_EVENT_ADDRESS | SCTP_EVENT_SEND_FAILURE | SCTP_EVENT_PEER_ERROR | SCTP_EVENT_SHUTDOWN | SCTP_EVENT_PARTIAL_DELIVERY | SCTP_EVENT_ADAPTATION_LAYER | SCTP_EVENT_AUTHENTICATION | SCTP_EVENT_SENDER_DRY -) - -type SCTPNotificationType int - -const ( - SCTP_SN_TYPE_BASE = SCTPNotificationType(iota + (1 << 15)) - SCTP_ASSOC_CHANGE - SCTP_PEER_ADDR_CHANGE - SCTP_SEND_FAILED - SCTP_REMOTE_ERROR - SCTP_SHUTDOWN_EVENT - SCTP_PARTIAL_DELIVERY_EVENT - SCTP_ADAPTATION_INDICATION - SCTP_AUTHENTICATION_INDICATION - SCTP_SENDER_DRY_EVENT -) - -type NotificationHandler func([]byte) error - -type EventSubscribe struct { - DataIO uint8 - Association uint8 - Address uint8 - SendFailure uint8 - PeerError uint8 - Shutdown uint8 - PartialDelivery uint8 - AdaptationLayer uint8 - Authentication uint8 - SenderDry uint8 -} - -const ( - SCTP_CMSG_INIT = iota - SCTP_CMSG_SNDRCV - SCTP_CMSG_SNDINFO - SCTP_CMSG_RCVINFO - SCTP_CMSG_NXTINFO -) - -const ( - SCTP_UNORDERED = 1 << iota - SCTP_ADDR_OVER - SCTP_ABORT - SCTP_SACK_IMMEDIATELY - SCTP_EOF -) - -const ( - SCTP_MAX_STREAM = 0xffff -) - -type InitMsg struct { - NumOstreams uint16 - MaxInstreams uint16 - MaxAttempts uint16 - MaxInitTimeout uint16 -} - -type SndRcvInfo struct { - Stream uint16 - SSN uint16 - Flags uint16 - _ uint16 - PPID uint32 - Context uint32 - TTL uint32 - TSN uint32 - CumTSN uint32 - AssocID int32 -} - -type SndInfo struct { - SID uint16 - Flags uint16 - PPID uint32 - Context uint32 - AssocID int32 -} - -type GetAddrsOld struct { - AssocID int32 - AddrNum int32 - Addrs uintptr -} - -type NotificationHeader struct { - Type uint16 - Flags uint16 - Length uint32 -} - -type SCTPState uint16 - -const ( - SCTP_COMM_UP = SCTPState(iota) - SCTP_COMM_LOST - SCTP_RESTART - SCTP_SHUTDOWN_COMP - SCTP_CANT_STR_ASSOC -) - -var nativeEndian binary.ByteOrder -var sndRcvInfoSize uintptr - -func init() { - i := uint16(1) - if *(*byte)(unsafe.Pointer(&i)) == 0 { - nativeEndian = binary.BigEndian - } else { - nativeEndian = binary.LittleEndian - } - info := SndRcvInfo{} - sndRcvInfoSize = unsafe.Sizeof(info) -} - -func toBuf(v interface{}) []byte { - var buf bytes.Buffer - binary.Write(&buf, nativeEndian, v) - return buf.Bytes() -} - -func htons(h uint16) uint16 { - if nativeEndian == binary.LittleEndian { - return (h << 8 & 0xff00) | (h >> 8 & 0xff) - } - return h -} - -var ntohs = htons - -// setInitOpts sets options for an SCTP association initialization -// see https://tools.ietf.org/html/rfc4960#page-25 -func setInitOpts(fd int, options InitMsg) error { - optlen := unsafe.Sizeof(options) - _, _, err := setsockopt(fd, SCTP_INITMSG, uintptr(unsafe.Pointer(&options)), uintptr(optlen)) - return err -} - -func setNumOstreams(fd, num int) error { - return setInitOpts(fd, InitMsg{NumOstreams: uint16(num)}) -} - -type SCTPAddr struct { - IPAddrs []net.IPAddr - Port int -} - -func (a *SCTPAddr) ToRawSockAddrBuf() []byte { - p := htons(uint16(a.Port)) - if len(a.IPAddrs) == 0 { // if a.IPAddrs list is empty - fall back to IPv4 zero addr - s := syscall.RawSockaddrInet4{ - Family: syscall.AF_INET, - Port: p, - } - copy(s.Addr[:], net.IPv4zero) - return toBuf(s) - } - buf := []byte{} - for _, ip := range a.IPAddrs { - ipBytes := ip.IP - if len(ipBytes) == 0 { - ipBytes = net.IPv4zero - } - if ip4 := ipBytes.To4(); ip4 != nil { - s := syscall.RawSockaddrInet4{ - Family: syscall.AF_INET, - Port: p, - } - copy(s.Addr[:], ip4) - buf = append(buf, toBuf(s)...) - } else { - var scopeid uint32 - ifi, err := net.InterfaceByName(ip.Zone) - if err == nil { - scopeid = uint32(ifi.Index) - } - s := syscall.RawSockaddrInet6{ - Family: syscall.AF_INET6, - Port: p, - Scope_id: scopeid, - } - copy(s.Addr[:], ipBytes) - buf = append(buf, toBuf(s)...) - } - } - return buf -} - -func (a *SCTPAddr) String() string { - var b bytes.Buffer - - for n, i := range a.IPAddrs { - if i.IP.To4() != nil { - b.WriteString(i.String()) - } else if i.IP.To16() != nil { - b.WriteRune('[') - b.WriteString(i.String()) - b.WriteRune(']') - } - if n < len(a.IPAddrs)-1 { - b.WriteRune('/') - } - } - b.WriteRune(':') - b.WriteString(strconv.Itoa(a.Port)) - return b.String() -} - -func (a *SCTPAddr) Network() string { return "sctp" } - -func ResolveSCTPAddr(network, addrs string) (*SCTPAddr, error) { - tcpnet := "" - switch network { - case "", "sctp": - tcpnet = "tcp" - case "sctp4": - tcpnet = "tcp4" - case "sctp6": - tcpnet = "tcp6" - default: - return nil, fmt.Errorf("invalid net: %s", network) - } - elems := strings.Split(addrs, "/") - if len(elems) == 0 { - return nil, fmt.Errorf("invalid input: %s", addrs) - } - ipaddrs := make([]net.IPAddr, 0, len(elems)) - for _, e := range elems[:len(elems)-1] { - tcpa, err := net.ResolveTCPAddr(tcpnet, e+":") - if err != nil { - return nil, err - } - ipaddrs = append(ipaddrs, net.IPAddr{IP: tcpa.IP, Zone: tcpa.Zone}) - } - tcpa, err := net.ResolveTCPAddr(tcpnet, elems[len(elems)-1]) - if err != nil { - return nil, err - } - if tcpa.IP != nil { - ipaddrs = append(ipaddrs, net.IPAddr{IP: tcpa.IP, Zone: tcpa.Zone}) - } else { - ipaddrs = nil - } - return &SCTPAddr{ - IPAddrs: ipaddrs, - Port: tcpa.Port, - }, nil -} - -func SCTPConnect(fd int, addr *SCTPAddr) (int, error) { - buf := addr.ToRawSockAddrBuf() - param := GetAddrsOld{ - AddrNum: int32(len(buf)), - Addrs: uintptr(uintptr(unsafe.Pointer(&buf[0]))), - } - optlen := unsafe.Sizeof(param) - _, _, err := getsockopt(fd, SCTP_SOCKOPT_CONNECTX3, uintptr(unsafe.Pointer(¶m)), uintptr(unsafe.Pointer(&optlen))) - if err == nil { - return int(param.AssocID), nil - } else if err != syscall.ENOPROTOOPT { - return 0, err - } - r0, _, err := setsockopt(fd, SCTP_SOCKOPT_CONNECTX, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))) - return int(r0), err -} - -func SCTPBind(fd int, addr *SCTPAddr, flags int) error { - var option uintptr - switch flags { - case SCTP_BINDX_ADD_ADDR: - option = SCTP_SOCKOPT_BINDX_ADD - case SCTP_BINDX_REM_ADDR: - option = SCTP_SOCKOPT_BINDX_REM - default: - return syscall.EINVAL - } - - buf := addr.ToRawSockAddrBuf() - _, _, err := setsockopt(fd, option, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))) - return err -} - -type SCTPConn struct { - _fd int32 - notificationHandler NotificationHandler -} - -func (c *SCTPConn) fd() int { - return int(atomic.LoadInt32(&c._fd)) -} - -func NewSCTPConn(fd int, handler NotificationHandler) *SCTPConn { - conn := &SCTPConn{ - _fd: int32(fd), - notificationHandler: handler, - } - return conn -} - -func (c *SCTPConn) Write(b []byte) (int, error) { - return c.SCTPWrite(b, nil) -} - -func (c *SCTPConn) Read(b []byte) (int, error) { - n, _, err := c.SCTPRead(b) - if n < 0 { - n = 0 - } - return n, err -} - -func (c *SCTPConn) SetInitMsg(numOstreams, maxInstreams, maxAttempts, maxInitTimeout int) error { - return setInitOpts(c.fd(), InitMsg{ - NumOstreams: uint16(numOstreams), - MaxInstreams: uint16(maxInstreams), - MaxAttempts: uint16(maxAttempts), - MaxInitTimeout: uint16(maxInitTimeout), - }) -} - -func (c *SCTPConn) SubscribeEvents(flags int) error { - var d, a, ad, sf, p, sh, pa, ada, au, se uint8 - if flags&SCTP_EVENT_DATA_IO > 0 { - d = 1 - } - if flags&SCTP_EVENT_ASSOCIATION > 0 { - a = 1 - } - if flags&SCTP_EVENT_ADDRESS > 0 { - ad = 1 - } - if flags&SCTP_EVENT_SEND_FAILURE > 0 { - sf = 1 - } - if flags&SCTP_EVENT_PEER_ERROR > 0 { - p = 1 - } - if flags&SCTP_EVENT_SHUTDOWN > 0 { - sh = 1 - } - if flags&SCTP_EVENT_PARTIAL_DELIVERY > 0 { - pa = 1 - } - if flags&SCTP_EVENT_ADAPTATION_LAYER > 0 { - ada = 1 - } - if flags&SCTP_EVENT_AUTHENTICATION > 0 { - au = 1 - } - if flags&SCTP_EVENT_SENDER_DRY > 0 { - se = 1 - } - param := EventSubscribe{ - DataIO: d, - Association: a, - Address: ad, - SendFailure: sf, - PeerError: p, - Shutdown: sh, - PartialDelivery: pa, - AdaptationLayer: ada, - Authentication: au, - SenderDry: se, - } - optlen := unsafe.Sizeof(param) - _, _, err := setsockopt(c.fd(), SCTP_EVENTS, uintptr(unsafe.Pointer(¶m)), uintptr(optlen)) - return err -} - -func (c *SCTPConn) SubscribedEvents() (int, error) { - param := EventSubscribe{} - optlen := unsafe.Sizeof(param) - _, _, err := getsockopt(c.fd(), SCTP_EVENTS, uintptr(unsafe.Pointer(¶m)), uintptr(unsafe.Pointer(&optlen))) - if err != nil { - return 0, err - } - var flags int - if param.DataIO > 0 { - flags |= SCTP_EVENT_DATA_IO - } - if param.Association > 0 { - flags |= SCTP_EVENT_ASSOCIATION - } - if param.Address > 0 { - flags |= SCTP_EVENT_ADDRESS - } - if param.SendFailure > 0 { - flags |= SCTP_EVENT_SEND_FAILURE - } - if param.PeerError > 0 { - flags |= SCTP_EVENT_PEER_ERROR - } - if param.Shutdown > 0 { - flags |= SCTP_EVENT_SHUTDOWN - } - if param.PartialDelivery > 0 { - flags |= SCTP_EVENT_PARTIAL_DELIVERY - } - if param.AdaptationLayer > 0 { - flags |= SCTP_EVENT_ADAPTATION_LAYER - } - if param.Authentication > 0 { - flags |= SCTP_EVENT_AUTHENTICATION - } - if param.SenderDry > 0 { - flags |= SCTP_EVENT_SENDER_DRY - } - return flags, nil -} - -func (c *SCTPConn) SetDefaultSentParam(info *SndRcvInfo) error { - optlen := unsafe.Sizeof(*info) - _, _, err := setsockopt(c.fd(), SCTP_DEFAULT_SENT_PARAM, uintptr(unsafe.Pointer(info)), uintptr(optlen)) - return err -} - -func (c *SCTPConn) GetDefaultSentParam() (*SndRcvInfo, error) { - info := &SndRcvInfo{} - optlen := unsafe.Sizeof(*info) - _, _, err := getsockopt(c.fd(), SCTP_DEFAULT_SENT_PARAM, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(&optlen))) - return info, err -} - -func resolveFromRawAddr(ptr unsafe.Pointer, n int) (*SCTPAddr, error) { - addr := &SCTPAddr{ - IPAddrs: make([]net.IPAddr, n), - } - - switch family := (*(*syscall.RawSockaddrAny)(ptr)).Addr.Family; family { - case syscall.AF_INET: - addr.Port = int(ntohs(uint16((*(*syscall.RawSockaddrInet4)(ptr)).Port))) - tmp := syscall.RawSockaddrInet4{} - size := unsafe.Sizeof(tmp) - for i := 0; i < n; i++ { - a := *(*syscall.RawSockaddrInet4)(unsafe.Pointer( - uintptr(ptr) + size*uintptr(i))) - addr.IPAddrs[i] = net.IPAddr{IP: a.Addr[:]} - } - case syscall.AF_INET6: - addr.Port = int(ntohs(uint16((*(*syscall.RawSockaddrInet4)(ptr)).Port))) - tmp := syscall.RawSockaddrInet6{} - size := unsafe.Sizeof(tmp) - for i := 0; i < n; i++ { - a := *(*syscall.RawSockaddrInet6)(unsafe.Pointer( - uintptr(ptr) + size*uintptr(i))) - var zone string - ifi, err := net.InterfaceByIndex(int(a.Scope_id)) - if err == nil { - zone = ifi.Name - } - addr.IPAddrs[i] = net.IPAddr{IP: a.Addr[:], Zone: zone} - } - default: - return nil, fmt.Errorf("unknown address family: %d", family) - } - return addr, nil -} - -func sctpGetAddrs(fd, id, optname int) (*SCTPAddr, error) { - - type getaddrs struct { - assocId int32 - addrNum uint32 - addrs [4096]byte - } - param := getaddrs{ - assocId: int32(id), - } - optlen := unsafe.Sizeof(param) - _, _, err := getsockopt(fd, uintptr(optname), uintptr(unsafe.Pointer(¶m)), uintptr(unsafe.Pointer(&optlen))) - if err != nil { - return nil, err - } - return resolveFromRawAddr(unsafe.Pointer(¶m.addrs), int(param.addrNum)) -} - -func (c *SCTPConn) SCTPGetPrimaryPeerAddr() (*SCTPAddr, error) { - - type sctpGetSetPrim struct { - assocId int32 - addrs [128]byte - } - param := sctpGetSetPrim{ - assocId: int32(0), - } - optlen := unsafe.Sizeof(param) - _, _, err := getsockopt(c.fd(), SCTP_PRIMARY_ADDR, uintptr(unsafe.Pointer(¶m)), uintptr(unsafe.Pointer(&optlen))) - if err != nil { - return nil, err - } - return resolveFromRawAddr(unsafe.Pointer(¶m.addrs), 1) -} - -func (c *SCTPConn) SCTPLocalAddr(id int) (*SCTPAddr, error) { - return sctpGetAddrs(c.fd(), id, SCTP_GET_LOCAL_ADDRS) -} - -func (c *SCTPConn) SCTPRemoteAddr(id int) (*SCTPAddr, error) { - return sctpGetAddrs(c.fd(), id, SCTP_GET_PEER_ADDRS) -} - -func (c *SCTPConn) LocalAddr() net.Addr { - addr, err := sctpGetAddrs(c.fd(), 0, SCTP_GET_LOCAL_ADDRS) - if err != nil { - return nil - } - return addr -} - -func (c *SCTPConn) RemoteAddr() net.Addr { - addr, err := sctpGetAddrs(c.fd(), 0, SCTP_GET_PEER_ADDRS) - if err != nil { - return nil - } - return addr -} - -func (c *SCTPConn) PeelOff(id int) (*SCTPConn, error) { - type peeloffArg struct { - assocId int32 - sd int - } - param := peeloffArg{ - assocId: int32(id), - } - optlen := unsafe.Sizeof(param) - _, _, err := getsockopt(c.fd(), SCTP_SOCKOPT_PEELOFF, uintptr(unsafe.Pointer(¶m)), uintptr(unsafe.Pointer(&optlen))) - if err != nil { - return nil, err - } - return &SCTPConn{_fd: int32(param.sd)}, nil -} - -func (c *SCTPConn) SetDeadline(t time.Time) error { - return syscall.EOPNOTSUPP -} - -func (c *SCTPConn) SetReadDeadline(t time.Time) error { - return syscall.EOPNOTSUPP -} - -func (c *SCTPConn) SetWriteDeadline(t time.Time) error { - return syscall.EOPNOTSUPP -} - -type SCTPListener struct { - fd int - m sync.Mutex -} - -func (ln *SCTPListener) Addr() net.Addr { - laddr, err := sctpGetAddrs(ln.fd, 0, SCTP_GET_LOCAL_ADDRS) - if err != nil { - return nil - } - return laddr -} - -type SCTPSndRcvInfoWrappedConn struct { - conn *SCTPConn -} - -func NewSCTPSndRcvInfoWrappedConn(conn *SCTPConn) *SCTPSndRcvInfoWrappedConn { - conn.SubscribeEvents(SCTP_EVENT_DATA_IO) - return &SCTPSndRcvInfoWrappedConn{conn} -} - -func (c *SCTPSndRcvInfoWrappedConn) Write(b []byte) (int, error) { - if len(b) < int(sndRcvInfoSize) { - return 0, syscall.EINVAL - } - info := (*SndRcvInfo)(unsafe.Pointer(&b[0])) - n, err := c.conn.SCTPWrite(b[sndRcvInfoSize:], info) - return n + int(sndRcvInfoSize), err -} - -func (c *SCTPSndRcvInfoWrappedConn) Read(b []byte) (int, error) { - if len(b) < int(sndRcvInfoSize) { - return 0, syscall.EINVAL - } - n, info, err := c.conn.SCTPRead(b[sndRcvInfoSize:]) - if err != nil { - return n, err - } - copy(b, toBuf(info)) - return n + int(sndRcvInfoSize), err -} - -func (c *SCTPSndRcvInfoWrappedConn) Close() error { - return c.conn.Close() -} - -func (c *SCTPSndRcvInfoWrappedConn) LocalAddr() net.Addr { - return c.conn.LocalAddr() -} - -func (c *SCTPSndRcvInfoWrappedConn) RemoteAddr() net.Addr { - return c.conn.RemoteAddr() -} - -func (c *SCTPSndRcvInfoWrappedConn) SetDeadline(t time.Time) error { - return c.conn.SetDeadline(t) -} - -func (c *SCTPSndRcvInfoWrappedConn) SetReadDeadline(t time.Time) error { - return c.conn.SetReadDeadline(t) -} - -func (c *SCTPSndRcvInfoWrappedConn) SetWriteDeadline(t time.Time) error { - return c.conn.SetWriteDeadline(t) -} - -func (c *SCTPSndRcvInfoWrappedConn) SetWriteBuffer(bytes int) error { - return c.conn.SetWriteBuffer(bytes) -} - -func (c *SCTPSndRcvInfoWrappedConn) GetWriteBuffer() (int, error) { - return c.conn.GetWriteBuffer() -} - -func (c *SCTPSndRcvInfoWrappedConn) SetReadBuffer(bytes int) error { - return c.conn.SetReadBuffer(bytes) -} - -func (c *SCTPSndRcvInfoWrappedConn) GetReadBuffer() (int, error) { - return c.conn.GetReadBuffer() -} - -// SocketConfig contains options for the SCTP socket. -type SocketConfig struct { - // If Control is not nil it is called after the socket is created but before - // it is bound or connected. - Control func(network, address string, c syscall.RawConn) error - - // InitMsg is the options to send in the initial SCTP message - InitMsg InitMsg -} - -func (cfg *SocketConfig) Listen(net string, laddr *SCTPAddr) (*SCTPListener, error) { - return listenSCTPExtConfig(net, laddr, cfg.InitMsg, cfg.Control) -} - -func (cfg *SocketConfig) Dial(net string, laddr, raddr *SCTPAddr) (*SCTPConn, error) { - return dialSCTPExtConfig(net, laddr, raddr, cfg.InitMsg, cfg.Control) -} diff --git a/vendor/github.com/ishidawataru/sctp/sctp_linux.go b/vendor/github.com/ishidawataru/sctp/sctp_linux.go deleted file mode 100644 index d96d09e5ca92..000000000000 --- a/vendor/github.com/ishidawataru/sctp/sctp_linux.go +++ /dev/null @@ -1,305 +0,0 @@ -// +build linux,!386 -// Copyright 2019 Wataru Ishida. All rights reserved. -// -// 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. - -package sctp - -import ( - "io" - "net" - "sync/atomic" - "syscall" - "unsafe" -) - -func setsockopt(fd int, optname, optval, optlen uintptr) (uintptr, uintptr, error) { - // FIXME: syscall.SYS_SETSOCKOPT is undefined on 386 - r0, r1, errno := syscall.Syscall6(syscall.SYS_SETSOCKOPT, - uintptr(fd), - SOL_SCTP, - optname, - optval, - optlen, - 0) - if errno != 0 { - return r0, r1, errno - } - return r0, r1, nil -} - -func getsockopt(fd int, optname, optval, optlen uintptr) (uintptr, uintptr, error) { - // FIXME: syscall.SYS_GETSOCKOPT is undefined on 386 - r0, r1, errno := syscall.Syscall6(syscall.SYS_GETSOCKOPT, - uintptr(fd), - SOL_SCTP, - optname, - optval, - optlen, - 0) - if errno != 0 { - return r0, r1, errno - } - return r0, r1, nil -} - -type rawConn struct { - sockfd int -} - -func (r rawConn) Control(f func(fd uintptr)) error { - f(uintptr(r.sockfd)) - return nil -} - -func (r rawConn) Read(f func(fd uintptr) (done bool)) error { - panic("not implemented") -} - -func (r rawConn) Write(f func(fd uintptr) (done bool)) error { - panic("not implemented") -} - -func (c *SCTPConn) SCTPWrite(b []byte, info *SndRcvInfo) (int, error) { - var cbuf []byte - if info != nil { - cmsgBuf := toBuf(info) - hdr := &syscall.Cmsghdr{ - Level: syscall.IPPROTO_SCTP, - Type: SCTP_CMSG_SNDRCV, - } - - // bitwidth of hdr.Len is platform-specific, - // so we use hdr.SetLen() rather than directly setting hdr.Len - hdr.SetLen(syscall.CmsgSpace(len(cmsgBuf))) - cbuf = append(toBuf(hdr), cmsgBuf...) - } - return syscall.SendmsgN(c.fd(), b, cbuf, nil, 0) -} - -func parseSndRcvInfo(b []byte) (*SndRcvInfo, error) { - msgs, err := syscall.ParseSocketControlMessage(b) - if err != nil { - return nil, err - } - for _, m := range msgs { - if m.Header.Level == syscall.IPPROTO_SCTP { - switch m.Header.Type { - case SCTP_CMSG_SNDRCV: - return (*SndRcvInfo)(unsafe.Pointer(&m.Data[0])), nil - } - } - } - return nil, nil -} - -func (c *SCTPConn) SCTPRead(b []byte) (int, *SndRcvInfo, error) { - oob := make([]byte, 254) - for { - n, oobn, recvflags, _, err := syscall.Recvmsg(c.fd(), b, oob, 0) - if err != nil { - return n, nil, err - } - - if n == 0 && oobn == 0 { - return 0, nil, io.EOF - } - - if recvflags&MSG_NOTIFICATION > 0 && c.notificationHandler != nil { - if err := c.notificationHandler(b[:n]); err != nil { - return 0, nil, err - } - } else { - var info *SndRcvInfo - if oobn > 0 { - info, err = parseSndRcvInfo(oob[:oobn]) - } - return n, info, err - } - } -} - -func (c *SCTPConn) Close() error { - if c != nil { - fd := atomic.SwapInt32(&c._fd, -1) - if fd > 0 { - info := &SndRcvInfo{ - Flags: SCTP_EOF, - } - c.SCTPWrite(nil, info) - syscall.Shutdown(int(fd), syscall.SHUT_RDWR) - return syscall.Close(int(fd)) - } - } - return syscall.EBADF -} - -func (c *SCTPConn) SetWriteBuffer(bytes int) error { - return syscall.SetsockoptInt(c.fd(), syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes) -} - -func (c *SCTPConn) GetWriteBuffer() (int, error) { - return syscall.GetsockoptInt(c.fd(), syscall.SOL_SOCKET, syscall.SO_SNDBUF) -} - -func (c *SCTPConn) SetReadBuffer(bytes int) error { - return syscall.SetsockoptInt(c.fd(), syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes) -} - -func (c *SCTPConn) GetReadBuffer() (int, error) { - return syscall.GetsockoptInt(c.fd(), syscall.SOL_SOCKET, syscall.SO_RCVBUF) -} - -// ListenSCTP - start listener on specified address/port -func ListenSCTP(net string, laddr *SCTPAddr) (*SCTPListener, error) { - return ListenSCTPExt(net, laddr, InitMsg{NumOstreams: SCTP_MAX_STREAM}) -} - -// ListenSCTPExt - start listener on specified address/port with given SCTP options -func ListenSCTPExt(network string, laddr *SCTPAddr, options InitMsg) (*SCTPListener, error) { - return listenSCTPExtConfig(network, laddr, options, nil) -} - -// listenSCTPExtConfig - start listener on specified address/port with given SCTP options and socket configuration -func listenSCTPExtConfig(network string, laddr *SCTPAddr, options InitMsg, control func(network, address string, c syscall.RawConn) error) (*SCTPListener, error) { - af, ipv6only := favoriteAddrFamily(network, laddr, nil, "listen") - sock, err := syscall.Socket( - af, - syscall.SOCK_STREAM, - syscall.IPPROTO_SCTP, - ) - if err != nil { - return nil, err - } - - // close socket on error - defer func() { - if err != nil { - syscall.Close(sock) - } - }() - if err = setDefaultSockopts(sock, af, ipv6only); err != nil { - return nil, err - } - if control != nil { - rc := rawConn{sockfd: sock} - if err = control(network, laddr.String(), rc); err != nil { - return nil, err - } - } - err = setInitOpts(sock, options) - if err != nil { - return nil, err - } - - if laddr != nil { - // If IP address and/or port was not provided so far, let's use the unspecified IPv4 or IPv6 address - if len(laddr.IPAddrs) == 0 { - if af == syscall.AF_INET { - laddr.IPAddrs = append(laddr.IPAddrs, net.IPAddr{IP: net.IPv4zero}) - } else if af == syscall.AF_INET6 { - laddr.IPAddrs = append(laddr.IPAddrs, net.IPAddr{IP: net.IPv6zero}) - } - } - err = SCTPBind(sock, laddr, SCTP_BINDX_ADD_ADDR) - if err != nil { - return nil, err - } - } - err = syscall.Listen(sock, syscall.SOMAXCONN) - if err != nil { - return nil, err - } - return &SCTPListener{ - fd: sock, - }, nil -} - -// AcceptSCTP waits for and returns the next SCTP connection to the listener. -func (ln *SCTPListener) AcceptSCTP() (*SCTPConn, error) { - fd, _, err := syscall.Accept4(ln.fd, 0) - return NewSCTPConn(fd, nil), err -} - -// Accept waits for and returns the next connection connection to the listener. -func (ln *SCTPListener) Accept() (net.Conn, error) { - return ln.AcceptSCTP() -} - -func (ln *SCTPListener) Close() error { - syscall.Shutdown(ln.fd, syscall.SHUT_RDWR) - return syscall.Close(ln.fd) -} - -// DialSCTP - bind socket to laddr (if given) and connect to raddr -func DialSCTP(net string, laddr, raddr *SCTPAddr) (*SCTPConn, error) { - return DialSCTPExt(net, laddr, raddr, InitMsg{NumOstreams: SCTP_MAX_STREAM}) -} - -// DialSCTPExt - same as DialSCTP but with given SCTP options -func DialSCTPExt(network string, laddr, raddr *SCTPAddr, options InitMsg) (*SCTPConn, error) { - return dialSCTPExtConfig(network, laddr, raddr, options, nil) -} - -// dialSCTPExtConfig - same as DialSCTP but with given SCTP options and socket configuration -func dialSCTPExtConfig(network string, laddr, raddr *SCTPAddr, options InitMsg, control func(network, address string, c syscall.RawConn) error) (*SCTPConn, error) { - af, ipv6only := favoriteAddrFamily(network, laddr, raddr, "dial") - sock, err := syscall.Socket( - af, - syscall.SOCK_STREAM, - syscall.IPPROTO_SCTP, - ) - if err != nil { - return nil, err - } - - // close socket on error - defer func() { - if err != nil { - syscall.Close(sock) - } - }() - if err = setDefaultSockopts(sock, af, ipv6only); err != nil { - return nil, err - } - if control != nil { - rc := rawConn{sockfd: sock} - if err = control(network, laddr.String(), rc); err != nil { - return nil, err - } - } - err = setInitOpts(sock, options) - if err != nil { - return nil, err - } - if laddr != nil { - // If IP address and/or port was not provided so far, let's use the unspecified IPv4 or IPv6 address - if len(laddr.IPAddrs) == 0 { - if af == syscall.AF_INET { - laddr.IPAddrs = append(laddr.IPAddrs, net.IPAddr{IP: net.IPv4zero}) - } else if af == syscall.AF_INET6 { - laddr.IPAddrs = append(laddr.IPAddrs, net.IPAddr{IP: net.IPv6zero}) - } - } - err := SCTPBind(sock, laddr, SCTP_BINDX_ADD_ADDR) - if err != nil { - return nil, err - } - } - _, err = SCTPConnect(sock, raddr) - if err != nil { - return nil, err - } - return NewSCTPConn(sock, nil), nil -} diff --git a/vendor/github.com/ishidawataru/sctp/sctp_unsupported.go b/vendor/github.com/ishidawataru/sctp/sctp_unsupported.go deleted file mode 100644 index 118fe159e92d..000000000000 --- a/vendor/github.com/ishidawataru/sctp/sctp_unsupported.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build !linux linux,386 -// Copyright 2019 Wataru Ishida. All rights reserved. -// -// 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. - -package sctp - -import ( - "errors" - "net" - "runtime" - "syscall" -) - -var ErrUnsupported = errors.New("SCTP is unsupported on " + runtime.GOOS + "/" + runtime.GOARCH) - -func setsockopt(fd int, optname, optval, optlen uintptr) (uintptr, uintptr, error) { - return 0, 0, ErrUnsupported -} - -func getsockopt(fd int, optname, optval, optlen uintptr) (uintptr, uintptr, error) { - return 0, 0, ErrUnsupported -} - -func (c *SCTPConn) SCTPWrite(b []byte, info *SndRcvInfo) (int, error) { - return 0, ErrUnsupported -} - -func (c *SCTPConn) SCTPRead(b []byte) (int, *SndRcvInfo, error) { - return 0, nil, ErrUnsupported -} - -func (c *SCTPConn) Close() error { - return ErrUnsupported -} - -func (c *SCTPConn) SetWriteBuffer(bytes int) error { - return ErrUnsupported -} - -func (c *SCTPConn) GetWriteBuffer() (int, error) { - return 0, ErrUnsupported -} - -func (c *SCTPConn) SetReadBuffer(bytes int) error { - return ErrUnsupported -} - -func (c *SCTPConn) GetReadBuffer() (int, error) { - return 0, ErrUnsupported -} - -func ListenSCTP(net string, laddr *SCTPAddr) (*SCTPListener, error) { - return nil, ErrUnsupported -} - -func ListenSCTPExt(net string, laddr *SCTPAddr, options InitMsg) (*SCTPListener, error) { - return nil, ErrUnsupported -} - -func listenSCTPExtConfig(network string, laddr *SCTPAddr, options InitMsg, control func(network, address string, c syscall.RawConn) error) (*SCTPListener, error) { - return nil, ErrUnsupported -} - -func (ln *SCTPListener) Accept() (net.Conn, error) { - return nil, ErrUnsupported -} - -func (ln *SCTPListener) AcceptSCTP() (*SCTPConn, error) { - return nil, ErrUnsupported -} - -func (ln *SCTPListener) Close() error { - return ErrUnsupported -} - -func DialSCTP(net string, laddr, raddr *SCTPAddr) (*SCTPConn, error) { - return nil, ErrUnsupported -} - -func DialSCTPExt(network string, laddr, raddr *SCTPAddr, options InitMsg) (*SCTPConn, error) { - return nil, ErrUnsupported -} - -func dialSCTPExtConfig(network string, laddr, raddr *SCTPAddr, options InitMsg, control func(network, address string, c syscall.RawConn) error) (*SCTPConn, error) { - return nil, ErrUnsupported -} diff --git a/vendor/gopkg.in/yaml.v3/decode.go b/vendor/gopkg.in/yaml.v3/decode.go index df36e3a30f55..0173b6982e84 100644 --- a/vendor/gopkg.in/yaml.v3/decode.go +++ b/vendor/gopkg.in/yaml.v3/decode.go @@ -100,7 +100,10 @@ func (p *parser) peek() yaml_event_type_t { if p.event.typ != yaml_NO_EVENT { return p.event.typ } - if !yaml_parser_parse(&p.parser, &p.event) { + // It's curious choice from the underlying API to generally return a + // positive result on success, but on this case return true in an error + // scenario. This was the source of bugs in the past (issue #666). + if !yaml_parser_parse(&p.parser, &p.event) || p.parser.error != yaml_NO_ERROR { p.fail() } return p.event.typ @@ -320,6 +323,8 @@ type decoder struct { decodeCount int aliasCount int aliasDepth int + + mergedFields map[interface{}]bool } var ( @@ -808,6 +813,11 @@ func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) { } } + mergedFields := d.mergedFields + d.mergedFields = nil + + var mergeNode *Node + mapIsNew := false if out.IsNil() { out.Set(reflect.MakeMap(outt)) @@ -815,11 +825,18 @@ func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) { } for i := 0; i < l; i += 2 { if isMerge(n.Content[i]) { - d.merge(n.Content[i+1], out) + mergeNode = n.Content[i+1] continue } k := reflect.New(kt).Elem() if d.unmarshal(n.Content[i], k) { + if mergedFields != nil { + ki := k.Interface() + if mergedFields[ki] { + continue + } + mergedFields[ki] = true + } kkind := k.Kind() if kkind == reflect.Interface { kkind = k.Elem().Kind() @@ -833,6 +850,12 @@ func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) { } } } + + d.mergedFields = mergedFields + if mergeNode != nil { + d.merge(n, mergeNode, out) + } + d.stringMapType = stringMapType d.generalMapType = generalMapType return true @@ -844,7 +867,8 @@ func isStringMap(n *Node) bool { } l := len(n.Content) for i := 0; i < l; i += 2 { - if n.Content[i].ShortTag() != strTag { + shortTag := n.Content[i].ShortTag() + if shortTag != strTag && shortTag != mergeTag { return false } } @@ -861,7 +885,6 @@ func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { var elemType reflect.Type if sinfo.InlineMap != -1 { inlineMap = out.Field(sinfo.InlineMap) - inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) elemType = inlineMap.Type().Elem() } @@ -870,6 +893,9 @@ func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { d.prepare(n, field) } + mergedFields := d.mergedFields + d.mergedFields = nil + var mergeNode *Node var doneFields []bool if d.uniqueKeys { doneFields = make([]bool, len(sinfo.FieldsList)) @@ -879,13 +905,20 @@ func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { for i := 0; i < l; i += 2 { ni := n.Content[i] if isMerge(ni) { - d.merge(n.Content[i+1], out) + mergeNode = n.Content[i+1] continue } if !d.unmarshal(ni, name) { continue } - if info, ok := sinfo.FieldsMap[name.String()]; ok { + sname := name.String() + if mergedFields != nil { + if mergedFields[sname] { + continue + } + mergedFields[sname] = true + } + if info, ok := sinfo.FieldsMap[sname]; ok { if d.uniqueKeys { if doneFields[info.Id] { d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.Line, name.String(), out.Type())) @@ -911,6 +944,11 @@ func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.Line, name.String(), out.Type())) } } + + d.mergedFields = mergedFields + if mergeNode != nil { + d.merge(n, mergeNode, out) + } return true } @@ -918,19 +956,29 @@ func failWantMap() { failf("map merge requires map or sequence of maps as the value") } -func (d *decoder) merge(n *Node, out reflect.Value) { - switch n.Kind { +func (d *decoder) merge(parent *Node, merge *Node, out reflect.Value) { + mergedFields := d.mergedFields + if mergedFields == nil { + d.mergedFields = make(map[interface{}]bool) + for i := 0; i < len(parent.Content); i += 2 { + k := reflect.New(ifaceType).Elem() + if d.unmarshal(parent.Content[i], k) { + d.mergedFields[k.Interface()] = true + } + } + } + + switch merge.Kind { case MappingNode: - d.unmarshal(n, out) + d.unmarshal(merge, out) case AliasNode: - if n.Alias != nil && n.Alias.Kind != MappingNode { + if merge.Alias != nil && merge.Alias.Kind != MappingNode { failWantMap() } - d.unmarshal(n, out) + d.unmarshal(merge, out) case SequenceNode: - // Step backwards as earlier nodes take precedence. - for i := len(n.Content) - 1; i >= 0; i-- { - ni := n.Content[i] + for i := 0; i < len(merge.Content); i++ { + ni := merge.Content[i] if ni.Kind == AliasNode { if ni.Alias != nil && ni.Alias.Kind != MappingNode { failWantMap() @@ -943,6 +991,8 @@ func (d *decoder) merge(n *Node, out reflect.Value) { default: failWantMap() } + + d.mergedFields = mergedFields } func isMerge(n *Node) bool { diff --git a/vendor/modules.txt b/vendor/modules.txt index 771738cf4903..3bfb8330e07e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -236,7 +236,6 @@ github.com/docker/docker/client github.com/docker/docker/errdefs github.com/docker/docker/libnetwork/ipamutils github.com/docker/docker/libnetwork/resolvconf -github.com/docker/docker/libnetwork/types github.com/docker/docker/opts github.com/docker/docker/pkg/archive github.com/docker/docker/pkg/chrootarchive @@ -353,9 +352,6 @@ github.com/hashicorp/go-retryablehttp # github.com/hashicorp/golang-lru v0.5.3 ## explicit; go 1.12 github.com/hashicorp/golang-lru/simplelru -# github.com/ishidawataru/sctp v0.0.0-20210226210310-f2269e66cdee -## explicit; go 1.12 -github.com/ishidawataru/sctp # github.com/klauspost/compress v1.15.1 ## explicit; go 1.15 github.com/klauspost/compress @@ -695,7 +691,7 @@ google.golang.org/protobuf/types/known/durationpb google.golang.org/protobuf/types/known/fieldmaskpb google.golang.org/protobuf/types/known/timestamppb google.golang.org/protobuf/types/known/wrapperspb -# gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b +# gopkg.in/yaml.v3 v3.0.0 ## explicit gopkg.in/yaml.v3 # github.com/docker/docker => github.com/docker/docker v20.10.3-0.20220414164044-61404de7df1a+incompatible